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":"loader-Dc9OwY5I.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Routes from './client-routes.ts';\nimport { boot, importCore, strategy } from './boot.ts';\nimport type { Core, LoaderOptions, Navigation } from './boot.ts';\n\nexport type { LoaderOptions, NavigateOptions } from './boot.ts';\nexport { startWithoutNavigation } from './static-loader.ts';\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 * Returns a function that removes the listeners and stops the core.\n */\nexport function start(options: LoaderOptions): () => void {\n return boot(options, options.navigate === false ? undefined : navigation);\n}\n\n/** Starts loading the page of a link, unless the link asks not to. */\nfunction prefetch(link: HTMLAnchorElement | undefined): void {\n if (link && strategy(link) !== 'none') {\n void import('./navigate.ts').then((module) => module.prefetch(link.href));\n }\n}\n\n/**\n * Imports the code with which the core reads the pages that navigation adds.\n * A core that runs loads it when the loader navigates. A core that starts\n * later loads it with the core, when the page has records that navigation\n * marked.\n */\nconst routes = (): (typeof Routes)['ready'] =>\n import('./client-routes.ts').then((module) => module.ready);\n\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. Returns how the loader imports\n * the core.\n */\nfunction navigation({ options, listen, core, scan }: Navigation): () => Promise<Core> {\n const rpc = `${options.rpc ?? '/_brumate'}/`;\n // The page without its hash, to tell a change of the hash from a change of the page.\n let page = String(location.href).split('#')[0];\n const go = (url: string, init?: RequestInit, push = true, reload = false): void => {\n page = url.split('#')[0]!;\n if (core()) {\n void routes();\n }\n void import('./navigate.ts').then((module) =>\n module.navigate({\n url,\n init,\n push,\n reload,\n transition: typeof options.navigate === 'object' && options.navigate.transition === true,\n // The core forgets the old page, or only stops reading, when layouts stay.\n leave: async (partial) => {\n if (core()) {\n (await routes())(partial);\n }\n },\n enter: () => {\n void core()?.then((client) => client.init({ ...options, listen: scan }));\n page = location.href.split('#')[0]!;\n },\n }),\n );\n };\n // A link to another page of this site, which the loader loads itself.\n const pageLink = (target: EventTarget | null): HTMLAnchorElement | undefined => {\n const link = (target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;\n return link &&\n !link.target &&\n !link.matches('[download],[data-reload]') &&\n link.origin === location.origin &&\n // A link to a place in the same page scrolls there.\n !(link.hash && link.href.split('#')[0] === page)\n ? link\n : undefined;\n };\n listen(document, 'click', (event) => {\n const mouse = event as MouseEvent;\n const link = pageLink(event.target);\n if (\n !link ||\n event.defaultPrevented ||\n mouse.button ||\n mouse.metaKey ||\n mouse.ctrlKey ||\n mouse.shiftKey ||\n mouse.altKey\n ) {\n return;\n }\n event.preventDefault();\n go(link.href);\n });\n // A page loads when the pointer rests on its link, or the link gets focus, so a click finds it loading.\n let resting: ReturnType<typeof setTimeout> | undefined;\n listen(\n document,\n 'pointerover',\n (event) => {\n const link = pageLink(event.target);\n if (link) {\n clearTimeout(resting);\n resting = setTimeout(() => prefetch(link), 80);\n }\n },\n { passive: true },\n );\n listen(document, 'pointerout', () => clearTimeout(resting), { passive: true });\n listen(document, 'focusin', (event) => prefetch(pageLink(event.target)));\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n const submitter = (event as SubmitEvent).submitter;\n const action = submitter?.getAttribute('formaction') ?? form.getAttribute('action') ?? '';\n const method = submitter?.getAttribute('formmethod') ?? form.getAttribute('method');\n if (event.defaultPrevented || method?.toLowerCase() !== 'post' || !action.startsWith(rpc)) {\n return;\n }\n event.preventDefault();\n go(action, { method: 'POST', body: new FormData(form, submitter) });\n });\n // A server function that redirects, from `rpc.ts`. Another site loads in full.\n listen(document, 'brumate:redirect', (event) => {\n const url = new URL((event as CustomEvent<string>).detail, location.href);\n if (url.origin === location.origin) {\n event.preventDefault();\n go(url.href, undefined, true, true);\n }\n });\n // A hot update whose markup changed loads the page again, in place. With `init`, the whole\n // page is replaced, as for a form, so layouts render again too, and it keeps the scroll.\n listen(document, 'brumate:reload', () => go(location.href, { method: 'GET' }, false));\n listen(window, 'popstate', () => {\n // A change of the hash only stays on the page.\n if (location.href.split('#')[0] !== page) {\n go(location.href, undefined, false);\n }\n });\n return () =>\n Promise.all([importCore(), document.querySelector('[b-offset],[b-roots]') && routes()]).then(\n ([client]) => client,\n );\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,MAAM,SAAoC;CACxD,OAAO,KAAK,SAAS,QAAQ,aAAa,QAAQ,KAAA,IAAY,UAAU;AAC1E;;AAGA,SAAS,SAAS,MAA2C;CAC3D,IAAI,QAAQ,SAAS,IAAI,MAAM,QAC7B,OAAY,yBAAgB,CAAC,MAAM,WAAW,OAAO,SAAS,KAAK,IAAI,CAAC;AAE5E;;;;;;;AAQA,MAAM,eACJ,OAAO,8BAAqB,CAAC,MAAM,WAAW,OAAO,KAAK;;;;;;;AAQ5D,SAAS,WAAW,EAAE,SAAS,QAAQ,MAAM,QAAyC;CACpF,MAAM,MAAM,GAAG,QAAQ,OAAO,YAAY;CAE1C,IAAI,OAAO,OAAO,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CAC5C,MAAM,MAAM,KAAa,MAAoB,OAAO,MAAM,SAAS,UAAgB;EACjF,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EACtB,IAAI,KAAK,GACP,OAAY;EAEd,OAAY,yBAAgB,CAAC,MAAM,WACjC,OAAO,SAAS;GACd;GACA;GACA;GACA;GACA,YAAY,OAAO,QAAQ,aAAa,YAAY,QAAQ,SAAS,eAAe;GAEpF,OAAO,OAAO,YAAY;IACxB,IAAI,KAAK,GACP,CAAC,MAAM,OAAO,EAAA,CAAG,OAAO;GAE5B;GACA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,OAAO,WAAW,GAAG,GACtF;EAEF,MAAM,eAAe;EACrB,GAAG,QAAQ;GAAE,QAAQ;GAAQ,MAAM,IAAI,SAAS,MAAM,SAAS;EAAE,CAAC;CACpE,CAAC;CAED,OAAO,UAAU,qBAAqB,UAAU;EAC9C,MAAM,MAAM,IAAI,IAAK,MAA8B,QAAQ,SAAS,IAAI;EACxE,IAAI,IAAI,WAAW,SAAS,QAAQ;GAClC,MAAM,eAAe;GACrB,GAAG,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI;EACpC;CACF,CAAC;CAGD,OAAO,UAAU,wBAAwB,GAAG,SAAS,MAAM,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;CACpF,OAAO,QAAQ,kBAAkB;EAE/B,IAAI,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,MAClC,GAAG,SAAS,MAAM,KAAA,GAAW,KAAK;CAEtC,CAAC;CACD,aACE,QAAQ,IAAI,CAAC,WAAW,GAAG,SAAS,cAAc,sBAAsB,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,MACrF,CAAC,YAAY,MAChB;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"navigate-CzLjnoPH.js","names":[],"sources":["../src/runtime/navigate.ts"],"sourcesContent":["// Client navigation. The loader imports it on the first navigation, so pages\n// that never navigate do not load it.\n\nexport interface Visit {\n url: string;\n /** For a form that posts to a server function. */\n init?: RequestInit;\n /** False for the back and forward buttons, which already changed the history. */\n push: boolean;\n /**\n * Runs before the new page replaces the old one. `partial` is true when\n * the page keeps its layouts and replaces only some routes.\n */\n leave: (partial: boolean) => Promise<void>;\n /** Runs after the first render of the new page is in the document. */\n enter: () => void;\n /** Swaps the page inside a view transition, where the browser has them. */\n transition?: boolean;\n /**\n * Loads the page after a server function changed something, as for a\n * redirect from one. As a form does, it replaces the whole page, and does\n * not use a page that a link loaded early.\n */\n reload?: boolean;\n}\n\n/**\n * Runs `update` inside a view transition, with a type that tells how the page\n * was reached: `push` for a link, `traverse` for the back and forward\n * buttons, and `form` for a form. Without transitions, it runs `update`.\n */\nasync function transition(visit: Visit, update: () => void): Promise<void> {\n if (!visit.transition || typeof document.startViewTransition !== 'function') {\n update();\n return;\n }\n const types = [visit.init || visit.reload ? 'form' : visit.push ? 'push' : 'traverse'];\n // Browsers that have transitions without types take only a callback.\n const started =\n typeof ViewTransition !== 'undefined' && 'types' in ViewTransition.prototype\n ? document.startViewTransition({ update, types })\n : document.startViewTransition(update);\n await started.updateCallbackDone;\n}\n\nlet controller: AbortController | undefined;\n\nconst STATE = 'script[b-state]';\nconst REGION = /^R(-?\\d+):([^:]+):(\\d+):(.*)$/;\n\n/** A route slot in the page, between `<!--R…-->` and `<!--/R-->`. */\ninterface Region {\n /** The scope of the layout that renders the slot. */\n layout: number;\n name: string;\n /** The scope of the route in the slot. */\n root: number;\n key: string;\n start: Comment;\n end: Comment;\n children: Region[];\n}\n\n/** Finds the route slots in a document, nested as the routes are. */\nfunction regions(root: Node): Region[] {\n const top: Region[] = [];\n const stack: Region[] = [];\n const walker = (root.ownerDocument ?? (root as Document)).createTreeWalker(root, 128);\n for (\n let node = walker.nextNode() as Comment | null;\n node;\n node = walker.nextNode() as Comment | null\n ) {\n const match = REGION.exec(node.data);\n if (match) {\n const region: Region = {\n layout: Number(match[1]),\n name: match[2]!,\n root: Number(match[3]),\n key: decodeURIComponent(match[4]!),\n start: node,\n end: node,\n children: [],\n };\n (stack.at(-1)?.children ?? top).push(region);\n stack.push(region);\n } else if (node.data === '/R' && stack.length > 0) {\n stack.pop()!.end = node;\n }\n }\n return top;\n}\n\ninterface Plan {\n /** Old slots and the new slots that replace them. */\n replace: [Region, Region][];\n alias: Map<number, number>;\n}\n\n/**\n * Pairs the slots of the old and the new page by name. A layout with the\n * same key stays, and its slots are compared in turn. Any other route is\n * replaced. Returns undefined when the pages do not line up.\n */\nfunction plan(old: Region[], next: Region[], result: Plan): Plan | undefined {\n for (const region of next) {\n const before = old.find((item) => item.name === region.name);\n if (!before) {\n return undefined;\n }\n result.alias.set(region.layout, before.layout);\n if (before.key === region.key && region.children.length > 0) {\n // The layout stays, so its new scope stands for the old one.\n result.alias.set(region.root, before.root);\n if (!plan(before.children, region.children, result)) {\n return undefined;\n }\n } else {\n result.replace.push([before, region]);\n }\n }\n return result;\n}\n\nfunction between(start: Node, end: Node): Node[] {\n const nodes = [start];\n for (let node = start.nextSibling; node && nodes.at(-1) !== end; node = node.nextSibling) {\n nodes.push(node);\n }\n return nodes;\n}\n\n/**\n * The server writes a component's stylesheet before its first instance, so\n * an old route can hold the stylesheet of a component that a kept layout\n * still shows. Such a stylesheet moves to the head. The others go with the\n * route, so the page keeps only the CSS of the components that it shows.\n */\nfunction keepStyles(removed: HTMLStyleElement[]): void {\n for (const style of removed) {\n const id = style.getAttribute('b-style')!;\n // The component ID ends with the hash that scopes its elements, as `s-<hash>`.\n const attribute = `s-${id.slice(id.lastIndexOf('_') + 1)}`;\n const present = document.querySelector(`style[b-style=\"${CSS.escape(id)}\"]`);\n if (!present && document.querySelector(`[${attribute}]`)) {\n document.head.append(style);\n }\n }\n}\n\n/**\n * True when a slot's end comment is a sibling of its start comment. The end\n * comes after the start in the document, so it then follows it.\n */\nfunction complete(region: Region): boolean {\n return region.start.parentNode === region.end.parentNode;\n}\n\n/**\n * Plans to replace only the routes that change, when the new page has the\n * same root route as the current one. Returns undefined when it cannot.\n */\nfunction planRoutes(next: Document, state: Element | null, requested: number): Plan | undefined {\n const scripts = document.querySelectorAll(`${STATE}[b-route]`);\n const route = scripts[scripts.length - 1]?.getAttribute('b-route');\n if (!route || state?.getAttribute('b-route') !== route) {\n return undefined;\n }\n // A page that did not start its IDs above this one, such as a static file that\n // ignores the request header, would mix its IDs with the kept layouts.\n if (state.getAttribute('b-root') !== String(requested)) {\n return undefined;\n }\n const result = plan(regions(document.body), regions(next.body), {\n replace: [],\n alias: new Map(),\n });\n if (\n !result ||\n result.replace.length === 0 ||\n !result.replace.every(([before, region]) => complete(before) && complete(region))\n ) {\n return undefined;\n }\n return result;\n}\n\n/** Replaces the routes that change, and keeps the rest of the page. */\nfunction replaceRoutes(next: Document, state: Element, result: Plan): void {\n const removed: HTMLStyleElement[] = [];\n for (const [before, region] of result.replace) {\n const nodes = between(before.start, before.end);\n for (const node of nodes) {\n if (node.nodeType === 1) {\n const element = node as Element;\n if (element.matches('style[b-style]')) {\n removed.push(element as HTMLStyleElement);\n }\n removed.push(...element.querySelectorAll<HTMLStyleElement>('style[b-style]'));\n }\n }\n const parent = before.start.parentNode!;\n for (const node of between(region.start, region.end)) {\n parent.insertBefore(document.adoptNode(node), before.start);\n }\n for (const node of nodes) {\n node.parentNode?.removeChild(node);\n }\n }\n keepStyles(removed);\n // The core drops the scopes of the old routes, and adds only the scopes of the new ones.\n state.setAttribute('b-drop', result.replace.map(([before]) => before.root).join(','));\n state.setAttribute('b-roots', result.replace.map(([, region]) => region.root).join(','));\n state.setAttribute('b-alias', [...result.alias].map(([from, to]) => `${from}:${to}`).join(','));\n // The records run as they are added, after the IDs and these attributes are set.\n for (const script of next.body.querySelectorAll<HTMLScriptElement>(STATE)) {\n document.body.append(runnable(script));\n }\n}\n\n/** Moves the IDs of a page above the IDs of the page in the browser. */\ninterface Shift {\n /** The number to add to each scope and boundary ID. */\n by: number;\n /** The `b-root` of its state records, which keeps their references apart. */\n root: string;\n}\n\n/**\n * A page whose IDs do not start where this page asked, such as a prerendered\n * file on a static host, has its IDs moved before it is read. Returns\n * undefined when the server started them there.\n */\nfunction shiftFor(state: Element | null, requested: number): Shift | undefined {\n if (!state) {\n return undefined;\n }\n const root = Number(state.getAttribute('b-root') ?? 0);\n return root === requested ? undefined : { by: requested - root, root: String(requested) };\n}\n\nconst COMMENT_IDS = /^([tb])(\\d+)(:.*)$|^([ilP])(\\d+)$/;\n/** Attributes that hold a scope ID, then `:` and more. */\nconst SCOPED = ['b-b', 'b-result'];\n/** Attributes that hold only a scope or boundary ID. */\nconst IDS = ['b-v', 'b-l', 'b-h', 'b-next'];\n\n/**\n * Adds a number to every scope and boundary ID in markup that the server\n * rendered: anchors, markers, swap scripts and state records. The core moves\n * the IDs inside a state record when it reads one with `b-offset`.\n */\nfunction shiftIds(root: Node, shift: Shift): void {\n const add = (value: string): string => String(Number(value) + shift.by);\n const visit = (node: Node): void => {\n if (node.nodeType === 8) {\n const comment = node as Comment;\n const region = REGION.exec(comment.data);\n if (region) {\n const layout = Number(region[1]) < 0 ? region[1]! : add(region[1]!);\n comment.data = `R${layout}:${region[2]}:${add(region[3]!)}:${region[4]}`;\n return;\n }\n const match = COMMENT_IDS.exec(comment.data);\n if (match) {\n comment.data = match[1]\n ? `${match[1]}${add(match[2]!)}${match[3]}`\n : `${match[4]}${add(match[5]!)}`;\n }\n return;\n }\n if (node.nodeType !== 1) {\n return;\n }\n const element = node as Element;\n for (const name of SCOPED) {\n const value = element.getAttribute(name);\n if (value) {\n const [scope, rest] = value.split(':') as [string, string];\n element.setAttribute(name, `${add(scope)}:${rest}`);\n }\n }\n for (const name of IDS) {\n const value = element.getAttribute(name);\n if (value) {\n element.setAttribute(name, add(value));\n }\n }\n // Only a script can match the state selector, so other elements skip it. The text of a\n // record is not changed: the core moves the IDs in its value when it reads it.\n if (element.localName === 'script' && element.matches(STATE)) {\n element.setAttribute('b-offset', String(shift.by));\n element.setAttribute('b-root', shift.root);\n } else if (element.tagName === 'SCRIPT' && !element.hasAttribute('type')) {\n // The scripts that swap in `#loading` bodies and their head name the boundary.\n element.textContent = element.textContent!.replace(\n /\\$b([SH])\\((\\d+)/g,\n (_, kind: string, id: string) => `$b${kind}(${add(id)}`,\n );\n }\n for (const child of element.tagName === 'TEMPLATE'\n ? (element as HTMLTemplateElement).content.childNodes\n : element.childNodes) {\n visit(child);\n }\n };\n visit(root);\n}\n\n/** A number above every scope and boundary ID in the page, for the server to start the next page at. */\nfunction base(): number {\n let value = 0;\n for (const script of document.querySelectorAll(`${STATE}[b-next]`)) {\n value = Math.max(value, Number(script.getAttribute('b-next')));\n }\n return value;\n}\n\n/**\n * The Content Security Policy nonce of the page that the browser loaded.\n * Its policy stays for the whole visit, so scripts of later pages need it,\n * not the nonce of their own response. Read once, while a script holds it.\n */\nlet loadedNonce: string | undefined;\n\n/** The nonce of a script. Browsers hide the attribute once the page loads, and keep the property. */\nfunction nonceOf(script: HTMLScriptElement): string | null {\n return script.nonce || script.getAttribute('nonce');\n}\n\nfunction pageNonce(): string | undefined {\n for (const script of loadedNonce ? [] : document.querySelectorAll('script')) {\n loadedNonce = nonceOf(script) || undefined;\n if (loadedNonce) {\n break;\n }\n }\n return loadedNonce;\n}\n\n/** Copies a script, so the browser runs it. Scripts from a parser that has no window do not run. */\nfunction runnable(script: HTMLScriptElement): HTMLScriptElement {\n const copy = document.createElement('script');\n for (const attribute of script.attributes) {\n if (attribute.name !== 'nonce') {\n copy.setAttribute(attribute.name, attribute.value);\n }\n }\n // A script that its server gave a nonce runs under the policy of the loaded page.\n const nonce = nonceOf(script);\n if (nonce) {\n copy.nonce = pageNonce() ?? nonce;\n // A DOM without the property, such as in tests, reads the attribute.\n copy.setAttribute('nonce', copy.nonce);\n }\n copy.textContent = script.textContent;\n return copy;\n}\n\n/** Moves nodes into the body. Inline scripts, such as the ones that swap in `#loading` bodies, run. */\nfunction append(nodes: Node[], shift: Shift | undefined): void {\n for (const node of nodes) {\n if (shift) {\n shiftIds(node, shift);\n }\n const adopted = document.adoptNode(node);\n const scripts: HTMLScriptElement[] = [];\n if (adopted.nodeType === 1) {\n if ((adopted as Element).matches('script')) {\n scripts.push(adopted as HTMLScriptElement);\n }\n scripts.push(...(adopted as Element).querySelectorAll('script'));\n }\n document.body.append(adopted);\n for (const script of scripts) {\n if (\n !script.src &&\n (!script.type || script.type === 'text/javascript' || script.type === 'module')\n ) {\n script.replaceWith(runnable(script));\n }\n }\n }\n}\n\n/** Makes the head of the page match the new one, keeping elements that are in both. */\nfunction updateHead(next: Document): void {\n const keep = new Map<string, Element>();\n for (const element of document.head.children) {\n keep.set(element.outerHTML, element);\n }\n // A copy, because adopting an element removes it from the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const element of [...next.head.children]) {\n const html = element.outerHTML;\n if (keep.has(html)) {\n keep.delete(html);\n } else {\n document.head.append(document.adoptNode(element));\n }\n }\n for (const element of keep.values()) {\n // Module scripts stay, because removing them does not unload them.\n if (!(element.tagName === 'SCRIPT' && (element as HTMLScriptElement).src)) {\n element.remove();\n }\n }\n}\n\nfunction scroll(url: URL, saved: number | undefined): void {\n if (saved !== undefined) {\n window.scrollTo(0, saved);\n return;\n }\n const target = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1)));\n if (target) {\n target.scrollIntoView();\n } else {\n window.scrollTo(0, 0);\n }\n}\n\n/**\n * Loads a page and replaces the current one with it. The first render of the\n * page replaces the document as soon as it arrives. Markup that the server\n * streams after it, such as `#loading` bodies, follows as it arrives.\n */\n// Pages that a link started to load before its click, by URL without the hash.\nconst prefetched = new Map<\n string,\n { at: number; base: number; response: Promise<Response>; controller: AbortController }\n>();\n\n/** How long a page that loaded early is used, in milliseconds. */\nconst FRESH = 10_000;\n\n/**\n * Starts loading a page before its link is clicked. A click within a few\n * seconds uses the response, so the page arrives sooner.\n */\nexport function prefetch(url: string): void {\n const key = url.split('#')[0]!;\n const entry = prefetched.get(key);\n if (entry && performance.now() - entry.at < FRESH) {\n return;\n }\n entry?.controller.abort();\n const requested = base();\n const loading = new AbortController();\n const response = fetch(key, {\n headers: { 'x-brumate-base': String(requested) },\n signal: loading.signal,\n });\n const next = { at: performance.now(), base: requested, response, controller: loading };\n // A failed load is not used. The click loads the page again.\n response.catch(() => {\n if (prefetched.get(key) === next) {\n prefetched.delete(key);\n }\n });\n prefetched.set(key, next);\n}\n\n/** Stops the pages that loaded early and were not used, so they free their connections. */\nfunction clearPrefetched(): void {\n for (const entry of prefetched.values()) {\n entry.controller.abort();\n }\n prefetched.clear();\n}\n\n/** The response of a page that loaded early for these IDs, if it is still fresh. */\nfunction takePrefetched(url: string, requested: number): Promise<Response> | undefined {\n const key = url.split('#')[0]!;\n const entry = prefetched.get(key);\n prefetched.delete(key);\n if (entry && entry.base === requested && performance.now() - entry.at < FRESH) {\n return entry.response;\n }\n entry?.controller.abort();\n return undefined;\n}\n\n// The end of the first render, which can be split across chunks.\nconst HTML_END = /<\\/html\\s*>/gi;\n\nexport async function navigate(visit: Visit): Promise<void> {\n // Read before the page changes, while the scripts of the loaded page are in it.\n pageNonce();\n controller?.abort();\n const requested = base();\n const current = new AbortController();\n controller = current;\n // The scroll position of the page that is left, for the back button.\n history.replaceState({ ...history.state, scroll: window.scrollY }, '');\n let response: Response;\n try {\n const early = visit.init || visit.reload ? undefined : takePrefetched(visit.url, requested);\n const headers = new Headers(visit.init?.headers);\n headers.set('x-brumate-base', String(requested));\n response = await (early ??\n fetch(visit.url, { ...visit.init, headers, signal: current.signal }));\n // Other pages loaded for this page, whose IDs no longer fit the next one.\n clearPrefetched();\n } catch (error) {\n // A later navigation stopped this one.\n if (current.signal.aborted) {\n return;\n }\n location.assign(visit.url);\n throw error;\n }\n if (current.signal.aborted) {\n // A page that loaded early is not tied to the signal, so its body is cancelled here.\n response.body?.cancel().catch(() => {});\n return;\n }\n const type = response.headers.get('content-type') ?? '';\n if (!type.includes('text/html') || !response.body) {\n if (!visit.init) {\n // Not a page, such as a file. The browser opens it.\n location.assign(visit.url);\n return;\n }\n // The error of a form post, which a browser without scripts shows as text.\n const text = await response.text();\n response = new Response(\n `<!doctype html><pre>${text.replace(/[&<]/g, (char) => (char === '&' ? '&amp;' : '&lt;'))}</pre>`,\n );\n }\n const url = new URL(response.url || visit.url, location.href);\n url.hash = new URL(visit.url, location.href).hash;\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n // Frees the connection of a page that a later navigation replaced.\n const stop = (): void => {\n reader.cancel().catch(() => {});\n };\n // The next chunk, or nothing once a later navigation started.\n const read = async (): Promise<ReadableStreamReadResult<string> | undefined> => {\n try {\n const chunk = await reader.read();\n if (!current.signal.aborted) {\n return chunk;\n }\n } catch (error) {\n if (!current.signal.aborted) {\n throw error;\n }\n }\n stop();\n return undefined;\n };\n\n // The first render ends with </html>. What comes after it streams in later.\n let text = '';\n let end = -1;\n while (end === -1) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const chunk = await read();\n if (!chunk) {\n return;\n }\n if (chunk.done) {\n end = text.length;\n break;\n }\n // A tag split across chunks starts at the last `<` of the text so far.\n HTML_END.lastIndex = Math.max(0, text.lastIndexOf('<'));\n text += chunk.value;\n const match = HTML_END.exec(text);\n if (match) {\n end = match.index + match[0].length;\n }\n }\n const next = new DOMParser().parseFromString(text.slice(0, end), 'text/html');\n const state = next.body.querySelector(`${STATE}[b-route]`);\n const shift = visit.init ? undefined : shiftFor(state, requested);\n if (shift) {\n shiftIds(next.body, shift);\n }\n // A link keeps the layouts that stay the same. A form, or a redirect from a server\n // function, replaces the whole page, because what it changed can show anywhere on it.\n const routes = visit.init || visit.reload ? undefined : planRoutes(next, state, requested);\n await visit.leave(routes !== undefined);\n if (current.signal.aborted) {\n stop();\n return;\n }\n await transition(visit, () => {\n // A copy, because removing an attribute changes the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const attribute of [...document.documentElement.attributes]) {\n document.documentElement.removeAttribute(attribute.name);\n }\n for (const attribute of next.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n // Read before the head moves, because moving the <title> clears it in `next`.\n const title = next.title;\n updateHead(next);\n document.title = title;\n const same = url.href === location.href;\n const top = window.scrollY;\n if (routes) {\n replaceRoutes(next, state!, routes);\n } else {\n document.body.replaceWith(document.adoptNode(next.body));\n // The state records of the page run in order, so the core reads them when it starts again.\n for (const script of document.body.querySelectorAll<HTMLScriptElement>(STATE)) {\n script.replaceWith(runnable(script));\n }\n }\n // A link to the page itself, or a form that comes back to it, does not add to the history.\n if (visit.push && !same) {\n history.pushState({}, '', url);\n } else if (!same) {\n history.replaceState(history.state, '', url);\n }\n visit.enter();\n if ((visit.init || visit.reload) && same) {\n // A form that comes back to its page keeps the place on the page.\n window.scrollTo(0, top);\n } else {\n scroll(url, visit.push ? undefined : (history.state?.scroll as number | undefined));\n }\n });\n if (current.signal.aborted) {\n stop();\n return;\n }\n\n // Later markup is parsed in a document without a window, so it can arrive\n // in any pieces. A node is complete once the parser has moved past it.\n const sink = document.implementation.createHTMLDocument('');\n sink.open();\n sink.write('<!doctype html><body>');\n let rest = text.slice(end);\n for (;;) {\n if (rest) {\n sink.write(rest);\n append([...sink.body.childNodes].slice(0, -1), shift);\n }\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const chunk = await read();\n if (!chunk) {\n return;\n }\n if (chunk.done) {\n break;\n }\n rest = chunk.value;\n }\n sink.close();\n append([...sink.body.childNodes], shift);\n}\n"],"mappings":";;;;;;AA+BA,eAAe,WAAW,OAAc,QAAmC;CACzE,IAAI,CAAC,MAAM,cAAc,OAAO,SAAS,wBAAwB,YAAY;EAC3E,OAAO;EACP;CACF;CACA,MAAM,QAAQ,CAAC,MAAM,QAAQ,MAAM,SAAS,SAAS,MAAM,OAAO,SAAS,UAAU;CAMrF,OAHE,OAAO,mBAAmB,eAAe,WAAW,eAAe,YAC/D,SAAS,oBAAoB;EAAE;EAAQ;CAAM,CAAC,IAC9C,SAAS,oBAAoB,MAAM,EAAA,CAC3B;AAChB;AAEA,IAAI;AAEJ,MAAM,QAAQ;AACd,MAAM,SAAS;;AAgBf,SAAS,QAAQ,MAAsB;CACrC,MAAM,MAAgB,CAAC;CACvB,MAAM,QAAkB,CAAC;CACzB,MAAM,UAAU,KAAK,iBAAkB,KAAA,CAAmB,iBAAiB,MAAM,GAAG;CACpF,KACE,IAAI,OAAO,OAAO,SAAS,GAC3B,MACA,OAAO,OAAO,SAAS,GACvB;EACA,MAAM,QAAQ,OAAO,KAAK,KAAK,IAAI;EACnC,IAAI,OAAO;GACT,MAAM,SAAiB;IACrB,QAAQ,OAAO,MAAM,EAAE;IACvB,MAAM,MAAM;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AAI,CAAC,OACH;EAEF,IAAI,MAAM,MACR;EAEF,OAAO,MAAM;CACf;CACA,KAAK,MAAM;CACX,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,GAAG,KAAK;AACzC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"produce-BRGHP7e0.js","names":[],"sources":["../src/runtime/produce.ts"],"sourcesContent":["const DRAFT = Symbol('brumate.draft');\n\ninterface DraftState {\n base: Record<PropertyKey, unknown>;\n /** A shallow copy, made on the first change. */\n copy: Record<PropertyKey, unknown> | undefined;\n parent: DraftState | undefined;\n /** Drafts of the objects inside, by key. */\n children: Map<PropertyKey, DraftState & { proxy: object }>;\n modified: boolean;\n}\n\n/** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */\nfunction isDraftable(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction latest(state: DraftState): Record<PropertyKey, unknown> {\n return state.copy ?? state.base;\n}\n\n/** Copies an object and its parents on the first change. */\nfunction prepare(state: DraftState): Record<PropertyKey, unknown> {\n for (\n let current: DraftState | undefined = state;\n current && !current.modified;\n current = current.parent\n ) {\n current.modified = true;\n current.copy = (\n Array.isArray(current.base) ? [...current.base] : { ...current.base }\n ) as Record<PropertyKey, unknown>;\n }\n return state.copy!;\n}\n\nfunction stateOf(value: unknown): DraftState | undefined {\n return typeof value === 'object' && value !== null\n ? ((value as Record<PropertyKey, unknown>)[DRAFT] as DraftState | undefined)\n : undefined;\n}\n\nfunction createDraft(\n base: Record<PropertyKey, unknown>,\n parent: DraftState | undefined,\n): DraftState & { proxy: object } {\n const state = {\n base,\n copy: undefined,\n parent,\n children: new Map(),\n modified: false,\n } as DraftState & {\n proxy: object;\n };\n // An empty target, so the draft can report the keys of the copy.\n const target = Array.isArray(base) ? [] : Object.create(Object.getPrototypeOf(base));\n state.proxy = new Proxy(target, {\n get(_, key) {\n if (key === DRAFT) {\n return state;\n }\n const source = latest(state);\n const value = source[key];\n if (!Object.hasOwn(source, key) || !isDraftable(value) || value !== state.base[key]) {\n return value;\n }\n let child = state.children.get(key);\n if (!child) {\n child = createDraft(value, state);\n state.children.set(key, child);\n }\n return child.proxy;\n },\n set(_, key, value) {\n const source = latest(state);\n if (Object.is(source[key], value) && Object.hasOwn(source, key)) {\n return true;\n }\n prepare(state)[key] = value;\n state.children.delete(key);\n return true;\n },\n deleteProperty(_, key) {\n if (Object.hasOwn(latest(state), key)) {\n delete prepare(state)[key];\n state.children.delete(key);\n }\n return true;\n },\n has(_, key) {\n return key in latest(state);\n },\n ownKeys() {\n return Reflect.ownKeys(latest(state));\n },\n getOwnPropertyDescriptor(_, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(latest(state), key);\n if (descriptor && key !== 'length') {\n descriptor.configurable = true;\n descriptor.writable = true;\n }\n return descriptor;\n },\n defineProperty(_, key, descriptor) {\n prepare(state);\n return Reflect.defineProperty(state.copy!, key, descriptor);\n },\n });\n return state;\n}\n\n/** Returns the final value of a draft: the base if nothing changed, or a new object that shares what did not. */\nfunction finalize(state: DraftState): unknown {\n if (!state.modified) {\n // A child can change without its parent being copied yet.\n for (const child of state.children.values()) {\n if (child.modified) {\n prepare(state);\n break;\n }\n }\n if (!state.modified) {\n return state.base;\n }\n }\n const copy = state.copy!;\n for (const [key, child] of state.children) {\n if (copy[key] === child.base) {\n copy[key] = finalize(child);\n }\n }\n // Drafts can also be assigned to other keys, such as when an array is reordered.\n for (const key of Reflect.ownKeys(copy)) {\n const draft = stateOf(copy[key]);\n if (draft) {\n copy[key] = finalize(draft);\n }\n }\n return copy;\n}\n\n/**\n * Returns a changed copy of a value. The recipe changes a draft as if it\n * were the value. Objects that it does not change keep their identity, and\n * if it changes nothing, the value itself is returned. A recipe can also\n * return a new value. Only plain objects and arrays are drafted.\n */\nexport function produce<T>(base: T, recipe: (draft: T) => T | void): T {\n if (!isDraftable(base)) {\n const result = recipe(base);\n return result === undefined ? base : result;\n }\n const state = createDraft(base, undefined);\n const result = recipe(state.proxy as T);\n if (result !== undefined && result !== state.proxy) {\n return resolve(result, new Set()) as T;\n }\n return finalize(state) as T;\n}\n\n/** Replaces the drafts in a value that a recipe returns, such as the result of `draft.filter(…)`. */\nfunction resolve(value: unknown, seen: Set<unknown>): unknown {\n const draft = stateOf(value);\n if (draft) {\n return finalize(draft);\n }\n if (!isDraftable(value) || seen.has(value)) {\n return value;\n }\n seen.add(value);\n for (const key of Reflect.ownKeys(value)) {\n value[key] = resolve(value[key], seen);\n }\n return value;\n}\n"],"mappings":";AAAA,MAAM,QAAQ,OAAO,eAAe;;AAapC,SAAS,YAAY,OAAuD;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO;CAET,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,OAAO,OAAiD;CAC/D,OAAO,MAAM,QAAQ,MAAM;AAC7B;;AAGA,SAAS,QAAQ,OAAiD;CAChE,KACE,IAAI,UAAkC,OACtC,WAAW,CAAC,QAAQ,UACpB,UAAU,QAAQ,QAClB;EACA,QAAQ,WAAW;EACnB,QAAQ,OACN,MAAM,QAAQ,QAAQ,IAAI,IAAI,CAAC,GAAG,QAAQ,IAAI,IAAI,EAAE,GAAG,QAAQ,KAAK;CAExE;CACA,OAAO,MAAM;AACf;AAEA,SAAS,QAAQ,OAAwC;CACvD,OAAO,OAAO,UAAU,YAAY,UAAU,OACxC,MAAuC,SACzC,KAAA;AACN;AAEA,SAAS,YACP,MACA,QACgC;CAChC,MAAM,QAAQ;EACZ;EACA,MAAM,KAAA;EACN;EACA,0BAAU,IAAI,IAAI;EAClB,UAAU;CACZ;CAIA,MAAM,SAAS,MAAM,QAAQ,IAAI,IAAI,CAAC,IAAI,OAAO,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ime/rpc.ts"],"sourcesContent":["import { toJSONAsync } from 'seroval';\nimport type { Scope } from './client.ts';\nimport { disabledFeatures, plugins } from './serial.ts';\nimport { Upload, replaceDeep } from './calls.ts';\nimport { fromChunkStream } from './stream.ts';\n\n/**\n * True for a file or a blob. One from another frame, or another DOM, is an\n * instance of another `Blob` class, so its methods tell instead.\n */\nfunction isBlob(value: unknown): value is Blob {\n if (value instanceof Blob) {\n return true;\n }\n const blob = value as Partial<Blob> | null;\n return (\n typeof blob === 'object' &&\n blob !== null &&\n typeof blob.size === 'number' &&\n typeof blob.type === 'string' &&\n typeof blob.arrayBuffer === 'function' &&\n typeof blob.slice === 'function'\n );\n}\n\n/**\n * Calls a server function. It is a separate module, so pages that never call\n * one never load seroval's serializer.\n *\n * Files and blobs in the arguments, in arrays and plain objects, go as parts\n * of multipart form data. `signal` aborts the call.\n */\nexport async function call(\n prefix: string,\n id: string,\n args: unknown[],\n signal?: AbortSignal,\n): Promise<unknown> {\n const files: Blob[] = [];\n const sent = replaceDeep(args, (value) =>\n isBlob(value) ? new Upload(files.push(value) - 1) : undefined,\n );\n const json = JSON.stringify(await toJSONAsync(sent, { plugins, disabledFeatures }));\n let init: RequestInit;\n if (files.length > 0) {\n const form = new FormData();\n form.set('args', json);\n // A blob of another DOM is copied, because form data takes only its own.\n const blobs = await Promise.all(\n files.map((file: Blob) =>\n // Typed as a Blob, so the check narrows a blob of another DOM to never.\n file instanceof Blob\n ? file\n : (file as Blob)\n .arrayBuffer()\n .then((data) => new Blob([data], { type: (file as Blob).type })),\n ),\n );\n for (const [index, blob] of blobs.entries()) {\n form.set(`file${index}`, blob, (files[index] as Partial<File>).name ?? 'blob');\n }\n init = { headers: { 'x-brumate-args': 'form' }, body: form };\n } else {\n init = { headers: { 'content-type': 'application/json' }, body: json };\n }\n return post(prefix, id, { ...init, signal });\n}\n\n/**\n * Sends a form to a server function, and returns its result. The form data\n * goes as it is, files included, as when the browser posts the form.\n */\nexport async function submit(prefix: string, id: string, form: FormData): Promise<unknown> {\n return post(prefix, id, { headers: { 'x-brumate-result': '1' }, body: form });\n}\n\n/** Posts to a server function, and reads its answer. */\nasync function post(prefix: string, id: string, init: RequestInit): Promise<unknown> {\n return answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}`, { ...init, method: 'POST' }),\n );\n}\n\n/** Reads the answer of a server function: its result, a redirect or an error. */\nasync function answer(id: string, response: Response): Promise<unknown> {\n // The server functions whose memos load again, from `refresh` on the server.\n const refreshed = response.headers.get('x-brumate-refresh');\n if (refreshed) {\n const ids = refreshed.split(',');\n void refreshMemos(ids);\n document.dispatchEvent(new CustomEvent('brumate:refresh', { detail: ids }));\n }\n const location = response.headers.get('x-brumate-redirect');\n if (location !== null) {\n // The loader navigates on the client when it can. Without client navigation, the page loads in full.\n const redirect = new CustomEvent('brumate:redirect', { detail: location, cancelable: true });\n if (document.dispatchEvent(redirect)) {\n window.location.assign(location);\n }\n // The page is leaving, so the call never settles.\n return new Promise(() => {});\n }\n if (!response.ok) {\n let message = `Server function \"${id}\" failed with status ${response.status}`;\n try {\n message = ((await response.json()) as { error: string }).error;\n } catch {\n // The body is not the error of a server function.\n }\n throw Object.assign(new Error(message), { name: 'ServerError', status: response.status });\n }\n // Promises and async iterables in the result settle as the rest of the answer arrives.\n return fromChunkStream(response.body!);\n}\n\n// The code below reads the core with `import()`, not a static import: a module that imports\n// the core statically would make the package build move the core into a chunk of its own, behind\n// a module that only re-exports it, which a page loads one after the other. The core is loaded\n// already when it runs, so the import costs no request. It names the exports it uses, so a build\n// keeps only them.\n\n/**\n * Loads again the memos that call these server functions, after a server\n * function named them with `refresh`. Each component on the page knows its\n * own memos, from its client module. It is here, and not in the core, because\n * only the answer of a server call starts it.\n */\nexport function refreshMemos(ids: string[]): Promise<void> {\n return import('./client.ts').then(({ descendants, loadModule, loadPart, scopes }) => {\n for (const root of scopes.values()) {\n if (!root.m) {\n continue;\n }\n void loadModule(root.m).then(async (module) => {\n const entries = ids.flatMap((id) => module.refresh?.[id] ?? []);\n if (entries.length === 0) {\n return;\n }\n const updates = await loadPart(module, 'update');\n for (const [kind, name] of entries) {\n for (const target of kind === root.k ? [root] : descendants(root, kind)) {\n if (scopes.has(target.id)) {\n (updates[name] as (scope: Scope) => void)(target);\n }\n }\n }\n });\n }\n });\n}\n\n/**\n * Sends a form to the server function of its `$action`, and writes the\n * result into the `$action` when it arrives. It is pending until then. See\n * `submitAction` in the core.\n */\nexport function sendAction(form: HTMLFormElement, submitter: HTMLElement | null): Promise<void> {\n const [scopeId, slot] = form.getAttribute('b-result')!.split(':').map(Number) as [number, number];\n const data = new FormData(form, submitter);\n const action = form.getAttribute('b-action')!;\n return import('./client.ts').then(({ asyncMemo, rpcPrefix, scopes, track }) => {\n const scope = scopes.get(scopeId);\n if (scope) {\n asyncMemo(scope, slot, track(submit(rpcPrefix, action, data)));\n }\n });\n}\n"],"mappings":";;;;;;;AAUA,SAAS,OAAO,OAA+B;CAC7C,IAAI,iBAAiB,MACnB,OAAO;CAET,MAAM,OAAO;CACb,OACE,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,gBAAgB,cAC5B,OAAO,KAAK,UAAU;AAE1B;;;;;;;;AASA,eAAsB,KACpB,QACA,IACA,MACA,QACkB;CAClB,MAAM,QAAgB,CAAC;CACvB,MAAM,OAAO,YAAY,OAAO,UAC9B,OAAO,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,KAAK,IAAI,CAAC,IAAI,KAAA,CACtD;CACA,MAAM,OAAO,KAAK,UAAU,MAAM,YAAY,MAAM;EAAE;EAAS;CAAiB,CAAC,CAAC;CAClF,IAAI;CACJ,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,OAAO,IAAI,SAAS;EAC1B,KAAK,IAAI,QAAQ,IAAI;EAErB,MAAM,QAAQ,MAAM,QAAQ,IAC1B,MAAM,KAAK,SAET,gBAAgB,OACZ,OACC,KACE,YAAY,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,IAAI,CAAC,CAAC;CAEjE,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","names":["id","spreadText"],"sources":["../../src/runtime/client.ts"],"sourcesContent":["import {\n VOID_ELEMENTS,\n actionAttributes,\n attributeText,\n insertValue,\n rawHTML,\n spread as spreadText,\n textValue,\n} from './html.ts';\nimport type { Raw } from './html.ts';\nimport {\n CHILDREN,\n ElementReference,\n FunctionReference,\n ITEM,\n ITEM_SLOT,\n MODULE,\n OWNER,\n SOURCE,\n isAsyncIterable,\n stateValues,\n} from './shared.ts';\nimport type { PackedState, PageState, ScopeState } from './shared.ts';\nimport type { Context as ContextValue } from './context.ts';\n\nexport { affix, attribute, classAttribute, escape, raw, spread, vars } from './html.ts';\nexport type { Raw } from './html.ts';\nexport { produce } from './produce.ts';\n// For `client-routes.ts`, which reads the core with `import()`.\nexport { ElementReference, FunctionReference } from './shared.ts';\nexport { createContext } from './context.ts';\n\ntype Update = [kind: number, name: string];\n\n/** The entry of a compiled client module. */\nexport interface ClientModule {\n id: string;\n /** Prop names to slot indices. `*` is the slot of a props object. */\n props: Record<string, number>;\n /** Scope kind, then slot, to the updates that read it. */\n g: Record<number, Record<number, Update[]>>;\n /**\n * Imports a part of the module. A module without it holds every part\n * itself, as a small component's module does.\n */\n load?: (part: string) => Promise<Part>;\n /** Server function ID to the memos that call it, as scope kind and update, for `refresh`. */\n refresh?: Record<string, Update[]>;\n}\n\n/** A part of a client module: one client root, or the updates. */\nexport type Part = Record<string, unknown>;\n\n/** The part that holds an export: `h<n>` and `c<n>` have their own, the rest are in `update`. */\nfunction partOf(name: string): string {\n return /^[hc]\\d/.test(name) ? name : 'update';\n}\n\n/** The instance of a scope in the page. */\nexport interface Scope {\n id: number;\n /** The scope's ID in the compiled component. */\n k: number;\n p?: Scope;\n /** The component ID, for a component's root scope. */\n m?: string;\n s: unknown[];\n /** The item of a list item scope. */\n i?: unknown;\n c?: Record<number, number>;\n /** The scope that rendered a component's root scope. */\n o?: Scope;\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 children: Set<Scope>;\n /** The `b-root` of the render that the server rendered the scope in. */\n r?: string;\n cleanups?: Map<string, () => void>;\n keys?: Map<number, unknown>;\n /** Set while the scope is the body of an `#offscreen` block that is hidden. */\n h?: HiddenBody;\n /** Effects and `$client` callbacks to run when the `#offscreen` body around the scope shows. */\n w?: Set<string>;\n}\n\nexport interface CoreOptions {\n /**\n * Imports the client module of a component. Undefined for a component that\n * has no client code, which a build leaves out.\n */\n load: (id: string) => Promise<ClientModule> | undefined;\n /** Adds event listeners for the `b-on` attributes in new markup. */\n listen: (root: ParentNode) => void;\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n}\n\n// The core keeps only what every page needs: it reads the state, runs handlers and updates.\n// Each helper that compiled code calls is an export of its own, so a build leaves out the ones\n// that no component calls. Features that change how the core reads the page, such as client\n// navigation and hot updates, live in their own modules and set `hooks` when they load.\n\nlet options: CoreOptions;\n/** The URL prefix of server function calls, from the options. */\nexport let rpcPrefix = '/_brumate';\n/** The scopes of the page, by ID. */\nexport const scopes: Map<number, Scope> = new Map();\n\n/** What modules of optional features add to the core. See `client-routes.ts` and `hot`. */\nexport const hooks: {\n /** Changes a state record before its scopes are added, such as for a page that navigation added. */\n record?: (script: Element, state: PageState) => PageState;\n /** Runs after the scopes of a state record are added. */\n added?: (added: Scope[]) => void;\n} = {};\n\n/** What the devtools overlay hears from the core. It is set only in development. */\nexport interface DevtoolsHooks {\n /** The core started, with the scopes of the page, and a way to write a slot, as a handler does. */\n attach?(core: {\n scopes: Map<number, Scope>;\n set: (scope: Scope, slot: number, value: unknown) => void;\n }): void;\n /** A handler starts for an event. */\n handler?(ref: string, element: Element, event?: Event): void;\n /** A part of a component's client code loaded. */\n part?(component: string, name: string): void;\n /** A slot got a new value. */\n write?(scope: Scope, slot: number, value: unknown): void;\n}\n\n/** The global key of the devtools hooks. */\nexport const DEVTOOLS: unique symbol = Symbol.for('brumate.devtools');\n\n/**\n * True on the dev server, which has the devtools. A Vite build replaces it\n * with `false`, so the calls of the devtools hooks are left out. Without\n * Vite, `import.meta.env` is undefined, and the hooks are off.\n */\nconst DEV = (import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\nfunction devtools(): DevtoolsHooks | undefined {\n return (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS];\n}\nconst modules = new Map<string, ClientModule>();\nconst loading = new Map<string, Promise<ClientModule>>();\nconst parts = new Map<string, Promise<Part>>();\nconst loadedParts = new Map<string, Part>();\nconst comments = new Map<string, Comment>();\nconst elements = new Map<string, Element>();\n// Scopes that the client creates get negative IDs, so they never match IDs\n// from state records that the server streams later.\nlet nextId = -1;\n\n// Records of one render share references through an array, so a later record can settle a\n// promise of an earlier one. Each render on the page has its own array, by its `b-root`.\nconst refs = new Map<string, unknown[]>();\n\n/**\n * A state record: its script, and its code, which seroval wrote. The code\n * takes the references of its render and the functions that make brumate's\n * values, and returns the value of the record.\n */\ntype StateRecord = [\n script: HTMLScriptElement | null,\n code: (refs: unknown[], values: typeof stateValues) => unknown,\n];\n\n/**\n * The records that ran before the core started, or while it stopped. Each\n * state script hands its record to `push`, which the core replaces while it\n * runs, so it reads later records at once.\n */\nfunction stateQueue(): StateRecord[] {\n const global = globalThis as { $brm?: StateRecord[] };\n return (global.$brm ??= []);\n}\n\n/** Reads the records that later state scripts hand over. Set while the core runs. */\nfunction pushRecords(...added: StateRecord[]): number {\n for (const record of added) {\n readRecord(record);\n }\n return 0;\n}\n\n/**\n * Reads a state record. The first record holds the page state, and later\n * records settle the promises in it.\n */\nfunction readRecord([script, code]: StateRecord): void {\n // A record of a page that navigation replaced before the core started.\n if (!script?.isConnected) {\n return;\n }\n const root = script.getAttribute('b-root') ?? '0';\n if (!refs.has(root)) {\n refs.set(root, []);\n }\n const decoded = code(refs.get(root)!, stateValues);\n // Records with scopes: the page state, and the state of each `#loading` body.\n if (script.hasAttribute('b-scopes')) {\n const unpacked = unpackState(decoded as PackedState);\n const added = addScopes(hooks.record ? hooks.record(script, unpacked) : unpacked, root);\n if (writes > 0) {\n refresh(added);\n }\n }\n}\n\n/**\n * Updates scopes that the server rendered before values changed on the\n * client, such as the body of a `#loading` block that streams in after an\n * event. Effects do not run: they run only when a value changes.\n */\nfunction refresh(added: Scope[]): void {\n for (const scope of added) {\n const id = rootOf(scope).m;\n if (!id) {\n continue;\n }\n void loadModule(id).then(async (module) => {\n const names = new Set<string>();\n for (const slots of Object.values(module.g)) {\n for (const entries of Object.values(slots)) {\n for (const [kind, name] of entries) {\n if (kind === scope.k && name[0] !== 'e') {\n names.add(name);\n }\n }\n }\n }\n if (names.size === 0) {\n return;\n }\n const updates = await loadPart(module, 'update');\n // Memos first, so the other updates read their new values.\n for (const name of [...names].toSorted(\n (a, b) => Number(b[0] === 'm') - Number(a[0] === 'm'),\n )) {\n if (scopes.has(scope.id)) {\n (updates[name] as (scope: Scope) => void)(scope);\n }\n }\n });\n }\n}\n\n/** Reads the groups of scope records back into one record per scope. See `PackedState`. */\nfunction unpackState(state: PackedState): PageState {\n // Items to take from the list in a slot of another record, once every record is read.\n const taken: [records: ScopeState[], source: number, slot: number, first: number][] = [];\n for (const group of state.g ?? []) {\n const [k, base, flags] = group as number[];\n const count = group[3] as number;\n let at = 4;\n const m = flags & MODULE ? (group[at++] as string) : undefined;\n const source: ScopeState[] | undefined = flags & SOURCE ? [] : undefined;\n if (source) {\n taken.push([source, group[at++] as number, group[at++] as number, flags & ITEM_SLOT]);\n }\n // The first slot of a taken item is not written. The gap before the slots holds its place.\n const skip = source && flags & ITEM_SLOT ? 1 : 0;\n let id = flags & OWNER ? 0 : base;\n while (at < group.length) {\n id += group[at++] as number;\n const s = group.slice(at - skip, (at += count - skip));\n const record: ScopeState = flags & OWNER ? { k, o: id - base } : { k, p: base };\n record.s = s;\n if (m !== undefined) {\n record.m = m;\n }\n if (source) {\n source.push(record);\n } else if (flags & ITEM_SLOT) {\n record.i = s[0];\n } else if (flags & ITEM) {\n record.i = group[at++];\n }\n if (flags & CHILDREN) {\n record.c = group[at++] as Record<number, number>;\n }\n state[id] = record;\n }\n }\n delete state.g;\n for (const [records, source, slot, first] of taken) {\n // An array, or a Set, whose order the state keeps.\n const values = Array.from(state[source]!.s![slot] as Iterable<unknown>);\n for (let n = 0; n < records.length; n++) {\n const record = records[n]!;\n record.i = values[n];\n if (first) {\n record.s![0] = values[n];\n }\n }\n }\n return state;\n}\n\nfunction addScopes(state: PageState, root: string): Scope[] {\n const added: Scope[] = [];\n for (const [key, record] of Object.entries(state)) {\n const id = Number(key);\n const scope: Scope = {\n id,\n k: record.k ?? 0,\n m: record.m,\n s: record.s ?? [],\n i: record.i,\n c: record.c,\n v: record.v,\n x: record.x,\n children: new Set(),\n r: root,\n };\n scopes.set(id, scope);\n added.push(scope);\n }\n for (const scope of added) {\n const record = state[scope.id]!;\n if (record.p !== undefined) {\n scope.p = scopes.get(record.p);\n scope.p?.children.add(scope);\n treeChanges++;\n }\n if (record.o !== undefined) {\n scope.o = scopes.get(record.o);\n }\n }\n const seen = new Set<object>();\n for (const scope of added) {\n // A provided value can hold functions, which a component that reads the context calls.\n for (const key of Object.keys(scope.v ?? {})) {\n scope.v![key] = callable(scope.v![key], seen);\n }\n for (let i = 0; i < scope.s.length; i++) {\n const value = callable(scope.s[i], seen);\n scope.s[i] = value;\n // A value that a later state record settles replaces its promise.\n if (value instanceof Promise) {\n void value.then((result) => {\n settled.set(value, result);\n if (scope.s[i] === value) {\n set(scope, i, result);\n }\n });\n }\n }\n }\n hooks.added?.(added);\n return added;\n}\n\n/**\n * Indexes the markers of markup that others insert, such as streamed\n * `#loading` bodies and the pages that navigation adds, so `findComment` can\n * take its records at once.\n */\nlet markerObserver: MutationObserver | undefined;\n\n/** Stops reading state records and markers that arrive later. Later records wait for `init`. */\nexport function dispose(): void {\n const queue = stateQueue();\n if (queue.push === pushRecords) {\n // The array's own `push` again, so records wait in it.\n delete (queue as { push?: unknown }).push;\n }\n markerObserver?.disconnect();\n markerObserver = undefined;\n}\n\n/**\n * Stops reading, before client navigation replaces only some routes. The\n * server renders the new routes with its current values, so only the writes\n * that come after count for the records that stream in later.\n */\nexport function leaveRoutes(): void {\n dispose();\n writes = 0;\n}\n\n/**\n * Removes the scopes of a render, by its `b-root`, with the scopes inside\n * them. Their cleanups run, and their memos no longer load. Its markup\n * stays. `brumate/testing` calls it when a mounted component unmounts.\n */\nexport function removeRoot(root: string): void {\n const inside = (scope: Scope): boolean => {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current.r === root) {\n return true;\n }\n }\n return false;\n };\n // Deleting from a map while iterating it is safe.\n for (const scope of scopes.values()) {\n if (inside(scope)) {\n removeScope(scope);\n }\n }\n refs.delete(root);\n for (const cache of [comments, elements]) {\n for (const [key, node] of cache) {\n if (!node.isConnected) {\n cache.delete(key);\n }\n }\n }\n}\n\n/**\n * Forgets the code of components that changed on the dev server, so the next\n * event or update loads the new code. Their state stays. `brumate/hot` calls it.\n */\nexport function forget(ids: string[]): void {\n for (const id of ids) {\n modules.delete(id);\n loading.delete(id);\n // Deleting the entry that a loop is at is safe for a Map.\n for (const key of parts.keys()) {\n if (key.startsWith(`${id}:`)) {\n parts.delete(key);\n loadedParts.delete(key);\n }\n }\n }\n}\n\n/** The values of the signals of components whose markup changed, for when the page renders again. */\nconst remounts = new Map<\n string,\n { after: Record<number, string[]>; values: Record<string, unknown>[] }\n>();\n\n/**\n * Keeps the values of the signals of each instance of a component, by\n * name, before the page renders again with its new markup. `brumate/hot` calls it.\n */\nexport function remount(\n detail: {\n id: string;\n before: Record<number, string[]>;\n after: Record<number, string[]>;\n signals: string[];\n }[],\n): void {\n hooks.added = restoreRemounts;\n for (const { id, before, after, signals } of detail) {\n const names = new Set(signals);\n const instances = [...scopes.values()].filter((scope) => scope.m === id);\n remounts.set(id, {\n after,\n // The signals of the script of the component. Signals of blocks, such as of a `#for`\n // body, start again.\n values: instances.map((root) => {\n const values: Record<string, unknown> = {};\n (before[root.k] ?? []).forEach((name, slot) => {\n if (names.has(name)) {\n values[name] = root.s[slot];\n }\n });\n return values;\n }),\n });\n }\n}\n\n/** Writes back the values of signals that `onRemount` kept, into the instances of the new page. */\nfunction restoreRemounts(added: Scope[]): void {\n for (const [id, { after, values }] of remounts) {\n const instances = added.filter((scope) => scope.m === id);\n if (instances.length === 0) {\n continue;\n }\n remounts.delete(id);\n instances.forEach((root, index) => {\n const saved = values[index];\n (after[root.k] ?? []).forEach((name, slot) => {\n if (saved && name in saved) {\n set(root, slot, saved[name]);\n }\n });\n });\n }\n}\n\n/**\n * Forgets the page, before another page replaces it. Cleanups run. Loaded\n * modules and parts stay, so the next page does not load them again. Only\n * client navigation calls it.\n */\nexport function leavePage(): void {\n dispose();\n for (const scope of scopes.values()) {\n for (const cleanup of scope.cleanups?.values() ?? []) {\n cleanup();\n }\n }\n scopes.clear();\n comments.clear();\n elements.clear();\n pendingEffects.clear();\n hiding = undefined;\n loads.clear();\n loadingSlots.clear();\n for (const memoController of memoControllers.values()) {\n memoController.abort();\n }\n memoControllers.clear();\n // The next page reuses scope IDs, so a guess left here would match its memos.\n guesses?.map.clear();\n nextId = -1;\n refs.clear();\n writes = 0;\n // Calls of the old page that are still out no longer count for its guesses.\n calling = 0;\n callEpoch++;\n lastHandler = Promise.resolve();\n}\n\n/** Reads the page state. The loader calls it once, before the first handler. */\nexport function init(value: CoreOptions): void {\n options = value;\n rpcPrefix = value.rpc ?? '/_brumate';\n const queue = stateQueue();\n // Records that are still streaming settle their promises when their scripts run.\n queue.push = pushRecords;\n for (const record of queue.splice(0)) {\n readRecord(record);\n }\n markerObserver = new MutationObserver(indexAdded);\n markerObserver.observe(document, { childList: true, subtree: true });\n // The whole document, because `#head` content is in the head.\n indexMarkers(document.documentElement);\n if (DEV) {\n devtools()?.attach?.({ scopes, set });\n }\n}\n\n/** Replaces function references with functions that call them. */\nfunction callable(value: unknown, seen: Set<object>): unknown {\n if (value instanceof FunctionReference) {\n return (...args: unknown[]) => call(value.ref, scopes.get(value.scope), args);\n }\n if (typeof value === 'object' && value !== null && !seen.has(value)) {\n seen.add(value);\n const prototype = Object.getPrototypeOf(value);\n if (Array.isArray(value) || prototype === Object.prototype || prototype === null) {\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n record[key] = callable(record[key], seen);\n }\n }\n }\n return value;\n}\n\nexport function loadModule(id: string): Promise<ClientModule> {\n let promise = loading.get(id);\n if (!promise) {\n // A component without client code has nothing to update.\n promise = Promise.resolve(options.load(id)).then((loaded) => {\n const module = loaded ?? { id, props: {}, g: {} };\n modules.set(id, module);\n return module;\n });\n loading.set(id, promise);\n }\n return promise;\n}\n\nexport function loadPart(module: ClientModule, name: string): Promise<Part> {\n const key = `${module.id}:${name}`;\n let promise = parts.get(key);\n if (!promise) {\n promise = (module.load ? module.load(name) : Promise.resolve(module as unknown as Part)).then(\n (part) => {\n loadedParts.set(key, part);\n if (DEV) {\n devtools()?.part?.(module.id, name);\n }\n return part;\n },\n );\n parts.set(key, promise);\n }\n return promise;\n}\n\ntype Handler = (scope: Scope | undefined, ...args: unknown[]) => unknown;\n\nasync function resolve(ref: string): Promise<Handler> {\n const [id, name] = ref.split('#') as [string, string];\n const module = await loadModule(id);\n const part = await loadPart(module, partOf(name));\n return part[name] as Handler;\n}\n\nasync function call(ref: string, scope: Scope | undefined, args: unknown[]): Promise<unknown> {\n return (await resolve(ref))(scope, ...args);\n}\n\n// The handler of the previous event, once it has started.\nlet lastHandler: Promise<unknown> = Promise.resolve();\n\n/**\n * Keeps `currentTarget` on an event. The handler runs after the event has\n * finished dispatching, when the browser has already cleared it.\n */\nfunction withTarget(event: Event, element: Element): Event {\n return new Proxy(event, {\n get(target, key) {\n if (key === 'currentTarget') {\n return element;\n }\n const value: unknown = Reflect.get(target, key);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * Runs the handler `ref` for an element. The scope comes from the element's\n * `b-b` anchor, or from the nearest element around it that has one, which\n * the compiler checks is in the same scope.\n */\nexport function handle(element: Element, ref: string, event?: Event): Promise<unknown> {\n const anchor = element.closest('[b-b]')?.getAttribute('b-b');\n const scope = anchor ? scopes.get(Number(anchor.split(':')[0])) : undefined;\n // A `<window>` or `<document>` listener in a hidden `#offscreen` body does not run.\n if (scope && hiding?.hidden(scope) && element.hasAttribute('b-listen')) {\n return Promise.resolve();\n }\n const args = event ? [withTarget(event, element)] : [];\n if (DEV) {\n devtools()?.handler?.(ref, element, event);\n }\n // Parts load in parallel, but handlers start in the order of their events,\n // so an input handler runs before the submit handler of a later event.\n const loaded = resolve(ref);\n const started = lastHandler\n .then(() => loaded)\n .then((handler) => ({ value: handler(scope, ...args) }));\n lastHandler = started.catch(() => {});\n return started.then((result) => result.value);\n}\n\n/** Returns the instance of a scope by its ID. */\nexport function scopeOf(id: number): Scope | undefined {\n return scopes.get(id);\n}\n\n// Slots\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Slots hold any value.\nexport function get(scope: Scope, slot: number): any {\n const value = scope.s[slot];\n // A value that the server still streams. A memo that reads it waits for it.\n if (computing > 0 && value instanceof Promise) {\n throw new NotReady(value);\n }\n if (value instanceof ElementReference) {\n const element = findElement(value.scope, value.anchor);\n if (element) {\n scope.s[slot] = element;\n }\n return element ?? undefined;\n }\n return value;\n}\n\n// The number of writes since the page loaded, so scopes that stream in later know to update.\nlet writes = 0;\n\nexport function set<T>(scope: Scope, slot: number, value: T): T {\n if (!Object.is(scope.s[slot], value)) {\n writes++;\n scope.s[slot] = value;\n if (DEV) {\n devtools()?.write?.(scope, slot, value);\n }\n trigger(scope, slot);\n }\n return value;\n}\n\n/**\n * The names of a call of a module function, for its shared code. Each ref\n * is a slot of `scope`, `[scope, slot]` for a slot of another scope, or\n * `[value]` for a value that does not change, such as a literal argument.\n */\nexport function cells(scope: Scope, links: unknown[], names: string[]): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n names.forEach((name, index) => {\n const ref = links[index];\n let owner = scope;\n let slot: number;\n if (typeof ref === 'number') {\n slot = ref;\n } else if ((ref as unknown[]).length === 2) {\n [owner, slot] = ref as [Scope, number];\n } else {\n Object.defineProperty(result, name, { get: () => (ref as unknown[])[0], set: () => {} });\n return;\n }\n Object.defineProperty(result, name, {\n get: () => get(owner, slot),\n set: (value: unknown) => set(owner, slot, value),\n });\n });\n return result;\n}\n\n// The latest load of each async memo, by `<scope>:<slot>`, so older results are dropped.\nconst loads = new Map<string, number>();\n// Numbers loads across all memos, so a load is never numbered like an older one still in flight.\nlet loadCount = 0;\nconst loadingSlots = new Set<string>();\n\n/** Marks a memo as loading. Its readers update the first time, so `$isPending` becomes true. */\nfunction startLoading(scope: Scope, slot: number, key: string): void {\n if (!loadingSlots.has(key)) {\n loadingSlots.add(key);\n trigger(scope, slot);\n }\n}\n\n/** True for a promise, or any object with a `then` method. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as PromiseLike<unknown>).then === 'function'\n );\n}\n\n/**\n * Writes the result of an async memo when it arrives. Until then the slot\n * keeps its value, and `pending` is true. Only the latest load is written.\n */\nexport function asyncMemo(scope: Scope, slot: number, promise: Promise<unknown>): void {\n const key = `${scope.id}:${slot}`;\n const load = ++loadCount;\n loads.set(key, load);\n startLoading(scope, slot, key);\n const settle = (value?: unknown, failed = false): void => {\n if (loads.get(key) !== load) {\n return;\n }\n loadingSlots.delete(key);\n if (!failed && !Object.is(scope.s[slot], value)) {\n set(scope, slot, value);\n } else {\n trigger(scope, slot);\n }\n };\n const fail = (error: unknown): void => {\n // A newer load of the memo aborted this one.\n if (loads.get(key) === load) {\n console.error(error);\n settle(undefined, true);\n }\n };\n promise.then((value) => {\n if (!isAsyncIterable(value)) {\n settle(value);\n return;\n }\n // A stream, such as a server function that yields: the memo takes each\n // value, and is pending until the first arrives. A newer load stops it.\n void (async () => {\n try {\n for await (const item of value) {\n if (loads.get(key) !== load) {\n break;\n }\n if (loadingSlots.has(key)) {\n settle(item);\n } else if (!Object.is(scope.s[slot], item)) {\n set(scope, slot, item);\n }\n }\n } catch (error) {\n fail(error);\n }\n })();\n }, fail);\n}\n\n/** Thrown when a memo reads a value that is still loading. */\nclass NotReady extends Error {\n readonly source: Promise<unknown>;\n\n constructor(source: Promise<unknown>) {\n super('The value is still loading');\n this.source = source;\n }\n}\n\n// More than 0 while a memo computes, so reading a value that is still loading stops it.\nlet computing = 0;\n\n/** Aborts the server function calls of a memo's compute, by memo key. */\nconst memoControllers = new Map<string, AbortController>();\n/** The key of the memo that computes, if any. */\nlet memoKey: string | undefined;\n\n/** The signal for server function calls while a memo computes. It is made on the first call. */\nfunction memoSignal(): AbortSignal | undefined {\n if (memoKey === undefined) {\n return undefined;\n }\n let controller = memoControllers.get(memoKey);\n if (!controller) {\n controller = new AbortController();\n memoControllers.set(memoKey, controller);\n }\n return controller.signal;\n}\n\n/**\n * Computes a memo. A promise loads, and the memo keeps its value until it\n * settles. A memo that reads a value that is still loading keeps its value\n * too, and is pending until that value arrives and the memo computes again.\n */\nexport function memo(scope: Scope, slot: number, compute: () => unknown): void {\n const key = `${scope.id}:${slot}`;\n // A guess stays while its source has not changed, such as when a value the server streamed arrives.\n if (guesses?.same(key)) {\n return;\n }\n let value: unknown;\n // Server function calls of the last compute are aborted, because their answers are out of date.\n memoControllers.get(key)?.abort();\n memoControllers.delete(key);\n const outer = memoKey;\n memoKey = key;\n computing++;\n try {\n value = compute();\n } catch (error) {\n if (!(error instanceof NotReady)) {\n throw error;\n }\n startLoading(scope, slot, key);\n return;\n } finally {\n computing--;\n memoKey = outer;\n }\n if (isThenable(value) || isAsyncIterable(value)) {\n asyncMemo(scope, slot, Promise.resolve(value));\n return;\n }\n // The values it read have arrived, so it is no longer pending.\n const waited = loadingSlots.delete(key);\n loads.delete(key);\n // An optimistic value that computes again follows its source, and drops its guess.\n guesses?.map.delete(key);\n if (!Object.is(scope.s[slot], value)) {\n set(scope, slot, value);\n } else if (waited) {\n trigger(scope, slot);\n }\n}\n\ninterface Guesses {\n /** Optimistic values that hold a guess, with the slot that each goes back to. */\n map: Map<string, { scope: Scope; slot: number; source?: [Scope, number]; base?: unknown }>;\n same: (key: string) => boolean;\n reset: () => void;\n}\n\n/**\n * The guesses of `$optimistic` values. The first `guess` sets it, so the\n * code that reads guesses is left out of a build that makes none.\n */\nlet guesses: Guesses | undefined;\n/** The values of promises that the server streamed, so a guess knows its source did not change. */\nconst settled = new WeakMap<Promise<unknown>, unknown>();\n\n/** True while the source of a guess holds the value it had when the guess was made. */\nfunction sameSource(key: string): boolean {\n const entry = guesses!.map.get(key);\n if (!entry?.source) {\n return false;\n }\n const current = entry.source[0].s[entry.source[1]];\n return (\n Object.is(current, entry.base) ||\n (entry.base instanceof Promise && settled.get(entry.base) === current)\n );\n}\n/** Server calls that have not finished, from forms and from `rpc`. */\nlet calling = 0;\n/** Counts the pages that client navigation left, so calls of an old page are not counted down. */\nlet callEpoch = 0;\n\n/**\n * Writes a guess into an optimistic value. It goes back to its source when\n * the source changes, which computes it again, or when every server call of\n * the page finishes, such as after a post failed.\n */\nexport function guess<T>(\n scope: Scope,\n slot: number,\n ...rest: [value: T] | [sourceScope: Scope, sourceSlot: number, value: T]\n): T {\n const value = rest.at(-1) as T;\n const source = rest.length === 3 ? ([rest[0], rest[1]] as [Scope, number]) : undefined;\n const base = source && source[0].s[source[1]];\n guesses ??= { map: new Map(), same: sameSource, reset: resetGuesses };\n guesses.map.set(`${scope.id}:${slot}`, { scope, slot, source, base });\n return set(scope, slot, value);\n}\n\n/** Counts a server call, and puts guesses back when the last one finishes. */\nexport function track<T>(request: Promise<T>): Promise<T> {\n calling++;\n const epoch = callEpoch;\n const done = (): void => {\n if (epoch !== callEpoch) {\n return;\n }\n calling--;\n // Waits a task, so memos that the answer refreshed start to load first.\n setTimeout(() => calling || guesses?.reset(), 0);\n };\n request.then(done, done);\n return request;\n}\n\nfunction resetGuesses(): void {\n for (const [key, { scope, slot, source }] of guesses!.map) {\n // A source that loads again, such as a refreshed list, resets the guess when it arrives.\n if (source && pending(source[0], source[1])) {\n continue;\n }\n guesses!.map.delete(key);\n if (source && scopes.has(scope.id) && !Object.is(scope.s[slot], source[0].s[source[1]])) {\n set(scope, slot, source[0].s[source[1]]);\n }\n }\n}\n\n/** True while a new value of a memo loads, or while the server still streams its value. */\nexport function pending(scope: Scope, slot: number): boolean {\n return loadingSlots.has(`${scope.id}:${slot}`) || scope.s[slot] instanceof Promise;\n}\n\n/** `x++`, `x--`, `++x` and `--x`. */\nexport function update(scope: Scope, slot: number, delta: number, prefix: boolean): number {\n const previous = get(scope, slot) as number;\n set(scope, slot, previous + delta);\n return prefix ? previous + delta : previous;\n}\n\nfunction rootOf(scope: Scope): Scope {\n let current = scope;\n while (current.p) {\n current = current.p;\n }\n return current;\n}\n\nfunction trigger(scope: Scope, slot: number): void {\n const id = rootOf(scope).m!;\n const module = modules.get(id);\n const updates = loadedParts.get(`${id}:update`);\n if (module && updates) {\n run(module, updates, scope, slot);\n return;\n }\n // The first write to a component loads its update code. Later writes wait in order.\n void loadModule(id).then(async (loaded) => {\n if (loaded.g[scope.k]?.[slot]) {\n run(loaded, await loadPart(loaded, 'update'), scope, slot);\n }\n });\n}\n\n// Effects wait until every other update of a write has run, and run once each.\nconst pendingEffects = new Map<string, () => void>();\nlet running = 0;\nlet flushing = false;\n/** Counts changes to the scope tree, so `run` knows when the descendants it found are out of date. */\nlet treeChanges = 0;\n\nfunction run(module: ClientModule, updates: Part, scope: Scope, slot: number): void {\n running++;\n // The descendants of each kind, found once while the tree does not change.\n let found: Map<number, Scope[]> | undefined;\n let foundAt = treeChanges;\n try {\n for (const [kind, name] of module.g[scope.k]?.[slot] ?? []) {\n const fn = updates[name] as (scope: Scope) => void;\n if (kind === scope.k) {\n runUpdate(fn, name, scope);\n continue;\n }\n if (foundAt !== treeChanges) {\n found = undefined;\n foundAt = treeChanges;\n }\n found ??= new Map();\n let targets = found.get(kind);\n if (!targets) {\n targets = descendants(scope, kind);\n found.set(kind, targets);\n }\n for (const target of targets) {\n runUpdate(fn, name, target);\n }\n }\n } finally {\n running--;\n }\n if (running === 0) {\n flushEffects();\n }\n}\n\n/** Runs an update on a scope. An effect waits until the other updates have run. */\nfunction runUpdate(fn: (scope: Scope) => void, name: string, target: Scope): void {\n if (name[0] === 'e') {\n pendingEffects.set(`${target.id}:${name}`, () => {\n if (scopes.has(target.id)) {\n fn(target);\n }\n });\n } else {\n fn(target);\n }\n}\n\n/**\n * Runs the effects that writes scheduled, in the order they were first\n * scheduled. Writes in an effect schedule more effects, which run after.\n */\nfunction flushEffects(): void {\n if (flushing) {\n return;\n }\n flushing = true;\n try {\n // A map iterator also visits entries that are added while it runs.\n for (const [key, runEffect] of pendingEffects) {\n pendingEffects.delete(key);\n runEffect();\n }\n } finally {\n flushing = false;\n }\n}\n\nexport function descendants(scope: Scope, kind: number, result: Scope[] = []): Scope[] {\n for (const child of scope.children) {\n if (child.k === kind) {\n result.push(child);\n }\n descendants(child, kind, result);\n }\n return result;\n}\n\nfunction destroy(scope: Scope): void {\n for (const child of Array.from(scope.children)) {\n destroy(child);\n }\n // The content of a `#portal` is elsewhere in the page, so it is removed by its markers.\n const start = comments.get(`P${scope.id}`);\n if (start?.isConnected) {\n const end = rangeEnd(start);\n clear(start, end);\n start.remove();\n end.remove();\n }\n removeScope(scope);\n}\n\n/**\n * Removes a scope from the page: its cleanups run, and its memo state goes,\n * so a load that settles later is not written. Its markup stays.\n */\nexport function removeScope(scope: Scope): void {\n for (const cleanup of scope.cleanups?.values() ?? []) {\n cleanup();\n }\n for (let slot = 0; slot < scope.s.length; slot++) {\n const key = `${scope.id}:${slot}`;\n memoControllers.get(key)?.abort();\n memoControllers.delete(key);\n loads.delete(key);\n loadingSlots.delete(key);\n guesses?.map.delete(key);\n }\n if (scope.h) {\n hiding?.bodies.delete(scope.h);\n }\n scopes.delete(scope.id);\n scope.p?.children.delete(scope);\n treeChanges++;\n}\n\nfunction disposeKinds(scope: Scope, kinds: number[]): void {\n for (const child of Array.from(scope.children)) {\n if (kinds.includes(child.k)) {\n destroy(child);\n }\n }\n}\n\n// DOM\n\nconst MARKER = /^[btilP]-?\\d/;\n\nfunction markerKey(data: string): string {\n return data[0] === 'b' ? data.split(':').slice(0, 2).join(':') : data;\n}\n\nfunction indexMarkers(root: Node): void {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const data = (node as Comment).data;\n if (MARKER.test(data)) {\n comments.set(markerKey(data), node as Comment);\n }\n }\n}\n\n/** Indexes the markers in the nodes that mutation records added. */\nfunction indexAdded(records: MutationRecord[]): void {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n indexMarkers(node);\n } else if (node.nodeType === 8 && MARKER.test((node as Comment).data)) {\n comments.set(markerKey((node as Comment).data), node as Comment);\n }\n }\n }\n}\n\n/**\n * Finds a marker in the page. Returns undefined when the markup is not in\n * the page, such as `children` inside a block that is closed. Updates to it\n * do nothing, and it updates when the client inserts it again.\n */\nfunction findComment(key: string): Comment | undefined {\n let comment = comments.get(key);\n if (!comment?.isConnected) {\n // The index has every marker in the page once it reads the records that\n // are waiting. Before the core starts, or between pages, it reads the page.\n if (markerObserver) {\n indexAdded(markerObserver.takeRecords());\n } else {\n indexMarkers(document.documentElement);\n }\n comment = comments.get(key);\n }\n return comment?.isConnected ? comment : undefined;\n}\n\nfunction findElement(scope: number, anchor: number): Element | null {\n const key = `${scope}:${anchor}`;\n let element = elements.get(key);\n if (!element?.isConnected) {\n element = document.querySelector(`[b-b=\"${key}\"]`) ?? undefined;\n if (element) {\n elements.set(key, element);\n }\n }\n return element ?? null;\n}\n\n/** Returns the marker that ends the range that `start` opens. */\nfunction rangeEnd(start: Comment): Comment {\n let depth = 0;\n for (let node = start.nextSibling; node; node = node.nextSibling) {\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data[0] === '/') {\n if (depth === 0) {\n return node as Comment;\n }\n depth--;\n } else if (MARKER.test(data)) {\n depth++;\n }\n }\n }\n throw new Error(`Missing end marker for <!--${start.data}-->`);\n}\n\nfunction clear(start: Node, end: Node): void {\n while (start.nextSibling && start.nextSibling !== end) {\n start.nextSibling.remove();\n }\n}\n\n/**\n * Inserts rendered HTML before a node, or at the end of a parent, and runs\n * the work that waits for it.\n */\nfunction insertHTML(before: Node | { parent: ParentNode }, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n const fragment = template.content;\n // Markers that others inserted first, so the new markers win over them.\n if (markerObserver) {\n indexAdded(markerObserver.takeRecords());\n }\n indexMarkers(fragment);\n options.listen(fragment);\n const server = serverScopes(fragment);\n // The nodes of the insert, when hidden `#offscreen` markup can contain them.\n const added = hiding?.bodies.size ? [...fragment.childNodes] : undefined;\n if ('parent' in before) {\n before.parent.append(fragment);\n } else {\n before.parentNode!.insertBefore(fragment, before);\n }\n if (added) {\n hiding!.added(added);\n }\n // The records of this insert, whose markers are indexed already.\n markerObserver?.takeRecords();\n for (const fn of afterInsert.splice(0)) {\n fn();\n }\n // HTML from the server, such as `children`, can be older than the values on the client.\n if (server.length > 0) {\n refresh(server);\n }\n}\n\n/**\n * Returns the scopes from the server that markup refers to. Markup that the\n * client renders has client scopes, so these come from HTML that the server\n * rendered, such as the `children` of a component.\n */\nfunction serverScopes(root: ParentNode): Scope[] {\n const ids = new Set<number>();\n for (const element of root.querySelectorAll('[b-b]')) {\n ids.add(Number(element.getAttribute('b-b')!.split(':')[0]));\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const match = /^[tb](\\d+):/.exec((node as Comment).data);\n if (match) {\n ids.add(Number(match[1]));\n }\n }\n return [...ids].flatMap((id) => {\n const scope = scopes.get(id);\n return scope ? [scope] : [];\n });\n}\n\n/**\n * Renders a `#portal` body into its target, between markers with its scope\n * ID. `kinds` names the body, so a new target first removes it from the old one.\n */\nexport function portalTo(\n scope: Scope,\n target: unknown,\n render: Render,\n kinds: number[] = [],\n): void {\n disposeKinds(scope, kinds);\n const element = typeof target === 'string' ? document.querySelector(target) : target;\n if (!(element instanceof Element)) {\n return;\n }\n // The body's scope is the first scope that the render creates.\n const id = nextId;\n insertHTML({ parent: element }, `<!--P${id}-->${render(scope)}<!--/P-->`);\n}\n\n/** Writes an inserted value between `<!--t…-->` and `<!--/t-->`. */\nexport function text(scope: Scope, anchor: number, value: unknown): void {\n const start = findComment(`t${scope.id}:${anchor}`);\n if (start) {\n write(start.parentNode!, start.nextSibling, rangeEnd(start), value);\n }\n}\n\n/** Writes an inserted value that is the whole content of the element with the anchor. */\nexport function content(scope: Scope, anchor: number, value: unknown): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n write(element, element.firstChild, null, value);\n }\n}\n\n/**\n * Writes the text of an element whose content is text, such as a `<textarea>`\n * or a `<title>`. A `<textarea>` gets the value too, as `value` does on an\n * `<input>`, so a change replaces what the user typed.\n */\nexport function writeText(scope: Scope, anchor: number, value: unknown): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n const written = textValue(value);\n element.textContent = written;\n if (element instanceof HTMLTextAreaElement) {\n element.value = written;\n }\n }\n}\n\n/**\n * Replaces the nodes of `parent` from `first` up to `end`, or to its last\n * child, with a value. A text node that stays a text node keeps its node.\n */\nfunction write(\n parent: Node & ParentNode,\n first: ChildNode | null,\n end: Node | null,\n value: unknown,\n): void {\n if (\n (typeof value === 'string' || typeof value === 'number') &&\n first?.nodeType === 3 &&\n first.nextSibling === end\n ) {\n // Hidden text keeps its new value for when it shows.\n const saved = hiding?.nodes.get(first);\n if (saved) {\n saved.v = String(value);\n } else {\n (first as Text).data = String(value);\n }\n return;\n }\n while (first && first !== end) {\n const next = first.nextSibling;\n first.remove();\n first = next;\n }\n insertHTML(end ?? { parent }, insertValue(value));\n}\n\nfunction setAttribute(element: Element, name: string, value: unknown): void {\n if (name === 'value' || name === 'checked') {\n (element as unknown as Record<string, unknown>)[name] =\n name === 'checked' ? Boolean(value) : (value ?? '');\n }\n const written = attributeText(name, value);\n if (written === undefined) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, written);\n }\n if (name === 'style') {\n hiding?.styled(element);\n }\n}\n\nexport function attr(scope: Scope, anchor: number, name: string, value: unknown): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n setAttribute(element, name, value);\n }\n}\n\nexport function attrs(scope: Scope, anchor: number, values: Record<string, unknown>): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n for (const [name, value] of Object.entries(values)) {\n if (name !== 'children' && !/^on[A-Z]/.test(name)) {\n setAttribute(element, name, value);\n }\n }\n }\n}\n\ntype Render = (parent: Scope, item?: unknown, index?: number) => string;\n\n/** Shows the branch at `index` of `#if` or `#switch`, or nothing for -1. */\nexport function branch(\n scope: Scope,\n anchor: number,\n index: number,\n renders: (Render | undefined)[],\n kinds: number[],\n): void {\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n if (Number(start.data.split(':')[2]) === index) {\n return;\n }\n const end = rangeEnd(start);\n disposeKinds(scope, kinds);\n clear(start, end);\n start.data = `b${scope.id}:${anchor}:${index}`;\n const render = renders[index];\n if (render) {\n insertHTML(end, render(scope));\n }\n}\n\n/** Renders the body of `#key` again when its value changes. */\nexport function rekey(\n scope: Scope,\n anchor: number,\n value: unknown,\n render: Render,\n kinds: number[],\n): void {\n scope.keys ??= new Map();\n if (scope.keys.has(anchor) && Object.is(scope.keys.get(anchor), value)) {\n return;\n }\n scope.keys.set(anchor, value);\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n disposeKinds(scope, kinds);\n clear(start, end);\n insertHTML(end, render(scope));\n}\n\n/**\n * Renders the body of a `#try` block again, for its `reset` function. If the\n * body throws, the fallback renders again with the error.\n */\nexport async function reset(\n scope: Scope,\n anchor: number,\n id: string,\n body: string,\n fallback: string,\n kinds: number[],\n): Promise<void> {\n const updates = await loadPart(await loadModule(id), 'update');\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n disposeKinds(scope, kinds);\n clear(start, end);\n let html: string;\n try {\n html = (updates[body] as Render)(scope);\n } catch (error) {\n // Scopes that the body created before it threw.\n disposeKinds(scope, kinds);\n afterInsert.length = 0;\n html = (updates[fallback] as (parent: Scope, error: unknown) => string)(scope, error);\n }\n insertHTML(end, html);\n}\n\n/** Renders the body of a `#client` block once. */\nexport function fill(scope: Scope, anchor: number, render: Render): void {\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n if (start.nextSibling === end) {\n insertHTML(end, render(scope));\n }\n}\n\n/**\n * Shows or hides the body of an `#offscreen` block. A body that the page\n * does not have yet renders the first time it shows. `kind` is the body's\n * scope ID in the compiled component.\n */\nexport function offscreen(\n scope: Scope,\n anchor: number,\n value: unknown,\n render: Render,\n kind: number,\n): void {\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n const visible = Boolean(value);\n // 1 for a body that shows, 0 for one that is hidden, and -1 for one that has not rendered.\n const state = start.data.split(':')[2];\n if (visible ? state === '1' : state !== '1') {\n return;\n }\n start.data = `b${scope.id}:${anchor}:${visible ? 1 : 0}`;\n const end = rangeEnd(start);\n if (state === '-1') {\n insertHTML(end, render(scope));\n return;\n }\n let body: Scope | undefined;\n for (const child of scope.children) {\n if (child.k === kind) {\n body = child;\n }\n }\n if (body) {\n hiding ??= createHiding();\n if (visible) {\n hiding.show(body);\n } else {\n hiding.hide(body, start, end);\n }\n }\n}\n\n/** A hidden `#offscreen` body: its scope, and the ranges of its markup and of its portals. */\nexport interface HiddenBody {\n scope: Scope;\n ranges: [start: Comment, end: Comment][];\n}\n\n/**\n * What a hidden node had before it was hidden: `n` hidden bodies that hide\n * it, and the text of a text node, or the inline `display` of an element\n * with its priority and whether it had a `style` attribute.\n */\ninterface Saved {\n n: number;\n v: string;\n p?: string;\n a?: boolean;\n}\n\ninterface Hiding {\n bodies: Set<HiddenBody>;\n nodes: WeakMap<Node, Saved>;\n hide: (body: Scope, start: Comment, end: Comment) => void;\n show: (body: Scope) => void;\n /** True for a scope in a hidden body. */\n hidden: (scope: Scope) => boolean;\n /** Keeps an effect for when its body shows, and returns true, if its scope is hidden. */\n paused: (scope: Scope, name: string) => boolean;\n /** Hides the nodes that an insert added to hidden markup. */\n added: (nodes: Node[]) => void;\n /** Keeps an element hidden after its `style` attribute changed. */\n styled: (element: Element) => void;\n}\n\n/**\n * The code of hidden `#offscreen` bodies. The first body that hides sets it\n * up, so the core of a page without one only checks that it is not there.\n * A body is hidden with an inline `display: none !important` on each element\n * at its top level, which no stylesheet overrides, and empty text for each\n * text node. The nodes stay in the page, so form fields, focus and media\n * keep their state.\n */\nlet hiding: Hiding | undefined;\n\n/** True for a scope that is `ancestor` or inside it, also through the owner of a component. */\nfunction within(scope: Scope, ancestor: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\n/** True for a scope in a hidden `#offscreen` body. */\nfunction hidden(scope: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current.h) {\n return true;\n }\n }\n return false;\n}\n\n/** The nodes between two markers. */\nfunction between([start, end]: [Comment, Comment]): Node[] {\n const result: Node[] = [];\n for (let node = start.nextSibling; node && node !== end; node = node.nextSibling) {\n result.push(node);\n }\n return result;\n}\n\n/** The inline style of an element, which an element that is not HTML or SVG may not have. */\nfunction display(element: Element): CSSStyleDeclaration | undefined {\n return (element as HTMLElement).style;\n}\n\nfunction createHiding(): Hiding {\n const bodies = new Set<HiddenBody>();\n const nodes = new WeakMap<Node, Saved>();\n const hideNode = (node: Node): void => {\n const saved = nodes.get(node);\n if (saved) {\n saved.n++;\n return;\n }\n if (node.nodeType === 3) {\n nodes.set(node, { n: 1, v: (node as Text).data });\n (node as Text).data = '';\n return;\n }\n const style = node.nodeType === 1 ? display(node as Element) : undefined;\n if (style) {\n nodes.set(node, {\n n: 1,\n v: style.getPropertyValue('display'),\n p: style.getPropertyPriority('display'),\n a: (node as Element).hasAttribute('style'),\n });\n style.setProperty('display', 'none', 'important');\n }\n };\n const showNode = (node: Node): void => {\n const saved = nodes.get(node);\n if (!saved || --saved.n > 0) {\n return;\n }\n nodes.delete(node);\n if (node.nodeType === 3) {\n (node as Text).data = saved.v;\n return;\n }\n const element = node as Element;\n const style = display(element)!;\n if (saved.v) {\n style.setProperty('display', saved.v, saved.p);\n } else {\n style.removeProperty('display');\n }\n if (!saved.a && element.getAttribute('style') === '') {\n element.removeAttribute('style');\n }\n };\n return {\n bodies,\n nodes,\n hidden,\n hide(body, start, end) {\n const record: HiddenBody = { scope: body, ranges: [[start, end]] };\n body.h = record;\n bodies.add(record);\n const inside = [...scopes.values()].filter((scope) => within(scope, body));\n for (const scope of inside) {\n // The content of a `#portal` in the body, elsewhere in the page.\n const portal = comments.get(`P${scope.id}`);\n if (portal?.isConnected) {\n record.ranges.push([portal, rangeEnd(portal)]);\n }\n }\n for (const range of record.ranges) {\n between(range).forEach(hideNode);\n }\n // Effects and `$client` callbacks that ran stop, and run again when the body shows.\n for (const scope of inside) {\n for (const [name, cleanup] of scope.cleanups ?? []) {\n cleanup();\n (scope.w ??= new Set()).add(name);\n }\n scope.cleanups?.clear();\n }\n },\n show(body) {\n const record = body.h;\n if (!record) {\n return;\n }\n body.h = undefined;\n bodies.delete(record);\n for (const range of record.ranges) {\n if (range[0].isConnected) {\n between(range).forEach(showNode);\n }\n }\n for (const scope of scopes.values()) {\n if (scope.w && within(scope, body) && !hidden(scope)) {\n const ref = `${rootOf(scope).m}#`;\n for (const name of scope.w) {\n void call(ref + name, scope, []);\n }\n scope.w = undefined;\n }\n }\n },\n paused(scope, name) {\n if (bodies.size === 0 || !hidden(scope)) {\n return false;\n }\n (scope.w ??= new Set()).add(name);\n return true;\n },\n added(added) {\n for (const node of added) {\n for (const record of bodies) {\n for (const [start, end] of record.ranges) {\n if (\n node.parentNode === start.parentNode &&\n start.compareDocumentPosition(node) & 4 &&\n node.compareDocumentPosition(end) & 4\n ) {\n hideNode(node);\n }\n }\n // A `#portal` that renders in a hidden body, whose nodes follow its marker.\n const data = node.nodeType === 8 ? (node as Comment).data : '';\n const scope = /^P-?\\d+$/.test(data) ? scopes.get(Number(data.slice(1))) : undefined;\n if (scope && within(scope, record.scope)) {\n record.ranges.push([node as Comment, rangeEnd(node as Comment)]);\n }\n }\n }\n },\n styled(element) {\n const saved = nodes.get(element);\n const style = display(element);\n if (saved && style) {\n saved.v = style.getPropertyValue('display');\n saved.p = style.getPropertyPriority('display');\n saved.a = element.hasAttribute('style');\n style.setProperty('display', 'none', 'important');\n }\n },\n };\n}\n\ninterface Item {\n scope: Scope;\n nodes: Node[];\n}\n\n/** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */\nexport function list(\n scope: Scope,\n anchor: number,\n items: unknown[],\n key: (item: unknown, index: number) => unknown,\n render: Render,\n assign: (scope: Scope, item: unknown, index: number) => void,\n fallback: Render | undefined,\n fallbackKinds: number[],\n): void {\n const start = findComment(`b${scope.id}:${anchor}`);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n const previous = new Map<unknown, Item>();\n const others: Node[] = [];\n let position = 0;\n for (let node = start.nextSibling; node && node !== end;) {\n const data = node.nodeType === 8 ? (node as Comment).data : undefined;\n // An item between `<!--i…-->` and `<!--/i-->`, or one element whose `b-b` names the scope.\n const id = data\n ? /^i(-?\\d+)$/.exec(data)?.[1]\n : (node as Element).getAttribute?.('b-b')?.split(':')[0];\n const item = id === undefined ? undefined : scopes.get(Number(id));\n let last: Node = node;\n // The elements of the fallback have scopes of its kinds.\n if (item && (data || (item.p === scope && !fallbackKinds.includes(item.k)))) {\n if (data) {\n last = rangeEnd(node as Comment);\n }\n const nodes = [node];\n for (let current = node; current !== last;) {\n nodes.push((current = current.nextSibling!));\n }\n previous.set(key(item.i, position++), { scope: item, nodes });\n } else {\n others.push(node);\n }\n node = last.nextSibling;\n }\n\n if (items.length === 0) {\n if (previous.size === 0 && others.length > 0) {\n return;\n }\n for (const item of previous.values()) {\n destroy(item.scope);\n }\n clear(start, end);\n if (fallback) {\n insertHTML(end, fallback(scope));\n }\n return;\n }\n\n disposeKinds(scope, fallbackKinds);\n for (const node of others) {\n node.parentNode?.removeChild(node);\n }\n const parent = end.parentNode!;\n // The first node after the items placed so far. An item already there is not\n // moved, because moving a node restarts its animations and drops its focus.\n let cursor: Node = start.nextSibling!;\n // New items next to each other go into the page with one insert.\n let added = '';\n const flush = (): void => {\n if (added) {\n insertHTML(cursor, added);\n added = '';\n }\n };\n items.forEach((value, index) => {\n const id = key(value, index);\n const item = previous.get(id);\n if (item) {\n // Before the item's updates run, so they see the new items before it.\n flush();\n previous.delete(id);\n // Slots that keep their values do not trigger updates.\n assign(item.scope, value, index);\n if (item.nodes[0] === cursor) {\n cursor = item.nodes.at(-1)!.nextSibling!;\n } else {\n for (const node of item.nodes) {\n parent.insertBefore(node, cursor);\n }\n }\n } else {\n added += render(scope, value, index);\n }\n });\n flush();\n for (const item of previous.values()) {\n destroy(item.scope);\n for (const node of item.nodes) {\n node.parentNode?.removeChild(node);\n }\n }\n}\n\n/** Sets a style variable on the top-level elements of a component instance. */\nexport function setVar(scope: Scope, name: string, value: unknown): void {\n const css = value === null || value === undefined || value === false ? '' : String(value);\n for (const element of document.querySelectorAll<HTMLElement>(`[b-v=\"${scope.id}\"]`)) {\n element.style.setProperty(name, css);\n }\n}\n\n/** The scope that provides a context to `scope`: itself or the nearest one above it. */\nfunction findProvider(scope: Scope, key: string): Scope | undefined {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (current.v && key in current.v) {\n return current;\n }\n }\n return undefined;\n}\n\n/** Writes a provided value, and the slot of every scope that reads it from this provider. */\nexport function updateContext(scope: Scope, context: ContextValue<unknown>, value: unknown): void {\n scope.v ??= {};\n scope.v[context.key] = value;\n for (const target of scopes.values()) {\n const slot = target.x?.[context.key];\n if (slot !== undefined && findProvider(target, context.key) === scope) {\n set(target, slot, value);\n }\n }\n}\n\n/** Sets the title of the page. */\nexport function title(value: unknown): void {\n document.title = value === null || value === undefined ? '' : String(value);\n}\n\n/** Writes a prop of a child component. */\nexport function prop(scope: Scope, anchor: number, name: string, value: unknown): void {\n const id = scope.c?.[anchor];\n const child = id === undefined ? undefined : scopes.get(id);\n if (!child?.m) {\n return;\n }\n const apply = (module: ClientModule): void => {\n const slot = module.props[name];\n if (slot !== undefined) {\n // A promise loads as an async memo does: the prop keeps its value, and is pending until it settles.\n if (isThenable(value)) {\n asyncMemo(child, slot, Promise.resolve(value));\n } else {\n set(child, slot, value);\n }\n return;\n }\n const all = module.props['*'];\n if (all !== undefined) {\n set(child, all, { ...(get(child, all) as object), [name]: value });\n }\n };\n const module = modules.get(child.m);\n if (module) {\n apply(module);\n } else {\n void loadModule(child.m).then(apply);\n }\n}\n\n/** Runs an effect or a `$client` callback, after the cleanup of its previous run. */\nexport function effect(scope: Scope, name: string, callback: () => unknown): void {\n // In a hidden `#offscreen` body, it runs when the body shows.\n if (hiding?.paused(scope, name)) {\n return;\n }\n scope.cleanups ??= new Map();\n scope.cleanups.get(name)?.();\n const cleanup = callback();\n // An entry without a cleanup too, so a hidden `#offscreen` body knows what to run again.\n scope.cleanups.set(name, typeof cleanup === 'function' ? (cleanup as () => void) : noop);\n}\n\nfunction noop(): void {}\n\n/** Renders the attributes of a form or button that posts to a server function. */\nexport function action(name: string, id: string, method?: string, result?: string): string {\n return actionAttributes(rpcPrefix, name, id, method, result);\n}\n\n/**\n * Sends a form of an `$action`. The code is in `rpc.ts`, which every server\n * call loads, so the core holds only this.\n */\nexport function submitAction(form: HTMLFormElement, submitter: HTMLElement | null): void {\n void import('./rpc.ts').then((module) => module.sendAction(form, submitter));\n}\n\n/** Calls a server function. */\nexport async function rpc(id: string, args: unknown[]): Promise<unknown> {\n // Read before the import, while the memo that calls it computes.\n const signal = memoSignal();\n return track(import('./rpc.ts').then((module) => module.call(rpcPrefix, id, args, signal)));\n}\n\n// Rendering on the client\n\n/** Renders a value inserted in markup. */\nexport function insert(value: unknown): string {\n return insertValue(value);\n}\n\n/** A component's client render function, from its `?brumate-render` module. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Components take any props.\nexport type Component<P = any> = (props: P) => string;\n\nfunction resolveScope(scope: Scope | number | undefined): Scope | undefined {\n return typeof scope === 'number' ? scopes.get(scope) : scope;\n}\n\n/**\n * Renders a child component on the client. With `scope` and `anchor`,\n * records the child's scope so the parent can update its props.\n */\nexport function component<P>(\n Child: Component<P>,\n props: P,\n _ctx?: unknown,\n scope?: Scope | number,\n anchor?: number,\n): string {\n const parent = resolveScope(scope);\n if (parent && anchor !== undefined) {\n parent.c ??= {};\n parent.c[anchor] = nextId;\n }\n if (parent) {\n setOwner(parent);\n }\n return Child(props);\n}\n\nexport function dynamic(\n tag: unknown,\n attributes: Record<string, unknown>,\n children: Raw | undefined,\n _ctx?: unknown,\n scope?: Scope | number,\n): string {\n if (typeof tag === 'function') {\n return component(\n tag as Component,\n children ? { ...attributes, children } : attributes,\n undefined,\n scope,\n );\n }\n const name = String(tag);\n const open = `<${name}${spreadText(attributes)}>`;\n return VOID_ELEMENTS.has(name) ? open : `${open}${children ? rawHTML(children) : ''}</${name}>`;\n}\n\n/** Work that waits until rendered markup is in the page. */\nexport const afterInsert: (() => void)[] = [];\n\n/** The scope that renders the next component, which becomes its owner. */\nlet owner: Scope | undefined;\n\n// The helpers below are what the server's render context does, for markup that the client\n// renders. Each is an export of its own, so a build keeps only those that its components call.\n\n/** Creates a scope for markup that the client renders, and returns its ID. */\nexport function createScope(kind: number, parent?: Scope | number, module?: string): number {\n const id = nextId--;\n const parentScope = resolveScope(parent);\n const created: Scope = { id, k: kind, p: parentScope, m: module, s: [], children: new Set() };\n if (module !== undefined && owner) {\n created.o = owner;\n owner = undefined;\n }\n parentScope?.children.add(created);\n treeChanges++;\n scopes.set(id, created);\n return id;\n}\n\n/** The ID that `$id()` makes. Client scope IDs are negative, so they differ from the server's. */\nexport function makeId(scope: Scope | number, index: number): string {\n return `b${resolveScope(scope)!.id}-${index}`;\n}\n\n/** Sets the owner of the next component's root scope. */\nexport function setOwner(scope: Scope | number): void {\n owner = resolveScope(scope);\n}\n\n/** Provides a value of a context to the scopes inside `scope`. */\nexport function provideValue<T>(context: ContextValue<T>, value: T, scope: Scope | number): void {\n const target = resolveScope(scope)!;\n target.v ??= {};\n target.v[context.key] = value;\n}\n\n/** Reads a context, and records its slot so that changes to the provided value reach it. */\nexport function consumeContext<T>(\n context: ContextValue<T>,\n scope: Scope | number,\n slot?: number,\n): T {\n const target = resolveScope(scope)!;\n if (slot !== undefined) {\n target.x ??= {};\n target.x[context.key] = slot;\n }\n const provider = findProvider(target, context.key);\n return provider ? (provider.v![context.key] as T) : context.defaultValue;\n}\n\nexport function setSlots(id: number, values: unknown[]): void {\n scopes.get(id)!.s = values;\n}\n\nexport function setItem(id: number, value: unknown): void {\n scopes.get(id)!.i = value;\n}\n\nexport function elementAt(scope: number, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n}\n\n/** Adds the markup of a `#head` block to the document's head. */\nexport function addHead(html: string): void {\n afterInsert.push(() => insertHTML({ parent: document.head }, html));\n}\n\n/** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */\nexport function addPortal(html: string): void {\n afterInsert.push(() => insertHTML({ parent: document.body }, html));\n}\n\n/** Adds a component's stylesheet to the page, if the server did not. */\nexport function addStyle(id: string, css: string): string {\n if (!document.querySelector(`style[b-style=\"${id}\"]`)) {\n const sheet = document.createElement('style');\n sheet.setAttribute('b-style', id);\n sheet.textContent = css;\n document.head.append(sheet);\n }\n return '';\n}\n\n/** A function prop rendered on the client calls the parent's exported handler. */\nexport function handlerProp(value: unknown, ref: string, scope: Scope | number): unknown {\n if (typeof value !== 'function') {\n return value;\n }\n const instance = resolveScope(scope);\n return (...args: unknown[]) => call(ref, instance, args);\n}\n\n/**\n * What the loader calls. It is one export, so the loader's import of the core\n * names one export, and a build keeps the rest only when components call them.\n */\nexport const loader: {\n init: typeof init;\n handle: typeof handle;\n dispose: typeof dispose;\n submitAction: typeof submitAction;\n} = { init, handle, dispose, submitAction };\n"],"mappings":";;;;;;AAsDA,SAAS,OAAO,MAAsB;CACpC,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO;AACvC;AAgDA,IAAI;;AAEJ,IAAW,YAAY;;AAEvB,MAAa,yBAA6B,IAAI,IAAI;;AAGlD,MAAa,QAKT,CAAC;;AAkBL,MAAa,WAA0B,OAAO,IAAI,kBAAkB;;;;;;AAOpE,MAAM,MAAO,YAA4C,KAAK;AAE9D,SAAS,WAAsC;CAC7C,OAAQ,WAAyD;AACnE;AACA,MAAM,0BAAU,IAAI,IAA0B;AAC9C,MAAM,0BAAU,IAAI,IAAmC;AACvD,MAAM,wBAAQ,IAAI,IAA2B;AAC7C,MAAM,8BAAc,IAAI,IAAkB;AAC1C,MAAM,2BAAW,IAAI,IAAqB;AAC1C,MAAM,2BAAW,IAAI,IAAqB;AAG1C,IAAI,SAAS;AAIb,MAAM,uBAAO,IAAI,IAAuB;;;;;;AAiBxC,SAAS,aAA4B;CACnC,MAAM,SAAS;CACf,OAAQ,OAAO,SAAS,CAAC;AAC3B;;AAGA,SAAS,YAAY,GAAG,OAA8B;CACpD,KAAK,MAAM,UAAU,OACnB,WAAW,MAAM;CAEnB,OAAO;AACT;;;;;AAMA,SAAS,WAAW,CAAC,QAAQ,OAA0B;CAErD,IAAI,CAAC,QAAQ,aACX;CAEF,MAAM,OAAO,OAAO,aAAa,QAAQ,KAAK;CAC9C,IAAI,CAAC,KAAK,IAAI,IAAI,GAChB,KAAK,IAAI,MAAM,CAAC,CAAC;CAEnB,MAAM,UAAU,KAAK,KAAK,IAAI,IAAI,GAAI,WAAW;CAEjD,IAAI,OAAO,aAAa,UAAU,GAAG;EACnC,MAAM,WAA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