@wcstack/state 3.5.4 → 4.0.0-rc.2

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 (82) hide show
  1. package/README.ja.md +669 -428
  2. package/README.md +667 -426
  3. package/dist/auto.min.js +1 -2
  4. package/dist/define.d.ts +4 -8
  5. package/dist/define.js +1 -1
  6. package/dist/index.d.ts +139 -1483
  7. package/dist/index.esm.js +1 -2
  8. package/dist/manifest.d.ts +18 -59
  9. package/dist/manifest.esm.js +542 -1202
  10. package/dist/parser.d.ts +49 -103
  11. package/dist/parser.esm.js +662 -831
  12. package/dist/split/auto.js +1 -0
  13. package/dist/split/chunks/chunk-732CB4QN.js +1 -0
  14. package/dist/split/chunks/chunk-7PN5YNZZ.js +1 -0
  15. package/dist/split/chunks/chunk-FF6KHTYS.js +1 -0
  16. package/dist/split/chunks/chunk-HFKGUDDJ.js +1 -0
  17. package/dist/split/chunks/chunk-PKDBVBAP.js +1 -0
  18. package/dist/split/chunks/chunk-QI7P7YPP.js +1 -0
  19. package/dist/split/chunks/chunk-QQH6N5CJ.js +1 -0
  20. package/dist/split/chunks/chunk-UM3O6QXD.js +1 -0
  21. package/dist/split/chunks/chunk-WEL3YSG7.js +1 -0
  22. package/dist/split/chunks/chunk-WWJNAZVP.js +1 -0
  23. package/dist/split/chunks/chunk-YOPPVWPQ.js +1 -0
  24. package/dist/split/core.d.ts +114 -1168
  25. package/dist/split/core.js +1 -2
  26. package/dist/split/features/devtools.d.ts +23 -3
  27. package/dist/split/features/devtools.js +1 -2
  28. package/dist/split/features/diagnostics.d.ts +27 -5
  29. package/dist/split/features/diagnostics.js +1 -2
  30. package/dist/split/features/formats.d.ts +21 -5
  31. package/dist/split/features/formats.js +1 -2
  32. package/dist/split/features/list-keys.d.ts +24 -0
  33. package/dist/split/features/list-keys.js +1 -0
  34. package/dist/split/features/recursion.d.ts +23 -3
  35. package/dist/split/features/recursion.js +1 -2
  36. package/dist/split/features/scopes.d.ts +25 -4
  37. package/dist/split/features/scopes.js +1 -2
  38. package/dist/split/features/ssr.d.ts +23 -3
  39. package/dist/split/features/ssr.js +1 -2
  40. package/dist/split/features/temporal.d.ts +19 -4
  41. package/dist/split/features/temporal.js +1 -2
  42. package/dist/wcs-manifest.json +43 -49
  43. package/package.json +15 -17
  44. package/dist/auto.min.js.map +0 -1
  45. package/dist/index.esm.js.map +0 -1
  46. package/dist/split/chunks/binder.js +0 -2
  47. package/dist/split/chunks/binder.js.map +0 -1
  48. package/dist/split/chunks/checkDependency.js +0 -2
  49. package/dist/split/chunks/checkDependency.js.map +0 -1
  50. package/dist/split/chunks/declarationAliases.js +0 -2
  51. package/dist/split/chunks/declarationAliases.js.map +0 -1
  52. package/dist/split/chunks/declarationHooks.js +0 -2
  53. package/dist/split/chunks/declarationHooks.js.map +0 -1
  54. package/dist/split/chunks/diagnosticsHooks.js +0 -2
  55. package/dist/split/chunks/diagnosticsHooks.js.map +0 -1
  56. package/dist/split/chunks/errorGuidance.js +0 -2
  57. package/dist/split/chunks/errorGuidance.js.map +0 -1
  58. package/dist/split/chunks/featureBridge.js +0 -2
  59. package/dist/split/chunks/featureBridge.js.map +0 -1
  60. package/dist/split/chunks/features.d.ts +0 -29
  61. package/dist/split/chunks/filterRegistry.js +0 -2
  62. package/dist/split/chunks/filterRegistry.js.map +0 -1
  63. package/dist/split/chunks/getAllPropertyDescriptors.js +0 -2
  64. package/dist/split/chunks/getAllPropertyDescriptors.js.map +0 -1
  65. package/dist/split/chunks/lifecycleHooks.js +0 -2
  66. package/dist/split/chunks/lifecycleHooks.js.map +0 -1
  67. package/dist/split/chunks/pathDiagnostics.js +0 -2
  68. package/dist/split/chunks/pathDiagnostics.js.map +0 -1
  69. package/dist/split/chunks/registerComponents.js +0 -2
  70. package/dist/split/chunks/registerComponents.js.map +0 -1
  71. package/dist/split/chunks/setAll.js +0 -2
  72. package/dist/split/chunks/setAll.js.map +0 -1
  73. package/dist/split/chunks/version.js +0 -2
  74. package/dist/split/chunks/version.js.map +0 -1
  75. package/dist/split/core.js.map +0 -1
  76. package/dist/split/features/devtools.js.map +0 -1
  77. package/dist/split/features/diagnostics.js.map +0 -1
  78. package/dist/split/features/formats.js.map +0 -1
  79. package/dist/split/features/recursion.js.map +0 -1
  80. package/dist/split/features/scopes.js.map +0 -1
  81. package/dist/split/features/ssr.js.map +0 -1
  82. package/dist/split/features/temporal.js.map +0 -1
@@ -1,2 +1 @@
1
- import{r as t,l as e,a as n,C as o}from"../chunks/lifecycleHooks.js";import{k as r,l as s,a,m as i,D as c,V as l,n as u,W as d,g as f,o as h,R as p,p as m,i as g,q as y,r as w}from"../chunks/pathDiagnostics.js";import{r as $,d as b}from"../chunks/errorGuidance.js";import{r as v,g as k,N as P}from"../chunks/getAllPropertyDescriptors.js";import{c as S}from"../chunks/filterRegistry.js";import{n as x}from"../chunks/declarationAliases.js";import{q as I,u as j,t as C,v as N,w as M,j as A,i as O,x as R,y as E,z as W,A as K,B as L,C as D,D as B,E as z,F as T,o as F,G as V,H as q,I as G,J as _,K as H,L as U,M as X}from"../chunks/binder.js";import{a as J,r as Q}from"../chunks/featureBridge.js";import{p as Y}from"../chunks/diagnosticsHooks.js";import{g as Z,a as tt,c as et}from"../chunks/checkDependency.js";const nt={written:function(t,e,n){const o=t.bindableEventMap,r=o[e.path],s="string"==typeof r,a=s?r:e.segments.length>1&&-1===e.path.indexOf("#")?o[e.segments[0]]:void 0;if("string"!=typeof a)return;const i=t.rootNode;i instanceof ShadowRoot&&i.host.dispatchEvent(new CustomEvent(a,{detail:s&&void 0!==n?n.value:void 0,bubbles:!0}))}};let ot=!1;function rt(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function st(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function at(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function it(t){return t.startsWith("$")}function ct(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function lt(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||$(`${e} must be an array of strings.`);const o=[],r=new Set;for(const t of n)"string"==typeof t&&0!==t.length||$(`${e} entries must be non-empty strings.`),t.startsWith("$")&&$(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),r.has(t)&&$(`${e} entry "${t}" is duplicated.`),r.add(t),o.push(t);return o}function ut(t){x(t);const e=lt(t,r)??[],n=lt(t,s)??[],o=k(t),i=function(t){const e=t[a];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];for(const t of e){const e=o[t];if(void 0===e){if(i.has(t)){c.push(t);continue}$(`${r} entry "${t}" is not declared on the state.${b(t,ct(o,"value"))}`)}"function"==typeof e.value&&$(`${r} entry "${t}" is a method. Declare it in ${s} instead.`)}for(const t of n){const e=o[t];void 0===e&&$(`${s} entry "${t}" is not declared on the state.${b(t,ct(o,"method"))}`),"function"!=typeof e.value&&$(`${s} entry "${t}" is not a method. Declare it in ${r} instead.`)}return{bindables:e,commands:n,streamBackedBindables:c}}function dt(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||$(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const s=I(t);null!==s&&"function"==typeof s.define||$(`DCC: CustomElementRegistry is unavailable for "${o}".`),s.get(o)&&$(`DCC: "${o}" is already registered. A custom element name can only be defined once.`);const a=document.createElement("template"),c=a.content.ownerDocument;for(const t of Array.from(e.childNodes))a.content.appendChild(c.importNode(t,!0));const l=e.mode,{bindables:u,commands:d,streamBackedBindables:f}=ut(n),h=u.length>0||d.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const r=n.map(t=>({name:t,async:!0}));return{...o,commands:r}}(o,u,d):null,p=u.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,u):{},m=S.tagNames.state,g=class extends HTMLElement{static template=a;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=p;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(i))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const t=I(this._shadow);return null!==t&&j(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(g.bindableEventMap).length>0){const e=t.querySelector(m);e?(ot||(ot=!0,v("dcc",nt)),e.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${r} but its template has no <${S.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(m)??null}},y=k(n);for(const[t,e]of Object.entries(y)){if(it(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=at(t,o)}else n.get=rt(t),n.set=st(t);Object.defineProperty(g.prototype,t,n)}for(const t of f)Object.defineProperty(g.prototype,t,{configurable:!0,enumerable:!0,get:rt(t),set:st(t)});s.define(o,g)}async function ft(t,o,r){const s=t;try{s.hasAttribute("bind-component")&&$(`"bind-component" cannot be used inside a [${i}] host. DCC state comes from the template, not from a component property.`);const a=await async function(t,o){if(t.hasAttribute("src")){const n=t.getAttribute("src");if(n.endsWith(".js"))return await e(n);$(`DCC: Unsupported src type: ${n}`)}const r=t.querySelector('script[type="module"]');if(r)return await n(r,o.tagName.toLowerCase());$(`DCC: No state source found for "${o.tagName.toLowerCase()}".`)}(s,o);dt(o,r,a),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}const ht={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(i)?ft(t,e.host,e):null}};let pt=!1;function mt(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function gt(t,e){for(const n of t)if(mt(e,n.innerSegments))return n;return null}function yt(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+c+n.join(c)}const wt=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function $t(t,e,n){const o=wt.get(t);return void 0===o?null:(...t)=>{const r=t.slice();for(let t=0;t<o.length;t++){const n=o[t];"string"==typeof r[n]&&(r[n]=e(r[n]))}return n(r)}}const bt=new WeakMap;function vt(t,e,n){let o=bt.get(t);void 0===o&&(o=new Map,bt.set(t,o));const r=o.get(e);null!=r&&$(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function kt(t,e){if(null===t)return!1;const n=bt.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+c)||t.startsWith(e+c))return!0;return!1}const Pt=new WeakMap;const St=[];function xt(t,e,n,o){if(e.length>0){const r=n.split(c),s=gt(e,r);if(null!==s)return o&&s.readonly&&$(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${l}.${s.innerSegments.join(c)}#${u}: ${s.outerPathInfo.path}"). Write "${s.outerPathInfo.path}" on the root, or drop #${u} from the injection.`),yt(s,r)}return t+c+n}function It(t,e,n){let o=-1,r=null;for(const t of e){const e=t.outerPathInfo.path;e.length<=o||(n===e?(o=e.length,r=t.innerSegments.join(c)):n.startsWith(e+c)&&(o=e.length,r=t.innerSegments.join(c)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+c))return n.slice(t.length+1)}return r}function jt(t,e,n=St){return new Proxy({},{get(o,r){if("string"==typeof r&&"then"!==r){if("$"===r[0]){if("$postUpdate"===r||"$getAll"===r){const o=r;return(r,...s)=>e[o](xt(t,n,r,!1),...s)}if("$setAll"===r)return(o,...r)=>e.$setAll(xt(t,n,o,!0),...r);if("$resolve"===r)return(o,...r)=>e.$resolve(xt(t,n,o,r.length>1),...r);const o=$t(r,e=>xt(t,n,e,!1),t=>e[r](...t));return null!==o?o:e[r]}return e[xt(t,n,r,!1)]}},set:(o,r,s)=>"string"!=typeof r||("$"===r[0]?(e[r]=s,!0):(e[xt(t,n,r,!0)]=s,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Ct=new WeakMap,Nt=[];const Mt=new WeakMap,At=new WeakSet;function Ot(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let Rt=null;let Et=0;const Wt=["$watch",a,"$scan","$listKeys",h,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Kt=new Set;function Lt(t,e,n){const o=t.stateObject[e];if("function"==typeof o)try{const r=o.call(n());r instanceof Promise&&r.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function Dt(t,e,n,o,r,s=new Set){0===n.length&&$(`Cannot build a mount record without host bindings for "${e}".`),x(r);const a=[],i=new Set;let l=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(c);i.has(n)&&$("Duplicate mapping rule for web component."),i.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(u)};a.push(o),0===e.length&&(l=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const d=++Et,f=`#m${d}`,{getterKeys:h,setterKeys:p}=function(t){const e=new Set,n=new Set,o=k(t);for(const[t,r]of Object.entries(o))"function"==typeof r.get&&e.add(t),"function"==typeof r.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(r),m=new Set;for(const t of a)1===t.innerSegments.length&&m.add(t.innerSegments[0]);const g={};for(const t of Object.keys(r))t.startsWith("$")||h.has(t)||p.has(t)||"function"!=typeof r[t]&&(s.has(t)||m.has(t)||(g[t]=r[t]));return{id:d,marker:f,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?f:l.outerPathInfo.path+c+f,stateObject:r,getterKeys:h,setterKeys:p,injectedKeys:s,mappedKeys:m,hasReadonlyEntries:a.some(t=>t.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Bt(t){const e=t.indexOf(c);return-1===e?t:t.slice(0,e)}function zt(t,e){const n=gt(t.entries,e);return null===n?null:yt(n,e)}function Tt(t,e){return t.markerBasePath+c+e}function Ft(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const s=e+c+n;r.set(n,{accessorName:o,indexShift:f(s).wildcardCount-f(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(s),t.addedGetterPaths.add(s))}function Vt(t,e){return!t.injectedKeys.has(e)&&(!t.getterKeys.has(e)&&"function"==typeof t.stateObject[e]||!t.mappedKeys.has(e)&&(Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e)))}function qt(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(c)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${Bt(e)}: path") or declare the key on the component state.`}const Gt=/^\$(\d+)$/;function _t(t,e){if(!t.hasReadonlyEntries)return null;const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=Bt(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||Vt(t,o))return null;const r=function(t,e){return gt(t.entries,e)}(t,e.split(c));return null!==r&&r.readonly?r:null}function Ht(t,e){const n=_t(t,e);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);$(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${u}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${u} from the mount.`)}return Ut(t,e)}function Ut(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(c);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===d){o=t;break}if(-1===o)return Ft(t,t.markerBasePath,e,e),Tt(t,e);if(Vt(t,n[0]))return Ft(t,t.markerBasePath,e,e),Tt(t,e);const r=n.slice(0,o+1),s=n.slice(o+1),a=zt(t,r);null===a&&$(qt(t,e)),0===s.length&&$(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const i=a+c+t.marker;return Ft(t,i,s.join(c),e),i+c+s.join(c)}(t,e);const o=Bt(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return Tt(t,e);if(Vt(t,o))return Tt(t,e);const r=zt(t,e.split(c));if(null!==r)return r;$(qt(t,e))}const Xt=new Set(["prop","radio","checkbox"]);function Jt(t,e,n){let o;const r=Gt.exec(e.statePathName);if(null!==r){const s=function(t,e){if(void 0===e)return t.delta;const n=Ut(t,e);return f(n).wildcardCount-f(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(r[1])+s}`}else if(o=Ut(t,e.statePathName),"for"===e.bindingType){const n=f(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+c+d,n)}const s=e.propModifiers,a=null===r&&Array.isArray(s)&&Xt.has(e.bindingType??"")&&!s.includes(u)&&null!==_t(t,e.statePathName);return o!==e.statePathName||a?{...e,statePathName:o,statePathInfo:f(o),...a?{propModifiers:[...s,u]}:{}}:e}function Qt(t,e,n,o,r){if(void 0===o)return;const s=f(n).wildcardCount-f(e).wildcardCount;return 0===s?o:(r.length<s&&$(`Cannot resolve "${e}" from this mount: the mounted prefix has ${s} wildcard(s) but the host context provides only ${r.length} index(es).`),[...r.slice(0,s),...o])}function Yt(t,e,n){if(-1!==t.indexOf(d))return e;const o=e.split(c);let r=0;for(let t=0;t<o.length&&r<n.length;t++)o[t]===d&&(o[t]=String(n[r++]));return o.join(c)}const Zt=new WeakMap,te=new WeakMap;const ee=new WeakMap;const ne=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),oe=new WeakMap;function re(t){return oe.get(t)??null}let se=!1;function ae(t,e){se||(se=!0,C(t=>Zt.has(t)?t.host:null)),Zt.set(t,e),oe.set(e,t);let n=ee.get(e.parentStateElement);void 0===n&&(n=new Map,ee.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=te.get(e.component);void 0===o&&(o=new Map,te.set(e.component,o));const r=o.get(e.stateProp)!==e;o.set(e.stateProp,e),r&&ne.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}function ie(t){return Zt.get(t)??null}function ce(t){return le(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(c),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function le(t){const e=ee.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function ue(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=ee.get(t);if(void 0===o)return null;const r=e.indexOf(c,n),s=-1===r?e.slice(n):e.slice(n,r),a=o.get(s);if(void 0===a)return null;const i=a.deref();return void 0===i?(o.delete(s),null):i}const de=new WeakMap,fe=new Set;function he(t,e,n,o){let r=de.get(t);if(void 0===r){if(!o)return null;r=new Map,de.set(t,r)}let s=r.get(e);if(void 0===s){if(!o)return null;s=new Map,r.set(e,s)}let a=s.get(n);if(void 0===a){if(!o)return null;a={holders:new Set,byListIndex:new WeakMap,noIndex:null},s.set(n,a)}return a}function pe(t,e){if(!t.component.isConnected)return!1;const n=N(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function me(t,e,n,o){const r=he(t,e,n,!1);if(null===r)return null;const s=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==s){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&pe(n,e)?n:null}(s,o);if(null!==t)return{record:t,entry:s.entry}}let a=null,i=null;for(const t of r.holders){const s=t.ref.deref();void 0!==s?pe(s,o)&&(null!==i&&$(`[wcs/mount-export-ambiguous] "${e}${c}${n}" is exported by two mounted components on the same instance: <${i.component.tagName.toLowerCase()}> and <${s.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=t,i=s):r.holders.delete(t)}return null===a||null===i?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:i,entry:a.entry})}function ge(t){const e=t.parentStateElement,n=N(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[M](n,()=>{t.$postUpdate(o.exportedPath)})})}const ye=new WeakMap,we=new WeakMap,$e=new WeakMap,be=new WeakMap;function ve(t,e){we.set(t,e);const n=[];for(let t=e?.listIndex.parentListIndex??null;null!==t;t=t.parentListIndex)n.push(t);be.set(t,n)}function ke(t){return N(t.component)??we.get(t)??null}function Pe(t){return ke(t)?.listIndex??null}function Se(t){$(`The host row of <${t.component.tagName.toLowerCase()}> was removed.`)}function xe(t){for(;null!==t;t=t.parentListIndex)if(O(t))return!0;return!1}function Ie(t,e){return!t.component.isConnected&&(xe(e)||!0===be.get(t)?.some(t=>O(t)))}class je{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(t,e,n,o,r,s,a,i=!1){this.record=t,this.markerParentPath=e,this.listIndex=n,this.hostRow=o,this.isBase=r,this.receiver=s,this.handler=a,this.authorFacing=i}authorThis(t,e){return this.authorFacing?e:new Proxy(t,new je(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return A(f(this.markerParentPath+c+t),this.listIndex)}hostIndexes(){const t=this.listIndex??Pe(this.record),e=this.hostRow??t;return(null===this.listIndex?e!==t||Ie(this.record,e):xe(e))&&Se(this.record),e?.indexes??[]}resolveTreePath(t,e){return-1===e.indexOf(d)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Z(e).wildcardType&&!Ie(this.record,this.listIndex)?e:Yt(t,e,this.hostIndexes())}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(this.resolveTreePath(t,Ut(this.record,t)))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.hostIndexes(),o=this.receiver,r=this.handler,s=this.listIndex;if("$resolve"===e)return(e,r,...s)=>{const a=s.length>0?Ht(t,e):Ut(t,e),i=Qt(0,e,a,r??[],n);return o.$resolve(a,i,...s)};const a=e;return(e,i,...c)=>{const l="$setAll"===a?Ht(t,e):Ut(t,e),u=Qt(0,e,l,void 0===i&&"$getAll"===a&&null===s&&null===tt(r,f(l).wildcardPaths[0])?[]:i,n);return o[a](l,u,...c)}}const t=this.record,n=this.receiver,o=$t(e,e=>this.resolveTreePath(e,Ut(t,e)),t=>n[e](...t));return null!==o?o:this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return et(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(this.authorThis(t,n))}return this.receiver[this.resolveTreePath(e,Ut(this.record,e))]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const r=this.accessorNameFor(e);if(void 0!==r){this.record.setterKeys.has(r)||$(`Cannot write to "${r}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,r,n,this.authorThis(t,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(t,e)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(A(f(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+c+e]=n}finally{this.handler.popAddress()}return!0}return t[e]=n,!0}return this.receiver[this.resolveTreePath(e,Ht(this.record,e))]=n,!0}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return Ut(this.record,e),!0}catch{return!1}}}function Ce(t,e,n,o){const r=e.pathInfo.path,s=r===t.markerBasePath,a=s?function(t,e){let n=ye.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},ye.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(a,new je(t,r,e.listIndex,e.listIndex??Pe(t),s,n,o))}function Ne(t){if(null===Pe(t))return t.component[t.stateProp];let e=$e.get(t);if(void 0===e){const n={row:null};$e.set(t,e=[Me(t,n),n])}return e[0]}function Me(t,e){const n=()=>{const n=ke(t);return void 0!==e&&$e.get(t)?.[0]!==a&&n.listIndex!==e.row&&Se(t),n},o=()=>{const e=n();return Ie(t,e?.listIndex??null)&&Se(t),e?.listIndex.indexes??[]},r=(e,n)=>-1===n.indexOf(d)?n:"partial"===Z(n).wildcardType?Yt(e,n,o()):-1===n.indexOf("#")&&Ie(t,Pe(t))?Se(t):n,s=(e,o)=>{let r;const s=n();return t.parentStateElement.createState(e,t=>{r=t[M](s,()=>o(t))}),r},a=new Proxy({},{get(e,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(t,e,n,o,r){return"$postUpdate"===e?e=>n("readonly",n=>n.$postUpdate(r(e,Ut(t,e)))):(r,s,...a)=>{const i="$setAll"===e||"$resolve"===e&&a.length>0,c=i?Ht(t,r):Ut(t,r),l=Qt(0,r,c,"$resolve"===e?s??[]:s,o());return n(i?"writable":"readonly",t=>t[e](c,l,...a))}}(t,n,s,o,r);const a=$t(n,e=>r(e,Ut(t,e)),t=>s("readonly",e=>e[n](...t)));if(null!==a)return a;const i=e=>e["$"===n[0]?n:r(n,Ut(t,n))],c=s("readonly",i);return"$"===n[0]||t.getterKeys.has(n)||"function"!=typeof t.stateObject[n]?c:function(...t){return s("writable",e=>i(e).apply(this,t))}},set:(e,n,o)=>("string"==typeof n&&s("writable",e=>{e["$"===n[0]?n:r(n,Ht(t,n))]=o}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return Ut(t,n),!0}catch{return!1}}});return a}function Ae(t,e){const n=ie(e);null!==n&&n.stateProp!==t.stateProp&&$(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&function(t){const e=E(t);e.dispose();const n=[],o=document.createTreeWalker(t);for(;o.nextNode();)e.handleAddedNode(o.currentNode,n,t=>{console.error("[@wcstack/state] a binding failed to start again on the mount scope's re-initialization.",t)});R(n)}(e),ae(e,t),e instanceof ShadowRoot&&K(e,t.parentStateElement),function(t,e,n){const o=(e,n)=>Jt(t,e,n);D(e,n?t=>function(t,e){for(let n=t;n!==e;n=n.parentNode)if(T(n))return!0;return!1}(t,e):void 0);const r=N(t.component);ve(t,r);const s=e instanceof ShadowRoot?e:e.getRootNode();B(s,e,void 0,o),z(e,r,o)}(t,e,null!==n),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=Ut(t,n)}catch{continue}const o=e.indexOf(c+t.marker);if(-1===o)continue;const r=e.slice(0,o+1+t.marker.length),s=e.slice(r.length+1),a=e.slice(0,o)+c+s,i=f(a);if(i.wildcardCount!==t.delta)continue;const l={markerTerminalPath:r,suffix:s,markerPath:e,exportedPath:a};t.exports.set(a,l),he(t.parentStateElement,i.parentPath,i.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:l}),t.parentStateElement.addDynamicDependency(e,a),Y?.markExported(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=N(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const r=`${n}|${o.exportedPath}`;if(fe.has(r))continue;const s=f(o.exportedPath);let a;t.parentStateElement.createState("readonly",t=>{t[M](e,()=>{a=t[s.parentPath]})}),null!=a&&s.lastSegment in Object(a)&&(fe.add(r),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" 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.`))}}(t),ge(t),L(e,Promise.resolve())}function Oe(t,e){const n=Re(t,e).rebindAddresses();R(n),ge(t)}function Re(t,e){const n=E(e),o=N(t.component);return ve(t,o),n.forEachActiveBindingNode(t=>W(t,o)),n}function Ee(t){for(let e=t.parentNode;null!==e;e=e.parentNode){const t=ie(e);if(null!==t)return Ee(t.component),void Re(t,e)}}function We(t,e){if(function(t){const e=ee.get(t);return void 0!==e&&e.size>0}(e))for(const n of le(e)){if(!Ke(n.component,t))continue;const e=re(n);null!==e&&Oe(n,e)}}function Ke(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const Le={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const r=ue(t,e.pathInfo.path);if(null!==r)return Ce(r,e,n,o)}return P},readMissing(t,e,n,o,r){if(null===n){if(kt(t.rootNode??null,e.pathInfo.path))return;return P}if(!0===t.hasMounts){const n=me(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r){const s=Ce(t,A(f(e.markerTerminalPath),n),o,r);return Reflect.get(s,e.suffix)}(n.record,n.entry,e.listIndex,o,r)}return P},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=Pt.get(t);if(void 0===n||0===n.size)return null;const o=e+c;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&$(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return P},writeMissing(t,e,n,o,r,s,a){if(!0===t.hasMounts){const n=me(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r,s){const a=Ce(t,A(f(e.markerTerminalPath),n),r,s);return Reflect.set(a,e.suffix,o)}(n.record,n.entry,e.listIndex,r,s,a)}return P},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=ue(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(c,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),s=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(s);return void 0!==a?a.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,r){if(!0!==t.hasMounts)return r;const s=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=Zt.get(n);if(void 0!==t)return t;n=n.parentNode}return Zt.get(e)??null}(e,n);if(null===s)return r;const a=s.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==a?r-a:0},updated(t,e,n){const o=function(t){return Ct.get(t)??Nt}(t);for(const r of o){const o=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const a=It(r.mountPath,r.injections,e);if(null===a||""===a)continue;o.add(a);const i=n.absolutePathInfo.pathInfo.wildcardCount;if(i>0&&null!==n.listIndex){const t=F(n.listIndex,i);(s[a]??=[]).push(t)}}if(o.size>0)try{r.callback.call(jt(r.mountPath,n,r.injections),Array.from(o),s)}catch(t){console.error(`[@wcstack/state] volume "${r.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>kt(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){We(e,t)}};let De=!1;const Be=new WeakMap;function ze(t){let e=Be.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Be.set(t,e)),e}function Te(t,e){null!==e.slotRootNode&&(!function(t,e,n){const o=bt.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function Fe(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{vt(n,o,t)}catch{return console.error(`[@wcstack/state] <${S.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return V(n)?.markHasVolume?.(),e.slotRootNode=n,!0}async function Ve(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");let s;try{!function(t){0===t.length&&$('"mount" requires a non-empty tree path.');const e=f(t);for(const n of e.segments)0===n.length&&$(`"mount" path "${t}" has an empty segment.`),n===d&&$(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&$(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),s=function(t,e){const n=[],o=new Set;let r;try{r=U(t)}catch(t){$(`[wcs/mount-path-invalid] <${S.tagNames.state} mount="${e}"> has an invalid ${S.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==l)continue;const r=t.propSegments.slice(1),s=t.statePathInfo,a=n=>$(`[wcs/mount-path-invalid] <${S.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==d&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${l}.<key>: path"); change "mount" to move the whole volume.`),(s.wildcardCount>0||"$"===s.path[0]||"#"===s.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==u)&&a(`an injection accepts only #${u}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:s,readonly:t.propModifiers.includes(u)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(S.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&$('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${S.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),vt(o,r,t),V(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===V(o)&&function(t,e){const n=()=>{if(null!==V(t))return;const n=t.querySelectorAll(S.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${S.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${S.tagNames.state}> to this root node (an empty <${S.tagNames.state}></${S.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&Te(t,e),t.settleInitialization()};let i;try{await Promise.resolve(),i=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const c=t.connectedRootNode??null;null!==c&&Fe(t,e,c)?function(t,e,n,o,r,s,a=[]){const i={mountPath:n,volumeState:o,injections:a,onGrafted:r,acquireSlot:s};if(null!==e)return void wn(e,i);bn(),function(t,e){if(At.has(t))return void Ot(e);let n=Mt.get(t);void 0===n&&(n=[],Mt.set(t,n)),n.push(e)}(t,i)}(c,V(c),r,i,a,()=>Fe(t,e,c),s):a(null)}const qe={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=ze(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{vt(n,e.mountPath,t),V(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,o}return Ve(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=ze(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&V(n)===e.graftInfo.rootStateElement&&mn(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==Be.get(t)?.initializing)return;const e=t.getAttribute("mount");$(`Cannot replace the state of <${S.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){At.add(t);const e=Mt.get(t);if(void 0!==e){Mt.delete(t);for(const t of e)Ot(t)}}(e)},initializeFailureCleared(t,e){!function(t){At.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=ze(t);return null!==e.graftInfo&&mn(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,Te(t,e)),t.clearConnectedRootNode(),!0}};let Ge=!1;const _e=new WeakMap;function He(t,e){let n=_e.get(t);n||(n=new Set,_e.set(t,n)),n.add(e)}const Ue=new WeakMap;const Xe=new WeakMap,Je=new WeakMap;const Qe=new WeakMap;const Ye={isComplete:function(t,e){return!0===_e.get(t)?.has(e)},isDeclared:function(t,e){return!0===Ue.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=Xe.get(t);o||(o=new Map,Xe.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=Je.get(t);o||(o=new Map,Je.set(t,o));let r=o.get(e);r||(r=new Set,o.set(e,r)),r.add(n)},rememberOverwrittenValue:function(t,e,n,o){let r=Qe.get(t);r||(r=new Map,Qe.set(t,r));let s=r.get(e);s||(s=new Map,r.set(e,s)),s.has(n)||s.set(n,o)}};function Ze(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}const tn=new WeakMap;class en{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=tn.get(t);return n?n.get(e)??null:null}(t,e)??$("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const nn=t=>()=>t;function on(t,e,n,o){!function(t,e,n){let o=tn.get(t);o||(o=new Map,tn.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(Ze(o));const r=function(t,e){const n=new en(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:nn(r),enumerable:!0,configurable:!0}),He(e,n),rn(e,n)}function rn(t,e){if(m in t){const n=t[m];"function"==typeof n?n.call(t,e).catch(t=>{$(`Error in ${m}: ${t instanceof Error?t.message:String(t)}`)}):$(`${m} is not a function.`)}}const sn=new Set;function an(t,e){sn.has(t)||(sn.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function cn(t){!function(t){const e=t.component.tagName.toLowerCase(),n=t.stateProp;let o=null;for(const r of t.entries){if(0===r.innerSegments.length)continue;const s=r.innerSegments[0];o??=k(t.stateObject);const a=o[s];let i;if(t.getterKeys.has(s)||t.setterKeys.has(s)||"function"==typeof a?.get||"function"==typeof a?.set)i="an accessor";else if("function"==typeof a?.value)i="a method";else{if(t.mappedKeys.has(s)||t.injectedKeys.has(s)||!Object.prototype.hasOwnProperty.call(t.stateObject,s))continue;i="an own data key"}const l=r.innerSegments.join(c);an(`${e}|${n}|${l}|entry`,`<${e}>.${n} declares "${s}" as ${i}, which hides the mounted entry "${n}.${l}: ${r.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(t);const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let r,s=!1;for(const a of e){if(null===t.rootEntry)continue;if(s||(r=ln(t),s=!0),"object"!=typeof r||null===r||!(a in r))continue;const e=t.rootEntry.outerPathInfo.path;an(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${e}.${a}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}function ln(t){const e=t.rootEntry,n=N(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[M](n,()=>{o=t[e.outerPathInfo.path]})}),o}const un=new WeakMap;function dn(t,e){t.landInitialization(),$(e)}async function fn(t,e){const n=t;if(n.hasAttribute("bind-component")){const s=n.parentNode,a=s instanceof ShadowRoot?s.host:s instanceof Element?s:null,i=a?_(a):null;null!==a&&null!==i||$(`"bind-component" requires <${S.tagNames.state}> to be a direct child of a custom element.`),s instanceof ShadowRoot||a.hasAttribute(S.bindAttributeName)||dn(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&$(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const l=n.getAttribute("bind-component");!function(t,e){let n=Ue.get(t);n||(n=new Set,Ue.set(t,n)),n.add(e)}(a,l);const u=I(a);null===u&&$(`CustomElementRegistry is unavailable for <${i}>.`);const d=t.connectGeneration;if(await u.whenDefined(i.toLowerCase()),a.hasAttribute(S.bindAttributeName)&&await H(a),t.connectGeneration!==d)return!0;l in a||$(`Component does not have property "${l}" for state binding.`);let f=a[l];"object"==typeof f&&null!==f||$(`Component property "${l}" is not an object for state binding.`);const h=function(t,e){const n=Xe.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,l);if(void 0!==h&&function(t,e){if(!t.hasAttribute(S.bindAttributeName))return!1;const n=q(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,l)&&(a[l]=h,f=h),e.boundComponent=a,e.boundComponentStateProp=l,t.setBoundComponent(a,l),s instanceof ShadowRoot||(q(a)??[]).some(t=>t.propSegments[0]===l)||dn(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (data-wcs="${l}: path").`),a.hasAttribute(S.bindAttributeName)){const c=(q(a)??[]).filter(t=>t.propSegments[0]===l);if(c.length>0){const u=V(a.getRootNode())??dn(t,`No state tree found on this root for mount host <${i}>.`);let d=(o=a,r=l,te.get(o)?.get(r)??null);const h=null!==d;if(null===d&&(!function(t,e,n){const o=Qe.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Qe.get(t).delete(e)}}(a,l,f),d=Dt(a,l,c,u,f,function(t,e){return Je.get(t)?.get(e)}(a,l)),cn(d)),e.mountRecord=d,n.parentNode!==s)return!1;try{Ae(d,s instanceof ShadowRoot?s:a)}catch(e){throw t.landInitialization(),e}if(!h){const t=Me(d);Object.defineProperty(a,l,{get:()=>t,enumerable:!0,configurable:!0}),He(a,l)}return rn(a,l),function(t){const e=Wt.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(p)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Kt.has(n)||(Kt.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(d),Lt(d,"$connectedCallback",()=>Ne(d)),!1}}on(t,e.boundComponent,e.boundComponentStateProp,f)}var o,r;return!1}const hn={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=un.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},un.set(t,e)),e}(t);return fn(t,e).then(n=>!!n||null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=un.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&Oe(n,o)}),t.isConnected&&(Ee(n.component),Re(n,o)),Lt(n,"$connectedCallback",()=>Ne(n)),!0},disconnecting(t){const e=un.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord;return Lt(n,"$disconnectedCallback",()=>Ne(n)),function(t){const e=$e.get(t);void 0!==e&&(e[1].row=Pe(t),$e.delete(t))}(n),ge(e.mountRecord),t.clearConnectedRootNode(),!0}};let pn=!1;function mn(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const r=n.call(jt(t.mountPath,o,t.injections));r instanceof Promise&&r.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function gn(t,e,n,o){const r=n[g];if(void 0!==r){const n=Q(e),s=[],a=new Set;let i=0;for(const[n,c]of Object.entries(r)){const r=xt(e,o,n,!1),l=function(t,n,...r){c.call(jt(e,this,o),t,n,...r)};s.push({path:r,pathInfo:f(r),handler:l,order:1e6+i++}),a.add(r),t.setPathInfo(r,"prop","watch")}s.length>0&&(n.addEntries(t,s),t.addVolumeWatchPaths?.(a),n.start(t))}const s=n[y];if(void 0!==s){const n=new Map;for(const[t,r]of Object.entries(s))n.set(xt(e,o,t,!1),r);t.mergeVolumeListKeys?.(n)}const a=n[h];"function"==typeof a&&(!function(t,e){let n=Ct.get(t);void 0===n&&(n=[],Ct.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:a}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}function yn(t,e,n,o=[]){x(n),function(t,e,n,o){const r=0===o.length?null:k(n);for(const t of o){const n=t.innerSegments[0],o=r[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||$(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${l}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const s=n[g];if(void 0!==s){"object"==typeof s&&null!==s||$(`${g} must be an object mapping state paths to handler functions.`);const t=Q(e);for(const[e,n]of Object.entries(s))"function"!=typeof n&&$(`${g} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[y];if(void 0!==i){"object"==typeof i&&null!==i||$(`${y} must be an object mapping list paths to key specs.`);for(const[n,r]of Object.entries(i)){(0===n.length||"string"!=typeof r&&"function"!=typeof r)&&$(`${y} entry "${n}" must map a list path to a field name or a key function.`);const s=xt(e,o,n,!1);t.listKeys?.has(s)&&$(`${y} entry "${s}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[a]&&$(`Volume "${e}" declares ${a}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&$(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[w]&&$(`Volume "${e}" declares ${w}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(k(n)))-1!==t.indexOf(p)&&$(`Volume "${e}" declares "${t}", which uses "${p}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:r,accessors:s}=function(t,e){const n={},o=new Map;for(const[r,s]of Object.entries(k(t)))r.startsWith("$")||e.has(r)||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(n[r]=s.value):o.set(r,s));return{data:n,accessors:o}}(n,new Set(o.map(t=>t.innerSegments[0]))),i=f(e),u=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(u)return;$(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],r=""===n?o in t:void 0!==t[n+c+o];n=""===n?o:n+c+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(u)return;$(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=r}),function(t,e){let n=Pt.get(t);void 0===n&&(n=new Set,Pt.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,r]of s){const s=e+c+n,a=r.get,i=r.set,l={enumerable:!1,configurable:!0};"function"==typeof a&&(l.get=function(){return a.call(jt(e,this,o))}),"function"==typeof i&&(l.set=function(t){i.call(jt(e,this,o),t)}),t.defineTreeAccessor(s,l)}gn(t,e,n,o);const d=n.$connectedCallback;return"function"==typeof d&&t.createState("writable",t=>{let n;try{n=d.call(jt(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function wn(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=yn(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let $n=!1;function bn(){$n||($n=!0,De||(De=!0,v("scopes",Le),J(ce)),Ge||(Ge=!0,t("scopes",qe)),pn||(pn=!0,t("bindComponent",hn),G(Ye)),Rt=wn,X(vn))}function vn(t,e){(function(t){const e=bt.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){At.delete(t);const n=Mt.get(t);if(void 0===n||0===n.length||null===Rt)return;Mt.delete(t);const o=Rt;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const kn={name:"scopes",install(){bn(),pt||(pt=!0,t("dcc",ht))}};export{kn as default,kn as scopes};
2
- //# sourceMappingURL=scopes.js.map
1
+ import{a as e,c as t}from"../chunks/chunk-PKDBVBAP.js";import{b as n,n as o,o as l}from"../chunks/chunk-7PN5YNZZ.js";import"../chunks/chunk-HFKGUDDJ.js";import{e as r,f as i}from"../chunks/chunk-UM3O6QXD.js";import{a}from"../chunks/chunk-732CB4QN.js";import"../chunks/chunk-QI7P7YPP.js";import"../chunks/chunk-QQH6N5CJ.js";import"../chunks/chunk-WWJNAZVP.js";import{a as s,b as u,c,d,f,h,j as p}from"../chunks/chunk-YOPPVWPQ.js";var m=new WeakMap,g=new WeakMap,$=new WeakMap,w="will not graft: the root state failed to initialize.",b=new WeakSet,y=new WeakMap,v=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],k=["$commandTokens","$eventTokens","$on","$errorCallback"],N=e=>`[@wcstack/state] <${a.tagNames.state} mount="${e}">`,j=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),O=e=>e?.element?.isConnected?e:void 0;function P(e){let t=$.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function C(e,t){m.set(t,e);let n=$.get(t);if($.delete(t),Array.isArray(n))for(let t of n)M(t,e)}function A(e,t){console.error(`${N(e.t)} ${t}`),function(e){let t=g.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}(e),e.Xe?.(),e.Xe=null}function x(e,t){let n=e.state?.[t];if("function"==typeof n)try{let t=n.call(e.chroot);null!==t&&"object"==typeof t&&"function"==typeof t.then&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}}function M(e,t){if(b.has(t))return A(e,"will not graft: its component is wired to its host.");let n=e.state,o=t.target,l=e.t.split("."),r=o;for(let e of l)r=r?.[e];if(void 0!==r&&!0!==t.hydrated)return A(e,`will not graft: the root state already has "${e.t}".`);let i=function(e,t){let n=e=>`${t}.${e}`;return new Proxy({},{get(t,o){if("symbol"==typeof o)return;if(36!==o.charCodeAt(0))return e.proxy[n(o)];let l=e.proxy[o];return"$eqPath"===o?(e,t)=>l(n(e),n(t)):j.has(o)&&"function"==typeof l?(e,...t)=>l(n(e),...t):l},set:(t,o,l)=>"symbol"!=typeof o&&(e.proxy[n(o)]=l,!0)})}(t,e.t);e.chroot=i;let a={},s={},u=new Set;for(let t=n;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let n of Object.getOwnPropertyNames(t)){if(u.has(n)||"constructor"===n)continue;u.add(n);let{get:o,set:l,value:r}=Object.getOwnPropertyDescriptor(t,n);if(void 0!==o||void 0!==l)s[`${e.t}.${n}`]={get:o&&function(){return o.call(i)},set:l&&function(e){l.call(i,e)}};else{if("$"===n[0])continue;if("function"==typeof r){let t=r.bind(i);s[`${e.t}.${n}`]={get:()=>t}}else a[n]=r}}if(void 0===r){for(let e=1;e<l.length;e++){let n=t.o(l.slice(0,e).join("."));null==t.zt(n,null)&&t.P(n,null,{})}t.P(t.o(e.t),null,a)}t.Gn(Object.defineProperties({},s));for(let e in s)t.Ee(t.o(e),null);e.engine=t;let c=y.get(t);void 0===c&&y.set(t,c=[]),c.push(e.t),e.el.isConnected&&x(e,"$connectedCallback"),e.Xe?.(),e.Xe=null}function S(e,t){let n=$.get(e);if(Array.isArray(n))for(let e of n)A(e,w);$.set(e,t)}var W=new WeakMap;function D(e,t){let n=e.getAttribute("mount");if(null===n)return null;let l={el:e,root:t,t:n,state:null,engine:null,chroot:null,Xe:null},r=null;if(function(e){return""!==e&&e.split(".").every(e=>""!==e&&!/[*$#@\s]/.test(e))}(n))if(e.hasAttribute(a.bindAttributeName))r='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=g.get(t);void 0===e&&g.set(t,e=new Map);let o=e.get(n);if(void 0!==o&&o!==l&&(null===o.engine?o.el.isConnected:O(o.engine)))r=`will not graft: another volume already holds "${n}".`;else{if(null===o?.engine){let e=$.get(t);Array.isArray(e)&&$.set(t,e.filter(e=>e!==o)),o.Xe?.(),o.Xe=null}e.set(n,l)}}else r='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{vo:!0,start(e){if(null!==r)return A(l,r);if(g.get(t).get(n)===l){for(let t of v)if(void 0!==e[t])return A(l,`${t} is not run in a volume — declare it on the root state.`);for(let t of k)void 0!==e[t]&&console.warn(`${N(n)} ${t} is not run in a volume (it belongs to the root).`);return l.state=e,new Promise(e=>{l.Xe=e;let n=O(m.get(t))??O(o.get(t)),r=$.get(t);void 0!==n?M(l,n):P(t)?A(l,w):$.set(t,[...Array.isArray(r)?r:[],l])})}},qe(){null!==l.engine&&x(l,"$connectedCallback")},On(){null!==l.engine&&x(l,"$disconnectedCallback")},reset(){p(`re-setting a volume is not supported: its data was copied into the root tree at "${n}" — write the paths under it on the root instead.`)}}}var Q=new WeakMap,E=new WeakMap;function R(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||p(`${t} must be an array of state member names.`);let o=new Set;for(let e of n)("string"!=typeof e||""===e)&&p(`${t} entries must be non-empty strings.`),"$"===e[0]&&p(`${t} entry "${e}": internal ($) members are never exposed.`),o.has(e)&&p(`${t} entry "${e}" is duplicated.`),o.add(e);return n}function q(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let o=document.createDocumentFragment();for(let e of[...t.childNodes])o.appendChild(e.cloneNode(!0));let l=t.mode;return{start(t){e.hasAttribute("bind-component")&&p("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,o){e.includes("-")||p(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&p(`DCC: <${e}> is already defined.`);let l=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(o),r=R(o,"$bindables"),i=R(o,"$commands");for(let e of r){let t=l.get(e);void 0===t&&p(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&p(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of i){let t=l.get(e);void 0===t&&p(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&p(`$commands entry "${e}" is not a method: list it in $bindables.`)}let s={tag:e,bindables:r},u=new WeakMap,c=new WeakMap,d=o=>{if(u.has(o))return u.get(o);if(o.hasAttribute("data-wc-definition"))return null;let l=o.attachShadow({mode:n});l.appendChild(t.cloneNode(!0));let i=l.querySelector(a.tagNames.state);return u.set(o,i),Q.set(o,s),null===i&&r.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${a.tagNames.state}>: no change events.`),i},f=e=>d(e)?.engine??null,h=e=>Promise.resolve(d(e)?.initializePromise).then(()=>{let t=c.get(e);c.delete(e);let n=f(e);if(void 0!==t&&null!==n)for(let[e,o]of t)n.proxy[e]=o});class m extends HTMLElement{static{this.wcBindable=0===r.length&&0===i.length?null:{protocol:"wc-bindable",version:1,properties:r.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:r.map(e=>({name:e})),...0===i.length?{}:{commands:i.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==d(this)&&h(this)}get stateElement(){return d(this)}}for(let[e,t]of l)"function"==typeof t.value?Object.defineProperty(m.prototype,e,{configurable:!0,value(...t){return h(this).then(()=>{let n=f(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(m.prototype,e,{configurable:!0,get(){return f(this)?.proxy[e]},set(t){let n=f(this);if(null!==n)n.proxy[e]=t;else{let n=c.get(this);void 0===n&&c.set(this,n=[]),n.push([e,t])}}});customElements.define(e,m)}(n.localName,o,l,t)},qe(){},On(){},reset(){p("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var X=new WeakMap,z=new WeakSet,I=new WeakMap,Z=new WeakMap,B="data-wcs-wired",F=new WeakMap,J=new WeakMap,K=new WeakMap,T=0,Y=new Set,U={},V=["$watch","$stream","$renderedCallback"],G=e=>e.split(".",1)[0];function H(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function L(e,t){let n=e.a,o=G(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(B);else if(!ee(n,o)){let e=n.getAttribute(B)?.split(" ")??[];e.includes(o)||n.setAttribute(B,[...e,o].join(" "))}F.get(n)?.ce===o&&p(`<${n.localName}>.${o} has loaded its state: the wiring "${e.name}" added afterwards cannot reach it — bind the host's wiring before the component loads.`);let l=X.get(n);void 0===l&&X.set(n,l=[]),l.push(e),t&&z.add(e);let r=I.get(n);return void 0===r&&I.set(n,r=new Map),r.has(o)||r.set(o,n[o]),Z.get(n)?.(),!1}function _(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${a.tagNames.state}[bind-component]`)}function ee(e,t){let n=e.getAttribute(a.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}var te=new Set;function ne(e,t){te.has(e)||(te.add(e),console.warn(`[@wcstack/state] ${t}`))}var oe=(e,t)=>t in e.state;function le(e,t){let n=re(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function re(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function ie(e,t,n){if(null!==n.getter)return;let o,l=e.host,i=l.engine,a=G(n.t),s=l.entries.find(e=>e.$===n.t);if(void 0===s&&null!==n.w)return function(e,t){let n,o=t.w;for(;null!==o&&void 0===(n=e.st.get(o));)o=o.w;if(null===o||void 0===n)return;let l=e.N,i=e.host.engine,a=i.o(n.p.t+t.t.slice(o.t.length));if(null===a.getter)return;let s=n,u=()=>{let n=ae(e,s.r);return 0===t.n?n:(i.resolve(H(a.t,[...i.D(n),...l.D(r(l.h,t.n))]),null),i.rr)};t.getter=()=>{let e=u();return a.n>0&&null===e?void 0:i.v(a,e)},null!==a.Z&&(t.Z=n=>{let o=u();se(e,s.e,()=>i.P(a,o,n)),e.an=t}),t.n>0&&(t.A=l.Oe++),e.st.set(t,{e:s.e,p:a,r:s.r})}(e,n);if(0!==n.n)return;if(void 0!==s){if(s.$!==a?oe(l,a):le(l,a))return;o=s.ue}else{if(null===t||null!==n.w||"$"===a[0]||oe(l,a))return;s=t,o=i.o(`${t.ue.t}.${a}`)}let u=s.r,c=s;n.getter=()=>i.v(o,ae(e,u)),n.Z=t=>{se(e,c,()=>i.P(o,u,t)),e.an=n},e.st.set(n,{e:s,p:o,r:u})}function ae(e,t){return null!==t&&!t.d&&p(`The host row of <${e.host.el.localName}> was removed.`),t}function se(e,t,n){let o=Y.has(e.N);Y.add(e.N),e.from=t;try{n()}finally{o||Y.delete(e.N),e.from=null}}var ue=(e,t)=>t||!Y.has(e.m.N)||null!==e.m.from&&e.m.from!==e.e;function ce(e,t){if(e.cn===t||null===e.host.engine)return;e.cn=t,T+=t?1:-1;let n=e.host.engine,o=K.get(n);void 0===o&&K.set(n,o=new Map);for(let n of e.se){let e=o.get(n.e.ue);void 0===e&&o.set(n.e.ue,e=new Map);let l=e.get(n.e.r);void 0===l&&e.set(n.e.r,l=new Set),t?l.add(n):(l.delete(n),0===l.size&&e.delete(n.e.r))}let l=e.host.entries.find(e=>""===e.$);if(void 0!==l){null===e.Q&&function(e,t){let n=e.host,o=n.engine;e.Q=new Map;let l=new Set;for(let r=n.state;null!==r&&r!==Object.prototype;r=Object.getPrototypeOf(r))for(let i of Object.getOwnPropertyNames(r)){if(l.has(i))continue;l.add(i);let a=Object.getOwnPropertyDescriptor(r,i);if(void 0===a.get&&void 0===a.set||"$"===i[0]||i.includes("*"))continue;let s=G(i);if(i!==s&&!oe(n,s))continue;let u=o.o(`${t.ue.t}.${i}`);if(null===u.getter)he(o,u,t.ue);else if(!de.has(u.getter))continue;e.Q.set(u,e.N.o(i))}}(e,l);for(let o of e.Q.keys())t&&null===o.getter&&he(n,o,l.ue),n.R.Ne(n,o,l.r);e.Q.size>0&&n.xe(),t&&function(e,t){let n=e.host.engine;for(let[o,l]of e.Q){let r=n.v(o.w,t.r);if(null===r||"object"!=typeof r||!(o.l in r))continue;let i=e.host.el.localName;ne(`${i}|${o.t}`,`[wcs/mount-export-shadowed] <${i}>.${e.host.ce}.${l.t} is exported at "${o.t}" 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.`)}}(e,l)}}var de=new WeakSet;function fe(e,t,n,o){let l=K.get(e)?.get(t)?.get(n);if(void 0===l)return null;let r=null;for(let e of l)""!==e.e.$||!0!==e.m.Q?.has(o)||e.m===r||(null!==r&&p(`[wcs/mount-export-ambiguous] "${o.t}" is exported by two mounted components on the same instance: <${r.host.el.localName}> and <${e.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),r=e.m);return r}function he(e,t,n){let o=t.w,l=t.l,r=()=>{let t=e.read(o,e.h);return null!==t&&"object"==typeof t&&l in t?t:null};t.getter=()=>{let o=r();if(null!==o)return o[l];let i=fe(e,n,e.h,t);return null===i?void 0:i.N.read(i.Q.get(t),null)},de.add(t.getter),t.Z=i=>{let a=null===r()?fe(e,n,e.h,t):null;if(null===a){let t=e.read(o,e.h);return void(null!==t&&"object"==typeof t&&(t[l]=i))}let s=a.Q.get(t);void 0===re(a.host.state,s.t)?.set&&p(`Cannot write to "${s.t}" on mounted <${a.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),a.N.P(s,null,i)},t.n>0&&(t.A=e.Oe++)}function pe(e,t,n,o,l,r){if(null!==t.getter)return e.R.Ne(e,t,n),void e.xe();if("*"===t.l){if(null===n)return;if(n.O=n.s.G[n.b],e.R.Vt(n),null!==n.u)for(let t of n.u.values())e.U(t)}else e.wn(t,n);s.pe?.(e,t,n,o,l,r),e.Ee(t,n)}function me(e){let t=e.m.N;for(let[n,o]of e.m.st)o.e===e.e&&(0===n.n?t.R.Ne(t,n,null):t.Jt(n.c[n.n],e=>t.R.Ne(t,n,e)));t.xe()}function ge(e,t,n,o,l,i,a){let s=n.t.slice(t.t.length);if(""===s)return me(e);let u,c=e.m,d=c.N;if(""===e.e.$){u=s.slice(1);let e=G(u);if("$"===e[0]||oe(c.host,e)||c.host.entries.some(e=>""!==e.$&&(u===e.$||u.startsWith(`${e.$}.`))))return}else u=e.e.$+s;let f=[];for(let e=t.n+1;e<=n.n;e++)f.push(r(o,e).b);d.resolve(H(u,f),null);let h=d.rp,p=d.rr;h.n>0&&null===p||pe(d,h,p,l,i,a)}function $e(e,t,n,o,l,i,a){if(0===T)return;let s=Y.has(e);Y.add(e);try{let s=J.get(e);!a&&void 0!==s&&s.cn&&!Y.has(s.host.engine)&&function(e,t,n,o,l,r){let i,a=t;for(;null!==a&&void 0===(i=e.st.get(a));)a=a.w;if(null===a||void 0===i)return;let s=e.host.engine;if(a===t&&e.an===t)return void(e.an=null);if(null!==i.r&&!i.r.d)return;let u=[...s.D(i.r),...e.N.D(n)];s.resolve(H(i.p.t+t.t.slice(a.t.length),u),null);let c=s.rp,d=s.rr;c.n>0&&null===d||se(e,i.e,()=>pe(s,c,d,o,l,r))}(s,t,n,o,l,i),a&&void 0!==s&&s.cn&&null!==s.Q&&function(e,t){let n=e.host.entries.find(e=>""===e.$),o=e.host.engine;for(let[l,r]of e.Q)r===t&&(o.R.Ne(o,l,n.r),o.xe())}(s,t);let u=K.get(e);if(void 0===u)return;for(let[e,s]of u)if(t.Y(e)){let u=s.get(0===e.n?null:r(n,e.n));if(void 0!==u)for(let r of[...u])ue(r,a)&&ge(r,e,t,n,o,l,i)}else if(e.Y(t))for(let[e,o]of[...s])if(0===t.n||r(e,t.n)===n)for(let e of[...o])ue(e,a)&&me(e)}finally{s||Y.delete(e)}}async function we(e,t){ce(e,!0);for(let t of e.se)me(t);t?.(),!e.broken&&(await e.N.ae("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&s.element?.(e.N,"connected"))}function be(r,u){let c=r.getAttribute("bind-component");if(null===c)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=o.get(t)?.element;if(!(e.K||void 0!==n&&n!==e&&n.isConnected)){S(t,e);for(let e of W.get(t)??[])e()}}),null}(r,u);let d=r.parentNode,f=d instanceof ShadowRoot,m=f?d.host:d instanceof Element?d:null,g=()=>{let e=null===m?void 0:F.get(m)?.F;return e?.el===r?e:null},$=e=>{throw f&&S(d,r),e};return{dt:()=>(null!==m&&m.localName.includes("-")?async function(e,t,o,l){let r=o.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&p(`<${a.tagNames.state} bind-component> takes its state from <${r}>.${t}: it cannot also load one (state / src / json / an inline script).`),await n(o).whenDefined(r);let i=F.get(o);if(void 0!==i)return i.ce!==t&&p(`<${r}> already has a <${a.tagNames.state} bind-component="${i.ce}">.`),i.state;let s=()=>(X.get(o)??[]).filter(e=>G(e.name)===t);if(0===s().length&&(ee(o,t)||((e,t)=>!0===e.getAttribute(B)?.split(" ").includes(t))(o,t))){let e;await new Promise((n,l)=>{Z.set(o,n),e=function(e,t){P(e)&&t();let n=W.get(e)??new Set;return W.set(e,n.add(t)),()=>n.delete(t)}(o.getRootNode(),()=>l(new Error(`[@wcstack/state] <${r}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}Z.delete(o);let u=s(),c=I.get(o),d=void 0!==c&&c.has(t)?c.get(t):o[t];if((null===d||"object"!=typeof d)&&p(`"bind-component": <${r}>.${t} must be an object (the component's state), got ${null===d?"null":typeof d}.`),0===u.length&&l){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${r}>, or mount it from the host (${a.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),U}let f=[];for(let e of u){let n=e.name===t?"":e.name.slice(t.length+1);f.some(e=>e.$===n)&&p(`<${r}> maps "${e.name}" twice.`);let l=n.split(".").indexOf("*");if(l>=0){let o=n.split(".").slice(0,l).join(".");p(`<${r}> maps "${e.name}": the component-side path of a mount cannot contain "*"${""===o?"":` — map the list itself ("${t}.${o}: <the host's list>")`}.`)}f.push({$:n,ue:e.o,r:e.r,ro:z.has(e)}),e.engine.kn(e),""!==n&&delete o[e.name]}let h=0===u.length?function(e){let t=Object.getOwnPropertyDescriptors(e),n=Object.isFrozen(e);for(let e of Object.values(t))"value"in e&&!1===e.writable&&(e.writable=!0,n=!0);return n?Object.create(Object.getPrototypeOf(e),t):e}(d):d;return F.set(o,i={el:o,ce:t,state:h,engine:0===u.length?null:u[0].engine,entries:f,F:null}),h}(r,c,m,!f):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${a.tagNames.state}> to be a direct child of a custom element.`))).catch($),async start(n,o){let u=!1;await async function(n,o,r,u,c){if(u===U)return;let d=h(u);d&&await d;let f=F.get(o);f.engine&&u.$recursion&&p(`[wcs/mount-dollar-declaration] <${o.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);let m=f.F;if(null!==m&&m.el!==n&&m.el.isConnected&&p(`<${o.localName}> already has a connected <${a.tagNames.state} bind-component="${f.ce}">.`),null!==m&&ce(m,!1),null!==m&&function(e,t,n){let o=e.N,l=`[${a.bindAttributeName}]`,r=e=>1===e.nodeType&&(e.matches(l)||null!==e.querySelector(l)),i=new Set,s=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&i.add(e)},u=(e,t)=>{for(let n=e.Pn(t);null!==n&&n!==t;n=n.nextSibling)s(n);s(t)};for(let e of o.re.values())for(let t of e)if(null===t.B)s(t.a);else for(let e of t.B.q)u(t.B,e.S);for(let e of o.oe.values())for(let t of[e.E,...e.j??[]])null!==t&&u(t,t.S);for(let t of e.I)t.parentNode===n&&r(t)&&i.add(t);if(0===i.size)return!1;let c=[...n.childNodes].filter(n=>n!==t&&!i.has(n)&&!e.I.includes(n)&&(r(n)||o.It&&n.textContent.includes("{{")));return c.length>0&&console.warn(`[@wcstack/state] <${e.host.el.localName}>: ${c.length} node(s) added beside the content taken over are not bound.`),!0}(m,n,r))return async function(e,t,n,o){e.el.engine=null,e.el=t,e.N.element=t,t.engine=e.N,e.I=e.I.filter(e=>e.parentNode===n),t.isConnected?await we(e,o):o()}(m,n,r,c);let g=new i(u,new t);g.element=n,n.engine=g,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let o=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof o&&"constructor"!==t&&n.set(o,null)}let o=(t,n,o)=>Reflect.apply(t,e.proxy,o);e.K=e=>{let t=n.get(e);return null===t&&n.set(e,t=new Proxy(e,{apply:o})),t}}(g,u);let $={el:n,I:[],N:g,host:f,se:[],st:new Map,cn:!1,an:null,from:null,Q:null};for(let e of f.entries)$.se.push({m:$,e});f.F=$,J.set(g,$);let w=null===f.engine;w?s.element?.(g,"mounting"):(function(e){let t=e.N,n=e.host,o=n.engine,l=n.el.localName,r=n.entries.find(e=>""===e.$)??null;for(let e of n.entries){if(""===e.$)continue;let t=G(e.$);oe(n,t)&&(e.$!==t||le(n,t))&&ne(`${l}.${e.$}`,`[wcs/mount-own-key-shadow] <${l}>: "${n.ce}.${e.$}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==r){let e=o.v(r.ue,r.r);if(null!==e&&"object"==typeof e)for(let t of Object.keys(n.state))"$"!==t[0]&&t in e&&!n.entries.some(e=>e.$===t)&&ne(`${l}.${t}`,`[wcs/mount-own-key-shadow] <${l}>: its own "${t}" hides "${r.ue.t}.${t}" — remove the default to read the tree, or rename it to keep it private.`)}let i=V.filter(e=>void 0!==n.state[e]);i.length>0&&ne(`${l}.${n.ce}$`,`[wcs/mount-dollar-declaration] <${l}>: ${i.join(", ")} ${1===i.length?"is":"are"} not run in a mounted component — declare it on the root state.`);let a=t.Ze;t.Ze=n=>{ie(e,r,n),a.call(t,n)};let s=[...t.L.all()];for(let t of s)ie(e,r,t);for(let e of s)a.call(t,e);let u=n.entries.filter(e=>null!==e.r);if(u.length>0){let e=t._t;t._t=()=>{u.every(e=>e.r.d)&&e.call(t)}}}($),ce($,!0),b.add(g),C(g,r));let y=s.ir?.(r);l(g,r),y?.(),$.I=[...r.childNodes],e(),w&&g.bn(),Object.defineProperty(o,f.ce,{configurable:!0,enumerable:!0,get:()=>g.proxy});let v=o.$stateReadyCallback;if("function"==typeof v)try{let e=v.call(o,f.ce);null!==e&&"object"==typeof e&&"function"==typeof e.then&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}c(),n.isConnected?(await g.ae("$connectedCallback"),w&&n.isConnected&&s.element?.(g,"connected")):ce($,!1)}(r,m,f?d:m,n,()=>{u=!0,o()}).catch(e=>{let t=g();return!u&&null!==t&&(t.broken=!0),$(e)})},qe(){let e=g();null!==e&&we(e).catch(e=>console.error(e))},On(){let e=g();null!==e&&(ce(e,!1),!e.broken&&(e.N.ae("$disconnectedCallback"),null===e.host.engine&&s.element?.(e.N,"disconnected")))},reset(){p(`re-setting a component's state is not supported: write <${m?.localName}>.${c} instead.`)}}}var ye={name:"scopes",install(){s.ot=c(f,s.ot,D),s.ot=c(f,s.ot,q),s.ot=c(f,s.ot,be),s.Jo=L,s.wo=_,s.element=u(s.element,(e,t)=>{if("mounting"!==t)return;let n=e.element.getRootNode();C(e,n),function(e,t){let n=t.host,o=void 0===n?void 0:Q.get(n);void 0!==o&&E.set(e,{host:n,def:o})}(e,n)}),s.pe=u(s.pe,(e,t,n,o,l,r)=>{(function(e,t,n,o){let l=E.get(e);if(void 0===l)return;let r=t.t.split(".",1)[0];if(!l.def.bindables.includes(r))return;let i=o&&t.t===r;l.host.dispatchEvent(new CustomEvent(`${l.def.tag}:${r}-changed`,{detail:i?n:void 0,bubbles:!0}))})(e,t,l,r),$e(e,t,n,o,l,r,!1)}),s.me=u(s.me,(e,t,n)=>$e(e,t,n,void 0,void 0,!1,!0)),s.Re=c(d,s.Re,(e,t,n,o,l)=>(function(e,t){let n=y.get(e);if(void 0!==n&&0===t.n)for(let e of n)e.startsWith(`${t.t}.`)&&p(`writing "${t.t}" would replace the volume grafted at "${e}"; write the paths under it instead.`)}(e,t),function(e,t,n){let o,l=J.get(e);if(void 0===l)return!1;for(let e=t;null!==e&&void 0===o;e=e.w)o=l.st.get(e);if(void 0===o)return!1;let r=o.e;return!((null===r.r||r.r.d)&&!r.ro)&&(!!n||(ae(l,r.r),void p(`[wcs/mount-readonly] <${l.host.el.localName}> cannot write "${t.t}": it is mounted read-only ("${l.host.ce}${""===r.$?"":`.${r.$}`}#ro: ${r.ue.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,l)));let e=s.ie;s.ie=(t,n)=>{let o=y.get(t);void 0!==o&&o.length>0&&p(`re-setting a root state with grafted volumes (${o.join(", ")}) is not supported: their data is part of the tree.`),function(e){let t=K.get(e);if(void 0===t)return!1;for(let e of t.values())if(e.size>0)return!0;return!1}(t)&&p("re-setting a root state with mounted components is not supported: they read its data."),e?.(t,n)}}},ve=ye;export{ve as default,ye as scopes};
@@ -1,9 +1,29 @@
1
- import { I as IStateFeature } from '../chunks/features.js';
1
+ /**
2
+ * The places the core calls into add-ons (docs/state-engine-rewrite/addons-plan.ja.md §1.2).
3
+ *
4
+ * Add-ons ship as separate entries of the same build as the core (`features/*`): they reach
5
+ * the core's internals directly, and the core only calls out through these slots. A slot is
6
+ * empty until an installed feature fills it (the object starts with none: a list of null slots
7
+ * would be the core's bytes), so a page without the feature pays one `?.` check. A feature
8
+ * restoring a slot may set it to null.
9
+ * Slots are added with the first feature that needs them; several features share one through
10
+ * chain / first. The slots `element` and `detail` keep their names (a DevTools-facing field and a DOM
11
+ * name share them); the others are shortened by the build. An empty slot is read through
12
+ * Object.prototype: a page that polluted it (a value under `element`, say) breaks the core loudly
13
+ * there, as it does wherever the core reads a plain object's keys (`$behavior`); not defended.
14
+ */
15
+
16
+ /** An add-on entry: `installFeatures([temporal, diagnostics])` before the state is defined. */
17
+ interface Feature {
18
+ readonly name: string;
19
+ install(): void;
20
+ }
2
21
 
3
22
  /**
4
- * features/ssr.ts — サーバー描画とハイドレーション(@wcstack/state/features/ssr)。
23
+ * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —
24
+ * see src/ssr/ssr.ts.
5
25
  */
6
26
 
7
- declare const ssr: IStateFeature;
27
+ declare const ssr: Feature;
8
28
 
9
29
  export { ssr as default, ssr };
@@ -1,2 +1 @@
1
- import{c as t,a as e,S as n}from"../chunks/filterRegistry.js";import{Q as s,R as o,S as r,U as a,V as i,W as c,X as l,Y as d,Z as u,_ as f,y as p,$ as m,a0 as h,G as g,a1 as y,a2 as b,a3 as N,a4 as S,N as w,x,a5 as A,a6 as v,L as T,a7 as k,a8 as C,a9 as D,D as O,aa as _,ab as $,ac as j,ad as P,ae as E,af as M,ag as B,ah as q,ai as R,aj as F,ak as I,al as H,am as z,j as W,an as J,v as V,ao as L,ap as G,aq as Q,ar as U,as as X,at as Y,au as Z,g as K}from"../chunks/binder.js";import{H as tt,a as et}from"../chunks/registerComponents.js";import{V as nt}from"../chunks/version.js";import{W as st,g as ot}from"../chunks/pathDiagnostics.js";import"../chunks/errorGuidance.js";import"../chunks/lifecycleHooks.js";import"../chunks/declarationAliases.js";import"../chunks/setAll.js";import"../chunks/checkDependency.js";import"../chunks/getAllPropertyDescriptors.js";import"../chunks/declarationHooks.js";import"../chunks/diagnosticsHooks.js";const rt=/^@@wcs-(?:for|if|elseif|else):[^-]/,at=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,it=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,ct=/^@@wcs-text-start:(.+)$/;function lt(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function dt(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),s=[];for(;n.nextNode();){const t=n.currentNode;e(t.data)&&s.push(t)}return s}const ut=t=>rt.test(t),ft=t=>at.test(t),pt=t=>at.test(t)||it.test(t);function mt(t){return"else"===t.bindingType?"else:":`${t.bindingType}: ${ht(t.statePathName,t.outFilters)}`}function ht(t,e){let n=t;for(const t of e){const e=t.literals??t.args;n+=`|${t.filterName}`,t.args.length>0&&(n+=`(${t.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return n}const gt=/--|-$|[\0\n\r\u2028\u2029]/;function yt(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const s=i(c(t.fragment,n.nodePath));if(null===s)continue;const o=c(e,n.nodePath);o.parentNode.replaceChild(document.createComment(s),o)}return e}class bt extends tt{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=nt.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(e){const n=t.tagNames.ssr,s=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!s)return null;return s.querySelector(n)}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const s=Object.getOwnPropertyDescriptor(e,t);if(void 0!==s&&"function"==typeof s.get)continue;const o=e[t];"function"!=typeof o&&(n[t]=o)}return n}static buildContent(n,i,c){const l=c??n.ownerDocument;e.seen&&function(t){const e=new Map;for(const n of dt(t,ft)){if(null===n.parentNode)continue;const[,t,s]=at.exec(n.data),o=s.split(":")[0],r=n.previousSibling?.data,a=`@@wcs-${t}-end:${s}`;if(r!==`@@wcs-${t}:${o}`&&e.get(r)!==o)for(let t=n;null!==t;){const e=t.nextSibling;t.remove(),t=t.data===a?null:e}else"for"===t&&e.set(a,o)}}(l);const d=document.createElement("script");d.setAttribute("type","application/json"),d.textContent=lt(JSON.stringify(i)),n.appendChild(d);for(const[e,s]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of dt(n.shift(),ut)){const s=t.data,o=s.slice(s.indexOf(":")+1);if(e.has(o))continue;const r=a(o);null!==r&&(e.set(o,r),n.push(r.fragment))}return e}(l)){const o=document.createElement("template");o.setAttribute("id",e),o.setAttribute(t.bindAttributeName,mt(s.parseBindTextResult)),o.content.appendChild(yt(s)),n.appendChild(o)}const u=n.ownerDocument,f=s();if(f.length>0){const t={};for(let e=0;e<f.length;e++){const n=f[e];if(!n.isConnected||n.ownerDocument!==u)continue;const s=o(n);if(0===s.length)continue;const r=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",r);const a={};for(const t of s)a[t.propName]=t.value;t[r]=a}if(Object.keys(t).length>0){const e=document.createElement("script");e.setAttribute("type","application/json"),e.setAttribute("data-wcs-ssr-props",""),e.textContent=lt(JSON.stringify(t)),n.appendChild(e)}}r()}static removeBlockBoundaryComments(t){for(const e of dt(t,pt))e.remove()}static removeStructuralComments(t){for(const e of dt(t,ut))e.remove()}static restoreTextBindings(t){for(const e of dt(t,t=>ct.test(t))){const t=ct.exec(e.data)[1],n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let s=e.nextSibling;e.remove();const o=`@@wcs-text-end:${t}`;for(;s;){const t=s.nextSibling;if(s.nodeType===Node.COMMENT_NODE&&s.data===o){s.parentNode.removeChild(s);break}s.parentNode.removeChild(s),s=t}}}static cleanupDom(e){const n=document.body,s=e.querySelectorAll(t.tagNames.ssr),o=new Map;for(const t of s){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&o.set(e,t)}}for(const t of dt(n,ft)){const e=at.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let s=t.nextSibling;for(;s;){const t=s.nextSibling;if(s.nodeType===Node.COMMENT_NODE&&s.data===n){s.remove();break}s.remove(),s=t}t.remove()}bt.restoreTextBindings(n);const r=e=>{for(const n of dt(e,ut)){const e=o.get(n.data.split(":")[1]);if(e){const s=document.createElement("template"),o=e.getAttribute(t.bindAttributeName);o&&s.setAttribute(t.bindAttributeName,o);const a=document.importNode(e.content,!0);if(a.childNodes.length>0)s.content.appendChild(a);else for(const t of Array.from(e.childNodes))s.content.appendChild(document.importNode(t,!0));r(s.content),n.parentNode.replaceChild(s,n)}}};r(n);const a=e.querySelectorAll("[data-wcs-ssr-id]");for(const t of a)t.removeAttribute("data-wcs-ssr-id");for(const t of s)t.remove()}}const Nt={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const n=t.tagNames.state,s=t.tagNames.ssr,o=e.querySelectorAll(`${n}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of o){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===s)continue;const n=document.createElement(s);n.setAttribute("version",nt),bt.buildContent(n,bt.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(n,t)}r()},reset:function(){d(),r(),e.seen=!1}};const St=new Set(["for","if","elseif","else"]);function wt(t){const[,e,n]=at.exec(t),[s,...o]=n.split(":");return"for"===e?{type:e,uuid:s,path:o[0],index:parseInt(o[1],10),nodes:[]}:{type:e,uuid:s,path:o.join(":"),index:null,nodes:[]}}function xt(e){const n=[];for(const s of e)if(s.nodeType===Node.ELEMENT_NODE){const e=s;e.hasAttribute(t.bindAttributeName)&&n.push(e),Array.from(e.children).some(e=>e.localName===t.tagNames.state&&L(e))||n.push(...G(e))}else null!==l(s)&&n.push(s);return n}function At(t){const[e,n,s]=Q(t),o=new U;return{bindingInfos:o.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:e,bindingSession:o,deferredSpreads:s}}const vt=/^\s*@@\s*(?:wcs-text)?\s*:/;function Tt(t,e){for(const n of e)"event"===n.bindingType||St.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&vt.test(n.node.data))&&t.push(n)}function kt(t,e){const n=[];for(let s=0;s<t.nodes.length;s++){const o=e.get(t.nodes[s]);o?s+=o.nodes.length+1:n.push(t.nodes[s])}return n}function Ct(t,e,n,s,o,r){e.length>0&&(t.spreads=e);for(const t of e)Y(t.node);m(e,n,s,o,r)}function Dt(t,e){const n=a(e),s=g(t.getRootNode());let o=null;if(n&&s){const{statePathName:t,outFilters:e}=n.parseBindTextResult;s.createState("readonly",n=>{const s=y(n[t],X(e,"output"));Array.isArray(s)&&(o=s)})}return o}function Ot(e,n){return`@@${{for:t.commentForPrefix,if:t.commentIfPrefix,elseif:t.commentElseIfPrefix,else:t.commentElsePrefix}[e]}:${n}`}function _t(t,e,n){const s=Ot(e,n);return dt(t,t=>t===s)[0]??null}function $t(e,n){const s=e,o=n.templates,r=new Map;for(const[t,e]of o)for(const n of dt(e.content,ut))r.set(n.data.slice(n.data.indexOf(":")+1),t);const a=new Set(v(e));if(a.size>0)for(const t of dt(s,ut)){const e=t.data.slice(t.data.indexOf(":")+1);let n=t.parentNode;for(;null!==n&&!a.has(n);)n=n.parentNode;null===n||r.has(e)||r.set(e,n)}const i=new Map,c=[];for(const[e,n]of o){const s=n.getAttribute(t.bindAttributeName)||"";let o=T(s)[0];const a=o.bindingType,l=r.get(e),d=i.get(l);"else"===a&&d&&(o={...d,outFilters:[...d.outFilters,k()],bindingType:"else"}),"if"===a||"elseif"===a?i.set(l,o):"else"===a&&i.set(l,null),c.push([e,n,o])}for(const[t,e,n]of c.reverse()){const o=document.importNode(e.content,!0),r="for"===n.bindingType?n.statePathName:void 0;C(o),"string"==typeof r&&D(o,r),O(s,o,r);const a={fragment:o,parseBindTextResult:n,nodeInfos:_(o)};$(t,s,a)}}const jt={hydrate:async function(e){await u(e);const n=e.querySelectorAll(t.tagNames.ssr);for(const t of n){const n=t;if(!n.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${n.version}", client="${nt}". Falling back to full render.`),bt.cleanupDom(e),!1}const s=function(t){const e=[];for(const n of dt(t,pt)){if(!ft(n.data)){e.pop();continue}const t=wt(n.data),s=e.at(-1);if("for"===t.type&&s&&s.uuid!==t.uuid)return[t,s];e.push(t)}return null}(document.body);if(null!==s){const[t,n]=s;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${n.type}: ${n.path}" (known limitation). Falling back to full render.`),bt.cleanupDom(e),!1}for(const t of n)$t(e,t);bt.restoreTextBindings(document.body);const o=function(t){const e=[];for(const n of dt(t,ft)){const t=wt(n.data);t.start=n;const s=n.data.replace("-start:","-end:");let o=n.nextSibling;for(;o&&(o.nodeType!==Node.COMMENT_NODE||o.data!==s);)t.nodes.push(o),o=o.nextSibling;e.push(t)}return e}(document.body),r=new Map,a=function(t,e,n=new Map){const s=new Map,o=[],r=new Map(e.map(t=>[t.start,t])),a=new Set;for(let t=e.length-1;t>=0;t--){const n=xt(e[t].nodes).filter(t=>!a.has(t));for(const t of n)a.add(t);e[t].subscribers=n}for(const a of e){const e=kt(a,r);if(0===e.length)continue;const i=e.some(t=>ut(t.data));if(i){const t=document.createComment(`wcs-row-end:${a.uuid}`);a.nodes[a.nodes.length-1].after(t),e.push(t)}const{bindingInfos:c,subscriberNodes:l,bindingSession:d,deferredSpreads:u}=At(a.subscribers);for(const t of c)if(t.node!==t.replaceNode){const n=e.indexOf(t.node);n>=0&&(e[n]=t.replaceNode)}const f=j(e,i);P(f,d),E(f,c),M(f,l);const p=c.filter(t=>B(t,q));if(R(f,p),"for"===a.type&&null!==a.index){const e=_t(t,"for",a.uuid);if(e){let t=n.get(a.uuid);if(!t){const o=Dt(e,a.uuid)??a.path;t=s.get(o),t||s.set(o,t=[]),n.set(a.uuid,t)}const r=t[a.index]??=F(null,a.index);I(e,r,f),H(e,f.lastNode),z(e,f);const i=ot(a.path+"."+st),l=W(i,r);J(f,l),d.initialize(c,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Tt(o,c),Ct(f,u,l,d,c,p)}}else{const e=a.start.previousSibling,n=e?.data===Ot(a.type,a.uuid)?e:_t(t,a.type,a.uuid);if(n){z(n,f);const t=V(n);J(f,t),d.initialize(c,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Tt(o,c),Ct(f,u,t,d,c,p)}}}return o}(document.body,o,r);bt.removeBlockBoundaryComments(document.body);const i=[];for(const t of n)t.parentNode&&(i.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[,c,l]=f(document.body),d=[],v=[],T=p(document.body),k=T.initialize(c);m(l,null,T);for(const t of k)if("event"!==t.bindingType)if(St.has(t.bindingType))v.push(t);else{if(t.statePathName.includes(st))continue;d.push(t)}for(const t of v)if("for"===t.bindingType){const e=h(t),n=t.replaceNode.getRootNode(),s=g(n);s&&s.createState("readonly",n=>{const s=y(n[t.statePathName],t.outFilters);if(Array.isArray(s)){const n=r.get(t.uuid);n&&b(s,n),N(e,s),S(t.node,s),w(e,s)}})}x([...d,...a]);for(const{el:t,parent:e,next:n}of i)e.insertBefore(t,n);const C=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))C.set(t.getAttribute("data-wcs-ssr-id"),t);for(const n of e.querySelectorAll(t.tagNames.ssr))for(const[t,e]of Object.entries(n.hydrateProps)){const n=C.get(t);if(n)for(const[t,s]of Object.entries(e))A?.isDeclared(n,t)||(n[t]=s)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},textMarker:function(t){const e=t.node.nodeType===Node.COMMENT_NODE,n=e?l(t.node):null,s=n??(e?t.statePathName:ht(t.statePathName,t.outFilters));if(!gt.test(s))return s;const o=n?.split("|")[0].trim();return o&&!gt.test(o)?o:t.statePathName},loadState(t){const e=t.parentNode;if(!e)return null;const n=bt.find(e);if(!n)return null;const s=n.stateData;return Object.keys(s).length>0?s:null},async emitSnapshot(e){await K(e.rootNode);const n=bt.extractStateData(e),s=document.createElement(t.tagNames.ssr);s.setAttribute("version",nt),bt.buildContent(s,n,e.rootNode),e.parentNode?.insertBefore(s,e)}};let Pt=!1;function Et(){Pt||(Pt=!0,Z(jt),et(e=>{e.get(t.tagNames.ssr)||e.define(t.tagNames.ssr,bt)}),function(){const t=globalThis;void 0===t[n]&&(t[n]=Nt)}())}const Mt={name:"ssr",install(){Et()}};export{Mt as default,Mt as ssr};
2
- //# sourceMappingURL=ssr.js.map
1
+ import{a as e}from"../chunks/chunk-WEL3YSG7.js";import{b as t,c as l}from"../chunks/chunk-FF6KHTYS.js";import"../chunks/chunk-PKDBVBAP.js";import{a as n,i as r,j as o,k as i,l as s,m as a}from"../chunks/chunk-7PN5YNZZ.js";import"../chunks/chunk-HFKGUDDJ.js";import"../chunks/chunk-UM3O6QXD.js";import{a as u}from"../chunks/chunk-732CB4QN.js";import"../chunks/chunk-QI7P7YPP.js";import"../chunks/chunk-QQH6N5CJ.js";import"../chunks/chunk-WWJNAZVP.js";import{a as c,b as f}from"../chunks/chunk-YOPPVWPQ.js";var d=e=>e.split(".").slice(0,2).join("."),p=class extends t{static find(e){return e.querySelector?.(u.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=u.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends p{})}var h=()=>u.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,x=new WeakSet,k=new WeakMap;function T(e,t){let l=[];for(let n=e;null!==n&&(l.push(n),n!==t);n=n.nextSibling);return l}function $(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.I?e.Ve:e.I[e.I.length-1];function W(e,t,l){let n=[v(null===l?"wcs-[":`wcs-[:${l}`)];for(let e of t)null===l&&n.push(v("wcs-|")),n.push(...T(e.Ve,j(e)));n.push(v("wcs-]")),e.after(...n);for(let e of n)x.add(e)}function C(e){if(e instanceof r){W(e.S,e.ve,null);for(let t of e.ve)E(t);return}let t=e.F;null!==t&&(W(e.q[e.q.length-1].S,[t],e.b),E(t))}function E(e){if(null!==e.u)for(let t of e.u)C(t)}var q=new Set(["script","style","template","textarea","title"]),P="data-wcs-raw",I=e=>q.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 O=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.j)for(let e of t.j)l.set(e.S,e);for(let t of e.re.values())for(let e of t)if(null!==e.B)for(let t of e.B.q)l.set(t.S,e.B);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=>x.has(e)||1===e.nodeType&&t.has(e)&&_(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)?k.has(e):t.has(l)&&w(l,"wcs-t:"))&&(k.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=>k.has(e))&&e.setAttribute(P,l.map(e=>k.has(e)?`{{ ${k.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"}${O++}`;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($(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,s,o))}t.before(i)}function V(e){!function(e){if(null!==e.querySelector(u.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=>k.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(`${u.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 B=Symbol.for("wcstack.state.ssr.impl"),D=new Map,U=new WeakMap,_=e=>!0===c.wo?.(e),J=e=>1===e.nodeType&&!I(e)&&!_(e),Q=e=>e.f.flat().concat(e._??[]),Y=e=>{for(let t of Q(e))t.remove()};function F(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=F(a,t,l):(l.push(a),J(a)&&G(a,t))}a=e}let u={branch:void 0===n[1]?null:Number(n[1]),f:i,_:a??o.appendChild(v("wcs-]"))},c=Q(u);a=u._.nextSibling;for(let e of c)l?.push(e),t&&s.add(e);return t&&null!==r?D.set(r,u):Y(u),a}function G(e,t){for(let l=e.firstChild;null!==l;)w(l,"wcs-[")?l=F(l,t):(J(l)&&G(l,t),l=l.nextSibling)}function H(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]?$(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)&&(_(r)?U.set(r,{ssr:t,Te: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),G(e,l)}function K(e){let t=U.get(e);if(void 0===t||(U.delete(e),H(e,t.ssr,t.Te),!t.Te))return null;let l=c.Te;return c.Te=re,()=>{c.Te=l,Z()}}function Z(){for(let e of D.values())Y(e);D.clear()}function z(e){let t=[];for(let l=document.createTreeWalker(e,128);l.nextNode();)t.push(l.currentNode);return t}function L(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 X(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))x.add(e);else if(e.localName.includes("-")&&!_(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(k.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&&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&&[u.commentIfPrefix,u.commentElseIfPrefix,u.commentElsePrefix].includes(e.data),te=e=>3===e.nodeType&&""===e.data.trim(),le=e=>(D.get(e)?._??e).nextSibling;function ne(e,t){if(t.length!==e.nn.childNodes.length)return!1;let l=e.Rn;for(let n=0;n<l.length;n++){let r=l[n],o=e.nn,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.ho[n]=i}return!0}function re(e,t,l){if(0===D.size)return null;let n=t,r=0;if(!l){let e=u.commentIfPrefix;if(!y(t,e))for(let l=t.previousSibling;null!==l&&(ee(l)||te(l))&&(ee(l)&&r++,!y(l,e));l=l.previousSibling);for(let l=t.nextSibling;!D.has(n)&&null!==l&&!y(l,e)&&(ee(l)||te(l));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),Y(o),null;let i=o.f.shift();if(0===o.f.length&&D.delete(n),o._?.replaceWith(...T(t,n)),o._=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._;)e++}if(!ne(e,s)){let l=(e.Tn?e.root:e.nn).cloneNode(!0);s=e.Tn?[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(){c.An=X,c.ir=K;let t=c.element;c.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.ae;e.ae=(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(`[${P}]`)))e.textContent=e.getAttribute(P),e.removeAttribute(P);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&&!_(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 > ${u.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,l=[]);for(let r of n(t.getAttribute(u.bindAttributeName)??"")){let t=r.Ge;r.ye[0]===i&&l.push([e?L(e,t,1,0):t,r.ye.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:L(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]:L(n,r[2],2,1)??r[2]};for(let t of z(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 z(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=u.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 c=o.content.firstChild;n.replaceWith(.../^\s*elseif\s*:/.test(c?.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):H(w,r,s),r.remove(),s&&(c.Te=re,queueMicrotask(()=>{Z(),c.Te=null}))}(l),t?.(l,r)},function(){let e=globalThis;e[B]={build:V,reset(){O=0}},void 0===e[g]&&(e[g]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[B].build(t),reset:()=>e[B].reset()})}(),c.$o=f(c.$o,m);for(let e of l())m(e)}},ie=oe;export{ie as default,oe as ssr};
@@ -1,9 +1,24 @@
1
- import { I as IStateFeature } from '../chunks/features.js';
2
-
3
1
  /**
4
- * features/temporal.ts — `$watch` / `$scan` / `$streams`(@wcstack/state/features/temporal)。
2
+ * The places the core calls into add-ons (docs/state-engine-rewrite/addons-plan.ja.md §1.2).
3
+ *
4
+ * Add-ons ship as separate entries of the same build as the core (`features/*`): they reach
5
+ * the core's internals directly, and the core only calls out through these slots. A slot is
6
+ * empty until an installed feature fills it (the object starts with none: a list of null slots
7
+ * would be the core's bytes), so a page without the feature pays one `?.` check. A feature
8
+ * restoring a slot may set it to null.
9
+ * Slots are added with the first feature that needs them; several features share one through
10
+ * chain / first. The slots `element` and `detail` keep their names (a DevTools-facing field and a DOM
11
+ * name share them); the others are shortened by the build. An empty slot is read through
12
+ * Object.prototype: a page that polluted it (a value under `element`, say) breaks the core loudly
13
+ * there, as it does wherever the core reads a plain object's keys (`$behavior`); not defended.
5
14
  */
6
15
 
7
- declare const temporal: IStateFeature;
16
+ /** An add-on entry: `installFeatures([temporal, diagnostics])` before the state is defined. */
17
+ interface Feature {
18
+ readonly name: string;
19
+ install(): void;
20
+ }
21
+
22
+ declare const temporal: Feature;
8
23
 
9
24
  export { temporal as default, temporal };
@@ -1,2 +1 @@
1
- import{r as t}from"../chunks/declarationHooks.js";import{S as e,d as n,a as o,D as r,W as s,b as a,g as i,M as c,c as u,e as l,f,h as d,i as h,j as p}from"../chunks/pathDiagnostics.js";import{n as m}from"../chunks/declarationAliases.js";import{r as y,L as $,d as w}from"../chunks/errorGuidance.js";import{c as g,d as v,e as b,l as k,f as j,i as O,h as P,j as I,k as x,m as S,n as A,o as M,p as E}from"../chunks/binder.js";import{g as z,N as W,r as R}from"../chunks/getAllPropertyDescriptors.js";import{i as C}from"../chunks/filterRegistry.js";import{s as _}from"../chunks/featureBridge.js";const D=new WeakMap,F=new Set,N=new Set;function T(t){return t.byFromPath.size>0||t.byResetPath.size>0}function L(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function G(t){return D.get(t)}function B(t){H(t),D.delete(t)}function H(t){F.delete(t),N.delete(t)}const K=new WeakSet;let q=0;function Q(t){return G(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function U(t){if(0===N.size)return;if(e=t.absolutePathInfo.stateElement,!N.has(e))return;var e;const n=Q(t);if(void 0!==n)for(const t of n)V(t)}function V(t){K.has(t)||(K.add(t),q++)}function J(t){return!!K.delete(t)&&(q--,!0)}const X=/^(?:0|[1-9]\d*)$/;function Y(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function Z(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);if(Array.isArray(t)){return e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&X.test(e)&&Y(t,e))?"array":null}return(e===Object.prototype||null===e)&&Reflect.ownKeys(t).every(e=>"string"==typeof e&&Y(t,e))?"object":null}function tt(t,e){const n=Z(t);if(null===n)return t;const o=t,r=e.get(o);if(void 0!==r)return r;let s;s="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,s);for(const t of Object.keys(o))s[t]=tt(o[t],e);return s}function et(t){return tt(t,new Map)}function nt(t,e,n){if(Object.is(t,e))return!0;const o=Z(e);if(null===o||"object"!=typeof t||null===t)return!1;const r=t,s=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(r).length!==Object.keys(s).length)return!1;if(Z(t)!==o)return!1;let a=n.get(r);if(void 0===a)a=new Set,n.set(r,a);else if(a.has(s))return!0;if(a.add(s),"array"===o){for(let e=0;e<t.length;e++)if(!nt(r[e],s[e],n))return!1;return!0}return Object.keys(s).every(t=>Object.prototype.hasOwnProperty.call(r,t)&&nt(r[t],s[t],n))}function ot(t,e){return nt(t,e,new Map)}const rt=new WeakMap;function st(t,e){if("function"!=typeof e)return;const n=rt.get(e);void 0===n?rt.set(e,new Set([t])):n.add(t)}function at(t,e){return"function"==typeof e&&!0===rt.get(e)?.has(t)}const it={"read-source":t=>`${e} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${e} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${e} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${e} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${e} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${e} could not write the output "${t}".`},ct={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function ut(t,o,r){null!==n&&n({type:"state:watch-error",phase:o,path:`${e}.${t}`,error:r})}function lt(t,e,n){console.error(`[@wcstack/state] ${it[n](t)}`,e),ut(t,ct[n],e)}function ft(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function dt(t,n){n.then(void 0,()=>{}),lt(t,new TypeError(`${e} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const ht=new WeakSet;const pt="[wcs/scan-declaration-invalid]",mt=Object.freeze([]);function yt(t){return`${e} entry "${t}"`}function $t(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function wt(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${s}${s}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${$}`}function gt(t,e,n){0===n.length&&y(`${pt} ${t} "${e}" must be a non-empty state path.${$}`),n.startsWith("$")&&y(`${pt} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${$}`),n.includes("@")&&y(`${pt} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${$}`),n in Object.prototype&&y(`${pt} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${$}`);const o=i(n);for(const r of o.segments)0===r.length&&y(`${pt} ${t} ${e} "${n}" has an empty path segment.${$}`);return o.wildcardCount>c&&y(`${pt} ${t} ${e} "${n}" exceeds the maximum wildcard depth (${c}).`),o}function vt(t,n,a,i){const c=yt(t);0===t.length&&y(`${pt} ${e} entry name must be a non-empty string.${$}`),(t.includes(r)||t.includes(s))&&y(`${pt} ${c} must be a flat property name ("${r}" and "${s}" are not allowed). The output is a property the runtime owns.${$}`),t.startsWith("$")&&y(`${pt} ${c} must not start with "$" (reserved namespace).${$}`),t in Object.prototype&&y(`${pt} ${c} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${$}`),n.has(t)&&y(`${pt} ${c} conflicts with a getter declared on the state.${$}`),a.has(t)&&y(`${pt} ${c} conflicts with a setter declared on the state.${$}`),i.has(t)&&y(`${pt} ${c} conflicts with the ${o} entry of the same name — each output has exactly one owner.${$}`)}function bt(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!at(t,o)&&y(`${pt} ${yt(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${$}`)}function kt(t,e,n,o,s,i){const c=yt(t),u=void 0!==e.from,l=void 0!==e.on;if(u===l&&y(`${pt} ${c} must declare exactly one of "from" (a state path) or "on" (an event-token name).${$}`),l){const t=e.on;return"string"==typeof t&&0!==t.length||y(`${pt} ${c} "on" must be a non-empty event-token name.${$}`),n.has(t)||y(`${pt} ${c} on "${t}" is not declared in ${a}.${w(t,n)}${$}`),{kind:"event",tokenName:t}}const f=e.from;"string"!=typeof f&&y(`${pt} ${c} "from" must be a state path string.${$}`);const d=gt(c,"from",f),h=$t(d,o)??i?.recursiveGetterOwning(f)??null;null!==h&&y(wt(c,"from",f,h));const p=$t(d,s);return null!==p&&y(function(t,e,n){return`${pt} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${$}`}(c,f,p)),(f===t||f.startsWith(t+r))&&y(`${pt} ${c} from "${f}" reads the entry's own output — the scan would fold its own writes forever.${$}`),{kind:"path",path:f,pathInfo:d}}function jt(t,e,n,o){if(void 0===e)return mt;const a=yt(t);Array.isArray(e)||y(`${pt} ${a} "resetOn" must be an array of state paths.${$}`);const i=[];for(const t of e){"string"!=typeof t&&y(`${pt} ${a} "resetOn" must contain only state path strings.${$}`);const e=gt(a,"resetOn",t);e.wildcardCount>0&&y(`${pt} ${a} resetOn "${t}" must not contain "${s}" — a reset returns the whole output to "initial".${$}`);const c=$t(e,o);null!==c&&y(wt(a,"resetOn",t,c)),"path"===n.kind&&t===n.path&&y(`${pt} ${a} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${$}`),"path"===n.kind&&t.startsWith(n.path+r)&&y(`${pt} ${a} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${$}`),i.push(t)}return i}function Ot(t,n,r=null){const s=t[e];if(void 0===s)return null;("object"!=typeof s||null===s||Array.isArray(s))&&y(`${pt} ${e} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${$}`);const a=new Set,c=new Set,u=new Set,l=new Map;for(const[e,n]of Object.entries(z(t)))"function"==typeof n.get?a.add(e):"function"==typeof n.set&&u.add(e),"function"==typeof n.set&&c.add(e),"function"==typeof n.value&&l.set(e,n.value);const f=function(t){m(t);const e=t[o];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),d=[];let h=0;for(const[t,e]of Object.entries(s)){vt(t,a,c,f),("object"!=typeof e||null===e||Array.isArray(e))&&y(`${pt} ${yt(t)} must be an object ({ from | on, initial, fold, resetOn? }).${$}`);const o=e;bt(t,l,o);const s=kt(t,o,n,a,u,r);"initial"in o||y(`${pt} ${yt(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${$}`),"function"!=typeof o.fold&&y(`${pt} ${yt(t)} fold must be a function.${$}`);const i=jt(t,o.resetOn,s,a);d.push({name:t,source:s,fold:o.fold,initial:o.initial,resetOn:i,order:h++})}return function(t){const n=new Set(t.map(t=>t.name)),o=new Map;for(const r of t){for(const t of r.resetOn){const o=i(t).segments[0];n.has(o)&&y(`${pt} ${yt(r.name)} resetOn "${t}" reads the ${e} output "${o}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${$}`)}if("path"===r.source.kind){const t=r.source.pathInfo.segments[0];n.has(t)&&o.set(r.name,t)}}for(const t of o.keys()){const r=[t];let s=o.get(t);for(;void 0!==s&&r.length<=n.size;)s===t&&y(`${pt} ${e} entries ${[...r,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${$}`),r.push(s),s=o.get(s)}}(d),d.length>0?d:null}function Pt(t){const e=t.fold;return(n,o,...r)=>{const s=n;let a="read-output";try{const n=s[t.name];a="threw";const i=function(t){return K.has(t)}(t),c=i&&!ot(n,t.initial)?et(t.initial):n,u=e(c,o,...r);if(ft(u))return void dt(t.name,u);Object.is(u,n)||(a="write",s[t.name]=u,st(t.name,u)),i&&J(t)}catch(e){lt(t.name,e,a)}}}function It(t,e,n){const o=function(t,e){B(t);const n=new Map,o=new Map,r=new Map;for(const t of e){"path"===t.source.kind&&L(n,t.source.path,t);for(const e of t.resetOn)L(o,e,t),"event"===t.source.kind&&L(r,e,t)}const s={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:r};return D.set(t,s),s}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&(o.resetOn.some(n=>e.includes(n)&&g().hasQueuedPath(t,n))&&V(o))}const r=new Set;for(const e of o.byFromPath.keys())r.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return r.size>0?r:null}const xt="scanEntries",St={order:8,validate(t,e,n){const o=Ot(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(xt,o)},applyEarly(t,e,n){const o=n.get(xt)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=et(n.initial);t[n.name]=e,st(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&v(t,n.source.tokenName).subscribe(Pt(n))}(t,o))},register(t,e,n){const o=n.get(xt)??null,r=function(t){const e=new Map,n=G(t);if(void 0!==n)for(const t of n.entries)J(t)&&e.set(t.name,t.resetOn);return B(t),e}(t);t.setScanPaths?.(null===o?null:It(t,o,r))}};let At=!1;const Mt=Object.freeze([]),Et=Object.freeze([]);function zt(t,e,n){const o=new Set([n]),r=[n];for(;r.length>0;){const n=r.pop(),s=t.staticDependency.get(n)??Mt,a=t.dynamicDependency.get(n)??Mt,i=e.byFromPath.get(n)??Et;for(const t of[...s,...a,...i.map(t=>t.name)])o.has(t)||(o.add(t),r.push(t))}return o}const Wt=Symbol("wcs-stream-last-notified-uncertain"),Rt=new WeakMap;function Ct(t,e){const n=Rt.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function _t(t,e){const n=Rt.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Wt,error:Object.is(o.error,null)?null:Wt})}const Dt=new Set;function Ft(t){Dt.delete(t)}const Nt=new WeakMap;function Tt(t){return Nt.get(t)??new Map}function Lt(t){Ft(t);const e=Nt.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,_t(t,n.name)}const Gt=(t,e)=>e,Bt=new Set;function Ht(t,e){m(e);const n=e[o];if(void 0===n)return void Ct(t,Bt);"object"==typeof n&&null!==n||y(`${o} must be an object mapping stream names to stream definitions.`);const a=new Map,i=z(e);for(const[c,u]of Object.entries(n)){0===c.length&&y(`${o} entry name must be a non-empty string.`),c.includes(r)&&y(`${o} entry "${c}" must be a flat property name ("${r}" is not allowed).`),c.includes(s)&&y(`${o} entry "${c}" must be a flat property name ("${s}" is not allowed).`),c.startsWith("$")&&y(`${o} entry "${c}" must not start with "$" (reserved namespace).`),c in Object.prototype&&y(`${o} entry "${c}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(c)&&y(`${o} entry "${c}" conflicts with a getter declared on the state.`),t.setterPaths.has(c)&&y(`${o} entry "${c}" conflicts with a setter declared on the state.`),"object"==typeof u&&null!==u||y(`${o} entry "${c}" must be an object ({ args?, source, fold?, initial? }).`);const n=u,l=i[c]?.value;"function"!=typeof l||l===n.initial||at(c,l)||y(`${o} entry "${c}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&y(`${o} entry "${c}" source must be a function.`);const f=void 0!==n.fold;f&&"function"!=typeof n.fold&&y(`${o} entry "${c}" fold must be a function.`),f&&!("initial"in n)&&y(`${o} entry "${c}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&y(`${o} entry "${c}" args must be a function.`);const d={name:c,definition:{args:n.args??null,source:n.source,fold:n.fold??Gt,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};c in e||(e[c]=d.definition.initial,st(c,d.definition.initial)),a.set(c,d)}!function(t,e){Nt.set(t,e)}(t,a),Ct(t,new Set(a.keys()))}const Kt=new WeakMap,qt=new WeakMap;function Qt(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const r=Tt(t).get(o);return void 0!==r?n(r):void 0},has:(e,n)=>"string"==typeof n&&Tt(t).has(n),ownKeys:()=>Array.from(Tt(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const r=Tt(t).get(o);return void 0!==r?{configurable:!0,enumerable:!0,value:n(r)}:void 0},set(){y(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){y(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Ut(t){const e=Kt.get(t);if(void 0!==e)return e;const n=Qt(t,u,t=>t.status);return Kt.set(t,n),n}function Vt(t){const e=qt.get(t);if(void 0!==e)return e;const n=Qt(t,l,t=>t.error);return qt.set(t,n),n}function Jt(t){Kt.delete(t),qt.delete(t)}let Xt=null;function Yt(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const Zt={read(t,e){!function(t,e){null!==Xt&&Xt.add(k(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===u?Yt(Ut(t),e.pathInfo.segments):n===l?Yt(Vt(t),e.pathInfo.segments):W},get:(t,e)=>e===u?Ut(t.stateElement):e===l?Vt(t.stateElement):W};let te=0,ee=null,ne=0;const oe=new WeakMap;function re(t){te=t+1}function se(){te=0}function ae(t){if(te>0){const e=ee??=new Map;te>(e.get(t)??0)&&e.set(t,te),ne=Math.max(ne,te)}}function ie(t,e){return oe.get(t)?.get(e)??0}async function ce(t,e,n,r){let s=null;const a=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",a,{once:!0});try{const i=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError(`[@wcstack/state] ${o}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void a();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;r.fold(t.value)}if(n.aborted)return;r.done()}catch(t){if(n.aborted)return;r.fail(t)}finally{n.removeEventListener("abort",a)}}function ue(t){ye();const e=Tt(t);if(0!==e.size){!function(t){Dt.add(t)}(t);for(const n of e.values())le(t,n)}}function le(t,n){n.controller?.abort();const s=new AbortController;n.controller=s;const a=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const s=Xt,a=new Set;let i;Xt=a;try{t.createState("readonly",t=>{i=n(t)})}finally{Xt=s}i instanceof Promise&&y(`${o} entry "${e.name}" args must be synchronous (it returned a Promise).`);const c=`${u}${r}${e.name}`,f=`${l}${r}${e.name}`;for(const n of a){const r=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||r.path!==e.name&&r.path!==c&&r.path!==f||y(`${o} entry "${e.name}" args must not read the stream itself ("${r.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),r.wildcardCount>0&&y(`${o} entry "${e.name}" args must not read wildcard paths ("${r.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=a,i}(t,n);!function(t,n){const r=G(t);if(void 0!==r&&0!==n.depAddresses.size)for(const s of r.entries){if("path"!==s.source.kind||s.source.pathInfo.segments[0]!==n.name)continue;const a=zt(t,r,s.name);for(const t of n.depAddresses){const r=t.absolutePathInfo.pathInfo.path;a.has(r)&&y(`[wcs/scan-feedback-loop] ${o} entry "${n.name}" args read "${r}", which is derived from the ${e} output "${s.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,n),t.createState("writable",t=>{t[n.name]=n.definition.initial}),st(n.name,n.definition.initial),fe(t,n,"active",null);const i=n.definition,c={fold(e){t.createState("writable",t=>{const o=i.fold(t[n.name],e);t[n.name]=o,st(n.name,o)})},done(){fe(t,n,"done",null)},fail(e){fe(t,n,"error",e),s.abort()}};ce(i.source,a,s.signal,c)}function fe(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Rt.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),a=s.status!==n,i=!Object.is(s.error,o);(a||i)&&(!function(t,e,n,o){let r=Rt.get(t);void 0===r&&(r=new Map,Rt.set(t,r)),r.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{a&&t.$postUpdate(`${u}${r}${e.name}`),i&&t.$postUpdate(`${l}${r}${e.name}`)}))}function de(t){const e=Dt;if(0===e.size)return;const n=[];for(const o of e)for(const e of Tt(o).values()){let r=-1;for(const n of e.depAddresses)t.has(n)&&(r=Math.max(r,ie(t,n)));r>=0&&r<=d&&n.push({stateElement:o,entry:e,depth:r})}try{for(const{stateElement:t,entry:o,depth:r}of n)if(e.has(t)&&Tt(t).get(o.name)===o){re(r);try{le(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Tt(t).get(o.name)===o&&fe(t,o,"error",n)}}}finally{se()}}let he=!1;const pe=new WeakMap,me={order:20,apply(t,e){var n;Jt(t),Lt(n=t),Ft(n),Nt.delete(n),Ht(t,e),void 0!==e[o]&&t.attachAddressHooks?.("streams",o)},activate(t,e){if(!C()&&null!=t.connectedRootNode){if(null===e){if(!0!==t.initialized)return;return ue(t),void pe.set(t,t.connectGeneration??0)}e===t.connectGeneration&&pe.get(t)!==e&&ue(t)}},deactivate(t){Lt(t),Jt(t)}};function ye(){he||(he=!0,R("streams",Zt),t("streams",me),j(de,f))}const $e=new WeakMap;function we(t,e,n){let o=$e.get(t);void 0===o&&(o=new Map,$e.set(t,o)),o.set(e,n)}const ge=new Map;function ve(t,e){ge.has(t)||ge.set(t,e)}function be(t){return ge.get(t)}const ke=new WeakMap,je=new WeakMap,Oe=new Set,Pe=new Map;function Ie(t){return ke.get(t)??Pe}function xe(t){Oe.add(t),function(t){const e=D.get(t);void 0!==e&&(T(e)&&F.add(t),function(t){return t.eventResetByPath.size>0}(e)&&N.add(t))}(t)}function Se(){return Oe}function Ae(t,e){let n=je.get(t);void 0===n&&(n=new Map,je.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}const Me=new Map;function Ee(t){return je.get(t)??Me}function ze(t){0===t.length&&y(`[wcs/watch-declaration-invalid] ${h} entry name must be a non-empty state path.`),t.startsWith("$")&&y(`[wcs/watch-declaration-invalid] ${h} entry "${t}" must not start with "$" (reserved namespace).${$}`),t.includes("@")&&y(`[wcs/watch-declaration-invalid] ${h} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${$}`),t in Object.prototype&&y(`[wcs/watch-declaration-invalid] ${h} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=i(t);for(const n of e.segments)0===n.length&&y(`[wcs/watch-declaration-invalid] ${h} entry "${t}" has an empty path segment.${$}`);return e.wildcardCount>c&&y(`[wcs/watch-declaration-invalid] ${h} entry "${t}" exceeds the maximum wildcard depth (${c}).`),e}function We(t,e){const n=e[h];if(void 0===n)return null;"object"==typeof n&&null!==n||y(`[wcs/watch-declaration-invalid] ${h} must be an object mapping state paths to handler functions.${$}`);const o=new Map,r=new Set;let s=0;for(const[e,a]of Object.entries(n)){"function"!=typeof a&&y(`[wcs/watch-declaration-invalid] ${h} entry "${e}" must be a function.${$}`);const n=ze(e);o.set(e,{path:e,pathInfo:n,handler:a,order:s++}),r.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){ke.set(t,e)}(t,o),r.size>0?r:null}const Re={writeObserve(t,e,n,o,r){if(!r)return;const s=t.watchPaths,a=t.scanPaths;!0!==s?.has(e)&&!0!==a?.has(e)||ve(n,o)},swapped(t,e,n){var o;o=n,ge.has(o)&&ve(e,be(n))}};function Ce(t){for(let e=t;null!==e;e=e.parentListIndex)if(O(e))return!0;return!1}function _e(t,e,n){const o=n.absAddress.listIndex;let r="current",s=null;for(let a=0;a<e.wildcardCount;a++){const i=t[P](I(e.wildcardParentPathInfos[a],s)),c=x(i)?.[n.indexes[a]];if(void 0===c)return"gone";const u=S(o,a,e.wildcardCount);if(c!==u&&!A(c,u)){if(O(u))return"gone";r="replaced"}s=c}return r}function De(t,e,n){const o=new Map;for(const r of n){const n=_e(t,e,r);if("gone"===n)continue;const s="current"===n?1:0,a=r.indexes.join(","),i=o.get(a);(void 0===i||s>i.rank)&&o.set(a,{row:r,rank:s})}return Array.from(o.values(),t=>t.row)}const Fe=Object.freeze([]);function Ne(t,e,n,o){let r=t.get(n);return void 0===r&&(r={stateElement:e,entry:n,rows:[],reset:!1,depth:o},t.set(n,r)),r.depth=Math.max(r.depth,o),r}function Te(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function Le(t,e){return e.has(t.stateElement)&&!0===G(t.stateElement)?.entries.has(t.entry)}function Ge(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Be(n,t))||J(e)}function Be(t,e){return g().hasQueuedPath(t,e)}function He(t,e){!function(t,e,n){if(0!==q)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const r=Q(o);if(void 0!==r)for(const e of r)e.resetOn.some(e=>n(t,e))||J(e)}}(t,e,Be)}function Ke(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function qe(t,n,o){if(!Le(t,o))return Ge(t),null;const{stateElement:r,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const a=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(r,a))return function(t,n,o){if(ht.has(t))return;ht.add(t);const r=`[wcs/scan-source-computed] ${e} entry "${n}" from "${o}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${r}`),ut(n,"fold",new Error(r))}(s,s.name,a.path),null;if(function(t,e,n){const o=Tt(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(r,a.pathInfo.segments[0],n))return null;const i={plan:null,failure:"read-output"};try{r.createState("readonly",e=>{const n=e[s.name];i.failure="read-rows";const o=0===a.pathInfo.wildcardCount?t.rows:De(e,a.pathInfo,t.rows);i.failure="threw";const r=s.fold;let c=n;for(const t of o.sort(Te)){let n;try{n=Ke(e,a,t)}catch(t){lt(s.name,t,"read-source");continue}const o=r(c,n,be(t.absAddress),...t.indexes);if(ft(o))return void dt(s.name,o);c=o}Object.is(c,n)||(i.plan={group:t,next:c})})}catch(t){lt(s.name,t,i.failure)}return i.plan}function Qe(t,e){const{group:n}=t;if(!Le(n,e))return void Ge(n);const{stateElement:o,entry:r}=n;if(!n.reset||"event"!==r.source.kind||J(r))try{o.createState("writable",e=>{const o=e[r.name];if(n.reset?!ot(o,r.initial):!Object.is(o,t.next)){const o=n.reset?et(r.initial):t.next;e[r.name]=o,st(r.name,o)}})}catch(t){lt(r.name,t,"write")}}function Ue(t,e){if(He(t,e),0===F.size)return Fe;const n=new Map;for(const o of t){const r=o.absolutePathInfo.stateElement;if(!e.has(r))continue;const s=G(r);if(void 0===s)continue;const a=o.absolutePathInfo.pathInfo,i=ie(t,o),c=s.byFromPath.get(a.path);if(void 0!==c){let t=[];if(a.wildcardCount>0){if(null===o.listIndex)continue;t=M(o.listIndex,a.wildcardCount)}for(const e of c)Ne(n,r,e,i).rows.push({absAddress:o,indexes:t})}const u=s.byResetPath.get(a.path);if(void 0!==u)for(const t of u)Ne(n,r,t,i).reset=!0}if(0===n.size)return Fe;const o=Array.from(n.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];try{for(const n of o){re(n.depth);const o=qe(n,t,e);null!==o&&r.push(o)}}finally{se()}return r}function Ve(t){rn(),(0!==Ie(t).size||0!==Ee(t).size||function(t){const e=D.get(t);return void 0!==e&&T(e)}(t))&&(xe(t),function(t){const e=[];for(const n of Ie(t).values())Je(t,n)&&e.push(n);for(const n of Ee(t).values())for(const o of n)Je(t,o)&&e.push(o);if(0===e.length)return;t.createState("readonly",n=>{for(const o of e)try{we(t,E(t,o.pathInfo,null),n[o.path])}catch(e){Ye(t,o.path,"prime",e)}})}(t))}function Je(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Xe={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Ye(t,e,o,r){console.error(`[@wcstack/state] $watch ${Xe[o]} "${e}" threw.`,r),null!==n&&n({type:"state:watch-error",phase:o,path:e,error:r})}function Ze(t){const e=Se(),o=function(t){const e=ne;return e>0&&(oe.set(t,ee),ee=null,ne=0),e}(t);try{if(o>d){He(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:d,paths:e}),void(null!==n&&n({type:"state:watch-chain-limit",maxDepth:d,paths:e}))}if(0===e.size)return void He(t,e);!function(t,e){if(0!==t.length)try{for(const n of t)re(n.group.depth),Qe(n,e)}finally{se()}}(Ue(t,e),e),function(t,e){const n=[],o=new Set;for(const r of t){const t=r.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=r.absolutePathInfo.pathInfo.path;o.add(s);const a=Ie(t).get(s),i=Ee(t).get(s);if(void 0===a&&void 0===i)continue;const c=void 0===a?[]:[a];void 0!==i&&c.push(...i);for(const e of c){let o=[];if(e.pathInfo.wildcardCount>0){if(null===r.listIndex)continue;o=M(r.listIndex,e.pathInfo.wildcardCount)}n.push({stateElement:t,entry:e,absAddress:r,indexes:o})}}if(0===n.length)return;n.sort(en);const r=function(t,e){let n=null;for(let o=0;o<t.length;o++){const r=t[o];if(0===r.entry.pathInfo.wildcardCount)continue;const s=t[o-1];(Ce(r.absAddress.listIndex)||s?.entry===r.entry&&tn(s.indexes,r.indexes)||r.entry.pathInfo.wildcardParentPaths.some(t=>e.has(t)))&&(n??=new Set).add(r.entry)}if(null===n)return t;const o=new Set;for(const e of n){const n=t.filter(t=>t.entry===e),r=n[0].stateElement;try{r.createState("readonly",t=>{const r=new Set(De(t,e.pathInfo,n));for(const t of n)r.has(t)||o.add(t)})}catch(t){Ye(0,e.path,"evaluate",t);for(const t of n)o.add(t)}}return t.filter(t=>!o.has(t))}(n,o);try{for(const n of r){if(!e.has(n.stateElement))continue;const o=Ie(n.stateElement).get(n.entry.path)===n.entry,r=!0===Ee(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||r)&&(re(ie(t,n.absAddress)),nn(n))}}finally{se()}}(t,e)}finally{ge.clear()}}function tn(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function en(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function nn(t){const{stateElement:e,entry:o,absAddress:r,indexes:s}=t,a=Je(e,o);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){if(0===e.pathInfo.wildcardCount)return t[e.path];return t.$resolve(e.path,n)}(t,o,s)}catch(t){return void Ye(0,o.path,"evaluate",t)}const c=a?function(t,e){return $e.get(t)?.get(e)}(e,r):be(r);a&&we(e,r,i),null!==n&&n({type:"state:watch-fired",path:o.path,stateElement:e}),o.handler.call(t,i,c,...s)})}catch(t){Ye(0,o.path,"handler",t)}}let on=!1;function rn(){on||(on=!0,R("watch",Re),t("watch",sn),j(Ze,p),b(ae),_({assertValidPath:ze,addEntries:Ae,start:Ve}))}const sn={order:10,register(t,n){var o;o=t,Oe.delete(o),H(o),ke.delete(o),function(t){$e.delete(t)}(t);const r=We(t,n);t.setWatchPaths?.(r),null===r&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==r?h:e)},activate(t,e){C()||null==t.connectedRootNode||(null===e?!0===t.initialized:e===t.connectGeneration)&&Ve(t)},deactivate(t){var e;e=t,Oe.delete(e),H(e)}},an={name:"temporal",install(){rn(),At||(At=!0,t("scan",St),b(U)),ye()}};export{an as default,an as temporal};
2
- //# sourceMappingURL=temporal.js.map
1
+ import{a as t,c as e}from"../chunks/chunk-QI7P7YPP.js";import{a as n,b as r,c as i,d as s,e as l,j as o}from"../chunks/chunk-YOPPVWPQ.js";var a={},h=/\.\d/,u=new Set(Object.getOwnPropertyNames(Object.prototype)),f=0,c=!1,p=null,m=()=>{c=!1,f++};function d(){if(null===p)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=m,t.port1.unref?.(),p=()=>t.port2.postMessage(0)}else p=()=>setTimeout(m,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.Ae){for(let r of e)if(n.Y(r)&&(n.n===r.n||!(r.n<t.n&&t.c[r.n+1].Y(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var y=class{constructor(t,e){this.active=!1,this.ze=new Map,this.n=0,this.Eo=-1,this.Cn=new Set,this.Ee=null,this.engine=t,this.rt=e}Zo(){let t=this.engine;this.ze.clear();for(let e of this.rt)e.getter=null!==e.p.getter||e.p.ke,e.l=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.l.set(a,t.v(e.p,null)):this.In(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.l.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.tt?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}xo(){this.active=!1,this.ze.clear()}In(t,e,n,r){let i=this.engine.De(n,t.c[e]);for(let n of i.f)e===t.n?r(n):this.In(t,e+1,n,r)}ln(t,e,n,r){let i=this.ze.get(t);void 0===i&&this.ze.set(t,i=new Map);let s=i.get(e);void 0===s?i.set(e,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}pe(t,e,n,r,i){if(this.active){(this.Ee??=new Set).add(t);for(let s of this.rt){let l=s.p;l.n!==t.n||!l.Y(t)||this.ln(s,e,s.getter?s.l.get(e??a):l===t&&i&&this.engine.jt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}me(t,e){if(this.active)for(let n of this.rt)(n.getter||=null!==n.p.getter||n.p.ke)&&n.p.n===t.n&&n.p.Y(t)&&this.ln(n,e,n.l.get(e??a),!1)}qt(t,e){if(!this.active)return;let n=null;for(let r of this.rt){let i=r.p;if(!(i.n<t.n||i.c[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(i.n===t.n?this.ln(r,e,void 0,!0):this.In(i,t.n+1,e,t=>this.ln(r,t,void 0,!0)))}}}Pe(){let t=this.Ee;if(this.Ee=null,!this.active||0===this.ze.size)return;let e=this.ze;this.ze=new Map;let r=this.engine,i=[];for(let s of this.rt){let l=e.get(s);if(void 0===l)continue;let o,u=[...l].filter(([t])=>null===t||t.d);u.length>1&&u.sort((t,e)=>v(t[0],e[0]));for(let[e,[l,f,c]]of u){let u,p="evaluate",m=r.h;this.n=f+1,r.$e++;try{if(u=r.v(s.p,e),s.getter&&(s.l.set(e??a,u),Object.is(u,l)&&(h.test(s.t)||null!==e&&!c&&!(o??=null!==t&&g($(s.p),t)))))continue;if(f>32){i.includes(s.t)||i.push(s.t);continue}r.h=e,n.tt?.(r,{type:"state:watch-fired",path:s.t}),p="handler",s.handler.call(r.proxy,u,l,...r.D(e))}catch(t){console.error(`[@wcstack/state] $watch "${s.t}" failed; the other watches still run.`,t),n.tt?.(r,{type:"state:watch-error",phase:p,path:s.t,error:t})}finally{r.h=m,this.n=0,r.$e--}}}i.length>0&&this.No(i)}No(t){let e=d();e!==this.Eo&&(this.Eo=e,this.Cn.clear());let r=t.filter(t=>!this.Cn.has(t));if(0!==r.length){for(let t of r)this.Cn.add(t);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.tt?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function $(t){for(;null===t.getter&&null!==t.w;)t=t.w;return t}function v(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.s.te)n.unshift(e.b);for(let t=e;null!==t;t=t.s.te)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 w="$streamStatus",b="$streamError",j=new Set(Object.getOwnPropertyNames(Object.prototype)),z=!1;function P(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 k=class{constructor(t,e,n){this.jn=0,this.engine=t,this.entries=e,this.X=n}set(t,e,n){z=!0;try{this.engine.P(this.engine.o(`${t}.${e}`),null,n)}finally{z=!1}}er(){for(let t of this.entries)this.start(t,!0)}tr(){for(let t of this.entries)t.it=!1,t.z?.abort(),t.z=null}nr(){for(let t of this.entries)t.it=!1,null!==t.z&&(t.z.abort(),t.z=null),this.set(w,t.name,"idle")}me(t){let e=Math.max(this.X.n,this.jn);for(let n of this.entries)n.g===t&&(n.n=n.it?Math.max(n.n,e):e,n.it=!0)}Pe(){let t=this.engine,n=this.X,r=[];for(let i of this.entries){if(!i.it)continue;let s=i.n;if(i.it=!1,s>32)r.push(i.name),i.g.ee=e;else{n.n=s+1,t.$e++;try{this.start(i,!1)}finally{t.$e--,n.n=0}}}r.length>0&&n.No(r)}start(t,n){let r,i=this.engine;if(null!==t.z&&t.z.abort(),t.z=null,null!==t.g){let s=t.g;s.getter=t.args;let l=s.Ae.slice();O(s);try{r=i.read(s,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&o(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Ae)n.n>0&&o(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${w}.${t}`||n.t===`${b}.${t}`)&&o(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,s,r)}catch(r){O(s);for(let t of l)t.Ln(s);if(s.ee=e,n)throw r;return this.set(b,t.name,r),void this.set(w,t.name,"error")}}let s=new AbortController;t.z=s,i.P(i.o(t.name),null,t.W),this.set(b,t.name,null),this.set(w,t.name,"active"),this.or(t,s,r)}async or(t,e,n){let r=this.engine,i=e.signal,s=()=>!i.aborted&&t.z===e,l=r.o(t.name),o=this.X.n,a=d(),h=t.W;try{let e=await t.source(n,i);if(!s())return;let u=e=>{h=void 0!==t.Ro?t.Ro(h,e):e,this.jn=d()===a?o:0;try{r.P(l,null,h)}finally{this.jn=0}};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(i.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!s())return;if(e.done)break;u(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(i.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!s())return;if(e.done)break;u(e.value)}}}if(!s())return;t.z=null,this.set(w,t.name,"done")}catch(n){if(!s())return;t.z=null,e.abort(),this.set(b,t.name,n),this.set(w,t.name,"error")}}};function O(e){for(let t of e.Ae){let n=t.at.indexOf(e);n>=0&&t.at.splice(n,1),t.Tt.delete(e)}e.Ae.length=0,e.ee=t}var E=new WeakMap;function X(t){let e=E.get(t);return e?.target===t.target?e:void 0}function M(t,e){let r=new y(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&o("$watch must be an object mapping paths to handler functions.");let r=[];for(let i of Object.keys(e)){let s=e[i];(""===i||"$"===i[0]||i.includes("@")||u.has(i))&&o(`$watch path "${i}" is not a path of the state tree.`),"function"!=typeof s&&o(`$watch entry "${i}" must be a function.`);let l=t.o(i);n.yo?.(t,l,!0),r.push({t:i,p:l,handler:s,getter:!1,l:new WeakMap})}return r}(t,e.$watch)),i=new k(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&o("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let l of Object.keys(n)){let a=n[l];(""===l||"$"===l[0]||/[.*]/.test(l)||j.has(l))&&o(`$stream entry "${l}" must be a flat property name.`),(null===a||"object"!=typeof a)&&o(`$stream entry "${l}" must be an object.`);let h=a.source,u=a.fold,f=a.args,c=a.initial;"function"!=typeof h&&o(`$stream entry "${l}" needs a source function.`),void 0!==u&&"function"!=typeof u&&o(`$stream entry "${l}": fold must be a function.`),void 0!==u&&!("initial"in a)&&o(`$stream entry "${l}": fold needs an initial value.`),void 0!==f&&"function"!=typeof f&&o(`$stream entry "${l}": args must be a function.`),P(e,l)&&o(`$stream entry "${l}" collides with a getter, setter or method of the state.`),void 0===e[l]&&(e[l]=c),i[l]="idle",s[l]=null,r.push({name:l,source:h,Ro:u,W:c,z:null,it:!1,n:0,g:void 0===f?null:t.o(`$streamArgs.${l}`),args:void 0===f?null:function(){return f(this)}})}return e[w]=i,e[b]=s,r}(t,e),r),s=E.get(t);void 0!==s&&(s.X.xo(),s.Nt.tr()),E.set(t,{X:r,Nt:i,qe:s?.qe??!1,target:e})}function N(t,e){let n=E.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.qe="connected"===e),n.target===t.target)){if("disconnected"===e)return n.X.xo(),void n.Nt.nr();n.qe&&(n.X.Zo(),n.Nt.er())}}var S=["$streamStatus","$streamError"],x={name:"temporal",install(){n.ie=r(n.ie,M),n.element=r(n.element,N),n.pe=r(n.pe,(t,e,n,r,i,s)=>X(t)?.X.pe(e,n,r,i,s)),n.me=r(n.me,(t,e,n)=>{let r=X(t);void 0!==r&&(r.X.me(e,n),r.Nt.me(e))}),n.qt=r(n.qt,(t,e,n)=>X(t)?.X.qt(e,n)),n.Pe=r(n.Pe,t=>{let e=X(t);void 0!==e&&(e.X.Pe(),e.Nt.Pe())}),n.Kt=i(l,n.Kt,(t,e)=>{let n=e.split(".",1)[0];if(S.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Re=i(s,n.Re,(t,e)=>(!z&&36===e.t.charCodeAt(0)&&S.includes(e.t.split(".",1)[0])&&o(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},A=x;export{A as default,x as temporal};
@@ -21,7 +21,8 @@
21
21
  "flags": [
22
22
  "prevent",
23
23
  "stop",
24
- "ro"
24
+ "ro",
25
+ "direct"
25
26
  ],
26
27
  "keyValue": [
27
28
  "init",
@@ -62,6 +63,16 @@
62
63
  "mod",
63
64
  "abs",
64
65
  "clamp",
66
+ "int",
67
+ "float",
68
+ "falsy",
69
+ "truthy",
70
+ "defaults",
71
+ "coalesce",
72
+ "boolean",
73
+ "number",
74
+ "string",
75
+ "nullIfEmpty",
65
76
  "toFixed",
66
77
  "locale",
67
78
  "upper",
@@ -69,15 +80,12 @@
69
80
  "capitalize",
70
81
  "trim",
71
82
  "slice",
72
- "substr",
73
83
  "padStart",
74
84
  "padEnd",
75
85
  "repeat",
76
86
  "reverse",
77
87
  "truncate",
78
88
  "join",
79
- "int",
80
- "float",
81
89
  "round",
82
90
  "floor",
83
91
  "ceil",
@@ -87,15 +95,7 @@
87
95
  "time",
88
96
  "datetime",
89
97
  "ymd",
90
- "hms",
91
- "falsy",
92
- "truthy",
93
- "defaults",
94
- "coalesce",
95
- "boolean",
96
- "number",
97
- "string",
98
- "nullIfEmpty"
98
+ "hms"
99
99
  ],
100
100
  "filterMeta": {
101
101
  "eq": {
@@ -353,20 +353,6 @@
353
353
  "number"
354
354
  ]
355
355
  },
356
- "substr": {
357
- "description": "部分文字列 (pos,len)",
358
- "hasArgs": true,
359
- "resultType": "string",
360
- "acceptTypes": [
361
- "string"
362
- ],
363
- "minArgs": 2,
364
- "maxArgs": 2,
365
- "argTypes": [
366
- "number",
367
- "number"
368
- ]
369
- },
370
356
  "padStart": {
371
357
  "description": "先頭を埋める (length[,char]。char の既定は 0 — JS の既定は空白なので注意)",
372
358
  "hasArgs": true,
@@ -661,26 +647,9 @@
661
647
  "maxArgs": 0
662
648
  }
663
649
  },
664
- "filterAliases": {
665
- "inc": "add",
666
- "dec": "sub",
667
- "fix": "toFixed",
668
- "uc": "upper",
669
- "lc": "lower",
670
- "cap": "capitalize",
671
- "rep": "repeat",
672
- "rev": "reverse",
673
- "pad": "padStart",
674
- "null": "nullIfEmpty"
675
- },
676
- "declarationAliases": {
677
- "$updatedCallback": "$renderedCallback",
678
- "$streams": "$stream"
679
- },
680
- "apiAliases": {
681
- "$trackDependency": "$dependOn",
682
- "$untrackDependency": "$untracked"
683
- },
650
+ "filterAliases": {},
651
+ "declarationAliases": {},
652
+ "apiAliases": {},
684
653
  "reservedLifecycle": [
685
654
  "$connectedCallback",
686
655
  "$disconnectedCallback",
@@ -697,10 +666,35 @@
697
666
  "$on",
698
667
  "$stream",
699
668
  "$watch",
700
- "$scan",
701
669
  "$listKeys",
702
670
  "$recursion",
703
671
  "$streamStatus",
704
- "$streamError"
672
+ "$streamError",
673
+ "$behavior",
674
+ "$features"
675
+ ],
676
+ "behaviorOptions": {
677
+ "enableMustache": {
678
+ "type": "boolean",
679
+ "default": true
680
+ },
681
+ "sameValueGuard": {
682
+ "type": "boolean",
683
+ "default": true
684
+ },
685
+ "enableDirectionalInitialSync": {
686
+ "type": "boolean",
687
+ "default": true
688
+ }
689
+ },
690
+ "features": [
691
+ "formats",
692
+ "diagnostics",
693
+ "temporal",
694
+ "list-keys",
695
+ "scopes",
696
+ "recursion",
697
+ "ssr",
698
+ "devtools"
705
699
  ]
706
700
  }