import { c as LouiseError, y as DegradedEvent } from "./errors-CyuuoKx0.js"; import { i as EditorSession } from "./types-B8yzm4Q0.js"; //#region src/core/incidents/report.d.ts /** Where a failure came from: the Worker handler that saw it, or a fallback. */ type IncidentKind = "fetch" | "queue" | "scheduled" | "degraded"; /** * One failure, flat and JSON-serializable, so it crosses a queue or an HTTP * call unchanged. Build one with {@link buildIncidentReport} or * {@link incidentFromDegraded}, which redact it, rather than by hand. */ interface IncidentReport { readonly kind: IncidentKind; /** The grouping key from {@link fingerprintFailure}: 16 hex characters. */ readonly fingerprint: string; /** The error's class (`TypeError`), or a degrade's dotted name (`commerce.products`). */ readonly name: string; /** A `LouiseError`'s `code` (`DB_ERROR`), when the cause was one. */ readonly code?: string; /** One line, redacted, at most {@link MAX_INCIDENT_MESSAGE} characters. */ readonly message: string; /** * The request's pathname for `fetch`, never its query string; the queue's * name for `queue`; the cron expression for `scheduled`. Redacted like the * message, since a path can carry a token. */ readonly path?: string; /** The request's host, so preview traffic stays apart from production. */ readonly host?: string; /** The deployed version, when the site knows it. */ readonly release?: string; /** Whether the site marked this failure critical. */ readonly critical: boolean; /** Epoch milliseconds. */ readonly at: number; } /** What a sink gets beside the report. */ interface IncidentSinkContext { /** The Worker's bindings, for a sink that writes somewhere, such as D1. */ readonly env: Env; /** * The value that was thrown, or a degrade's cause, as it was: with its stack, * unredacted. An error whose `cause` chain holds a failed query is the * exception: it arrives as `loggableError`'s copy, of the same class and with * the same own fields, without the SQL and bound values its messages and * stacks carried. It lives in memory only. A sink that sends it anywhere, such * as an error tracker, owns scrubbing it first. */ readonly cause?: unknown; } /** * Takes each report. Capture runs a sink after the response, and a sink that * throws or rejects is logged and ignored, so it can't fail the request it's * reporting on. */ type IncidentSink = (report: IncidentReport, context: IncidentSinkContext) => void | Promise; /** Longest `message` a report keeps, counting the ellipsis that marks a cut. */ declare const MAX_INCIDENT_MESSAGE = 500; /** What {@link buildIncidentReport} takes. Everything but `kind` is optional. */ interface IncidentInput { readonly kind: IncidentKind; /** Whatever was thrown or caught. Its name, message, and code fill the report. */ readonly cause?: unknown; /** Overrides the cause's name, for example, with a degrade's dotted name. */ readonly name?: string; /** Overrides the cause's message. */ readonly message?: string; /** The request being served, for `path` and `host`. */ readonly request?: Request; /** The path when there's no request: a queue's name, a cron expression. */ readonly path?: string; readonly release?: string; readonly critical?: boolean; /** Epoch milliseconds. Defaults to `Date.now()`. */ readonly now?: number; } /** * Build a redacted {@link IncidentReport}. It never throws, whatever `cause` * holds: it runs while something else is already failing. * * @example * ```ts * try { * return await handle(request, env); * } catch (err) { * const report = buildIncidentReport({ kind: "fetch", cause: err, request }); * ctx.waitUntil(sink(report)); * throw err; * } * ``` */ declare function buildIncidentReport(input: IncidentInput): IncidentReport; /** * The report for a `reportDegraded` call: kind `degraded`, named for the * fallback that fired, with the cause's code when it was a `LouiseError`. */ declare function incidentFromDegraded(event: DegradedEvent, options?: Pick): IncidentReport; /** * Whether a report matches the site's critical list. Only the site knows which * failures matter most, so the list is a parameter (ADR 0022 § 6). An entry * that starts with `/` is a path prefix: `/cart` matches `/cart` and * `/cart/checkout`, not `/cartoon`. Any other entry is a name, and matches * that name and the dotted names under it: `commerce.checkout` matches * `commerce.checkout.session` too. */ declare function isCriticalIncident(report: Pick, critical: readonly string[]): boolean; /** * The grouping key for a failure: 16 hex characters from the kind, the name, * the code, and the message with its variable parts replaced (numbers, IDs, * quoted values, email addresses, tokens). "Row 41 not found" and "Row 97 not * found" share a fingerprint. * * It leaves out the path, so one bug across many pages is one incident; the * stack, whose line numbers move with every deploy; and the release, so a * failure that comes back after a fix reads as the same incident. It's pure * and synchronous, and gives the same answer for a raw message and for the * redacted one a report stores. */ declare function fingerprintFailure(failure: { readonly kind: IncidentKind; readonly name: string; readonly code?: string; readonly message: string; }): string; /** * The redaction every report's `message` and `path` get: a failed query's SQL * and bound values (`Failed query: … params: …`) shrink to the statement's * kind and table, email addresses become `[email]`, and a run of 24 or more * token characters that includes a digit becomes `[redacted]`. It's a floor, * not a guarantee, so never put personal data in an error message or a * degrade's details. */ declare function redactMessage(text: string): string; //#endregion //#region src/core/worker/capture.d.ts /** How `onIncident` is configured, in full. */ interface IncidentCaptureOptions { /** One sink or several. Each gets every report. */ readonly sinks: IncidentSink | readonly IncidentSink[]; /** * The failures that should alert: dotted names (`commerce.checkout`) and * path prefixes (`/cart`). See `isCriticalIncident`. Everything else is * counted and alerts no one. */ readonly critical?: readonly string[]; /** * The deployed version, read from the Worker's bindings, for example, a * version metadata binding's `id`. Omitted, reports carry no release. */ readonly release?: (env: Env) => string | undefined; } /** What `onIncident` takes: one sink, a list, or the full options. */ type IncidentCapture = IncidentSink | readonly IncidentSink[] | IncidentCaptureOptions; /** * Wrap a Worker's handlers so every failure they see becomes an incident. * `composeWorker` does this for you when you pass `onIncident`; call it * directly only for a handler you compose by hand. Call it once per Worker, * at module scope: each call listens for degrades and emitted incidents in * this isolate. * * `fetch`, `queue`, and `scheduled` keep their behavior. A throw is reported, * then re-thrown. An error whose `cause` chain holds a failed query, the query * error itself or an error that wraps one, is re-thrown as `loggableError`'s * copy, so the runtime's exception record doesn't keep its bound values. The * copy has the original's class, `name`, `code`, and other own fields, so an * `instanceof` check or a `code` mapping above it still matches; only the * query error's message and stack change, and its `query` and `params` are * left out. An error too big or too deep to check (a `cause` chain past ten * levels, or more than 5,000 fields or values) is copied too, with what's past * the limit left out. Any other thrown value is re-thrown as it was. A handler that * isn't there stays absent. */ declare function withIncidentCapture(handler: ExportedHandler, capture: IncidentCapture): ExportedHandler; /** * Report a failure you caught, as an incident, from code that has no `env` or * `ctx` of its own: framework middleware, a library callback. It joins the * degrades waiting for the next handler in this isolate to finish, and * reaches `composeWorker`'s `onIncident` sinks then. Without `onIncident`, * nothing listens, and it does nothing. It never throws. * * A cause reported here isn't reported again if it's re-thrown and reaches * `composeWorker`, so re-throwing after reporting is safe. * * @example * ```ts * try { * return await next(); * } catch (err) { * reportIncident({ kind: "fetch", cause: err, request }); * throw err; * } * ``` */ declare function reportIncident(input: IncidentInput): void; //#endregion //#region src/core/worker/gate.d.ts /** * Resolve the editor (admin) session for a request. The site wraps its own * auth—typically `resolveEditorSession(getLouiseAuth(env, url), request)`. * Returning `null` means "not an editor". */ type ResolveEditor = (request: Request, env: Env) => EditorSession | null | Promise; interface ApiGateConfig { /** The same resolver the editor routes are given. Passing the same function * means the session is looked up once per request, not once per layer. */ resolveEditor: ResolveEditor; /** * Path the gate protects. Default `/api/louise`. Matched on a segment * boundary: `/api/louise` and `/api/louise/…`, never `/api/louise-foo`. */ prefix?: string; } /** Where the editor API lives unless a site says otherwise. */ declare const LOUISE_API_PREFIX = "/api/louise"; /** `formRoute`'s default mount: one path per form, `/`. */ declare const LOUISE_FORMS_PATH = "/api/louise/forms"; /** `vitalsRoute`'s default mount. */ declare const LOUISE_VITALS_PATH = "/api/louise/vitals"; /** `statusRoute`'s default mount. */ declare const LOUISE_STATUS_PATH = "/api/louise/status"; /** * Whether `pathname` is where one of the toolkit's own public routes mounts * by default—a form submission, the vitals beacon, or the status probe. * * `composeWorker` doesn't need this: it can see a {@link publicRoute} mark * before the route runs. A gate that can't—framework middleware, which runs * before it knows which file will answer—exempts these paths instead, so an * anonymous visitor can still submit a form mounted as a framework route. */ declare function isLouisePublicPath(pathname: string): boolean; /** Whether `pathname` falls under `prefix`, on a segment boundary. */ declare function underPrefix(pathname: string, prefix: string): boolean; /** * Mark a route as reachable without an editor session under the gated prefix: * a contact form, a vitals beacon, a status probe. The route that is public says so here, * rather than a path list in the site's config that drifts from the code. * A public route still does its own checks (origin, validation, rate limit). */ declare function publicRoute(route: WorkerRoute): WorkerRoute; /** `mcpRoute`'s default mount, the one route that takes a bearer token. */ declare const LOUISE_MCP_PATH = "/api/louise/mcp"; /** * Mark a route that authenticates a bearer token itself. A request that * carries `Authorization: Bearer` reaches it without the gate's cookie check, * and the route verifies the token and refuses the request if it's no good. * Every other route under the prefix still turns a bearer-only request away, * so a token reaches only the routes that declared they take one (ADR 0012). * * A request with no bearer token goes through the gate as usual, so a marked * route still serves a signed-in editor in a browser under cookie rules. */ declare function bearerRoute(route: WorkerRoute): WorkerRoute; /** * Whether a request carries a bearer credential. Only the scheme counts here; * the route the request reaches decides whether the token is any good. */ declare function hasBearerCredential(request: Request): boolean; /** * Decide whether `request` may enter the editor API. Returns `null` to let it * through—including every request outside the prefix, which isn't the gate's * business—or the 401/403 `Response` to send instead. * * Credentials are the session cookie, so every unsafe method is origin-checked * (CSRF). So is a WebSocket upgrade: it's a GET, and a cross-site page can open * a socket that carries the editor's cookie, so method alone would let it by. * A bearer token (ADR 0009) isn't a credential here: it reaches only a * {@link bearerRoute}, which checks it itself and skips the origin check * because a browser can't attach one cross-site. That's decided by which * credential the route authenticated, never by a missing `Origin`. */ declare function louiseApiGate(request: Request, env: Env, config: ApiGateConfig): Promise; //#endregion //#region src/core/worker/healing.d.ts /** * The subset of `LouiseError.code`s that represent *transient* infrastructure * failures—the ones generally safe to retry, given an idempotent route. * Provided as guidance for building a policy; `withHealing` itself matches on * whatever codes your `rules` declare, not on this list. */ declare const TRANSIENT_CODES: readonly ["DB_ERROR", "CACHE_ERROR", "STORAGE_ERROR", "QUEUE_ERROR"]; /** * Context handed to a rule's `fallback` / `escalate` callback describing the * failure being healed. Carries the request and the typed error so a fallback * can consult a stale cache and an escalation can build a diagnostic payload. */ interface HealingContext { readonly request: Request; readonly env: Env; readonly ctx: ExecutionContext; /** The typed error that triggered healing (the last one, if retried). */ readonly error: LouiseError; /** `error.code`—the key matched against the policy (for example, "DB_ERROR"). */ readonly code: string; /** How many times the route was invoked before giving up (>= 1). */ readonly attempts: number; } /** What to do when a route throws a `LouiseError` of a given code. */ interface HealingRule { /** * Extra attempts after the first failure (0 = never retry). Each retry * re-invokes the wrapped route. Only enable for idempotent routes. */ readonly retries?: number; /** * Base backoff in ms between retries; attempt N waits * `backoffMs * 2 ** (N - 1)`. Defaults to 0 (retry immediately). Backoff * holds the request open, so keep it small on the hot path. */ readonly backoffMs?: number; /** * Serve this Response instead of throwing once retries are exhausted—the * "stale-fallback" strategy. Return for example, a cached copy or a graceful * degraded page. If omitted (and nothing else handles it), the error * re-throws. */ readonly fallback?: (ctx: HealingContext) => Response | Promise; /** * Hand the failure off out-of-band. Runs via `ctx.waitUntil`, so it never * blocks the response and its own errors can't break the request. This is * where a self-updating pipeline hooks in—for example, `enqueue(env.HEAL_QUEUE, * describeFailure(ctx))`. */ readonly escalate?: (ctx: HealingContext) => void | Promise; } interface HealingOptions { /** Recovery rules keyed by `LouiseError.code`. */ readonly rules: Readonly>>; /** * Applied when a caught `LouiseError`'s code has no explicit rule. Omit to * re-throw unrecognized codes (the safe default—never heal what you didn't * plan for). */ readonly fallbackRule?: HealingRule; /** * Injected delay for backoff. Defaults to a real `setTimeout`. Tests pass a * resolved no-op to run backoff logic without real time passing. */ readonly sleep?: (ms: number) => Promise; } /** * Wrap a {@link WorkerRoute} so thrown `LouiseError`s are healed by policy * instead of surfacing as failures. * * On each invocation the wrapped route runs. If it returns (a `Response` or * `undefined` pass-through) that value is returned unchanged. If it throws: * * 1. Non-`LouiseError`s re-throw immediately—we only heal typed errors. * 2. The error's `code` selects a rule (`rules[code]`, else `fallbackRule`). * No matching rule ⇒ re-throw. * 3. While attempts remain under the rule's `retries`, back off and re-run. * 4. Once retries are exhausted: `escalate` (fire-and-forget via * `waitUntil`), then `fallback` (return its Response, after a * `reportDegraded("worker.healing", …)` line)—or re-throw the last error * if the rule has neither. * * @example * const healed = withHealing(apiRoute, { * rules: { * DB_ERROR: { * retries: 2, * backoffMs: 50, * fallback: ({ request }) => serveStale(request), * escalate: ({ env, ...c }) => enqueue(env.HEAL_QUEUE, describeFailure(c)), * }, * }, * }); * export default composeWorker({ routes: [healed], fetch: ssrHandler }); */ declare function withHealing(route: WorkerRoute, options: HealingOptions): WorkerRoute; /** * A serializable snapshot of a healed failure—the payload you'd hand to an * out-of-band recovery job (a queue message, a log line, a self-updating * agent's work item). Deliberately flat and dependency-free so it survives * `JSON.stringify` across a queue boundary. */ interface FailureReport { /** `LouiseError.code`, for example, "DB_ERROR". */ readonly code: string; /** The error's message. A failed query's SQL and bound values, in it or * under it, are reduced the way `loggableError` reduces them. */ readonly message: string; readonly method: string; /** * The request's pathname only. A query string can carry a token, and this * report is meant to leave the request: onto a queue, into a log. */ readonly url: string; /** Attempts made before giving up. */ readonly attempts: number; /** Epoch ms when the report was built. */ readonly at: number; } /** * Build a {@link FailureReport} from a {@link HealingContext}—the concrete * thing an `escalate` hook enqueues. `now` is injectable for deterministic * tests. */ declare function describeFailure(ctx: HealingContext, now?: number): FailureReport; //#endregion //#region src/core/worker/edge-cache.d.ts /** Default cacheability-signal header: Cloudflare's own CDN-Cache-Control, which * is what a Cloudflare-targeting SSR adapter emits for a cacheable response. * Consumed here as the route's signal, then stripped so Cloudflare's automatic * (cookie-blind) edge cache never sees it. Override with * {@link EdgeCacheConfig.signalHeader} when a host signals some other way. */ declare const CDN_CACHE_CONTROL = "cloudflare-cdn-cache-control"; /** * Is `directive` an opt-in-to-cache Cache-Control value—`public`/unspecified * with a positive `max-age`, and not `no-store`/`no-cache`/`private`? The * provider emits `no-store` for any response a route didn't opt in (including * edit-mode `set(false)`), so this cleanly separates cacheable published renders * from everything else. */ declare function isCacheableDirective(directive: string | null | undefined): boolean; interface EdgeCacheConfig { /** * Return `true` to skip the cache (both read and write) for this request and * always run the handler—for example, an authenticated editor whose render is * personalized. Its response is still stripped of the cache signal, so it can * never be edge-cached either. */ bypass?: (request: Request) => boolean; /** The `Cache` to use. Defaults to `caches.default`. Injectable for tests. */ cache?: () => Cache; /** * The response header carrying the route's cacheability decision. Defaults to * {@link CDN_CACHE_CONTROL}. * * Configurable rather than hard-coded because WHICH header a route uses to say * "cache me" is the host's convention, not this layer's: a Cloudflare-targeting * SSR adapter emits `Cloudflare-CDN-Cache-Control`, and a host that signals * differently should not have to adopt that name to use this cache. */ signalHeader?: string; } /** * The URL a response is stored under: the request URL with tracking params * removed and the survivors sorted. Without this every `?utm_source=…` variant * of a shared link mints its own entry, so campaign traffic—exactly the burst * a cache is meant to absorb—would miss on almost every request. Only the * *key* is normalized; the handler still receives the untouched request, so a * page that reads its own query string is unaffected. */ declare function edgeCacheKeyUrl(url: string): string; /** * The default edit-mode cookie name—the one `createLouiseMiddleware` sets when * a visitor enters edit mode. * * Exported so the cookie and the predicate that looks for it are declared in one * place. Anything writing its own `"louise_edit"` literal would keep * working right up until the middleware default moved, and then fail by serving * an editor a cached public page—which is the exact bug this whole layer * exists to prevent, and the one that is hardest to notice. */ declare const LOUISE_EDIT_COOKIE = "louise_edit"; /** * Is this an edit-mode request? Detected by the edit cookie. * * Intended as the {@link EdgeCacheConfig.bypass} predicate, so an editor is * never served—nor stores into—the shared public cache entry, and always * gets a fresh personalized render. * * Pass `cookieName` when the middleware was configured with a custom * `editCookie`; the two must agree or the bypass silently stops bypassing. */ declare function isEditRequest(request: Request, cookieName?: string): boolean; declare function withEdgeCache(handler: (request: Request, env: Env, ctx: ExecutionContext) => Response | Promise, config?: EdgeCacheConfig): (request: Request, env: Env, ctx: ExecutionContext) => Promise; //#endregion //#region src/core/worker/kv-cache.d.ts /** The subset of a KV namespace this uses. */ interface KvCacheStore { get(key: string): Promise; put(key: string, value: string, options?: { expirationTtl?: number; }): Promise; delete(key: string): Promise; } interface KvCachedOptions { /** How long a value (and a miss) stays cached. At least 60—KV's minimum. */ ttlSeconds: number; /** * Cache `null` results too. Default `true`: a lookup keyed by something a * visitor controls (a hostname, a slug) otherwise costs one database read * per garbage request—this makes it one read per key per TTL. */ cacheMisses?: boolean; } /** * Read `key` from KV, or run `load` and store what it returns (JSON). `null` * from `load` means "not found" and is cached too, unless `cacheMisses: false`. * * Fails open: a KV read or write that throws is reported with `reportDegraded` * and otherwise ignored, and `load` runs, so a cache outage costs speed, never * correctness. A value that no longer parses * is treated as a miss. `kv` may be `undefined` (unbound in dev)—then this * is just `load()`. * * After a write to the underlying data, call {@link kvBust} for the key, or * readers see the old value for up to `ttlSeconds`. */ declare function kvCached(kv: KvCacheStore | undefined, key: string, load: () => Promise, options: KvCachedOptions): Promise; /** Drop a cached key after the data behind it changes. Fails open, like the * read, but a failed bust means readers can see the old value for up to the * TTL, so it's reported with `reportDegraded`. */ declare function kvBust(kv: KvCacheStore | undefined, key: string): Promise; //#endregion //#region src/core/worker/index.d.ts /** * A Louise-owned route: return a `Response` to handle the request, or * `undefined` to pass it to the next route (and ultimately the SSR fallback). */ type WorkerRoute = (request: Request, env: Env, ctx: ExecutionContext) => Response | undefined | Promise; /** * @typeParam Env - the Worker's bindings. * @typeParam QMessage - the queue's message type. Supply it (rather than * leaving the `unknown` default) so the `queue` consumer receives a typed * `MessageBatch` instead of having to cast every message body. */ interface ComposeWorkerOptions { /** Ordered route handlers; the first to return a `Response` wins. */ routes?: WorkerRoute[]; /** Fallback when no route matches—typically the handler the framework's * Cloudflare adapter exposes. */ fetch: NonNullable["fetch"]>; /** Optional Queue consumer, passed through unchanged. */ queue?: NonNullable["queue"]>; /** Optional Cron/scheduled handler, passed through unchanged. */ scheduled?: NonNullable["scheduled"]>; /** * Deny-by-default gate for the editor API (ADR 0012). Set it and every * request under `/api/louise` must resolve to an editor unless it's headed * for a {@link publicRoute}—including the site's own framework routes * under that prefix, which the fallback serves after the gate. Every route * response also gets the baseline security headers the site's middleware * never sees. Omitted, `composeWorker` behaves exactly as before. */ gate?: ApiGateConfig; /** * Incident capture (ADR 0022). Set it and a throw from `fetch`, `queue`, or * `scheduled`, and every `reportDegraded` call, becomes an * `IncidentReport` sent to these sinks after the response. A throw is still * re-thrown, so responses don't change. One sink, a list, or * `{ sinks, critical, release }`. Omitted, nothing is captured. */ onIncident?: IncidentCapture; } /** * Compose a Cloudflare `ExportedHandler` from Louise-owned routes plus an SSR * fallback, with optional `queue`/`scheduled` handlers. On `fetch`, each route * runs in order and the first `Response` short-circuits; if none match, the * `fetch` fallback handles it. With `gate`, the editor API is deny-by-default * (see {@link ComposeWorkerOptions.gate} and ADR 0012). With `onIncident`, * every failure the handlers see is reported (see * {@link ComposeWorkerOptions.onIncident} and ADR 0022). */ declare function composeWorker(options: ComposeWorkerOptions): ExportedHandler; //#endregion export { hasBearerCredential as A, IncidentKind as B, LOUISE_API_PREFIX as C, LOUISE_VITALS_PATH as D, LOUISE_STATUS_PATH as E, IncidentCapture as F, buildIncidentReport as G, IncidentSink as H, IncidentCaptureOptions as I, isCriticalIncident as J, fingerprintFailure as K, reportIncident as L, louiseApiGate as M, publicRoute as N, ResolveEditor as O, underPrefix as P, withIncidentCapture as R, ApiGateConfig as S, LOUISE_MCP_PATH as T, IncidentSinkContext as U, IncidentReport as V, MAX_INCIDENT_MESSAGE as W, redactMessage as Y, HealingOptions as _, KvCachedOptions as a, describeFailure as b, CDN_CACHE_CONTROL as c, edgeCacheKeyUrl as d, isCacheableDirective as f, HealingContext as g, FailureReport as h, KvCacheStore as i, isLouisePublicPath as j, bearerRoute as k, EdgeCacheConfig as l, withEdgeCache as m, WorkerRoute as n, kvBust as o, isEditRequest as p, incidentFromDegraded as q, composeWorker as r, kvCached as s, ComposeWorkerOptions as t, LOUISE_EDIT_COOKIE as u, HealingRule as v, LOUISE_FORMS_PATH as w, withHealing as x, TRANSIENT_CODES as y, IncidentInput as z };