brumate 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{boot-Difa0qdg.d.ts → boot-DkbcqdUz.d.ts} +2 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-De-7aGlO.js → client-C3vRNuLi.js} +353 -103
  4. package/dist/client-C3vRNuLi.js.map +1 -0
  5. package/dist/{client-DvsU9qxG.d.ts → client-CqGDbWd_.d.ts} +45 -8
  6. package/dist/{defer-DlFYiAuK.js → defer-M18UKyfG.js} +2 -2
  7. package/dist/{defer-DlFYiAuK.js.map → defer-M18UKyfG.js.map} +1 -1
  8. package/dist/{devtools-Di_dI9tS.js → devtools-YnvrZ6D8.js} +4 -4
  9. package/dist/{devtools-Di_dI9tS.js.map → devtools-YnvrZ6D8.js.map} +1 -1
  10. package/dist/{devtools-panel-BvIKX1LY.js → devtools-panel-DRcKclEG.js} +2 -2
  11. package/dist/{devtools-panel-BvIKX1LY.js.map → devtools-panel-DRcKclEG.js.map} +1 -1
  12. package/dist/{features-D5kLyihb.js → features-CbgII-o7.js} +4 -2
  13. package/dist/features-CbgII-o7.js.map +1 -0
  14. package/dist/{files-s4wmjcZV.js → files-HzPDUyTY.js} +2 -2
  15. package/dist/{files-s4wmjcZV.js.map → files-HzPDUyTY.js.map} +1 -1
  16. package/dist/index.d.ts +8 -4
  17. package/dist/index.js +2 -7
  18. package/dist/index.js.map +1 -1
  19. package/dist/{inspect-BLPt-dZZ.js → inspect-Q5W0A66e.js} +476 -122
  20. package/dist/inspect-Q5W0A66e.js.map +1 -0
  21. package/dist/{loader-krRrJuIv.js → loader-C-S3yzep.js} +13 -5
  22. package/dist/loader-C-S3yzep.js.map +1 -0
  23. package/dist/{navigate-BcV1qkkx.js → navigate-r23FFR6e.js} +5 -2
  24. package/dist/{navigate-BcV1qkkx.js.map → navigate-r23FFR6e.js.map} +1 -1
  25. package/dist/routes-D21FQyGF.js +51 -0
  26. package/dist/routes-D21FQyGF.js.map +1 -0
  27. package/dist/{rpc-BYYAj1vV.js → rpc-C_znDZ_w.js} +3 -3
  28. package/dist/{rpc-BYYAj1vV.js.map → rpc-C_znDZ_w.js.map} +1 -1
  29. package/dist/runtime/bundles.d.ts +1 -1
  30. package/dist/runtime/client.d.ts +2 -2
  31. package/dist/runtime/client.js +3 -3
  32. package/dist/runtime/devtools.d.ts +1 -1
  33. package/dist/runtime/devtools.js +1 -1
  34. package/dist/runtime/hot.d.ts +1 -1
  35. package/dist/runtime/loader.d.ts +2 -2
  36. package/dist/runtime/loader.js +2 -2
  37. package/dist/runtime/routes.js +1 -51
  38. package/dist/runtime/server.d.ts +2 -2
  39. package/dist/runtime/server.js +3 -3
  40. package/dist/runtime/signals.d.ts +2 -140
  41. package/dist/runtime/signals.js +4 -1
  42. package/dist/runtime/signals.js.map +1 -1
  43. package/dist/runtime/static-loader.d.ts +2 -2
  44. package/dist/runtime/static-loader.js +1 -1
  45. package/dist/runtime/testing.d.ts +24 -4
  46. package/dist/runtime/testing.js +66 -2
  47. package/dist/runtime/testing.js.map +1 -1
  48. package/dist/{produce-Cq6KKi7b.js → search-params-CM1RWR2P.js} +25 -3
  49. package/dist/search-params-CM1RWR2P.js.map +1 -0
  50. package/dist/{server-Doy5HR7r.js → server-BcT9icQ4.js} +107 -40
  51. package/dist/server-BcT9icQ4.js.map +1 -0
  52. package/dist/{server-CAwIqrXl.d.ts → server-dP_ucRiJ.d.ts} +42 -3
  53. package/dist/signals-BwD4u22K.d.ts +165 -0
  54. package/dist/{static-loader-DoHWsf9t.js → static-loader-Bt2WDkY1.js} +3 -3
  55. package/dist/{static-loader-DoHWsf9t.js.map → static-loader-Bt2WDkY1.js.map} +1 -1
  56. package/dist/{static-loader-9Nc1GvF0.d.ts → static-loader-DysAET-w.d.ts} +2 -2
  57. package/dist/{stream-BdhzvPQO.js → stream-DRjx0keF.js} +2 -2
  58. package/dist/{stream-BdhzvPQO.js.map → stream-DRjx0keF.js.map} +1 -1
  59. package/dist/vite.d.ts +1 -1
  60. package/dist/vite.js +18 -13
  61. package/dist/vite.js.map +1 -1
  62. package/elements.d.ts +239 -37
  63. package/package.json +6 -1
  64. package/skills/brumate/references/errors.md +46 -12
  65. package/skills/brumate/references/signals.md +27 -25
  66. package/skills/brumate/references/syntax.md +1 -1
  67. package/dist/client-De-7aGlO.js.map +0 -1
  68. package/dist/features-D5kLyihb.js.map +0 -1
  69. package/dist/inspect-BLPt-dZZ.js.map +0 -1
  70. package/dist/loader-krRrJuIv.js.map +0 -1
  71. package/dist/produce-Cq6KKi7b.js.map +0 -1
  72. package/dist/runtime/routes.js.map +0 -1
  73. package/dist/server-Doy5HR7r.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-BcT9icQ4.js","names":["running","attributeText","spreadAttributes"],"sources":["../src/runtime/request.ts","../src/runtime/cache.ts","../src/runtime/router.ts","../src/runtime/validate.ts","../src/runtime/submission.ts","../src/runtime/rate-limit.ts","../src/runtime/idempotent.ts","../src/runtime/server.ts"],"sourcesContent":["import { toJSON } from 'seroval';\nimport { deleteCookie, getCookies, setCookie } from './cookies.ts';\nimport type { CookieOptions } from './cookies.ts';\nimport { serialOptions, syncPlugins } from './serial.ts';\n\n/**\n * What a request is for. A form post to a server function is a call, and a\n * form post to a page with `?__action=<id>` is a page.\n */\nexport type RequestKind = 'page' | 'endpoint' | 'call' | 'defer';\n\n/**\n * Values that middleware hands to the components, server functions and\n * endpoints of a request, such as the user. An app adds fields to it:\n *\n * ```ts\n * declare module 'brumate/server' {\n * interface Locals {\n * user?: { id: string; name: string };\n * }\n * }\n * ```\n */\n// oxlint-disable-next-line typescript/no-empty-interface, typescript/no-empty-object-type -- Apps add the fields.\nexport interface Locals {}\n\n/** The server function that a request calls, with its arguments as they were read. */\nexport interface RequestCall {\n id: string;\n args: unknown[];\n}\n\nexport interface RequestEventOptions {\n kind?: RequestKind;\n /**\n * Keeps work going after the response ends, such as the `waitUntil` of\n * Cloudflare Workers. Without it, the promise runs on its own and its\n * error is logged.\n */\n waitUntil?: (promise: Promise<unknown>) => void;\n /**\n * The address of the client as the server saw it, such as the remote\n * address of the socket. `clientAddress` reads it, and looks past the\n * trusted proxies in `X-Forwarded-For` when it is one of them.\n */\n address?: string;\n /** True while the build prerenders the page. Rate limits do not count then. */\n prerender?: boolean;\n /** The `onError` of the app, which gets the errors of this request. */\n onError?: ServerErrorHandler;\n}\n\n/** Where the server takes the error of a `waitUntil` promise that no host keeps, in place of the log. */\nexport const failures: { report?: (error: unknown, event: RequestEvent) => void } = {};\n\n/** Where the server met an error: `'stream'` is a `#loading` body or a route after the response started. */\nexport type ServerErrorKind = RequestKind | 'stream';\n\n/** What `onError` of `src/middleware.ts` knows about an error. */\nexport interface ServerErrorInfo {\n /** The request that met the error, when there is one. */\n event: RequestEvent | undefined;\n kind: ServerErrorKind;\n}\n\n/** The `onError` export of `src/middleware.ts`. */\nexport type ServerErrorHandler = (error: unknown, info: ServerErrorInfo) => unknown;\n\n/** The `onError` of a request, with the errors it got, so an error read in two places counts once. */\nexport interface ErrorSink {\n handler: ServerErrorHandler;\n handled: WeakSet<object>;\n}\n\n/** The sink of a handler, or none without one. */\nexport function errorSink(handler: ServerErrorHandler | undefined): ErrorSink | undefined {\n return handler && { handler, handled: new WeakSet() };\n}\n\n/**\n * A request that the server handles: a server function call, a form post,\n * a page render, or a call of middleware or an endpoint. Its methods read\n * the request and change the response. Get it with `getEvent()`.\n */\n/** A step of the render of a page, for the Server tab of the devtools. */\nexport interface TraceEntry {\n kind: 'render' | 'stream' | 'memo' | 'call' | 'body';\n label: string;\n start: number;\n /** Undefined while it runs. */\n end?: number;\n failed?: boolean;\n}\n\nfunction noTrace(): void {}\n\n/** Ends an entry of the trace when a value settles, if it is a promise, or at once. */\nexport function traceValue<T>(value: T, end: (failed?: boolean) => void): T {\n const thenable = value as unknown as PromiseLike<unknown> | null | undefined;\n if (thenable && typeof thenable.then === 'function') {\n thenable.then(\n () => end(),\n () => end(true),\n );\n } else {\n end();\n }\n return value;\n}\n\n/** The headers that tell who the user is. */\nconst PERSONAL = new Set(['cookie', 'authorization']);\n\n/**\n * Calls `read` when code reads the headers that tell who the user is, by\n * name or by going through all the headers.\n */\nfunction watchPersonal(headers: Headers, read: () => void): void {\n const get = headers.get.bind(headers);\n const has = headers.has.bind(headers);\n Object.assign(headers, {\n get: (name: string) => {\n if (PERSONAL.has(name.toLowerCase())) {\n read();\n }\n return get(name);\n },\n has: (name: string) => {\n if (PERSONAL.has(name.toLowerCase())) {\n read();\n }\n return has(name);\n },\n });\n for (const method of ['entries', 'forEach', 'values', Symbol.iterator] as const) {\n const all = (headers[method] as (...args: unknown[]) => unknown).bind(headers);\n Object.defineProperty(headers, method, {\n value: (...args: unknown[]) => {\n read();\n return all(...args);\n },\n configurable: true,\n });\n }\n}\n\nexport class RequestEvent {\n readonly request: Request;\n /** What the request is for. */\n readonly kind: RequestKind;\n /** For a call, and a page that a form posted to, the server function and its arguments. */\n call?: RequestCall;\n /** Values for this request, which middleware writes and the rest of the request reads. */\n readonly locals: Locals = {};\n /** The address of the client as the server saw it, when the server passed it. */\n readonly address?: string;\n /** True while the build prerenders the page. */\n readonly prerender: boolean;\n /**\n * The pattern of the route files that matched the path, such as\n * `/todos/[id]`. `handleRoute` sets it. Undefined for a path that no route\n * matches.\n */\n route?: string;\n /** Headers to add to the response, such as `cache-control`. */\n readonly headers: Headers = new Headers();\n /** The status that `setStatus` set. */\n status?: number;\n /** Server functions that `refresh` named, whose memos the client loads again. */\n refreshed?: Set<unknown>;\n /** Cookies that this request set, or deleted with undefined, so later reads see them. */\n cookies?: Map<string, string | undefined>;\n /**\n * True once the request read its cookies or its `authorization` header, or\n * set a cookie, such as for a session. The answer then depends on the user,\n * so a page with `cache` is not cached for everyone.\n */\n personal = false;\n /**\n * In development, what the render of the page did and when, in\n * milliseconds from its start, for the Server tab of the devtools.\n */\n trace?: TraceEntry[];\n /** When the trace started, by `performance.now()`. */\n traceStart = 0;\n\n /** Starts an entry of the trace, when there is one, and returns what ends it. */\n traced(kind: TraceEntry['kind'], label: string): (failed?: boolean) => void {\n const trace = this.trace;\n if (!trace) {\n return noTrace;\n }\n const entry: TraceEntry = { kind, label, start: performance.now() - this.traceStart };\n trace.push(entry);\n return (failed) => {\n entry.end = performance.now() - this.traceStart;\n if (failed) {\n entry.failed = true;\n }\n };\n }\n\n /**\n * The tags of the `cached` functions that the request called, with the\n * version that each had then, so `revalidate` drops the page that it renders.\n */\n readonly cacheTags: Map<string, string | undefined> = new Map();\n private readonly controller = new AbortController();\n /**\n * Aborts when the request no longer needs an answer: the request's own\n * signal aborts, or the reader of the response went away, such as a\n * browser that left the page while it streamed. Pass it on, such as to\n * `fetch(url, { signal })`, so work that nobody waits for stops.\n */\n readonly signal: AbortSignal = this.controller.signal;\n /** Where the errors of the request go, when the app has an `onError`. */\n readonly errors: ErrorSink | undefined;\n private readonly keepGoing?: (promise: Promise<unknown>) => void;\n\n constructor(request: Request, options: RequestEventOptions = {}) {\n this.request = request;\n this.kind = options.kind ?? 'page';\n this.keepGoing = options.waitUntil;\n this.address = options.address;\n this.prerender = options.prerender ?? false;\n this.errors = errorSink(options.onError);\n watchPersonal(request.headers, () => {\n this.personal = true;\n });\n const outer = request.signal;\n if (outer?.aborted) {\n this.controller.abort(outer.reason);\n } else {\n outer?.addEventListener('abort', () => this.abort(outer.reason), { once: true });\n }\n }\n\n /** Aborts `signal`, such as when the response's reader went away. The server calls it. */\n abort(reason?: unknown): void {\n if (!this.signal.aborted) {\n this.controller.abort(reason);\n }\n }\n\n /**\n * Keeps work going after the response ends, such as a log line or\n * analytics. On a host that stops a function when its response ends, the\n * server passes the promise to the host, through the `waitUntil` option.\n * Elsewhere the promise runs on its own, and its error is logged.\n */\n waitUntil(promise: Promise<unknown>): void {\n if (this.keepGoing) {\n this.keepGoing(promise);\n } else {\n promise.catch((error: unknown) => (failures.report ?? console.error)(error, this));\n }\n }\n\n /**\n * Sets the status of the page response, such as 404 for a page that shows\n * that nothing was found. It works while the first render of a page runs.\n * Markup that streams later, such as a `#loading` body, cannot change it,\n * because the response has started by then.\n */\n setStatus(status: number): void {\n this.status = status;\n }\n\n /**\n * Asks the client to load again the memos that call a server function, such\n * as a list after a server function adds to it. The compiler gives those\n * memos client code, so they can load.\n */\n refresh(fn: (...args: never[]) => unknown): void {\n this.refreshed ??= new Set();\n this.refreshed.add(unwrap(fn));\n }\n\n /** The cookies of the request, with the ones that this request set or deleted. */\n getCookies(): Record<string, string> {\n return getCookies(this);\n }\n\n /** A cookie of the request, or the value that this request set. */\n getCookie(name: string): string | undefined {\n return getCookies(this)[name];\n }\n\n /**\n * Sets a cookie on the response. It is `HttpOnly`, `SameSite=Lax` and on\n * the path `/` unless the options say otherwise, and `Secure` on HTTPS.\n * Markup that streams later, such as a `#loading` body, cannot set cookies,\n * because the response has started.\n */\n setCookie(name: string, value: string, options: CookieOptions = {}): void {\n setCookie(this, name, value, options);\n }\n\n /** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\n deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): void {\n deleteCookie(this, name, options);\n }\n}\n\n/**\n * The event of the code that runs now. The runtime sets it while it calls a\n * server function, middleware, an endpoint or a memo, and clears it as soon\n * as the call returns, which is at its first `await`. One request at a time\n * runs until an `await`, so it is never the event of another request.\n */\nlet current: RequestEvent | undefined;\n/** The results of server function calls of the render that runs now, by function and arguments. */\nlet currentCalls: Map<string, unknown> | undefined;\n\n// `batched` of `brumate/batch` reads at once while the server answers, also in a test that\n// runs server code in a DOM. A symbol of the registry, so the browser code needs no import.\n(globalThis as Record<symbol, unknown>)[Symbol.for('brumate.inRequest')] = (): boolean =>\n current !== undefined || currentCalls !== undefined;\n\n/**\n * Runs a callback with an event, so `getEvent()` in its code before its first\n * `await` returns it. Returns what the callback returns, such as its promise.\n * `calls`, while a page renders, lets calls with the same arguments share a result.\n */\nexport function withEvent<T>(\n event: RequestEvent | undefined,\n callback: () => T,\n calls?: Map<string, unknown>,\n): T {\n const outer = current;\n const outerCalls = currentCalls;\n current = event;\n currentCalls = calls;\n try {\n return callback();\n } finally {\n current = outer;\n currentCalls = outerCalls;\n }\n}\n\n/** The event of the request being handled, or undefined, without throwing as `getEvent` does. */\nexport function currentEvent(): RequestEvent | undefined {\n return current;\n}\n\n/**\n * Returns the event of the request that the server handles: in a server\n * function, middleware or an endpoint, or while a component renders.\n *\n * Call it before the first `await` of the function, and keep it in a\n * variable. After an `await`, other requests may have run, so it throws.\n *\n * ```ts\n * async function save(todo: Todo) {\n * 'use server';\n * const event = getEvent();\n * await db.save(todo);\n * event.setCookie('saved', todo.id);\n * }\n * ```\n */\nexport function getEvent(): RequestEvent {\n if (!current) {\n throw new Error(\n 'getEvent() works in server functions, middleware and endpoints before their first await, and while a component renders. Call it at the start of the function, keep the event in a variable, and pass it to helpers',\n );\n }\n return current;\n}\n\n/**\n * Middleware that runs for every request of the app: pages, endpoints,\n * server function calls, form posts and the requests for `#defer` bodies.\n * It answers the request itself, or calls `next` for the answer and returns\n * it, changed or not. `event.kind` says what the request is for.\n */\nexport type EntryMiddleware = (\n event: RequestEvent,\n next: () => Promise<Response>,\n) => Response | Promise<Response>;\n\n/**\n * Types the middleware of the entry file, `src/middleware.ts`, which the\n * Vite plugin runs for every request:\n *\n * ```ts\n * export default defineMiddleware(async (event, next) => {\n * event.locals.user = await readUser(event);\n * return next();\n * });\n * ```\n */\nexport function defineMiddleware(middleware: EntryMiddleware): EntryMiddleware {\n return middleware;\n}\n\n/**\n * Runs the middleware of the entry, when there is one, around an answer.\n * `getEvent()` works in the middleware before its first `await`.\n */\nexport function runEntry(\n middleware: EntryMiddleware | undefined,\n event: RequestEvent,\n answer: () => Promise<Response>,\n): Promise<Response> {\n if (!middleware) {\n return answer();\n }\n return Promise.resolve(withEvent(event, () => middleware(event, answer)));\n}\n\n/**\n * Wraps a server function, so its calls while a page renders share a result\n * when their arguments are the same. Calls from the browser, which are\n * requests of their own, always run, so a function that changes something\n * runs each time.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n/** Marks the functions that `idempotent` made. A symbol of the registry. */\nexport const IDEMPOTENT: unique symbol = Symbol.for('brumate.idempotent') as never;\n\n/** The IDs of the server functions that `idempotent` made, which `dedupe` records. */\nexport const idempotentIds: Set<string> = new Set();\n\n/** The ID of each function that `idempotent` made, once the server registered it. */\nexport const idempotentId: WeakMap<object, string> = new WeakMap();\n\nexport function dedupe<F extends (...args: any[]) => unknown>(fn: F, id: string): F {\n // A form of a function that `idempotent` made gets a key when it renders.\n if (IDEMPOTENT in fn) {\n idempotentIds.add(id);\n idempotentId.set(fn, id);\n }\n const wrapper = ((...args: unknown[]) => {\n const cache = currentCalls;\n if (!cache) {\n return fn(...args);\n }\n let key: string;\n try {\n key = `${id} ${JSON.stringify(toJSON(args, { plugins: syncPlugins, ...serialOptions() }))}`;\n } catch {\n // Arguments that cannot be compared, such as a promise.\n return fn(...args);\n }\n if (!cache.has(key)) {\n cache.set(key, traceValue(fn(...args), current?.traced('call', id) ?? noTrace));\n }\n return cache.get(key);\n }) as F;\n Object.defineProperty(wrapper, ORIGINAL, { value: fn });\n return wrapper;\n}\n\n/**\n * The function that `dedupe` wrapped, on its wrapper. A symbol of the\n * registry, so two copies of the runtime agree on it.\n */\nconst ORIGINAL = Symbol.for('brumate.original');\n\n/**\n * The server function itself, for a wrapper that `dedupe` made. `refresh`\n * and `$action` compare server functions, and the registry holds them unwrapped.\n */\nexport function unwrap<T>(fn: T): T {\n return ((fn as Record<symbol, T | undefined> | null)?.[ORIGINAL] ?? fn) as T;\n}\n\n/**\n * An error whose message reaches the client. A server function call that\n * throws it rejects with the message, and the response has its status.\n * Other errors reach the client as a generic message, so server details stay\n * on the server.\n */\nexport class ServerError extends Error {\n readonly status: number;\n\n constructor(message: string, options: { status?: number } = {}) {\n super(message);\n this.name = 'ServerError';\n this.status = options.status ?? 400;\n }\n}\n\n/** Thrown by `redirect`. */\nexport class Redirect extends Error {\n readonly location: string;\n readonly status: number;\n\n constructor(location: string, status: number) {\n super(`Redirect to ${location}`);\n this.name = 'Redirect';\n this.location = location;\n this.status = status;\n }\n}\n\n/**\n * Stops a server function and sends the browser to another page. While a\n * page renders, the error reaches the caller of `render`, which can\n * answer with a redirect.\n */\nexport function redirect(location: string, status = 303): never {\n throw new Redirect(location, status);\n}\n\nexport function isRedirect(error: unknown): error is Redirect {\n return error instanceof Redirect;\n}\n","// Results of server code that requests share, by their arguments, for a time.\n// A store keeps them as text, so a store of another process, such as Redis,\n// can keep them too. Tags name what a result depends on, and `revalidate`\n// drops every result of a tag.\n\nimport { fromJSON, toJSON } from 'seroval';\nimport { currentEvent, withEvent } from './request.ts';\nimport { serialOptions, syncPlugins } from './serial.ts';\n\n/**\n * Where cached results live. Values are text. `maxAge` is in seconds, after\n * which the store can drop the value. Each method can return a promise.\n */\nexport interface CacheStore {\n get(key: string): Promise<string | null | undefined> | string | null | undefined;\n set(key: string, value: string, maxAge: number): Promise<void> | void;\n}\n\ninterface Entry {\n /** The value, as seroval writes it. */\n value: unknown;\n /** When the value expires, in milliseconds since 1970. */\n expires: number;\n /** The version of each tag when the value was made. */\n tags: Record<string, string>;\n}\n\n/** Tags live longer than any result, so a result never outlives the version of its tag. */\nconst TAG_AGE = 365 * 24 * 60 * 60;\n\n/**\n * A store in the memory of the server, the default. Each process has its\n * own, and it keeps at most `size` values, dropping the oldest first.\n */\nexport function memoryStore(size = 1000): CacheStore & { readonly memory: true } {\n const values = new Map<string, { value: string; expires: number }>();\n return {\n memory: true,\n get(key) {\n const item = values.get(key);\n if (!item) {\n return undefined;\n }\n if (item.expires <= Date.now()) {\n values.delete(key);\n return undefined;\n }\n return item.value;\n },\n set(key, value, maxAge) {\n values.delete(key);\n values.set(key, { value, expires: Date.now() + maxAge * 1000 });\n for (const oldest of values.keys()) {\n if (values.size <= size) {\n break;\n }\n values.delete(oldest);\n }\n },\n };\n}\n\nlet store: CacheStore = memoryStore();\n\n/**\n * Sets the store of `cached`, such as one that keeps results in Redis for\n * every process of the app. Set it before the first request.\n */\nexport function setCacheStore(next: CacheStore): void {\n store = next;\n}\n\n/** The store of unstorage, which Nitro gives as `useStorage()`. */\ninterface Storage {\n getItem(key: string): Promise<unknown>;\n setItem(key: string, value: string, options?: { ttl?: number }): Promise<void>;\n getItemRaw?(key: string): Promise<unknown>;\n setItemRaw?(key: string, value: string, options?: { ttl?: number }): Promise<void>;\n}\n\n/**\n * A store of `cached` from an unstorage storage, such as Nitro's\n * `useStorage('cache')`. It reads and writes the values as they are, since\n * `getItem` would parse text that looks like JSON.\n */\nexport function storageStore(storage: Storage): CacheStore {\n return {\n get: async (key) => {\n const value = await (storage.getItemRaw ?? storage.getItem).call(storage, key);\n if (value instanceof Uint8Array) {\n return new TextDecoder().decode(value);\n }\n return typeof value === 'string' ? value : undefined;\n },\n set: (key, value, maxAge) =>\n (storage.setItemRaw ?? storage.setItem).call(storage, key, value, { ttl: maxAge }),\n };\n}\n\nexport interface CachedOptions<A extends unknown[]> {\n /** Seconds that a result is used for the same arguments. */\n maxAge: number;\n /** What a result depends on, for `revalidate`. A function gets the arguments. */\n tags?: string[] | ((...args: A) => string[]);\n /**\n * The name of the results in the store. A store that other processes\n * share, such as Redis, needs one, so each process finds the same results.\n */\n name?: string;\n}\n\n/** Calls that are running, by key, so calls with the same arguments share one run. */\nconst running = new Map<string, Promise<unknown>>();\nlet unnamed = 0;\n\n/** The text of a value, as the store keeps it. */\nfunction write(value: unknown): unknown {\n return toJSON(value, { plugins: syncPlugins, ...serialOptions() });\n}\n\n/**\n * Makes a function that keeps its results for `maxAge` seconds, by its\n * arguments, and returns a kept result in place of running again. Use it for\n * data that every user sees the same, such as a list of products.\n *\n * - The function runs without the request: `getEvent()` throws in it, so a\n * result never holds one user's data. Pass what it needs as arguments.\n * - Arguments and results are values that brumate can send, such as plain\n * objects, arrays, dates and maps.\n * - Calls with the same arguments while one runs share that run.\n * - `revalidate(tag)` drops the results of a tag.\n */\nexport function cached<A extends unknown[], R>(\n fn: (...args: A) => Promise<R> | R,\n options: CachedOptions<A>,\n): (...args: A) => Promise<Awaited<R>> {\n const id = options.name ?? `#${unnamed++}`;\n return async (...args: A): Promise<Awaited<R>> => {\n if (options.name === undefined && !('memory' in store)) {\n throw new Error(\n 'Give cached a name, such as cached(fn, { name: \"products\", maxAge: 60 }), so every process finds its results in the store',\n );\n }\n const key = `brumate:cache:${id}:${JSON.stringify(write(args))}`;\n const tags = typeof options.tags === 'function' ? options.tags(...args) : (options.tags ?? []);\n // A page that uses the result depends on its tags too.\n const event = currentEvent();\n for (const tag of tags) {\n if (!event?.cacheTags.has(tag)) {\n event?.cacheTags.set(tag, undefined);\n }\n }\n const versions = await tagVersions(tags);\n for (const tag of tags) {\n if (event?.cacheTags.get(tag) === undefined) {\n event?.cacheTags.set(tag, versions[tag]);\n }\n }\n const kept = await store.get(key);\n if (kept) {\n const entry = JSON.parse(kept) as Entry;\n let fresh = entry.expires > Date.now();\n if (fresh) {\n for (const tag of tags) {\n if (entry.tags[tag] !== versions[tag]) {\n fresh = false;\n break;\n }\n }\n }\n if (fresh) {\n return fromJSON(entry.value as never, { plugins: syncPlugins }) as Awaited<R>;\n }\n }\n let run = running.get(key) as Promise<Awaited<R>> | undefined;\n if (!run) {\n const started = (async (): Promise<Awaited<R>> => {\n const value = await withEvent(undefined, () => fn(...args));\n const entry: Entry = {\n value: write(value),\n expires: Date.now() + options.maxAge * 1000,\n tags: versions,\n };\n await store.set(key, JSON.stringify(entry), options.maxAge);\n return value;\n })();\n run = started;\n running.set(key, started);\n void started.then(\n () => running.delete(key),\n () => running.delete(key),\n );\n }\n // Each caller gets its own copy, so one cannot change the result of another.\n return fromJSON(write(await run) as never, { plugins: syncPlugins }) as Awaited<R>;\n };\n}\n\n/** The store of `cached`, which the page cache of the server shares. */\nexport function cacheStore(): CacheStore {\n return store;\n}\n\n/** The versions of tags. A tag that was never revalidated has version `0`. */\nexport async function tagVersions(tags: Iterable<string>): Promise<Record<string, string>> {\n const versions: Record<string, string> = {};\n const reads: Promise<void>[] = [];\n for (const tag of tags) {\n reads.push(\n (async () => {\n versions[tag] = (await store.get(`brumate:tag:${tag}`)) ?? '0';\n })(),\n );\n }\n await Promise.all(reads);\n return versions;\n}\n\nlet revalidations = 0;\n\n/**\n * Drops the results of `cached` functions with these tags, such as after a\n * server function changes the data. The next call runs the function again.\n * To show the new data on the page, call `refresh` too.\n */\nexport async function revalidate(...tags: string[]): Promise<void> {\n const version = `${Date.now()}.${revalidations++}`;\n const writes: (Promise<void> | void)[] = [];\n for (const tag of tags) {\n writes.push(store.set(`brumate:tag:${tag}`, version, TAG_AGE));\n }\n await Promise.all(writes);\n}\n","import type { Component } from './server.ts';\n\n/** Imports the module of a route file. */\nexport type Loader = () => Promise<{ default: Component }>;\n\n/** Answers a request at the path of an endpoint, for one method. */\nexport type Handler = (\n request: Request,\n params: Record<string, string>,\n) => Response | Promise<Response>;\n\n/**\n * Runs before the routes of a folder. It answers the request itself, or\n * calls `next` for the answer of the route and returns it, changed or not.\n */\nexport type Middleware = (\n request: Request,\n next: () => Promise<Response>,\n) => Response | Promise<Response>;\n\n/** Imports `_middleware.ts`. */\nexport type MiddlewareLoader = () => Promise<{ middleware: Middleware }>;\n\n/** Imports an endpoint: a module that exports a handler for each method, such as `GET`. */\nexport type EndpointLoader = () => Promise<Partial<Record<string, Handler>>>;\n\n/** A folder of routes, as `virtual:brumate/routes` describes it. */\nexport interface RouteNode {\n /** `_layout.brm`. */\n layout?: Loader;\n /** `index.brm`, or the file of a segment, such as `about.brm`. */\n page?: Loader;\n /** `_default.brm`: what a slot renders when its routes do not match. */\n fallback?: Loader;\n /** `_error.brm`: renders when a route of the folder throws, or when no route matches. */\n error?: Loader;\n /** `_loading.brm`: shows while a route of the folder streams in. */\n loading?: Loader;\n /** `_middleware.ts`: runs before the routes of the folder. */\n middleware?: MiddlewareLoader;\n /** A `.ts` file at this path, such as `api/todos.ts`. */\n endpoint?: EndpointLoader;\n /** Folders and files with a fixed segment. */\n static?: Record<string, RouteNode>;\n /** `[name]`: one segment, read as `params.name`. */\n dynamic?: { name: string; node: RouteNode };\n /** `[...name]`: the rest of the path, read as `params.name`. */\n rest?: { name: string; node: RouteNode };\n /** `@name` folders: routes that render in the `name` slot of the layout. */\n slots?: Record<string, RouteNode>;\n}\n\n/** A matched route: the component to render, and what renders in its slots. */\nexport interface RouteView {\n load: Loader;\n /**\n * The file and the params that the view depends on, such as\n * `/todos/[id]/_layout {\"id\":\"3\"}`. Two pages with the same key for a\n * layout render the same layout, so the client can keep it.\n */\n key: string;\n /** `children` and the named slots of a layout. */\n slots: Record<string, RouteView>;\n /** `_loading.brm` of the folder: the view streams in, and this shows until then. */\n loading?: Loader;\n}\n\nexport interface RouteMatch {\n view: RouteView;\n params: Record<string, string>;\n /** The pattern of the route files that matched, such as `/todos/[id]`, or `/` for the root. */\n route: string;\n /** The endpoint at the path, if the folder has one. */\n endpoint?: EndpointLoader;\n /** The middleware of the folders on the path, from the outside in. */\n middleware: MiddlewareLoader[];\n /**\n * Views that show an error in place of the route, from the innermost\n * `_error.brm` to the outermost. Each renders inside the layouts above it.\n */\n errors: RouteView[];\n}\n\n/** A layout and the slots that it renders around a view. */\ninterface Wrapper {\n layout: Loader;\n key: string;\n slots: Record<string, RouteView>;\n}\n\nfunction key(path: string, file: string, params: Record<string, string>): string {\n return `${path}/${file} ${JSON.stringify(params)}`;\n}\n\n/** Puts a view in the children slot of a layout, with its other slots. */\nfunction wrap(view: RouteView, wrapper: Wrapper | undefined): RouteView {\n return wrapper\n ? { load: wrapper.layout, key: wrapper.key, slots: { ...wrapper.slots, children: view } }\n : view;\n}\n\n/** The layout of a folder, or undefined when it has none. */\nfunction findWrapper(\n node: RouteNode,\n segments: string[],\n index: number,\n params: Record<string, string>,\n path: string,\n): Wrapper | undefined {\n return node.layout\n ? {\n layout: node.layout,\n key: key(path, '_layout', params),\n slots: namedSlots(node, segments, index, params, path),\n }\n : undefined;\n}\n\n/** The `_error.brm` of a folder, inside its layout. */\nfunction errorIn(\n error: Loader,\n wrapper: Wrapper | undefined,\n params: Record<string, string>,\n path: string,\n): RouteView {\n return wrap({ load: error, key: key(path, ERROR_VIEW, params), slots: {} }, wrapper);\n}\n\n/** The slots of a layout other than `children`, each matched against the same path. */\nfunction namedSlots(\n node: RouteNode,\n segments: string[],\n index: number,\n params: Record<string, string>,\n path: string,\n): Record<string, RouteView> {\n const slots: Record<string, RouteView> = {};\n for (const [name, slot] of Object.entries(node.slots ?? {})) {\n const match = matchNode(slot, segments, index, params, `${path}/@${name}`);\n if (match) {\n slots[name] = match.view;\n } else if (slot.fallback) {\n slots[name] = {\n load: slot.fallback,\n key: key(`${path}/@${name}`, '_default', params),\n slots: {},\n };\n }\n }\n return slots;\n}\n\n/** The view of an `_error.brm`. Its component gets the error as a prop. */\nconst ERROR_VIEW = '_error';\n\n/**\n * Matches the segments from `index` on. `path` is the folders of `node` in\n * the route files, such as `/todos/[id]`.\n */\nfunction matchNode(\n node: RouteNode,\n segments: string[],\n index: number,\n params: Record<string, string>,\n path = '',\n): RouteMatch | undefined {\n let inner: RouteMatch | undefined;\n if (index === segments.length) {\n if (node.page || node.endpoint) {\n inner = {\n view: { load: node.page ?? missingPage, key: key(path, 'index', params), slots: {} },\n params,\n route: path || '/',\n endpoint: node.endpoint,\n middleware: [],\n errors: [],\n };\n }\n } else {\n const first = segments[index]!;\n const fixed = node.static?.[first];\n inner = fixed && matchNode(fixed, segments, index + 1, params, `${path}/${first}`);\n if (!inner && node.dynamic) {\n const { name } = node.dynamic;\n inner = matchNode(\n node.dynamic.node,\n segments,\n index + 1,\n { ...params, [name]: first },\n `${path}/[${name}]`,\n );\n }\n if (!inner && node.rest) {\n const { name } = node.rest;\n inner = matchNode(\n node.rest.node,\n segments,\n segments.length,\n { ...params, [name]: segments.slice(index).join('/') },\n `${path}/[...${name}]`,\n );\n }\n }\n if (!inner) {\n return undefined;\n }\n // The route of the folder streams in after its layout, with the loading file until then.\n const content: RouteView = node.loading ? { ...inner.view, loading: node.loading } : inner.view;\n const wrapper = findWrapper(node, segments, index, params, path);\n let errors = inner.errors;\n if (wrapper) {\n errors = [];\n for (const view of inner.errors) {\n errors.push(wrap(view, wrapper));\n }\n }\n if (node.error) {\n errors.push(errorIn(node.error, wrapper, params, path));\n }\n return {\n view: wrap(content, wrapper),\n params: inner.params,\n route: inner.route,\n endpoint: inner.endpoint,\n middleware: node.middleware ? [node.middleware, ...inner.middleware] : inner.middleware,\n errors,\n };\n}\n\n/** An endpoint without a page: a GET that it does not answer has no page either. */\nexport const missingPage: Loader = () => {\n throw new Error('This path has an endpoint and no page');\n};\n\n/** Finds the route for a path. A path with a malformed escape, such as `/%E0`, matches none. */\nexport function matchRoute(tree: RouteNode, pathname: string): RouteMatch | undefined {\n let segments: string[];\n try {\n segments = [];\n for (const segment of pathname.split('/')) {\n if (segment) {\n segments.push(decodeURIComponent(segment));\n }\n }\n } catch {\n return undefined;\n }\n return matchNode(tree, segments, 0, {});\n}\n\n/**\n * The views for a path that no route matches: the `_error.brm` of the\n * root, inside the root layout, and the root middleware.\n */\nexport function notFound(tree: RouteNode): Pick<RouteMatch, 'errors' | 'middleware'> {\n return {\n errors: tree.error ? [errorIn(tree.error, findWrapper(tree, [], 0, {}, ''), {}, '')] : [],\n middleware: tree.middleware ? [tree.middleware] : [],\n };\n}\n","// Validation of server function arguments with any Standard Schema, such as\n// a schema of Zod, Valibot or ArkType. The helpers run in the body of a\n// server function, so they never reach the browser.\n\nimport { formValues } from './forms.ts';\nimport { ServerError } from './request.ts';\nimport type { StandardSchemaV1 } from './standard-schema.ts';\n\n/**\n * A problem that a schema found, as plain data that the server can send to\n * the browser. A path segment is a string or a number.\n */\nexport interface ValidationIssue {\n message: string;\n path?: (string | number)[];\n}\n\n/** The output of a schema, or the issues that it found. */\nexport type ParseResult<T> =\n | { value: T; issues?: undefined }\n | { value?: undefined; issues: ValidationIssue[] };\n\n/**\n * The error that `parse` throws when the value does not match. It answers\n * with status 400 and its message, as any `ServerError` does. Its `issues`\n * stay on the server.\n */\nexport class ValidationError extends ServerError {\n readonly issues: ValidationIssue[];\n\n constructor(issues: ValidationIssue[]) {\n super(summary(issues), { status: 400 });\n this.name = 'ValidationError';\n this.issues = issues;\n }\n}\n\n/** The longest message that `parse` sends, so a long input in a message stays short. */\nconst MAX_MESSAGE = 300;\n\n/** The message of a `ValidationError`: the first issue with its path, and how many others there are. */\nfunction summary(issues: ValidationIssue[]): string {\n const first = issues[0];\n if (!first) {\n return 'Invalid input';\n }\n const path = first.path?.join('.');\n let message = path ? `${path}: ${first.message}` : first.message;\n if (message.length > MAX_MESSAGE) {\n message = `${message.slice(0, MAX_MESSAGE)}…`;\n }\n const more = issues.length - 1;\n return more > 0 ? `${message} (${more} more ${more === 1 ? 'issue' : 'issues'})` : message;\n}\n\n/**\n * Copies an issue as plain data. A `{ key }` segment becomes its key, and a\n * symbol becomes its text, such as `Symbol(id)`. Other fields of the issue,\n * which some libraries add, are left out, so the input is not sent back.\n */\nfunction plainIssue(issue: StandardSchemaV1.Issue): ValidationIssue {\n const plain: ValidationIssue = { message: String(issue.message) };\n if (issue.path && issue.path.length > 0) {\n plain.path = [];\n for (const segment of issue.path) {\n const key = typeof segment === 'object' && segment !== null ? segment.key : segment;\n plain.path.push(typeof key === 'number' ? key : String(key));\n }\n }\n return plain;\n}\n\n/**\n * Validates a value with a Standard Schema. Returns `{ value }` with the\n * output of the schema, or `{ issues }` as plain data. It does not throw for\n * a value that does not match.\n */\nexport async function safeParse<S extends StandardSchemaV1>(\n schema: S,\n value: unknown,\n): Promise<ParseResult<StandardSchemaV1.InferOutput<S>>> {\n const props = schema['~standard'];\n if (props?.version !== 1 || typeof props.validate !== 'function') {\n throw new TypeError('The schema is not a Standard Schema of version 1');\n }\n const result = await props.validate(value);\n if (result.issues) {\n const issues: ValidationIssue[] = [];\n for (const issue of result.issues) {\n issues.push(plainIssue(issue));\n }\n return { issues };\n }\n return { value: result.value as StandardSchemaV1.InferOutput<S> };\n}\n\n/**\n * Validates a value with a Standard Schema, and returns the output of the\n * schema. A value that does not match throws a `ValidationError`, which\n * answers with status 400 and a message built from the first issue.\n *\n * ```ts\n * async function save(input: unknown) {\n * 'use server';\n * const todo = await parse(Todo, input);\n * await db.todos.save(todo);\n * }\n * ```\n */\nexport async function parse<S extends StandardSchemaV1>(\n schema: S,\n value: unknown,\n): Promise<StandardSchemaV1.InferOutput<S>> {\n const result = await safeParse(schema, value);\n if (result.issues) {\n throw new ValidationError(result.issues);\n }\n return result.value;\n}\n\n/**\n * Validates the data of a form with a Standard Schema. The entries become a\n * plain object first. Returns `{ value }` or `{ issues }`, and does not throw\n * for data that does not match, so a function of `$action` can return the\n * issues for the page to show.\n *\n * ```ts\n * async function signUp(form: FormData) {\n * 'use server';\n * const result = await parseForm(SignUp, form);\n * if (result.issues) {\n * return { errors: fieldErrors(result.issues) };\n * }\n * }\n * ```\n */\nexport async function parseForm<S extends StandardSchemaV1>(\n schema: S,\n form: FormData,\n): Promise<ParseResult<StandardSchemaV1.InferOutput<S>>> {\n const values = formValues(form);\n if (values.issues) {\n return { issues: values.issues };\n }\n return safeParse(schema, values.value);\n}\n\n/**\n * The messages of issues by field, for a page to show next to each field.\n * The key is the path joined with dots, such as `address.city`. Issues\n * without a path, and a path of `__proto__`, are under the key `''`. The\n * result is plain data, so a server function can return it.\n */\nexport function fieldErrors(\n issues: readonly (StandardSchemaV1.Issue | ValidationIssue)[],\n): Record<string, string[]> {\n const errors: Record<string, string[]> = {};\n for (const issue of issues) {\n let key = plainIssue(issue).path?.join('.') ?? '';\n if (key === '__proto__') {\n key = '';\n }\n (Object.hasOwn(errors, key) ? errors[key]! : (errors[key] = [])).push(String(issue.message));\n }\n return errors;\n}\n","// The server side of progressive forms: reads a submission, applies its\n// intent, validates it, and builds the reply that `createForm` shows.\n\nimport {\n INTENT,\n applyIntent,\n formValues,\n formatPath,\n getAt,\n groupIssues,\n parseIntent,\n parsePath,\n} from './forms.ts';\nimport type { Intent, PathSegment, SubmissionResult } from './forms.ts';\nimport type { StandardSchemaV1 } from './standard-schema.ts';\nimport { safeParse } from './validate.ts';\nimport type { ValidationIssue } from './validate.ts';\n\n/** What a server function adds to the reply of a submission. */\nexport interface ReplyOptions {\n /** Errors of the whole form, such as \"That email is taken\". */\n formErrors?: string[];\n /** Errors of fields, by field name, such as `{ email: ['That email is taken'] }`. */\n fieldErrors?: Record<string, string[]>;\n /** Sets the form back to its default values, such as after a save. */\n reset?: boolean;\n}\n\n/** The options of `parseSubmission`. */\nexport interface SubmissionOptions {\n /**\n * Field names whose values are never sent back, such as `password`. Files\n * are never sent back either, because a file input cannot be filled.\n */\n hide?: string[];\n}\n\ninterface SubmissionBase {\n /** The posted values, after the intent, before the schema. */\n payload: Record<string, unknown> | undefined;\n /** The reply for `createForm`, with the errors of the submission and of `options`. */\n reply(options?: ReplyOptions): SubmissionResult;\n}\n\n/** A submission whose values passed the schema. */\nexport interface SuccessfulSubmission<T> extends SubmissionBase {\n status: 'success';\n /** The output of the schema. */\n value: T;\n intent?: undefined;\n}\n\n/** A submission whose values did not pass the schema, or whose names or intent were not allowed. */\nexport interface FailedSubmission extends SubmissionBase {\n status: 'error';\n value?: undefined;\n intent?: Intent;\n issues: ValidationIssue[];\n}\n\n/** A submission of an intent button, such as \"Add an item\". It is not a save. */\nexport interface IntentSubmission extends SubmissionBase {\n status: 'intent';\n value?: undefined;\n intent: Intent;\n}\n\n/** A submission of a form: a success, an error, or an intent. */\nexport type Submission<T> = SuccessfulSubmission<T> | FailedSubmission | IntentSubmission;\n\n/** True for a file, so it is not sent back. */\nfunction isBlob(value: unknown): boolean {\n return typeof Blob !== 'undefined' && value instanceof Blob;\n}\n\n/** The values to send back: without files and hidden fields. */\nfunction echo(value: unknown, hidden: Set<string>, path: PathSegment[] = []): unknown {\n if (path.length > 0 && hidden.has(formatPath(path))) {\n return undefined;\n }\n if (isBlob(value)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n // oxlint-disable-next-line unicorn/no-new-array -- A list posted with gaps keeps them.\n const copy: unknown[] = new Array(value.length);\n for (const [index, item] of value.entries()) {\n if (index in value) {\n copy[index] = echo(item, hidden, [...path, index]);\n }\n }\n return copy;\n }\n if (typeof value === 'object' && value !== null) {\n const copy: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n const next = echo(item, hidden, [...path, key]);\n if (next !== undefined) {\n copy[key] = next;\n }\n }\n return copy;\n }\n return value;\n}\n\n/** A new ID for a reply, which the keys of the items of a changed list start with. */\nfunction replyId(): string {\n return Math.random().toString(36).slice(2, 10);\n}\n\n/**\n * Reads the data of a form that `createForm` shows. It turns the entries\n * into an object, as `parseForm` does, applies the intent of the button\n * that was pressed, and validates the values with a Standard Schema when\n * the button was not an intent. It does not throw for data that does not\n * match. `reply()` gives what the function returns, for `createForm` to show.\n *\n * ```ts\n * async function save(form: FormData) {\n * 'use server';\n * const submission = await parseSubmission(Order, form);\n * if (submission.status !== 'success') {\n * return submission.reply();\n * }\n * await db.orders.save(submission.value);\n * return submission.reply({ reset: true });\n * }\n * ```\n */\nexport async function parseSubmission<S extends StandardSchemaV1>(\n schema: S,\n form: FormData,\n options: SubmissionOptions = {},\n): Promise<Submission<StandardSchemaV1.InferOutput<S>>> {\n const hidden = new Set(options.hide);\n const id = replyId();\n function make(\n status: SubmissionResult['status'],\n payload: Record<string, unknown> | undefined,\n issues: ValidationIssue[],\n list?: string,\n ) {\n return {\n payload,\n reply(reply: ReplyOptions = {}): SubmissionResult {\n const grouped = groupIssues(issues);\n const errors = { ...grouped.errors };\n for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) {\n errors[name] = [...(Object.hasOwn(errors, name) ? errors[name]! : []), ...messages];\n }\n const keys: Record<string, string[]> = {};\n const items = list === undefined ? undefined : getAt(payload, parsePath(list)!);\n if (list !== undefined && Array.isArray(items)) {\n // oxlint-disable-next-line unicorn/no-new-array -- A list posted with gaps keeps them.\n const itemKeys: string[] = new Array(items.length);\n for (let index = 0; index < items.length; index++) {\n if (index in items) {\n itemKeys[index] = `${id}-${index}`;\n }\n }\n keys[list] = itemKeys;\n }\n const result: SubmissionResult = {\n status,\n value: reply.reset ? undefined : echo(payload, hidden),\n errors: reply.reset ? {} : errors,\n formErrors: [...grouped.formErrors, ...(reply.formErrors ?? [])],\n keys: reply.reset ? {} : keys,\n id,\n };\n if (reply.reset) {\n result.reset = true;\n }\n return result;\n },\n };\n }\n\n const raw = form.get(INTENT);\n const values = formValues(form, (name) => name === INTENT);\n if (values.issues) {\n return { status: 'error', issues: values.issues, ...make('error', undefined, values.issues) };\n }\n let payload: Record<string, unknown> | undefined = values.value;\n if (raw === null) {\n const result = await safeParse(schema, payload);\n if (result.issues) {\n return { status: 'error', issues: result.issues, ...make('error', payload, result.issues) };\n }\n return { status: 'success', value: result.value, ...make('success', payload, []) };\n }\n const intent = typeof raw === 'string' ? parseIntent(raw) : undefined;\n const applied = intent && applyIntent(payload, intent);\n if (!intent || !applied) {\n const issues = [{ message: 'The form asked for a change that it cannot make' }];\n return { status: 'error', intent, issues, ...make('error', payload, issues) };\n }\n payload = (applied.value ?? undefined) as Record<string, unknown> | undefined;\n if (intent.type === 'validate') {\n // Only the errors of the field and of the fields in it, so untouched fields show none.\n const result = await safeParse(schema, payload);\n const name = intent.name;\n const issues: ValidationIssue[] = [];\n for (const issue of result.issues ?? []) {\n const path = issue.path ? formatPath(issue.path) : '';\n if (path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`)) {\n issues.push(issue);\n }\n }\n return { status: 'intent', intent, ...make('intent', payload, issues) };\n }\n return { status: 'intent', intent, ...make('intent', payload, [], applied.list) };\n}\n","// Rate limits for server functions, endpoints and pages. A limit counts the\n// requests of each key, such as the user or the address of the client, in a\n// sliding window, and answers 429 with `Retry-After` once a key has made too\n// many.\n\nimport { RequestEvent, ServerError, getEvent } from './request.ts';\nimport type { Middleware } from './router.ts';\n\n/**\n * Where a limit keeps its counts. The default counts in memory, per\n * process. An app with more than one server passes a store on Redis or a\n * platform store, whose `increment` is one atomic command, such as `INCR`\n * with `EXPIRE`. A limit decides on the count that `increment` returns, so\n * requests at the same time cannot all read one count and all pass.\n */\nexport interface RateLimitStore {\n /**\n * Adds one to the count of a key, which expires after `ttl` milliseconds,\n * and returns the new count, in one atomic step.\n */\n increment(key: string, ttl: number): number | Promise<number>;\n /** The count of a key, or undefined when it has none or it expired. */\n get(key: string): number | undefined | Promise<number | undefined>;\n}\n\n/** A window as a number of milliseconds, or as text such as `'10s'`, `'1m'` or `'1h'`. */\nexport type Window = number | `${number}${'ms' | 's' | 'm' | 'h' | 'd'}`;\n\nexport interface RateLimitOptions {\n /** How many requests a key can make in the window. */\n max: number;\n /** The length of the window. */\n window: Window;\n /**\n * What to count by, from the event and the arguments of the call, such as\n * the ID of the user in `event.locals`, or the email of a sign-in form.\n * Without a key, or when it returns undefined, the limit counts by the\n * address of the client that the server passed. Each server function, or\n * each route for middleware, counts on its own, whatever the key.\n */\n key?: (event: RequestEvent, args: unknown[]) => string | undefined | Promise<string | undefined>;\n /** The event of the request. Defaults to `getEvent()`. */\n event?: RequestEvent;\n /** The store of the counts. Defaults to the store of `configureRateLimit`, or memory. */\n store?: RateLimitStore;\n /** Whether the limit counts. Defaults to `configureRateLimit`, which is on. */\n enabled?: boolean;\n}\n\nexport interface RateLimitConfig {\n /** The store of every limit that names none. Defaults to memory, which counts per process. */\n store?: RateLimitStore;\n /**\n * The proxies in front of the server, as addresses or CIDR ranges, such\n * as `10.0.0.0/8`. `clientAddress` reads `X-Forwarded-For` when the\n * address that the server saw is one of them. A range that is not an\n * address, with or without a prefix length, throws.\n */\n proxies?: string[];\n /** Whether limits count. Defaults to true. Pages that the build prerenders never count. */\n enabled?: boolean;\n}\n\n/**\n * The error of a request over its limit. Its status is 429, and\n * `retryAfter` is how many seconds to wait. In the browser, the call rejects\n * with it, and `retryAfter` comes from the `Retry-After` header.\n */\nexport class RateLimitError extends ServerError {\n readonly retryAfter: number;\n\n constructor(retryAfter: number) {\n super(\n `Too many requests. Try again in ${retryAfter} ${retryAfter === 1 ? 'second' : 'seconds'}`,\n {\n status: 429,\n },\n );\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\nconst UNITS: Record<string, number> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };\n\n/** The length of a window in milliseconds. */\nexport function windowMs(window: Window): number {\n if (typeof window === 'number') {\n return window;\n }\n const match = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/.exec(window);\n if (!match) {\n throw new TypeError(`The window \"${window}\" is not a length such as \"10s\", \"1m\" or \"1h\"`);\n }\n return Number(match[1]) * UNITS[match[2]!]!;\n}\n\n/** Counts in memory, per process. Expired keys go when they are read, and in a sweep now and then. */\nexport function createMemoryStore(now: () => number = Date.now): RateLimitStore {\n const counts = new Map<string, { count: number; expires: number }>();\n let sweeps = 0;\n function sweep(): void {\n if (++sweeps % 1000 !== 0) {\n return;\n }\n const time = now();\n for (const [key, entry] of counts) {\n if (entry.expires <= time) {\n counts.delete(key);\n }\n }\n }\n return {\n increment(key, ttl) {\n sweep();\n const time = now();\n const entry = counts.get(key);\n if (!entry || entry.expires <= time) {\n counts.set(key, { count: 1, expires: time + ttl });\n return 1;\n }\n entry.count++;\n return entry.count;\n },\n get(key) {\n const entry = counts.get(key);\n return entry && entry.expires > now() ? entry.count : undefined;\n },\n };\n}\n\nconst config: RateLimitConfig = {};\nlet memory: RateLimitStore | undefined;\nlet warned = false;\n/** The clock, which tests replace. */\nlet clock: () => number = Date.now;\n\n/** Sets the defaults of every limit: the store, the trusted proxies, and whether limits count. */\nexport function configureRateLimit(options: RateLimitConfig): void {\n // A typo in a range throws here, rather than trusting the wrong addresses later.\n for (const range of options.proxies ?? []) {\n parseRange(range);\n }\n Object.assign(config, options);\n}\n\n/** Replaces the clock of the limits, for tests. Returns the clock from before. */\nexport function setRateLimitClock(now: () => number): () => number {\n const previous = clock;\n clock = now;\n memory = createMemoryStore(now);\n warned = false;\n return previous;\n}\n\n/** True in development and in tests, from `NODE_ENV`. A runtime without it is production. */\nfunction isDevelopment(): boolean {\n const process = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process;\n const mode = process?.env?.NODE_ENV;\n return mode === 'development' || mode === 'test';\n}\n\n/**\n * What a limit counts per: the server function, the pattern of the route,\n * such as `/api/[id]`, or one count for every path that no route matches.\n */\nfunction getTarget(event: RequestEvent): string {\n return event.call?.id ?? event.route ?? '(no route)';\n}\n\n/**\n * The key of a request: the key of the app, or the address of the client.\n * Without either, callers would share one count, and one client could use\n * up the limit of all. So it throws in production. In development it warns\n * once and returns undefined, and the limit does not count.\n */\nasync function readKey(\n event: RequestEvent,\n options: RateLimitOptions,\n): Promise<string | undefined> {\n const key = (await options.key?.(event, event.call?.args ?? [])) ?? clientAddress(event);\n if (key !== undefined) {\n return key;\n }\n const message = `rateLimit: the request to \"${getTarget(event)}\" has no key, because the server did not pass the address of the client. Pass \\`address\\` to the handler of the server, or set \\`key\\` on the limit.`;\n if (!isDevelopment()) {\n throw new Error(message);\n }\n if (!warned) {\n warned = true;\n console.warn(`${message} Until then, the limit does not count in development.`);\n }\n return undefined;\n}\n\n/**\n * Counts a request, and throws a `RateLimitError` when its key has made\n * more than `max` requests in the window.\n */\nasync function check(event: RequestEvent, options: RateLimitOptions): Promise<void> {\n if (event.prerender || !(options.enabled ?? config.enabled ?? true)) {\n return;\n }\n const key = await readKey(event, options);\n if (key === undefined) {\n return;\n }\n const name = `${key} ${getTarget(event)}`;\n const store = options.store ?? config.store ?? (memory ??= createMemoryStore(clock));\n const window = windowMs(options.window);\n const now = clock();\n const bucket = Math.floor(now / window);\n const elapsed = now - bucket * window;\n // Two counts per key, this window and the last. The last one weighs by how much of it is still\n // inside the sliding window, so a burst at the edge of a window does not get through. The\n // request counts first, and the limit decides on the count that the store returns, so requests\n // at the same time each get their own count. A refused request counts too, so a client that\n // keeps trying stays refused until it slows down.\n const [current, previous = 0] = await Promise.all([\n store.increment(`${name} ${bucket}`, window * 2),\n store.get(`${name} ${bucket - 1}`),\n ]);\n const weight = 1 - elapsed / window;\n if (current + previous * weight <= options.max) {\n return;\n }\n // When the next request passes: later in this window, once enough of the last one has left it,\n // or in the next window, once enough of this one has.\n const room = options.max - current - 1;\n const wait =\n room >= 0 && previous > 0\n ? window * (1 - room / previous) - elapsed\n : window -\n elapsed +\n (current > options.max - 1 ? window * (1 - (options.max - 1) / current) : 0);\n const retryAfter = Math.max(1, Math.ceil(wait / 1000));\n event.headers.set('retry-after', String(retryAfter));\n throw new RateLimitError(retryAfter);\n}\n\n/**\n * Limits how often a key, such as the user or the address of the client,\n * can call a server function. Call it first thing in the function, before\n * its first `await`, as `getEvent()`:\n *\n * ```ts\n * async function signIn(email: string, password: string) {\n * 'use server';\n * await rateLimit({ ...rateLimit.strict, key: () => email.toLowerCase() });\n * // …\n * }\n * ```\n *\n * The fourth call in 10 seconds for one email rejects with a\n * `RateLimitError`, with status 429 and `Retry-After`, and the rest of the\n * function does not run. Without a `key`, the limit counts by the address\n * of the client, which the server passes to its handler as `address`. In\n * production, a limit with neither throws. `rateLimit.middleware(options)`\n * limits every request under a folder of routes, or of the whole app from\n * the entry.\n */\nexport const rateLimit: RateLimit = Object.assign(\n (options: RateLimitOptions): Promise<void> => {\n const event = options.event ?? getEvent();\n return check(event, options);\n },\n {\n middleware:\n (options: RateLimitOptions): RateLimitMiddleware =>\n async (target: Request | RequestEvent, next: () => Promise<Response>) => {\n const event = target instanceof RequestEvent ? target : (options.event ?? getEvent());\n try {\n await check(event, options);\n } catch (error) {\n if (error instanceof RateLimitError) {\n return new Response(error.message, {\n status: 429,\n headers: { 'retry-after': String(error.retryAfter), 'content-type': 'text/plain' },\n });\n }\n throw error;\n }\n return next();\n },\n strict: { max: 3, window: '10s' } satisfies RateLimitOptions,\n },\n);\n\n/** A middleware of a folder, `(request, next)`, or of the entry, `(event, next)`. */\nexport type RateLimitMiddleware = Middleware &\n ((event: RequestEvent, next: () => Promise<Response>) => Promise<Response>);\n\nexport interface RateLimit {\n (options: RateLimitOptions): Promise<void>;\n /**\n * A limit for every request that passes through a middleware, of a folder\n * or of the entry. A request over the limit answers 429 with `Retry-After`.\n * Each route counts on its own, by its pattern, such as `/api/[id]`.\n */\n middleware: (options: RateLimitOptions) => RateLimitMiddleware;\n /** A limit for functions that guess at secrets, such as a sign-in or a code check: 3 calls in 10 seconds. */\n strict: RateLimitOptions;\n}\n\n// Addresses\n\n/** The 16 bytes of an address, or undefined for text that is not one. */\nfunction parseAddress(text: string): Uint8Array | undefined {\n const value = text.trim().replace(/^\\[|\\]$/g, '');\n if (value.includes(':')) {\n return parseIPv6(value);\n }\n const parts = value.split('.');\n if (parts.length !== 4) {\n return undefined;\n }\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part) || Number(part) >= 256) {\n return undefined;\n }\n }\n const bytes = new Uint8Array(16);\n bytes[10] = 0xff;\n bytes[11] = 0xff;\n for (const [index, part] of parts.entries()) {\n bytes[12 + index] = Number(part);\n }\n return bytes;\n}\n\nfunction parseIPv6(value: string): Uint8Array | undefined {\n // An IPv4 tail, such as `::ffff:1.2.3.4`, becomes two groups.\n const tail = /^(.*:)(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(value);\n let text = value;\n if (tail) {\n const v4 = parseAddress(tail[2]!);\n if (!v4) {\n return undefined;\n }\n text = `${tail[1]}${((v4[12]! << 8) | v4[13]!).toString(16)}:${((v4[14]! << 8) | v4[15]!).toString(16)}`;\n }\n const halves = text.split('::');\n if (halves.length > 2) {\n return undefined;\n }\n const head = halves[0] ? halves[0].split(':') : [];\n const rest = halves[1] ? halves[1].split(':') : [];\n const missing = 8 - head.length - rest.length;\n if (missing < 0 || (halves.length === 1 && missing !== 0)) {\n return undefined;\n }\n const groups = [...head, ...Array<string>(missing).fill('0'), ...rest];\n const bytes = new Uint8Array(16);\n for (const [index, group] of groups.entries()) {\n if (!/^[\\da-f]{1,4}$/i.test(group)) {\n return undefined;\n }\n const number = Number.parseInt(group, 16);\n bytes[index * 2] = number >> 8;\n bytes[index * 2 + 1] = number & 0xff;\n }\n return bytes;\n}\n\nfunction isIPv4(bytes: Uint8Array): boolean {\n for (const byte of bytes.slice(0, 10)) {\n if (byte !== 0) {\n return false;\n }\n }\n return bytes[10] === 0xff && bytes[11] === 0xff;\n}\n\n/** A range of addresses, as its first address and the number of bits that must match. */\ninterface Range {\n base: Uint8Array;\n bits: number;\n}\n\n/**\n * Reads a range: an address, or a CIDR such as `10.0.0.0/8` or `fd00::/8`.\n * Throws for anything else, such as `10.0.0.0/` or `10.0.0.0/33`, since a\n * range that matched every address would trust any `X-Forwarded-For`.\n */\nfunction parseRange(range: string): Range {\n const [text, length, ...extra] = range.split('/');\n const base = parseAddress(text!);\n const v4 = base !== undefined && isIPv4(base);\n if (\n !base ||\n extra.length > 0 ||\n (length !== undefined && (!/^\\d{1,3}$/.test(length) || Number(length) > (v4 ? 32 : 128)))\n ) {\n throw new TypeError(\n `The proxy range \"${range}\" is not an address, or an address and a prefix length such as \"10.0.0.0/8\"`,\n );\n }\n // Addresses are 16 bytes, with an IPv4 one in the last 4, so its prefix length moves by 96.\n return { base, bits: length === undefined ? 128 : Number(length) + (v4 ? 96 : 0) };\n}\n\nfunction inParsedRange(address: Uint8Array, { base, bits }: Range): boolean {\n if (isIPv4(base) !== isIPv4(address)) {\n return false;\n }\n for (let bit = 0; bit < bits; bit++) {\n const mask = 0x80 >> (bit % 8);\n if (((address[bit >> 3]! ^ base[bit >> 3]!) & mask) !== 0) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * True if an address is in a range: an address, or a CIDR such as\n * `10.0.0.0/8` or `fd00::/8`. Throws for a range that is neither.\n */\nexport function inRange(address: Uint8Array, range: string): boolean {\n return inParsedRange(address, parseRange(range));\n}\n\n/** The text of an address. An IPv6 address counts by its /64, since one client often holds a whole subnet. */\nfunction formatAddress(bytes: Uint8Array): string {\n if (isIPv4(bytes)) {\n return bytes.slice(12).join('.');\n }\n const groups: string[] = [];\n for (let index = 0; index < 8; index++) {\n groups.push(index < 4 ? ((bytes[index * 2]! << 8) | bytes[index * 2 + 1]!).toString(16) : '0');\n }\n return groups.join(':');\n}\n\n/**\n * The address of the client of a request. It is the address that the server\n * saw, which the handler of the server passes as `address`. When that\n * address is one of the proxies that `configureRateLimit({ proxies })`\n * names, it comes from `X-Forwarded-For`: the header is read from the right,\n * past the trusted proxies, because a client can write anything at its\n * left. An IPv6 address counts by its /64.\n *\n * Undefined when the server passed no address, whatever the headers say,\n * since nothing then shows that the header comes from a proxy. Undefined too\n * when the first hop past the proxies is not an address.\n */\nexport function clientAddress(\n event: RequestEvent,\n proxies: string[] = config.proxies ?? [],\n): string | undefined {\n const seen = event.address === undefined ? undefined : parseAddress(event.address);\n if (!seen) {\n return undefined;\n }\n const ranges: ReturnType<typeof parseRange>[] = [];\n for (const proxy of proxies) {\n ranges.push(parseRange(proxy));\n }\n function trusted(address: Uint8Array): boolean {\n for (const range of ranges) {\n if (inParsedRange(address, range)) {\n return true;\n }\n }\n return false;\n }\n if (!trusted(seen)) {\n return formatAddress(seen);\n }\n const hops: string[] = [];\n for (const hop of (event.request.headers.get('x-forwarded-for') ?? '').split(',')) {\n if (hop.trim() !== '') {\n hops.push(hop);\n }\n }\n let client = seen;\n for (let index = hops.length - 1; index >= 0; index--) {\n const address = parseAddress(hops[index]!);\n // A hop that is not an address stops here, rather than reading what the client wrote left of it.\n if (!address) {\n return undefined;\n }\n client = address;\n if (!trusted(address)) {\n break;\n }\n }\n // When every hop is a proxy, the request comes from the first of them.\n return formatAddress(client);\n}\n","// Forms that a second post must not run again, such as one that places an\n// order. Each form that the server renders for such a function gets a key in\n// its URL, and the server answers a post with a key that it has seen with\n// the result that it kept, without running the function again.\n\nimport { fromJSON, toJSON } from 'seroval';\nimport { cacheStore } from './cache.ts';\nimport {\n IDEMPOTENT,\n currentEvent,\n idempotentId,\n isRedirect,\n redirect,\n withEvent,\n} from './request.ts';\nimport { serialOptions, syncPlugins } from './serial.ts';\n\n/** What a post with a key gave: a result, or a redirect. */\ntype Outcome = { result: unknown } | { redirect: { location: string; status: number } };\n\n/** Runs that are going on, by key, so a second post while the first runs waits for it. */\nconst running = new Map<string, Promise<Outcome>>();\n\nexport interface IdempotentOptions {\n /** Seconds that the result of a key is kept. Defaults to 600. */\n maxAge?: number;\n}\n\n/**\n * Makes a server function that runs once for each form that the server\n * renders for it. A second post of the same form, such as a double click\n * before the page loaded or a post again after a reload, gets the result of\n * the first, or the same redirect, without running the function again.\n *\n * - It works for the exported functions of a `'use server'` file, used as the\n * `action` of a form.\n * - The key is in the URL of the form, so a page with such a form is not\n * cached for everyone. Each render has a new key.\n * - With scripts, the form gets a new key after each answer, so a post that\n * the user means again runs again.\n * - A call without a key, such as from a handler, runs as usual.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport function idempotent<F extends (...args: any[]) => unknown>(\n fn: F,\n options: IdempotentOptions = {},\n): F {\n const maxAge = options.maxAge ?? 600;\n const wrapper = ((...args: unknown[]) => {\n const event = currentEvent();\n const key = event && new URL(event.request.url).searchParams.get('__key');\n const id = idempotentId.get(wrapper);\n if (!event || !key || !id || !/^[\\w-]{8,64}$/.test(key)) {\n return fn(...args);\n }\n const storeKey = `brumate:once:${id}:${key}`;\n let run = running.get(storeKey);\n if (!run) {\n run = (async (): Promise<Outcome> => {\n const kept = await cacheStore().get(storeKey);\n if (kept) {\n return fromJSON(JSON.parse(kept) as never, { plugins: syncPlugins }) as Outcome;\n }\n let outcome: Outcome;\n try {\n outcome = { result: await withEvent(event, () => fn(...args)) };\n } catch (error) {\n // A redirect is the answer of the post, so a second post redirects too. Other errors\n // are not kept, so the post can be tried again.\n if (!isRedirect(error)) {\n throw error;\n }\n outcome = { redirect: { location: error.location, status: error.status } };\n }\n const text = JSON.stringify(toJSON(outcome, { plugins: syncPlugins, ...serialOptions() }));\n await cacheStore().set(storeKey, text, maxAge);\n return outcome;\n })();\n running.set(storeKey, run);\n void run.then(\n () => running.delete(storeKey),\n () => running.delete(storeKey),\n );\n }\n return run.then((outcome) => {\n if ('redirect' in outcome) {\n redirect(outcome.redirect.location, outcome.redirect.status);\n }\n return outcome.result;\n });\n }) as F;\n Object.defineProperty(wrapper, IDEMPOTENT, { value: true });\n return wrapper;\n}\n","import { crossSerialize, crossSerializeStream, fromJSON } from 'seroval';\nimport type { SerovalJSON } from 'seroval';\nimport { cacheStore, tagVersions } from './cache.ts';\nimport {\n VOID_ELEMENTS,\n actionAttributes,\n attribute as attributeText,\n escape,\n escapeAttribute,\n bindEntry,\n handlerEntry,\n insertValue,\n isRaw,\n onAttribute,\n rawHTML,\n ownValue,\n spread as spreadAttributes,\n styleElement,\n} from './html.ts';\nimport { MODIFIERS } from './events.ts';\nimport { closesParagraph, firstTag } from '../nesting.ts';\nimport type { Raw } from './html.ts';\nimport { callPlugins, serialOptions, plugins, syncPlugins } from './serial.ts';\nimport { serverSecrets } from './secrets.ts';\nimport {\n Binding,\n CHILDREN,\n CHILDREN_REF,\n ChildrenReference,\n ElementReference,\n FunctionReference,\n ITEM,\n ITEM_SLOT,\n MODULE,\n OWNER,\n PARTS,\n PREFIX,\n PropPromise,\n SOURCE,\n MemoError,\n SlotReference,\n addEntryHandlers,\n isAsyncIterable,\n isBinding,\n isSlotReference,\n parseId,\n} from './shared.ts';\nimport { functionReferences } from './calls.ts';\nimport { STREAM_TYPE, toChunkStream } from './stream.ts';\nimport type { PackedState, PageState, PropSink, ScopeId, ScopeState } from './shared.ts';\nimport {\n Redirect,\n RequestEvent,\n ServerError,\n errorSink,\n failures,\n idempotentIds,\n isRedirect,\n runEntry,\n unwrap,\n withEvent,\n} from './request.ts';\nimport type {\n EntryMiddleware,\n ErrorSink,\n RequestKind,\n ServerErrorHandler,\n ServerErrorKind,\n TraceEntry,\n} from './request.ts';\nimport type { Context as ContextValue } from './context.ts';\n\nexport {\n affix,\n classAttribute,\n escape,\n escapeAttribute,\n internal,\n mergeAttributes,\n raw,\n vars,\n} from './html.ts';\nexport type { Raw } from './html.ts';\nexport { produce } from './produce.ts';\nexport { searchParam } from './search-params.ts';\nexport { createContext, navigationContext, routeContext } from './context.ts';\nexport type { NavigationState, Route } from './context.ts';\nimport { ROUTE_KEY } from './context.ts';\nimport { matchRoute, missingPage, notFound } from './router.ts';\nimport type { MiddlewareLoader, RouteMatch, RouteNode, RouteView } from './router.ts';\nexport { matchRoute } from './router.ts';\nexport type {\n EndpointLoader,\n Handler,\n Loader,\n Middleware,\n MiddlewareLoader,\n RouteMatch,\n RouteNode,\n RouteView,\n} from './router.ts';\nexport {\n RequestEvent,\n ServerError,\n dedupe,\n defineMiddleware,\n getEvent,\n isRedirect,\n redirect,\n withEvent,\n} from './request.ts';\nexport type {\n EntryMiddleware,\n Locals,\n Redirect,\n RequestCall,\n RequestEventOptions,\n RequestKind,\n ServerErrorHandler,\n ServerErrorInfo,\n ServerErrorKind,\n} from './request.ts';\nexport { ValidationError, fieldErrors, parse, parseForm, safeParse } from './validate.ts';\nexport { parseSubmission } from './submission.ts';\nexport type {\n FailedSubmission,\n IntentSubmission,\n ReplyOptions,\n Submission,\n SubmissionOptions,\n SuccessfulSubmission,\n} from './submission.ts';\nexport type { Intent, SubmissionResult } from './forms.ts';\nexport { RateLimitError, clientAddress, configureRateLimit, rateLimit } from './rate-limit.ts';\nexport type {\n RateLimit,\n RateLimitConfig,\n RateLimitMiddleware,\n RateLimitOptions,\n RateLimitStore,\n Window,\n} from './rate-limit.ts';\nexport type { ParseResult, ValidationIssue } from './validate.ts';\nexport type { StandardSchemaV1 } from './standard-schema.ts';\nexport { createSession, parseCookies, serializeCookie, toNodeHeaders } from './cookies.ts';\nexport { cached, memoryStore, revalidate, setCacheStore, storageStore } from './cache.ts';\nexport { useSerialEntry } from './shared.ts';\nexport { idempotent } from './idempotent.ts';\nexport type { IdempotentOptions } from './idempotent.ts';\nexport type { CachedOptions, CacheStore } from './cache.ts';\nexport type { CookieOptions, Session, SessionOptions } from './cookies.ts';\nexport { ElementReference, FunctionReference };\nexport { unbind } from './shared.ts';\n\n/** What `$bind(name)` passes a child: the value of the name, and the scope and slot it writes. */\nexport function binding<T>(value: T, scope: ScopeId, slot: number, set?: unknown): Binding<T> {\n return new Binding(value, new SlotReference(scope, slot), set);\n}\nexport type { PageState, ScopeId, ScopeState };\n\n/** The scope and the slot that hold the list of a list item. */\nexport type ItemSource = readonly [scope: ScopeId, slot: number];\n\n/** A `#loading` body that renders after the rest of the page. */\ninterface Boundary {\n id: ScopeId;\n /** Resolves to the body's markup, and its scopes in `ctx.state`. */\n render: Promise<{ html: string; ctx: Context }>;\n /** True when a `#try` body around it failed, so its markers were never sent. */\n cancelled?: boolean;\n /** A body around the target of a request for a `#defer` body, which renders but is not sent. */\n around?: boolean;\n /** The `#reveal` group that orders it, when it is in one. */\n group?: RevealGroup;\n /** The `#try` blocks around it, from the outside in. */\n catchers: Catcher[];\n}\n\n/** A `#try` that is rendering its body, and how to render its `#catch` body later. */\ninterface Catcher {\n /** The marker of the block, `<scope>:<anchor>`. */\n key: string;\n /** Renders the `#catch` body for an error, in a context of its own. */\n render: (ctx: Context, error: unknown) => Promise<string>;\n}\n\n/** The order of a `#reveal` block. */\nexport type RevealOrder = 'sequential' | 'backwards' | 'together' | 'natural';\n\n/**\n * The `#loading` bodies of a `#reveal` block, in the order of the markup.\n * When a body is ready, the stream asks the group, which sends the bodies\n * that its order lets show. The data of every body still loads at once.\n */\nclass RevealGroup {\n readonly order: RevealOrder;\n readonly collapsed: boolean;\n /** The bodies that stream, each with how to send it once it is ready. */\n private readonly members: { id: ScopeId; send?: (after: string) => void; sent?: boolean }[] = [];\n /** The fallbacks that `collapsed` hides until the body before them shows. */\n readonly hidden: Set<ScopeId> = new Set();\n private closed = false;\n\n constructor(order: RevealOrder, collapsed: boolean) {\n this.order = order;\n this.collapsed = collapsed;\n }\n\n /** True when a body that is ready can render in place, before the bodies that stream. */\n mayShow(): boolean {\n return this.order === 'natural' || (this.order === 'sequential' && this.members.length === 0);\n }\n\n /** True when the fallback of the next body that streams waits, for `collapsed`. */\n hides(): boolean {\n return this.collapsed && this.members.length > 0;\n }\n\n add(id: ScopeId): void {\n this.members.push({ id });\n }\n\n /** The body is ready, or failed with nothing to send. `send` writes it, and runs `after` with it. */\n ready(id: ScopeId, send: (after: string) => void): void {\n let member: (typeof this.members)[number] | undefined;\n for (const item of this.members) {\n if (item.id === id) {\n member = item;\n break;\n }\n }\n if (member) {\n member.send = send;\n this.flush();\n } else {\n send('');\n }\n }\n\n /** The block ended, so the group knows its last body. */\n close(): void {\n this.closed = true;\n this.flush();\n }\n\n private flush(): void {\n const { members } = this;\n const sendAt = (index: number): void => {\n const member = members[index]!;\n member.sent = true;\n // `collapsed`: the body that shows brings the fallback of the next one in.\n const next = members[index + 1];\n member.send!(next && this.hidden.has(next.id) ? `$bF(${scriptJSON(next.id)})` : '');\n };\n if (this.order === 'natural') {\n for (const [index, member] of members.entries()) {\n if (member.send && !member.sent) {\n sendAt(index);\n }\n }\n } else if (this.order === 'sequential') {\n for (let index = 0; index < members.length && members[index]!.send; index++) {\n if (!members[index]!.sent) {\n sendAt(index);\n }\n }\n } else if (this.closed && this.order === 'backwards') {\n for (let index = members.length - 1; index >= 0 && members[index]!.send; index--) {\n if (!members[index]!.sent) {\n sendAt(index);\n }\n }\n } else if (this.closed) {\n // Every body must be ready before any is sent.\n let allReady = true;\n for (const member of members) {\n if (!member.send) {\n allReady = false;\n break;\n }\n }\n if (allReady) {\n for (const [index, member] of members.entries()) {\n if (!member.sent) {\n sendAt(index);\n }\n }\n }\n }\n }\n}\n\n/** The last entry of the inserted children that comes from `from`. */\nfunction findLastInserted<T extends { from: ScopeId }>(\n inserted: readonly T[],\n from: ScopeId | undefined,\n): T | undefined {\n for (let index = inserted.length - 1; index >= 0; index--) {\n if (inserted[index]!.from === from) {\n return inserted[index];\n }\n }\n return undefined;\n}\n\n/** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */\nfunction holdsBoundary(id: ScopeId, target: ScopeId): boolean {\n return typeof target === 'string' && target.startsWith(`${id}.`);\n}\n\n/** The `#defer` body that a render renders, for the request of the browser that asks for it. */\nexport interface DeferTarget {\n /** The boundary ID of the block. */\n boundary: ScopeId;\n /** The scope and the anchor of the block, as `<scope>:<anchor>`, which the render checks. */\n at: string;\n /**\n * `found` once the render reaches the block at `at`. `moved` when it reaches the boundary\n * elsewhere, such as after the data of the page changed and moved the IDs before it.\n */\n status?: 'found' | 'moved';\n}\n\n/** A point in a render that `restore` goes back to. */\nexport interface Mark {\n /** The prefix of the IDs of the block that the render was in, and its counters then. */\n prefix: string;\n scope: number;\n boundary: number;\n /** How many blocks the render was in. */\n depth: number;\n undo: number;\n owner: ScopeId | undefined;\n}\n\n/**\n * Where a render takes its scope and boundary IDs from. The page takes\n * numbers from its base. Each `#loading` body has its own, whose IDs are the\n * ID of its boundary, a dot and a number, such as `5.0`. A body resumes when\n * its data arrives, so with one counter for the page its IDs, and those of\n * the markup after it, would depend on that order.\n *\n * A block whose shape depends on data, such as an `#if` or a `#for`, also\n * numbers the scopes of its bodies after an ID of its own. The markup after\n * the block then keeps its IDs, whichever branch rendered and however many\n * items a list had, so a later request for a `#defer` body numbers the page\n * the same way even when the user or the data before the block differs.\n */\ninterface IdSpace {\n /** `''` for the page, or the ID of the boundary or block and a dot. */\n prefix: string;\n scope: number;\n /** The counter of boundary IDs, which blocks take their IDs from too. */\n boundary: number;\n /** The number of the first scope, and the scopes from there on, so an ID finds its scope. */\n first: number;\n entries: (ScopeEntry | undefined)[];\n}\n\nfunction spaceId(space: IdSpace, n: number): ScopeId {\n return space.prefix ? `${space.prefix}${n}` : n;\n}\n\n/**\n * True for an ID that a render made after `mark`: a scope of the same space\n * from its counter on, or a scope inside a block or boundary from then on.\n */\nfunction madeAfter(mark: Mark, id: ScopeId): boolean {\n const text = String(id);\n if (!text.startsWith(mark.prefix)) {\n return false;\n }\n const rest = text.slice(mark.prefix.length);\n const dot = rest.indexOf('.');\n return dot === -1 ? Number(rest) >= mark.scope : Number(rest.slice(0, dot)) >= mark.boundary;\n}\n\n/** A scope of a render: its record, and what the server keeps of it while the page renders. */\nexport interface ScopeEntry extends PropSink {\n id: ScopeId;\n /** The prefix of the ID and the number after it, such as `'5.'` and `1`, or `''` and `3`. */\n prefix: string;\n n: number;\n record: ScopeState;\n /** The render whose state holds the record. */\n ctx: Context | undefined;\n /** The ID space that finds the scope by its ID, for a scope that `scope()` made. */\n space?: IdSpace;\n /** The scope that the contexts of this one are found in. */\n parent?: ScopeId;\n /** The values of contexts that this scope provides. */\n values?: Map<string, unknown>;\n /** The names of the slots, so an error can name a value that cannot be sent. */\n names?: string[];\n /** The scope and the slot that hold the list of this list item. */\n source?: ItemSource;\n}\n\n/**\n * Tracks the scopes of one render. A `#loading` body renders in a child\n * context, so its scopes are written with its markup.\n */\nexport class Context {\n /**\n * The scopes of this render, in the order it made them, with their\n * records. A record that this render adds to a scope of another render,\n * such as a link from a `#loading` body to a scope of the page, is here\n * too, as a scope of its own.\n */\n readonly scopes: ScopeEntry[] = [];\n /**\n * Every ID space of the page, across the renders of `#loading` bodies, on\n * the root context. A scope is found by its ID in the entries of its space.\n * The spaces are put in a map by prefix only when a scope is looked up\n * outside the blocks that are open, since a render makes many and looks\n * up few, and each string key costs a hash.\n */\n private readonly made: IdSpace[] = [];\n private byPrefix: Map<string, IdSpace> | undefined;\n private indexed = 0;\n /** The records that this render adds to scopes of other renders, by ID. */\n private partials: Map<ScopeId, ScopeEntry> | undefined;\n /** The scope that the render used last, since it uses one a few times in a row. */\n private last: ScopeEntry | undefined;\n private readonly root: Context;\n /** The keys of the signals that a visible `$client` waits for. See `near`. */\n private waited?: Set<string>;\n /** The ID spaces of the blocks that the render is in, from the outside in. */\n private readonly spaces: IdSpace[];\n private readonly baseId: number;\n /** The `#defer` body to render, in the request for it. The rest of the page renders no body. */\n target: DeferTarget | undefined;\n /** True in the context of the target body and the bodies inside it. */\n private inTarget = false;\n private readonly boundaries: Boundary[] = [];\n private readonly styles = new Set<string>();\n /** Markup of `#portal` blocks, written at the end of the page. */\n readonly portals: string[] = [];\n /** Markup of `#head` blocks. */\n private readonly heads: string[] = [];\n private pageTitle: string | undefined;\n /** The titles that this render set, and whether they all came from a `<title>` in `#head`. */\n private titles = { count: 0, markup: true };\n private onBoundary: ((boundary: Boundary) => void) | undefined;\n /** The `#try` blocks of the parents of this context, from the outside in. */\n outer: Catcher[] = [];\n /** The `#try` blocks of this context that are rendering their bodies now. */\n private readonly catchers: Catcher[] = [];\n /** The scope that renders the next component, which becomes its owner. */\n private owner: ScopeId | undefined;\n /**\n * Children that render where they are inserted: the scope of the markup\n * that wrote them, and the scope where they are, for their contexts.\n */\n private readonly inserted: { from: ScopeId; at: ScopeId; tag?: string }[] = [];\n /** Takes back what this context added to the page, from the newest, for `restore`. */\n private readonly undo: (() => void)[] = [];\n\n /** The URL prefix of server function calls. */\n private rpcPrefix = '/_brumate';\n /** The ID of the build, for forms that post to server functions. See `RenderOptions`. */\n build: string | undefined;\n /** True in development, where a memo that failed or a `#catch` sends its error to the browser. */\n development = false;\n\n /** Results of server functions that a form posted to this page, for `$action`. */\n actions: Map<unknown, unknown> = new Map();\n /** The params of the route of the page, for `$route`. */\n params: Record<string, string> = {};\n /** The request of the page, when it renders with one. */\n event: RequestEvent | undefined;\n /** The sink of the event, or of the `onError` option of a render without a request. */\n errors: ErrorSink | undefined;\n /** Results of server function calls in this render, so the same call runs once. */\n readonly calls: Map<string, unknown> = new Map();\n\n /** The event of the request, or undefined when the render has none. */\n requestEvent(): RequestEvent | undefined {\n return this.root.event;\n }\n\n /** Where the errors of the render go, when the app has an `onError`. */\n errorSink(): ErrorSink | undefined {\n return this.root.errors;\n }\n\n /** The event of the page, for `getEvent()` in a component, which the compiler rewrites to this. */\n getEvent(): RequestEvent {\n const event = this.root.event;\n if (!event) {\n throw new Error('getEvent() works while a page renders with a request, such as in a route');\n }\n return event;\n }\n\n /** Starts an entry of the trace of the request, in development. */\n traced(kind: TraceEntry['kind'], label: string): ((failed?: boolean) => void) | undefined {\n return this.root.event?.traced(kind, label);\n }\n\n /** Marks the request of the page as one that depends on the user, so the page is not cached for everyone. */\n personal(): void {\n if (this.root.event) {\n this.root.event.personal = true;\n }\n }\n\n /** Runs code of the render with its event and its call results, such as a memo's compute. */\n run<T>(callback: () => T): T {\n return withEvent(this.root.event, callback, this.root.calls);\n }\n\n /** The result of a server function that a form posted to this page. */\n actionResult(fn: unknown): unknown {\n return this.root.actions.get(unwrap(fn));\n }\n\n /** `prefix` is the boundary ID and a dot, for the context of a `#loading` body. */\n constructor(root?: Context, rpc?: string, base = 0, prefix = '') {\n this.root = root ?? this;\n if (rpc) {\n this.rpcPrefix = rpc;\n }\n const first = prefix ? 0 : base;\n this.spaces = [{ prefix, scope: first, boundary: first, first, entries: [] }];\n this.root.made.push(this.spaces[0]!);\n this.baseId = base;\n }\n\n /** The base of the render, which the browser sends back to ask for a `#defer` body. */\n base(): number {\n return this.root.baseId;\n }\n\n /** True in a request for a `#defer` body, outside the body, once the body has started. */\n past(): boolean {\n return this.root.target?.status === 'found' && !this.inTarget;\n }\n\n /**\n * A number above every scope and boundary ID of the page so far, so a\n * later render can start there. The IDs inside boundaries start with one.\n */\n next(): number {\n const space = this.root.spaces[0]!;\n return Math.max(space.scope, space.boundary);\n }\n\n /** The space that the next IDs come from. */\n private get space(): IdSpace {\n return this.spaces.at(-1)!;\n }\n\n /**\n * Starts a block whose shape depends on data, such as an `#if` or a\n * `#for`. The scopes of its bodies are numbered after one ID that the\n * block takes, until `leave`. A `#loading` body that renders in place\n * passes the ID of its boundary, so its scopes get the IDs that they\n * would get in a stream.\n */\n enter(id: ScopeId = spaceId(this.space, this.space.boundary++)): void {\n const space: IdSpace = { prefix: `${id}.`, scope: 0, boundary: 0, first: 0, entries: [] };\n this.spaces.push(space);\n this.root.made.push(space);\n }\n\n /** Ends the block that `enter` started. */\n leave(): void {\n this.spaces.pop();\n }\n\n /** Returns the URL prefix of server function calls. */\n rpc(): string {\n return this.root.rpcPrefix;\n }\n\n /** True when the render is in development. */\n isDev(): boolean {\n return this.root.development;\n }\n\n /** Returns the ID of the build, when the render has one. */\n buildId(): string | undefined {\n return this.root.build;\n }\n\n /**\n * Returns a new scope ID. `kind` is the scope's ID in the compiled\n * component, `parent` is the scope that contains it, and `module` is the\n * component ID of a component's root scope.\n */\n scope(kind: number, parent?: ScopeId, module?: string): ScopeId {\n const root = this.root;\n const space = this.space;\n const n = space.scope++;\n const id = space.prefix ? `${space.prefix}${n}` : n;\n const record: ScopeState = {};\n record.k = kind;\n if (parent !== undefined) {\n record.p = parent;\n }\n let up = parent;\n if (module !== undefined) {\n record.m = module;\n // A component's root scope links to the scope that rendered it.\n if (root.owner !== undefined) {\n record.o = root.owner;\n up = root.owner;\n root.owner = undefined;\n }\n }\n // A scope at the top of children that are inserted elsewhere finds its contexts there.\n const inserted = findLastInserted(root.inserted, up);\n if (inserted) {\n up = inserted.at;\n record.t = inserted.at;\n }\n const entry: ScopeEntry = { id, prefix: space.prefix, n, record, ctx: this, parent: up, space };\n this.scopes.push(entry);\n space.entries.push(entry);\n this.last = entry;\n return id;\n }\n\n /** The scope of the page with an ID, from any render. */\n private find(id: ScopeId): ScopeEntry | undefined {\n const root = this.root;\n if (typeof id === 'number') {\n const page = root.made[0]!;\n return page.entries[id - page.first];\n }\n const dot = id.lastIndexOf('.');\n let n = 0;\n for (let i = dot + 1; i < id.length; i++) {\n n = n * 10 + id.charCodeAt(i) - 48;\n }\n // The scope is usually in a block that is still open, such as the item of a list.\n for (let i = this.spaces.length - 1; i >= 0; i--) {\n const space = this.spaces[i]!;\n if (space.prefix.length === dot + 1 && id.startsWith(space.prefix)) {\n return space.entries[n - space.first];\n }\n }\n const byPrefix = (root.byPrefix ??= new Map());\n for (; root.indexed < root.made.length; root.indexed++) {\n const space = root.made[root.indexed]!;\n byPrefix.set(space.prefix, space);\n }\n const space = byPrefix.get(id.slice(0, dot + 1));\n return space?.entries[n - space.first];\n }\n\n /**\n * Renders children where a component inserts them, at `at`. Their scopes\n * keep `from`, the scope of the markup that wrote them, for their values,\n * and find their contexts from `at`.\n */\n async children(\n from: ScopeId,\n at: ScopeId,\n renderBody: () => Promise<string>,\n tag?: string,\n ): Promise<string> {\n const { inserted } = this.root;\n // Children that a component passes on, as `<Select>{children}</Select>`, render where the\n // component that gets them inserts them, so they find their contexts there too.\n const outer = findLastInserted(inserted, at);\n const entry = { from, at: outer ? outer.at : at, tag: tag ?? outer?.tag };\n if (outer) {\n // The browser finds the component that holds these children by this.\n const passing = this.find(at);\n if (passing) {\n passing.record.f = outer.at;\n }\n }\n inserted.push(entry);\n try {\n return await renderBody();\n } finally {\n inserted.splice(inserted.indexOf(entry), 1);\n }\n }\n\n /** The tag of the element where the children that render now are inserted, for spacers. */\n spacerTag(): string {\n return this.root.inserted.at(-1)?.tag ?? 'div';\n }\n\n /**\n * The ID that `$id()` makes: the scope's ID and the position of the call.\n * A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also\n * works as a CSS selector, such as `#b5_1-0`.\n */\n id(scope: ScopeId, index: number): string {\n return `b${String(scope).replace(/\\./g, '_')}-${index}`;\n }\n\n /** Sets the owner of the next component's root scope. */\n own(scope: ScopeId): void {\n this.root.owner = scope;\n }\n\n /** Provides a value of a context to the scopes inside `scope`. */\n provide<T>(context: ContextValue<T>, value: T, scope: ScopeId): void {\n const node = this.find(scope)!;\n node.values ??= new Map();\n node.values.set(context.key, value);\n const record = this.record(scope);\n record.v ??= {};\n record.v[context.key] = value;\n }\n\n /**\n * Reads a context from the nearest scope above `scope` that provides it.\n * With `slot`, records which slot holds it, so the client can update it\n * when the provided value changes.\n */\n consume<T>(context: ContextValue<T>, scope: ScopeId, slot?: number): T {\n if (slot !== undefined) {\n const record = this.record(scope);\n record.x ??= {};\n record.x[context.key] = slot;\n }\n // A scope reads the contexts of the scopes above it, not its own, so a component can read a\n // context and provide it again to the scopes inside it.\n for (let id: ScopeId | undefined = this.find(scope)?.parent; id !== undefined;) {\n const node = this.find(id);\n if (node?.values?.has(context.key)) {\n return node.values.get(context.key) as T;\n }\n id = node?.parent;\n }\n // The route of the page comes from its request and the params of its route.\n if (context.key === ROUTE_KEY) {\n const url = new URL(this.root.event?.request.url ?? 'http://localhost/');\n return { url, search: url.searchParams, params: this.root.params } as T;\n }\n return context.defaultValue;\n }\n\n /** The ID that the next call to `scope()` returns. */\n peek(): ScopeId {\n return spaceId(this.space, this.space.scope);\n }\n\n /** Marks the render so far, such as before a `#try` body, for `restore`. */\n mark(): Mark {\n const { prefix, scope, boundary } = this.space;\n return {\n prefix,\n scope,\n boundary,\n depth: this.spaces.length,\n undo: this.undo.length,\n owner: this.root.owner,\n };\n }\n\n /**\n * Takes back what the render added to the page since `mark`, such as a\n * `#try` body that threw, whose markup is not sent: its scopes, the\n * stylesheets it counted as sent, its `#portal` and `#head` markup, its\n * title, its `#loading` bodies, and its links to child components.\n */\n restore(mark: Mark): void {\n this.drop(mark);\n // A body that threw left the blocks inside it without `leave`.\n this.spaces.length = mark.depth;\n for (const undo of this.undo.splice(mark.undo).toReversed()) {\n undo();\n }\n this.root.owner = mark.owner;\n }\n\n /**\n * Forgets the scopes of this render from `from` on, such as those of a\n * `#try` body that threw, so the client does not resume markup that was\n * never sent. `#loading` bodies render in contexts of their own, so their\n * scopes stay.\n */\n private drop(mark: Mark): void {\n this.last = undefined;\n // The scopes are kept in place, since a spread of a long list would pass too many arguments.\n const { scopes } = this;\n let kept = 0;\n for (const entry of scopes) {\n if (!madeAfter(mark, entry.id)) {\n scopes[kept++] = entry;\n continue;\n }\n const { space } = entry;\n if (space?.entries[entry.n - space.first] === entry) {\n space.entries[entry.n - space.first] = undefined;\n }\n this.partials?.delete(entry.id);\n }\n scopes.length = kept;\n }\n\n /** The scope of this render with an ID, or the record that this render adds to another's. */\n private entry(scope: ScopeId): ScopeEntry {\n const last = this.last;\n if (last && last.id === scope) {\n return last;\n }\n let entry = this.find(scope);\n if (entry?.ctx !== this) {\n this.partials ??= new Map();\n entry = this.partials.get(scope);\n if (!entry) {\n const [prefix, n] = splitId(scope);\n entry = { id: scope, prefix, n, record: {}, ctx: this };\n this.partials.set(scope, entry);\n this.scopes.push(entry);\n }\n }\n this.last = entry;\n return entry;\n }\n\n private record(scope: ScopeId): ScopeState {\n return this.entry(scope).record;\n }\n\n /** The record of a scope in the state of this render, if it is there. */\n ownRecord(scope: ScopeId): ScopeState | undefined {\n const entry = this.find(scope);\n return entry?.ctx === this ? entry.record : this.partials?.get(scope)?.record;\n }\n\n /** The records of the scopes of this render, by ID, in the order the render made them. */\n get state(): StateMap {\n const state: StateMap = new Map();\n for (const entry of this.scopes) {\n state.set(entry.id, entry.record);\n }\n return state;\n }\n\n /**\n * The list of each list item scope whose list is a slot of an enclosing\n * scope, as `[scope, slot]`. The items of a list share one array.\n */\n get sources(): Map<ScopeId, ItemSource> {\n const sources = new Map<ScopeId, ItemSource>();\n for (const entry of this.scopes) {\n if (entry.source) {\n sources.set(entry.id, entry.source);\n }\n }\n return sources;\n }\n\n /** The scope that `unbind` collects the promise props of its component in. */\n sink(scope: ScopeId): PropSink {\n return this.entry(scope);\n }\n\n slots(scope: ScopeId, values: unknown[], names?: string[]): void {\n const entry = this.entry(scope);\n entry.record.s = values;\n if (names) {\n entry.names = names;\n }\n // Elements that components forwarded to a signal of this scope, which rendered before it.\n const forwarded = this.forwards?.get(scope);\n if (forwarded) {\n this.forwards!.delete(scope);\n for (const [slot, value] of forwarded) {\n values[slot] = value;\n }\n }\n // A promise that a parent passed as a prop stays a promise in the browser. The first slot\n // that holds it is the prop: a memo of the prop holds the same promise in a later slot.\n let wrapped: unknown[] | undefined;\n for (let slot = 0; slot < values.length; slot++) {\n const value = values[slot];\n if (\n value instanceof Promise &&\n entry.props?.includes(value) &&\n values.indexOf(value) === slot\n ) {\n wrapped ??= [...values];\n // In production the state carries a safe error, as for a memo. The read of the promise\n // logs the real one.\n wrapped[slot] = new PropPromise(\n this.isDev()\n ? value\n : value.catch((error: unknown) => {\n const safe = new Error(\n error instanceof ServerError\n ? error.message\n : 'The page could not compute a value',\n );\n safe.stack = '';\n throw safe;\n }),\n );\n }\n }\n entry.props = undefined;\n if (wrapped) {\n entry.record.s = wrapped;\n }\n }\n\n /** Elements that bound props of components forwarded to the slots of scopes that have no slots yet. */\n private forwards?: Map<ScopeId, Map<number, ElementReference>>;\n\n /**\n * Writes the element that a component forwards to a slot of a scope above it, and on through\n * the props that scope binds in turn. The parent records its slots after its children render,\n * so a write for a scope that has none waits for them.\n */\n private forward(target: SlotReference, value: ElementReference): void {\n const record = this.ownRecord(target.scope);\n if (!record?.s) {\n const waiting = ((this.forwards ??= new Map()).get(target.scope) ?? new Map()) as Map<\n number,\n ElementReference\n >;\n waiting.set(target.slot, value);\n this.forwards.set(target.scope, waiting);\n return;\n }\n record.s[target.slot] = value;\n const next = (record.b as Record<number, unknown> | undefined)?.[target.slot];\n if (isSlotReference(next)) {\n this.forward(next, value);\n }\n }\n\n /**\n * Records the props that a parent bound with `$bind`, among the props that\n * the component writes: `slots` has the slot of each, by its name. Its\n * writes in the browser go to the parent's slots.\n */\n bindings(scope: ScopeId, props: Record<string, unknown>, slots: Record<string, number>): void {\n this.bound(scope, props, slots);\n for (const [name, slot] of Object.entries(slots)) {\n const value = props[name];\n const record = this.entry(scope).record;\n // An element that the component wrote into its prop goes to the signal that it is bound to.\n const written = record.s?.[slot];\n if (\n isBinding(value) &&\n written instanceof ElementReference &&\n isSlotReference(value.target)\n ) {\n this.forward(value.target, written);\n }\n }\n }\n\n /**\n * Records where the bound props write, before the component renders its markup, so an element\n * that it forwards can name the signal at the end of the bindings. See `refKey`.\n */\n bound(scope: ScopeId, props: Record<string, unknown>, slots: Record<string, number>): void {\n for (const [name, slot] of Object.entries(slots)) {\n const value = props[name];\n if (isBinding(value)) {\n (this.entry(scope).record.b ??= {})[slot] = value.target;\n }\n }\n }\n\n /**\n * Records the item of a list that can change on the client. `source` is\n * the scope and slot that hold the list, when the compiler found one, so\n * the client can take the item from there.\n */\n item(scope: ScopeId, value: unknown, source?: ItemSource): void {\n const entry = this.entry(scope);\n entry.record.i = value;\n if (source) {\n entry.source = source;\n }\n }\n\n /** Records the scope where the template with the scope `template` was called. */\n call(template: ScopeId, at: ScopeId): void {\n this.record(template).l = at;\n }\n\n /** Records the scope of a child component at an anchor of its parent. */\n link(scope: ScopeId, anchor: number, child: ScopeId): void {\n const record = this.record(scope);\n const links = (record.c ??= {});\n links[anchor] = child;\n this.undo.push(() => {\n if (links[anchor] === child) {\n delete links[anchor];\n }\n });\n }\n\n /**\n * A `ref` that the rest props of a component hold is a binding of a signal above. The element\n * that spreads them goes to that signal, as when the component names `ref` itself.\n */\n restRef<T extends Record<string, unknown>>(\n attributes: T,\n scope: ScopeId,\n anchor: number,\n tag?: unknown,\n ): T {\n const value = attributes.ref;\n if (typeof tag !== 'function' && isBinding(value)) {\n if (isSlotReference(value.target)) {\n this.forward(value.target, new ElementReference(scope, anchor));\n } else {\n // A setter has no slot to write, so the client calls it on resume from this record.\n (this.record(scope).r ??= {})[anchor] = value.target;\n }\n }\n return attributes;\n }\n\n /**\n * The `b-near` attribute of a visible `$client` that reads the signal at `slot` of `scope`,\n * which a component may get with `ref=$bind(...)`. It records the key, so `refKey` marks only\n * the elements that a callback waits for.\n */\n near(scope: ScopeId, slot: number): string {\n const key = `${scope}.${slot}`;\n (this.root.waited ??= new Set()).add(key);\n return ` b-near=\"${key}\"`;\n }\n\n /**\n * The `b-r` attribute of an element that a component forwards for its caller: the scope and slot\n * of the signal at the end of the bindings, `S.slot`, when a visible `$client` waits for it.\n * The loader finds the element by it. Empty otherwise.\n */\n refKey(scope: ScopeId, slot: number): string {\n let target = this.ownRecord(scope)?.b?.[slot];\n let key = '';\n while (isSlotReference(target)) {\n key = `${target.scope}.${target.slot}`;\n // A render inside a `#loading` body is another context, which finds the scopes above it.\n target = this.find(target.scope)?.record.b?.[target.slot];\n }\n return this.root.waited?.has(key) ? ` b-r=\"${key}\"` : '';\n }\n\n /** Returns the reference that a `ref` signal holds on the server. */\n element(scope: ScopeId, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n }\n\n /**\n * Marks a function as a client function, so it serializes as a reference.\n * `args` are the arguments of a handler that `$handler` made, which go\n * with the reference. Each call makes a new reference, so a function that\n * `$handler` marks gets a copy for its arguments.\n */\n fn<T>(value: T, ref: string, scope: ScopeId, args?: unknown[]): T {\n if (typeof value !== 'function') {\n return value;\n }\n if (args === undefined && /#t\\d/.test(ref)) {\n // A `#template` renders where the component that gets it inserts it, so it reads the\n // contexts there, as children do.\n const render = value as unknown as (...rest: unknown[]) => Promise<unknown>;\n function template(...rest: unknown[]): Lazy {\n // The insert links the template's scope to where it is inserted.\n return new Children(scope, async (ctx, at) => insert(await render(...rest), ctx, at));\n }\n functionReferences.set(template, new FunctionReference(ref, scope));\n return template as T;\n }\n if (args === undefined) {\n functionReferences.set(value, new FunctionReference(ref, scope));\n return value;\n }\n const bound = Object.assign((...rest: unknown[]) => value(...args, ...rest), value) as T &\n object;\n functionReferences.set(bound, new FunctionReference(ref, scope, args));\n return bound;\n }\n\n /** Returns a component's stylesheet the first time the page renders the component. */\n style(id: string, css: string): string {\n const styles = this.root.styles;\n if (styles.has(id)) {\n return '';\n }\n styles.add(id);\n this.undo.push(() => styles.delete(id));\n return styleElement(id, css);\n }\n\n /** Adds the markup of a `#head` block. */\n head(html: string): void {\n // After the first render, the head has been sent, so a `#loading` body sends its own.\n const heads = (this.root.sent ? this : this.root).heads;\n heads.push(html);\n this.undo.push(() => removeLast(heads, html));\n }\n\n /**\n * Sets the title of the page. The last call wins. `markup` is true for a\n * `<title>` in `#head`, which is in the head already.\n */\n title(value: unknown, markup = false): void {\n const target = this.root.sent ? this : this.root;\n const previous = target.pageTitle;\n const titles = { ...target.titles };\n const title = value === null || value === undefined ? '' : String(value);\n target.pageTitle = title;\n target.titles = { count: titles.count + 1, markup: titles.markup && markup };\n this.undo.push(() => {\n if (target.pageTitle === title) {\n target.pageTitle = previous;\n target.titles = titles;\n }\n });\n }\n\n /** True once the first render is done, and its head is about to be sent. */\n private sent = false;\n\n /** Marks the first render as done. Head markup after it streams with its `#loading` body. */\n send(): void {\n this.root.sent = true;\n }\n\n /**\n * The head markup and the title that a `#loading` body set, after the\n * head was sent. The title is undefined if the body set none.\n */\n lateHead(): { html: string; title: string | undefined } {\n return { html: this.heads.join(''), title: this.pageTitle };\n }\n\n /** The markup for the document's head: the title and the `#head` blocks. */\n headHTML(): string {\n // One `<title>` in `#head` is the title of the head itself. With more, the head gets the\n // last one first, so a reader without scripts sees it.\n const { count, markup } = this.root.titles;\n const title =\n this.root.pageTitle === undefined || (count === 1 && markup)\n ? ''\n : `<title>${escape(this.root.pageTitle)}</title>`;\n return title + this.root.heads.join('');\n }\n\n /** Adds the markup of a `#portal` block, which goes after the rest of the page. */\n portal(html: string): void {\n this.portals.push(html);\n this.undo.push(() => removeLast(this.portals, html));\n }\n\n /** Adds the head markup and the title of a body that renders in place, to the head of the page. */\n adoptHead(late: { html: string; title: string | undefined }): void {\n if (late.html) {\n this.root.heads.push(late.html);\n }\n if (late.title !== undefined) {\n this.root.pageTitle = late.title;\n }\n }\n\n /** True when the bodies of `#defer` blocks render in place, for a page that renders in order. */\n inOrder = false;\n\n /** The `#reveal` blocks that are open in this context, the innermost last. */\n private readonly reveals: RevealGroup[] = [];\n\n /** Starts a `#reveal` block: the `#loading` bodies until `revealEnd` show in its order. */\n revealStart(order: RevealOrder, collapsed: boolean): void {\n const group = new RevealGroup(order, collapsed);\n this.reveals.push(group);\n // A `#try` body that fails ends the block, so the bodies that it held are sent.\n this.undo.push(() => group.close());\n }\n\n /** Ends the `#reveal` block that `revealStart` started. */\n revealEnd(): void {\n this.reveals.pop()?.close();\n }\n\n /** The group of the `#reveal` block around the next body, when the stream orders it. */\n private get reveal(): RevealGroup | undefined {\n return this.root.target ? undefined : this.reveals.at(-1);\n }\n\n /** True when a `#loading` body that is ready can render in place, as its `#reveal` allows. */\n mayShow(): boolean {\n return this.reveal?.mayShow() ?? true;\n }\n\n /** Starts the fallback of a `#loading` body, which `collapsed` hides in a template. */\n fallbackStart(id: ScopeId): string {\n const group = this.reveal;\n if (!group?.hides()) {\n return '';\n }\n group.hidden.add(id);\n return `<template b-f=\"${id}\">`;\n }\n\n /** Ends the fallback that `fallbackStart` started. */\n fallbackEnd(id: ScopeId): string {\n return this.reveal?.hidden.has(id) ? '</template>' : '';\n }\n\n /**\n * Starts a `#try` body. A `#loading` body inside it that fails renders the `#catch` body with\n * `draw`, after the page is sent. The returned function ends the `#try` body.\n */\n catcher(key: string, draw: Catcher['render']): () => void {\n const entry = { key, render: draw };\n this.catchers.push(entry);\n return () => removeLast(this.catchers, entry);\n }\n\n /** Returns the ID of a new `#loading` boundary. */\n boundary(): ScopeId {\n return spaceId(this.space, this.space.boundary++);\n }\n\n /** Renders a `#loading` body after the rest of the page, in its own context and ID space. */\n defer(id: ScopeId, renderBody: (ctx: Context) => Promise<string>): void {\n const target = this.root.target;\n if (!target || this.inTarget) {\n // A block in the markup of a `#reveal`, or in a component that it renders, joins its group.\n this.register(id, renderBody, this.inTarget);\n } else if (holdsBoundary(id, target.boundary)) {\n // The request for a `#defer` body renders the bodies around it, without sending them.\n this.register(id, renderBody, false, true);\n }\n }\n\n /**\n * Renders the body of a `#defer` block, in the request for it. `at` is\n * the scope and the anchor of the block. A page renders only the\n * fallback, so it does nothing then.\n */\n deferBlock(id: ScopeId, at: string, renderBody: (ctx: Context) => Promise<string>): void {\n const target = this.root.target;\n // A reader that runs no scripts never fires the trigger, so the body renders with the page.\n if (!target && this.root.inOrder) {\n this.register(id, renderBody, false);\n return;\n }\n if (!target || this.inTarget) {\n return;\n }\n if (holdsBoundary(id, target.boundary)) {\n this.register(id, renderBody, false, true);\n return;\n }\n if (id !== target.boundary) {\n return;\n }\n if (at !== target.at) {\n target.status = 'moved';\n return;\n }\n target.status = 'found';\n this.register(id, renderBody, true);\n }\n\n private register(\n id: ScopeId,\n renderBody: (ctx: Context) => Promise<string>,\n inTarget: boolean,\n around = false,\n ): void {\n const child = new Context(this.root, undefined, 0, `${id}.`);\n child.inTarget = inTarget;\n const catchers = [...this.outer, ...this.catchers];\n child.outer = catchers;\n const group = this.reveal;\n group?.add(id);\n const end = around ? undefined : this.traced('body', `#loading ${id}`);\n const boundary: Boundary = {\n id,\n render: renderBody(child).then(\n (html) => {\n end?.();\n return { html, ctx: child };\n },\n (error: unknown) => {\n end?.(true);\n throw error;\n },\n ),\n around,\n group,\n catchers,\n };\n // The page does not wait for it, so a failure must not be unhandled.\n boundary.render.catch(() => {});\n const root = this.root;\n if (root.onBoundary) {\n root.onBoundary(boundary);\n } else {\n root.boundaries.push(boundary);\n }\n this.undo.push(() => {\n boundary.cancelled = true;\n removeLast(root.boundaries, boundary);\n });\n }\n\n /** Receives every boundary, including those registered before this call. */\n watch(onBoundary: (boundary: Boundary) => void): void {\n this.onBoundary = onBoundary;\n for (const boundary of this.boundaries.splice(0)) {\n onBoundary(boundary);\n }\n }\n}\n\n/** Removes the last copy of a value from a list. */\nfunction removeLast<T>(list: T[], value: T): void {\n const index = list.lastIndexOf(value);\n if (index !== -1) {\n list.splice(index, 1);\n }\n}\n\n/** Thrown when code reads a memo whose value is still loading. It carries the load. */\nexport class NotReady extends Error {\n readonly source: Promise<unknown>;\n\n constructor(source: Promise<unknown>) {\n super('The value is still loading');\n this.name = 'NotReady';\n this.source = source;\n }\n}\n\n/** A memo on the server. It computes on its first read, so nothing waits for a memo that nothing reads. */\nexport interface Memo<T = unknown> {\n compute: () => T;\n /** The render, whose event server functions that the compute calls read. */\n ctx?: Context;\n state: 'idle' | 'pending' | 'done' | 'failed';\n value?: unknown;\n error?: unknown;\n load?: Promise<unknown>;\n /** The name of the memo, for the trace of the devtools. */\n name?: string;\n}\n\n/** Declares a memo. Its value is computed when it is first read. */\nexport function memo<T>(compute: () => T, ctx?: Context, name?: string): Memo<T> {\n return { compute, ctx, state: 'idle', name };\n}\n\n/**\n * Reads a memo. A value that is still loading throws `NotReady` with its\n * load, and a memo that read such a value stays unread, so it computes\n * again when it is read after the load settles.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Memos hold any value.\nexport function read(node: Memo): any {\n if (node.state === 'done') {\n return node.value;\n }\n if (node.state === 'failed') {\n throw node.error;\n }\n if (node.state === 'pending') {\n throw new NotReady(node.load!);\n }\n let value: unknown;\n try {\n // Server functions that it calls read the event of the page before their first await.\n value = node.ctx ? node.ctx.run(node.compute) : node.compute();\n } catch (error) {\n if (!(error instanceof NotReady)) {\n node.state = 'failed';\n node.error = error;\n }\n throw error;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n (typeof (value as PromiseLike<unknown>).then === 'function' || isAsyncIterable(value))\n ) {\n node.state = 'pending';\n // A memo that loads is a step of the render, in the trace of the devtools.\n const end = node.ctx?.traced('memo', node.name ?? 'memo');\n node.load = Promise.resolve(value)\n .then(firstValue)\n .finally(() => end?.())\n .then(\n (result) => {\n node.state = 'done';\n node.value = result;\n },\n (error: unknown) => {\n node.state = 'failed';\n node.error = error;\n },\n );\n throw new NotReady(node.load);\n }\n node.state = 'done';\n node.value = value;\n return value;\n}\n\n/**\n * The first value of an async iterable, such as a server function that\n * streams. A page renders once, so the server stops reading after it. Other\n * values are themselves.\n */\nasync function firstValue(value: unknown): Promise<unknown> {\n if (!isAsyncIterable(value)) {\n return value;\n }\n const iterator = value[Symbol.asyncIterator]();\n const first = await iterator.next();\n await iterator.return?.();\n return first.value;\n}\n\n/** Waits for the value of a memo, through every load it reads. */\nexport async function wait(node: Memo): Promise<unknown> {\n for (;;) {\n try {\n return read(node);\n } catch (error) {\n if (!(error instanceof NotReady)) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- Each load can reveal another one.\n await error.source.catch(() => {});\n }\n }\n}\n\n/**\n * The value of a memo when it is ready, or a promise of it while it loads.\n * The render then awaits only a memo that is loading.\n */\nexport function ready(node: Memo): unknown {\n try {\n return read(node);\n } catch (error) {\n if (error instanceof NotReady) {\n return wait(node);\n }\n throw error;\n }\n}\n\n/**\n * The value of a memo for the page state: its value when it is ready, or\n * a promise of it while it loads. A memo that fails gives a `MemoError`\n * either way, so the page renders, the stream goes on, and a read in the\n * browser throws the error as a memo that failed there.\n */\nexport function stateValue(node: Memo): unknown {\n try {\n return read(node);\n } catch (error) {\n if (error instanceof NotReady) {\n return wait(node).catch((failure: unknown) => heldError(failure, node.ctx));\n }\n return heldError(error, node.ctx);\n }\n}\n\n/**\n * The error of a memo for the page state. In development it is the error as seroval\n * writes it: its name, message, own properties, `cause` and the `errors` of an `AggregateError`,\n * and no stack (the serial options leave stacks out). In production it is the message of\n * a `ServerError`, which the app chose to show, or else a generic message, and the error is\n * logged, as for a server function that fails.\n */\nfunction heldError(error: unknown, ctx?: Context): MemoError {\n let sent: Error;\n if (ctx?.isDev()) {\n sent = error instanceof Error ? error : new Error(String(error));\n } else {\n sent = safeError(error, 'The page could not compute a value', ctx);\n }\n // The mark is what the serial plugin tests, as `brumate.slot` is for slot references.\n return Object.assign(new MemoError(sent), { [Symbol.for('brumate.held')]: true });\n}\n\n/**\n * Starts the load of an awaited memo before the statements that it does not\n * read, where the compiler moves its declaration. It keeps a synchronous\n * throw of the compute and a rejection in the memo, so the `await` where the\n * source has it throws them, not the start.\n */\nexport function start(node: Memo): void {\n try {\n const value = ready(node);\n if (value instanceof Promise) {\n value.catch(() => {});\n }\n } catch {}\n}\n\n/**\n * Starts every memo of a run of declarations that the render waits for,\n * so they load at the same time. Returns a promise that settles when all\n * of them have, or undefined when none is loading. A memo that fails\n * throws here, or rejects the promise.\n */\nexport function waitAll(nodes: Memo[]): Promise<unknown> | undefined {\n const loads: Promise<unknown>[] = [];\n for (const node of nodes) {\n const value = ready(node);\n if (value instanceof Promise) {\n loads.push(value);\n }\n }\n return loads.length === 0 ? undefined : Promise.all(loads);\n}\n\n/**\n * True when every memo has its value, so a `#loading` body that reads them\n * can render in place. A memo that is not computed yet computes here, so\n * the loads of the memos that are not ready start now, and the body that\n * streams later finds them loading. A memo that failed counts as not ready:\n * the body streams, and throws where it reads the memo.\n */\nexport function settled(nodes: Memo[]): boolean {\n let result = true;\n for (const node of nodes) {\n try {\n read(node);\n } catch {\n result = false;\n }\n }\n return result;\n}\n\nconst LAZY: unique symbol = Symbol.for('brumate.lazy');\n\n/** Markup that renders where it is inserted, so it can read the contexts there. */\nexport interface Lazy {\n [LAZY]: (\n ctx: Context,\n scope: ScopeId | undefined,\n tag?: string,\n anchor?: number,\n ) => Promise<string>;\n}\n\n/**\n * The children of a component, which render where the component inserts\n * them, so they read the contexts that the component provides. `from` is the\n * scope of the markup that wrote them.\n */\nexport function children(\n from: ScopeId,\n renderBody: (ctx: Context) => Promise<string>,\n ref?: string,\n): Lazy {\n return new Children(from, renderBody, ref);\n}\n\n/** The symbol of raw HTML. See `html.ts`. */\nconst RAW: unique symbol = Symbol.for('brumate.raw') as never;\n\n/**\n * Children of a component. The first render keeps its HTML as raw HTML, so\n * the page state sends it for the browser to insert, such as when a block\n * that holds the children opens. A class, since the serializer tests only\n * class instances.\n */\nclass Children implements Lazy {\n readonly [LAZY]: Lazy[typeof LAZY];\n /** The HTML of the first render, under the symbol of raw HTML. */\n [RAW]?: string;\n /**\n * The export that renders the children in the browser, which the page state sends in place of\n * their HTML. Each insert in the browser then renders them with new scopes.\n */\n [CHILDREN_REF]?: ChildrenReference;\n\n constructor(\n from: ScopeId,\n renderBody: (ctx: Context, at?: ScopeId) => Promise<string>,\n ref?: string,\n ) {\n if (ref !== undefined) {\n this[CHILDREN_REF] = new ChildrenReference(ref, from);\n }\n this[LAZY] = async (ctx, at, tag, anchor) => {\n // The browser keeps what the server rendered at this insert, when it reads the page later.\n const reference = this[CHILDREN_REF];\n if (reference && reference.at === undefined && anchor !== undefined) {\n reference.at = at;\n reference.anchor = anchor;\n }\n const html = await (at === undefined\n ? renderBody(ctx)\n : ctx.children(from, at, () => renderBody(ctx, at), tag));\n if (ref === undefined) {\n this[RAW] ??= html;\n }\n return html;\n };\n }\n}\n\n/**\n * The tag of the spacers of a windowed list in children: a row in a table body, an item in a\n * list, as the element where the children are inserted says, or else a `div`.\n */\nexport function spacerTag(ctx: Context): string {\n return ctx.spacerTag();\n}\n\n/** Makes markup that renders where it is inserted, such as the children of a layout. */\nexport function lazy(\n renderAt: (ctx: Context, scope: ScopeId | undefined) => Promise<string>,\n): Lazy {\n return { [LAZY]: renderAt };\n}\n\nfunction isLazy(value: unknown): value is Lazy {\n return typeof value === 'object' && value !== null && LAZY in value;\n}\n\n/** Renders the attributes of a form or button that posts to a server function. */\nexport function action(\n ctx: Context,\n name: string,\n id: string,\n method?: string,\n result?: string,\n): string {\n // The key goes to one visitor, so the page is not cached for everyone.\n let key: string | undefined;\n if (idempotentIds.has(id)) {\n key = crypto.randomUUID();\n ctx.personal();\n }\n return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId(), key);\n}\n\n/**\n * The result of a server function that a form posted to this page, for\n * `$action`, or undefined when the page was not rendered for a post.\n */\nexport function actionResult(ctx: Context, fn: unknown): unknown {\n return ctx.actionResult(fn);\n}\n\n/**\n * Renders a value inserted in markup. `ctx`, `scope` and `anchor` are where it\n * is inserted, for markup that renders there.\n */\nexport function insert(\n value: unknown,\n ctx?: Context,\n scope?: ScopeId,\n tag?: string,\n anchor?: number,\n): string | Promise<string> {\n // A value that is ready renders without a promise, because most inserts are plain text.\n if (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as PromiseLike<unknown>).then === 'function'\n ) {\n return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope, tag, anchor));\n }\n if (isLazy(value) && ctx) {\n return value[LAZY](ctx, scope, tag, anchor);\n }\n // The output of a template links its scope to where it is inserted, so a `#try` there catches\n // its errors.\n if (isRaw(value) && value.s !== undefined && ctx && scope !== undefined) {\n ctx.call(value.s, scope);\n }\n if (Array.isArray(value)) {\n const parts: (string | Promise<string>)[] = [];\n let allStrings = true;\n for (const item of value) {\n const part = insert(item, ctx, scope, tag);\n if (typeof part !== 'string') {\n allStrings = false;\n }\n parts.push(part);\n }\n return allStrings ? parts.join('') : Promise.all(parts).then((all) => all.join(''));\n }\n return insertValue(value);\n}\n\n// A compiled component answers a string. Its type is `Markup` of brumate/elements, an object type\n// that a string stands in for. The bundle cannot import that type without a copy of its own.\n// oxlint-disable-next-line typescript/no-explicit-any -- Components take any props.\nexport type Component<P = any> = (props: P, ctx: Context) => Promise<string | object>;\n\n/** True for a promise, or any object with a `then` function, which markup waits for. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as PromiseLike<unknown>).then === 'function'\n );\n}\n\n/**\n * Renders an attribute of an element. A promise renders once it settles, so the element is sent\n * with its final attributes: the render waits for it, as for a promise in text.\n */\nexport function attribute(name: string, value: unknown): string | Promise<string> {\n return isThenable(value)\n ? Promise.resolve(value).then((resolved) => attributeText(name, resolved))\n : attributeText(name, value);\n}\n\n/**\n * Renders a child component. With `scope` and `anchor`, records the child's\n * scope so the parent can update its props on the client.\n */\nexport function component<P>(\n Child: Component<P>,\n props: P,\n ctx: Context,\n scope?: ScopeId,\n anchor?: number,\n paragraph?: string,\n): Promise<string> {\n // A request for a `#defer` body sends only that body, so the rest of the page renders no more\n // components once the body has started, and loads no more of their data.\n if (ctx.past()) {\n return Promise.resolve('');\n }\n if (scope !== undefined && anchor !== undefined) {\n ctx.link(scope, anchor, ctx.peek());\n }\n if (scope !== undefined) {\n ctx.own(scope);\n }\n const given = (props as { children?: unknown } | undefined)?.children;\n // Children that the browser renders itself need no HTML from the server.\n if (!(given instanceof Children) || given[CHILDREN_REF]) {\n return checkParagraph(Child(props, ctx) as Promise<string>, ctx, paragraph);\n }\n // Children that the component did not insert render after it, inside its root scope, so the\n // page state has their HTML for the browser.\n const root = ctx.peek();\n return checkParagraph(\n (Child(props, ctx) as Promise<string>).then(async (html) => {\n if (given[RAW] === undefined) {\n await given[LAZY](ctx, root);\n }\n return html;\n }),\n ctx,\n paragraph,\n );\n}\n\n/**\n * In development, throws when a component inside a `<p>` starts with an element that closes the\n * `<p>`. `paragraph` names the component and where it is, and only the compiler sets it. The\n * browser splits the markers of the blocks of the page there, so it is an error before that.\n */\nfunction checkParagraph(\n rendered: Promise<string>,\n ctx: Context,\n paragraph: string | undefined,\n): Promise<string> {\n if (paragraph === undefined || !ctx.isDev()) {\n return rendered;\n }\n return rendered.then((html) => {\n const tag = typeof html === 'string' ? firstTag(html) : undefined;\n if (tag !== undefined && closesParagraph(tag)) {\n throw new Error(\n `${paragraph} renders <${tag}>, which the HTML parser does not keep inside a <p>: it closes the <p> and splits the markers of the page [BRM185]. Move the component out of the <p>, or make it render a <span>, as with as=\"span\"`,\n );\n }\n return html;\n });\n}\n\n/** Renders a dynamic tag, which can be an element name or a component. */\nexport function dynamic(\n tag: string | Component,\n attributes: Record<string, unknown>,\n content: Raw | Lazy | undefined,\n ctx: Context,\n scope?: ScopeId,\n ref?: unknown,\n): string | Promise<string> {\n if (typeof tag === 'function') {\n // The binding of `ref`, which the component forwards to its element.\n if (ref !== undefined) {\n attributes = { ...attributes, ref };\n }\n // The anchor links the component to the tag, so updates reach its props. It is no prop.\n const { 'b-b': bound, 'b-on': entries, ...passed } = attributes;\n // The handlers of the tag reach the component as `onClick` props that refer to the client\n // functions, as those of a component written by name do. A `b-on` that a live rest held\n // would not go to the browser. A handler of the same event that a rest prop passed on is\n // merged with them.\n addEntryHandlers(passed, entries, scope, (reference) => {\n const handler = Object.assign(\n () => {},\n reference.modifiers ? { [MODIFIERS]: reference.modifiers } : {},\n );\n functionReferences.set(handler, reference);\n return handler;\n });\n return component(\n tag,\n content ? { ...passed, children: content } : passed,\n ctx,\n scope,\n bound === undefined ? undefined : Number((ownValue('b-b', bound) as string).split(':')[1]),\n );\n }\n // The handlers of a dynamic element, and those that its props pass on, go into one `b-on`.\n const on: string[] = [];\n const written = spread(attributes, on);\n // A promise among the attributes renders once it settles.\n if (typeof written !== 'string') {\n return written.then((text) => dynamicElement(tag, text, on, content, ctx, scope));\n }\n return dynamicElement(tag, written, on, content, ctx, scope);\n}\n\n/** Renders a dynamic tag that names an element, with its attributes written. */\nfunction dynamicElement(\n tag: string,\n attributes: string,\n on: string[],\n content: Raw | Lazy | undefined,\n ctx: Context,\n scope?: ScopeId,\n): string | Promise<string> {\n const open = `<${tag}${attributes}${onAttribute(on, '')}>`;\n if (VOID_ELEMENTS.has(tag)) {\n return open;\n }\n if (isLazy(content)) {\n return Promise.resolve(content[LAZY](ctx, scope)).then((html) => `${open}${html}</${tag}>`);\n }\n return `${open}${content && isRaw(content) ? rawHTML(content) : ''}</${tag}>`;\n}\n\n/** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */\nfunction holds(value: unknown, target: unknown, seen = new Set<unknown>()): boolean {\n if (value === target) {\n return true;\n }\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n return false;\n }\n seen.add(value);\n let items: unknown[] = [];\n if (value instanceof Map) {\n items = [...value.keys(), ...value.values()];\n } else if (value instanceof Set) {\n items = [...value];\n } else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) {\n items = Object.values(value);\n }\n for (const item of items) {\n if (holds(item, target, seen)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The error of a value in the state of a page that cannot be sent to the\n * browser, which names the value and its component.\n */\nfunction unsendable(error: unknown, ctx: Context): Error {\n const secret = secretErrors.get(error as Error);\n const target = secret ?? (error as { value?: unknown }).value;\n if (target === undefined) {\n return error instanceof Error ? error : new Error(String(error));\n }\n for (const { record, names } of ctx.scopes) {\n let index = -1;\n for (const [slot, value] of (record.s ?? []).entries()) {\n if (holds(value, target)) {\n index = slot;\n break;\n }\n }\n if (index === -1) {\n continue;\n }\n let owner: ScopeState | undefined = record;\n while (owner && owner.m === undefined && owner.p !== undefined) {\n owner = ctx.ownRecord(owner.p);\n }\n const name = names?.[index] ?? `slot ${index}`;\n if (secret !== undefined) {\n return new Error(\n `The value of \"${name}\" in ${owner?.m ?? 'a component'} is the value of a server environment variable, and code that runs in the browser reads it. Read the variable in a server function, and send the browser only what it needs.`,\n );\n }\n const kind = (target as object)?.constructor?.name ?? typeof target;\n return new Error(\n `The value of \"${name}\" in ${owner?.m ?? 'a component'} holds a ${kind}, which cannot be sent to the browser, and code that runs in the browser reads it. Use it in a server function, or create it in the browser, such as in $client.`,\n { cause: error },\n );\n }\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/** The secret that each error of `secretError` found. The error does not hold it, so a log does not show it. */\nconst secretErrors = new WeakMap<Error, string>();\n\n/** The code of each secret as seroval writes a string: in double quotes, escaped. */\nconst secretCode = new Map<string, string>();\n\n/**\n * An error for a record of the page state that holds the value of a server\n * environment variable as a string, or undefined. A record holds a string\n * as its code in quotes, so this is one search of the code per secret.\n */\nfunction secretError(code: string): Error | undefined {\n for (const secret of serverSecrets()) {\n let literal = secretCode.get(secret);\n if (literal === undefined) {\n literal = crossSerialize(secret);\n secretCode.set(secret, literal);\n }\n if (code.includes(literal)) {\n const error = new Error(\n 'The page state holds the value of a server environment variable, which is not sent to the browser',\n );\n secretErrors.set(error, secret);\n return error;\n }\n }\n return undefined;\n}\n\n/** JSON that is safe in a `<script>`, with each `<` escaped. */\nfunction scriptJSON(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** The fields that a record in a group of `PackedState` can have. */\nconst PACKED_FIELDS = new Set(['k', 'p', 'o', 'm', 's', 'i', 'c']);\n\n/** True when a record has a field that `PackedState` has no place for. */\nfunction hasUnpackedField(record: ScopeState): boolean {\n for (const field of Object.keys(record)) {\n if (!PACKED_FIELDS.has(field)) {\n return true;\n }\n }\n return false;\n}\n\n/** A group of `PackedState` while `packState` collects it. */\n/** How many of the last groups `packState` compares a record with, before it looks up its name. */\nconst RECENT_GROUPS = 4;\n\ninterface PackGroup {\n k: number;\n base: ScopeId;\n flags: number;\n count: number;\n m: string | undefined;\n /** The prefix of the IDs inside a `#loading` body, or `''`. */\n prefix: string;\n /** The scopes of the group, with their numbers after the prefix. */\n entries: ScopeEntry[];\n}\n\n/** The prefix of an ID and its number after it, such as `['', 3]` or `['5.', 1]`. */\nfunction splitId(id: ScopeId): [prefix: string, n: number] {\n if (typeof id === 'number') {\n return ['', id];\n }\n const dot = id.lastIndexOf('.');\n return [id.slice(0, dot + 1), Number(id.slice(dot + 1))];\n}\n\n/** The records of the scopes of a render, by scope ID. */\nexport type StateMap = Map<ScopeId, ScopeState>;\n\n/** The records of a state as a map, for a state written as an object, such as in tests. */\nfunction toStateMap(state: PageState | StateMap): StateMap {\n if (state instanceof Map) {\n return state;\n }\n const map: StateMap = new Map();\n for (const [key, record] of Object.entries(state)) {\n map.set(parseId(key), record);\n }\n return map;\n}\n\n/**\n * Visits the scopes of a state in the order of the keys of an object: number\n * IDs ascending, then string IDs in the order they were made. A render makes\n * its number IDs in order, so the scopes are only copied to sort them when\n * they are not.\n */\nfunction visitOrdered(entries: readonly ScopeEntry[], visit: (entry: ScopeEntry) => void): void {\n let numbers: readonly ScopeEntry[] = entries;\n let last = -Infinity;\n for (const entry of entries) {\n if (typeof entry.id === 'number') {\n if (entry.id < last) {\n const numeric: ScopeEntry[] = [];\n for (const item of entries) {\n if (typeof item.id === 'number') {\n numeric.push(item);\n }\n }\n numbers = numeric.toSorted((a, b) => (a.id as number) - (b.id as number));\n break;\n }\n last = entry.id;\n }\n }\n for (const entry of numbers) {\n if (typeof entry.id === 'number') {\n visit(entry);\n }\n }\n for (const entry of entries) {\n if (typeof entry.id !== 'number') {\n visit(entry);\n }\n }\n}\n\n/**\n * The list that the client can take the items of a group from: the items\n * are list items with the same source, the source's record is in `state`,\n * and the item of the scope at each position of the group is the value at\n * that position of the list. The client reads the same list, so it gets the\n * same values. Otherwise the items are written.\n */\nfunction groupSource(\n record: (id: ScopeId) => ScopeState | undefined,\n group: PackGroup,\n): ItemSource | undefined {\n const { entries } = group;\n const source = entries[0]!.source;\n if (!source || !(group.flags & (ITEM | ITEM_SLOT))) {\n return undefined;\n }\n const value = record(source[0])?.s?.[source[1]];\n // Seroval keeps the order of a Set. A Map's entries are new arrays, which the check below rejects.\n const list = value instanceof Set ? Array.from(value) : value;\n if (!Array.isArray(list) || list.length < entries.length) {\n return undefined;\n }\n for (let n = 0; n < entries.length; n++) {\n const entry = entries[n]!;\n if (entry.source !== source || !Object.is(list[n], entry.record.i)) {\n return undefined;\n }\n }\n return source;\n}\n\n/**\n * Writes the records of scopes with the same kind, parent and shape, such as\n * the items of a list, in groups. Each one then costs its slots and the gap\n * to the ID before it. The items of a list whose list is in `sources` and in\n * the state are not written. See `PackedState`.\n */\nexport function packState(\n input: PageState | StateMap,\n sources?: Map<ScopeId, ItemSource>,\n): PackedState {\n const state = toStateMap(input);\n const entries: ScopeEntry[] = [];\n for (const [id, record] of state) {\n const [prefix, n] = splitId(id);\n entries.push({ id, prefix, n, record, ctx: undefined, source: sources?.get(id) });\n }\n return packEntries(entries, (id) => state.get(id));\n}\n\n/** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */\nfunction packEntries(\n scopes: readonly ScopeEntry[],\n lookup: (id: ScopeId) => ScopeState | undefined,\n): PackedState {\n const result: PackedState = {};\n const groups = new Map<string, PackGroup>();\n const recent: PackGroup[] = [];\n // Number IDs come in ascending order, and the IDs inside blocks in the order the render made\n // them, as an object orders its keys, so the gaps are positive and the output stays the same.\n visitOrdered(scopes, (entry) => {\n const { id, record, prefix, n } = entry;\n // The root scope of a component in a list item has its own owner, the item, at the same\n // distance before it in each item. The parent of other scopes is the same for the group.\n let base: ScopeId | undefined = record.p;\n if (base === undefined && record.o !== undefined) {\n const [ownerPrefix, owner] = splitId(record.o);\n base = ownerPrefix === prefix ? n - owner : undefined;\n }\n if (\n record.k === undefined ||\n base === undefined ||\n (record.p !== undefined && record.o !== undefined) ||\n hasUnpackedField(record)\n ) {\n result[id] = record;\n return;\n }\n const slots = record.s ?? [];\n let flags = record.p === undefined ? OWNER : 0;\n if ('i' in record) {\n flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? ITEM_SLOT : ITEM;\n }\n if (record.c) {\n flags |= CHILDREN;\n }\n if (record.m !== undefined) {\n flags |= MODULE;\n }\n // The scopes of a list come in runs, so the last groups usually hold the record's group,\n // and the name of the group, a new string to hash, is made only when they do not.\n let group: PackGroup | undefined;\n for (const item of recent) {\n if (\n item.k === record.k &&\n item.base === base &&\n item.flags === flags &&\n item.count === slots.length &&\n item.m === record.m &&\n item.prefix === prefix\n ) {\n group = item;\n break;\n }\n }\n if (!group) {\n const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ''}`;\n group = groups.get(name);\n if (!group) {\n group = {\n k: record.k,\n base,\n flags,\n count: slots.length,\n m: record.m,\n prefix,\n entries: [],\n };\n groups.set(name, group);\n }\n recent.unshift(group);\n if (recent.length > RECENT_GROUPS) {\n recent.pop();\n }\n }\n group.entries.push(entry);\n });\n const packed: unknown[][] = [];\n for (const group of groups.values()) {\n const { entries } = group;\n // A group of one scope is no shorter than its record.\n if (entries.length === 1) {\n result[entries[0]!.id] = entries[0]!.record;\n continue;\n }\n const source = groupSource(lookup, group);\n let flags = source ? group.flags | SOURCE : group.flags;\n if (group.prefix) {\n flags |= PREFIX;\n }\n const values: unknown[] = [group.k, group.base, flags, group.count];\n if (group.m !== undefined) {\n values.push(group.m);\n }\n if (source) {\n values.push(source[0], source[1]);\n }\n if (group.prefix) {\n values.push(group.prefix);\n }\n // With a source, the client takes the item, and the first slot when it is the item.\n const from = source && flags & ITEM_SLOT ? 1 : 0;\n const item = !source && flags & ITEM;\n // Inside a `#loading` body, and for component root scopes, the first gap is from 0.\n let last = flags & (OWNER | PREFIX) ? 0 : (group.base as number);\n for (const { n: number, record: scope } of entries) {\n values.push(number - last);\n const slots = scope.s ?? [];\n for (let n = from; n < slots.length; n++) {\n values.push(slots[n]);\n }\n if (item) {\n values.push(scope.i);\n }\n if (flags & CHILDREN) {\n values.push(scope.c);\n }\n last = number;\n }\n packed.push(values);\n }\n if (packed.length > 0) {\n result.g = packed;\n }\n return result;\n}\n\n/**\n * Serializes the page state as seroval cross-reference code, one record at\n * a time. The first record holds the state, and each later record settles a\n * promise in it. Records that share `refs` can refer to each other's values.\n *\n * With `last`, no later record of the render reads this one, so a state\n * without promises is one record that assigns only the references that it\n * uses twice. That record is smaller, and faster to write. A state with a\n * promise makes `crossSerialize` throw, and then it streams as usual.\n */\nfunction serializeState(\n state: PageState | StateMap | Context,\n refs: Map<unknown, number>,\n onRecord: (code: string, initial: boolean) => void,\n onError: (error: unknown) => void,\n onDone: () => void,\n sources?: Map<ScopeId, ItemSource>,\n last = false,\n): void {\n const packed =\n state instanceof Context\n ? packEntries(state.scopes, (id) => state.ownRecord(id))\n : packState(state, sources);\n // A record that holds the value of a server variable is not sent, nor any after it.\n let leaked = false;\n function send(code: string, initial: boolean): void {\n const error = leaked ? undefined : secretError(code);\n if (error) {\n leaked = true;\n onError(error);\n } else if (!leaked) {\n onRecord(code, initial);\n }\n }\n if (last) {\n let code: string | undefined;\n try {\n code = crossSerialize(packed, {\n plugins: syncPlugins,\n ...serialOptions(),\n refs,\n assignSharedRefsOnly: true,\n });\n } catch {\n // The stream gives the same error for a value that cannot be sent, with the same references.\n refs.clear();\n }\n if (code !== undefined) {\n send(code, true);\n onDone();\n return;\n }\n }\n crossSerializeStream(packed, {\n plugins,\n ...serialOptions(),\n refs,\n onSerialize: send,\n onError,\n onDone,\n });\n}\n\n/**\n * Serializes the page state as the code of state records. `onRecord`\n * receives each record as soon as it is ready. The promise resolves when\n * every promise in the state has settled.\n */\nexport function streamState(\n state: PageState | StateMap,\n onRecord: (code: string, initial: boolean) => void,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n serializeState(state, new Map(), onRecord, reject, resolve);\n });\n}\n\n/**\n * Defines `$bR`, which hands the code of a state record and its script to\n * the core, through `self.$brm`. The core runs the code when it starts, or\n * at once when it has started. The first record of each render defines it.\n */\nconst RECORD = 'function $bR(f){(self.$brm=self.$brm||[]).push([document.currentScript,f])}';\n\nexport interface StateAttributes {\n /** A number above every ID so far, on each record with scopes. */\n next?: number;\n /** The first record of a render defines `$bR`. Later ones call it. */\n define?: boolean;\n /** The route of the page. */\n route?: string;\n /** The base of the render, when it is above 0, or the key of a `#defer` body's records. */\n root?: number | string;\n /** The Content Security Policy nonce of the script. */\n nonce?: string;\n /** The params of the route of the page, on its first record, for `$route` in the browser. */\n params?: Record<string, string>;\n /** The ID of the build that rendered the page, on its first record, for skew protection. */\n build?: string;\n /** The URLs of the bundles that the components of the record need, which the browser imports. */\n load?: string[];\n /** The ID of a `#loading` boundary whose body failed. The record is the error. */\n fail?: ScopeId;\n /** The marker of a `#try` whose `#catch` body replaces its body, from the template `b-c`. */\n catches?: string;\n}\n\n/**\n * Returns the script of a state record. `scopes` marks a record with scopes,\n * as opposed to one that settles a promise. The record is code that seroval\n * wrote, as a function of the references of its render, `$R`, and of the\n * functions that make brumate's values, `$b`. seroval escapes every `<` in\n * the strings in it.\n */\nexport function stateScript(\n code: string,\n scopes = false,\n attributes: StateAttributes = {},\n): string {\n // seroval writes `<` in strings as `\\\\x3C`, so these never appear. A change there must not open the script.\n if (code.includes('</') || code.includes('<!')) {\n throw new Error('A state record would end its script');\n }\n let extra = attributes.nonce === undefined ? '' : ` nonce=\"${escapeAttribute(attributes.nonce)}\"`;\n extra += ' b-state';\n if (scopes) {\n extra += ' b-scopes';\n }\n if (attributes.next !== undefined) {\n extra += ` b-next=\"${attributes.next}\"`;\n }\n if (attributes.load !== undefined && attributes.load.length > 0) {\n extra += ` b-load=\"${escapeAttribute(attributes.load.join(' '))}\"`;\n }\n // Records of a render that starts above 0 name it, so their references stay apart from other renders.\n if (attributes.root) {\n extra += ` b-root=\"${attributes.root}\"`;\n }\n if (attributes.route !== undefined) {\n extra += ` b-route=\"${escapeAttribute(attributes.route)}\"`;\n }\n if (attributes.params !== undefined) {\n extra += ` b-params=\"${escapeAttribute(JSON.stringify(attributes.params))}\"`;\n }\n if (attributes.build !== undefined) {\n extra += ` b-build=\"${escapeAttribute(attributes.build)}\"`;\n }\n if (attributes.fail !== undefined) {\n extra += ` b-fail=\"${attributes.fail}\"`;\n }\n if (attributes.catches !== undefined) {\n extra += ` b-catch=\"${attributes.catches}\"`;\n }\n return `<script${extra}>${attributes.define ? RECORD : ''}$bR(($R,$b)=>(${code}))</script>`;\n}\n\n// Moves the head markup of a `#loading` body into the head, and sets the title.\n// A `<title>` of `#head` keeps its text: the head gets a title of its own for `document.title`.\nconst HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h=\"'+i+'\"]'),h=document.head;e&&(h.append(e.content),e.remove());t!=null&&(h.querySelector('title:not([b-t])')||h.prepend(document.createElement('title')),document.title=t)}`;\n\n// Shows a fallback that `#reveal (collapsed)` held in a <template>, when the body before it shows.\nconst SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f=\"'+i+'\"]');t&&t.replaceWith(t.content)}`;\n\n// Moves a `#loading` body from its <template> into the page, in place of the fallback.\nconst SWAP = `function $bS(i){var t=document.querySelector('template[b-l=\"'+i+'\"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;\n\n// In development, the swap keeps the fallback that it removes and the body that it adds, by\n// boundary, so the devtools can show the fallback again.\nconst SWAP_DEV = `function $bS(i){var t=document.querySelector('template[b-l=\"'+i+'\"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode,f=[];for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\\\d/.test(n.data))d++}var x=n.nextSibling;f.push(p.removeChild(n));n=x}(self.$bD||(self.$bD={}))[i]={f:f,b:[].slice.call(t.content.childNodes)};p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;\n\n/**\n * The record that tells the browser a `#loading` body failed. Its code is the error, and the\n * browser hands it to the nearest `#try` around the boundary.\n */\nfunction failScript(\n error: unknown,\n refs: Map<unknown, number>,\n boundary: ScopeId,\n root: number | string | undefined,\n nonce: string | undefined,\n): string {\n let code: string;\n try {\n code = crossSerialize(error, { plugins: syncPlugins, ...serialOptions(), refs });\n } catch {\n // An error that cannot be sent is shown by its message.\n code = crossSerialize(new Error(String(error)), {\n plugins: syncPlugins,\n ...serialOptions(),\n refs,\n });\n }\n return stateScript(code, false, { root, nonce, fail: boundary });\n}\n\nexport interface RenderResult {\n /** The markup. A `#loading` body that is not ready shows its fallback. */\n html: string;\n /** The script that holds the page state. */\n state: string;\n /**\n * Markup to write after the page, as it is ready: the bodies of\n * `#loading` blocks, and the state records that settle promises.\n */\n pending: AsyncIterable<string>;\n /** Headers that the page set while it rendered, such as cookies. */\n headers: Headers;\n /** The status that `setStatus` set while the page rendered, or 200. */\n status: number;\n /**\n * A number above every ID of this render, once its `#loading` bodies have\n * rendered. Another root on the same page passes it as `base`.\n */\n next: () => number;\n /** Markup for the document's head: the `$title` and the `#head` blocks. */\n head: string;\n /**\n * The event of the request. Its `signal` aborts when the reader of the\n * response goes away, which `streamParts` and `renderToStream` report.\n */\n event?: RequestEvent;\n /**\n * With the `defer` option, whether the render found the block: `found`,\n * `moved` when the boundary is at another place, such as after the data\n * of the page changed, or `missing`.\n */\n defer?: 'found' | 'moved' | 'missing';\n}\n\n/** The `pending` of a render that has nothing left to send. */\nconst NOTHING_PENDING: AsyncIterable<string> = {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.resolve({ done: true, value: undefined }),\n }),\n};\n\ninterface Queue<T> {\n push: (item: T) => void;\n close: () => void;\n fail: (error: unknown) => void;\n iterable: AsyncIterable<T>;\n}\n\n/** An async iterable that a producer pushes into. */\nfunction createQueue<T>(): Queue<T> {\n const items: T[] = [];\n let wake: (() => void) | undefined;\n let closed = false;\n let failure: { error: unknown } | undefined;\n function notify(): void {\n wake?.();\n wake = undefined;\n }\n return {\n push(item) {\n items.push(item);\n notify();\n },\n close() {\n closed = true;\n notify();\n },\n fail(error) {\n failure = { error };\n notify();\n },\n iterable: {\n async *[Symbol.asyncIterator]() {\n for (;;) {\n if (items.length > 0) {\n yield items.shift()!;\n } else if (failure) {\n throw failure.error;\n } else if (closed) {\n return;\n } else {\n // oxlint-disable-next-line no-await-in-loop -- Each wait is for the next item.\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n }\n },\n },\n };\n}\n\nexport interface RenderOptions {\n /** The `onError` of the app, which gets the errors of a render without a request event. */\n onError?: ServerErrorHandler;\n /** The URL prefix of server function calls, for forms that post to one. Defaults to `/_brumate`. */\n rpc?: string;\n /** In development: the swaps of `#loading` bodies keep their fallbacks, for the devtools. */\n dev?: boolean;\n /**\n * The first scope and boundary ID. A page that the client loads in place\n * of another starts above the IDs of the page it keeps parts of.\n */\n base?: number;\n /** Names the route of the page, so the client knows which layouts it can keep. */\n route?: string;\n /**\n * Renders `#loading` and `#defer` bodies in place, in the order of the\n * page, instead of streaming them in `<template>`s that a script swaps in.\n * The page arrives later, and complete, for readers that run no scripts,\n * such as crawlers. The state is the same either way. `'bots'`, the\n * default, does it for requests whose `User-Agent` is a known crawler. A\n * function decides for each request.\n */\n inOrder?: boolean | 'bots' | ((request: Request) => boolean);\n /** The params of the route of the page, for `$route`. `handleRoute` sets them. */\n params?: Record<string, string>;\n /** Results of server functions that a form posted to this page, by function, for `$action`. */\n actions?: Map<unknown, unknown>;\n /**\n * The request of the page. Components and the server functions that their\n * memos call read it with `getEvent()`. Headers and cookies that they set\n * are in the `headers` that `render` returns.\n */\n request?: Request;\n /** The event of the request, in place of `request`, such as one that middleware already set cookies on. */\n event?: RequestEvent;\n /**\n * Keeps work going after the response ends, for `event.waitUntil`, such\n * as the `waitUntil` of Cloudflare Workers. Without it, the promise runs\n * on its own and its error is logged.\n */\n waitUntil?: (promise: Promise<unknown>) => void;\n /**\n * A Content Security Policy nonce for the inline scripts: the state\n * records, and the scripts that swap in `#loading` bodies.\n */\n nonce?: string;\n /**\n * The ID of the build, for skew protection. The page state carries it,\n * and the browser sends it with each call. The Vite plugin sets it in\n * builds. See `handleRequest`.\n */\n build?: string;\n /**\n * The address of the client as the server saw it, such as the remote\n * address of the socket, for `clientAddress` and rate limits.\n */\n address?: string;\n /** True while the build prerenders the page. Rate limits do not count then. */\n prerender?: boolean;\n /**\n * Renders only the body of this `#defer` block, for the request that the\n * browser sends when the block's trigger fires. Pass the `base` of the\n * page too, so the IDs of the page come out the same. The body comes from\n * `pending`, and `html` and `state` are empty.\n */\n defer?: { boundary: ScopeId; at: string };\n /**\n * The bundles of the client build. Each state record with scopes names, in `b-load`, the\n * URLs of the bundles that hold the code of its components, so the browser loads only the\n * code of the page. In a build, those of the client build are the default (see\n * `setClientBundles`), so only a render that wants others passes them.\n */\n bundles?: ClientBundles;\n}\n\n/** The bundles of the client build, for a render whose options name none. */\nlet clientBundles: ClientBundles | undefined;\n\n/**\n * Sets the bundles that a render names when its options name none. The Vite plugin calls it in\n * a server build with those of the client build, so a server that calls `render()` itself gets\n * pages whose code loads. The dev server loads each component by its module and sets none.\n */\nexport function setClientBundles(bundles: ClientBundles | undefined): void {\n clientBundles = bundles;\n}\n\n/** The bundles of a client build, by the ID of their root component, such as a route. */\nexport interface ClientBundles {\n /** The URL of the chunk of each bundle. */\n chunks: Record<string, string>;\n /** The URLs of the stylesheets that the modules of each bundle import. */\n styles?: Record<string, string[]>;\n /** The IDs of the components whose code each bundle holds. */\n members: Record<string, string[]>;\n /** The roots whose bundles the browser has, such as those of a page that asks for a `#defer` body. */\n loaded?: string[];\n}\n\n/** The first bundle that holds each component, for each table of members. */\nconst bundleOwners = new WeakMap<ClientBundles['members'], Map<string, string>>();\n\n/**\n * Returns the URLs of the bundles that hold the code of the components of `scopes`, other than\n * those in `sent`. A root loads its own bundle, and another component the first bundle that\n * holds it, unless a bundle in `sent` holds it. `sent` and `covered` keep the bundles and the\n * components of the render so far.\n */\nfunction bundleUrls(\n bundles: ClientBundles,\n scopes: Iterable<string | undefined>,\n sent: Set<string>,\n covered: Set<string>,\n): string[] {\n let owners = bundleOwners.get(bundles.members);\n if (!owners) {\n owners = new Map();\n for (const [root, ids] of Object.entries(bundles.members)) {\n for (const id of ids) {\n if (!owners.has(id)) {\n owners.set(id, root);\n }\n }\n }\n bundleOwners.set(bundles.members, owners);\n }\n const urls: string[] = [];\n for (const id of scopes) {\n if (id === undefined || covered.has(id)) {\n continue;\n }\n covered.add(id);\n const root = bundles.chunks[id] === undefined ? owners.get(id) : id;\n if (root === undefined || sent.has(root)) {\n continue;\n }\n sent.add(root);\n urls.push(bundles.chunks[root]!, ...(bundles.styles?.[root] ?? []));\n for (const member of bundles.members[root] ?? []) {\n covered.add(member);\n }\n }\n return urls;\n}\n\n/**\n * Renders the parts of a page. It returns as soon as the markup is rendered.\n * `#loading` bodies and promises in the state do not hold it up: they come\n * later, from `pending`. `renderToStream` puts the parts together. Use this\n * directly to send the response headers that server functions set before\n * the stream starts.\n */\nexport async function render<P>(\n Root: Component<P>,\n props: P,\n options: RenderOptions = {},\n): Promise<RenderResult> {\n const scriptTag =\n options.nonce === undefined ? '<script>' : `<script nonce=\"${escapeAttribute(options.nonce)}\">`;\n const ctx = new Context(undefined, options.rpc, options.base);\n if (options.actions) {\n ctx.actions = options.actions;\n }\n if (options.params) {\n ctx.params = options.params;\n }\n ctx.build = options.build;\n ctx.development = options.dev === true;\n if (options.defer) {\n ctx.target = { ...options.defer };\n }\n ctx.inOrder =\n !options.defer &&\n rendersInOrder(options.inOrder ?? 'bots', options.request ?? options.event?.request);\n const event =\n options.event ??\n (options.request\n ? new RequestEvent(options.request, {\n kind: options.defer ? 'defer' : 'page',\n waitUntil: options.waitUntil,\n address: options.address,\n prerender: options.prerender,\n onError: options.onError,\n })\n : undefined);\n ctx.event = event;\n ctx.errors = event ? event.errors : errorSink(options.onError);\n // The first part of each component runs with the event, and so do memos, which the compiler gives `$$ctx`.\n const rendered = (await ctx.run(() => Root(props, ctx))) as string;\n ctx.send();\n const html = beforeBodyEnd(rendered, ctx.portals.join(''));\n // The queue of `pending` is made only when something is pending, because it costs a lot for a small page.\n let queue: Queue<string> | undefined;\n function pending(): Queue<string> {\n return (queue ??= createQueue<string>());\n }\n // Records share references, so later records can point into earlier ones.\n const refs = new Map<unknown, number>();\n const { nonce } = options;\n // The records of a `#defer` body have references of their own, apart from those of the page.\n const root = options.defer ? `d${options.defer.boundary}` : options.base;\n // The first record, the page state, defines `$bR` for the others.\n let first = true;\n let open = 0;\n let swap = false;\n let headSwap = false;\n function finish(): void {\n open--;\n if (open === 0) {\n queue?.close();\n }\n }\n // The page state is the only record when no `#loading` body is pending.\n let boundaries = 0;\n // The function that swaps a body in, which the first swap of the page defines.\n const swapScript = options.dev ? SWAP_DEV : SWAP;\n // `$bF` is defined in the first script that shows a held fallback.\n let fallbackDefined = false;\n function showFallback(): string {\n if (fallbackDefined) {\n return '';\n }\n fallbackDefined = true;\n return `${SHOW_FALLBACK};`;\n }\n // The bundles that the records of this render named, and the components that they hold.\n const bundles = options.bundles ?? clientBundles;\n const sentBundles = new Set<string>();\n const coveredComponents = new Set<string>();\n if (bundles?.loaded) {\n bundleUrls(bundles, bundles.loaded, sentBundles, coveredComponents);\n }\n function serialize(\n target: Context,\n onScopes: (script: string) => void,\n route?: string,\n onError: (error: unknown) => void = (error) => pending().fail(unsendable(error, target)),\n last = false,\n ): void {\n open++;\n serializeState(\n target,\n refs,\n (code, initial) => {\n if (initial) {\n const ids: (string | undefined)[] = [];\n for (const entry of target.scopes) {\n ids.push(entry.record.m);\n }\n onScopes(\n stateScript(code, true, {\n next: ctx.next(),\n load: bundles && bundleUrls(bundles, ids, sentBundles, coveredComponents),\n route,\n root,\n nonce,\n define: first,\n // The params go with the route, so the browser reads them after a navigation.\n params: route === undefined ? undefined : options.params,\n build: first ? options.build : undefined,\n }),\n );\n first = false;\n } else {\n pending().push(stateScript(code, false, { root, nonce }));\n }\n },\n onError,\n finish,\n undefined,\n last,\n );\n }\n\n // Renders the `#catch` body of the nearest `#try` around a boundary whose body failed.\n async function renderCatch(\n boundary: Boundary,\n error: unknown,\n kind: ServerErrorKind,\n ): Promise<{ html: string; ctx: Context; key: string } | undefined> {\n const entry = boundary.catchers.at(-1);\n if (!entry) {\n return undefined;\n }\n const child = new Context(ctx, undefined, 0, `${boundary.id}c.`);\n child.outer = boundary.catchers.slice(0, -1);\n try {\n return { html: await entry.render(child, error), ctx: child, key: entry.key };\n } catch (failure) {\n logError(failure, kind, ctx.errorSink(), event);\n return undefined;\n }\n }\n\n // In order: the bodies render where they are, so the page waits for every one of them.\n const inOrder: Boundary[] | undefined = ctx.inOrder ? [] : undefined;\n // When the reader of the response leaves, the bodies that are not sent yet are not sent.\n function stopped(): boolean {\n return event?.signal.aborted === true;\n }\n event?.signal.addEventListener('abort', () => queue?.close(), { once: true });\n ctx.watch((boundary) => {\n if (inOrder) {\n inOrder.push(boundary);\n return;\n }\n boundaries++;\n open++;\n // A body whose `#reveal` holds it waits for its turn. One that is not sent still takes its\n // turn, and can show the fallback after it.\n function skip(after: string): void {\n if (after) {\n pending().push(`${scriptTag}${showFallback()}${after}</script>`);\n }\n finish();\n }\n function turn(send: (after: string) => void): void {\n if (boundary.group) {\n boundary.group.ready(boundary.id, send);\n } else {\n send('');\n }\n }\n boundary.render.then(\n (result) => {\n // A `#try` body around it failed, so the page has no markers for it. A body around the\n // target of a `#defer` request is in the page already.\n if (boundary.cancelled || boundary.around || stopped()) {\n turn(skip);\n return;\n }\n turn((after) => {\n serialize(result.ctx, (script) => {\n // An ID inside a boundary, such as `5.1`, is a string.\n const id = scriptJSON(boundary.id);\n let call = `${swap ? '' : swapScript}$bS(${id})`;\n swap = true;\n if (after) {\n call += `;${showFallback()}${after}`;\n }\n const late = result.ctx.lateHead();\n let head = '';\n if (late.html || late.title !== undefined) {\n head = `<template b-h=\"${boundary.id}\">${late.html}</template>`;\n const title = late.title === undefined ? '' : `,${scriptJSON(late.title)}`;\n call += `;${headSwap ? '' : HEAD}$bH(${id}${title})`;\n headSwap = true;\n }\n pending().push(\n // The body moves in before its record runs, so the core finds its markup when it reads the scopes.\n `<template b-l=\"${boundary.id}\">${result.html}</template>${head}${result.ctx.portals.join('')}${scriptTag}${call}</script>${script}`,\n );\n });\n finish();\n });\n },\n (error: unknown) => {\n if (boundary.cancelled || boundary.around || stopped()) {\n logError(error, 'stream', ctx.errorSink(), event);\n turn(skip);\n return;\n }\n // The body never arrives. The `#try` around the boundary renders its `#catch` body in its\n // place, or the browser gets the error when there is no `#try`.\n turn((after) => {\n if (ctx.isDev()) {\n logError(error, 'stream', ctx.errorSink(), event);\n }\n void renderCatch(boundary, error, 'stream').then((result) => {\n if (!result) {\n pending().push(\n failScript(caught(error, ctx, 'stream'), refs, boundary.id, root, nonce),\n );\n skip(after);\n return;\n }\n serialize(result.ctx, (script) => {\n pending().push(\n `<template b-c=\"${result.key}\">${result.html}</template>${result.ctx.portals.join('')}` +\n `${stateScript('0', false, { root, nonce, catches: result.key })}${script}`,\n );\n });\n skip(after);\n });\n });\n },\n );\n });\n\n if (options.defer) {\n // The browser has the page. It gets only the body, from `pending`.\n return {\n html: '',\n state: '',\n pending: queue === undefined && open === 0 ? NOTHING_PENDING : pending().iterable,\n headers: event?.headers ?? new Headers(),\n status: event?.status ?? 200,\n next: () => ctx.next(),\n head: '',\n defer: ctx.target!.status ?? 'missing',\n };\n }\n\n let state = '';\n // The state of the page is serialized before this returns, so a value that cannot be sent\n // fails the render here, with its name, instead of leaving the page without its state.\n let failure: unknown;\n serialize(\n ctx,\n (script) => {\n state = script;\n },\n options.route,\n (error) => {\n failure = error;\n },\n boundaries === 0 && (inOrder === undefined || inOrder.length === 0),\n );\n if (failure !== undefined) {\n throw unsendable(failure, ctx);\n }\n let page = html;\n if (inOrder) {\n // Each body that renders can add more, so the list grows while it is read.\n const bodies = new Map<string, string>();\n const portals: string[] = [];\n // The `#catch` bodies of the `#try` blocks around a body that failed.\n const catches: [key: string, html: string][] = [];\n for (let index = 0; index < inOrder.length; index++) {\n const boundary = inOrder[index]!;\n let result: { html: string; ctx: Context };\n try {\n // oxlint-disable-next-line no-await-in-loop -- The bodies settle in the order of the page.\n result = await boundary.render;\n } catch (error) {\n if (boundary.cancelled || boundary.around) {\n continue;\n }\n if (ctx.isDev()) {\n logError(error, 'page', ctx.errorSink(), event);\n }\n // oxlint-disable-next-line no-await-in-loop -- The bodies settle in the order of the page.\n const replacement = await renderCatch(boundary, error, 'page');\n if (!replacement) {\n // The fallback stays in the page.\n logError(error, 'page', ctx.errorSink(), event);\n continue;\n }\n catches.push([replacement.key, replacement.html]);\n portals.push(...replacement.ctx.portals);\n serialize(\n replacement.ctx,\n (script) => {\n state += script;\n },\n undefined,\n (failed) => {\n failure = failed;\n },\n );\n if (failure !== undefined) {\n throw unsendable(failure, replacement.ctx);\n }\n continue;\n }\n if (boundary.cancelled || boundary.around) {\n continue;\n }\n bodies.set(String(boundary.id), result.html);\n portals.push(...result.ctx.portals);\n ctx.adoptHead(result.ctx.lateHead());\n // The records of the bodies follow the page state, so they run after it, as when they stream.\n serialize(\n result.ctx,\n (script) => {\n state += script;\n },\n undefined,\n (error) => {\n failure = error;\n },\n index === inOrder.length - 1,\n );\n if (failure !== undefined) {\n throw unsendable(failure, result.ctx);\n }\n }\n let shell = rendered;\n for (const [key, catchHTML] of catches) {\n shell = replaceBlock(shell, key, catchHTML);\n }\n page = beforeBodyEnd(inlineBodies(shell, bodies), [...ctx.portals, ...portals].join(''));\n }\n return {\n html: page,\n state,\n // Nothing is open when the page has no `#loading` body that is not ready and no promise in its state.\n pending: queue === undefined && open === 0 ? NOTHING_PENDING : pending().iterable,\n headers: event?.headers ?? new Headers(),\n status: event?.status ?? 200,\n next: () => ctx.next(),\n head: ctx.headHTML(),\n event,\n };\n}\n\n/** Crawlers and link previews, which read the page without running its scripts. */\nconst BOTS =\n /bot\\b|bot\\/|crawl|spider|slurp|bingpreview|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|lighthouse|google-inspectiontool|headlesschrome/i;\n\n/** True if a render with these options writes its bodies in place. */\nfunction rendersInOrder(\n option: boolean | 'bots' | ((request: Request) => boolean),\n request: Request | undefined,\n): boolean {\n if (typeof option === 'boolean') {\n return option;\n }\n if (!request) {\n return false;\n }\n if (typeof option === 'function') {\n return option(request);\n }\n return BOTS.test(request.headers.get('user-agent') ?? '');\n}\n\n/**\n * Replaces what a block holds, between its markers, with other markup. `key` is the scope and\n * the anchor in the start marker. A page without the block stays as it is.\n */\nfunction replaceBlock(html: string, key: string, inner: string): string {\n const open = `<!--b${key}-->`;\n const at = html.indexOf(open);\n if (at === -1) {\n return html;\n }\n const comments = /<!--([^>]*?)-->/g;\n comments.lastIndex = at + open.length;\n let depth = 0;\n for (let found = comments.exec(html); found; found = comments.exec(html)) {\n const data = found[1]!;\n if (data[0] === '/') {\n if (depth === 0) {\n return html.slice(0, at + open.length) + inner + html.slice(found.index);\n }\n depth--;\n } else if (/^[btilP]-?\\d/.test(data)) {\n depth++;\n }\n }\n return html;\n}\n\n// The markers of a `#loading` or `#defer` boundary, and the end of one.\nconst BOUNDARY_MARKER = /<!--(l[\\d.]+|\\/l)-->/g;\n\n/**\n * Puts the bodies of boundaries in place of their fallbacks, with the bodies\n * inside them, as the swap script would in the browser. A `#defer` block\n * loses its `<template>` too, so the browser does not ask for a body that\n * is there. A boundary without a body keeps its fallback.\n */\nexport function inlineBodies(html: string, bodies: Map<string, string>): string {\n let result = '';\n let position = 0;\n BOUNDARY_MARKER.lastIndex = 0;\n for (let match = BOUNDARY_MARKER.exec(html); match; match = BOUNDARY_MARKER.exec(html)) {\n if (match[1] === '/l') {\n continue;\n }\n const id = match[1]!.slice(1);\n // The end of this boundary, past the boundaries inside its fallback.\n let depth = 0;\n let end = -1;\n for (let inner = BOUNDARY_MARKER.exec(html); inner; inner = BOUNDARY_MARKER.exec(html)) {\n if (inner[1] !== '/l') {\n depth++;\n } else if (depth === 0) {\n end = inner.index + inner[0].length;\n break;\n } else {\n depth--;\n }\n }\n if (end === -1) {\n break;\n }\n const body = bodies.get(id);\n if (body === undefined) {\n continue;\n }\n let before = html.slice(position, match.index);\n before = before.replace(\n new RegExp(\n `<template b-b=\"[^\"]*\" b-defer=\"[^\":]*:${id.replace(/\\./g, '\\\\.')}:[^\"]*\"></template>$`,\n ),\n '',\n );\n result += before + inlineBodies(body, bodies);\n position = end;\n BOUNDARY_MARKER.lastIndex = end;\n }\n return result + html.slice(position);\n}\n\nexport interface DocumentOptions extends RenderOptions {\n /**\n * Markup before the component, for a component that does not render\n * `<html>`. A function receives the markup for the document's head.\n */\n start?: string | ((head: string) => string);\n /** Markup for the head, before the head of the components, such as the `<link>` of a CSS file. */\n head?: string;\n /**\n * Markup right after the page state, such as the client entry. Make\n * module scripts `async`, so they run before the stream ends.\n */\n scripts?: string;\n /** Markup after the first render, for a component that does not render `<html>`. */\n end?: string;\n}\n\nexport type StreamOptions = DocumentOptions;\n\nconst HTML = /<html[\\s>]/i;\nconst HTML_TAG = /^<html((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>/i;\nconst ATTRIBUTE_NAME = /([^\\s\"'<>/=]+)(?:=(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Adds `b-html` to the `<html>` tag, with the names of the attributes that the page sent, so\n * client navigation can tell them from those that a script sets.\n */\nfunction nameHtmlAttributes(page: string): string {\n const tag = HTML_TAG.exec(page);\n if (!tag) {\n return page;\n }\n const names: string[] = [];\n // The server owns `b-html`, so one that the author wrote is dropped.\n const attributes = tag[1]!.replace(ATTRIBUTE_NAME, (text, name: string) => {\n if (name.toLowerCase() === 'b-html') {\n return '';\n }\n names.push(name);\n return text;\n });\n if (attributes === tag[1] && names.length === 0) {\n // Nothing to name, so the tag stays as written.\n return page;\n }\n const list = names.length > 0 ? ` b-html=\"${escapeAttribute(names.join(' '))}\"` : '';\n return `${page.slice(0, 5)}${attributes.trimEnd()}${list}>${page.slice(tag[0].length)}`;\n}\n\n/**\n * Inserts markup before `</body>`, or at the end if there is none. `index`\n * is where `</body>` is, when the caller found it already.\n */\nfunction beforeBodyEnd(\n html: string,\n content: string,\n index = content ? html.toLowerCase().lastIndexOf('</body>') : -1,\n): string {\n if (!content) {\n return html;\n }\n return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);\n}\n\n/**\n * Builds the first chunk of a page: the whole rendered document, with the\n * page state and the scripts. A component that renders `<html>` gets the\n * doctype, its head before `</head>`, and the state and scripts before\n * `</body>`. Markup that resolves later is written after it.\n */\nfunction firstRender(\n html: string,\n componentHead: string,\n state: string,\n options: DocumentOptions,\n): string {\n const head = (options.head ?? '') + componentHead;\n const tail = state + (options.scripts ?? '');\n const match = HTML.exec(html);\n if (!match) {\n const before =\n typeof options.start === 'function' ? options.start(head) : (options.start ?? '');\n return before + html + tail + (options.end ?? '');\n }\n // Markup before <html>, such as the stylesheet of the root component, belongs in the head.\n const headContent = html.slice(0, match.index) + head;\n let page = nameHtmlAttributes(html.slice(match.index));\n // The page is lowercased once, to find its tags whatever their case.\n const lower = page.toLowerCase();\n const headEnd = lower.indexOf('</head>');\n let bodyEnd = lower.lastIndexOf('</body>');\n let at = headEnd;\n let inserted = headContent;\n if (headEnd === -1 && headContent) {\n const bodyStart = lower.search(/<body[\\s>]/);\n at = bodyStart === -1 ? page.indexOf('>') + 1 : bodyStart;\n inserted = `<head>${headContent}</head>`;\n }\n if (at !== -1 && inserted) {\n page = page.slice(0, at) + inserted + page.slice(at);\n // `</body>` moves with the markup before it, or is in the head markup when that comes after it.\n const own = inserted.toLowerCase();\n if (bodyEnd >= at) {\n bodyEnd += own.length;\n } else if (own.includes('</body>')) {\n bodyEnd = at + own.lastIndexOf('</body>');\n }\n }\n return `<!doctype html>${beforeBodyEnd(page, tail, bodyEnd)}`;\n}\n\n/**\n * Renders a component as a stream. The first chunk is the whole first\n * render, sent as soon as it is ready. Each `#loading` body and each state\n * record that settles a promise follows it as it resolves. A component that\n * renders `<html>` gets the doctype and its head.\n */\nexport function renderToStream<P>(\n Root: Component<P>,\n props: P,\n options: DocumentOptions = {},\n): ReadableStream<string> {\n return partsStream(() => render(Root, props, options), options);\n}\n\n/** Streams the parts of a page from `render`: the first render whole, then what resolves later. */\nexport function streamParts(\n parts: RenderResult,\n options: DocumentOptions = {},\n): ReadableStream<string> {\n return partsStream(() => parts, options);\n}\n\n/** A stream of the parts of a page. An error while it gets or writes them fails the stream. */\nfunction partsStream(\n getParts: () => RenderResult | Promise<RenderResult>,\n options: DocumentOptions,\n): ReadableStream<string> {\n let parts: RenderResult | undefined;\n let cancelled = false;\n return new ReadableStream<string>({\n async start(controller) {\n try {\n parts = await getParts();\n if (cancelled) {\n parts.event?.abort();\n return;\n }\n await writeParts(parts, options, controller, () => cancelled);\n } catch (error) {\n if (!cancelled) {\n controller.error(error);\n }\n }\n },\n // The reader went away, such as a browser that left the page while it streamed. The event's\n // signal aborts, so the work that nobody waits for stops.\n cancel(reason) {\n cancelled = true;\n parts?.event?.abort(reason);\n },\n });\n}\n\nasync function writeParts(\n parts: RenderResult,\n options: DocumentOptions,\n controller: ReadableStreamDefaultController<string>,\n cancelled: () => boolean = () => false,\n): Promise<void> {\n controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));\n if (parts.pending !== NOTHING_PENDING) {\n for await (const chunk of parts.pending) {\n if (cancelled()) {\n return;\n }\n controller.enqueue(chunk);\n }\n }\n if (!cancelled()) {\n controller.close();\n }\n}\n\n/**\n * The message and status that answer an error. A `ServerError` sends its\n * own. Any other error is logged, and sends `fallback` with status 500.\n */\nfunction errorAnswer(\n error: unknown,\n fallback: string,\n kind: ServerErrorKind,\n event: RequestEvent | undefined,\n): { message: string; status: number } {\n if (error instanceof ServerError) {\n return { message: error.message, status: error.status };\n }\n logError(error, kind, event?.errors, event);\n return { message: fallback, status: 500 };\n}\n\nfailures.report = (error, event) => logError(error, event.kind, event.errors, event);\n\n/**\n * Logs an error of the server, or gives it to `onError` when the app has one, which then logs\n * what it wants. A `ServerError` is an answer, so the handler does not get it. A handler that\n * fails has its error logged with the first one.\n */\nfunction logError(\n error: unknown,\n kind: ServerErrorKind,\n sink: ErrorSink | undefined,\n event: RequestEvent | undefined,\n): void {\n if (!sink) {\n console.error(error);\n return;\n }\n if (error instanceof ServerError) {\n return;\n }\n if (typeof error === 'object' && error !== null) {\n if (sink.handled.has(error)) {\n return;\n }\n sink.handled.add(error);\n }\n // The body of a `#defer` block streams in a response of its own.\n if (kind === 'stream' && event?.kind === 'defer') {\n kind = 'defer';\n }\n function fail(failure: unknown): void {\n console.error(failure);\n console.error(error);\n }\n try {\n const result = sink.handler(error, { event, kind });\n if (isThenable(result)) {\n Promise.resolve(result).catch(fail);\n }\n } catch (failure) {\n fail(failure);\n }\n}\n\n/** Errors that `safeError` logged, so a failure read in two places logs once. */\nconst logged = new WeakSet<object>();\n\n/**\n * The error that the page state may carry in production: a plain `Error` with the message of a\n * `ServerError`, or `fallback`, and no stack, which holds paths of the server. Any other error is\n * logged once. A thrown value that is not an object is logged each time.\n */\nfunction safeError(error: unknown, fallback: string, ctx?: Context, kind?: ServerErrorKind): Error {\n let message = fallback;\n const event = ctx?.requestEvent();\n const sink = ctx?.errorSink();\n if (error instanceof ServerError) {\n message = error.message;\n } else if (typeof error !== 'object' || error === null || sink) {\n // The sink counts the errors of its request.\n logError(error, kind ?? event?.kind ?? 'page', sink, event);\n } else if (!logged.has(error)) {\n logged.add(error);\n logError(error, kind ?? event?.kind ?? 'page', sink, event);\n }\n const safe = new Error(message);\n safe.stack = '';\n return safe;\n}\n\n/**\n * The error that a `#catch` body gets on the server, which the page state carries to the\n * browser. In development it is the error itself, for debugging. In production it is a plain\n * `Error` with the message of a `ServerError`, or a generic message, and the real error is\n * logged, as for a server function that fails. The body renders with this value too, so the\n * HTML cannot print what the state does not carry.\n */\nexport function caught(error: unknown, ctx: Context, kind?: ServerErrorKind): unknown {\n if (ctx.isDev()) {\n return error;\n }\n return safeError(error, 'The page could not render this part', ctx, kind);\n}\n\n/** True for a request that a `<form>` sent, without client code. */\nfunction isFormPost(request: Request): boolean {\n const type = request.headers.get('content-type') ?? '';\n return (\n type.startsWith('application/x-www-form-urlencoded') || type.startsWith('multipart/form-data')\n );\n}\n\n/** The answer to a call or a form post from a page of another site. See `isCrossSite`. */\nfunction crossSiteAnswer(): Response {\n return new Response('Calls from other sites are not allowed', { status: 403 });\n}\n\n/** The answer to a call or a form post to a server function that does not exist. */\nfunction unknownAnswer(id: string): Response {\n return new Response(`Unknown server function \"${id}\"`, { status: 404 });\n}\n\n/**\n * A response with `init`. A DOM environment such as happy-dom drops\n * `set-cookie` from the headers that a response is made with, but keeps the\n * ones added after, so a page in `brumate/testing` keeps its cookies.\n */\nfunction respond(body: BodyInit | null, init: ResponseInit & { headers: Headers }): Response {\n const result = new Response(body, init);\n if (result.headers.getSetCookie().length === 0) {\n for (const cookie of init.headers.getSetCookie()) {\n result.headers.append('set-cookie', cookie);\n }\n }\n return result;\n}\n\n/**\n * True when a request names a build other than the server's, so its page is\n * from before a deploy. Calls send the build in `x-brumate-build`, and forms\n * without scripts in `__build` of their URL.\n */\nfunction isSkewed(request: Request, build: string | undefined): boolean {\n const sent =\n request.headers.get('x-brumate-build') ?? new URL(request.url).searchParams.get('__build');\n return build !== undefined && sent !== null && sent !== build;\n}\n\n/**\n * The answer to a form without scripts, from a page of another build, that\n * posts to a function that is gone. It goes back to its page, which loads\n * with the new build, or to `/` when the page is on another site.\n */\nfunction backAnswer(request: Request): Response {\n let location = '/';\n const referer = request.headers.get('referer');\n if (referer) {\n try {\n const page = new URL(referer);\n if (page.origin === new URL(request.url).origin) {\n location = `${page.pathname}${page.search}`;\n }\n } catch {\n // A referer that is not a URL goes to `/`.\n }\n }\n return new Response(null, { status: 303, headers: { location } });\n}\n\n/** The answer to a request from a page of another build that the server cannot serve. */\nfunction skewAnswer(build: string): Response {\n return new Response(JSON.stringify({ error: 'The site changed. Load the page again' }), {\n status: 409,\n headers: { 'content-type': 'application/json', 'x-brumate-build': build },\n });\n}\n\n/**\n * Calls a server function with the data of a form that the browser sent.\n * Returns its result, or the response that answers the post instead: a\n * `redirect` in the function sends the browser there, and an error answers\n * with a short text page, because there is no page to report it in. The\n * response has `headers`. With `base`, the location of a redirect is\n * resolved against it.\n */\nasync function callWithForm(\n invoke: () => unknown,\n headers: Headers,\n event: RequestEvent,\n base?: string,\n): Promise<{ result: unknown } | { answer: Response }> {\n try {\n return { result: await invoke() };\n } catch (error) {\n return { answer: formFailure(error, headers, event, base) };\n }\n}\n\n/** The answer to a form post whose server function threw, or whose data could not be read. */\nfunction formFailure(\n error: unknown,\n headers: Headers,\n event: RequestEvent,\n base?: string,\n): Response {\n if (error instanceof Redirect) {\n headers.set('location', base ? new URL(error.location, base).href : error.location);\n return respond(null, { status: error.status, headers });\n }\n const { message, status } = errorAnswer(error, 'The server function failed', 'call', event);\n headers.set('content-type', 'text/plain; charset=utf-8');\n return respond(message, { status, headers });\n}\n\n/**\n * Calls a server function with the data of a form that the browser sent, and\n * sends the browser back to the page with a redirect. The response has the\n * headers of the event, such as cookies that the function set.\n */\nasync function handleForm(invoke: () => unknown, event: RequestEvent): Promise<Response> {\n const { headers } = event;\n const outcome = await callWithForm(invoke, headers, event);\n if ('answer' in outcome) {\n return outcome.answer;\n }\n headers.set('location', event.request.headers.get('referer') ?? '/');\n return respond(null, { status: 303, headers });\n}\n\n/**\n * The arguments of a call. They come as seroval JSON, or as multipart form\n * data when they hold files: the JSON in `args`, and each file in\n * `file<index>`, whose index stands in the JSON.\n */\nasync function readArgs(request: Request): Promise<unknown[]> {\n if (!request.headers.has('x-brumate-args')) {\n return fromJSON<unknown[]>((await request.json()) as SerovalJSON, {\n plugins,\n ...serialOptions(),\n });\n }\n const form = await request.formData();\n return fromJSON<unknown[]>(JSON.parse(String(form.get('args'))) as SerovalJSON, {\n plugins: callPlugins(undefined, form),\n ...serialOptions(),\n });\n}\n\nexport interface RequestOptions {\n /**\n * Other origins that may call server functions and post forms to them,\n * such as `https://app.example.com`. The origin of the request is always\n * allowed.\n */\n origins?: string[];\n /**\n * The middleware of the entry, which runs for every request before\n * anything else: pages, endpoints, calls, form posts and `#defer` bodies.\n * The Vite plugin passes the default export of `src/middleware.ts`.\n */\n middleware?: EntryMiddleware;\n /**\n * The `onError` export of `src/middleware.ts`, which gets each error of the server that is not\n * a `ServerError`, in place of `console.error`. The Vite plugin passes it.\n */\n onError?: ServerErrorHandler;\n /**\n * The middleware of each `'use server'` file, by the ID of each of its\n * functions. It runs before the function, after the middleware of the\n * entry. `virtual:brumate/server` passes them.\n */\n fileMiddleware?: Record<string, EntryMiddleware>;\n /** Keeps work going after the response ends, for `event.waitUntil`. See `RenderOptions`. */\n waitUntil?: (promise: Promise<unknown>) => void;\n /**\n * The ID of the build, for skew protection. A call from a page of another\n * build to a function that is gone answers 409 with this ID in\n * `x-brumate-build`, and the browser loads the page again. A call to a\n * function that still exists runs. The Vite plugin sets it in builds.\n */\n build?: string;\n /** The address of the client as the server saw it, for `clientAddress` and rate limits. */\n address?: string;\n /** True while the build prerenders the pages. Rate limits do not count then. */\n prerender?: boolean;\n}\n\n/**\n * True when a request comes from a page of another site. Server function\n * calls and form posts send the cookies of the user, so another site must\n * not be able to make them.\n *\n * The browser sends `Origin` with every call and post. Without it, an older\n * browser's `Sec-Fetch-Site` decides. A request with neither does not come\n * from a page in a browser, so it is allowed.\n */\nexport function isCrossSite(request: Request, options: RequestOptions = {}): boolean {\n const origin = request.headers.get('origin');\n if (origin === null) {\n const site = request.headers.get('sec-fetch-site');\n return site === 'cross-site' || site === 'same-site';\n }\n if (origin === 'null') {\n return true;\n }\n if (options.origins?.includes(origin)) {\n return false;\n }\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return true;\n }\n // The server can see itself under another name than the page, such as\n // `localhost` behind a proxy, so the host headers count too.\n return ![\n new URL(request.url).host,\n request.headers.get('host'),\n request.headers.get('x-forwarded-host'),\n ].includes(host);\n}\n\n/**\n * Answers a server function call from `brumate/client`. Returns undefined\n * when the request is not a call, so other handlers can answer it. Server\n * functions read the request with `getEvent()`. A call from a page of\n * another site answers 403. See `isCrossSite`.\n */\nexport async function handleRequest(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions: Record<string, (...args: any[]) => unknown>,\n request: Request,\n prefix = '/_brumate',\n options: RequestOptions = {},\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n if (request.method !== 'POST' || !url.pathname.startsWith(`${prefix}/`)) {\n return undefined;\n }\n if (isCrossSite(request, options)) {\n return crossSiteAnswer();\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n // The browser asks for the build of the server when the code of its page fails to load.\n if (id === '') {\n const headers: Record<string, string> =\n options.build === undefined ? {} : { 'x-brumate-build': options.build };\n return new Response(null, { status: 204, headers });\n }\n // A call with files sends its arguments as form data, with this header.\n const form = isFormPost(request) && !request.headers.has('x-brumate-args');\n // A form without scripts posts to the function, and wants a page back, not the result. The\n // loader sends a form of an `$action` with this header, and wants the result.\n const posted = form && !request.headers.has('x-brumate-result');\n const fn = functions[id];\n if (!fn) {\n if (!isSkewed(request, options.build)) {\n return unknownAnswer(id);\n }\n return posted ? backAnswer(request) : skewAnswer(options.build!);\n }\n const event = new RequestEvent(request, {\n kind: 'call',\n waitUntil: options.waitUntil,\n address: options.address,\n prerender: options.prerender,\n onError: options.onError,\n });\n // The arguments are read before the middleware runs, so a check can depend on them. Arguments\n // that fail to read, such as a regular expression, answer as an error of the call.\n let args: unknown[];\n try {\n args = form ? [await request.formData()] : await readArgs(request);\n } catch (error) {\n return posted\n ? formFailure(error, event.headers, event)\n : callFailure(error, event.headers, event);\n }\n event.call = { id, args };\n // The function runs with its event, so `getEvent()` before its first await returns it.\n function invoke(): unknown {\n return withEvent(event, () => fn(...args));\n }\n return runEntry(options.middleware, event, () =>\n runEntry(options.fileMiddleware?.[id], event, () =>\n posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke()),\n ),\n );\n}\n\n/**\n * Answers a server function call with its result as a stream of seroval\n * chunks, so promises and async iterables in it stream as they settle. A\n * redirect is sent as a header, so the client can follow it. An error\n * answers with a message that the client throws.\n */\nasync function answerCall(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions: Record<string, (...args: any[]) => unknown>,\n event: RequestEvent,\n run: () => Promise<unknown>,\n): Promise<Response> {\n const { headers } = event;\n try {\n const result = await run();\n // The client loads again the memos that call the server functions that `refresh` named.\n const { refreshed } = event;\n if (refreshed?.size) {\n const ids: string[] = [];\n for (const key of Object.keys(functions)) {\n if (refreshed.has(unwrap(functions[key]))) {\n ids.push(key);\n }\n }\n if (ids.length > 0) {\n headers.set('x-brumate-refresh', ids.join(','));\n }\n }\n headers.set('content-type', STREAM_TYPE);\n return respond(\n toChunkStream(result, (reason) => event.abort(reason)),\n { headers },\n );\n } catch (error) {\n return callFailure(error, headers, event);\n }\n}\n\n/** The answer to a call whose server function threw, or whose arguments could not be read. */\nfunction callFailure(error: unknown, headers: Headers, event: RequestEvent): Response {\n if (error instanceof Redirect) {\n headers.set('x-brumate-redirect', error.location);\n return respond(null, { status: 204, headers });\n }\n const { message, status } = errorAnswer(error, 'The server function failed', 'call', event);\n headers.set('content-type', 'application/json');\n return respond(JSON.stringify({ error: message }), { status, headers });\n}\n\ninterface ResolvedView {\n key: string;\n component: Component;\n slots: Record<string, ResolvedView>;\n /** `_loading.brm`: the view streams in, and this shows until then. */\n loading?: Component;\n /** The `cache` export of the module script of the file. */\n cache?: PageCache;\n}\n\n/**\n * How long a page can be cached for everyone, as a route exports it from\n * its module script: `export const cache = { maxAge: 60 }`. A layout's\n * applies to the pages below it, and the nearest one wins.\n */\nexport interface PageCache {\n /** Seconds that a cache can serve the page without asking again. */\n maxAge: number;\n /** Seconds after `maxAge` that a cache can serve the old page while it gets a new one. */\n staleWhileRevalidate?: number;\n}\n\n/** A page that the server keeps, as the store holds it. */\ninterface KeptPage {\n status: number;\n headers: [string, string][];\n body: string;\n /** When the page expires, in milliseconds since 1970. */\n expires: number;\n /** The versions of the tags of the `cached` functions that the page called. */\n tags: Record<string, string>;\n}\n\n/** The key of a page in the store: its URL, and the base of a client navigation, by build. */\nfunction pageKey(url: URL, request: Request, build: string | undefined): string {\n const base = request.headers.get('x-brumate-base') ?? '';\n return `brumate:page:${build ?? ''}:${base}:${url.pathname}${url.search}`;\n}\n\n/** The page that the store keeps for a key, when it is still fresh. */\nasync function keptPage(key: string): Promise<Response | undefined> {\n const text = await cacheStore().get(key);\n if (!text) {\n return undefined;\n }\n const page = JSON.parse(text) as KeptPage;\n const tags = Object.keys(page.tags);\n const versions = await tagVersions(tags);\n if (page.expires <= Date.now()) {\n return undefined;\n }\n for (const tag of tags) {\n if (versions[tag] !== page.tags[tag]) {\n return undefined;\n }\n }\n const headers = new Headers(page.headers);\n const maxAge = Number(/max-age=(\\d+)/.exec(headers.get('cache-control') ?? '')?.[1] ?? 0);\n headers.set('age', String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1000))));\n headers.set('x-brumate-cache', 'hit');\n return new Response(page.body, { status: page.status, headers });\n}\n\n/** Keeps a public page in the store until its `max-age` ends. */\nasync function keepPage(key: string, response: Response, event: RequestEvent): Promise<void> {\n const maxAge = Number(\n /max-age=(\\d+)/.exec(response.headers.get('cache-control') ?? '')?.[1] ?? 0,\n );\n if (maxAge <= 0) {\n return;\n }\n const missing: string[] = [];\n for (const [tag, version] of event.cacheTags) {\n if (version === undefined) {\n missing.push(tag);\n }\n }\n const versions = await tagVersions(missing);\n const kept: [string, string][] = [];\n for (const [name, value] of response.headers) {\n if (name !== 'set-cookie') {\n kept.push([name, value]);\n }\n }\n // The body streams, so the tags of late bodies, such as of `#loading`, are in only after it ends.\n const body = await response.clone().text();\n const tags: Record<string, string> = {};\n for (const [tag, version] of event.cacheTags) {\n tags[tag] = version ?? versions[tag]!;\n }\n const page: KeptPage = {\n status: response.status,\n headers: kept,\n body,\n expires: Date.now() + maxAge * 1000,\n tags,\n };\n await cacheStore().set(key, JSON.stringify(page), maxAge);\n}\n\n/** The `cache` of the page of a view: the nearest one along its `children`. */\nfunction pageCache(view: ResolvedView): PageCache | undefined {\n const inner = view.slots.children;\n return (inner && pageCache(inner)) ?? view.cache;\n}\n\n/**\n * The `cache-control` of a page with `cache`. It is public only when the\n * request did not read or set anything of the user, and the page is a\n * success without cookies.\n */\nfunction cacheControl(\n cache: PageCache,\n event: RequestEvent | undefined,\n response: Response,\n): string {\n if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) {\n return 'private, no-cache';\n }\n const parts = ['public', `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];\n if (cache.staleWhileRevalidate !== undefined) {\n parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);\n }\n return parts.join(', ');\n}\n\n// Pages that `cache` made private in development, so each warns once.\nconst warnedPrivate = new Set<string>();\n\n/** Imports every module of a matched route before it renders. */\nasync function resolveView(view: RouteView): Promise<ResolvedView> {\n const names = Object.keys(view.slots);\n const pending: Promise<ResolvedView>[] = [];\n for (const slot of Object.values(view.slots)) {\n pending.push(resolveView(slot));\n }\n const [module, loading, ...slots] = await Promise.all([\n view.load(),\n view.loading?.(),\n ...pending,\n ]);\n const resolved: Record<string, ResolvedView> = {};\n for (const [index, name] of names.entries()) {\n resolved[name] = slots[index]!;\n }\n return {\n key: view.key,\n component: module.default,\n loading: loading?.default,\n cache: (module as { cache?: PageCache }).cache,\n slots: resolved,\n };\n}\n\n/**\n * Renders a view where its layout inserts it. A view with a loading file\n * streams in after the rest of the page, as a `#loading` body does.\n */\nasync function renderView(\n view: ResolvedView,\n props: Record<string, unknown>,\n ctx: Context,\n scope: ScopeId | undefined,\n): Promise<string> {\n if (!view.loading) {\n return component(viewComponent(view, props), {}, ctx, scope);\n }\n const id = ctx.boundary();\n const fallback = await component(view.loading, props, ctx, scope);\n ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));\n return `<!--l${id}-->${fallback}<!--/l-->`;\n}\n\n/**\n * A component that renders a route, with its slots rendering where the\n * layout inserts them. `props` go to every view, such as `params`.\n */\n/** The component IDs of a view and of the views in its slots. */\nfunction viewIds(view: ResolvedView): string[] {\n const id = (view.component as { brumateId?: string }).brumateId;\n const ids: string[] = id === undefined ? [] : [id];\n for (const slot of Object.values(view.slots)) {\n ids.push(...viewIds(slot));\n }\n return ids;\n}\n\nfunction viewComponent(view: ResolvedView, props: Record<string, unknown>): Component {\n return (_props, ctx) => {\n const own: Record<string, unknown> = { ...props };\n for (const [name, slot] of Object.entries(view.slots)) {\n // Comments mark the slot, its layout's scope, the scope of its route and the route's key,\n // so the client can replace only the routes that change.\n own[name] = lazy(async (at, scope) => {\n const root = at.peek();\n const html = await renderView(slot, props, at, scope);\n return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;\n });\n }\n return view.component(own, ctx);\n };\n}\n\nexport interface RouteOptions extends DocumentOptions, RequestOptions {\n /**\n * The HTML that the build prerendered for the path, for a server that has\n * the file. The server sends it at once, then renders the `#defer` blocks\n * with the `load` or `idle` trigger in the same response, in place of a\n * request for each. Requests for a `#defer` body and client navigation\n * render the route as usual.\n */\n shell?: string;\n /**\n * Keeps the pages that `cache` makes public in the store of `cached`, and\n * answers the next request for the same URL from it until `maxAge` ends or\n * `revalidate` drops a tag that the page used. Defaults to true. A CDN in\n * front of the server can keep them instead.\n */\n pageCache?: boolean;\n /**\n * Throws errors that are not a `ServerError` instead of rendering\n * `_error.brm`, so a dev server can show them, such as with `errorPage`\n * from `brumate/vite`. The Vite plugin sets it in development.\n */\n dev?: boolean;\n /** The server functions, by ID, for forms that post to a page. `virtual:brumate/routes` passes them. */\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions?: Record<string, (...args: any[]) => unknown>;\n /**\n * The URLs of the modules that every page loads early: the loader, and the\n * core that the first event loads. A page gets them as `Link` headers and\n * as `<link rel=\"modulepreload\">` in its head. `virtual:brumate/routes`\n * passes them from the client build.\n */\n hints?: string[];\n /**\n * The URLs of the bundle of each root component, such as a route or a layout, by component ID:\n * its chunk, the chunks that it imports and its stylesheets. A page adds the scripts of its\n * views to `hints`, so the code of the page loads with the HTML, and links to their\n * stylesheets in its head. `virtual:brumate/routes` passes them.\n */\n bundleHints?: Record<string, string[]>;\n /**\n * Receives the `Link` values of `hints` before the page renders, so a\n * server can send them as `103 Early Hints`, such as with Node's\n * `response.writeEarlyHints({ link })`.\n */\n earlyHints?: (links: string[]) => void;\n}\n\n/**\n * Runs the server function that a form without scripts posted to a page, as\n * `?__action=<id>`. Returns its result for `$action`, or the response that\n * answers the post instead of the page: a redirect, or an error.\n * `handleRoute` adds the cookies of the event to that response, and no other\n * headers of the event.\n */\nasync function runAction(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n fn: (...args: any[]) => unknown,\n event: RequestEvent,\n): Promise<{ actions: Map<unknown, unknown> } | { answer: Response }> {\n const { request } = event;\n const args = event.call!.args;\n const outcome = await callWithForm(\n () => withEvent(event, () => fn(...args)),\n new Headers(),\n event,\n request.url,\n );\n return 'answer' in outcome ? outcome : { actions: new Map([[fn, outcome.result]]) };\n}\n\n/**\n * Reads the server function that a form without scripts posted to a page,\n * as `?__action=<id>`, into `event.call`, before any middleware runs.\n * Returns the response that answers the post instead of the page: a post\n * from another site, an unknown function, or a form that cannot be read.\n */\nasync function readAction(\n url: URL,\n event: RequestEvent,\n options: RouteOptions,\n): Promise<Response | undefined> {\n const { request } = event;\n const id = url.searchParams.get('__action');\n if (request.method !== 'POST' || id === null) {\n return undefined;\n }\n if (isCrossSite(request, options)) {\n return crossSiteAnswer();\n }\n if (!options.functions?.[id]) {\n // A form from a page of another build goes back to its page, which loads with the new build.\n return isSkewed(request, options.build) ? backAnswer(request) : unknownAnswer(id);\n }\n try {\n event.call = { id, args: [await request.formData()] };\n } catch (error) {\n return formFailure(error, new Headers(), event, request.url);\n }\n return undefined;\n}\n\n/** Renders the page of a route tree, streamed, with the results of a form for `$action`. */\nasync function renderPage(\n view: ResolvedView,\n props: Record<string, unknown>,\n request: Request,\n options: RouteOptions,\n extra: { actions?: Map<unknown, unknown>; status?: number },\n): Promise<Response> {\n // A page that the client loads in place of another starts above its IDs.\n const base = Number(request.headers.get('x-brumate-base'));\n const defer = deferTarget(request);\n if (defer) {\n return renderDeferred(view, props, request, options, defer, base);\n }\n // In development, the render records what it does and when, for the Server tab of the devtools.\n const event = options.event;\n if (options.dev && event) {\n event.trace = [];\n event.traceStart = performance.now();\n }\n const path = new URL(request.url).pathname;\n const endRender = event?.traced('render', path) ?? (() => {});\n // Client navigation has the loader and the core already. The stylesheets of the bundles of the\n // views go in the head of every page, so a navigation keeps those of the next page.\n const navigation = request.headers.has('x-brumate-base');\n const wanted: string[] = navigation ? [] : [...(options.hints ?? [])];\n const styles = new Set<string>();\n for (const id of viewIds(view)) {\n for (const url of options.bundleHints?.[id] ?? []) {\n // A relative URL is relative to the page, which is wrong on a page deeper than the base,\n // so the state records name those stylesheets for the loader instead.\n if (url.endsWith('.css')) {\n if (!url.startsWith('.')) {\n styles.add(url);\n }\n } else if (!navigation) {\n wanted.push(url);\n }\n }\n }\n const hints = [...new Set(wanted)];\n // A page with a nonce, under a strict policy, loads only what carries the nonce. A `Link`\n // header cannot, so the links are in the head only.\n const nonce = options.nonce === undefined ? '' : ` nonce=\"${escapeAttribute(options.nonce)}\"`;\n const links: string[] = [];\n if (!nonce) {\n for (const url of hints) {\n links.push(`<${url}>; rel=modulepreload`);\n }\n }\n if (links.length > 0) {\n options.earlyHints?.(links);\n }\n let preload = '';\n for (const url of hints) {\n preload += `<link rel=\"modulepreload\"${nonce} href=\"${escapeAttribute(url)}\">`;\n }\n for (const url of styles) {\n preload += `<link rel=\"stylesheet\"${nonce} href=\"${escapeAttribute(url)}\">`;\n }\n const parts = await render(\n viewComponent(view, props),\n {},\n {\n ...options,\n request,\n actions: extra.actions,\n route: view.key,\n params: props.params as Record<string, string> | undefined,\n base: Number.isSafeInteger(base) && base > 0 ? base : undefined,\n },\n );\n endRender();\n const endStream = event?.traced('stream', 'the rest of the page') ?? (() => {});\n const headers = new Headers(parts.headers);\n headers.set('content-type', 'text/html; charset=utf-8');\n // The same URL answers the request for a `#defer` body with that body only, and a navigation,\n // which sends `x-brumate-base`, without the links of the core.\n headers.append('vary', 'x-brumate-defer');\n headers.append('vary', 'x-brumate-base');\n for (const link of links) {\n headers.append('link', link);\n }\n let html = streamParts(parts, { ...options, head: preload + (options.head ?? '') });\n if (event?.trace) {\n // The trace goes last, once every body has streamed, as JSON that the devtools read.\n const trace = event.trace;\n html = html.pipeThrough(\n new TransformStream<string, string>({\n flush(controller) {\n endStream();\n const json = JSON.stringify({ route: path, entries: trace }).replace(/</g, '\\\\u003c');\n controller.enqueue(`<script type=\"application/json\" b-trace>${json}</script>`);\n },\n }),\n );\n }\n const body = html.pipeThrough(new TextEncoderStream());\n const cache = request.method === 'GET' || request.method === 'HEAD' ? pageCache(view) : undefined;\n if (!cache) {\n return respond(body, { status: extra.status ?? parts.status, headers });\n }\n // A page with `cache` renders in full before its headers go out, so a `#loading` body that\n // reads the user makes it private too.\n const response = respond(await new Response(body).arrayBuffer(), {\n status: extra.status ?? parts.status,\n headers,\n });\n const control = cacheControl(cache, options.event, response);\n if (options.dev) {\n // A browser would keep the page while the files change, so the dev server only says what\n // the page would get.\n response.headers.set('cache-control', 'no-cache');\n response.headers.set('x-brumate-cache', control);\n if (control.startsWith('private') && !warnedPrivate.has(view.key)) {\n warnedPrivate.add(view.key);\n console.warn(\n `The page ${new URL(request.url).pathname} exports cache, but it read cookies or the authorization header, or set a cookie, so it is not cached for everyone. Move what reads the user into #defer.`,\n );\n }\n } else {\n response.headers.set('cache-control', control);\n }\n return response;\n}\n\n/**\n * The `#defer` block that a request asks for, from `x-brumate-defer:\n * <boundary> <scope>:<anchor>`, which the browser sends when the block's\n * trigger fires.\n */\nfunction deferTarget(request: Request): { boundary: ScopeId; at: string } | undefined {\n const match = /^([\\d.]+) (-?[\\d.]+:\\d+)$/.exec(request.headers.get('x-brumate-defer') ?? '');\n return match ? { boundary: parseId(match[1]!), at: match[2]! } : undefined;\n}\n\n/**\n * Renders the route again and answers with the body of one `#defer` block:\n * its markup in a `<template b-l>`, the script that swaps it in, and its\n * state. The page renders with the base it had, so its IDs come out the\n * same. When the block is not where the browser has it, such as after the\n * data of the page changed, the answer is 409 and the fallback stays.\n */\nasync function renderDeferred(\n view: ResolvedView,\n props: Record<string, unknown>,\n request: Request,\n options: RouteOptions,\n defer: { boundary: ScopeId; at: string },\n base: number,\n): Promise<Response> {\n const bundles = options.bundles ?? clientBundles;\n const parts = await render(\n viewComponent(view, props),\n {},\n {\n ...options,\n request,\n route: view.key,\n params: props.params as Record<string, string> | undefined,\n base: Number.isSafeInteger(base) && base > 0 ? base : undefined,\n defer,\n // The page that asks for the body has the bundles of its views.\n bundles: bundles && { ...bundles, loaded: viewIds(view) },\n },\n );\n const headers = new Headers(parts.headers);\n headers.append('vary', 'x-brumate-defer');\n if (parts.defer !== 'found') {\n return respond(null, { status: parts.defer === 'moved' ? 409 : 404, headers });\n }\n headers.set('content-type', 'text/html; charset=utf-8');\n headers.set('x-brumate-defer', String(defer.boundary));\n const body = new ReadableStream<string>({\n async start(controller) {\n try {\n if (parts.pending !== NOTHING_PENDING) {\n for await (const chunk of parts.pending) {\n controller.enqueue(chunk);\n }\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n },\n }).pipeThrough(new TextEncoderStream());\n return respond(body, { status: parts.status, headers });\n}\n\n/**\n * Renders the first `_error.brm` that renders, from the innermost. Its\n * component gets `error`, with the message and the status.\n */\nasync function renderError(\n views: RouteView[],\n error: { message: string; status: number },\n params: Record<string, string>,\n request: Request,\n options: RouteOptions,\n): Promise<Response | undefined> {\n for (const view of views) {\n try {\n // oxlint-disable-next-line no-await-in-loop -- The next file renders only when this one throws.\n const resolved = await resolveView(view);\n // oxlint-disable-next-line no-await-in-loop -- The next file renders only when this one throws.\n return await renderPage(resolved, { params, error }, request, options, {\n status: error.status,\n });\n } catch (failure) {\n // An error file that throws hands the error to the one outside it.\n logError(failure, options.event?.kind ?? 'page', options.event?.errors, options.event);\n }\n }\n return undefined;\n}\n\n/** Runs the middleware of the folders on the path, from the outside in, around the answer. */\nasync function runMiddleware(\n loaders: MiddlewareLoader[],\n request: Request,\n event: RequestEvent,\n answer: () => Promise<Response>,\n): Promise<Response> {\n const [first, ...rest] = loaders;\n if (!first) {\n return answer();\n }\n const { middleware } = await first();\n return withEvent(event, () =>\n middleware(request, () => runMiddleware(rest, request, event, answer)),\n );\n}\n\n/**\n * Answers a request with the route that matches its path, streamed:\n *\n * - The `_middleware.ts` of each folder on the path runs first, from the outside in.\n * - An endpoint at the path answers the methods that it exports.\n * - A form without scripts that posts to the page with `?__action=<id>`\n * runs that server function first, and the page renders with its result\n * for `$action`.\n * - A route that throws renders the nearest `_error.brm`, and a path that\n * no route matches renders the `_error.brm` of the root with status 404.\n *\n * Returns undefined when no route matches and the root has no error file or\n * middleware. A `redirect` while the page renders answers with a redirect.\n */\nexport async function handleRoute(\n tree: RouteNode,\n request: Request,\n options: RouteOptions = {},\n): Promise<Response | undefined> {\n if (\n options.shell !== undefined &&\n (request.method === 'GET' || request.method === 'HEAD') &&\n !deferTarget(request) &&\n !request.headers.has('x-brumate-base')\n ) {\n return fillHoles(tree, request, options.shell, options);\n }\n const url = new URL(request.url);\n const match = matchRoute(tree, url.pathname);\n // One event for the request: middleware, endpoints, a form's server function and the page\n // share it, so cookies that one sets reach the response and the others read them.\n const event =\n options.event ??\n new RequestEvent(request, {\n kind: await requestKind(request, match),\n waitUntil: options.waitUntil,\n address: options.address,\n prerender: options.prerender,\n onError: options.onError,\n });\n // Rate limits count by the pattern of the route, so `/api/1` and `/api/2` share a count.\n event.route = match?.route;\n const answer = await routeAnswer(tree, match, url, { ...options, event });\n return answer && withHeaders(answer, event.headers);\n}\n\n/**\n * What a request to a route is for: the body of a `#defer` block, an\n * endpoint when the folder has one that answers the method, or a page. A\n * path that no route matches is a page, the 404 page.\n */\nasync function requestKind(request: Request, match: RouteMatch | undefined): Promise<RequestKind> {\n if (deferTarget(request)) {\n return 'defer';\n }\n if (match?.endpoint) {\n const endpoint = await match.endpoint();\n const method = request.method === 'HEAD' ? 'GET' : request.method;\n // A method that the endpoint does not answer gets 405 from it, unless the page answers GET.\n if (endpoint[method] || request.method !== 'GET') {\n return 'endpoint';\n }\n }\n return 'page';\n}\n\n/**\n * The `#defer` blocks of a prerendered page that the server renders in the\n * response: those with the `load` or `idle` trigger. A `visible` block is\n * far down the page, so it waits for the browser to ask for it.\n */\nconst HOLE = /<template b-b=\"([^\"]+)\" b-defer=\"(?:load|idle):([^:\"]+):([^\"]*)\"/g;\n\n/**\n * Answers with a prerendered page, then with the body of each of its\n * `#defer` blocks as it is ready, as a `#loading` body streams. Each body\n * renders in a request of its own, as when the browser asks for it, so\n * middleware runs for it. The loader leaves the marked blocks alone, and a\n * block whose body fails keeps its fallback.\n */\nfunction fillHoles(\n tree: RouteNode,\n request: Request,\n shell: string,\n options: RouteOptions,\n): Response {\n const holes = [...shell.matchAll(HOLE)];\n const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });\n if (holes.length === 0) {\n return new Response(request.method === 'HEAD' ? null : shell, { headers });\n }\n // The bodies are for the user who asks, so the response is not cached for everyone.\n headers.set('cache-control', 'private, no-cache');\n headers.append('vary', 'x-brumate-defer');\n headers.append('vary', 'x-brumate-base');\n const marked = shell.replace(HOLE, (template) => `${template} b-hole`);\n async function loadBody([, at, boundary, base]: RegExpExecArray): Promise<string> {\n const asked = new Headers(request.headers);\n asked.set('x-brumate-defer', `${boundary} ${at}`);\n asked.set('x-brumate-base', base!);\n try {\n const answer = await handleRoute(tree, new Request(request.url, { headers: asked }), {\n ...options,\n shell: undefined,\n event: undefined,\n });\n return answer?.ok && answer.headers.get('x-brumate-defer') === boundary\n ? await answer.text()\n : '';\n } catch (error) {\n logError(error, 'defer', options.event?.errors ?? errorSink(options.onError), options.event);\n return '';\n }\n }\n const bodies: Promise<string>[] = [];\n for (const hole of holes) {\n bodies.push(loadBody(hole));\n }\n const body = new ReadableStream<string>({\n async start(controller) {\n controller.enqueue(marked);\n // Each body as it is ready, so a slow one does not hold back the others.\n const pending = new Map<number, Promise<{ html: string; index: number }>>();\n for (const [index, promise] of bodies.entries()) {\n pending.set(\n index,\n promise.then((html) => ({ html, index })),\n );\n }\n while (pending.size > 0) {\n // oxlint-disable-next-line no-await-in-loop -- The bodies stream in the order they are ready.\n const { html, index } = await Promise.race(pending.values());\n pending.delete(index);\n if (html) {\n controller.enqueue(html);\n }\n }\n controller.close();\n },\n }).pipeThrough(new TextEncoderStream());\n return new Response(request.method === 'HEAD' ? null : body, { headers });\n}\n\n/** A response with more headers, such as cookies that middleware set. */\nfunction withHeaders(answer: Response, headers: Headers): Response {\n // A rendered page has them already.\n const sent = new Set(answer.headers.getSetCookie());\n const cookies: string[] = [];\n for (const cookie of headers.getSetCookie()) {\n if (!sent.has(cookie)) {\n cookies.push(cookie);\n }\n }\n if (cookies.length === 0) {\n return answer;\n }\n // A response can have headers that cannot change, such as one from `Response.redirect`.\n const result = respond(answer.body, answer);\n for (const cookie of cookies) {\n result.headers.append('set-cookie', cookie);\n }\n // A cookie is for one user, so a page with it is not cached for everyone.\n if (/^\\s*public\\b/.test(result.headers.get('cache-control') ?? '')) {\n result.headers.set('cache-control', 'private, no-cache');\n }\n return result;\n}\n\nasync function routeAnswer(\n tree: RouteNode,\n match: RouteMatch | undefined,\n url: URL,\n options: RouteOptions,\n): Promise<Response | undefined> {\n const event = options.event!;\n const { request } = event;\n // The body of a `#defer` block from a page of another build: its boundaries may differ.\n if (deferTarget(request) && isSkewed(request, options.build)) {\n return skewAnswer(options.build!);\n }\n if (!match) {\n const missing = notFound(tree);\n if (missing.errors.length === 0 && missing.middleware.length === 0 && !options.middleware) {\n return undefined;\n }\n return runEntry(options.middleware, event, () =>\n runMiddleware(missing.middleware, request, event, async () => {\n const page = await renderError(\n missing.errors,\n { message: 'Not found', status: 404 },\n {},\n request,\n options,\n );\n return page ?? new Response('Not found', { status: 404 });\n }),\n );\n }\n // A post from another site is refused before any middleware runs.\n const refused = await readAction(url, event, options);\n if (refused) {\n return refused;\n }\n return runEntry(options.middleware, event, () =>\n runMiddleware(match.middleware, request, event, () =>\n answerRoute(match, request, url, options),\n ),\n );\n}\n\n/** Answers a request that a route matches, after its middleware. `url` is the URL of the request. */\nasync function answerRoute(\n match: RouteMatch,\n request: Request,\n url: URL,\n options: RouteOptions,\n): Promise<Response> {\n if (match.endpoint) {\n const endpoint = await match.endpoint();\n const handler =\n endpoint[request.method] ?? (request.method === 'HEAD' ? endpoint.GET : undefined);\n if (handler) {\n try {\n return await withEvent(options.event, () => handler(request, match.params));\n } catch (error) {\n // A redirect is an answer, and so is a `ServerError`, which `logError` leaves out.\n if (!isRedirect(error) && options.event?.errors) {\n logError(error, 'endpoint', options.event.errors, options.event);\n }\n throw error;\n }\n }\n if (match.view.load === missingPage || request.method !== 'GET') {\n const allow: string[] = [];\n for (const name of Object.keys(endpoint)) {\n if (/^[A-Z]+$/.test(name)) {\n allow.push(name);\n }\n }\n return new Response('Method not allowed', {\n status: 405,\n headers: { allow: allow.join(', ') },\n });\n }\n }\n const event = options.event!;\n const call = event.call;\n // A form that posts to a page runs the middleware of its function's file, as a call does.\n return runEntry(call && options.fileMiddleware?.[call.id], event, () =>\n renderRoute(match, request, url, options),\n );\n}\n\n/** Runs the server function that a form posted to the page, if any, and renders the page. */\nasync function renderRoute(\n match: RouteMatch,\n request: Request,\n url: URL,\n options: RouteOptions,\n): Promise<Response> {\n let actions: Map<unknown, unknown> | undefined;\n const event = options.event!;\n if (event.call) {\n const outcome = await runAction(options.functions![event.call.id]!, event);\n if ('answer' in outcome) {\n return outcome.answer;\n }\n actions = outcome.actions;\n }\n // A page that the server kept, for a request that has not read the user so far. Middleware\n // ran before, so a check of access still runs.\n const keep =\n !event.call &&\n !options.dev &&\n options.pageCache !== false &&\n event.kind === 'page' &&\n (request.method === 'GET' || request.method === 'HEAD');\n const key = keep ? pageKey(url, request, options.build) : undefined;\n if (key && !event.personal) {\n const kept = await keptPage(key);\n if (kept) {\n return kept;\n }\n }\n try {\n const view = await resolveView(match.view);\n const response = await renderPage(view, { params: match.params }, request, options, {\n actions,\n });\n if (key && /^\\s*public\\b/.test(response.headers.get('cache-control') ?? '')) {\n await keepPage(key, response, event);\n }\n return response;\n } catch (error) {\n if (isRedirect(error)) {\n return new Response(null, {\n status: error.status,\n headers: { location: new URL(error.location, url).href },\n });\n }\n if (options.dev && !(error instanceof ServerError)) {\n logError(error, options.event?.kind ?? 'page', options.event?.errors, options.event);\n throw error;\n }\n const page = await renderError(\n match.errors,\n errorAnswer(error, 'Something went wrong', options.event?.kind ?? 'page', options.event),\n match.params,\n request,\n options,\n );\n if (page) {\n return page;\n }\n throw error;\n }\n}\n\n/**\n * Renders an object of attributes. A handler in it, such as an `onClick`\n * that a component passes on with `...rest`, goes into `on` as a `b-on`\n * entry: the client function that it refers to, with the scope that the\n * function belongs to and the modifiers of its wrappers. A function that\n * refers to nothing in the browser is left out.\n */\nexport function spread(\n attributes: Record<string, unknown>,\n on?: string[],\n names?: boolean,\n): string | Promise<string> {\n // A promise among the values renders once they settle, as an attribute does.\n for (const value of Object.values(attributes)) {\n if (isThenable(value)) {\n const keys = Object.keys(attributes);\n return Promise.all(Object.values(attributes)).then((values) => {\n const resolved: Record<string, unknown> = {};\n for (const [index, name] of keys.entries()) {\n resolved[name] = values[index];\n }\n return spread(resolved, on, names);\n });\n }\n }\n // The `b-on` of a dynamic tag that names a component reaches the component as a prop, and\n // its handlers come first, as the element's own.\n const entries = on && ownValue('b-on', attributes['b-on']);\n if (typeof entries === 'string') {\n on!.unshift(entries);\n const { 'b-on': _, ...rest } = attributes;\n return spread(rest, on, names) as string;\n }\n for (const [name, value] of Object.entries(attributes)) {\n // A merged handler writes one entry for each of its parts.\n const parts =\n on && /^on[A-Z]/.test(name) && typeof value === 'function'\n ? ((value as { [PARTS]?: object[] })[PARTS] ?? [value])\n : [];\n for (const part of parts) {\n const reference = functionReferences.get(part);\n if (reference) {\n const modifiers = (part as { [MODIFIERS]?: string[] })[MODIFIERS];\n on!.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));\n }\n }\n // A binding that a rest prop passed on writes its slot, or calls its setter.\n if (on && (name === 'value' || name === 'checked') && isBinding(value)) {\n const setter =\n typeof value.set === 'function' ? functionReferences.get(value.set) : undefined;\n on.push(bindEntry(name, value.ref, setter));\n }\n }\n return spreadAttributes(attributes, names);\n}\n\nexport { onAttribute };\n"],"mappings":";;;;;;;;;;;;AAqDA,MAAa,WAAuE,CAAC;;AAsBrF,SAAgB,UAAU,SAAgE;CACxF,OAAO,WAAW;EAAE;EAAS,yBAAS,IAAI,QAAQ;CAAE;AACtD;AAiBA,SAAS,UAAgB,CAAC;;AAG1B,SAAgB,WAAc,OAAU,KAAoC;CAC1E,MAAM,WAAW;CACjB,IAAI,YAAY,OAAO,SAAS,SAAS,YACvC,SAAS,WACD,IAAI,SACJ,IAAI,IAAI,CAChB;MAEA,IAAI;CAEN,OAAO;AACT;;AAGA,MAAM,2BAAW,IAAI,IAAI,CAAC,UAAU,eAAe,CAAC;;;;;AAMpD,SAAS,cAAc,SAAkB,MAAwB;CAC/D,MAAM,MAAM,QAAQ,IAAI,KAAK,OAAO;CACpC,MAAM,MAAM,QAAQ,IAAI,KAAK,OAAO;CACpC,OAAO,OAAO,SAAS;EACrB,MAAM,SAAiB;GACrB,IAAI,SAAS,IAAI,KAAK,YAAY,CAAC,GACjC,KAAK;GAEP,OAAO,IAAI,IAAI;EACjB;EACA,MAAM,SAAiB;GACrB,IAA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