jq79 0.5.13 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/jq79.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jq79.ts","../src/dom.ts","../src/reactive.ts","../src/transform.ts"],"sourcesContent":["\nimport { $, $$, $create, sanitizeHTML, allowedHosts } from \"./dom\"\nimport type { AllowUrl } from \"./dom\"\nimport { $reactive, $toRaw, untracked, createEffectScope, ALSO_WAKEN_BY } from \"./reactive\"\nimport type { ReactiveDeepData, EffectScope } from \"./reactive\"\nimport { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, type PropDecl } from \"./transform\"\n\nexport { $, $$, $create } from \"./dom\"\nexport { $reactive, $toRaw } from \"./reactive\"\n\n// the package version, substituted at build time (tsup/vitest `define`, read\n// from package.json - releases bump it there and nowhere else). The typeof\n// guard is what keeps the raw source runnable: tests and any bundler that\n// doesn't define it see a bare identifier, not a ReferenceError\ndeclare const __JQ79_VERSION__: string\nconst VERSION = typeof __JQ79_VERSION__ === \"string\" ? __JQ79_VERSION__ : \"0.0.0-dev\"\n\ntype TemplateNode = {\n tag: string\n attrs: Record<string, string>\n children: (TemplateNode | string)[]\n // the tag as the author capitalized it, present only when they wrote it\n // uppercase-initial - i.e. when they meant a component. `tag` cannot answer\n // this: the HTML parser lowercases it, so the claim is captured before the\n // parse (see stampComponentTag) and lifted off attrs here, where it stops\n // looking like an attribute to every loop downstream\n component?: string\n}\n\ntype TagBlock = {\n attrs: Record<string, string>\n content: string\n // <style scoped> only: `content` rewritten to require the component's scope\n // attribute. Kept beside the original rather than replacing it, because a\n // shadow root doesn't want it - see headStyle()\n scoped?: string\n}\n\nconst elementAttrs = (el: Element): Record<string, string> =>\n Object.fromEntries(Array.from(el.attributes).map(attr => [attr.name, attr.value]))\n\n// text is kept verbatim - not trimmed, not dropped when it's only whitespace.\n// A template is HTML, so the space in `<span>a</span>\\n<span>b</span>` is the\n// same space the browser would collapse-and-render between them, and CSS gets\n// to decide what it's worth (nothing in a block or flex container, one space\n// between inline elements). Trimming it here, as this used to, silently glued\n// siblings together and ate the spaces in `hola <b>mundo</b> adios`\n//\n// A <template>'s children are read from its .content fragment: that is where\n// the HTML parser puts them, and its childNodes are empty. Without the descent\n// they are not in the AST at all - which is where slot content is written\n// (<template :slot.name>), and why a nested <template> used to render as an\n// empty element whatever was inside it\nconst elementToAST = (el: Element): TemplateNode => {\n const attrs = elementAttrs(el)\n // the pre-parse stamp becomes a field and leaves attrs entirely: it is not a\n // prop, not a directive and not an attribute, and every loop that walks attrs\n // would otherwise need to know its name\n const component = attrs[COMPONENT_TAG_ATTR]\n delete attrs[COMPONENT_TAG_ATTR]\n return {\n tag: el.tagName.toLowerCase(),\n attrs,\n ...(component === undefined ? {} : { component }),\n children: Array.from((el instanceof HTMLTemplateElement ? el.content : el).childNodes).flatMap((node): (TemplateNode | string)[] => {\n if (node.nodeType === Node.TEXT_NODE) {\n const text = node.textContent ?? \"\"\n return text ? [text] : []\n }\n if (node.nodeType === Node.ELEMENT_NODE) {\n return [elementToAST(node as Element)]\n }\n return []\n })\n }\n}\n\n// evaluated with `with` (rather than passing scope keys as positional params)\n// so only the identifiers an expression actually references are read from\n// `scope` - which is what makes dependency tracking in $reactive\n// precise instead of \"read everything up front\". `extras` are passed as\n// function parameters (outside the `with`), so scope keys still win but names\n// like $event resolve when the scope doesn't shadow them\n//\n// Compiled functions are cached: an expression is re-evaluated on every effect\n// run - once per interpolation, once per :each item - while the set of distinct\n// expressions is fixed by the source. The `extras` names are part of the key,\n// not just the expression: they become the function's parameters, so the same\n// expression compiled with and without $event is two different functions. A\n// syntactically invalid expression caches its failure (null) so it isn't\n// recompiled, and rethrown as undefined, exactly as before\nconst compiled = new Map<string, Function | null>()\n\nconst compileExpr = (expr: string, params: string[]): Function | null => {\n const key = `${params.join(\",\")}|${expr}`\n let fn = compiled.get(key)\n if (fn === undefined) {\n try {\n // the newline before `)` ends a trailing line comment in the\n // expression ({{ msg // greeting }}); ASI doesn't apply inside parens,\n // so everything else is untouched. Without it the comment eats the\n // rest of this single-line body and the expression never compiles\n fn = new Function(\"$scope\", ...params, `with ($scope) { return (${expr}\\n); }`)\n } catch {\n fn = null // a syntax error: it will never compile, so don't try again\n }\n compiled.set(key, fn)\n }\n return fn\n}\n\n// a template expression is re-evaluated constantly - once per effect run, once\n// per interpolation, once per :each item - so a value that is briefly undefined\n// mid-render has to fail quietly, and the catch below stays. A ReferenceError\n// is the one failure worth a word: `with` resolves a name against the store and\n// then globalThis, so a name that resolves nowhere is declared nowhere - a\n// typo, a dropped prop, or the trap this was written for, a top-level\n// `function` declaration, which transformSetupScript leaves as an ordinary\n// lexical binding instead of a store property\n//\n// It is reported late rather than where it throws, because \"declared nowhere\"\n// is not yet decidable at that moment: a factory script assigns its bindings to\n// the store when it returns, so an async factory renders its whole template\n// before any of its names exist. Reporting waits until no script is still\n// running (pendingScripts), and then asks whether the name resolves *now*.\n//\n// The re-check is `name in scope` rather than a re-evaluation, because\n// re-evaluating is not pure: `@click=\"count++ + missing\"` increments before it\n// throws, and running it again to see if it still throws would increment twice\n// and notify. `in` walks the same scope chain (:each scopes are\n// Object.create(scope), :with is a proxy over it) and evaluates nothing\nconst MISSING_NAME_RE = /^(?:([\\w$]+) is not defined|Can't find variable: ([\\w$]+))/\n\n// the queue holds live scopes, so it is capped: a script that never settles\n// would otherwise let it grow for the life of the page\nconst MAX_PENDING_REPORTS = 100\n\ntype PendingReport = { name: string; expr: string; scope: Record<string, any> }\n\nconst pendingReports = new Map<string, PendingReport>()\nconst reportedExprErrors = new Set<string>()\nlet pendingScripts = 0\nlet flushScheduled = false\n\n// everything else an expression can throw - overwhelmingly a member access on\n// an undefined value, `{{ game.is.loaded }}` over a game with no `is`. Unlike a\n// missing name it needs no deferral and gets none: the engine already caught a\n// real exception and wrote the message, so there is nothing left to decide and\n// it is reported where it throws, as an error rather than a warning.\n//\n// That means a value still on its way is reported too - `{{ user.name }}` over\n// a user that a fetch will fill renders empty and says so, once. It is a\n// deliberate trade against the silence it replaces, which hid a render that was\n// actively wrong (a thrown `:disabled` is falsy, so the button rendered\n// *enabled*). The fix is the one the message names: `user?.name`, or `:if`.\n//\n// Deduped by expression text alone. A `:each` over 1000 rows throws 1000 times\n// per render and the Set is what keeps that to one line; keying finer - by\n// message too, as the missing-name queue does - would let one broken path\n// report once per distinct message. There is no queue behind it because there\n// is nothing to re-check, and so nothing that could retain a live scope\nconst reportedFailedExprs = new Set<string>()\n\nconst flushExprReports = () => {\n flushScheduled = false\n if (pendingScripts > 0) return // a script started meanwhile; its release re-schedules\n pendingReports.forEach(({ name, expr, scope }, key) => {\n if (name in scope) return // it arrived late - a factory's bindings, a prop\n reportedExprErrors.add(key)\n console.warn(\n `jq79: ${name} is not defined - evaluating \"${expr}\". Template expressions ` +\n `resolve against the component store: a top-level let/var/const in a :setup ` +\n `script, a declared prop, or a global. Note a \"function name() {}\" declaration ` +\n `is not on the store - write \"const name = () => {}\".`\n )\n })\n pendingReports.clear()\n}\n\nconst scheduleExprReportFlush = () => {\n if (flushScheduled || pendingScripts > 0 || !pendingReports.size) return\n flushScheduled = true\n queueMicrotask(flushExprReports)\n}\n\n// scripts run before the template renders, so the counter is already up when\n// the first evaluation fails. Both script modes settle through a promise;\n// the factory's has to cover the merge, not just the module body\nconst trackScript = (settled: Promise<unknown>) => {\n pendingScripts++\n const release = () => {\n pendingScripts--\n scheduleExprReportFlush()\n }\n settled.then(release, release)\n}\n\n// console.error, not warn: a name that resolves nowhere is a warning because\n// the runtime can only say the name is absent, while this one caught a real\n// exception - it has a message the engine wrote, and the expression rendered as\n// nothing instead of doing what it says\nconst reportFailedExpr = (expr: string, error: unknown) => {\n if (reportedFailedExprs.has(expr)) return\n reportedFailedExprs.add(expr)\n const message = (error as Error)?.message || String(error)\n console.error(\n `jq79: ${message} - evaluating \"${expr}\". The expression rendered as nothing. ` +\n `If the value arrives later, guard it - \"a?.b\", or :if on the element.`\n )\n}\n\nconst reportExprError = (expr: string, scope: Record<string, any>, error: unknown) => {\n if (!(error instanceof ReferenceError)) return reportFailedExpr(expr, error)\n const match = MISSING_NAME_RE.exec(error.message)\n const name = match?.[1] ?? match?.[2]\n if (!name) return // an engine whose wording we don't know: stay quiet, as before\n // keyed on name and expression, not on the expression alone, so two missing\n // names in one expression stay distinguishable - and so a :each of 1000 items\n // enqueues one entry rather than 1000\n const key = `${name}|${expr}`\n if (reportedExprErrors.has(key) || pendingReports.has(key)) return\n if (pendingReports.size >= MAX_PENDING_REPORTS) return\n pendingReports.set(key, { name, expr, scope })\n scheduleExprReportFlush()\n}\n\nconst runExpr = (expr: string, scope: Record<string, any>, extras?: Record<string, any>): any => {\n const fn = compileExpr(expr, extras ? Object.keys(extras) : [])\n if (!fn) return undefined // a syntax error: compileExpr cached the failure, and it stays undefined\n return fn(scope, ...(extras ? Object.values(extras) : []))\n}\n\nconst evalExpr = (expr: string, scope: Record<string, any>, extras?: Record<string, any>): any => {\n try {\n return runExpr(expr, scope, extras)\n } catch (error) {\n reportExprError(expr, scope, error)\n return undefined\n }\n}\n\n// the same evaluation for an @event attribute, which swallows far less. Every\n// word of the reason evalExpr catches is about rendering: an expression is\n// re-evaluated per effect run, per interpolation, per :each item, so a value\n// that is briefly undefined mid-render has to render empty rather than tear the\n// render down. A handler runs in an event listener - not in an effect, once,\n// when the user clicked - so there is no transient failure to absorb, only a\n// bug to report, and an exception belongs in the console with its stack. That\n// is what `@click=\"save\"` has always done (the call happens outside the try,\n// on the returned function); this is what makes `@click=\"save()\"` and\n// `@click=\"count++\"` behave the same rather than the other way round.\n//\n// ReferenceError is the exception, for the reason it always is: it is not yet\n// decidable at throw time. A factory assigns its names to the store when it\n// returns, so a click while one is still in flight throws for a name that is\n// about to exist - reportExprError re-checks after the scripts settle and stays\n// quiet if it arrived, which throwing here would replace with a false alarm\nconst evalHandler = (expr: string, scope: Record<string, any>, extras: Record<string, any>): any => {\n try {\n return runExpr(expr, scope, extras)\n } catch (error) {\n if (!(error instanceof ReferenceError)) throw error\n reportExprError(expr, scope, error)\n return undefined\n }\n}\n\n// [\\s\\S] rather than `.` so an expression can span lines, like the ones in\n// directive attributes (which reach evalExpr wrapped in parens either way)\nconst interpolate = (template: string, scope: Record<string, any>): string =>\n template.replace(/{{\\s*([\\s\\S]+?)\\s*}}/g, (_, expr) => evalExpr(expr, scope) ?? \"\")\n\n\nconst CONTROL_ATTRS = new Set([\":attrs\", \":class\", \":value\", \":checked\", \":selected\", \":if\", \":elseif\", \":else\", \":each\", \":key\", \":with\", \":text\", \":html\", \":html.allowed\", \":props\"])\n\n// a control attribute is one the static-attr loop and nested-component prop\n// collection must skip. The set holds the fixed names; `:class.<name>` (the\n// single-flag shorthand) and `:props.<n>` (one spread among several) are\n// open-ended, so they're matched by prefix - they can't be enumerated into the set\nconst isControlAttr = (attr: string): boolean =>\n CONTROL_ATTRS.has(attr) || attr.startsWith(\":class.\") || attr.startsWith(\":props.\") ||\n attr === \":slot\" || attr.startsWith(\":slot.\")\n// `item in items`, `item, i in items`, `(value, key) in props` - the second\n// binding is the array index or the object key, parens optional (Vue-style).\n// The list expression can span lines, so it matches [\\s\\S] rather than `.`\nconst EACH_PATTERN = /^\\s*\\(?\\s*(\\w+)\\s*(?:,\\s*(\\w+))?\\s*\\)?\\s+in\\s+([\\s\\S]+)$/\n\ntype ConditionalBranch = { expr?: string; node: TemplateNode }\n\n\n// @event attributes: @click=\"onClick\", @submit.prevent=\"$event => onSubmit($event)\",\n// or an inline statement like @click=\"count = count + 1\". The expression is\n// evaluated (with `$event` in scope) on every event; if it yields a function,\n// that function is then invoked with the event - so both a handler reference\n// and an inline arrow/statement work. Modifiers after dots: .prevent .stop\n// .self (runtime guards) and .once .capture (addEventListener options)\nconst bindEvent = (el: Element, attr: string, expr: string, scope: Record<string, any>) => {\n const [name, ...modifiers] = attr.slice(1).split(\".\")\n const mods = new Set(modifiers)\n\n el.addEventListener(name, event => {\n if (mods.has(\"self\") && event.target !== el) return\n if (mods.has(\"prevent\")) event.preventDefault()\n if (mods.has(\"stop\")) event.stopPropagation()\n\n const handler = evalHandler(expr, scope, { $event: event })\n if (typeof handler === \"function\") handler.call(el, event)\n }, { once: mods.has(\"once\"), capture: mods.has(\"capture\") })\n}\n\n// @event on a component tag: the tag renders as comment anchors, so there is\n// no element to listen on - the attribute subscribes to the child instance's\n// $emit channel (instance.on) instead, which survives the child's re-renders\n// and works detached. Native DOM events from the child's inner DOM never\n// arrive here: they bubble past the anchors to shared ancestors (a listener\n// on a wrapping element hears those); a child that wants its native event\n// heard on its tag re-emits it. .prevent flips the child's $emit() return to\n// false, .stop keeps the emit off the DOM dispatch, .once unsubscribes after\n// one call; .self and .capture have no meaning on this channel and are ignored\nconst wireTagEvent = (instance: Component79, attr: string, expr: string, scope: Record<string, any>) => {\n const [name, ...modifiers] = attr.slice(1).split(\".\")\n const mods = new Set(modifiers)\n\n const listener = (event: CustomEvent) => {\n if (mods.has(\"prevent\")) event.preventDefault()\n if (mods.has(\"stop\")) event.stopPropagation()\n if (mods.has(\"once\")) instance.off(name, listener)\n\n // untracked, so a tag handler behaves like an element handler no matter\n // when the emit fires: an element handler never runs inside an effect,\n // but $emit can (a $: that emits, a setup-script emit inside the parent's\n // creation effect), and the handler's reads would land in that effect's\n // deps. Today that is contained - cross-store deps are never notified,\n // and the creation effect's definition guard no-ops a spurious wake - but\n // \"what a handler reads is nobody's dependency\" shouldn't hinge on either\n untracked(() => {\n const handler = evalHandler(expr, scope, { $event: event })\n if (typeof handler === \"function\") handler(event)\n })\n }\n instance.on(name, listener)\n}\n\nconst kebabToCamel = (name: string) => name.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase())\n\n// the inverse, used only by the pre-parse name rewrite (see expandNameCase):\n// uppercase ASCII letters only, never digits - `:props.0` is a generated\n// attribute name and splitting on digits would mangle it. Round-trips through\n// kebabToCamel, acronyms included: userID -> user-i-d -> userID\nconst camelToKebab = (name: string) => name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)\n\n// the stable boundaries of a rendered chunk. An element is its own handle, but\n// a fragment (a nested component: two anchors with the instance's DOM between\n// them) empties itself into the parent on insertion - after that its identity\n// answers nothing, and what stays put are its first and last children. Callers\n// that reposition or remove a chunk later (:each entries, :if branches) must\n// capture its bounds *before* inserting it and work on the range\ntype NodeRange = { first: Node; last: Node }\n\nconst boundsOf = (node: Node): NodeRange =>\n node instanceof DocumentFragment\n ? { first: node.firstChild!, last: node.lastChild! }\n : { first: node, last: node }\n\n// removes [first..last] inclusive - the range's content is dynamic (a nested\n// component's DOM comes and goes between its anchors), so it walks siblings\n// rather than assuming any particular nodes in between\nconst removeRange = ({ first, last }: NodeRange) => {\n for (let node: Node | null = first; node; ) {\n const next: Node | null = node === last ? null : node.nextSibling\n node.parentNode?.removeChild(node)\n node = next\n }\n}\n\n// moves [first..last] inclusive so the range starts right after `prev`\nconst moveRangeAfter = ({ first, last }: NodeRange, prev: Node) => {\n const ref = prev.nextSibling\n for (let node: Node | null = first; node; ) {\n const next: Node | null = node === last ? null : node.nextSibling\n prev.parentNode!.insertBefore(node, ref)\n node = next\n }\n}\n\n// finds the scope variable a template tag refers to. HTML parsing lowercases\n// tag names, so <NestedComponent> arrives as \"nestedcomponent\" and matching is\n// case-insensitive with dashes stripped (<nested-component> works too). Only\n// PascalCase scope keys participate, so ordinary variables named like real\n// elements (title, code, ...) never hijack them\nconst findComponentKey = (scope: Record<string, any>, tag: string): string | null => {\n const normalized = tag.replace(/-/g, \"\").toLowerCase()\n for (let obj: any = scope; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {\n for (const key of Object.keys(obj)) {\n if (/^[A-Z]/.test(key) && key.replace(/-/g, \"\").toLowerCase() === normalized) return key\n }\n }\n return null\n}\n\n// every name a tag *could* have resolved to, walking the same chain\n// findComponentKey does. Deduped and sorted, because the chain can hold one\n// name twice (a prop shadowing a sibling) and the order it comes out in is the\n// prototype's, which means nothing to a reader scanning for their typo\nconst componentsInScope = (scope: Record<string, any>): string[] => {\n const names = new Set<string>()\n for (let obj: any = scope; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {\n for (const key of Object.keys(obj)) if (/^[A-Z]/.test(key)) names.add(key)\n }\n return [...names].sort()\n}\n\n// a tag whose name resolves to no component, once nothing can still supply one.\n// The error names what *is* in scope: the mistake is nearly always a typo or a\n// missing import, and both are one glance from the list. \"(none)\" is its own\n// answer - it says the component has no components at all, which points at the\n// import rather than at the spelling\nconst unresolvedComponent = (tag: string, scope: Record<string, any>): Error => {\n const names = componentsInScope(scope)\n return new Error(\n `jq79: <${tag}> is not defined - no component of that name is in scope, and nothing renders here. ` +\n `Import it in a :setup script, declare it as a prop, or add a <template name=\"${tag}\"> to this file. ` +\n `In scope: ${names.length ? names.join(\", \") : \"(none)\"}.`\n )\n}\n\n// how deep a component may nest inside itself before the runtime calls it a\n// cycle. Deeper than any real tree, shallower than the JS stack: a truncated\n// render with an error on the console beats a stack overflow with none\nconst MAX_NESTING_DEPTH = 200\nlet nestingDepth = 0\n\n// ---------------------------------------------------------------------------\n// slots - content projection\n//\n// A component tag's children are content the child renders where it wrote a\n// <slot>. The dot marks the named variant on both sides, like :model.<name>\n// and :class.<name> already do:\n//\n// <!-- Card.html --> <!-- the parent -->\n// <section> <Card>\n// <header> <template :slot.header><h2>{{ t }}</h2></template>\n// <slot.header>?</slot.header>\n// </header> <p>{{ body }}</p>\n// <slot /> </Card>\n// </section>\n//\n// Three rules decide everything below:\n//\n// 1. Content belongs to the parent - its AST, its scope, its effects, its\n// scoped styles. The child decides *where* it goes and *whether* it goes,\n// never what the names in it mean.\n// 2. Slot props are declared, not injected: `:slot=\"{ item }\"` on the usage\n// site, for the same reason :each writes `item in rows`. Every bare name in\n// the parent's file is introduced by the parent, so a `<slot :item>` the\n// child adds later can't silently capture one.\n// 3. What isn't projected isn't rendered. No <slot>, or one behind a false\n// :if, and the content's effects never exist.\n//\n// The content travels as a thunk, not as DOM: an instance is replaced (a\n// definition swap, a hot reload) and one <slot> may render many times, so a\n// pre-rendered fragment would leak effects and could only be inserted once\n// ---------------------------------------------------------------------------\n\n// renders one slot's content at the position the child put the <slot>: it is\n// handed the slot's props (lazy, so each read re-evaluates in the child's\n// scope), that position's scope and effect scope, and the style mode the\n// child renders under\ntype SlotRenderer = (\n props: Record<string, () => any>,\n slotScope: Record<string, any>,\n fx: EffectScope,\n shadow: boolean\n) => Node\n\ntype SlotMap = Record<string, SlotRenderer>\n\n// the content an instance was handed, by slot name. Symbol-keyed and\n// non-enumerable on the store's data, like UNFILLED_PROPS: it rides the scope\n// chain (so a <slot> inside an :each or a :with finds it) and never shows up\n// as data - not in Object.keys, not in a snapshot spread, not in the props a\n// nested component is handed\nconst SLOTS = Symbol(\"jq79.slots\")\n\n// <slot>, <slot.header-bar>: the hole and its name. Names arrive kebab-case\n// whichever way they were authored (the HTML parser lowercases tag names and\n// attribute modifiers alike, so expandNameCase normalizes camelCase to kebab\n// before parsing) and are camelCase where read - <slot.header-bar> and\n// <slot.headerBar> are :slot.header-bar is $slots.headerBar\nconst isSlotTag = (tag: string): boolean => tag === \"slot\" || tag.startsWith(\"slot.\")\n\nconst slotName = (suffix: string): string => (suffix ? kebabToCamel(suffix) : \"default\")\n\n// the content of one slot, as written at the usage site\ntype SlotContent = { nodes: (TemplateNode | string)[]; binder?: string }\n\n// the :slot attribute of a <template>, if it carries one\nconst slotAttrOf = (node: TemplateNode): string | undefined =>\n Object.keys(node.attrs).find(attr => attr === \":slot\" || attr.startsWith(\":slot.\"))\n\nconst slotAttrName = (name: string) => (name === \"default\" ? \":slot\" : `:slot.${name}`)\n\n// whitespace-only text between two <template :slot> blocks is the indentation\n// between them and nothing else - the same call renderNodes makes between the\n// branches of an :if chain. It is what decides whether a tag has default\n// content at all, which is what $slots.default answers\nconst isMeaningful = (node: TemplateNode | string): boolean => typeof node !== \"string\" || node.trim() !== \"\"\n\n// a component tag's children, partitioned by slot name: a direct\n// <template :slot.<name>> child fills that name, everything else is the\n// default slot's content. The attribute's value is the pattern the content\n// binds the slot's props to - on the tag itself for the default, since the\n// default content has no <template> of its own to carry it\nconst partitionSlots = (node: TemplateNode): Record<string, SlotContent> => {\n const contents: Record<string, SlotContent> = {}\n const loose: (TemplateNode | string)[] = []\n\n node.children.forEach(child => {\n const attr = typeof child === \"object\" && child.tag === \"template\" ? slotAttrOf(child) : undefined\n if (typeof child === \"string\" || attr === undefined) {\n loose.push(child)\n return\n }\n const name = slotName(attr.slice(\":slot.\".length))\n // first wins, like two <template name=\"X\"> in one file: a duplicate is a\n // typo, and the fix is to delete one - not to guess which\n if (name in contents) {\n console.warn(`jq79: two <template ${slotAttrName(name)}> in <${node.tag}>; the second was ignored`)\n return\n }\n contents[name] = { nodes: child.children, binder: child.attrs[attr] || undefined }\n })\n\n const hasLoose = loose.some(isMeaningful)\n if (hasLoose && \"default\" in contents) {\n console.warn(\n `jq79: <${node.tag}> has both a <template :slot> and content outside it - ` +\n \"the <template> is the default slot's content, and the rest was ignored\"\n )\n } else if (hasLoose) {\n contents.default = { nodes: loose, binder: node.attrs[\":slot\"] || undefined }\n }\n return contents\n}\n\n// `:slot=\"{ item, index: i, total = 0 }\"` - the names the content binds the\n// slot's props to. The bindings are accessors, not values: each read\n// re-evaluates the child's expression, so an effect that reads `item` tracks\n// exactly what that expression touches, on every run (createWithScope's design)\nconst bindSlotProps = (scope: Record<string, any>, binder: string | undefined, props: Record<string, () => any>) => {\n parsePropsPattern(binder)?.forEach(({ name, as, default: fallback }) => {\n const local = as ?? name\n Object.defineProperty(scope, local, {\n enumerable: true,\n configurable: true,\n get: () => {\n const value = props[name]?.()\n return value === undefined && fallback !== undefined ? evalExpr(fallback, scope) : value\n },\n // a slot prop is the child's value: it arrives on every read and there\n // is nowhere for a write to go. Silence would be worse - `with` swallows\n // an assignment to a getter without a word\n set: () => console.warn(`jq79: \"${local}\" is a slot prop - it comes from the component, so assigning to it does nothing`),\n })\n })\n}\n\n// a <template :slot> only fills a slot as a direct child of a component tag,\n// where the usage site takes it out of the children before they are ever\n// rendered (see partitionSlots). Anywhere else the position is a mistake, and\n// rendering the content in place - in the wrong scope, into a <template>\n// nobody clones - would be a strange way to say so. A comment rather than\n// nothing: an :if branch needs a node to hold on to (see boundsOf)\nconst misplacedSlotContent = (node: TemplateNode): Node => {\n const attr = slotAttrOf(node)\n console.warn(`jq79: <template ${attr}> fills a slot only as a direct child of a component tag; here it rendered nothing`)\n return document.createComment(`misplaced ${attr}`)\n}\n\n// what a usage site hands its instance: every slot it filled, as the thunk\n// that renders it. Built once per site, and in one call - a component tag is\n// on the stack while its whole subtree renders below it (a component that\n// renders itself does this 200 deep), so the intermediates stay in here rather\n// than in the frame that waits\nconst buildSlots = (node: TemplateNode, scope: Record<string, any>): SlotMap | null => {\n const contents = Object.entries(partitionSlots(node))\n if (!contents.length) return null\n const slots: SlotMap = {}\n contents.forEach(([name, content]) => { slots[name] = makeSlotRenderer(content, scope) })\n return slots\n}\n\n// the thunk one slot's content becomes: the usage site closes over its AST and\n// its scope, the child calls it wherever (and however many times) it renders\n// the matching <slot>\nconst makeSlotRenderer = (content: SlotContent, parentScope: Record<string, any>): SlotRenderer =>\n (props, slotScope, fx, shadow) => {\n // the parent's scope, plus the names the content declared for the slot's\n // props (rule 1: what the content says is decided where it was written)\n const scope: Record<string, any> = Object.create(parentScope)\n bindSlotProps(scope, content.binder, props)\n // this content reads the parent's store (its own names) and the child's\n // (through the slot props), so every effect created anywhere inside it is\n // registered with both - see ALSO_WAKEN_BY. Appended rather than assigned:\n // content forwarded through a <slot> inside slot content is still woken by\n // the store it came from\n const inherited: Record<string, any>[] = (scope as any)[ALSO_WAKEN_BY] ?? []\n Object.defineProperty(scope, ALSO_WAKEN_BY, { value: [...inherited, slotScope] })\n\n const contentFx = createEffectScope(scope)\n // rule 3: the <slot> is the content's lifetime. When the child's subtree at\n // this position goes - an :if turning false, the instance being replaced,\n // the whole child being destroyed - the content's effects go with it\n fx.onDispose(() => contentFx.dispose())\n return renderNodes(content.nodes, scope, contentFx, shadow)\n }\n\n// <slot />, <slot.name>fallback</slot.name>: where the parent's content goes.\n// Unfilled, the slot renders its own children instead - in this component's\n// scope, since that content is this component's. Every attribute that isn't a\n// directive is a slot prop: `:item=\"item\"` evaluates here and reaches the\n// content under the name it declared, a plain attribute passes a literal\n// string, and there are no reserved names (the slot's own name is in the tag).\n// Bracketed by anchors like a nested component, so the chunk has stable bounds\n// even when it renders nothing (see boundsOf)\nconst renderSlot = (node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const name = slotName(node.tag.slice(\"slot.\".length))\n const wrapper = document.createDocumentFragment()\n const anchor = document.createComment(node.tag)\n const endAnchor = document.createComment(`/${node.tag}`)\n wrapper.append(anchor, endAnchor)\n\n const render = (scope as any)[SLOTS]?.[name] as SlotRenderer | undefined\n if (!render) {\n wrapper.insertBefore(renderNodes(node.children, scope, fx, shadow), endAnchor)\n return wrapper\n }\n\n const props: Record<string, () => any> = {}\n Object.entries(node.attrs).forEach(([attr, value]) => {\n // the scope stamp is the component's, not a prop; @events have no element\n // to bind here; and a directive means what it means everywhere else -\n // :if/:each/:with decide whether and how often this slot renders, so they\n // are the renderer's, not the content's\n if (attr === SCOPE_ATTR || isControlAttr(attr) || attr.startsWith(\"@\")) return\n if (attr.startsWith(\":\")) {\n const expr = value || attr.slice(1)\n props[kebabToCamel(attr.slice(1))] = () => evalExpr(expr, scope)\n } else {\n props[kebabToCamel(attr)] = () => value\n }\n })\n\n wrapper.insertBefore(render(props, scope, fx, shadow), endAnchor)\n return wrapper\n}\n\n// <MyComponent :user :title=\"'str'\"></MyComponent> - renders a child\n// component instance at this position. Props: `:name=\"expr\"` evaluates expr\n// in the parent scope (`:name` alone is shorthand for `:name=\"name\"`), plain\n// attributes pass through as literal strings, and kebab-case prop names\n// become camelCase. Props stay live: a parent effect re-evaluates each\n// expression and writes it into the child's store. The component variable is\n// reactive too - while it's undefined (e.g. an `await import(...)` still in\n// flight) nothing renders, and the child appears when it resolves.\n// `shadow` is the parent's style mode, carried down the whole render: a child\n// of a shadow-rendered component renders inside that shadow root, so its\n// <style> has to go in there with it - document.head can't reach into a shadow\n// tree, and a style that never applies to its own component would still be\n// restyling the page around it\nconst renderNestedComponent = (key: string, node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n // two anchors bracketing everything this usage site ever renders: the\n // instance's DOM is dynamic (the definition can resolve late or be swapped),\n // so a caller that needs to move or remove this chunk later can't hold any\n // of it - it holds the anchors, which never move on their own (see boundsOf)\n const anchor = document.createComment(key)\n const endAnchor = document.createComment(`/${key}`)\n const wrapper = document.createDocumentFragment()\n wrapper.append(anchor, endAnchor)\n\n // the tag's children, as content for the child's <slot>s. Built once per\n // usage site (the AST doesn't change) and closed over the parent's scope\n // here, so every instance this site ever renders is handed the same thunks\n const slots = buildSlots(node, scope)\n\n const props: Record<string, string> = {} // prop name -> expression in parent scope\n const models: Record<string, string> = {} // model name -> assignable expression in parent scope\n const events: Array<[string, string]> = [] // @attr (modifiers included) -> handler expression\n // named props AND spreads in source order - what a :props merge folds over so\n // precedence follows the JS object-spread rule (later wins). `name` absent\n // marks a spread: the whole object's properties, not one binding\n const sources: Array<{ name?: string; expr: string }> = []\n let hasSpread = false\n Object.entries(node.attrs).forEach(([attr, value]) => {\n // the parent's scope stamp is stamped on every template element, this tag\n // included - it's not a prop, and the child renders under its own scope\n if (attr === SCOPE_ATTR) return\n if (attr === \":props\" || attr.startsWith(\":props.\")) {\n // :props=\"obj\" spreads obj's own properties as props; :props.<n> is one\n // spread among several (the `...obj` sugar rewrites to it - see\n // expandPropsSpread), the suffix only keeping the attribute names distinct\n hasSpread = true\n sources.push({ expr: value })\n return\n }\n if (isControlAttr(attr)) return\n if (attr.startsWith(\"@\")) {\n events.push([attr, value])\n } else if (attr === \":model\" || attr.startsWith(\":model.\")) {\n // :model[.name]=\"expr\" - two-way: a prop down plus a writeback listener\n // (wired below, once the instance exists). The modifier arrives\n // kebab-case whichever way it was authored (expandNameCase rewrote any\n // camelCase before parsing); the bare :model binds the name \"default\"\n const name = attr === \":model\" ? \"default\" : kebabToCamel(attr.slice(\":model.\".length))\n models[name] = value || (attr === \":model\" ? \"model\" : name)\n } else if (attr.startsWith(\":\")) {\n const name = kebabToCamel(attr.slice(1))\n props[name] = value || name\n sources.push({ name, expr: value || name })\n } else {\n const name = kebabToCamel(attr)\n const expr = JSON.stringify(value)\n props[name] = expr\n sources.push({ name, expr })\n }\n })\n\n // each model is also a prop down: the child reads the value under the\n // model's name - `model` for the default, because a prop named `default`\n // could never be read from a child expression (reserved word). Without the\n // prop this isn't two-way, it's upward collection: a parent reset or an\n // initial value would never reach the child\n const modelAttr = (name: string) => (name === \"default\" ? \":model\" : `:model.${name}`)\n const modelProp = (name: string) => (name === \"default\" ? \"model\" : name)\n // the newline keeps `= $value` out of a trailing line comment in the\n // expression (:model=\"uname // the username\") - glued on the same line,\n // the assignment would vanish into the comment and compile as a bare read,\n // dropping every update without a word\n const assignment = (expr: string) => `${expr}\\n= $value`\n // the models whose expression will never take an update, decided here rather\n // than at update time: an assignment that landed and one that was dropped\n // both evaluate to the value assigned, so the result can't tell them apart -\n // which is what $updateModel's return has to report\n const unassignable = new Set<string>()\n Object.entries(models).forEach(([name, expr]) => {\n const prop = modelProp(name)\n if (props[prop] !== undefined) {\n console.warn(`jq79: <${node.tag}> binds prop \"${prop}\" through both :${prop} and ${modelAttr(name)} - ${modelAttr(name)} wins`)\n }\n props[prop] = expr\n // an expression that can't be an assignment target is a wiring mistake -\n // say so now, not on the first update that silently goes nowhere\n if (compileExpr(assignment(expr), [\"$value\"]) === null) {\n unassignable.add(name)\n console.warn(`jq79: ${modelAttr(name)}=\"${expr}\" is not assignable - updates from <${node.tag}> will be dropped`)\n }\n })\n\n // the full prop set the child gets, resolved in source order: each named prop\n // sets one key, each spread merges an object's own properties, later sources\n // overwriting earlier (the JS object-spread rule). :model bindings apply last,\n // so they win - the same precedence the collision warning above promises. A\n // spread expression that isn't an object contributes nothing (fail closed,\n // like :with), so an `await`-pending object spreads once it resolves\n const resolveProps = (): Record<string, any> => {\n const out: Record<string, any> = {}\n sources.forEach(({ name, expr }) => {\n if (name !== undefined) out[name] = evalExpr(expr, scope)\n else {\n const obj = evalExpr(expr, scope)\n if (obj !== null && typeof obj === \"object\") Object.assign(out, obj)\n }\n })\n Object.entries(models).forEach(([name, expr]) => { out[modelProp(name)] = evalExpr(expr, scope) })\n return out\n }\n\n let current: Component79 | null = null\n let currentDef: Component79 | null = null\n let childFx: EffectScope | null = null\n\n // a usage site that resolves to no component renders nothing, which is\n // deliberate - `undefined` while an `await import(...)` is in flight has to\n // wait quietly, and the child appears when it lands. Two cases can never\n // resolve, though, and both are wiring mistakes worth naming: a value that\n // isn't a component (and so will never become one by waiting), and a name\n // the component declared as a prop that the parent passed nothing for. Once\n // each, per usage site: an effect re-runs\n const reported = new Set<string>()\n const reportUnresolved = (value: any) => {\n if (value === undefined || value === null) {\n const unfilled: Set<string> | undefined = (scope as any)[UNFILLED_PROPS]\n if (!unfilled?.has(key) || reported.has(\"unfilled\")) return\n reported.add(\"unfilled\")\n console.error(\n `jq79: <${node.tag}> is declared as a prop and the parent passed nothing - nothing renders here. ` +\n `Pass it (:${key}=\"…\"), or drop it from the signature to use the one declared in this file.`\n )\n return\n }\n if (reported.has(\"type\")) return\n reported.add(\"type\")\n console.error(`jq79: <${node.tag}> is ${typeof value}, not a component - nothing renders here`)\n }\n\n fx.effect(() => {\n const value = evalExpr(key, scope)\n const nextDef = value instanceof Component79 ? value : null\n if (!nextDef) reportUnresolved(value)\n if (nextDef === currentDef) return\n\n childFx?.dispose()\n childFx = null\n current?.destroy() // detaches its marker range, removing the child's DOM\n current = null\n currentDef = nextDef\n if (!nextDef) return\n\n // a fresh instance per usage site: the definition's parsed parts (and\n // pre-resolved modules) are shared, but store/effects/DOM are per instance\n const instance = new Component79({\n template: nextDef.template,\n scripts: nextDef.scripts,\n styles: nextDef.styles,\n modules: nextDef.modules,\n filename: nextDef.filename,\n // its file's other components, and which of them it is: without the\n // first a child rendered here loses the siblings its definition could\n // see, and without the second hot reload can't tell it what it is\n siblings: nextDef.siblings,\n name: nextDef.name,\n })\n // the content this site wrote inside the tag, before the first render: a\n // <slot> is resolved while rendering, so the map has to be there by then\n if (slots) instance.slots = slots\n // the writeback half of :model - the function the child's $updateModel\n // calls, handed over before the first render. Not an event: nothing about\n // a parent-child assignment wants a CustomEvent bubbling through the page\n // on every keystroke, and a direct call has no payload shape to get wrong.\n // The name is normalized like the attribute was (kebab->camel; absent\n // means the default model), and a name nothing binds warns: a typo must\n // not be an input that types into the void\n if (Object.keys(models).length) {\n // each mistake is warned once per instance, not once per keystroke: an\n // input updating a typo'd name would otherwise flood the console on\n // every character typed into it\n const warned = new Set<string>()\n instance.modelWriteback = (rawName, value) => {\n const name = rawName == null ? \"default\" : kebabToCamel(String(rawName))\n const expr = models[name]\n if (expr === undefined) {\n if (!warned.has(name)) {\n warned.add(name)\n console.warn(`jq79: <${node.tag}> has no ${modelAttr(name)} - bound: ${Object.keys(models).map(modelAttr).join(\", \")}`)\n }\n return false\n }\n if (unassignable.has(name)) return false // already warned, at wiring time\n // untracked, like the tag handlers: a child updating from its setup\n // script runs inside the parent's *creation* effect, and the reads a\n // path assignment makes (`user` in `user.name = $value`) would land\n // in its deps - donating that effect one wasted (guard-stopped) wake\n // per later write. An imperative writeback is nobody's dependency\n untracked(() => evalExpr(assignment(expr), scope, { $value: value }))\n return true\n }\n }\n\n // @event on the tag listens to this instance's $emit channel (and only\n // this instance's - a grandchild's emit arrives here solely as an\n // explicit re-emit)\n events.forEach(([attr, expr]) => wireTagEvent(instance, attr, expr, scope))\n\n // what this component actually takes, decided by its signature. Applied to\n // every path that writes a prop - the seed here and both sync paths below -\n // or an undeclared name would be filtered on the first render and reappear\n // on the next update\n const declared = declaredPropSet(instance.scripts)\n warnUndeclared(node, key, Object.keys(props), declared)\n const seed = pickDeclared(untracked(resolveProps), declared)\n // mounting into a fragment attaches no shadow root of its own: a\n // shadow-rendered child keeps its <style> elements inline, next to the DOM\n // they style, and the parent's shadow root is what scopes both\n const holder = document.createDocumentFragment()\n // rendering a child happens on this same stack, so a component that\n // renders itself recurses as deep as its data does - and a cycle in that\n // data would recurse until the JS stack gave out, ~900 identical frames\n // naming nothing. Cut and named instead, exactly like the effect runner\n // cuts an effect that wakes itself\n if (nestingDepth >= MAX_NESTING_DEPTH) {\n console.error(\n `jq79: <${node.tag}> is ${MAX_NESTING_DEPTH} levels deep inside itself; giving up here. ` +\n \"A component that renders itself stops when its data stops - is there a cycle in it?\"\n )\n return\n }\n nestingDepth++\n try {\n ;(shadow ? instance.renderShadow(seed) : instance.render(seed)).mount(holder)\n } finally {\n nestingDepth--\n }\n endAnchor.parentNode!.insertBefore(holder, endAnchor)\n\n const syncFx = createEffectScope(scope)\n // without a spread the prop set is fixed and known: one effect per prop, so\n // a change to one prop re-syncs only that prop. A spread's key set is\n // dynamic and its precedence is positional, so it can't be resolved a key at\n // a time across independent effects (whichever re-ran last would win) - one\n // effect re-merges everything in order and writes the diff, clearing keys a\n // spread has dropped since last run. Named props are always in the merge, so\n // they're never cleared; the extra cost is confined to spread-using tags\n if (hasSpread) {\n let written: string[] = []\n syncFx.effect(() => {\n const next = pickDeclared(resolveProps(), declared)\n const nextKeys = Object.keys(next)\n written.forEach(key => { if (!(key in next)) (instance.data as Record<string, any>)[key] = undefined })\n nextKeys.forEach(key => { (instance.data as Record<string, any>)[key] = next[key] })\n written = nextKeys\n })\n } else {\n Object.entries(props).forEach(([name, expr]) => {\n if (declared !== null && !declared.has(name)) return\n syncFx.effect(() => { (instance.data as Record<string, any>)[name] = evalExpr(expr, scope) })\n })\n }\n\n childFx = syncFx\n current = instance\n })\n\n fx.onDispose(() => {\n childFx?.dispose()\n current?.destroy()\n })\n\n return wrapper\n}\n\n// :with=\"expr\" narrows the scope for an element and its subtree: names\n// resolve against the expression's value first, then fall back to the outer\n// scope. The value is re-evaluated lazily on every name lookup (never\n// snapshotted), so an effect reading through this proxy tracks both the\n// expression's own dependencies and the property it reads - replacing the\n// object or mutating one of its properties re-renders exactly the dependents,\n// without rebuilding the subtree. Assignments to names the object owns write\n// through to it (reactively, if it came from a store); everything else\n// behaves as if the :with weren't there\nconst createWithScope = (expr: string, scope: Record<string, any>): Record<string, any> => {\n const source = (): Record<string, any> | null => {\n const value = evalExpr(expr, scope)\n return value !== null && typeof value === \"object\" ? value : null\n }\n return new Proxy(scope, {\n has(target, key) {\n const obj = source()\n return (obj !== null && Reflect.has(obj, key)) || Reflect.has(target, key)\n },\n get(target, key) {\n const obj = source()\n if (obj !== null && Reflect.has(obj, key)) return obj[key as string]\n return Reflect.get(target, key)\n },\n set(target, key, value) {\n const obj = source()\n if (obj !== null && Reflect.has(obj, key)) {\n obj[key as string] = value\n return true\n }\n return Reflect.set(target, key, value)\n },\n })\n}\n\n// what :class accepts, flattened to single class tokens: a string of\n// space-separated names, an array (entries normalized recursively), or an\n// object whose truthy-valued keys are the names (a key may itself hold\n// several). Everything else - null, false, numbers - contributes nothing, so\n// `cond && 'active'` reads naturally. The object form reads each value, so a\n// store-backed flag is tracked per key\nconst classNames = (value: any): string[] => {\n if (typeof value === \"string\") return value.split(/\\s+/).filter(Boolean)\n if (Array.isArray(value)) return value.flatMap(classNames)\n if (value !== null && typeof value === \"object\")\n return Object.entries(value).flatMap(([name, on]) => (on ? classNames(name) : []))\n return []\n}\n\n// what :html.allowed accepts, normalized to an AllowUrl predicate: host\n// patterns (a comma-separated string or an array - see allowedHosts in\n// ./dom) or a function (url: URL, tag, attr) => boolean. Anything else -\n// including a policy expression that evaluates to undefined - denies every\n// destination: the attribute declares the intent to restrict, so a broken\n// policy fails closed, and so does a predicate that throws\nconst normalizeAllowUrl = (policy: any): AllowUrl => {\n if (typeof policy === \"function\") {\n return (url, tag, attr) => {\n try {\n return !!policy(url, tag, attr)\n } catch {\n return false\n }\n }\n }\n if (typeof policy === \"string\" || Array.isArray(policy)) return allowedHosts(policy)\n return () => false\n}\n\n// HTML's boolean attributes, verbatim from the spec's list. Presence is the\n// whole message for these: `disabled=\"false\"` and `disabled=\"0\"` both disable,\n// so the value they carry is noise. This is a table of a fact, not of a jq79\n// convention - nobody in this repo decides what belongs in it, which is what\n// earns it a place in a codebase that otherwise has no name tables\nconst BOOLEAN_ATTRS = new Set([\n \"allowfullscreen\", \"async\", \"autofocus\", \"autoplay\", \"checked\", \"controls\",\n \"default\", \"defer\", \"disabled\", \"formnovalidate\", \"inert\", \"ismap\",\n \"itemscope\", \"loop\", \"multiple\", \"muted\", \"nomodule\", \"novalidate\", \"open\",\n \"playsinline\", \"readonly\", \"required\", \"reversed\", \"selected\",\n])\n\n// the one value rule, shared by `:attr=\"expr\"` and `:attrs` so the two forms\n// can never disagree:\n//\n// - a boolean attribute is removed by ANY falsy value and set to \"\" when\n// truthy, so `:disabled=\"items.length\"` enables the button on an empty list\n// (with `value !== false` as the only test, 0 set the attribute and disabled\n// it - the trap renderComponent.test.ts used to pin);\n// - every other attribute is removed only by null/undefined, so `false`, `0`\n// and `\"\"` are written. `aria-expanded=\"false\"` and a `data-` flag mean\n// something that absent cannot say.\n//\n// Asking the DOM which family a name belongs to (`typeof el[name] ===\n// \"boolean\"`) is deliberately not what this does: jsdom and Chrome disagree on\n// `autofocus` and every `aria-*`, so the tests would pin a semantics the\n// browser doesn't have - and `readonly`/`novalidate`/`ismap` reflect under\n// camelCase property names no kebab->camel pass can produce, failing toward\n// `readonly=\"false\"`, which is read-only\nconst applyAttr = (el: Element, name: string, value: any) => {\n const boolean = BOOLEAN_ATTRS.has(name)\n if (boolean ? !value : value == null) el.removeAttribute(name)\n else el.setAttribute(name, boolean ? \"\" : String(value))\n}\n\n// renders a single element node: static attrs, @event listeners, a reactive\n// :attrs object, and its content - :text/:html override the element's own\n// children with a reactive textContent/innerHTML, otherwise children render\n// normally. :if/:elseif/:else/:each are handled by renderNodes, which decides\n// *whether*/*how many times* a node is rendered before calling this. Tags\n// matching a PascalCase scope variable render as nested components instead\nconst renderNode = (node: TemplateNode, outerScope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n // :with applies to the element's own bindings (@events, :attrs) and its\n // whole subtree. On a :each element the item scope is already in place, so\n // :with=\"item\" works\n const withExpr = node.attrs[\":with\"]\n const scope = withExpr !== undefined ? createWithScope(withExpr, outerScope) : outerScope\n\n // before the component-key scan, so <slot> is <slot> even in a file that\n // happens to have a component named Slot in scope: the tag is the library's\n // now, and a name that resolved it away would be a very quiet surprise\n if (isSlotTag(node.tag)) return renderSlot(node, scope, fx, shadow)\n if (node.tag === \"template\" && slotAttrOf(node) !== undefined) return misplacedSlotContent(node)\n\n const componentKey = findComponentKey(scope, node.tag)\n if (componentKey) return renderNestedComponent(componentKey, node, scope, fx, shadow)\n\n const el = document.createElement(node.tag)\n\n // <UserCrad /> - written as a component (node.component), resolving to no\n // component, and not an element either. Nothing else on the page can supply\n // the name once every script has settled, so this renders no markup, no\n // styles, no children and no script, forever, and says so by throwing rather\n // than leaving a hole where a region of the page was meant to be.\n //\n // All three conditions carry weight. Without the capitalization <lable> and\n // <svg> would be fatal (createElement builds SVG names in the HTML namespace,\n // so an <svg> is an HTMLUnknownElement too); without the element check <DIV>\n // would be, though it renders a perfectly good div; and without the pending\n // count a factory that awaits $mounted() before returning its components\n // could never render one, which is exactly what the watcher below is for.\n //\n // An *absent* count is a fourth case, and it is not zero: renderComponent()\n // renders a template against a store somebody else owns and assembles, so\n // nothing there has finished and nothing says a key can't still be written\n // in. The claim being tested is a component's claim about its own scripts,\n // and where none was made the tag waits for the upgrade, as it always has.\n //\n // Written without a local for the count because renderNode is on the stack\n // for the whole of the subtree below it, so a slot here is a slot per level\n // of a component nested inside itself - see renderWith\n if (node.component && el instanceof HTMLUnknownElement && ((scope as any)[PENDING_SCRIPTS] as PendingScripts | undefined)?.count === 0) {\n throw unresolvedComponent(node.component, scope)\n }\n\n // a tag that isn't standard HTML but has no matching scope key *yet* may be\n // a component that arrives later (e.g. an async factory script exposing an\n // imported component after `await`). Watch for the key: the effect tracks\n // no deps, so it only re-runs on the store's new-key sweep, and swaps the\n // placeholder element for the component exactly once\n // dashes included, because findComponentKey matches them case-insensitively\n // with dashes stripped: <drop-area> resolves DropArea, so a dashed tag is a\n // possible component too, not only a custom element\n const mayUpgrade = el instanceof HTMLUnknownElement || node.tag.includes(\"-\")\n if (mayUpgrade) {\n let upgraded = false\n fx.effect(() => {\n if (upgraded) return\n const key = findComponentKey(scope, node.tag)\n if (!key) return\n upgraded = true\n const replacement = renderNestedComponent(key, node, scope, fx, shadow)\n // whoever tears this subtree down holds `el`, which the swap detaches -\n // so the component's anchors must remove themselves when the scope goes\n const range = boundsOf(replacement)\n fx.onDispose(() => removeRange(range))\n el.replaceWith(replacement)\n })\n }\n\n Object.entries(node.attrs).forEach(([key, value]) => {\n if (key.startsWith(\"@\")) bindEvent(el, key, value, scope)\n else if (key === \":model\" || key.startsWith(\":model.\")) {\n // :model binds component tags only (see TODOS/2026-07-15.model-directive.md;\n // the native-element form is parked there). Warn on a real element, but\n // not on a tag that may still upgrade into a component - the upgrade\n // re-renders through renderNestedComponent, models and all\n if (!mayUpgrade) {\n console.warn(`jq79: ${key} on <${node.tag}> does nothing - :model binds component tags only (for now)`)\n }\n } else if (isControlAttr(key)) {\n // a directive of its own, bound further down (or by renderNodes)\n } else if (key.startsWith(\":\")) {\n // :name=\"expr\" binds that one attribute, reactively - the single-key\n // case :attrs=\"{ name: expr }\" was carrying. `:name` alone is shorthand\n // for `:name=\"name\"`, like props and :model.<name>, and the shorthand\n // reads the camelCase variable while the attribute keeps its written\n // (kebab) name: `:aria-expanded` binds `ariaExpanded`, because\n // `aria-expanded` as an expression is a subtraction.\n //\n // On a tag that may still upgrade this is a *parameter*, not an\n // attribute: leave it written verbatim, as before, so the upgrade's\n // renderNestedComponent still finds it. A component tag has no single\n // root for an attribute to land on anyway (TODOS/2026-07-15.class-directive.md)\n if (mayUpgrade) el.setAttribute(key, value)\n else {\n const name = key.slice(1)\n const expr = value || kebabToCamel(name)\n fx.effect(() => applyAttr(el, name, evalExpr(expr, scope)))\n }\n } else el.setAttribute(key, value)\n })\n\n const bindExpr = node.attrs[\":attrs\"]\n if (bindExpr !== undefined) {\n let boundKeys: string[] = []\n\n fx.effect(() => {\n boundKeys.forEach(key => el.removeAttribute(key))\n const bound = evalExpr(bindExpr, scope)\n boundKeys = bound && typeof bound === \"object\" ? Object.keys(bound) : []\n boundKeys.forEach(key => applyAttr(el, key, bound[key]))\n })\n }\n\n // :class=\"expr\" adds classes on top of the static `class` attribute, and\n // :class.<name>=\"expr\" is the single-flag shorthand for `{ <name>: expr }`\n // (the name routed through classNames, so an empty `:class.` can't reach\n // classList.add, which throws on \"\"). Both feed one effect and one set of\n // added classes: only classes this binding added are ever removed, so the\n // static list survives every re-run, even when the expression names one of\n // its classes and then drops it (class=\"btn\" :class=\"{ btn: cond }\" keeps\n // btn on false)\n const classExpr = node.attrs[\":class\"]\n const classToggles = Object.entries(node.attrs)\n .filter(([key]) => key.startsWith(\":class.\"))\n .map(([key, expr]): [string, string] => [key.slice(\":class.\".length), expr])\n if (classExpr !== undefined || classToggles.length) {\n const staticClasses = new Set(classNames(node.attrs.class ?? \"\"))\n let bound: string[] = []\n\n fx.effect(() => {\n const next = classExpr !== undefined ? classNames(evalExpr(classExpr, scope)) : []\n classToggles.forEach(([name, expr]) => {\n if (evalExpr(expr, scope)) next.push(...classNames(name))\n })\n bound.forEach(name => {\n if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)\n })\n el.classList.add(...next)\n bound = next\n })\n }\n\n // :text=\"expr\" sets textContent reactively, replacing any children.\n // :html=\"expr\" sets innerHTML reactively, sanitizing the value first so\n // untrusted content can't inject scripts/attributes (see sanitizeHTML in\n // ./dom). Both skip rendering the element's own children/interpolation.\n // :html.allowed=\"expr\" adds a destination policy for the content's\n // href/src URLs - evaluated in the same effect, so a policy held in the\n // store is as reactive as the content itself\n const textExpr = node.attrs[\":text\"]\n const htmlExpr = node.attrs[\":html\"]\n const allowedExpr = node.attrs[\":html.allowed\"]\n if (allowedExpr !== undefined && htmlExpr === undefined) {\n console.warn(\"jq79: :html.allowed without :html on the same element does nothing\")\n }\n if (textExpr !== undefined) {\n fx.effect(() => { el.textContent = String(evalExpr(textExpr, scope) ?? \"\") })\n } else if (htmlExpr !== undefined) {\n fx.effect(() => {\n const options = allowedExpr !== undefined ? { allowUrl: normalizeAllowUrl(evalExpr(allowedExpr, scope)) } : undefined\n el.innerHTML = sanitizeHTML(String(evalExpr(htmlExpr, scope) ?? \"\"), options)\n })\n } else if (el instanceof HTMLTemplateElement) {\n // a plain nested <template> stays what HTML says it is: an inert element\n // whose children live in .content, which is where whoever clones it looks\n // for them. They render (bindings and all) and go there - appended as\n // childNodes they would be in the DOM but in no document fragment, seen by\n // nothing and rendered by nobody\n el.content.appendChild(renderNodes(node.children, scope, fx, shadow))\n } else {\n el.appendChild(renderNodes(node.children, scope, fx, shadow))\n }\n\n // :value / :checked / :selected write the DOM *property*, not the\n // attribute - the attribute is only a form control's default, and detaches\n // the moment the user interacts (which is why :attrs=\"{ value }\" stops\n // driving a typed-in input). One-way, store -> DOM: the way back stays an\n // explicit @input/@change. :value skips the write when the property\n // already holds the string, so an unrelated re-run can't move the caret of\n // the input the user is typing into. Registered after the children render:\n // :value on a <select> can only pick an <option> that already exists\n const valueExpr = node.attrs[\":value\"]\n if (valueExpr !== undefined) {\n fx.effect(() => {\n const value = String(evalExpr(valueExpr, scope) ?? \"\")\n if ((el as HTMLInputElement).value !== value) (el as HTMLInputElement).value = value\n })\n }\n ;([\":checked\", \":selected\"] as const).forEach(attr => {\n const expr = node.attrs[attr]\n if (expr === undefined) return\n const prop = attr.slice(1) as \"checked\" | \"selected\"\n fx.effect(() => { (el as any)[prop] = !!evalExpr(expr, scope) })\n })\n\n return el\n}\n\n// a :if/:elseif*/:else? chain sharing one anchor comment so the active branch\n// can be swapped in place without disturbing sibling positions. Only depends\n// on whatever the branch expressions read (e.g. \"score\"), and skips\n// rebuilding entirely when the active branch hasn't actually changed\nconst renderConditional = (branches: ConditionalBranch[], scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const anchor = document.createComment(\"if\")\n const wrapper = document.createDocumentFragment()\n wrapper.appendChild(anchor)\n\n let current: NodeRange | null = null\n let activeBranch: ConditionalBranch | null = null\n let branchFx: EffectScope | null = null\n\n fx.effect(() => {\n const next = branches.find(branch => branch.expr === undefined || evalExpr(branch.expr, scope)) ?? null\n if (next === activeBranch) return\n\n branchFx?.dispose()\n if (current) removeRange(current)\n current = null\n activeBranch = next\n if (!next) return\n\n branchFx = createEffectScope(scope)\n // bounds captured before inserting: a component branch is a fragment, and\n // inserting it is what empties it (see boundsOf)\n const rendered = renderNode(next.node, scope, branchFx, shadow)\n current = boundsOf(rendered)\n anchor.parentNode!.insertBefore(rendered, anchor.nextSibling)\n })\n\n return wrapper\n}\n\n// defines a loop-local binding directly as `scope`'s own property. Plain\n// assignment (scope[key] = value) would only do this if the key isn't\n// already own on `scope` *or anywhere up its prototype chain* - if it isn't,\n// JS delegates the [[Set]] to whatever's up there, which for us is another\n// reactive proxy's `set` trap: it would wrap `value` as if it were a genuine\n// store mutation and fire a bogus notify() under a name (e.g. \"item\") shared\n// by every unrelated item in every :each on the page. defineProperty always\n// writes to `scope` itself, never delegating, so this can't happen\nconst defineScopeVar = (scope: Record<string, any>, key: string, value: any) => {\n Object.defineProperty(scope, key, { value, writable: true, enumerable: true, configurable: true })\n}\n\ntype EachEntry = { key: any; item: any; scope: Record<string, any>; range: NodeRange; fx: EffectScope }\n\n// what :each iterates besides arrays: dictionaries, as their entries. Class\n// instances, Maps and the rest stay out - the store doesn't wrap them\n// (isPlainData), so their contents wouldn't be tracked and the list would go\n// silently stale\nconst isPlainObject = (value: any): value is Record<string, any> => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n// :each=\"item in items\" (or \"item, i in items\" / \"(value, key) in props\"),\n// optionally keyed with :key=\"expr\". Only depends on what the list expression\n// reads, and on each run diffs by key: unchanged items (same key, same item\n// reference) keep their DOM/effects, changed/added ones are (re)rendered,\n// removed ones are disposed. Without :key, an array uses position - fine for\n// append-only lists, wasteful for reordering - and an object uses the\n// property key, which is already the stable identity. Each item gets its own\n// scope via Object.create(scope), so the bindings and `$index` shadow\n// same-named outer names without copying the parent scope's keys\nconst renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const match = node.attrs[\":each\"].match(EACH_PATTERN)\n if (!match) return document.createComment(`invalid :each expression \"${node.attrs[\":each\"]}\"`)\n\n const [, itemName, atName, listExpr] = match\n const keyExpr = node.attrs[\":key\"]\n const { [\":each\"]: _each, [\":key\"]: _key, ...itemAttrs } = node.attrs\n const itemNode: TemplateNode = { ...node, attrs: itemAttrs }\n\n const anchor = document.createComment(\"each\")\n const wrapper = document.createDocumentFragment()\n wrapper.appendChild(anchor)\n\n // :if on the same element is not per-item filtering, and rendering\n // everything in silence reads like a broken filter - say it out loud\n if (\":if\" in node.attrs || \":elseif\" in node.attrs || \":else\" in node.attrs) {\n console.warn(\"jq79: :if/:elseif/:else on a :each element is ignored; filter the list expression instead\")\n }\n\n let entries: EachEntry[] = []\n let warnedDuplicates = false\n\n fx.effect(() => {\n const list = evalExpr(listExpr, scope)\n // both sources normalize to [at, item] pairs: the index for an array, the\n // property key for a plain object (insertion order). Object entries are\n // read off the store proxy, so each value is tracked under its own key -\n // adds, deletes and changes all wake this effect\n const pairs: [any, any][] = Array.isArray(list)\n ? list.map((item, index): [any, any] => [index, item])\n : isPlainObject(list) ? Object.entries(list) : []\n // buckets rather than a key->entry map: duplicate keys (a user error, but\n // one that must degrade instead of corrupt) consume entries in order of\n // appearance, so no entry is ever matched twice - matching one twice is\n // how a reused row got disposed and a removed one resurrected\n const previous = new Map<any, EachEntry[]>()\n entries.forEach(entry => {\n const bucket = previous.get(entry.key)\n if (bucket) bucket.push(entry)\n else previous.set(entry.key, [entry])\n })\n\n const seen = new Set<any>()\n const moved: EachEntry[] = []\n const nextEntries = pairs.map(([at, item], index): EachEntry => {\n const itemScope = Object.create(scope)\n defineScopeVar(itemScope, itemName, item)\n if (atName) defineScopeVar(itemScope, atName, at)\n defineScopeVar(itemScope, \"$index\", index)\n const key = keyExpr !== undefined ? evalExpr(keyExpr, itemScope) : at\n if (seen.has(key) && !warnedDuplicates) {\n warnedDuplicates = true\n console.warn(`jq79: duplicate :key in :each \"${node.attrs[\":each\"]}\"; duplicates pair up by position`)\n }\n seen.add(key)\n const existing = previous.get(key)?.shift()\n\n if (existing && Object.is(existing.item, item)) {\n if (existing.scope.$index !== index) moved.push(existing)\n defineScopeVar(existing.scope, \"$index\", index)\n if (atName) defineScopeVar(existing.scope, atName, at)\n return existing\n }\n\n if (existing) {\n existing.fx.dispose()\n removeRange(existing.range)\n }\n\n const itemFx = createEffectScope(scope)\n // bounds captured before the positioning pass inserts the entry: a\n // component entry is a fragment, which empties on insertion (see boundsOf)\n const range = boundsOf(renderNode(itemNode, itemScope, itemFx, shadow))\n return { key, item, scope: itemScope, fx: itemFx, range }\n })\n\n // whatever no new item consumed is gone\n previous.forEach(bucket => bucket.forEach(entry => {\n entry.fx.dispose()\n removeRange(entry.range)\n }))\n\n let prevNode: Node = anchor\n nextEntries.forEach(entry => {\n if (prevNode.nextSibling !== entry.range.first) moveRangeAfter(entry.range, prevNode)\n prevNode = entry.range.last\n })\n\n // reused entries that changed position: their tracked bindings re-run off\n // the list notification anyway, but a binding that reads only `$index` or\n // the named key tracked nothing - refresh them so the move reaches those\n // too. Untracked, so these runs don't feed this list effect's own deps\n moved.forEach(entry => untracked(() => entry.fx.refresh()))\n\n entries = nextEntries\n })\n\n return wrapper\n}\n\n// renders a list of sibling template nodes (text + elements), grouping\n// consecutive :if/:elseif/:else nodes into a single conditional block\nconst renderNodes = (nodes: (TemplateNode | string)[], scope: Record<string, any>, fx: EffectScope, shadow = false): DocumentFragment => {\n const fragment = document.createDocumentFragment()\n let i = 0\n\n while (i < nodes.length) {\n const node = nodes[i]\n\n if (typeof node === \"string\") {\n const textNode = document.createTextNode(node)\n // static text is most of a template (all of its indentation, for a start):\n // only text with a {{ expression }} in it needs an effect to stay in sync\n if (node.includes(\"{{\")) fx.effect(() => { textNode.textContent = interpolate(node, scope) })\n fragment.appendChild(textNode)\n i++\n continue\n }\n\n if (\":each\" in node.attrs) {\n fragment.appendChild(renderEach(node, scope, fx, shadow))\n i++\n continue\n }\n\n if (\":if\" in node.attrs) {\n const branches: ConditionalBranch[] = [{ expr: node.attrs[\":if\"], node }]\n i++\n\n // the branches of a chain are siblings in the AST, but the template writes\n // them on their own lines - so the whitespace between them is indentation\n // and nothing else, and it's dropped rather than rendered: only one branch\n // is ever in the DOM, so there is nothing for it to be a space *between*\n const nextBranch = (attr: string): TemplateNode | undefined => {\n let next = i\n while (next < nodes.length && typeof nodes[next] === \"string\" && !(nodes[next] as string).trim()) next++\n const candidate = nodes[next]\n if (typeof candidate === \"object\" && attr in candidate.attrs) {\n i = next + 1\n return candidate\n }\n return undefined\n }\n\n for (let elseif = nextBranch(\":elseif\"); elseif; elseif = nextBranch(\":elseif\")) {\n branches.push({ expr: elseif.attrs[\":elseif\"], node: elseif })\n }\n const elseNode = nextBranch(\":else\")\n if (elseNode) branches.push({ node: elseNode })\n\n fragment.appendChild(renderConditional(branches, scope, fx, shadow))\n continue\n }\n\n fragment.appendChild(renderNode(node, scope, fx, shadow))\n i++\n }\n\n return fragment\n}\n\nexport const renderComponent = (component: Component79, data: ReactiveDeepData<Record<string, any>>, shadow = false): Node =>\n renderNodes(component.template, data, createEffectScope(data), shadow)\n\ntype ComponentParts = {\n template: TemplateNode[]\n scripts: TagBlock[]\n styles: TagBlock[]\n // pre-resolved modules for `import(...)` calls in setup scripts, keyed by\n // the literal specifier. Bundlers (the jq79/vite plugin) fill this so\n // imports resolve from the bundle instead of being fetched at runtime\n modules?: Record<string, any>\n // where this component came from (a URL for fetch(), a path for the vite\n // plugin). Names the setup scripts in devtools - see scriptSourceUrl\n filename?: string\n // the components the file's <template name=\"...\"> blocks declared, by name.\n // Every component parsed out of one file holds this same map - itself\n // included - which is what makes a sibling usable without an import, and\n // what lets a <template name=\"TreeNode\"> render a <TreeNode>\n siblings?: Record<string, Component79>\n // which of the file's components this is: a template's name, or undefined\n // for the file's own. The file is the hot-reload unit, so a reparse hands\n // each live instance the parts belonging to the component it is\n name?: string\n}\n\nconst VOID_ELEMENTS = new Set([\n \"area\", \"base\", \"br\", \"col\", \"embed\", \"hr\", \"img\", \"input\",\n \"link\", \"meta\", \"param\", \"source\", \"track\", \"wbr\",\n])\n\n// a self-closing tag with its attributes; quoted attribute values are matched\n// as whole chunks so a \"/>\" inside one doesn't end the tag early. The tag name\n// admits a dot for the named forms of a tag - <slot.header /> - which is a\n// legal HTML tag name (the tokenizer reads to the first space, \"/\" or \">\")\nconst SELF_CLOSING_RE = /<([A-Za-z][\\w.-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*?)\\/>/g\nconst RAW_BLOCK_RE = /(<script[\\s\\S]*?<\\/script\\s*>|<style[\\s\\S]*?<\\/style\\s*>)/gi\n\n// expands self-closing tags (<MyComponent />, <div />) into explicit\n// open+close pairs BEFORE DOM parsing. The HTML parser ignores the slash and\n// would treat them as unclosed, swallowing the following siblings. Void\n// elements keep their native behavior, and <script>/<style> contents are\n// passed through untouched so code inside them is never rewritten\nconst expandSelfClosingTags = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1 // odd chunks are the captured script/style blocks\n ? chunk\n : chunk.replace(SELF_CLOSING_RE, (match, tag: string, attrs: string) =>\n VOID_ELEMENTS.has(tag.toLowerCase()) ? match : `<${tag}${attrs}></${tag}>`\n )\n )\n .join(\"\")\n\n// a start tag with its attributes, quote-aware so a \">\" inside a value doesn't\n// end it early; and a single spread attribute in name position (preceded by\n// start-or-whitespace), its expression an identifier or member path\nconst OPEN_TAG_RE = /<([A-Za-z][\\w.-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>/g\nconst ATTR_SPREAD_RE = /\"[^\"]*\"|'[^']*'|(^|\\s)\\.\\.\\.([A-Za-z_$][\\w$.]*)/g\n\n// `...expr` as an attribute is sugar for :props=\"expr\" (spread an object's\n// properties as props - see renderNestedComponent). Rewritten BEFORE DOM\n// parsing, into a value-based :props.<n>, because the HTML parser lowercases\n// attribute *names*: with the expression in the name, `...userData` would arrive\n// as `...userdata` and resolve to nothing. Moving it into a value - which the\n// parser leaves untouched - keeps camelCase intact. Same pre-parse string move\n// as expandSelfClosingTags, with the same defenses against rewriting code that\n// only looks like a spread: <script>/<style> bodies are split out (a JS `...rest`\n// there is not an attribute), only a start tag's interior is scanned (text\n// between tags is safe), and quoted values are consumed whole so a genuine JS\n// spread in a value (@click=\"f(...args)\", :x=\"{ ...a }\") is skipped. The <n>\n// suffix (per tag) only keeps several spreads' attribute names distinct. A call\n// (`...getProps()`) stops at the paren and is left alone - use :props=\"expr()\"\nconst expandPropsSpread = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1\n ? chunk\n : chunk.replace(OPEN_TAG_RE, (_match, tag: string, attrs: string) => {\n let n = 0\n const rewritten = attrs.replace(ATTR_SPREAD_RE, (whole, space: string | undefined, expr: string | undefined) =>\n expr === undefined ? whole : `${space}:props.${n++}=\"${expr}\"`\n )\n return `<${tag}${rewritten}>`\n })\n )\n .join(\"\")\n\n// a `:`-prefixed attribute name in name position, and a </slot.name> closing\n// tag. Both quote-aware for the same reason ATTR_SPREAD_RE is: a colon inside\n// a value (@click=\"a ? b : c\", style=\"color: red\") is not an attribute name\nconst ATTR_NAME_RE = /\"[^\"]*\"|'[^']*'|(^|\\s)(:[\\w.$-]+)/g\nconst CLOSE_SLOT_RE = /<\\/slot\\.([\\w.$-]+)(\\s*)>/gi\nconst SLOT_TAG_RE = /^slot\\./i\n\n// camelCase -> kebab-case for every name the HTML parser would lowercase,\n// BEFORE it gets the chance: `:firstName` would arrive as `:firstname` and\n// kebabToCamel (which is what reads these names back out) would have nothing\n// to un-kebab, so the prop, model or slot would silently land under the wrong\n// key. Rewriting to `:first-name` here means both spellings converge on the\n// same camelCase name downstream - the author picks, the runtime doesn't care.\n//\n// Runs FIRST among the pre-parse passes, which is what keeps it simple: it\n// never sees the `:props.<n>` that expandPropsSpread generates, and a\n// <slot.firstName /> is still one occurrence rather than the open+close pair\n// expandSelfClosingTags turns it into. Same defenses as the passes after it -\n// <script>/<style> bodies split out, only start-tag interiors scanned, quoted\n// values consumed whole.\n//\n// Two name positions, not one: attribute names (`:model.firstName`) and the\n// dotted tag names (`<slot.firstName>`), whose closing halves are rewritten\n// too or the parser sees a mismatched pair. Component tags are deliberately\n// left alone - findComponentKey already matches them case-insensitively with\n// dashes stripped, so <UserCard> needs no help and rewriting it would only\n// obscure what the author wrote\nconst kebabTagName = (tag: string): string =>\n SLOT_TAG_RE.test(tag) ? `slot.${camelToKebab(tag.slice(\"slot.\".length))}` : tag\n\n// the same pass records what it declined to rewrite. An uppercase-initial tag\n// is a claim about a component: HTML's own elements are matched\n// case-insensitively but nobody writes <DIV> by accident, and a custom element\n// may not be spelled that way at all. So <UserCard> is a name the author\n// expected to resolve - which is what lets renderNode throw when it doesn't\n// (see unresolvedComponent).\n//\n// Carried in a *value* rather than left in the tag name, because the value is\n// the one place the HTML parser preserves case - the same move expandPropsSpread\n// makes for `...userData`, and for the same reason. elementToAST lifts it\n// straight off attrs into a field, so no attribute loop downstream ever sees\n// it - and since that lift is unconditional, the name has to be one no author\n// would write: a plain `:component` would eat the prop of that name off\n// <Card :component=\"Widget\" />\nconst COMPONENT_TAG_ATTR = \":jq79-component\"\nconst COMPONENT_TAG_RE = /^[A-Z]/\n\n// appends the stamp inside the tag, *before* a self-closing slash: this pass\n// runs first and expandSelfClosingTags still has to recognize the `/>` that\n// OPEN_TAG_RE swept into the attributes. A slash inside a quoted value can't be\n// mistaken for it - only a trailing one is matched\nconst TRAILING_SLASH_RE = /\\/\\s*$/\n\nconst stampComponentTag = (tag: string, attrs: string): string => {\n if (!COMPONENT_TAG_RE.test(tag)) return attrs\n const stamp = ` ${COMPONENT_TAG_ATTR}=\"${tag}\"`\n const slash = TRAILING_SLASH_RE.exec(attrs)\n return slash ? `${attrs.slice(0, slash.index)}${stamp}${slash[0]}` : `${attrs}${stamp}`\n}\n\nconst expandNameCase = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1\n ? chunk\n : chunk\n .replace(OPEN_TAG_RE, (_match, tag: string, attrs: string) => {\n const rewritten = attrs.replace(ATTR_NAME_RE, (whole, space: string | undefined, name: string | undefined) =>\n name === undefined ? whole : `${space}${camelToKebab(name)}`\n )\n return `<${kebabTagName(tag)}${stampComponentTag(tag, rewritten)}>`\n })\n .replace(CLOSE_SLOT_RE, (_match, suffix: string, space: string) => `</slot.${camelToKebab(suffix)}${space}>`)\n )\n .join(\"\")\n\n// <style scoped> support. Every element of the component's own template is\n// stamped with data-jq79=\"<hash>\" and the style's selectors are rewritten to\n// require that attribute, so its rules can't reach anything the component\n// didn't render. Purely a runtime transform (the browser parses the CSS), so\n// it works the same for a bundled component and one loaded with fetch()\nconst SCOPE_ATTR = \"data-jq79\"\n\n// FNV-1a over the source: stable per definition (not per instance), so N\n// instances of the same component share one refcounted <style> in the head\nconst scopeHash = (src: string): string => {\n let hash = 2166136261\n for (let i = 0; i < src.length; i++) hash = Math.imul(hash ^ src.charCodeAt(i), 16777619)\n return (hash >>> 0).toString(36)\n}\n\nconst stampScope = (nodes: (TemplateNode | string)[], scope: string) => {\n nodes.forEach(node => {\n if (typeof node === \"string\") return\n node.attrs[SCOPE_ATTR] = scope\n stampScope(node.children, scope)\n })\n}\n\n// the scope attribute goes on the selector's last compound - the element the\n// rule actually targets - but *before* a pseudo-element, which must stay last\n// (\".a::before\" scopes to \".a[data-jq79='x']::before\", not \"::before[...]\")\nconst scopeSelector = (selectorText: string, scope: string): string =>\n selectorText\n .split(\",\")\n .map(part => {\n const selector = part.trim()\n const pseudoAt = selector.indexOf(\"::\")\n const target = pseudoAt === -1 ? selector : selector.slice(0, pseudoAt)\n const pseudoElement = pseudoAt === -1 ? \"\" : selector.slice(pseudoAt)\n return `${target}[${SCOPE_ATTR}=\"${scope}\"]${pseudoElement}`\n })\n .join(\", \")\n\n// CSSStyleRule is scoped in place; CSSGroupingRule (@media, @supports,\n// @container) is recursed into; everything else - notably @keyframes, whose\n// \"selectors\" are percentages - is left alone\nconst scopeRules = (rules: CSSRuleList, scope: string) => {\n Array.from(rules).forEach(rule => {\n if (rule instanceof CSSStyleRule) rule.selectorText = scopeSelector(rule.selectorText, scope)\n else if (rule instanceof CSSGroupingRule) scopeRules(rule.cssRules, scope)\n })\n}\n\n// the CSS parser is the browser's own (no dependency, no hand-rolled parser).\n// Note browsers *silently drop* rules whose selector they can't parse, which\n// is what Vue's :deep()/::v-deep/>>> escape hatches are - unsupported here,\n// and warned about rather than left to vanish\nconst scopeCss = (css: string, scope: string): string => {\n if (/:deep\\(|::v-deep|>>>/.test(css)) {\n console.warn(\"jq79: :deep()/::v-deep/>>> are not supported in <style scoped>; the rule will be dropped by the browser\")\n }\n const sheet = new CSSStyleSheet()\n sheet.replaceSync(css)\n scopeRules(sheet.cssRules, scope)\n return Array.from(sheet.cssRules).map(rule => rule.cssText).join(\"\\n\")\n}\n\n// a component name has to be PascalCase to be usable: findComponentKey only\n// ever considers capitalized scope keys, so a lowercase name would declare a\n// component no tag could reference. It is also what keeps the named exports\n// from colliding with a definition's own fields, which are all lowercase\nconst COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]*$/\n\n// converts a string of HTML into an AST representation of the component:\n// - template: the non-script/style top-level elements, as TemplateNodes\n// - scripts/styles: { attrs, content } blocks in source order\n// - siblings: the components its top-level <template name=\"...\"> declared\nconst parseComponentString = (component: string): ComponentParts => {\n // example\n // <script :setup=\"{ fname, lname }\">\n // const fullName = `${fname} ${lname}`\n // </script>\n //\n // <div :attrs=\"{ fullName }\"></div>\n // <div class=\"full-name\">\n // {{ fullName }}\n // </div>\n //\n // <style>\n // .full-name {\n // color: red;\n // }\n // </style>\n\n // parsed as the content of a <template> so leading <script>/<style> tags\n // aren't reparented into <head> by the HTML parser. All three pre-DOM string\n // rewrites run here, and the order is load-bearing: camelCase names ->\n // kebab-case first (before `:props.<n>` exists to be mangled and while a\n // self-closing tag is still one occurrence), then `...expr` -> :props.<n>\n // (which reads the raw camelCase before the parser can lowercase names),\n // then self-closing tags\n const prepared = expandSelfClosingTags(expandPropsSpread(expandNameCase(component)))\n const parsedDOM = new DOMParser().parseFromString(`<template>${prepared}</template>`, \"text/html\")\n const root = parsedDOM.querySelector(\"template\") as HTMLTemplateElement\n\n // a top-level <template> declares another component of this file; everything\n // else is this one's own\n const own: Element[] = []\n const declarations: HTMLTemplateElement[] = []\n Array.from(root.content.children).forEach(el => {\n if (el.tagName === \"TEMPLATE\") declarations.push(el as HTMLTemplateElement)\n else own.push(el)\n })\n\n // the file's own component hashes the whole file: every component in it\n // re-renders on any edit anyway (the file is the hot-reload unit), so a\n // stamp that changes when a sibling is edited costs nothing, and scopeHash\n // gets to keep hashing the source it was handed\n const parts = componentPartsFrom(own, component)\n\n // one map, shared by reference: it is filled below, after each definition\n // has already been handed it, so every component of the file sees all the\n // others *and itself* - which is what makes a recursive component possible\n const siblings: Record<string, Component79> = {}\n declarations.forEach(el => {\n const name = el.getAttribute(\"name\")\n // ignored rather than fatal, like every other malformed thing here: a bad\n // save mid-typing must not take the page down, least of all under HMR\n if (name === null) {\n console.warn(\"jq79: a top-level <template> without a name declares nothing and was ignored\")\n return\n }\n if (!COMPONENT_NAME_RE.test(name)) {\n console.warn(\n `jq79: <template name=\"${name}\"> was ignored - a component name has to be PascalCase, ` +\n \"or no tag could ever reference it (only capitalized names resolve as components)\"\n )\n return\n }\n if (name in siblings) {\n console.warn(`jq79: two <template name=\"${name}\"> in one file; the second was ignored`)\n return\n }\n // its own source is its own scope: a named template is a shadow root\n // inside a shadow root, so the file's scoped rules stop at its boundary\n // and its own stop there too\n siblings[name] = new Component79({ ...componentPartsFrom(Array.from(el.content.children), el.innerHTML), siblings, name })\n })\n if (Object.keys(siblings).length) parts.siblings = siblings\n\n return parts\n}\n\n// the script/style/markup split of one component's top-level elements, with\n// <style scoped> resolved against the source those elements came from - the\n// whole file for its own component, a <template>'s contents for a named one,\n// so the two get different stamps and neither can style the other\nconst componentPartsFrom = (elements: Element[], hashSource: string): ComponentParts => {\n const scripts: TagBlock[] = []\n const styles: TagBlock[] = []\n const template: TemplateNode[] = []\n\n elements.forEach(el => {\n const block: TagBlock = { attrs: elementAttrs(el), content: el.textContent ?? \"\" }\n\n if (el.tagName === \"SCRIPT\") scripts.push(block)\n else if (el.tagName === \"STYLE\") styles.push(block)\n else template.push(elementToAST(el))\n })\n\n // <style lang=\"scss\"> is compiled by the jq79/vite plugin, so a `lang` still\n // here means this component never went through it - it was fetched, loaded\n // from a URL, or built from an inline string. The browser would drop the\n // uncompiled source without a word, so say it out loud instead\n styles.forEach(style => {\n if (\"lang\" in style.attrs) {\n console.warn(\n `jq79: <style lang=\"${style.attrs.lang}\"> needs the jq79/vite plugin to compile it. ` +\n \"This component didn't go through the bundler, so its styles were left uncompiled and the browser will ignore them.\"\n )\n }\n })\n\n // scoping is resolved once, here: the stamped template and the scoped CSS\n // are what every instance of this definition renders and injects. An\n // uncompiled `lang` block is left as it was written - rewriting selectors\n // in something that isn't CSS yet would only garble what devtools shows\n const isScoped = (style: TagBlock) => \"scoped\" in style.attrs && !(\"lang\" in style.attrs)\n if (styles.some(isScoped)) {\n const scope = scopeHash(hashSource)\n stampScope(template, scope)\n styles.forEach(style => {\n if (isScoped(style)) style.scoped = scopeCss(style.content, scope)\n })\n }\n\n return { template, scripts, styles }\n}\n\n// loads .html URLs as components, delegating anything else to native import().\n// Goes to fetchComponent rather than Component79.fetch because an import wants\n// the component, not the chainable handle the public entry point returns\nconst importResource = (url: string): Promise<any> =>\n /\\.html?([?#]|$)/.test(url) ? fetchComponent(url) : import(url)\n\n// a relative specifier means \"next to the file that wrote it\", so it is\n// resolved against the component's own URL before importResource sees it -\n// neither of that function's two branches would otherwise land there. The\n// native import() inside it resolves against *this module* (dist/jq79.js), and\n// fetch() against the document; a component in a subdirectory gets a 404 from\n// the first and the page's directory from the second.\n//\n// What comes back is always a fully absolute URL, and that is the load-bearing\n// part rather than a detail of formatting. A *path* would be resolved by that\n// same native import() against the library module's ORIGIN - and the library\n// is the one file on the page most likely to come from somewhere else:\n//\n// page http://localhost:8024/craft/app.html\n// jq79 https://jgermade.github.io/jq79/jq79.js\n// \"/craft/services/x.js\" -> https://jgermade.github.io/craft/services/x.js\n//\n// which is a CORS error naming a host the app never mentioned. Only an\n// absolute URL means the same thing to both branches.\n//\n// For the same reason a *root-absolute* specifier is resolved too, not passed\n// through: `/x.js` means the page's root to whoever wrote it, and the page is\n// the only base under which the two branches agree. Bare specifiers (\"lodash\")\n// are the exception that stays untouched - they belong to the import map or\n// the bundler, and resolving one would quietly turn it into a path.\n//\n// The base is absolutized first, the way hotKey does and for the same reason:\n// the filename may itself be relative (\"./card.html\", from an import() in a\n// parent), and a relative URL cannot be a base\nconst RESOLVABLE_SPECIFIER_RE = /^(?:\\.\\.?\\/|\\/|[a-z][a-z0-9+.-]*:)/i\n\nconst resolveSpecifier = (spec: string, filename: string | undefined): string => {\n if (!RESOLVABLE_SPECIFIER_RE.test(spec)) return spec\n try {\n return new URL(spec, new URL(filename ?? \"\", document.baseURI)).href\n } catch {\n return spec\n }\n}\n\n// ---------------------------------------------------------------------------\n// naming scripts for devtools\n//\n// setup scripts are compiled with new Function (they need `with`, which is a\n// SyntaxError in a module), so no bundler source map can reach them: they show\n// up as an anonymous \"VM1234\" script, breakpoints don't survive a reload, and\n// stack traces name nothing. A //# sourceURL comment fixes all three - the\n// compiled script takes the component's name, so it is findable in the sources\n// tree, keeps its breakpoints, and appears by name in stack traces.\n//\n// The line numbers it reports are the compiled script's own, not the .html\n// file's: the engine wraps a Function body in a header (\"function anonymous(\n// args\\n) {\\n\") that shifts everything down, and no amount of padding can\n// shift code *up* to match a <script> sitting on line 1. Reporting the\n// component's real lines would need a source map, which the runtime doesn't\n// emit today\n// ---------------------------------------------------------------------------\n\n// where a script block came from: the component's filename, and its index\n// among the component's scripts (two scripts in one file need distinct names,\n// or devtools shows only one of them)\ntype ScriptLocation = { filename?: string; index?: number }\n\n// what running a script tells its caller: the promise it settles through, and\n// whether it already finished on this stack. `sync` is the fast path the render\n// gate is built on - see runSetupScript\ntype ScriptRun = { settled: Promise<unknown>; sync: boolean }\n\n// nothing to name an inline component's scripts after, so they stay anonymous\nconst sourceUrlComment = (filename: string | undefined, index: number): string =>\n filename ? `\\n//# sourceURL=${filename}?jq79-script=${index}` : \"\"\n\n// what a <style> block injects into document.head: the scoped rewrite when it\n// has one, the source otherwise. A shadow root uses `content` directly instead\n// - scoping is what a shadow root already does, and doing both would break the\n// `:host` rules only shadow rendering can have (`:host[data-jq79=...]` matches\n// nothing: the host element is outside the template, so it carries no stamp)\nconst headStyle = (style: TagBlock): string => style.scoped ?? style.content\n\n// document.head styles are shared by content and refcounted, so N instances\n// of the same component (e.g. one per :each item) inject a single <style> tag\n// that goes away when the last instance is destroyed\nconst styleRegistry = new Map<string, { el: HTMLStyleElement; count: number }>()\n\nconst acquireStyle = (content: string) => {\n let entry = styleRegistry.get(content)\n if (!entry) {\n const el = document.createElement(\"style\")\n el.textContent = content\n document.head.appendChild(el)\n entry = { el, count: 0 }\n styleRegistry.set(content, entry)\n }\n entry.count++\n}\n\nconst releaseStyle = (content: string) => {\n const entry = styleRegistry.get(content)\n if (entry && --entry.count <= 0) {\n entry.el.remove()\n styleRegistry.delete(content)\n }\n}\n\n// scripts run inside `with (scriptScope)`, where scriptScope's `has` trap\n// claims ownership of every name that is neither a real global, an injected\n// library helper, nor one of the internal helpers. This makes `with` route ALL\n// other reads/writes through the reactive store - even bare assignments to\n// names never declared with let/const, which would otherwise leak onto\n// globalThis - while `console`, `Promise`, `fetch`, etc. still resolve\n// normally. get/set are deliberately not trapped: they default-forward to\n// `scope` (the reactive proxy), preserving tracking and notify.\n// The body is wrapped in an async IIFE so top-level `await` works: everything\n// up to the first await runs synchronously, and later assignments update the\n// DOM reactively when they happen.\n//\n// Returns whether the body ran to completion synchronously, plus the promise it\n// settles through. renderWith needs the *synchronous* answer - a script that\n// finished in this turn cannot hold anything up, so the template can render on\n// this stack exactly as it always has (see the render gate). Asking the promise\n// instead would defer every render by a microtask, including the overwhelmingly\n// common case of a script with no await in it at all.\n//\n// The flag is set on the code's last line, after the `with` block rather than\n// inside it, so the scope proxy never sees the name - and appended, so the\n// author's line numbers (which sourceUrlComment maps for devtools) don't shift\nconst runSetupScript = (code: string, scope: Record<string, any>, effect: (run: () => void) => void, instanceHelpers: Record<string, any> = {}, importer: (url: string) => Promise<any> = importResource, at: ScriptLocation = {}): ScriptRun => {\n // instanceHelpers are per-component-instance additions (e.g. $emit, which\n // is bound to this instance's DOM position)\n const helpers = { ...SETUP_HELPERS, ...instanceHelpers }\n const scriptScope = new Proxy(scope, {\n has: (target, key) =>\n key !== \"$__effect\" && key !== \"$__import\" && key !== \"$__state\" &&\n (Reflect.has(target, key) || !(key in globalThis) && !(key in helpers)),\n })\n const state: { done?: boolean } = {}\n const result: Promise<void> = new Function(\n \"$scope\", \"$__effect\", \"$__import\", \"$__state\", ...Object.keys(helpers),\n `return (async () => { with ($scope) { ${code} }\\n;$__state.done = true })()${sourceUrlComment(at.filename, at.index ?? 0)}`\n )(scriptScope, effect, importer, state, ...Object.values(helpers))\n result.catch(error => console.error(\"jq79: error in :setup script\", error))\n trackScript(result)\n return { settled: result, sync: state.done === true }\n}\n\n// puts a component's declared props on the store, before any script runs and\n// before the first render: the names, so the template can bind to them even\n// when the parent passes nothing, and the defaults, so it binds to something.\n//\n// A prop the parent *did* pass is already on the store (render() seeds it), so\n// a default only fills an `undefined` - which is also what JS destructuring\n// does with the same pattern, so both modes agree. It happens once, at setup:\n// re-applying a default later would need an effect that reads and writes the\n// same key, and that effect would wake itself forever.\n//\n// `null` props means the component declared no signature at all, which is not\n// the same as declaring an empty one: it keeps today's permissive behavior\nconst declareProps = (store: Record<string, any>, props: PropDecl[] | null) => {\n props?.forEach(({ name, default: expr }) => {\n if (store[name] !== undefined) return\n store[name] = expr === undefined ? undefined : evalExpr(expr, store)\n })\n}\n\n// a setup script's signature. A bare `<script :setup>` is a CLOSED signature -\n// the same as `<script :setup=\"{}\">`, declaring zero props and taking none -\n// because the difference between \"takes nothing\" and \"takes anything\" should\n// not be a pair of braces somebody didn't type. Permissive is still reachable,\n// it just has to be asked for: `<script :setup=\"_\">`, the same `_` convention\n// factory scripts already use, which parsePropsPattern reads as no signature.\n//\n// Only the empty *value* is closed. An absent attribute (a factory <script>\n// with no :setup at all) stays `null`, so its signature is still read from the\n// factory's first parameter\nconst setupSignature = (script: TagBlock): PropDecl[] | null => {\n const pattern = script.attrs[\":setup\"]\n if (pattern === undefined) return null\n if (pattern.trim() === \"\") return []\n const props = parsePropsPattern(pattern)\n if (!props) warnUnreadableSignature(script, pattern)\n return props\n}\n\n// script blocks already warned about, keyed by the block itself - parsed once\n// and shared by every instance of a definition, the same reason warnUndeclared\n// keys on the template node. It matters for a smaller reason here too:\n// setupSignature is called three times per render (both declared-name passes\n// and the script loop's declareProps), so even one mount would say it thrice\nconst signatureWarned = new WeakSet<TagBlock>()\n\n// a value that isn't a props pattern reads as \"declared no signature\", which is\n// the most permissive mode there is - so a typo doesn't fail, it quietly opts\n// the component out of the contract it was trying to write. That is now the\n// only accidental route left to permissive: a bare :setup is closed and `_` is\n// the opt-out you have to ask for, so the mode nothing lands in by accident is\n// still reachable by getting it wrong. Both of parsePropsPattern's nulls count\n// - not-an-object (\",{ a }\", \"props\") and unbalanced (\"{ a, b\") - and only `_`\n// is exempt, because intent is the sole thing separating it from the typos\nconst warnUnreadableSignature = (script: TagBlock, pattern: string) => {\n if (pattern.trim() === \"_\" || signatureWarned.has(script)) return\n signatureWarned.add(script)\n console.warn(\n `jq79: :setup=\"${pattern}\" is not a props pattern, so this component declares no ` +\n `signature and takes whatever a parent passes - write the props it takes ` +\n `(\"{ a, b }\"), a bare :setup for none, or \"_\" to stay open on purpose`\n )\n}\n\n// every prop name a component's scripts declare, across both script modes.\n// Read before the store exists, because what a component declares decides\n// which of its file's sibling components it can still see: declaring a name\n// says it comes from the parent, so the file's own definition of that name is\n// deliberately not in this component's scope\nconst declaredPropNames = (scripts: TagBlock[]): Set<string> => {\n const names = new Set<string>()\n scripts.forEach(script => {\n const declarations = parseFactoryProps(script.content) ?? setupSignature(script)\n declarations?.forEach(({ name }) => names.add(name))\n })\n return names\n}\n\n// the same names, but null when NO script declared a signature at all - the\n// distinction declareProps already keeps, and the only one that can decide\n// whether to filter what a parent passes. `<script :setup>` and\n// `<script :setup=\"{}\">` are both closed signatures that take nothing (see\n// setupSignature); `<script :setup=\"_\">` is the permissive one\nconst declaredPropSet = (scripts: TagBlock[]): Set<string> | null => {\n let names: Set<string> | null = null\n scripts.forEach(script => {\n const declarations = parseFactoryProps(script.content) ?? setupSignature(script)\n if (!declarations) return\n const into = (names ??= new Set())\n declarations.forEach(({ name }) => into.add(name))\n })\n return names\n}\n\n// drops the props a component didn't declare, so an undeclared name is simply\n// absent from its store rather than quietly present: `{{ label }}` renders\n// empty and `{{ user.name }}` throws on the member access, both at the usage\n// site that got the name wrong. A null signature keeps everything - see\n// declaredPropSet. Silent by design: the main source of extra keys is a\n// `:props` spread of an object wider than the component (`...sdk`), where\n// taking only the declared few is the point, not a mistake to report\nconst pickDeclared = (props: Record<string, any>, declared: Set<string> | null): Record<string, any> => {\n if (declared === null) return props\n const out: Record<string, any> = {}\n Object.keys(props).forEach(key => { if (declared.has(key)) out[key] = props[key] })\n return out\n}\n\n// names already reported by warnUndeclared, keyed by the template node - which\n// is the usage site itself, built once and shared by every instance it ever\n// renders. So a :each over 200 rows says it once, not once per row, and a\n// definition swap doesn't repeat what the last one already said\nconst undeclaredWarned = new WeakMap<TemplateNode, Set<string>>()\n\n// a parameter the child's signature doesn't declare is dropped by pickDeclared\n// and never reaches its store - `{{ bar }}` renders empty at the other end of\n// the file. Written parameters only: this is handed the named ones (`:bar`,\n// and the prop each :model binds), never a `:props` spread's keys, because a\n// spread of an object wider than the component is the documented, intended use\n// and taking only the declared few is its point - see pickDeclared. A\n// component with no signature at all declares nothing to compare against\nconst warnUndeclared = (node: TemplateNode, name: string, written: string[], declared: Set<string> | null) => {\n if (declared === null) return\n const said = undeclaredWarned.get(node) ?? new Set<string>()\n undeclaredWarned.set(node, said)\n written.forEach(prop => {\n if (declared.has(prop) || said.has(prop)) return\n said.add(prop)\n console.warn(`jq79: :${prop} is not declared by <${name}> - add it to the :setup signature, or drop it`)\n })\n}\n\n// the sibling components this one resolves by name, or null when there are\n// none left to resolve. They go on the store's *prototype* rather than in it:\n// the component-key scan walks the chain, so <Row> resolves; they stay out of\n// the data, so Object.keys, snapshots and spreads never see them; and an own\n// key shadows a prototype one, so a prop the parent did pass wins for free\nconst siblingsInScope = (\n siblings: Record<string, Component79> | undefined,\n declared: Set<string>\n): Record<string, Component79> | null => {\n if (!siblings) return null\n // null-prototype, for the same reason storeApi is: `key in scope` must not\n // start answering true for toString, constructor and the rest\n const inScope: Record<string, Component79> = Object.create(null)\n let any = false\n Object.entries(siblings).forEach(([name, component]) => {\n if (declared.has(name)) return\n inScope[name] = component\n any = true\n })\n return any ? inScope : null\n}\n\n// names a component declared as props and the parent passed nothing for. Such\n// a name can never become a component later - there is no binding on the tag\n// to update it - so a <Tag> reading one is a wiring mistake that can be named\n// on sight, unlike the `undefined` of an import still in flight. Symbol-keyed\n// and non-enumerable: it rides the scope chain (so an :each item scope finds\n// it too) without ever showing up as data\nconst UNFILLED_PROPS = Symbol(\"jq79.unfilledProps\")\n\n// how many of this render generation's scripts have yet to settle, as a live\n// box rather than a snapshot. Rides the scope chain like UNFILLED_PROPS, and\n// for one reader: a <Tag> naming no component in scope is only a mistake once\n// nothing is left that could still supply the name.\n//\n// The count is not the render gate. A script that called $mounted() released\n// the template and is still running - that is the whole point of the call - so\n// at paint time this can be non-zero, and a name arriving from a factory that\n// awaited $mounted() is exactly the case the count keeps quiet. Read live, so\n// an :if that opens after everything settled is judged against the scripts as\n// they are then, not as they were at the first paint\nconst PENDING_SCRIPTS = Symbol(\"jq79.pendingScripts\")\n\ntype PendingScripts = { count: number }\n\n// default-import interop for factory scripts: real modules expose .default,\n// while importing an .html component resolves to the Component79 itself\nconst interopDefault = (mod: any) => (mod && mod.default !== undefined ? mod.default : mod)\n\n// runs a factory script: the (rewritten) module body executes in plain\n// lexical strict-mode scope - no `with`, no implicit reactivity - with the\n// library helpers as parameters, then the default export is called with the\n// instance context and a returned object is merged into the store. A fully\n// synchronous body invokes the factory before the first render, matching\n// setup-script timing; bodies with top-level await (static imports included)\n// resolve later and the template updates reactively\nconst runFactoryScript = (code: string, scope: Record<string, any>, effect: (run: () => void) => void, instanceHelpers: Record<string, any> = {}, importer: (url: string) => Promise<any> = importResource, at: ScriptLocation = {}): ScriptRun => {\n const helpers = { ...SETUP_HELPERS, ...instanceHelpers }\n const $__exports: { default?: (props: Record<string, any>, ctx: Record<string, any>) => any; done?: boolean } = {}\n const result: Promise<void> = new Function(\n \"$__exports\", \"$__default\", \"$__import\", ...Object.keys(helpers),\n `return (async () => { \"use strict\";\\n${code}\\n;$__exports.done = true })()${sourceUrlComment(at.filename, at.index ?? 0)}`\n )($__exports, interopDefault, importer, ...Object.values(helpers))\n\n const logError = (error: any) => console.error(\"jq79: error in factory script\", error)\n let invoked = false\n // what invoke() is still waiting on, memoized: it is called from both paths\n // below and does its work once, but the *second* caller is the one whose\n // promise is tracked - without this it would see `undefined` and count the\n // script as settled while an async factory's bindings are still on the way\n let merging: Promise<void> | undefined\n const invoke = (): Promise<void> | undefined => {\n if (invoked) return merging\n invoked = true\n const factory = $__exports.default\n if (typeof factory !== \"function\") return undefined\n const merge = (bindings: any) => {\n if (bindings && typeof bindings === \"object\") Object.assign(scope, bindings)\n }\n // the sync path is invoked straight from render(), so a throwing factory\n // must be caught here too - not just by the `result` rejection handler\n try {\n // props first, ctx second. Both are the store: the pattern destructures\n // the props it declared (copying, as destructuring does - $props is the\n // live view for a primitive the parent reassigns later)\n const returned = factory(scope, { $data: scope, $props: scope, $effect: effect, ...instanceHelpers })\n if (returned instanceof Promise) merging = returned.then(merge).catch(logError)\n else merge(returned)\n } catch (error) {\n logError(error)\n }\n return merging\n }\n\n // tracked through the merge, not just the module body: a factory's names\n // reach the store in `merge`, and a template expression that reads one before\n // then is not an authoring mistake (see reportExprError)\n const settled = result.then(invoke, logError)\n trackScript(settled)\n if ($__exports.done) invoke() // fully-sync body: factory runs before first render\n // sync only if the bindings are already on the store: a factory whose body\n // finished but whose *factory* returned a promise (an async factory, or one\n // that awaits $mounted()) still has names on the way, and the render gate\n // must treat it as pending rather than race its merge\n return { settled, sync: $__exports.done === true && merging === undefined }\n}\n\n// ---------------------------------------------------------------------------\n// hot reload\n//\n// Both delivery paths want the same thing when a .html file changes: reparse\n// it, and re-render every live instance of it in place, keeping its data. The\n// swap lives in the runtime (hotReplace, below) so jq79/dev and the Vite\n// plugin share one implementation instead of two - and so it can reach the\n// private fields it needs (the markers, the holding fragment) rather than\n// poking at them from outside, which is what the plugin used to do.\n//\n// Finding the instances is the part only the runtime can do: a component\n// fetched at runtime is reachable from nothing but the DOM it rendered. So\n// instances register themselves - but only once a page opts in, before the\n// runtime loads. Nothing here costs a bundled app anything: with the registry\n// off, an instance is not tracked at all.\n// ---------------------------------------------------------------------------\n\nconst HOT_FLAG = \"__JQ79_HMR_ENABLED__\"\nconst HOT_RUNTIME = \"__JQ79_HMR__\"\n\n// live instances by filename. WeakRef because a destroyed component that the\n// page has dropped must stay collectable: `:each` churns through clones\nlet hotRegistry: Map<string, Set<WeakRef<Component79>>> | null = null\n\nconst hotRegister = (instance: Component79) => {\n if (!hotRegistry || !instance.filename) return\n let refs = hotRegistry.get(instance.filename)\n if (!refs) hotRegistry.set(instance.filename, (refs = new Set()))\n refs.add(new WeakRef(instance))\n}\n\n// the same file reaches the runtime under different names - \"./card.html\" from\n// an import() in a setup script, \"/cards/card.html\" from a fetch, \"cards/card.\n// html\" from the dev server that watched it - and they all have to land on one\n// key. Resolving against the page is what settles them\nconst hotKey = (filename: string): string => {\n try {\n return new URL(filename, document.baseURI).pathname\n } catch {\n return filename\n }\n}\n\n// swaps the file's new source into every instance that came from `filename`,\n// and returns how many of them were *on the page* and so re-rendered. Zero\n// means the change is not visible anywhere - the file is a page rather than a\n// component, or nothing has mounted it yet - and the caller (a dev server)\n// should fall back to reloading. Definitions and instances that have been\n// destroyed but not yet collected are patched all the same; they just don't\n// count, because nothing on screen changed for them\nexport const hotUpdate = (filename: string, src: string): number => {\n if (!hotRegistry) return 0\n\n const key = hotKey(filename)\n // parsed once and shared by every instance - which is already what a\n // definition and the clones :component makes from it do\n const parts = parseComponentString(src)\n // the file is the hot-reload unit, so one reparse serves every component it\n // declares: an instance is handed the parts of the component it *is*, by\n // name. A name that is no longer in the file (a <template> renamed or\n // deleted) has no parts to be given, and only a reload can fix the page\n let orphaned = false\n const partsFor = (instance: Component79): ComponentParts | null =>\n instance.name === undefined ? parts : parts.siblings?.[instance.name] ?? null\n\n let rerendered = 0\n for (const [name, refs] of hotRegistry) {\n if (hotKey(name) !== key) continue\n for (const ref of refs) {\n const instance = ref.deref()\n if (!instance) {\n refs.delete(ref) // collected since the last update\n continue\n }\n const next = partsFor(instance)\n if (!next) {\n orphaned = true\n continue\n }\n if (instance.hotReplace(next)) rerendered++\n }\n if (!refs.size) hotRegistry.delete(name)\n }\n return orphaned ? 0 : rerendered\n}\n\n// starts tracking instances, so hotUpdate can find them. jq79/dev's client\n// calls this through the global handshake at the foot of this file; it is\n// exported so a bundled app - or a test - can opt in directly\nexport const enableHotReload = (): void => {\n hotRegistry ??= new Map()\n ;(globalThis as any)[HOT_RUNTIME] = { update: hotUpdate }\n}\n\ntype EmitListener = (event: CustomEvent, payload: any) => void\n\n// how long a first render may sit behind its scripts before the console says so\nconst STUCK_RENDER_DELAY = 3000\n\n// a script that neither returns nor calls $mounted() holds the template\n// forever, and the failure looks like nothing at all: no error, no markup, a\n// component indistinguishable from one nobody mounted. So the wait is loud\n// after a few seconds - and it keeps waiting, because rendering on a timer\n// would make the moment of the first render depend on the machine it runs on.\n//\n// Armed only on the deferred path, so a page of synchronous components creates\n// no timers at all\nconst warnIfStuck = (component: Component79, gates: Promise<void>[]) => {\n const timer = setTimeout(() => {\n console.warn(\n `jq79: ${component.name ? `<${component.name}>` : \"a component\"}${component.filename ? ` (${component.filename})` : \"\"} ` +\n `has been waiting ${STUCK_RENDER_DELAY / 1000}s for a :setup script and has rendered nothing. ` +\n \"The template waits until every script returns or calls $mounted() - add an \" +\n \"await $mounted() above the slow part to render first and fill in after.\"\n )\n }, STUCK_RENDER_DELAY)\n // unref where it exists (node/vitest): a pending timer must not be what keeps\n // a process alive. Browsers have no such notion and no such need\n ;(timer as any)?.unref?.()\n Promise.all(gates).then(() => clearTimeout(timer))\n}\n\nconst fetchComponent = async (url: string): Promise<Component79> => {\n const response = await fetch(url)\n if (!response.ok) throw new Error(`failed to fetch component from ${url}: ${response.status}`)\n // the URL names the component's scripts in devtools, and is where the\n // browser will look for the source when a breakpoint lands in one\n return new Component79(await response.text(), { filename: url })\n}\n\n// a parsed single-file component. Typical lifecycle:\n//\n// const jq79 = new Component79(src) // or await Component79.fetch(url)\n// jq79.on(\"submit\", (e, payload) => {}) // hear this instance's $emit events\n// jq79.mount(\"#app\", { user }) // render (reactive DOM, scripts, styles) + attach\n// ... // (mountShadow mounts into a shadow root)\n// jq79.detach() // detach, keeping state - mount() re-attaches\n// .destroy() // dispose effects and remove styles\nexport class Component79 {\n // the version of jq79 this class came from, so a page can tell which build it\n // loaded (a CDN <script> pins nothing on its own)\n static readonly version: string = VERSION\n\n template: TemplateNode[]\n scripts: TagBlock[]\n styles: TagBlock[]\n // pre-resolved modules for setup-script `import(...)` calls (see\n // ComponentParts.modules); checked before falling back to fetch/import\n modules?: Record<string, any>\n // the component's origin, used to name its scripts in devtools\n filename?: string\n // the other components declared in the same file, by name (see\n // ComponentParts.siblings). They are also this definition's own properties,\n // so `const { Row } = await Component79.fetch(url)` reaches them\n siblings?: Record<string, Component79>\n // this component's name inside its file, for the components a <template>\n // declared; the file's own component has none - it is the default, and a\n // default is named by whoever imports it\n name?: string\n // the content the usage site handed this instance, by slot name (see the\n // slots section). Not part of a definition - it belongs to the tag that\n // wrote it - so renderNestedComponent sets it on the instance it creates,\n // and every render reads it from here: a hot reload re-renders from a data\n // snapshot, which a symbol on the store would not survive\n slots?: SlotMap\n // the writeback half of :model, same story: the function that assigns into\n // the parent, set by renderNestedComponent before the first render and\n // called by this instance's $updateModel. Kept outside the render generation\n // so it survives re-render and hot reload. Absent means no :model on the tag\n // (or no tag at all - a root mount), which makes every $updateModel a no-op.\n // Internal: set by the usage site, not part of the public API\n modelWriteback?: (name: string | undefined, value: any) => boolean\n\n data: ReactiveDeepData<Record<string, any>> | null = null\n\n private fx: EffectScope | null = null\n // holds the rendered nodes while detached; anchors keep this fragment as\n // their parentNode, so effects keep the (detached) DOM up to date and a\n // later mount() shows current state\n private content: DocumentFragment | null = null\n // markers bracketing the component's output so detach() can collect nodes\n // that :if/:each inserted next to the anchors after mounting\n private startMarker: Comment | null = null\n private endMarker: Comment | null = null\n // shadow rendering keeps per-instance <style> elements; head rendering goes\n // through the shared refcounted styleRegistry instead\n private styleEls: HTMLStyleElement[] = []\n private ownsSharedStyles = false\n private useShadow = false\n private mountRoot: Element | ShadowRoot | DocumentFragment | null = null\n // settles the $mounted() promise handed to this render generation's scripts\n private resolveMounted: (() => void) | null = null\n // whether this generation's template has been built. A render held back by a\n // script (see the gate in renderWith) has markers but no nodes, and $mounted()\n // must not resolve on attach alone - a script awaiting it would wake to an\n // empty component and find nothing to query\n private renderDone = false\n // instance-level listeners for $emit events, registered with on(). Kept\n // outside the render generation so they survive re-render and destroy()\n private emitListeners = new Map<string, Set<EmitListener>>()\n\n constructor(src: string | ComponentParts, options: { modules?: Record<string, any>; filename?: string } = {}) {\n const parts = typeof src === \"string\" ? parseComponentString(src) : src\n this.template = parts.template\n this.scripts = parts.scripts\n this.styles = parts.styles\n this.modules = options.modules ?? (typeof src === \"string\" ? undefined : src.modules)\n this.filename = options.filename ?? (typeof src === \"string\" ? undefined : src.filename)\n this.siblings = parts.siblings\n this.name = parts.name\n this.adoptSiblings()\n hotRegister(this) // a no-op unless the page enabled hot reload\n }\n\n // the parser builds a file's sibling definitions before anyone has told it\n // where the file came from, so whoever holds the parse hands its origin down\n // - and keeps doing it after a hot reload, which parses the file afresh.\n // Without it a reloaded child would have no filename, and an instance with\n // no filename is not tracked: the next edit would never reach it\n private adoptSiblings() {\n if (!this.siblings) return\n Object.entries(this.siblings).forEach(([name, sibling]) => {\n sibling.filename ??= this.filename\n sibling.modules ??= this.modules\n // the file's own component also *is* the file: its named components hang\n // off it as properties, which is what `const { Row } = …` reads (and\n // what the bundler re-exports by name)\n if (!this.name) (this as any)[name] = sibling\n })\n }\n\n // swaps this component's parsed parts for `src`'s and, if it is on the page,\n // re-renders it where it stands - seeded with a snapshot of its data, so\n // props and store values survive (the setup script runs again, so whatever it\n // initializes is reset). Returns whether it re-rendered: an instance that was\n // never rendered is a *definition*, and patching its parts is all there is to\n // do - the clones :component made from it are instances in their own right,\n // registered under the same filename, and re-render themselves.\n //\n // Dev-only, and not part of the public API: jq79/dev and the Vite plugin call\n // it when a file changes. It re-attaches against the markers rather than\n // mountRoot on purpose - a nested clone is mounted into a fragment that is\n // then emptied into the page, so its mountRoot is a stale, detached fragment\n // while its markers sit where its DOM actually is\n hotReplace(src: string | ComponentParts): boolean {\n const parts = typeof src === \"string\" ? parseComponentString(src) : src\n // the source just changed, so what was already said about it no longer\n // applies: without this the author fixes the typo, saves, and the next typo\n // in the same expression is deduped away against the old one. `compiled`\n // needs no such reset - it is keyed by expression text, so edited source is\n // a different key\n reportedExprErrors.clear()\n pendingReports.clear()\n reportedFailedExprs.clear()\n const marker = this.startMarker\n const rendered = !!(marker && this.content)\n\n // where its output sits now, if it is on the page. A rendered-but-detached\n // instance (markers in the holding fragment) re-renders detached, and a\n // later mount() attaches the new output - like any update it missed away\n const live = rendered && marker!.isConnected\n const parent = live ? (marker!.parentNode as Element | ShadowRoot | DocumentFragment) : null\n const before = live ? this.endMarker!.nextSibling : null\n const data = { ...this.data }\n const shadow = this.useShadow\n\n // destroy() releases the styles it acquired, so it has to run while\n // this.styles is still the *old* set - swapping the parts first would leak\n // the old stylesheet into the head and release a new one nobody holds\n if (rendered) this.destroy()\n\n this.template = parts.template\n this.scripts = parts.scripts\n this.styles = parts.styles\n // the file's other components as they are now: the next render resolves\n // <Row> against these, so a parent picks up an edited child even when the\n // child's own instances are patched separately\n this.siblings = parts.siblings\n this.adoptSiblings()\n if (!rendered) return false // a definition: its clones re-render themselves\n\n this.renderWith(data, shadow)\n if (!parent) return false\n\n // shadow styles live inline, right before the DOM they style (attach()\n // appends them ahead of the content), so they go back the same way\n if (shadow) this.styleEls.forEach(el => parent.insertBefore(el, before))\n parent.insertBefore(this.content!, before)\n this.mountRoot = parent\n this.settleMounted()\n return true\n }\n\n // downloads and parses a component, handing back a PendingComponent79: a\n // handle that can be mounted right away, and that awaits to this component -\n // so both of these are the whole program\n //\n // Component79.fetch(\"./app.html\").mount(\"main\")\n // const app = await Component79.fetch(\"./app.html\")\n static fetch(url: string): PendingComponent79 {\n if (Array.isArray(url)) throw new TypeError(\"Component79.fetch takes one URL; use fetchAll for an array\")\n return new PendingComponent79(fetchComponent(url))\n }\n\n // fetches them all at once and resolves to the components in the same order,\n // so one await destructures them - and, like Promise.all, the first failure\n // rejects the whole thing. A plain promise, not a handle: mounting a *list*\n // of components has no single meaning\n static fetchAll(urls: string[]): Promise<Component79[]> {\n return Promise.all(urls.map(fetchComponent))\n }\n\n // subscribes to this instance's $emit events, on top of the DOM CustomEvent\n // dispatch - so it hears emits even while the component is detached (where\n // the event has no ancestors to bubble to). Chainable; can be called before\n // render()\n on(eventName: string, listener: EmitListener): this {\n if (!this.emitListeners.has(eventName)) this.emitListeners.set(eventName, new Set())\n this.emitListeners.get(eventName)!.add(listener)\n return this\n }\n\n off(eventName: string, listener: EmitListener): this {\n this.emitListeners.get(eventName)?.delete(listener)\n return this\n }\n\n render(data: Record<string, any> = {}): this {\n return this.renderWith(data, false)\n }\n\n // like render(), but styles are injected into a shadow root attached to the\n // mount target instead of document.head, so they don't leak globally\n renderShadow(data: Record<string, any> = {}): this {\n return this.renderWith(data, true)\n }\n\n private renderWith(data: Record<string, any>, shadow: boolean): this {\n this.destroy()\n\n // what this component can see of its file's other components, and which of\n // its declared props arrived empty - both decided by the signature, before\n // the store exists (see siblingsInScope / UNFILLED_PROPS)\n const declared = declaredPropNames(this.scripts)\n const siblingScope = siblingsInScope(this.siblings, declared)\n const raw: Record<string, any> = siblingScope\n ? Object.assign(Object.create(siblingScope), data)\n : { ...data }\n const unfilled = new Set([...declared].filter(name => !(name in data)))\n if (unfilled.size) Object.defineProperty(raw, UNFILLED_PROPS, { value: unfilled })\n // the slot content, for the <slot>s the template renders, and the static\n // map of which names were filled, for the component to ask about\n // (`<footer :if=\"$slots.footer\">`). Filled at the usage site, so it can\n // only change when the tag itself re-renders - which builds a new instance\n if (this.slots) Object.defineProperty(raw, SLOTS, { value: this.slots })\n // in place before the store wraps it, because the scripts that increment it\n // run against the store and the template reads it back through the same\n // scope chain. Read back out of `raw` where it is needed rather than kept\n // in a local: this frame is on the stack for the whole of the subtree it\n // renders, so a component nested inside itself pays for it once per level -\n // and the depth guard at MAX_NESTING_DEPTH only beats a RangeError while\n // this function stays small (see the note in docs/development.md)\n Object.defineProperty(raw, PENDING_SCRIPTS, { value: { count: 0 } as PendingScripts })\n\n const store = $reactive(raw)\n const fx = createEffectScope(store)\n this.data = store\n this.fx = fx\n this.useShadow = shadow\n\n this.startMarker = document.createComment(\"jq79\")\n this.endMarker = document.createComment(\"/jq79\")\n\n // $emit dispatches a bubbling CustomEvent from this instance's start\n // marker, so once mounted it travels up the real DOM and parents can\n // listen on any ancestor (or with @event-name on a wrapping element).\n // Captures the marker rather than `this` so a later re-render's scripts\n // can't dispatch from the wrong generation - the same guard keeps stale\n // generations from reaching the instance's on() listeners.\n // The on() channel runs *first* (it's where @event on a component tag is\n // wired - see wireTagEvent) so its listeners can shape the DOM dispatch:\n // stopPropagation() there keeps the event off the DOM entirely, and the\n // event is cancelable so preventDefault() - from either channel - flips\n // the return to false, telling the emitting child \"the parent vetoed\"\n const marker = this.startMarker\n // model:update used to be the writeback's event name; it is a direct call\n // now ($updateModel), so an emit under that name reaches nothing. Said\n // once per generation rather than per keystroke, and said at all because\n // the alternative is a child whose edits silently stop arriving\n let warnedModelUpdate = false\n const $emit = (eventName: string, payload?: any): boolean => {\n if (eventName === \"model:update\" && !warnedModelUpdate) {\n warnedModelUpdate = true\n console.warn(\"jq79: $emit('model:update', …) no longer feeds :model - call $updateModel(value) or $updateModel(name, value) instead\")\n }\n const event = new CustomEvent(eventName, { detail: payload, bubbles: true, composed: true, cancelable: true })\n if (marker === this.startMarker) {\n this.emitListeners.get(eventName)?.forEach(listener => listener(event, payload))\n }\n // cancelBubble is the spec's legacy name, but it's the only *readable*\n // accessor for the stop-propagation flag - hence the deprecation hint\n if (!event.cancelBubble) marker.dispatchEvent(event)\n return !event.defaultPrevented\n }\n\n // `await $mounted()` suspends a setup script until the component is\n // rendered *and* attached, so code below it can querySelector its own DOM.\n // If this instance is never mounted, the promise stays pending and the\n // script's tail never runs.\n //\n // Calling it is also how a script releases the first render - see the gate\n // below - so the two halves of the contract are one call: \"put me on the\n // page, and don't wait for the rest of me\"\n let resolveMounted!: () => void\n const mounted = new Promise<void>(resolve => { resolveMounted = resolve })\n this.resolveMounted = resolveMounted\n this.renderDone = false\n\n // $self / $$self mirror $ / $$ but only search this instance's own\n // output: the sibling nodes between its markers. They work detached too\n // (the holding fragment keeps markers and rendered nodes as siblings),\n // though the template renders after the scripts run, so they only find\n // something from post-await code or callbacks\n const endMarker = this.endMarker\n const $$self = (selector: string): Element[] => {\n const found: Element[] = []\n for (let node: Node | null = marker.nextSibling; node && node !== endMarker; node = node.nextSibling) {\n if (node instanceof Element) {\n if (node.matches(selector)) found.push(node)\n found.push(...Array.from(node.querySelectorAll(selector)))\n }\n }\n return found\n }\n const $self = (selector: string): Element | null => $$self(selector)[0] ?? null\n\n // import() calls whose specifier was pre-resolved by a bundler (the\n // modules map) get the bundled module; everything else falls back to the\n // runtime importResource (fetch for .html, native import otherwise),\n // relative to this component's file. The map is keyed by the literal\n // specifier the script wrote, so it is consulted *before* resolution -\n // what the bundler hoisted and what the source says are the same string\n const modules = this.modules\n const $import = (url: string): Promise<any> =>\n modules && url in modules\n ? Promise.resolve(modules[url])\n : importResource(resolveSpecifier(url, this.filename))\n\n // the writeback half of :model, from the child's side: one argument is the\n // value for the default model (the bare :model), two are a name and a\n // value. Arity is what tells them apart, so the value is never inspected -\n // an object with `name`/`value` keys is just a value, which is exactly\n // what a payload-shaped contract could not promise. Returns whether a\n // bound model took it; no :model at the usage site is a silent no-op,\n // since a child may be designed to work bound or unbound\n const $updateModel = (...args: [value?: any] | [name: string, value: any]): boolean => {\n const [name, value] = args.length > 1 ? args as [string, any] : [undefined, args[0]]\n // the same stale-generation guard $emit has: destroy() nulls the marker,\n // so a closure the old child leaked (a timer, a registered callback)\n // cannot keep writing a parent that replaced it\n if (marker !== this.startMarker) return false\n return this.modelWriteback?.(name, value) ?? false\n }\n\n // the names a component answers on top of its store: $emit, so an inline\n // handler can emit without routing through a setup function\n // (@input=\"$emit('update', $event.target.value)\"), $updateModel, the\n // writeback a :model binding listens for, and $slots, the static map of\n // the names the usage site filled, so a wrapper can be dropped when\n // nothing filled it (<footer :if=\"$slots.footer\">). All reach the\n // template (through templateScope, below) and both script modes (as\n // instance helpers), and a same-named store key shadows any of them.\n // Null-prototype, for the same reason storeApi is: `key in injected` must\n // not start answering true for toString, constructor and the rest\n const injected: Record<string, any> = Object.assign(Object.create(null), {\n $emit,\n $updateModel,\n $slots: Object.fromEntries(Object.keys(this.slots ?? {}).map(name => [name, true])),\n })\n\n // scripts run before the template renders so `$:` values are initialized;\n // a `:mounted` script defers entirely until mount() instead. A top-level\n // `export default` switches the script to factory mode (plain lexical JS)\n // a `:mounted` script is deferred by prepending the await on the code's own\n // first line, so deferring doesn't shift the lines devtools reports for it\n const defer = (code: string) => `await $mounted();${code}`\n\n // what the first render is still waiting for. A script holds the template\n // back until it returns or calls $mounted() - whichever comes first - so\n // `let rows = await fetch(...)` renders once, with rows, instead of\n // rendering empty and filling in. `:mounted` is not a special case here: it\n // *is* a script that yields on line 0, which is what `defer` above writes.\n //\n // One gate per script, not one per instance: a script yielding must not\n // release the render on behalf of a sibling script that is still fetching\n const gates: Promise<void>[] = []\n let allSync = true\n\n this.scripts.forEach((script, index) => {\n let resolveGate!: () => void\n gates.push(new Promise<void>(resolve => { resolveGate = resolve }))\n // whether this gate is already open on *this* stack, which is not the\n // same as the script having finished: a script that yields immediately\n // (`await $mounted()` on its first line, which is what `:mounted`\n // compiles to) never finishes synchronously but holds nothing up either.\n // Reading the promise instead would push every such render a microtask\n // later, for no one's benefit\n let open = false\n const release = () => { open = true; resolveGate() }\n // this script's own view of $mounted: the call releases its gate, the\n // promise it returns is the instance's (one mount, one resolution)\n const $mounted = () => { release(); return mounted }\n // the file's other components are passed as parameters of the compiled\n // script, not just left on the store's prototype: a factory script runs\n // as plain lexical JS with no `with`, so a bare `Row` in one would\n // resolve to nothing at all. In setup mode this composes with `with` -\n // scriptScope's `has` declines any name that is a helper, so the\n // parameter is what the name resolves to\n const instanceHelpers = { $mounted, $self, $$self, ...injected, ...siblingScope }\n const at: ScriptLocation = { filename: this.filename, index }\n const deferred = \":mounted\" in script.attrs\n const factoryCode = transformFactoryScript(script.content)\n const run = ((): ScriptRun => {\n if (factoryCode !== null) {\n // a factory publishes its names by returning them, so one that yields\n // before it returns renders against a store where none of them exist.\n // In factory mode `:mounted` yields on line 0, which means *always* -\n // and unlike a setup script there is no way to put the useful half\n // above the yield. Awaiting $mounted() inside the factory does what\n // the author meant, and is what the message points at\n if (deferred) {\n console.warn(\n \"jq79: :mounted on a factory script renders the template before the factory has returned, \" +\n \"so none of its bindings exist yet - await $mounted() inside the factory instead.\"\n )\n }\n declareProps(store, parseFactoryProps(script.content))\n const body = deferred ? defer(factoryCode) : factoryCode\n return runFactoryScript(body, store, fx.effect, instanceHelpers, $import, at)\n }\n const { vars, code } = transformSetupScript(script.content)\n declareProps(store, setupSignature(script))\n // pre-declare script vars on the store so `with` resolves assignments\n // to them (and reads of them) through the reactive proxy\n vars.forEach(name => { if (!(name in store)) (store as any)[name] = undefined })\n const body = deferred ? defer(code) : code\n return runSetupScript(body, store, fx.effect, instanceHelpers, $import, at)\n })()\n // a script that threw has nothing left to contribute, so its rejection\n // releases the gate exactly as completion does - the error is already\n // reported by the runner, and holding the template hostage to it would\n // turn one broken script into a blank component. It also stops counting\n // as a source of names, for that same reason.\n //\n // A script that finished on this stack is counted at zero rather than\n // incremented and decremented a microtask later: its names are on the\n // store already, and the promise it settles through does not resolve\n // until after the synchronous paint - which is every paint, for the\n // components that have no await in them at all\n if (run.sync) run.settled.then(release, release)\n else {\n const pending: PendingScripts = (raw as any)[PENDING_SCRIPTS]\n pending.count++\n const settle = () => { pending.count--; release() }\n run.settled.then(settle, settle)\n }\n if (!run.sync && !open) allSync = false\n })\n\n const content = document.createDocumentFragment()\n // the injected names, served by has/get only - never as own keys - so\n // Object.keys, snapshot spreads and the component-key scan don't see them,\n // and every read still forwards through the reactive store, keeping\n // dependency tracking intact\n const templateScope = new Proxy(store as Record<string, any>, {\n has: (target, key) => (typeof key === \"string\" && key in injected) || Reflect.has(target, key),\n get: (target, key, receiver) =>\n typeof key === \"string\" && key in injected && !Reflect.has(target, key)\n ? injected[key]\n : Reflect.get(target, key, receiver),\n })\n // the markers go in either way, so render() returns something mountable\n // whether or not the template has been built yet: they are what detach()\n // collects between and what the deferred pass inserts before, exactly as\n // :if/:each anchors already work. That is what keeps render() and mount()\n // synchronous while the first render itself is allowed to wait\n content.append(this.startMarker, this.endMarker)\n this.content = content\n if (allSync) {\n // nothing is pending, so the template is built on this stack - the\n // ordinary case, and byte-for-byte the timing render() has always had.\n //\n // Written out rather than routed through the closure below on purpose: a\n // component that nests itself recurses through here, so one extra frame\n // per level is one fewer level before the stack gives out - enough, when\n // this was a shared `paint()`, to overflow *underneath* the depth guard\n // at MAX_NESTING_DEPTH and turn a named error back into a RangeError\n this.endMarker.parentNode!.insertBefore(renderNodes(this.template, templateScope, fx, shadow), this.endMarker)\n this.renderDone = true\n this.settleMounted()\n } else {\n Promise.all(gates).then(() => {\n // destroy() nulls the markers and a re-render replaces them, so a gate\n // that opens after either one has nothing left to paint into\n if (marker !== this.startMarker) return\n this.endMarker!.parentNode!.insertBefore(renderNodes(this.template, templateScope, fx, shadow), this.endMarker!)\n this.renderDone = true\n this.settleMounted()\n })\n warnIfStuck(this, gates)\n }\n\n if (shadow) {\n this.styleEls = this.styles.map(style => {\n const el = document.createElement(\"style\")\n el.textContent = style.content // the source: a shadow root scopes it already\n return el\n })\n } else {\n this.styles.forEach(style => acquireStyle(headStyle(style)))\n this.ownsSharedStyles = true\n }\n\n return this\n }\n\n // renders (when needed) and attaches in one call: the component is rendered\n // on the first mount, and re-rendered fresh whenever `data` is passed.\n // mount(el) on an already-rendered component just re-attaches, keeping its\n // state - the detach()/mount() round trip. Rendering here keeps whichever\n // style mode was last used (document.head unless renderShadow/mountShadow\n // chose a shadow root)\n mount(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n const target = typeof parent === \"string\" ? $(parent) : parent\n if (!target) throw new Error(`mount target not found: ${parent}`)\n if (!this.content || data !== undefined) this.renderWith(data ?? {}, this.useShadow)\n return this.attach(target)\n }\n\n // like mount(), but renders with styles scoped to a shadow root on the\n // target instead of document.head\n mountShadow(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n const target = typeof parent === \"string\" ? $(parent) : parent\n if (!target) throw new Error(`mount target not found: ${parent}`)\n if (!this.content || data !== undefined || !this.useShadow) this.renderWith(data ?? {}, true)\n return this.attach(target)\n }\n\n private attach(target: Element | ShadowRoot | DocumentFragment): this {\n if (this.mountRoot) this.detach()\n\n const root = this.useShadow && target instanceof Element\n ? target.shadowRoot ?? target.attachShadow({ mode: \"open\" })\n : target\n if (this.useShadow) this.styleEls.forEach(el => root.appendChild(el))\n root.appendChild(this.content!)\n this.mountRoot = root\n this.settleMounted()\n return this\n }\n\n // `await $mounted()` means \"rendered and on the page\", so it waits for both -\n // whichever lands last calls this. In the ordinary synchronous flow the render\n // is already done and this is the attach; for a component whose first render\n // a script held back, it is the other way round\n private settleMounted() {\n if (this.renderDone && this.mountRoot) this.resolveMounted?.()\n }\n\n // detaches from the DOM while keeping all state; a later mount() re-attaches\n // with any updates that happened while detached already applied\n detach(): this {\n if (!this.mountRoot || !this.content || !this.startMarker || !this.endMarker) return this\n\n // move everything between the markers (inclusive) back into the holding\n // fragment - including nodes :if/:each inserted after mounting\n let node: Node | null = this.startMarker\n while (node) {\n const nextNode: Node | null = node.nextSibling\n this.content.appendChild(node)\n if (node === this.endMarker) break\n node = nextNode\n }\n\n this.mountRoot = null\n return this\n }\n\n destroy(): this {\n this.detach()\n this.fx?.dispose()\n this.fx = null\n // a store this component was handed (a shared `$reactive`) outlives it, and\n // holds a listener per store that nested it - drop this instance's\n this.data?.$dispose()\n this.styleEls.forEach(el => el.parentNode?.removeChild(el))\n this.styleEls = []\n if (this.ownsSharedStyles) {\n this.styles.forEach(style => releaseStyle(headStyle(style)))\n this.ownsSharedStyles = false\n }\n this.content = null\n this.startMarker = null\n this.endMarker = null\n this.renderDone = false\n this.data = null\n this.resolveMounted = null\n return this\n }\n}\n\n// what Component79.fetch() hands back: a component that hasn't arrived yet.\n//\n// Every method queues onto the fetch and returns the handle, so a whole page\n// is one expression and the calls run in the order they were written:\n//\n// C79.fetch(\"./app.html\").on(\"save\", persist).mount(\"main\", { user })\n//\n// It is also thenable, resolving to the Component79 itself - which is what\n// keeps `await Component79.fetch(url)` (and importResource, and a handle\n// dropped into Promise.all) working exactly as before. Queued calls keep the\n// resolved value, so awaiting a chain gives the mounted component.\n//\n// The catch: mount() here returns the handle, not the component - there is no\n// component yet to return. That's why the whole lifecycle is on the handle and\n// not just mount(): nobody should have to await merely to destroy something.\nexport class PendingComponent79 {\n // the fetch with every queued call chained onto it, each passing the\n // component through - so `chain` always settles to the component, however\n // many calls were queued, and a failure anywhere rejects the rest\n private chain: Promise<Component79>\n\n constructor(component: Promise<Component79>) {\n this.chain = component\n }\n\n private queue(action: (component: Component79) => void): this {\n this.chain = this.chain.then(component => {\n action(component)\n return component\n })\n return this\n }\n\n then<TResult1 = Component79, TResult2 = never>(\n onfulfilled?: ((value: Component79) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.chain.then(onfulfilled, onrejected)\n }\n\n // a chain nobody awaits reports a failed fetch as an unhandled rejection,\n // like any dropped promise chain - these are for callers who'd rather handle\n // it. catch() returns a promise, not a handle: the chain ends here\n catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<Component79 | TResult> {\n return this.chain.catch(onrejected)\n }\n\n finally(onfinally?: (() => void) | null): Promise<Component79> {\n return this.chain.finally(onfinally)\n }\n\n mount(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n return this.queue(component => component.mount(parent, data))\n }\n\n mountShadow(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n return this.queue(component => component.mountShadow(parent, data))\n }\n\n render(data: Record<string, any> = {}): this {\n return this.queue(component => component.render(data))\n }\n\n renderShadow(data: Record<string, any> = {}): this {\n return this.queue(component => component.renderShadow(data))\n }\n\n on(eventName: string, listener: EmitListener): this {\n return this.queue(component => component.on(eventName, listener))\n }\n\n off(eventName: string, listener: EmitListener): this {\n return this.queue(component => component.off(eventName, listener))\n }\n\n detach(): this {\n return this.queue(component => component.detach())\n }\n\n destroy(): this {\n return this.queue(component => component.destroy())\n }\n}\n\nexport { Component79 as C79 }\n\nexport const parseComponent = (component: string): Component79 => new Component79(component)\n\n// library helpers injected into setup scripts. They behave like extra\n// globals: a same-named scope property (render data or a top-level\n// declaration) shadows them\nconst SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, Component79 }\n\n// the hot-reload handshake. jq79/dev serves a classic script that sets the flag\n// below; classic scripts run before deferred module ones, so the flag is always\n// set before this module evaluates. The page's copy of the runtime can come from\n// anywhere - a CDN, an import map, dist/ - and the dev client has no way to\n// import *that* copy, so the runtime hands itself to the client instead\nif (typeof globalThis !== \"undefined\" && (globalThis as any)[HOT_FLAG]) enableHotReload()\n\n","// DOM helpers: tiny query/create utilities, also injected into component\n// scripts as $, $$ and $create\n\n// $(selector) queries the document; $(el, selector) queries within el. The\n// selector is required in the element form - an empty one is a SyntaxError\nexport function $(selector: string): Element | null\nexport function $(el: Element, selector: string): Element | null\nexport function $(selectorOrEl: string | Element, selector?: string): Element | null {\n return typeof selectorOrEl === \"string\"\n ? document.querySelector(selectorOrEl)\n : selectorOrEl.querySelector(selector!)\n}\n\nexport function $$(selector: string): Element[]\nexport function $$(el: Element, selector: string): Element[]\nexport function $$(selectorOrEl: string | Element, selector?: string): Element[] {\n return Array.from(\n typeof selectorOrEl === \"string\"\n ? document.querySelectorAll(selectorOrEl)\n : selectorOrEl.querySelectorAll(selector!)\n )\n}\n\n// $create(tag, attrs): attrs are set as attributes, except className, which\n// may be a string or an array of class names.\nexport const $create = (tag: string, attrs: Record<string, any> = {}): HTMLElement => {\n const el = document.createElement(tag);\n for (const [name, value] of Object.entries(attrs)) {\n if (name === 'className') {\n el.className = Array.isArray(value) ? value.join(' ') : value;\n } else if (name === 'textContent') {\n el.textContent = value;\n } else if (name === 'children') {\n for (const child of value) {\n el.appendChild(child);\n }\n } else {\n el.setAttribute(name, value);\n }\n }\n return el;\n};\n\nconst ALLOWED_TAGS = new Set([\n 'a', 'b', 'i', 'em', 'strong', 'p', 'br', 'ul', 'ol', 'li',\n 'blockquote', 'code', 'pre', 'span', 'div', 'h1', 'h2', 'h3',\n 'h4', 'h5', 'h6', 'img'\n]);\n\nconst ALLOWED_ATTR: Record<string, Set<string>> = {\n a: new Set(['href', 'title']),\n img: new Set(['src', 'alt']),\n '*': new Set(['class']), // atributos permitidos en cualquier tag\n};\n\nconst SAFE_URL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);\n\nexport function isSafeUrl(value: string): boolean {\n try {\n // resolver relativo a algo neutro para poder leer el protocolo\n const url = new URL(value, 'https://example.com');\n return SAFE_URL_PROTOCOLS.has(url.protocol);\n } catch {\n return false;\n }\n}\n\n// la política de destinos: decide si un href/src ya seguro por protocolo\n// puede apuntar a donde apunta. Restringe *sobre* el chequeo de protocolo,\n// nunca en su lugar\nexport type AllowUrl = (url: URL, tag: string, attr: string) => boolean;\n\nexport type SanitizeOptions = { allowUrl?: AllowUrl };\n\nconst DEFAULT_PORTS: Record<string, string> = { 'https:': '443', 'http:': '80' };\n\ntype HostPattern = { host: RegExp; port: string | null };\n\n// \"host[:puerto]\": `*` casa exactamente UNA etiqueta dns - la regla de los\n// certificados TLS, no la de CSP: *.germade.dev casa a.germade.dev, pero ni\n// germade.dev (escribe los dos para incluir el apex) ni a.b.germade.dev.\n// Sin puerto casa cualquiera; un patrón inválido devuelve null y no casa\n// nada - una política rota cierra, no abre\nfunction compileHostPattern(pattern: string): HostPattern | null {\n const match = pattern.trim().toLowerCase().match(/^([a-z\\d*][a-z\\d.*-]*?)(?::(\\d{1,5}|\\*))?$/);\n if (!match) return null;\n const [, host, port] = match;\n const labels = host.split('.');\n if (labels.some(label => label !== '*' && !/^[a-z\\d-]+$/.test(label))) return null;\n // las etiquetas validadas no llevan metacaracteres de regex, así que no\n // hay nada que escapar; los puntos los pone el join\n const re = new RegExp(`^${labels.map(label => (label === '*' ? '[^.]+' : label)).join('\\\\.')}$`);\n return { host: re, port: !port || port === '*' ? null : port };\n}\n\n// compila una lista de patrones (string separado por comas, o array) en un\n// predicado AllowUrl. El puerto comparado es el *efectivo* de la URL (el\n// explícito, o el del esquema), así \"germade.dev:443\" casa https://germade.dev.\n// Una URL sin host (mailto:) no casa ningún patrón: los patrones hablan de\n// hosts - la forma función de la política puede admitirla si quiere\nexport const allowedHosts = (patterns: string | string[]): AllowUrl => {\n const compiled = (Array.isArray(patterns) ? patterns : patterns.split(','))\n .map(compileHostPattern)\n .filter((p): p is HostPattern => p !== null);\n return url => {\n const host = url.hostname.toLowerCase();\n const port = url.port || DEFAULT_PORTS[url.protocol] || '';\n return compiled.some(p => p.host.test(host) && (p.port === null || p.port === port));\n };\n};\n\n// consulta la política con la URL resuelta contra la página, para que una\n// URL relativa se juzgue como el destino same-origin que realmente es. Un\n// predicado que lanza, o una URL que no parsea, es un no\nfunction consultAllowUrl(allowUrl: AllowUrl, value: string, tag: string, attr: string): boolean {\n try {\n return !!allowUrl(new URL(value, document.baseURI), tag, attr);\n } catch {\n return false;\n }\n}\n\n// el saneado es recursivo, así que la profundidad del input es profundidad\n// de pila. 512 es lo que toleran los parsers de los navegadores antes de\n// aplanar el anidamiento, con lo que ningún documento legítimo pierde nada -\n// y superar el límite lanza un RangeError con nombre, en vez de reventar la\n// pila en algún punto indeterminado más arriba\nconst MAX_SANITIZE_DEPTH = 512;\n\n// copia los hijos de `source` en `target`, saneando los elementos y clonando\n// el texto; cualquier otra cosa (comentarios, etc.) se descarta\nfunction appendSanitizedChildren(source: ParentNode, target: HTMLElement, depth: number, allowUrl?: AllowUrl): void {\n if (depth > MAX_SANITIZE_DEPTH) {\n throw new RangeError(`jq79: sanitizeHTML input nests deeper than ${MAX_SANITIZE_DEPTH} elements`);\n }\n for (const child of Array.from(source.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n const sanitizedChild = sanitizeNode(child as HTMLElement, depth, allowUrl);\n if (sanitizedChild) target.appendChild(sanitizedChild);\n } else if (child.nodeType === Node.TEXT_NODE) {\n target.appendChild(child.cloneNode());\n }\n }\n}\n\n// sanea un elemento (los llamadores solo pasan nodos ELEMENT_NODE)\nfunction sanitizeNode(node: HTMLElement, depth: number, allowUrl?: AllowUrl): HTMLElement | null {\n const tag = node.tagName.toLowerCase();\n if (!ALLOWED_TAGS.has(tag)) return null; // tag no permitido → se descarta el nodo entero\n\n const clean = document.createElement(tag);\n\n for (const attr of Array.from(node.attributes)) {\n const name = attr.name.toLowerCase();\n const allowedForTag = ALLOWED_ATTR[tag]?.has(name);\n const allowedGlobal = ALLOWED_ATTR['*']?.has(name);\n if (!allowedForTag && !allowedGlobal) continue;\n\n if (name === 'href' || name === 'src') {\n if (!isSafeUrl(attr.value)) continue;\n if (allowUrl && !consultAllowUrl(allowUrl, attr.value, tag, name)) continue;\n }\n\n clean.setAttribute(name, attr.value);\n }\n\n // fuerza rel seguro en enlaces (target nunca se copia: no está permitido)\n if (tag === 'a') clean.setAttribute('rel', 'noopener noreferrer');\n\n appendSanitizedChildren(node, clean, depth + 1, allowUrl);\n\n return clean;\n}\n\nexport function sanitizeHTML(html: string, options?: SanitizeOptions): string {\n // parsear con <template> en vez de con DOMParser: el contenido de un template\n // es un documento inerte igual (ni scripts ni imágenes se ejecutan al asignar\n // innerHTML), pero el parseo de fragmento conserva el espacio en blanco inicial\n // que el modo \"before body\" de un documento completo descartaría - así una\n // primera línea indentada (un diff, un <pre>) llega con su sangría intacta\n const template = document.createElement('template');\n template.innerHTML = html;\n const container = document.createElement('div');\n\n appendSanitizedChildren(template.content, container, 0, options?.allowUrl);\n\n return container.innerHTML;\n}","// the reactive store ($reactive): proxy-based deep reactivity with\n// dot-path dependency tracking, plus the effect-scope helper the renderer\n// uses to tear down a subtree's bindings in one call\n\ntype ChangeListener = (value: any, dotKey: string) => void\ntype AnyChangeListener = (dotKey: string, value: any) => void\ntype ListenerOptions = { immediate?: boolean }\ntype Unsubscribe = () => void\n\nexport type ReactiveDeepData<T> = T & {\n $on: (dotKey: string, listener: ChangeListener, options?: ListenerOptions) => Unsubscribe\n $onAny: (listener: AnyChangeListener, options?: ListenerOptions) => Unsubscribe\n // runs `run` immediately, recording every dotKey it reads off this store, then\n // re-runs it whenever a changed dotKey overlaps one of those - see pathsOverlap.\n // `alsoWakenBy` registers the same effect with other stores as well, so a\n // change in any of them wakes it too (see ATTACH)\n $effect: (run: () => void, alsoWakenBy?: Record<string, any>[]) => Unsubscribe\n // drops this store's subscriptions to the stores nested inside it (see\n // bridge). A store that outlives the one holding it - the shared-state case -\n // would otherwise keep the dead holder's listeners on its own list forever\n $dispose: () => void\n}\n\nconst getByPath = (obj: Record<string, any>, dotKey: string): any =>\n dotKey.split(\".\").reduce((acc, key) => (acc == null ? undefined : acc[key]), obj)\n\n// only plain objects and arrays get deep-wrapped by the reactive store;\n// class instances (Component79, Date, DOM nodes, ...) pass through untouched\n// so their identity, prototypes and internals stay intact\nconst isPlainData = (value: object): boolean => {\n if (Array.isArray(value)) return true\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nconst walkLeaves = (obj: Record<string, any>, path: string, visit: (dotKey: string, value: any) => void) => {\n Object.entries(obj).forEach(([key, value]) => {\n const dotKey = path ? `${path}.${key}` : key\n if (value && typeof value === \"object\" && isPlainData(value)) walkLeaves(value, dotKey, visit)\n else visit(dotKey, value)\n })\n}\n\n// true when `a` and `b` sit on the same ancestor/descendant line, e.g.\n// \"user\" & \"user.address.city\" (a change to either affects the other) - false\n// for siblings like \"user.name\" & \"user.age\"\nconst pathsOverlap = (a: string, b: string): boolean =>\n a === b || a.startsWith(`${b}.`) || b.startsWith(`${a}.`)\n\n// reads the raw object behind a store proxy. Module-level (not per-store) so a\n// value that is already reactive - in this store or in another one - can be\n// unwrapped before being wrapped again. Without it, handing the same object to\n// two stores has each one wrapping the other's proxies, and since a wrap walks\n// what it wraps, the nesting compounds until the process stops responding\nconst RAW = Symbol(\"jq79.raw\")\n\n// a free function rather than a method on the store, because the store API is\n// served from the root proxy alone (see storeApi): `store.$toRaw()` would work\n// and `store.user.$toRaw()` would not, which is the case callers actually have.\n// The RAW symbol travels on every proxy at every depth, so this works anywhere.\n// What it returns is the real object, not a copy: writes to it notify nobody\nexport const $toRaw = <T>(value: T): T => {\n let raw: any = value\n while (raw !== null && typeof raw === \"object\" && raw[RAW]) raw = raw[RAW]\n return raw\n}\n\n// marks a store's *root* proxy. A store put inside another store (a setup\n// script's `const local = $reactive(...)`) has to pass through whole: it owns\n// its listeners and its $on/$effect, so unwrapping it would strip away the very\n// thing it is. Nested proxies carry no such marker and are unwrapped freely\nconst STORE = Symbol(\"jq79.store\")\n\nconst isStore = (value: any): boolean =>\n value !== null && typeof value === \"object\" && value[STORE] === true\n\n// active $effect() runs, innermost last - a module-level stack (rather than\n// one per store) so nested effects across stores still nest correctly; reads\n// during a proxy's `get` trap are attributed to whichever run is on top\nconst trackerStack: Set<string>[] = []\n\n// runs fn with dependency tracking suspended - reads inside it are attributed\n// to a throwaway set instead of the currently running effect\nexport const untracked = <T>(fn: () => T): T => {\n trackerStack.push(new Set())\n try {\n return fn()\n } finally {\n trackerStack.pop()\n }\n}\n\ntype Effect = { deps: Set<string>; run: () => void }\n\n// an effect lives in exactly one store's `effects` set - the one whose\n// $effect created it - and only that store's notify walks it. Content that\n// reads two stores at once (a component's slot content: the parent's names\n// plus the slot props the child passes it) needs one record in both sets, so\n// a store serves this attach handle beside $on/$effect. Tracking already\n// spans stores - trackerStack is module-level, so one run's deps are whatever\n// it read, wherever it read it - only the waking didn't.\n//\n// Named like the compiled scripts' internals ($__effect, $__import) because it\n// is one: `key in store` never answers true for a storeApi name, so `with`\n// can't see it and no template expression can reach it.\n//\n// The cost, accepted: deps are dot-paths with no store namespace, so a name\n// that exists in both stores wakes the effect from either. A spurious re-run,\n// never a stale render\nconst ATTACH = \"$__attach\"\n\n// the extra stores every effect created off a scope must be attached to. Read\n// by createEffectScope off the scope it is given, so a scope can hand the\n// arrangement down to whatever renders inside it (nested :each item scopes,\n// a nested component's prop-sync effects) without every call site knowing\nexport const ALSO_WAKEN_BY = Symbol(\"jq79.alsoWakenBy\")\n\nexport const $reactive = <T extends Record<string, any>>(data: T): ReactiveDeepData<T> => {\n const exactListeners = new Map<string, Set<ChangeListener>>()\n const anyListeners = new Set<AnyChangeListener>()\n const effects = new Set<Effect>()\n\n // one proxy per raw object, for this store alone. Keyed by the *raw object*\n // rather than by its path, so identity travels with the object: :each diffs\n // its items by reference (Object.is), and a reordered list has to hand back\n // the same proxy for the same item or every row would re-render. The flip\n // side is that an object's path is fixed when it is first wrapped, so after a\n // reorder its notifications carry the old index - effects that read the list\n // itself still wake up (pathsOverlap), which is what makes it a non-issue in\n // practice\n const proxies = new WeakMap<object, Record<string, any>>()\n\n // $on/$onAny/$effect are served from the root proxy's `get` instead of being\n // defined on the object: a store must leave nothing behind on the data it was\n // handed, and two stores over one object would otherwise clobber each other's\n // handles. Null-prototype, so `key in storeApi` can't match Object.prototype\n const storeApi: Record<string, any> = Object.create(null)\n\n const notify = (dotKey: string, value: any, isNewKey = false) => {\n exactListeners.get(dotKey)?.forEach(listener => listener(value, dotKey))\n anyListeners.forEach(listener => listener(dotKey, value))\n effects.forEach(effect => {\n // a newly-created key re-runs every effect: an effect that read the\n // name while it didn't exist couldn't track it (`with` skipped the\n // store entirely), so dep matching would never wake it up\n if (isNewKey || Array.from(effect.deps).some(dep => pathsOverlap(dep, dotKey))) effect.run()\n })\n }\n\n const isWrappable = (value: any): value is Record<string, any> =>\n value !== null && typeof value === \"object\" && isPlainData(value)\n\n // a store nested inside this one keeps its own listeners and its own effects,\n // and this store's effects are not among them - so a write through the inner\n // store notifies nobody out here, and a component rendering `{{ cart.items }}`\n // off a `$reactive` it was handed would never update. The holder subscribes\n // instead, and re-notifies the inner store's changes under the path it sits at\n // (\"items.0\" -> \"cart.items.0\"). An effect that read through `cart` recorded\n // exactly that path's ancestor as a dependency, so pathsOverlap wakes it.\n // Chains compose: re-notifying runs this store's own $onAny listeners, which\n // is how a store two levels down still reaches the top\n const bridges = new Map<string, { store: any; unsubscribe: Unsubscribe }>()\n\n const bridge = (store: any, path: string) => {\n const current = bridges.get(path)\n if (current?.store === store) return\n current?.unsubscribe()\n bridges.set(path, {\n store,\n unsubscribe: store.$onAny((dotKey: string, value: any) => notify(`${path}.${dotKey}`, value)),\n })\n }\n\n // the key no longer holds the store it held: stop listening to it\n const unbridge = (path: string) => {\n bridges.get(path)?.unsubscribe()\n bridges.delete(path)\n }\n\n // the reactive view of `raw`, created on demand. Callers must hand it a raw\n // object (see $toRaw at both call sites): wrapping a proxy is what compounds\n const wrap = (raw: Record<string, any>, path: string): Record<string, any> => {\n const cached = proxies.get(raw)\n if (cached) return cached\n\n // keys that were deleted off this object. `with ($scope)` resolves a name\n // through [[HasProperty]], so without a claim here a deleted key would fall\n // through to globalThis and the *whole* expression would die of\n // ReferenceError - `user ? user.name : \"none\"` must take its else branch\n // instead. The cost: `\"user\" in store` stays true after a delete\n let tombstones: Set<string> | null = null\n\n const proxy: Record<string, any> = new Proxy(raw, {\n has(target, key) {\n return Reflect.has(target, key) || (typeof key === \"string\" && tombstones?.has(key) === true)\n },\n get(target, key, receiver) {\n if (key === RAW) return target\n if (key === STORE) return path === \"\"\n if (typeof key !== \"string\") return Reflect.get(target, key, receiver)\n if (path === \"\" && key in storeApi) return storeApi[key]\n\n const dotKey = path ? `${path}.${key}` : key\n trackerStack[trackerStack.length - 1]?.add(dotKey)\n\n // nested objects are wrapped here rather than up front, so the object\n // handed to $reactive is never rewritten\n const value = Reflect.get(target, key, receiver)\n if (isStore(value)) {\n bridge(value, dotKey)\n return value\n }\n\n const raw = $toRaw(value)\n return isWrappable(raw) ? wrap(raw, dotKey) : raw\n },\n set(target, key: string, value, receiver) {\n // an assignment delegated up the prototype chain from a derived scope\n // (Object.create(store) child, or a wrapping proxy): if the key isn't\n // a real property of this store, honor the receiver so the new binding\n // lands on the derived scope - a scope-local variable, not a store\n // mutation, so no notify. If the key IS a store property, fall through\n // and mutate the store itself regardless of receiver, so assignments\n // like @click=\"count = count + 1\" work from any nested scope\n if (receiver !== proxy && !Object.prototype.hasOwnProperty.call(target, key)) {\n return Reflect.set(target, key, value, receiver)\n }\n\n const dotKey = path ? `${path}.${key}` : key\n // store the raw value, never a proxy - including one of our own, so\n // that `list = [list[1], list[0]]` doesn't write proxies back into the\n // data. Reads re-wrap it, from the cache, as the very same proxy. A\n // whole store assigned in is the exception: it stays as it is\n const stored = isStore(value) ? value : $toRaw(value)\n const isNewKey = !Object.prototype.hasOwnProperty.call(target, key)\n // a primitive write that changes nothing notifies nobody: it's what\n // lets an effect write the value it just read (a normalizing\n // assignment, a prop sync) and settle instead of waking itself\n // forever. Only primitives and functions: re-writing the SAME object\n // reference stays loud, because that is the cross-store \"deep touch\"\n // channel - a parent's prop sync forwards `user.name = x` to the\n // child's store by re-assigning the same `user`, and the child's\n // listeners live on the child's store, not the parent's. A new key\n // always announces itself - the sweep is its whole point\n if (!isNewKey && Object.is(target[key], stored) && (stored === null || typeof stored !== \"object\")) return true\n target[key] = stored\n tombstones?.delete(key) // the key exists again: no claim needed\n if (isStore(stored)) bridge(stored, dotKey)\n else unbridge(dotKey)\n const notified = isStore(stored) || !isWrappable(stored) ? stored : wrap(stored, dotKey)\n notify(dotKey, notified, isNewKey)\n return true\n },\n // `delete data.user` is a plain-object mutation like any other, so it\n // notifies like one - with `undefined`, which is what a read returns\n // afterwards. Array methods that shrink (pop, splice) delete their dead\n // slots through this trap too. No new-key sweep: whoever depended on the\n // key tracked it while it existed, so dep matching wakes exactly them\n deleteProperty(target, key) {\n if (typeof key !== \"string\") return Reflect.deleteProperty(target, key)\n const had = Object.prototype.hasOwnProperty.call(target, key)\n const deleted = Reflect.deleteProperty(target, key)\n if (deleted && had) {\n const dotKey = path ? `${path}.${key}` : key\n ;(tombstones ??= new Set()).add(key)\n unbridge(dotKey) // a nested store it held: stop listening to it\n notify(dotKey, undefined)\n }\n return deleted\n }\n })\n\n proxies.set(raw, proxy)\n return proxy\n }\n\n const reactive = wrap($toRaw(data), \"\") as ReactiveDeepData<T>\n\n // a store handed in with the data (a prop, or render data) is bridged here\n // rather than on first read, so a listener registered before anything reads\n // the key still hears it. Only the top level is scanned: that's where a prop\n // lands, and descending would mean walking whatever else was handed in - a\n // highlighter, an API client - to its leaves. A store sitting deeper is\n // bridged when the read that reaches it wraps its parent\n Object.entries($toRaw(data)).forEach(([key, value]) => {\n if (isStore(value)) bridge(value, key)\n })\n\n const $on = (dotKey: string, listener: ChangeListener, { immediate = false }: ListenerOptions = {}): Unsubscribe => {\n if (!exactListeners.has(dotKey)) exactListeners.set(dotKey, new Set())\n exactListeners.get(dotKey)!.add(listener)\n if (immediate) listener(getByPath(reactive, dotKey), dotKey)\n return () => exactListeners.get(dotKey)?.delete(listener)\n }\n\n const $onAny = (listener: AnyChangeListener, { immediate = false }: ListenerOptions = {}): Unsubscribe => {\n anyListeners.add(listener)\n if (immediate) walkLeaves(reactive, \"\", (dotKey, value) => listener(dotKey, value))\n return () => anyListeners.delete(listener)\n }\n\n const $effect = (run: () => void, alsoWakenBy?: Record<string, any>[]): Unsubscribe => {\n // a notify landing while this effect runs (an item's render writing to\n // the store, waking the very effect that is rendering it) must not\n // re-enter mid-run - the half-done run would race its own repeat over\n // shared state, which is how :each once tripled its rows. It marks the\n // run dirty instead, and repeats *after* it finishes, against settled\n // state, until clean. Still fully synchronous: everything happens before\n // the triggering assignment returns\n let running = false\n let dirty = false\n const effect: Effect = {\n deps: new Set(),\n run: () => {\n if (running) {\n dirty = true\n return\n }\n running = true\n try {\n let cycles = 0\n do {\n dirty = false\n const deps = new Set<string>()\n trackerStack.push(deps)\n try {\n run()\n } finally {\n trackerStack.pop()\n effect.deps = deps\n }\n } while (dirty && ++cycles < 100)\n // an effect that keeps writing its own dependencies used to die by\n // stack overflow; now it is cut off and named\n if (dirty) console.error(\"jq79: an effect re-woke itself 100 times in a row (it writes what it reads); giving up on it settling\")\n } finally {\n running = false\n }\n },\n }\n effects.add(effect)\n // the shared case is rare (only slot content asks for it) and this\n // function is on the stack for as long as whatever it renders - a\n // component that renders itself stacks 200 of these - so it keeps the\n // shape it had, and the extra bookkeeping lives in its own frame\n if (alsoWakenBy?.length) return attachAndRun(effect, alsoWakenBy)\n effect.run()\n return () => { effects.delete(effect) }\n }\n\n // attached before the first run, so a store that notifies during it (a setup\n // script's write, a prop sync) reaches this effect like any other\n const attachAndRun = (effect: Effect, alsoWakenBy: Record<string, any>[]): Unsubscribe => {\n const detach = alsoWakenBy.map(store => store?.[ATTACH]?.(effect)).filter(Boolean) as Unsubscribe[]\n effect.run()\n return () => {\n effects.delete(effect)\n detach.forEach(drop => drop())\n }\n }\n\n const $__attach = (effect: Effect): Unsubscribe => {\n effects.add(effect)\n return () => { effects.delete(effect) }\n }\n\n const $dispose = () => {\n bridges.forEach(({ unsubscribe }) => unsubscribe())\n bridges.clear()\n }\n\n storeApi.$on = $on\n storeApi.$onAny = $onAny\n storeApi.$effect = $effect\n storeApi.$dispose = $dispose\n storeApi[ATTACH] = $__attach\n\n return reactive\n}\n// groups the disposers of every $effect created for one rendered subtree\n// (an :if branch, an :each item, ...) so the whole subtree's bindings can be\n// torn down in one call when that subtree is replaced/removed. `scope.$effect`\n// resolves through the prototype chain up to the root store no matter how\n// many nested :each scopes sit in between (see renderEach's itemScope)\nexport type EffectScope = {\n effect: (run: () => void) => void\n // registers an arbitrary cleanup (e.g. destroying a nested component) to\n // run when this subtree is torn down\n onDispose: (fn: Unsubscribe) => void\n // re-runs every effect registered on this scope, nested scopes excluded:\n // how :each tells a reused, repositioned entry's dep-less bindings (the\n // `{{ $index }}`-only case) about their move. Deps stay as they were -\n // callers run it untracked\n refresh: () => void\n dispose: () => void\n}\n\nexport const createEffectScope = (scope: Record<string, any>): EffectScope => {\n const disposers: Unsubscribe[] = []\n const runs: (() => void)[] = []\n // whatever the scope was handed (slot content is the only thing that sets\n // it today): the stores this scope's effects belong to besides their own.\n // Left undefined when there are none, which is $effect's fast path\n const alsoWakenBy: Record<string, any>[] | undefined = (scope as any)[ALSO_WAKEN_BY]\n return {\n effect: run => {\n disposers.push(scope.$effect(run, alsoWakenBy))\n runs.push(run)\n },\n onDispose: fn => { disposers.push(fn) },\n refresh: () => { runs.forEach(run => run()) },\n dispose: () => {\n disposers.splice(0).forEach(dispose => dispose())\n runs.length = 0\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// :setup script transform\n//\n// setup scripts are written like Svelte components:\n//\n// let firstName = null\n// $: fullName = `${firstName} ${lastName}`\n// fetchUser().then(user => { firstName = user.firstName })\n//\n// and are executed inside `with ($scope)` against the component's reactive\n// store, so plain assignments (even from async callbacks) go through the\n// proxy's set trap and re-render whatever depends on them. To make that work\n// the source is lightly rewritten - no full JS parser, just a scanner that is\n// string/comment-aware and only touches code at brace/paren depth 0:\n// - `let/var/const x = ...` at the top level loses its keyword, becoming a\n// scope assignment (the name is pre-declared on the store so the `with`\n// lookup resolves it)\n// - `$: x = expr` becomes `$__effect(() => { x = expr })`, re-running when a\n// dependency read inside expr changes ($__effect is deliberately NOT a\n// property of the scope, so `with` falls through to the function parameter)\n// ---------------------------------------------------------------------------\n\ntype SetupTransform = { vars: string[]; code: string }\n\n// a declaration whose target is an identifier (`let x`), an object pattern\n// (`let { a }`, space optional) or an array pattern (`let [x]`)\nconst DECLARATION_START_RE = /(?:let|var|const)(?:\\s+(?=[A-Za-z_$])|\\s*(?=[{[]))/y\nconst REACTIVE_LABEL_RE = /\\$:\\s*/y\nconst IMPORT_CALL_RE = /import(?=\\s*\\()/y\nconst REACTIVE_ASSIGN_RE = /\\$:\\s*([A-Za-z_$][\\w$]*)\\s*=(?!=)/y\n\nconst skipString = (src: string, start: number): number => {\n const quote = src[start]\n let i = start + 1\n while (i < src.length) {\n if (src[i] === \"\\\\\") { i += 2; continue }\n if (src[i] === quote) return i + 1\n i++\n }\n return src.length\n}\n\nconst skipLineComment = (src: string, start: number): number => {\n const end = src.indexOf(\"\\n\", start)\n return end === -1 ? src.length : end\n}\n\nconst skipBlockComment = (src: string, start: number): number => {\n const end = src.indexOf(\"*/\", start + 2)\n return end === -1 ? src.length : end + 2\n}\n\n// index of the next thing that isn't whitespace or a comment\nconst skipToToken = (src: string, start: number): number => {\n let i = start\n while (i < src.length) {\n if (/\\s/.test(src[i])) { i++; continue }\n if (src[i] === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (src[i] === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n break\n }\n return i\n}\n\n// ---------------------------------------------------------------------------\n// regex literals. The scanners walk the source counting bracket depth, and a\n// regex walked as if it were code poisons that count: `split(/\\//)` puts two\n// slashes side by side (a line comment, as far as a scanner knows) and the\n// `)` after them is skipped uncounted; `/[(]/` inflates the depth for good.\n// So a `/` that opens a regex is consumed whole - and whether it opens one is\n// the classic lexer call, made the way every tokenizer makes it: by what came\n// before. Division needs a completed expression on its left; everywhere else\n// a `/` can only be a regex.\n// ---------------------------------------------------------------------------\n\n// reserved words a regex can follow. Reserved only - `of` is not (`const of\n// = 4; of / 2` is legal division), so `for (x of /re/)` stays unrescued\n// rather than risking real code\nconst REGEX_AFTER_WORD = new Set([\n \"return\", \"typeof\", \"case\", \"in\", \"instanceof\", \"new\", \"delete\", \"void\", \"do\", \"else\", \"yield\", \"await\",\n])\n\n// whether a `/` at `at` opens a regex literal rather than a division: looks\n// backward past whitespace and block comments for the last meaningful thing.\n// A completed expression - identifier, number, closing quote or bracket,\n// postfix ++/-- - takes division; a reserved word or any other punctuator\n// admits a regex. Only consulted for the rare `/` that is neither `//` nor\n// `/*`, so the scanners pay nothing on the common path\nconst regexAllowed = (src: string, at: number): boolean => {\n let i = at - 1\n while (i >= 0) {\n const ch = src[i]\n if (/\\s/.test(ch)) { i--; continue }\n if (ch === \"/\" && src[i - 1] === \"*\") {\n const open = src.lastIndexOf(\"/*\", i - 2)\n if (open === -1) return true // an unopened comment tail: malformed input\n i = open - 1\n continue\n }\n break\n }\n if (i < 0) return true // the start of the source starts an expression\n const ch = src[i]\n if (/[\\w$]/.test(ch)) {\n let start = i\n while (start > 0 && /[\\w$]/.test(src[start - 1])) start--\n return REGEX_AFTER_WORD.has(src.slice(start, i + 1))\n }\n if ((ch === \"+\" || ch === \"-\") && src[i - 1] === ch) return false // postfix ++/--\n return !\")]}\\\"'`.\".includes(ch)\n}\n\n// consumes a regex literal (with its flags): backslash escapes, and character\n// classes, where an unescaped `/` doesn't close the literal (`/[/]/` is one\n// regex). A literal can't contain an unescaped newline, so hitting one means\n// the classification was wrong or the input malformed - stop there, bounding\n// any damage to a single line\nconst skipRegex = (src: string, start: number): number => {\n let i = start + 1\n let inClass = false\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"\\\\\") { i += 2; continue }\n if (ch === \"\\n\") return i\n if (ch === \"[\") inClass = true\n else if (ch === \"]\") inClass = false\n else if (ch === \"/\" && !inClass) {\n i++\n while (i < src.length && /[a-z]/i.test(src[i])) i++ // flags\n return i\n }\n i++\n }\n return src.length\n}\n\n// tokens that can't *start* a statement, so a line beginning with one is\n// continuing the previous expression rather than opening a new statement -\n// the same call JS's automatic semicolon insertion makes. Unary-only forms\n// (!, ~, ++, --) are deliberately absent: those do start a statement, and JS\n// inserts the semicolon before them\nconst CONTINUATION_RE = /^(\\?\\.|\\?\\?|&&|\\|\\||\\*\\*|[.,+\\-*/%&|^<>=?:([])/\n\n// the last meaningful character before `at`: walks back past whitespace and\n// block comments, the way regexAllowed does. A line comment can't be skipped\n// from behind (its start is only findable forwards), so a line ending in one\n// reports the comment's text instead - callers treat that as \"not the char I\n// was looking for\", which degrades to ending the statement, exactly as\n// before this helper existed\nconst lastMeaningfulBefore = (src: string, at: number): string => {\n let i = at - 1\n while (i >= 0) {\n const ch = src[i]\n if (/\\s/.test(ch)) { i--; continue }\n if (ch === \"/\" && src[i - 1] === \"*\") {\n const open = src.lastIndexOf(\"/*\", i - 2)\n if (open === -1) return \"\"\n i = open - 1\n continue\n }\n return ch\n }\n return \"\"\n}\n\n// end of a statement starting at `start`: the first `;` or line break that\n// isn't inside a string/comment or unbalanced brackets. A line break only\n// ends the statement if the next line can't continue it, so leading-dot\n// method chains and multi-line operator chains stay in one piece:\n//\n// $: total = items\n// .filter(item => item.active) <- still the same statement\n// .length\n//\n// ...and only if the current line *can* end it: a line whose last meaningful\n// character is `,` or `=` left its expression incomplete (a multi-line\n// declarator list writes exactly this), so the statement continues - the\n// same ASI call as the leading-token check, made from the other side\nconst findStatementEnd = (src: string, start: number): number => {\n let depth = 0\n let i = start\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth--\n else if (depth <= 0 && ch === \";\") return i\n else if (depth <= 0 && ch === \"\\n\") {\n const next = skipToToken(src, i + 1)\n const continues =\n next < src.length &&\n (CONTINUATION_RE.test(src.slice(next, next + 2)) || [\",\", \"=\"].includes(lastMeaningfulBefore(src, i)))\n if (!continues) return i\n i = next\n continue\n }\n i++\n }\n return src.length\n}\n\n// ---------------------------------------------------------------------------\n// top-level declarations. `let x = 1` loses its keyword and becomes a scope\n// assignment (x pre-declared on the store). A destructuring declarator\n// becomes an *assignment pattern*: inside `with`, `({ a, b } = obj)` writes\n// every binding through the reactive proxy - which is what makes it reactive.\n// The parens keep the `{` from opening a block, and a leading `;` keeps the\n// `(` from gluing onto the previous line as a call. Multi-declarator\n// statements (`let a = 1, b = 2`) register every binding, not just the first.\n// These lean on the pattern helpers defined with the props signature below\n// (splitTopLevel, indexOfTopLevel, defaultAssignIndex); the scanner only\n// runs long after the module evaluates, so the order is cosmetic\n// ---------------------------------------------------------------------------\n\ntype Declarator = { raw: string; codeEnd: number }\n\n// splits a declarator list at top-level commas, keeping each segment's raw\n// text (layout and comments included) and where its last meaningful token\n// ends - the spot a closing paren must go, so a trailing comment can't\n// swallow it\nconst splitDeclarators = (src: string): Declarator[] => {\n const parts: Declarator[] = []\n let depth = 0\n let start = 0\n let lastEnd = 0\n const flush = (end: number) => {\n parts.push({ raw: src.slice(start, end), codeEnd: Math.max(0, lastEnd - start) })\n start = end + 1\n lastEnd = start\n }\n let i = 0\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); lastEnd = i; continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); lastEnd = i; continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth--\n else if (ch === \",\" && depth <= 0) { flush(i); i++; continue }\n if (!/\\s/.test(ch)) lastEnd = i + 1\n i++\n }\n flush(src.length)\n return parts\n}\n\n// the *binding* names a destructuring pattern declares - unlike\n// parsePropsPattern, which answers \"which props\" (the keys), this answers\n// \"which variables\": `{ a: x }` binds x, `{ a: { b } }` binds b,\n// `[x, ...rest]` binds x and rest. Defaults are stripped; what remains is a\n// nested pattern (recurse) or the bound identifier\nconst patternBindings = (src: string): string[] => {\n const pattern = src.trim()\n if (!pattern.startsWith(\"{\") && !pattern.startsWith(\"[\")) {\n return IDENTIFIER_RE.test(pattern) ? [pattern] : []\n }\n const names: string[] = []\n for (let part of splitTopLevel(pattern.slice(1, patternCloseIndex(pattern)))) {\n if (part.startsWith(\"...\")) part = part.slice(3).trim()\n const assign = defaultAssignIndex(part)\n if (assign !== -1) part = part.slice(0, assign).trim()\n if (pattern.startsWith(\"{\")) {\n const colon = indexOfTopLevel(part, \":\")\n if (colon !== -1) {\n names.push(...patternBindings(part.slice(colon + 1)))\n continue\n }\n }\n names.push(...patternBindings(part))\n }\n return names\n}\n\n// one `let/var/const` declarator list, rewritten to scope assignments.\n// Each segment's initializer is re-scanned so an `import()` inside it is\n// rewritten like anywhere else - nothing else can match in there, since a\n// nested top-level declaration inside a declarator is a SyntaxError in JS\nconst rewriteDeclarators = (src: string): SetupTransform => {\n const vars: string[] = []\n const rewritten = splitDeclarators(src).map(({ raw, codeEnd }) => {\n const lead = raw.match(/^\\s*/)![0]\n if (codeEnd <= lead.length) return { text: raw, empty: true }\n const body = raw.slice(lead.length, codeEnd)\n const tail = raw.slice(codeEnd)\n const assign = defaultAssignIndex(body)\n const target = (assign === -1 ? body : body.slice(0, assign)).trim()\n const isPattern = body[0] === \"{\" || body[0] === \"[\"\n if (isPattern) vars.push(...patternBindings(target))\n else if (IDENTIFIER_RE.test(target)) vars.push(target)\n const code = transformSetupScript(body).code\n return { text: `${lead}${isPattern ? `(${code})` : code}${tail}`, empty: false }\n })\n\n // a trailing comment-only segment (`let a = 1, // note` cut at its line\n // end) is re-attached without its comma, so the output stays a statement\n const tail: string[] = []\n while (rewritten.length && rewritten[rewritten.length - 1].empty) tail.unshift(rewritten.pop()!.text)\n let code = rewritten.map(part => part.text).join(\",\") + tail.join(\"\")\n if (code.trimStart().startsWith(\"(\")) code = `;${code}`\n return { vars, code }\n}\n\nexport const transformSetupScript = (src: string): SetupTransform => {\n const vars: string[] = []\n let out = \"\"\n let i = 0\n let depth = 0\n let atStatementStart = true\n\n while (i < src.length) {\n const ch = src[i]\n const next = src[i + 1]\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n const end = skipString(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n if (ch === \"/\" && (next === \"/\" || next === \"*\")) {\n const end = next === \"/\" ? skipLineComment(src, i) : skipBlockComment(src, i)\n out += src.slice(i, end)\n i = end\n continue\n }\n if (ch === \"/\" && regexAllowed(src, i)) {\n const end = skipRegex(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n\n // `import(...)` is a keyword form, so it can't be intercepted through the\n // scope - rewrite the identifier to the injected $__import (which loads\n // .html URLs as components via Component79.fetch and delegates the rest to\n // native import). The `(` is left for the scanner so depth stays balanced\n if (ch === \"i\" && (i === 0 || !/[\\w$.]/.test(src[i - 1]))) {\n IMPORT_CALL_RE.lastIndex = i\n if (IMPORT_CALL_RE.test(src)) {\n out += \"$__import\"\n i += \"import\".length\n atStatementStart = false\n continue\n }\n }\n\n if (depth === 0 && atStatementStart) {\n DECLARATION_START_RE.lastIndex = i\n const decl = DECLARATION_START_RE.exec(src)\n if (decl) {\n const start = i + decl[0].length\n const end = findStatementEnd(src, start)\n const { vars: names, code } = rewriteDeclarators(src.slice(start, end))\n vars.push(...names)\n out += code\n i = end\n atStatementStart = false\n continue\n }\n\n REACTIVE_LABEL_RE.lastIndex = i\n const label = REACTIVE_LABEL_RE.exec(src)\n if (label) {\n REACTIVE_ASSIGN_RE.lastIndex = i\n const assign = REACTIVE_ASSIGN_RE.exec(src)\n if (assign) vars.push(assign[1])\n const start = i + label[0].length\n const end = findStatementEnd(src, start)\n // the body is re-scanned rather than sliced raw, so an `import()`\n // inside it gets the $__import rewrite like anywhere else. Safe to\n // recurse: strings/comments/regexes copy through unchanged, and a\n // depth-0 declaration inside a labeled statement is a SyntaxError\n // in JS anyway, so nothing else can rewrite\n out += `$__effect(() => { ${transformSetupScript(src.slice(start, end)).code} });`\n i = end\n continue\n }\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n\n out += ch\n i++\n }\n\n return { vars, code: out }\n}\n\n// ---------------------------------------------------------------------------\n// factory scripts - a <script> whose top level has `export default` runs as a\n// plain lexical module instead of a `with`-scoped setup script: no implicit\n// reactivity, no `$:` labels - standard JS that editors and type-checkers\n// understand. The default export is called with the instance context\n// ({ $data, $effect, $emit, $mounted, $self, $$self }) and a returned object\n// is merged into the reactive store for the template to use.\n// Detection is backwards-safe: `export default` is a SyntaxError inside a\n// setup script, so no previously-working component can change behavior.\n// The same scanner rewrites the module-only syntax into a Function body:\n// - `export default X` -> `$__exports.default = X`\n// - `import d from \"m\"` -> `const d = $__default(await $__import(\"m\"))`\n// (and the other static clause forms), so imports resolve through the same\n// $__import as setup scripts: bundler map first, then fetch/native import\n// ---------------------------------------------------------------------------\n\nconst EXPORT_DEFAULT_RE = /export\\s+default(?![\\w$])/y\n// clause (default/namespace/named, no quotes or parens) + specifier; the\n// no-clause alternative requires the specifier right away, so dynamic\n// `import(...)` and `import.meta` never match\nconst STATIC_IMPORT_RE = /import\\s*(?:([\\w$\\s,{}*]+?)\\s*from\\s*)?([\"'])([^\"'\\n]+)\\2/y\n\n// splits an import clause on top-level commas: `d, { a, b as c }` keeps the\n// braced group together\nconst splitImportClause = (clause: string): string[] => {\n const parts: string[] = []\n let depth = 0\n let start = 0\n for (let i = 0; i <= clause.length; i++) {\n const ch = clause[i]\n if (ch === \"{\") depth++\n else if (ch === \"}\") depth--\n else if (i === clause.length || (ch === \",\" && depth === 0)) {\n const part = clause.slice(start, i).trim()\n if (part) parts.push(part)\n start = i + 1\n }\n }\n return parts\n}\n\n// one static import statement -> const bindings from the awaited module\nconst staticImportToAwait = (clause: string | undefined, spec: string, n: number): string => {\n const source = `await $__import(${JSON.stringify(spec)})`\n if (clause === undefined) return source // side-effect import\n const parts = splitImportClause(clause)\n const bindings: string[] = []\n let ref = source\n if (parts.length > 1) {\n const tmp = `$__mod${n}`\n bindings.push(`${tmp} = ${source}`)\n ref = tmp\n }\n for (const part of parts) {\n if (part.startsWith(\"{\")) bindings.push(`${part.replace(/\\s+as\\s+/g, \": \")} = ${ref}`)\n else if (part.startsWith(\"*\")) bindings.push(`${part.replace(/^\\*\\s*as\\s+/, \"\")} = ${ref}`)\n else bindings.push(`${part} = $__default(${ref})`)\n }\n return `const ${bindings.join(\", \")}`\n}\n\n// ---------------------------------------------------------------------------\n// the component's prop signature\n//\n// A component declares the props it takes as a destructuring pattern, in the\n// place each script mode already puts its inputs: the `:setup` attribute's\n// value, or the factory's *first* parameter (the ctx moved to the second).\n// Position is fixed, so the signature is read straight from the source string -\n// no parser, no execution - and the runtime can seed the defaults on the store\n// before the first render, which is what makes them reach the template even in\n// factory mode (where JS would only apply them inside the function body).\n//\n// <script :setup=\"{ label = 'Total', step = 1 }\">\n// export default ({ label = \"Total\" }, { $data }) => {}\n//\n// An object pattern *is* the declaration; anything else (`_`, a plain\n// identifier, no attribute at all) declares nothing and stays permissive.\n// ---------------------------------------------------------------------------\n\n// `as` is the local name the pattern binds the key to, when it isn't the key\n// itself (`{ item: row }`). A prop signature has no use for it - what the\n// store holds is the key - but the slot binder (`:slot=\"{ item: row }\"`) is\n// the same pattern read for the other half: which names the content uses\nexport type PropDecl = { name: string; default?: string; as?: string }\n\nconst IDENTIFIER_RE = /^[A-Za-z_$][\\w$]*$/\n\n// index of the bracket that closes the one opening at src[0], skipping\n// strings, comments and regex literals; src.length when unbalanced\nconst patternCloseIndex = (src: string): number => {\n let depth = 0\n let i = 0\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch) && --depth === 0) return i\n i++\n }\n return src.length\n}\n\n// index of the first `ch` at bracket depth 0, skipping strings and comments\nconst indexOfTopLevel = (src: string, ch: string): number => {\n let depth = 0\n let i = 0\n while (i < src.length) {\n const c = src[i]\n if (c === \"'\" || c === '\"' || c === \"`\") { i = skipString(src, i); continue }\n if (c === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (c === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (c === \"/\" && c !== ch && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(c)) depth++\n else if (\")]}\".includes(c)) depth--\n else if (depth === 0 && c === ch) return i\n i++\n }\n return -1\n}\n\nconst splitTopLevel = (src: string): string[] => {\n const parts: string[] = []\n let depth = 0\n let start = 0\n let i = 0\n while (i <= src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (ch !== undefined && \"([{\".includes(ch)) depth++\n else if (ch !== undefined && \")]}\".includes(ch)) depth--\n else if (i === src.length || (ch === \",\" && depth === 0)) {\n const part = src.slice(start, i).trim()\n if (part) parts.push(part)\n start = i + 1\n }\n i++\n }\n return parts\n}\n\n// the `=` that opens a default value: the first one at depth 0 that isn't part\n// of `==`/`===` or an arrow's `=>` (so `{ format = a => a }` keeps its default)\nconst defaultAssignIndex = (src: string): number => {\n let from = 0\n while (from < src.length) {\n const at = indexOfTopLevel(src.slice(from), \"=\")\n if (at === -1) return -1\n const i = from + at\n if (src[i + 1] !== \"=\" && src[i + 1] !== \">\" && src[i - 1] !== \"=\" && src[i - 1] !== \"!\") return i\n from = i + 1\n }\n return -1\n}\n\n// a destructuring pattern -> the props it declares. null means \"no signature\":\n// the pattern isn't an object one (`_`, `props`, nothing at all), so the\n// component declares nothing and keeps the permissive, undeclared behavior.\n// `{}` parses to [] - a closed signature that declares zero props\nexport const parsePropsPattern = (pattern: string | undefined): PropDecl[] | null => {\n const src = (pattern ?? \"\").trim()\n if (!src.startsWith(\"{\")) return null\n\n // to the `}` that closes the pattern, so a parameter's own default value\n // (`({ label } = {})`) is left out of it\n const close = patternCloseIndex(src)\n if (close >= src.length) return null // unbalanced: not a pattern we can read\n\n const props: PropDecl[] = []\n for (const part of splitTopLevel(src.slice(1, close))) {\n if (part.startsWith(\"...\")) continue // a rest element names no prop\n const assign = defaultAssignIndex(part)\n const named = assign === -1 ? part : part.slice(0, assign)\n const fallback = assign === -1 ? undefined : part.slice(assign + 1).trim()\n // `{ user: { id } }` and `{ user: renamed }` both declare `user`: what the\n // store holds is the key, whatever the pattern binds it to\n const colon = indexOfTopLevel(named, \":\")\n const name = (colon === -1 ? named : named.slice(0, colon)).trim()\n if (!IDENTIFIER_RE.test(name)) continue\n const decl: PropDecl = { name }\n if (fallback !== undefined) decl.default = fallback\n // only a plain rename is kept: `{ user: { id } }` binds no single name, so\n // there is nothing to record - the prop is still declared under its key\n const local = colon === -1 ? \"\" : named.slice(colon + 1).trim()\n if (IDENTIFIER_RE.test(local)) decl.as = local\n props.push(decl)\n }\n return props\n}\n\n// index just past a top-level `export default`, or -1\nconst findExportDefault = (src: string): number => {\n let i = 0\n let depth = 0\n let atStatementStart = true\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); atStatementStart = false; continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); atStatementStart = false; continue }\n\n if (ch === \"e\" && depth === 0 && atStatementStart && (i === 0 || !/[\\w$.]/.test(src[i - 1]))) {\n EXPORT_DEFAULT_RE.lastIndex = i\n const found = EXPORT_DEFAULT_RE.exec(src)\n if (found) return i + found[0].length\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n i++\n }\n return -1\n}\n\nconst ASYNC_RE = /^async(?![\\w$])/\nconst FUNCTION_RE = /^function(?![\\w$])\\s*\\*?\\s*[A-Za-z_$][\\w$]*|^function(?![\\w$])\\s*\\*?/\n\n// source text of the exported function's first parameter, or null when there\n// is no parameter list to read (`export default Factory`, `export default\n// props => ...`, an exported object) - all of which declare nothing\nconst firstParameterSource = (src: string): string | null => {\n const start = findExportDefault(src)\n if (start === -1) return null\n\n let i = skipToToken(src, start)\n const rest = src.slice(i)\n if (ASYNC_RE.test(rest)) i = skipToToken(src, i + \"async\".length)\n const fn = FUNCTION_RE.exec(src.slice(i))\n if (fn) i = skipToToken(src, i + fn[0].length)\n if (src[i] !== \"(\") return null\n\n // the parameter list runs to the `)` that closes this `(`\n let depth = 0\n let end = i\n while (end < src.length) {\n const ch = src[end]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { end = skipString(src, end); continue }\n if (ch === \"/\" && src[end + 1] === \"/\") { end = skipLineComment(src, end); continue }\n if (ch === \"/\" && src[end + 1] === \"*\") { end = skipBlockComment(src, end); continue }\n if (ch === \"/\" && regexAllowed(src, end)) { end = skipRegex(src, end); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch) && --depth === 0) break\n end++\n }\n return splitTopLevel(src.slice(i + 1, end))[0] ?? \"\"\n}\n\n// the props declared by a factory script's first parameter. Throws the\n// migration error when it finds the pre-0.4 signature there - the ctx used to\n// be the first parameter, and the change is silent otherwise ($data would just\n// come back undefined). `$` is what tells them apart: what carries one comes\n// from the library, what doesn't comes from the parent, everywhere in jq79\nexport const parseFactoryProps = (src: string): PropDecl[] | null => {\n const first = firstParameterSource(src)\n if (first === null) return null\n const props = parsePropsPattern(first)\n const ctxName = props?.find(prop => prop.name.startsWith(\"$\"))?.name\n if (ctxName) {\n throw new Error(\n `jq79: the factory signature is (props, ctx), so \\`${ctxName}\\` can't be destructured from the first parameter. ` +\n `Write \\`export default (props, { ${ctxName} }) => …\\`, or \\`_\\` in place of props if the component takes none.`\n )\n }\n return props\n}\n\n// rewrites a factory script into a Function body, or returns null when the\n// script has no top-level `export default` (i.e. it's a regular setup script)\nexport const transformFactoryScript = (src: string): string | null => {\n let out = \"\"\n let i = 0\n let depth = 0\n let atStatementStart = true\n let isFactory = false\n let modCount = 0\n\n while (i < src.length) {\n const ch = src[i]\n const next = src[i + 1]\n const atWordBoundary = i === 0 || !/[\\w$.]/.test(src[i - 1])\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n const end = skipString(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n if (ch === \"/\" && (next === \"/\" || next === \"*\")) {\n const end = next === \"/\" ? skipLineComment(src, i) : skipBlockComment(src, i)\n out += src.slice(i, end)\n i = end\n continue\n }\n if (ch === \"/\" && regexAllowed(src, i)) {\n const end = skipRegex(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n\n if (ch === \"i\" && atWordBoundary) {\n // dynamic import() -> $__import, same rewrite as setup scripts\n IMPORT_CALL_RE.lastIndex = i\n if (IMPORT_CALL_RE.test(src)) {\n out += \"$__import\"\n i += \"import\".length\n atStatementStart = false\n continue\n }\n if (depth === 0 && atStatementStart) {\n STATIC_IMPORT_RE.lastIndex = i\n const staticImport = STATIC_IMPORT_RE.exec(src)\n if (staticImport) {\n out += staticImportToAwait(staticImport[1], staticImport[3], modCount++)\n i += staticImport[0].length\n atStatementStart = false\n continue\n }\n }\n }\n\n if (ch === \"e\" && atWordBoundary && depth === 0 && atStatementStart) {\n EXPORT_DEFAULT_RE.lastIndex = i\n const exportDefault = EXPORT_DEFAULT_RE.exec(src)\n if (exportDefault) {\n isFactory = true\n out += \"$__exports.default =\"\n i += exportDefault[0].length\n atStatementStart = false\n continue\n }\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n\n out += ch\n i++\n }\n\n return isFactory ? out : null\n}\n\n"],"mappings":"qjBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,OAAAE,EAAA,OAAAC,GAAA,YAAAC,GAAA,cAAAC,GAAA,WAAAC,EAAA,QAAAC,EAAA,gBAAAA,EAAA,uBAAAC,GAAA,oBAAAC,GAAA,cAAAC,GAAA,mBAAAC,GAAA,oBAAAC,KAAA,eAAAC,GAAAb,ICOO,SAASc,EAAEC,EAAgCC,EAAmC,CACnF,OAAO,OAAOD,GAAiB,SAC3B,SAAS,cAAcA,CAAY,EACnCA,EAAa,cAAcC,CAAS,CAC1C,CAIO,SAASC,GAAGF,EAAgCC,EAA8B,CAC/E,OAAO,MAAM,KACX,OAAOD,GAAiB,SACpB,SAAS,iBAAiBA,CAAY,EACtCA,EAAa,iBAAiBC,CAAS,CAC7C,CACF,CAIO,IAAME,GAAU,CAACC,EAAaC,EAA6B,CAAC,IAAmB,CACpF,IAAMC,EAAK,SAAS,cAAcF,CAAG,EACrC,OAAW,CAACG,EAAMC,CAAK,IAAK,OAAO,QAAQH,CAAK,EAC9C,GAAIE,IAAS,YACXD,EAAG,UAAY,MAAM,QAAQE,CAAK,EAAIA,EAAM,KAAK,GAAG,EAAIA,UAC/CD,IAAS,cAClBD,EAAG,YAAcE,UACRD,IAAS,WAClB,QAAWE,KAASD,EAClBF,EAAG,YAAYG,CAAK,OAGtBH,EAAG,aAAaC,EAAMC,CAAK,EAG/B,OAAOF,CACT,EAEMI,GAAe,IAAI,IAAI,CAC3B,IAAK,IAAK,IAAK,KAAM,SAAU,IAAK,KAAM,KAAM,KAAM,KACtD,aAAc,OAAQ,MAAO,OAAQ,MAAO,KAAM,KAAM,KACxD,KAAM,KAAM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aw","Component79","PendingComponent79","enableHotReload","hotUpdate","parseComponent","renderComponent","__toCommonJS","$","selectorOrEl","selector","$$","$create","tag","attrs","el","name","value","child","ALLOWED_TAGS","ALLOWED_ATTR","SAFE_URL_PROTOCOLS","isSafeUrl","url","DEFAULT_PORTS","compileHostPattern","pattern","match","host","port","labels","label","allowedHosts","patterns","compiled","p","consultAllowUrl","allowUrl","attr","MAX_SANITIZE_DEPTH","appendSanitizedChildren","source","target","depth","sanitizedChild","sanitizeNode","node","clean","allowedForTag","allowedGlobal","sanitizeHTML","html","options","template","container","getByPath","obj","dotKey","acc","key","isPlainData","value","proto","walkLeaves","path","visit","pathsOverlap","a","b","RAW","$toRaw","raw","STORE","isStore","trackerStack","untracked","fn","ATTACH","ALSO_WAKEN_BY","$reactive","data","exactListeners","anyListeners","effects","proxies","storeApi","notify","isNewKey","listener","effect","dep","isWrappable","bridges","bridge","store","current","unbridge","wrap","cached","tombstones","proxy","target","receiver","stored","notified","had","deleted","reactive","$on","immediate","$onAny","$effect","run","alsoWakenBy","running","dirty","cycles","deps","attachAndRun","detach","drop","$__attach","$dispose","unsubscribe","createEffectScope","scope","disposers","runs","dispose","DECLARATION_START_RE","REACTIVE_LABEL_RE","IMPORT_CALL_RE","REACTIVE_ASSIGN_RE","skipString","src","start","quote","i","skipLineComment","end","skipBlockComment","skipToToken","REGEX_AFTER_WORD","regexAllowed","at","ch","open","skipRegex","inClass","CONTINUATION_RE","lastMeaningfulBefore","findStatementEnd","depth","next","splitDeclarators","parts","lastEnd","flush","patternBindings","pattern","IDENTIFIER_RE","names","part","splitTopLevel","patternCloseIndex","assign","defaultAssignIndex","colon","indexOfTopLevel","rewriteDeclarators","vars","rewritten","raw","codeEnd","lead","body","tail","target","isPattern","code","transformSetupScript","out","atStatementStart","decl","label","EXPORT_DEFAULT_RE","STATIC_IMPORT_RE","splitImportClause","clause","staticImportToAwait","spec","source","bindings","ref","tmp","c","from","parsePropsPattern","close","props","named","fallback","name","local","findExportDefault","found","ASYNC_RE","FUNCTION_RE","firstParameterSource","rest","fn","parseFactoryProps","first","ctxName","prop","transformFactoryScript","isFactory","modCount","atWordBoundary","staticImport","exportDefault","VERSION","elementAttrs","el","attr","elementToAST","attrs","component","COMPONENT_TAG_ATTR","node","text","compiled","compileExpr","expr","params","key","fn","MISSING_NAME_RE","MAX_PENDING_REPORTS","pendingReports","reportedExprErrors","pendingScripts","flushScheduled","reportedFailedExprs","flushExprReports","name","scope","scheduleExprReportFlush","trackScript","settled","release","reportFailedExpr","error","message","reportExprError","match","runExpr","extras","evalExpr","evalHandler","interpolate","template","_","CONTROL_ATTRS","isControlAttr","EACH_PATTERN","bindEvent","modifiers","mods","event","handler","wireTagEvent","instance","listener","untracked","kebabToCamel","c","camelToKebab","boundsOf","removeRange","first","last","next","moveRangeAfter","prev","ref","findComponentKey","tag","normalized","obj","componentsInScope","names","unresolvedComponent","MAX_NESTING_DEPTH","nestingDepth","SLOTS","isSlotTag","slotName","suffix","slotAttrOf","slotAttrName","isMeaningful","partitionSlots","contents","loose","child","hasLoose","bindSlotProps","binder","props","parsePropsPattern","as","fallback","local","value","misplacedSlotContent","buildSlots","slots","content","makeSlotRenderer","parentScope","slotScope","fx","shadow","inherited","ALSO_WAKEN_BY","contentFx","createEffectScope","renderNodes","renderSlot","wrapper","anchor","endAnchor","render","SCOPE_ATTR","renderNestedComponent","models","events","sources","hasSpread","modelAttr","modelProp","assignment","unassignable","prop","resolveProps","out","current","currentDef","childFx","reported","reportUnresolved","UNFILLED_PROPS","nextDef","Component79","warned","rawName","declared","declaredPropSet","warnUndeclared","seed","pickDeclared","holder","syncFx","written","nextKeys","createWithScope","source","target","classNames","on","normalizeAllowUrl","policy","url","allowedHosts","BOOLEAN_ATTRS","applyAttr","boolean","renderNode","outerScope","withExpr","componentKey","PENDING_SCRIPTS","mayUpgrade","upgraded","replacement","range","bindExpr","boundKeys","bound","classExpr","classToggles","staticClasses","textExpr","htmlExpr","allowedExpr","options","sanitizeHTML","valueExpr","renderConditional","branches","activeBranch","branchFx","branch","rendered","defineScopeVar","isPlainObject","proto","renderEach","itemName","atName","listExpr","keyExpr","_each","_key","itemAttrs","itemNode","entries","warnedDuplicates","list","pairs","item","index","previous","entry","bucket","seen","moved","nextEntries","at","itemScope","existing","itemFx","prevNode","nodes","fragment","i","textNode","nextBranch","candidate","elseif","elseNode","renderComponent","data","VOID_ELEMENTS","SELF_CLOSING_RE","RAW_BLOCK_RE","expandSelfClosingTags","src","chunk","OPEN_TAG_RE","ATTR_SPREAD_RE","expandPropsSpread","_match","n","rewritten","whole","space","ATTR_NAME_RE","CLOSE_SLOT_RE","SLOT_TAG_RE","kebabTagName","COMPONENT_TAG_RE","TRAILING_SLASH_RE","stampComponentTag","stamp","slash","expandNameCase","scopeHash","hash","stampScope","scopeSelector","selectorText","part","selector","pseudoAt","pseudoElement","scopeRules","rules","rule","scopeCss","css","sheet","COMPONENT_NAME_RE","parseComponentString","prepared","root","own","declarations","parts","componentPartsFrom","siblings","elements","hashSource","scripts","styles","block","style","isScoped","importResource","fetchComponent","RESOLVABLE_SPECIFIER_RE","resolveSpecifier","spec","filename","sourceUrlComment","headStyle","styleRegistry","acquireStyle","releaseStyle","runSetupScript","code","effect","instanceHelpers","importer","helpers","SETUP_HELPERS","scriptScope","state","result","declareProps","store","setupSignature","script","pattern","warnUnreadableSignature","signatureWarned","declaredPropNames","parseFactoryProps","into","undeclaredWarned","said","siblingsInScope","inScope","any","interopDefault","mod","runFactoryScript","$__exports","logError","invoked","merging","invoke","factory","merge","bindings","returned","HOT_FLAG","HOT_RUNTIME","hotRegistry","hotRegister","refs","hotKey","hotUpdate","orphaned","partsFor","rerendered","enableHotReload","STUCK_RENDER_DELAY","warnIfStuck","gates","timer","response","__publicField","sibling","marker","live","parent","before","PendingComponent79","urls","eventName","siblingScope","raw","unfilled","$reactive","warnedModelUpdate","$emit","payload","resolveMounted","mounted","resolve","endMarker","$$self","found","$self","modules","$import","injected","args","defer","allSync","resolveGate","open","deferred","factoryCode","transformFactoryScript","run","body","vars","transformSetupScript","pending","settle","templateScope","receiver","$","nextNode","action","onfulfilled","onrejected","onfinally","parseComponent","component","Component79","SETUP_HELPERS","$","$$","$create","$reactive","$toRaw","HOT_FLAG","enableHotReload"]}
1
+ {"version":3,"sources":["../src/jq79.ts","../src/dom.ts","../src/reactive.ts","../src/transform.ts"],"sourcesContent":["\nimport { $, $$, $create, sanitizeHTML, allowedHosts } from \"./dom\"\nimport type { AllowUrl } from \"./dom\"\nimport { $reactive, $toRaw, untracked, createEffectScope, ALSO_WAKEN_BY } from \"./reactive\"\nimport type { ReactiveDeepData, EffectScope } from \"./reactive\"\nimport { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, type PropDecl } from \"./transform\"\n\nexport { $, $$, $create } from \"./dom\"\nexport { $reactive, $toRaw } from \"./reactive\"\n\n// the package version, substituted at build time (tsup/vitest `define`, read\n// from package.json - releases bump it there and nowhere else). The typeof\n// guard is what keeps the raw source runnable: tests and any bundler that\n// doesn't define it see a bare identifier, not a ReferenceError\ndeclare const __JQ79_VERSION__: string\nconst VERSION = typeof __JQ79_VERSION__ === \"string\" ? __JQ79_VERSION__ : \"0.0.0-dev\"\n\ntype TemplateNode = {\n tag: string\n attrs: Record<string, string>\n children: (TemplateNode | string)[]\n // the tag as the author capitalized it, present only when they wrote it\n // uppercase-initial - i.e. when they meant a component. `tag` cannot answer\n // this: the HTML parser lowercases it, so the claim is captured before the\n // parse (see stampComponentTag) and lifted off attrs here, where it stops\n // looking like an attribute to every loop downstream\n component?: string\n}\n\ntype TagBlock = {\n attrs: Record<string, string>\n content: string\n // <style scoped> only: `content` rewritten to require the component's scope\n // attribute. Kept beside the original rather than replacing it, because a\n // shadow root doesn't want it - see headStyle()\n scoped?: string\n}\n\nconst elementAttrs = (el: Element): Record<string, string> =>\n Object.fromEntries(Array.from(el.attributes).map(attr => [attr.name, attr.value]))\n\n// text is kept verbatim - not trimmed, not dropped when it's only whitespace.\n// A template is HTML, so the space in `<span>a</span>\\n<span>b</span>` is the\n// same space the browser would collapse-and-render between them, and CSS gets\n// to decide what it's worth (nothing in a block or flex container, one space\n// between inline elements). Trimming it here, as this used to, silently glued\n// siblings together and ate the spaces in `hola <b>mundo</b> adios`\n//\n// A <template>'s children are read from its .content fragment: that is where\n// the HTML parser puts them, and its childNodes are empty. Without the descent\n// they are not in the AST at all - which is where slot content is written\n// (<template :slot.name>), and why a nested <template> used to render as an\n// empty element whatever was inside it\nconst elementToAST = (el: Element): TemplateNode => {\n const attrs = elementAttrs(el)\n // the pre-parse stamp becomes a field and leaves attrs entirely: it is not a\n // prop, not a directive and not an attribute, and every loop that walks attrs\n // would otherwise need to know its name\n const component = attrs[COMPONENT_TAG_ATTR]\n delete attrs[COMPONENT_TAG_ATTR]\n return {\n tag: el.tagName.toLowerCase(),\n attrs,\n ...(component === undefined ? {} : { component }),\n children: Array.from((el instanceof HTMLTemplateElement ? el.content : el).childNodes).flatMap((node): (TemplateNode | string)[] => {\n if (node.nodeType === Node.TEXT_NODE) {\n const text = node.textContent ?? \"\"\n return text ? [text] : []\n }\n if (node.nodeType === Node.ELEMENT_NODE) {\n return [elementToAST(node as Element)]\n }\n return []\n })\n }\n}\n\n// evaluated with `with` (rather than passing scope keys as positional params)\n// so only the identifiers an expression actually references are read from\n// `scope` - which is what makes dependency tracking in $reactive\n// precise instead of \"read everything up front\". `extras` are passed as\n// function parameters (outside the `with`), so scope keys still win but names\n// like $event resolve when the scope doesn't shadow them\n//\n// Compiled functions are cached: an expression is re-evaluated on every effect\n// run - once per interpolation, once per :each item - while the set of distinct\n// expressions is fixed by the source. The `extras` names are part of the key,\n// not just the expression: they become the function's parameters, so the same\n// expression compiled with and without $event is two different functions. A\n// syntactically invalid expression caches its failure (null) so it isn't\n// recompiled, and rethrown as undefined, exactly as before\nconst compiled = new Map<string, Function | null>()\n\nconst compileExpr = (expr: string, params: string[]): Function | null => {\n const key = `${params.join(\",\")}|${expr}`\n let fn = compiled.get(key)\n if (fn === undefined) {\n try {\n // the newline before `)` ends a trailing line comment in the\n // expression ({{ msg // greeting }}); ASI doesn't apply inside parens,\n // so everything else is untouched. Without it the comment eats the\n // rest of this single-line body and the expression never compiles\n fn = new Function(\"$scope\", ...params, `with ($scope) { return (${expr}\\n); }`)\n } catch {\n fn = null // a syntax error: it will never compile, so don't try again\n }\n compiled.set(key, fn)\n }\n return fn\n}\n\n// a template expression is re-evaluated constantly - once per effect run, once\n// per interpolation, once per :each item - so a value that is briefly undefined\n// mid-render has to fail quietly, and the catch below stays. A ReferenceError\n// is the one failure worth a word: `with` resolves a name against the store and\n// then globalThis, so a name that resolves nowhere is declared nowhere - a\n// typo, a dropped prop, or the trap this was written for, a top-level\n// `function` declaration, which transformSetupScript leaves as an ordinary\n// lexical binding instead of a store property\n//\n// It is reported late rather than where it throws, because \"declared nowhere\"\n// is not yet decidable at that moment: a factory script assigns its bindings to\n// the store when it returns, so an async factory renders its whole template\n// before any of its names exist. Reporting waits until no script is still\n// running (pendingScripts), and then asks whether the name resolves *now*.\n//\n// The re-check is `name in scope` rather than a re-evaluation, because\n// re-evaluating is not pure: `@click=\"count++ + missing\"` increments before it\n// throws, and running it again to see if it still throws would increment twice\n// and notify. `in` walks the same scope chain (:each scopes are\n// Object.create(scope), :with is a proxy over it) and evaluates nothing\nconst MISSING_NAME_RE = /^(?:([\\w$]+) is not defined|Can't find variable: ([\\w$]+))/\n\n// the queue holds live scopes, so it is capped: a script that never settles\n// would otherwise let it grow for the life of the page\nconst MAX_PENDING_REPORTS = 100\n\ntype PendingReport = { name: string; expr: string; scope: Record<string, any> }\n\nconst pendingReports = new Map<string, PendingReport>()\nconst reportedExprErrors = new Set<string>()\nlet pendingScripts = 0\nlet flushScheduled = false\n\n// everything else an expression can throw - overwhelmingly a member access on\n// an undefined value, `{{ game.is.loaded }}` over a game with no `is`. Unlike a\n// missing name it needs no deferral and gets none: the engine already caught a\n// real exception and wrote the message, so there is nothing left to decide and\n// it is reported where it throws, as an error rather than a warning.\n//\n// That means a value still on its way is reported too - `{{ user.name }}` over\n// a user that a fetch will fill renders empty and says so, once. It is a\n// deliberate trade against the silence it replaces, which hid a render that was\n// actively wrong (a thrown `:disabled` is falsy, so the button rendered\n// *enabled*). The fix is the one the message names: `user?.name`, or `:if`.\n//\n// Deduped by expression text alone. A `:each` over 1000 rows throws 1000 times\n// per render and the Set is what keeps that to one line; keying finer - by\n// message too, as the missing-name queue does - would let one broken path\n// report once per distinct message. There is no queue behind it because there\n// is nothing to re-check, and so nothing that could retain a live scope\nconst reportedFailedExprs = new Set<string>()\n\nconst flushExprReports = () => {\n flushScheduled = false\n if (pendingScripts > 0) return // a script started meanwhile; its release re-schedules\n pendingReports.forEach(({ name, expr, scope }, key) => {\n if (name in scope) return // it arrived late - a factory's bindings, a prop\n reportedExprErrors.add(key)\n console.warn(\n `jq79: ${name} is not defined - evaluating \"${expr}\". Template expressions ` +\n `resolve against the component store: a top-level let/var/const in a :setup ` +\n `script, a declared prop, or a global. Note a \"function name() {}\" declaration ` +\n `is not on the store - write \"const name = () => {}\".`\n )\n })\n pendingReports.clear()\n}\n\nconst scheduleExprReportFlush = () => {\n if (flushScheduled || pendingScripts > 0 || !pendingReports.size) return\n flushScheduled = true\n queueMicrotask(flushExprReports)\n}\n\n// scripts run before the template renders, so the counter is already up when\n// the first evaluation fails. Both script modes settle through a promise;\n// the factory's has to cover the merge, not just the module body\nconst trackScript = (settled: Promise<unknown>) => {\n pendingScripts++\n const release = () => {\n pendingScripts--\n scheduleExprReportFlush()\n }\n settled.then(release, release)\n}\n\n// console.error, not warn: a name that resolves nowhere is a warning because\n// the runtime can only say the name is absent, while this one caught a real\n// exception - it has a message the engine wrote, and the expression rendered as\n// nothing instead of doing what it says\nconst reportFailedExpr = (expr: string, error: unknown) => {\n if (reportedFailedExprs.has(expr)) return\n reportedFailedExprs.add(expr)\n const message = (error as Error)?.message || String(error)\n console.error(\n `jq79: ${message} - evaluating \"${expr}\". The expression rendered as nothing. ` +\n `If the value arrives later, guard it - \"a?.b\", or :if on the element.`\n )\n}\n\nconst reportExprError = (expr: string, scope: Record<string, any>, error: unknown) => {\n if (!(error instanceof ReferenceError)) return reportFailedExpr(expr, error)\n const match = MISSING_NAME_RE.exec(error.message)\n const name = match?.[1] ?? match?.[2]\n if (!name) return // an engine whose wording we don't know: stay quiet, as before\n // keyed on name and expression, not on the expression alone, so two missing\n // names in one expression stay distinguishable - and so a :each of 1000 items\n // enqueues one entry rather than 1000\n const key = `${name}|${expr}`\n if (reportedExprErrors.has(key) || pendingReports.has(key)) return\n if (pendingReports.size >= MAX_PENDING_REPORTS) return\n pendingReports.set(key, { name, expr, scope })\n scheduleExprReportFlush()\n}\n\nconst runExpr = (expr: string, scope: Record<string, any>, extras?: Record<string, any>): any => {\n const fn = compileExpr(expr, extras ? Object.keys(extras) : [])\n if (!fn) return undefined // a syntax error: compileExpr cached the failure, and it stays undefined\n return fn(scope, ...(extras ? Object.values(extras) : []))\n}\n\nconst evalExpr = (expr: string, scope: Record<string, any>, extras?: Record<string, any>): any => {\n try {\n return runExpr(expr, scope, extras)\n } catch (error) {\n reportExprError(expr, scope, error)\n return undefined\n }\n}\n\n// the same evaluation for an @event attribute, which swallows far less. Every\n// word of the reason evalExpr catches is about rendering: an expression is\n// re-evaluated per effect run, per interpolation, per :each item, so a value\n// that is briefly undefined mid-render has to render empty rather than tear the\n// render down. A handler runs in an event listener - not in an effect, once,\n// when the user clicked - so there is no transient failure to absorb, only a\n// bug to report, and an exception belongs in the console with its stack. That\n// is what `@click=\"save\"` has always done (the call happens outside the try,\n// on the returned function); this is what makes `@click=\"save()\"` and\n// `@click=\"count++\"` behave the same rather than the other way round.\n//\n// ReferenceError is the exception, for the reason it always is: it is not yet\n// decidable at throw time. A factory assigns its names to the store when it\n// returns, so a click while one is still in flight throws for a name that is\n// about to exist - reportExprError re-checks after the scripts settle and stays\n// quiet if it arrived, which throwing here would replace with a false alarm\nconst evalHandler = (expr: string, scope: Record<string, any>, extras: Record<string, any>): any => {\n try {\n return runExpr(expr, scope, extras)\n } catch (error) {\n if (!(error instanceof ReferenceError)) throw error\n reportExprError(expr, scope, error)\n return undefined\n }\n}\n\n// [\\s\\S] rather than `.` so an expression can span lines, like the ones in\n// directive attributes (which reach evalExpr wrapped in parens either way)\nconst interpolate = (template: string, scope: Record<string, any>): string =>\n template.replace(/{{\\s*([\\s\\S]+?)\\s*}}/g, (_, expr) => evalExpr(expr, scope) ?? \"\")\n\n\nconst CONTROL_ATTRS = new Set([\":attrs\", \":class\", \":value\", \":checked\", \":selected\", \":if\", \":elseif\", \":else\", \":each\", \":key\", \":with\", \":text\", \":html\", \":html.allowed\", \":props\"])\n\n// a control attribute is one the static-attr loop and nested-component prop\n// collection must skip. The set holds the fixed names; `:class.<name>` (the\n// single-flag shorthand) and `:props.<n>` (one spread among several) are\n// open-ended, so they're matched by prefix - they can't be enumerated into the set\nconst isControlAttr = (attr: string): boolean =>\n CONTROL_ATTRS.has(attr) || attr.startsWith(\":class.\") || attr.startsWith(\":props.\") ||\n attr === \":slot\" || attr.startsWith(\":slot.\")\n// `item in items`, `item, i in items`, `(value, key) in props` - the second\n// binding is the array index or the object key, parens optional (Vue-style).\n// The list expression can span lines, so it matches [\\s\\S] rather than `.`\nconst EACH_PATTERN = /^\\s*\\(?\\s*(\\w+)\\s*(?:,\\s*(\\w+))?\\s*\\)?\\s+in\\s+([\\s\\S]+)$/\n\ntype ConditionalBranch = { expr?: string; node: TemplateNode }\n\n\n// @event attributes: @click=\"onClick\", @submit.prevent=\"$event => onSubmit($event)\",\n// or an inline statement like @click=\"count = count + 1\". The expression is\n// evaluated (with `$event` in scope) on every event; if it yields a function,\n// that function is then invoked with the event - so both a handler reference\n// and an inline arrow/statement work. Modifiers after dots: .prevent .stop\n// .self (runtime guards) and .once .capture (addEventListener options)\nconst bindEvent = (el: Element, attr: string, expr: string, scope: Record<string, any>) => {\n const [name, ...modifiers] = attr.slice(1).split(\".\")\n const mods = new Set(modifiers)\n\n el.addEventListener(name, event => {\n if (mods.has(\"self\") && event.target !== el) return\n if (mods.has(\"prevent\")) event.preventDefault()\n if (mods.has(\"stop\")) event.stopPropagation()\n\n const handler = evalHandler(expr, scope, { $event: event })\n if (typeof handler === \"function\") handler.call(el, event)\n }, { once: mods.has(\"once\"), capture: mods.has(\"capture\") })\n}\n\n// @event on a component tag: the tag renders as comment anchors, so there is\n// no element to listen on - the attribute subscribes to the child instance's\n// $emit channel (instance.on) instead, which survives the child's re-renders\n// and works detached. Native DOM events from the child's inner DOM never\n// arrive here: they bubble past the anchors to shared ancestors (a listener\n// on a wrapping element hears those); a child that wants its native event\n// heard on its tag re-emits it. .prevent flips the child's $emit() return to\n// false, .stop keeps the emit off the DOM dispatch, .once unsubscribes after\n// one call; .self and .capture have no meaning on this channel and are ignored\nconst wireTagEvent = (instance: Component79, attr: string, expr: string, scope: Record<string, any>) => {\n const [name, ...modifiers] = attr.slice(1).split(\".\")\n const mods = new Set(modifiers)\n\n const listener = (event: CustomEvent) => {\n if (mods.has(\"prevent\")) event.preventDefault()\n if (mods.has(\"stop\")) event.stopPropagation()\n if (mods.has(\"once\")) instance.off(name, listener)\n\n // untracked, so a tag handler behaves like an element handler no matter\n // when the emit fires: an element handler never runs inside an effect,\n // but $emit can (a $: that emits, a setup-script emit inside the parent's\n // creation effect), and the handler's reads would land in that effect's\n // deps. Today that is contained - cross-store deps are never notified,\n // and the creation effect's definition guard no-ops a spurious wake - but\n // \"what a handler reads is nobody's dependency\" shouldn't hinge on either\n untracked(() => {\n const handler = evalHandler(expr, scope, { $event: event })\n if (typeof handler === \"function\") handler(event)\n })\n }\n instance.on(name, listener)\n}\n\nconst kebabToCamel = (name: string) => name.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase())\n\n// the inverse, used only by the pre-parse name rewrite (see expandNameCase):\n// uppercase ASCII letters only, never digits - `:props.0` is a generated\n// attribute name and splitting on digits would mangle it. Round-trips through\n// kebabToCamel, acronyms included: userID -> user-i-d -> userID\nconst camelToKebab = (name: string) => name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)\n\n// the stable boundaries of a rendered chunk. An element is its own handle, but\n// a fragment (a nested component: two anchors with the instance's DOM between\n// them) empties itself into the parent on insertion - after that its identity\n// answers nothing, and what stays put are its first and last children. Callers\n// that reposition or remove a chunk later (:each entries, :if branches) must\n// capture its bounds *before* inserting it and work on the range\ntype NodeRange = { first: Node; last: Node }\n\nconst boundsOf = (node: Node): NodeRange =>\n node instanceof DocumentFragment\n ? { first: node.firstChild!, last: node.lastChild! }\n : { first: node, last: node }\n\n// removes [first..last] inclusive - the range's content is dynamic (a nested\n// component's DOM comes and goes between its anchors), so it walks siblings\n// rather than assuming any particular nodes in between\nconst removeRange = ({ first, last }: NodeRange) => {\n for (let node: Node | null = first; node; ) {\n const next: Node | null = node === last ? null : node.nextSibling\n node.parentNode?.removeChild(node)\n node = next\n }\n}\n\n// removes several ranges that sit next to each other, in one DOM call each run\n// rather than one per node. A list dropping all its rows hands them over as a\n// single span: unlinking 10,000 rows one at a time is 40% of that operation,\n// profiled - see TODOS/2026-08-23.batch-range-removal.md. Runs are built by the\n// caller, which is the only place that knows what else is going\nconst removeRuns = (runs: NodeRange[][]) => {\n runs.forEach(run => {\n if (run.length === 1) return removeRange(run[0])\n const parent = run[0].first.parentNode\n if (!parent) return\n // both ends sit between nodes, so nothing is partially selected and whole\n // nodes are what gets unlinked\n const range = document.createRange()\n range.setStartBefore(run[0].first)\n range.setEndAfter(run[run.length - 1].last)\n range.deleteContents()\n })\n}\n\n// groups the entries `isDead` selects into runs of DOM neighbours, walking\n// `ordered` (which is in DOM order). Adjacency is confirmed rather than assumed:\n// a gap - an entry removed earlier in the same pass - starts a new run, so a\n// live entry can never end up inside one\nconst contiguousRuns = <T extends { range: NodeRange }>(ordered: T[], isDead: (entry: T) => boolean): NodeRange[][] => {\n const runs: NodeRange[][] = []\n let run: NodeRange[] | null = null\n ordered.forEach(entry => {\n if (!isDead(entry)) {\n run = null\n return\n }\n if (run && run[run.length - 1].last.nextSibling === entry.range.first) run.push(entry.range)\n else runs.push((run = [entry.range]))\n })\n return runs\n}\n\n// moves [first..last] inclusive so the range starts right after `prev`\nconst moveRangeAfter = ({ first, last }: NodeRange, prev: Node) => {\n const ref = prev.nextSibling\n for (let node: Node | null = first; node; ) {\n const next: Node | null = node === last ? null : node.nextSibling\n prev.parentNode!.insertBefore(node, ref)\n node = next\n }\n}\n\n// finds the scope variable a template tag refers to. HTML parsing lowercases\n// tag names, so <NestedComponent> arrives as \"nestedcomponent\" and matching is\n// case-insensitive with dashes stripped (<nested-component> works too). Only\n// PascalCase scope keys participate, so ordinary variables named like real\n// elements (title, code, ...) never hijack them\nconst scanComponentKey = (scope: Record<string, any>, tag: string): string | null => {\n const normalized = tag.replace(/-/g, \"\").toLowerCase()\n for (let obj: any = scope; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {\n for (const key of Object.keys(obj)) {\n if (/^[A-Z]/.test(key) && key.replace(/-/g, \"\").toLowerCase() === normalized) return key\n }\n }\n return null\n}\n\n// The scan above is run for every element rendered, and it walks the whole\n// scope chain calling Object.keys at each level - which profiling puts at 13.7%\n// of the create path, four times the next attributable frame, almost all of it\n// answering \"no\" for tags like <td>. Within one render pass the answer can't\n// change: it is a *key*, not the value behind it, so every row of a :each\n// resolves a tag identically, and a store write mid-pass restarts the pass\n// rather than continuing it (the reentrancy guard in reactive.ts).\n//\n// So it is memoized for exactly one pass and no longer. It has to be no longer:\n// a template renders before its setup script settles, so `const Row = await\n// $import(...)` arrives as a new store key *after* elements are on the page -\n// and a cached \"no component called Row\" that outlived the pass would never be\n// revisited. See TODOS/2026-08-23.component-key-scan.md\n// The memo answers for one *base* scope - the one the pass was opened with -\n// and nothing below it. A lookup walks from wherever it starts up to that base,\n// checking own keys as it goes (an :each item scope has two or three, a :with\n// a handful), and only then consults the memo. So a name introduced under the\n// base still shadows correctly, and a scope that never reaches the base at all\n// - a nested component renders against its own store - has simply been fully\n// scanned by the time the walk ends, which is the answer anyway\nlet tagMemo: Map<string, string | null> | null = null\nlet memoBase: object | null = null\n\n// opened and closed by hand rather than by a wrapper taking a callback: a\n// component that renders itself through :each stacks one renderEach per level,\n// and a callback would add a frame to each of them. The cyclic-component test\n// cuts off at 200 levels, and on a CI runner that extra frame per level was the\n// difference between cutting off and a RangeError - the same reason $effect\n// keeps its own shape (see reactive.ts)\ntype RenderPass = { memo: Map<string, string | null> | null; base: object | null }\n\nconst openRenderPass = (base: Record<string, any>): RenderPass => {\n const outer: RenderPass = { memo: tagMemo, base: memoBase }\n tagMemo = new Map()\n memoBase = base\n return outer\n}\n\nconst closeRenderPass = (outer: RenderPass) => {\n tagMemo = outer.memo\n memoBase = outer.base\n}\n\nconst findComponentKey = (scope: Record<string, any>, tag: string): string | null => {\n if (!tagMemo) return scanComponentKey(scope, tag)\n const normalized = tag.replace(/-/g, \"\").toLowerCase()\n for (let obj: any = scope; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {\n if (obj === memoBase) {\n if (tagMemo.has(tag)) return tagMemo.get(tag)!\n const key = scanComponentKey(obj, tag)\n tagMemo.set(tag, key)\n return key\n }\n for (const key of Object.keys(obj)) {\n if (/^[A-Z]/.test(key) && key.replace(/-/g, \"\").toLowerCase() === normalized) return key\n }\n }\n return null\n}\n\n// every name a tag *could* have resolved to, walking the same chain\n// findComponentKey does. Deduped and sorted, because the chain can hold one\n// name twice (a prop shadowing a sibling) and the order it comes out in is the\n// prototype's, which means nothing to a reader scanning for their typo\nconst componentsInScope = (scope: Record<string, any>): string[] => {\n const names = new Set<string>()\n for (let obj: any = scope; obj && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {\n for (const key of Object.keys(obj)) if (/^[A-Z]/.test(key)) names.add(key)\n }\n return [...names].sort()\n}\n\n// a tag whose name resolves to no component, once nothing can still supply one.\n// The error names what *is* in scope: the mistake is nearly always a typo or a\n// missing import, and both are one glance from the list. \"(none)\" is its own\n// answer - it says the component has no components at all, which points at the\n// import rather than at the spelling\nconst unresolvedComponent = (tag: string, scope: Record<string, any>): Error => {\n const names = componentsInScope(scope)\n return new Error(\n `jq79: <${tag}> is not defined - no component of that name is in scope, and nothing renders here. ` +\n `Import it in a :setup script, declare it as a prop, or add a <template name=\"${tag}\"> to this file. ` +\n `In scope: ${names.length ? names.join(\", \") : \"(none)\"}.`\n )\n}\n\n// how deep a component may nest inside itself before the runtime calls it a\n// cycle. Deeper than any real tree, shallower than the JS stack: a truncated\n// render with an error on the console beats a stack overflow with none\nconst MAX_NESTING_DEPTH = 200\nlet nestingDepth = 0\n\n// ---------------------------------------------------------------------------\n// slots - content projection\n//\n// A component tag's children are content the child renders where it wrote a\n// <slot>. The dot marks the named variant on both sides, like :model.<name>\n// and :class.<name> already do:\n//\n// <!-- Card.html --> <!-- the parent -->\n// <section> <Card>\n// <header> <template :slot.header><h2>{{ t }}</h2></template>\n// <slot.header>?</slot.header>\n// </header> <p>{{ body }}</p>\n// <slot /> </Card>\n// </section>\n//\n// Three rules decide everything below:\n//\n// 1. Content belongs to the parent - its AST, its scope, its effects, its\n// scoped styles. The child decides *where* it goes and *whether* it goes,\n// never what the names in it mean.\n// 2. Slot props are declared, not injected: `:slot=\"{ item }\"` on the usage\n// site, for the same reason :each writes `item in rows`. Every bare name in\n// the parent's file is introduced by the parent, so a `<slot :item>` the\n// child adds later can't silently capture one.\n// 3. What isn't projected isn't rendered. No <slot>, or one behind a false\n// :if, and the content's effects never exist.\n//\n// The content travels as a thunk, not as DOM: an instance is replaced (a\n// definition swap, a hot reload) and one <slot> may render many times, so a\n// pre-rendered fragment would leak effects and could only be inserted once\n// ---------------------------------------------------------------------------\n\n// renders one slot's content at the position the child put the <slot>: it is\n// handed the slot's props (lazy, so each read re-evaluates in the child's\n// scope), that position's scope and effect scope, and the style mode the\n// child renders under\ntype SlotRenderer = (\n props: Record<string, () => any>,\n slotScope: Record<string, any>,\n fx: EffectScope,\n shadow: boolean\n) => Node\n\ntype SlotMap = Record<string, SlotRenderer>\n\n// the content an instance was handed, by slot name. Symbol-keyed and\n// non-enumerable on the store's data, like UNFILLED_PROPS: it rides the scope\n// chain (so a <slot> inside an :each or a :with finds it) and never shows up\n// as data - not in Object.keys, not in a snapshot spread, not in the props a\n// nested component is handed\nconst SLOTS = Symbol(\"jq79.slots\")\n\n// <slot>, <slot.header-bar>: the hole and its name. Names arrive kebab-case\n// whichever way they were authored (the HTML parser lowercases tag names and\n// attribute modifiers alike, so expandNameCase normalizes camelCase to kebab\n// before parsing) and are camelCase where read - <slot.header-bar> and\n// <slot.headerBar> are :slot.header-bar is $slots.headerBar\nconst isSlotTag = (tag: string): boolean => tag === \"slot\" || tag.startsWith(\"slot.\")\n\nconst slotName = (suffix: string): string => (suffix ? kebabToCamel(suffix) : \"default\")\n\n// the content of one slot, as written at the usage site\ntype SlotContent = { nodes: (TemplateNode | string)[]; binder?: string }\n\n// the :slot attribute of a <template>, if it carries one\nconst slotAttrOf = (node: TemplateNode): string | undefined =>\n Object.keys(node.attrs).find(attr => attr === \":slot\" || attr.startsWith(\":slot.\"))\n\nconst slotAttrName = (name: string) => (name === \"default\" ? \":slot\" : `:slot.${name}`)\n\n// whitespace-only text between two <template :slot> blocks is the indentation\n// between them and nothing else - the same call renderNodes makes between the\n// branches of an :if chain. It is what decides whether a tag has default\n// content at all, which is what $slots.default answers\nconst isMeaningful = (node: TemplateNode | string): boolean => typeof node !== \"string\" || node.trim() !== \"\"\n\n// a component tag's children, partitioned by slot name: a direct\n// <template :slot.<name>> child fills that name, everything else is the\n// default slot's content. The attribute's value is the pattern the content\n// binds the slot's props to - on the tag itself for the default, since the\n// default content has no <template> of its own to carry it\nconst partitionSlots = (node: TemplateNode): Record<string, SlotContent> => {\n const contents: Record<string, SlotContent> = {}\n const loose: (TemplateNode | string)[] = []\n\n node.children.forEach(child => {\n const attr = typeof child === \"object\" && child.tag === \"template\" ? slotAttrOf(child) : undefined\n if (typeof child === \"string\" || attr === undefined) {\n loose.push(child)\n return\n }\n const name = slotName(attr.slice(\":slot.\".length))\n // first wins, like two <template name=\"X\"> in one file: a duplicate is a\n // typo, and the fix is to delete one - not to guess which\n if (name in contents) {\n console.warn(`jq79: two <template ${slotAttrName(name)}> in <${node.tag}>; the second was ignored`)\n return\n }\n contents[name] = { nodes: child.children, binder: child.attrs[attr] || undefined }\n })\n\n const hasLoose = loose.some(isMeaningful)\n if (hasLoose && \"default\" in contents) {\n console.warn(\n `jq79: <${node.tag}> has both a <template :slot> and content outside it - ` +\n \"the <template> is the default slot's content, and the rest was ignored\"\n )\n } else if (hasLoose) {\n contents.default = { nodes: loose, binder: node.attrs[\":slot\"] || undefined }\n }\n return contents\n}\n\n// `:slot=\"{ item, index: i, total = 0 }\"` - the names the content binds the\n// slot's props to. The bindings are accessors, not values: each read\n// re-evaluates the child's expression, so an effect that reads `item` tracks\n// exactly what that expression touches, on every run (createWithScope's design)\nconst bindSlotProps = (scope: Record<string, any>, binder: string | undefined, props: Record<string, () => any>) => {\n parsePropsPattern(binder)?.forEach(({ name, as, default: fallback }) => {\n const local = as ?? name\n Object.defineProperty(scope, local, {\n enumerable: true,\n configurable: true,\n get: () => {\n const value = props[name]?.()\n return value === undefined && fallback !== undefined ? evalExpr(fallback, scope) : value\n },\n // a slot prop is the child's value: it arrives on every read and there\n // is nowhere for a write to go. Silence would be worse - `with` swallows\n // an assignment to a getter without a word\n set: () => console.warn(`jq79: \"${local}\" is a slot prop - it comes from the component, so assigning to it does nothing`),\n })\n })\n}\n\n// a <template :slot> only fills a slot as a direct child of a component tag,\n// where the usage site takes it out of the children before they are ever\n// rendered (see partitionSlots). Anywhere else the position is a mistake, and\n// rendering the content in place - in the wrong scope, into a <template>\n// nobody clones - would be a strange way to say so. A comment rather than\n// nothing: an :if branch needs a node to hold on to (see boundsOf)\nconst misplacedSlotContent = (node: TemplateNode): Node => {\n const attr = slotAttrOf(node)\n console.warn(`jq79: <template ${attr}> fills a slot only as a direct child of a component tag; here it rendered nothing`)\n return document.createComment(`misplaced ${attr}`)\n}\n\n// what a usage site hands its instance: every slot it filled, as the thunk\n// that renders it. Built once per site, and in one call - a component tag is\n// on the stack while its whole subtree renders below it (a component that\n// renders itself does this 200 deep), so the intermediates stay in here rather\n// than in the frame that waits\nconst buildSlots = (node: TemplateNode, scope: Record<string, any>): SlotMap | null => {\n const contents = Object.entries(partitionSlots(node))\n if (!contents.length) return null\n const slots: SlotMap = {}\n contents.forEach(([name, content]) => { slots[name] = makeSlotRenderer(content, scope) })\n return slots\n}\n\n// the thunk one slot's content becomes: the usage site closes over its AST and\n// its scope, the child calls it wherever (and however many times) it renders\n// the matching <slot>\nconst makeSlotRenderer = (content: SlotContent, parentScope: Record<string, any>): SlotRenderer =>\n (props, slotScope, fx, shadow) => {\n // the parent's scope, plus the names the content declared for the slot's\n // props (rule 1: what the content says is decided where it was written)\n const scope: Record<string, any> = Object.create(parentScope)\n bindSlotProps(scope, content.binder, props)\n // this content reads the parent's store (its own names) and the child's\n // (through the slot props), so every effect created anywhere inside it is\n // registered with both - see ALSO_WAKEN_BY. Appended rather than assigned:\n // content forwarded through a <slot> inside slot content is still woken by\n // the store it came from\n const inherited: Record<string, any>[] = (scope as any)[ALSO_WAKEN_BY] ?? []\n Object.defineProperty(scope, ALSO_WAKEN_BY, { value: [...inherited, slotScope] })\n\n const contentFx = createEffectScope(scope)\n // rule 3: the <slot> is the content's lifetime. When the child's subtree at\n // this position goes - an :if turning false, the instance being replaced,\n // the whole child being destroyed - the content's effects go with it\n fx.onDispose(() => contentFx.dispose())\n return renderNodes(content.nodes, scope, contentFx, shadow)\n }\n\n// <slot />, <slot.name>fallback</slot.name>: where the parent's content goes.\n// Unfilled, the slot renders its own children instead - in this component's\n// scope, since that content is this component's. Every attribute that isn't a\n// directive is a slot prop: `:item=\"item\"` evaluates here and reaches the\n// content under the name it declared, a plain attribute passes a literal\n// string, and there are no reserved names (the slot's own name is in the tag).\n// Bracketed by anchors like a nested component, so the chunk has stable bounds\n// even when it renders nothing (see boundsOf)\nconst renderSlot = (node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const name = slotName(node.tag.slice(\"slot.\".length))\n const wrapper = document.createDocumentFragment()\n const anchor = document.createComment(node.tag)\n const endAnchor = document.createComment(`/${node.tag}`)\n wrapper.append(anchor, endAnchor)\n\n const render = (scope as any)[SLOTS]?.[name] as SlotRenderer | undefined\n if (!render) {\n wrapper.insertBefore(renderNodes(node.children, scope, fx, shadow), endAnchor)\n return wrapper\n }\n\n const props: Record<string, () => any> = {}\n Object.entries(node.attrs).forEach(([attr, value]) => {\n // the scope stamp is the component's, not a prop; @events have no element\n // to bind here; and a directive means what it means everywhere else -\n // :if/:each/:with decide whether and how often this slot renders, so they\n // are the renderer's, not the content's\n if (attr === SCOPE_ATTR || isControlAttr(attr) || attr.startsWith(\"@\")) return\n if (attr.startsWith(\":\")) {\n const expr = value || attr.slice(1)\n props[kebabToCamel(attr.slice(1))] = () => evalExpr(expr, scope)\n } else {\n props[kebabToCamel(attr)] = () => value\n }\n })\n\n wrapper.insertBefore(render(props, scope, fx, shadow), endAnchor)\n return wrapper\n}\n\n// <MyComponent :user :title=\"'str'\"></MyComponent> - renders a child\n// component instance at this position. Props: `:name=\"expr\"` evaluates expr\n// in the parent scope (`:name` alone is shorthand for `:name=\"name\"`), plain\n// attributes pass through as literal strings, and kebab-case prop names\n// become camelCase. Props stay live: a parent effect re-evaluates each\n// expression and writes it into the child's store. The component variable is\n// reactive too - while it's undefined (e.g. an `await import(...)` still in\n// flight) nothing renders, and the child appears when it resolves.\n// `shadow` is the parent's style mode, carried down the whole render: a child\n// of a shadow-rendered component renders inside that shadow root, so its\n// <style> has to go in there with it - document.head can't reach into a shadow\n// tree, and a style that never applies to its own component would still be\n// restyling the page around it\nconst renderNestedComponent = (key: string, node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n // two anchors bracketing everything this usage site ever renders: the\n // instance's DOM is dynamic (the definition can resolve late or be swapped),\n // so a caller that needs to move or remove this chunk later can't hold any\n // of it - it holds the anchors, which never move on their own (see boundsOf)\n const anchor = document.createComment(key)\n const endAnchor = document.createComment(`/${key}`)\n const wrapper = document.createDocumentFragment()\n wrapper.append(anchor, endAnchor)\n\n // the tag's children, as content for the child's <slot>s. Built once per\n // usage site (the AST doesn't change) and closed over the parent's scope\n // here, so every instance this site ever renders is handed the same thunks\n const slots = buildSlots(node, scope)\n\n const props: Record<string, string> = {} // prop name -> expression in parent scope\n const models: Record<string, string> = {} // model name -> assignable expression in parent scope\n const events: Array<[string, string]> = [] // @attr (modifiers included) -> handler expression\n // named props AND spreads in source order - what a :props merge folds over so\n // precedence follows the JS object-spread rule (later wins). `name` absent\n // marks a spread: the whole object's properties, not one binding\n const sources: Array<{ name?: string; expr: string }> = []\n let hasSpread = false\n Object.entries(node.attrs).forEach(([attr, value]) => {\n // the parent's scope stamp is stamped on every template element, this tag\n // included - it's not a prop, and the child renders under its own scope\n if (attr === SCOPE_ATTR) return\n if (attr === \":props\" || attr.startsWith(\":props.\")) {\n // :props=\"obj\" spreads obj's own properties as props; :props.<n> is one\n // spread among several (the `...obj` sugar rewrites to it - see\n // expandPropsSpread), the suffix only keeping the attribute names distinct\n hasSpread = true\n sources.push({ expr: value })\n return\n }\n if (isControlAttr(attr)) return\n if (attr.startsWith(\"@\")) {\n events.push([attr, value])\n } else if (attr === \":model\" || attr.startsWith(\":model.\")) {\n // :model[.name]=\"expr\" - two-way: a prop down plus a writeback listener\n // (wired below, once the instance exists). The modifier arrives\n // kebab-case whichever way it was authored (expandNameCase rewrote any\n // camelCase before parsing); the bare :model binds the name \"default\"\n const name = attr === \":model\" ? \"default\" : kebabToCamel(attr.slice(\":model.\".length))\n models[name] = value || (attr === \":model\" ? \"model\" : name)\n } else if (attr.startsWith(\":\")) {\n const name = kebabToCamel(attr.slice(1))\n props[name] = value || name\n sources.push({ name, expr: value || name })\n } else {\n const name = kebabToCamel(attr)\n const expr = JSON.stringify(value)\n props[name] = expr\n sources.push({ name, expr })\n }\n })\n\n // each model is also a prop down: the child reads the value under the\n // model's name - `model` for the default, because a prop named `default`\n // could never be read from a child expression (reserved word). Without the\n // prop this isn't two-way, it's upward collection: a parent reset or an\n // initial value would never reach the child\n const modelAttr = (name: string) => (name === \"default\" ? \":model\" : `:model.${name}`)\n const modelProp = (name: string) => (name === \"default\" ? \"model\" : name)\n // the newline keeps `= $value` out of a trailing line comment in the\n // expression (:model=\"uname // the username\") - glued on the same line,\n // the assignment would vanish into the comment and compile as a bare read,\n // dropping every update without a word\n const assignment = (expr: string) => `${expr}\\n= $value`\n // the models whose expression will never take an update, decided here rather\n // than at update time: an assignment that landed and one that was dropped\n // both evaluate to the value assigned, so the result can't tell them apart -\n // which is what $updateModel's return has to report\n const unassignable = new Set<string>()\n Object.entries(models).forEach(([name, expr]) => {\n const prop = modelProp(name)\n if (props[prop] !== undefined) {\n console.warn(`jq79: <${node.tag}> binds prop \"${prop}\" through both :${prop} and ${modelAttr(name)} - ${modelAttr(name)} wins`)\n }\n props[prop] = expr\n // an expression that can't be an assignment target is a wiring mistake -\n // say so now, not on the first update that silently goes nowhere\n if (compileExpr(assignment(expr), [\"$value\"]) === null) {\n unassignable.add(name)\n console.warn(`jq79: ${modelAttr(name)}=\"${expr}\" is not assignable - updates from <${node.tag}> will be dropped`)\n }\n })\n\n // the full prop set the child gets, resolved in source order: each named prop\n // sets one key, each spread merges an object's own properties, later sources\n // overwriting earlier (the JS object-spread rule). :model bindings apply last,\n // so they win - the same precedence the collision warning above promises. A\n // spread expression that isn't an object contributes nothing (fail closed,\n // like :with), so an `await`-pending object spreads once it resolves\n const resolveProps = (): Record<string, any> => {\n const out: Record<string, any> = {}\n sources.forEach(({ name, expr }) => {\n if (name !== undefined) out[name] = evalExpr(expr, scope)\n else {\n const obj = evalExpr(expr, scope)\n if (obj !== null && typeof obj === \"object\") Object.assign(out, obj)\n }\n })\n Object.entries(models).forEach(([name, expr]) => { out[modelProp(name)] = evalExpr(expr, scope) })\n return out\n }\n\n let current: Component79 | null = null\n let currentDef: Component79 | null = null\n let childFx: EffectScope | null = null\n\n // a usage site that resolves to no component renders nothing, which is\n // deliberate - `undefined` while an `await import(...)` is in flight has to\n // wait quietly, and the child appears when it lands. Two cases can never\n // resolve, though, and both are wiring mistakes worth naming: a value that\n // isn't a component (and so will never become one by waiting), and a name\n // the component declared as a prop that the parent passed nothing for. Once\n // each, per usage site: an effect re-runs\n const reported = new Set<string>()\n const reportUnresolved = (value: any) => {\n if (value === undefined || value === null) {\n const unfilled: Set<string> | undefined = (scope as any)[UNFILLED_PROPS]\n if (!unfilled?.has(key) || reported.has(\"unfilled\")) return\n reported.add(\"unfilled\")\n console.error(\n `jq79: <${node.tag}> is declared as a prop and the parent passed nothing - nothing renders here. ` +\n `Pass it (:${key}=\"…\"), or drop it from the signature to use the one declared in this file.`\n )\n return\n }\n if (reported.has(\"type\")) return\n reported.add(\"type\")\n console.error(`jq79: <${node.tag}> is ${typeof value}, not a component - nothing renders here`)\n }\n\n fx.effect(() => {\n const value = evalExpr(key, scope)\n const nextDef = value instanceof Component79 ? value : null\n if (!nextDef) reportUnresolved(value)\n if (nextDef === currentDef) return\n\n childFx?.dispose()\n childFx = null\n current?.destroy() // detaches its marker range, removing the child's DOM\n current = null\n currentDef = nextDef\n if (!nextDef) return\n\n // a fresh instance per usage site: the definition's parsed parts (and\n // pre-resolved modules) are shared, but store/effects/DOM are per instance\n const instance = new Component79({\n template: nextDef.template,\n scripts: nextDef.scripts,\n styles: nextDef.styles,\n modules: nextDef.modules,\n filename: nextDef.filename,\n // its file's other components, and which of them it is: without the\n // first a child rendered here loses the siblings its definition could\n // see, and without the second hot reload can't tell it what it is\n siblings: nextDef.siblings,\n name: nextDef.name,\n })\n // the content this site wrote inside the tag, before the first render: a\n // <slot> is resolved while rendering, so the map has to be there by then\n if (slots) instance.slots = slots\n // the writeback half of :model - the function the child's $updateModel\n // calls, handed over before the first render. Not an event: nothing about\n // a parent-child assignment wants a CustomEvent bubbling through the page\n // on every keystroke, and a direct call has no payload shape to get wrong.\n // The name is normalized like the attribute was (kebab->camel; absent\n // means the default model), and a name nothing binds warns: a typo must\n // not be an input that types into the void\n if (Object.keys(models).length) {\n // each mistake is warned once per instance, not once per keystroke: an\n // input updating a typo'd name would otherwise flood the console on\n // every character typed into it\n const warned = new Set<string>()\n instance.modelWriteback = (rawName, value) => {\n const name = rawName == null ? \"default\" : kebabToCamel(String(rawName))\n const expr = models[name]\n if (expr === undefined) {\n if (!warned.has(name)) {\n warned.add(name)\n console.warn(`jq79: <${node.tag}> has no ${modelAttr(name)} - bound: ${Object.keys(models).map(modelAttr).join(\", \")}`)\n }\n return false\n }\n if (unassignable.has(name)) return false // already warned, at wiring time\n // untracked, like the tag handlers: a child updating from its setup\n // script runs inside the parent's *creation* effect, and the reads a\n // path assignment makes (`user` in `user.name = $value`) would land\n // in its deps - donating that effect one wasted (guard-stopped) wake\n // per later write. An imperative writeback is nobody's dependency\n untracked(() => evalExpr(assignment(expr), scope, { $value: value }))\n return true\n }\n }\n\n // @event on the tag listens to this instance's $emit channel (and only\n // this instance's - a grandchild's emit arrives here solely as an\n // explicit re-emit)\n events.forEach(([attr, expr]) => wireTagEvent(instance, attr, expr, scope))\n\n // what this component actually takes, decided by its signature. Applied to\n // every path that writes a prop - the seed here and both sync paths below -\n // or an undeclared name would be filtered on the first render and reappear\n // on the next update\n const declared = declaredPropSet(instance.scripts)\n warnUndeclared(node, key, Object.keys(props), declared)\n const seed = pickDeclared(untracked(resolveProps), declared)\n // mounting into a fragment attaches no shadow root of its own: a\n // shadow-rendered child keeps its <style> elements inline, next to the DOM\n // they style, and the parent's shadow root is what scopes both\n const holder = document.createDocumentFragment()\n // rendering a child happens on this same stack, so a component that\n // renders itself recurses as deep as its data does - and a cycle in that\n // data would recurse until the JS stack gave out, ~900 identical frames\n // naming nothing. Cut and named instead, exactly like the effect runner\n // cuts an effect that wakes itself\n if (nestingDepth >= MAX_NESTING_DEPTH) {\n console.error(\n `jq79: <${node.tag}> is ${MAX_NESTING_DEPTH} levels deep inside itself; giving up here. ` +\n \"A component that renders itself stops when its data stops - is there a cycle in it?\"\n )\n return\n }\n nestingDepth++\n try {\n ;(shadow ? instance.renderShadow(seed) : instance.render(seed)).mount(holder)\n } finally {\n nestingDepth--\n }\n endAnchor.parentNode!.insertBefore(holder, endAnchor)\n\n // deep: a prop sync forwards whatever the expression evaluates to, whole,\n // into the child's store - it reads `user`, never `user.name`, so it can't\n // track what it passes on. A parent's deep mutation reaches the child\n // through this effect or not at all (see $effect's `deep`)\n const syncFx = createEffectScope(scope, true)\n // without a spread the prop set is fixed and known: one effect per prop, so\n // a change to one prop re-syncs only that prop. A spread's key set is\n // dynamic and its precedence is positional, so it can't be resolved a key at\n // a time across independent effects (whichever re-ran last would win) - one\n // effect re-merges everything in order and writes the diff, clearing keys a\n // spread has dropped since last run. Named props are always in the merge, so\n // they're never cleared; the extra cost is confined to spread-using tags\n if (hasSpread) {\n let written: string[] = []\n syncFx.effect(() => {\n const next = pickDeclared(resolveProps(), declared)\n const nextKeys = Object.keys(next)\n written.forEach(key => { if (!(key in next)) (instance.data as Record<string, any>)[key] = undefined })\n nextKeys.forEach(key => { (instance.data as Record<string, any>)[key] = next[key] })\n written = nextKeys\n })\n } else {\n Object.entries(props).forEach(([name, expr]) => {\n if (declared !== null && !declared.has(name)) return\n syncFx.effect(() => { (instance.data as Record<string, any>)[name] = evalExpr(expr, scope) })\n })\n }\n\n childFx = syncFx\n current = instance\n })\n\n fx.onDispose(() => {\n childFx?.dispose()\n current?.destroy()\n })\n\n return wrapper\n}\n\n// :with=\"expr\" narrows the scope for an element and its subtree: names\n// resolve against the expression's value first, then fall back to the outer\n// scope. The value is re-evaluated lazily on every name lookup (never\n// snapshotted), so an effect reading through this proxy tracks both the\n// expression's own dependencies and the property it reads - replacing the\n// object or mutating one of its properties re-renders exactly the dependents,\n// without rebuilding the subtree. Assignments to names the object owns write\n// through to it (reactively, if it came from a store); everything else\n// behaves as if the :with weren't there\nconst createWithScope = (expr: string, scope: Record<string, any>): Record<string, any> => {\n const source = (): Record<string, any> | null => {\n const value = evalExpr(expr, scope)\n return value !== null && typeof value === \"object\" ? value : null\n }\n return new Proxy(scope, {\n has(target, key) {\n const obj = source()\n return (obj !== null && Reflect.has(obj, key)) || Reflect.has(target, key)\n },\n get(target, key) {\n const obj = source()\n if (obj !== null && Reflect.has(obj, key)) return obj[key as string]\n return Reflect.get(target, key)\n },\n set(target, key, value) {\n const obj = source()\n if (obj !== null && Reflect.has(obj, key)) {\n obj[key as string] = value\n return true\n }\n return Reflect.set(target, key, value)\n },\n })\n}\n\n// what :class accepts, flattened to single class tokens: a string of\n// space-separated names, an array (entries normalized recursively), or an\n// object whose truthy-valued keys are the names (a key may itself hold\n// several). Everything else - null, false, numbers - contributes nothing, so\n// `cond && 'active'` reads naturally. The object form reads each value, so a\n// store-backed flag is tracked per key\nconst classNames = (value: any): string[] => {\n if (typeof value === \"string\") return value.split(/\\s+/).filter(Boolean)\n if (Array.isArray(value)) return value.flatMap(classNames)\n if (value !== null && typeof value === \"object\")\n return Object.entries(value).flatMap(([name, on]) => (on ? classNames(name) : []))\n return []\n}\n\n// what :html.allowed accepts, normalized to an AllowUrl predicate: host\n// patterns (a comma-separated string or an array - see allowedHosts in\n// ./dom) or a function (url: URL, tag, attr) => boolean. Anything else -\n// including a policy expression that evaluates to undefined - denies every\n// destination: the attribute declares the intent to restrict, so a broken\n// policy fails closed, and so does a predicate that throws\nconst normalizeAllowUrl = (policy: any): AllowUrl => {\n if (typeof policy === \"function\") {\n return (url, tag, attr) => {\n try {\n return !!policy(url, tag, attr)\n } catch {\n return false\n }\n }\n }\n if (typeof policy === \"string\" || Array.isArray(policy)) return allowedHosts(policy)\n return () => false\n}\n\n// HTML's boolean attributes, verbatim from the spec's list. Presence is the\n// whole message for these: `disabled=\"false\"` and `disabled=\"0\"` both disable,\n// so the value they carry is noise. This is a table of a fact, not of a jq79\n// convention - nobody in this repo decides what belongs in it, which is what\n// earns it a place in a codebase that otherwise has no name tables\nconst BOOLEAN_ATTRS = new Set([\n \"allowfullscreen\", \"async\", \"autofocus\", \"autoplay\", \"checked\", \"controls\",\n \"default\", \"defer\", \"disabled\", \"formnovalidate\", \"inert\", \"ismap\",\n \"itemscope\", \"loop\", \"multiple\", \"muted\", \"nomodule\", \"novalidate\", \"open\",\n \"playsinline\", \"readonly\", \"required\", \"reversed\", \"selected\",\n])\n\n// the one value rule, shared by `:attr=\"expr\"` and `:attrs` so the two forms\n// can never disagree:\n//\n// - a boolean attribute is removed by ANY falsy value and set to \"\" when\n// truthy, so `:disabled=\"items.length\"` enables the button on an empty list\n// (with `value !== false` as the only test, 0 set the attribute and disabled\n// it - the trap renderComponent.test.ts used to pin);\n// - every other attribute is removed only by null/undefined, so `false`, `0`\n// and `\"\"` are written. `aria-expanded=\"false\"` and a `data-` flag mean\n// something that absent cannot say.\n//\n// Asking the DOM which family a name belongs to (`typeof el[name] ===\n// \"boolean\"`) is deliberately not what this does: jsdom and Chrome disagree on\n// `autofocus` and every `aria-*`, so the tests would pin a semantics the\n// browser doesn't have - and `readonly`/`novalidate`/`ismap` reflect under\n// camelCase property names no kebab->camel pass can produce, failing toward\n// `readonly=\"false\"`, which is read-only\nconst applyAttr = (el: Element, name: string, value: any) => {\n const boolean = BOOLEAN_ATTRS.has(name)\n if (boolean ? !value : value == null) el.removeAttribute(name)\n else el.setAttribute(name, boolean ? \"\" : String(value))\n}\n\n// renders a single element node: static attrs, @event listeners, a reactive\n// :attrs object, and its content - :text/:html override the element's own\n// children with a reactive textContent/innerHTML, otherwise children render\n// normally. :if/:elseif/:else/:each are handled by renderNodes, which decides\n// *whether*/*how many times* a node is rendered before calling this. Tags\n// matching a PascalCase scope variable render as nested components instead\nconst renderNode = (node: TemplateNode, outerScope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n // :with applies to the element's own bindings (@events, :attrs) and its\n // whole subtree. On a :each element the item scope is already in place, so\n // :with=\"item\" works\n const withExpr = node.attrs[\":with\"]\n const scope = withExpr !== undefined ? createWithScope(withExpr, outerScope) : outerScope\n\n // before the component-key scan, so <slot> is <slot> even in a file that\n // happens to have a component named Slot in scope: the tag is the library's\n // now, and a name that resolved it away would be a very quiet surprise\n if (isSlotTag(node.tag)) return renderSlot(node, scope, fx, shadow)\n if (node.tag === \"template\" && slotAttrOf(node) !== undefined) return misplacedSlotContent(node)\n\n const componentKey = findComponentKey(scope, node.tag)\n if (componentKey) return renderNestedComponent(componentKey, node, scope, fx, shadow)\n\n const el = document.createElement(node.tag)\n\n // <UserCrad /> - written as a component (node.component), resolving to no\n // component, and not an element either. Nothing else on the page can supply\n // the name once every script has settled, so this renders no markup, no\n // styles, no children and no script, forever, and says so by throwing rather\n // than leaving a hole where a region of the page was meant to be.\n //\n // All three conditions carry weight. Without the capitalization <lable> and\n // <svg> would be fatal (createElement builds SVG names in the HTML namespace,\n // so an <svg> is an HTMLUnknownElement too); without the element check <DIV>\n // would be, though it renders a perfectly good div; and without the pending\n // count a factory that awaits $mounted() before returning its components\n // could never render one, which is exactly what the watcher below is for.\n //\n // An *absent* count is a fourth case, and it is not zero: renderComponent()\n // renders a template against a store somebody else owns and assembles, so\n // nothing there has finished and nothing says a key can't still be written\n // in. The claim being tested is a component's claim about its own scripts,\n // and where none was made the tag waits for the upgrade, as it always has.\n //\n // Written without a local for the count because renderNode is on the stack\n // for the whole of the subtree below it, so a slot here is a slot per level\n // of a component nested inside itself - see renderWith\n if (node.component && el instanceof HTMLUnknownElement && ((scope as any)[PENDING_SCRIPTS] as PendingScripts | undefined)?.count === 0) {\n throw unresolvedComponent(node.component, scope)\n }\n\n // a tag that isn't standard HTML but has no matching scope key *yet* may be\n // a component that arrives later (e.g. an async factory script exposing an\n // imported component after `await`). Watch for the key: the effect tracks\n // no deps, so it only re-runs on the store's new-key sweep, and swaps the\n // placeholder element for the component exactly once\n // dashes included, because findComponentKey matches them case-insensitively\n // with dashes stripped: <drop-area> resolves DropArea, so a dashed tag is a\n // possible component too, not only a custom element\n const mayUpgrade = el instanceof HTMLUnknownElement || node.tag.includes(\"-\")\n if (mayUpgrade) {\n let upgraded = false\n fx.effect(() => {\n if (upgraded) return\n const key = findComponentKey(scope, node.tag)\n if (!key) return\n upgraded = true\n const replacement = renderNestedComponent(key, node, scope, fx, shadow)\n // whoever tears this subtree down holds `el`, which the swap detaches -\n // so the component's anchors must remove themselves when the scope goes\n const range = boundsOf(replacement)\n fx.onDispose(() => removeRange(range))\n el.replaceWith(replacement)\n })\n }\n\n Object.entries(node.attrs).forEach(([key, value]) => {\n if (key.startsWith(\"@\")) bindEvent(el, key, value, scope)\n else if (key === \":model\" || key.startsWith(\":model.\")) {\n // :model binds component tags only (see TODOS/2026-07-15.model-directive.md;\n // the native-element form is parked there). Warn on a real element, but\n // not on a tag that may still upgrade into a component - the upgrade\n // re-renders through renderNestedComponent, models and all\n if (!mayUpgrade) {\n console.warn(`jq79: ${key} on <${node.tag}> does nothing - :model binds component tags only (for now)`)\n }\n } else if (isControlAttr(key)) {\n // a directive of its own, bound further down (or by renderNodes)\n } else if (key.startsWith(\":\")) {\n // :name=\"expr\" binds that one attribute, reactively - the single-key\n // case :attrs=\"{ name: expr }\" was carrying. `:name` alone is shorthand\n // for `:name=\"name\"`, like props and :model.<name>, and the shorthand\n // reads the camelCase variable while the attribute keeps its written\n // (kebab) name: `:aria-expanded` binds `ariaExpanded`, because\n // `aria-expanded` as an expression is a subtraction.\n //\n // On a tag that may still upgrade this is a *parameter*, not an\n // attribute: leave it written verbatim, as before, so the upgrade's\n // renderNestedComponent still finds it. A component tag has no single\n // root for an attribute to land on anyway (TODOS/2026-07-15.class-directive.md)\n if (mayUpgrade) el.setAttribute(key, value)\n else {\n const name = key.slice(1)\n const expr = value || kebabToCamel(name)\n fx.effect(() => applyAttr(el, name, evalExpr(expr, scope)))\n }\n } else el.setAttribute(key, value)\n })\n\n const bindExpr = node.attrs[\":attrs\"]\n if (bindExpr !== undefined) {\n let boundKeys: string[] = []\n\n fx.effect(() => {\n boundKeys.forEach(key => el.removeAttribute(key))\n const bound = evalExpr(bindExpr, scope)\n boundKeys = bound && typeof bound === \"object\" ? Object.keys(bound) : []\n boundKeys.forEach(key => applyAttr(el, key, bound[key]))\n })\n }\n\n // :class=\"expr\" adds classes on top of the static `class` attribute, and\n // :class.<name>=\"expr\" is the single-flag shorthand for `{ <name>: expr }`\n // (the name routed through classNames, so an empty `:class.` can't reach\n // classList.add, which throws on \"\"). Both feed one effect and one set of\n // added classes: only classes this binding added are ever removed, so the\n // static list survives every re-run, even when the expression names one of\n // its classes and then drops it (class=\"btn\" :class=\"{ btn: cond }\" keeps\n // btn on false)\n const classExpr = node.attrs[\":class\"]\n const classToggles = Object.entries(node.attrs)\n .filter(([key]) => key.startsWith(\":class.\"))\n .map(([key, expr]): [string, string] => [key.slice(\":class.\".length), expr])\n if (classExpr !== undefined || classToggles.length) {\n const staticClasses = new Set(classNames(node.attrs.class ?? \"\"))\n let bound: string[] = []\n\n fx.effect(() => {\n const next = classExpr !== undefined ? classNames(evalExpr(classExpr, scope)) : []\n classToggles.forEach(([name, expr]) => {\n if (evalExpr(expr, scope)) next.push(...classNames(name))\n })\n bound.forEach(name => {\n if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)\n })\n el.classList.add(...next)\n bound = next\n })\n }\n\n // :text=\"expr\" sets textContent reactively, replacing any children.\n // :html=\"expr\" sets innerHTML reactively, sanitizing the value first so\n // untrusted content can't inject scripts/attributes (see sanitizeHTML in\n // ./dom). Both skip rendering the element's own children/interpolation.\n // :html.allowed=\"expr\" adds a destination policy for the content's\n // href/src URLs - evaluated in the same effect, so a policy held in the\n // store is as reactive as the content itself\n const textExpr = node.attrs[\":text\"]\n const htmlExpr = node.attrs[\":html\"]\n const allowedExpr = node.attrs[\":html.allowed\"]\n if (allowedExpr !== undefined && htmlExpr === undefined) {\n console.warn(\"jq79: :html.allowed without :html on the same element does nothing\")\n }\n if (textExpr !== undefined) {\n fx.effect(() => { el.textContent = String(evalExpr(textExpr, scope) ?? \"\") })\n } else if (htmlExpr !== undefined) {\n fx.effect(() => {\n const options = allowedExpr !== undefined ? { allowUrl: normalizeAllowUrl(evalExpr(allowedExpr, scope)) } : undefined\n el.innerHTML = sanitizeHTML(String(evalExpr(htmlExpr, scope) ?? \"\"), options)\n })\n } else if (el instanceof HTMLTemplateElement) {\n // a plain nested <template> stays what HTML says it is: an inert element\n // whose children live in .content, which is where whoever clones it looks\n // for them. They render (bindings and all) and go there - appended as\n // childNodes they would be in the DOM but in no document fragment, seen by\n // nothing and rendered by nobody\n renderNodes(node.children, scope, fx, shadow, el.content)\n } else {\n renderNodes(node.children, scope, fx, shadow, el)\n }\n\n // :value / :checked / :selected write the DOM *property*, not the\n // attribute - the attribute is only a form control's default, and detaches\n // the moment the user interacts (which is why :attrs=\"{ value }\" stops\n // driving a typed-in input). One-way, store -> DOM: the way back stays an\n // explicit @input/@change. :value skips the write when the property\n // already holds the string, so an unrelated re-run can't move the caret of\n // the input the user is typing into. Registered after the children render:\n // :value on a <select> can only pick an <option> that already exists\n const valueExpr = node.attrs[\":value\"]\n if (valueExpr !== undefined) {\n fx.effect(() => {\n const value = String(evalExpr(valueExpr, scope) ?? \"\")\n if ((el as HTMLInputElement).value !== value) (el as HTMLInputElement).value = value\n })\n }\n ;([\":checked\", \":selected\"] as const).forEach(attr => {\n const expr = node.attrs[attr]\n if (expr === undefined) return\n const prop = attr.slice(1) as \"checked\" | \"selected\"\n fx.effect(() => { (el as any)[prop] = !!evalExpr(expr, scope) })\n })\n\n return el\n}\n\n// a :if/:elseif*/:else? chain sharing one anchor comment so the active branch\n// can be swapped in place without disturbing sibling positions. Only depends\n// on whatever the branch expressions read (e.g. \"score\"), and skips\n// rebuilding entirely when the active branch hasn't actually changed\nconst renderConditional = (branches: ConditionalBranch[], scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const anchor = document.createComment(\"if\")\n const wrapper = document.createDocumentFragment()\n wrapper.appendChild(anchor)\n\n let current: NodeRange | null = null\n let activeBranch: ConditionalBranch | null = null\n let branchFx: EffectScope | null = null\n\n fx.effect(() => {\n const next = branches.find(branch => branch.expr === undefined || evalExpr(branch.expr, scope)) ?? null\n if (next === activeBranch) return\n\n branchFx?.dispose()\n if (current) removeRange(current)\n current = null\n activeBranch = next\n if (!next) return\n\n branchFx = createEffectScope(scope)\n // bounds captured before inserting: a component branch is a fragment, and\n // inserting it is what empties it (see boundsOf)\n const rendered = renderNode(next.node, scope, branchFx, shadow)\n current = boundsOf(rendered)\n anchor.parentNode!.insertBefore(rendered, anchor.nextSibling)\n })\n\n return wrapper\n}\n\n// defines a loop-local binding directly as `scope`'s own property. Plain\n// assignment (scope[key] = value) would only do this if the key isn't\n// already own on `scope` *or anywhere up its prototype chain* - if it isn't,\n// JS delegates the [[Set]] to whatever's up there, which for us is another\n// reactive proxy's `set` trap: it would wrap `value` as if it were a genuine\n// store mutation and fire a bogus notify() under a name (e.g. \"item\") shared\n// by every unrelated item in every :each on the page. defineProperty always\n// writes to `scope` itself, never delegating, so this can't happen\nconst defineScopeVar = (scope: Record<string, any>, key: string, value: any) => {\n Object.defineProperty(scope, key, { value, writable: true, enumerable: true, configurable: true })\n}\n\ntype EachEntry = { key: any; item: any; scope: Record<string, any>; range: NodeRange; fx: EffectScope }\n\n// what :each iterates besides arrays: dictionaries, as their entries. Class\n// instances, Maps and the rest stay out - the store doesn't wrap them\n// (isPlainData), so their contents wouldn't be tracked and the list would go\n// silently stale\nconst isPlainObject = (value: any): value is Record<string, any> => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n// :each=\"item in items\" (or \"item, i in items\" / \"(value, key) in props\"),\n// optionally keyed with :key=\"expr\". Only depends on what the list expression\n// reads, and on each run diffs by key: unchanged items (same key, same item\n// reference) keep their DOM/effects, changed/added ones are (re)rendered,\n// removed ones are disposed. Without :key, an array uses position - fine for\n// append-only lists, wasteful for reordering - and an object uses the\n// property key, which is already the stable identity. Each item gets its own\n// scope via Object.create(scope), so the bindings and `$index` shadow\n// same-named outer names without copying the parent scope's keys\n// does anything in this subtree name one of `names` as an identifier? Attribute\n// values and text alike, since either can hold an expression - a prop handing a\n// position to a nested component (`<Row :n=\"$index\">`) is an attribute on a node\n// inside the item, which is why the walk has to cover children's attrs too.\n//\n// Over-approximating is the safe direction and the intended one: a name that\n// appears in a string literal costs a refresh that wasn't needed, which is\n// exactly what happens today for every list. Missing one would leave a binding\n// stale, and the walk cannot - a template expression is source text\nconst mentionsAny = (node: TemplateNode | string, names: string[]): boolean => {\n if (typeof node === \"string\") return names.some(name => identifierIn(node, name))\n return Object.values(node.attrs).some(value => names.some(name => identifierIn(value, name))) ||\n node.children.some(child => mentionsAny(child, names))\n}\n\n// `name` as a whole word: `$index` must not match inside `$indexes`, and `i`\n// must not match inside `items`. `$` counts as a word character here, which is\n// why the boundaries are checked by hand rather than with \\b - \\b treats `$`\n// as a boundary and would find the `i` of `$index` when looking for `i`\nconst IDENTIFIER_CHAR = /[A-Za-z0-9_$]/\n\nconst identifierIn = (text: string, name: string): boolean => {\n for (let at = text.indexOf(name); at !== -1; at = text.indexOf(name, at + 1)) {\n const before = at === 0 ? \"\" : text[at - 1]\n const after = text[at + name.length] ?? \"\"\n if (!IDENTIFIER_CHAR.test(before) && !IDENTIFIER_CHAR.test(after)) return true\n }\n return false\n}\n\nconst renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {\n const match = node.attrs[\":each\"].match(EACH_PATTERN)\n if (!match) return document.createComment(`invalid :each expression \"${node.attrs[\":each\"]}\"`)\n\n const [, itemName, atName, listExpr] = match\n const keyExpr = node.attrs[\":key\"]\n const { [\":each\"]: _each, [\":key\"]: _key, ...itemAttrs } = node.attrs\n const itemNode: TemplateNode = { ...node, attrs: itemAttrs }\n\n // An entry that changed position needs its position-only bindings re-run -\n // `$index` and the `, at` name are plain scope vars, untracked by design, so\n // nothing can wake them (see EffectScope.refresh). But refresh re-runs *every*\n // effect on the entry, and in a list whose template names no position at all\n // - the common one - all of that recomputes strings that cannot have changed:\n // it was 9ms of removeRow's 25ms. Decided once, from the template, rather\n // than per row per render. The item name is deliberately not in this list:\n // nearly every binding reads it, and it is not what goes stale.\n // See TODOS/2026-08-23.positional-refresh.md\n const positionalNames = [\"$index\", ...(atName ? [atName] : [])]\n const readsPosition = mentionsAny(itemNode, positionalNames)\n\n const anchor = document.createComment(\"each\")\n const wrapper = document.createDocumentFragment()\n wrapper.appendChild(anchor)\n\n // :if on the same element is not per-item filtering, and rendering\n // everything in silence reads like a broken filter - say it out loud\n if (\":if\" in node.attrs || \":elseif\" in node.attrs || \":else\" in node.attrs) {\n console.warn(\"jq79: :if/:elseif/:else on a :each element is ignored; filter the list expression instead\")\n }\n\n let entries: EachEntry[] = []\n let warnedDuplicates = false\n\n // one memo for the whole diff: every row resolves its tags to the same scope\n // keys, so the scan that used to run per element per row now runs once per\n // distinct tag (see findComponentKey)\n fx.effect(() => {\n const pass = openRenderPass(scope)\n try {\n const list = evalExpr(listExpr, scope)\n // both sources normalize to [at, item] pairs: the index for an array, the\n // property key for a plain object (insertion order). Object entries are\n // read off the store proxy, so each value is tracked under its own key -\n // adds, deletes and changes all wake this effect\n const pairs: [any, any][] = Array.isArray(list)\n ? list.map((item, index): [any, any] => [index, item])\n : isPlainObject(list) ? Object.entries(list) : []\n // buckets rather than a key->entry map: duplicate keys (a user error, but\n // one that must degrade instead of corrupt) consume entries in order of\n // appearance, so no entry is ever matched twice - matching one twice is\n // how a reused row got disposed and a removed one resurrected\n const previous = new Map<any, EachEntry[]>()\n entries.forEach(entry => {\n const bucket = previous.get(entry.key)\n if (bucket) bucket.push(entry)\n else previous.set(entry.key, [entry])\n })\n\n const seen = new Set<any>()\n const moved: EachEntry[] = []\n const nextEntries = pairs.map(([at, item], index): EachEntry => {\n const itemScope = Object.create(scope)\n defineScopeVar(itemScope, itemName, item)\n if (atName) defineScopeVar(itemScope, atName, at)\n defineScopeVar(itemScope, \"$index\", index)\n const key = keyExpr !== undefined ? evalExpr(keyExpr, itemScope) : at\n if (seen.has(key) && !warnedDuplicates) {\n warnedDuplicates = true\n console.warn(`jq79: duplicate :key in :each \"${node.attrs[\":each\"]}\"; duplicates pair up by position`)\n }\n seen.add(key)\n const existing = previous.get(key)?.shift()\n\n if (existing && Object.is(existing.item, item)) {\n if (readsPosition && existing.scope.$index !== index) moved.push(existing)\n defineScopeVar(existing.scope, \"$index\", index)\n if (atName) defineScopeVar(existing.scope, atName, at)\n return existing\n }\n\n if (existing) {\n existing.fx.dispose()\n removeRange(existing.range)\n }\n\n const itemFx = createEffectScope(scope)\n // bounds captured before the positioning pass inserts the entry: a\n // component entry is a fragment, which empties on insertion (see boundsOf)\n const range = boundsOf(renderNode(itemNode, itemScope, itemFx, shadow))\n return { key, item, scope: itemScope, fx: itemFx, range }\n })\n\n // whatever no new item consumed is gone. Effects are torn down one by one\n // as always; the DOM goes in runs of neighbours, which is what makes\n // clearing a long list one mutation instead of one per row\n const dead = new Set<EachEntry>()\n previous.forEach(bucket => bucket.forEach(entry => dead.add(entry)))\n if (dead.size) {\n dead.forEach(entry => entry.fx.dispose())\n removeRuns(contiguousRuns(entries, entry => dead.has(entry)))\n }\n\n let prevNode: Node = anchor\n nextEntries.forEach(entry => {\n if (prevNode.nextSibling !== entry.range.first) moveRangeAfter(entry.range, prevNode)\n prevNode = entry.range.last\n })\n\n // reused entries that changed position: their tracked bindings re-run off\n // the list notification anyway, but a binding that reads only `$index` or\n // the named key tracked nothing - refresh them so the move reaches those\n // too. Untracked, so these runs don't feed this list effect's own deps\n moved.forEach(entry => untracked(() => entry.fx.refresh()))\n\n entries = nextEntries\n } finally {\n closeRenderPass(pass)\n }\n })\n\n return wrapper\n}\n\n// renders a list of sibling template nodes (text + elements), grouping\n// consecutive :if/:elseif/:else nodes into a single conditional block\n// `into` renders straight into an element that is not in the document yet -\n// what renderElement does for an element's own children. Every element used to\n// get a DocumentFragment of its own, filled and then emptied into it: for a\n// 10,000-row table that is 70,000 fragments and a second pass over every node,\n// and the intermediate is invisible either way because the element is still\n// detached. Callers that need a standalone chunk (a component's content, an\n// :if branch) omit it and get the fragment\nconst renderNodes = <T extends ParentNode>(\n nodes: (TemplateNode | string)[],\n scope: Record<string, any>,\n fx: EffectScope,\n shadow = false,\n into?: T\n): T | DocumentFragment => {\n const fragment = into ?? document.createDocumentFragment()\n let i = 0\n\n while (i < nodes.length) {\n const node = nodes[i]\n\n if (typeof node === \"string\") {\n const textNode = document.createTextNode(node)\n // static text is most of a template (all of its indentation, for a start):\n // only text with a {{ expression }} in it needs an effect to stay in sync\n if (node.includes(\"{{\")) fx.effect(() => { textNode.textContent = interpolate(node, scope) })\n fragment.appendChild(textNode)\n i++\n continue\n }\n\n if (\":each\" in node.attrs) {\n fragment.appendChild(renderEach(node, scope, fx, shadow))\n i++\n continue\n }\n\n if (\":if\" in node.attrs) {\n const branches: ConditionalBranch[] = [{ expr: node.attrs[\":if\"], node }]\n i++\n\n // the branches of a chain are siblings in the AST, but the template writes\n // them on their own lines - so the whitespace between them is indentation\n // and nothing else, and it's dropped rather than rendered: only one branch\n // is ever in the DOM, so there is nothing for it to be a space *between*\n const nextBranch = (attr: string): TemplateNode | undefined => {\n let next = i\n while (next < nodes.length && typeof nodes[next] === \"string\" && !(nodes[next] as string).trim()) next++\n const candidate = nodes[next]\n if (typeof candidate === \"object\" && attr in candidate.attrs) {\n i = next + 1\n return candidate\n }\n return undefined\n }\n\n for (let elseif = nextBranch(\":elseif\"); elseif; elseif = nextBranch(\":elseif\")) {\n branches.push({ expr: elseif.attrs[\":elseif\"], node: elseif })\n }\n const elseNode = nextBranch(\":else\")\n if (elseNode) branches.push({ node: elseNode })\n\n fragment.appendChild(renderConditional(branches, scope, fx, shadow))\n continue\n }\n\n fragment.appendChild(renderNode(node, scope, fx, shadow))\n i++\n }\n\n return fragment\n}\n\nexport const renderComponent = (component: Component79, data: ReactiveDeepData<Record<string, any>>, shadow = false): Node =>\n renderNodes(component.template, data, createEffectScope(data), shadow)\n\ntype ComponentParts = {\n template: TemplateNode[]\n scripts: TagBlock[]\n styles: TagBlock[]\n // pre-resolved modules for `import(...)` calls in setup scripts, keyed by\n // the literal specifier. Bundlers (the jq79/vite plugin) fill this so\n // imports resolve from the bundle instead of being fetched at runtime\n modules?: Record<string, any>\n // where this component came from (a URL for fetch(), a path for the vite\n // plugin). Names the setup scripts in devtools - see scriptSourceUrl\n filename?: string\n // the components the file's <template name=\"...\"> blocks declared, by name.\n // Every component parsed out of one file holds this same map - itself\n // included - which is what makes a sibling usable without an import, and\n // what lets a <template name=\"TreeNode\"> render a <TreeNode>\n siblings?: Record<string, Component79>\n // which of the file's components this is: a template's name, or undefined\n // for the file's own. The file is the hot-reload unit, so a reparse hands\n // each live instance the parts belonging to the component it is\n name?: string\n}\n\nconst VOID_ELEMENTS = new Set([\n \"area\", \"base\", \"br\", \"col\", \"embed\", \"hr\", \"img\", \"input\",\n \"link\", \"meta\", \"param\", \"source\", \"track\", \"wbr\",\n])\n\n// a self-closing tag with its attributes; quoted attribute values are matched\n// as whole chunks so a \"/>\" inside one doesn't end the tag early. The tag name\n// admits a dot for the named forms of a tag - <slot.header /> - which is a\n// legal HTML tag name (the tokenizer reads to the first space, \"/\" or \">\")\nconst SELF_CLOSING_RE = /<([A-Za-z][\\w.-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*?)\\/>/g\nconst RAW_BLOCK_RE = /(<script[\\s\\S]*?<\\/script\\s*>|<style[\\s\\S]*?<\\/style\\s*>)/gi\n\n// expands self-closing tags (<MyComponent />, <div />) into explicit\n// open+close pairs BEFORE DOM parsing. The HTML parser ignores the slash and\n// would treat them as unclosed, swallowing the following siblings. Void\n// elements keep their native behavior, and <script>/<style> contents are\n// passed through untouched so code inside them is never rewritten\nconst expandSelfClosingTags = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1 // odd chunks are the captured script/style blocks\n ? chunk\n : chunk.replace(SELF_CLOSING_RE, (match, tag: string, attrs: string) =>\n VOID_ELEMENTS.has(tag.toLowerCase()) ? match : `<${tag}${attrs}></${tag}>`\n )\n )\n .join(\"\")\n\n// a start tag with its attributes, quote-aware so a \">\" inside a value doesn't\n// end it early; and a single spread attribute in name position (preceded by\n// start-or-whitespace), its expression an identifier or member path\nconst OPEN_TAG_RE = /<([A-Za-z][\\w.-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>/g\nconst ATTR_SPREAD_RE = /\"[^\"]*\"|'[^']*'|(^|\\s)\\.\\.\\.([A-Za-z_$][\\w$.]*)/g\n\n// `...expr` as an attribute is sugar for :props=\"expr\" (spread an object's\n// properties as props - see renderNestedComponent). Rewritten BEFORE DOM\n// parsing, into a value-based :props.<n>, because the HTML parser lowercases\n// attribute *names*: with the expression in the name, `...userData` would arrive\n// as `...userdata` and resolve to nothing. Moving it into a value - which the\n// parser leaves untouched - keeps camelCase intact. Same pre-parse string move\n// as expandSelfClosingTags, with the same defenses against rewriting code that\n// only looks like a spread: <script>/<style> bodies are split out (a JS `...rest`\n// there is not an attribute), only a start tag's interior is scanned (text\n// between tags is safe), and quoted values are consumed whole so a genuine JS\n// spread in a value (@click=\"f(...args)\", :x=\"{ ...a }\") is skipped. The <n>\n// suffix (per tag) only keeps several spreads' attribute names distinct. A call\n// (`...getProps()`) stops at the paren and is left alone - use :props=\"expr()\"\nconst expandPropsSpread = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1\n ? chunk\n : chunk.replace(OPEN_TAG_RE, (_match, tag: string, attrs: string) => {\n let n = 0\n const rewritten = attrs.replace(ATTR_SPREAD_RE, (whole, space: string | undefined, expr: string | undefined) =>\n expr === undefined ? whole : `${space}:props.${n++}=\"${expr}\"`\n )\n return `<${tag}${rewritten}>`\n })\n )\n .join(\"\")\n\n// a `:`-prefixed attribute name in name position, and a </slot.name> closing\n// tag. Both quote-aware for the same reason ATTR_SPREAD_RE is: a colon inside\n// a value (@click=\"a ? b : c\", style=\"color: red\") is not an attribute name\nconst ATTR_NAME_RE = /\"[^\"]*\"|'[^']*'|(^|\\s)(:[\\w.$-]+)/g\nconst CLOSE_SLOT_RE = /<\\/slot\\.([\\w.$-]+)(\\s*)>/gi\nconst SLOT_TAG_RE = /^slot\\./i\n\n// camelCase -> kebab-case for every name the HTML parser would lowercase,\n// BEFORE it gets the chance: `:firstName` would arrive as `:firstname` and\n// kebabToCamel (which is what reads these names back out) would have nothing\n// to un-kebab, so the prop, model or slot would silently land under the wrong\n// key. Rewriting to `:first-name` here means both spellings converge on the\n// same camelCase name downstream - the author picks, the runtime doesn't care.\n//\n// Runs FIRST among the pre-parse passes, which is what keeps it simple: it\n// never sees the `:props.<n>` that expandPropsSpread generates, and a\n// <slot.firstName /> is still one occurrence rather than the open+close pair\n// expandSelfClosingTags turns it into. Same defenses as the passes after it -\n// <script>/<style> bodies split out, only start-tag interiors scanned, quoted\n// values consumed whole.\n//\n// Two name positions, not one: attribute names (`:model.firstName`) and the\n// dotted tag names (`<slot.firstName>`), whose closing halves are rewritten\n// too or the parser sees a mismatched pair. Component tags are deliberately\n// left alone - findComponentKey already matches them case-insensitively with\n// dashes stripped, so <UserCard> needs no help and rewriting it would only\n// obscure what the author wrote\nconst kebabTagName = (tag: string): string =>\n SLOT_TAG_RE.test(tag) ? `slot.${camelToKebab(tag.slice(\"slot.\".length))}` : tag\n\n// the same pass records what it declined to rewrite. An uppercase-initial tag\n// is a claim about a component: HTML's own elements are matched\n// case-insensitively but nobody writes <DIV> by accident, and a custom element\n// may not be spelled that way at all. So <UserCard> is a name the author\n// expected to resolve - which is what lets renderNode throw when it doesn't\n// (see unresolvedComponent).\n//\n// Carried in a *value* rather than left in the tag name, because the value is\n// the one place the HTML parser preserves case - the same move expandPropsSpread\n// makes for `...userData`, and for the same reason. elementToAST lifts it\n// straight off attrs into a field, so no attribute loop downstream ever sees\n// it - and since that lift is unconditional, the name has to be one no author\n// would write: a plain `:component` would eat the prop of that name off\n// <Card :component=\"Widget\" />\nconst COMPONENT_TAG_ATTR = \":jq79-component\"\nconst COMPONENT_TAG_RE = /^[A-Z]/\n\n// appends the stamp inside the tag, *before* a self-closing slash: this pass\n// runs first and expandSelfClosingTags still has to recognize the `/>` that\n// OPEN_TAG_RE swept into the attributes. A slash inside a quoted value can't be\n// mistaken for it - only a trailing one is matched\nconst TRAILING_SLASH_RE = /\\/\\s*$/\n\nconst stampComponentTag = (tag: string, attrs: string): string => {\n if (!COMPONENT_TAG_RE.test(tag)) return attrs\n const stamp = ` ${COMPONENT_TAG_ATTR}=\"${tag}\"`\n const slash = TRAILING_SLASH_RE.exec(attrs)\n return slash ? `${attrs.slice(0, slash.index)}${stamp}${slash[0]}` : `${attrs}${stamp}`\n}\n\nconst expandNameCase = (src: string): string =>\n src\n .split(RAW_BLOCK_RE)\n .map((chunk, i) =>\n i % 2 === 1\n ? chunk\n : chunk\n .replace(OPEN_TAG_RE, (_match, tag: string, attrs: string) => {\n const rewritten = attrs.replace(ATTR_NAME_RE, (whole, space: string | undefined, name: string | undefined) =>\n name === undefined ? whole : `${space}${camelToKebab(name)}`\n )\n return `<${kebabTagName(tag)}${stampComponentTag(tag, rewritten)}>`\n })\n .replace(CLOSE_SLOT_RE, (_match, suffix: string, space: string) => `</slot.${camelToKebab(suffix)}${space}>`)\n )\n .join(\"\")\n\n// <style scoped> support. Every element of the component's own template is\n// stamped with data-jq79=\"<hash>\" and the style's selectors are rewritten to\n// require that attribute, so its rules can't reach anything the component\n// didn't render. Purely a runtime transform (the browser parses the CSS), so\n// it works the same for a bundled component and one loaded with fetch()\nconst SCOPE_ATTR = \"data-jq79\"\n\n// FNV-1a over the source: stable per definition (not per instance), so N\n// instances of the same component share one refcounted <style> in the head\nconst scopeHash = (src: string): string => {\n let hash = 2166136261\n for (let i = 0; i < src.length; i++) hash = Math.imul(hash ^ src.charCodeAt(i), 16777619)\n return (hash >>> 0).toString(36)\n}\n\nconst stampScope = (nodes: (TemplateNode | string)[], scope: string) => {\n nodes.forEach(node => {\n if (typeof node === \"string\") return\n node.attrs[SCOPE_ATTR] = scope\n stampScope(node.children, scope)\n })\n}\n\n// the scope attribute goes on the selector's last compound - the element the\n// rule actually targets - but *before* a pseudo-element, which must stay last\n// (\".a::before\" scopes to \".a[data-jq79='x']::before\", not \"::before[...]\")\nconst scopeSelector = (selectorText: string, scope: string): string =>\n selectorText\n .split(\",\")\n .map(part => {\n const selector = part.trim()\n const pseudoAt = selector.indexOf(\"::\")\n const target = pseudoAt === -1 ? selector : selector.slice(0, pseudoAt)\n const pseudoElement = pseudoAt === -1 ? \"\" : selector.slice(pseudoAt)\n return `${target}[${SCOPE_ATTR}=\"${scope}\"]${pseudoElement}`\n })\n .join(\", \")\n\n// CSSStyleRule is scoped in place; CSSGroupingRule (@media, @supports,\n// @container) is recursed into; everything else - notably @keyframes, whose\n// \"selectors\" are percentages - is left alone\nconst scopeRules = (rules: CSSRuleList, scope: string) => {\n Array.from(rules).forEach(rule => {\n if (rule instanceof CSSStyleRule) rule.selectorText = scopeSelector(rule.selectorText, scope)\n else if (rule instanceof CSSGroupingRule) scopeRules(rule.cssRules, scope)\n })\n}\n\n// the CSS parser is the browser's own (no dependency, no hand-rolled parser).\n// Note browsers *silently drop* rules whose selector they can't parse, which\n// is what Vue's :deep()/::v-deep/>>> escape hatches are - unsupported here,\n// and warned about rather than left to vanish\nconst scopeCss = (css: string, scope: string): string => {\n if (/:deep\\(|::v-deep|>>>/.test(css)) {\n console.warn(\"jq79: :deep()/::v-deep/>>> are not supported in <style scoped>; the rule will be dropped by the browser\")\n }\n const sheet = new CSSStyleSheet()\n sheet.replaceSync(css)\n scopeRules(sheet.cssRules, scope)\n return Array.from(sheet.cssRules).map(rule => rule.cssText).join(\"\\n\")\n}\n\n// a component name has to be PascalCase to be usable: findComponentKey only\n// ever considers capitalized scope keys, so a lowercase name would declare a\n// component no tag could reference. It is also what keeps the named exports\n// from colliding with a definition's own fields, which are all lowercase\nconst COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]*$/\n\n// converts a string of HTML into an AST representation of the component:\n// - template: the non-script/style top-level elements, as TemplateNodes\n// - scripts/styles: { attrs, content } blocks in source order\n// - siblings: the components its top-level <template name=\"...\"> declared\nconst parseComponentString = (component: string): ComponentParts => {\n // example\n // <script :setup=\"{ fname, lname }\">\n // const fullName = `${fname} ${lname}`\n // </script>\n //\n // <div :attrs=\"{ fullName }\"></div>\n // <div class=\"full-name\">\n // {{ fullName }}\n // </div>\n //\n // <style>\n // .full-name {\n // color: red;\n // }\n // </style>\n\n // parsed as the content of a <template> so leading <script>/<style> tags\n // aren't reparented into <head> by the HTML parser. All three pre-DOM string\n // rewrites run here, and the order is load-bearing: camelCase names ->\n // kebab-case first (before `:props.<n>` exists to be mangled and while a\n // self-closing tag is still one occurrence), then `...expr` -> :props.<n>\n // (which reads the raw camelCase before the parser can lowercase names),\n // then self-closing tags\n const prepared = expandSelfClosingTags(expandPropsSpread(expandNameCase(component)))\n const parsedDOM = new DOMParser().parseFromString(`<template>${prepared}</template>`, \"text/html\")\n const root = parsedDOM.querySelector(\"template\") as HTMLTemplateElement\n\n // a top-level <template> declares another component of this file; everything\n // else is this one's own\n const own: Element[] = []\n const declarations: HTMLTemplateElement[] = []\n Array.from(root.content.children).forEach(el => {\n if (el.tagName === \"TEMPLATE\") declarations.push(el as HTMLTemplateElement)\n else own.push(el)\n })\n\n // the file's own component hashes the whole file: every component in it\n // re-renders on any edit anyway (the file is the hot-reload unit), so a\n // stamp that changes when a sibling is edited costs nothing, and scopeHash\n // gets to keep hashing the source it was handed\n const parts = componentPartsFrom(own, component)\n\n // one map, shared by reference: it is filled below, after each definition\n // has already been handed it, so every component of the file sees all the\n // others *and itself* - which is what makes a recursive component possible\n const siblings: Record<string, Component79> = {}\n declarations.forEach(el => {\n const name = el.getAttribute(\"name\")\n // ignored rather than fatal, like every other malformed thing here: a bad\n // save mid-typing must not take the page down, least of all under HMR\n if (name === null) {\n console.warn(\"jq79: a top-level <template> without a name declares nothing and was ignored\")\n return\n }\n if (!COMPONENT_NAME_RE.test(name)) {\n console.warn(\n `jq79: <template name=\"${name}\"> was ignored - a component name has to be PascalCase, ` +\n \"or no tag could ever reference it (only capitalized names resolve as components)\"\n )\n return\n }\n if (name in siblings) {\n console.warn(`jq79: two <template name=\"${name}\"> in one file; the second was ignored`)\n return\n }\n // its own source is its own scope: a named template is a shadow root\n // inside a shadow root, so the file's scoped rules stop at its boundary\n // and its own stop there too\n siblings[name] = new Component79({ ...componentPartsFrom(Array.from(el.content.children), el.innerHTML), siblings, name })\n })\n if (Object.keys(siblings).length) parts.siblings = siblings\n\n return parts\n}\n\n// the script/style/markup split of one component's top-level elements, with\n// <style scoped> resolved against the source those elements came from - the\n// whole file for its own component, a <template>'s contents for a named one,\n// so the two get different stamps and neither can style the other\nconst componentPartsFrom = (elements: Element[], hashSource: string): ComponentParts => {\n const scripts: TagBlock[] = []\n const styles: TagBlock[] = []\n const template: TemplateNode[] = []\n\n elements.forEach(el => {\n const block: TagBlock = { attrs: elementAttrs(el), content: el.textContent ?? \"\" }\n\n if (el.tagName === \"SCRIPT\") scripts.push(block)\n else if (el.tagName === \"STYLE\") styles.push(block)\n else template.push(elementToAST(el))\n })\n\n // <style lang=\"scss\"> is compiled by the jq79/vite plugin, so a `lang` still\n // here means this component never went through it - it was fetched, loaded\n // from a URL, or built from an inline string. The browser would drop the\n // uncompiled source without a word, so say it out loud instead\n styles.forEach(style => {\n if (\"lang\" in style.attrs) {\n console.warn(\n `jq79: <style lang=\"${style.attrs.lang}\"> needs the jq79/vite plugin to compile it. ` +\n \"This component didn't go through the bundler, so its styles were left uncompiled and the browser will ignore them.\"\n )\n }\n })\n\n // scoping is resolved once, here: the stamped template and the scoped CSS\n // are what every instance of this definition renders and injects. An\n // uncompiled `lang` block is left as it was written - rewriting selectors\n // in something that isn't CSS yet would only garble what devtools shows\n const isScoped = (style: TagBlock) => \"scoped\" in style.attrs && !(\"lang\" in style.attrs)\n if (styles.some(isScoped)) {\n const scope = scopeHash(hashSource)\n stampScope(template, scope)\n styles.forEach(style => {\n if (isScoped(style)) style.scoped = scopeCss(style.content, scope)\n })\n }\n\n return { template, scripts, styles }\n}\n\n// loads .html URLs as components, delegating anything else to native import().\n// Goes to fetchComponent rather than Component79.fetch because an import wants\n// the component, not the chainable handle the public entry point returns\nconst importResource = (url: string): Promise<any> =>\n /\\.html?([?#]|$)/.test(url) ? fetchComponent(url) : import(url)\n\n// a relative specifier means \"next to the file that wrote it\", so it is\n// resolved against the component's own URL before importResource sees it -\n// neither of that function's two branches would otherwise land there. The\n// native import() inside it resolves against *this module* (dist/jq79.js), and\n// fetch() against the document; a component in a subdirectory gets a 404 from\n// the first and the page's directory from the second.\n//\n// What comes back is always a fully absolute URL, and that is the load-bearing\n// part rather than a detail of formatting. A *path* would be resolved by that\n// same native import() against the library module's ORIGIN - and the library\n// is the one file on the page most likely to come from somewhere else:\n//\n// page http://localhost:8024/craft/app.html\n// jq79 https://jgermade.github.io/jq79/jq79.js\n// \"/craft/services/x.js\" -> https://jgermade.github.io/craft/services/x.js\n//\n// which is a CORS error naming a host the app never mentioned. Only an\n// absolute URL means the same thing to both branches.\n//\n// For the same reason a *root-absolute* specifier is resolved too, not passed\n// through: `/x.js` means the page's root to whoever wrote it, and the page is\n// the only base under which the two branches agree. Bare specifiers (\"lodash\")\n// are the exception that stays untouched - they belong to the import map or\n// the bundler, and resolving one would quietly turn it into a path.\n//\n// The base is absolutized first, the way hotKey does and for the same reason:\n// the filename may itself be relative (\"./card.html\", from an import() in a\n// parent), and a relative URL cannot be a base\nconst RESOLVABLE_SPECIFIER_RE = /^(?:\\.\\.?\\/|\\/|[a-z][a-z0-9+.-]*:)/i\n\nconst resolveSpecifier = (spec: string, filename: string | undefined): string => {\n if (!RESOLVABLE_SPECIFIER_RE.test(spec)) return spec\n try {\n return new URL(spec, new URL(filename ?? \"\", document.baseURI)).href\n } catch {\n return spec\n }\n}\n\n// ---------------------------------------------------------------------------\n// naming scripts for devtools\n//\n// setup scripts are compiled with new Function (they need `with`, which is a\n// SyntaxError in a module), so no bundler source map can reach them: they show\n// up as an anonymous \"VM1234\" script, breakpoints don't survive a reload, and\n// stack traces name nothing. A //# sourceURL comment fixes all three - the\n// compiled script takes the component's name, so it is findable in the sources\n// tree, keeps its breakpoints, and appears by name in stack traces.\n//\n// The line numbers it reports are the compiled script's own, not the .html\n// file's: the engine wraps a Function body in a header (\"function anonymous(\n// args\\n) {\\n\") that shifts everything down, and no amount of padding can\n// shift code *up* to match a <script> sitting on line 1. Reporting the\n// component's real lines would need a source map, which the runtime doesn't\n// emit today\n// ---------------------------------------------------------------------------\n\n// where a script block came from: the component's filename, and its index\n// among the component's scripts (two scripts in one file need distinct names,\n// or devtools shows only one of them)\ntype ScriptLocation = { filename?: string; index?: number }\n\n// what running a script tells its caller: the promise it settles through, and\n// whether it already finished on this stack. `sync` is the fast path the render\n// gate is built on - see runSetupScript\ntype ScriptRun = { settled: Promise<unknown>; sync: boolean }\n\n// nothing to name an inline component's scripts after, so they stay anonymous\nconst sourceUrlComment = (filename: string | undefined, index: number): string =>\n filename ? `\\n//# sourceURL=${filename}?jq79-script=${index}` : \"\"\n\n// what a <style> block injects into document.head: the scoped rewrite when it\n// has one, the source otherwise. A shadow root uses `content` directly instead\n// - scoping is what a shadow root already does, and doing both would break the\n// `:host` rules only shadow rendering can have (`:host[data-jq79=...]` matches\n// nothing: the host element is outside the template, so it carries no stamp)\nconst headStyle = (style: TagBlock): string => style.scoped ?? style.content\n\n// document.head styles are shared by content and refcounted, so N instances\n// of the same component (e.g. one per :each item) inject a single <style> tag\n// that goes away when the last instance is destroyed\nconst styleRegistry = new Map<string, { el: HTMLStyleElement; count: number }>()\n\nconst acquireStyle = (content: string) => {\n let entry = styleRegistry.get(content)\n if (!entry) {\n const el = document.createElement(\"style\")\n el.textContent = content\n document.head.appendChild(el)\n entry = { el, count: 0 }\n styleRegistry.set(content, entry)\n }\n entry.count++\n}\n\nconst releaseStyle = (content: string) => {\n const entry = styleRegistry.get(content)\n if (entry && --entry.count <= 0) {\n entry.el.remove()\n styleRegistry.delete(content)\n }\n}\n\n// scripts run inside `with (scriptScope)`, where scriptScope's `has` trap\n// claims ownership of every name that is neither a real global, an injected\n// library helper, nor one of the internal helpers. This makes `with` route ALL\n// other reads/writes through the reactive store - even bare assignments to\n// names never declared with let/const, which would otherwise leak onto\n// globalThis - while `console`, `Promise`, `fetch`, etc. still resolve\n// normally. get/set are deliberately not trapped: they default-forward to\n// `scope` (the reactive proxy), preserving tracking and notify.\n// The body is wrapped in an async IIFE so top-level `await` works: everything\n// up to the first await runs synchronously, and later assignments update the\n// DOM reactively when they happen.\n//\n// Returns whether the body ran to completion synchronously, plus the promise it\n// settles through. renderWith needs the *synchronous* answer - a script that\n// finished in this turn cannot hold anything up, so the template can render on\n// this stack exactly as it always has (see the render gate). Asking the promise\n// instead would defer every render by a microtask, including the overwhelmingly\n// common case of a script with no await in it at all.\n//\n// The flag is set on the code's last line, after the `with` block rather than\n// inside it, so the scope proxy never sees the name - and appended, so the\n// author's line numbers (which sourceUrlComment maps for devtools) don't shift\nconst runSetupScript = (code: string, scope: Record<string, any>, effect: (run: () => void) => void, instanceHelpers: Record<string, any> = {}, importer: (url: string) => Promise<any> = importResource, at: ScriptLocation = {}): ScriptRun => {\n // instanceHelpers are per-component-instance additions (e.g. $emit, which\n // is bound to this instance's DOM position)\n const helpers = { ...SETUP_HELPERS, ...instanceHelpers }\n const scriptScope = new Proxy(scope, {\n has: (target, key) =>\n key !== \"$__effect\" && key !== \"$__import\" && key !== \"$__state\" &&\n (Reflect.has(target, key) || !(key in globalThis) && !(key in helpers)),\n })\n const state: { done?: boolean } = {}\n const result: Promise<void> = new Function(\n \"$scope\", \"$__effect\", \"$__import\", \"$__state\", ...Object.keys(helpers),\n `return (async () => { with ($scope) { ${code} }\\n;$__state.done = true })()${sourceUrlComment(at.filename, at.index ?? 0)}`\n )(scriptScope, effect, importer, state, ...Object.values(helpers))\n result.catch(error => console.error(\"jq79: error in :setup script\", error))\n trackScript(result)\n return { settled: result, sync: state.done === true }\n}\n\n// puts a component's declared props on the store, before any script runs and\n// before the first render: the names, so the template can bind to them even\n// when the parent passes nothing, and the defaults, so it binds to something.\n//\n// A prop the parent *did* pass is already on the store (render() seeds it), so\n// a default only fills an `undefined` - which is also what JS destructuring\n// does with the same pattern, so both modes agree. It happens once, at setup:\n// re-applying a default later would need an effect that reads and writes the\n// same key, and that effect would wake itself forever.\n//\n// `null` props means the component declared no signature at all, which is not\n// the same as declaring an empty one: it keeps today's permissive behavior\nconst declareProps = (store: Record<string, any>, props: PropDecl[] | null) => {\n props?.forEach(({ name, default: expr }) => {\n if (store[name] !== undefined) return\n store[name] = expr === undefined ? undefined : evalExpr(expr, store)\n })\n}\n\n// a setup script's signature. A bare `<script :setup>` is a CLOSED signature -\n// the same as `<script :setup=\"{}\">`, declaring zero props and taking none -\n// because the difference between \"takes nothing\" and \"takes anything\" should\n// not be a pair of braces somebody didn't type. Permissive is still reachable,\n// it just has to be asked for: `<script :setup=\"_\">`, the same `_` convention\n// factory scripts already use, which parsePropsPattern reads as no signature.\n//\n// Only the empty *value* is closed. An absent attribute (a factory <script>\n// with no :setup at all) stays `null`, so its signature is still read from the\n// factory's first parameter\nconst setupSignature = (script: TagBlock): PropDecl[] | null => {\n const pattern = script.attrs[\":setup\"]\n if (pattern === undefined) return null\n if (pattern.trim() === \"\") return []\n const props = parsePropsPattern(pattern)\n if (!props) warnUnreadableSignature(script, pattern)\n return props\n}\n\n// script blocks already warned about, keyed by the block itself - parsed once\n// and shared by every instance of a definition, the same reason warnUndeclared\n// keys on the template node. It matters for a smaller reason here too:\n// setupSignature is called three times per render (both declared-name passes\n// and the script loop's declareProps), so even one mount would say it thrice\nconst signatureWarned = new WeakSet<TagBlock>()\n\n// a value that isn't a props pattern reads as \"declared no signature\", which is\n// the most permissive mode there is - so a typo doesn't fail, it quietly opts\n// the component out of the contract it was trying to write. That is now the\n// only accidental route left to permissive: a bare :setup is closed and `_` is\n// the opt-out you have to ask for, so the mode nothing lands in by accident is\n// still reachable by getting it wrong. Both of parsePropsPattern's nulls count\n// - not-an-object (\",{ a }\", \"props\") and unbalanced (\"{ a, b\") - and only `_`\n// is exempt, because intent is the sole thing separating it from the typos\nconst warnUnreadableSignature = (script: TagBlock, pattern: string) => {\n if (pattern.trim() === \"_\" || signatureWarned.has(script)) return\n signatureWarned.add(script)\n console.warn(\n `jq79: :setup=\"${pattern}\" is not a props pattern, so this component declares no ` +\n `signature and takes whatever a parent passes - write the props it takes ` +\n `(\"{ a, b }\"), a bare :setup for none, or \"_\" to stay open on purpose`\n )\n}\n\n// every prop name a component's scripts declare, across both script modes.\n// Read before the store exists, because what a component declares decides\n// which of its file's sibling components it can still see: declaring a name\n// says it comes from the parent, so the file's own definition of that name is\n// deliberately not in this component's scope\nconst declaredPropNames = (scripts: TagBlock[]): Set<string> => {\n const names = new Set<string>()\n scripts.forEach(script => {\n const declarations = parseFactoryProps(script.content) ?? setupSignature(script)\n declarations?.forEach(({ name }) => names.add(name))\n })\n return names\n}\n\n// the same names, but null when NO script declared a signature at all - the\n// distinction declareProps already keeps, and the only one that can decide\n// whether to filter what a parent passes. `<script :setup>` and\n// `<script :setup=\"{}\">` are both closed signatures that take nothing (see\n// setupSignature); `<script :setup=\"_\">` is the permissive one\nconst declaredPropSet = (scripts: TagBlock[]): Set<string> | null => {\n let names: Set<string> | null = null\n scripts.forEach(script => {\n const declarations = parseFactoryProps(script.content) ?? setupSignature(script)\n if (!declarations) return\n const into = (names ??= new Set())\n declarations.forEach(({ name }) => into.add(name))\n })\n return names\n}\n\n// drops the props a component didn't declare, so an undeclared name is simply\n// absent from its store rather than quietly present: `{{ label }}` renders\n// empty and `{{ user.name }}` throws on the member access, both at the usage\n// site that got the name wrong. A null signature keeps everything - see\n// declaredPropSet. Silent by design: the main source of extra keys is a\n// `:props` spread of an object wider than the component (`...sdk`), where\n// taking only the declared few is the point, not a mistake to report\nconst pickDeclared = (props: Record<string, any>, declared: Set<string> | null): Record<string, any> => {\n if (declared === null) return props\n const out: Record<string, any> = {}\n Object.keys(props).forEach(key => { if (declared.has(key)) out[key] = props[key] })\n return out\n}\n\n// names already reported by warnUndeclared, keyed by the template node - which\n// is the usage site itself, built once and shared by every instance it ever\n// renders. So a :each over 200 rows says it once, not once per row, and a\n// definition swap doesn't repeat what the last one already said\nconst undeclaredWarned = new WeakMap<TemplateNode, Set<string>>()\n\n// a parameter the child's signature doesn't declare is dropped by pickDeclared\n// and never reaches its store - `{{ bar }}` renders empty at the other end of\n// the file. Written parameters only: this is handed the named ones (`:bar`,\n// and the prop each :model binds), never a `:props` spread's keys, because a\n// spread of an object wider than the component is the documented, intended use\n// and taking only the declared few is its point - see pickDeclared. A\n// component with no signature at all declares nothing to compare against\nconst warnUndeclared = (node: TemplateNode, name: string, written: string[], declared: Set<string> | null) => {\n if (declared === null) return\n const said = undeclaredWarned.get(node) ?? new Set<string>()\n undeclaredWarned.set(node, said)\n written.forEach(prop => {\n if (declared.has(prop) || said.has(prop)) return\n said.add(prop)\n console.warn(`jq79: :${prop} is not declared by <${name}> - add it to the :setup signature, or drop it`)\n })\n}\n\n// the sibling components this one resolves by name, or null when there are\n// none left to resolve. They go on the store's *prototype* rather than in it:\n// the component-key scan walks the chain, so <Row> resolves; they stay out of\n// the data, so Object.keys, snapshots and spreads never see them; and an own\n// key shadows a prototype one, so a prop the parent did pass wins for free\nconst siblingsInScope = (\n siblings: Record<string, Component79> | undefined,\n declared: Set<string>\n): Record<string, Component79> | null => {\n if (!siblings) return null\n // null-prototype, for the same reason storeApi is: `key in scope` must not\n // start answering true for toString, constructor and the rest\n const inScope: Record<string, Component79> = Object.create(null)\n let any = false\n Object.entries(siblings).forEach(([name, component]) => {\n if (declared.has(name)) return\n inScope[name] = component\n any = true\n })\n return any ? inScope : null\n}\n\n// names a component declared as props and the parent passed nothing for. Such\n// a name can never become a component later - there is no binding on the tag\n// to update it - so a <Tag> reading one is a wiring mistake that can be named\n// on sight, unlike the `undefined` of an import still in flight. Symbol-keyed\n// and non-enumerable: it rides the scope chain (so an :each item scope finds\n// it too) without ever showing up as data\nconst UNFILLED_PROPS = Symbol(\"jq79.unfilledProps\")\n\n// how many of this render generation's scripts have yet to settle, as a live\n// box rather than a snapshot. Rides the scope chain like UNFILLED_PROPS, and\n// for one reader: a <Tag> naming no component in scope is only a mistake once\n// nothing is left that could still supply the name.\n//\n// The count is not the render gate. A script that called $mounted() released\n// the template and is still running - that is the whole point of the call - so\n// at paint time this can be non-zero, and a name arriving from a factory that\n// awaited $mounted() is exactly the case the count keeps quiet. Read live, so\n// an :if that opens after everything settled is judged against the scripts as\n// they are then, not as they were at the first paint\nconst PENDING_SCRIPTS = Symbol(\"jq79.pendingScripts\")\n\ntype PendingScripts = { count: number }\n\n// default-import interop for factory scripts: real modules expose .default,\n// while importing an .html component resolves to the Component79 itself\nconst interopDefault = (mod: any) => (mod && mod.default !== undefined ? mod.default : mod)\n\n// runs a factory script: the (rewritten) module body executes in plain\n// lexical strict-mode scope - no `with`, no implicit reactivity - with the\n// library helpers as parameters, then the default export is called with the\n// instance context and a returned object is merged into the store. A fully\n// synchronous body invokes the factory before the first render, matching\n// setup-script timing; bodies with top-level await (static imports included)\n// resolve later and the template updates reactively\nconst runFactoryScript = (code: string, scope: Record<string, any>, effect: (run: () => void) => void, instanceHelpers: Record<string, any> = {}, importer: (url: string) => Promise<any> = importResource, at: ScriptLocation = {}): ScriptRun => {\n const helpers = { ...SETUP_HELPERS, ...instanceHelpers }\n const $__exports: { default?: (props: Record<string, any>, ctx: Record<string, any>) => any; done?: boolean } = {}\n const result: Promise<void> = new Function(\n \"$__exports\", \"$__default\", \"$__import\", ...Object.keys(helpers),\n `return (async () => { \"use strict\";\\n${code}\\n;$__exports.done = true })()${sourceUrlComment(at.filename, at.index ?? 0)}`\n )($__exports, interopDefault, importer, ...Object.values(helpers))\n\n const logError = (error: any) => console.error(\"jq79: error in factory script\", error)\n let invoked = false\n // what invoke() is still waiting on, memoized: it is called from both paths\n // below and does its work once, but the *second* caller is the one whose\n // promise is tracked - without this it would see `undefined` and count the\n // script as settled while an async factory's bindings are still on the way\n let merging: Promise<void> | undefined\n const invoke = (): Promise<void> | undefined => {\n if (invoked) return merging\n invoked = true\n const factory = $__exports.default\n if (typeof factory !== \"function\") return undefined\n const merge = (bindings: any) => {\n if (bindings && typeof bindings === \"object\") Object.assign(scope, bindings)\n }\n // the sync path is invoked straight from render(), so a throwing factory\n // must be caught here too - not just by the `result` rejection handler\n try {\n // props first, ctx second. Both are the store: the pattern destructures\n // the props it declared (copying, as destructuring does - $props is the\n // live view for a primitive the parent reassigns later)\n const returned = factory(scope, { $data: scope, $props: scope, $effect: effect, ...instanceHelpers })\n if (returned instanceof Promise) merging = returned.then(merge).catch(logError)\n else merge(returned)\n } catch (error) {\n logError(error)\n }\n return merging\n }\n\n // tracked through the merge, not just the module body: a factory's names\n // reach the store in `merge`, and a template expression that reads one before\n // then is not an authoring mistake (see reportExprError)\n const settled = result.then(invoke, logError)\n trackScript(settled)\n if ($__exports.done) invoke() // fully-sync body: factory runs before first render\n // sync only if the bindings are already on the store: a factory whose body\n // finished but whose *factory* returned a promise (an async factory, or one\n // that awaits $mounted()) still has names on the way, and the render gate\n // must treat it as pending rather than race its merge\n return { settled, sync: $__exports.done === true && merging === undefined }\n}\n\n// ---------------------------------------------------------------------------\n// hot reload\n//\n// Both delivery paths want the same thing when a .html file changes: reparse\n// it, and re-render every live instance of it in place, keeping its data. The\n// swap lives in the runtime (hotReplace, below) so jq79/dev and the Vite\n// plugin share one implementation instead of two - and so it can reach the\n// private fields it needs (the markers, the holding fragment) rather than\n// poking at them from outside, which is what the plugin used to do.\n//\n// Finding the instances is the part only the runtime can do: a component\n// fetched at runtime is reachable from nothing but the DOM it rendered. So\n// instances register themselves - but only once a page opts in, before the\n// runtime loads. Nothing here costs a bundled app anything: with the registry\n// off, an instance is not tracked at all.\n// ---------------------------------------------------------------------------\n\nconst HOT_FLAG = \"__JQ79_HMR_ENABLED__\"\nconst HOT_RUNTIME = \"__JQ79_HMR__\"\n\n// live instances by filename. WeakRef because a destroyed component that the\n// page has dropped must stay collectable: `:each` churns through clones\nlet hotRegistry: Map<string, Set<WeakRef<Component79>>> | null = null\n\nconst hotRegister = (instance: Component79) => {\n if (!hotRegistry || !instance.filename) return\n let refs = hotRegistry.get(instance.filename)\n if (!refs) hotRegistry.set(instance.filename, (refs = new Set()))\n refs.add(new WeakRef(instance))\n}\n\n// the same file reaches the runtime under different names - \"./card.html\" from\n// an import() in a setup script, \"/cards/card.html\" from a fetch, \"cards/card.\n// html\" from the dev server that watched it - and they all have to land on one\n// key. Resolving against the page is what settles them\nconst hotKey = (filename: string): string => {\n try {\n return new URL(filename, document.baseURI).pathname\n } catch {\n return filename\n }\n}\n\n// swaps the file's new source into every instance that came from `filename`,\n// and returns how many of them were *on the page* and so re-rendered. Zero\n// means the change is not visible anywhere - the file is a page rather than a\n// component, or nothing has mounted it yet - and the caller (a dev server)\n// should fall back to reloading. Definitions and instances that have been\n// destroyed but not yet collected are patched all the same; they just don't\n// count, because nothing on screen changed for them\nexport const hotUpdate = (filename: string, src: string): number => {\n if (!hotRegistry) return 0\n\n const key = hotKey(filename)\n // parsed once and shared by every instance - which is already what a\n // definition and the clones :component makes from it do\n const parts = parseComponentString(src)\n // the file is the hot-reload unit, so one reparse serves every component it\n // declares: an instance is handed the parts of the component it *is*, by\n // name. A name that is no longer in the file (a <template> renamed or\n // deleted) has no parts to be given, and only a reload can fix the page\n let orphaned = false\n const partsFor = (instance: Component79): ComponentParts | null =>\n instance.name === undefined ? parts : parts.siblings?.[instance.name] ?? null\n\n let rerendered = 0\n for (const [name, refs] of hotRegistry) {\n if (hotKey(name) !== key) continue\n for (const ref of refs) {\n const instance = ref.deref()\n if (!instance) {\n refs.delete(ref) // collected since the last update\n continue\n }\n const next = partsFor(instance)\n if (!next) {\n orphaned = true\n continue\n }\n if (instance.hotReplace(next)) rerendered++\n }\n if (!refs.size) hotRegistry.delete(name)\n }\n return orphaned ? 0 : rerendered\n}\n\n// starts tracking instances, so hotUpdate can find them. jq79/dev's client\n// calls this through the global handshake at the foot of this file; it is\n// exported so a bundled app - or a test - can opt in directly\nexport const enableHotReload = (): void => {\n hotRegistry ??= new Map()\n ;(globalThis as any)[HOT_RUNTIME] = { update: hotUpdate }\n}\n\ntype EmitListener = (event: CustomEvent, payload: any) => void\n\n// how long a first render may sit behind its scripts before the console says so\nconst STUCK_RENDER_DELAY = 3000\n\n// a script that neither returns nor calls $mounted() holds the template\n// forever, and the failure looks like nothing at all: no error, no markup, a\n// component indistinguishable from one nobody mounted. So the wait is loud\n// after a few seconds - and it keeps waiting, because rendering on a timer\n// would make the moment of the first render depend on the machine it runs on.\n//\n// Armed only on the deferred path, so a page of synchronous components creates\n// no timers at all\nconst warnIfStuck = (component: Component79, gates: Promise<void>[]) => {\n const timer = setTimeout(() => {\n console.warn(\n `jq79: ${component.name ? `<${component.name}>` : \"a component\"}${component.filename ? ` (${component.filename})` : \"\"} ` +\n `has been waiting ${STUCK_RENDER_DELAY / 1000}s for a :setup script and has rendered nothing. ` +\n \"The template waits until every script returns or calls $mounted() - add an \" +\n \"await $mounted() above the slow part to render first and fill in after.\"\n )\n }, STUCK_RENDER_DELAY)\n // unref where it exists (node/vitest): a pending timer must not be what keeps\n // a process alive. Browsers have no such notion and no such need\n ;(timer as any)?.unref?.()\n Promise.all(gates).then(() => clearTimeout(timer))\n}\n\nconst fetchComponent = async (url: string): Promise<Component79> => {\n const response = await fetch(url)\n if (!response.ok) throw new Error(`failed to fetch component from ${url}: ${response.status}`)\n // the URL names the component's scripts in devtools, and is where the\n // browser will look for the source when a breakpoint lands in one\n return new Component79(await response.text(), { filename: url })\n}\n\n// a parsed single-file component. Typical lifecycle:\n//\n// const jq79 = new Component79(src) // or await Component79.fetch(url)\n// jq79.on(\"submit\", (e, payload) => {}) // hear this instance's $emit events\n// jq79.mount(\"#app\", { user }) // render (reactive DOM, scripts, styles) + attach\n// ... // (mountShadow mounts into a shadow root)\n// jq79.detach() // detach, keeping state - mount() re-attaches\n// .destroy() // dispose effects and remove styles\nexport class Component79 {\n // the version of jq79 this class came from, so a page can tell which build it\n // loaded (a CDN <script> pins nothing on its own)\n static readonly version: string = VERSION\n\n template: TemplateNode[]\n scripts: TagBlock[]\n styles: TagBlock[]\n // pre-resolved modules for setup-script `import(...)` calls (see\n // ComponentParts.modules); checked before falling back to fetch/import\n modules?: Record<string, any>\n // the component's origin, used to name its scripts in devtools\n filename?: string\n // the other components declared in the same file, by name (see\n // ComponentParts.siblings). They are also this definition's own properties,\n // so `const { Row } = await Component79.fetch(url)` reaches them\n siblings?: Record<string, Component79>\n // this component's name inside its file, for the components a <template>\n // declared; the file's own component has none - it is the default, and a\n // default is named by whoever imports it\n name?: string\n // the content the usage site handed this instance, by slot name (see the\n // slots section). Not part of a definition - it belongs to the tag that\n // wrote it - so renderNestedComponent sets it on the instance it creates,\n // and every render reads it from here: a hot reload re-renders from a data\n // snapshot, which a symbol on the store would not survive\n slots?: SlotMap\n // the writeback half of :model, same story: the function that assigns into\n // the parent, set by renderNestedComponent before the first render and\n // called by this instance's $updateModel. Kept outside the render generation\n // so it survives re-render and hot reload. Absent means no :model on the tag\n // (or no tag at all - a root mount), which makes every $updateModel a no-op.\n // Internal: set by the usage site, not part of the public API\n modelWriteback?: (name: string | undefined, value: any) => boolean\n\n data: ReactiveDeepData<Record<string, any>> | null = null\n\n private fx: EffectScope | null = null\n // holds the rendered nodes while detached; anchors keep this fragment as\n // their parentNode, so effects keep the (detached) DOM up to date and a\n // later mount() shows current state\n private content: DocumentFragment | null = null\n // markers bracketing the component's output so detach() can collect nodes\n // that :if/:each inserted next to the anchors after mounting\n private startMarker: Comment | null = null\n private endMarker: Comment | null = null\n // shadow rendering keeps per-instance <style> elements; head rendering goes\n // through the shared refcounted styleRegistry instead\n private styleEls: HTMLStyleElement[] = []\n private ownsSharedStyles = false\n private useShadow = false\n private mountRoot: Element | ShadowRoot | DocumentFragment | null = null\n // settles the $mounted() promise handed to this render generation's scripts\n private resolveMounted: (() => void) | null = null\n // whether this generation's template has been built. A render held back by a\n // script (see the gate in renderWith) has markers but no nodes, and $mounted()\n // must not resolve on attach alone - a script awaiting it would wake to an\n // empty component and find nothing to query\n private renderDone = false\n // instance-level listeners for $emit events, registered with on(). Kept\n // outside the render generation so they survive re-render and destroy()\n private emitListeners = new Map<string, Set<EmitListener>>()\n\n constructor(src: string | ComponentParts, options: { modules?: Record<string, any>; filename?: string } = {}) {\n const parts = typeof src === \"string\" ? parseComponentString(src) : src\n this.template = parts.template\n this.scripts = parts.scripts\n this.styles = parts.styles\n this.modules = options.modules ?? (typeof src === \"string\" ? undefined : src.modules)\n this.filename = options.filename ?? (typeof src === \"string\" ? undefined : src.filename)\n this.siblings = parts.siblings\n this.name = parts.name\n this.adoptSiblings()\n hotRegister(this) // a no-op unless the page enabled hot reload\n }\n\n // the parser builds a file's sibling definitions before anyone has told it\n // where the file came from, so whoever holds the parse hands its origin down\n // - and keeps doing it after a hot reload, which parses the file afresh.\n // Without it a reloaded child would have no filename, and an instance with\n // no filename is not tracked: the next edit would never reach it\n private adoptSiblings() {\n if (!this.siblings) return\n Object.entries(this.siblings).forEach(([name, sibling]) => {\n sibling.filename ??= this.filename\n sibling.modules ??= this.modules\n // the file's own component also *is* the file: its named components hang\n // off it as properties, which is what `const { Row } = …` reads (and\n // what the bundler re-exports by name)\n if (!this.name) (this as any)[name] = sibling\n })\n }\n\n // swaps this component's parsed parts for `src`'s and, if it is on the page,\n // re-renders it where it stands - seeded with a snapshot of its data, so\n // props and store values survive (the setup script runs again, so whatever it\n // initializes is reset). Returns whether it re-rendered: an instance that was\n // never rendered is a *definition*, and patching its parts is all there is to\n // do - the clones :component made from it are instances in their own right,\n // registered under the same filename, and re-render themselves.\n //\n // Dev-only, and not part of the public API: jq79/dev and the Vite plugin call\n // it when a file changes. It re-attaches against the markers rather than\n // mountRoot on purpose - a nested clone is mounted into a fragment that is\n // then emptied into the page, so its mountRoot is a stale, detached fragment\n // while its markers sit where its DOM actually is\n hotReplace(src: string | ComponentParts): boolean {\n const parts = typeof src === \"string\" ? parseComponentString(src) : src\n // the source just changed, so what was already said about it no longer\n // applies: without this the author fixes the typo, saves, and the next typo\n // in the same expression is deduped away against the old one. `compiled`\n // needs no such reset - it is keyed by expression text, so edited source is\n // a different key\n reportedExprErrors.clear()\n pendingReports.clear()\n reportedFailedExprs.clear()\n const marker = this.startMarker\n const rendered = !!(marker && this.content)\n\n // where its output sits now, if it is on the page. A rendered-but-detached\n // instance (markers in the holding fragment) re-renders detached, and a\n // later mount() attaches the new output - like any update it missed away\n const live = rendered && marker!.isConnected\n const parent = live ? (marker!.parentNode as Element | ShadowRoot | DocumentFragment) : null\n const before = live ? this.endMarker!.nextSibling : null\n const data = { ...this.data }\n const shadow = this.useShadow\n\n // destroy() releases the styles it acquired, so it has to run while\n // this.styles is still the *old* set - swapping the parts first would leak\n // the old stylesheet into the head and release a new one nobody holds\n if (rendered) this.destroy()\n\n this.template = parts.template\n this.scripts = parts.scripts\n this.styles = parts.styles\n // the file's other components as they are now: the next render resolves\n // <Row> against these, so a parent picks up an edited child even when the\n // child's own instances are patched separately\n this.siblings = parts.siblings\n this.adoptSiblings()\n if (!rendered) return false // a definition: its clones re-render themselves\n\n this.renderWith(data, shadow)\n if (!parent) return false\n\n // shadow styles live inline, right before the DOM they style (attach()\n // appends them ahead of the content), so they go back the same way\n if (shadow) this.styleEls.forEach(el => parent.insertBefore(el, before))\n parent.insertBefore(this.content!, before)\n this.mountRoot = parent\n this.settleMounted()\n return true\n }\n\n // downloads and parses a component, handing back a PendingComponent79: a\n // handle that can be mounted right away, and that awaits to this component -\n // so both of these are the whole program\n //\n // Component79.fetch(\"./app.html\").mount(\"main\")\n // const app = await Component79.fetch(\"./app.html\")\n static fetch(url: string): PendingComponent79 {\n if (Array.isArray(url)) throw new TypeError(\"Component79.fetch takes one URL; use fetchAll for an array\")\n return new PendingComponent79(fetchComponent(url))\n }\n\n // fetches them all at once and resolves to the components in the same order,\n // so one await destructures them - and, like Promise.all, the first failure\n // rejects the whole thing. A plain promise, not a handle: mounting a *list*\n // of components has no single meaning\n static fetchAll(urls: string[]): Promise<Component79[]> {\n return Promise.all(urls.map(fetchComponent))\n }\n\n // subscribes to this instance's $emit events, on top of the DOM CustomEvent\n // dispatch - so it hears emits even while the component is detached (where\n // the event has no ancestors to bubble to). Chainable; can be called before\n // render()\n on(eventName: string, listener: EmitListener): this {\n if (!this.emitListeners.has(eventName)) this.emitListeners.set(eventName, new Set())\n this.emitListeners.get(eventName)!.add(listener)\n return this\n }\n\n off(eventName: string, listener: EmitListener): this {\n this.emitListeners.get(eventName)?.delete(listener)\n return this\n }\n\n render(data: Record<string, any> = {}): this {\n return this.renderWith(data, false)\n }\n\n // like render(), but styles are injected into a shadow root attached to the\n // mount target instead of document.head, so they don't leak globally\n renderShadow(data: Record<string, any> = {}): this {\n return this.renderWith(data, true)\n }\n\n private renderWith(data: Record<string, any>, shadow: boolean): this {\n this.destroy()\n\n // what this component can see of its file's other components, and which of\n // its declared props arrived empty - both decided by the signature, before\n // the store exists (see siblingsInScope / UNFILLED_PROPS)\n const declared = declaredPropNames(this.scripts)\n const siblingScope = siblingsInScope(this.siblings, declared)\n const raw: Record<string, any> = siblingScope\n ? Object.assign(Object.create(siblingScope), data)\n : { ...data }\n const unfilled = new Set([...declared].filter(name => !(name in data)))\n if (unfilled.size) Object.defineProperty(raw, UNFILLED_PROPS, { value: unfilled })\n // the slot content, for the <slot>s the template renders, and the static\n // map of which names were filled, for the component to ask about\n // (`<footer :if=\"$slots.footer\">`). Filled at the usage site, so it can\n // only change when the tag itself re-renders - which builds a new instance\n if (this.slots) Object.defineProperty(raw, SLOTS, { value: this.slots })\n // in place before the store wraps it, because the scripts that increment it\n // run against the store and the template reads it back through the same\n // scope chain. Read back out of `raw` where it is needed rather than kept\n // in a local: this frame is on the stack for the whole of the subtree it\n // renders, so a component nested inside itself pays for it once per level -\n // and the depth guard at MAX_NESTING_DEPTH only beats a RangeError while\n // this function stays small (see the note in docs/development.md)\n Object.defineProperty(raw, PENDING_SCRIPTS, { value: { count: 0 } as PendingScripts })\n\n const store = $reactive(raw)\n const fx = createEffectScope(store)\n this.data = store\n this.fx = fx\n this.useShadow = shadow\n\n this.startMarker = document.createComment(\"jq79\")\n this.endMarker = document.createComment(\"/jq79\")\n\n // $emit dispatches a bubbling CustomEvent from this instance's start\n // marker, so once mounted it travels up the real DOM and parents can\n // listen on any ancestor (or with @event-name on a wrapping element).\n // Captures the marker rather than `this` so a later re-render's scripts\n // can't dispatch from the wrong generation - the same guard keeps stale\n // generations from reaching the instance's on() listeners.\n // The on() channel runs *first* (it's where @event on a component tag is\n // wired - see wireTagEvent) so its listeners can shape the DOM dispatch:\n // stopPropagation() there keeps the event off the DOM entirely, and the\n // event is cancelable so preventDefault() - from either channel - flips\n // the return to false, telling the emitting child \"the parent vetoed\"\n const marker = this.startMarker\n // model:update used to be the writeback's event name; it is a direct call\n // now ($updateModel), so an emit under that name reaches nothing. Said\n // once per generation rather than per keystroke, and said at all because\n // the alternative is a child whose edits silently stop arriving\n let warnedModelUpdate = false\n const $emit = (eventName: string, payload?: any): boolean => {\n if (eventName === \"model:update\" && !warnedModelUpdate) {\n warnedModelUpdate = true\n console.warn(\"jq79: $emit('model:update', …) no longer feeds :model - call $updateModel(value) or $updateModel(name, value) instead\")\n }\n const event = new CustomEvent(eventName, { detail: payload, bubbles: true, composed: true, cancelable: true })\n if (marker === this.startMarker) {\n this.emitListeners.get(eventName)?.forEach(listener => listener(event, payload))\n }\n // cancelBubble is the spec's legacy name, but it's the only *readable*\n // accessor for the stop-propagation flag - hence the deprecation hint\n if (!event.cancelBubble) marker.dispatchEvent(event)\n return !event.defaultPrevented\n }\n\n // `await $mounted()` suspends a setup script until the component is\n // rendered *and* attached, so code below it can querySelector its own DOM.\n // If this instance is never mounted, the promise stays pending and the\n // script's tail never runs.\n //\n // Calling it is also how a script releases the first render - see the gate\n // below - so the two halves of the contract are one call: \"put me on the\n // page, and don't wait for the rest of me\"\n let resolveMounted!: () => void\n const mounted = new Promise<void>(resolve => { resolveMounted = resolve })\n this.resolveMounted = resolveMounted\n this.renderDone = false\n\n // $self / $$self mirror $ / $$ but only search this instance's own\n // output: the sibling nodes between its markers. They work detached too\n // (the holding fragment keeps markers and rendered nodes as siblings),\n // though the template renders after the scripts run, so they only find\n // something from post-await code or callbacks\n const endMarker = this.endMarker\n const $$self = (selector: string): Element[] => {\n const found: Element[] = []\n for (let node: Node | null = marker.nextSibling; node && node !== endMarker; node = node.nextSibling) {\n if (node instanceof Element) {\n if (node.matches(selector)) found.push(node)\n found.push(...Array.from(node.querySelectorAll(selector)))\n }\n }\n return found\n }\n const $self = (selector: string): Element | null => $$self(selector)[0] ?? null\n\n // import() calls whose specifier was pre-resolved by a bundler (the\n // modules map) get the bundled module; everything else falls back to the\n // runtime importResource (fetch for .html, native import otherwise),\n // relative to this component's file. The map is keyed by the literal\n // specifier the script wrote, so it is consulted *before* resolution -\n // what the bundler hoisted and what the source says are the same string\n const modules = this.modules\n const $import = (url: string): Promise<any> =>\n modules && url in modules\n ? Promise.resolve(modules[url])\n : importResource(resolveSpecifier(url, this.filename))\n\n // the writeback half of :model, from the child's side: one argument is the\n // value for the default model (the bare :model), two are a name and a\n // value. Arity is what tells them apart, so the value is never inspected -\n // an object with `name`/`value` keys is just a value, which is exactly\n // what a payload-shaped contract could not promise. Returns whether a\n // bound model took it; no :model at the usage site is a silent no-op,\n // since a child may be designed to work bound or unbound\n const $updateModel = (...args: [value?: any] | [name: string, value: any]): boolean => {\n const [name, value] = args.length > 1 ? args as [string, any] : [undefined, args[0]]\n // the same stale-generation guard $emit has: destroy() nulls the marker,\n // so a closure the old child leaked (a timer, a registered callback)\n // cannot keep writing a parent that replaced it\n if (marker !== this.startMarker) return false\n return this.modelWriteback?.(name, value) ?? false\n }\n\n // the names a component answers on top of its store: $emit, so an inline\n // handler can emit without routing through a setup function\n // (@input=\"$emit('update', $event.target.value)\"), $updateModel, the\n // writeback a :model binding listens for, and $slots, the static map of\n // the names the usage site filled, so a wrapper can be dropped when\n // nothing filled it (<footer :if=\"$slots.footer\">). All reach the\n // template (through templateScope, below) and both script modes (as\n // instance helpers), and a same-named store key shadows any of them.\n // Null-prototype, for the same reason storeApi is: `key in injected` must\n // not start answering true for toString, constructor and the rest\n const injected: Record<string, any> = Object.assign(Object.create(null), {\n $emit,\n $updateModel,\n $slots: Object.fromEntries(Object.keys(this.slots ?? {}).map(name => [name, true])),\n })\n\n // scripts run before the template renders so `$:` values are initialized;\n // a `:mounted` script defers entirely until mount() instead. A top-level\n // `export default` switches the script to factory mode (plain lexical JS)\n // a `:mounted` script is deferred by prepending the await on the code's own\n // first line, so deferring doesn't shift the lines devtools reports for it\n const defer = (code: string) => `await $mounted();${code}`\n\n // what the first render is still waiting for. A script holds the template\n // back until it returns or calls $mounted() - whichever comes first - so\n // `let rows = await fetch(...)` renders once, with rows, instead of\n // rendering empty and filling in. `:mounted` is not a special case here: it\n // *is* a script that yields on line 0, which is what `defer` above writes.\n //\n // One gate per script, not one per instance: a script yielding must not\n // release the render on behalf of a sibling script that is still fetching\n const gates: Promise<void>[] = []\n let allSync = true\n\n this.scripts.forEach((script, index) => {\n let resolveGate!: () => void\n gates.push(new Promise<void>(resolve => { resolveGate = resolve }))\n // whether this gate is already open on *this* stack, which is not the\n // same as the script having finished: a script that yields immediately\n // (`await $mounted()` on its first line, which is what `:mounted`\n // compiles to) never finishes synchronously but holds nothing up either.\n // Reading the promise instead would push every such render a microtask\n // later, for no one's benefit\n let open = false\n const release = () => { open = true; resolveGate() }\n // this script's own view of $mounted: the call releases its gate, the\n // promise it returns is the instance's (one mount, one resolution)\n const $mounted = () => { release(); return mounted }\n // the file's other components are passed as parameters of the compiled\n // script, not just left on the store's prototype: a factory script runs\n // as plain lexical JS with no `with`, so a bare `Row` in one would\n // resolve to nothing at all. In setup mode this composes with `with` -\n // scriptScope's `has` declines any name that is a helper, so the\n // parameter is what the name resolves to\n const instanceHelpers = { $mounted, $self, $$self, ...injected, ...siblingScope }\n const at: ScriptLocation = { filename: this.filename, index }\n const deferred = \":mounted\" in script.attrs\n const factoryCode = transformFactoryScript(script.content)\n const run = ((): ScriptRun => {\n if (factoryCode !== null) {\n // a factory publishes its names by returning them, so one that yields\n // before it returns renders against a store where none of them exist.\n // In factory mode `:mounted` yields on line 0, which means *always* -\n // and unlike a setup script there is no way to put the useful half\n // above the yield. Awaiting $mounted() inside the factory does what\n // the author meant, and is what the message points at\n if (deferred) {\n console.warn(\n \"jq79: :mounted on a factory script renders the template before the factory has returned, \" +\n \"so none of its bindings exist yet - await $mounted() inside the factory instead.\"\n )\n }\n declareProps(store, parseFactoryProps(script.content))\n const body = deferred ? defer(factoryCode) : factoryCode\n return runFactoryScript(body, store, fx.effect, instanceHelpers, $import, at)\n }\n const { vars, code } = transformSetupScript(script.content)\n declareProps(store, setupSignature(script))\n // pre-declare script vars on the store so `with` resolves assignments\n // to them (and reads of them) through the reactive proxy\n vars.forEach(name => { if (!(name in store)) (store as any)[name] = undefined })\n const body = deferred ? defer(code) : code\n return runSetupScript(body, store, fx.effect, instanceHelpers, $import, at)\n })()\n // a script that threw has nothing left to contribute, so its rejection\n // releases the gate exactly as completion does - the error is already\n // reported by the runner, and holding the template hostage to it would\n // turn one broken script into a blank component. It also stops counting\n // as a source of names, for that same reason.\n //\n // A script that finished on this stack is counted at zero rather than\n // incremented and decremented a microtask later: its names are on the\n // store already, and the promise it settles through does not resolve\n // until after the synchronous paint - which is every paint, for the\n // components that have no await in them at all\n if (run.sync) run.settled.then(release, release)\n else {\n const pending: PendingScripts = (raw as any)[PENDING_SCRIPTS]\n pending.count++\n const settle = () => { pending.count--; release() }\n run.settled.then(settle, settle)\n }\n if (!run.sync && !open) allSync = false\n })\n\n const content = document.createDocumentFragment()\n // the injected names, served by has/get only - never as own keys - so\n // Object.keys, snapshot spreads and the component-key scan don't see them,\n // and every read still forwards through the reactive store, keeping\n // dependency tracking intact\n const templateScope = new Proxy(store as Record<string, any>, {\n has: (target, key) => (typeof key === \"string\" && key in injected) || Reflect.has(target, key),\n get: (target, key, receiver) =>\n typeof key === \"string\" && key in injected && !Reflect.has(target, key)\n ? injected[key]\n : Reflect.get(target, key, receiver),\n })\n // the markers go in either way, so render() returns something mountable\n // whether or not the template has been built yet: they are what detach()\n // collects between and what the deferred pass inserts before, exactly as\n // :if/:each anchors already work. That is what keeps render() and mount()\n // synchronous while the first render itself is allowed to wait\n content.append(this.startMarker, this.endMarker)\n this.content = content\n if (allSync) {\n // nothing is pending, so the template is built on this stack - the\n // ordinary case, and byte-for-byte the timing render() has always had.\n //\n // Written out rather than routed through the closure below on purpose: a\n // component that nests itself recurses through here, so one extra frame\n // per level is one fewer level before the stack gives out - enough, when\n // this was a shared `paint()`, to overflow *underneath* the depth guard\n // at MAX_NESTING_DEPTH and turn a named error back into a RangeError\n this.endMarker.parentNode!.insertBefore(renderNodes(this.template, templateScope, fx, shadow), this.endMarker)\n this.renderDone = true\n this.settleMounted()\n } else {\n Promise.all(gates).then(() => {\n // destroy() nulls the markers and a re-render replaces them, so a gate\n // that opens after either one has nothing left to paint into\n if (marker !== this.startMarker) return\n this.endMarker!.parentNode!.insertBefore(renderNodes(this.template, templateScope, fx, shadow), this.endMarker!)\n this.renderDone = true\n this.settleMounted()\n })\n warnIfStuck(this, gates)\n }\n\n if (shadow) {\n this.styleEls = this.styles.map(style => {\n const el = document.createElement(\"style\")\n el.textContent = style.content // the source: a shadow root scopes it already\n return el\n })\n } else {\n this.styles.forEach(style => acquireStyle(headStyle(style)))\n this.ownsSharedStyles = true\n }\n\n return this\n }\n\n // renders (when needed) and attaches in one call: the component is rendered\n // on the first mount, and re-rendered fresh whenever `data` is passed.\n // mount(el) on an already-rendered component just re-attaches, keeping its\n // state - the detach()/mount() round trip. Rendering here keeps whichever\n // style mode was last used (document.head unless renderShadow/mountShadow\n // chose a shadow root)\n mount(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n const target = typeof parent === \"string\" ? $(parent) : parent\n if (!target) throw new Error(`mount target not found: ${parent}`)\n if (!this.content || data !== undefined) this.renderWith(data ?? {}, this.useShadow)\n return this.attach(target)\n }\n\n // like mount(), but renders with styles scoped to a shadow root on the\n // target instead of document.head\n mountShadow(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n const target = typeof parent === \"string\" ? $(parent) : parent\n if (!target) throw new Error(`mount target not found: ${parent}`)\n if (!this.content || data !== undefined || !this.useShadow) this.renderWith(data ?? {}, true)\n return this.attach(target)\n }\n\n private attach(target: Element | ShadowRoot | DocumentFragment): this {\n if (this.mountRoot) this.detach()\n\n const root = this.useShadow && target instanceof Element\n ? target.shadowRoot ?? target.attachShadow({ mode: \"open\" })\n : target\n if (this.useShadow) this.styleEls.forEach(el => root.appendChild(el))\n root.appendChild(this.content!)\n this.mountRoot = root\n this.settleMounted()\n return this\n }\n\n // `await $mounted()` means \"rendered and on the page\", so it waits for both -\n // whichever lands last calls this. In the ordinary synchronous flow the render\n // is already done and this is the attach; for a component whose first render\n // a script held back, it is the other way round\n private settleMounted() {\n if (this.renderDone && this.mountRoot) this.resolveMounted?.()\n }\n\n // detaches from the DOM while keeping all state; a later mount() re-attaches\n // with any updates that happened while detached already applied\n detach(): this {\n if (!this.mountRoot || !this.content || !this.startMarker || !this.endMarker) return this\n\n // move everything between the markers (inclusive) back into the holding\n // fragment - including nodes :if/:each inserted after mounting\n let node: Node | null = this.startMarker\n while (node) {\n const nextNode: Node | null = node.nextSibling\n this.content.appendChild(node)\n if (node === this.endMarker) break\n node = nextNode\n }\n\n this.mountRoot = null\n return this\n }\n\n destroy(): this {\n this.detach()\n this.fx?.dispose()\n this.fx = null\n // a store this component was handed (a shared `$reactive`) outlives it, and\n // holds a listener per store that nested it - drop this instance's\n this.data?.$dispose()\n this.styleEls.forEach(el => el.parentNode?.removeChild(el))\n this.styleEls = []\n if (this.ownsSharedStyles) {\n this.styles.forEach(style => releaseStyle(headStyle(style)))\n this.ownsSharedStyles = false\n }\n this.content = null\n this.startMarker = null\n this.endMarker = null\n this.renderDone = false\n this.data = null\n this.resolveMounted = null\n return this\n }\n}\n\n// what Component79.fetch() hands back: a component that hasn't arrived yet.\n//\n// Every method queues onto the fetch and returns the handle, so a whole page\n// is one expression and the calls run in the order they were written:\n//\n// C79.fetch(\"./app.html\").on(\"save\", persist).mount(\"main\", { user })\n//\n// It is also thenable, resolving to the Component79 itself - which is what\n// keeps `await Component79.fetch(url)` (and importResource, and a handle\n// dropped into Promise.all) working exactly as before. Queued calls keep the\n// resolved value, so awaiting a chain gives the mounted component.\n//\n// The catch: mount() here returns the handle, not the component - there is no\n// component yet to return. That's why the whole lifecycle is on the handle and\n// not just mount(): nobody should have to await merely to destroy something.\nexport class PendingComponent79 {\n // the fetch with every queued call chained onto it, each passing the\n // component through - so `chain` always settles to the component, however\n // many calls were queued, and a failure anywhere rejects the rest\n private chain: Promise<Component79>\n\n constructor(component: Promise<Component79>) {\n this.chain = component\n }\n\n private queue(action: (component: Component79) => void): this {\n this.chain = this.chain.then(component => {\n action(component)\n return component\n })\n return this\n }\n\n then<TResult1 = Component79, TResult2 = never>(\n onfulfilled?: ((value: Component79) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.chain.then(onfulfilled, onrejected)\n }\n\n // a chain nobody awaits reports a failed fetch as an unhandled rejection,\n // like any dropped promise chain - these are for callers who'd rather handle\n // it. catch() returns a promise, not a handle: the chain ends here\n catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<Component79 | TResult> {\n return this.chain.catch(onrejected)\n }\n\n finally(onfinally?: (() => void) | null): Promise<Component79> {\n return this.chain.finally(onfinally)\n }\n\n mount(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n return this.queue(component => component.mount(parent, data))\n }\n\n mountShadow(parent: Element | ShadowRoot | DocumentFragment | string, data?: Record<string, any>): this {\n return this.queue(component => component.mountShadow(parent, data))\n }\n\n render(data: Record<string, any> = {}): this {\n return this.queue(component => component.render(data))\n }\n\n renderShadow(data: Record<string, any> = {}): this {\n return this.queue(component => component.renderShadow(data))\n }\n\n on(eventName: string, listener: EmitListener): this {\n return this.queue(component => component.on(eventName, listener))\n }\n\n off(eventName: string, listener: EmitListener): this {\n return this.queue(component => component.off(eventName, listener))\n }\n\n detach(): this {\n return this.queue(component => component.detach())\n }\n\n destroy(): this {\n return this.queue(component => component.destroy())\n }\n}\n\nexport { Component79 as C79 }\n\nexport const parseComponent = (component: string): Component79 => new Component79(component)\n\n// library helpers injected into setup scripts. They behave like extra\n// globals: a same-named scope property (render data or a top-level\n// declaration) shadows them\nconst SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, Component79 }\n\n// the hot-reload handshake. jq79/dev serves a classic script that sets the flag\n// below; classic scripts run before deferred module ones, so the flag is always\n// set before this module evaluates. The page's copy of the runtime can come from\n// anywhere - a CDN, an import map, dist/ - and the dev client has no way to\n// import *that* copy, so the runtime hands itself to the client instead\nif (typeof globalThis !== \"undefined\" && (globalThis as any)[HOT_FLAG]) enableHotReload()\n\n","// DOM helpers: tiny query/create utilities, also injected into component\n// scripts as $, $$ and $create\n\n// $(selector) queries the document; $(el, selector) queries within el. The\n// selector is required in the element form - an empty one is a SyntaxError\nexport function $(selector: string): Element | null\nexport function $(el: Element, selector: string): Element | null\nexport function $(selectorOrEl: string | Element, selector?: string): Element | null {\n return typeof selectorOrEl === \"string\"\n ? document.querySelector(selectorOrEl)\n : selectorOrEl.querySelector(selector!)\n}\n\nexport function $$(selector: string): Element[]\nexport function $$(el: Element, selector: string): Element[]\nexport function $$(selectorOrEl: string | Element, selector?: string): Element[] {\n return Array.from(\n typeof selectorOrEl === \"string\"\n ? document.querySelectorAll(selectorOrEl)\n : selectorOrEl.querySelectorAll(selector!)\n )\n}\n\n// $create(tag, attrs): attrs are set as attributes, except className, which\n// may be a string or an array of class names.\nexport const $create = (tag: string, attrs: Record<string, any> = {}): HTMLElement => {\n const el = document.createElement(tag);\n for (const [name, value] of Object.entries(attrs)) {\n if (name === 'className') {\n el.className = Array.isArray(value) ? value.join(' ') : value;\n } else if (name === 'textContent') {\n el.textContent = value;\n } else if (name === 'children') {\n for (const child of value) {\n el.appendChild(child);\n }\n } else {\n el.setAttribute(name, value);\n }\n }\n return el;\n};\n\nconst ALLOWED_TAGS = new Set([\n 'a', 'b', 'i', 'em', 'strong', 'p', 'br', 'ul', 'ol', 'li',\n 'blockquote', 'code', 'pre', 'span', 'div', 'h1', 'h2', 'h3',\n 'h4', 'h5', 'h6', 'img'\n]);\n\nconst ALLOWED_ATTR: Record<string, Set<string>> = {\n a: new Set(['href', 'title']),\n img: new Set(['src', 'alt']),\n '*': new Set(['class']), // atributos permitidos en cualquier tag\n};\n\nconst SAFE_URL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);\n\nexport function isSafeUrl(value: string): boolean {\n try {\n // resolver relativo a algo neutro para poder leer el protocolo\n const url = new URL(value, 'https://example.com');\n return SAFE_URL_PROTOCOLS.has(url.protocol);\n } catch {\n return false;\n }\n}\n\n// la política de destinos: decide si un href/src ya seguro por protocolo\n// puede apuntar a donde apunta. Restringe *sobre* el chequeo de protocolo,\n// nunca en su lugar\nexport type AllowUrl = (url: URL, tag: string, attr: string) => boolean;\n\nexport type SanitizeOptions = { allowUrl?: AllowUrl };\n\nconst DEFAULT_PORTS: Record<string, string> = { 'https:': '443', 'http:': '80' };\n\ntype HostPattern = { host: RegExp; port: string | null };\n\n// \"host[:puerto]\": `*` casa exactamente UNA etiqueta dns - la regla de los\n// certificados TLS, no la de CSP: *.germade.dev casa a.germade.dev, pero ni\n// germade.dev (escribe los dos para incluir el apex) ni a.b.germade.dev.\n// Sin puerto casa cualquiera; un patrón inválido devuelve null y no casa\n// nada - una política rota cierra, no abre\nfunction compileHostPattern(pattern: string): HostPattern | null {\n const match = pattern.trim().toLowerCase().match(/^([a-z\\d*][a-z\\d.*-]*?)(?::(\\d{1,5}|\\*))?$/);\n if (!match) return null;\n const [, host, port] = match;\n const labels = host.split('.');\n if (labels.some(label => label !== '*' && !/^[a-z\\d-]+$/.test(label))) return null;\n // las etiquetas validadas no llevan metacaracteres de regex, así que no\n // hay nada que escapar; los puntos los pone el join\n const re = new RegExp(`^${labels.map(label => (label === '*' ? '[^.]+' : label)).join('\\\\.')}$`);\n return { host: re, port: !port || port === '*' ? null : port };\n}\n\n// compila una lista de patrones (string separado por comas, o array) en un\n// predicado AllowUrl. El puerto comparado es el *efectivo* de la URL (el\n// explícito, o el del esquema), así \"germade.dev:443\" casa https://germade.dev.\n// Una URL sin host (mailto:) no casa ningún patrón: los patrones hablan de\n// hosts - la forma función de la política puede admitirla si quiere\nexport const allowedHosts = (patterns: string | string[]): AllowUrl => {\n const compiled = (Array.isArray(patterns) ? patterns : patterns.split(','))\n .map(compileHostPattern)\n .filter((p): p is HostPattern => p !== null);\n return url => {\n const host = url.hostname.toLowerCase();\n const port = url.port || DEFAULT_PORTS[url.protocol] || '';\n return compiled.some(p => p.host.test(host) && (p.port === null || p.port === port));\n };\n};\n\n// consulta la política con la URL resuelta contra la página, para que una\n// URL relativa se juzgue como el destino same-origin que realmente es. Un\n// predicado que lanza, o una URL que no parsea, es un no\nfunction consultAllowUrl(allowUrl: AllowUrl, value: string, tag: string, attr: string): boolean {\n try {\n return !!allowUrl(new URL(value, document.baseURI), tag, attr);\n } catch {\n return false;\n }\n}\n\n// el saneado es recursivo, así que la profundidad del input es profundidad\n// de pila. 512 es lo que toleran los parsers de los navegadores antes de\n// aplanar el anidamiento, con lo que ningún documento legítimo pierde nada -\n// y superar el límite lanza un RangeError con nombre, en vez de reventar la\n// pila en algún punto indeterminado más arriba\nconst MAX_SANITIZE_DEPTH = 512;\n\n// copia los hijos de `source` en `target`, saneando los elementos y clonando\n// el texto; cualquier otra cosa (comentarios, etc.) se descarta\nfunction appendSanitizedChildren(source: ParentNode, target: HTMLElement, depth: number, allowUrl?: AllowUrl): void {\n if (depth > MAX_SANITIZE_DEPTH) {\n throw new RangeError(`jq79: sanitizeHTML input nests deeper than ${MAX_SANITIZE_DEPTH} elements`);\n }\n for (const child of Array.from(source.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n const sanitizedChild = sanitizeNode(child as HTMLElement, depth, allowUrl);\n if (sanitizedChild) target.appendChild(sanitizedChild);\n } else if (child.nodeType === Node.TEXT_NODE) {\n target.appendChild(child.cloneNode());\n }\n }\n}\n\n// sanea un elemento (los llamadores solo pasan nodos ELEMENT_NODE)\nfunction sanitizeNode(node: HTMLElement, depth: number, allowUrl?: AllowUrl): HTMLElement | null {\n const tag = node.tagName.toLowerCase();\n if (!ALLOWED_TAGS.has(tag)) return null; // tag no permitido → se descarta el nodo entero\n\n const clean = document.createElement(tag);\n\n for (const attr of Array.from(node.attributes)) {\n const name = attr.name.toLowerCase();\n const allowedForTag = ALLOWED_ATTR[tag]?.has(name);\n const allowedGlobal = ALLOWED_ATTR['*']?.has(name);\n if (!allowedForTag && !allowedGlobal) continue;\n\n if (name === 'href' || name === 'src') {\n if (!isSafeUrl(attr.value)) continue;\n if (allowUrl && !consultAllowUrl(allowUrl, attr.value, tag, name)) continue;\n }\n\n clean.setAttribute(name, attr.value);\n }\n\n // fuerza rel seguro en enlaces (target nunca se copia: no está permitido)\n if (tag === 'a') clean.setAttribute('rel', 'noopener noreferrer');\n\n appendSanitizedChildren(node, clean, depth + 1, allowUrl);\n\n return clean;\n}\n\nexport function sanitizeHTML(html: string, options?: SanitizeOptions): string {\n // parsear con <template> en vez de con DOMParser: el contenido de un template\n // es un documento inerte igual (ni scripts ni imágenes se ejecutan al asignar\n // innerHTML), pero el parseo de fragmento conserva el espacio en blanco inicial\n // que el modo \"before body\" de un documento completo descartaría - así una\n // primera línea indentada (un diff, un <pre>) llega con su sangría intacta\n const template = document.createElement('template');\n template.innerHTML = html;\n const container = document.createElement('div');\n\n appendSanitizedChildren(template.content, container, 0, options?.allowUrl);\n\n return container.innerHTML;\n}","// the reactive store ($reactive): proxy-based deep reactivity with\n// dot-path dependency tracking, plus the effect-scope helper the renderer\n// uses to tear down a subtree's bindings in one call\n\ntype ChangeListener = (value: any, dotKey: string) => void\ntype AnyChangeListener = (dotKey: string, value: any) => void\ntype ListenerOptions = { immediate?: boolean }\ntype Unsubscribe = () => void\n\nexport type EffectOptions = {\n // wake this effect for writes below its dependencies, not only on them\n deep?: boolean\n // internal: the extra stores this effect must also be registered with, so a\n // change in any of them wakes it (see ATTACH). Slot content is the only\n // thing that sets it, by way of createEffectScope - it is deliberately not\n // part of what this API tells users about\n alsoWakenBy?: Record<string, any>[]\n}\n\nexport type ReactiveDeepData<T> = T & {\n $on: (dotKey: string, listener: ChangeListener, options?: ListenerOptions) => Unsubscribe\n $onAny: (listener: AnyChangeListener, options?: ListenerOptions) => Unsubscribe\n // runs `run` immediately, recording every dotKey it reads off this store, then\n // re-runs it whenever a changed dotKey overlaps one of those - see TrieNode.\n //\n // `deep` also wakes it for writes *below* what it read. It is for the one\n // shape the store cannot see into: an effect that hands a value to code\n // outside its view - a chart library, a canvas, a request - and so reads\n // nothing the proxy can record (see docs/reactive-data.md)\n $effect: (run: () => void, options?: EffectOptions) => Unsubscribe\n // drops this store's subscriptions to the stores nested inside it (see\n // bridge). A store that outlives the one holding it - the shared-state case -\n // would otherwise keep the dead holder's listeners on its own list forever\n $dispose: () => void\n}\n\nconst getByPath = (obj: Record<string, any>, dotKey: string): any =>\n dotKey.split(\".\").reduce((acc, key) => (acc == null ? undefined : acc[key]), obj)\n\n// only plain objects and arrays get deep-wrapped by the reactive store;\n// class instances (Component79, Date, DOM nodes, ...) pass through untouched\n// so their identity, prototypes and internals stay intact\nconst isPlainData = (value: object): boolean => {\n if (Array.isArray(value)) return true\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nconst walkLeaves = (obj: Record<string, any>, path: string, visit: (dotKey: string, value: any) => void) => {\n Object.entries(obj).forEach(([key, value]) => {\n const dotKey = path ? `${path}.${key}` : key\n if (value && typeof value === \"object\" && isPlainData(value)) walkLeaves(value, dotKey, visit)\n else visit(dotKey, value)\n })\n}\n\n// Effect deps live in a trie keyed by path segment: a write walks down its own\n// segments, so the nodes it passes through are its ancestors and the subtree it\n// lands on is its descendants, with no comparison against unrelated effects.\n// `own` holds effects depending on this node's exact path; `deep` holds the ones\n// that want everything under it too (see the `deep` flag on $effect).\n//\n// Which of the two directions actually wakes an effect is the thing that makes\n// this fast, and it is not symmetric - see effectsFor and\n// TODOS/2026-08-23.narrow-the-wake-rule.md\n//\n// `children`/`own`/`deep` are allocated on first use and `parent`/`segment` let\n// a removal walk back up without re-splitting the path: a 10,000-row table is\n// ~40,000 nodes, and three eager allocations each (a Map and two Sets, almost\n// all of them staying empty) cost more than the index saves\ntype TrieNode = {\n children: Map<string, TrieNode> | null\n own: Set<Effect> | null\n deep: Set<Effect> | null\n parent: TrieNode | null\n segment: string\n}\n\n// the dep an `ownKeys` read records, as a reserved last segment on the\n// enumerated object's own path: an ordinary trie child that no walk for a real\n// key can reach, and that the subtree sweep still reaches when the whole object\n// is replaced - which is correct, a new object is a new key set. A real\n// property named \" keys\" collides with it, the same way a flat key containing\n// a dot collides with the nested path of the same name (tests/reactive.test.ts)\nconst KEYS_SEGMENT = \" keys\"\n\nconst keysPath = (path: string): string => (path ? `${path}.${KEYS_SEGMENT}` : KEYS_SEGMENT)\n\nconst createTrieNode = (parent: TrieNode | null, segment: string): TrieNode =>\n ({ children: null, own: null, deep: null, parent, segment })\n\nconst isEmptyNode = (node: TrieNode): boolean =>\n !node.own?.size && !node.deep?.size && !node.children?.size\n\n// reads the raw object behind a store proxy. Module-level (not per-store) so a\n// value that is already reactive - in this store or in another one - can be\n// unwrapped before being wrapped again. Without it, handing the same object to\n// two stores has each one wrapping the other's proxies, and since a wrap walks\n// what it wraps, the nesting compounds until the process stops responding\nconst RAW = Symbol(\"jq79.raw\")\n\n// a free function rather than a method on the store, because the store API is\n// served from the root proxy alone (see storeApi): `store.$toRaw()` would work\n// and `store.user.$toRaw()` would not, which is the case callers actually have.\n// The RAW symbol travels on every proxy at every depth, so this works anywhere.\n// What it returns is the real object, not a copy: writes to it notify nobody\nexport const $toRaw = <T>(value: T): T => {\n let raw: any = value\n while (raw !== null && typeof raw === \"object\" && raw[RAW]) raw = raw[RAW]\n return raw\n}\n\n// marks a store's *root* proxy. A store put inside another store (a setup\n// script's `const local = $reactive(...)`) has to pass through whole: it owns\n// its listeners and its $on/$effect, so unwrapping it would strip away the very\n// thing it is. Nested proxies carry no such marker and are unwrapped freely\nconst STORE = Symbol(\"jq79.store\")\n\nconst isStore = (value: any): boolean =>\n value !== null && typeof value === \"object\" && value[STORE] === true\n\n// active $effect() runs, innermost last - a module-level stack (rather than\n// one per store) so nested effects across stores still nest correctly; reads\n// during a proxy's `get` trap are attributed to whichever run is on top\nconst trackerStack: Set<string>[] = []\n\n// runs fn with dependency tracking suspended - reads inside it are attributed\n// to a throwaway set instead of the currently running effect\nexport const untracked = <T>(fn: () => T): T => {\n trackerStack.push(new Set())\n try {\n return fn()\n } finally {\n trackerStack.pop()\n }\n}\n\n// `reindex` holds one callback per store this effect is registered with (its\n// own, plus any it was attached to), each keeping that store's trie in step\n// with the deps of the last settled run. It lives on the effect rather than\n// in a per-store map because `run` has to reach it without a lookup\ntype Effect = { deps: Set<string>; run: () => void; reindex: Set<(deps: Set<string>) => void>; deep: boolean; order: number }\n\n// creation order, module-wide. The flat `effects` set used to give this for\n// free - iterating it ran effects oldest-first, so a parent's bindings always\n// went before those of a child it had rendered. Matching through the trie\n// returns them in walk order instead, and the tutorial's setup scripts are\n// sensitive to it (a child effect running before its parent's re-sync reads\n// state the parent has not written yet). Effects are ordered explicitly rather\n// than left to whatever the index happens to yield\nlet effectsCreated = 0\n\n// the deps an effect has before its first run, and what indexEffect compares\n// its first run against. Never written to - every run installs a fresh set -\n// so one frozen instance stands in for the two empty sets each effect used to\n// allocate. 30,000 effects is 60,000 of them\nconst NO_DEPS: ReadonlySet<string> = new Set()\n\n// an effect lives in exactly one store's `effects` set - the one whose\n// $effect created it - and only that store's notify walks it. Content that\n// reads two stores at once (a component's slot content: the parent's names\n// plus the slot props the child passes it) needs one record in both sets, so\n// a store serves this attach handle beside $on/$effect. Tracking already\n// spans stores - trackerStack is module-level, so one run's deps are whatever\n// it read, wherever it read it - only the waking didn't.\n//\n// Named like the compiled scripts' internals ($__effect, $__import) because it\n// is one: `key in store` never answers true for a storeApi name, so `with`\n// can't see it and no template expression can reach it.\n//\n// The cost, accepted: deps are dot-paths with no store namespace, so a name\n// that exists in both stores wakes the effect from either. A spurious re-run,\n// never a stale render\nconst ATTACH = \"$__attach\"\n\n// the extra stores every effect created off a scope must be attached to. Read\n// by createEffectScope off the scope it is given, so a scope can hand the\n// arrangement down to whatever renders inside it (nested :each item scopes,\n// a nested component's prop-sync effects) without every call site knowing\nexport const ALSO_WAKEN_BY = Symbol(\"jq79.alsoWakenBy\")\n\nexport const $reactive = <T extends Record<string, any>>(data: T): ReactiveDeepData<T> => {\n const exactListeners = new Map<string, Set<ChangeListener>>()\n const anyListeners = new Set<AnyChangeListener>()\n const effects = new Set<Effect>()\n\n // one proxy per raw object, for this store alone. Keyed by the *raw object*\n // rather than by its path, so identity travels with the object: :each diffs\n // its items by reference (Object.is), and a reordered list has to hand back\n // the same proxy for the same item or every row would re-render. The flip\n // side is that an object's path is fixed when it is first wrapped, so after a\n // reorder its notifications carry the old index - effects that read the list\n // itself still wake up (they hold its ancestor as a dep), which is what makes it a non-issue in\n // practice\n const proxies = new WeakMap<object, Record<string, any>>()\n\n // $on/$onAny/$effect are served from the root proxy's `get` instead of being\n // defined on the object: a store must leave nothing behind on the data it was\n // handed, and two stores over one object would otherwise clobber each other's\n // handles. Null-prototype, so `key in storeApi` can't match Object.prototype\n const storeApi: Record<string, any> = Object.create(null)\n\n // this store's dep index (see TrieNode). Segments come from splitting a\n // dotKey on \".\", which is also why a flat key written as \"a.b\" indexes\n // exactly where the nested a.b lives - the collision dot-paths have always\n // had, preserved rather than special-cased\n const depTrie = createTrieNode(null, \"\")\n\n // hands back the node it registered on, which is what lets a removal skip the\n // path entirely (see indexEffect)\n const insertDep = (dep: string, effect: Effect): TrieNode => {\n let node = depTrie\n dep.split(\".\").forEach(segment => {\n const children = (node.children ??= new Map())\n let child = children.get(segment)\n if (!child) {\n child = createTrieNode(node, segment)\n children.set(segment, child)\n }\n node = child\n })\n ;((effect.deep ? (node.deep ??= new Set()) : (node.own ??= new Set()))).add(effect)\n return node\n }\n\n // prunes the nodes it empties on the way back up, so a list that churns\n // through rows doesn't leave the trie growing over the dead ones. Follows\n // `parent` rather than re-walking from the root: tearing down a 10,000-row\n // table is 30,000 of these, and splitting each path again to find a node the\n // caller was already holding is most of what that used to cost\n const removeDep = (node: TrieNode, effect: Effect) => {\n ;(effect.deep ? node.deep : node.own)?.delete(effect)\n let current: TrieNode | null = node\n while (current?.parent && isEmptyNode(current)) {\n current.parent.children!.delete(current.segment)\n current = current.parent\n }\n }\n\n const nodeAt = (dep: string): TrieNode | undefined => {\n let node: TrieNode | undefined = depTrie\n for (const segment of dep.split(\".\")) {\n node = node.children?.get(segment)\n if (!node) return undefined\n }\n return node\n }\n\n // every effect this write concerns. Two directions, and they are not\n // symmetric:\n //\n // - **downwards**, always: whatever hangs off the node the walk lands on. A\n // dep of \"user.name\" hears `user = {...}`, because replacing the object\n // replaced the name with it.\n // - **upwards**, only where an ancestor dep is the only channel a change\n // has (see `coarsePath`). A dep of \"data\" does NOT hear\n // `data[5].label = x`: an effect that read the array on its way to row\n // 7's label has no stake in row 5's, and waking all of them is what made\n // 100 row writes cost 100,000 effect runs - see\n // TODOS/2026-08-23.narrow-the-wake-rule.md\n //\n // Returned as a snapshot, so the effects it wakes can reindex themselves -\n // or dispose each other - while it drains\n const effectsFor = (dotKey: string): Set<Effect> => {\n const matched = new Set<Effect>()\n const sweep = (from: TrieNode) => {\n const pending = from.children ? [...from.children.values()] : []\n while (pending.length) {\n const next = pending.pop()!\n next.own?.forEach(effect => matched.add(effect))\n next.deep?.forEach(effect => matched.add(effect))\n next.children?.forEach(child => pending.push(child))\n }\n }\n\n let node: TrieNode | undefined = depTrie\n const segments = dotKey.split(\".\")\n let path = \"\"\n for (let depth = 0; depth < segments.length - 1; depth++) {\n node = node.children?.get(segments[depth])\n if (!node) return matched\n path = path ? `${path}.${segments[depth]}` : segments[depth]\n node.deep?.forEach(effect => matched.add(effect))\n // a nested store sits here: an effect that read through it holds this\n // path and nothing below it, so its own set is the whole channel\n if (bridges.has(path)) node.own?.forEach(effect => matched.add(effect))\n // ...whereas an array's length stands for the array: everything that\n // read an element has to hear a truncation, and those deps are below\n if (depth === segments.length - 2 && segments[depth + 1] === \"length\") {\n node.own?.forEach(effect => matched.add(effect))\n sweep(node)\n }\n }\n node = node.children?.get(segments[segments.length - 1])\n if (!node) return matched\n node.own?.forEach(effect => matched.add(effect))\n node.deep?.forEach(effect => matched.add(effect))\n sweep(node)\n return matched\n }\n\n // Reaching `data[5].label` reads three paths and tracks all three, but for an\n // ordinary effect the two ancestors carry no information the leaf doesn't: a\n // write to \"data\" or \"data.5\" reaches \"data.5.label\" through the subtree\n // sweep anyway. Dropping them is a third of the index to build, hold and tear\n // down on a list of any size.\n //\n // Not for a `deep` effect, where it is exactly backwards - a forwarding\n // effect wakes off its *ancestor* entries, so its shallowest dep is the one\n // doing the work and the leaves are the redundant ones\n const indexable = (effect: Effect, deps: Set<string>): Set<string> => {\n if (effect.deep || deps.size < 2) return deps\n // every ancestor of every dep is redundant, so mark them by walking each\n // dep's own dots rather than comparing deps against each other: a `:each`\n // over 10,000 rows tracks 10,000 deps, and the pairwise version of this\n // was 100,000,000 string comparisons\n const redundant = new Set<string>()\n deps.forEach(dep => {\n for (let dot = dep.indexOf(\".\"); dot !== -1; dot = dep.indexOf(\".\", dot + 1)) {\n redundant.add(dep.slice(0, dot))\n }\n })\n if (!redundant.size) return deps\n const kept = new Set<string>()\n deps.forEach(dep => { if (!redundant.has(dep)) kept.add(dep) })\n return kept\n }\n\n // registers `effect` with this store's trie and keeps it in step. Each store\n // tracks what it indexed for the effect separately, because a detach must\n // clear this trie without touching the others\n const indexEffect = (effect: Effect): Unsubscribe => {\n // dep -> the node it sits on, so removal never re-walks a path: the\n // overwhelmingly common re-run has identical deps and touches the trie not\n // at all, and a disposal goes straight to the nodes it registered\n // almost every effect ends up with exactly one dep once the redundant\n // ancestors are pruned - a row binding reads one path - so the single case\n // is held in two slots and the Map is allocated only when a second arrives\n let soleDep: string | null = null\n let soleNode: TrieNode | null = null\n let indexed: Map<string, TrieNode> | null = null\n // what the last run tracked, before pruning. The comparison has to happen\n // against these rather than against what is indexed, because pruning them\n // is itself work this fast path exists to skip\n let lastTracked: ReadonlySet<string> = NO_DEPS\n\n const placed = (dep: string): boolean =>\n indexed ? indexed.has(dep) : soleDep === dep\n\n const place = (dep: string) => {\n const node = insertDep(dep, effect)\n if (indexed) indexed.set(dep, node)\n else if (soleDep === null) { soleDep = dep; soleNode = node }\n else {\n indexed = new Map([[soleDep, soleNode!], [dep, node]])\n soleDep = soleNode = null\n }\n }\n\n const unplaceStale = (deps: Set<string>) => {\n if (indexed) {\n indexed.forEach((node, dep) => {\n if (deps.has(dep)) return\n removeDep(node, effect)\n indexed!.delete(dep)\n })\n return\n }\n if (soleDep !== null && !deps.has(soleDep)) {\n removeDep(soleNode!, effect)\n soleDep = soleNode = null\n }\n }\n\n const unplaceAll = () => {\n if (indexed) indexed.forEach(node => removeDep(node, effect))\n else if (soleNode) removeDep(soleNode, effect)\n indexed = null\n soleDep = soleNode = null\n }\n const sync = (tracked: Set<string>) => {\n // an effect that re-runs almost always reads exactly what it read last\n // time, and this is on the path of every single run: same count and every\n // path seen before means nothing about the index can have changed\n if (tracked.size === lastTracked.size) {\n let unchanged = true\n tracked.forEach(dep => { unchanged &&= lastTracked.has(dep) })\n if (unchanged) return\n }\n lastTracked = tracked\n const deps = indexable(effect, tracked)\n unplaceStale(deps)\n deps.forEach(dep => { if (!placed(dep)) place(dep) })\n }\n effect.reindex.add(sync)\n sync(effect.deps) // an effect attached after it first ran arrives with deps\n return () => {\n effect.reindex.delete(sync)\n unplaceAll()\n lastTracked = NO_DEPS\n }\n }\n\n // wakes the effects sitting on one exact path, without the subtree sweep a\n // full notify does. Two callers want this: a key-set change (nothing under\n // the object changed, only which keys it has) and a container replaced by one\n // holding the same elements (see notifyReplaced)\n const wakeExactly = (dep: string) => {\n const node = nodeAt(dep)\n if (node) runMatched(new Set([...(node.own ?? []), ...(node.deep ?? [])]))\n }\n\n // an object's key set changed. Effects only - a key set isn't a value, so\n // there is nothing to hand $on/$onAny that they don't already get from the\n // key's own notification\n const notifyKeys = (path: string) => wakeExactly(keysPath(path))\n\n // oldest first, and re-checking membership as it goes: an effect disposed by\n // an earlier one in this same pass (a list diff tearing down the rows it just\n // woke) must not run\n const runMatched = (matched: Set<Effect>) => {\n const ordered = Array.from(matched)\n // effects are usually collected in creation order already - one node's set\n // is filled as its effects are made, and a subtree sweep of a freshly-built\n // list walks them the same way. Checking costs one pass; sorting a woken\n // set of 10,000 costs rather more\n let sorted = true\n for (let i = 1; sorted && i < ordered.length; i++) sorted = ordered[i - 1].order < ordered[i].order\n if (!sorted) ordered.sort((a, b) => a.order - b.order)\n ordered.forEach(effect => { if (effects.has(effect)) effect.run() })\n }\n\n const notify = (dotKey: string, value: any, isNewKey = false) => {\n exactListeners.get(dotKey)?.forEach(listener => listener(value, dotKey))\n anyListeners.forEach(listener => listener(dotKey, value))\n // a newly-created key re-runs every effect: an effect that read the\n // name while it didn't exist couldn't track it (`with` skipped the\n // store entirely), so dep matching would never wake it up\n if (isNewKey) effects.forEach(effect => effect.run())\n // `effects.has` stands in for the membership check `effects.forEach` used\n // to give for free: an effect disposed by an earlier effect in this same\n // notify (a list diff tearing down the rows it just woke) must not run\n else runMatched(effectsFor(dotKey))\n }\n\n // both sides are containers of the same kind, so what changed can be asked\n // rather than assumed. Not the same object - that case never gets here (a\n // same-reference write is the deep-touch channel and stays loud), and not a\n // store on either side, which passes through whole\n const replaceable = (previous: any, next: any): boolean =>\n previous !== next &&\n previous !== null && next !== null &&\n typeof previous === \"object\" && typeof next === \"object\" &&\n !isStore(previous) && !isStore(next) &&\n isPlainData(previous) && isPlainData(next) &&\n Array.isArray(previous) === Array.isArray(next)\n\n const keyCount = (container: any): number =>\n Array.isArray(container) ? container.length : Object.keys(container).length\n\n // which keys hold a different value than they did, or null when so many do\n // that notifying them one at a time would cost more than sweeping the\n // container. Arrays - the case this exists for - are walked by index, so a\n // 10,000 element list is compared without building a key array or a set of\n // them: that bookkeeping alone was costing more than it saved on every\n // replacement that ends up sweeping anyway\n const GIVE_UP: null = null\n\n const whatChanged = (previous: any, next: any): string[] | null => {\n if (Array.isArray(next)) {\n const before = previous.length\n const after = next.length\n // nothing on one side means nothing to reuse on the other\n if (!before || !after) return GIVE_UP\n const span = Math.max(before, after)\n const changed: string[] = []\n for (let index = 0; index < span; index++) {\n if (Object.is($toRaw(previous[index]), $toRaw(next[index]))) continue\n changed.push(String(index))\n if (changed.length * 2 >= span) return GIVE_UP\n }\n return changed\n }\n const keys = new Set([...Object.keys(previous), ...Object.keys(next)])\n if (!keys.size) return GIVE_UP\n const changed: string[] = []\n keys.forEach(key => { if (!Object.is($toRaw(previous[key]), $toRaw(next[key]))) changed.push(key) })\n return changed.length * 2 >= keys.size ? GIVE_UP : changed\n }\n\n // A container replaced by another container: notify the elements that\n // actually differ instead of the container and everything under it.\n // `data = [...data, ...more]` holds the very same row objects at every index\n // it had before, so waking all thirty thousand of their bindings to re-render\n // identical output is ~150ms of a 208ms append - see\n // TODOS/2026-08-23.notify-the-difference.md\n //\n // One level deep on purpose: an element that differs is a changed value, and\n // notifying it sweeps its own subtree, which is what a changed value deserves\n const notifyReplaced = (dotKey: string, previous: any, next: any, notified: any) => {\n // one write, one wake: every path below contributes to a single set that\n // runs once at the end. Notifying them one at a time re-ran an effect that\n // depends on several of them once per path\n const matched = new Set<Effect>()\n const collectExact = (dep: string) => {\n const node = nodeAt(dep)\n node?.own?.forEach(effect => matched.add(effect))\n node?.deep?.forEach(effect => matched.add(effect))\n }\n\n const changed = whatChanged(previous, next)\n // when most of the container differs there is nothing to spare: `data = []`\n // and a wholesale replacement change every key, and reaching each one\n // through its own trie walk costs more than the single sweep it replaces.\n // whatChanged says so by giving up. The decision has to come before\n // anything is announced, or the plain notify would fire the container's\n // listeners a second time\n if (!changed) return notify(dotKey, notified)\n\n exactListeners.get(dotKey)?.forEach(listener => listener(notified, dotKey))\n // $onAny hears the container and nothing else, exactly as it did when this\n // was one notify. It is what a bridge re-notifies upstairs, and the holder\n // sweeps its own side off that one path - announcing each changed element\n // as well would be a thousand redundant notifications for the same news\n anyListeners.forEach(listener => listener(dotKey, notified))\n // the container itself did change: whoever read it, or forwards it whole,\n // hears that - but nothing is swept on its account\n collectExact(dotKey)\n\n changed.forEach(key => {\n const after = $toRaw(next[key])\n const child = `${dotKey}.${key}`\n const value = isWrappable(after) ? wrap(after, child) : after\n exactListeners.get(child)?.forEach(listener => listener(value, child))\n effectsFor(child).forEach(effect => matched.add(effect))\n })\n if (keyCount(previous) !== keyCount(next)) collectExact(keysPath(dotKey))\n // an array's length is a real dep (a `:each` reads it on its way through\n // list.map) and is not one of the keys walked above. Collected exactly:\n // the sweep a length write normally carries is for a truncation, and the\n // elements that a shrink dropped are already in `keys`\n if (Array.isArray(next) && previous.length !== next.length) {\n const lengthKey = `${dotKey}.length`\n exactListeners.get(lengthKey)?.forEach(listener => listener(next.length, lengthKey))\n collectExact(lengthKey)\n }\n runMatched(matched)\n }\n\n const isWrappable = (value: any): value is Record<string, any> =>\n value !== null && typeof value === \"object\" && isPlainData(value)\n\n // a store nested inside this one keeps its own listeners and its own effects,\n // and this store's effects are not among them - so a write through the inner\n // store notifies nobody out here, and a component rendering `{{ cart.items }}`\n // off a `$reactive` it was handed would never update. The holder subscribes\n // instead, and re-notifies the inner store's changes under the path it sits at\n // (\"items.0\" -> \"cart.items.0\"). An effect that read through `cart` recorded\n // exactly that path's ancestor as a dependency, so the trie walk wakes it.\n // Chains compose: re-notifying runs this store's own $onAny listeners, which\n // is how a store two levels down still reaches the top\n const bridges = new Map<string, { store: any; unsubscribe: Unsubscribe }>()\n\n const bridge = (store: any, path: string) => {\n const current = bridges.get(path)\n if (current?.store === store) return\n current?.unsubscribe()\n bridges.set(path, {\n store,\n unsubscribe: store.$onAny((dotKey: string, value: any) => notify(`${path}.${dotKey}`, value)),\n })\n }\n\n // the key no longer holds the store it held: stop listening to it\n const unbridge = (path: string) => {\n bridges.get(path)?.unsubscribe()\n bridges.delete(path)\n }\n\n // the reactive view of `raw`, created on demand. Callers must hand it a raw\n // object (see $toRaw at both call sites): wrapping a proxy is what compounds\n const wrap = (raw: Record<string, any>, path: string): Record<string, any> => {\n const cached = proxies.get(raw)\n if (cached) return cached\n\n // keys that were deleted off this object. `with ($scope)` resolves a name\n // through [[HasProperty]], so without a claim here a deleted key would fall\n // through to globalThis and the *whole* expression would die of\n // ReferenceError - `user ? user.name : \"none\"` must take its else branch\n // instead. The cost: `\"user\" in store` stays true after a delete\n let tombstones: Set<string> | null = null\n\n const proxy: Record<string, any> = new Proxy(raw, {\n has(target, key) {\n return Reflect.has(target, key) || (typeof key === \"string\" && tombstones?.has(key) === true)\n },\n // reading the key set is a dependency of its own: `Object.keys(props)`,\n // `{...props}`, `for...in` and renderEach's `Object.entries` all care\n // about which keys exist, not about what any one of them holds. It used\n // to be caught only by the coarse ancestor rule, which is now gone -\n // this is the same job Svelte gives a per-object `version` signal, held\n // as an ordinary trie child under a reserved final segment (see\n // KEYS_SEGMENT), so adds and deletes wake exactly the effects enumerating\n ownKeys(target) {\n trackerStack[trackerStack.length - 1]?.add(keysPath(path))\n return Reflect.ownKeys(target)\n },\n get(target, key, receiver) {\n if (key === RAW) return target\n if (key === STORE) return path === \"\"\n if (typeof key !== \"string\") return Reflect.get(target, key, receiver)\n if (path === \"\" && key in storeApi) return storeApi[key]\n\n const dotKey = path ? `${path}.${key}` : key\n trackerStack[trackerStack.length - 1]?.add(dotKey)\n\n // nested objects are wrapped here rather than up front, so the object\n // handed to $reactive is never rewritten\n const value = Reflect.get(target, key, receiver)\n if (isStore(value)) {\n bridge(value, dotKey)\n return value\n }\n\n const raw = $toRaw(value)\n return isWrappable(raw) ? wrap(raw, dotKey) : raw\n },\n set(target, key: string, value, receiver) {\n // an assignment delegated up the prototype chain from a derived scope\n // (Object.create(store) child, or a wrapping proxy): if the key isn't\n // a real property of this store, honor the receiver so the new binding\n // lands on the derived scope - a scope-local variable, not a store\n // mutation, so no notify. If the key IS a store property, fall through\n // and mutate the store itself regardless of receiver, so assignments\n // like @click=\"count = count + 1\" work from any nested scope\n if (receiver !== proxy && !Object.prototype.hasOwnProperty.call(target, key)) {\n return Reflect.set(target, key, value, receiver)\n }\n\n const dotKey = path ? `${path}.${key}` : key\n // store the raw value, never a proxy - including one of our own, so\n // that `list = [list[1], list[0]]` doesn't write proxies back into the\n // data. Reads re-wrap it, from the cache, as the very same proxy. A\n // whole store assigned in is the exception: it stays as it is\n const stored = isStore(value) ? value : $toRaw(value)\n const isNewKey = !Object.prototype.hasOwnProperty.call(target, key)\n // a primitive write that changes nothing notifies nobody: it's what\n // lets an effect write the value it just read (a normalizing\n // assignment, a prop sync) and settle instead of waking itself\n // forever. Only primitives and functions: re-writing the SAME object\n // reference stays loud, because that is the cross-store \"deep touch\"\n // channel - a parent's prop sync forwards `user.name = x` to the\n // child's store by re-assigning the same `user`, and the child's\n // listeners live on the child's store, not the parent's. A new key\n // always announces itself - the sweep is its whole point\n if (!isNewKey && Object.is(target[key], stored) && (stored === null || typeof stored !== \"object\")) return true\n const previous = target[key]\n target[key] = stored\n tombstones?.delete(key) // the key exists again: no claim needed\n if (isStore(stored)) bridge(stored, dotKey)\n else unbridge(dotKey)\n const notified = isStore(stored) || !isWrappable(stored) ? stored : wrap(stored, dotKey)\n // a new key already re-runs every effect in the store (see notify), so\n // the key set growing needs no announcement of its own - only a delete,\n // which wakes precisely, does\n if (!isNewKey && replaceable(previous, stored)) notifyReplaced(dotKey, previous, stored, notified)\n else notify(dotKey, notified, isNewKey)\n return true\n },\n // `delete data.user` is a plain-object mutation like any other, so it\n // notifies like one - with `undefined`, which is what a read returns\n // afterwards. Array methods that shrink (pop, splice) delete their dead\n // slots through this trap too. No new-key sweep: whoever depended on the\n // key tracked it while it existed, so dep matching wakes exactly them\n deleteProperty(target, key) {\n if (typeof key !== \"string\") return Reflect.deleteProperty(target, key)\n const had = Object.prototype.hasOwnProperty.call(target, key)\n const deleted = Reflect.deleteProperty(target, key)\n if (deleted && had) {\n const dotKey = path ? `${path}.${key}` : key\n ;(tombstones ??= new Set()).add(key)\n unbridge(dotKey) // a nested store it held: stop listening to it\n notify(dotKey, undefined)\n // the key set shrank: whoever enumerated this object hears it even\n // if it never read the key that went (see the ownKeys trap)\n notifyKeys(path)\n }\n return deleted\n }\n })\n\n proxies.set(raw, proxy)\n return proxy\n }\n\n const reactive = wrap($toRaw(data), \"\") as ReactiveDeepData<T>\n\n // a store handed in with the data (a prop, or render data) is bridged here\n // rather than on first read, so a listener registered before anything reads\n // the key still hears it. Only the top level is scanned: that's where a prop\n // lands, and descending would mean walking whatever else was handed in - a\n // highlighter, an API client - to its leaves. A store sitting deeper is\n // bridged when the read that reaches it wraps its parent\n Object.entries($toRaw(data)).forEach(([key, value]) => {\n if (isStore(value)) bridge(value, key)\n })\n\n const $on = (dotKey: string, listener: ChangeListener, { immediate = false }: ListenerOptions = {}): Unsubscribe => {\n if (!exactListeners.has(dotKey)) exactListeners.set(dotKey, new Set())\n exactListeners.get(dotKey)!.add(listener)\n if (immediate) listener(getByPath(reactive, dotKey), dotKey)\n return () => exactListeners.get(dotKey)?.delete(listener)\n }\n\n const $onAny = (listener: AnyChangeListener, { immediate = false }: ListenerOptions = {}): Unsubscribe => {\n anyListeners.add(listener)\n if (immediate) walkLeaves(reactive, \"\", (dotKey, value) => listener(dotKey, value))\n return () => anyListeners.delete(listener)\n }\n\n const $effect = (run: () => void, { deep = false, alsoWakenBy }: EffectOptions = {}): Unsubscribe => {\n // a notify landing while this effect runs (an item's render writing to\n // the store, waking the very effect that is rendering it) must not\n // re-enter mid-run - the half-done run would race its own repeat over\n // shared state, which is how :each once tripled its rows. It marks the\n // run dirty instead, and repeats *after* it finishes, against settled\n // state, until clean. Still fully synchronous: everything happens before\n // the triggering assignment returns\n let running = false\n let dirty = false\n const effect: Effect = {\n deps: NO_DEPS as Set<string>,\n reindex: new Set(),\n deep,\n order: effectsCreated++,\n run: () => {\n if (running) {\n dirty = true\n return\n }\n running = true\n try {\n let cycles = 0\n do {\n dirty = false\n const deps = new Set<string>()\n trackerStack.push(deps)\n try {\n run()\n } finally {\n trackerStack.pop()\n effect.deps = deps\n }\n } while (dirty && ++cycles < 100)\n // an effect that keeps writing its own dependencies used to die by\n // stack overflow; now it is cut off and named\n if (dirty) console.error(\"jq79: an effect re-woke itself 100 times in a row (it writes what it reads); giving up on it settling\")\n } finally {\n running = false\n // the settled deps are the only ones worth indexing: the repeats of\n // a dirty run overwrite each other, and a notify that lands mid-run\n // is queued rather than dispatched, so nothing reads the index in\n // between. In `finally` so a run that throws still leaves the index\n // matching the deps the run did commit\n effect.reindex.forEach(sync => sync(effect.deps))\n }\n },\n }\n effects.add(effect)\n const stopIndexing = indexEffect(effect)\n const forget = () => {\n effects.delete(effect)\n stopIndexing()\n }\n // the shared case is rare (only slot content asks for it) and this\n // function is on the stack for as long as whatever it renders - a\n // component that renders itself stacks 200 of these - so it keeps the\n // shape it had, and the extra bookkeeping lives in its own frame\n if (alsoWakenBy?.length) return attachAndRun(effect, alsoWakenBy, forget)\n effect.run()\n return forget\n }\n\n // attached before the first run, so a store that notifies during it (a setup\n // script's write, a prop sync) reaches this effect like any other\n const attachAndRun = (effect: Effect, alsoWakenBy: Record<string, any>[], forget: Unsubscribe): Unsubscribe => {\n const detach = alsoWakenBy.map(store => store?.[ATTACH]?.(effect)).filter(Boolean) as Unsubscribe[]\n effect.run()\n return () => {\n forget()\n detach.forEach(drop => drop())\n }\n }\n\n const $__attach = (effect: Effect): Unsubscribe => {\n effects.add(effect)\n const stopIndexing = indexEffect(effect)\n return () => {\n effects.delete(effect)\n stopIndexing()\n }\n }\n\n const $dispose = () => {\n bridges.forEach(({ unsubscribe }) => unsubscribe())\n bridges.clear()\n }\n\n storeApi.$on = $on\n storeApi.$onAny = $onAny\n storeApi.$effect = $effect\n storeApi.$dispose = $dispose\n storeApi[ATTACH] = $__attach\n\n return reactive\n}\n// groups the disposers of every $effect created for one rendered subtree\n// (an :if branch, an :each item, ...) so the whole subtree's bindings can be\n// torn down in one call when that subtree is replaced/removed. `scope.$effect`\n// resolves through the prototype chain up to the root store no matter how\n// many nested :each scopes sit in between (see renderEach's itemScope)\nexport type EffectScope = {\n effect: (run: () => void) => void\n // registers an arbitrary cleanup (e.g. destroying a nested component) to\n // run when this subtree is torn down\n onDispose: (fn: Unsubscribe) => void\n // re-runs every effect registered on this scope, nested scopes excluded:\n // how :each tells a reused, repositioned entry's dep-less bindings (the\n // `{{ $index }}`-only case) about their move. Deps stay as they were -\n // callers run it untracked\n refresh: () => void\n dispose: () => void\n}\n\n// `deep` marks every effect this scope creates as forwarding a value wholesale\n// rather than reading into it - the prop-sync scope, and nothing else so far.\n// See the `deep` flag on $effect\nexport const createEffectScope = (scope: Record<string, any>, deep = false): EffectScope => {\n const disposers: Unsubscribe[] = []\n const runs: (() => void)[] = []\n // whatever the scope was handed (slot content is the only thing that sets\n // it today): the stores this scope's effects belong to besides their own.\n // Left undefined when there are none, which is $effect's fast path\n const alsoWakenBy: Record<string, any>[] | undefined = (scope as any)[ALSO_WAKEN_BY]\n return {\n effect: run => {\n disposers.push(scope.$effect(run, { deep, alsoWakenBy }))\n runs.push(run)\n },\n onDispose: fn => { disposers.push(fn) },\n refresh: () => { runs.forEach(run => run()) },\n dispose: () => {\n disposers.splice(0).forEach(dispose => dispose())\n runs.length = 0\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// :setup script transform\n//\n// setup scripts are written like Svelte components:\n//\n// let firstName = null\n// $: fullName = `${firstName} ${lastName}`\n// fetchUser().then(user => { firstName = user.firstName })\n//\n// and are executed inside `with ($scope)` against the component's reactive\n// store, so plain assignments (even from async callbacks) go through the\n// proxy's set trap and re-render whatever depends on them. To make that work\n// the source is lightly rewritten - no full JS parser, just a scanner that is\n// string/comment-aware and only touches code at brace/paren depth 0:\n// - `let/var/const x = ...` at the top level loses its keyword, becoming a\n// scope assignment (the name is pre-declared on the store so the `with`\n// lookup resolves it)\n// - `$: x = expr` becomes `$__effect(() => { x = expr })`, re-running when a\n// dependency read inside expr changes ($__effect is deliberately NOT a\n// property of the scope, so `with` falls through to the function parameter)\n// ---------------------------------------------------------------------------\n\ntype SetupTransform = { vars: string[]; code: string }\n\n// a declaration whose target is an identifier (`let x`), an object pattern\n// (`let { a }`, space optional) or an array pattern (`let [x]`)\nconst DECLARATION_START_RE = /(?:let|var|const)(?:\\s+(?=[A-Za-z_$])|\\s*(?=[{[]))/y\nconst REACTIVE_LABEL_RE = /\\$:\\s*/y\nconst IMPORT_CALL_RE = /import(?=\\s*\\()/y\nconst REACTIVE_ASSIGN_RE = /\\$:\\s*([A-Za-z_$][\\w$]*)\\s*=(?!=)/y\n\nconst skipString = (src: string, start: number): number => {\n const quote = src[start]\n let i = start + 1\n while (i < src.length) {\n if (src[i] === \"\\\\\") { i += 2; continue }\n if (src[i] === quote) return i + 1\n i++\n }\n return src.length\n}\n\nconst skipLineComment = (src: string, start: number): number => {\n const end = src.indexOf(\"\\n\", start)\n return end === -1 ? src.length : end\n}\n\nconst skipBlockComment = (src: string, start: number): number => {\n const end = src.indexOf(\"*/\", start + 2)\n return end === -1 ? src.length : end + 2\n}\n\n// index of the next thing that isn't whitespace or a comment\nconst skipToToken = (src: string, start: number): number => {\n let i = start\n while (i < src.length) {\n if (/\\s/.test(src[i])) { i++; continue }\n if (src[i] === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (src[i] === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n break\n }\n return i\n}\n\n// ---------------------------------------------------------------------------\n// regex literals. The scanners walk the source counting bracket depth, and a\n// regex walked as if it were code poisons that count: `split(/\\//)` puts two\n// slashes side by side (a line comment, as far as a scanner knows) and the\n// `)` after them is skipped uncounted; `/[(]/` inflates the depth for good.\n// So a `/` that opens a regex is consumed whole - and whether it opens one is\n// the classic lexer call, made the way every tokenizer makes it: by what came\n// before. Division needs a completed expression on its left; everywhere else\n// a `/` can only be a regex.\n// ---------------------------------------------------------------------------\n\n// reserved words a regex can follow. Reserved only - `of` is not (`const of\n// = 4; of / 2` is legal division), so `for (x of /re/)` stays unrescued\n// rather than risking real code\nconst REGEX_AFTER_WORD = new Set([\n \"return\", \"typeof\", \"case\", \"in\", \"instanceof\", \"new\", \"delete\", \"void\", \"do\", \"else\", \"yield\", \"await\",\n])\n\n// whether a `/` at `at` opens a regex literal rather than a division: looks\n// backward past whitespace and block comments for the last meaningful thing.\n// A completed expression - identifier, number, closing quote or bracket,\n// postfix ++/-- - takes division; a reserved word or any other punctuator\n// admits a regex. Only consulted for the rare `/` that is neither `//` nor\n// `/*`, so the scanners pay nothing on the common path\nconst regexAllowed = (src: string, at: number): boolean => {\n let i = at - 1\n while (i >= 0) {\n const ch = src[i]\n if (/\\s/.test(ch)) { i--; continue }\n if (ch === \"/\" && src[i - 1] === \"*\") {\n const open = src.lastIndexOf(\"/*\", i - 2)\n if (open === -1) return true // an unopened comment tail: malformed input\n i = open - 1\n continue\n }\n break\n }\n if (i < 0) return true // the start of the source starts an expression\n const ch = src[i]\n if (/[\\w$]/.test(ch)) {\n let start = i\n while (start > 0 && /[\\w$]/.test(src[start - 1])) start--\n return REGEX_AFTER_WORD.has(src.slice(start, i + 1))\n }\n if ((ch === \"+\" || ch === \"-\") && src[i - 1] === ch) return false // postfix ++/--\n return !\")]}\\\"'`.\".includes(ch)\n}\n\n// consumes a regex literal (with its flags): backslash escapes, and character\n// classes, where an unescaped `/` doesn't close the literal (`/[/]/` is one\n// regex). A literal can't contain an unescaped newline, so hitting one means\n// the classification was wrong or the input malformed - stop there, bounding\n// any damage to a single line\nconst skipRegex = (src: string, start: number): number => {\n let i = start + 1\n let inClass = false\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"\\\\\") { i += 2; continue }\n if (ch === \"\\n\") return i\n if (ch === \"[\") inClass = true\n else if (ch === \"]\") inClass = false\n else if (ch === \"/\" && !inClass) {\n i++\n while (i < src.length && /[a-z]/i.test(src[i])) i++ // flags\n return i\n }\n i++\n }\n return src.length\n}\n\n// tokens that can't *start* a statement, so a line beginning with one is\n// continuing the previous expression rather than opening a new statement -\n// the same call JS's automatic semicolon insertion makes. Unary-only forms\n// (!, ~, ++, --) are deliberately absent: those do start a statement, and JS\n// inserts the semicolon before them\nconst CONTINUATION_RE = /^(\\?\\.|\\?\\?|&&|\\|\\||\\*\\*|[.,+\\-*/%&|^<>=?:([])/\n\n// the last meaningful character before `at`: walks back past whitespace and\n// block comments, the way regexAllowed does. A line comment can't be skipped\n// from behind (its start is only findable forwards), so a line ending in one\n// reports the comment's text instead - callers treat that as \"not the char I\n// was looking for\", which degrades to ending the statement, exactly as\n// before this helper existed\nconst lastMeaningfulBefore = (src: string, at: number): string => {\n let i = at - 1\n while (i >= 0) {\n const ch = src[i]\n if (/\\s/.test(ch)) { i--; continue }\n if (ch === \"/\" && src[i - 1] === \"*\") {\n const open = src.lastIndexOf(\"/*\", i - 2)\n if (open === -1) return \"\"\n i = open - 1\n continue\n }\n return ch\n }\n return \"\"\n}\n\n// end of a statement starting at `start`: the first `;` or line break that\n// isn't inside a string/comment or unbalanced brackets. A line break only\n// ends the statement if the next line can't continue it, so leading-dot\n// method chains and multi-line operator chains stay in one piece:\n//\n// $: total = items\n// .filter(item => item.active) <- still the same statement\n// .length\n//\n// ...and only if the current line *can* end it: a line whose last meaningful\n// character is `,` or `=` left its expression incomplete (a multi-line\n// declarator list writes exactly this), so the statement continues - the\n// same ASI call as the leading-token check, made from the other side\nconst findStatementEnd = (src: string, start: number): number => {\n let depth = 0\n let i = start\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth--\n else if (depth <= 0 && ch === \";\") return i\n else if (depth <= 0 && ch === \"\\n\") {\n const next = skipToToken(src, i + 1)\n const continues =\n next < src.length &&\n (CONTINUATION_RE.test(src.slice(next, next + 2)) || [\",\", \"=\"].includes(lastMeaningfulBefore(src, i)))\n if (!continues) return i\n i = next\n continue\n }\n i++\n }\n return src.length\n}\n\n// ---------------------------------------------------------------------------\n// top-level declarations. `let x = 1` loses its keyword and becomes a scope\n// assignment (x pre-declared on the store). A destructuring declarator\n// becomes an *assignment pattern*: inside `with`, `({ a, b } = obj)` writes\n// every binding through the reactive proxy - which is what makes it reactive.\n// The parens keep the `{` from opening a block, and a leading `;` keeps the\n// `(` from gluing onto the previous line as a call. Multi-declarator\n// statements (`let a = 1, b = 2`) register every binding, not just the first.\n// These lean on the pattern helpers defined with the props signature below\n// (splitTopLevel, indexOfTopLevel, defaultAssignIndex); the scanner only\n// runs long after the module evaluates, so the order is cosmetic\n// ---------------------------------------------------------------------------\n\ntype Declarator = { raw: string; codeEnd: number }\n\n// splits a declarator list at top-level commas, keeping each segment's raw\n// text (layout and comments included) and where its last meaningful token\n// ends - the spot a closing paren must go, so a trailing comment can't\n// swallow it\nconst splitDeclarators = (src: string): Declarator[] => {\n const parts: Declarator[] = []\n let depth = 0\n let start = 0\n let lastEnd = 0\n const flush = (end: number) => {\n parts.push({ raw: src.slice(start, end), codeEnd: Math.max(0, lastEnd - start) })\n start = end + 1\n lastEnd = start\n }\n let i = 0\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); lastEnd = i; continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); lastEnd = i; continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth--\n else if (ch === \",\" && depth <= 0) { flush(i); i++; continue }\n if (!/\\s/.test(ch)) lastEnd = i + 1\n i++\n }\n flush(src.length)\n return parts\n}\n\n// the *binding* names a destructuring pattern declares - unlike\n// parsePropsPattern, which answers \"which props\" (the keys), this answers\n// \"which variables\": `{ a: x }` binds x, `{ a: { b } }` binds b,\n// `[x, ...rest]` binds x and rest. Defaults are stripped; what remains is a\n// nested pattern (recurse) or the bound identifier\nconst patternBindings = (src: string): string[] => {\n const pattern = src.trim()\n if (!pattern.startsWith(\"{\") && !pattern.startsWith(\"[\")) {\n return IDENTIFIER_RE.test(pattern) ? [pattern] : []\n }\n const names: string[] = []\n for (let part of splitTopLevel(pattern.slice(1, patternCloseIndex(pattern)))) {\n if (part.startsWith(\"...\")) part = part.slice(3).trim()\n const assign = defaultAssignIndex(part)\n if (assign !== -1) part = part.slice(0, assign).trim()\n if (pattern.startsWith(\"{\")) {\n const colon = indexOfTopLevel(part, \":\")\n if (colon !== -1) {\n names.push(...patternBindings(part.slice(colon + 1)))\n continue\n }\n }\n names.push(...patternBindings(part))\n }\n return names\n}\n\n// one `let/var/const` declarator list, rewritten to scope assignments.\n// Each segment's initializer is re-scanned so an `import()` inside it is\n// rewritten like anywhere else - nothing else can match in there, since a\n// nested top-level declaration inside a declarator is a SyntaxError in JS\nconst rewriteDeclarators = (src: string): SetupTransform => {\n const vars: string[] = []\n const rewritten = splitDeclarators(src).map(({ raw, codeEnd }) => {\n const lead = raw.match(/^\\s*/)![0]\n if (codeEnd <= lead.length) return { text: raw, empty: true }\n const body = raw.slice(lead.length, codeEnd)\n const tail = raw.slice(codeEnd)\n const assign = defaultAssignIndex(body)\n const target = (assign === -1 ? body : body.slice(0, assign)).trim()\n const isPattern = body[0] === \"{\" || body[0] === \"[\"\n if (isPattern) vars.push(...patternBindings(target))\n else if (IDENTIFIER_RE.test(target)) vars.push(target)\n const code = transformSetupScript(body).code\n return { text: `${lead}${isPattern ? `(${code})` : code}${tail}`, empty: false }\n })\n\n // a trailing comment-only segment (`let a = 1, // note` cut at its line\n // end) is re-attached without its comma, so the output stays a statement\n const tail: string[] = []\n while (rewritten.length && rewritten[rewritten.length - 1].empty) tail.unshift(rewritten.pop()!.text)\n let code = rewritten.map(part => part.text).join(\",\") + tail.join(\"\")\n if (code.trimStart().startsWith(\"(\")) code = `;${code}`\n return { vars, code }\n}\n\nexport const transformSetupScript = (src: string): SetupTransform => {\n const vars: string[] = []\n let out = \"\"\n let i = 0\n let depth = 0\n let atStatementStart = true\n\n while (i < src.length) {\n const ch = src[i]\n const next = src[i + 1]\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n const end = skipString(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n if (ch === \"/\" && (next === \"/\" || next === \"*\")) {\n const end = next === \"/\" ? skipLineComment(src, i) : skipBlockComment(src, i)\n out += src.slice(i, end)\n i = end\n continue\n }\n if (ch === \"/\" && regexAllowed(src, i)) {\n const end = skipRegex(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n\n // `import(...)` is a keyword form, so it can't be intercepted through the\n // scope - rewrite the identifier to the injected $__import (which loads\n // .html URLs as components via Component79.fetch and delegates the rest to\n // native import). The `(` is left for the scanner so depth stays balanced\n if (ch === \"i\" && (i === 0 || !/[\\w$.]/.test(src[i - 1]))) {\n IMPORT_CALL_RE.lastIndex = i\n if (IMPORT_CALL_RE.test(src)) {\n out += \"$__import\"\n i += \"import\".length\n atStatementStart = false\n continue\n }\n }\n\n if (depth === 0 && atStatementStart) {\n DECLARATION_START_RE.lastIndex = i\n const decl = DECLARATION_START_RE.exec(src)\n if (decl) {\n const start = i + decl[0].length\n const end = findStatementEnd(src, start)\n const { vars: names, code } = rewriteDeclarators(src.slice(start, end))\n vars.push(...names)\n out += code\n i = end\n atStatementStart = false\n continue\n }\n\n REACTIVE_LABEL_RE.lastIndex = i\n const label = REACTIVE_LABEL_RE.exec(src)\n if (label) {\n REACTIVE_ASSIGN_RE.lastIndex = i\n const assign = REACTIVE_ASSIGN_RE.exec(src)\n if (assign) vars.push(assign[1])\n const start = i + label[0].length\n const end = findStatementEnd(src, start)\n // the body is re-scanned rather than sliced raw, so an `import()`\n // inside it gets the $__import rewrite like anywhere else. Safe to\n // recurse: strings/comments/regexes copy through unchanged, and a\n // depth-0 declaration inside a labeled statement is a SyntaxError\n // in JS anyway, so nothing else can rewrite\n out += `$__effect(() => { ${transformSetupScript(src.slice(start, end)).code} });`\n i = end\n continue\n }\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n\n out += ch\n i++\n }\n\n return { vars, code: out }\n}\n\n// ---------------------------------------------------------------------------\n// factory scripts - a <script> whose top level has `export default` runs as a\n// plain lexical module instead of a `with`-scoped setup script: no implicit\n// reactivity, no `$:` labels - standard JS that editors and type-checkers\n// understand. The default export is called with the instance context\n// ({ $data, $effect, $emit, $mounted, $self, $$self }) and a returned object\n// is merged into the reactive store for the template to use.\n// Detection is backwards-safe: `export default` is a SyntaxError inside a\n// setup script, so no previously-working component can change behavior.\n// The same scanner rewrites the module-only syntax into a Function body:\n// - `export default X` -> `$__exports.default = X`\n// - `import d from \"m\"` -> `const d = $__default(await $__import(\"m\"))`\n// (and the other static clause forms), so imports resolve through the same\n// $__import as setup scripts: bundler map first, then fetch/native import\n// ---------------------------------------------------------------------------\n\nconst EXPORT_DEFAULT_RE = /export\\s+default(?![\\w$])/y\n// clause (default/namespace/named, no quotes or parens) + specifier; the\n// no-clause alternative requires the specifier right away, so dynamic\n// `import(...)` and `import.meta` never match\nconst STATIC_IMPORT_RE = /import\\s*(?:([\\w$\\s,{}*]+?)\\s*from\\s*)?([\"'])([^\"'\\n]+)\\2/y\n\n// splits an import clause on top-level commas: `d, { a, b as c }` keeps the\n// braced group together\nconst splitImportClause = (clause: string): string[] => {\n const parts: string[] = []\n let depth = 0\n let start = 0\n for (let i = 0; i <= clause.length; i++) {\n const ch = clause[i]\n if (ch === \"{\") depth++\n else if (ch === \"}\") depth--\n else if (i === clause.length || (ch === \",\" && depth === 0)) {\n const part = clause.slice(start, i).trim()\n if (part) parts.push(part)\n start = i + 1\n }\n }\n return parts\n}\n\n// one static import statement -> const bindings from the awaited module\nconst staticImportToAwait = (clause: string | undefined, spec: string, n: number): string => {\n const source = `await $__import(${JSON.stringify(spec)})`\n if (clause === undefined) return source // side-effect import\n const parts = splitImportClause(clause)\n const bindings: string[] = []\n let ref = source\n if (parts.length > 1) {\n const tmp = `$__mod${n}`\n bindings.push(`${tmp} = ${source}`)\n ref = tmp\n }\n for (const part of parts) {\n if (part.startsWith(\"{\")) bindings.push(`${part.replace(/\\s+as\\s+/g, \": \")} = ${ref}`)\n else if (part.startsWith(\"*\")) bindings.push(`${part.replace(/^\\*\\s*as\\s+/, \"\")} = ${ref}`)\n else bindings.push(`${part} = $__default(${ref})`)\n }\n return `const ${bindings.join(\", \")}`\n}\n\n// ---------------------------------------------------------------------------\n// the component's prop signature\n//\n// A component declares the props it takes as a destructuring pattern, in the\n// place each script mode already puts its inputs: the `:setup` attribute's\n// value, or the factory's *first* parameter (the ctx moved to the second).\n// Position is fixed, so the signature is read straight from the source string -\n// no parser, no execution - and the runtime can seed the defaults on the store\n// before the first render, which is what makes them reach the template even in\n// factory mode (where JS would only apply them inside the function body).\n//\n// <script :setup=\"{ label = 'Total', step = 1 }\">\n// export default ({ label = \"Total\" }, { $data }) => {}\n//\n// An object pattern *is* the declaration; anything else (`_`, a plain\n// identifier, no attribute at all) declares nothing and stays permissive.\n// ---------------------------------------------------------------------------\n\n// `as` is the local name the pattern binds the key to, when it isn't the key\n// itself (`{ item: row }`). A prop signature has no use for it - what the\n// store holds is the key - but the slot binder (`:slot=\"{ item: row }\"`) is\n// the same pattern read for the other half: which names the content uses\nexport type PropDecl = { name: string; default?: string; as?: string }\n\nconst IDENTIFIER_RE = /^[A-Za-z_$][\\w$]*$/\n\n// index of the bracket that closes the one opening at src[0], skipping\n// strings, comments and regex literals; src.length when unbalanced\nconst patternCloseIndex = (src: string): number => {\n let depth = 0\n let i = 0\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch) && --depth === 0) return i\n i++\n }\n return src.length\n}\n\n// index of the first `ch` at bracket depth 0, skipping strings and comments\nconst indexOfTopLevel = (src: string, ch: string): number => {\n let depth = 0\n let i = 0\n while (i < src.length) {\n const c = src[i]\n if (c === \"'\" || c === '\"' || c === \"`\") { i = skipString(src, i); continue }\n if (c === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (c === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (c === \"/\" && c !== ch && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (\"([{\".includes(c)) depth++\n else if (\")]}\".includes(c)) depth--\n else if (depth === 0 && c === ch) return i\n i++\n }\n return -1\n}\n\nconst splitTopLevel = (src: string): string[] => {\n const parts: string[] = []\n let depth = 0\n let start = 0\n let i = 0\n while (i <= src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }\n if (ch !== undefined && \"([{\".includes(ch)) depth++\n else if (ch !== undefined && \")]}\".includes(ch)) depth--\n else if (i === src.length || (ch === \",\" && depth === 0)) {\n const part = src.slice(start, i).trim()\n if (part) parts.push(part)\n start = i + 1\n }\n i++\n }\n return parts\n}\n\n// the `=` that opens a default value: the first one at depth 0 that isn't part\n// of `==`/`===` or an arrow's `=>` (so `{ format = a => a }` keeps its default)\nconst defaultAssignIndex = (src: string): number => {\n let from = 0\n while (from < src.length) {\n const at = indexOfTopLevel(src.slice(from), \"=\")\n if (at === -1) return -1\n const i = from + at\n if (src[i + 1] !== \"=\" && src[i + 1] !== \">\" && src[i - 1] !== \"=\" && src[i - 1] !== \"!\") return i\n from = i + 1\n }\n return -1\n}\n\n// a destructuring pattern -> the props it declares. null means \"no signature\":\n// the pattern isn't an object one (`_`, `props`, nothing at all), so the\n// component declares nothing and keeps the permissive, undeclared behavior.\n// `{}` parses to [] - a closed signature that declares zero props\nexport const parsePropsPattern = (pattern: string | undefined): PropDecl[] | null => {\n const src = (pattern ?? \"\").trim()\n if (!src.startsWith(\"{\")) return null\n\n // to the `}` that closes the pattern, so a parameter's own default value\n // (`({ label } = {})`) is left out of it\n const close = patternCloseIndex(src)\n if (close >= src.length) return null // unbalanced: not a pattern we can read\n\n const props: PropDecl[] = []\n for (const part of splitTopLevel(src.slice(1, close))) {\n if (part.startsWith(\"...\")) continue // a rest element names no prop\n const assign = defaultAssignIndex(part)\n const named = assign === -1 ? part : part.slice(0, assign)\n const fallback = assign === -1 ? undefined : part.slice(assign + 1).trim()\n // `{ user: { id } }` and `{ user: renamed }` both declare `user`: what the\n // store holds is the key, whatever the pattern binds it to\n const colon = indexOfTopLevel(named, \":\")\n const name = (colon === -1 ? named : named.slice(0, colon)).trim()\n if (!IDENTIFIER_RE.test(name)) continue\n const decl: PropDecl = { name }\n if (fallback !== undefined) decl.default = fallback\n // only a plain rename is kept: `{ user: { id } }` binds no single name, so\n // there is nothing to record - the prop is still declared under its key\n const local = colon === -1 ? \"\" : named.slice(colon + 1).trim()\n if (IDENTIFIER_RE.test(local)) decl.as = local\n props.push(decl)\n }\n return props\n}\n\n// index just past a top-level `export default`, or -1\nconst findExportDefault = (src: string): number => {\n let i = 0\n let depth = 0\n let atStatementStart = true\n while (i < src.length) {\n const ch = src[i]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { i = skipString(src, i); atStatementStart = false; continue }\n if (ch === \"/\" && src[i + 1] === \"/\") { i = skipLineComment(src, i); continue }\n if (ch === \"/\" && src[i + 1] === \"*\") { i = skipBlockComment(src, i); continue }\n if (ch === \"/\" && regexAllowed(src, i)) { i = skipRegex(src, i); atStatementStart = false; continue }\n\n if (ch === \"e\" && depth === 0 && atStatementStart && (i === 0 || !/[\\w$.]/.test(src[i - 1]))) {\n EXPORT_DEFAULT_RE.lastIndex = i\n const found = EXPORT_DEFAULT_RE.exec(src)\n if (found) return i + found[0].length\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n i++\n }\n return -1\n}\n\nconst ASYNC_RE = /^async(?![\\w$])/\nconst FUNCTION_RE = /^function(?![\\w$])\\s*\\*?\\s*[A-Za-z_$][\\w$]*|^function(?![\\w$])\\s*\\*?/\n\n// source text of the exported function's first parameter, or null when there\n// is no parameter list to read (`export default Factory`, `export default\n// props => ...`, an exported object) - all of which declare nothing\nconst firstParameterSource = (src: string): string | null => {\n const start = findExportDefault(src)\n if (start === -1) return null\n\n let i = skipToToken(src, start)\n const rest = src.slice(i)\n if (ASYNC_RE.test(rest)) i = skipToToken(src, i + \"async\".length)\n const fn = FUNCTION_RE.exec(src.slice(i))\n if (fn) i = skipToToken(src, i + fn[0].length)\n if (src[i] !== \"(\") return null\n\n // the parameter list runs to the `)` that closes this `(`\n let depth = 0\n let end = i\n while (end < src.length) {\n const ch = src[end]\n if (ch === \"'\" || ch === '\"' || ch === \"`\") { end = skipString(src, end); continue }\n if (ch === \"/\" && src[end + 1] === \"/\") { end = skipLineComment(src, end); continue }\n if (ch === \"/\" && src[end + 1] === \"*\") { end = skipBlockComment(src, end); continue }\n if (ch === \"/\" && regexAllowed(src, end)) { end = skipRegex(src, end); continue }\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch) && --depth === 0) break\n end++\n }\n return splitTopLevel(src.slice(i + 1, end))[0] ?? \"\"\n}\n\n// the props declared by a factory script's first parameter. Throws the\n// migration error when it finds the pre-0.4 signature there - the ctx used to\n// be the first parameter, and the change is silent otherwise ($data would just\n// come back undefined). `$` is what tells them apart: what carries one comes\n// from the library, what doesn't comes from the parent, everywhere in jq79\nexport const parseFactoryProps = (src: string): PropDecl[] | null => {\n const first = firstParameterSource(src)\n if (first === null) return null\n const props = parsePropsPattern(first)\n const ctxName = props?.find(prop => prop.name.startsWith(\"$\"))?.name\n if (ctxName) {\n throw new Error(\n `jq79: the factory signature is (props, ctx), so \\`${ctxName}\\` can't be destructured from the first parameter. ` +\n `Write \\`export default (props, { ${ctxName} }) => …\\`, or \\`_\\` in place of props if the component takes none.`\n )\n }\n return props\n}\n\n// rewrites a factory script into a Function body, or returns null when the\n// script has no top-level `export default` (i.e. it's a regular setup script)\nexport const transformFactoryScript = (src: string): string | null => {\n let out = \"\"\n let i = 0\n let depth = 0\n let atStatementStart = true\n let isFactory = false\n let modCount = 0\n\n while (i < src.length) {\n const ch = src[i]\n const next = src[i + 1]\n const atWordBoundary = i === 0 || !/[\\w$.]/.test(src[i - 1])\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n const end = skipString(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n if (ch === \"/\" && (next === \"/\" || next === \"*\")) {\n const end = next === \"/\" ? skipLineComment(src, i) : skipBlockComment(src, i)\n out += src.slice(i, end)\n i = end\n continue\n }\n if (ch === \"/\" && regexAllowed(src, i)) {\n const end = skipRegex(src, i)\n out += src.slice(i, end)\n i = end\n atStatementStart = false\n continue\n }\n\n if (ch === \"i\" && atWordBoundary) {\n // dynamic import() -> $__import, same rewrite as setup scripts\n IMPORT_CALL_RE.lastIndex = i\n if (IMPORT_CALL_RE.test(src)) {\n out += \"$__import\"\n i += \"import\".length\n atStatementStart = false\n continue\n }\n if (depth === 0 && atStatementStart) {\n STATIC_IMPORT_RE.lastIndex = i\n const staticImport = STATIC_IMPORT_RE.exec(src)\n if (staticImport) {\n out += staticImportToAwait(staticImport[1], staticImport[3], modCount++)\n i += staticImport[0].length\n atStatementStart = false\n continue\n }\n }\n }\n\n if (ch === \"e\" && atWordBoundary && depth === 0 && atStatementStart) {\n EXPORT_DEFAULT_RE.lastIndex = i\n const exportDefault = EXPORT_DEFAULT_RE.exec(src)\n if (exportDefault) {\n isFactory = true\n out += \"$__exports.default =\"\n i += exportDefault[0].length\n atStatementStart = false\n continue\n }\n }\n\n if (\"([{\".includes(ch)) depth++\n else if (\")]}\".includes(ch)) depth = Math.max(0, depth - 1)\n\n if (ch === \"\\n\" || ch === \";\" || ch === \"}\") atStatementStart = true\n else if (!/\\s/.test(ch)) atStatementStart = false\n\n out += ch\n i++\n }\n\n return isFactory ? out : null\n}\n\n"],"mappings":"qjBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,OAAAE,G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AAK,MAAMA,GAAaA,EAAU,QAAQ,CAAC,CACpD,CACF,EAIO,IAAMoZ,GAAkBC,GAAmC,IAAIC,EAAYD,CAAS,EAKrFE,GAAqC,CAAE,EAAAC,GAAG,GAAAC,GAAI,QAAAC,GAAS,UAAAC,GAAW,OAAAC,EAAQ,YAAAN,CAAY,EAOxF,OAAO,WAAe,KAAgB,WAAmBO,EAAQ,GAAGC,GAAgB","names":["jq79_exports","__export","$","$$","$create","$reactive","$toRaw","Component79","PendingComponent79","enableHotReload","hotUpdate","parseComponent","renderComponent","__toCommonJS","$","selectorOrEl","selector","$$","$create","tag","attrs","el","name","value","child","ALLOWED_TAGS","ALLOWED_ATTR","SAFE_URL_PROTOCOLS","isSafeUrl","url","DEFAULT_PORTS","compileHostPattern","pattern","match","host","port","labels","label","allowedHosts","patterns","compiled","p","consultAllowUrl","allowUrl","attr","MAX_SANITIZE_DEPTH","appendSanitizedChildren","source","target","depth","sanitizedChild","sanitizeNode","node","clean","allowedForTag","allowedGlobal","sanitizeHTML","html","options","template","container","getByPath","obj","dotKey","acc","key","isPlainData","value","proto","walkLeaves","path","visit","KEYS_SEGMENT","keysPath","createTrieNode","parent","segment","isEmptyNode","node","RAW","$toRaw","raw","STORE","isStore","trackerStack","untracked","fn","effectsCreated","NO_DEPS","ATTACH","ALSO_WAKEN_BY","$reactive","data","exactListeners","anyListeners","effects","proxies","storeApi","depTrie","insertDep","dep","effect","children","child","removeDep","current","nodeAt","effectsFor","matched","sweep","from","pending","next","segments","depth","bridges","indexable","deps","redundant","dot","kept","indexEffect","soleDep","soleNode","indexed","lastTracked","placed","place","unplaceStale","unplaceAll","sync","tracked","unchanged","wakeExactly","runMatched","notifyKeys","ordered","sorted","i","a","b","notify","isNewKey","listener","replaceable","previous","keyCount","container","GIVE_UP","whatChanged","before","after","span","changed","index","keys","notifyReplaced","notified","collectExact","isWrappable","wrap","lengthKey","bridge","store","unbridge","cached","tombstones","proxy","target","receiver","stored","had","deleted","reactive","$on","immediate","$onAny","$effect","run","deep","alsoWakenBy","running","dirty","cycles","stopIndexing","forget","attachAndRun","detach","drop","$__attach","$dispose","unsubscribe","createEffectScope","scope","disposers","runs","dispose","DECLARATION_START_RE","REACTIVE_LABEL_RE","IMPORT_CALL_RE","REACTIVE_ASSIGN_RE","skipString","src","start","quote","i","skipLineComment","end","skipBlockComment","skipToToken","REGEX_AFTER_WORD","regexAllowed","at","ch","open","skipRegex","inClass","CONTINUATION_RE","lastMeaningfulBefore","findStatementEnd","depth","next","splitDeclarators","parts","lastEnd","flush","patternBindings","pattern","IDENTIFIER_RE","names","part","splitTopLevel","patternCloseIndex","assign","defaultAssignIndex","colon","indexOfTopLevel","rewriteDeclarators","vars","rewritten","raw","codeEnd","lead","body","tail","target","isPattern","code","transformSetupScript","out","atStatementStart","decl","label","EXPORT_DEFAULT_RE","STATIC_IMPORT_RE","splitImportClause","clause","staticImportToAwait","spec","source","bindings","ref","tmp","c","from","parsePropsPattern","close","props","named","fallback","name","local","findExportDefault","found","ASYNC_RE","FUNCTION_RE","firstParameterSource","rest","fn","parseFactoryProps","first","ctxName","prop","transformFactoryScript","isFactory","modCount","atWordBoundary","staticImport","exportDefault","VERSION","elementAttrs","el","attr","elementToAST","attrs","component","COMPONENT_TAG_ATTR","node","text","compiled","compileExpr","expr","params","key","fn","MISSING_NAME_RE","MAX_PENDING_REPORTS","pendingReports","reportedExprErrors","pendingScripts","flushScheduled","reportedFailedExprs","flushExprReports","name","scope","scheduleExprReportFlush","trackScript","settled","release","reportFailedExpr","error","message","reportExprError","match","runExpr","extras","evalExpr","evalHandler","interpolate","template","_","CONTROL_ATTRS","isControlAttr","EACH_PATTERN","bindEvent","modifiers","mods","event","handler","wireTagEvent","instance","listener","untracked","kebabToCamel","c","camelToKebab","boundsOf","removeRange","first","last","next","removeRuns","runs","run","range","contiguousRuns","ordered","isDead","entry","moveRangeAfter","prev","ref","scanComponentKey","tag","normalized","obj","tagMemo","memoBase","openRenderPass","base","outer","closeRenderPass","findComponentKey","componentsInScope","names","unresolvedComponent","MAX_NESTING_DEPTH","nestingDepth","SLOTS","isSlotTag","slotName","suffix","slotAttrOf","slotAttrName","isMeaningful","partitionSlots","contents","loose","child","hasLoose","bindSlotProps","binder","props","parsePropsPattern","as","fallback","local","value","misplacedSlotContent","buildSlots","slots","content","makeSlotRenderer","parentScope","slotScope","fx","shadow","inherited","ALSO_WAKEN_BY","contentFx","createEffectScope","renderNodes","renderSlot","wrapper","anchor","endAnchor","render","SCOPE_ATTR","renderNestedComponent","models","events","sources","hasSpread","modelAttr","modelProp","assignment","unassignable","prop","resolveProps","out","current","currentDef","childFx","reported","reportUnresolved","UNFILLED_PROPS","nextDef","Component79","warned","rawName","declared","declaredPropSet","warnUndeclared","seed","pickDeclared","holder","syncFx","written","nextKeys","createWithScope","source","target","classNames","on","normalizeAllowUrl","policy","url","allowedHosts","BOOLEAN_ATTRS","applyAttr","boolean","renderNode","outerScope","withExpr","componentKey","PENDING_SCRIPTS","mayUpgrade","upgraded","replacement","bindExpr","boundKeys","bound","classExpr","classToggles","staticClasses","textExpr","htmlExpr","allowedExpr","options","sanitizeHTML","valueExpr","renderConditional","branches","activeBranch","branchFx","branch","rendered","defineScopeVar","isPlainObject","proto","mentionsAny","identifierIn","IDENTIFIER_CHAR","at","before","after","renderEach","itemName","atName","listExpr","keyExpr","_each","_key","itemAttrs","itemNode","positionalNames","readsPosition","entries","warnedDuplicates","pass","list","pairs","item","index","previous","bucket","seen","moved","nextEntries","itemScope","existing","itemFx","dead","prevNode","nodes","into","fragment","textNode","nextBranch","candidate","elseif","elseNode","renderComponent","data","VOID_ELEMENTS","SELF_CLOSING_RE","RAW_BLOCK_RE","expandSelfClosingTags","src","chunk","i","OPEN_TAG_RE","ATTR_SPREAD_RE","expandPropsSpread","_match","n","rewritten","whole","space","ATTR_NAME_RE","CLOSE_SLOT_RE","SLOT_TAG_RE","kebabTagName","COMPONENT_TAG_RE","TRAILING_SLASH_RE","stampComponentTag","stamp","slash","expandNameCase","scopeHash","hash","stampScope","scopeSelector","selectorText","part","selector","pseudoAt","pseudoElement","scopeRules","rules","rule","scopeCss","css","sheet","COMPONENT_NAME_RE","parseComponentString","prepared","root","own","declarations","parts","componentPartsFrom","siblings","elements","hashSource","scripts","styles","block","style","isScoped","importResource","fetchComponent","RESOLVABLE_SPECIFIER_RE","resolveSpecifier","spec","filename","sourceUrlComment","headStyle","styleRegistry","acquireStyle","releaseStyle","runSetupScript","code","effect","instanceHelpers","importer","helpers","SETUP_HELPERS","scriptScope","state","result","declareProps","store","setupSignature","script","pattern","warnUnreadableSignature","signatureWarned","declaredPropNames","parseFactoryProps","undeclaredWarned","said","siblingsInScope","inScope","any","interopDefault","mod","runFactoryScript","$__exports","logError","invoked","merging","invoke","factory","merge","bindings","returned","HOT_FLAG","HOT_RUNTIME","hotRegistry","hotRegister","refs","hotKey","hotUpdate","orphaned","partsFor","rerendered","enableHotReload","STUCK_RENDER_DELAY","warnIfStuck","gates","timer","response","__publicField","sibling","marker","live","parent","PendingComponent79","urls","eventName","siblingScope","raw","unfilled","$reactive","warnedModelUpdate","$emit","payload","resolveMounted","mounted","resolve","endMarker","$$self","found","$self","modules","$import","injected","args","defer","allSync","resolveGate","open","deferred","factoryCode","transformFactoryScript","body","vars","transformSetupScript","pending","settle","templateScope","receiver","$","nextNode","action","onfulfilled","onrejected","onfinally","parseComponent","component","Component79","SETUP_HELPERS","$","$$","$create","$reactive","$toRaw","HOT_FLAG","enableHotReload"]}