An EmDash plugin (native, content:write only) with one admin page: a diigo username and an ISO week. It reads diigo-cache's public page (?in=<week>&by=created) as microformats, follows rel=next, and creates a draft in issues shaped like seed/issues.json. Transport is a DIIGO_CACHE service binding rather than ctx.http.fetch: EmDash's SSRF guard refuses localhost, and the binding names one worker. Logic lives in src/week.ts with the fetcher passed in; tests read fixtures in diigo-cache's markup. The checklist's goal 2 now names potluck; DiigoBridge waits. Generated-by: Claude Opus 5.5
147 lines
5.9 KiB
TypeScript
147 lines
5.9 KiB
TypeScript
/**
|
||
* @file a week of bookmarks, read as microformats from diigo-cache's public
|
||
* page, drafted as a potluck issue.
|
||
*/
|
||
|
||
import { mf2 } from "microformats-parser";
|
||
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
|
||
/** pages of matches one draft will read (100 bookmarks each) */
|
||
export const MAX_PAGES = 10;
|
||
|
||
/** one bookmark, as its h-entry says */
|
||
export type Bookmark = {
|
||
url: string;
|
||
title: string;
|
||
description: string;
|
||
tags: string[];
|
||
/** when it was bookmarked, ISO */
|
||
published: string;
|
||
};
|
||
|
||
/** `yyyy-Www` for the ISO 8601 week holding `d` (UTC) */
|
||
export function isoWeek(d: Date): string {
|
||
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
||
const day = t.getUTCDay() || 7;
|
||
t.setUTCDate(t.getUTCDate() + 4 - day); // the week's Thursday names its year
|
||
const year = t.getUTCFullYear();
|
||
const week = Math.ceil(((t.getTime() - Date.UTC(year, 0, 1)) / DAY_MS + 1) / 7);
|
||
return `${year}-W${String(week).padStart(2, "0")}`;
|
||
}
|
||
|
||
/** the last full ISO week before `now` */
|
||
export function lastWeek(now: Date): string {
|
||
return isoWeek(new Date(now.getTime() - 7 * DAY_MS));
|
||
}
|
||
|
||
/** Monday 00:00Z of ISO week `week` (`2026-W41`), or undefined if malformed */
|
||
export function weekStart(week: string): Date | undefined {
|
||
const m = /^(\d{4})-W(\d{2})$/.exec(week);
|
||
if (!m) return undefined;
|
||
const [year, w] = [Number(m[1]), Number(m[2])];
|
||
const jan4 = Date.UTC(year, 0, 4);
|
||
const monday = jan4 - ((new Date(jan4).getUTCDay() || 7) - 1) * DAY_MS + (w - 1) * 7 * DAY_MS;
|
||
const start = new Date(monday);
|
||
return w >= 1 && isoWeek(start) === week ? start : undefined;
|
||
}
|
||
|
||
/** the first string value of an mf2 property, or "" */
|
||
const first = (props: Record<string, unknown[]>, name: string): string => {
|
||
const v = props[name]?.[0];
|
||
return typeof v === "string" ? v : "";
|
||
};
|
||
|
||
/** the bookmarks in a page's `h-feed`, and its `rel=next` link if any */
|
||
export function readPage(html: string, url: string): { bookmarks: Bookmark[]; next?: string } {
|
||
const { items, rels } = mf2(html, { baseUrl: url });
|
||
const feed = items.find((i) => i.type?.includes("h-feed"));
|
||
const bookmarks = (feed?.children ?? [])
|
||
.filter((e) => e.type?.includes("h-entry"))
|
||
.map((e) => {
|
||
const props = e.properties as Record<string, unknown[]>;
|
||
const tags = (props.category ?? []).filter((t): t is string => typeof t === "string");
|
||
return {
|
||
url: first(props, "bookmark-of"),
|
||
title: first(props, "name"),
|
||
description: first(props, "summary"),
|
||
tags,
|
||
published: first(props, "published"),
|
||
};
|
||
})
|
||
.filter((b) => b.url !== "");
|
||
return { bookmarks, next: rels.next?.[0] };
|
||
}
|
||
|
||
/**
|
||
* a user's bookmarks from an ISO week, oldest first, by when they were
|
||
* bookmarked: diigo-cache's `/public/<user>?in=<week>&by=created`,
|
||
* following `rel=next` up to {@link MAX_PAGES} pages.
|
||
*
|
||
* @param get fetches a path on diigo-cache, answering its HTML; it throws
|
||
* on anything but a 200
|
||
*/
|
||
export async function readWeek(get: (path: string) => Promise<string>, user: string, week: string): Promise<Bookmark[]> {
|
||
const base = "https://diigo-cache.invalid";
|
||
let path: string | undefined = `/public/${encodeURIComponent(user)}?in=${encodeURIComponent(week)}&by=created`;
|
||
const bookmarks: Bookmark[] = [];
|
||
for (let n = 0; path && n < MAX_PAGES; n += 1) {
|
||
const page = readPage(await get(path), base + path);
|
||
bookmarks.push(...page.bookmarks);
|
||
const next: URL | undefined = page.next ? new URL(page.next) : undefined;
|
||
path = next && next.origin === base ? next.pathname + next.search : undefined;
|
||
}
|
||
return bookmarks.reverse();
|
||
}
|
||
|
||
/** a Portable Text span */
|
||
type Span = { _type: "span"; _key: string; text: string; marks: string[] };
|
||
/** a Portable Text block */
|
||
type Block = { _type: "block"; _key: string; style: string; markDefs: { _type: "link"; _key: string; href: string }[]; children: Span[] };
|
||
|
||
/** a bookmark as one paragraph: the link, the description, then tag links (as in seed/issues.json) */
|
||
function bookmarkBlock(b: Bookmark, i: number): Block {
|
||
const k = `b${i}`;
|
||
const markDefs: Block["markDefs"] = [{ _type: "link", _key: `${k}-a`, href: b.url }];
|
||
const children: Span[] = [{ _type: "span", _key: `${k}-t`, text: b.title || b.url, marks: [`${k}-a`] }];
|
||
if (b.description) children.push({ _type: "span", _key: `${k}-d`, text: `: ${b.description}`, marks: [] });
|
||
b.tags.forEach((tag, j) => {
|
||
markDefs.push({ _type: "link", _key: `${k}-g${j}`, href: `/tag/${encodeURIComponent(tag)}` });
|
||
children.push({ _type: "span", _key: `${k}-s${j}`, text: " ", marks: [] });
|
||
children.push({ _type: "span", _key: `${k}-n${j}`, text: tag, marks: [`${k}-g${j}`] });
|
||
});
|
||
return { _type: "block", _key: k, style: "normal", markDefs, children };
|
||
}
|
||
|
||
/** the issue's tags: every bookmark's, deduplicated, in order of first use */
|
||
export function issueTags(bookmarks: Bookmark[]): string[] {
|
||
return [...new Set(bookmarks.flatMap((b) => b.tags))];
|
||
}
|
||
|
||
/** `Oct 5–11` (or `Sep 28–Oct 4`) for the week starting `monday` */
|
||
function range(monday: Date): string {
|
||
const sunday = new Date(monday.getTime() + 6 * DAY_MS);
|
||
const fmt = (d: Date, withMonth: boolean) =>
|
||
withMonth ? d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }) : String(d.getUTCDate());
|
||
return `${fmt(monday, true)}–${fmt(sunday, sunday.getUTCMonth() !== monday.getUTCMonth())}`;
|
||
}
|
||
|
||
/** the fields of a draft `issues` entry for `week`: title, week, dek, body */
|
||
export function draftIssue(week: string, bookmarks: Bookmark[]): Record<string, unknown> {
|
||
const monday = weekStart(week);
|
||
if (!monday) throw new Error(`week: expected an ISO week like 2026-W41, got ${JSON.stringify(week)}`);
|
||
const intro: Block = {
|
||
_type: "block",
|
||
_key: "intro",
|
||
style: "normal",
|
||
markDefs: [],
|
||
children: [{ _type: "span", _key: "intro-t", text: "(draft) A line or two about the week goes here.", marks: [] }],
|
||
};
|
||
return {
|
||
title: `Week ${week}`,
|
||
week,
|
||
dek: `${range(monday)}: ${bookmarks.length} bookmark${bookmarks.length === 1 ? "" : "s"}. (draft)`,
|
||
body: [intro, ...bookmarks.map(bookmarkBlock)],
|
||
};
|
||
}
|