@wcstack/state 4.0.0-rc.7 → 4.0.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.ja.md +29 -34
  2. package/README.md +29 -34
  3. package/dist/auto.min.js +2 -1
  4. package/dist/auto.min.js.map +1 -0
  5. package/dist/index.esm.js +2 -1
  6. package/dist/index.esm.js.map +1 -0
  7. package/dist/split/auto.js +2 -1
  8. package/dist/split/auto.js.map +1 -0
  9. package/dist/split/chunks/{chunk-V34ZHCK5.js → chunk-4NJBYXIT.js} +2 -1
  10. package/dist/split/chunks/chunk-4NJBYXIT.js.map +1 -0
  11. package/dist/split/chunks/{chunk-JMPQHCIT.js → chunk-55J45X6H.js} +2 -1
  12. package/dist/split/chunks/chunk-55J45X6H.js.map +1 -0
  13. package/dist/split/chunks/{chunk-LTBR3OV5.js → chunk-7AYOQHZH.js} +2 -1
  14. package/dist/split/chunks/chunk-7AYOQHZH.js.map +1 -0
  15. package/dist/split/chunks/chunk-EIMTT5I3.js +2 -0
  16. package/dist/split/chunks/chunk-EIMTT5I3.js.map +1 -0
  17. package/dist/split/chunks/chunk-L3PFEJP7.js +2 -0
  18. package/dist/split/chunks/chunk-L3PFEJP7.js.map +1 -0
  19. package/dist/split/chunks/{chunk-W5KT4PQ3.js → chunk-M5SODAAE.js} +2 -1
  20. package/dist/split/chunks/chunk-M5SODAAE.js.map +1 -0
  21. package/dist/split/chunks/{chunk-SPWZUBQS.js → chunk-NOPTR2L3.js} +2 -1
  22. package/dist/split/chunks/chunk-NOPTR2L3.js.map +1 -0
  23. package/dist/split/chunks/chunk-SAUVGHSB.js +2 -0
  24. package/dist/split/chunks/chunk-SAUVGHSB.js.map +1 -0
  25. package/dist/split/chunks/{chunk-ARPZVNKL.js → chunk-UD3AYVP2.js} +2 -1
  26. package/dist/split/chunks/chunk-UD3AYVP2.js.map +1 -0
  27. package/dist/split/chunks/{chunk-XF6V6DWR.js → chunk-W4KOY6GT.js} +2 -1
  28. package/dist/split/chunks/chunk-W4KOY6GT.js.map +1 -0
  29. package/dist/split/chunks/{chunk-2EGTC36Y.js → chunk-ZN52NEIB.js} +2 -1
  30. package/dist/split/chunks/chunk-ZN52NEIB.js.map +1 -0
  31. package/dist/split/core.js +2 -1
  32. package/dist/split/core.js.map +1 -0
  33. package/dist/split/features/devtools.js +2 -1
  34. package/dist/split/features/devtools.js.map +1 -0
  35. package/dist/split/features/diagnostics.js +2 -1
  36. package/dist/split/features/diagnostics.js.map +1 -0
  37. package/dist/split/features/formats.js +2 -1
  38. package/dist/split/features/formats.js.map +1 -0
  39. package/dist/split/features/list-keys.js +2 -1
  40. package/dist/split/features/list-keys.js.map +1 -0
  41. package/dist/split/features/native-commands.js +2 -1
  42. package/dist/split/features/native-commands.js.map +1 -0
  43. package/dist/split/features/recursion.js +2 -1
  44. package/dist/split/features/recursion.js.map +1 -0
  45. package/dist/split/features/scopes.js +2 -1
  46. package/dist/split/features/scopes.js.map +1 -0
  47. package/dist/split/features/ssr.js +2 -1
  48. package/dist/split/features/ssr.js.map +1 -0
  49. package/dist/split/features/temporal.js +2 -1
  50. package/dist/split/features/temporal.js.map +1 -0
  51. package/package.json +1 -1
  52. package/dist/split/chunks/chunk-27N3IPIZ.js +0 -1
  53. package/dist/split/chunks/chunk-7EWPQMA6.js +0 -1
  54. package/dist/split/chunks/chunk-ALVA5TQM.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"names":["slots","WeakMap","waiting","ORPHAN","wired","WeakSet","grafted","REJECTED","NOT_RUN","PREFIX","path","config","tagNames","state","PATH_APIS","Set","live","e","element","isConnected","failed","root","w","get","Array","isArray","rootEngineCreated","engine","list","delete","v","graft","release","held","fail","message","console","error","settle","callLifecycle","name","fn","r","call","chroot","then","has","target","segs","split","at","s","hydrated","prefix","key","Proxy","_t","charCodeAt","proxy","keyPath","rest","set","value","chrootOf","data","defs","seen","o","Object","prototype","getPrototypeOf","getOwnPropertyNames","add","getOwnPropertyDescriptor","next","bind","i","length","p","pattern","slice","join","readData","write","registerAccessors","defineProperties","changed","push","el","orphan","giveUp","claimVolume","getAttribute","problem","every","test","validPath","hasAttribute","bindAttributeName","Map","other","filter","x","lenient","start","warn","Promise","resolve","engines","connected","disconnected","reset","raiseError","instances","byEngine","names","n","claimDcc","host","content","document","createDocumentFragment","childNodes","appendChild","cloneNode","mode","tag","includes","customElements","all","out","streams","$stream","keys","members","bindables","commands","d","def","states","pending","ensure","shadow","attachShadow","querySelector","inner","ready","initializePromise","queued","k","Dcc","HTMLElement","this","wcBindable","protocol","version","properties","map","event","getter","inputs","async","connectedCallback","stateElement","defineProperty","configurable","args","apply","q","define","localName","hostBindings","readonlyWiring","before","WIRED","hosts","mounts","index","registered","active","UNWIRED","INERT","headOf","fill","idx","String","hostBinding","b","ro","node","head","documentElement","removeAttribute","wiredInMarkup","heads","setAttribute","prop","values","componentScope","text","RegExp","replace","wireLate","scope","parentElement","E","getRootNode","bound","mountSubtree","warned","warnOnce","own","h","surface","findDescriptor","mountKey","m","whole","H","entries","find","parent","info","synth","C","component","hp","from","row","depth","indexesOf","rowAt","ctx","rr","readUntracked","setter","across","skip","slot","slotCount","mountUnder","outer","through","alive","was","reaches","reached","register","on","byP","byRow","size","exports","answer","exporting","exportAccessors","strategy","invalidate","schedule","cp","last","warnShadowed","exporter","found","tree","read","touch","old","direct","item","arr","resetRow","children","l","sync","syncListsUnder","hooks","written","refresh","forAllRows","lists","into","cpath","some","startsWith","rp","crow","crossed","hr","up","g","exportReached","isUnder","built","loading","loadFeatures","$recursion","current","attr","binds","nodeType","matches","kept","top","parentNode","range","anchor","headAt","nextSibling","bs","rootBindings","chain","br","branches","rootLists","view","extra","nodes","added","mustache","textContent","takesOver","reconnect","resume","Engine","DirtyStrategy","methods","f","_self","Reflect","bindMethods","independent","declared","base","onPatternCreated","made","patterns","drain","inPlace","wire","adopted","adoptScope","mount","drainBinds","watchRendered","enumerable","$stateReadyCallback","callHook","broken","claimComponent","connectedCallbackPromise","catch","watchRoot","ShadowRoot","Element","mine","load","light","a","registryOf","whenDefined","wiring","marked","wiredOnServer","stop","j","onRootFailed","Error","finally","original","queueMicrotask","star","indexOf","unregister","ds","getOwnPropertyDescriptors","frozen","isFrozen","writable","create","melt","reject","scopes","install","claim","first","taken","phase","rootMoved","dccEngineCreated","exact","dispatchEvent","CustomEvent","detail","bubbles","dccWritten","getterReached","beforeWrite","handled","_row","_value","guardAncestorWrite","guardReadonlyMount","declare","hasMounts","scopes_default"],"sources":["../../../src/scopes/volume.ts","../../../src/scopes/dcc.ts","../../../src/scopes/component.ts","../../../src/features/scopes.ts"],"sourcesContent":["/**\n * Volumes — `<wcs-state mount=\"p\">` (README \"Mounting Additional State\"). A volume is not a\n * root: its state is grafted onto the root tree at `p` by ordinary writes, its getters and\n * setters become root accessors at `p.<key>`, its methods live at `p.<method>`, and inside all\n * of them — and in its `$connectedCallback` / `$disconnectedCallback` — `this` is chrooted at\n * `p` (`this.x` is the tree's `p.x`). Load order does not matter: a volume that loads before its\n * root grafts when the root engine is created, before the page is bound; if the root fails to\n * initialize, its volumes report it and settle. A root hydrated from a server snapshot (SSR)\n * already holds the volume's data at `p`: the volume adopts it (3.x D14). A volume in a component\n * wired to its host (`data-wcs=\"state…\"`) is refused, whenever it loads (3.x left it pending).\n *\n * Not carried over from @wcstack/state 3.3 (approved simplifications, each an error rather than\n * a silent no-op): injections on the volume element (`data-wcs=\"state.k: …\"`), and a volume's\n * own `$watch` / `$listKeys` / `$renderedCallback` — declare them on the root.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport type { WcsState } from \"../element\";\nimport { config } from \"../config\";\nimport { engines } from \"../dom/mount\";\nimport { raiseError } from \"../parser/raiseError\";\n\nexport interface Volume {\n readonly el: HTMLElement;\n readonly root: Node;\n readonly path: string;\n state: Record<string, any> | null;\n engine: Engine | null;\n chroot: object | null;\n /** Settles the element's connectedCallbackPromise. */\n settle: (() => void) | null;\n}\n\n/** Mount paths held on each root (reserved when a volume connects, kept once grafted). */\nconst slots = new WeakMap<Node, Map<string, Volume>>();\n/**\n * Loaded volumes waiting for their root's engine; an element: the root's `<wcs-state>` that failed\n * to initialize (what loads later fails with it while it is in the page: failed()).\n */\nconst waiting = new WeakMap<Node, Volume[] | Element>();\nconst ORPHAN = \"will not graft: the root state failed to initialize.\";\n/** The engines of components wired to their host: they read the host's tree, a volume has none to graft onto. */\nexport const wired = new WeakSet<Engine>();\n/** The volumes grafted onto each engine. */\nexport const grafted = new WeakMap<Engine, Volume[]>();\n\nconst REJECTED = [\"$stream\", \"$streams\", \"$scan\", \"$recursion\", \"$watch\", \"$listKeys\", \"$renderedCallback\", \"$updatedCallback\", \"$behavior\", \"$features\"];\nconst NOT_RUN = [\"$commandTokens\", \"$eventTokens\", \"$on\", \"$errorCallback\"];\nconst PREFIX = (path: string) => `[@wcstack/state] <${config.tagNames.state} mount=\"${path}\">`;\n\n/** `$` APIs that take a state path: inside a volume the path is relative to the mount. */\nconst PATH_APIS = new Set([\"$getAll\", \"$setAll\", \"$resolve\", \"$postUpdate\", \"$dependOn\", \"$eq\", \"$eqIndex\"]);\n\nfunction chrootOf(engine: Engine, prefix: string): object {\n const at = (key: string) => `${prefix}.${key}`;\n return new Proxy({}, {\n get(_t, key) {\n if (typeof key === \"symbol\") return undefined;\n if (key.charCodeAt(0) !== 36) return engine.proxy[at(key)];\n const v = engine.proxy[key];\n if (key === \"$eqPath\") return (path: string, keyPath: string) => v(at(path), at(keyPath));\n return PATH_APIS.has(key) && typeof v === \"function\" ? (path: string, ...rest: unknown[]) => v(at(path), ...rest) : v;\n },\n set(_t, key, value) {\n if (typeof key === \"symbol\") return false;\n engine.proxy[at(key as string)] = value;\n return true;\n },\n });\n}\n\nfunction validPath(path: string): boolean {\n return path !== \"\" && path.split(\".\").every((s) => s !== \"\" && !/[*$#@\\s]/.test(s));\n}\n\n/**\n * An engine whose `<wcs-state>` is in the page: nothing grafts onto one that is out (a root out of the\n * page lets go of its root node; a component whose `<wcs-state>` alone left stays registered).\n */\nconst live = (e: Engine | undefined): Engine | undefined => ((e?.element as Node | undefined)?.isConnected ? e : undefined);\n\n/** The root `<wcs-state>` on `root` failed to initialize, and is still in the page. */\nfunction failed(root: Node): boolean {\n const w = waiting.get(root);\n return w !== undefined && !Array.isArray(w) && w.isConnected;\n}\n\n/** The engine created on `root`: graft the volumes that were waiting for it (before its page is bound). */\nexport function rootEngineCreated(engine: Engine, root: Node): void {\n const list = waiting.get(root);\n waiting.delete(root);\n if (Array.isArray(list)) for (const v of list) graft(v, engine);\n}\n\nfunction release(v: Volume): void {\n const held = slots.get(v.root);\n if (held?.get(v.path) === v) held.delete(v.path);\n}\n\n/**\n * A root engine's `<wcs-state>` left the page (\"disconnected\"), or is back (\"back\"; a component's:\n * \"connected\"). Out, the mount paths its volumes hold let go of it (they are kept on the root node,\n * which outlives the content it bound). Back, and still its root's engine (the core holds the root\n * again unless another `<wcs-state>` bound it meanwhile), the volumes that connected meanwhile graft,\n * and its own hold their paths again — unless another volume took one meanwhile.\n */\nexport function rootMoved(engine: Engine, phase: string): void {\n const list = grafted.get(engine) ?? [];\n if (phase === \"disconnected\") for (const v of list) release(v);\n else if (phase !== \"reset\" && live(engines.get(engine.root!)) === engine) {\n rootEngineCreated(engine, engine.root!);\n for (const v of list) if (!slots.get(v.root)!.has(v.path)) slots.get(v.root)!.set(v.path, v);\n }\n}\n\n/** Reports a volume that will not graft, releases its slot and settles its promise. */\nfunction fail(v: Volume, message: string): void {\n console.error(`${PREFIX(v.path)} ${message}`);\n release(v);\n v.settle?.();\n v.settle = null;\n}\n\nfunction callLifecycle(v: Volume, name: \"$connectedCallback\" | \"$disconnectedCallback\"): void {\n const fn = v.state?.[name];\n if (typeof fn !== \"function\") return;\n try {\n const r = fn.call(v.chroot);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, (e: unknown) => console.error(e));\n } catch (e) {\n console.error(e);\n }\n}\n\nfunction graft(v: Volume, engine: Engine): void {\n if (wired.has(engine)) return fail(v, \"will not graft: its component is wired to its host.\");\n const state = v.state!;\n const target = engine.target;\n const segs = v.path.split(\".\");\n let at: any = target;\n for (const s of segs) at = at == null ? undefined : at[s];\n // a root hydrated from a server snapshot (ssr/ssr.ts) has the volume's data there already: adopted\n if (at !== undefined && (engine as any).hydrated !== true) return fail(v, `will not graft: the root state already has \"${v.path}\".`);\n const chroot = chrootOf(engine, v.path);\n v.chroot = chroot;\n // the data; accessors and methods (bound to the chroot) apart, as root accessors at `p.<key>`,\n // so that whatever replaces the data (the snapshot, a write of the mount path) keeps them\n const data: Record<string, unknown> = {};\n const defs: PropertyDescriptorMap = {};\n const seen = new Set<string>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (seen.has(key) || key === \"constructor\") continue;\n seen.add(key);\n const { get, set, value } = Object.getOwnPropertyDescriptor(o, key)!;\n if (get !== undefined || set !== undefined) {\n defs[`${v.path}.${key}`] = {\n get: get && function () { return get.call(chroot); },\n set: set && function (next: unknown) { set.call(chroot, next); },\n };\n } else if (key[0] === \"$\") continue;\n else if (typeof value === \"function\") {\n const fn = value.bind(chroot);\n defs[`${v.path}.${key}`] = { get: () => fn };\n } else data[key] = value;\n }\n }\n if (at === undefined) {\n // intermediate objects of a deep mount path, then the volume's own object\n for (let i = 1; i < segs.length; i++) {\n const p = engine.pattern(segs.slice(0, i).join(\".\"));\n if (engine.readData(p, null) == null) engine.write(p, null, {});\n }\n engine.write(engine.pattern(v.path), null, data);\n }\n // registered as the root's own are (a row-level getter gets its cache slot; the paths under\n // them read through them)\n (engine as any).registerAccessors(Object.defineProperties({}, defs));\n for (const path in defs) engine.changed(engine.pattern(path), null);\n v.engine = engine;\n let list = grafted.get(engine);\n if (list === undefined) grafted.set(engine, (list = []));\n list.push(v);\n if (v.el.isConnected) callLifecycle(v, \"$connectedCallback\");\n v.settle?.();\n v.settle = null;\n}\n\n/**\n * A root `<wcs-state>` (the one no claim took; asked by the last, claimComponent): if it fails to\n * initialize, the volumes waiting on `root` settle instead of waiting forever, and so do the ones\n * that load later — and the components waiting there for their wiring (onRootFailed).\n */\nexport function watchRoot(el: HTMLElement, root: Node): null {\n (el as WcsState).connectedCallbackPromise.catch(() => {\n // a root that bound the page (only its $connectedCallback failed), or a stray second one (#47)\n // beside the root that binds it: nothing failed for what waits there\n const live = engines.get(root)?.element as Element | undefined;\n if ((el as WcsState).bound || (live !== undefined && live !== el && live.isConnected)) return;\n orphan(root, el);\n for (const f of giveUp.get(root) ?? []) f();\n });\n return null;\n}\n\n/**\n * The state of `root` failed to initialize (`el`: the page's root, or a component's in its shadow\n * root): the volumes waiting there report it and settle, and so do those that load later while\n * `el` is in the page.\n */\nexport function orphan(root: Node, el: Element): void {\n const list = waiting.get(root);\n if (Array.isArray(list)) for (const v of list) fail(v, ORPHAN);\n waiting.set(root, el);\n}\n\n/** What else waits on a root node's `<wcs-state>` (a component, for the page's wiring). */\nconst giveUp = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Calls `fn` when (or if) the root `<wcs-state>` on `root` fails to initialize; the function\n * returned stops waiting (what `fn` holds is not kept for as long as the page lives).\n */\nexport function onRootFailed(root: Node, fn: () => void): () => boolean {\n if (failed(root)) fn();\n const s = giveUp.get(root) ?? new Set();\n giveUp.set(root, s.add(fn));\n return () => s.delete(fn);\n}\n\n/** `<wcs-state mount=\"p\">`: claimed instead of becoming a root. */\nexport function claimVolume(el: HTMLElement, root: Node): Claimed | null {\n const path = el.getAttribute(\"mount\");\n if (path === null) return null;\n const v: Volume = { el, root, path, state: null, engine: null, chroot: null, settle: null };\n let problem: string | null = null;\n if (!validPath(path)) problem = `has an invalid mount path: it must be a static path (no \"*\", \"$\", \"#\", \"@\").`;\n else if (el.hasAttribute(config.bindAttributeName)) problem = `injections (data-wcs=\"state.<key>: …\") are not supported — read the root path in a root getter.`;\n else {\n let held = slots.get(root);\n if (held === undefined) slots.set(root, (held = new Map()));\n const other = held.get(path);\n // one grafted onto a root that left the page holds it no more, nor does one waiting for its root\n // out of the page (the page's content replaced): that one yields, and never grafts. (One out of\n // the page that no other volume asks for still grafts when its root comes.)\n if (other !== undefined && other !== v && (other.engine === null ? other.el.isConnected : live(other.engine))) {\n problem = `will not graft: another volume already holds \"${path}\".`;\n } else {\n if (other?.engine === null) {\n const list = waiting.get(root);\n if (Array.isArray(list)) waiting.set(root, list.filter((x) => x !== other));\n other.settle?.();\n other.settle = null;\n }\n held.set(path, v);\n }\n }\n return {\n // a volume that cannot load resolves its connectedCallbackPromise (3.x; it reports, as below)\n lenient: true,\n start(state): Promise<void> | void {\n if (problem !== null) return fail(v, problem);\n // (it yielded its slot while it loaded: see above)\n if (slots.get(root)!.get(path) !== v) return;\n for (const key of REJECTED) if (state[key] !== undefined) return fail(v, `${key} is not run in a volume — declare it on the root state.`);\n for (const key of NOT_RUN) if (state[key] !== undefined) console.warn(`${PREFIX(path)} ${key} is not run in a volume (it belongs to the root).`);\n v.state = state;\n return new Promise<void>((resolve) => {\n v.settle = resolve;\n const engine = live(engines.get(root));\n const list = waiting.get(root);\n if (engine !== undefined) graft(v, engine);\n else if (failed(root)) fail(v, ORPHAN);\n else waiting.set(root, [...(Array.isArray(list) ? list : []), v]);\n });\n },\n connected() {\n if (v.engine !== null) callLifecycle(v, \"$connectedCallback\");\n },\n disconnected() {\n // a grafted volume keeps its data and its slot (there is no unmount)\n if (v.engine !== null) callLifecycle(v, \"$disconnectedCallback\");\n },\n reset() {\n raiseError(`re-setting a volume is not supported: its data was copied into the root tree at \"${path}\" — write the paths under it on the root instead.`);\n },\n };\n}\n\n/** A root write that would replace an object a volume is grafted under. */\nexport function guardAncestorWrite(engine: Engine, p: Pattern): void {\n const list = grafted.get(engine);\n if (list === undefined || p.depth !== 0) return;\n for (const { path } of list) {\n if (path.startsWith(`${p.path}.`)) raiseError(`writing \"${p.path}\" would replace the volume grafted at \"${path}\"; write the paths under it instead.`);\n }\n}\n","/**\n * Declarative Custom Components (README \"DCC\"). The `<wcs-state>` inside the shadow root of a\n * `[data-wc-definition]` host is not a root: it defines the host's tag. Each instance gets a\n * copy of the definition's (untouched) shadow content, whose own `<wcs-state>` is an ordinary\n * root with a fresh state. The class's prototype reads and writes that state (writes before it\n * initializes wait for it; methods return Promises); `$bindables` / `$commands` become its\n * `static wcBindable`, and a write to a bindable (or under it, or a `$postUpdate`) dispatches\n * `<tag>:<prop>-changed` from the instance — a notification: `detail` carries the written value\n * only for a write of the member itself, and the declared getter reads the member off the element.\n *\n * The shadow is built on first use — an accessor or the connect, whichever comes first — not in\n * the constructor: a `for` row binds its elements before they are inserted, a parser-made\n * instance has no attributes in its constructor, and the definition host itself (upgraded by\n * define()) already has its shadow.\n */\nimport type { Engine } from \"../engine\";\nimport type { Pattern } from \"../pattern\";\nimport type { Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { raiseError } from \"../parser/raiseError\";\n\ninterface Definition {\n readonly tag: string;\n readonly bindables: readonly string[];\n}\n\n/** DCC instances by host element, and the definition of each instance's inner engine. */\nconst instances = new WeakMap<Element, Definition>();\nconst byEngine = new WeakMap<Engine, { host: Element; def: Definition }>();\n\nfunction names(state: Record<string, any>, key: string): string[] {\n const v = state[key];\n if (v === undefined) return [];\n if (!Array.isArray(v)) raiseError(`${key} must be an array of state member names.`);\n const seen = new Set<string>();\n for (const n of v) {\n if (typeof n !== \"string\" || n === \"\") raiseError(`${key} entries must be non-empty strings.`);\n if (n[0] === \"$\") raiseError(`${key} entry \"${n}\": internal ($) members are never exposed.`);\n if (seen.has(n)) raiseError(`${key} entry \"${n}\" is duplicated.`);\n seen.add(n);\n }\n return v;\n}\n\n/** Every member of the state (own and inherited), by descriptor. */\nfunction members(state: Record<string, any>): Map<string, PropertyDescriptor> {\n const out = new Map<string, PropertyDescriptor>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const key of Object.getOwnPropertyNames(o)) {\n if (key === \"constructor\" || key[0] === \"$\" || out.has(key)) continue;\n out.set(key, Object.getOwnPropertyDescriptor(o, key)!);\n }\n }\n const streams = state.$stream;\n if (streams !== null && typeof streams === \"object\") for (const n of Object.keys(streams)) if (!out.has(n)) out.set(n, { value: undefined });\n return out;\n}\n\nfunction define(tag: string, content: DocumentFragment, mode: ShadowRootMode, state: Record<string, any>): void {\n if (!tag.includes(\"-\")) raiseError(`DCC: <${tag} data-wc-definition> is not a valid custom element name.`);\n if (customElements.get(tag) !== undefined) raiseError(`DCC: <${tag}> is already defined.`);\n const all = members(state);\n const bindables = names(state, \"$bindables\");\n const commands = names(state, \"$commands\");\n for (const n of bindables) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$bindables entry \"${n}\" does not exist on the state.`);\n if (typeof d.value === \"function\") raiseError(`$bindables entry \"${n}\" is a method: list it in $commands.`);\n }\n for (const n of commands) {\n const d = all.get(n);\n if (d === undefined) raiseError(`$commands entry \"${n}\" does not exist on the state.`);\n if (typeof d.value !== \"function\") raiseError(`$commands entry \"${n}\" is not a method: list it in $bindables.`);\n }\n const def: Definition = { tag, bindables };\n /** Each instance's inner `<wcs-state>` (null: a definition host, or content without one). */\n const states = new WeakMap<Element, any>();\n const pending = new WeakMap<Element, [string, unknown][]>();\n /** Builds the instance's shadow once; its inner `<wcs-state>`. */\n const ensure = (el: Element): any => {\n if (states.has(el)) return states.get(el);\n if (el.hasAttribute(\"data-wc-definition\")) return null;\n const shadow = el.attachShadow({ mode });\n shadow.appendChild(content.cloneNode(true));\n const state = shadow.querySelector(config.tagNames.state);\n states.set(el, state);\n instances.set(el, def);\n if (state === null && bindables.length > 0) {\n console.warn(`[@wcstack/state] DCC: <${tag}> declares $bindables but its content has no <${config.tagNames.state}>: no change events.`);\n }\n return state;\n };\n /** The instance's inner engine once its state initialized, else null. */\n const inner = (el: Element): any => ensure(el)?.engine ?? null;\n /** Resolves when the instance's state initialized, before its `$connectedCallback` (and lands the writes queued before). */\n const ready = (el: Element): Promise<void> => Promise.resolve(ensure(el)?.initializePromise).then(() => {\n const queued = pending.get(el);\n pending.delete(el);\n const engine = inner(el);\n if (queued !== undefined && engine !== null) for (const [k, v] of queued) engine.proxy[k] = v;\n });\n\n class Dcc extends HTMLElement {\n static wcBindable = bindables.length === 0 && commands.length === 0 ? null : {\n protocol: \"wc-bindable\", version: 1,\n properties: bindables.map((name) => ({ name, event: `${tag}:${name}-changed`, getter: (e: Event) => (e.target as any)[name] })),\n inputs: bindables.map((name) => ({ name })),\n ...(commands.length === 0 ? {} : { commands: commands.map((name) => ({ name, async: true })) }),\n };\n\n connectedCallback(): void {\n if (ensure(this) !== null) void ready(this);\n }\n\n /** The inner `<wcs-state>` (as in 3.3; builds the shadow if it is not built yet). */\n get stateElement(): HTMLElement | null {\n return ensure(this);\n }\n }\n for (const [name, d] of all) {\n if (typeof d.value === \"function\") {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n value(this: Element, ...args: unknown[]) {\n return ready(this).then(() => {\n const engine = inner(this);\n return engine === null ? undefined : engine.proxy[name].apply(engine.proxy, args);\n });\n },\n });\n } else {\n Object.defineProperty(Dcc.prototype, name, {\n configurable: true,\n get(this: Element) { return inner(this)?.proxy[name]; },\n set(this: Element, value: unknown) {\n const engine = inner(this);\n if (engine !== null) engine.proxy[name] = value;\n else {\n let q = pending.get(this);\n if (q === undefined) pending.set(this, (q = []));\n q.push([name, value]);\n }\n },\n });\n }\n }\n customElements.define(tag, Dcc);\n}\n\n/** The `<wcs-state>` of a definition host: claimed to define the tag. */\nexport function claimDcc(el: HTMLElement, root: Node): Claimed | null {\n const host = (root as ShadowRoot).host;\n if (host === undefined || !host.hasAttribute(\"data-wc-definition\")) return null;\n // the definition's content, before anything touches it: every instance starts from this\n const content = document.createDocumentFragment();\n for (const n of [...root.childNodes]) content.appendChild(n.cloneNode(true));\n const mode = (root as ShadowRoot).mode;\n return {\n start(state) {\n if (el.hasAttribute(\"bind-component\")) raiseError(\"DCC: a <wcs-state bind-component> cannot define a component (use one mechanism).\");\n define(host.localName, content, mode, state);\n },\n connected() {},\n disconnected() {},\n reset() {\n raiseError(\"re-setting a DCC definition is not supported: each instance loads its own state.\");\n },\n };\n}\n\n/** A root engine was created: an instance's inner state gets its host's change events. */\nexport function dccEngineCreated(engine: Engine, root: Node): void {\n const host = (root as ShadowRoot).host;\n const def = host === undefined ? undefined : instances.get(host);\n if (def !== undefined) byEngine.set(engine, { host, def });\n}\n\n/**\n * A write at a bindable, under it, or its `$postUpdate`: `<tag>:<prop>-changed` from the\n * instance, with the written value as `detail` only for a data write of the member itself.\n */\nexport function dccWritten(engine: Engine, p: Pattern, value: unknown, direct: boolean): void {\n const info = byEngine.get(engine);\n if (info === undefined) return;\n const name = p.path.split(\".\", 1)[0];\n if (!info.def.bindables.includes(name)) return;\n const exact = direct && p.path === name;\n info.host.dispatchEvent(new CustomEvent(`${info.def.tag}:${name}-changed`, { detail: exact ? value : undefined, bubbles: true }));\n}\n","/**\n * Component mounts — `<wcs-state bind-component=\"prop\">` directly inside a custom element\n * (README \"Web Component Binding\"). Each component runs an engine of its own over its state\n * object (the host element's `prop`): its bindings, rows, `$1`, event indexes, getters and\n * private keys are the component's. The host wires it with ordinary property bindings on the\n * element (`state: user`, `state.x: path`, `state: .` in a row); those are taken over as\n * mount entries, and the component reads and writes the mounted keys through the host's\n * engine. Changes cross both ways through the `written` / `getterReached` hooks: the host's\n * reach the components mounted on them, and a component's writes under a mounted key reach\n * the host (and, from there, the other components mounted on the same data).\n *\n * Own keys stay private (rule R1): a key the component declares itself is its own, except a\n * one-segment partial entry, which wins over a data default. Unwired, a Shadow DOM component\n * owns an independent tree; a Light DOM one cannot (it shares the page) and fails loudly.\n *\n * `#ro` on an entry (`state#ro: user`) is honoured as in 3.3: a component's code writing through it\n * throws `[wcs/mount-readonly]`, an element's write-back inside the component is dropped.\n *\n * A whole mount's accessors are exported at the mount point (README \"Exported getters\"): the host\n * reads `user.display` (row by row for `state: .`) from the component mounted there, unless the\n * tree has the key.\n * A mounted component runs no temporal declaration and no `$renderedCallback`, and refuses `$recursion`.\n */\nimport { Engine, rowAt } from \"../engine\";\nimport { WILDCARD, type Pattern } from \"../pattern\";\nimport type { StateRow } from \"../list\";\nimport type { Binding } from \"../dom/view\";\nimport { hooks, loadFeatures, type Claimed } from \"../hooks\";\nimport { config } from \"../config\";\nimport { DirtyStrategy } from \"../strategy/dirty\";\nimport { engines, mount, mountSubtree } from \"../dom/mount\";\nimport { bind, drainBinds } from \"../dom/binder\";\nimport { registryOf } from \"../dom/wc\";\nimport { raiseError } from \"../parser/raiseError\";\nimport type { WcsState } from \"../element\";\nimport { onRootFailed, orphan, rootEngineCreated, watchRoot, wired } from \"./volume\";\n\ninterface Entry {\n /** The component-side path (\"\" = the whole state). */\n readonly inner: string;\n /** The host pattern and row (at the pattern's depth) it is mounted on. */\n readonly outer: Pattern;\n readonly row: StateRow | null;\n /** Mounted `#ro`: the component reads it and does not write it. */\n readonly ro: boolean;\n}\n\n/** What a host element keeps across the `<wcs-state>` elements its renders create. */\ninterface Host {\n readonly el: Element;\n readonly prop: string;\n /** The author's state object: the component's private data lives here. */\n readonly state: Record<string, any>;\n /** The host's engine (null: an unwired, independent component). */\n readonly engine: Engine | null;\n readonly entries: Entry[];\n current: Mount | null;\n}\n\ninterface Synth {\n readonly e: Entry;\n readonly p: Pattern;\n readonly row: StateRow | null;\n}\n\ninterface Mount {\n /** Its `<wcs-state>`: a new one that takes the scope over replaces it (resume). */\n el: HTMLElement;\n /** The nodes of the scope root once it was bound: still there, a new `<wcs-state>` takes the scope over. */\n nodes: ChildNode[];\n readonly component: Engine;\n readonly host: Host;\n readonly slots: { m: Mount; e: Entry }[];\n /** Component patterns that read and write the host. */\n readonly synth: Map<Pattern, Synth>;\n registered: boolean;\n /** A mounted key its setter just wrote through the host (its `written` is not forwarded again). */\n skip: Pattern | null;\n /** The entry a change of the component is crossing to the host through: its other entries still take it. */\n from: Entry | null;\n /** Exported accessors (a whole mount's): host pattern (`user.display`) → the component's accessor pattern. */\n exports: Map<Pattern, Pattern> | null;\n /**\n * It failed before its bindings were built (a markup error): what it bound before the error follows\n * the host while it is connected, as a root's does (#384), and no lifecycle hook runs — its\n * `$connectedCallback` never did.\n */\n broken?: boolean;\n}\n\ntype Slot = Mount[\"slots\"][number];\n\n/** Plain property bindings hosts made on custom elements: the candidates for wiring. */\nconst hostBindings = new WeakMap<Element, Binding[]>();\n/** Those of them written with `#ro`. */\nconst readonlyWiring = new WeakSet<Binding>();\n/** An element property's value before a host's first write to it (a mount takes the component's). */\nconst before = new WeakMap<Element, Map<string, unknown>>();\n/** Components waiting for their host to bind the wiring written in its markup. */\nconst waiting = new WeakMap<Element, () => void>();\n/**\n * SSR: a row is a clone of its plan, so the server's output carries no `data-wcs` on a row's\n * elements. A host binding made while rendering on the server writes the heads it binds here\n * instead, so a component whose class is defined before the client adopts the row still waits\n * for its wiring (as it does for `data-wcs`); the client's host binding removes it.\n */\nconst WIRED = \"data-wcs-wired\";\nconst onServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\nconst hosts = new WeakMap<Element, Host>();\nconst mounts = new WeakMap<Engine, Mount>();\n/** Mount entries by host engine, host pattern and host row. */\nconst index = new WeakMap<Engine, Map<Pattern, Map<StateRow | null, Set<Slot>>>>();\nlet registered = 0;\n/** Engines a change is crossing from: it does not come back to them. */\nconst active = new Set<Engine>();\n\nconst UNWIRED = {};\n/** Declarations a mounted component does not run (`$listKeys` runs: it keys the component's own lists). */\nconst INERT = [\"$watch\", \"$stream\", \"$renderedCallback\"];\n\nconst headOf = (path: string): string => path.split(\".\", 1)[0];\n\n/** `a.*.b.*` with [2, 5] → `a.2.b.5`. */\nfunction fill(path: string, idx: number[]): string {\n let i = 0;\n return path.split(\".\").map((s) => (s === WILDCARD ? String(idx[i++]) : s)).join(\".\");\n}\n\n/** The core's hook: a plain property binding on a custom element (before it applies). */\nexport function hostBinding(b: Binding, ro: boolean): boolean {\n const el = b.node as Element;\n const head = headOf(b.name);\n if (!onServer()) el.removeAttribute(WIRED);\n else if (!wiredInMarkup(el, head)) {\n const heads = el.getAttribute(WIRED)?.split(\" \") ?? [];\n if (!heads.includes(head)) el.setAttribute(WIRED, [...heads, head].join(\" \"));\n }\n // the component took its wiring when it loaded: a mount is not re-wired\n if (hosts.get(el)?.prop === head) {\n raiseError(`<${el.localName}>.${head} has loaded its state: the wiring \"${b.name}\" added afterwards cannot reach it — bind the host's wiring before the component loads.`);\n }\n let list = hostBindings.get(el);\n if (list === undefined) hostBindings.set(el, (list = []));\n list.push(b);\n if (ro) readonlyWiring.add(b);\n let values = before.get(el);\n if (values === undefined) before.set(el, (values = new Map()));\n if (!values.has(head)) values.set(head, (el as any)[head]);\n waiting.get(el)?.();\n return false;\n}\n\n/** The core's hook: a Light DOM component's content is bound by its own engine. */\nexport function componentScope(el: Element): boolean {\n return el.localName.includes(\"-\") && el.querySelector(`:scope > ${config.tagNames.state}[bind-component]`) !== null;\n}\n\nfunction wiredInMarkup(host: Element, prop: string): boolean {\n const text = host.getAttribute(config.bindAttributeName);\n return text !== null && new RegExp(`(^|;)\\\\s*${prop.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\s*[.#:]`).test(text);\n}\n\n/**\n * A host whose wiring is in its markup, and which the page did not bind: it was out of the page when\n * the page's state loaded, or was inserted since — by code, not by a `for:` / `if:` (which binds it\n * before inserting it) or the router (which hands it over). Its `<wcs-state>` hands it over as the\n * router does (src/dom/binder.ts): it is bound now, or once its root's state is in the page (it has not\n * loaded yet, or its `<wcs-state>` is out). In a Light DOM component, that component's engine binds it,\n * when it mounts (now, if it has). A host the page did bind is left alone (an element is walked once),\n * and so is one whose root failed before binding the page (onRootFailed refuses the component).\n */\nfunction wireLate(host: Element): void {\n let scope = host.parentElement;\n while (scope !== null && !componentScope(scope)) scope = scope.parentElement;\n const E = engines.get(scope ?? host.getRootNode());\n const el = E?.element as WcsState | undefined;\n // (the binder binds to the page's engine now, or keeps the host for when it is in the page)\n if (el?.isConnected ? el.bound : scope === null) {\n if (scope === null) bind(host);\n else mountSubtree(E!, host);\n }\n}\n\n/** The server's output says the host binds `prop` on this row element (see WIRED). */\nconst wiredOnServer = (host: Element, prop: string): boolean => host.getAttribute(WIRED)?.split(\" \").includes(prop) === true;\n\n/** A frozen author object is copied into a writable one (same prototype). */\nfunction melt(o: Record<string, any>): Record<string, any> {\n const ds = Object.getOwnPropertyDescriptors(o);\n let frozen = Object.isFrozen(o);\n for (const d of Object.values(ds)) if (\"value\" in d && d.writable === false) { d.writable = true; frozen = true; }\n return frozen ? Object.create(Object.getPrototypeOf(o), ds) : o;\n}\n\nasync function load(el: HTMLElement, prop: string, host: Element, light: boolean): Promise<Record<string, any>> {\n const tag = host.localName;\n if ([\"state\", \"src\", \"json\"].some((a) => el.hasAttribute(a)) || el.querySelector('script[type=\"module\"]') !== null) {\n raiseError(`<${config.tagNames.state} bind-component> takes its state from <${tag}>.${prop}: it cannot also load one (state / src / json / an inline script).`);\n }\n await registryOf(host).whenDefined(tag);\n let h = hosts.get(host);\n if (h !== undefined) {\n if (h.prop !== prop) raiseError(`<${tag}> already has a <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n return h.state;\n }\n const wiring = () => (hostBindings.get(host) ?? []).filter((b) => headOf(b.name) === prop);\n // the host binds its wiring when it renders the element (a row before inserting it; the page\n // when its state loads; a server-rendered row when the client adopts it), or when the\n // element's class is defined — or, written in its markup on a host the page did not bind, now\n const marked = wiredInMarkup(host, prop);\n if (marked && wiring().length === 0) wireLate(host);\n if (wiring().length === 0 && (marked || wiredOnServer(host, prop))) {\n // (if the page's state fails, its wiring never comes)\n let stop!: () => boolean;\n await new Promise<void>((r, j) => {\n waiting.set(host, r);\n stop = onRootFailed(host.getRootNode(), () => j(new Error(`[@wcstack/state] <${tag}>.${prop} will not mount: the root state failed to initialize.`)));\n }).finally(() => stop());\n }\n waiting.delete(host);\n const bs = wiring();\n const values = before.get(host);\n const original = values !== undefined && values.has(prop) ? values.get(prop) : (host as any)[prop];\n if (original === null || typeof original !== \"object\") {\n raiseError(`\"bind-component\": <${tag}>.${prop} must be an object (the component's state), got ${original === null ? \"null\" : typeof original}.`);\n }\n if (bs.length === 0 && light) {\n // reported as an uncaught error, after this element settles (as 3.3 does)\n const error = new Error(`[@wcstack/state] A plain (unwired) Light DOM \"bind-component\" is not supported. Attach a shadow root to <${tag}>, or mount it from the host (${config.bindAttributeName}=\"${prop}: path\").`);\n queueMicrotask(() => { throw error; });\n return UNWIRED;\n }\n const entries: Entry[] = [];\n for (const b of bs) {\n const inner = b.name === prop ? \"\" : b.name.slice(prop.length + 1);\n if (entries.some((e) => e.inner === inner)) raiseError(`<${tag}> maps \"${b.name}\" twice.`);\n const star = inner.split(\".\").indexOf(WILDCARD);\n if (star >= 0) {\n const list = inner.split(\".\").slice(0, star).join(\".\");\n raiseError(`<${tag}> maps \"${b.name}\": the component-side path of a mount cannot contain \"*\"${list === \"\" ? \"\" : ` — map the list itself (\"${prop}.${list}: <the host's list>\")`}.`);\n }\n entries.push({ inner, outer: b.pattern, row: b.row, ro: readonlyWiring.has(b) });\n // the component reads the host from now on: the binding no longer writes the element\n b.engine.unregister(b);\n if (inner !== \"\") delete (host as any)[b.name];\n }\n const state = bs.length === 0 ? melt(original as Record<string, any>) : original as Record<string, any>;\n hosts.set(host, (h = { el: host, prop, state, engine: bs.length === 0 ? null : bs[0].engine, entries, current: null }));\n return state;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n console.warn(`[@wcstack/state] ${message}`);\n}\n\n/** Whether `key` is the component's own (a data default, an accessor or a method of its state). */\nconst own = (h: Host, key: string): boolean => key in h.state;\n\n/** The component's own surface for `key`: an accessor or a method (a data default is not). */\nfunction surface(h: Host, key: string): boolean {\n const d = findDescriptor(h.state, key);\n return d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\");\n}\n\n/**\n * The component's patterns that read and write the host: a partial entry's path, and under a\n * whole mount every top-level key the component does not declare itself.\n */\nfunction wire(m: Mount): void {\n const C = m.component;\n const h = m.host;\n const H = h.engine!;\n const tag = h.el.localName;\n const whole = h.entries.find((e) => e.inner === \"\") ?? null;\n for (const e of h.entries) {\n if (e.inner === \"\") continue;\n const head = headOf(e.inner);\n // a one-segment entry wins over a data default; the component's own surface (an accessor,\n // a method) and an own key above a deep entry win over the entry\n if (own(h, head) && (e.inner !== head || surface(h, head))) {\n warnOnce(`${tag}.${e.inner}`, `[wcs/mount-own-key-shadow] <${tag}>: \"${h.prop}.${e.inner}\" is hidden by the component's own \"${head}\"; rename one side.`);\n }\n }\n if (whole !== null) {\n const at = H.readUntracked(whole.outer, whole.row);\n if (at !== null && typeof at === \"object\") {\n for (const key of Object.keys(h.state)) {\n if (key[0] !== \"$\" && key in at && !h.entries.some((e) => e.inner === key)) {\n warnOnce(`${tag}.${key}`, `[wcs/mount-own-key-shadow] <${tag}>: its own \"${key}\" hides \"${whole.outer.path}.${key}\" — remove the default to read the tree, or rename it to keep it private.`);\n }\n }\n }\n }\n const declared = INERT.filter((k) => h.state[k] !== undefined);\n if (declared.length > 0) {\n warnOnce(`${tag}.${h.prop}$`, `[wcs/mount-dollar-declaration] <${tag}>: ${declared.join(\", \")} ${declared.length === 1 ? \"is\" : \"are\"} not run in a mounted component — declare it on the root state.`);\n }\n const base = (C as any).onPatternCreated;\n (C as any).onPatternCreated = (p: Pattern) => {\n mountKey(m, whole, p);\n base.call(C, p);\n };\n // patterns the engine made before (the parents of the component's own accessors): mounted\n // keys among them, then what now reads through them. A snapshot: both loops walk it (a pattern\n // made during the first goes through the wrapped onPatternCreated above).\n const made = [...C.patterns.all()];\n for (const p of made) mountKey(m, whole, p);\n for (const p of made) base.call(C, p);\n // a mount in a host row goes with the row (4.0 discards a removed row's element): it renders no\n // more — what it would read of the row throws (live), its own keys stay readable and writable.\n // So does a mount inside a component that went with its row: it reads the tree through that one.\n const drain = C.drain;\n C.drain = () => {\n if (inPlace(m)) drain.call(C);\n };\n}\n\n/** Every host row a mount reads through is still there: its own, and those of the components it is in. */\nfunction inPlace(m: Mount | undefined): boolean {\n for (; m !== undefined; m = mounts.get(m.host.engine!)) {\n if (m.host.entries.some((e) => e.row !== null && !e.row.alive)) return false;\n }\n return true;\n}\n\n/**\n * `element.state` is the component's proxy, handed out as an object: a function the state declares\n * (a method, or a function-valued key it starts with) read off it always runs on it, whatever `this`\n * it is called with — detached (`const { toggle } = element.state`), as a listener\n * (`button.addEventListener(\"click\", element.state.toggle)`), by a timer — as 3.x's `bind` did\n * (#331; an explicit `call(other)` is ignored, as with `bind`). It is wrapped once per function, in a\n * proxy that keeps the function's properties, statics, `new`, `name` and identity across reads; a\n * function a key comes to hold later, the tree's or its own, is returned as it is. Only reads through\n * the proxy itself are wrapped, not through a view of it (`createStateAsync(\"readonly\")`, whose\n * methods must run on the read-only view). A root's proxy is only lent to a callback, and a volume's\n * methods are bound to its chroot already.\n */\nfunction bindMethods(C: Engine, state: object): void {\n const methods = new Map<unknown, unknown>();\n for (let o: object | null = state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n const v = Object.getOwnPropertyDescriptor(o, k)!.value;\n if (typeof v === \"function\" && k !== \"constructor\") methods.set(v, null);\n }\n }\n const apply = (f: (...a: unknown[]) => unknown, _self: unknown, args: unknown[]): unknown => Reflect.apply(f, C.proxy, args);\n C.bound = (fn) => {\n let b = methods.get(fn);\n if (b === null) methods.set(fn, (b = new Proxy(fn, { apply })));\n return b;\n };\n}\n\nfunction findDescriptor(o: object, key: string): PropertyDescriptor | undefined {\n for (let x: object | null = o; x !== null && x !== Object.prototype; x = Object.getPrototypeOf(x)) {\n const d = Object.getOwnPropertyDescriptor(x, key);\n if (d !== undefined) return d;\n }\n return undefined;\n}\n\nfunction mountKey(m: Mount, whole: Entry | null, p: Pattern): void {\n if (p.getter !== null) return;\n const h = m.host;\n const H = h.engine!;\n const head = headOf(p.path);\n let e = h.entries.find((x) => x.inner === p.path);\n if (e === undefined && p.parent !== null) return mountUnder(m, p);\n if (p.depth !== 0) return;\n let target: Pattern;\n if (e !== undefined) {\n if (e.inner !== head ? own(h, head) : surface(h, head)) return;\n target = e.outer;\n } else if (whole !== null && p.parent === null && head[0] !== \"$\" && !own(h, head)) {\n e = whole;\n target = H.pattern(`${whole.outer.path}.${head}`);\n } else {\n return;\n }\n const row = e.row;\n const through = e;\n p.getter = () => H.readUntracked(target, live(m, row));\n p.setter = (value: unknown) => {\n across(m, through, () => H.write(target, row, value));\n m.skip = p;\n };\n m.synth.set(p, { e, p: target, row });\n}\n\n/**\n * The host row an entry is mounted on, for reading or writing through it. A removed row is gone\n * for good (4.0 never puts a removed row's element in another row): nothing of it is the\n * component's any more, and the position it had may hold another row now (3.4 #367 / #368).\n */\nfunction live(m: Mount, row: StateRow | null): StateRow | null {\n if (row !== null && !row.alive) raiseError(`The host row of <${m.host.el.localName}> was removed.`);\n return row;\n}\n\n/** Runs a change of component `m` crossing to its host through entry `e`. */\nfunction across(m: Mount, e: Entry, fn: () => void): void {\n const was = active.has(m.component);\n active.add(m.component);\n m.from = e;\n try {\n fn();\n } finally {\n if (!was) active.delete(m.component);\n m.from = null;\n }\n}\n\n/** Whether a change crossing from the component's own entry `from` (or from its host) reaches `slot`. */\nconst reaches = (slot: Slot, reached: boolean): boolean =>\n reached || !active.has(slot.m.component) || (slot.m.from !== null && slot.m.from !== slot.e);\n\n/**\n * A path under a mounted key whose host counterpart is a getter (a host getter, a recursive\n * family): read — and written, if it has a setter — through the host, row by row.\n */\nfunction mountUnder(m: Mount, p: Pattern): void {\n let s: Pattern | null = p.parent;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return;\n const C = m.component;\n const H = m.host.engine!;\n const hp = H.pattern(info.p.path + p.path.slice(s.path.length));\n if (hp.getter === null) return;\n const from = info;\n /**\n * The host row of `hp`: the entry's own row (not the row now at its position), and under it the\n * component's rows (a component path with a `*` of its own).\n */\n const at = (): StateRow | null => {\n const r = live(m, from.row);\n if (p.depth === 0) return r;\n H.resolve(fill(hp.path, [...H.indexesOf(r), ...C.indexesOf(rowAt(C.ctx, p.depth))]), null);\n return (H as any).rr as StateRow | null;\n };\n p.getter = () => {\n const r = at();\n return hp.depth > 0 && r === null ? undefined : H.readUntracked(hp, r);\n };\n if (hp.setter !== null) {\n p.setter = (value: unknown) => {\n const r = at();\n across(m, from.e, () => H.write(hp, r, value));\n m.skip = p;\n };\n }\n if (p.depth > 0) p.slot = (C as any).slotCount++;\n m.synth.set(p, { e: from.e, p: hp, row: from.row });\n}\n\nfunction register(m: Mount, on: boolean): void {\n if (m.registered === on || m.host.engine === null) return;\n m.registered = on;\n registered += on ? 1 : -1;\n const H = m.host.engine;\n let byP = index.get(H);\n if (byP === undefined) index.set(H, (byP = new Map()));\n for (const slot of m.slots) {\n let byRow = byP.get(slot.e.outer);\n if (byRow === undefined) byP.set(slot.e.outer, (byRow = new Map()));\n let set = byRow.get(slot.e.row);\n if (set === undefined) byRow.set(slot.e.row, (set = new Set()));\n if (on) set.add(slot);\n else {\n set.delete(slot);\n if (set.size === 0) byRow.delete(slot.e.row);\n }\n }\n const whole = m.host.entries.find((e) => e.inner === \"\");\n if (whole === undefined) return;\n if (m.exports === null) exportAccessors(m, whole);\n // the host's readers of the exported paths: the component answers them now (a re-set of the\n // host while it was away forgot the answer), or no longer\n for (const hp of m.exports!.keys()) {\n if (on && hp.getter === null) answer(H, hp, whole.outer);\n H.strategy.invalidate(H, hp, whole.row);\n }\n if (m.exports!.size > 0) H.schedule();\n if (on) warnShadowed(m, whole);\n}\n\n// ---------------------------------------------------------------- exported accessors\n\n/** The getters `answer` gave host patterns (a re-set of the host forgets them with its accessors). */\nconst exporting = new WeakSet<object>();\n\n/**\n * README \"Exported getters\": a whole mount's accessors (getters and setters, not methods or\n * private data, no `*` in the name) are read at the mount point. The host's own accessor there\n * wins; a key the tree has wins (`wcs/mount-export-shadowed`).\n */\nfunction exportAccessors(m: Mount, whole: Entry): void {\n const h = m.host;\n const H = h.engine!;\n m.exports = new Map();\n const seen = new Set<string>();\n for (let o: object | null = h.state; o !== null && o !== Object.prototype; o = Object.getPrototypeOf(o)) {\n for (const k of Object.getOwnPropertyNames(o)) {\n if (seen.has(k)) continue;\n seen.add(k);\n const d = Object.getOwnPropertyDescriptor(o, k)!;\n if ((d.get === undefined && d.set === undefined) || k[0] === \"$\" || k.includes(WILDCARD)) continue;\n // a dotted accessor exports only from the component's own data (`form.label`), not the tree's\n const head = headOf(k);\n if (k !== head && !own(h, head)) continue;\n const hp = H.pattern(`${whole.outer.path}.${k}`);\n // the host's own accessor there wins\n if (hp.getter === null) answer(H, hp, whole.outer);\n else if (!exporting.has(hp.getter)) continue;\n m.exports.set(hp, m.component.pattern(k));\n }\n }\n}\n\n/** The mount that exports `hp` at host row `row` (the row at the mount point's depth). */\nfunction exporter(H: Engine, outer: Pattern, row: StateRow | null, hp: Pattern): Mount | null {\n const set = index.get(H)?.get(outer)?.get(row);\n if (set === undefined) return null;\n let found: Mount | null = null;\n for (const slot of set) {\n if (slot.e.inner !== \"\" || slot.m.exports?.has(hp) !== true || slot.m === found) continue;\n if (found !== null) {\n raiseError(`[wcs/mount-export-ambiguous] \"${hp.path}\" is exported by two mounted components on the same instance: <${found.host.el.localName}> and <${slot.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`);\n }\n found = slot.m;\n }\n return found;\n}\n\n/** Makes host pattern `hp` read (and write) the accessor of the component mounted at `outer`, row by row. */\nfunction answer(H: Engine, hp: Pattern, outer: Pattern): void {\n const parent = hp.parent!;\n const last = hp.last;\n /** The tree's object that has the key, or null. */\n const tree = (): any => {\n const o = H.read(parent, H.ctx) as any;\n return o !== null && typeof o === \"object\" && last in o ? o : null;\n };\n hp.getter = () => {\n const o = tree();\n if (o !== null) return o[last];\n const m = exporter(H, outer, H.ctx, hp);\n return m === null ? undefined : m.component.read(m.exports!.get(hp)!, null);\n };\n exporting.add(hp.getter);\n hp.setter = (value: unknown) => {\n const o = tree();\n const m = o === null ? exporter(H, outer, H.ctx, hp) : null;\n if (m === null) {\n // no component answers it here: the tree's own key\n const at = H.read(parent, H.ctx) as any;\n if (at !== null && typeof at === \"object\") at[last] = value;\n return;\n }\n const cp = m.exports!.get(hp)!;\n if (findDescriptor(m.host.state, cp.path)?.set === undefined) {\n raiseError(`Cannot write to \"${cp.path}\" on mounted <${m.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`);\n }\n m.component.write(cp, null, value);\n };\n if (hp.depth > 0) hp.slot = H.slotCount++;\n}\n\nfunction warnShadowed(m: Mount, whole: Entry): void {\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n const o = H.readUntracked(hp.parent!, whole.row) as any;\n if (o === null || typeof o !== \"object\" || !(hp.last in o)) continue;\n const tag = m.host.el.localName;\n warnOnce(`${tag}|${hp.path}`, `[wcs/mount-export-shadowed] <${tag}>.${m.host.prop}.${cp.path} is exported at \"${hp.path}\" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`);\n }\n}\n\n/** A component's exported accessor was reached (it may now differ): so are the host's readers of it. */\nfunction exportReached(m: Mount, g: Pattern): void {\n const whole = m.host.entries.find((e) => e.inner === \"\")!;\n const H = m.host.engine!;\n for (const [hp, cp] of m.exports!) {\n if (cp !== g) continue;\n H.strategy.invalidate(H, hp, whole.row);\n H.schedule();\n }\n}\n\n/**\n * The `beforeWrite` hook: a component's write through a `#ro` entry, or through an entry whose\n * host row is gone. Code (a method, `element.state`, `$setAll` / `$resolve`) is refused; an\n * element's write-back (a two-way input in the component) is dropped, as `#ro` on that binding\n * would (@wcstack/state 3.3).\n */\nexport function guardReadonlyMount(E: Engine, p: Pattern, element: boolean): boolean {\n const m = mounts.get(E);\n if (m === undefined) return false;\n let info: Synth | undefined;\n for (let s: Pattern | null = p; s !== null && info === undefined; s = s.parent) info = m.synth.get(s);\n if (info === undefined) return false;\n const e = info.e;\n // the host's row went away (an await outlived it): the write has nowhere to land (3.3.x)\n const gone = e.row !== null && !e.row.alive;\n if (!gone && !e.ro) return false;\n if (element) return true;\n live(m, e.row);\n raiseError(`[wcs/mount-readonly] <${m.host.el.localName}> cannot write \"${p.path}\": it is mounted read-only (\"${m.host.prop}${e.inner === \"\" ? \"\" : `.${e.inner}`}#ro: ${e.outer.path}\"). Write it on the host, or drop #ro from the mount.`);\n}\n\n/** A host engine that has components mounted on it: its state cannot be re-set. */\nexport function hasMounts(engine: Engine): boolean {\n const byP = index.get(engine);\n if (byP === undefined) return false;\n for (const byRow of byP.values()) if (byRow.size > 0) return true;\n return false;\n}\n\n/**\n * Applies a change another engine made to shared data: the lists under it re-sync (an\n * element's row takes the array's new element), hooks see it, dependents update.\n */\nfunction touch(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n if (p.getter !== null) {\n E.strategy.invalidate(E, p, row);\n E.schedule();\n return;\n }\n if (p.last === WILDCARD) {\n if (row === null) return;\n row.item = (row.list.arr as unknown[])[row.index];\n E.strategy.resetRow(row);\n if (row.children !== null) for (const l of row.children.values()) E.sync(l);\n } else {\n (E as any).syncListsUnder(p, row);\n }\n hooks.written?.(E, p, row, old, value, direct);\n E.changed(p, row);\n}\n\n/** The value an entry is mounted on may have been replaced: every key read through it is stale. */\nfunction refresh(slot: Slot): void {\n const C = slot.m.component;\n for (const [p, s] of slot.m.synth) {\n if (s.e !== slot.e) continue;\n if (p.depth === 0) C.strategy.invalidate(C, p, null);\n else C.forAllRows(p.lists[p.depth]!, (r) => C.strategy.invalidate(C, p, r));\n }\n C.schedule();\n}\n\n/** A host change at or under an entry: the component's path under the mounted key. */\nfunction into(slot: Slot, q: Pattern, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n const rest = p.path.slice(q.path.length);\n if (rest === \"\") return refresh(slot);\n const m = slot.m;\n const C = m.component;\n let cpath: string;\n if (slot.e.inner === \"\") {\n cpath = rest.slice(1);\n const head = headOf(cpath);\n // the component keeps it private, or a partial entry maps it elsewhere (the longest prefix wins)\n if (head[0] === \"$\" || own(m.host, head) || m.host.entries.some((x) => x.inner !== \"\" && (cpath === x.inner || cpath.startsWith(`${x.inner}.`)))) return;\n } else {\n cpath = slot.e.inner + rest;\n }\n const idx: number[] = [];\n for (let k = q.depth + 1; k <= p.depth; k++) idx.push(rowAt(row, k)!.index);\n C.resolve(fill(cpath, idx), null);\n const cp = (C as any).rp as Pattern;\n const crow = (C as any).rr as StateRow | null;\n if (cp.depth > 0 && crow === null) return;\n touch(C, cp, crow, old, value, direct);\n}\n\n/** A component's write under a mounted key: the host's path, with the host row's indexes first. */\nfunction up(m: Mount, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean): void {\n let s: Pattern | null = p;\n let info: Synth | undefined;\n while (s !== null && (info = m.synth.get(s)) === undefined) s = s.parent;\n if (s === null || info === undefined) return; // private data\n const H = m.host.engine!;\n if (s === p && m.skip === p) {\n m.skip = null; // its setter wrote through the host\n return;\n }\n // its host row went away (a write there is refused; `$postUpdate` is not a write): the position\n // it had may hold another row now\n if (info.row !== null && !info.row.alive) return;\n const idx = [...H.indexesOf(info.row), ...m.component.indexesOf(row)];\n H.resolve(fill(info.p.path + p.path.slice(s.path.length), idx), null);\n const hp = (H as any).rp as Pattern;\n const hr = (H as any).rr as StateRow | null;\n if (hp.depth > 0 && hr === null) return;\n across(m, info.e, () => touch(H, hp, hr, old, value, direct));\n}\n\n/**\n * The `written` / `getterReached` hook: a change in engine E crosses to the host it is mounted\n * on (a write, not a getter reached) and to the components mounted on it. A write does not come\n * back to the engines it is crossing from; a getter reached does — it only invalidates, and the\n * components a write started in read the host's getters too.\n */\nexport function crossed(E: Engine, p: Pattern, row: StateRow | null, old: unknown, value: unknown, direct: boolean, reached: boolean): void {\n if (registered === 0) return;\n const was = active.has(E);\n active.add(E);\n try {\n const m = mounts.get(E);\n if (!reached && m !== undefined && m.registered && !active.has(m.host.engine!)) up(m, p, row, old, value, direct);\n if (reached && m !== undefined && m.registered && m.exports !== null) exportReached(m, p);\n const byP = index.get(E);\n if (byP === undefined) return;\n for (const [q, byRow] of byP) {\n if (p.isUnder(q)) {\n const set = byRow.get(q.depth === 0 ? null : rowAt(row, q.depth));\n if (set !== undefined) for (const slot of [...set]) if (reaches(slot, reached)) into(slot, q, p, row, old, value, direct);\n } else if (q.isUnder(p)) {\n for (const [r, set] of [...byRow]) {\n if (p.depth !== 0 && rowAt(r, p.depth) !== row) continue;\n for (const slot of [...set]) if (reaches(slot, reached)) refresh(slot);\n }\n }\n }\n } finally {\n if (!was) active.delete(E);\n }\n}\n\nasync function start(el: HTMLElement, host: Element, root: Node, state: Record<string, any>, built: () => void): Promise<void> {\n if (state === UNWIRED) return;\n // the add-ons its `$features` names, before anything reads the host's current mount\n const loading = loadFeatures(state);\n if (loading) await loading;\n const h = hosts.get(host)!;\n // a mounted engine is never \"mounting\": its `$recursion` would run half set up — refused, as in a volume\n if (h.engine && state.$recursion) {\n raiseError(`[wcs/mount-dollar-declaration] <${host.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);\n }\n const old = h.current;\n if (old !== null && old.el !== el && old.el.isConnected) {\n raiseError(`<${host.localName}> already has a connected <${config.tagNames.state} bind-component=\"${h.prop}\">.`);\n }\n if (old !== null) register(old, false);\n if (old !== null && takesOver(old, el, root)) return resume(old, el, root, built);\n const C = new Engine(state, new DirtyStrategy());\n C.element = el;\n (el as any).engine = C;\n bindMethods(C, state);\n const m: Mount = { el, nodes: [], component: C, host: h, slots: [], synth: new Map(), registered: false, skip: null, from: null, exports: null };\n for (const e of h.entries) m.slots.push({ m, e });\n h.current = m;\n mounts.set(C, m);\n const independent = h.engine === null;\n if (!independent) {\n wire(m);\n register(m, true);\n // the volumes in it are refused (graft), those that loaded first and those that load later\n wired.add(C);\n rootEngineCreated(C, root);\n } else {\n hooks.element?.(C, \"mounting\");\n }\n // a Light DOM component in a server-rendered page takes the server's nodes of its content (F33)\n const adopted = hooks.adoptScope?.(root);\n mount(C, root as ShadowRoot | Element);\n adopted?.();\n m.nodes = [...root.childNodes];\n drainBinds();\n if (independent) C.watchRendered();\n Object.defineProperty(host, h.prop, { configurable: true, enumerable: true, get: () => C.proxy });\n const ready = (host as any).$stateReadyCallback;\n if (typeof ready === \"function\") {\n try {\n const r = ready.call(host, h.prop);\n if (r !== null && typeof r === \"object\" && typeof r.then === \"function\") r.then(undefined, (e: unknown) => console.error(e));\n } catch (e) {\n console.error(e);\n }\n }\n // the bindings are built: what waits for them goes on, whatever $connectedCallback does (as a root)\n built();\n // taken out while it initialized: it hears the host, and runs `$connectedCallback`, when it is back\n if (!el.isConnected) {\n register(m, false);\n return;\n }\n await C.callHook(\"$connectedCallback\");\n if (independent && el.isConnected) hooks.element?.(C, \"connected\");\n}\n\n/**\n * Whether a new `<wcs-state bind-component>` takes the scope of the old mount `o` over (resume)\n * instead of binding its root afresh: when nodes the old engine bound or rendered are still in the\n * root (it swapped only its `<wcs-state>`). A kept `<style>`, whitespace or other nodes without\n * bindings do not count: content rendered again, its `<wcs-state>` included, is bound afresh. Nodes\n * with bindings added since next to kept bound ones (the old engine cannot take them, a new one\n * cannot take the kept ones) are reported.\n */\nfunction takesOver(o: Mount, el: Node, root: Node): boolean {\n // (a `<wcs-state>` in another root of the host finds none of the old nodes there)\n const C = o.component;\n const attr = `[${config.bindAttributeName}]`;\n const binds = (n: Node): boolean => n.nodeType === 1 && ((n as Element).matches(attr) || (n as Element).querySelector(attr) !== null);\n // the root's children the old engine binds or rendered\n const kept = new Set<Node>();\n const top = (n: Node | null): void => {\n while (n !== null && n.parentNode !== root) n = n.parentNode;\n if (n !== null) kept.add(n);\n };\n const range = (v: { headAt(n: Node): Node | null }, anchor: Node): void => {\n for (let n = v.headAt(anchor); n !== null && n !== anchor; n = n.nextSibling) top(n);\n top(anchor);\n };\n for (const bs of C.rootBindings.values()) {\n for (const b of bs) {\n if (b.chain === null) top(b.node);\n else for (const br of b.chain.branches) range(b.chain, br.anchor);\n }\n }\n for (const l of C.rootLists.values()) for (const v of [l.view, ...(l.extra ?? [])]) if (v !== null) range(v, v.anchor);\n for (const n of o.nodes) if (n.parentNode === root && binds(n)) kept.add(n);\n if (kept.size === 0) return false;\n const added = [...root.childNodes].filter((n) => n !== el && !kept.has(n) && !o.nodes.includes(n)\n && (binds(n) || (C.mustache && n.textContent!.includes(\"{{\"))));\n if (added.length > 0) {\n console.warn(`[@wcstack/state] <${o.host.el.localName}>: ${added.length} node(s) added beside the content taken over are not bound.`);\n }\n return true;\n}\n\n/**\n * A new `<wcs-state bind-component>` over the content the old one bound (a component that swapped only\n * its `<wcs-state>`): it takes the scope over, as a reconnection — the old engine's bindings, rows and\n * `{{ }}` anchors are on these nodes. Walking them again would bind nothing (an element walked once is\n * left alone) and read the text the bindings rendered as markup (3.x #417 / #419). Nodes with bindings\n * added since are not bound (takesOver reports them).\n */\nasync function resume(m: Mount, el: HTMLElement, root: Node, built: () => void): Promise<void> {\n // the old element lets go of the engine (its createState no longer reaches the scope)\n (m.el as any).engine = null;\n m.el = el;\n m.component.element = el;\n (el as any).engine = m.component;\n m.nodes = m.nodes.filter((n) => n.parentNode === root);\n // (taken out while it initialized: it hears the host when it is back, as a mount does)\n if (el.isConnected) await reconnect(m, built);\n else built();\n}\n\n/**\n * A mount connected again (or taken over, resume): it hears the host from now on, then\n * `$connectedCallback` — after `built`, for a take-over (getBindingsReady goes on as for a mount).\n */\nasync function reconnect(m: Mount, built?: () => void): Promise<void> {\n register(m, true);\n for (const slot of m.slots) refresh(slot);\n built?.();\n if (m.broken) return;\n // (async: a `$connectedCallback` that throws rejects, as one that rejects does)\n await m.component.callHook(\"$connectedCallback\");\n if (m.host.engine === null && m.el.isConnected) hooks.element?.(m.component, \"connected\");\n}\n\n/** `<wcs-state bind-component=\"prop\">`: claimed instead of becoming a root of its page. */\nexport function claimComponent(el: HTMLElement, root: Node): Claimed | null {\n const prop = el.getAttribute(\"bind-component\");\n // the last claim: a `<wcs-state>` neither a volume nor a DCC definition nor a component is a root\n if (prop === null) return watchRoot(el, root);\n const parent = el.parentNode;\n const shadow = parent instanceof ShadowRoot;\n const host = shadow ? (parent as ShadowRoot).host : parent instanceof Element ? parent : null;\n /** Its mount, from the moment it is made (`$connectedCallback` may still run, or have thrown); null once another `<wcs-state>` took it over. */\n const mine = (): Mount | null => {\n const m = host === null ? undefined : hosts.get(host)?.current;\n return m?.el === el ? m : null;\n };\n // a component that does not mount: the volumes in its shadow root have no tree to graft onto\n const failed = (e: unknown): never => {\n if (shadow) orphan(parent!, el);\n throw e;\n };\n /** Its bindings were built (it mounted, or took a scope over). */\n let bound = false;\n return {\n load() {\n return (host === null || !host.localName.includes(\"-\")\n ? Promise.reject(new Error(`[@wcstack/state] \"bind-component\" requires <${config.tagNames.state}> to be a direct child of a custom element.`))\n : load(el, prop, host, !shadow)).catch(failed);\n },\n async start(state, built) {\n await start(el, host!, shadow ? parent! : host!, state, () => {\n bound = true;\n built();\n }).catch((e) => {\n // (one whose `$connectedCallback` failed is an ordinary mount)\n const m = mine();\n if (!bound && m !== null) m.broken = true;\n return failed(e);\n });\n },\n connected() {\n // a failed `$connectedCallback` is reported as a root's on reconnect is\n const m = mine();\n if (m !== null) reconnect(m).catch((e) => console.error(e));\n // a newer `<wcs-state>` took the scope over: put back where it was, this one takes the scope over\n // again, as a new one would — once the DOM operation that put it back is done (it may take the\n // newer one out), and refused while the newer one is still in\n else if (bound) {\n void Promise.resolve().then(() => {\n if (el.parentNode === parent) return start(el, host!, shadow ? parent! : host!, hosts.get(host!)!.state, () => {});\n }).catch((e) => console.error(e));\n }\n // still waiting for its host's wiring: the host is back (wireLate)\n else if (waiting.has(host!)) wireLate(host!);\n },\n disconnected() {\n const m = mine();\n if (m === null) return;\n register(m, false);\n if (m.broken) return;\n m.component.callHook(\"$disconnectedCallback\");\n if (m.host.engine === null) hooks.element?.(m.component, \"disconnected\");\n },\n reset() {\n raiseError(`re-setting a component's state is not supported: write <${host?.localName}>.${prop} instead.`);\n },\n };\n}\n","/**\n * The scopes add-on (@wcstack/state/features/scopes): `<wcs-state>` elements that are not roots.\n * Volumes (`<wcs-state mount=\"p\">`, src/scopes/volume.ts), Declarative Custom Components\n * (`[data-wc-definition]`, src/scopes/dcc.ts) and component mounts (`<wcs-state\n * bind-component>`, src/scopes/component.ts).\n */\nimport { chain, first, handled, hooks, taken, type Feature } from \"../hooks\";\nimport { raiseError } from \"../parser/raiseError\";\nimport { claimVolume, grafted, guardAncestorWrite, rootEngineCreated, rootMoved } from \"../scopes/volume\";\nimport { claimDcc, dccEngineCreated, dccWritten } from \"../scopes/dcc\";\nimport { claimComponent, componentScope, crossed, guardReadonlyMount, hasMounts, hostBinding } from \"../scopes/component\";\n\nexport const scopes: Feature = {\n name: \"scopes\",\n install(): void {\n hooks.claim = first(taken, hooks.claim, claimVolume);\n hooks.claim = first(taken, hooks.claim, claimDcc);\n // last: what it does not take is a root, which it watches for the volumes (watchRoot)\n hooks.claim = first(taken, hooks.claim, claimComponent);\n hooks.hostBinding = hostBinding;\n hooks.componentScope = componentScope;\n hooks.element = chain(hooks.element, (engine, phase) => {\n if (phase !== \"mounting\") return rootMoved(engine, phase);\n const root = (engine.element as Node).getRootNode();\n rootEngineCreated(engine, root);\n dccEngineCreated(engine, root);\n });\n hooks.written = chain(hooks.written, (engine, p, row, old, value, direct) => {\n dccWritten(engine, p, value, direct);\n crossed(engine, p, row, old, value, direct, false);\n });\n hooks.getterReached = chain(hooks.getterReached, (engine, g, row) => crossed(engine, g, row, undefined, undefined, false, true));\n hooks.beforeWrite = first(handled, hooks.beforeWrite, (engine, p, _row, _value, element) => {\n guardAncestorWrite(engine, p);\n return guardReadonlyMount(engine, p, element);\n });\n // first, before what is installed (in any order) replaces its runtime for the new state:\n // a refused re-set leaves the old state, its watches, streams and keys as they were\n const declared = hooks.declare;\n hooks.declare = (engine, target) => {\n const list = grafted.get(engine);\n if (list !== undefined && list.length > 0) {\n raiseError(`re-setting a root state with grafted volumes (${list.map((v) => v.path).join(\", \")}) is not supported: their data is part of the tree.`);\n }\n if (hasMounts(engine)) raiseError(\"re-setting a root state with mounted components is not supported: they read its data.\");\n declared?.(engine, target);\n };\n },\n};\nexport default scopes;\n"],"mappings":"odAmCA,IAAMA,EAAQ,IAAIC,QAKZC,EAAU,IAAID,QACdE,EAAS,uDAEFC,EAAQ,IAAIC,QAEZC,EAAU,IAAIL,QAErBM,EAAW,CAAC,UAAW,WAAY,QAAS,aAAc,SAAU,YAAa,oBAAqB,mBAAoB,YAAa,aACvIC,EAAU,CAAC,iBAAkB,eAAgB,MAAO,kBACpDC,EAAUC,GAAiB,qBAAqBC,EAAOC,SAASC,gBAAgBH,MAGhFI,EAAY,IAAIC,IAAI,CAAC,UAAW,UAAW,WAAY,cAAe,YAAa,MAAO,aA4B1FC,EAAQC,GAAgDA,GAAGC,SAA8BC,YAAcF,OAAI,EAGjH,SAASG,EAAOC,GACd,IAAMC,EAAIpB,EAAQqB,IAAIF,GACtB,YAAa,IAANC,IAAoBE,MAAMC,QAAQH,IAAMA,EAAEH,WACnD,CAGO,SAASO,EAAkBC,EAAgBN,GAChD,IAAMO,EAAO1B,EAAQqB,IAAIF,GAEzB,GADAnB,EAAQ2B,OAAOR,GACXG,MAAMC,QAAQG,GAAO,QAAWE,KAAKF,EAAMG,EAAMD,EAAGH,EAC1D,CAEA,SAASK,EAAQF,GACf,IAAMG,EAAOjC,EAAMuB,IAAIO,EAAET,MACrBY,GAAMV,IAAIO,EAAEpB,KAAUoB,GAAGG,EAAKJ,OAAOC,EAAEpB,EAC7C,CAmBA,SAASwB,EAAKJ,EAAWK,GACvBC,QAAQC,MAAM,GAAG5B,EAAOqB,EAAEpB,MAASyB,KACnCH,EAAQF,GACRA,EAAEQ,OACFR,EAAEQ,GAAS,IACb,CAEA,SA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GAAMxM,IAAI4B,GACnG,QAAa,IAAT2K,EAAoB,OAAO,EAC/B,IAAM7M,EAAI6M,EAAK7M,EAGf,SADuB,OAAVA,EAAEmN,GAAiBnN,EAAEmN,EAAIe,KACxBlO,EAAE2K,QACZ1K,IACJF,GAAKwM,EAAGvM,EAAEmN,QACVpH,EAAW,yBAAyBwG,EAAElG,KAAK9B,GAAGkF,4BAA4B5F,EAAEpE,iCAAoC8M,EAAElG,KAAK8E,KAAmB,KAAZnL,EAAEgI,EAAe,GAAK,IAAIhI,EAAEgI,WAAehI,EAAEgO,GAAMvO,2DACnL,CCjkBawY,CAAmBvX,EAAQmD,EAAG5D,KAIvC,IAAM0T,EAAWxD,EAAM+H,GACvB/H,EAAM+H,GAAU,CAACxX,EAAQoB,KACvB,IAAMnB,EAAOtB,EAAQiB,IAAII,QACZ,IAATC,GAAsBA,EAAKiD,OAAS,GACtCmC,EAAW,iDAAiDpF,EAAKiI,IAAK/H,GAAMA,EAAEpB,GAAMuE,KAAK,4DD4jB1F,SAAmBtD,GACxB,IAAM8N,EAAMxE,EAAM1J,IAAII,GACtB,QAAY,IAAR8N,EAAmB,OAAO,EAC9B,QAAWC,KAASD,EAAIpD,SAAU,GAAIqD,EAAMC,KAAO,EAAG,OAAO,EAC7D,OAAO,CACT,CC/jBUyJ,CAAUzX,IAASqF,EAAW,yFAClC4N,IAAWjT,EAAQoB,GAEvB,GAEKsW,GAAQvB","ignoreList":[]}
@@ -1 +1,2 @@
1
- import{a as e}from"../chunks/chunk-27N3IPIZ.js";import{b as t,c as l}from"../chunks/chunk-ARPZVNKL.js";import"../chunks/chunk-JMPQHCIT.js";import{a as n,i as r,j as o,k as i,l as s,m as a}from"../chunks/chunk-7EWPQMA6.js";import"../chunks/chunk-XF6V6DWR.js";import"../chunks/chunk-LTBR3OV5.js";import{a as c}from"../chunks/chunk-W5KT4PQ3.js";import"../chunks/chunk-2EGTC36Y.js";import"../chunks/chunk-SPWZUBQS.js";import"../chunks/chunk-ALVA5TQM.js";import{a as u,b as f}from"../chunks/chunk-V34ZHCK5.js";var d=e=>e.split(".").slice(0,2).join("."),p=class extends t{static find(e){return e.querySelector?.(c.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return d(this.version)===d(e)}};function m(e){let t=c.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends p{})}var h=()=>c.tagNames.ssr,g=Symbol.for("wcstack.ssr.snapshotBuilder"),b=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),v=e=>document.createComment(e),y=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,w=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),N=new WeakMap,S=new WeakMap,A=new WeakMap,k=new WeakSet,x=new WeakMap;function $(e,t){let l=[];for(let n=e;null!==n&&(l.push(n),n!==t);n=n.nextSibling);return l}function T(e,t,...l){for(let l of Array.from(e.attributes))t.setAttribute(l.name,l.value);return(t.content??t).append(...l),t}var W=e=>null===e.D?e.Ue:e.D[e.D.length-1];function j(e,t,l){let n=[v(null===l?"wcs-[":`wcs-[:${l}`)];for(let e of t)null===l&&n.push(v("wcs-|")),n.push(...$(e.Ue,W(e)));n.push(v("wcs-]")),e.after(...n);for(let e of n)k.add(e)}function C(e){if(e instanceof r){j(e.S,e.Ne,null);for(let t of e.Ne)q(t);return}let t=e.O;null!==t&&(j(e.G[e.G.length-1].S,[t],e.b),q(t))}function q(e){if(null!==e.c)for(let t of e.c)C(t)}var O=new Set(["script","style","template","textarea","title"]),E="data-wcs-raw",M=e=>O.has(e.localName)||e.localName===h();function I(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(v("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(v("wcs-s")):1===t.nodeType&&!M(t)&&I(t)}var P=0;function R(t,l){let n=t.getRootNode(),r=[l];for(let e of S.get(n)??[])e!==l&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let o=new Map;for(let e of r){let t=N.get(e);if(void 0===t)continue;let l=new Map;for(let t of e.oe.values())if(null!==t.E&&l.set(t.E.S,t.E),null!==t.L)for(let e of t.L)l.set(e.S,e);for(let t of e.ce.values())for(let e of t)if(null!==e._)for(let t of e._.G)l.set(t.S,e._);let n=new Set;for(let[e,r]of t){o.set(e,r);let t=l.get(e);void 0!==t&&!n.has(t)&&e.isConnected&&(n.add(t),C(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=A.get(e);if(void 0!==t){let l=document.createTreeWalker(e,133,{acceptNode:e=>k.has(e)||1===e.nodeType&&t.has(e)&&L(e)?2:1}),n=[];for(let e=l.nextNode();null!==e;e=l.nextNode()){let l=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(M(e.parentNode)?x.has(e):t.has(l)&&w(l,"wcs-t:"))&&(x.has(e)||t.get(e)!==e.data):!t.has(e))&&n.push(e)}for(let e of n)e.remove()}let l=Array.from(e.childNodes);M(e)&&l.some(e=>x.has(e))&&e.setAttribute(E,l.map(e=>x.has(e)?`{{ ${x.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}I(9===n.nodeType?n.body:n);let i=document.createElement(h());i.setAttribute("version",e);let s=document.createElement("script");s.type="application/json",s.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let l of Object.keys(e)){if("$"===l[0])continue;let n=Object.getOwnPropertyDescriptor(e,l);void 0!==n.get||void 0!==n.set||"function"==typeof n.value||(t[l]=n.value)}return t}(l.target)),i.append(s);for(let[e,t]of o){if(!e.isConnected)continue;let l=e.parentNode;for(;null!==l&&"svg"!==l.localName&&"foreignObject"!==l.localName;)l=l.parentElement;let n="svg"===l?.localName,r=`wcs-${n?"s":"t"}${P++}`;e.replaceWith(v(`wcs-p:${r}`));let o=document.importNode(a(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(T(e,document.createElement("template"),...e.childNodes));if(n){let e=document.createElementNS(l.namespaceURI,"svg");e.append(o),o=e}let s=document.createElement("template");s.id=r,i.append(T(t,s,o))}t.before(i)}function U(e){!function(e){if(null!==e.querySelector(c.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>x.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${c.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===h())continue;let e=t.engine;null!=e&&R(t,e)}}var V=Symbol.for("wcstack.state.ssr.impl"),D=new Map,Q=new WeakMap,L=e=>!0===u.$o?.(e),G=e=>1===e.nodeType&&!M(e)&&!L(e),J=e=>e.f.flat().concat(e.q??[]),Z=e=>{for(let t of J(e))t.remove()};function B(e,t,l){let n=/^wcs-\[(?::(\d+))?/.exec(e.data),r=e.previousSibling,o=e.parentNode,i=[],a=e.nextSibling;for(e.remove();null!==a&&!y(a,"wcs-]");){let e=a.nextSibling;if(y(a,"wcs-|"))i.push([]),a.remove();else{0===i.length&&i.push([]);let l=i[i.length-1];w(a,"wcs-[")?e=B(a,t,l):(l.push(a),G(a)&&K(a,t))}a=e}let c={branch:void 0===n[1]?null:Number(n[1]),f:i,q:a??o.appendChild(v("wcs-]"))},u=J(c);a=c.q.nextSibling;for(let e of u)l?.push(e),t&&s.add(e);return t&&null!==r?D.set(r,c):Z(c),a}function K(e,t){for(let l=e.firstChild;null!==l;)w(l,"wcs-[")?l=B(l,t):(G(l)&&K(l,t),l=l.nextSibling)}function _(e,t,l){let n=e=>{for(let r of Array.from(e.childNodes))if(r.parentNode===e)if(8===r.nodeType){let e=r.data;try{if("wcs-s"===e)r.remove();else if("wcs-e"===e)r.replaceWith("");else if(e.startsWith("wcs-t:")){let t=v(`@@:${decodeURIComponent(e.slice(6))}`),l=r.nextSibling;for(;null!==l&&!y(l,"wcs-/t");){let e=l.nextSibling;l.remove(),l=e}l?.remove(),r.replaceWith(t)}else if(e.startsWith("wcs-p:")){let l=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==l){let t=r.parentNode,n="s"===e[10]?T(l,document.createElementNS(t.namespaceURI,"template"),...document.importNode(l.content.firstChild,!0).childNodes):document.importNode(l,!0);n.removeAttribute("id"),t.replaceChild(n,r)}}}catch{}}else 1===r.nodeType&&!M(r)&&(L(r)?Q.set(r,{ssr:t,Oe:l}):n(r))};n(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let l=t.previousSibling;null!==l&&(8===l.nodeType||te(l)||"template"===l.localName);l=l.previousSibling)e.unshift(l);let l=0,n=0;if(e.forEach((e,t)=>{w(e,"wcs-[")?n++:y(e,"wcs-]")&&--n<0&&(n=0,l=t+1)}),0===n)continue;let r=0;for(let n=t.firstChild;null!==n;n=n.nextSibling)if(w(n,"wcs-["))r++;else if(y(n,"wcs-]")&&0===r--){t.prepend(...e.slice(l));break}}}(e),K(e,l)}function z(e){let t=Q.get(e);if(void 0===t||(Q.delete(e),_(e,t.ssr,t.Oe),!t.Oe))return null;let l=u.Oe;return u.Oe=re,()=>{u.Oe=l,H()}}function H(){for(let e of D.values())Z(e);D.clear()}function F(e){let t=[];for(let l=document.createTreeWalker(e,128);l.nextNode();)t.push(l.currentNode);return t}function X(e,t,l,n){let r=null;for(let n of e){let e=n[l];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===r||e.length>r[l].length)&&(r=n)}let o=r?.[n];if(null==o)return null;let i=r[l],s=""===i?t:t.slice(i.length+1);return""===o?s:""===s?o:`${o}.${s}`}function Y(e,t,l){if(b()){if(l instanceof Array){for(let e=l.length;e-- >0;)o(l[e])&&l.splice(e,1);let e=t;if(l.some(i))k.add(e);else if(e.localName.includes("-")&&!L(e)){let t=new Map;for(let l=document.createTreeWalker(e,133);l.nextNode();)t.set(l.currentNode,l.currentNode.data);A.set(e,t)}return}if("string"==typeof l){if(x.set(t,l),M(t.parentNode))return;let e=v(`wcs-t:${encodeURIComponent(l)}`),n=v("wcs-/t");return t.before(e),void t.after(n)}let n=N.get(e);void 0===n&&N.set(e,n=new Map),n.set(t,l);let r=t.getRootNode(),s=S.get(r);return void 0===s&&S.set(r,s=new Set),void s.add(e)}if("string"!=typeof l&&D.size>0){let e=D.get(l);void 0!==e&&(D.delete(l),D.set(t,e))}}var ee=e=>null!==e&&8===e.nodeType&&[c.commentIfPrefix,c.commentElseIfPrefix,c.commentElsePrefix].includes(e.data),te=e=>3===e.nodeType&&""===e.data.trim(),le=e=>(D.get(e)?.q??e).nextSibling;function ne(e,t){if(t.length!==e.sn.childNodes.length)return!1;let l=e.On;for(let n=0;n<l.length;n++){let r=l[n],o=e.sn,i=t[r[0]];for(let e=0;;){if(o=o.childNodes[r[e]],i?.nodeName!==o.nodeName)return!1;if(++e===r.length)break;i=i.firstChild;for(let t=r[e];t>0&&null!==i;t--)i=le(i)}e.ko[n]=i}return!0}function re(e,t,l){if(0===D.size)return null;let n=t,r=0;if(!l){let e=c.commentIfPrefix;if(!y(t,e))for(let l=t.previousSibling;null!==l&&1!==l.nodeType&&(ee(l)&&r++,!y(l,e));l=l.previousSibling);for(let l=t.nextSibling;!D.has(n)&&null!==l&&!y(l,e)&&1!==l.nodeType;l=l.nextSibling)ee(l)&&(n=l)}let o=D.get(n);if(void 0===o)return null;if(!l&&o.branch!==r)return D.delete(n),Z(o),null;let i=o.f.shift();if(0===o.f.length&&D.delete(n),o.q?.replaceWith(...$(t,n)),o.q=null,void 0===i)return null;let s=[];for(let e=0;e<i.length;e++){let t=D.get(i[e]);if(s.push(i[e]),void 0!==t)for(;e<i.length&&i[e]!==t.q;)e++}if(!ne(e,s)){let l=(e.In?e.root:e.sn).cloneNode(!0);s=e.In?[l]:[...l.childNodes],ne(e,s),(i[0]??o.f.find(e=>e.length>0)?.[0]??t).before(l);for(let e of i)e.remove()}return s}var oe={name:"ssr",install(){u.jn=Y,u.hr=z;let t=u.element;u.element=(l,r)=>{"mounting"===r&&function(t){let l=t.element;if(!l.hasAttribute("enable-ssr")||b())return;let r=l.previousElementSibling,o=r?.localName===h(),i=o?r.getAttribute("version"):null,s=null===i||d(i)===d(e);if(s){let e=t,l=e.ke;e.ke=(e,n)=>"$connectedCallback"===e?void 0:l.call(t,e,n)}if(!o)return;let a=!s&&parseInt(i)<4,f=/^3\.(\d+)\.(\d+)$/.exec(i),p=null!==f&&(+f[1]-5||+f[2]-3)>=0;s||console.warn(`[@wcstack/state] <${h()} version="${i}"> does not match ${e}: its snapshot is discarded, and the page renders on the client from its own state.${a&&!p?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let m=s?r.querySelector('script[type="application/json"]'):null;if(null!==m){let e=JSON.parse(m.textContent||"{}"),l=t.target;for(let t of Object.keys(e)){let n=Object.getOwnPropertyDescriptor(l,t);void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)||(l[t]=e[t])}t.hydrated=!0}let g=l.getRootNode();for(let e of Array.from(g.querySelectorAll(`[${E}]`)))e.textContent=e.getAttribute(E),e.removeAttribute(E);let w=9===g.nodeType?g.body:g;a?function(e,t,l){let r=new Map,o=e=>{let t=e.parentElement;for(;null!==t&&!L(t);)t=t.parentElement;if(null===t)return null;let l=r.get(t);if(void 0===l){let e=o(t),i=t.querySelector(`:scope > ${c.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,l=[]);for(let r of n(t.getAttribute(c.bindAttributeName)??"")){let t=r.Qe;r.$e[0]===i&&l.push([e?X(e,t,1,0):t,r.$e.slice(1).join("."),e&&t])}}return l},i=(e,t,l)=>{let n=o(e);if(null===n)return t;let r=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===r)return l?t:X(n,t,0,1)??t;let i=r[1].replace(/#m\d+\./g,"").slice(0,-1);return n.some(e=>""===e[1]&&(e[0]===i||e[2]===i))?r[2]:X(n,r[2],2,1)??r[2]};for(let t of F(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let n=t.nextSibling;for(;null!==n&&!y(n,`@@wcs-${e[1]}-end:${e[2]}`);)n=n.nextSibling;if(null!==n){for(;t.nextSibling!==n;)t.nextSibling.remove();n.remove(),t.replaceWith(..."text"===e[1]?[v(`@@:${i(t,e[2],l)}`)]:[])}}let s=(e,l)=>{for(let n of F(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(n.data)?.[1],r=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===r)continue;let o=document.importNode(r,!0),a=c.bindAttributeName;o.removeAttribute("id"),o.setAttribute(a,o.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,r)=>t+i(l??n,r))),s(o.content,l??n);let u=o.content.firstChild;n.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?o.content.childNodes:[o])}};s(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(w,r,p):_(w,r,s),r.remove(),s&&(u.Oe=re,queueMicrotask(()=>{H(),u.Oe=null}))}(l),t?.(l,r)},function(){let e=globalThis;e[V]={build:U,reset(){P=0}},void 0===e[g]&&(e[g]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[V].build(t),reset:()=>e[V].reset()})}(),u.To=f(u.To,m);for(let e of l())m(e)}},ie=oe;export{ie as default,oe as ssr};
1
+ import{a as e}from"../chunks/chunk-SAUVGHSB.js";import{b as t,c as l}from"../chunks/chunk-UD3AYVP2.js";import"../chunks/chunk-55J45X6H.js";import{a as n,i as r,j as o,k as i,l as s,m as a}from"../chunks/chunk-L3PFEJP7.js";import"../chunks/chunk-W4KOY6GT.js";import"../chunks/chunk-7AYOQHZH.js";import{a as c}from"../chunks/chunk-M5SODAAE.js";import"../chunks/chunk-ZN52NEIB.js";import"../chunks/chunk-NOPTR2L3.js";import"../chunks/chunk-EIMTT5I3.js";import{a as u,b as f}from"../chunks/chunk-4NJBYXIT.js";var d=e=>e.split(".").slice(0,2).join("."),p=class extends t{static find(e){return e.querySelector?.(c.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return d(this.version)===d(e)}};function m(e){let t=c.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends p{})}var h=()=>c.tagNames.ssr,g=Symbol.for("wcstack.ssr.snapshotBuilder"),b=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),v=e=>document.createComment(e),y=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,w=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),N=new WeakMap,S=new WeakMap,A=new WeakMap,k=new WeakSet,x=new WeakMap;function $(e,t){let l=[];for(let n=e;null!==n&&(l.push(n),n!==t);n=n.nextSibling);return l}function T(e,t,...l){for(let l of Array.from(e.attributes))t.setAttribute(l.name,l.value);return(t.content??t).append(...l),t}var j=e=>null===e.D?e.Ue:e.D[e.D.length-1];function O(e,t,l){let n=[v(null===l?"wcs-[":`wcs-[:${l}`)];for(let e of t)null===l&&n.push(v("wcs-|")),n.push(...$(e.Ue,j(e)));n.push(v("wcs-]")),e.after(...n);for(let e of n)k.add(e)}function q(e){if(e instanceof r){O(e.S,e.Ne,null);for(let t of e.Ne)E(t);return}let t=e.O;null!==t&&(O(e.G[e.G.length-1].S,[t],e.b),E(t))}function E(e){if(null!==e.c)for(let t of e.c)q(t)}var W=new Set(["script","style","template","textarea","title"]),C="data-wcs-raw",I=e=>W.has(e.localName)||e.localName===h();function M(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(v("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(v("wcs-s")):1===t.nodeType&&!I(t)&&M(t)}var P=0;function R(t,l){let n=t.getRootNode(),r=[l];for(let e of S.get(n)??[])e!==l&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let o=new Map;for(let e of r){let t=N.get(e);if(void 0===t)continue;let l=new Map;for(let t of e.oe.values())if(null!==t.E&&l.set(t.E.S,t.E),null!==t.L)for(let e of t.L)l.set(e.S,e);for(let t of e.ce.values())for(let e of t)if(null!==e._)for(let t of e._.G)l.set(t.S,e._);let n=new Set;for(let[e,r]of t){o.set(e,r);let t=l.get(e);void 0!==t&&!n.has(t)&&e.isConnected&&(n.add(t),q(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=A.get(e);if(void 0!==t){let l=document.createTreeWalker(e,133,{acceptNode:e=>k.has(e)||1===e.nodeType&&t.has(e)&&V(e)?2:1}),n=[];for(let e=l.nextNode();null!==e;e=l.nextNode()){let l=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(I(e.parentNode)?x.has(e):t.has(l)&&w(l,"wcs-t:"))&&(x.has(e)||t.get(e)!==e.data):!t.has(e))&&n.push(e)}for(let e of n)e.remove()}let l=Array.from(e.childNodes);I(e)&&l.some(e=>x.has(e))&&e.setAttribute(C,l.map(e=>x.has(e)?`{{ ${x.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}M(9===n.nodeType?n.body:n);let i=document.createElement(h());i.setAttribute("version",e);let s=document.createElement("script");s.type="application/json",s.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let l of Object.keys(e)){if("$"===l[0])continue;let n=Object.getOwnPropertyDescriptor(e,l);void 0!==n.get||void 0!==n.set||"function"==typeof n.value||(t[l]=n.value)}return t}(l.target)),i.append(s);for(let[e,t]of o){if(!e.isConnected)continue;let l=e.parentNode;for(;null!==l&&"svg"!==l.localName&&"foreignObject"!==l.localName;)l=l.parentElement;let n="svg"===l?.localName,r=`wcs-${n?"s":"t"}${P++}`;e.replaceWith(v(`wcs-p:${r}`));let o=document.importNode(a(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(T(e,document.createElement("template"),...e.childNodes));if(n){let e=document.createElementNS(l.namespaceURI,"svg");e.append(o),o=e}let s=document.createElement("template");s.id=r,i.append(T(t,s,o))}t.before(i)}function U(e){!function(e){if(null!==e.querySelector(c.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>x.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${c.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===h())continue;let e=t.engine;null!=e&&R(t,e)}}var D=Symbol.for("wcstack.state.ssr.impl"),J=new Map,G=new WeakMap,V=e=>!0===u.$o?.(e),B=e=>1===e.nodeType&&!I(e)&&!V(e),H=e=>e.f.flat().concat(e.q??[]),L=e=>{for(let t of H(e))t.remove()};function Y(e,t,l){let n=/^wcs-\[(?::(\d+))?/.exec(e.data),r=e.previousSibling,o=e.parentNode,i=[],a=e.nextSibling;for(e.remove();null!==a&&!y(a,"wcs-]");){let e=a.nextSibling;if(y(a,"wcs-|"))i.push([]),a.remove();else{0===i.length&&i.push([]);let l=i[i.length-1];w(a,"wcs-[")?e=Y(a,t,l):(l.push(a),B(a)&&_(a,t))}a=e}let c={branch:void 0===n[1]?null:Number(n[1]),f:i,q:a??o.appendChild(v("wcs-]"))},u=H(c);a=c.q.nextSibling;for(let e of u)l?.push(e),t&&s.add(e);return t&&null!==r?J.set(r,c):L(c),a}function _(e,t){for(let l=e.firstChild;null!==l;)w(l,"wcs-[")?l=Y(l,t):(B(l)&&_(l,t),l=l.nextSibling)}function z(e,t,l){let n=e=>{for(let r of Array.from(e.childNodes))if(r.parentNode===e)if(8===r.nodeType){let e=r.data;try{if("wcs-s"===e)r.remove();else if("wcs-e"===e)r.replaceWith("");else if(e.startsWith("wcs-t:")){let t=v(`@@:${decodeURIComponent(e.slice(6))}`),l=r.nextSibling;for(;null!==l&&!y(l,"wcs-/t");){let e=l.nextSibling;l.remove(),l=e}l?.remove(),r.replaceWith(t)}else if(e.startsWith("wcs-p:")){let l=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==l){let t=r.parentNode,n="s"===e[10]?T(l,document.createElementNS(t.namespaceURI,"template"),...document.importNode(l.content.firstChild,!0).childNodes):document.importNode(l,!0);n.removeAttribute("id"),t.replaceChild(n,r)}}}catch{}}else 1===r.nodeType&&!I(r)&&(V(r)?G.set(r,{ssr:t,Oe:l}):n(r))};n(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let l=t.previousSibling;null!==l&&(8===l.nodeType||te(l)||"template"===l.localName);l=l.previousSibling)e.unshift(l);let l=0,n=0;if(e.forEach((e,t)=>{w(e,"wcs-[")?n++:y(e,"wcs-]")&&--n<0&&(n=0,l=t+1)}),0===n)continue;let r=0;for(let n=t.firstChild;null!==n;n=n.nextSibling)if(w(n,"wcs-["))r++;else if(y(n,"wcs-]")&&0===r--){t.prepend(...e.slice(l));break}}}(e),_(e,l)}function X(e){let t=G.get(e);if(void 0===t||(G.delete(e),z(e,t.ssr,t.Oe),!t.Oe))return null;let l=u.Oe;return u.Oe=re,()=>{u.Oe=l,Z()}}function Z(){for(let e of J.values())L(e);J.clear()}function F(e){let t=[];for(let l=document.createTreeWalker(e,128);l.nextNode();)t.push(l.currentNode);return t}function K(e,t,l,n){let r=null;for(let n of e){let e=n[l];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===r||e.length>r[l].length)&&(r=n)}let o=r?.[n];if(null==o)return null;let i=r[l],s=""===i?t:t.slice(i.length+1);return""===o?s:""===s?o:`${o}.${s}`}function Q(e,t,l){if(b()){if(l instanceof Array){for(let e=l.length;e-- >0;)o(l[e])&&l.splice(e,1);let e=t;if(l.some(i))k.add(e);else if(e.localName.includes("-")&&!V(e)){let t=new Map;for(let l=document.createTreeWalker(e,133);l.nextNode();)t.set(l.currentNode,l.currentNode.data);A.set(e,t)}return}if("string"==typeof l){if(x.set(t,l),I(t.parentNode))return;let e=v(`wcs-t:${encodeURIComponent(l)}`),n=v("wcs-/t");return t.before(e),void t.after(n)}let n=N.get(e);void 0===n&&N.set(e,n=new Map),n.set(t,l);let r=t.getRootNode(),s=S.get(r);return void 0===s&&S.set(r,s=new Set),void s.add(e)}if("string"!=typeof l&&J.size>0){let e=J.get(l);void 0!==e&&(J.delete(l),J.set(t,e))}}var ee=e=>null!==e&&8===e.nodeType&&[c.commentIfPrefix,c.commentElseIfPrefix,c.commentElsePrefix].includes(e.data),te=e=>3===e.nodeType&&""===e.data.trim(),le=e=>(J.get(e)?.q??e).nextSibling;function ne(e,t){if(t.length!==e.sn.childNodes.length)return!1;let l=e.On;for(let n=0;n<l.length;n++){let r=l[n],o=e.sn,i=t[r[0]];for(let e=0;;){if(o=o.childNodes[r[e]],i?.nodeName!==o.nodeName)return!1;if(++e===r.length)break;i=i.firstChild;for(let t=r[e];t>0&&null!==i;t--)i=le(i)}e.ko[n]=i}return!0}function re(e,t,l){if(0===J.size)return null;let n=t,r=0;if(!l){let e=c.commentIfPrefix;if(!y(t,e))for(let l=t.previousSibling;null!==l&&1!==l.nodeType&&(ee(l)&&r++,!y(l,e));l=l.previousSibling);for(let l=t.nextSibling;!J.has(n)&&null!==l&&!y(l,e)&&1!==l.nodeType;l=l.nextSibling)ee(l)&&(n=l)}let o=J.get(n);if(void 0===o)return null;if(!l&&o.branch!==r)return J.delete(n),L(o),null;let i=o.f.shift();if(0===o.f.length&&J.delete(n),o.q?.replaceWith(...$(t,n)),o.q=null,void 0===i)return null;let s=[];for(let e=0;e<i.length;e++){let t=J.get(i[e]);if(s.push(i[e]),void 0!==t)for(;e<i.length&&i[e]!==t.q;)e++}if(!ne(e,s)){let l=(e.In?e.root:e.sn).cloneNode(!0);s=e.In?[l]:[...l.childNodes],ne(e,s),(i[0]??o.f.find(e=>e.length>0)?.[0]??t).before(l);for(let e of i)e.remove()}return s}var oe={name:"ssr",install(){u.jn=Q,u.hr=X;let t=u.element;u.element=(l,r)=>{"mounting"===r&&function(t){let l=t.element;if(!l.hasAttribute("enable-ssr")||b())return;let r=l.previousElementSibling,o=r?.localName===h(),i=o?r.getAttribute("version"):null,s=null===i||d(i)===d(e);if(s){let e=t,l=e.ke;e.ke=(e,n)=>"$connectedCallback"===e?void 0:l.call(t,e,n)}if(!o)return;let a=!s&&parseInt(i)<4,f=/^3\.(\d+)\.(\d+)$/.exec(i),p=null!==f&&(+f[1]-5||+f[2]-3)>=0;s||console.warn(`[@wcstack/state] <${h()} version="${i}"> does not match ${e}: its snapshot is discarded, and the page renders on the client from its own state.${a&&!p?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let m=s?r.querySelector('script[type="application/json"]'):null;if(null!==m){let e=JSON.parse(m.textContent||"{}"),l=t.target;for(let t of Object.keys(e)){let n=Object.getOwnPropertyDescriptor(l,t);void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)||(l[t]=e[t])}t.hydrated=!0}let g=l.getRootNode();for(let e of Array.from(g.querySelectorAll(`[${C}]`)))e.textContent=e.getAttribute(C),e.removeAttribute(C);let w=9===g.nodeType?g.body:g;a?function(e,t,l){let r=new Map,o=e=>{let t=e.parentElement;for(;null!==t&&!V(t);)t=t.parentElement;if(null===t)return null;let l=r.get(t);if(void 0===l){let e=o(t),i=t.querySelector(`:scope > ${c.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,l=[]);for(let r of n(t.getAttribute(c.bindAttributeName)??"")){let t=r.Je;r.$e[0]===i&&l.push([e?K(e,t,1,0):t,r.$e.slice(1).join("."),e&&t])}}return l},i=(e,t,l)=>{let n=o(e);if(null===n)return t;let r=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===r)return l?t:K(n,t,0,1)??t;let i=r[1].replace(/#m\d+\./g,"").slice(0,-1);return n.some(e=>""===e[1]&&(e[0]===i||e[2]===i))?r[2]:K(n,r[2],2,1)??r[2]};for(let t of F(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let n=t.nextSibling;for(;null!==n&&!y(n,`@@wcs-${e[1]}-end:${e[2]}`);)n=n.nextSibling;if(null!==n){for(;t.nextSibling!==n;)t.nextSibling.remove();n.remove(),t.replaceWith(..."text"===e[1]?[v(`@@:${i(t,e[2],l)}`)]:[])}}let s=(e,l)=>{for(let n of F(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(n.data)?.[1],r=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===r)continue;let o=document.importNode(r,!0),a=c.bindAttributeName;o.removeAttribute("id"),o.setAttribute(a,o.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,r)=>t+i(l??n,r))),s(o.content,l??n);let u=o.content.firstChild;n.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?o.content.childNodes:[o])}};s(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(w,r,p):z(w,r,s),r.remove(),s&&(u.Oe=re,queueMicrotask(()=>{Z(),u.Oe=null}))}(l),t?.(l,r)},function(){let e=globalThis;e[D]={build:U,reset(){P=0}},void 0===e[g]&&(e[g]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[D].build(t),reset:()=>e[D].reset()})}(),u.To=f(u.To,m);for(let e of l())m(e)}},ie=oe;export{ie as default,oe as ssr};
2
+ //# sourceMappingURL=ssr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["majorMinor","v","split","slice","join","Ssr","HTMLElementBase","find","root","querySelector","config","tagNames","ssr","version","this","getAttribute","stateData","script","JSON","parse","textContent","templates","map","Map","t","Array","from","children","localName","set","id","hydrateProps","getTemplate","get","verifyVersion","VERSION","defineSsr","registry","tag","define","BUILDER","Symbol","for","isServer","document","documentElement","hasAttribute","mark","data","createComment","isMark","n","nodeType","startsMark","prefix","startsWith","anchors","WeakMap","enginesByRoot","kept","skip","WeakSet","rawTexts","range","to","out","push","nextSibling","attrs","content","a","attributes","setAttribute","name","value","append","lastOf","b","nodes","first","length","region","after","blocks","branch","add","visitView","ForView","anchor","rowViews","visitBlock","cur","current","branches","index","c","RAW","Set","RAW_ATTR","raw","el","has","protectTexts","parent","childNodes","replaceWith","ids","snapshot","engine","getRootNode","engines","E","element","own","byAnchor","l","rootLists","values","view","extra","bs","rootBindings","chain","br","done","template","isConnected","h","querySelectorAll","w","createTreeWalker","acceptNode","scoped","nextNode","p","previousSibling","includes","parentNode","remove","cs","some","body","createElement","type","stringify","replace","charCodeAt","toString","padStart","json","target","key","Object","keys","d","getOwnPropertyDescriptor","e","parentElement","svg","importNode","templateContent","x","namespaceURI","createElementNS","before","build","doc","state","o","options","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","checked","forms","previousElementSibling","IMPL","held","deferred","hooks","componentScope","enters","nodesOf","r","rows","flat","concat","tail","drop","read","start","keep","row","m","exec","next","strip","Number","appendChild","walked","firstChild","prepare","container","adopt","walk","text","decodeURIComponent","copy","removeAttribute","replaceChild","run","isBlank","unshift","open","forEach","i","depth","prepend","mend","adoptScope","host","delete","prev","release","clear","comments","scope","currentNode","across","wiring","path","best","k","rest","ssrMark","node","source","isOuter","splice","setsContent","encodeURIComponent","close","es","size","isIfAnchor","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","trim","fits","plan","fragment","paths","nodePaths","j","nodeName","scratch","isFor","head","shift","inner","fresh","single","cloneNode","install","phase","found","same","callHook","args","call","old","parseInt","console","warn","snap","hydrated","wirings","wiringOf","up","prop","parseBindTextsForElement","bindAttributeName","at","statePathName","propSegments","asIs","reverse","restore","_","f","test","legacy","queueMicrotask","hydrate","g","globalThis","reset","protocol","installBuilder","tags","registries","ssr_default"],"sources":["../../../src/ssr/element.ts","../../../src/ssr/ssr.ts","../../../src/features/ssr.ts"],"sourcesContent":["/**\n * `<wcs-ssr>` (`config.tagNames.ssr`): the server's snapshot before a `<wcs-state enable-ssr>` —\n * `version`, the state's data (a JSON `<script>`) and the page-level templates. The SSR add-on\n * defines the tag; this class only reads the snapshot (the add-on hydrates from it and removes it).\n */\nimport { config } from \"../config\";\nimport { VERSION } from \"../version\";\nimport { HTMLElementBase } from \"../element\";\n\nexport interface ISsrElement {\n /** The @wcstack/state version that rendered the page. */\n readonly version: string;\n /** The state's data the server rendered with. */\n readonly stateData: Record<string, any>;\n /** The page-level templates, by id. */\n readonly templates: Map<string, HTMLTemplateElement>;\n /** Always empty: every binding is applied when the client adopts the server's DOM (3.x kept a value table here). */\n readonly hydrateProps: Record<string, Record<string, unknown>>;\n getTemplate(id: string): HTMLTemplateElement | null;\n /** The snapshot is adoptable: the same major.minor as this build. */\n verifyVersion(): boolean;\n}\n\n/** `4.0.1` → `4.0`: a snapshot is adoptable by the same major.minor. */\nexport const majorMinor = (v: string): string => v.split(\".\").slice(0, 2).join(\".\");\n\nexport class Ssr extends HTMLElementBase implements ISsrElement {\n /** The first snapshot element under `root`, or null. */\n static find(root: Node): ISsrElement | null {\n return ((root as ParentNode).querySelector?.(config.tagNames.ssr) as Ssr | null) ?? null;\n }\n\n get version(): string {\n return this.getAttribute(\"version\") ?? \"\";\n }\n\n get stateData(): Record<string, any> {\n const script = this.querySelector('script[type=\"application/json\"]');\n return script === null ? {} : JSON.parse(script.textContent || \"{}\");\n }\n\n get templates(): Map<string, HTMLTemplateElement> {\n const map = new Map<string, HTMLTemplateElement>();\n // quoted: `children` is an internal name the bundles shorten (mangle.mjs)\n for (const t of Array.from(this[\"children\"])) if (t.localName === \"template\") map.set(t.id, t as HTMLTemplateElement);\n return map;\n }\n\n get hydrateProps(): Record<string, Record<string, unknown>> {\n return {};\n }\n\n getTemplate(id: string): HTMLTemplateElement | null {\n return this.templates.get(id) ?? null;\n }\n\n verifyVersion(): boolean {\n return majorMinor(this.version) === majorMinor(VERSION);\n }\n}\n\n/** Defines `<wcs-ssr>` in `registry` (once per registry). */\nexport function defineSsr(registry: CustomElementRegistry): void {\n const tag = config.tagNames.ssr;\n if (registry.get(tag) === undefined) registry.define(tag, class extends Ssr {});\n}\n","/**\n * Server-side rendering with @wcstack/server (README \"Server-Side Rendering\"), for\n * `<wcs-state enable-ssr>` roots.\n *\n * Server (`<html data-wcs-server>`): the page renders as usual; the snapshot builder\n * (`Symbol.for(\"wcstack.ssr.snapshotBuilder\")`, called by the server before it serializes)\n * then makes the DOM adoptable:\n * - every view's rows / branch move right after its anchor, between `<!--wcs-[-->` and\n * `<!--wcs-]-->`, each row opened by `<!--wcs-|-->` (a branch region carries its index,\n * `<!--wcs-[:i-->`, and follows the chain's last anchor so the chain's templates stay adjacent);\n * - a page-level anchor becomes `<!--wcs-p:ID-->`, its template kept in `<wcs-ssr>` as\n * `<template id=ID>`; a page-level text binding (a mustache, a comment binding) is wrapped in\n * `<!--wcs-t:EXPR-->…<!--wcs-/t-->` (the client puts a comment binding back);\n * - adjacent text nodes are separated (`<!--wcs-s-->`) and empty ones kept (`<!--wcs-e-->`), so\n * parsing the HTML gives back the rows' exact structure;\n * - `<wcs-ssr version>` before the element holds the state's data (JSON) and the templates.\n *\n * Client: before the page is bound, the texts and templates are restored and the regions read where\n * they are (their marks go; the page's walk passes their nodes by); each block the engine builds\n * takes its region's next row instead of a clone (a row's nested regions wait for its nested views\n * in turn). The server's nodes never leave the page — no custom element in a row or a branch is\n * disconnected — and get their bindings; a view's anchors move after its rows instead. A row that\n * does not fit its plan is built anew in its place, and the rows no view took go once the page is\n * bound. `$connectedCallback` does not run (the server ran it).\n *\n * A snapshot of another major.minor is discarded, and the page renders on the client as it would\n * without a server: the state comes from its own source, `$connectedCallback` runs, and the server's\n * rows and marks give way to the templates they came from — those of @wcstack/server 3.x's output\n * too (`legacy`).\n *\n * Not carried over from @wcstack/state 3.3 (approved): the inline snapshot for servers without\n * the builder protocol, and the property value table (every binding is applied on adoption).\n */\nimport type { Engine } from \"../engine\";\nimport { ForView, type Block, type IfView, type RowPlan, type Spec } from \"../dom/view\";\nimport { config } from \"../config\";\nimport { hooks } from \"../hooks\";\n\nimport { VERSION } from \"../version\";\nimport { isOuter, setsContent, templateContent, walked } from \"../dom/plan\";\nimport { majorMinor } from \"./element\";\nimport { parseBindTextsForElement } from \"../parser/parseBindTextsForElement\";\n/** The snapshot element's tag (`config.tagNames.ssr`, `wcs-ssr` by default). */\nconst tag = (): string => config.tagNames.ssr;\nconst BUILDER = Symbol.for(\"wcstack.ssr.snapshotBuilder\");\n\nexport const isServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\n\nconst mark = (data: string): Comment => document.createComment(data);\nconst isMark = (n: Node | null, data: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data === data;\nconst startsMark = (n: Node | null, prefix: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data.startsWith(prefix);\n\n// ---------------------------------------------------------------- server\n\n/** Page-level anchors (the walker's) and the template each replaced, by engine. */\nconst anchors = new WeakMap<Engine, Map<Node, Element>>();\n/** The engines that recorded anchors in a page (its root node): the page's, and its Light DOM components'. */\nconst enginesByRoot = new WeakMap<Node, Set<Engine>>();\n/**\n * The custom elements the page's walker bound, with the nodes in them then (and a text's data): the\n * walk is post-order, so its anchors, text marks and rows are there, and the element's own bindings\n * have not written yet. What an element renders from a value comes later: in the server's HTML the\n * client would walk it as the page's markup (a user's `{{ … }}`, a `data-wcs` in sanitized HTML),\n * so the snapshot leaves it — and a text with `{{` that it was not then (a value's, in a node of\n * its own or one the page wrote) — to the client.\n */\nconst kept = new WeakMap<Node, Map<Node, string>>();\n/** What the client does not walk: a region (rows it adopts), an element whose content a binding sets. */\nconst skip = new WeakSet<Node>();\n/**\n * Mustache texts: their expressions. In an element whose content is text (`<textarea>`, `<title>`),\n * a mark would be text to the browser, and the value the client's markup: the element takes its\n * template along instead (`data-wcs-raw`), and the client puts it back before binding the page.\n */\nconst rawTexts = new WeakMap<Node, string>();\n\n/** Nodes from `from` to `to`, siblings, inclusive. */\nfunction range(from: Node, to: Node): Node[] {\n const out: Node[] = [];\n for (let n: Node | null = from; n !== null; n = n.nextSibling) {\n out.push(n);\n if (n === to) break;\n }\n return out;\n}\n\n/** `to` with `from`'s attributes, and `content` (into a template's content when it has one). */\nfunction attrs<T extends Element>(from: Element, to: T, ...content: Node[]): T {\n for (const a of Array.from(from.attributes)) to.setAttribute(a.name, a.value);\n ((to as unknown as HTMLTemplateElement).content ?? to).append(...content);\n return to;\n}\n\nconst lastOf = (b: Block): Node => (b.nodes === null ? b.first : b.nodes[b.nodes.length - 1]);\n\n/** Moves the blocks' nodes right after `after`, as one region. */\nfunction region(after: Node, blocks: Block[], branch: number | null): void {\n const nodes: Node[] = [mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`)];\n for (const b of blocks) {\n if (branch === null) nodes.push(mark(\"wcs-|\"));\n nodes.push(...range(b.first, lastOf(b)));\n }\n nodes.push(mark(\"wcs-]\"));\n (after as ChildNode).after(...nodes);\n for (const n of nodes) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(v.anchor, v.rowViews, null);\n for (const b of v.rowViews) visitBlock(b);\n return;\n }\n const cur = v.current;\n if (cur === null) return;\n region(v.branches[v.branches.length - 1].anchor, [cur], v.index);\n visitBlock(cur);\n}\n\nfunction visitBlock(b: Block): void {\n if (b.children !== null) for (const c of b.children) visitView(c);\n}\n\nconst RAW = new Set([\"script\", \"style\", \"template\", \"textarea\", \"title\"]);\nconst RAW_ATTR = \"data-wcs-raw\";\nconst raw = (el: Element): boolean => RAW.has(el.localName) || el.localName === tag();\n\n/** Keeps every text node a text node through HTML serialization and parsing. */\nfunction protectTexts(parent: Node): void {\n for (const n of Array.from(parent.childNodes)) {\n if (n.nodeType === 3) {\n if ((n as Text).data === \"\") n.replaceWith(mark(\"wcs-e\"));\n else if (n.nextSibling !== null && n.nextSibling.nodeType === 3) n.after(mark(\"wcs-s\"));\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n protectTexts(n);\n }\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value).replace(/[<>&\\u2028\\u2029]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n}\n\n/** The state's own data (no `$` keys, no accessors, no functions). */\nfunction data(target: Record<string, any>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(target)) {\n if (key[0] === \"$\") continue;\n const d = Object.getOwnPropertyDescriptor(target, key)!;\n if (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\") continue;\n out[key] = d.value;\n }\n return out;\n}\n\nlet ids = 0;\n\nfunction snapshot(el: Element, engine: Engine): void {\n const root = el.getRootNode() as Document | ShadowRoot;\n // the page's engine, and those of the Light DOM components in it: their walkers' anchors are in\n // the page too (a Shadow DOM component's are in its own shadow root)\n const engines = [engine];\n for (const E of enginesByRoot.get(root) ?? []) {\n if (E !== engine && (E.element as Element | null)?.hasAttribute(\"bind-component\") === true) engines.push(E);\n }\n const map = new Map<Node, Element>();\n for (const E of engines) {\n const own = anchors.get(E);\n if (own === undefined) continue;\n // the views the walker made, top down (a nested view's region stays inside its row's)\n const byAnchor = new Map<Node, ForView | IfView>();\n for (const l of E.rootLists.values()) {\n if (l.view !== null) byAnchor.set(l.view.anchor, l.view);\n if (l.extra !== null) for (const v of l.extra) byAnchor.set(v.anchor, v);\n }\n for (const bs of E.rootBindings.values()) {\n for (const b of bs) if (b.chain !== null) for (const br of b.chain.branches) byAnchor.set(br.anchor, b.chain);\n }\n const done = new Set<ForView | IfView>();\n for (const [anchor, template] of own) {\n map.set(anchor, template);\n const v = byAnchor.get(anchor);\n if (v !== undefined && !done.has(v) && anchor.isConnected) {\n done.add(v);\n visitView(v);\n }\n }\n }\n for (const h of Array.from(root.querySelectorAll(\"*\"))) {\n const own = kept.get(h);\n if (own !== undefined) {\n // what the client does not walk is left: what `skip` has, and — the page's — a Light DOM\n // component (bound later, by its own engine). A text without `{{` is no markup to the client,\n // whoever wrote it; one the page wrote is left as it was written, and a mustache's where the\n // client puts its expression back: right after its mark (the client replaces what follows it),\n // or in a text element (`data-wcs-raw`). Elsewhere it goes: an element may drop comments, or\n // move a text element's text out, and its value would be the client's markup\n const w = document.createTreeWalker(h, 133, {\n acceptNode: (n) => (skip.has(n) || (n.nodeType === 1 && own.has(n) && scoped(n as Element)) ? 2 : 1),\n });\n const out: ChildNode[] = [];\n for (let n = w.nextNode(); n !== null; n = w.nextNode()) {\n const p = n.previousSibling!;\n if (n.nodeType === 3\n ? (n as Text).data.includes(\"{{\")\n && !(raw(n.parentNode as Element) ? rawTexts.has(n) : own.has(p) && startsMark(p, \"wcs-t:\"))\n && (rawTexts.has(n) || own.get(n) !== (n as Text).data)\n : !own.has(n)) out.push(n as ChildNode);\n }\n for (const n of out) n.remove();\n }\n const cs = Array.from(h.childNodes);\n if (raw(h) && cs.some((c) => rawTexts.has(c))) {\n // (a comment there — a server's DOM may parse one in a <textarea> — is text to a browser)\n h.setAttribute(RAW_ATTR, cs.map((c) => (rawTexts.has(c) ? `{{ ${rawTexts.get(c)} }}` : c.nodeType === 8 ? `<!--${(c as Comment).data}-->` : c.textContent)).join(\"\"));\n }\n }\n protectTexts(root.nodeType === 9 ? (root as Document).body : root);\n const ssr = document.createElement(tag());\n ssr.setAttribute(\"version\", VERSION);\n const script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.textContent = json(data(engine.target));\n ssr.append(script);\n for (const [anchor, template] of map) {\n if (!anchor.isConnected) continue;\n // the anchor's context, by name (a server's DOM may not know <foreignObject> leads back to HTML):\n // SVG under <svg> — its id says so (`wcs-s…`) — and HTML under <foreignObject>\n let e = anchor.parentNode as Element | null;\n while (e !== null && e.localName !== \"svg\" && e.localName !== \"foreignObject\") e = e.parentElement;\n const svg = e?.localName === \"svg\";\n const id = `wcs-${svg ? \"s\" : \"t\"}${ids++}`;\n (anchor as ChildNode).replaceWith(mark(`wcs-p:${id}`));\n let c: Node = document.importNode(templateContent(template as HTMLTemplateElement), true);\n // a template in it that is an SVG element goes as an HTML one, which a serializer reads (the\n // client's parser reads it back in its context)\n for (const x of Array.from((c as Element).querySelectorAll(\"template\"))) {\n // by namespace, not `instanceof SVGElement`: a server window (@wcstack/server) need not expose that global\n if (x.namespaceURI === \"http://www.w3.org/2000/svg\") x.replaceWith(attrs(x, document.createElement(\"template\"), ...x.childNodes));\n }\n // an SVG template's content goes in <svg>, so the client's parser reads it as SVG\n if (svg) {\n const w = document.createElementNS(e!.namespaceURI, \"svg\");\n w.append(c);\n c = w;\n }\n const t = document.createElement(\"template\");\n t.id = id;\n ssr.append(attrs(template, t, c));\n }\n el.before(ssr);\n}\n\n/**\n * The form controls' current state into their markup, as 3.x wrote it: an input's value (its\n * `value` attribute) and checkedness (`checked`), a textarea's value (its text), the options a\n * select has selected (`selected`) — whatever set them (a `value:` / `checked:` / `selectedIndex:`\n * binding, `radio:`, a row's), where it differs from what the markup gives back. The page then shows\n * the server's values before the client binds it, or without JS; the client's bindings find them\n * there, and write over them from then on. On a page with a `<wcs-state>` only (enable-ssr or not).\n * A password's value never goes into the HTML (3.x wrote it): the client's binding fills it in.\n */\nfunction forms(doc: Document): void {\n if (doc.querySelector(config.tagNames.state) === null) return;\n for (const n of Array.from(doc.querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n // (a single select without a marked option, its first enabled one selected: what a parser selects)\n if (n.multiple || o.some((x) => x.hasAttribute(\"selected\")) || o[n.selectedIndex] !== o.find((x) => !x.disabled)) {\n for (const x of o) x.toggleAttribute(\"selected\", x.selected);\n }\n } else if (n.localName === \"textarea\") {\n // (a value with `{{` in it would be the client's markup there, a mustache; a mustache in it is\n // the client's to put back — see snapshot: both left to the client)\n if (n.value !== n.defaultValue && !n.value.includes(\"{{\") && !Array.from(n.childNodes).some((c) => rawTexts.has(c as Node))) n.textContent = n.value;\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n n.toggleAttribute(\"checked\", n.checked);\n } else if (n.type !== \"password\" && n.value !== n.defaultValue) {\n n.setAttribute(\"value\", n.value);\n }\n }\n}\n\n/** The builder the server calls before it serializes (protocol wcs-ssr-snapshot v1). */\nfunction build(doc: Document): void {\n // first: moving the rows into their regions (snapshot) may change what a select has selected\n forms(doc);\n for (const el of Array.from(doc.querySelectorAll(`${config.tagNames.state}[enable-ssr]`))) {\n if (el.hasAttribute(\"mount\") || el.hasAttribute(\"bind-component\")) continue;\n if (el.previousElementSibling?.localName === tag()) continue;\n const engine = (el as any).engine as Engine | null;\n if (engine !== null && engine !== undefined) snapshot(el, engine);\n }\n}\n\n/** Where the builder finds this module: the latest evaluation (a server may load one per render). */\nconst IMPL = Symbol.for(\"wcstack.state.ssr.impl\");\n\nexport function installBuilder(): void {\n const g = globalThis as any;\n g[IMPL] = { build, reset() { ids = 0; } };\n // another engine's builder (the current @wcstack/state) is not replaced\n if (g[BUILDER] === undefined) {\n g[BUILDER] = { protocol: \"wcs-ssr-snapshot\", version: 1, build: (doc: Document) => g[IMPL].build(doc), reset: () => g[IMPL].reset() };\n }\n}\n\n// ---------------------------------------------------------------- client\n\ninterface Region {\n /** The branch the region renders (null: a list). */\n readonly branch: number | null;\n /** Each row's nodes, where the server put them (a region in the row included). */\n readonly rows: Node[][];\n /**\n * The region's end mark, after its rows: the server put a view's rows after its anchor, and the view\n * renders them before it — the anchor goes here when the view takes the first row (null after).\n */\n tail: ChildNode | null;\n}\n\n/** Regions waiting for their view, by the node right before them (a view's anchor). */\nconst held = new Map<Node, Region>();\n\n/**\n * The Light DOM components of a page being hydrated, by host: their content is bound by their own\n * engine, which starts later (once its host is wired, or its class defined), so it keeps the\n * server's nodes until then and is prepared when that engine binds it (adoptScope).\n */\nconst deferred = new WeakMap<Node, { ssr: Element; adopt: boolean }>();\nconst scoped = (el: Element): boolean => hooks.componentScope?.(el) === true;\n\n/** An element regions may be in: not a text element, nor a Light DOM component (its engine reads its own). */\nconst enters = (n: Node): boolean => n.nodeType === 1 && !raw(n as Element) && !scoped(n as Element);\n\n/** A region's nodes: its rows', and its end mark. */\nconst nodesOf = (r: Region): Node[] => r.rows.flat().concat(r.tail ?? []);\n\n/** Takes a region's nodes out of the page (rows no view took, or not the plan's). */\nconst drop = (r: Region): void => {\n for (const n of nodesOf(r)) (n as ChildNode).remove();\n};\n\n/**\n * Reads the region `start` opens where it is: its marks go but its end mark, and its nodes stay (no\n * custom element in them is disconnected). It is held by the node before it, its view's anchor (the\n * page's walk then passes its nodes by: its blocks bind them where they are), or dropped (`keep`\n * false, or no node before it). A region in it — in a row, after a view's anchor of the row, or in an\n * element of it — is read in turn. Its nodes go in `row` (the row it is in); returns the node after it.\n */\nfunction read(start: Comment, keep: boolean, row?: Node[]): Node | null {\n const m = /^wcs-\\[(?::(\\d+))?/.exec(start.data)!;\n const key = start.previousSibling;\n const parent = start.parentNode!;\n const rows: Node[][] = [];\n let n: Node | null = start.nextSibling;\n start.remove();\n while (n !== null && !isMark(n, \"wcs-]\")) {\n let next: Node | null = n.nextSibling;\n if (isMark(n, \"wcs-|\")) {\n rows.push([]);\n (n as ChildNode).remove();\n } else {\n // (a branch has no row marks; a list's node before its first one is a value's)\n if (rows.length === 0) rows.push([]);\n const own = rows[rows.length - 1];\n if (startsMark(n, \"wcs-[\")) next = read(n as Comment, keep, own);\n else {\n own.push(n);\n if (enters(n)) strip(n, keep);\n }\n }\n n = next;\n }\n // (cut short — a parser moved its end mark into an element (see mend): it ends with its parent)\n const r: Region = { branch: m[1] === undefined ? null : Number(m[1]), rows, tail: (n ?? parent.appendChild(mark(\"wcs-]\"))) as ChildNode };\n const nodes = nodesOf(r);\n n = r.tail!.nextSibling;\n // (not spread: a region may have more nodes than a call takes arguments)\n for (const x of nodes) {\n row?.push(x);\n if (keep) walked.add(x);\n }\n if (keep && key !== null) {\n held.set(key, r);\n } else {\n drop(r);\n }\n return n;\n}\n\n/** Reads every region under `parent` (see read). */\nfunction strip(parent: Node, keep: boolean): void {\n for (let n: Node | null = parent.firstChild; n !== null; ) {\n if (startsMark(n, \"wcs-[\")) {\n n = read(n as Comment, keep);\n } else {\n if (enters(n)) strip(n, keep);\n n = n.nextSibling;\n }\n }\n}\n\n/** Texts and templates back to what the page was written with; the regions read (see strip). */\nfunction prepare(container: Node, ssr: Element, adopt: boolean): void {\n const walk = (parent: Node): void => {\n for (const n of Array.from(parent.childNodes)) {\n // a text marker takes the nodes up to its end with it\n if (n.parentNode !== parent) continue;\n if (n.nodeType === 8) {\n const d = (n as Comment).data;\n // (a mark the server did not write — in a value — that does not parse is left as it is;\n // a string given to replaceWith goes in as a text node)\n try {\n if (d === \"wcs-s\") n.remove();\n else if (d === \"wcs-e\") n.replaceWith(\"\");\n else if (d.startsWith(\"wcs-t:\")) {\n // the value between the markers, back to a text binding: a comment binding, which binds\n // whether or not the page's mustaches are on (it was a mustache, or a comment binding)\n const text = mark(`@@:${decodeURIComponent(d.slice(6))}`);\n let e: ChildNode | null = n.nextSibling;\n while (e !== null && !isMark(e, \"wcs-/t\")) {\n const next = e.nextSibling;\n e.remove();\n e = next;\n }\n e?.remove();\n n.replaceWith(text);\n } else if (d.startsWith(\"wcs-p:\")) {\n const t = ssr.querySelector(`template[id=\"${d.slice(6)}\"]`) as HTMLTemplateElement | null;\n if (t !== null) {\n const p = n.parentNode as Element;\n // an SVG template (`wcs-s…`): its content came in <svg> (so parsed as SVG)\n const copy = d[10] === \"s\"\n ? attrs(t, document.createElementNS(p.namespaceURI, \"template\"), ...document.importNode(t.content.firstChild!, true).childNodes)\n : document.importNode(t, true);\n copy.removeAttribute(\"id\");\n p.replaceChild(copy, n);\n }\n }\n } catch { /* */ }\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n if (scoped(n as Element)) deferred.set(n, { ssr, adopt });\n else walk(n);\n }\n }\n };\n walk(container);\n mend(container);\n strip(container, adopt);\n}\n\n/**\n * A region a parser cut: its start mark in a <table>, its rows and end mark in the <tbody> the parser\n * added at its first <tr> (the regions after it with them). The comments and templates right before\n * the <tbody> that the cut region starts with go into it — its anchor and marks: nothing in them\n * connects — and the rows stay where they are. A <tbody> written in the page (a row of a list of\n * them, a branch) holds no end mark of a region that starts before it, and is left alone.\n */\nfunction mend(container: Node): void {\n for (const body of Array.from((container as ParentNode).querySelectorAll(\"table > tbody\"))) {\n const run: Node[] = [];\n for (let p = body.previousSibling; p !== null && (p.nodeType === 8 || isBlank(p) || (p as Element).localName === \"template\"); p = p.previousSibling) run.unshift(p);\n // the regions the run leaves open (an end mark whose start is before the run — past an element —\n // closes a region that stays where it is, with what comes before the mark)\n let from = 0;\n let open = 0;\n run.forEach((n, i) => {\n if (startsMark(n, \"wcs-[\")) open++;\n else if (isMark(n, \"wcs-]\") && --open < 0) {\n open = 0;\n from = i + 1;\n }\n });\n if (open === 0) continue;\n // ... and the <tbody> ends one: the parser moved its rows in\n let depth = 0;\n for (let c = body.firstChild; c !== null; c = c.nextSibling) {\n if (startsMark(c, \"wcs-[\")) depth++;\n else if (isMark(c, \"wcs-]\") && depth-- === 0) {\n body.prepend(...run.slice(from));\n break;\n }\n }\n }\n}\n\n/**\n * The `adoptScope` hook: a Light DOM component's engine binds its host. Its content is prepared\n * now, and its blocks take the server's nodes while its walk runs (a walk adopts synchronously).\n * What it did not adopt is dropped after the walk: the regions held then are its own (a page's are\n * read and adopted in one go too, and dropped before anything else runs).\n */\nexport function adoptScope(host: Node): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n prepare(host, d.ssr, d.adopt);\n if (!d.adopt) return null;\n const prev = hooks.adopt;\n hooks.adopt = adopt;\n return () => {\n hooks.adopt = prev;\n release();\n };\n}\n\n/** Drops the held regions: rows no view took. */\nfunction release(): void {\n for (const r of held.values()) drop(r);\n held.clear();\n}\n\n/** The comments under `scope`, in document order. */\nfunction comments(scope: Node): Comment[] {\n const out: Comment[] = [];\n for (const w = document.createTreeWalker(scope, 128); w.nextNode(); ) out.push(w.currentNode as Comment);\n return out;\n}\n\n/**\n * A Light DOM component's wiring, one entry per mapping: [the page's path (null: not known — a key\n * private to the component around), its own path (\"\" for a whole mount, `state: user`), the path as\n * its host wrote it (null at the top: the page's)].\n */\ntype Wiring = (string | null)[][];\n\n/** `path` from column `from` of `wiring` to column `to`, by the longest it is or starts with; null: none. */\nfunction across(wiring: Wiring, path: string, from: number, to: number): string | null {\n let best: (string | null)[] | null = null;\n for (const w of wiring) {\n const k = w[from];\n if (k !== null && (k === \"\" || path === k || path.startsWith(`${k}.`)) && (best === null || k.length > best[from]!.length)) best = w;\n }\n const v = best?.[to];\n if (v == null) return null;\n const k = best![from]!;\n const rest = k === \"\" ? path : path.slice(k.length + 1);\n return v === \"\" ? rest : rest === \"\" ? v : `${v}.${rest}`;\n}\n\n/**\n * The output of @wcstack/server 3.x back to the page as written, as 3.x's own fallback did\n * (`Ssr.cleanupDom`): a row or a branch (`<!--@@wcs-for-start:…-->` up to its `-end` mark among its\n * siblings) goes, a text between its marks becomes a comment binding of what the mark holds (before\n * 3.5.3 the path alone, its filters lost: the warning says so; from 3.5.3, `fresh`, the binding's\n * expression as written: wcstack#373), a template's mark (`<!--@@wcs-for:ID-->`) becomes the template\n * `<wcs-ssr>` keeps under that id (whose content has the marks of the templates in it), and the\n * elements lose `data-wcs-ssr-id`.\n *\n * In a Light DOM component, 3.x wrote a template's own path as the page's (`state: user` makes `name`\n * `user.name`; a private key `user.#m1.name`, or `#m2.name` in a partial mount; in a component in a\n * component, through both), and so the marks' paths before 3.5.3: they go back to the component's own\n * through its host's wiring (the content of a template is the component's already). A mark from 3.5.3\n * is the component's own text, not mapped (it may name a key that is one of the page's wired paths\n * too: `state.x: v; state.v: w`). An expression a comment cannot hold (one with a `--`) falls back to\n * its path, unfiltered. From 3.5.4 (wcstack#427) that is the path the component wrote, read as written\n * like any other mark: the value shows, without its filters. 3.5.3 wrote the page's path there\n * instead, which is mapped back when it names a private key (`#mN.`: never in the component's own\n * text, so the mapping cannot misread a 3.5.4 mark); a wired one cannot be told from the component's\n * own text, and is read as it — a component key of that name shows its value, the right one only when\n * the wiring keeps the name, else the text stays empty (a limit of 3.5.3 output only: migration guide\n * §3.6).\n */\nfunction legacy(container: Node, ssr: Element, fresh: boolean): void {\n const wirings = new Map<Element, Wiring>();\n /** The wiring of the Light DOM component `n` is in (a nested one's composed with the one around), or null. */\n const wiringOf = (n: Node): Wiring | null => {\n let h = n.parentElement;\n while (h !== null && !scoped(h)) h = h.parentElement;\n if (h === null) return null;\n let wiring = wirings.get(h);\n if (wiring === undefined) {\n const up = wiringOf(h);\n const prop = h.querySelector(`:scope > ${config.tagNames.state}[bind-component]`)!.getAttribute(\"bind-component\");\n wirings.set(h, (wiring = []));\n for (const b of parseBindTextsForElement(h.getAttribute(config.bindAttributeName) ?? \"\")) {\n const at = b.statePathName;\n if (b.propSegments[0] === prop) wiring.push([up ? across(up, at, 1, 0) : at, b.propSegments.slice(1).join(\".\"), up && at]);\n }\n }\n return wiring;\n };\n /**\n * A path 3.x wrote at `n`, as the component's own there (`asIs`: a text mark from 3.5.3, left as it\n * is but for a private key's path, which 3.5.3's fallback writes).\n */\n const own = (n: Node, path: string, asIs?: boolean): string => {\n const wiring = wiringOf(n);\n if (wiring === null) return path;\n // (no `|`: a mark with filters, from 3.5.3, is the component's own text, a `#m1.` in it an argument's)\n const m = /^([^|]*)#m\\d+\\.([^|]*)$/.exec(path);\n if (m === null) return asIs ? path : across(wiring, path, 0, 1) ?? path;\n // after the last private key mark, a component's own path: this one's when what comes before the\n // mark is this one's mount path (`user.#m1.name`, `user.profile.#m3.name`, `#m2.box.#m4.name` with\n // `state: box`; nothing for a partial mount, `#m2.name`), else the one's around it, which this one\n // is mounted on (`#m2.box.k` with `state: box`)\n const at = m[1].replace(/#m\\d+\\./g, \"\").slice(0, -1);\n return wiring.some((w) => w[1] === \"\" && (w[0] === at || w[2] === at)) ? m[2] : across(wiring, m[2], 2, 1) ?? m[2];\n };\n // from the last: a row's own marks go before the row does\n for (const c of comments(container).reverse()) {\n const m = /^@@wcs-(\\w+)-start:([\\s\\S]*)/.exec(c.data);\n if (m === null) continue;\n // (no end among its siblings — an output cut short: left as it is)\n let e = c.nextSibling;\n while (e !== null && !isMark(e, `@@wcs-${m[1]}-end:${m[2]}`)) e = e.nextSibling;\n if (e === null) continue;\n while (c.nextSibling !== e) c.nextSibling!.remove();\n e.remove();\n c.replaceWith(...(m[1] === \"text\" ? [mark(`@@:${own(c, m[2], fresh)}`)] : []));\n }\n const restore = (scope: Node, at?: Node): void => {\n for (const c of comments(scope)) {\n const id = /^@@wcs-(?:for|if|elseif|else):(\\S+)$/.exec(c.data)?.[1];\n const t = Array.from(ssr.querySelectorAll(\"template\")).find((x) => x.id === id);\n if (t === undefined) continue;\n const copy = document.importNode(t, true);\n const a = config.bindAttributeName;\n copy.removeAttribute(\"id\");\n copy.setAttribute(a, copy.getAttribute(a)!.replace(/^(\\s*\\w+\\s*:\\s*)([^\\s|]+)/, (_, k: string, p: string) => k + own(at ?? c, p)));\n restore(copy.content, at ?? c);\n // 3.x made each `elseif` an `if` in an `else` of its own (whose content starts with it): back\n // to the chain of templates it was written as\n const f = copy.content.firstChild as Element | null;\n c.replaceWith(...(/^\\s*elseif\\s*:/.test(f?.getAttribute?.(a) ?? \"\") ? copy.content.childNodes : [copy]));\n }\n };\n restore(container);\n for (const e of Array.from((container as ParentNode).querySelectorAll(\"[data-wcs-ssr-id]\"))) e.removeAttribute(\"data-wcs-ssr-id\");\n}\n\n/** The `element` hook, \"mounting\": a client root with a server snapshot adopts the server's DOM. */\nexport function hydrate(engine: Engine): void {\n const el = engine.element as Element;\n if (!el.hasAttribute(\"enable-ssr\") || isServer()) return;\n const ssr = el.previousElementSibling;\n const found = ssr?.localName === tag();\n const version = found ? ssr!.getAttribute(\"version\") : null;\n const same = version === null || majorMinor(version) === majorMinor(VERSION);\n if (same) {\n // the server ran $connectedCallback; the client does not\n const e = engine as any;\n const callHook = e.callHook;\n e.callHook = (name: string, args?: unknown[]) => (name === \"$connectedCallback\" ? undefined : callHook.call(engine, name, args));\n }\n if (!found) return;\n // @wcstack/server 3.x's output: marks of its own; from 3.5.3 on a text mark holds the binding's\n // expression (see legacy). A prerelease, or a version that does not parse, counts as older\n const old = !same && parseInt(version!) < 4;\n const v = /^3\\.(\\d+)\\.(\\d+)$/.exec(version!);\n const fresh = v !== null && (+v[1] - 5 || +v[2] - 3) >= 0;\n if (!same) {\n // (the filters' sentence: output before 3.5.3 only)\n console.warn(`[@wcstack/state] <${tag()} version=\"${version}\"> does not match ${VERSION}: its snapshot is discarded, and the page renders on the client from its own state.${old && !fresh\n ? \" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.\"\n : \"\"}`);\n }\n const script = same ? ssr!.querySelector('script[type=\"application/json\"]') : null;\n if (script !== null) {\n const snap = JSON.parse(script.textContent || \"{}\") as Record<string, unknown>;\n const target = engine.target;\n for (const key of Object.keys(snap)) {\n const d = Object.getOwnPropertyDescriptor(target, key);\n if (d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\")) continue;\n target[key] = snap[key];\n }\n // the snapshot holds the server's volume data too: a volume adopts it (scopes/volume.ts)\n (engine as any).hydrated = true;\n }\n const root = el.getRootNode() as Document | ShadowRoot;\n for (const r of Array.from(root.querySelectorAll(`[${RAW_ATTR}]`))) {\n r.textContent = r.getAttribute(RAW_ATTR);\n r.removeAttribute(RAW_ATTR);\n }\n const container = root.nodeType === 9 ? (root as Document).body : root;\n if (old) legacy(container, ssr!, fresh);\n else prepare(container, ssr!, same);\n ssr!.remove();\n if (same) {\n // only while the page is adopted — its walk, which runs now: every other block is built with one\n // null check. What no view took then goes before anything else runs\n hooks.adopt = adopt;\n queueMicrotask(() => {\n release();\n hooks.adopt = null;\n });\n }\n}\n\n/**\n * The `ssrMark` hook: on the server, records (and leaves `outerHTML:` / `outerText:` to the client); on the client,\n * a held region follows its template's anchor.\n */\nexport function ssrMark(engine: Engine, node: Node, source: Element | string | Spec[]): void {\n if (isServer()) {\n if (source instanceof Array) {\n // `outerHTML:` / `outerText:` replace the element with the value: the client would find no\n // binding there, and walk the value as the page's markup. The server renders the element as\n // written; the client binds it and applies the value\n for (let i = source.length; i-- > 0; ) if (isOuter(source[i])) source.splice(i, 1);\n // a custom element (a Light DOM component binds its own) whose content no binding sets: what\n // is in it now is the page's (see kept)\n const el = node as Element;\n if (source.some(setsContent)) skip.add(el);\n else if (el.localName.includes(\"-\") && !scoped(el)) {\n const own = new Map<Node, string>();\n for (const w = document.createTreeWalker(el, 133); w.nextNode(); ) own.set(w.currentNode, (w.currentNode as Text).data);\n kept.set(el, own);\n }\n return;\n }\n if (typeof source === \"string\") {\n rawTexts.set(node, source);\n if (raw(node.parentNode as Element)) return;\n const open = mark(`wcs-t:${encodeURIComponent(source)}`);\n const close = mark(\"wcs-/t\");\n (node as Text).before(open);\n (node as Text).after(close);\n return;\n }\n let map = anchors.get(engine);\n if (map === undefined) anchors.set(engine, (map = new Map()));\n map.set(node, source);\n const root = node.getRootNode();\n let es = enginesByRoot.get(root);\n if (es === undefined) enginesByRoot.set(root, (es = new Set()));\n es.add(engine);\n return;\n }\n // (an element's specs are never a key: the templates the anchors replaced are)\n if (typeof source !== \"string\" && held.size > 0) {\n const r = held.get(source as Element);\n if (r !== undefined) {\n held.delete(source as Element);\n held.set(node, r);\n }\n }\n}\n\n/** An anchor of an `if` / `elseif` / `else` chain (the core names them by config). */\nconst isIfAnchor = (n: Node | null): boolean =>\n n !== null && n.nodeType === 8 && [config.commentIfPrefix, config.commentElseIfPrefix, config.commentElsePrefix].includes((n as Comment).data);\nconst isBlank = (n: Node): boolean => n.nodeType === 3 && (n as Text).data.trim() === \"\";\n\n/** The next of the plan's nodes after `n`: a held region after an anchor is the anchor's view's. */\nconst after = (n: Node): Node | null => (held.get(n)?.tail ?? n).nextSibling;\n\n/**\n * Whether a row's top-level nodes `own` have the plan's nodes where a binding lands — not so when a\n * Light DOM element added children before them, or a parser moved them (see mend); puts them\n * in `plan.scratch` for the block.\n */\nfunction fits(plan: RowPlan, own: Node[]): boolean {\n if (own.length !== plan.fragment.childNodes.length) return false;\n const paths = plan.nodePaths;\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n let a: Node = plan.fragment;\n let b: Node | null | undefined = own[path[0]];\n for (let j = 0; ; ) {\n a = a.childNodes[path[j]];\n if (b?.nodeName !== a.nodeName) return false;\n if (++j === path.length) break;\n b = b.firstChild;\n for (let k = path[j]; k > 0 && b !== null; k--) b = after(b);\n }\n plan.scratch[i] = b;\n }\n return true;\n}\n\n/**\n * The `adopt` hook: the next server row (or branch) of the view anchored at `anchor` — its top-level\n * nodes, left where they are (the view inserts nothing, and no custom element in them is disconnected).\n */\nexport function adopt(plan: RowPlan, anchor: Node, isFor: boolean): ChildNode[] | null {\n if (held.size === 0) return null;\n let key = anchor;\n let branch = 0;\n if (!isFor) {\n // only this chain: an `if` anchor starts one (a chain right before or after is another). No\n // element is between its anchors: whitespace, comments (readChain) and the text a comment binding\n // there renders may be\n const head = config.commentIfPrefix;\n if (!isMark(anchor, head)) {\n for (let p = anchor.previousSibling; p !== null && p.nodeType !== 1; p = p.previousSibling) {\n if (isIfAnchor(p)) branch++;\n if (isMark(p, head)) break;\n }\n }\n // up to the anchor its region follows (the branch's nodes come right after it)\n for (let n = anchor.nextSibling; !held.has(key) && n !== null && !isMark(n, head) && n.nodeType !== 1; n = n.nextSibling) {\n if (isIfAnchor(n)) key = n;\n }\n }\n const r = held.get(key);\n if (r === undefined) return null;\n if (!isFor && r.branch !== branch) {\n // the server rendered another branch: it goes, this one is built\n held.delete(key);\n drop(r);\n return null;\n }\n const nodes = r.rows.shift();\n if (r.rows.length === 0) held.delete(key);\n // a view renders before its anchor (a branch before its own: the chain's anchors from it on), and\n // the server put its rows after: the anchors go where the rows end\n r.tail?.replaceWith(...range(anchor, key));\n r.tail = null;\n if (nodes === undefined) return null;\n // the row's own top-level nodes (a region in it is a nested view's)\n let own: Node[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const inner = held.get(nodes[i]);\n own.push(nodes[i]);\n // (its nodes follow it, up to its end mark)\n if (inner !== undefined) while (i < nodes.length && nodes[i] !== inner.tail) i++;\n }\n if (!fits(plan, own)) {\n // rendered anew, in its place (the rows around it stay; an empty one's place is before the next\n // row, or the anchor): its nodes found before it is in the page (a custom element in it may add\n // children as it connects)\n const fresh = (plan.single ? plan.root! : plan.fragment).cloneNode(true);\n own = plan.single ? [fresh] : [...fresh.childNodes];\n fits(plan, own);\n ((nodes[0] ?? r.rows.find((x) => x.length > 0)?.[0] ?? anchor) as ChildNode).before(fresh);\n for (const n of nodes) (n as ChildNode).remove();\n }\n return own as ChildNode[];\n}\n","/**\n * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —\n * see src/ssr/ssr.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { adoptScope, hydrate, installBuilder, ssrMark } from \"../ssr/ssr\";\nimport { defineSsr } from \"../ssr/element\";\nimport { registries } from \"../element\";\n\nexport const ssr: Feature = {\n name: \"ssr\",\n install(): void {\n hooks.ssrMark = ssrMark;\n hooks.adoptScope = adoptScope;\n // the snapshot first, before what is installed (in any order) runs at \"mounting\": a volume\n // grafting there adopts it, and its $connectedCallback writes over it (3.x D14)\n const prev = hooks.element;\n hooks.element = (engine, phase) => {\n if (phase === \"mounting\") hydrate(engine);\n prev?.(engine, phase);\n };\n installBuilder();\n // `<wcs-ssr>` in every registry `<wcs-state>` is defined in, now and later\n hooks.tags = chain(hooks.tags, defineSsr);\n for (const r of registries()) defineSsr(r);\n },\n};\nexport default ssr;\n"],"mappings":"yfAwBO,IAAMA,EAAcC,GAAsBA,EAAEC,MAAM,KAAKC,MAAM,EAAG,GAAGC,KAAK,KAElEC,EAAN,cAAkBC,EAEvB,WAAOC,CAAKC,GACV,OAASA,EAAoBC,gBAAgBC,EAAOC,SAASC,MAAuB,IACtF,CAEA,WAAIC,GACF,OAAOC,KAAKC,aAAa,YAAc,EACzC,CAEA,aAAIC,GACF,IAAMC,EAASH,KAAKL,cAAc,mCAClC,OAAkB,OAAXQ,EAAkB,CAAC,EAAIC,KAAKC,MAAMF,EAAOG,aAAe,KACjE,CAEA,aAAIC,GACF,IAAMC,EAAM,IAAIC,IAEhB,QAAWC,KAAKC,MAAMC,KAAKZ,KAAKa,UAAkC,aAAhBH,EAAEI,WAA0BN,EAAIO,IAAIL,EAAEM,GAAIN,GAC5F,OAAOF,CACT,CAEA,gBAAIS,GACF,MAAO,CAAC,CACV,CAEA,WAAAC,CAAYF,GACV,OAAOhB,KAAKO,UAAUY,IAAIH,IAA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/L,GAG5B,IAAMsM,EAAInF,EAAK7I,QAAQsI,WACvB5G,EAAEU,eAAgB,iBAAiB6L,KAAKD,GAAGtR,eAAeuD,IAAM,IAAM4I,EAAK7I,QAAQmC,WAAa,CAAC0G,GACnG,GAEFiF,EAAQtF,GACR,QAAWjD,KAAKnI,MAAMC,KAAMmL,EAAyB7E,iBAAiB,sBAAuB4B,EAAEuD,gBAAgB,kBACjH,CA8CWoF,CAAO1F,EAAWjM,EAAM4P,GAC5B5D,EAAQC,EAAWjM,EAAMkQ,GAC9BlQ,EAAK8H,SACDoI,IAGFxF,EAAMwB,GAAQA,GACd0F,eAAe,KACbtE,IACA5C,EAAMwB,GAAQ,OAGpB,CC9pBgC2F,CAAQ7L,GAClCqH,IAAOrH,EAAQgK,IDuRd,WACL,IAAM8B,EAAIC,WACVD,EAAEvH,GAAQ,CAAEd,QAAO,KAAAuI,GAAUlM,EAAM,CAAG,QAEnB,IAAfgM,EAAElQ,KACJkQ,EAAElQ,GAAW,CAAEqQ,SAAU,mBAAoBhS,QAAS,EAAGwJ,MAAQC,GAAkBoI,EAAEvH,GAAMd,MAAMC,GAAMsI,MAAO,IAAMF,EAAEvH,GAAMyH,SAEhI,CC5RIE,GAEAxH,EAAMyH,GAAOrL,EAAM4D,EAAMyH,GAAM3Q,GAC/B,QAAWsJ,KAAKsH,IAAc5Q,EAAUsJ,EAC1C,GAEKuH,GAAQrS","ignoreList":[]}
@@ -1 +1,2 @@
1
- import{a as t,c as e}from"../chunks/chunk-2EGTC36Y.js";import{a as n,b as r,c as s,d as i,e as o,j as l}from"../chunks/chunk-V34ZHCK5.js";var a={},u=/\.\d/,h=new Set(Object.getOwnPropertyNames(Object.prototype)),f=0,c=!1,p=null,d=()=>{c=!1,f++};function m(){if(null===p)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=d,t.port1.unref?.(),p=()=>t.port2.postMessage(0)}else p=()=>setTimeout(d,0);return c||(c=!0,p()),f}function g(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.Q){for(let r of e)if(n.ee(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var y=class{constructor(t,e){this.active=!1,this.Ge=new Map,this.n=0,this.Ao=-1,this.Bn=new Set,this._e=null,this.engine=t,this.ct=e}ur(){let t=this.engine;this.Ge.clear();for(let e of this.ct)e.getter=null!==e.p.getter||e.p.se,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(a,t.v(e.p,null)):this.Mn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0}prime(t,e){try{e()}catch(e){console.error(`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`,e),n.st?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}Fo(){this.active=!1,this.Ge.clear()}Mn(t,e,n,r){let s=this.engine.We(n,t.h[e]);for(let n of s.f)e===t.n?r(n):this.Mn(t,e+1,n,r)}un(t,e,n,r){let s=this.Ge.get(t);void 0===s&&this.Ge.set(t,s=new Map);let i=s.get(e);void 0===i?s.set(e,[n,this.n,r]):(i[1]<this.n&&(i[1]=this.n),i[2]||=r)}be(t,e,n,r,s){if(this.active){(this._e??=new Set).add(t);for(let i of this.ct){let o=i.p;o.n!==t.n||!o.ee(t)||this.un(i,e,i.getter?i.s.get(e??a):o===t&&s&&this.engine.Wt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ve(t,e){if(this.active)for(let n of this.ct)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===t.n&&n.p.ee(t)&&this.un(n,e,n.s.get(e??a),!1)}Jt(t,e){if(!this.active)return;let n=null;for(let r of this.ct){let s=r.p;if(!(s.n<t.n||s.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(s.n===t.n?this.un(r,e,void 0,!0):this.Mn(s,t.n+1,e,t=>this.un(r,t,void 0,!0)))}}}Fe(){let t=this._e;if(this._e=null,!this.active||0===this.Ge.size)return;let e=this.Ge;this.Ge=new Map;let r=this.engine,s=[];for(let i of this.ct){let o=e.get(i);if(void 0===o)continue;let l,h=[...o].filter(([t])=>null===t||t.y);h.length>1&&h.sort((t,e)=>$(t[0],e[0]));for(let[e,[o,f,c]]of h){let h,p="evaluate",d=r.u;this.n=f+1,r.Pe++;try{if(h=r.v(i.p,e),i.getter&&(i.s.set(e??a,h),Object.is(h,o)&&(u.test(i.t)||null!==e&&!c&&!(l??=null!==t&&g(v(i.p),t)))))continue;if(f>32){s.includes(i.t)||s.push(i.t);continue}r.u=e,n.st?.(r,{type:"state:watch-fired",path:i.t}),p="handler",i.handler.call(r.proxy,h,o,...r.H(e))}catch(t){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,t),n.st?.(r,{type:"state:watch-error",phase:p,path:i.t,error:t})}finally{r.u=d,this.n=0,r.Pe--}}}s.length>0&&this.Oo(s)}Oo(t){let e=m();e!==this.Ao&&(this.Ao=e,this.Bn.clear());let r=t.filter(t=>!this.Bn.has(t));if(0!==r.length){for(let t of r)this.Bn.add(t);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.st?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function v(t){for(;null===t.getter&&null!==t.d;)t=t.d;return t}function $(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.ae)n.unshift(e.b);for(let t=e;null!==t;t=t.l.ae)r.unshift(t.b);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var b="$streamStatus",w="$streamError",O=new Set(Object.getOwnPropertyNames(Object.prototype)),j=!1;function B(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var J=class{constructor(t,e,n){this.engine=t,this.entries=e,this.B=n}set(t,e,n){j=!0;try{this.engine.T(this.engine.o(`${t}.${e}`),null,n)}finally{j=!1}}dr(){for(let t of this.entries)this.start(t,!0)}fr(){for(let t of this.entries)t.ut=!1,t.J?.abort(),t.J=null}pr(){for(let t of this.entries)t.ut=!1,null!==t.J&&(t.J.abort(),t.J=null),this.set(b,t.name,"idle")}ve(t){let e=this.B.n;for(let n of this.entries)n.g===t&&(n.n=n.ut?Math.max(n.n,e):e,n.ut=!0)}Fe(){let t=this.engine,n=this.B,r=[];for(let s of this.entries){if(!s.ut)continue;let i=s.n;if(s.ut=!1,i>32)r.push(s.name),s.g.z=e;else{n.n=i+1,t.Pe++;try{this.start(s,!1)}finally{t.Pe--,n.n=0}}}r.length>0&&n.Oo(r)}start(t,n){let r,s=this.engine;if(null!==t.J&&t.J.abort(),t.J=null,null!==t.g){let i=t.g;i.getter=t.args;let o=i.Q.slice();k(i);try{r=s.read(i,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&l(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Q)n.n>0&&l(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${b}.${t}`||n.t===`${w}.${t}`)&&l(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,i,r)}catch(r){k(i);for(let t of o)t._n(i);if(i.z=e,n)throw r;return this.set(w,t.name,r),void this.set(b,t.name,"error")}}let i=new AbortController;t.J=i,s.T(s.o(t.name),null,t.U),this.set(w,t.name,null),this.set(b,t.name,"active"),this.mr(t,i,r)}async mr(t,e,n){let r=this.engine,s=e.signal,i=()=>!s.aborted&&t.J===e,o=r.o(t.name),l=this.B.n,a=m(),u=t=>{m()===a&&(this.B.n=l);try{t()}finally{this.B.n=0}},h=t.U;try{let e=await t.source(n,s);if(!i())return;let l=e=>{h=void 0!==t.Co?t.Co(h,e):e,u(()=>r.T(o,null,h))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(s.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!i())return;if(e.done)break;l(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(s.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!i())return;if(e.done)break;l(e.value)}}}if(!i())return;t.J=null,u(()=>this.set(b,t.name,"done"))}catch(n){if(!i())return;t.J=null,e.abort(),u(()=>{this.set(w,t.name,n),this.set(b,t.name,"error")})}}};function k(e){for(let t of e.Q){let n=t.M.indexOf(e);n>=0&&t.M.splice(n,1),t.pt.delete(e)}e.Q.length=0,e.z=t}var M=new WeakMap;function S(t){let e=M.get(t);return e?.target===t.target?e:void 0}function A(t,e){let r=new y(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&l("$watch must be an object mapping paths to handler functions.");let r=[];for(let s of Object.keys(e)){let i=e[s];(""===s||"$"===s[0]||s.includes("@")||h.has(s))&&l(`$watch path "${s}" is not a path of the state tree.`),"function"!=typeof i&&l(`$watch entry "${s}" must be a function.`);let o=t.o(s);n.So?.(t,o,!0),r.push({t:s,p:o,handler:i,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),s=new J(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&l("$stream must be an object mapping stream names to definitions.");let r=[],s={},i={};for(let o of Object.keys(n)){let a=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||O.has(o))&&l(`$stream entry "${o}" must be a flat property name.`),(null===a||"object"!=typeof a)&&l(`$stream entry "${o}" must be an object.`);let u=a.source,h=a.fold,f=a.args,c=a.initial;"function"!=typeof u&&l(`$stream entry "${o}" needs a source function.`),void 0!==h&&"function"!=typeof h&&l(`$stream entry "${o}": fold must be a function.`),void 0!==h&&!("initial"in a)&&l(`$stream entry "${o}": fold needs an initial value.`),void 0!==f&&"function"!=typeof f&&l(`$stream entry "${o}": args must be a function.`),B(e,o)&&l(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===e[o]&&(e[o]=c),s[o]="idle",i[o]=null,r.push({name:o,source:u,Co:h,U:c,J:null,ut:!1,n:0,g:void 0===f?null:t.o(`$streamArgs.${o}`),args:void 0===f?null:function(){return f(this)}})}return e[b]=s,e[w]=i,r}(t,e),r),i=M.get(t);void 0!==i&&(i.B.Fo(),i.Ot.fr()),M.set(t,{B:r,Ot:s,Xe:i?.Xe??!1,target:e})}function C(t,e){let n=M.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Xe="connected"===e),n.target===t.target)){if("disconnected"===e)return n.B.Fo(),void n.Ot.pr();n.Xe&&(n.B.ur(),n.Ot.dr())}}var F=["$streamStatus","$streamError"],G={name:"temporal",install(){n.de=r(n.de,A),n.element=r(n.element,C),n.be=r(n.be,(t,e,n,r,s,i)=>S(t)?.B.be(e,n,r,s,i)),n.ve=r(n.ve,(t,e,n)=>{let r=S(t);void 0!==r&&(r.B.ve(e,n),r.Ot.ve(e))}),n.Jt=r(n.Jt,(t,e,n)=>S(t)?.B.Jt(e,n)),n.Fe=r(n.Fe,t=>{let e=S(t);void 0!==e&&(e.B.Fe(),e.Ot.Fe())}),n.ot=s(o,n.ot,(t,e)=>{let n=e.split(".",1)[0];if(F.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Ae=s(i,n.Ae,(t,e)=>(!j&&36===e.t.charCodeAt(0)&&F.includes(e.t.split(".",1)[0])&&l(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},P=G;export{P as default,G as temporal};
1
+ import{a as t,c as e}from"../chunks/chunk-ZN52NEIB.js";import{a as n,b as r,c as s,d as i,e as o,j as l}from"../chunks/chunk-4NJBYXIT.js";var a={},u=/\.\d/,h=new Set(Object.getOwnPropertyNames(Object.prototype)),f=0,c=!1,p=null,d=()=>{c=!1,f++};function m(){if(null===p)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=d,t.port1.unref?.(),p=()=>t.port2.postMessage(0)}else p=()=>setTimeout(d,0);return c||(c=!0,p()),f}function g(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.J){for(let r of e)if(n.ee(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var y=class{constructor(t,e){this.active=!1,this.Ge=new Map,this.n=0,this.Ao=-1,this.Bn=new Set,this._e=null,this.engine=t,this.ct=e}ur(){let t=this.engine;this.Ge.clear();for(let e of this.ct)e.getter=null!==e.p.getter||e.p.se,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(a,t.v(e.p,null)):this.Mn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0}prime(t,e){try{e()}catch(e){console.error(`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`,e),n.st?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}Fo(){this.active=!1,this.Ge.clear()}Mn(t,e,n,r){let s=this.engine.We(n,t.h[e]);for(let n of s.f)e===t.n?r(n):this.Mn(t,e+1,n,r)}un(t,e,n,r){let s=this.Ge.get(t);void 0===s&&this.Ge.set(t,s=new Map);let i=s.get(e);void 0===i?s.set(e,[n,this.n,r]):(i[1]<this.n&&(i[1]=this.n),i[2]||=r)}be(t,e,n,r,s){if(this.active){(this._e??=new Set).add(t);for(let i of this.ct){let o=i.p;o.n!==t.n||!o.ee(t)||this.un(i,e,i.getter?i.s.get(e??a):o===t&&s&&this.engine.Wt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ve(t,e){if(this.active)for(let n of this.ct)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===t.n&&n.p.ee(t)&&this.un(n,e,n.s.get(e??a),!1)}Qt(t,e){if(!this.active)return;let n=null;for(let r of this.ct){let s=r.p;if(!(s.n<t.n||s.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(s.n===t.n?this.un(r,e,void 0,!0):this.Mn(s,t.n+1,e,t=>this.un(r,t,void 0,!0)))}}}Fe(){let t=this._e;if(this._e=null,!this.active||0===this.Ge.size)return;let e=this.Ge;this.Ge=new Map;let r=this.engine,s=[];for(let i of this.ct){let o=e.get(i);if(void 0===o)continue;let l,h=[...o].filter(([t])=>null===t||t.y);h.length>1&&h.sort((t,e)=>$(t[0],e[0]));for(let[e,[o,f,c]]of h){let h,p="evaluate",d=r.u;this.n=f+1,r.Pe++;try{if(h=r.v(i.p,e),i.getter&&(i.s.set(e??a,h),Object.is(h,o)&&(u.test(i.t)||null!==e&&!c&&!(l??=null!==t&&g(v(i.p),t)))))continue;if(f>32){s.includes(i.t)||s.push(i.t);continue}r.u=e,n.st?.(r,{type:"state:watch-fired",path:i.t}),p="handler",i.handler.call(r.proxy,h,o,...r.H(e))}catch(t){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,t),n.st?.(r,{type:"state:watch-error",phase:p,path:i.t,error:t})}finally{r.u=d,this.n=0,r.Pe--}}}s.length>0&&this.Oo(s)}Oo(t){let e=m();e!==this.Ao&&(this.Ao=e,this.Bn.clear());let r=t.filter(t=>!this.Bn.has(t));if(0!==r.length){for(let t of r)this.Bn.add(t);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.st?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function v(t){for(;null===t.getter&&null!==t.d;)t=t.d;return t}function $(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.ae)n.unshift(e.b);for(let t=e;null!==t;t=t.l.ae)r.unshift(t.b);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var b="$streamStatus",w="$streamError",O=new Set(Object.getOwnPropertyNames(Object.prototype)),j=!1;function B(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var Q=class{constructor(t,e,n){this.engine=t,this.entries=e,this.B=n}set(t,e,n){j=!0;try{this.engine.T(this.engine.o(`${t}.${e}`),null,n)}finally{j=!1}}dr(){for(let t of this.entries)this.start(t,!0)}fr(){for(let t of this.entries)t.ut=!1,t.Q?.abort(),t.Q=null}pr(){for(let t of this.entries)t.ut=!1,null!==t.Q&&(t.Q.abort(),t.Q=null),this.set(b,t.name,"idle")}ve(t){let e=this.B.n;for(let n of this.entries)n.g===t&&(n.n=n.ut?Math.max(n.n,e):e,n.ut=!0)}Fe(){let t=this.engine,n=this.B,r=[];for(let s of this.entries){if(!s.ut)continue;let i=s.n;if(s.ut=!1,i>32)r.push(s.name),s.g.z=e;else{n.n=i+1,t.Pe++;try{this.start(s,!1)}finally{t.Pe--,n.n=0}}}r.length>0&&n.Oo(r)}start(t,n){let r,s=this.engine;if(null!==t.Q&&t.Q.abort(),t.Q=null,null!==t.g){let i=t.g;i.getter=t.args;let o=i.J.slice();k(i);try{r=s.read(i,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&l(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.J)n.n>0&&l(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${b}.${t}`||n.t===`${w}.${t}`)&&l(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,i,r)}catch(r){k(i);for(let t of o)t._n(i);if(i.z=e,n)throw r;return this.set(w,t.name,r),void this.set(b,t.name,"error")}}let i=new AbortController;t.Q=i,s.T(s.o(t.name),null,t.U),this.set(w,t.name,null),this.set(b,t.name,"active"),this.mr(t,i,r)}async mr(t,e,n){let r=this.engine,s=e.signal,i=()=>!s.aborted&&t.Q===e,o=r.o(t.name),l=this.B.n,a=m(),u=t=>{m()===a&&(this.B.n=l);try{t()}finally{this.B.n=0}},h=t.U;try{let e=await t.source(n,s);if(!i())return;let l=e=>{h=void 0!==t.Co?t.Co(h,e):e,u(()=>r.T(o,null,h))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(s.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!i())return;if(e.done)break;l(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(s.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!i())return;if(e.done)break;l(e.value)}}}if(!i())return;t.Q=null,u(()=>this.set(b,t.name,"done"))}catch(n){if(!i())return;t.Q=null,e.abort(),u(()=>{this.set(w,t.name,n),this.set(b,t.name,"error")})}}};function k(e){for(let t of e.J){let n=t.M.indexOf(e);n>=0&&t.M.splice(n,1),t.pt.delete(e)}e.J.length=0,e.z=t}var M=new WeakMap;function S(t){let e=M.get(t);return e?.target===t.target?e:void 0}function A(t,e){let r=new y(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&l("$watch must be an object mapping paths to handler functions.");let r=[];for(let s of Object.keys(e)){let i=e[s];(""===s||"$"===s[0]||s.includes("@")||h.has(s))&&l(`$watch path "${s}" is not a path of the state tree.`),"function"!=typeof i&&l(`$watch entry "${s}" must be a function.`);let o=t.o(s);n.So?.(t,o,!0),r.push({t:s,p:o,handler:i,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),s=new Q(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&l("$stream must be an object mapping stream names to definitions.");let r=[],s={},i={};for(let o of Object.keys(n)){let a=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||O.has(o))&&l(`$stream entry "${o}" must be a flat property name.`),(null===a||"object"!=typeof a)&&l(`$stream entry "${o}" must be an object.`);let u=a.source,h=a.fold,f=a.args,c=a.initial;"function"!=typeof u&&l(`$stream entry "${o}" needs a source function.`),void 0!==h&&"function"!=typeof h&&l(`$stream entry "${o}": fold must be a function.`),void 0!==h&&!("initial"in a)&&l(`$stream entry "${o}": fold needs an initial value.`),void 0!==f&&"function"!=typeof f&&l(`$stream entry "${o}": args must be a function.`),B(e,o)&&l(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===e[o]&&(e[o]=c),s[o]="idle",i[o]=null,r.push({name:o,source:u,Co:h,U:c,Q:null,ut:!1,n:0,g:void 0===f?null:t.o(`$streamArgs.${o}`),args:void 0===f?null:function(){return f(this)}})}return e[b]=s,e[w]=i,r}(t,e),r),i=M.get(t);void 0!==i&&(i.B.Fo(),i.Ot.fr()),M.set(t,{B:r,Ot:s,Xe:i?.Xe??!1,target:e})}function F(t,e){let n=M.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Xe="connected"===e),n.target===t.target)){if("disconnected"===e)return n.B.Fo(),void n.Ot.pr();n.Xe&&(n.B.ur(),n.Ot.dr())}}var P=["$streamStatus","$streamError"],G={name:"temporal",install(){n.de=r(n.de,A),n.element=r(n.element,F),n.be=r(n.be,(t,e,n,r,s,i)=>S(t)?.B.be(e,n,r,s,i)),n.ve=r(n.ve,(t,e,n)=>{let r=S(t);void 0!==r&&(r.B.ve(e,n),r.Ot.ve(e))}),n.Qt=r(n.Qt,(t,e,n)=>S(t)?.B.Qt(e,n)),n.Fe=r(n.Fe,t=>{let e=S(t);void 0!==e&&(e.B.Fe(),e.Ot.Fe())}),n.ot=s(o,n.ot,(t,e)=>{let n=e.split(".",1)[0];if(P.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Ae=s(i,n.Ae,(t,e)=>(!j&&36===e.t.charCodeAt(0)&&P.includes(e.t.split(".",1)[0])&&l(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},C=G;export{C as default,G as temporal};
2
+ //# sourceMappingURL=temporal.js.map