brumate 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-C25Sa6vq.d.ts → boot-SCWYwuUd.d.ts} +8 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BBtVTOIt.js +3506 -0
- package/dist/client-BBtVTOIt.js.map +1 -0
- package/dist/{client-D0CqSxoO.d.ts → client-Cs3o4key.d.ts} +390 -181
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-BbD7JQhj.js → defer-BLJjxqVc.js} +4 -4
- package/dist/defer-BLJjxqVc.js.map +1 -0
- package/dist/{devtools-CQgD7NPB.js → devtools-DTpsVFbn.js} +56 -82
- package/dist/devtools-DTpsVFbn.js.map +1 -0
- package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-C1Dfv6nq.js} +397 -333
- package/dist/devtools-panel-C1Dfv6nq.js.map +1 -0
- package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-DZIiMDnS.js +506 -0
- package/dist/files-DZIiMDnS.js.map +1 -0
- package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
- package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.js +31 -22
- package/dist/highlight.js.map +1 -1
- package/dist/{html-mNTKzaDD.js → html-DS9B1H-M.js} +92 -22
- package/dist/html-DS9B1H-M.js.map +1 -0
- package/dist/{html-Bq1rFxX_.d.ts → html-Gggepsf-.d.ts} +22 -5
- package/dist/index.d.ts +98 -10
- package/dist/index.js +639 -104
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BHpOw1LF.js → inspect-DomFHy5O.js} +3832 -695
- package/dist/inspect-DomFHy5O.js.map +1 -0
- package/dist/{loader-Dos_3NP0.js → loader-D62komKu.js} +20 -14
- package/dist/loader-D62komKu.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/{produce-Doc91GkX.js → produce-BNIpmZq2.js} +138 -9
- package/dist/produce-BNIpmZq2.js.map +1 -0
- package/dist/{produce-D0V0ICkz.d.ts → produce-CRfouraC.d.ts} +44 -5
- package/dist/{rpc-ygMRPmN4.js → rpc-BTMb8jap.js} +11 -6
- package/dist/rpc-BTMb8jap.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +11 -29
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +23 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -2
- package/dist/runtime/forms.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -5
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +38 -1
- package/dist/runtime/signals.js +33 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{server-CxVDYE_V.js → server-BTtsQFFw.js} +633 -163
- package/dist/server-BTtsQFFw.js.map +1 -0
- package/dist/{server-DuFYRXrd.d.ts → server-CYw15Dsg.d.ts} +103 -22
- package/dist/{static-loader-nZssh66R.js → static-loader-C_GYIFtt.js} +79 -99
- package/dist/static-loader-C_GYIFtt.js.map +1 -0
- package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-DVuLmXeu.d.ts} +2 -2
- package/dist/{stream-DCYZO4IF.js → stream-r4V5zBKm.js} +102 -16
- package/dist/stream-r4V5zBKm.js.map +1 -0
- package/dist/vite.d.ts +13 -20
- package/dist/vite.js +1956 -554
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +3 -3
- package/package.json +12 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-BD6XT-s5.js +0 -1968
- package/dist/client-BD6XT-s5.js.map +0 -1
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-BzllthiF.js.map +0 -1
- package/dist/defer-BbD7JQhj.js.map +0 -1
- package/dist/devtools-CQgD7NPB.js.map +0 -1
- package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
- package/dist/events-CSs7OwIC.js.map +0 -1
- package/dist/files-BXSSrQgc.js +0 -205
- package/dist/files-BXSSrQgc.js.map +0 -1
- package/dist/forms-Bg-CwGqX.js.map +0 -1
- package/dist/html-mNTKzaDD.js.map +0 -1
- package/dist/inspect-BHpOw1LF.js.map +0 -1
- package/dist/loader-Dos_3NP0.js.map +0 -1
- package/dist/navigate-O78d_zGN.js.map +0 -1
- package/dist/produce-Doc91GkX.js.map +0 -1
- package/dist/rpc-ygMRPmN4.js.map +0 -1
- package/dist/server-CxVDYE_V.js.map +0 -1
- package/dist/static-loader-nZssh66R.js.map +0 -1
- package/dist/stream-DCYZO4IF.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-BD6XT-s5.js","names":["spreadText","id"],"sources":["../src/runtime/client.ts"],"sourcesContent":["import { trustedHTML } from './trusted.ts';\nimport { loadOnce } from './skew.ts';\nimport {\n VOID_ELEMENTS,\n actionAttributes,\n attributeText,\n insertValue,\n bindEntry,\n handlerEntry,\n spread as spreadText,\n textValue,\n} from './html.ts';\nimport type { NavigationReport } from './navigate.ts';\nimport type { SerialEntry } from './values.ts';\nimport type { Raw } from './html.ts';\nimport {\n Binding,\n CHILDREN,\n ElementReference,\n FunctionReference,\n ITEM,\n ITEM_SLOT,\n MODULE,\n OWNER,\n PREFIX,\n SOURCE,\n SlotReference,\n isAsyncIterable,\n isBinding,\n isSlotReference,\n useSerialEntry,\n parseId,\n stateValues,\n} from './shared.ts';\nimport type { PackedState, PageState, ScopeId, ScopeState } from './shared.ts';\nimport { ROUTE_KEY } from './context.ts';\nexport { navigationContext, routeContext } from './context.ts';\nimport type { Context as ContextValue, Route } from './context.ts';\n\nexport {\n affix,\n attribute,\n classAttribute,\n escape,\n mergeAttributes,\n onAttribute,\n raw,\n vars,\n} 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, unbind } 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 * The `#try` blocks that catch errors of client code, by the scope kinds\n * inside their bodies: the kind of the scope that holds the block, the\n * anchor of the block, the render functions of the body and the `#catch`\n * body, and the kinds of both bodies.\n */\n t?: Record<\n number,\n [owner: number, anchor: number, body: string, fallback: string, kinds: number[]]\n >;\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 /^[hct]\\d/.test(name) ? name : 'update';\n}\n\n/** The instance of a scope in the page. */\nexport interface Scope {\n id: ScopeId;\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, ScopeId>;\n /** The scope that rendered a component's root scope. */\n o?: Scope;\n /** For children that a component inserted, the scope where they are, for contexts. */\n t?: 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 /** The slots of a parent that the bound props of a component write, by the slot of the prop. */\n /**\n * What the bound props write, by the slot of the prop: a slot of a parent,\n * or the setter of `$bind(name, fn)`, as a function or a reference.\n */\n b?: Record<number, unknown>;\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 /** The exports of the serial entry, for the values of the app in the page state. */\n serial?: SerialEntry;\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 /** Imports a part of a module, once for each part, as the loader preloads it. */\n loadPart?: (module: ClientModule, part: string) => Promise<Part>;\n /** Adds event listeners for the `b-on` attributes in new markup. */\n listen: (root: ParentNode) => void;\n /** Tells the loader that the markup that `listen` scanned is in the page now. */\n inserted?: () => void;\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** The ID of the build of the page, for skew protection. Calls send it, and a deploy is noticed. */\n build?: string;\n /**\n * Receives every error of client code first: of a handler, an effect, a\n * `$client` callback or a memo that loads. `scope` is the ID of the scope\n * that the code belongs to, when it has one.\n */\n onError?: (error: unknown, info: { scope?: ScopeId }) => void;\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 ID of the build of the page, from the loader. Undefined on the dev server. */\nexport let build: string | undefined;\n\n/**\n * Tells the page that the site changed since it loaded: a call answered 409\n * with another build, or the code of a handler is gone. The loader then\n * loads the next page in full, and an app can save a draft first.\n */\nexport function skew(reason: 'call' | 'code' | 'defer'): void {\n document.dispatchEvent(new CustomEvent('brumate:skew', { detail: reason }));\n}\n/** The scopes of the page, by ID. */\nexport const scopes: Map<ScopeId, 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<ScopeId, Scope>;\n set: (scope: Scope, slot: number, value: unknown) => void;\n /** Runs the code of a reference for an element, as an event or a trigger does. */\n handle?: (element: Element, ref: string, event?: Event) => Promise<unknown>;\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 /**\n * A handler ran: when its event came, when its code was ready and the\n * handlers before it had started, when the call returned, and what it\n * returned, which is a promise for an async handler.\n */\n handled?(run: {\n ref: string;\n element: Element;\n event?: string;\n begun: number;\n ready: number;\n end: number;\n result: unknown;\n }): void;\n /** The updates of a write ran: how many, and how long they took with their effects. */\n updated?(count: number, start: number, end: number): void;\n /**\n * Code of a component starts to load: its entry, or a part, and why.\n * `done` settles when it has loaded.\n */\n load?(component: string, part: string, reason: string, done: Promise<unknown>): void;\n /** The loader asks the server for the body of a `#defer` block. */\n defer?(template: Element, done: Promise<unknown>): void;\n /** A slot got a new value. */\n write?(scope: Scope, slot: number, value: unknown): void;\n /**\n * An effect or a `$client` callback, by its name in the update code, ran\n * and took `time` milliseconds, or its cleanup ran.\n */\n effect?(scope: Scope, name: string, kind: 'run' | 'cleanup', time: number): void;\n /** A client navigation changed the page: the routes that stayed, and those it replaced. */\n navigated?(report: NavigationReport): 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. With\n * `memosOnly`, as for scopes that the client just rendered with its values,\n * only the memos run, so the ones that load start.\n */\nfunction refresh(added: Scope[], memosOnly = false): void {\n // The scopes of each module, which load it once.\n const byModule = new Map<string, Scope[]>();\n for (const scope of added) {\n const id = rootOf(scope).m;\n if (!id) {\n continue;\n }\n const list = byModule.get(id);\n if (list) {\n list.push(scope);\n } else {\n byModule.set(id, [scope]);\n }\n }\n for (const [id, list] of byModule) {\n void loadModule(id, 'state').then(async (module) => {\n // The names of the updates of each kind of scope, memos first, so the other updates read\n // their new values.\n const byKind = new Map<number, string[]>();\n for (const scope of list) {\n if (!byKind.has(scope.k)) {\n byKind.set(scope.k, refreshNames(module, scope.k, memosOnly));\n }\n }\n let any = false;\n for (const names of byKind.values()) {\n any ||= names.length > 0;\n }\n if (!any) {\n return;\n }\n const updates = await loadPart(module, 'update', 'state');\n for (const scope of list) {\n for (const name of byKind.get(scope.k)!) {\n if (scopes.has(scope.id)) {\n (updates[name] as (scope: Scope) => void)(scope);\n }\n }\n }\n });\n }\n}\n\n/** The names of the updates of a kind of scope that `refresh` runs, memos first. */\nfunction refreshNames(module: ClientModule, kind: number, memosOnly: boolean): string[] {\n const memos = new Set<string>();\n const others = new Set<string>();\n for (const slots of Object.values(module.g)) {\n for (const entries of Object.values(slots)) {\n for (const [entryKind, name] of entries) {\n if (entryKind !== kind || name[0] === 'e') {\n continue;\n }\n if (name[0] === 'm') {\n memos.add(name);\n } else if (!memosOnly) {\n others.add(name);\n }\n }\n }\n }\n return [...memos, ...others];\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: ScopeId, 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 ScopeId, group[at++] as number, flags & ITEM_SLOT]);\n }\n // Scopes inside a `#loading` body: their IDs are this prefix and a number.\n const prefix = flags & PREFIX ? (group[at++] as string) : '';\n const id = (n: number): ScopeId => (prefix ? prefix + n : 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 n = flags & (OWNER | PREFIX) ? 0 : base;\n while (at < group.length) {\n n += group[at++] as number;\n const s = group.slice(at - skip, (at += count - skip));\n const record: ScopeState = flags & OWNER ? { k, o: id(n - 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, ScopeId>;\n }\n state[id(n)] = 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 = parseId(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 b: record.b,\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 if (record.t !== undefined) {\n scope.t = scopes.get(record.t);\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 unindexed.length = 0;\n rendered.length = 0;\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 renderedLoads.clear();\n for (const { timer } of timers.values()) {\n clearTimeout(timer);\n }\n timers.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 if (value.serial) {\n useSerialEntry(value.serial);\n }\n rpcPrefix = value.rpc ?? '/_brumate';\n build = value.build;\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 watchTitles(document);\n if (DEV) {\n devtools()?.attach?.({ scopes, set, handle });\n }\n}\n\n/**\n * The handlers that the core makes from references, with their references,\n * so a spread in markup that the browser renders passes them on in `b-on`,\n * as a spread on the server does.\n */\nconst handlerReferences = new WeakMap<object, FunctionReference>();\n\n/** The modifiers that the wrappers of `brumate/events` put on a handler. */\nconst MODIFIERS = Symbol.for('brumate.modifiers');\n\n/**\n * Renders an object of attributes. With `on`, a handler in it that the core\n * made from a reference goes into `on` as a `b-on` entry, with the scope and\n * the arguments of its reference and the modifiers of its wrappers.\n */\nexport function spread(attributes: Record<string, unknown>, on?: string[]): string {\n if (on) {\n for (const [name, value] of Object.entries(attributes)) {\n const reference =\n /^on[A-Z]/.test(name) && typeof value === 'function'\n ? handlerReferences.get(value)\n : undefined;\n if (reference) {\n on.push(\n handlerEntry(name, reference.ref, reference.scope, reference.modifiers, reference.args),\n );\n }\n // A binding that a rest prop passed on writes its slot, or calls its setter.\n if ((name === 'value' || name === 'checked') && isBinding(value)) {\n on.push(bindEntry(name, value.ref, setterReference(value.set)));\n }\n }\n }\n return spreadText(attributes);\n}\n\n/** The reference of the setter of a binding: as the state has it, or of a handler that the core made. */\nfunction setterReference(set: unknown): FunctionReference | undefined {\n if (set instanceof FunctionReference) {\n return set;\n }\n return typeof set === 'function' ? handlerReferences.get(set) : undefined;\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 if (isTemplate(value.ref)) {\n return templateReference(value.ref, scopes.get(value.scope));\n }\n const handler = (...args: unknown[]): unknown =>\n call(value.ref, scopes.get(value.scope), [...(value.args ?? []), ...args]);\n handlerReferences.set(handler, value);\n return handler;\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\n/**\n * Why the core loads code, for the Loading tab of the devtools: an event,\n * a call of a function prop, a template, the scopes of a state record, a\n * write, an error, a reset of `#try`, or a prop of a child.\n */\nexport type LoadReason =\n | 'event'\n | 'call'\n | 'template'\n | 'state'\n | 'write'\n | 'error'\n | 'reset'\n | 'prop';\n\nexport function loadModule(id: string, reason: LoadReason = 'write'): 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 if (DEV) {\n devtools()?.load?.(id, 'entry', reason, promise);\n }\n }\n return promise;\n}\n\nexport function loadPart(\n module: ClientModule,\n name: string,\n reason: LoadReason = 'write',\n): Promise<Part> {\n const key = `${module.id}:${name}`;\n let promise = parts.get(key);\n if (!promise) {\n let loaded: Promise<Part>;\n if (!module.load) {\n loaded = Promise.resolve(module as unknown as Part);\n } else {\n loaded = options.loadPart ? options.loadPart(module, name) : module.load(name);\n }\n promise = loaded.then((part) => {\n loadedParts.set(key, part);\n if (DEV) {\n devtools()?.part?.(module.id, name);\n }\n return part;\n });\n parts.set(key, promise);\n if (DEV) {\n devtools()?.load?.(module.id, module.load ? name : 'all', reason, promise);\n }\n }\n return promise;\n}\n\ntype Handler = (scope: Scope | undefined, ...args: unknown[]) => unknown;\n\n/** Waits forever once the page loads again, so no error shows before it goes. */\nlet reloading: Promise<never> | undefined;\n\nasync function resolve(ref: string, reason: LoadReason): Promise<Handler> {\n const [id, name] = ref.split('#') as [string, string];\n try {\n const module = await loadModule(id, reason);\n const part = await loadPart(module, partOf(name), reason);\n return part[name] as Handler;\n } catch (error) {\n // After a deploy, the files of a build can be gone. The page loads again, with the new code,\n // once for each build. Any other error, such as a module that throws, goes to `#try`.\n const next = await serverBuild();\n if (!reloading && next !== undefined && loadOnce(next)) {\n skew('code');\n location.reload();\n reloading = new Promise(() => {});\n }\n if (reloading) {\n return reloading;\n }\n throw error;\n }\n}\n\n/**\n * Asks the server for its build, after the code of a handler failed to\n * load. Returns it when it is not the build of the page. Undefined without\n * a build, when the request fails, or when the builds are the same.\n */\nasync function serverBuild(): Promise<string | undefined> {\n if (build === undefined) {\n return undefined;\n }\n try {\n const response = await fetch(`${rpcPrefix}/`, {\n method: 'POST',\n headers: { 'x-brumate-build': build },\n });\n const current = response.headers.get('x-brumate-build');\n return current !== null && current !== build ? current : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function call(ref: string, scope: Scope | undefined, args: unknown[]): Promise<unknown> {\n return (await resolve(ref, 'call'))(scope, ...args);\n}\n\n/** True for a reference to a `#template` that a component got as a prop, such as `Page#t3`. */\nfunction isTemplate(ref: string): boolean {\n return /#t\\d/.test(ref);\n}\n\n/** The code of templates that is still loading. Updates wait for it, since a render cannot. */\nconst loadingTemplates = new Set<Promise<unknown>>();\n\n/**\n * A `#template` of another component, which renders at once, as markup does.\n * Its code starts to load when the page state is read, and updates wait for it.\n */\nfunction templateReference(ref: string, scope: Scope | undefined): (...args: unknown[]) => unknown {\n let render: Handler | undefined;\n // A template that fails to load stops holding up updates too, and its error is reported.\n const code: Promise<unknown> = resolve(ref, 'template')\n .then((handler) => {\n render = handler;\n })\n .finally(() => loadingTemplates.delete(code));\n loadingTemplates.add(code);\n return (...args) => (render ? render(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, entry: string, event?: Event): Promise<unknown> {\n // A handler that a spread passed on, such as `Parent#h1@3`, runs in the scope of its owner.\n // A handler that `$handler` made has its arguments after another `@`.\n const [ref, owner, encoded] = entry.split('@') as [string, string | undefined, string?];\n const bound = encoded ? (JSON.parse(decodeURIComponent(encoded)) as unknown[]) : [];\n const anchor = owner ?? element.closest('[b-b]')?.getAttribute('b-b')?.split(':')[0];\n const scope = anchor ? scopes.get(parseId(anchor)) : 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 // `value=$bind(name)` on an element: the core writes the slot of the name, `hops` parents up\n // from the element's scope, from the value of the element, or whether a box is checked.\n // `value=$bind(name, fn)`: the setter takes the value of the element. A ref names its scope\n // after `@`, so the prefix is `$set:`.\n if (ref.startsWith('$set:')) {\n const field = element as HTMLInputElement;\n return call(ref.slice(5), scope, [\n /^(checkbox|radio)$/i.test(field.type) ? field.checked : field.value,\n ]);\n }\n if (ref.startsWith('$bind#')) {\n const [hops = 0, slot = 0] = ref.slice(6).split('.').map(Number);\n let target = scope;\n for (let hop = 0; hop < hops; hop++) {\n target = target?.p;\n }\n const field = element as HTMLInputElement;\n if (target) {\n set(target, slot, /^(checkbox|radio)$/i.test(field.type) ? field.checked : field.value);\n }\n return Promise.resolve();\n }\n const args = event ? [...bound, withTarget(event, element)] : bound;\n const begun = DEV ? performance.now() : 0;\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, 'event');\n const started = lastHandler\n .then(() => loaded)\n .then((handler) => {\n if (!DEV) {\n return { value: handler(scope, ...args) };\n }\n const ready = performance.now();\n const value = handler(scope, ...args);\n devtools()?.handled?.({\n ref,\n element,\n event: event?.type,\n begun,\n ready,\n end: performance.now(),\n result: value,\n });\n return { value };\n });\n lastHandler = started.catch(() => {});\n // An error of the handler, or of the promise that an async one returns, goes to the nearest\n // `#try` around its scope.\n return started\n .then((result) => result.value)\n .catch((error: unknown) => {\n fail(scope, error);\n });\n}\n\n/**\n * Reports an error of client code: a handler, an effect, a `$client`\n * callback or a memo that loads. It renders the `#catch` body of the nearest\n * `#try` around the scope of the code, through the parents and the owners of\n * scopes. Without one, the page gets a `brumate:error` event on `window`,\n * with the error and the scope, and the error is logged.\n */\nexport function fail(scope: Scope | undefined, error: unknown): void {\n options.onError?.(error, { scope: scope?.id });\n void (async () => {\n for (let current = scope; current; current = current.p ?? current.o) {\n const id = rootOf(current).m;\n if (!id) {\n continue;\n }\n // oxlint-disable-next-line no-await-in-loop -- Each scope can belong to another component.\n const module = await loadModule(id, 'error');\n const entry = module.t?.[current.k];\n if (!entry) {\n continue;\n }\n // The scope that holds the block, which the anchor of the block counts from.\n let owner = current.p;\n while (owner && owner.k !== entry[0]) {\n owner = owner.p;\n }\n if (owner) {\n // oxlint-disable-next-line no-await-in-loop -- The first `#try` found catches the error.\n await catchInto(owner, module, entry, error);\n return;\n }\n }\n window.dispatchEvent(new CustomEvent('brumate:error', { detail: { error, scope } }));\n console.error(error);\n })();\n}\n\n/** Renders the `#catch` body of a `#try` with an error, in place of what the block shows. */\nasync function catchInto(\n owner: Scope,\n module: ClientModule,\n [, anchor, , fallback, kinds]: NonNullable<ClientModule['t']>[number],\n error: unknown,\n): Promise<void> {\n const updates = await loadPart(module, 'update', 'error');\n const start = findComment(`b${owner.id}:${anchor}`);\n if (!start) {\n return;\n }\n const end = rangeEnd(start);\n disposeKinds(owner, kinds);\n clear(start, end);\n insertHTML(end, (updates[fallback] as (parent: Scope, error: unknown) => string)(owner, error));\n}\n\n/** Returns the instance of a scope by its ID. */\nexport function scopeOf(id: ScopeId): 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\n/**\n * Writes a slot from code of a component. A prop that a parent bound with\n * `$bind` writes the parent's slot too, through any number of levels, and\n * the parent's update of the prop then finds the value already there. A\n * binding with a setter, `$bind(name, fn)`, calls it in place of the write,\n * and the parent's update of the prop writes the value that it keeps.\n */\nexport function set<T>(scope: Scope, slot: number, value: T): T {\n const bound = scope.b?.[slot];\n if (bound === undefined || isSlotReference(bound)) {\n writeSlot(scope, slot, value);\n const target = bound && scopes.get(bound.scope);\n if (target) {\n set(target, bound.slot, value);\n }\n } else if (bound instanceof FunctionReference) {\n void call(bound.ref, scopes.get(bound.scope), [...(bound.args ?? []), value]);\n } else if (typeof bound === 'function') {\n void bound(value);\n }\n return value;\n}\n\n/** Writes a slot, and updates what reads it. */\nfunction writeSlot(scope: Scope, slot: number, value: unknown): void {\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}\n\n/** What `$bind(name)` passes a child, in markup that the browser renders. */\nexport function binding<T>(\n value: T,\n scope: Scope | ScopeId,\n slot: number,\n set?: unknown,\n): Binding<T> {\n return new Binding(\n value,\n new SlotReference(typeof scope === 'object' ? scope.id : scope, slot),\n set,\n );\n}\n\n/**\n * Records the props that a parent bound with `$bind`, among the props that a\n * component the browser renders writes: `slots` has the slot of each, by its name.\n */\nexport function bindings(\n scope: Scope | ScopeId,\n props: Record<string, unknown>,\n slots: Record<string, number>,\n): void {\n const target = typeof scope === 'object' ? scope : scopes.get(scope);\n for (const [name, slot] of Object.entries(slots)) {\n const value = props[name];\n if (target && isBinding(value)) {\n (target.b ??= {})[slot] = value.target;\n }\n }\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/** The timers of debounced and throttled memos, by `scope:slot`, with when each last computed. */\nconst timers = new Map<string, { timer?: ReturnType<typeof setTimeout>; last: number }>();\n\n/**\n * Computes a memo of `$debounced` after its value stops changing for `ms`,\n * or one of `$throttled` at most once every `ms`, with the last value after\n * the wait. The memo is pending while it waits.\n */\nexport function timed(\n scope: Scope,\n slot: number,\n ms: number,\n throttle: boolean,\n compute: () => unknown,\n): void {\n const key = `${scope.id}:${slot}`;\n const state = timers.get(key) ?? { last: -Infinity };\n timers.set(key, state);\n const run = (): void => {\n state.timer = undefined;\n state.last = Date.now();\n // A scope that left the page computes no more.\n if (scopes.get(scope.id) === scope) {\n memo(scope, slot, compute);\n }\n };\n const since = Date.now() - state.last;\n if (throttle && state.timer === undefined && since >= ms) {\n run();\n return;\n }\n if (!throttle) {\n clearTimeout(state.timer);\n state.timer = undefined;\n }\n state.timer ??= setTimeout(run, throttle ? ms - since : ms);\n startLoading(scope, slot, key);\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 failed = (error: unknown): void => {\n // A newer load of the memo aborted this one. The memo keeps its value, and the error goes\n // to the nearest `#try` around the memo.\n if (loads.get(key) === load) {\n fail(scope, 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 failed(error);\n }\n })();\n }, failed);\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 const rendered = scope.s[slot];\n if (renderedLoads.delete(key) && isThenable(rendered)) {\n asyncMemo(scope, slot, Promise.resolve(rendered));\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 && loadingTemplates.size === 0) {\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, and\n // for the templates that the updates can render.\n const loading = loadModule(id).then(async (loaded) => {\n if (loaded.g[scope.k]?.[slot]) {\n const code = await loadPart(loaded, 'update');\n await Promise.allSettled(loadingTemplates);\n run(loaded, code, scope, slot);\n }\n });\n loadingUpdates.add(loading);\n void loading.finally(() => loadingUpdates.delete(loading));\n}\n\n/** The updates that wait for their code. */\nconst loadingUpdates = new Set<Promise<unknown>>();\n\n/**\n * Resolves when the updates of the writes so far have run, including those\n * whose code is loading. `transition` of `brumate/events` waits for it.\n */\nexport async function updated(): Promise<void> {\n while (loadingUpdates.size > 0) {\n // oxlint-disable-next-line no-await-in-loop -- An update can start more loads.\n await Promise.allSettled(loadingUpdates);\n }\n}\n\n(globalThis as { [key: symbol]: unknown })[Symbol.for('brumate.updated')] = updated;\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\n/** The updates that ran since the outermost `run` started, and when it started, for the devtools. */\nlet updateCount = 0;\nlet updateStart = 0;\n\nfunction run(module: ClientModule, updates: Part, scope: Scope, slot: number): void {\n if (DEV && running === 0) {\n updateCount = 0;\n updateStart = performance.now();\n }\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 if (DEV) {\n devtools()?.updated?.(updateCount, updateStart, performance.now());\n }\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 (DEV) {\n updateCount++;\n }\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 if (scope.children.size > 0) {\n for (const child of Array.from(scope.children)) {\n destroy(child);\n }\n }\n // The content of a `#portal` is elsewhere in the page, so it is removed by its markers.\n const start = portals > 0 ? comments.get(`P${scope.id}`) : undefined;\n if (start?.isConnected) {\n const end = rangeEnd(start);\n clear(start, end);\n start.remove();\n end.remove();\n }\n removeScope(scope);\n sweepIndexes();\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 if (scope.cleanups) {\n for (const cleanup of scope.cleanups.values()) {\n cleanup();\n }\n }\n // The state of the slots that load or wait, which most scopes, such as rows of a list, have not.\n const waiting =\n memoControllers.size + timers.size + loads.size + loadingSlots.size + (guesses?.map.size ?? 0);\n for (let slot = 0; waiting > 0 && slot < scope.s.length; slot++) {\n const key = `${scope.id}:${slot}`;\n memoControllers.get(key)?.abort();\n memoControllers.delete(key);\n clearTimeout(timers.get(key)?.timer);\n timers.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\nconst SCOPE_MARKER = /^[tb](-?[\\d.]+):/;\n\n/** True for markup that names a scope from the server: a `b-b` or marker with an ID that is not negative. */\nconst SERVER_SCOPES = /b-b=\"\\d|<!--[tb]\\d/;\n\n/** The scopes that the client made since the last insert, which the next insert holds. */\nconst rendered: Scope[] = [];\n\n/** How many `#portal` markers the page has had, so a scope looks for its own only when any have. */\nlet portals = 0;\n\n/**\n * Indexes the markers and the bound elements under `root`, so that updates find them without a\n * search of the page. A search for each row of a long list takes time that grows with the list.\n * With `ids`, it also collects the IDs of the scopes that the markup names. The IDs of scopes\n * that the client made are negative.\n */\nfunction indexMarkers(root: Node, ids?: Set<ScopeId>, withElements = true): void {\n // The query finds the bound elements in native code, and the walk visits only comments, so\n // the code here runs for each marker, not for each node of a long list.\n if (withElements) {\n indexElements(root, ids);\n }\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 continue;\n }\n comments.set(markerKey(data), node as Comment);\n if (data[0] === 'P') {\n portals++;\n }\n const match = ids && SCOPE_MARKER.exec(data);\n if (match) {\n ids!.add(parseId(match[1]!));\n }\n }\n}\n\n/** The size of the indexes at which they next drop the nodes that left the page. */\nlet sweepAt = 4096;\n\n/**\n * Drops the nodes that left the page from the indexes, once they have grown to twice their size\n * after the last sweep, so a list that the client fills and empties again does not keep its old\n * rows. A node that comes back is indexed again when it is inserted.\n */\nfunction sweepIndexes(): void {\n if (comments.size + elements.size < sweepAt) {\n return;\n }\n for (const [key, node] of comments) {\n if (!node.isConnected) {\n comments.delete(key);\n }\n }\n for (const [key, node] of elements) {\n if (!node.isConnected) {\n elements.delete(key);\n }\n }\n sweepAt = Math.max(4096, 2 * (comments.size + elements.size));\n}\n\nfunction indexElements(root: Node, ids?: Set<ScopeId>): void {\n if (root.nodeType === 1) {\n indexElement(root as Element, ids);\n }\n if (root.nodeType === 1 || root.nodeType === 9 || root.nodeType === 11) {\n for (const element of (root as ParentNode).querySelectorAll('[b-b]')) {\n indexElement(element, ids);\n }\n }\n}\n\n/**\n * The nodes that inserts of the client put in the page, from the first to the last of each,\n * whose bound elements are not indexed yet. A list that the client creates is often never\n * updated row by row, so its elements are indexed when an update first needs one of them.\n */\nconst unindexed: [first: Node, last: Node][] = [];\n\nfunction indexInserts(): void {\n for (const [first, last] of unindexed.splice(0)) {\n if (first.isConnected) {\n for (let node: Node | null = first; node; node = node.nextSibling) {\n indexElements(node);\n if (node === last) {\n break;\n }\n }\n } else if (last.isConnected) {\n // The first nodes left the page, such as the first rows of a list that were removed, so\n // the walk goes back from the last node, past the start of the insert if it must.\n for (let node: Node | null = last; node; node = node.previousSibling) {\n indexElements(node);\n }\n }\n }\n}\n\nfunction indexElement(element: Element, ids?: Set<ScopeId>): void {\n const key = element.getAttribute('b-b');\n if (key === null) {\n return;\n }\n elements.set(key, element);\n ids?.add(parseId(key.slice(0, key.indexOf(':'))));\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 const data = (node as Comment).data;\n comments.set(markerKey(data), node as Comment);\n if (data[0] === 'P') {\n portals++;\n }\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: ScopeId, anchor: number): Element | null {\n const key = `${scope}:${anchor}`;\n let element = elements.get(key);\n if (!element?.isConnected) {\n // As for markers: once the core starts, the index has every bound element in the page,\n // with those of the inserts that are waiting.\n if (markerObserver) {\n indexAdded(markerObserver.takeRecords());\n indexInserts();\n element = elements.get(key);\n }\n // An insert whose first node left the page, such as the first row of a list that was\n // removed, has elements that the walk did not reach.\n if (!element?.isConnected) {\n element = document.querySelector(`[b-b=\"${key}\"]`) ?? undefined;\n if (element) {\n elements.set(key, element);\n }\n }\n }\n return element?.isConnected ? 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 if (start.nextSibling === end || !start.nextSibling) {\n return;\n }\n // One removal of the whole range, which costs less than one for each node of a long list.\n const range = document.createRange();\n range.setStartAfter(start);\n range.setEndBefore(end);\n range.deleteContents();\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 = trustedHTML(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 // The scopes that the renders since the last insert made, whose markup this is.\n const client = rendered.splice(0);\n // Markup from the server, such as `children`, names scopes with IDs that are not negative.\n // Only then are the elements of the insert read for them now.\n const fromServer = SERVER_SCOPES.test(html);\n const ids = fromServer ? new Set<ScopeId>() : undefined;\n indexMarkers(fragment, ids, fromServer);\n options.listen(fragment);\n watchTitles(fragment);\n const server: Scope[] = [];\n for (const id of ids ?? []) {\n const scope = typeof id === 'number' && id < 0 ? undefined : scopes.get(id);\n if (scope) {\n server.push(scope);\n }\n }\n if (!fromServer && fragment.firstChild) {\n unindexed.push([fragment.firstChild, fragment.lastChild!]);\n // Many inserts that no update read are indexed at once, so they do not hold their nodes.\n if (unindexed.length > 256) {\n indexInserts();\n }\n }\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 and whose handlers listen already.\n markerObserver?.takeRecords();\n options.inserted?.();\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 // Scopes that the client just rendered have its values, but the memos that load start here.\n const live = client.filter((scope) => scopes.has(scope.id));\n if (live.length > 0) {\n refresh(live, true);\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 // Each is written only when it differs, as a write of the same text still notifies observers.\n if (element.textContent !== written) {\n element.textContent = written;\n }\n if (element instanceof HTMLTextAreaElement && element.value !== written) {\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 const text = String(value);\n if (saved) {\n saved.v = text;\n } else if ((first as Text).data !== text) {\n // The same text again changes nothing, and a write would still notify observers.\n (first as Text).data = text;\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\n/** The `value` and `checked` that updates last wrote to each field. */\nconst fieldValues = new WeakMap<Element, Map<string, unknown>>();\n\nfunction setAttribute(element: Element, name: string, value: unknown): void {\n if (isBinding(value)) {\n value = value.value;\n }\n // A write of the same value changes nothing on screen, yet it still costs a style check and\n // notifies observers, so each write is skipped when the element already has the value.\n if (name === 'value' || name === 'checked') {\n const field = element as unknown as Record<string, unknown>;\n const next = name === 'checked' ? Boolean(value) : String(value ?? '');\n // The field takes the value when it differs from the value that updates wrote last, not each\n // time an update runs, so what the user typed or checked stays while the value stays, such\n // as the posted values of a form that validation reads again. Before the first write, the\n // field is compared as it is now.\n const written = fieldValues.get(element) ?? new Map<string, unknown>();\n fieldValues.set(element, written);\n const before = written.has(name) ? written.get(name) : field[name];\n written.set(name, next);\n if (!Object.is(before, next) && field[name] !== next) {\n field[name] = next;\n }\n }\n const written = attributeText(name, value);\n if (element.getAttribute(name) === (written ?? null)) {\n return;\n }\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\n/** The attributes that the last update of a spread wrote, so the next one removes those it drops. */\nconst spreadNames = new WeakMap<Element, Set<string>>();\n\nexport function attrs(\n scope: Scope,\n anchor: number,\n values: Record<string, unknown>,\n own: string[] = [],\n): void {\n const element = findElement(scope.id, anchor);\n if (element) {\n // The first update in the browser takes the attributes that are not the element's own, nor\n // those of brumate, as the ones that the server's spread wrote.\n if (!spreadNames.has(element)) {\n spreadNames.set(\n element,\n new Set(\n element\n .getAttributeNames()\n .filter((name) => !own.includes(name) && !/^(b-|data-prefetch$)/.test(name)),\n ),\n );\n }\n const names = new Set<string>();\n for (const [name, value] of Object.entries(values)) {\n if (name !== 'children' && !/^on[A-Z]/.test(name)) {\n names.add(name);\n setAttribute(element, name, value);\n }\n }\n for (const name of spreadNames.get(element) ?? []) {\n if (!names.has(name)) {\n setAttribute(element, name, undefined);\n }\n }\n spreadNames.set(element, names);\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, 'reset'), 'update', 'reset');\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/**\n * Renders the body of a `#client` block once, in place of its fallback.\n * `kinds` are the scope IDs inside the fallback, whose instances go.\n */\nexport function fill(scope: Scope, anchor: number, render: Render, kinds: number[] = []): void {\n const start = findComment(`b${scope.id}:${anchor}`);\n // A block that rendered its body has a third number.\n if (!start || start.data.split(':').length > 2) {\n return;\n }\n start.data += ':1';\n const end = rangeEnd(start);\n disposeKinds(scope, kinds);\n clear(start, end);\n insertHTML(end, render(scope));\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(parseId(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 /** The first and last node of the item, which are the same node for one element. */\n first: Node;\n last: Node;\n /** The place of the item in the list before the update. */\n position: number;\n /** True for an item whose key is in the new list. */\n kept: boolean;\n /** True for a kept item that stays in place. */\n still: boolean;\n}\n\nconst ITEM_MARKER = /^i(-?[\\d.]+)$/;\n\n/** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */\n/** The items of a `#for` list: an array as it is, since `list` only reads it, or any iterable as an array. */\nexport function listOf(value: Iterable<unknown> | ArrayLike<unknown>): unknown[] {\n return Array.isArray(value) ? value : Array.from(value);\n}\n\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 let others: Node[] | undefined;\n let position = 0;\n for (let node = start.nextSibling; node && node !== end;) {\n // An item between `<!--i…-->` and `<!--/i-->`, or one element whose `b-b` names the scope.\n let data: string | undefined;\n let id: string | undefined;\n if (node.nodeType === 8) {\n data = (node as Comment).data;\n id = ITEM_MARKER.exec(data)?.[1];\n } else if (node.nodeType === 1) {\n const bound = (node as Element).getAttribute('b-b');\n id = bound === null ? undefined : bound.slice(0, bound.indexOf(':'));\n }\n const item = id === undefined ? undefined : scopes.get(parseId(id));\n let last: Node = node;\n // The elements of the fallback have scopes of its kinds.\n if (item && (data !== undefined || (item.p === scope && !fallbackKinds.includes(item.k)))) {\n if (data !== undefined) {\n last = rangeEnd(node as Comment);\n }\n previous.set(key(item.i, position), {\n scope: item,\n first: node,\n last,\n position: position++,\n kept: false,\n still: false,\n });\n } else {\n (others ??= []).push(node);\n }\n node = last.nextSibling;\n }\n\n const count = items.length;\n if (count === 0) {\n if (previous.size === 0 && others) {\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 if (others) {\n for (const node of others) {\n node.parentNode?.removeChild(node);\n }\n }\n const parent = end.parentNode!;\n // The key of each item, and the items that stay, in the new order. A key that repeats keeps\n // its item once, as below.\n const keys: unknown[] = Array.from({ length: count });\n const kept: Item[] = [];\n for (let index = 0; index < count; index++) {\n const id = (keys[index] = key(items[index], index));\n const item = previous.get(id);\n if (item && !item.kept) {\n item.kept = true;\n kept.push(item);\n }\n }\n // The items that stay in place: the longest run of them that keeps the old order. Only the\n // others move, because moving a node restarts its animations and drops its focus.\n markInPlace(kept);\n // When no item stays, the old ones go first, in one removal, and the new ones go in after.\n if (kept.length === 0 && previous.size > 0) {\n for (const item of previous.values()) {\n destroy(item.scope);\n }\n previous.clear();\n clear(start, end);\n }\n // The first node after the items placed so far.\n let cursor: Node = start.nextSibling!;\n // New items next to each other go into the page with one insert.\n let added = '';\n for (let index = 0; index < count; index++) {\n const id = keys[index];\n const item = previous.get(id);\n if (!item) {\n added += render(scope, items[index], index);\n continue;\n }\n // Before the item's updates run, so they see the new items before it.\n if (added) {\n insertHTML(cursor, added);\n added = '';\n }\n previous.delete(id);\n // Slots that keep their values do not trigger updates.\n assign(item.scope, items[index], index);\n if (item.still) {\n // The nodes between the cursor and the item belong to items that move or go.\n cursor = item.last.nextSibling!;\n } else {\n for (let node = item.first; ;) {\n const next = node.nextSibling;\n parent.insertBefore(node, cursor);\n if (node === item.last) {\n break;\n }\n node = next!;\n }\n }\n }\n if (added) {\n insertHTML(cursor, added);\n }\n for (const item of previous.values()) {\n destroy(item.scope);\n for (let node: Node | null = item.first; node;) {\n const next: Node | null = node === item.last ? null : node.nextSibling;\n node.parentNode?.removeChild(node);\n node = next;\n }\n }\n}\n\n/**\n * Marks the items of a list that keep their places: the longest run of `kept`, the items that\n * stay in their new order, whose old positions go up.\n */\nfunction markInPlace(kept: Item[]): void {\n let sorted = true;\n for (let index = 1; index < kept.length; index++) {\n if (kept[index - 1]!.position > kept[index]!.position) {\n sorted = false;\n break;\n }\n }\n if (sorted) {\n for (const item of kept) {\n item.still = true;\n }\n return;\n }\n // `tails[length - 1]` is the index of the item that ends the run of that length with the\n // lowest position, and `before` links each item to the item before it in its run.\n const tails: number[] = [];\n const before: number[] = [];\n for (let index = 0; index < kept.length; index++) {\n const position = kept[index]!.position;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if (kept[tails[middle]!]!.position < position) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n before[index] = low > 0 ? tails[low - 1]! : -1;\n tails[low] = index;\n }\n for (let index = tails.at(-1) ?? -1; index >= 0; index = before[index]!) {\n kept[index]!.still = true;\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 if (element.style.getPropertyValue(name) !== css) {\n element.style.setProperty(name, css);\n }\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 // Children that a component inserted find their contexts where they are, through `t`.\n for (\n let current: Scope | undefined = scope;\n current;\n current = current.t ?? current.p ?? current.o\n ) {\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 setTitle(value === null || value === undefined ? '' : String(value));\n}\n\n/**\n * Sets `document.title`, which writes the first `<title>` of the document.\n * The head gets a `<title>` of its own first, so a `<title>` in markup keeps its text.\n */\nfunction setTitle(text: string): void {\n if (!document.head.querySelector('title:not([b-t])')) {\n document.head.prepend(document.createElement('title'));\n }\n document.title = text;\n}\n\n/** Watches the `<title>` elements of markup, once one is in the page. */\nlet titleObserver: MutationObserver | undefined;\n\nconst PAGE_TITLE = 'title[b-t]';\n\n/** True when a node is or holds a `<title>` of markup. */\nfunction holdsTitle(node: Node): boolean {\n return node instanceof Element && (node.matches(PAGE_TITLE) || !!node.querySelector(PAGE_TITLE));\n}\n\n/** Gives the page the text of its last `<title>` in markup. Without one, the title stays. */\nfunction syncTitle(): void {\n const titles = document.querySelectorAll(PAGE_TITLE);\n const last = titles[titles.length - 1];\n if (last && document.title !== last.textContent) {\n setTitle(last.textContent ?? '');\n }\n}\n\n/**\n * Starts to follow the `<title>` elements of markup, when `root` has one. A\n * block that adds or removes one, or a change of its text, sets the title.\n */\nfunction watchTitles(root: ParentNode): void {\n if (titleObserver || !root.querySelector(PAGE_TITLE)) {\n return;\n }\n titleObserver = new MutationObserver((records) => {\n for (const record of records) {\n const target = record.target instanceof Element ? record.target : record.target.parentElement;\n if (\n target?.closest(PAGE_TITLE) ||\n [...record.addedNodes].some(holdsTitle) ||\n [...record.removedNodes].some(holdsTitle)\n ) {\n syncTitle();\n return;\n }\n }\n });\n titleObserver.observe(document, { childList: true, subtree: true, characterData: true });\n}\n\n/** Writes a prop of a child component. */\n// The keys that the spreads of child components passed last, by the child's scope and anchor.\nconst spreadKeys = new WeakMap<Scope, Map<number, Set<string>>>();\n\n/**\n * Updates the props of a child component from a spread. A key that the\n * spread passed before and no longer has becomes undefined. `after` names\n * the props after the spread, which win over it.\n */\nexport function spreadProps(\n scope: Scope,\n anchor: number,\n value: Record<string, unknown> | null | undefined,\n after: string[],\n): void {\n const byAnchor = spreadKeys.get(scope) ?? new Map<number, Set<string>>();\n spreadKeys.set(scope, byAnchor);\n const before = byAnchor.get(anchor) ?? new Set();\n const keys = new Set(Object.keys(value ?? {}).filter((key) => !after.includes(key)));\n byAnchor.set(anchor, keys);\n for (const key of keys) {\n prop(scope, anchor, key, value![key]);\n }\n for (const key of before) {\n if (!keys.has(key)) {\n prop(scope, anchor, key, undefined);\n }\n }\n}\n\nexport function prop(scope: Scope, anchor: number, name: string, value: unknown): void {\n // A prop that the parent binds passes its value. The child keeps the slot it writes from its render.\n if (isBinding(value)) {\n value = value.value;\n }\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 // The parent's value. A bound prop does not write it back.\n writeSlot(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, 'prop').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 let cleanup: unknown;\n const start = DEV ? performance.now() : 0;\n try {\n cleanup = callback();\n } catch (error) {\n // The error goes to the nearest `#try` around the effect. The effect runs again on the next change.\n fail(scope, error);\n }\n // An entry without a cleanup too, so a hidden `#offscreen` body knows what to run again.\n let stored = typeof cleanup === 'function' ? (cleanup as () => void) : noop;\n if (DEV) {\n devtools()?.effect?.(scope, name, 'run', performance.now() - start);\n // Each way that a cleanup runs calls this function: the next run, a removed scope, a hidden\n // `#offscreen` body, or a page that navigation leaves.\n const own = stored;\n stored = () => {\n devtools()?.effect?.(scope, name, 'cleanup', 0);\n own();\n };\n }\n scope.cleanups.set(name, stored);\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, build);\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. Children render here, at `scope`, for their contexts. */\nexport function insert(value: unknown, _ctx?: unknown, scope?: Scope | ScopeId): string {\n return value instanceof Children ? value.render(resolveScope(scope)) : insertValue(value);\n}\n\n/** Children that render where they are inserted, and the scopes that they find contexts from. */\nconst insertedChildren: { from: Scope | undefined; at: Scope }[] = [];\n\n/**\n * Children of a component that the client renders. They render where the\n * component inserts them, so they read the contexts that it provides. `from`\n * is the scope of the markup that wrote them.\n */\nclass Children {\n private readonly from: Scope | undefined;\n private readonly html: () => string;\n\n constructor(from: Scope | ScopeId | undefined, html: () => string) {\n this.from = resolveScope(from);\n this.html = html;\n }\n\n render(at: Scope | undefined): string {\n if (!at) {\n return this.html();\n }\n const entry = { from: this.from, at };\n insertedChildren.push(entry);\n try {\n return this.html();\n } finally {\n insertedChildren.splice(insertedChildren.indexOf(entry), 1);\n }\n }\n}\n\n/** The children of a component that the client renders. See `Children`. */\nexport function children(from: Scope | ScopeId | undefined, html: () => string): Children {\n return new Children(from, html);\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 | ScopeId | undefined): Scope | undefined {\n if (typeof scope === 'object') {\n return scope;\n }\n return scope === undefined ? undefined : scopes.get(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 inner: Raw | Children | undefined,\n _ctx?: unknown,\n scope?: Scope | number,\n): string {\n if (typeof tag === 'function') {\n return component(\n tag as Component,\n inner ? { ...attributes, children: inner } : attributes,\n undefined,\n scope,\n );\n }\n const name = String(tag);\n const open = `<${name}${spreadText(attributes)}>`;\n return VOID_ELEMENTS.has(name)\n ? open\n : `${open}${inner ? insert(inner, undefined, scope) : ''}</${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 | ScopeId, 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 rendered.push(created);\n if (module !== undefined && owner) {\n created.o = owner;\n owner = undefined;\n }\n // A scope at the top of children that are inserted elsewhere finds its contexts there.\n const up = created.o ?? parentScope;\n for (let index = insertedChildren.length - 1; index >= 0; index--) {\n if (insertedChildren[index]!.from === up) {\n created.t = insertedChildren[index]!.at;\n break;\n }\n }\n parentScope?.children.add(created);\n treeChanges++;\n scopes.set(id, created);\n return id;\n}\n\n/**\n * The ID that `$id()` makes, as the server does. Client scope IDs are\n * negative, so they differ from the server's.\n */\nexport function makeId(scope: Scope | ScopeId, index: number): string {\n return `b${String(resolveScope(scope)!.id).replace(/\\./g, '_')}-${index}`;\n}\n\n/** Sets the owner of the next component's root scope. */\nexport function setOwner(scope: Scope | ScopeId): 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 | ScopeId): 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 | ScopeId,\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 if (provider) {\n return provider.v![context.key] as T;\n }\n if (context.key === ROUTE_KEY && !globals.has(ROUTE_KEY)) {\n globals.set(ROUTE_KEY, currentRoute());\n }\n return (globals.has(context.key) ? globals.get(context.key) : context.defaultValue) as T;\n}\n\n/** The values of the contexts that the runtime provides to the whole page, by key. */\nconst globals = new Map<string, unknown>();\n\n/** The route of the page: `location`, and the params of the route from the last page state. */\nfunction currentRoute(): Route {\n const records = document.querySelectorAll('script[b-state][b-params]');\n const params = records[records.length - 1]?.getAttribute('b-params');\n const url = new URL(location.href);\n return { url, search: url.searchParams, params: params ? JSON.parse(params) : {} };\n}\n\n/**\n * Writes a context that the runtime provides to the whole page, and the\n * slot of every scope that reads it without a provider above it.\n */\nexport function setGlobal(key: string, value: unknown): void {\n globals.set(key, value);\n for (const target of scopes.values()) {\n const slot = target.x?.[key];\n if (slot !== undefined && !findProvider(target, key)) {\n set(target, slot, value);\n }\n }\n}\n\n/** Reads the route of the page again, after navigation changed it. */\nexport function updateRoute(): void {\n setGlobal(ROUTE_KEY, currentRoute());\n}\n\n/**\n * Slots that the render of a component in the browser filled with a promise,\n * by `scope:slot`. The first compute of their memo takes that promise\n * instead of calling again, so a server function is called once per row.\n */\nconst renderedLoads = new Set<string>();\n\nexport function setSlots(id: ScopeId, values: unknown[]): void {\n scopes.get(id)!.s = values;\n // A render function computes a memo that loads as a promise, which the first compute of the\n // memo takes. Its failure is the memo's to report, not an unhandled rejection.\n for (let slot = 0; slot < values.length; slot++) {\n const value = values[slot];\n if (isThenable(value)) {\n renderedLoads.add(`${id}:${slot}`);\n Promise.resolve(value).catch(noop);\n }\n }\n}\n\nexport function setItem(id: ScopeId, value: unknown): void {\n scopes.get(id)!.i = value;\n}\n\nexport function elementAt(scope: ScopeId, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n}\n\n/**\n * Warns in development that the browser renders a `#defer` block of a\n * component, such as inside a `#client` body of its parent. Only the server\n * renders the body, so the fallback stays.\n */\nexport function deferInBrowser(id: string): void {\n if (DEV) {\n console.warn(\n `${id} renders a #defer block in the browser, so it shows its fallback only. Render the component in markup that the server renders.`,\n );\n }\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(\n value: unknown,\n ref: string,\n scope: Scope | number,\n bound: unknown[] = [],\n modifiers?: string[],\n): unknown {\n // A template renders at once, and the client has its code already.\n if (typeof value !== 'function' || isTemplate(ref)) {\n return value;\n }\n const instance = resolveScope(scope);\n const handler = (...args: unknown[]): unknown => call(ref, instance, [...bound, ...args]);\n // A spread of markup that the browser renders passes it on, with the modifiers of its wrappers.\n // A scope that is not in the page yet has its ID in `scope`.\n handlerReferences.set(\n handler,\n new FunctionReference(\n ref,\n instance?.id ?? (scope as ScopeId),\n bound.length > 0 ? bound : undefined,\n modifiers ?? (value as { [MODIFIERS]?: string[] })[MODIFIERS],\n ),\n );\n return handler;\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 submit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],"sources":["../src/runtime/client-routes.ts"],"sourcesContent":["// What the core needs to read the pages that client navigation adds. Only\n// `navigate.ts` writes the attributes that this module reads, so the loader\n// imports it when it navigates or finds such a record, and a page that never\n// navigates does not load it. Importing it sets the core's `record` hook.\n//\n// It reads the core with `import()`, as `rpc.ts` does, and imports nothing\n// else. A static import of the core would make the package build move the\n// core into a chunk behind a module that only re-exports it, and a static\n// import of `shared.ts` would split that module out of the core of a page.\n// The core is loaded already, or loads with this module.\n\nimport type * as Client from './client.ts';\nimport type { Scope } from './client.ts';\nimport type { PageState, ScopeId, ScopeState } from './shared.ts';\n\n/** The parts of the core that this module uses. */\ntype Core = Pick<\n typeof Client,\n 'ElementReference' | 'FunctionReference' | 'hooks' | 'removeScope' | 'scopes'\n>;\n\n/** Reads an ID, as `parseId` in `shared.ts` does. This module imports no code of its own. */\nfunction readId(text: string): ScopeId {\n return /^-?\\d+$/.test(text) ? Number(text) : text;\n}\n\n/** Adds a number to an ID, as `shiftId` in `shared.ts` does. */\nfunction shiftId(id: ScopeId, by: number): ScopeId {\n if (typeof id === 'number') {\n return id + by;\n }\n const dot = id.indexOf('.');\n return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;\n}\n\n/** Adds a number to the scope IDs of a state record. */\nfunction shiftState(core: Core, state: PageState, by: number): PageState {\n const { ElementReference, FunctionReference } = core;\n const seen = new Set<object>();\n // References to elements and client functions name the scope of their markup.\n const shiftValue = (value: unknown): unknown => {\n if (value instanceof ElementReference) {\n return new ElementReference(shiftId(value.scope, by), value.anchor);\n }\n if (value instanceof FunctionReference) {\n return new FunctionReference(value.ref, shiftId(value.scope, by));\n }\n // A later record settles it, with a value whose IDs move too.\n if (value instanceof Promise) {\n return value.then(shiftValue);\n }\n if (typeof value === 'object' && value !== null && !seen.has(value)) {\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n value[index] = shiftValue(item);\n });\n } else if (Object.getPrototypeOf(value) === Object.prototype) {\n for (const [key, item] of Object.entries(value)) {\n (value as Record<string, unknown>)[key] = shiftValue(item);\n }\n }\n }\n return value;\n };\n const result: PageState = {};\n for (const [key, record] of Object.entries(state)) {\n result[shiftId(readId(key), by)] = {\n ...record,\n p: record.p === undefined ? undefined : shiftId(record.p, by),\n o: record.o === undefined ? undefined : shiftId(record.o, by),\n c:\n record.c &&\n Object.fromEntries(\n Object.entries(record.c).map(([anchor, id]) => [anchor, shiftId(id, by)]),\n ),\n s: record.s?.map(shiftValue),\n };\n }\n return result;\n}\n\n/** Removes scopes and the scopes inside them, and runs their cleanups. */\nfunction dropScopes(core: Core, roots: Set<ScopeId>): void {\n const inside = (scope: Scope): boolean => {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (roots.has(current.id)) {\n return true;\n }\n }\n return false;\n };\n // Deleting from a map while iterating it is safe.\n for (const scope of core.scopes.values()) {\n if (inside(scope)) {\n core.removeScope(scope);\n }\n }\n}\n\n/**\n * Reads the attributes that navigation set on a state record. A page whose\n * IDs started at another number, such as a prerendered file, has them moved\n * with `b-offset`. A page that replaced only some routes of the one before\n * it drops the old routes with `b-drop`, and adds only the scopes inside\n * `b-roots`, with the scopes of the kept layouts in place of the new\n * page's copies of them, by `b-alias`.\n */\nfunction routeRecord(core: Core, script: Element, state: PageState): PageState {\n // Only records with scopes hold IDs. Later records settle promises, which `shiftState` wraps.\n const offset = Number(script.getAttribute('b-offset') ?? 0);\n const value = offset ? shiftState(core, state, offset) : state;\n const drop = script.getAttribute('b-drop');\n if (drop) {\n dropScopes(core, new Set(drop.split(',').map(readId)));\n }\n const list = script.getAttribute('b-roots');\n if (list === null) {\n return value;\n }\n const roots = new Set(list.split(',').filter(Boolean).map(readId));\n const alias = new Map<ScopeId, ScopeId>();\n for (const pair of (script.getAttribute('b-alias') ?? '').split(',').filter(Boolean)) {\n const [from, to] = pair.split(':').map(readId) as [ScopeId, ScopeId];\n alias.set(from, to);\n }\n const kept = (id: ScopeId): boolean => {\n for (let current: ScopeId | undefined = id; current !== undefined;) {\n if (roots.has(current)) {\n return true;\n }\n const record: ScopeState | undefined = value[current];\n current = record?.p ?? record?.o;\n }\n return false;\n };\n const resolve = (id: ScopeId | undefined): ScopeId | undefined =>\n id === undefined ? undefined : (alias.get(id) ?? id);\n const result: PageState = {};\n for (const [key, record] of Object.entries(value)) {\n // The new page renders the kept layouts again. Their scopes are not added.\n const id = readId(key);\n if (kept(id)) {\n result[id] = { ...record, p: resolve(record.p), o: resolve(record.o) };\n }\n }\n return result;\n}\n\n/**\n * Settles once the core reads records with this module, with the function\n * that forgets the page before navigation replaces it, or only stops reading\n * when layouts stay.\n */\nexport const ready: Promise<(partial: boolean) => void> = import('./client.ts').then(\n ({ ElementReference, FunctionReference, hooks, leavePage, leaveRoutes, removeScope, scopes }) => {\n const core = { ElementReference, FunctionReference, hooks, removeScope, scopes };\n hooks.record = (script, state) => routeRecord(core, script, state);\n return (partial) => (partial ? leaveRoutes() : leavePage());\n },\n);\n"],"mappings":";;AAsBA,SAAS,OAAO,MAAuB;CACrC,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,IAAI,IAAI;AAC/C;;AAGA,SAAS,QAAQ,IAAa,IAAqB;CACjD,IAAI,OAAO,OAAO,UAChB,OAAO,KAAK;CAEd,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,MAAM,GAAG;AACxD;;AAGA,SAAS,WAAW,MAAY,OAAkB,IAAuB;CACvE,MAAM,EAAE,kBAAkB,sBAAsB;CAChD,MAAM,uBAAO,IAAI,IAAY;CAE7B,MAAM,cAAc,UAA4B;EAC9C,IAAI,iBAAiB,kBACnB,OAAO,IAAI,iBAAiB,QAAQ,MAAM,OAAO,EAAE,GAAG,MAAM,MAAM;EAEpE,IAAI,iBAAiB,mBACnB,OAAO,IAAI,kBAAkB,MAAM,KAAK,QAAQ,MAAM,OAAO,EAAE,CAAC;EAGlE,IAAI,iBAA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,EAAE,kBAAkB,mBAAmB,OAAO,WAAW,aAAa,aAAa,aAAa;CAC/F,MAAM,OAAO;EAAE;EAAkB;EAAmB;EAAO;EAAa;CAAO;CAC/E,MAAM,UAAU,QAAQ,UAAU,YAAY,MAAM,QAAQ,KAAK;CACjE,QAAQ,YAAa,UAAU,YAAY,IAAI,UAAU;AAC3D,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cookies-BzllthiF.js","names":[],"sources":["../src/runtime/cookies.ts"],"sourcesContent":["// Cookies and sessions, for server functions, rendering, middleware and\n// endpoints. They read the request of a `RequestEvent` and write `set-cookie`\n// headers on its response.\n\nimport type { RequestEvent } from './request.ts';\n\nexport interface CookieOptions {\n /** Seconds until the cookie expires. Without it, the cookie lasts until the browser closes. */\n maxAge?: number;\n expires?: Date;\n /** Defaults to `/`. */\n path?: string;\n domain?: string;\n /** Defaults to true when the request is HTTPS. */\n secure?: boolean;\n /** Keeps the cookie from browser code. Defaults to true. */\n httpOnly?: boolean;\n /** Defaults to `lax`. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Reads the cookies of a `cookie` header. */\nexport function parseCookies(header: string | null): Record<string, string> {\n const result: Record<string, string> = {};\n for (const part of (header ?? '').split(';')) {\n const index = part.indexOf('=');\n if (index === -1) {\n continue;\n }\n const name = part.slice(0, index).trim();\n if (name && !(name in result)) {\n const value = part.slice(index + 1).trim();\n try {\n result[name] = decodeURIComponent(value);\n } catch {\n result[name] = value;\n }\n }\n }\n return result;\n}\n\n/** Writes a `set-cookie` header value. */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n if (!/^[\\w!#$%&'*+.^`|~-]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid cookie name`);\n }\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? '/'}`];\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.floor(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (options.httpOnly !== false) {\n parts.push('HttpOnly');\n }\n if (options.secure) {\n parts.push('Secure');\n }\n parts.push(\n `SameSite=${(options.sameSite ?? 'lax').replace(/^./, (letter) => letter.toUpperCase())}`,\n );\n return parts.join('; ');\n}\n\n/** The parsed `cookie` header of each event, with the header it was parsed from. */\nconst parsed = new WeakMap<\n RequestEvent,\n { header: string | null; cookies: Record<string, string> }\n>();\n\n/** The cookies of the request, with the ones that this request set or deleted. */\nexport function getCookies(event: RequestEvent): Record<string, string> {\n const header = event.request.headers.get('cookie');\n let cached = parsed.get(event);\n if (cached?.header !== header) {\n cached = { header, cookies: parseCookies(header) };\n parsed.set(event, cached);\n }\n // A copy, so the caller cannot change the cache.\n const result = { ...cached.cookies };\n for (const [name, value] of event.cookies ?? []) {\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n}\n\n/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */\nexport function setCookie(\n event: RequestEvent,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n event.personal = true;\n const secure = options.secure ?? new URL(event.request.url).protocol === 'https:';\n event.headers.append('set-cookie', serializeCookie(name, value, { ...options, secure }));\n event.cookies ??= new Map();\n event.cookies.set(name, value);\n}\n\n/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\nexport function deleteCookie(\n event: RequestEvent,\n name: string,\n options: Pick<CookieOptions, 'path' | 'domain'> = {},\n): void {\n // `secure` follows the request, as for a cookie set without it.\n setCookie(event, name, '', { ...options, secure: undefined, maxAge: 0, expires: new Date(0) });\n event.cookies!.set(name, undefined);\n}\n\nexport interface SessionOptions {\n /**\n * Signs the cookie, so a browser cannot change it. Use a random string of\n * at least 32 characters, kept out of the code, such as in an environment\n * variable. A list signs with the first and accepts all, for changing it.\n */\n secret: string | string[];\n /** The name of the cookie. Defaults to `session`. */\n name?: string;\n /** Seconds until the session expires. Defaults to 7 days. */\n maxAge?: number;\n /** Other options of the cookie. */\n cookie?: Omit<CookieOptions, 'maxAge' | 'expires'>;\n}\n\nexport interface Session<T> {\n /** The data of the session, or undefined when there is none, it expired, or its signature does not match. */\n get(event: RequestEvent): Promise<T | undefined>;\n /** Replaces the data of the session, and starts its time again. */\n set(event: RequestEvent, data: T): Promise<void>;\n /** Changes some fields of the data, and returns the new data. */\n update(event: RequestEvent, change: Partial<T>): Promise<T>;\n /** Ends the session. */\n clear(event: RequestEvent): void;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst keys = new Map<string, Promise<CryptoKey>>();\n\nfunction key(secret: string): Promise<CryptoKey> {\n let promise = keys.get(secret);\n if (!promise) {\n promise = crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n keys.set(secret, promise);\n }\n return promise;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let text = '';\n for (const byte of bytes) {\n text += String.fromCharCode(byte);\n }\n return btoa(text).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array<ArrayBuffer> {\n const base64 = text.replace(/-/g, '+').replace(/_/g, '/');\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n\n/**\n * A session in a signed cookie. The browser can read the data, but cannot\n * change it, so keep secrets out of it: store an ID, and look the rest up\n * on the server.\n *\n * ```ts\n * export const session = createSession<{ userId: string }>({ secret: process.env.SESSION_SECRET! });\n *\n * async function login(form: FormData) {\n * 'use server';\n * const event = getEvent();\n * await session.set(event, { userId: await checkPassword(form) });\n * }\n * ```\n */\nexport function createSession<T>(options: SessionOptions): Session<T> {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];\n if (secrets.length === 0 || secrets.some((secret) => secret.length < 32)) {\n throw new Error('A session secret needs at least 32 characters');\n }\n const name = options.name ?? 'session';\n const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;\n\n const read = async (event: RequestEvent): Promise<T | undefined> => {\n const value = getCookies(event)[name];\n const dot = value?.lastIndexOf('.') ?? -1;\n if (!value || dot === -1) {\n return undefined;\n }\n const payload = value.slice(0, dot);\n let signature: Uint8Array<ArrayBuffer>;\n try {\n signature = fromBase64Url(value.slice(dot + 1));\n } catch {\n return undefined;\n }\n // Any of the secrets can have signed it, such as an older one while a secret changes.\n const checks = await Promise.all(\n secrets.map(async (secret) =>\n crypto.subtle.verify('HMAC', await key(secret), signature, encoder.encode(payload)),\n ),\n );\n if (!checks.includes(true)) {\n return undefined;\n }\n try {\n const { d: data, e: expires } = JSON.parse(decoder.decode(fromBase64Url(payload))) as {\n d: T;\n e: number;\n };\n return expires > Date.now() ? data : undefined;\n } catch {\n return undefined;\n }\n };\n\n const write = async (event: RequestEvent, data: T): Promise<void> => {\n const payload = toBase64Url(\n encoder.encode(JSON.stringify({ d: data, e: Date.now() + maxAge * 1000 })),\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign('HMAC', await key(secrets[0]!), encoder.encode(payload)),\n );\n const value = `${payload}.${toBase64Url(signature)}`;\n // Browsers drop cookies over about 4 KB.\n if (value.length > 4000) {\n throw new Error(\n `The session is ${value.length} bytes, over the 4000 that a cookie can hold. Store an ID in it instead`,\n );\n }\n setCookie(event, name, value, { ...options.cookie, maxAge });\n };\n\n return {\n get: read,\n set: write,\n async update(event, change) {\n const data = { ...(await read(event)), ...change } as T;\n await write(event, data);\n return data;\n },\n clear: (event) =>\n deleteCookie(event, name, { path: options.cookie?.path, domain: options.cookie?.domain }),\n };\n}\n\n/**\n * The headers of a response for Node's `writeHead`, with each `set-cookie`\n * apart. `Object.fromEntries(headers)` joins them into one, which browsers\n * read as a single cookie.\n */\nexport function toNodeHeaders(headers: Headers): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = Object.fromEntries(headers);\n const cookies = headers.getSetCookie();\n if (cookies.length > 0)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ACF,MAAM,EAAE,GAAG,MAAM,GAAG,YAAY,KAAK,MAAM,QAAQ,OAAO,cAAc,OAAO,CAAC,CAAC;GAIjF,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,KAAA;EACvC,QAAQ;GACN;EACF;CACF;CAEA,MAAM,QAAQ,OAAO,OAAqB,SAA2B;EACnE,MAAM,UAAU,YACd,QAAQ,OAAO,KAAK,UAAU;GAAE,GAAG;GAAM,GAAG,KAAK,IAAI,IAAI,SAAS;EAAK,CAAC,CAAC,CAC3E;EAIA,MAAM,QAAQ,GAAG,QAAQ,GAAG,YAAY,IAHlB,WACpB,MAAM,OAAO,OAAO,KAAK,QAAQ,MAAM,IAAI,QAAQ,EAAG,GAAG,QAAQ,OAAO,OAAO,CAAC,CAElC,CAAC;EAEjD,IAAI,MAAM,SAAS,KACjB,MAAM,IAAI,MACR,kBAAkB,MAAM,OAAO,wEACjC;EAEF,UAAU,OAAO,MAAM,OAAO;GAAE,GAAG,QAAQ;GAAQ;EAAO,CAAC;CAC7D;CAEA,OAAO;EACL,KAAK;EACL,KAAK;EACL,MAAM,OAAO,OAAO,QAAQ;GAC1B,MAAM,OAAO;IAAE,GAAI,MAAM,KAAK,KAAK;IAAI,GAAG;GAAO;GACjD,MAAM,MAAM,OAAO,IAAI;GACvB,OAAO;EACT;EACA,QAAQ,UACN,aAAa,OAAO,MAAM;GAAE,MAAM,QAAQ,QAAQ;GAAM,QAAQ,QAAQ,QAAQ;EAAO,CAAC;CAC5F;AACF;;;;;;AAOA,SAAgB,cAAc,SAAqD;CACjF,MAAM,SAA4C,OAAO,YAAY,OAAO;CAC5E,MAAM,UAAU,QAAQ,aAAa;CACrC,IAAI,QAAQ,SAAS,GACnB,OAAO,gBAAgB;CAEzB,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"defer-BbD7JQhj.js","names":[],"sources":["../src/runtime/defer.ts"],"sourcesContent":["// Loads the body of a `#defer` block. The loader imports this module when\n// the block's trigger fires, so a page without `#defer` does not load it.\n//\n// The server renders the route again for the request and answers with what\n// it streams for a `#loading` body that is ready: the body in a\n// `<template b-l>`, the script that swaps it in, and its state records.\n// This module adds that markup to the page and runs its scripts, in order.\n\nimport { build, skew } from './client.ts';\nimport { trustedHTML, trustedScript } from './trusted.ts';\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\n/** The Content Security Policy nonce of the page, which the scripts of the answer need to run. */\nfunction pageNonce(): string | undefined {\n for (const script of document.querySelectorAll('script')) {\n const nonce = nonceOf(script);\n if (nonce) {\n return nonce;\n }\n }\n return undefined;\n}\n\n/** The templates whose bodies were asked for. */\nconst requested = new WeakSet<Element>();\n\n/**\n * Asks the server for the body of the `#defer` block of a `<template\n * b-defer>`, and puts it in place of the fallback. When the server cannot\n * render it, such as a page that changed since it loaded, or a static host\n * that answers with the whole page, the fallback stays.\n */\nexport async function loadDeferred(template: Element): Promise<void> {\n // Once, so the devtools can fire the trigger before the loader does.\n if (requested.has(template)) {\n return;\n }\n requested.add(template);\n const [, boundary, base] = template.getAttribute('b-defer')!.split(':') as [\n string,\n string,\n string,\n ];\n const response = await fetch(location.href, {\n headers: {\n 'x-brumate-defer': `${boundary} ${template.getAttribute('b-b')}`,\n 'x-brumate-base': base,\n ...(build === undefined ? {} : { 'x-brumate-build': build }),\n },\n });\n if (response.status === 409 && response.headers.get('x-brumate-build')) {\n // The site changed since the page loaded. The fallback stays, and the next page loads in full.\n skew('defer');\n return;\n }\n if (!response.ok || response.headers.get('x-brumate-defer') !== boundary) {\n return;\n }\n const parsed = document.createElement('template');\n parsed.innerHTML = trustedHTML(await response.text());\n const nonce = pageNonce();\n // A copy, because appending moves nodes out of the live list.\n for (const node of Array.from(parsed.content.childNodes)) {\n if (node.nodeName !== 'SCRIPT') {\n document.body.append(node);\n continue;\n }\n // A script from `innerHTML` does not run, so a copy goes in its place.\n const script = node as 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 if (nonce) {\n copy.nonce = nonce;\n }\n copy.textContent = trustedScript(script.textContent ?? '');\n document.body.append(copy);\n }\n}\n"],"mappings":";;;;AAWA,SAAS,QAAQ,QAA0C;CACzD,OAAO,OAAO,SAAS,OAAO,aAAa,OAAO;AACpD;;AAGA,SAAS,YAAgC;CACvC,KAAK,MAAM,UAAU,SAAS,iBAAiB,QAAQ,GAAG;EACxD,MAAM,QAAQ,QAAQ,MAAM;EAC5B,IAAI,OACF,OAAO;CAEX;AAEF;;AAGA,MAAM,4BAAY,IAAI,QAAiB;;;;;;;AAQvC,eAAsB,aAAa,UAAkC;CAEnE,IAAI,UAAU,IAAI,QAAQ,GACxB;CAEF,UAAU,IAAI,QAAQ;CACtB,MAAM,GAAG,UAAU,QAAQ,SAAS,aAAa,SAAS,CAAC,CAAE,MAAM,GAAG;CAKtE,MAAM,WAAW,MAAM,MAAM,SAAS,MAAM,EAC1C,SAAS;EACP,mBAAmB,GAAG,SAAS,GAAG,SAAS,aAAa,KAAK;EAC7D,kBAAkB;EAClB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,mBAAmB,MAAM;CAC5D,EACF,CAAC;CACD,IAAI,SAAS,WAAW,OAAO,SAAS,QAAQ,IAAI,iBAAiB,GAAG;EAEtE,KAAK,OAAO;EACZ;CACF;CACA,IAAI,CAAC,SAAS,MAAM,SAAS,QAAQ,IAAI,iBAAiB,MAAM,UAC9D;CAEF,MAAM,SAAS,SAAS,cAAc,UAAU;CAChD,OAAO,YAAY,YAAY,MAAM,SAAS,KAAK,CAAC;CACpD,MAAM,QAAQ,UAAU;CAExB,KAAK,MAAM,QAAQ,MAAM,KAAK,OAAO,QAAQ,UAAU,GAAG;EACxD,IAAI,KAAK,aAAa,UAAU;GAC9B,SAAS,KAAK,OAAO,IAAI;GACzB;EACF;EAEA,MAAM,SAAS;EACf,MAAM,OAAO,SAAS,cAAc,QAAQ;EAC5C,KAAK,MAAM,aAAa,OAAO,YAC7B,IAAI,UAAU,SAAS,SACrB,KAAK,aAAa,UAAU,MAAM,UAAU,KAAK;EAGrD,IAAI,OACF,KAAK,QAAQ;EAEf,KAAK,cAAc,cAAc,OAAO,eAAe,EAAE;EACzD,SAAS,KAAK,OAAO,IAAI;CAC3B;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"devtools-CQgD7NPB.js","names":[],"sources":["../src/runtime/devtools.ts"],"sourcesContent":["// The devtools overlay of development builds. This module only listens to\n// the core and shows a button. The panel loads when the button is pressed,\n// so the page behaves as in production until then.\n\nimport type { NavigationReport } from './navigate.ts';\nimport type { DevtoolsHooks, Scope } from './client.ts';\nimport type * as Panel from './devtools-panel.ts';\nimport type { ScopeId } from './shared.ts';\n\n// The same key as the core's, without importing the core.\nconst DEVTOOLS = Symbol.for('brumate.devtools');\n\n/** Something that happened on the page, for the log of the panel. */\nexport interface DevtoolsEntry {\n time: number;\n kind: 'handler' | 'part' | 'write' | 'call';\n text: string;\n /** The scope of a write, so the panel can mark it. */\n scope?: ScopeId;\n /** For a write: the component, the scope in the compiled component, and the slot. */\n write?: { component: string; k: number; slot: number };\n}\n\n/** What the plugin tells the devtools about the dev server. */\nexport interface DevtoolsMeta {\n version?: string;\n vite?: string;\n}\n\n/** An error for the Errors tab: of a render on the server, of Vite, or of code in the browser. */\nexport interface ErrorEntry {\n time: number;\n source: 'server' | 'compile' | 'browser';\n message: string;\n stack?: string;\n /** The lines around the error, as Vite's overlay shows them. */\n frame?: string;\n /** The place of the error, such as a compile error in a `.brm` file. */\n loc?: { file: string; line: number; column: number };\n /** The plugin that threw it, such as `brumate`. */\n plugin?: string;\n}\n\n/** What Vite's overlay gets, and what `errorPage` sends. */\nexport interface ErrorPayload {\n message: string;\n stack?: string;\n frame?: string;\n plugin?: string;\n id?: string;\n loc?: { file?: string; line: number; column: number };\n}\n\n/** The part of `import.meta.hot` that the devtools listen to. */\ninterface HotContext {\n on(event: string, listener: (payload: never) => void): void;\n}\n\n/** Code of a component that loaded, or is loading, for the Loading tab. */\nexport interface LoadEntry {\n component: string;\n /** The part, such as `h3` or `update`, `entry` for the module, or `all` for a merged module. */\n part: string;\n /**\n * Why it loaded: `event`, `block`, `call`, `template`, `state`, `write`, `error`, `reset` or\n * `prop`, or a preload: `hover`, `visible`, `idle` or `eager`.\n */\n reason: string;\n start: number;\n end?: number;\n failed?: boolean;\n /** For a preload: true once something ran the code, such as a handler. */\n used: boolean;\n}\n\n/** A server function call, for the Timeline tab. */\nexport interface CallTiming {\n name: string;\n start: number;\n end?: number;\n /** The status of the answer, `redirect` for a redirect, or `failed`. */\n status?: number | 'redirect' | 'failed';\n /** How long the function took on the server, from the `Server-Timing` of the dev server. */\n server?: number;\n}\n\n/** A batch of updates that a write ran, with its effects. */\nexport interface UpdateTiming {\n count: number;\n start: number;\n end: number;\n}\n\n/**\n * A handler that ran, for the Timeline tab: when its event came, when its\n * code was ready and the handlers before it had started, when its call\n * returned, and when the promise of an async handler settled. The server\n * calls and the updates that ran meanwhile are its own.\n */\nexport interface Interaction {\n ref: string;\n /** What happened, such as `click on <button>`. */\n label: string;\n begun: number;\n ready: number;\n end: number;\n settled?: number;\n failed?: boolean;\n calls: CallTiming[];\n updates: UpdateTiming[];\n}\n\n/** A block of the page that renders later, for the Blocks tab. */\nexport interface BlockEntry {\n kind: 'loading' | 'defer' | 'client' | '$client';\n /** The boundary of `#loading` and `#defer`, or the `b-b` of the template of the others. */\n id: string;\n /** The trigger of `#defer`, `#client` and `$client`. */\n trigger?: string;\n /** The reference that `#client` and `$client` run. */\n ref?: string;\n /** The template that the loader reads for `#defer`, `#client` and `$client`. */\n template?: Element;\n state: 'waiting' | 'loading' | 'streaming' | 'rendered' | 'failed';\n /** When the panel first saw the block, when its trigger fired, and when it rendered. */\n seen: number;\n fired?: number;\n rendered?: number;\n /** True while the devtools show its fallback in place of its body. */\n fallback?: boolean;\n}\n\n/** The loads that are preloads, which the Loading tab marks when nothing used them. */\nexport const PRELOADS: ReadonlySet<string> = new Set(['hover', 'visible', 'idle', 'eager']);\n\n/** An effect or a `$client` callback of a scope, with how it ran. */\nexport interface EffectEntry {\n scope: ScopeId;\n /** The ID of the component of the scope, and the scope's number in it. */\n component: string;\n k: number;\n /** Its name in the update code: `e<n>` for an effect, `c<n>` for a `$client` callback. */\n name: string;\n runs: number;\n /** When its last runs were, the newest last, at most 50. */\n recent: number[];\n /** The time of all its runs, in milliseconds. */\n time: number;\n cleanups: number;\n lastCleanup?: number;\n /** False once its cleanup ran and it has not run again, such as in a removed scope. */\n active: boolean;\n}\n\nexport interface DevtoolsState {\n scopes?: Map<ScopeId, Scope>;\n /** Writes a slot, as a handler does, so the page updates. */\n set?: (scope: Scope, slot: number, value: unknown) => void;\n /** Runs a reference for an element, as the loader does for a trigger. */\n handle?: (element: Element, ref: string, event?: Event) => Promise<unknown>;\n log: DevtoolsEntry[];\n /** The code that loaded, by `component:part`, in the order it started. */\n loads: Map<string, LoadEntry>;\n /** The blocks of the page, by kind and ID. */\n blocks: Map<string, BlockEntry>;\n /** Asks the server for the body of a `#defer` block now. */\n fire?: (block: BlockEntry) => void;\n /**\n * Shows the fallback of a `#loading` or `#defer` block in place of its\n * body, or its body again. False when the page did not keep its fallback.\n */\n showFallback?: (block: BlockEntry, on: boolean) => boolean;\n /** The scopes written since the panel last drew, by scope ID. */\n written: Set<ScopeId>;\n /** The URL prefix of the inspect endpoint of the dev server. */\n endpoint: string;\n /** The versions of brumate and Vite, from the plugin. */\n meta: DevtoolsMeta;\n /** The errors of the page, oldest first. */\n errors: ErrorEntry[];\n /** The handlers that ran, oldest first, with their calls and updates. */\n timeline: Interaction[];\n /** The effects and `$client` callbacks that ran, by scope and name. */\n effects: Map<string, EffectEntry>;\n /** The client navigations of the page, newest last, at most 20. */\n navigations: NavigationReport[];\n /** Opens the panel on a tab, such as `errors`. */\n open?: (tab: string) => void;\n /** Shows the number of errors on the tab. */\n errorCount?: () => void;\n /** True while the elements that change are outlined on the page. */\n flash: boolean;\n /** Turns the outlines of changed elements on or off, and keeps the choice. */\n setFlash?: (on: boolean) => void;\n /** While the panel is open: sets its top edge to a place of the pointer, and keeps it. */\n resize?: (clientY: number) => void;\n resized?: () => void;\n /** Called after each change, while the panel is open. */\n changed?: () => void;\n}\n\nconst MAX_LOG = 300;\n\n/**\n * The logo of brumate: the pole and the bowl of a b, in outline, where the\n * pole runs through the left of the bowl. The part they share is orange.\n */\nexport const LOGO = `<svg viewBox=\"0 0 32 32\" width=\"100%\" height=\"100%\" aria-hidden=\"true\"><defs><linearGradient id=\"brumate-logo-fill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#ffc38a\"/><stop offset=\".5\" stop-color=\"#ee7a3e\"/><stop offset=\"1\" stop-color=\"#e0445a\"/></linearGradient><clipPath id=\"brumate-logo-pole\"><rect x=\"7.5\" y=\"2.5\" width=\"8\" height=\"27\" rx=\"4\"/></clipPath></defs><circle cx=\"18\" cy=\"19.5\" r=\"10\" fill=\"url(#brumate-logo-fill)\" clip-path=\"url(#brumate-logo-pole)\"/><g fill=\"none\" stroke=\"#ece8e4\" stroke-width=\"2.2\"><rect x=\"7.5\" y=\"2.5\" width=\"8\" height=\"27\" rx=\"4\"/><circle cx=\"18\" cy=\"19.5\" r=\"10\"/></g></svg>`;\n\n/** The root scope of a scope, whose `m` names its component. */\nexport function rootOf(scope: Scope): Scope {\n let root = scope;\n while (root.p) {\n root = root.p;\n }\n return root;\n}\n\n/** A short text for a value in the log. */\nexport function preview(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);\n }\n if (typeof value === 'function') {\n return 'function';\n }\n if (Array.isArray(value)) {\n return `Array(${value.length})`;\n }\n if (value instanceof Element) {\n return `<${value.tagName.toLowerCase()}>`;\n }\n if (value !== null && typeof value === 'object') {\n const name = value.constructor?.name;\n return name && name !== 'Object' ? name : `{${Object.keys(value).slice(0, 3).join(', ')}}`;\n }\n return String(value);\n}\n\n/**\n * Reads the blocks of the page from their markers, and updates their state.\n * Returns true when something changed.\n *\n * - `#defer`: a `<template b-defer>`, and `<!--l…-->` around its fallback until its body arrives.\n * - `#loading`: `<!--l…-->` around its fallback until the server streams its body.\n * - `#client`: a `<template b-client>` with a `#k` reference, and a marker that gets `:1` once\n * its body rendered.\n * - `$client`: a `<template b-client>` with a `#c` reference.\n */\nexport function scanBlocks(state: DevtoolsState): boolean {\n const now = performance.now();\n let changed = false;\n const open = new Map<string, Comment>();\n const markers = new Map<string, Comment>();\n const walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const data = (node as Comment).data;\n if (/^l[\\d.-]+$/.test(data)) {\n open.set(data.slice(1), node as Comment);\n } else if (/^b-?[\\d.]+:\\d+/.test(data)) {\n markers.set(data.slice(1).split(':').slice(0, 2).join(':'), node as Comment);\n }\n }\n const seen = new Set<string>();\n const update = (key: string, make: () => BlockEntry, next: BlockEntry['state']): void => {\n seen.add(key);\n let block = state.blocks.get(key);\n if (!block) {\n block = make();\n state.blocks.set(key, block);\n changed = true;\n }\n if (block.state === 'rendered' || block.state === next) {\n return;\n }\n // A `#defer` that asked for its body and still shows its fallback did not get it.\n if (block.state === 'loading' && next === 'waiting') {\n return;\n }\n block.state = next;\n if (next === 'rendered') {\n block.rendered = now;\n }\n changed = true;\n };\n const deferBoundaries = new Set<string>();\n for (const template of document.querySelectorAll('template[b-defer]')) {\n const [trigger, boundary] = template.getAttribute('b-defer')!.split(':') as [string, string];\n deferBoundaries.add(boundary);\n update(\n `defer:${boundary}`,\n () => ({ kind: 'defer', id: boundary, trigger, template, state: 'waiting', seen: now }),\n open.has(boundary) ? 'waiting' : 'rendered',\n );\n }\n for (const boundary of open.keys()) {\n if (!deferBoundaries.has(boundary)) {\n update(\n `loading:${boundary}`,\n () => ({ kind: 'loading', id: boundary, state: 'streaming', seen: now }),\n 'streaming',\n );\n }\n }\n for (const template of document.querySelectorAll('template[b-client]')) {\n const [trigger, ref] = template.getAttribute('b-client')!.split('=') as [string, string];\n const id = template.getAttribute('b-b') ?? '';\n const block = /#k\\d+$/.test(ref);\n const marker = markers.get(id);\n update(\n `client:${id}`,\n () => ({\n kind: block ? 'client' : '$client',\n id,\n trigger,\n ref,\n template,\n state: 'waiting',\n seen: now,\n }),\n // A `$client` callback has run once its trigger fired.\n (\n block\n ? marker && marker.data.split(':').length > 2\n : state.blocks.get(`client:${id}`)?.fired\n )\n ? 'rendered'\n : 'waiting',\n );\n }\n // A `#loading` block whose markers are gone rendered its body. Other blocks that left the page,\n // such as on navigation, are dropped.\n for (const [key, block] of state.blocks) {\n if (seen.has(key)) {\n continue;\n }\n if (block.kind === 'loading') {\n if (block.state === 'streaming') {\n block.state = 'rendered';\n block.rendered = now;\n changed = true;\n }\n } else if (!block.template?.isConnected) {\n state.blocks.delete(key);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Adds an error to the Errors tab. An error of the server or of Vite opens\n * the panel on it, as Vite's overlay would. An error of the browser only\n * counts on the button.\n */\nexport function reportError(\n state: DevtoolsState,\n payload: ErrorPayload,\n source: ErrorEntry['source'],\n): void {\n const file = payload.loc?.file ?? payload.id;\n const entry: ErrorEntry = {\n time: performance.now(),\n // An error of a plugin, such as a compile error, is one, even when a render met it.\n source: source === 'server' && payload.plugin ? 'compile' : source,\n message: payload.message,\n ...(payload.stack ? { stack: payload.stack } : {}),\n ...(payload.frame ? { frame: payload.frame } : {}),\n ...(payload.plugin ? { plugin: payload.plugin } : {}),\n ...(payload.loc && file\n ? { loc: { file, line: payload.loc.line, column: payload.loc.column } }\n : {}),\n };\n // The same error again, such as on each request for the page, counts once.\n const last = state.errors.at(-1);\n if (last?.message !== entry.message || last.stack !== entry.stack) {\n state.errors.push(entry);\n if (state.errors.length > 50) {\n state.errors.shift();\n }\n }\n state.errorCount?.();\n state.changed?.();\n if (source !== 'browser') {\n state.open?.('errors');\n }\n}\n\n/** The code of the panel, which loads when it opens. */\nconst panelModule = (): Promise<typeof Panel> => import('./devtools-panel.ts');\n\n/** Where the choice to outline changed elements is kept. */\nconst FLASH_KEY = 'brumate:devtools:flash';\n/** How long an outline shows. */\nconst FLASH_MS = 700;\n/** The most outlines that one frame draws, so a big change does not stall the page. */\nconst MAX_FLASHES = 200;\n\n/** The class of an outline, by how many times the element changed in the last second. */\nfunction heatClass(count: number): string {\n if (count >= 5) {\n return 'hot';\n }\n return count >= 2 ? 'warm' : '';\n}\n\n/**\n * Outlines the elements that change, as an update writes them: green for an\n * element that changes now and then, yellow and red for one that changes\n * often. A MutationObserver sees every change of the page, so it needs no\n * hook of the core. The outlines are drawn in the shadow root, so the page\n * itself does not change.\n */\nfunction installFlash(state: DevtoolsState, root: ShadowRoot, host: Element): void {\n const layer = document.createElement('div');\n layer.className = 'flashes';\n root.append(layer);\n // How many times each element changed lately, for its colour.\n const heat = new WeakMap<Element, { count: number; time: number }>();\n const pending = new Set<Element>();\n let frame = 0;\n const draw = (): void => {\n frame = 0;\n let drawn = 0;\n for (const target of pending) {\n if (drawn >= MAX_FLASHES) {\n break;\n }\n const rect = target.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) {\n continue;\n }\n const now = performance.now();\n const last = heat.get(target);\n const count = last && now - last.time < 1000 ? last.count + 1 : 1;\n heat.set(target, { count, time: now });\n const box = document.createElement('div');\n box.className = `flash ${heatClass(count)}`;\n box.style.cssText = `left:${rect.left}px;top:${rect.top}px;width:${rect.width}px;height:${rect.height}px`;\n layer.append(box);\n setTimeout(() => box.remove(), FLASH_MS);\n drawn++;\n }\n pending.clear();\n };\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n let target: Node | null = record.target;\n if (record.type === 'childList') {\n // The elements that came in, or else the element that lost some.\n const added = [...record.addedNodes].filter((node) => node.nodeType === 1);\n for (const node of added) {\n pending.add(node as Element);\n }\n if (added.length > 0) {\n continue;\n }\n }\n if (target.nodeType !== 1) {\n target = target.parentElement;\n }\n if (\n target &&\n target !== host &&\n target !== document.documentElement &&\n target !== document.body\n ) {\n pending.add(target as Element);\n }\n }\n for (const target of pending) {\n // The devtools change their own markup, and the host carries their styles.\n if (target === host || host.contains(target)) {\n pending.delete(target);\n }\n }\n if (pending.size > 0 && frame === 0) {\n frame = requestAnimationFrame(draw);\n }\n });\n state.setFlash = (on) => {\n state.flash = on;\n if (on) {\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n } else {\n observer.disconnect();\n pending.clear();\n layer.replaceChildren();\n }\n try {\n localStorage.setItem(FLASH_KEY, on ? '1' : '0');\n } catch {\n // Storage can be off.\n }\n state.changed?.();\n };\n let saved = false;\n try {\n saved = localStorage.getItem(FLASH_KEY) === '1';\n } catch {\n // Storage can be off.\n }\n if (saved) {\n state.setFlash(true);\n }\n}\n\n/** True for an error of code that is not of the page, such as of a browser extension. */\nconst foreign = (stack: string | undefined, file = ''): boolean =>\n /^[a-z-]+-extension:/.test(file) ||\n (stack !== undefined && /[a-z-]+-extension:\\/\\//.test(stack) && !stack.includes(location.origin));\n\n/** Listens to the core, and adds the button that opens the panel. */\nexport function installDevtools(\n endpoint = '/__brumate/inspect',\n rpc = '/_brumate',\n meta: DevtoolsMeta = {},\n hot?: HotContext,\n): DevtoolsState {\n const state: DevtoolsState = {\n log: [],\n loads: new Map(),\n blocks: new Map(),\n written: new Set(),\n endpoint,\n meta,\n errors: [],\n timeline: [],\n effects: new Map(),\n navigations: [],\n flash: false,\n };\n /** The handler that a server call or an update that starts now belongs to. */\n const owner = (time: number): Interaction | undefined => {\n for (let index = state.timeline.length - 1; index >= 0; index--) {\n const run = state.timeline[index]!;\n // An update of the answer of a call comes a moment after the handler settled.\n if (run.begun <= time && (run.settled === undefined || time <= run.settled + 32)) {\n return run;\n }\n }\n return undefined;\n };\n const load = (component: string, part: string, reason: string, done: Promise<unknown>): void => {\n const key = `${component}:${part}`;\n const known = state.loads.get(key);\n if (known) {\n // The same code again, for a reason that is not a preload: the preload was used.\n if (!PRELOADS.has(reason)) {\n known.used = true;\n }\n return;\n }\n const entry: LoadEntry = { component, part, reason, start: performance.now(), used: false };\n state.loads.set(key, entry);\n done.then(\n () => {\n entry.end = performance.now();\n state.changed?.();\n },\n () => {\n entry.end = performance.now();\n entry.failed = true;\n state.changed?.();\n },\n );\n state.changed?.();\n };\n const add = (entry: Omit<DevtoolsEntry, 'time'>): void => {\n state.log.push({ ...entry, time: performance.now() });\n if (state.log.length > MAX_LOG) {\n state.log.splice(0, state.log.length - MAX_LOG);\n }\n state.changed?.();\n };\n const hooks: DevtoolsHooks = {\n attach(core) {\n state.scopes = core.scopes;\n state.set = core.set;\n state.handle = core.handle;\n state.changed?.();\n },\n load,\n handled(run) {\n const entry: Interaction = {\n ref: run.ref,\n label: `${run.event ?? 'call'} on <${run.element.tagName.toLowerCase()}>`,\n begun: run.begun,\n ready: run.ready,\n end: run.end,\n calls: [],\n updates: [],\n };\n if (run.result instanceof Promise) {\n run.result.then(\n () => {\n entry.settled = performance.now();\n state.changed?.();\n },\n () => {\n entry.settled = performance.now();\n entry.failed = true;\n state.changed?.();\n },\n );\n } else {\n entry.settled = run.end;\n }\n state.timeline.push(entry);\n if (state.timeline.length > 100) {\n state.timeline.shift();\n }\n state.changed?.();\n },\n updated(count, start, end) {\n if (count > 0) {\n owner(start)?.updates.push({ count, start, end });\n }\n },\n defer(template, done) {\n deferred(template, done);\n },\n handler(ref, element, event) {\n // The code of a handler runs, so a preload of its part was used.\n const [component, name] = ref.split('@')[0]!.split('#') as [string, string];\n const part = state.loads.get(`${component}:${/^[hct]\\d/.test(name) ? name : 'update'}`);\n if (part) {\n part.used = true;\n }\n if (element.tagName === 'TEMPLATE') {\n const block = [...state.blocks.values()].find((item) => item.template === element);\n if (block && block.fired === undefined) {\n block.fired = performance.now();\n if (block.kind === '$client') {\n block.state = 'rendered';\n block.rendered = block.fired;\n }\n }\n }\n add({\n kind: 'handler',\n text: `${event?.type ?? 'call'} on <${element.tagName.toLowerCase()}>: ${ref}`,\n });\n },\n part(component, name) {\n add({ kind: 'part', text: `loaded ${component} ${name}` });\n },\n effect(scope, name, kind, time) {\n const key = `${scope.id}:${name}`;\n let entry = state.effects.get(key);\n if (!entry) {\n entry = {\n scope: scope.id,\n component: rootOf(scope).m ?? '',\n k: scope.k,\n name,\n runs: 0,\n recent: [],\n time: 0,\n cleanups: 0,\n active: false,\n };\n state.effects.set(key, entry);\n }\n const now = performance.now();\n if (kind === 'run') {\n entry.runs++;\n entry.time += time;\n entry.recent.push(now);\n if (entry.recent.length > 50) {\n entry.recent.shift();\n }\n entry.active = true;\n } else {\n entry.cleanups++;\n entry.lastCleanup = now;\n entry.active = false;\n }\n state.changed?.();\n },\n navigated(report) {\n state.navigations.push(report);\n if (state.navigations.length > 20) {\n state.navigations.shift();\n }\n state.changed?.();\n },\n write(scope, slot, value) {\n state.written.add(scope.id);\n const root = rootOf(scope);\n add({\n kind: 'write',\n text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,\n scope: scope.id,\n write: { component: root.m ?? '', k: scope.k, slot },\n });\n },\n };\n (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS] = hooks;\n\n // The swap of a body keeps its fallback in development, by boundary, so the fallback can show\n // again. While it shows, the body is out of the page, and updates of its nodes wait there.\n state.showFallback = (block, on) => {\n const kept = (globalThis as { $bD?: Record<string, { f: Node[]; b: Node[] }> }).$bD?.[block.id];\n if (!kept || (block.fallback ?? false) === on) {\n return false;\n }\n const [shown, hidden] = on ? [kept.b, kept.f] : [kept.f, kept.b];\n const anchor = shown.find((node) => node.parentNode);\n if (!anchor) {\n return false;\n }\n for (const node of hidden) {\n anchor.parentNode!.insertBefore(node, anchor);\n }\n for (const node of shown) {\n node.parentNode?.removeChild(node);\n }\n block.fallback = on;\n state.changed?.();\n return true;\n };\n\n // Server function calls, with how long each took and how it answered.\n const original = globalThis.fetch.bind(globalThis);\n globalThis.fetch = async (input, init) => {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== location.origin || !url.pathname.startsWith(`${rpc}/`)) {\n return original(input, init);\n }\n const name = decodeURIComponent(url.pathname.slice(rpc.length + 1));\n const started = performance.now();\n const call: CallTiming = { name, start: started };\n owner(started)?.calls.push(call);\n try {\n const response = await original(input, init);\n const took = Math.round(performance.now() - started);\n const redirect = response.headers.get('x-brumate-redirect');\n call.end = performance.now();\n call.status = redirect ? 'redirect' : response.status;\n const server = /brumate;dur=([\\d.]+)/.exec(response.headers.get('server-timing') ?? '');\n if (server) {\n call.server = Number(server[1]);\n }\n state.changed?.();\n add({\n kind: 'call',\n text: `${name}: ${redirect ? `redirect to ${redirect}` : response.status} in ${took} ms`,\n });\n return response;\n } catch (error) {\n call.end = performance.now();\n call.status = 'failed';\n add({\n kind: 'call',\n text: `${name}: failed, ${error instanceof Error ? error.message : String(error)}`,\n });\n throw error;\n }\n };\n\n // Blocks: the markers of the page tell their state, so the panel follows the changes of the DOM.\n const deferred = (template: Element, done: Promise<unknown>): void => {\n const block = [...state.blocks.values()].find((item) => item.template === template);\n if (block) {\n block.fired ??= performance.now();\n block.state = 'loading';\n }\n void done.finally(() => {\n scanBlocks(state);\n state.changed?.();\n });\n };\n state.fire = (block) => {\n if (block.kind === 'defer' && block.template) {\n deferred(\n block.template,\n import('./defer.ts').then((module) => module.loadDeferred(block.template!)),\n );\n } else if (block.template && block.ref) {\n void state.handle?.(block.template, block.ref);\n }\n };\n if (typeof MutationObserver !== 'undefined') {\n let queued = false;\n new MutationObserver(() => {\n if (!queued) {\n queued = true;\n queueMicrotask(() => {\n queued = false;\n if (scanBlocks(state)) {\n state.changed?.();\n }\n });\n }\n }).observe(document, { childList: true, subtree: true, characterData: true });\n }\n scanBlocks(state);\n\n const host = document.createElement('brumate-devtools');\n const root = host.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = `\n.open { position: fixed; left: 50%; bottom: 0; z-index: 2147483647; transform: translateX(-50%); display: flex; justify-content: center; padding: 8px 16px 0; border: 0; background: none; color: #ece8e4; font: 600 12px/1 system-ui, -apple-system, sans-serif; cursor: pointer; touch-action: none; outline: none; }\n.open[hidden] { display: none; }\n.grip { width: 40px; height: 5px; border-radius: 4px 4px 0 0; background: rgb(25 24 26 / 0.88); box-shadow: 0 0 0 1px rgb(255 255 255 / 0.3); transition: opacity 150ms cubic-bezier(0.4, 0, 0.2, 1), width 150ms cubic-bezier(0.4, 0, 0.2, 1); }\n.open[data-errors] .grip { width: 56px; background: #e5484d; }\n.content { position: absolute; left: 50%; bottom: 0; transform: translate(-50%, 100%); display: flex; align-items: center; gap: 8px; padding: 5px 8px 5px 10px; white-space: nowrap; background: #222023; border: 1px solid #2f2c31; border-bottom: 0; border-radius: 10px 10px 0 0; box-shadow: 0 -4px 16px rgb(0 0 0 / 0.3); opacity: 0; pointer-events: none; transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1), opacity 150ms cubic-bezier(0.4, 0, 0.2, 1); }\n.open:hover .content, .open:focus-visible .content, .open:active .content { transform: translate(-50%, 0); opacity: 1; pointer-events: auto; }\n.open:hover .grip, .open:focus-visible .grip, .open:active .grip { opacity: 0; }\n.open:focus-visible .content { border-color: #ee7a3e; }\n.mark { display: inline-flex; width: 16px; height: 16px; }\n.version { padding: 1px 8px; border-radius: 999px; background: rgb(238 122 62 / 0.16); color: #ffb48a; font: 600 12px/20px ui-monospace, SFMono-Regular, Menlo, monospace; }\n.chevron { width: 12px; height: 12px; color: #a39a92; }\n.count { min-width: 18px; padding: 0 5px; box-sizing: border-box; border-radius: 999px; background: #e5484d; color: #fff; font: 600 11px/18px system-ui, sans-serif; text-align: center; }\n.count:empty { display: none; }\n.flashes { position: fixed; inset: 0; pointer-events: none; z-index: 2147483646; }\n.flash { position: fixed; box-sizing: border-box; border: 2px solid #7fd99a; border-radius: 3px; background: rgb(127 217 154 / 0.08); animation: flash 700ms ease-out forwards; }\n.flash.warm { border-color: #ffd166; background: rgb(255 209 102 / 0.1); }\n.flash.hot { border-color: #ff7a7a; background: rgb(255 122 122 / 0.12); }\n@keyframes flash { from { opacity: 1; } to { opacity: 0; } }\n@media (prefers-reduced-motion: reduce) { .flash { animation: none; } }\n@media (prefers-reduced-motion: reduce) { .grip, .content { transition: none; } }\n`;\n // The closed panel: a grip on the bottom edge that grows into a pull tab on hover or focus, so\n // it covers almost none of the page. A click, or a drag up, opens the panel.\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'open';\n button.title = 'brumate devtools (Alt+Shift+D)';\n button.innerHTML = `<span class=\"grip\"></span><span class=\"content\"><span class=\"mark\">${LOGO}</span><span class=\"version\"></span><span class=\"count\"></span><svg class=\"chevron\" viewBox=\"0 0 12 12\" aria-hidden=\"true\"><path d=\"M3 7.5 6 4.5 9 7.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></span>`;\n // The version of brumate, next to its mark.\n button.querySelector('.version')!.textContent = meta.version ? `v${meta.version}` : 'brumate';\n const label = (): void => {\n const errors = state.errors.length;\n button.setAttribute(\n 'aria-label',\n `Open the brumate devtools${meta.version ? `, version ${meta.version}` : ''}${errors > 0 ? `, ${errors} errors` : ''}`,\n );\n };\n label();\n // The number of errors, in red on the tab, and a red grip, so an error shows while it is closed.\n const count = button.querySelector<HTMLElement>('.count')!;\n state.errorCount = (): void => {\n count.textContent = state.errors.length > 0 ? String(state.errors.length) : '';\n button.toggleAttribute('data-errors', state.errors.length > 0);\n label();\n };\n // Dragging the tab up past a few pixels opens the panel under the pointer. A press that does not\n // move is left to the click.\n let dragged = false;\n button.addEventListener('pointerdown', (event) => {\n if (event.button !== 0) {\n return;\n }\n const start = event.clientY;\n let opened = false;\n dragged = false;\n const move = (next: PointerEvent): void => {\n if (!opened) {\n if (start - next.clientY < 4) {\n return;\n }\n opened = true;\n dragged = true;\n void panelModule().then(({ openPanel }) => {\n openPanel(root, state, 'overview');\n state.resize?.(next.clientY);\n });\n return;\n }\n state.resize?.(next.clientY);\n };\n // The tab hides as the panel opens, so the pointer is followed on the window.\n const end = (): void => {\n removeEventListener('pointermove', move);\n removeEventListener('pointerup', end);\n removeEventListener('pointercancel', end);\n if (opened) {\n state.resized?.();\n }\n };\n addEventListener('pointermove', move);\n addEventListener('pointerup', end);\n addEventListener('pointercancel', end);\n });\n button.addEventListener('click', () => {\n if (dragged) {\n dragged = false;\n return;\n }\n void panelModule().then(({ togglePanel }) => togglePanel(root, state));\n });\n // Alt+Shift+D opens and closes the panel. `code`, because Alt changes the key on macOS.\n addEventListener('keydown', (event) => {\n if (event.altKey && event.shiftKey && event.code === 'KeyD') {\n event.preventDefault();\n void panelModule().then(({ togglePanel }) => togglePanel(root, state));\n }\n });\n state.open = (tab) => {\n void import('./devtools-panel.ts').then(({ openPanel }) => openPanel(root, state, tab));\n };\n root.append(style, button);\n installFlash(state, root, host);\n\n // Errors of code of the page in the browser. Errors of other code are left out.\n addEventListener('error', (event) => {\n const stack = (event.error as Error | undefined)?.stack;\n if (foreign(stack, event.filename)) {\n return;\n }\n const error = event.error as Error | undefined;\n // The message of the error, without the `Uncaught` that the browser puts before it.\n reportError(\n state,\n { message: error?.message ?? event.message, stack: error?.stack },\n 'browser',\n );\n });\n addEventListener('unhandledrejection', (event) => {\n const reason = event.reason as Error | undefined;\n if (foreign(reason?.stack)) {\n return;\n }\n reportError(\n state,\n { message: reason?.message ?? String(event.reason), stack: reason?.stack },\n 'browser',\n );\n });\n // Errors of handlers and updates that no `#try` caught. The core catches them, so they do not\n // reach the listeners above.\n addEventListener('brumate:error', (event) => {\n const error = (event as CustomEvent<{ error: unknown }>).detail.error as Error | undefined;\n reportError(\n state,\n { message: error?.message ?? String(error), stack: error?.stack },\n 'browser',\n );\n });\n // Errors of Vite, such as a compile error after an edit, which its overlay would show. A good\n // update after them clears them.\n hot?.on('vite:error', (payload: { err: ErrorPayload }) => {\n reportError(state, payload.err, 'compile');\n });\n hot?.on('vite:afterUpdate', () => {\n const before = state.errors.length;\n state.errors = state.errors.filter((error) => error.source !== 'compile');\n if (state.errors.length !== before) {\n state.errorCount?.();\n state.changed?.();\n }\n });\n const append = (): void => {\n // Navigation replaces the body, so the button goes on the document element.\n document.documentElement.append(host);\n };\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', append);\n } else {\n append();\n }\n return state;\n}\n"],"mappings":";AAUA,MAAM,WAAW,OAAO,IAAI,kBAAkB;;AA2H9C,MAAa,2BAAgC,IAAI,IAAI;CAAC;CAAS;CAAW;CAAQ;AAAO,CAAC;AAoE1F,MAAM,UAAU;;;;;AAMhB,MAAa,OAAO;;AAGpB,SAAgB,OAAO,OAAqB;CAC1C,IAAI,OAAO;CACX,OAAO,KAAK,GACV,OAAO,KAAK;CAEd,OAAO;AACT;;AAGA,SAAgB,QAAQ,OAAwB;CAC9C,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK,UAAU,MAAM,SAAS,KAAK,GAAG,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,KAAK;CAE5E,IAAI,OAAO,UAAU,YACnB,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,SAAS,MAAM,OAAO;CAE/B,IAAI,iBAAiB,SACnB,OAAO,IAAI,MAAM,QAAQ,YAAY,EAAE;CAEzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,OAAO,MAAM,aAAa;EAChC,OAAO,QAAQ,SAAS,WAAW,OAAO,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;CAC1F;CACA,OAAO,OAAO,KAAK;AACrB;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA+B;CACxD,MAAM,MAAM,YAAY,IAAI;CAC5B,IAAI,UAAU;CACd,MAAM,uBAAO,IAAI,IAAqB;CACtC,M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