brumate 0.1.0 → 0.2.0

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 (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-BBLPU9JR.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +79 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-CRZlO11T.js → inspect-BJtACnQp.js} +928 -91
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-BBLPU9JR.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-CRZlO11T.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-DZsgnPKS.js","names":[],"sources":["../src/runtime/request.ts","../src/runtime/router.ts","../src/runtime/validate.ts","../src/runtime/server.ts"],"sourcesContent":["import { toJSON } from 'seroval';\nimport { deleteCookie, getCookies, setCookie } from './cookies.ts';\nimport type { CookieOptions } from './cookies.ts';\nimport { disabledFeatures, plugins } from './serial.ts';\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 */\nexport class RequestEvent {\n readonly request: Request;\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 constructor(request: Request) {\n this.request = request;\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/**\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/**\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 * 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.\nexport function dedupe<F extends (...args: any[]) => unknown>(fn: F, id: string): F {\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, disabledFeatures }))}`;\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, fn(...args));\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","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 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 wrapperOf(\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 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 = wrapperOf(node, segments, index, params, path);\n const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;\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 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 = pathname\n .split('/')\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\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, wrapperOf(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 { 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 = issue.path.map((segment) => {\n const key = typeof segment === 'object' && segment !== null ? segment.key : segment;\n return 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 return { issues: result.issues.map(plainIssue) };\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/** Names that would change the prototype of an object, or reach the one of its constructor. */\nconst FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Turns the entries of a form into a plain object:\n *\n * - A name that appears once holds its value.\n * - A name that appears more than once holds an array of its values.\n * - A name that ends with `[]` always holds an array, under the name without `[]`.\n * - Dots nest objects: `address.city` is `{ address: { city } }`.\n * - Values stay strings and files.\n *\n * A name with an empty part, a part such as `__proto__`, or one that needs\n * an object where another field holds a value, is an issue, and the schema\n * does not run.\n */\nfunction formValues(form: FormData): ParseResult<Record<string, unknown>> {\n const root: Record<string, unknown> = {};\n // The objects and arrays that this function made, so a field value is never taken for one.\n const objects = new Set<unknown>([root]);\n const arrays = new Set<unknown>();\n const issues: ValidationIssue[] = [];\n for (const [name, value] of form) {\n const list = name.endsWith('[]');\n const parts = (list ? name.slice(0, -2) : name).split('.');\n if (parts.some((part) => part === '' || FORBIDDEN.has(part))) {\n issues.push({ message: 'The form has a field name that is not allowed' });\n continue;\n }\n let target = root;\n let conflict = false;\n for (const part of parts.slice(0, -1)) {\n const next = Object.hasOwn(target, part) ? target[part] : undefined;\n if (next === undefined) {\n const child: Record<string, unknown> = {};\n objects.add(child);\n target[part] = child;\n target = child;\n } else if (objects.has(next)) {\n target = next as Record<string, unknown>;\n } else {\n conflict = true;\n break;\n }\n }\n const last = parts.at(-1)!;\n const current = Object.hasOwn(target, last) ? target[last] : undefined;\n if (conflict || objects.has(current)) {\n issues.push({ message: `Field \"${name}\" conflicts with another field`, path: parts });\n } else if (arrays.has(current)) {\n (current as unknown[]).push(value);\n } else if (current !== undefined || list) {\n const values = current === undefined ? [value] : [current, value];\n arrays.add(values);\n target[last] = values;\n } else {\n target[last] = value;\n }\n }\n return issues.length > 0 ? { issues } : { value: root };\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","import { crossSerializeStream, fromJSON } from 'seroval';\nimport type { SerovalJSON } from 'seroval';\nimport {\n VOID_ELEMENTS,\n actionAttributes,\n escape,\n escapeAttribute,\n insertValue,\n isRaw,\n rawHTML,\n spread,\n styleElement,\n} from './html.ts';\nimport type { Raw } from './html.ts';\nimport { disabledFeatures, plugins } from './serial.ts';\nimport {\n CHILDREN,\n ElementReference,\n FunctionReference,\n ITEM,\n ITEM_SLOT,\n MODULE,\n OWNER,\n SOURCE,\n isAsyncIterable,\n} from './shared.ts';\nimport { Upload, functionReferences, replaceDeep } from './calls.ts';\nimport { STREAM_TYPE, toChunkStream } from './stream.ts';\nimport type { PackedState, PageState, ScopeState } from './shared.ts';\nimport { Redirect, RequestEvent, ServerError, isRedirect, unwrap, withEvent } from './request.ts';\nimport type { Context as ContextValue } from './context.ts';\n\nexport {\n affix,\n attribute,\n classAttribute,\n escape,\n escapeAttribute,\n raw,\n spread,\n vars,\n} from './html.ts';\nexport type { Raw } from './html.ts';\nexport { produce } from './produce.ts';\nexport { createContext } 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 getEvent,\n isRedirect,\n redirect,\n withEvent,\n} from './request.ts';\nexport type { Redirect } from './request.ts';\nexport { ValidationError, fieldErrors, parse, parseForm, safeParse } from './validate.ts';\nexport type { ParseResult, ValidationIssue } from './validate.ts';\nexport type { StandardSchemaV1 } from './standard-schema.ts';\nexport { createSession, parseCookies, serializeCookie, toNodeHeaders } from './cookies.ts';\nexport type { CookieOptions, Session, SessionOptions } from './cookies.ts';\nexport { ElementReference, FunctionReference };\nexport type { PageState, ScopeState };\n\n/** The scope and the slot that hold the list of a list item. */\nexport type ItemSource = readonly [scope: number, slot: number];\n\n/** A `#loading` body that renders after the rest of the page. */\ninterface Boundary {\n id: number;\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}\n\n/** A point in a render that `restore` goes back to. */\nexport interface Mark {\n scope: number;\n undo: number;\n owner: number | undefined;\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 readonly state: PageState = {};\n private readonly root: Context;\n private nextScope = 0;\n private nextBoundary = 0;\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 private onBoundary: ((boundary: Boundary) => void) | undefined;\n /** The scope tree of the whole page, for finding contexts across `#loading` bodies. */\n private readonly tree = new Map<number, { parent?: number; values?: Map<string, unknown> }>();\n /** The scope that renders the next component, which becomes its owner. */\n private owner: number | undefined;\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 names of the slots of each scope, so an error can name a value that cannot be sent. */\n readonly slotNames: Map<number, string[]> = new Map();\n\n /** Results of server functions that a form posted to this page, for `$action`. */\n actions: Map<unknown, unknown> = new Map();\n /** The request of the page, when it renders with one. */\n event: RequestEvent | 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 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 /** 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 constructor(root?: Context, rpc?: string, base = 0) {\n this.root = root ?? this;\n if (rpc) {\n this.rpcPrefix = rpc;\n }\n this.nextScope = base;\n this.nextBoundary = base;\n }\n\n /** A number above every scope and boundary ID so far, so a later render can start there. */\n next(): number {\n return Math.max(this.root.nextScope, this.root.nextBoundary);\n }\n\n /** Returns the URL prefix of server function calls. */\n rpc(): string {\n return this.root.rpcPrefix;\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?: number, module?: string): number {\n const root = this.root;\n const id = root.nextScope++;\n const record = this.record(id);\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 root.tree.set(id, { parent: up });\n return id;\n }\n\n /** The ID that `$id()` makes: the scope's ID and the position of the call. */\n id(scope: number, index: number): string {\n return `b${scope}-${index}`;\n }\n\n /** Sets the owner of the next component's root scope. */\n own(scope: number): 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: number): void {\n const node = this.root.tree.get(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 that provides it, starting at\n * `scope`. With `slot`, records which slot holds it, so the client can\n * update it when the provided value changes.\n */\n consume<T>(context: ContextValue<T>, scope: number, slot?: number): T {\n if (slot !== undefined) {\n const record = this.record(scope);\n record.x ??= {};\n record.x[context.key] = slot;\n }\n for (let id: number | undefined = scope; id !== undefined;) {\n const node = this.root.tree.get(id);\n if (node?.values?.has(context.key)) {\n return node.values.get(context.key) as T;\n }\n id = node?.parent;\n }\n return context.defaultValue;\n }\n\n /** The ID that the next call to `scope()` returns. */\n peek(): number {\n return this.root.nextScope;\n }\n\n /** Marks the render so far, such as before a `#try` body, for `restore`. */\n mark(): Mark {\n return { scope: this.root.nextScope, undo: this.undo.length, owner: this.root.owner };\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.scope);\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(from: number): void {\n for (const key of Object.keys(this.state)) {\n const id = Number(key);\n if (id >= from) {\n delete this.state[id];\n this.root.slotNames.delete(id);\n this.root.tree.delete(id);\n this.sources.delete(id);\n }\n }\n }\n\n private record(scope: number): ScopeState {\n this.state[scope] ??= {};\n return this.state[scope];\n }\n\n slots(scope: number, values: unknown[], names?: string[]): void {\n this.record(scope).s = values;\n if (names) {\n this.root.slotNames.set(scope, names);\n }\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 readonly sources: Map<number, ItemSource> = new Map();\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: number, value: unknown, source?: ItemSource): void {\n this.record(scope).i = value;\n if (source) {\n this.sources.set(scope, source);\n }\n }\n\n /** Records the scope of a child component at an anchor of its parent. */\n link(scope: number, anchor: number, child: number): 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 /** Returns the reference that a `ref` signal holds on the server. */\n element(scope: number, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n }\n\n /** Marks a function as a client function, so it serializes as a reference. */\n fn<T>(value: T, ref: string, scope: number): T {\n if (typeof value === 'function') {\n functionReferences.set(value, new FunctionReference(ref, scope));\n }\n return value;\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 /** Sets the title of the page. The last call wins. */\n title(value: unknown): void {\n const target = this.root.sent ? this : this.root;\n const previous = target.pageTitle;\n const title = value === null || value === undefined ? '' : String(value);\n target.pageTitle = title;\n this.undo.push(() => {\n if (target.pageTitle === title) {\n target.pageTitle = previous;\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 const title =\n this.root.pageTitle === undefined ? '' : `<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 /** Returns the ID of a new `#loading` boundary. */\n boundary(): number {\n return this.root.nextBoundary++;\n }\n\n /** Renders a `#loading` body after the rest of the page, in its own context. */\n defer(id: number, renderBody: (ctx: Context) => Promise<string>): void {\n const child = new Context(this.root);\n const boundary: Boundary = {\n id,\n render: renderBody(child).then((html) => ({ html, ctx: child })),\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}\n\n/** Declares a memo. Its value is computed when it is first read. */\nexport function memo<T>(compute: () => T, ctx?: Context): Memo<T> {\n return { compute, ctx, state: 'idle' };\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 node.load = Promise.resolve(value)\n .then(firstValue)\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\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]: (ctx: Context, scope: number | undefined) => Promise<string>;\n}\n\n/** Makes markup that renders where it is inserted, such as the children of a layout. */\nexport function lazy(renderAt: (ctx: Context, scope: number | undefined) => Promise<string>): 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 return actionAttributes(ctx.rpc(), name, id, method, result);\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` and `scope` are where it is\n * inserted, for markup that renders there.\n */\nexport function insert(value: unknown, ctx?: Context, scope?: number): 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));\n }\n if (isLazy(value) && ctx) {\n return value[LAZY](ctx, scope);\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => insert(item, ctx, scope));\n return parts.every((part) => typeof part === 'string')\n ? parts.join('')\n : Promise.all(parts).then((all) => all.join(''));\n }\n return insertValue(value);\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Components take any props.\nexport type Component<P = any> = (props: P, ctx: Context) => Promise<string>;\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?: number,\n anchor?: number,\n): Promise<string> {\n if (scope !== undefined && anchor !== undefined) {\n ctx.link(scope, anchor, ctx.peek());\n }\n if (scope !== undefined) {\n ctx.own(scope);\n }\n return Child(props, ctx);\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 children: Raw | undefined,\n ctx: Context,\n scope?: number,\n): string | Promise<string> {\n if (typeof tag === 'function') {\n return component(tag, children ? { ...attributes, children } : attributes, ctx, scope);\n }\n const open = `<${tag}${spread(attributes)}>`;\n if (VOID_ELEMENTS.has(tag)) {\n return open;\n }\n return `${open}${children && isRaw(children) ? rawHTML(children) : ''}</${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 const items =\n value instanceof Map\n ? [...value.keys(), ...value.values()]\n : value instanceof Set\n ? [...value]\n : Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype\n ? Object.values(value)\n : [];\n return items.some((item) => holds(item, target, seen));\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 target = (error as { value?: unknown }).value;\n if (target === undefined) {\n return error instanceof Error ? error : new Error(String(error));\n }\n for (const [id, record] of Object.entries(ctx.state)) {\n const index = (record.s ?? []).findIndex((value) => holds(value, target));\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.state[owner.p];\n }\n const name = ctx.slotNames.get(Number(id))?.[index] ?? `slot ${index}`;\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/** 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/** A group of `PackedState` while `packState` collects it. */\ninterface PackGroup {\n k: number;\n base: number;\n flags: number;\n count: number;\n m: string | undefined;\n ids: number[];\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 state: PageState,\n sources: Map<number, ItemSource>,\n group: PackGroup,\n): ItemSource | undefined {\n const source = sources.get(group.ids[0]!);\n if (!source || !(group.flags & (ITEM | ITEM_SLOT))) {\n return undefined;\n }\n const value = state[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 = Array.isArray(value) ? value : value instanceof Set ? Array.from(value) : undefined;\n if (!list || list.length < group.ids.length) {\n return undefined;\n }\n for (let n = 0; n < group.ids.length; n++) {\n const id = group.ids[n]!;\n if (sources.get(id) !== source || !Object.is(list[n], state[id]!.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(state: PageState, sources?: Map<number, ItemSource>): PackedState {\n const result: PackedState = {};\n const groups = new Map<string, PackGroup>();\n // Integer keys come in ascending order, so the gaps are positive.\n for (const [key, record] of Object.entries(state)) {\n const id = Number(key);\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 const base = record.p ?? (record.o === undefined ? undefined : id - record.o);\n if (\n record.k === undefined ||\n base === undefined ||\n (record.p !== undefined && record.o !== undefined) ||\n !Object.keys(record).every((field) => PACKED_FIELDS.has(field))\n ) {\n result[id] = record;\n continue;\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 const name = `${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ''}`;\n const group = groups.get(name);\n if (group) {\n group.ids.push(id);\n } else {\n groups.set(name, { k: record.k, base, flags, count: slots.length, m: record.m, ids: [id] });\n }\n }\n const packed: unknown[][] = [];\n for (const group of groups.values()) {\n const { ids } = group;\n // A group of one scope is no shorter than its record.\n if (ids.length === 1) {\n result[ids[0]!] = state[ids[0]!]!;\n continue;\n }\n const source = sources && sources.size > 0 ? groupSource(state, sources, group) : undefined;\n const flags = source ? group.flags | SOURCE : group.flags;\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 // 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 let last = flags & OWNER ? 0 : group.base;\n for (const id of ids) {\n const record = state[id]!;\n values.push(id - last);\n const slots = record.s ?? [];\n for (let n = from; n < slots.length; n++) {\n values.push(slots[n]);\n }\n if (item) {\n values.push(record.i);\n }\n if (flags & CHILDREN) {\n values.push(record.c);\n }\n last = id;\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 */\nfunction serializeState(\n state: PageState,\n refs: Map<unknown, number>,\n onRecord: (code: string, initial: boolean) => void,\n onError: (error: unknown) => void,\n onDone: () => void,\n sources?: Map<number, ItemSource>,\n): void {\n crossSerializeStream(packState(state, sources), {\n plugins,\n disabledFeatures,\n refs,\n onSerialize: onRecord,\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,\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. */\n root?: number;\n /** The Content Security Policy nonce of the script. */\n nonce?: 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 // 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 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.\nconst HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h=\"'+i+'\"]');e&&(document.head.append(e.content),e.remove());t!=null&&(document.title=t)}`;\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\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\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 const 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 URL prefix of server function calls, for forms that post to one. Defaults to `/_brumate`. */\n rpc?: string;\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 /** 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 * 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\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 const event = options.event ?? (options.request ? new RequestEvent(options.request) : undefined);\n ctx.event = event;\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));\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 const pending = (): Queue<string> => (queue ??= createQueue<string>());\n // Records share references, so later records can point into earlier ones.\n const refs = new Map<unknown, number>();\n const { nonce, base: root } = options;\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 const finish = (): void => {\n open--;\n if (open === 0) {\n queue?.close();\n }\n };\n const serialize = (\n { state, sources }: Context,\n onScopes: (script: string) => void,\n route?: string,\n onError: (error: unknown) => void = (error) => pending().fail(error),\n ): void => {\n open++;\n serializeState(\n state,\n refs,\n (code, initial) => {\n if (initial) {\n onScopes(\n stateScript(code, true, { next: ctx.next(), route, root, nonce, define: first }),\n );\n first = false;\n } else {\n pending().push(stateScript(code, false, { root, nonce }));\n }\n },\n onError,\n finish,\n sources,\n );\n };\n\n ctx.watch((boundary) => {\n open++;\n boundary.render.then(\n (result) => {\n // A `#try` body around it failed, so the page has no markers for it.\n if (boundary.cancelled) {\n finish();\n return;\n }\n serialize(result.ctx, (script) => {\n let call = `${swap ? '' : SWAP}$bS(${boundary.id})`;\n swap = true;\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(${boundary.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 (error: unknown) => {\n // The fallback stays in the page.\n console.error(error);\n finish();\n },\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 );\n if (failure !== undefined) {\n throw unsendable(failure, ctx);\n }\n return {\n html,\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 };\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;\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 start = typeof options.start === 'function' ? options.start(head) : (options.start ?? '');\n return start + 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 = 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 return new ReadableStream<string>({\n async start(controller) {\n try {\n await writeParts(await getParts(), options, controller);\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\nasync function writeParts(\n parts: RenderResult,\n options: DocumentOptions,\n controller: ReadableStreamDefaultController<string>,\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 controller.enqueue(chunk);\n }\n }\n controller.close();\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(error: unknown, fallback: string): { message: string; status: number } {\n if (error instanceof ServerError) {\n return { message: error.message, status: error.status };\n }\n console.error(error);\n return { message: fallback, status: 500 };\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 * 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 // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n fn: (...args: any[]) => unknown,\n request: Request,\n event: RequestEvent,\n headers: Headers,\n base?: string,\n): Promise<{ result: unknown } | { answer: Response }> {\n try {\n const form = await request.formData();\n return { result: await withEvent(event, () => fn(form)) };\n } catch (error) {\n if (error instanceof Redirect) {\n headers.set('location', base ? new URL(error.location, base).href : error.location);\n return { answer: new Response(null, { status: error.status, headers }) };\n }\n const { message, status } = errorAnswer(error, 'The server function failed');\n headers.set('content-type', 'text/plain; charset=utf-8');\n return { answer: new Response(message, { status, headers }) };\n }\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(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n fn: (...args: any[]) => unknown,\n request: Request,\n event: RequestEvent,\n): Promise<Response> {\n const { headers } = event;\n const outcome = await callWithForm(fn, request, event, headers);\n if ('answer' in outcome) {\n return outcome.answer;\n }\n headers.set('location', request.headers.get('referer') ?? '/');\n return new Response(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>`, where an `Upload` 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 disabledFeatures,\n });\n }\n const form = await request.formData();\n const args = fromJSON<unknown[]>(JSON.parse(String(form.get('args'))) as SerovalJSON, {\n plugins,\n disabledFeatures,\n });\n return replaceDeep(args, (value) =>\n value instanceof Upload ? (form.get(`file${value.index}`) ?? undefined) : undefined,\n ) as unknown[];\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\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 const fn = functions[id];\n if (!fn) {\n return unknownAnswer(id);\n }\n const event = new RequestEvent(request);\n // The function runs with its event, so `getEvent()` before its first await returns it.\n const invoke = (args: unknown[]): unknown => withEvent(event, () => fn(...args));\n // A call with files sends its arguments as form data, with this header.\n if (isFormPost(request) && !request.headers.has('x-brumate-args')) {\n // The loader sends a form of an `$action` with this header, and wants the result, not a page.\n if (!request.headers.has('x-brumate-result')) {\n return handleForm(fn, request, event);\n }\n const form = await request.formData();\n return answerCall(functions, event, async () => invoke([form]));\n }\n // Arguments that fail to read, such as a regular expression, answer as an error of the call.\n return answerCall(functions, event, async () => invoke(await readArgs(request)));\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 = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));\n if (ids.length > 0) {\n headers.set('x-brumate-refresh', ids.join(','));\n }\n }\n headers.set('content-type', STREAM_TYPE);\n return new Response(toChunkStream(result), { headers });\n } catch (error) {\n if (error instanceof Redirect) {\n headers.set('x-brumate-redirect', error.location);\n return new Response(null, { status: 204, headers });\n }\n const { message, status } = errorAnswer(error, 'The server function failed');\n headers.set('content-type', 'application/json');\n return new Response(JSON.stringify({ error: message }), { status, headers });\n }\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}\n\n/** Imports every module of a matched route before it renders. */\nasync function resolveView(view: RouteView): Promise<ResolvedView> {\n const [module, loading, ...slots] = await Promise.all([\n view.load(),\n view.loading?.(),\n ...Object.values(view.slots).map(resolveView),\n ]);\n const names = Object.keys(view.slots);\n return {\n key: view.key,\n component: module.default,\n loading: loading?.default,\n slots: Object.fromEntries(names.map((name, index) => [name, slots[index]!])),\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: number | 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 */\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 * 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\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 request: Request,\n id: string,\n options: RouteOptions,\n event: RequestEvent,\n): Promise<{ actions: Map<unknown, unknown> } | { answer: Response }> {\n if (isCrossSite(request, options)) {\n return { answer: crossSiteAnswer() };\n }\n const fn = options.functions?.[id];\n if (!fn) {\n return { answer: unknownAnswer(id) };\n }\n const outcome = await callWithForm(fn, request, event, new Headers(), request.url);\n return 'answer' in outcome ? outcome : { actions: new Map([[fn, outcome.result]]) };\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 parts = await render(\n viewComponent(view, props),\n {},\n {\n ...options,\n request,\n actions: extra.actions,\n route: view.key,\n base: Number.isSafeInteger(base) && base > 0 ? base : undefined,\n },\n );\n const headers = new Headers(parts.headers);\n headers.set('content-type', 'text/html; charset=utf-8');\n const body = streamParts(parts, options).pipeThrough(new TextEncoderStream());\n return new Response(body, { status: extra.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 console.error(failure);\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 // 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 = options.event ?? new RequestEvent(request);\n const answer = await routeAnswer(tree, request, { ...options, event });\n return answer && withHeaders(answer, event.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 = headers.getSetCookie().filter((cookie) => !sent.has(cookie));\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 = new Response(answer.body, answer);\n for (const cookie of cookies) {\n result.headers.append('set-cookie', cookie);\n }\n return result;\n}\n\nasync function routeAnswer(\n tree: RouteNode,\n request: Request,\n options: RouteOptions,\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const match = matchRoute(tree, url.pathname);\n if (!match) {\n const missing = notFound(tree);\n if (missing.errors.length === 0 && missing.middleware.length === 0) {\n return undefined;\n }\n return runMiddleware(missing.middleware, request, options.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 return runMiddleware(match.middleware, request, options.event!, () =>\n answerRoute(match, request, url, options),\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 return withEvent(options.event, () => handler(request, match.params));\n }\n if (match.view.load === missingPage || request.method !== 'GET') {\n const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));\n return new Response('Method not allowed', {\n status: 405,\n headers: { allow: allow.join(', ') },\n });\n }\n }\n let actions: Map<unknown, unknown> | undefined;\n const posted = url.searchParams.get('__action');\n if (request.method === 'POST' && posted !== null) {\n const outcome = await runAction(request, posted, options, options.event!);\n if ('answer' in outcome) {\n return outcome.answer;\n }\n actions = outcome.actions;\n }\n try {\n const view = await resolveView(match.view);\n return await renderPage(view, { params: match.params }, request, options, { actions });\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 throw error;\n }\n const page = await renderError(\n match.errors,\n errorAnswer(error, 'Something went wrong'),\n match.params,\n request,\n options,\n );\n if (page) {\n return page;\n }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Y,MAAM,IAAI,GACX,EAAE,QAAQ,MAAM,OAAO,GAAG,SAAS,SAAS,EAAE,QAAQ,CAAC;CACvF,SAAS,OAAO;EACd,IAAI,WAAW,KAAK,GAClB,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ,MAAM;GACd,SAAS,EAAE,UAAU,IAAI,IAAI,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK;EACzD,CAAC;EAEH,IAAI,QAAQ,OAAO,EAAE,iBAAiB,cACpC,MAAM;EAER,MAAM,OAAO,MAAM,YACjB,MAAM,QACN,YAAY,OAAO,sBAAsB,GACzC,MAAM,QACN,SACA,OACF;EACA,IAAI,MACF,OAAO;EAET,MAAM;CACR;AACF"}
@@ -1,40 +0,0 @@
1
- import { f as raw } from "./html-DEeoepg3.js";
2
- //#region src/runtime/shared.ts
3
- /** An element that the server rendered. The client finds it by its anchor. */
4
- var ElementReference = class {
5
- scope;
6
- anchor;
7
- constructor(scope, anchor) {
8
- this.scope = scope;
9
- this.anchor = anchor;
10
- }
11
- };
12
- /** A client function: an export of a client module, and the scope it reads. */
13
- var FunctionReference = class {
14
- /** `<component id>#<export name>`. */
15
- ref;
16
- scope;
17
- constructor(ref, scope) {
18
- this.ref = ref;
19
- this.scope = scope;
20
- }
21
- };
22
- /**
23
- * Makes the values of brumate's plugins. A state record calls them as `$b`,
24
- * with one letter each, and the plugins read nodes of server function calls
25
- * with them too, so both give the same values.
26
- */
27
- const stateValues = {
28
- e: (scope, anchor) => new ElementReference(scope, anchor),
29
- f: (ref, scope) => new FunctionReference(ref, scope),
30
- r: raw,
31
- c: (id) => Object.assign(() => "", { brumateId: id })
32
- };
33
- /** True for a value that `for await` reads, such as the result of an async generator. */
34
- function isAsyncIterable(value) {
35
- return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
36
- }
37
- //#endregion
38
- export { stateValues as i, FunctionReference as n, isAsyncIterable as r, ElementReference as t };
39
-
40
- //# sourceMappingURL=shared-CWYOd0H3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-CWYOd0H3.js","names":[],"sources":["../src/runtime/shared.ts"],"sourcesContent":["// Values and types that the server and the browser share. It does not import\n// seroval, so the core, which reads the page state without it, stays small.\n// The plugins that write and read these values are in `serial.ts`.\n\nimport { raw } from './html.ts';\nimport type { Raw } from './html.ts';\n\n/** An element that the server rendered. The client finds it by its anchor. */\nexport class ElementReference {\n readonly scope: number;\n readonly anchor: number;\n\n constructor(scope: number, anchor: number) {\n this.scope = scope;\n this.anchor = anchor;\n }\n}\n\n/** A client function: an export of a client module, and the scope it reads. */\nexport class FunctionReference {\n /** `<component id>#<export name>`. */\n readonly ref: string;\n readonly scope: number;\n\n constructor(ref: string, scope: number) {\n this.ref = ref;\n this.scope = scope;\n }\n}\n\n/** A component, which the compiler marks with its ID. */\nexport type ComponentValue = ((...args: never[]) => unknown) & { brumateId: string };\n\n/**\n * Makes the values of brumate's plugins. A state record calls them as `$b`,\n * with one letter each, and the plugins read nodes of server function calls\n * with them too, so both give the same values.\n */\nexport const stateValues: {\n /** An element that the server rendered, by its scope and anchor. */\n e: (scope: number, anchor: number) => ElementReference;\n /** A client function, by its reference and scope. */\n f: (ref: string, scope: number) => FunctionReference;\n /** HTML that the client may insert again. */\n r: (html: string) => Raw;\n /**\n * A component, such as the value of a dynamic tag. The client gets a\n * function with the same ID that renders nothing. The client code that\n * changes the value uses the component's render module instead.\n */\n c: (id: string) => ComponentValue;\n} = {\n e: (scope, anchor) => new ElementReference(scope, anchor),\n f: (ref, scope) => new FunctionReference(ref, scope),\n r: raw,\n c: (id) => Object.assign(() => '', { brumateId: id }),\n};\n\n/** True for a value that `for await` reads, such as the result of an async generator. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/** The state of one scope in the page. */\nexport interface ScopeState {\n /** The scope's ID in the compiled component. */\n k?: number;\n /** The ID of the scope that contains this one. Component root scopes have none. */\n p?: number;\n /** The component ID of a component's root scope. */\n m?: string;\n /** The item of a list item scope. */\n i?: unknown;\n /** The scope that rendered a component's root scope, for finding contexts. */\n o?: number;\n /** The values that the scope provides, by context key. */\n v?: Record<string, unknown>;\n /** The slots that hold the contexts that the scope reads, by context key. */\n x?: Record<string, number>;\n /** Slot values, in the order of the scope's layout. */\n s?: unknown[];\n /** The scope IDs of child components, by anchor index. */\n c?: Record<number, number>;\n}\n\n/** The state of a page, by scope ID. */\nexport type PageState = Record<number, ScopeState>;\n\n/**\n * The flags of a group of scope records in `PackedState`:\n * - `ITEM_SLOT`: the item of each scope is its first slot.\n * - `ITEM`: each scope has its item after its slots.\n * - `CHILDREN`: each scope has its child components after that.\n * - `OWNER`: the scopes are component root scopes. `base` is the distance from the scope that\n * rendered each one, `o`, to the scope, and the first gap is from 0. Otherwise `base` is the\n * parent, `p`, of every scope.\n * - `MODULE`: the group has the component ID of its scopes after its header.\n * - `SOURCE`: the scopes are the items of a list whose list is a slot of an enclosing scope.\n * The header ends with that scope's ID and the slot's index, and the items are not written:\n * the item of the scope at position `n` in the group is the value at `n` of the list, or of\n * `Array.from` of a Set. With `ITEM_SLOT`, each scope writes its slots after the first.\n */\nexport const ITEM_SLOT = 1;\nexport const ITEM = 2;\nexport const CHILDREN = 4;\nexport const OWNER = 8;\nexport const MODULE = 16;\nexport const SOURCE = 32;\n\n/**\n * The page state as the server writes it. Records of scopes that share their\n * kind, their parent or owner, and their shape are in one group of `g`,\n * such as the items of a list, instead of one object each. A group is a flat\n * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, ...scopes]`, and each scope\n * is its ID as the gap from the one before it (the first from `base`), its\n * slots, and then its item and its child components, as `flags` says.\n */\nexport type PackedState = PageState & { g?: unknown[][] };\n"],"mappings":";;;AAQA,IAAa,mBAAb,MAA8B;CAC5B;CACA;CAEA,YAAY,OAAe,QAAgB;EACzC,KAAK,QAAQ;EACb,KAAK,SAAS;CAChB;AACF;;AAGA,IAAa,oBAAb,MAA+B;;CAE7B;CACA;CAEA,YAAY,KAAa,OAAe;EACtC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;AAUA,MAAa,cAaT;CACF,IAAI,OAAO,WAAW,IAAI,iBAAiB,OAAO,MAAM;CACxD,IAAI,KAAK,UAAU,IAAI,kBAAkB,KAAK,KAAK;CACnD,GAAG;CACH,IAAI,OAAO,OAAO,aAAa,IAAI,EAAE,WAAW,GAAG,CAAC;AACtD;;AAGA,SAAgB,gBAAgB,OAAiD;CAC/E,OACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAAiC,OAAO,mBAAmB;AAEvE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"static-loader-ClNkHZGn.js","names":[],"sources":["../src/runtime/boot.ts","../src/runtime/static-loader.ts"],"sourcesContent":["// The loader's code that every page runs. `loader.ts` adds client navigation,\n// and `static-loader.ts` starts it without, so a site that turns navigation\n// off does not have its code, or the parts of the core that only it uses, in\n// its bundle.\n\nimport type * as Client from './client.ts';\nimport type { ClientModule } from './client.ts';\n\nexport interface LoaderOptions {\n /**\n * Imports the client module of a component, by component ID. Undefined for\n * a component that has no client code.\n */\n load: (id: string) => Promise<ClientModule> | undefined;\n /** The URL prefix of server function calls. */\n rpc?: string;\n /**\n * Loads pages without a full page load: links to the same origin, the back\n * and forward buttons, forms that post to a server function, and redirects\n * from server functions to the same origin. Defaults to true.\n */\n navigate?: boolean | NavigateOptions;\n /**\n * After the page loads, while the browser is idle, loads the core and the\n * code of the handlers of elements in or near the viewport, so a first\n * event needs no request. Elements with `data-prefetch=\"none\"` are left\n * out, and nothing loads when the browser asks to save data or the\n * connection is 2G. Defaults to true.\n */\n preload?: boolean;\n}\n\nexport interface NavigateOptions {\n /**\n * Swaps the page inside a view transition, where the browser has them.\n * CSS can tell links, the back and forward buttons and forms apart with\n * the types `push`, `traverse` and `form`. A redirect from a server\n * function has the type `form`.\n */\n transition?: boolean;\n}\n\ninterface Entry {\n raw: string;\n type: string;\n modifiers: string[];\n ref: string;\n}\n\n// Parsed `b-on` values, so repeated events do not parse them again.\nconst parsed = new Map<string, Entry[]>();\n\nexport function entries(element: Element): Entry[] {\n const value = element.getAttribute('b-on') ?? '';\n return (parsed.get(value) ??\n parsed\n .set(\n value,\n value\n .split(' ')\n .filter(Boolean)\n .map((entry) => {\n const [name, ref] = entry.split('=') as [string, string];\n const [type, ...modifiers] = name.split(':') as [string, ...string[]];\n return { raw: entry, type, modifiers, ref };\n }),\n )\n .get(value))!;\n}\n\n/** The `prefetch` strategy of an element, from its `data-prefetch`. */\nexport function strategy(element: Element): string {\n return element.getAttribute('data-prefetch') ?? 'hover';\n}\n\n/** The functions of the core that the loader calls. */\nexport type Core = (typeof Client)['loader'];\n\n/**\n * Imports the core. It reads one export by name, so a build keeps only it and\n * the helpers that compiled components call.\n */\nexport const importCore = (): Promise<Core> =>\n import('./client.ts').then((client) => client.loader);\n\n/** Runs a function when the browser is idle. */\nconst idle = (fn: () => void): unknown => (window.requestIdleCallback ?? setTimeout)(fn);\n\n/** What the loader gives the code that loads pages without a full page load. */\nexport interface Navigation {\n options: LoaderOptions;\n listen: (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ) => void;\n core: () => Promise<Core> | undefined;\n scan: (root: ParentNode) => void;\n}\n\n/**\n * Starts resuming the page. Listens to the events in `b-on` attributes\n * and loads `brumate/client` and the component's module on the first one.\n * `navigate` adds client navigation, and returns how to import the core.\n * Returns a function that removes the listeners and stops the core.\n */\nexport function boot(\n options: LoaderOptions,\n navigate?: (navigation: Navigation) => () => Promise<Core>,\n): () => void {\n let core: Promise<Core> | undefined;\n const types = new Set<string>();\n const removers: (() => void)[] = [];\n const listen = (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ): void => {\n target.addEventListener(type, listener, flags);\n removers.push(() => target.removeEventListener(type, listener, flags));\n };\n\n // Client navigation imports the core with the code that reads the pages it adds.\n let load = importCore;\n const loadCore = (): Promise<Core> =>\n (core ??= load().then((client) => {\n client.init({ ...options, listen: scan });\n return client;\n }));\n\n // The devtools panel asks for the core when it opens, so it can show the page before any event.\n listen(document, 'brumate:core', () => void loadCore());\n\n // Starts loading the module of a handler and its part, as one step when the module holds them.\n const warm = (ref: string): void => {\n const [id, name] = ref.split('#') as [string, string];\n void options.load(id)?.then((module) => module.load?.(/^[hc]\\d/.test(name) ? name : 'update'));\n };\n\n const run = (element: Element, ref: string, event?: Event): void => {\n // The module loads while the core does, not after it.\n warm(ref);\n void loadCore().then((client) => client.handle(element, ref, event));\n };\n\n const apply = (event: Event, element: Element, entry: Entry): boolean => {\n if (entry.modifiers.includes('prevent')) {\n event.preventDefault();\n }\n if (entry.modifiers.includes('once')) {\n element.setAttribute(\n 'b-on',\n entries(element)\n .map((item) => item.raw)\n .filter((raw) => raw !== entry.raw)\n .join(' '),\n );\n }\n run(element, entry.ref, event);\n return entry.modifiers.includes('stop');\n };\n\n // Handlers run from the target outwards, as if each element had its own listener.\n const onEvent = (event: Event): void => {\n for (\n let node = event.target as Node | null;\n node && node !== document;\n node = node.parentNode\n ) {\n if (node.nodeType !== 1 || !(node as Element).hasAttribute('b-on')) {\n continue;\n }\n let stop = false;\n for (const entry of entries(node as Element)) {\n if (entry.type === event.type && apply(event, node as Element, entry)) {\n stop = true;\n }\n }\n if (stop) {\n event.stopPropagation();\n return;\n }\n }\n };\n\n // Templates are started once, even when markup is scanned again.\n const started = new WeakSet<Element>();\n const select = (root: ParentNode, selector: string): Element[] => {\n const found = [...root.querySelectorAll(selector)];\n if ((root as Element).matches?.(selector)) {\n found.unshift(root as Element);\n }\n return found.filter((element) => {\n if (element.tagName !== 'TEMPLATE') {\n return true;\n }\n if (started.has(element)) {\n return false;\n }\n started.add(element);\n return true;\n });\n };\n\n const visible =\n typeof IntersectionObserver === 'undefined'\n ? undefined\n : new IntersectionObserver(\n (records) => {\n for (const record of records) {\n if (record.isIntersecting) {\n visible!.unobserve(record.target);\n preload(record.target);\n }\n }\n },\n // Near the viewport counts too, so code loads before an element scrolls in.\n { rootMargin: '25%' },\n );\n removers.push(() => visible?.disconnect());\n\n // True once the page is idle after `load`, when elements with the default strategy preload\n // as they come near the viewport. See `preload` in the options.\n let eager = false;\n\n const scan = (root: ParentNode): void => {\n for (const element of select(root, '[data-prefetch=visible],[data-prefetch=idle]')) {\n if (strategy(element) === 'idle' || !visible) {\n idle(() => preload(element));\n } else {\n visible.observe(element);\n }\n }\n for (const element of select(root, '[b-on]:not(template)')) {\n for (const { type } of entries(element)) {\n if (!types.has(type)) {\n types.add(type);\n listen(document, type, onEvent, true);\n }\n }\n if (eager && strategy(element) === 'hover') {\n visible?.observe(element);\n }\n }\n for (const template of select(root, 'template[b-listen]')) {\n const target = template.getAttribute('b-listen') === 'window' ? window : document;\n for (const entry of entries(template)) {\n // Markup that is gone, such as a page that navigation replaced, no longer listens.\n listen(target, entry.type, (event) => {\n if (template.isConnected) {\n apply(event, template, entry);\n }\n });\n }\n }\n for (const template of select(root, 'template[b-client]')) {\n const [trigger, ref] = template.getAttribute('b-client')!.split('=') as [string, string];\n const go = (): void => run(template, ref);\n const next = template.nextElementSibling;\n if (trigger === 'idle') {\n idle(go);\n } else if (trigger === 'visible' && next && visible) {\n const observer = new IntersectionObserver((records) => {\n if (records.some((record) => record.isIntersecting)) {\n observer.disconnect();\n go();\n }\n });\n observer.observe(next);\n } else {\n go();\n }\n }\n };\n\n // Preloads the core and the parts of an element's handlers, so its first event does not wait for them.\n const preloaded = new WeakSet<Element>();\n const preload = (element: Element): void => {\n if (preloaded.has(element)) {\n return;\n }\n preloaded.add(element);\n void importCore();\n for (const entry of entries(element)) {\n warm(entry.ref);\n }\n };\n\n const hover = (event: Event): void => {\n const element = (event.target as Element).closest?.('[b-on]');\n if (element && strategy(element) === 'hover') {\n preload(element);\n }\n };\n listen(document, 'pointerover', hover, { passive: true });\n listen(document, 'focusin', hover);\n\n // A form of an `$action` sends its data with `fetch`, and the core writes the result into the page.\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n if (event.defaultPrevented || !form.hasAttribute?.('b-result')) {\n return;\n }\n event.preventDefault();\n const submitter = (event as SubmitEvent).submitter;\n void loadCore().then((client) => client.submitAction(form, submitter));\n });\n\n if (navigate) {\n load = navigate({ options, listen, core: () => core, scan });\n } else {\n // A hot update whose markup changed loads the page again.\n listen(document, 'brumate:reload', () => location.reload());\n }\n\n scan(document);\n // Markup that streams in later, such as a `#loading` body, has handlers too.\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n scan(node as Element);\n }\n }\n }\n });\n observer.observe(document, { childList: true, subtree: true });\n\n // After `load`, so the page's own requests go first, and only when the browser is idle.\n // `2g` matches `slow-2g` too.\n const connection = (navigator as { connection?: { saveData?: boolean; effectiveType?: string } })\n .connection;\n if (\n options.preload !== false &&\n !connection?.saveData &&\n !/2g/.test(connection?.effectiveType as string)\n ) {\n listen(window, 'load', () =>\n idle(() => {\n eager = true;\n scan(document);\n }),\n );\n }\n return () => {\n observer.disconnect();\n for (const remove of removers.splice(0)) {\n remove();\n }\n void core?.then((client) => client.dispose());\n };\n}\n","// The loader without client navigation, for `navigate: false`. It is a module\n// of its own, so a bundle that starts it has no import of the navigation code,\n// and keeps none of the core's exports that only navigation reads.\n\nimport { boot } from './boot.ts';\nimport type { LoaderOptions } from './boot.ts';\n\nexport type { LoaderOptions } from './boot.ts';\n\n/**\n * `start` for a site that loads every page with a full page load, as with\n * `navigate: false`. A bundle that only calls it leaves out the code of\n * client navigation.\n */\nexport function startWithoutNavigation(options: LoaderOptions): () => void {\n return boot(options);\n}\n"],"mappings":";AAkDA,MAAM,yBAAS,IAAI,IAAqB;AAExC,SAAgB,QAAQ,SAA2B;CACjD,MAAM,QAAQ,QAAQ,aAAa,MAAM,KAAK;CAC9C,OAAQ,OAAO,IAAI,KAAK,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O,CAAC,GACpC,OAAO;EAET,MAAW,MAAM,WAAW,OAAO,QAAQ,CAAC;CAC9C;AACF;;;;;;;;ACnVA,SAAgB,uBAAuB,SAAoC;CACzE,OAAO,KAAK,OAAO;AACrB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"stream-bgNCMcaA.js","names":[],"sources":["../src/runtime/calls.ts","../src/runtime/serial.ts","../src/runtime/stream.ts"],"sourcesContent":["// Values that only server function calls and their serialization use. They are\n// not in `shared.ts`, which the core imports, so a page's core does not hold them.\n\nimport type { FunctionReference } from './shared.ts';\n\n/** Server functions that are passed to the client, with their references. */\nexport const functionReferences: WeakMap<object, FunctionReference> = new WeakMap();\n\n/**\n * A file or a blob in the arguments of a server function call. The call\n * sends it as a part of multipart form data, named `file<index>`, instead\n * of in the JSON of the arguments.\n */\nexport class Upload {\n readonly index: number;\n\n constructor(index: number) {\n this.index = index;\n }\n}\n\n/**\n * Replaces each value in arrays and plain objects that `replace` returns a\n * value for. Returns a copy, or the value itself when nothing changed.\n */\nexport function replaceDeep(value: unknown, replace: (value: unknown) => unknown): unknown {\n const replaced = replace(value);\n if (replaced !== undefined) {\n return replaced;\n }\n if (Array.isArray(value)) {\n return value.map((item) => replaceDeep(item, replace));\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, replaceDeep(item, replace)]),\n );\n }\n return value;\n}\n","// The seroval plugins of brumate's values. The server writes the page state\n// with them as code, and server function calls as JSON, which both sides\n// read with them. The core does not import this module: a state record\n// is code that makes its values with `stateValues`, so seroval loads in the\n// browser only with the first server function call.\n\nimport { Feature, createPlugin } from 'seroval';\nimport type {\n Plugin,\n SerovalNode,\n StreamParsePluginContext,\n SyncParsePluginContext,\n} from 'seroval';\nimport { isRaw, rawHTML } from './html.ts';\nimport type { Raw } from './html.ts';\nimport { Upload, functionReferences } from './calls.ts';\nimport { ElementReference, stateValues } from './shared.ts';\nimport type { ComponentValue } from './shared.ts';\n\ntype ReferenceNode = { a: SerovalNode; b: SerovalNode };\n\n/**\n * Returns the parse functions of a plugin. `read` returns the values of the\n * node by key, and each mode parses them in that order, so the nodes match.\n */\nfunction parsers<T, K extends string>(\n read: (value: T) => Record<K, unknown>,\n): Plugin<T, Record<K, SerovalNode>>['parse'] {\n type N = Record<K, SerovalNode>;\n const parse = (value: T, ctx: SyncParsePluginContext | StreamParsePluginContext): N => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n node[key] = ctx.parse(node[key]);\n }\n return node as N;\n };\n return {\n sync: parse,\n stream: parse,\n async: async (value, ctx) => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n // oxlint-disable-next-line no-await-in-loop -- In order, as the other modes parse, so the IDs match.\n node[key] = await ctx.parse(node[key]);\n }\n return node as N;\n },\n };\n}\n\n// In the page state, each value is a call of `stateValues`, which the code of a record gets as `$b`.\n\n// No plugin here matches a plain object, so each one sets skipPlainObjects and seroval\n// does not run its test on object literals. Raw HTML is a class instance for this reason.\nconst ElementPlugin = createPlugin<ElementReference, ReferenceNode>({\n tag: 'brumate/element',\n skipPlainObjects: true,\n test: (value) => value instanceof ElementReference,\n parse: parsers((value) => ({ a: value.scope, b: value.anchor })),\n serialize: (node, ctx) => `$b.e(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.e(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\nconst FunctionPlugin = createPlugin<object, ReferenceNode>({\n tag: 'brumate/function',\n skipPlainObjects: true,\n test: (value) => typeof value === 'function' && functionReferences.has(value),\n parse: parsers((value) => {\n const reference = functionReferences.get(value)!;\n return { a: reference.ref, b: reference.scope };\n }),\n serialize: (node, ctx) => `$b.f(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.f(ctx.deserialize<string>(node.a), ctx.deserialize<number>(node.b)),\n});\n\n/** HTML, such as the `children` of a component, so the client can insert it again. */\nconst RawPlugin = createPlugin<Raw, { h: SerovalNode }>({\n tag: 'brumate/raw',\n skipPlainObjects: true,\n test: isRaw,\n parse: parsers((value) => ({ h: rawHTML(value) })),\n serialize: (node, ctx) => `$b.r(${ctx.serialize(node.h)})`,\n deserialize: (node, ctx) => stateValues.r(ctx.deserialize<string>(node.h)),\n});\n\n/** A component in the page state, such as the value of a dynamic tag. See `stateValues.c`. */\nconst ComponentPlugin = createPlugin<ComponentValue, { c: SerovalNode }>({\n tag: 'brumate/component',\n skipPlainObjects: true,\n test: (value) =>\n typeof value === 'function' && typeof (value as Partial<ComponentValue>).brumateId === 'string',\n parse: parsers((value) => ({ c: value.brumateId })),\n serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,\n deserialize: (node, ctx) => stateValues.c(ctx.deserialize<string>(node.c)),\n});\n\n/** A value that its string makes again, such as a `URL` from its `href`. */\nfunction stringPlugin<T extends { toString(): string }>(\n tag: string,\n type: new (text: string) => T,\n): Plugin<T, { v: SerovalNode }> {\n return createPlugin<T, { v: SerovalNode }>({\n tag,\n skipPlainObjects: true,\n test: (value) => value instanceof type,\n parse: parsers((value) => ({ v: value.toString() })),\n serialize: (node, ctx) => `new ${type.name}(${ctx.serialize(node.v)})`,\n deserialize: (node, ctx) => new type(ctx.deserialize<string>(node.v)),\n });\n}\n\nconst URLPlugin = stringPlugin('brumate/url', URL);\nconst SearchParamsPlugin = stringPlugin('brumate/search-params', URLSearchParams);\n\n/** A file in the arguments of a server function call. It is never in the page state. */\nconst UploadPlugin = createPlugin<Upload, { i: SerovalNode }>({\n tag: 'brumate/upload',\n skipPlainObjects: true,\n test: (value) => value instanceof Upload,\n parse: parsers((value) => ({ i: value.index })),\n serialize: () => {\n throw new Error('A file cannot be sent in the page');\n },\n deserialize: (node, ctx) => new Upload(ctx.deserialize<number>(node.i)),\n});\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const plugins: Plugin<any, any>[] = [\n ElementPlugin,\n FunctionPlugin,\n RawPlugin,\n ComponentPlugin,\n UploadPlugin,\n URLPlugin,\n SearchParamsPlugin,\n];\n\n/**\n * Features that are off in both directions:\n *\n * - Errors keep their name and message only. A stack trace would show the\n * server's files and code to the browser.\n * - Regular expressions are not sent. A pattern from a client could take\n * the server a long time to match, and reading one is refused as well.\n */\nexport const disabledFeatures: number = Feature.ErrorPrototypeStack | Feature.RegExp;\n","// The answer of a server function, as a stream of seroval chunks. Promises\n// and async iterables in the answer settle as their chunks arrive.\n//\n// Each chunk is a 12-byte header with the size of its data in bytes, as 8\n// hex digits, and the data: `;0x0000001f;{...}`. The reader knows how many\n// bytes to wait for, and can refuse a chunk that is too large.\n\nimport { Stream, fromCrossJSON, toCrossJSONStream } from 'seroval';\nimport type { SerovalNode } from 'seroval';\nimport { disabledFeatures, plugins } from './serial.ts';\n\nconst HEADER_SIZE = 12;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** The content type of a stream of chunks. */\nexport const STREAM_TYPE = 'application/x-brumate-stream';\n\n/** One chunk: its header and its data, in one array. */\nfunction chunk(text: string): Uint8Array {\n const data = encoder.encode(text);\n const result = new Uint8Array(HEADER_SIZE + data.length);\n encoder.encodeInto(`;0x${data.length.toString(16).padStart(8, '0')};`, result);\n result.set(data, HEADER_SIZE);\n return result;\n}\n\n/** Serializes a value as a stream of chunks. */\nexport function toChunkStream(value: unknown): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n toCrossJSONStream(value, {\n refs: new Map(),\n plugins,\n disabledFeatures,\n onParse(node) {\n controller.enqueue(chunk(JSON.stringify(node)));\n },\n onDone() {\n controller.close();\n },\n onError(error) {\n controller.error(error);\n },\n });\n },\n });\n}\n\n/** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */\nclass ChunkReader {\n private readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n private pieces: Uint8Array[] = [];\n private length = 0;\n private done = false;\n\n constructor(stream: ReadableStream<Uint8Array>) {\n this.reader = stream.getReader();\n }\n\n private async fill(size: number): Promise<void> {\n while (this.length < size && !this.done) {\n // oxlint-disable-next-line no-await-in-loop -- Pieces arrive in order.\n const piece = await this.reader.read();\n if (piece.done) {\n this.done = true;\n } else {\n this.pieces.push(piece.value);\n this.length += piece.value.length;\n }\n }\n }\n\n private take(size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n while (offset < size) {\n const piece = this.pieces[0]!;\n const count = Math.min(piece.length, size - offset);\n result.set(piece.subarray(0, count), offset);\n offset += count;\n if (count === piece.length) {\n this.pieces.shift();\n } else {\n this.pieces[0] = piece.subarray(count);\n }\n }\n this.length -= size;\n return result;\n }\n\n /** The data of the next chunk, or undefined at the end of the stream. */\n async next(): Promise<string | undefined> {\n await this.fill(HEADER_SIZE);\n if (this.length === 0) {\n return undefined;\n }\n const head = this.length < HEADER_SIZE ? '' : decoder.decode(this.take(HEADER_SIZE));\n const match = /^;0x([0-9a-f]{8});$/.exec(head);\n if (!match) {\n throw new Error('The answer of a server function is not a stream of chunks');\n }\n const size = Number.parseInt(match[1]!, 16);\n await this.fill(size);\n if (this.length < size) {\n throw new Error('The answer of a server function ended in the middle of a chunk');\n }\n return decoder.decode(this.take(size));\n }\n\n cancel(reason: unknown): void {\n this.done = true;\n void this.reader.cancel(reason).catch(() => {});\n }\n}\n\nconst ignore = (): void => {};\n\n/**\n * The refs of a stream. A promise in the answer can fail with nothing that\n * reads it, such as a field the caller ignores, so its failure is claimed\n * here. Code that awaits it still sees the failure.\n */\nclass Refs extends Map<number, unknown> {\n override set(id: number, value: unknown): this {\n if (value instanceof Promise) {\n value.catch(ignore);\n }\n return super.set(id, value);\n }\n}\n\n/**\n * Fails the promises and async iterables that still wait for a chunk, when\n * the stream ends early. Failing a settled one does nothing.\n */\nfunction failPending(refs: Refs, error: unknown): void {\n for (const value of refs.values()) {\n try {\n // The deserializer makes a Stream. A LiveStream comes only from user code, and its producer fails it.\n if (value instanceof Stream) {\n value.throw(error);\n } else if (value !== null && typeof value === 'object') {\n const resolver = value as { p?: unknown; f?: unknown };\n if (resolver.p instanceof Promise && typeof resolver.f === 'function') {\n resolver.p.catch(ignore);\n (resolver.f as (error: unknown) => void)(error);\n }\n }\n } catch {\n // A value that a plugin made, which has no such methods.\n }\n }\n}\n\n/**\n * Reads the first chunk of a stream as the value, and the rest in the\n * background, so the promises and async iterables in it settle as their\n * chunks arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = new ChunkReader(stream);\n const refs = new Refs();\n const read = (data: string): unknown =>\n fromCrossJSON(JSON.parse(data) as SerovalNode, { refs, plugins, disabledFeatures });\n const first = await reader.next();\n if (first === undefined) {\n throw new Error('The answer of a server function is empty');\n }\n const value = read(first);\n void (async () => {\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const data = await reader.next();\n if (data === undefined) {\n break;\n }\n read(data);\n }\n failPending(refs, new Error('The answer of a server function ended early'));\n } catch (error) {\n reader.cancel(error);\n failPending(refs, error);\n }\n })();\n return value;\n}\n"],"mappings":";;;;;AAMA,MAAa,qCAAyD,IAAI,QAAQ;;;;;;AAOlF,IAAa,SAAb,MAAoB;CAClB;CAEA,YAAY,OAAe;EACzB,KAAK,QAAQ;CACf;AACF;;;;;AAMA,SAAgB,YAAY,OAAgB,SAA+C;CACzF,MAAM,WAAW,QAAQ,KAAK;CAC9B,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,SAAS,YAAY,MAAM,OAAO,CAAC;CAEvD,IACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAO,eAAe,KAAK,MAAM,OAAO,WAExC,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,YAAY,MAAM,OAAO,CAAC,CAAC,CAC9E;C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