import { h as ValidationViolation } from "../../errors-CyuuoKx0.js"; import { g as CollectionConfig } from "../../rule-DYNYH_ha.js"; import { i as FormDefinition, s as FormMailer } from "../../types-Bv7XuMW0.js"; import { H as VectorIndex, a as AiRunner, i as AiGatewayOptions, l as AltTextOptions, v as RewriteOptions, y as SeoOptions } from "../../index-B0AD4_8S.js"; import { O as ResolveEditor, n as WorkerRoute } from "../../index-FUN1hqS9.js"; import { i as EditorSession, k as RateLimitBackend } from "../../types-B8yzm4Q0.js"; import { t as D1Client } from "../../session-BVt9M6O0.js"; import { _ as pageRedirects } from "../../index-ByWtUw-d.js"; import { A as json, C as draftBufferKey, D as EditorRouteEnv, E as writeDraftBuffer, M as runEditorRoute, N as tableMeta, O as guardEditor, S as clearDraftBuffer, T as shouldFlushBuffer, _ as parseDraftBase, a as SaveDraftDeps, b as DRAFT_BUFFER_TTL_SECONDS, c as VersionsRouteConfig, d as latestPendingDraft, f as versionsRoute, g as fieldRevs, h as fieldRev, i as PublishResult, j as matchPath, k as ident, l as applyPublish, m as DraftConflict, n as DraftSoftLocks, o as SaveDraftOptions, p as DRAFT_BASE_KEY, r as PublishDeps, s as SaveDraftResult, t as DraftSoftLockTarget, u as applySaveDraft, v as BufferedDraft, w as readDraftBuffer, x as DraftBufferKV, y as DEFAULT_FLUSH_MS } from "../../versions-DF-daHUH.js"; import { l as SpamVerdict } from "../../index-C7hyMj7j.js"; import { a as HealthSummary } from "../../index-DRef8wmJ.js"; import { r as IncidentTable } from "../../store-BeugRQ2n.js"; import { _ as MediaRefSource } from "../../index-CgrA3-eY.js"; import { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core"; //#region src/core/editor/editors.d.ts interface EditorsRouteConfig { /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Better Auth user table name. Default `"user"` (getLouiseAuth's default); * pass, for example, `"louise_user"` when a `tablePrefix`/modelName renames it. */ table?: string; /** Mount path. Default `/api/louise/editors`. */ path?: string; } /** * Build the `editors` editor route. GET (read) lists editors oldest-first; * POST (mutation) invites one by `{ name?, email }`; DELETE (mutation) removes * one by `?id=` but never the last. "Editor" means `role = 'admin'` throughout: * other rows in the table (customers) are neither listed nor deletable here. Returns `undefined` for a non-matching * path so `composeWorker` falls through to the next route / SSR. * * ```ts * // The session is already resolved by the host; hand it back via resolveEditor. * export const ALL: APIRoute = (ctx) => * runEditorRoute( * editorsRoute({ table: "louise_user", resolveEditor: () => ctx.locals.editor }), * ctx.request, * env, * ); * ``` */ declare function editorsRoute(config: EditorsRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/form.d.ts /** Env for a form capture route: the D1 binding (a KV binding too if the form * rate-limits, supplied via `rateLimitKv`). */ type FormRouteEnv = EditorRouteEnv; interface FormRouteConfig { /** The form definition (from `defineForm`). */ form: FormDefinition; /** Mount path. Default `/api/louise/forms/`. */ path?: string; /** Rate-limit backend, when the form declares `spam.rateLimit`—a KV binding * or Cloudflare's native Rate Limiting binding. */ rateLimitKv?: (env: Env) => RateLimitBackend; /** Rate-limit key for a request. Default: the `CF-Connecting-IP` header. */ clientKey?: (request: Request) => string; /** Turnstile secret, when the form declares `spam.turnstile`. */ turnstileSecret?: (env: Env) => string; /** Email transport for `notify.email`—wrap your `EMAIL` binding here. */ mailer?: (env: Env) => FormMailer; /** * Store into the shared generic `submissions` table as `{ form, data }` * instead of a per-form typed table—so an ad-hoc form needs no migration. * Pass the ready-made `submissions` table name (default `"submissions"`). */ genericTable?: string; /** Fired after a successful insert with the stored values (Tier 3 hook). */ onSubmit?: (values: Record, env: Env) => void | Promise; /** * Fired when a silent spam heuristic holds a submission, with which one. The * visitor still sees a success and nothing is stored, so this is the only * record: count held submissions, alert on a spike, or store them yourself. * Default: one log line with the form's name and the verdict, never the * field values. */ onSpam?: (verdict: SpamVerdict, env: Env, context: { form: string; body: Record; }) => void | Promise; /** * Answer a no-script post: a form-encoded submit from a browser that wants * HTML, which is what a plain `
` sends when its script is * slow, blocked, or broken. Return your own thank-you page or a re-rendered * form, or `undefined` for the default: a `303` back to the page the form was * on (its `Referer`), with `?form=&status=`, and for `invalid` * the failing field keys as `&invalid=email,message`, never the messages. A * JSON request always gets JSON. */ respond?: (outcome: FormOutcome, request: Request) => Response | undefined; } /** How a submission ended, for a no-script post. */ interface FormOutcome { /** The form's name. */ form: string; /** * `sent` (stored, or held as spam, which looks the same on purpose), * `invalid` (a field failed validation), `limited` (rate-limited), or * `refused` (the Turnstile check failed). */ status: "sent" | "invalid" | "limited" | "refused"; /** For `invalid`: the keys of the fields that failed. */ invalid?: string[]; /** For `invalid`: every violation, for a page that re-renders the form. */ violations?: readonly { path: string; message: string; }[]; } /** * Build a public form capture route from a `defineForm` definition. POST only, * same-origin-guarded; validates + coerces against the form's fields (422 on * violations), enforces the declared spam guard, inserts the row, and fires the * `onSubmit` hook. Returns `undefined` for a non-matching path so `composeWorker` * falls through. */ declare function formRoute(config: FormRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/health.d.ts interface HealthRouteConfig { /** Resolve the editor session (the health panel is editor-only). */ resolveEditor: ResolveEditor; /** Read the persisted summary—`null` when no scan has run yet. */ read: (env: Env) => Promise | HealthSummary | null; /** Mount path. Default `/api/louise/health`. */ path?: string; } /** * Build the health route. Returns `undefined` for a non-matching path so * `composeWorker` falls through. Only GET is served; the body is * `{ summary }` with `summary: null` until the first scan persists one. */ declare function healthRoute(config: HealthRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/incidents.d.ts interface IncidentsRouteConfig { /** Resolve the editor session. */ resolveEditor: ResolveEditor; /** Mount path. Default `/api/louise/incidents`. */ path?: string; /** Most rows a list returns. Default 100. */ limit?: number; /** The table, when you've extended `incidentsColumns`. */ table?: IncidentTable; } /** * The route over the site's `incidents` table: list them, read one, and * resolve one. Reads need an editor session; resolving is a write, so it also * passes the same-origin check. */ declare function incidentsRoute(config: IncidentsRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/inquiries.d.ts interface InquiriesRouteConfig { /** The inquiries table (site-composed or the ready-made `inquiries`). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Mount path. Default `/api/louise/inquiries`. */ path?: string; /** Max rows returned by GET. Default 200. */ limit?: number; } /** * Build the `inquiries` editor route. GET (read) lists submissions newest-first; * DELETE (mutation, same-origin-guarded) removes one by `?id=`. Returns * `undefined` for a non-matching path so `composeWorker` falls through to the * next route / SSR. */ declare function inquiriesRoute(config: InquiriesRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/status.d.ts /** * What a check returns: `true` when it passes, or `{ ok, ageMs }` when it also * knows how old the thing it checked is. Anything else counts as a failure. */ type StatusCheckResult = boolean | { ok: boolean; ageMs?: number | null; }; /** * One named check. It gets the Worker `env` and a signal that aborts at the * route's timeout, so a check that can pass the signal on (a `fetch`) stops * work it no longer needs. Keep it cheap: anyone can make it run. */ type StatusCheck = (env: Env, signal: AbortSignal) => StatusCheckResult | Promise; /** One check's outcome in the response body. */ interface StatusCheckReport { ok: boolean; /** How old the checked thing is, in milliseconds, when the check knows. */ ageMs?: number; } /** The response body: `ok` is true only when every check passed. */ interface StatusReport { ok: boolean; checks: Record; } /** How long a check gets before it counts as failed. */ declare const STATUS_CHECK_TIMEOUT_MS = 2000; interface RunStatusChecksOptions { /** Per-check time limit, in milliseconds. Default {@link STATUS_CHECK_TIMEOUT_MS}. */ timeoutMs?: number; } interface StatusRouteConfig extends RunStatusChecksOptions { /** * The checks, by name. The names appear in the response body, so don't put * anything in one you wouldn't publish. With no checks, the route answers * 200 whenever the Worker runs. */ checks: Record>; /** * Reuse a finished run's result for this many milliseconds, within one * Worker isolate, so a burst of requests costs one run of the checks per * isolate instead of one per request. Default `0`: every request runs them. */ reuseMs?: number; /** Mount path. Default `/api/louise/status`. */ path?: string; } /** * Run every check at once, each under its own timeout, and report the lot. * The route calls this; a scheduled job that wants the same answer can too. * Never throws: a check that throws or times out reports `{ ok: false }`, and * its error goes to the log. */ declare function runStatusChecks(env: Env, checks: Record>, options?: RunStatusChecksOptions): Promise; /** * Build the public status route. It answers `GET` and `HEAD` with 200 when * every check passes and 503 when any fails, throws, or times out, always * with `Cache-Control: no-store`. `HEAD` gets the status without the body. * * It's a {@link publicRoute}, so the API gate lets an anonymous probe through. * Returns `undefined` for a path it doesn't own, so `composeWorker` falls * through. */ declare function statusRoute(config: StatusRouteConfig): WorkerRoute; /** The part of a D1 binding {@link d1Check} uses. `D1Database` fits. */ interface StatusD1 { prepare(query: string): { first(): Promise; }; } /** * A check that passes when the database answers `SELECT 1`. It reads no rows, * so it costs next to nothing. A missing binding fails the check. * * @example d1Check((env) => env.DB) */ declare function d1Check(db: (env: Env) => StatusD1 | null | undefined): StatusCheck; /** A point in time: an ISO string, epoch milliseconds, or a `Date`. */ type StatusTimestamp = string | number | Date; /** * A check that passes when a timestamp is no older than `maxAgeMs`, and * reports its age: the last health scan, a catalog snapshot, any scheduled * job's last success. `read` returns the timestamp, or `null` when there's * none yet. * * It applies {@link isStale}'s rule, so it agrees with the Health panel. A * missing or unparseable timestamp fails, with no age, and so does a number * outside the `Date` range. One in the future (clock skew) passes with an age * of 0, and an age of exactly `maxAgeMs` passes. Pass `Infinity` to always * pass. A `NaN` or negative limit fails everything, so a misconfigured * monitor never reports healthy. * * @example ageCheck(async (env) => (await readHealthSummary(env.KV))?.checkedAt, 36 * 60 * 60 * 1000) */ declare function ageCheck(read: (env: Env) => StatusTimestamp | null | undefined | Promise, maxAgeMs: number): StatusCheck; //#endregion //#region src/core/editor/sitemap.d.ts /** How long a crawler or the edge may reuse either file. */ declare const SITEMAP_MAX_AGE_SECONDS = 60; interface SitemapRouteConfig { /** * The pages table: `slug`, and `status`, `noindex`, and `updatedAt` when it * has them. A table without `status` lists every row; one without * `updatedAt` lists no ``. */ table: SQLiteTable; /** * The site's public origin, `https://example.com`. A function gets the * request and `env`, for a site whose origin varies by environment. Never * taken from the request's own host, which a preview deploy doesn't share. */ origin: string | ((request: Request, env: Env) => string); /** The slug a site serves at `/`. It's listed as the origin's root. */ homeSlug?: string; /** A page's path from its slug. Default `/`, and `/` for `homeSlug`. */ pathFor?: (slug: string) => string; /** Slugs to leave out: rows that only back a section and have no page of their own. */ exclude?: readonly string[]; /** Paths served by files rather than rows, such as `/examples`, listed after the pages. */ extra?: readonly string[]; /** * The `site_settings` table. When its `disableIndexing` is on, the sitemap * lists nothing. `robots.txt` doesn't change: a crawler must still fetch the * pages to see their `noindex`. */ settingsTable?: SQLiteTable; /** Paths `robots.txt` asks crawlers not to fetch, such as `/api/`. Default none. */ disallow?: readonly string[]; /** Cache lifetime, in seconds. Default {@link SITEMAP_MAX_AGE_SECONDS}. */ maxAgeSeconds?: number; /** Where to serve the sitemap. Default `/sitemap.xml`. */ sitemapPath?: string; /** Where to serve robots.txt. Default `/robots.txt`. */ robotsPath?: string; } /** * Build the sitemap route. It answers `GET` and `HEAD` on the two paths, and * returns `undefined` for every other request. It's a {@link publicRoute}. * * ```ts * sitemapRoute({ * table: pages, * settingsTable: siteSettings, * origin: "https://example.com", * homeSlug: "home", * exclude: ["footer"], * extra: ["/examples"], * disallow: ["/api/"], * }); * ``` */ declare function sitemapRoute(config: SitemapRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/submissions.d.ts interface SubmissionsRouteConfig { /** The generic table name (default `"submissions"`). */ table?: string; /** The form name to scope this review to (matches `formRoute`'s form). */ form: string; /** Resolve the editor session. */ resolveEditor: ResolveEditor; /** Mount path. Default `/api/louise/submissions/`. */ path?: string; /** Max rows returned by GET. Default 200. */ limit?: number; } /** * Build the review route for one form's rows in the shared `submissions` table. * GET (read) returns each row's `id`/`createdAt` plus its parsed `data` fields * flattened onto the row (so the Settings panel renders columns as it does for a * typed table); DELETE (mutation, same-origin-guarded) removes one by `?id=`. */ declare function submissionsRoute(config: SubmissionsRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/settings.d.ts /** A settings key's sanitizer: clamp or normalize an incoming value, and return * the value to store. */ type SettingsSanitize = (value: unknown) => unknown; /** * The site-supplied halves of the `settings` route: per-key sanitizing on write, * and a transform on read. Both are optional, and a route without them behaves * exactly as before. * * Separate from {@link SettingsRouteConfig} so a host that generates the route * call can take these from a site-owned module and spread them in, while it * keeps the rest of the config. */ interface SettingsRouteHooks { /** * Per-key sanitizers, run on a patch before it's validated or written. A * patched key with an entry here is stored as the sanitizer's return value; * a key without one passes through unchanged. The allowlist still decides * what's written: a sanitizer for a key outside `columns` and `customKeys` * never runs on anything that gets stored. * * Sanitized values still go through the link-scheme and media-URL checks, so * a sanitizer can't let an unsafe `href` or an external image through. */ sanitize?: Record; /** Transform the merged settings on GET, for example to fill keys an older * row lacks from the site's defaults. Pure; must not mutate its input. */ read?: (settings: Record) => Record; } interface SettingsRouteConfig extends SettingsRouteHooks { /** The `site_settings` table (composed from `siteSettingsColumns` or the * ready-made `siteSettings`). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Drizzle property keys of the base columns a site exposes for editing; * only these structured columns are patched. */ columns: string[]; /** Site-specific setting keys, merged into the `custom` JSON object. */ customKeys?: string[]; /** Setting keys whose value must be a media-library URL (for example, `logoUrl`, * `defaultOgImageUrl`). A patched value that is a non-empty string not served * from {@link mediaBase} is rejected `422`, so an external hotlink can't be * stored. Requires {@link mediaBase}. */ imageKeys?: string[]; /** The site's `MEDIA_URL` base, used to validate {@link imageKeys}. */ mediaBase?: string; /** Mount path. Default `/api/louise/settings`. */ path?: string; /** Singleton row id. Default 1. */ id?: number; } /** * Reject any link row whose `href` names a scheme a site must not render. * * Settings hold `navLinks` / `socialLinks` as arrays of `{ label, href }`, and a * site renders them straight into `` in its chrome—on every page. * Nothing checked them: an editor could store `javascript:alert(1)` as a nav * destination and it would persist and render as a working link for every * visitor. Sections closed exactly this hole with the `link` field type, whose * own comment spells out the vector; settings never got the same treatment. * * Shape-driven rather than key-driven, deliberately. An `imageKeys`-style * allowlist means every site must remember to configure it, and the one that * forgets is the one that gets hit. Any patched value that is an array of objects * carrying an `href` is a link list—that key has one meaning—so a site's own * custom link setting is covered without opting in. * * Non-link values pass through untouched; this is not a type checker. */ declare function validateSettingsLinks(patch: Record): ValidationViolation[]; /** * Reject any patched {@link SettingsRouteConfig.imageKeys} value that isn't a * media-library URL—pure so the allowlist enforcement is unit-testable * independently of D1. Empty/absent/non-string values are skipped (clearing a * field is fine; type coercion isn't this check's job). */ declare function validateSettingsImages(patch: Record, imageKeys: Iterable, mediaBase: string): ValidationViolation[]; /** * Run each patched key that has a sanitizer through it, and return the new * patch. Keys without a sanitizer are copied unchanged, and the input isn't * mutated. Pure, so the sanitize step is unit-testable independently of D1. */ declare function sanitizeSettingsPatch(patch: Record, sanitize: Record): Record; interface SettingsPartition { /** Base columns to patch, keyed by Drizzle property name. */ columnUpdates: Record; /** Site-specific keys to merge into the `custom` JSON object. */ customUpdates: Record; /** Keys in neither allowlist—ignored, never written. */ ignored: string[]; } /** * Split an incoming settings patch into base-column updates, `custom`-extension * updates, and ignored (non-allowlisted) keys. Pure—the allowlist enforcement * lives here so it's unit-testable independently of D1. */ declare function partitionSettingsPatch(patch: Record, columns: Iterable, customKeys?: Iterable): SettingsPartition; /** The store-side settings config—the subset of {@link SettingsRouteConfig} the * {@link applySettingsPatch} write needs (no transport/auth concern). */ interface SettingsPatchConfig { table: SQLiteTable; columns: string[]; customKeys?: string[]; imageKeys?: string[]; mediaBase?: string; id?: number; /** Per-key sanitizers. See {@link SettingsRouteHooks.sanitize}. */ sanitize?: Record; } type SettingsPatchResult = { ok: true; ignored: string[]; } | { ok: false; status: number; error: string; ignored?: string[]; violations?: ValidationViolation[]; }; /** * Apply an already-validated settings patch to the singleton row: run the * site's per-key sanitizers, enforce media-strictness on image keys, split the patch into base-column vs `custom` * updates ({@link partitionSettingsPatch}), and write. Carries no transport/parse * concern—the raw {@link settingsRoute} (POST/PATCH) and a host's `settings` * Action each validate their own input, then converge here, so the merge + write * lives in exactly one place rather than being duplicated per adapter. */ declare function applySettingsPatch(env: Env, config: SettingsPatchConfig, rawPatch: Record): Promise; /** * Build the `settings` editor route. GET (read) returns the merged singleton * config; POST/PATCH (mutation, same-origin-guarded) patches the allowlisted * base columns + merges site-declared keys into `custom`. Returns `undefined` * for a non-matching path so `composeWorker` falls through. */ declare function settingsRoute(config: SettingsRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/settings-blob.d.ts /** A blob key's sanitizer: clamp/normalize the incoming value before it's * merged into the blob (mirrors the structured route's column coercion). */ type BlobSanitize = (value: unknown) => unknown; /** * Merge an incoming patch into a settings blob through an allowlist. For each * patch key present in `allow`, the sanitized value overwrites the blob key; * keys outside `allow` are collected in `ignored` (never written). Pure—the * allowlist enforcement lives here so it's unit-testable independently of D1 * (mirrors {@link partitionSettingsPatch} for the structured route). */ declare function mergeBlobPatch(blob: Record, patch: Record, allow: Record): { blob: Record; ignored: string[]; changed: number; }; interface BlobSettingsRouteConfig { /** The singleton `site_settings` table. */ table: SQLiteTable; /** Drizzle property name of the JSON blob column (for example, `"data"`). */ column: string; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Allowlisted top-level blob keys, each mapped to a sanitizer. Keys outside * this map are ignored (never written). */ allow: Record; /** Optional GET transform for the stored blob—for example, seed-merge so the panel * shows every known key even on an older row. Pure; must not mutate. */ read?: (blob: Record) => Record; /** Mount path. Default `/api/louise/settings`. */ path?: string; /** Singleton row id. Default 1. */ id?: number; } /** * Build the blob-mode `settings` editor route. GET (read) returns the merged * blob; POST/PATCH (mutation, same-origin-guarded) sanitizes + merges the * allowlisted keys into the blob and persists it via Drizzle (so the JSON * column serializes correctly). Returns `undefined` for a non-matching path so * `composeWorker` falls through. */ declare function blobSettingsRoute(config: BlobSettingsRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/save.d.ts interface SaveCollectionConfig { /** The collection's table (site-composed or ready-made). */ table: SQLiteTable; /** Editable field (Drizzle property key) allowlist. */ fields: string[]; /** Subset of `fields` whose value is rich HTML → sanitized before store. */ richFields?: string[]; } interface SaveRouteConfig { /** Editable collections keyed by the client's `collection` slug. */ collections: Record; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Rich-HTML sanitizer; defaults to louise-toolkit/security's `sanitizeRichHtml`. */ sanitize?: (html: string) => string; /** Mount path. Default `/api/louise/save`. */ path?: string; } type ResolvedField = { ok: true; stored: string; } | { ok: false; status: number; error: string; }; /** * Allowlist-check a field for a collection and sanitize it when it's a rich * field. Pure—the allowlist + sanitize decision lives here so it's * unit-testable independently of D1. */ declare function resolveFieldValue(collection: SaveCollectionConfig, field: string, value: unknown, sanitize: (html: string) => string): ResolvedField; /** * Apply an already-validated field save: look up the collection, allowlist-check * + sanitize the field ({@link resolveFieldValue}), then write it to the row's * primary key. Carries no transport/parse concern—the raw {@link saveRoute} and * a host's `save` endpoint each validate their own input, then converge here, so * the store logic (and the #96 body-validation contract about where parsing * happens) lives in exactly one place rather than being duplicated per adapter. */ declare function applyFieldSave(env: Env, collections: Record, sanitize: (html: string) => string, body: { collection: string; key: string; field: string; value: unknown; }): Promise<{ ok: true; } | { ok: false; status: number; error: string; }>; /** * Build the `save` editor route. POST only, same-origin-guarded. Returns * `undefined` for a non-matching path so `composeWorker` falls through. */ declare function saveRoute(config: SaveRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/overview.d.ts /** Content status—drafts + pages with unpublished changes (both drive the * ContentStatus card's "needs attention" count). */ interface OverviewContent { drafts: number; unpublished: number; /** ISO timestamp of the most recent edit, if the site tracks one. */ lastEditedAt?: string; } /** Inbox status—unread contact-form submissions. */ interface OverviewInbox { unread: number; } /** Site-health status—the persisted link-check / SEO summary (#106). */ interface OverviewHealth { brokenLinks: number; missingAlt: number; seoGaps: number; /** ISO timestamp of the last health check, if available. */ checkedAt?: string; /** Schema migrations the database hasn't applied yet, if the site checks. */ pendingMigrations?: string[]; } /** The overview payload—every slice optional so a card degrades to "absent" * rather than erroring when its data source isn't wired. */ interface OverviewData { content?: OverviewContent; inbox?: OverviewInbox; health?: OverviewHealth; } /** Resolve one overview slice from the runtime env. Return `undefined` (or throw) * to omit the slice; the matching card then hides itself. */ type SliceResolver = (env: Env) => T | undefined | Promise; interface OverviewRouteConfig { /** Resolve the editor session (the overview is editor-only). */ resolveEditor: ResolveEditor; /** Mount path. Default `/api/louise/overview`. */ path?: string; /** Content counts (drafts / unpublished). Omit → no content card. */ content?: SliceResolver; /** Unread inbox count. Omit → no inbox card. */ inbox?: SliceResolver; /** Persisted health summary (#106). Omit → no health card. */ health?: SliceResolver; } /** * Build the overview route. Returns `undefined` for a non-matching path so * `composeWorker` falls through. Only GET is served; the resolvers run in * parallel and absent slices are omitted from the response. */ declare function overviewRoute(config: OverviewRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/pages.d.ts /** Context passed to a {@link PagesRouteConfig.validate} hook. */ interface PagesValidateContext { operation: "create" | "update"; /** Row id on update. */ id?: number; } /** A server-side write validator. Throw {@link LouiseValidationError} to reject. */ type PagesValidator = (data: Record, ctx: PagesValidateContext) => void | Promise; /** The write a {@link PagesRouteConfig.afterWrite} hook runs after. */ interface PagesWrite { operation: "create" | "update" | "delete"; /** The written row's ID. After a delete, the ID the row had. */ id: number; } /** The editable `pages` fields (Drizzle property keys) exposed by default. */ declare const DEFAULT_PAGE_FIELDS: readonly ["slug", "title", "body", "status", "seoTitle", "seoDescription", "ogImage", "noindex", "sortOrder"]; interface PagesRouteConfig { /** The `pages` table (composed from `pagesColumns` or the ready-made `pages`). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Editable fields (Drizzle property keys) for create/update. */ fields?: readonly string[]; /** Rich-HTML fields sanitized on write. Default `["body"]`. */ richFields?: readonly string[]; /** Rich-HTML sanitizer; defaults to louise-toolkit/security's `sanitizeRichHtml`. */ sanitize?: (html: string) => string; /** Mount path (collection). Default `/api/louise/pages`. */ path?: string; /** * Optional server-side validation, run after field-allowlisting and before * the insert/update. Throw {@link LouiseValidationError}—for example, via * `assertValidSections(catalog, data.sections, ctx)`—to reject the write * with a 422 carrying the per-field violations. Only the allowlisted `data` * is passed, so absent fields (partial update) aren't spuriously validated. */ validate?: PagesValidator; /** * Transform the allowlisted write data before validation + store—clamp * lengths, coerce enums, normalize the slug, strict-media checks (a site's * `cleanPagePatch`). Runs after field-allowlisting, before {@link validate}. */ transform?: (data: Record, ctx: PagesValidateContext) => Record | Promise>; /** * Slugs rejected on create/update with a 422—for example, reserved file-route paths * the catch-all can never serve (so a page can't be saved and then be * silently unreachable). Compared after {@link transform}. */ reservedSlugs?: Iterable; /** * Best-effort hook after a successful create/update/delete—for example, sync * the search (FTS) index, which plain CRUD writes don't touch. A throw is * swallowed so search staleness can never fail the write itself. * * The second argument names the row the write touched, so you can update * that one row's index entry with `reindexDoc` instead of rebuilding the * whole index after every edit: * * ```ts * afterWrite: (_editor, { id }) => reindexDoc(db(env.DB), pages, pagesCollection, id), * ``` * * `reindexDoc` re-reads the row, so the same call removes the entry after a * delete. */ afterWrite?: (editor: EditorSession, write: PagesWrite) => void | Promise; /** * The collection's version-snapshot table (`collectionVersionsTable(...)`), * when the page uses the draft/publish workflow. DELETE then cascades to it * (`WHERE parent_id = :id`)—those snapshots have no FK to the page row, so * without this they orphan. Omit for an unversioned collection. * * With it, `status` is refused on create and update with a `422` (ADR 0021): * on a versioned page, only publish and unpublish change who sees it. */ versionsTable?: SQLiteTable; /** * Remember a page's old URL when its slug changes (#574). Pass the * `pageRedirects` table from `louise-toolkit/db`, added to your schema. An * update that changes a slug records `/old → /new` in the same batch as the * write, and a page created or renamed onto an old path clears the redirect * away from it, so a redirect never shadows a page. Serve them with * `resolvePageRedirect`. */ redirects?: typeof pageRedirects; /** * Keep an update in the page's pending draft (#530). An update writes the * live row, but publish copies the whole draft snapshot onto that row, so * without this, a rename made while a draft was pending comes undone at the * next publish, and a changed slug moves the page back to its old URL. * * With it, an update that changes a field of `config` also saves those * fields into the pending work: the KV buffer, else the newest pending draft. * A page with no pending work gets no draft. Pass the same `config` and * `bufferKv` as `versionsRoute`; it needs {@link versionsTable}. */ drafts?: { /** The collection config; its fields are the ones a draft snapshot holds. */ config: CollectionConfig; /** The KV draft buffer, as `versionsRoute` takes it. */ bufferKv?: (env: Env) => DraftBufferKV | undefined; }; } /** Keep only allowlisted fields from `input`, sanitizing the rich ones. Pure. */ declare function pickFields(input: Record, fields: Iterable, richFields: Iterable, sanitize: (html: string) => string): Record; /** * Build the `pages` editor route. Handles the collection path (GET list, POST * create) and the `/:id` item path (GET/PATCH/DELETE), where `:id` is all * digits. Returns `undefined` for any other path so `composeWorker` falls * through, which is what lets `versionsRoute`, `searchRoute`, and the other * routes under the same prefix mount in any order around it. */ declare function pagesRoute(config: PagesRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/search.d.ts /** Optional semantic-search deps for {@link SearchRouteConfig}. Supply both a * Vectorize index and a Workers AI runner (typically `(env) => env.VECTORIZE` * and `(env) => env.AI`); return `undefined` from either—the binding isn't * provisioned—and the route runs FTS-only, no error surfaced. */ interface SearchVectorConfig { /** The Vectorize index holding this collection's embedded content. */ index: (env: Env) => VectorIndex | undefined; /** The Workers AI runner used to embed the query. */ ai: (env: Env) => AiRunner | undefined; /** Embedding model id—MUST match the model the index was built with. */ model?: string; /** Route the query embedding through AI Gateway (#87)—caching, cost caps. */ gateway?: (env: Env) => AiGatewayOptions | undefined; /** How many nearest neighbours to pull before fusing. Default 20. */ topK?: number; /** Drop semantic matches scored below this floor before fusing, so a query * that matches nothing adds nothing. No default: omit it to keep every * match. See `SemanticSearchOptions.minScore` in `louise-toolkit/ai`. */ minScore?: number; } interface SearchRouteConfig { /** The searchable collection's main table. */ table: SQLiteTable; /** The collection config—must declare `search.fields`. */ config: CollectionConfig; /** Resolve the editor session (search is editor-only). */ resolveEditor: ResolveEditor; /** Mount path (the collection base). Default `/api/louise/pages`. */ path?: string; /** Optional semantic layer (#86). Omit for FTS-only search. */ vector?: SearchVectorConfig; } /** * Build the search route for a collection with a `search` config. Returns * `undefined` for any path it doesn't own so `composeWorker` falls through. */ declare function searchRoute(cfg: SearchRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/seo-fix.d.ts /** Default per-call cap for the SEO backfill (bounds AI/subrequest budget). */ declare const DEFAULT_SEO_FIX_BATCH = 8; interface SeoFixRouteConfig { /** The pages-like table (needs `id`, `status`, `seo_title`, `seo_description`). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** The Workers AI runner—typically `(env) => env.AI`. `undefined` → 503. */ ai: (env: Env) => AiRunner | undefined; /** Columns concatenated (HTML-stripped) as the model's content. Default `["title","body"]`. */ contentColumns?: string[]; /** Max pages fixed per call. Default {@link DEFAULT_SEO_FIX_BATCH}. */ batch?: number; /** Model/token options for `suggestSeo`. */ seoOptions?: SeoOptions; /** Optional AI Gateway routing (#87) for the SEO call. */ gateway?: (env: Env) => AiGatewayOptions | undefined; /** Mount path. Default `/api/louise/pages/generate-seo`; applying is at * `/apply`. */ path?: string; /** * The draft dependencies of a versioned pages collection, as `versionsRoute` * takes them (#549). An accepted suggestion is then saved as a draft through * `applySaveDraft`, so version history holds it and a later publish can't * blank it again; without it, it's written to the live row. */ drafts?: SaveDraftDeps; } /** * Build the SEO backfill route. Returns `undefined` for a non-matching path so * `composeWorker` falls through. Only POST is served; an optional `{ id }` in the * body targets one page (else a bulk backfill of published pages missing SEO). */ declare function seoFixRoute(config: SeoFixRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/ai.d.ts interface AiRouteConfig { /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** * The Workers AI runner—typically `(env) => env.AI`. Return `undefined` (for example, * the binding isn't provisioned) and the route answers 503, so the assist is * cleanly absent rather than erroring. */ ai: (env: Env) => AiRunner | undefined; /** Optional AI Gateway routing (#87) for the rewrite/SEO calls: caching, cost * caps, fallbacks, logging. Given the runtime `env`, return the gateway config * (or `undefined` to call Workers AI directly). */ gateway?: (env: Env) => AiGatewayOptions | undefined; /** * The site's voice for rewrites (#553): `instructions` (voice, audience, and * locale, in plain words) and up to two before-and-after `examples`. A site * fact, so a parameter; there's no default. */ rewrite?: Pick; /** The site's voice for SEO suggestions: `instructions`, as for rewrites. */ seo?: Pick; /** Mount base. Default `/api/louise/ai`. */ path?: string; } /** * Build the AI assists route. Returns `undefined` for any path it doesn't own so * `composeWorker` falls through. Each action is a POST guarded as a mutation * (same-origin + editor session), since it spends AI budget. */ declare function aiRoute(cfg: AiRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/resume.d.ts /** The columns a `${slug}_versions` table has—see content codegen's `collectionVersionsTable`. */ type VersionsTable = SQLiteTable & { id: SQLiteColumn; parentId: SQLiteColumn; status: SQLiteColumn; versionData: SQLiteColumn; }; interface ResumeDraftDeps { /** The collection's `${slug}_versions` table. */ versionsTable: VersionsTable; /** The collection slug—keys the KV buffer, as `applySaveDraft` does. */ collection: string; /** * The draft buffer, when the site turned buffering on (`bufferKv` in * `SaveDraftDeps`). Pass the same namespace, or a buffered edit newer than * the last D1 flush is invisible here. Omit when buffering is off. */ bufferKv?: DraftBufferKV; } /** The live row fields the read needs. */ interface ResumeDraftRow { id: number; /** * The row's pointer. No longer read: a draft is superseded when it's at or * below the highest version ever promoted (ADR 0021), which the query * finds itself. Kept so existing callers that pass the row still compile. */ publishedVersionId?: number | null; } /** * The editor's work-in-progress snapshot for a row, or `null` when there is * none (render the live row). Precedence matches `applySaveDraft`'s merge base: * * 1. the KV buffer, when `bufferKv` is given and holds one; * 2. the newest draft newer than every version ever promoted—an older draft * is superseded work, and resuming it would silently revert the page in * edit mode (the same rule as {@link latestPendingDraft}, ADR 0021). * * `d1` may be a raw binding or a Sessions-API session. For read-your-writes * behind read replication, pass one opened from the editor's bookmark * (`openD1Session(env.DB, readD1Bookmark(request))`), so a draft saved a * moment ago is visible to the page load that follows it. * * Returns the whole snapshot on purpose: which fields a page renders from it * (`sections`, `body`, …) is the site's schema, not this function's. */ declare function resumeDraft(d1: D1Client, deps: ResumeDraftDeps, row: ResumeDraftRow): Promise | null>; //#endregion //#region src/core/editor/media.d.ts /** Env for the media route: the D1 binding plus the R2 bucket + its public URL. * An optional `IMAGES` binding, when present, is used to read upload dimensions * via `.info()` (covers AVIF/TIFF). */ interface MediaRouteEnv extends EditorRouteEnv { MEDIA: R2Bucket; MEDIA_URL: string; IMAGES?: ImagesBinding; } interface MediaRouteConfig { /** The `media` table (composed from `mediaColumns` or the ready-made `media`). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Delete-safety sources: which `(table, columns)` to scan for a key before * deleting it (rich-text embeds, image-URL arrays, settings JSON). */ referenceSources?: MediaRefSource[]; /** Upload key prefix. Default `"web"`. */ scope?: string; /** Max accepted upload size in bytes (passed to `putMedia`). */ maxBytes?: number; /** Max rows returned by GET. Default 500. */ limit?: number; /** Mount path. Default `/api/louise/media`. */ path?: string; /** * Auto-generate alt text for uploaded images via Workers AI (#75). Given the * runtime `env`, return the AI runner (`env.AI`) to fill each new upload's * `alt` from the image; return `undefined` (or omit) to skip—uploads then * behave exactly as before (empty `alt`, set by hand in the media panel). * Best-effort: a model error or missing binding never fails the upload. */ altText?: (env: Env) => AiRunner | undefined; /** Model/prompt/token options for {@link altText} generation. */ altTextOptions?: AltTextOptions; /** Max images the one-click alt backfill (`POST /generate-alt`) fixes per call, * so a big library can't blow the Worker's subrequest/AI budget in one go; * the client re-runs until the count reaches zero. Default {@link DEFAULT_ALT_FIX_BATCH}. */ altFixBatch?: number; } /** * The SQL condition for an image whose alt text hasn't been written (#599). * Only NULL counts: `""` is an image the owner marked decorative, which HTML * says to skip. A site's health scan should count with this, so a decorative * image leaves the "missing a description" list. */ declare const MEDIA_ALT_MISSING_SQL = "(\"alt\" IS NULL)"; /** * The one-time migration for the three alt states (#599). Before, an empty * alt meant both "not written" and "cleared", so an existing `''` is * ambiguous; this makes each one "not written", and the owner marks what's * decorative. Run it before the new count goes live, with the table your * media registry uses. */ declare const MEDIA_ALT_UNDECIDED_SQL: (table?: string) => string; /** * Build the `media` editor route. GET lists the registry newest-first (each * item carries its public `url`), and `GET ?references=` returns * `{ references }` for one file. POST uploads + registers a verified image, * DELETE removes an asset after the reference scan (`409 in_use` unless * `?force=1`). Returns `undefined` for a non-matching path. */ declare function mediaRoute(config: MediaRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/media-list.d.ts interface ListMediaRouteConfig { /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Delete-safety sources: which `(table, columns)` to scan for a key before * deleting it. Omit to skip the scan. */ referenceSources?: MediaRefSource[]; /** Allowed upload scopes (R2 key prefixes); the first is the default when the * form omits `scope` or sends one not in the list. Default `["web"]`. */ scopes?: string[]; /** Max accepted upload size in bytes (passed to `putMedia`). */ maxBytes?: number; /** Mount path. Default `/api/louise/media`. */ path?: string; } /** * Build a registry-less `media` editor route. GET lists the R2 bucket * newest-first (each item carries its public `url`), and `GET ?references=` * returns `{ references }` for one file. POST uploads a verified * image under an allowlisted `scope`, DELETE removes an object after the * reference scan (`409 in_use` with `{ references }` unless `?force=1`). No D1 * `media` table is read or written. Returns `undefined` for a non-matching path. */ declare function listMediaRoute(config: ListMediaRouteConfig): WorkerRoute; //#endregion //#region src/core/editor/seed.d.ts interface SeedRouteConfig { /** The `site_settings` table (composed or ready-made). */ table: SQLiteTable; /** Resolve the editor session (site wraps its own auth). */ resolveEditor: ResolveEditor; /** Column values (Drizzle property keys) for the initial row. Default `{}`. */ defaults?: Record; /** Singleton row id. Default 1. */ id?: number; /** Mount path. Default `/api/louise/seed`. */ path?: string; /** Let a same-origin GET trigger the seed (a clickable Settings link). Default true. */ allowGet?: boolean; } /** * Build the `seed` editor route. Ensures the settings singleton exists (insert * with `defaults` when absent), idempotently. Returns `{ seeded: false }` when * the row already existed. Returns `undefined` for a non-matching path. */ declare function seedRoute(config: SeedRouteConfig): WorkerRoute; //#endregion export { type AiRouteConfig, type BlobSanitize, type BlobSettingsRouteConfig, type BufferedDraft, DEFAULT_FLUSH_MS, DEFAULT_PAGE_FIELDS, DEFAULT_SEO_FIX_BATCH, DRAFT_BASE_KEY, DRAFT_BUFFER_TTL_SECONDS, type DraftBufferKV, type DraftConflict, type DraftSoftLockTarget, type DraftSoftLocks, type EditorRouteEnv, type EditorsRouteConfig, type FormOutcome, type FormRouteConfig, type FormRouteEnv, type HealthRouteConfig, type IncidentsRouteConfig, type InquiriesRouteConfig, type ListMediaRouteConfig, MEDIA_ALT_MISSING_SQL, MEDIA_ALT_UNDECIDED_SQL, type MediaRouteConfig, type MediaRouteEnv, type OverviewContent, type OverviewData, type OverviewHealth, type OverviewInbox, type OverviewRouteConfig, type PagesRouteConfig, type PagesWrite, type PublishDeps, type PublishResult, type ResolveEditor, type ResolvedField, type ResumeDraftDeps, type ResumeDraftRow, type RunStatusChecksOptions, SITEMAP_MAX_AGE_SECONDS, STATUS_CHECK_TIMEOUT_MS, type SaveCollectionConfig, type SaveDraftDeps, type SaveDraftOptions, type SaveDraftResult, type SaveRouteConfig, type SearchRouteConfig, type SearchVectorConfig, type SeedRouteConfig, type SeoFixRouteConfig, type SettingsPartition, type SettingsPatchConfig, type SettingsRouteConfig, type SettingsRouteHooks, type SettingsSanitize, type SitemapRouteConfig, type StatusCheck, type StatusCheckReport, type StatusCheckResult, type StatusD1, type StatusReport, type StatusRouteConfig, type StatusTimestamp, type SubmissionsRouteConfig, type VersionsRouteConfig, ageCheck, aiRoute, applyFieldSave, applyPublish, applySaveDraft, applySettingsPatch, blobSettingsRoute, clearDraftBuffer, d1Check, draftBufferKey, editorsRoute, fieldRev, fieldRevs, formRoute, guardEditor, healthRoute, ident, incidentsRoute, inquiriesRoute, json, latestPendingDraft, listMediaRoute, matchPath, mediaRoute, mergeBlobPatch, overviewRoute, pagesRoute, parseDraftBase, partitionSettingsPatch, pickFields, readDraftBuffer, resolveFieldValue, resumeDraft, runEditorRoute, runStatusChecks, sanitizeSettingsPatch, saveRoute, searchRoute, seedRoute, seoFixRoute, settingsRoute, shouldFlushBuffer, sitemapRoute, statusRoute, submissionsRoute, tableMeta, validateSettingsImages, validateSettingsLinks, versionsRoute, writeDraftBuffer };