The card shows last week's issue with a link to it, or a button to draft it. Drafting a week that already has an issue (draft or published) is refused, with a link to that issue, rather than making a duplicate. Generated-by: Claude Opus 5.5
181 lines
8.1 KiB
TypeScript
181 lines
8.1 KiB
TypeScript
/**
|
|
* @file diigo-week: an EmDash plugin that drafts a potluck issue from a
|
|
* week of public diigo bookmarks.
|
|
*/
|
|
|
|
import { definePlugin } from "emdash";
|
|
import type { PluginDefinition, RouteContext } from "emdash";
|
|
import type { Block, BlockResponse } from "@emdash-cms/blocks";
|
|
import { draftIssue, issueTags, lastWeek, readWeek } from "./week.js";
|
|
|
|
/** the diigo username drafts read from, until the admin page saves another */
|
|
const DEFAULT_USER = "dckc-madmode";
|
|
|
|
/** something that answers HTTP requests: a service binding's `fetch` */
|
|
type Fetcher = { fetch(request: Request): Promise<Response> };
|
|
|
|
/**
|
|
* the `DIIGO_CACHE` service binding to diigo-cache, from the site worker's
|
|
* env. The binding is the plugin's only reach outside the site:
|
|
* `ctx.http.fetch` can't reach a dev server (it refuses localhost), and a
|
|
* binding names one worker rather than a host.
|
|
*/
|
|
async function diigoCache(): Promise<Fetcher> {
|
|
const { env } = await import("virtual:emdash/env");
|
|
const binding = env?.DIIGO_CACHE as Fetcher | undefined;
|
|
if (typeof binding?.fetch !== "function") {
|
|
throw new Error('no DIIGO_CACHE service binding: add { "binding": "DIIGO_CACHE", "service": "diigo-cache" } to services in wrangler.jsonc');
|
|
}
|
|
return binding;
|
|
}
|
|
|
|
/** GET a diigo-cache path as HTML; anything but a 200 is an error */
|
|
async function getter(cache: Fetcher): Promise<(path: string) => Promise<string>> {
|
|
return async (path) => {
|
|
const res = await cache.fetch(new Request(`https://diigo-cache${path}`, { headers: { accept: "text/html" } }));
|
|
const text = await res.text();
|
|
if (res.status !== 200) throw new Error(`diigo-cache ${path.split("?")[0]}: ${res.status} ${text.slice(0, 200)}`);
|
|
return text;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* assign `tags` to an issue in the `tag` taxonomy (as seed/issues.json
|
|
* does), creating terms that don't exist yet; returns the tags that
|
|
* couldn't be assigned, with why
|
|
*/
|
|
async function tagIssue(ctx: RouteContext, id: string, tags: string[]): Promise<string[]> {
|
|
const tax = ctx.taxonomies;
|
|
if (typeof tax?.createTerm !== "function" || typeof tax.addEntryTerms !== "function") throw new Error("this plugin lacks taxonomies:write");
|
|
const known = new Map((await tax.getTerms("tag")).map((t) => [t.slug, t.id]));
|
|
const ids: string[] = [];
|
|
const failed: string[] = [];
|
|
for (const tag of tags) {
|
|
try {
|
|
ids.push(known.get(tag) ?? (await tax.createTerm("tag", { label: tag, slug: tag })).id);
|
|
} catch (error) {
|
|
failed.push(`${tag} (${error instanceof Error ? error.message : String(error)})`);
|
|
}
|
|
}
|
|
if (ids.length) await tax.addEntryTerms("issues", id, "tag", ids);
|
|
return failed;
|
|
}
|
|
|
|
/** the issue already drafted or published for `week`, if any (issues
|
|
* are few: a scan of the newest is enough) */
|
|
async function issueFor(ctx: RouteContext, week: string): Promise<{ id: string; status: string; title: string } | undefined> {
|
|
const found = (await ctx.content!.list("issues", { limit: 100 })).items.find((it) => it.data.week === week);
|
|
return found && { id: found.id, status: found.status, title: String(found.data.title ?? week) };
|
|
}
|
|
|
|
/** a button-row link to an issue in the editor */
|
|
const openIssue = (id: string, label: string): Block => ({
|
|
type: "actions",
|
|
elements: [{ type: "link", label, target: { kind: "content", collection: "issues", id }, appearance: "primary" }],
|
|
});
|
|
|
|
/** draft `week` from `user`'s bookmarks, unless the week has an issue
|
|
* already: blocks that say what happened (with a link), and a toast */
|
|
async function draft(ctx: RouteContext, user: string, week: string): Promise<{ note: Block[]; toast: BlockResponse["toast"] }> {
|
|
try {
|
|
if (!/^[A-Za-z0-9_-]{1,64}$/.test(user)) throw new Error("diigo username: letters, digits, _ and - only");
|
|
const existing = await issueFor(ctx, week);
|
|
if (existing) {
|
|
return {
|
|
note: [
|
|
{ type: "banner", variant: "default", title: `${week} already has an issue`, description: `"${existing.title}" (${existing.status}). Delete it to draft the week again.` },
|
|
openIssue(existing.id, "Open it"),
|
|
],
|
|
toast: { message: `${week} already has an issue`, type: "info" },
|
|
};
|
|
}
|
|
const bookmarks = await readWeek(await getter(await diigoCache()), user, week);
|
|
const issue = draftIssue(week, bookmarks);
|
|
const content = ctx.content;
|
|
if (typeof content?.create !== "function") throw new Error("this plugin lacks content:write");
|
|
const created = await content.create("issues", issue);
|
|
const untagged = await tagIssue(ctx, created.id, issueTags(bookmarks));
|
|
if (untagged.length) ctx.log.warn("tags not assigned", { id: created.id, untagged });
|
|
ctx.log.info("drafted issue", { week, bookmarks: bookmarks.length, id: created.id });
|
|
return {
|
|
note: [
|
|
{ type: "banner", variant: "default", title: `Drafted "${issue.title}"`, description: `${bookmarks.length} bookmarks, as a draft at /issues/${created.slug ?? "(no slug)"}. Cut, comment, and publish.${untagged.length ? ` Tags not assigned: ${untagged.join(", ")}.` : ""}` },
|
|
openIssue(created.id, "Open the draft"),
|
|
],
|
|
toast: { message: `Drafted ${issue.title}`, type: "success" },
|
|
};
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
ctx.log.error("draft failed", { week, message });
|
|
return { note: [{ type: "banner", variant: "alert", title: "Couldn't draft the issue", description: message }], toast: { message, type: "error" } };
|
|
}
|
|
}
|
|
|
|
/** the admin page: a form for the diigo username and the week */
|
|
async function page(ctx: RouteContext, note: Block[] = [], toast?: BlockResponse["toast"]): Promise<BlockResponse> {
|
|
const user = (await ctx.kv.get<string>("user")) ?? DEFAULT_USER;
|
|
const blocks: Block[] = [
|
|
{ type: "header", text: "Draft an issue from diigo" },
|
|
{
|
|
type: "context",
|
|
text: "Reads a week of shared bookmarks from diigo-cache (by when they were bookmarked) and saves them as a draft issue for you to edit.",
|
|
},
|
|
{
|
|
type: "form",
|
|
block_id: "draft",
|
|
fields: [
|
|
{ type: "text_input", action_id: "user", label: "diigo username", initial_value: user },
|
|
{ type: "text_input", action_id: "week", label: "ISO week (UTC)", initial_value: lastWeek(new Date()) },
|
|
],
|
|
submit: { label: "Draft issue", action_id: "draft" },
|
|
},
|
|
];
|
|
blocks.push(...note);
|
|
return { blocks, toast };
|
|
}
|
|
|
|
/** the dashboard widget: last week's issue if there is one, else a button to draft it */
|
|
async function widget(ctx: RouteContext, note: Block[] = [], toast?: BlockResponse["toast"]): Promise<BlockResponse> {
|
|
const week = lastWeek(new Date());
|
|
if (note.length) return { blocks: note, toast };
|
|
const existing = await issueFor(ctx, week);
|
|
const blocks: Block[] = existing
|
|
? [{ type: "section", text: `${week}: "${existing.title}" (${existing.status})` }, openIssue(existing.id, "Open it")]
|
|
: [
|
|
{ type: "section", text: `${week} has no issue yet.` },
|
|
{ type: "actions", elements: [{ type: "button", action_id: "draft-last-week", label: `Draft ${week} from diigo`, style: "primary" }] },
|
|
];
|
|
return { blocks, toast };
|
|
}
|
|
|
|
export function createPlugin(): PluginDefinition {
|
|
return definePlugin({
|
|
id: "diigo-week",
|
|
version: "0.1.0",
|
|
capabilities: ["content:write", "taxonomies:write"],
|
|
admin: {
|
|
pages: [{ path: "/draft", label: "Draft from diigo", icon: "bookmark" }],
|
|
widgets: [{ id: "last-week", title: "This week's issue", size: "half" }],
|
|
},
|
|
routes: {
|
|
admin: {
|
|
permission: "plugins:manage",
|
|
handler: async (ctx) => {
|
|
const input = ctx.input as { type?: string; page?: string; action_id?: string; values?: Record<string, unknown> } | undefined;
|
|
const user = (await ctx.kv.get<string>("user")) ?? DEFAULT_USER;
|
|
if (input?.type === "block_action" && input.action_id === "draft-last-week") {
|
|
const { note, toast } = await draft(ctx, user, lastWeek(new Date()));
|
|
return widget(ctx, note, toast);
|
|
}
|
|
if (input?.page?.startsWith("widget:")) return widget(ctx);
|
|
if (input?.type !== "form_submit" || input.action_id !== "draft") return page(ctx);
|
|
const formUser = String(input.values?.user ?? "").trim();
|
|
if (/^[A-Za-z0-9_-]{1,64}$/.test(formUser)) await ctx.kv.set("user", formUser);
|
|
const { note, toast } = await draft(ctx, formUser, String(input.values?.week ?? "").trim());
|
|
return page(ctx, note, toast);
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|