@wcstack/state 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.ja.md +128 -90
  2. package/README.md +129 -91
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/define.d.ts +11 -7
  6. package/dist/index.d.ts +58 -15
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/manifest.d.ts +39 -5
  10. package/dist/manifest.esm.js +315 -253
  11. package/dist/parser.d.ts +16 -2
  12. package/dist/parser.esm.js +223 -50
  13. package/dist/split/chunks/binder.js +1 -1
  14. package/dist/split/chunks/binder.js.map +1 -1
  15. package/dist/split/chunks/checkDependency.js +1 -1
  16. package/dist/split/chunks/declarationAliases.js +2 -0
  17. package/dist/split/chunks/declarationAliases.js.map +1 -0
  18. package/dist/split/chunks/declarationHooks.js +2 -0
  19. package/dist/split/chunks/declarationHooks.js.map +1 -0
  20. package/dist/split/chunks/featureBridge.js +2 -0
  21. package/dist/split/chunks/featureBridge.js.map +1 -0
  22. package/dist/split/chunks/filterRegistry.js +1 -1
  23. package/dist/split/chunks/filterRegistry.js.map +1 -1
  24. package/dist/split/chunks/getAllPropertyDescriptors.js +1 -1
  25. package/dist/split/chunks/getAllPropertyDescriptors.js.map +1 -1
  26. package/dist/split/chunks/lifecycleHooks.js +1 -1
  27. package/dist/split/chunks/pathDiagnostics.js +1 -1
  28. package/dist/split/chunks/pathDiagnostics.js.map +1 -1
  29. package/dist/split/chunks/registerComponents.js +1 -1
  30. package/dist/split/chunks/registerComponents.js.map +1 -1
  31. package/dist/split/chunks/setAll.js +1 -1
  32. package/dist/split/chunks/setAll.js.map +1 -1
  33. package/dist/split/chunks/version.js +1 -1
  34. package/dist/split/core.d.ts +21 -9
  35. package/dist/split/core.js +1 -1
  36. package/dist/split/core.js.map +1 -1
  37. package/dist/split/features/devtools.js +1 -1
  38. package/dist/split/features/devtools.js.map +1 -1
  39. package/dist/split/features/diagnostics.js +1 -1
  40. package/dist/split/features/diagnostics.js.map +1 -1
  41. package/dist/split/features/formats.js +1 -1
  42. package/dist/split/features/formats.js.map +1 -1
  43. package/dist/split/features/recursion.js +1 -1
  44. package/dist/split/features/recursion.js.map +1 -1
  45. package/dist/split/features/scopes.js +1 -1
  46. package/dist/split/features/scopes.js.map +1 -1
  47. package/dist/split/features/ssr.js +1 -1
  48. package/dist/split/features/ssr.js.map +1 -1
  49. package/dist/split/features/temporal.js +1 -1
  50. package/dist/split/features/temporal.js.map +1 -1
  51. package/dist/wcs-manifest.json +98 -44
  52. package/package.json +1 -1
  53. package/dist/split/chunks/mount.js +0 -2
  54. package/dist/split/chunks/mount.js.map +0 -1
  55. package/dist/split/chunks/watchRuntime.js +0 -2
  56. package/dist/split/chunks/watchRuntime.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import{i as t,c as e,a as s}from"./filterRegistry.js";import{l as n,a,b as i,c as o,d as r,e as l,f as d,g as h,h as c,i as u}from"./lifecycleHooks.js";import{r as p,d as f}from"./errorGuidance.js";import{d as _,k as m,l as g,af as y,c as b,x as k,I as S,ag as w,H as P,ah as v,ai as $,aj as C,ak as x,al as I,am as A,an as N,ao as E,ap as z,G as D,j as L,y as R,o as j,aq as H,ar as O,as as T,at as G,au as M,g as F,av as U,aw as W,ax as V,ay as q}from"./binder.js";import{u as K,v as B,w as J,b as Q,x as X,m as Y,D as Z,W as tt,R as et,y as st,z as nt,o as at,A as it,I as ot,B as rt,M as lt,c as dt,d as ht,g as ct,N as ut,i as pt,l as ft,C as _t,f as mt}from"./pathDiagnostics.js";import{d as gt,e as yt,w as bt,f as kt,r as St,c as wt,b as Pt,g as vt,s as $t,h as Ct,a as xt,i as It}from"./setAll.js";import{N as At,g as Nt,b as Et,c as zt,d as Dt,e as Lt,f as Rt,h as jt,i as Ht,j as Ot,k as Tt,l as Gt,m as Mt,n as Ft}from"./getAllPropertyDescriptors.js";import{p as Ut}from"./diagnosticsHooks.js";class Wt{_loopContextStack=Array(K).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&p("Cannot create loop context for a state address that does not have a list index.");const s=t;this._length>=K&&p(`Exceeded maximum loop context stack depth of ${K}. Possible infinite loop.`);const n=this._loopContextStack[this._length-1];if(void 0!==n){n.pathInfo.wildcardCount+1!==s.pathInfo.wildcardCount&&p("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=s.pathInfo.wildcardPathInfos[s.pathInfo.wildcardPathInfos.length-2];n.pathInfo!==t&&p("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else s.listIndex.length!==s.pathInfo.wildcardCount&&p(`Cannot push loop context when there is no active loop context: the list index chain (length ${s.listIndex.length}) does not cover the wildcard path (wildcard count ${s.pathInfo.wildcardCount}).`);let a;this._loopContextStack[this._length]=s,this._length++;try{a=e(s)}finally{a instanceof Promise?a.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return a}}function Vt(t,e){const s=t.getterPaths;if(0===s.size)return!1;for(const t of ct(e).cumulativePaths)if(s.has(t))return!0;return!1}const qt=/^\$\d+$/,Kt=`${dt}${Z}`,Bt=`${ht}${Z}`,Jt=new WeakMap;function Qt(t,e,s,n){const a=ot[e];if(void 0===a&&"string"==typeof e&&36===e.charCodeAt(0)&&qt.test(e)&&p(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from ${rt}1 to ${rt}${lt}, with no leading zeros.`),void 0!==a){0===n.addressStackLength&&p(`No active state reference to get list index for "${e.toString()}".`);const t=n.lastAddressStack,s=t?.pathInfo;s&&!n.untracking&&n.stateElement?.getterPaths.has(s.path)&&n.stateElement.addIndexDependentGetterPath?.(s.path);const i=t?.listIndex;null==i&&p(`ListIndex not found: ${e.toString()}`);let o=a;const r=t.pathInfo,l=n.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let s=0;s<e.length;s++)o+=e[s](n,t)}const d=S(i,o,r.wildcardCount);return d?.index??p(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const a=n.stateElement?.addressHooks;if(a){const i=a.get;for(let a=0;a<i.length;a++){const o=i[a](n,e,s,t);if(o!==At)return o}}if("$"===e[0]){switch(e){case"$stateElement":return n.stateElement;case"$getAll":return(a,i)=>Pt(t,e,s,n)(a,i);case"$setAll":return(a,i,o,r)=>wt(t,e,s,n)(a,i,o,r);case"$postUpdate":return e=>function(t,e,s,n){const a=n.stateElement;return e=>{const i=gt(e),o=yt(t,i,s,n),r=m(i.pathInfo,o),l=g(a,r),d=b();d.enqueueAbsoluteAddress(l),bt(n.stateElement,r,n.stateElement.staticDependency,n.stateElement.dynamicDependency,n.stateElement.listPaths,s,"new",t=>{const e=g(a,t);y(e),d.enqueueAbsoluteAddress(e)});const h=a.addressHooks;if(h){const t=h.written;for(let e=0;e<t.length;e++)t[e](a,r.pathInfo)}}}(t,0,s,n)(e);case"$resolve":return(a,i,...o)=>St(t,e,s,n)(a,i,...o);case"$trackDependency":return t=>function(t,e,s,n){return t=>{-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===n.addressStackLength&&p(`No active state reference to track dependency for path "${t}".`);const e=n.lastAddressStack?.pathInfo??p("Internal error: lastAddressStack is null"),s=n.stateElement;n.stateElement.getterPaths.has(e.path)&&e.path!==t&&s.addDynamicDependency(t,e.path)}}(0,0,0,n)(t);case"$eq":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;if(Vt(n.stateElement,t))return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],e);let i;n.beginUntrack();try{i=s[t]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&C(n.stateElement,t,e,g(n.stateElement,a),i),Object.is(i,e)};case"$eqPath":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null,i=Vt(n.stateElement,t);let o,r=i?s[t]:void 0;n.beginUntrack();try{i||(r=s[t]),o=s[e]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&(i?w(n.stateElement,t):C(n.stateElement,t,o,g(n.stateElement,a),r)),Object.is(r,o)};case"$eqIndex":return(t,e=1)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;null!==a&&null!==a.listIndex||p(`$eqIndex("${t}") needs a list row scope.`);const i=S(a.listIndex,e-1,a.pathInfo.wildcardCount);if(null===i&&p(`$eqIndex("${t}", ${e}): no list index at that level.`),Vt(n.stateElement,t))return n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],i.index);const o=e===a.pathInfo.wildcardCount;let r,l;n.beginUntrack();try{r=s[t],o&&(l=s[a.pathInfo.wildcardParentPaths[e-1]])}finally{n.endUntrack()}if(n.stateElement.getterPaths.has(a.pathInfo.path)){const e=o?P(l):null;null!==e?v(n.stateElement,t,a.pathInfo,e,r):$(n.stateElement,t,i,g(n.stateElement,a),r)}return Object.is(r,i.index)};case"$untrackDependency":return t=>function(t,e,s,n){return t=>{n.beginUntrack();try{return t()}finally{n.endUntrack()}}}(0,0,0,n)(t);case J:return kt(n.stateElement)}if(!e.startsWith(Kt)&&!e.startsWith(Bt))return}const i=gt(e),o=yt(t,i,s,n),r=m(i.pathInfo,o);return vt(t,r,s,n)}if("symbol"==typeof e){const a=function(t){let e=Jt.get(t);return void 0===e&&(e=new Map,Jt.set(t,e)),e}(n),i=a.get(e);if(void 0!==i)return i;let o;switch(e){case L:o=(t,e=()=>{})=>function(t,e,s){void 0!==t.loopContext&&p("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return s()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(n,t,e);break;case D:o=e=>vt(t,e,s,n);break;case z:o=e=>Ct(t,e,s,n);break;case E:o=(e,a)=>$t(t,e,a,s,n);break;case N:o=()=>async function(t,e,s){const n=Reflect.get(t,st);"function"==typeof n&&await n.call(s)}(t,0,s);break;case A:o=()=>function(t,e,s){const n=Reflect.get(t,nt);"function"==typeof n&&n.call(s)}(t,0,s);break;case I:o=e=>function(t,e,s,n){const a=Reflect.get(t,at);let i;if("function"==typeof a){const t=new Set,o={};for(const s of e){if(s.absolutePathInfo.stateElement!==n.stateElement)continue;const e=s.absolutePathInfo.pathInfo,a=e.path;if(-1===a.indexOf("#")&&(t.add(a),e.wildcardCount>0)){const t=k(s.listIndex,e.wildcardCount),n=o[a];void 0===n?o[a]=[t]:n.push(t)}}i=a.call(s,Array.from(t),o)}const o=n.stateElement?.addressHooks;if(o){const t=o.updated;for(let a=0;a<t.length;a++)t[a](n.stateElement,e,s)}return i}(t,e,s,n);break;case x:o=(e,n)=>function(t,e,s,n){const a=Reflect.get(t,it);"function"==typeof a&&a.call(n,e,s)}(t,e,n,s);break;default:return Reflect.get(t,e,s)}return a.set(e,o),o}}class Xt{_stateElement;_addressStack=Array(K).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const s=R(t);null===s&&p("StateHandler: no state tree found on this root."),this._stateElement=s,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&p("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=K&&(this._hasRepeatedAddress()&&p(`[wcs/getter-cycle] Exceeded maximum address stack depth of ${K}. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),p(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of ${K} with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const s=this._addressStack[e];if(s){if(t.has(s))return!0;t.add(s)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const s=this._addressStack[e];s&&t.push(s.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&p(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,s){return Qt(t,e,s,this)}set(t,e,s,n){return xt(this),function(t,e,s,n,a){if("string"==typeof e){const i=gt(e),o=yt(t,i,n,a),r=m(i.pathInfo,o);return $t(t,r,s,n,a)}return Reflect.set(t,e,s,n)}(t,e,s,n,this)}has(t,e){return Reflect.has(t,e)}}const Yt="undefined"==typeof HTMLElement?class{}:HTMLElement;const Zt=new Set(["for","if","elseif","else"]);function te(e,s,n){const a=new Map;for(const t of n){const e=ct(t);if(null===e.lastWildcardPath)continue;const s=a.get(e.lastWildcardPath);void 0===s?a.set(e.lastWildcardPath,[e]):s.push(e)}const i=[],o=new Set,r=t=>{const s=g(e,t);if(o.has(s))return;o.add(s);const n=G(s);if(n instanceof Set?i.push(...n):void 0!==n&&i.push(n),null!==t.listIndex){const e=a.get(t.pathInfo.path);if(void 0!==e)for(const s of e)r(m(s,t.listIndex))}};M();try{if(e.createState("readonly",t=>{for(const n of s){const s=m(ct(n),null);r(s);try{bt(e,s,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",r)}catch{}}}),0===i.length)return;const n=function(t){const e=[],s=[];for(const n of t)Zt.has(n.bindingType)?e.push(n):s.push(n);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(s)}(i),a=()=>{j(n,void 0,{updatedCallback:!1})};if(t())return void a();const o=H("state",a);void 0!==o&&o.catch(O)}finally{T()}}class ee extends Yt{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return F(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Wt}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&p(`${e.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const e=this.__state,s=Ft();s.set("previousState",e),Et(this,t,s);const n=function(t){const e=new Set,s=t[B];if(void 0===s)return e;Array.isArray(s)||p(`${B} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${B} entries must be non-empty strings.`),t===J&&p(`${B} entry "${t}" conflicts with the reserved namespace name "${J}".`),e.has(t)&&p(`${B} entry "${t}" is duplicated.`),e.add(t);return e}(t),a=function(t){const e=new Set,s=t[Q];if(void 0===s)return e;Array.isArray(s)||p(`${Q} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${Q} entries must be non-empty strings.`),e.has(t)&&p(`${Q} entry "${t}" is duplicated.`),e.add(t);return e}(t),i=function(t){const e=t[Y];if(void 0===e)return null;"object"==typeof e&&null!==e||p(`${Y} must be an object mapping list paths to key specs.`);const s=new Map;for(const[t,n]of Object.entries(e)){0===t.length&&p(`${Y} entry path must be a non-empty string.`);const e=t.split(Z);e.some(t=>0===t.length)&&p(`${Y} entry "${t}" must not contain empty path segments.`),e[e.length-1]===tt&&p(`${Y} entry "${t}" must be the list path itself, not the element path (drop the trailing "${Z}${tt}").`),-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] ${Y} entry "${t}" uses "${et}", which ${Y} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${Z}${tt}${Z}children").`),"function"!=typeof n?("string"!=typeof n&&p(`${Y} entry "${t}" key spec must be a field name (string) or a function.`),0===n.length&&p(`${Y} entry "${t}" key field name must be a non-empty string.`),(n.includes(Z)||n.includes(tt))&&p(`${Y} entry "${t}" key field name "${n}" must be a flat property name ("${Z}" / "${tt}" are not allowed).`),n in Object.prototype&&p(`${Y} entry "${t}" key field name "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),s.set(t,n)):s.set(t,n)}return s.size>0?s:null}(t);s.set("eventTokenNames",a),zt(this,t,s),Dt(this,t,s),this._commandTokenNames=n,this._eventTokenNames=a,this._stateGeneration++,this.__state=t,void 0!==e&&Ut?.reset(this),this._hasUpdatedCallback=at in t,this._hasErrorCallback=it in t,U(this),Lt(this,t,s),function(t,e,s){const n=e[X];if(void 0!==n){"object"==typeof n&&null!==n||p(`${X} must be an object mapping event-token names to handler functions.`);for(const[e,a]of Object.entries(n))s.has(e)||p(`${X} entry "${e}" is not declared in $eventTokens.${f(e,s)}`),"function"!=typeof a&&p(`${X} entry "${e}" must be a function.`),_(t,e).subscribe(a)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const o=function(t){const e=new Set,s=new Set,n=Nt(t);for(const[t,a]of Object.entries(n))"function"==typeof a.get&&e.add(t),"function"==typeof a.set&&s.add(t);return{getterPaths:e,setterPaths:s}}(t);for(const t of o.getterPaths)this._getterPaths.add(t);for(const t of o.setterPaths)this._setterPaths.add(t);Rt(this,t,s),this._listKeys=i,this._rebuildPathInfo(),jt(this,t,s),Ht(this,null),this._resolveLoading?.()}attributeChangedCallback(t,s,n){this._initialized&&s!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===s?"absent":`"${s}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${e.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?W('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){p("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await a(t,e.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${e.tagNames.state}> element.`)},ut),s=await this._setStatePromise;return clearTimeout(t),s}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||p(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await n(t);p(`Unsupported src file type: ${t}`)}}catch(t){p(`Failed to initialize state: ${t}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,s]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=s}return await this._loadingPromise,null!==this._rootNode&&(V(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),p(t)}_failInitializeLoudly(t,s=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${e.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),s&&null!==this._rootNode&&null===R(this._rootNode)&&(q(this._rootNode,t),i(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{st in t&&await t[N]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{nt in t&&t[A]()})}async connectedCallback(){this._rootNode=this.getRootNode();const n=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(d(this))return void this._resolveConnectedCallback?.();this._treeless||R(this._rootNode)===this||V(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const t=o(this);if(null!==t)return void await t;const s=this.parentNode;if(s instanceof ShadowRoot&&s.host.hasAttribute(pt))try{r("dcc",`a <${e.tagNames.state}> inside a [${pt}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{r("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let n=!1;try{const t=l(this);null===t&&this.hasAttribute("bind-component")&&r("scopes",'the "bind-component" attribute'),n=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(n)return;let a=!1;try{a=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!a)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!t()||n!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!s())try{await W('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Ht(this,n),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!h(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&c(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{V(this.rootNode,null),It(this),Ot(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource()}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const s of t)e.add(s);this._watchPaths=e,this.attachAddressHooks("watch",ft)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[s,n]of t)e.has(s)&&p(`$listKeys entry "${s}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(s,n);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return _t(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&p("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const s=Tt(t,e);null===this._addressHooks&&(this._addressHooks=Gt()),Mt(this._addressHooks,s)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",mt)}_addDependency(t,e,s){const n=t.get(e);return void 0===n?(t.set(e,[s]),!0):!n.includes(s)&&(n.push(s),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,s="binding"){if("internal"!==s){const n=this._pathRegistrations.get(t);void 0===n?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===s}):"for"!==n.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:n.bound||"binding"===s})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+tt)),!this._pathSet.has(t)){const e=ct(t);if(this._pathSet.add(t),Ut?.check(this,this.__state,t,s),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ct(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,s){try{const n=function(t,e,s){const n=new Xt(t,s);return new Proxy(e,n)}(t,this._state,e);return s(n)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&p(`<${e.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);u(this),(this._hasGraftedVolumes||this._hasMounts)&&p("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const s=this.__state;this._state=t;const n=function(t){const e=new Set;for(const s of t)if(void 0!==s)for(const[t,n]of Object.entries(Nt(s)))t.startsWith("$")||t.includes(tt)||"function"==typeof n.value||e.add(t);return e}([s,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){te(this,t,this._pathRegistrations.keys())}}const se=[];function ne(t){se.includes(t)||se.push(t)}function ae(t=customElements){for(let e=0;e<se.length;e++)se[e](t);t.get(e.tagNames.state)||t.define(e.tagNames.state,ee)}export{Yt as H,ne as a,ae as r};
1
+ import{i as t,c as e,a as s}from"./filterRegistry.js";import{l as n,a,b as i,c as o,d as r,e as l,f as d,g as c,h,i as u}from"./lifecycleHooks.js";import{r as p,d as f}from"./errorGuidance.js";import{d as _,j as m,l as g,ai as y,c as b,o as k,m as S,aj as w,k as P,ak as $,al as v,am as C,an as x,ao as I,ap as A,aq as N,ar as E,h as z,w as R,F as D,z as L,as as j,at as O,au as H,av as T,aw as G,g as M,ax as F,ay as U,az as W,aA as q,aB as V}from"./binder.js";import{u as B,v as K,w as J,b as Q,x as X,q as Y,D as Z,W as tt,R as et,y as st,z as nt,o as at,A as it,I as ot,B as rt,M as lt,c as dt,e as ct,g as ht,N as ut,m as pt,h as ft,C as _t,k as mt,S as gt,a as yt,r as bt}from"./pathDiagnostics.js";import{n as kt}from"./declarationAliases.js";import{d as St,e as wt,n as Pt,w as $t,g as vt,f as Ct,r as xt,c as It,b as At,h as Nt,s as Et,a as zt,i as Rt}from"./setAll.js";import{N as Dt,g as Lt,a as jt,c as Ot,b as Ht}from"./getAllPropertyDescriptors.js";import{a as Tt,b as Gt,c as Mt,d as Ft,e as Ut,f as Wt,g as qt,h as Vt,i as Bt,j as Kt}from"./declarationHooks.js";import{p as Jt}from"./diagnosticsHooks.js";class Qt{_loopContextStack=Array(B).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&p("Cannot create loop context for a state address that does not have a list index.");const s=t;this._length>=B&&p(`Exceeded maximum loop context stack depth of ${B}. Possible infinite loop.`);const n=this._loopContextStack[this._length-1];if(void 0!==n){n.pathInfo.wildcardCount+1!==s.pathInfo.wildcardCount&&p("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=s.pathInfo.wildcardPathInfos[s.pathInfo.wildcardPathInfos.length-2];n.pathInfo!==t&&p("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else s.listIndex.length!==s.pathInfo.wildcardCount&&p(`Cannot push loop context when there is no active loop context: the list index chain (length ${s.listIndex.length}) does not cover the wildcard path (wildcard count ${s.pathInfo.wildcardCount}).`);let a;this._loopContextStack[this._length]=s,this._length++;try{a=e(s)}finally{a instanceof Promise?a.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return a}}function Xt(t,e){const s=t.getterPaths;if(0===s.size)return!1;for(const t of ht(e).cumulativePaths)if(s.has(t))return!0;return!1}const Yt=/^\$\d+$/,Zt=`${dt}${Z}`,te=`${ct}${Z}`,ee=new WeakMap;function se(t,e,s,n){const a=ot[e];if(void 0===a&&"string"==typeof e&&36===e.charCodeAt(0)&&Yt.test(e)&&p(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from ${rt}1 to ${rt}${lt}, with no leading zeros.`),void 0!==a){0===n.addressStackLength&&p(`No active state reference to get list index for "${e.toString()}".`);const t=n.lastAddressStack,s=t?.pathInfo;s&&!n.untracking&&n.stateElement?.getterPaths.has(s.path)&&n.stateElement.addIndexDependentGetterPath?.(s.path);const i=t?.listIndex;null==i&&p(`ListIndex not found: ${e.toString()}`);let o=a;const r=t.pathInfo,l=n.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let s=0;s<e.length;s++)o+=e[s](n,t)}const d=S(i,o,r.wildcardCount);return d?.index??p(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const a=n.stateElement?.addressHooks;if(a){const i=a.get;for(let a=0;a<i.length;a++){const o=i[a](n,e,s,t);if(o!==Dt)return o}}if("$"===e[0]){switch(e){case"$stateElement":return n.stateElement;case"$getAll":return(a,i)=>At(t,e,s,n)(a,i);case"$setAll":return(a,i,o,r)=>It(t,e,s,n)(a,i,o,r);case"$postUpdate":return e=>function(t,e,s,n){const a=n.stateElement;return e=>{const i=St(e),o=wt(t,i,s,n),r=m(i.pathInfo,o),l=g(a,r),d=b();d.enqueueAbsoluteAddress(l),Pt(a,i.pathInfo.path,()=>vt(t,r,s,n),s,n),$t(n.stateElement,r,n.stateElement.staticDependency,n.stateElement.dynamicDependency,n.stateElement.listPaths,s,"new",t=>{const e=g(a,t);y(e),d.enqueueAbsoluteAddress(e)});const c=a.addressHooks;if(c){const t=c.written;for(let e=0;e<t.length;e++)t[e](a,r.pathInfo)}}}(t,0,s,n)(e);case"$resolve":return(a,i,...o)=>xt(t,e,s,n)(a,i,...o);case"$dependOn":case"$trackDependency":return t=>function(t,e,s,n){return t=>{-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] ${String(e)}("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===n.addressStackLength&&p(`No active state reference to track dependency for path "${t}".`);const s=n.lastAddressStack?.pathInfo??p("Internal error: lastAddressStack is null"),a=n.stateElement;n.stateElement.getterPaths.has(s.path)&&s.path!==t&&a.addDynamicDependency(t,s.path)}}(0,e,0,n)(t);case"$eq":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;if(Xt(n.stateElement,t))return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],e);let i;n.beginUntrack();try{i=s[t]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&C(n.stateElement,t,e,g(n.stateElement,a),i),Object.is(i,e)};case"$eqPath":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null,i=Xt(n.stateElement,t);let o,r=i?s[t]:void 0;n.beginUntrack();try{i||(r=s[t]),o=s[e]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&(i?w(n.stateElement,t):C(n.stateElement,t,o,g(n.stateElement,a),r)),Object.is(r,o)};case"$eqIndex":return(t,e=1)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;null!==a&&null!==a.listIndex||p(`$eqIndex("${t}") needs a list row scope.`);const i=S(a.listIndex,e-1,a.pathInfo.wildcardCount);if(null===i&&p(`$eqIndex("${t}", ${e}): no list index at that level.`),Xt(n.stateElement,t))return n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],i.index);const o=e===a.pathInfo.wildcardCount;let r,l;n.beginUntrack();try{r=s[t],o&&(l=s[a.pathInfo.wildcardParentPaths[e-1]])}finally{n.endUntrack()}if(n.stateElement.getterPaths.has(a.pathInfo.path)){const e=o?P(l):null;null!==e?$(n.stateElement,t,a.pathInfo,e,r):v(n.stateElement,t,i,g(n.stateElement,a),r)}return Object.is(r,i.index)};case"$untracked":case"$untrackDependency":return t=>function(t,e,s,n){return t=>{n.beginUntrack();try{return t()}finally{n.endUntrack()}}}(0,0,0,n)(t);case J:return Ct(n.stateElement)}if(!e.startsWith(Zt)&&!e.startsWith(te))return}const i=St(e),o=wt(t,i,s,n),r=m(i.pathInfo,o);return vt(t,r,s,n)}if("symbol"==typeof e){const a=function(t){let e=ee.get(t);return void 0===e&&(e=new Map,ee.set(t,e)),e}(n),i=a.get(e);if(void 0!==i)return i;let o;switch(e){case R:o=(t,e=()=>{})=>function(t,e,s){void 0!==t.loopContext&&p("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return s()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(n,t,e);break;case z:o=e=>vt(t,e,s,n);break;case E:o=e=>Nt(t,e,s,n);break;case N:o=()=>async function(t,e,s){const n=Reflect.get(t,st);"function"==typeof n&&await n.call(s)}(t,0,s);break;case A:o=()=>function(t,e,s){const n=Reflect.get(t,nt);"function"==typeof n&&n.call(s)}(t,0,s);break;case I:o=e=>function(t,e,s,n){const a=Reflect.get(t,at);let i;if("function"==typeof a){const t=new Set,o={};for(const s of e){if(s.absolutePathInfo.stateElement!==n.stateElement)continue;const e=s.absolutePathInfo.pathInfo,a=e.path;if(-1===a.indexOf("#")&&(t.add(a),e.wildcardCount>0)){const t=k(s.listIndex,e.wildcardCount),n=o[a];void 0===n?o[a]=[t]:n.push(t)}}i=a.call(s,Array.from(t),o)}const o=n.stateElement?.addressHooks;if(o){const t=o.updated;for(let a=0;a<t.length;a++)t[a](n.stateElement,e,s)}return i}(t,e,s,n);break;case x:o=(e,n)=>function(t,e,s,n){const a=Reflect.get(t,it);"function"==typeof a&&a.call(n,e,s)}(t,e,n,s);break;default:return Reflect.get(t,e,s)}return a.set(e,o),o}}class ne{_stateElement;_addressStack=Array(B).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const s=D(t);null===s&&p("StateHandler: no state tree found on this root."),this._stateElement=s,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&p("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=B&&(this._hasRepeatedAddress()&&p(`[wcs/getter-cycle] Exceeded maximum address stack depth of ${B}. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),p(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of ${B} with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const s=this._addressStack[e];if(s){if(t.has(s))return!0;t.add(s)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const s=this._addressStack[e];s&&t.push(s.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&p(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,s){return se(t,e,s,this)}set(t,e,s,n){return zt(this),function(t,e,s,n,a){if("string"==typeof e){const i=St(e),o=wt(t,i,n,a),r=m(i.pathInfo,o);return Et(t,r,s,n,a)}return Reflect.set(t,e,s,n)}(t,e,s,n,this)}has(t,e){return Reflect.has(t,e)}deleteProperty(t,e){return zt(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,s){return zt(this),Reflect.defineProperty(t,e,s)}}const ae="undefined"==typeof HTMLElement?class{}:HTMLElement;const ie=new Set(["for","if","elseif","else"]);function oe(e,s,n){const a=new Map;for(const t of n){const e=ht(t);if(null===e.lastWildcardPath)continue;const s=a.get(e.lastWildcardPath);void 0===s?a.set(e.lastWildcardPath,[e]):s.push(e)}const i=[],o=new Set,r=t=>{const s=g(e,t);if(o.has(s))return;o.add(s);const n=T(s);if(n instanceof Set?i.push(...n):void 0!==n&&i.push(n),null!==t.listIndex){const e=a.get(t.pathInfo.path);if(void 0!==e)for(const s of e)r(m(s,t.listIndex))}};G();try{if(e.createState("readonly",t=>{for(const n of s){const s=m(ht(n),null);r(s);try{$t(e,s,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",r)}catch{}}}),0===i.length)return;const n=function(t){const e=[],s=[];for(const n of t)ie.has(n.bindingType)?e.push(n):s.push(n);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(s)}(i),a=()=>{L(n,void 0,{updatedCallback:!1})};if(t())return void a();const o=j("state",a);void 0!==o&&o.catch(O)}finally{H()}}const re=[[ft,"watch"],[gt,"scan"],[yt,"streams"],[bt,"recursion"]];class le extends ae{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return M(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Qt}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&p(`${e.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){kt(t),function(t){for(let e=0;e<re.length;e++){const[s,n]=re[e];s in t&&!Kt(n)&&p(V(n,`"${s}"`))}}(t);const e=this.__state,s=Bt();s.set("previousState",e),Tt(this,t,s);const n=function(t){const e=new Set,s=t[K];if(void 0===s)return e;Array.isArray(s)||p(`${K} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${K} entries must be non-empty strings.`),t===J&&p(`${K} entry "${t}" conflicts with the reserved namespace name "${J}".`),e.has(t)&&p(`${K} entry "${t}" is duplicated.`),e.add(t);return e}(t),a=function(t){const e=new Set,s=t[Q];if(void 0===s)return e;Array.isArray(s)||p(`${Q} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${Q} entries must be non-empty strings.`),e.has(t)&&p(`${Q} entry "${t}" is duplicated.`),e.add(t);return e}(t),i=function(t){const e=t[Y];if(void 0===e)return null;"object"==typeof e&&null!==e||p(`${Y} must be an object mapping list paths to key specs.`);const s=new Map;for(const[t,n]of Object.entries(e)){0===t.length&&p(`${Y} entry path must be a non-empty string.`);const e=t.split(Z);e.some(t=>0===t.length)&&p(`${Y} entry "${t}" must not contain empty path segments.`),e[e.length-1]===tt&&p(`${Y} entry "${t}" must be the list path itself, not the element path (drop the trailing "${Z}${tt}").`),-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] ${Y} entry "${t}" uses "${et}", which ${Y} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${Z}${tt}${Z}children").`),"function"!=typeof n?("string"!=typeof n&&p(`${Y} entry "${t}" key spec must be a field name (string) or a function.`),0===n.length&&p(`${Y} entry "${t}" key field name must be a non-empty string.`),(n.includes(Z)||n.includes(tt))&&p(`${Y} entry "${t}" key field name "${n}" must be a flat property name ("${Z}" / "${tt}" are not allowed).`),n in Object.prototype&&p(`${Y} entry "${t}" key field name "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),s.set(t,n)):s.set(t,n)}return s.size>0?s:null}(t);s.set("eventTokenNames",a),Gt(this,t,s),Mt(this,t,s),this._commandTokenNames=n,this._eventTokenNames=a,this._stateGeneration++,this.__state=t,void 0!==e&&Jt?.reset(this),this._hasUpdatedCallback=at in t,this._hasErrorCallback=it in t,F(this),Ft(this,t,s),function(t,e,s){const n=e[X];if(void 0!==n){"object"==typeof n&&null!==n||p(`${X} must be an object mapping event-token names to handler functions.`);for(const[e,a]of Object.entries(n))s.has(e)||p(`${X} entry "${e}" is not declared in $eventTokens.${f(e,s)}`),"function"!=typeof a&&p(`${X} entry "${e}" must be a function.`),_(t,e).subscribe(a)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const o=function(t){const e=new Set,s=new Set,n=Lt(t);for(const[t,a]of Object.entries(n))"function"==typeof a.get&&e.add(t),"function"==typeof a.set&&s.add(t);return{getterPaths:e,setterPaths:s}}(t);for(const t of o.getterPaths)this._getterPaths.add(t);for(const t of o.setterPaths)this._setterPaths.add(t);Ut(this,t,s),this._listKeys=i,this._rebuildPathInfo(),Wt(this,t,s),qt(this,null),this._resolveLoading?.()}attributeChangedCallback(t,s,n){this._initialized&&s!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===s?"absent":`"${s}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${e.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?U('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){p("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await a(t,e.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${e.tagNames.state}> element.`)},ut),s=await this._setStatePromise;return clearTimeout(t),s}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||p(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await n(t);p(`Unsupported src file type: ${t}`)}}catch(t){p(`Failed to initialize state: ${t}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,s]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=s}return await this._loadingPromise,null!==this._rootNode&&(W(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),p(t)}_failInitializeLoudly(t,s=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${e.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),s&&null!==this._rootNode&&null===D(this._rootNode)&&(q(this._rootNode,t),i(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{st in t&&await t[N]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{nt in t&&t[A]()})}async connectedCallback(){this._rootNode=this.getRootNode();const n=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(d(this))return void this._resolveConnectedCallback?.();this._treeless||D(this._rootNode)===this||W(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const t=o(this);if(null!==t)return void await t;if(this.hasAttribute("mount"))try{r("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const s=this.parentNode;if(s instanceof ShadowRoot&&s.host.hasAttribute(pt))try{r("dcc",`a <${e.tagNames.state}> inside a [${pt}] host`)}catch(t){this._failInitializeLoudly(t)}let n=!1;try{const t=l(this);null===t&&this.hasAttribute("bind-component")&&r("scopes",'the "bind-component" attribute'),n=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(n)return;let a=!1;try{a=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!a)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!t()||n!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!s())try{await U('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}qt(this,n),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!c(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&h(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{W(this.rootNode,null),Rt(this),Vt(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(t=>(kt(t),t))}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const s of t)e.add(s);this._watchPaths=e,this.attachAddressHooks("watch",ft)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[s,n]of t)e.has(s)&&p(`$listKeys entry "${s}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(s,n);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return _t(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&p("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const s=jt(t,e);null===this._addressHooks&&(this._addressHooks=Ot()),Ht(this._addressHooks,s)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",mt)}_addDependency(t,e,s){const n=t.get(e);return void 0===n?(t.set(e,[s]),!0):!n.includes(s)&&(n.push(s),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,s="binding"){if("internal"!==s){const n=this._pathRegistrations.get(t);void 0===n?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===s}):"for"!==n.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:n.bound||"binding"===s})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+tt)),!this._pathSet.has(t)){const e=ht(t);if(this._pathSet.add(t),Jt?.check(this,this.__state,t,s),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ht(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,s){try{const n=function(t,e,s){const n=new ne(t,s);return new Proxy(e,n)}(t,this._state,e);return s(n)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&p(`<${e.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);u(this),(this._hasGraftedVolumes||this._hasMounts)&&p("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const s=this.__state;this._state=t;const n=function(t){const e=new Set;for(const s of t)if(void 0!==s)for(const[t,n]of Object.entries(Lt(s)))t.startsWith("$")||t.includes(tt)||"function"==typeof n.value||e.add(t);return e}([s,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){oe(this,t,this._pathRegistrations.keys())}}const de=[],ce=[];function he(){const t=[];let e=0;for(let s=0;s<ce.length;s++){const n=ce[s].deref();void 0!==n&&(t.push(n),ce[e++]=ce[s])}return ce.length=e,t}function ue(t){if(!de.includes(t)){de.push(t);for(const e of he())t(e)}}function pe(t=customElements){he().includes(t)||ce.push(new WeakRef(t));for(let e=0;e<de.length;e++)de[e](t);t.get(e.tagNames.state)||t.define(e.tagNames.state,le)}export{ae as H,ue as a,pe as r};
2
2
  //# sourceMappingURL=registerComponents.js.map