@wcstack/state 3.3.0 → 3.5.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 (43) hide show
  1. package/README.ja.md +94 -27
  2. package/README.md +94 -27
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/index.d.ts +52 -1
  6. package/dist/index.esm.js +1 -1
  7. package/dist/index.esm.js.map +1 -1
  8. package/dist/split/chunks/binder.js +1 -1
  9. package/dist/split/chunks/binder.js.map +1 -1
  10. package/dist/split/chunks/checkDependency.js +1 -1
  11. package/dist/split/chunks/checkDependency.js.map +1 -1
  12. package/dist/split/chunks/declarationAliases.js.map +1 -1
  13. package/dist/split/chunks/diagnosticsHooks.js.map +1 -1
  14. package/dist/split/chunks/featureBridge.js +1 -1
  15. package/dist/split/chunks/filterRegistry.js +1 -1
  16. package/dist/split/chunks/filterRegistry.js.map +1 -1
  17. package/dist/split/chunks/getAllPropertyDescriptors.js +1 -1
  18. package/dist/split/chunks/lifecycleHooks.js +1 -1
  19. package/dist/split/chunks/lifecycleHooks.js.map +1 -1
  20. package/dist/split/chunks/pathDiagnostics.js +1 -1
  21. package/dist/split/chunks/pathDiagnostics.js.map +1 -1
  22. package/dist/split/chunks/registerComponents.js +1 -1
  23. package/dist/split/chunks/registerComponents.js.map +1 -1
  24. package/dist/split/chunks/setAll.js +1 -1
  25. package/dist/split/chunks/setAll.js.map +1 -1
  26. package/dist/split/chunks/version.js +1 -1
  27. package/dist/split/core.d.ts +77 -1
  28. package/dist/split/core.js +1 -1
  29. package/dist/split/features/devtools.js +1 -1
  30. package/dist/split/features/devtools.js.map +1 -1
  31. package/dist/split/features/diagnostics.js +1 -1
  32. package/dist/split/features/diagnostics.js.map +1 -1
  33. package/dist/split/features/formats.js +1 -1
  34. package/dist/split/features/formats.js.map +1 -1
  35. package/dist/split/features/recursion.js +1 -1
  36. package/dist/split/features/recursion.js.map +1 -1
  37. package/dist/split/features/scopes.js +1 -1
  38. package/dist/split/features/scopes.js.map +1 -1
  39. package/dist/split/features/ssr.js +1 -1
  40. package/dist/split/features/ssr.js.map +1 -1
  41. package/dist/split/features/temporal.js +1 -1
  42. package/dist/split/features/temporal.js.map +1 -1
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"pathDiagnostics.js","sources":["../../../../../src/define.ts","../../../../../src/address/PathInfo.ts","../../../../../src/platform/devtoolsSink.ts","../../../../../src/pathDiagnostics.ts"],"sourcesContent":["export const DELIMITER = '.';\nexport const WILDCARD = '*';\nexport const MAX_WILDCARD_DEPTH = 128;\n/**\n * 1 本のパスが持てるセグメント数の上限(`getPathInfo` が初回 intern のときだけ検査する)。\n *\n * `PathInfo` は自分の**全ての接頭辞**を intern するので、深さ N のパス 1 本で N 個の\n * `PathInfo` ができ、それぞれが長さ k の配列と Set を持つ = 時間もメモリも O(N²)。\n * 実測(Node 22・パス 1 本)で depth 400 → 145ms / 61MB、800 → 1162ms / 424MB、\n * 2000 → 既定 4GB ヒープで OOM。**約 4KB の `data-wcs` 属性値 1 つでタブを落とせた。**\n * ここで打ち切ると最悪でも 256² ≒ 65k 単位に収まる。\n *\n * 値は `MAX_WILDCARD_DEPTH`(128 = `$1..$128` の表の大きさ)を**使い切れる**ことから決めた:\n * `$recursion` の展開(`recursion/expand.ts`)が深さ 128 で作るパスは `a.*.b.*.…` の形で\n * 257 セグメントを超える。そこを割ると、ドキュメント済みの再帰深さが打ち切られてしまう。\n * 512 なら最悪でも 512² ≒ 262k 単位で、上の実測の 400 段(145ms / 61MB)の延長に収まる。\n * 実用のパスは 10 段に満たない。\n */\nexport const MAX_PATH_SEGMENTS = 512;\nexport const MAX_LOOP_DEPTH = 128;\n// 因果伝播(Phase 3)の 1 transaction あたり hop 上限。超過分の未処理 record は\n// quarantine し(適用済みの値は戻さない)、updater から例外は投げない。\nexport const MAX_PROPAGATION_HOPS = 32;\n\n// `$watch` ハンドラ起点の書き込み連鎖の打ち切り深さ(docs/state-watch-hook-design.md §7-2)。\n// watch ハンドラ内の書き込みは新しい microtask バッチを作るため MAX_PROPAGATION_HOPS の\n// ガードが効かず、書き込み先が動的なので `$streams` のような静的な自己依存検出もできない。\n// 値は MAX_PROPAGATION_HOPS と同値だが、別の打ち切り機構なので定数は共有しない。\nexport const MAX_WATCH_CHAIN_DEPTH = 32;\n\n// updater の drain 終了リスナーの実行順(昇順に呼ばれる。設計書 §3-2 層 1)。\n// watch が先なのは、watch ハンドラの書き込みが同じバッチの stream restart 判定に\n// 影響しないようにするため(watch → restart の一方向)。import 順に順序を持たせると\n// 無関係な import 整理で静かに壊れるため、明示的な優先度で固定する。\n//\n// devtools が最も先なのは、`state:update-batch` が「そのバッチに何が載ったか」の\n// 観測であり、watch / restart の副作用が乗る前の生の集合を報告すべきだから。\n// 既定値 0 のまま暗黙に先頭へ入るのに任せず、意図として定数で固定する\n// (docs/devtools-hook-protocol.md §4.3)。\nexport const DEVTOOLS_LISTENER_PRIORITY = 0;\nexport const WATCH_LISTENER_PRIORITY = 10;\nexport const STREAM_LISTENER_PRIORITY = 20;\n\n// data-wcs バインディング構文 `[prop][#mod]: [path][|filter...]` の区切り文字(単一正本・`@state` は v2 で撤去)。\n// これらは「死守の壁(構文契約)」であり値は不変。manifest.syntax.delimiters で公開される。\nexport const BINDING_SEPARATOR = ';'; // 複数バインディングの区切り\nexport const PROP_VALUE_SEPARATOR = ':'; // 左辺(prop)と右辺(path)の区切り\nexport const MODIFIER_SEPARATOR = '#'; // prop と修飾子の区切り\nexport const FILTER_SEPARATOR = '|'; // フィルタパイプの区切り\n\n// 修飾子(`#` 後)の語彙(単一正本)。manifest.syntax.modifiers で公開される。\n// フラグ形(`#prevent` — 値を取らない)とキー値形(`#init=element` — `=` で値を取る)。\n// 消費箇所(event/handler・BindingSession・twowayHandler・bindings/initialSync)は\n// この定数を参照する — 文字列リテラルの散在は tooling への収載漏れの温床だった\n// (docs/static-wiring-dx-design.md §2-2)。\nexport const MODIFIER_PREVENT = 'prevent';\nexport const MODIFIER_STOP = 'stop';\nexport const MODIFIER_READONLY = 'ro';\nexport const MODIFIER_FLAGS: readonly string[] = Object.freeze([\n MODIFIER_PREVENT, MODIFIER_STOP, MODIFIER_READONLY,\n]);\nexport const MODIFIER_KEY_INIT = 'init';\nexport const MODIFIER_KEY_SYNC = 'sync';\nexport const MODIFIER_KEYS: readonly string[] = Object.freeze([\n MODIFIER_KEY_INIT, MODIFIER_KEY_SYNC,\n]);\n\n// bindingType 判別と左辺 namespace の語彙(単一正本)。manifest.syntax.bindingTypes で\n// 公開される。パーサ(parseBindTextsForElement)とイベント層はこの定数に分岐する。\n// apply 層のディスパッチマップ(apply/applyChange.ts の applyChangeByFirstSegment)の\n// キー集合との一致は __tests__/manifest.test.ts の drift テストが強制する —\n// manifest エントリ(DOM 非依存)から apply 層を import しないための分離。\nexport const ELSE_KEYWORD = 'else';\nexport const SPREAD_PROP = '...';\nexport const EVENT_PROP_PREFIX = 'on';\nexport const EVENT_TOKEN_NAMESPACE = 'eventToken';\n/**\n * `<wcs-state mount>` の左辺 `state.<key>: path` — ボリュームの注入口(要件 B14③・3.x 計画 D28)。\n * 束縛ではなくマウントの宣言なので、束縛の収集(getParseBindTextResults)は作らず、ボリュームが接ぎ木の時に読む\n */\nexport const VOLUME_INJECTION_PROP = 'state';\nexport const COMMAND_NAMESPACE = 'command';\nexport const CLASS_NAMESPACE = 'class';\nexport const ATTR_NAMESPACE = 'attr';\nexport const STYLE_NAMESPACE = 'style';\n\n// リストインデックス参照名(`$1`..`$N`)の接頭辞(単一正本)。\n// manifest.syntax.indexParam で公開される。\nexport const INDEX_PARAM_PREFIX = '$';\n\n/**\n * stackIndexByIndexName\n * インデックス名からスタックインデックスへのマッピング\n * $1 => 0\n * $2 => 1\n * :\n * ${i + 1} => i\n * i < MAX_WILDCARD_DEPTH\n */\nconst tmpIndexByIndexName: { [key: PropertyKey]: number } = {};\nfor (let i = 0; i < MAX_WILDCARD_DEPTH; i++) {\n tmpIndexByIndexName[`${INDEX_PARAM_PREFIX}${i+1}`] = i;\n}\nexport const INDEX_BY_INDEX_NAME: { [key: PropertyKey]: number } = Object.freeze(tmpIndexByIndexName);\n\nexport const NO_SET_TIMEOUT = 60 * 1000; // 1分\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\nexport const STATE_CONNECTED_CALLBACK_NAME = \"$connectedCallback\";\nexport const STATE_DISCONNECTED_CALLBACK_NAME = \"$disconnectedCallback\";\n/** 旧名 `$updatedCallback` は 3.x の間のエイリアス(要件 B12・declarationAliases.ts) */\nexport const STATE_RENDERED_CALLBACK_NAME = \"$renderedCallback\";\nexport const STATE_ERROR_CALLBACK_NAME = \"$errorCallback\";\n\nexport const WEBCOMPONENT_STATE_READY_CALLBACK_NAME = \"$stateReadyCallback\";\n\nexport const STATE_BINDABLES_NAME = \"$bindables\";\nexport const STATE_COMMANDS_NAME = \"$commands\";\nexport const STATE_COMMAND_TOKENS_NAME = \"$commandTokens\";\nexport const STATE_COMMAND_NAMESPACE_NAME = \"$command\";\nexport const STATE_EVENT_TOKENS_NAME = \"$eventTokens\";\nexport const STATE_ON_NAME = \"$on\";\n/** 旧名 `$streams` は 3.x の間のエイリアス(要件 B12・declarationAliases.ts) */\nexport const STATE_STREAM_NAME = \"$stream\";\nexport const STATE_WATCH_NAME = \"$watch\";\nexport const STATE_SCAN_NAME = \"$scan\";\nexport const STATE_RECURSION_NAME = \"$recursion\";\n\n/**\n * 再帰ワイルドカード。オーサリング層($recursion 宣言・getter キー・API 引数)にだけ\n * 現れ、PathInfo には決して降ろさない — wildcardCount が不定になると ListIndex 連鎖長・\n * $1..$n・$resolve の厳密一致・走査の段数が同時に壊れる\n * (docs/state-recursive-path-design.md §2-1)。\n */\nexport const RECURSION_WILDCARD = \"**\";\nexport const STATE_LIST_KEYS_NAME = \"$listKeys\";\nexport const STATE_STREAM_STATUS_NAMESPACE_NAME = \"$streamStatus\";\nexport const STATE_STREAM_ERROR_NAMESPACE_NAME = \"$streamError\";\nexport const DCC_DEFINITION_ATTRIBUTE = \"data-wc-definition\";\n","import { DELIMITER, MAX_PATH_SEGMENTS, RECURSION_WILDCARD, WILDCARD } from \"../define.js\";\nimport { raiseError } from \"../raiseError.js\";\nimport { IPathInfo } from \"./types.js\";\n\nconst _cache: Map<string, IPathInfo> = new Map();\n\n/**\n * **tooling 専用**(`@wcstack/state/parser` の clearParserCaches からのみ呼ぶ)。\n * ランタイム文脈で呼んではならない — PathInfo のインスタンス同一性は正規化キー\n * (依存グラフ・アドレス比較)の前提であり、クリアすると同一パスの新旧インスタンスが\n * 併存して identity 比較が黙って壊れる。言語サーバー等の長時間プロセスが、編集中の\n * 中間パス(`user.n` 等)の恒久 intern によるメモリ単調増加を断つための出口。\n */\nexport function clearPathInfoCacheForTooling(): void {\n _cache.clear();\n}\n\nlet id: number = 0;\nexport function getPathInfo(path: string): IPathInfo {\n let pathInfo = _cache.get(path);\n if (typeof pathInfo !== \"undefined\") {\n return pathInfo;\n }\n // 再帰ワイルドカードはオーサリング層の記号で、ここへ降りてきてはならない\n // (降ろすと wildcardCount が不定になり ListIndex 連鎖長・$1..$n・$resolve の\n // 厳密一致・走査の段数が同時に壊れる。設計書 D2)。到達したということは、\n // `**` を解釈しない消費者に `**` パスが渡ったということ。通常のパスはこの検査を\n // 初回 intern のときにしか払わない(`**` パスは intern されないので読むたびに落ちる)。\n if (path.indexOf(RECURSION_WILDCARD) !== -1) {\n raiseError(\n `[wcs/recursion-unsupported] \"${path}\" uses \"${RECURSION_WILDCARD}\", which is not accepted here. ` +\n `It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path ` +\n `argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`\n );\n }\n // 深さの上限(初回 intern のときだけ払う)。`PathInfo` は**全ての接頭辞**を intern するので\n // 深さ N のパス 1 本で時間もメモリも O(N²) になり、上限が無いと約 4KB の属性値 1 つで\n // タブが落ちた(実測値は `MAX_PATH_SEGMENTS` の注記)。\n //\n // **ワイルドカードの段数はここでは見ない。** 段数の上限(`MAX_WILDCARD_DEPTH` = manifest の\n // `indexParam.maxDepth`)は `$1..$N` の表が引けるかという別の話で、`recursion/expand.ts` の\n // `[wcs/recursion-depth-exceeded]` と `proxy/traps/get.ts` の `$N` 範囲外診断が、原因を\n // 名指しできる場所で受け持っている(番人: `integration.recursionPrerequisites.test.ts` が\n // 「PathInfo 自体には段数の上限が無い」を固定している)。ここで先に落とすと、深さ超過か\n // 循環かの切り分けが効かなくなる\n const segmentCount = countSegments(path);\n if (segmentCount > MAX_PATH_SEGMENTS) {\n raiseError(\n `[wcs/binding-syntax] \"${path}\" has ${segmentCount} path segments — the limit is ${MAX_PATH_SEGMENTS}. ` +\n `Every prefix of a path is interned, so the cost grows with the square of the depth.`,\n );\n }\n pathInfo = Object.freeze(new PathInfo(path));\n _cache.set(path, pathInfo);\n return pathInfo;\n}\n\n/** `.` の数 + 1。`split` の配列を作らずに数える(初回 intern のときだけ通る) */\nfunction countSegments(path: string): number {\n let count = 1;\n for (let i = 0; i < path.length; i++) {\n if (path[i] === DELIMITER) {\n count++;\n }\n }\n return count;\n}\n\nclass PathInfo implements IPathInfo {\n readonly id: number = ++id;\n readonly path: string;\n readonly segments: string[];\n readonly lastSegment: string;\n readonly cumulativePaths: string[];\n readonly cumulativePathSet: Set<string>;\n readonly cumulativePathInfos: IPathInfo[];\n readonly cumulativePathInfoSet: Set<IPathInfo>;\n readonly parentPath: string | null;\n readonly wildcardPaths: string[];\n readonly wildcardPathSet: Set<string>;\n readonly indexByWildcardPath: Record<string, number>;\n readonly wildcardPathInfos: IPathInfo[];\n readonly wildcardPathInfoSet: Set<IPathInfo>;\n readonly wildcardParentPaths: string[];\n readonly wildcardParentPathSet: Set<string>;\n readonly wildcardParentPathInfos: IPathInfo[];\n readonly wildcardParentPathInfoSet: Set<IPathInfo>;\n readonly wildcardPositions: number[];\n readonly lastWildcardPath: string | null;\n readonly lastWildcardInfo: IPathInfo | null;\n readonly wildcardCount: number;\n readonly parentPathInfo: IPathInfo | null;\n constructor(path: string) {\n // Helper to get or create StructuredPathInfo instances, avoiding redundant creation for self-reference\n const getPattern = (_path: string): IPathInfo => {\n return (path === _path) ? this : getPathInfo(_path);\n };\n \n // Split the pattern into individual path segments (e.g., \"items.*.name\" → [\"items\", \"*\", \"name\"])\n const segments = path.split(\".\");\n \n // Arrays to track all cumulative paths from root to each segment\n const cumulativePaths = [];\n const cumulativePathInfos: IPathInfo[] = [];\n \n // Arrays to track wildcard-specific information\n const wildcardPaths = [];\n const indexByWildcardPath: Record<string, number> = {}; // Maps wildcard path to its index position\n const wildcardPathInfos = [];\n const wildcardParentPaths = []; // Paths of parent segments for each wildcard\n const wildcardParentPathInfos = [];\n const wildcardPositions = [];\n \n let currentPatternPath = \"\", prevPatternPath = \"\";\n let wildcardCount = 0;\n \n // Iterate through each segment to build cumulative paths and identify wildcards\n for(let i = 0; i < segments.length; i++) {\n currentPatternPath += segments[i];\n \n // If this segment is a wildcard, track it with all wildcard-specific metadata\n if (segments[i] === WILDCARD) {\n wildcardPaths.push(currentPatternPath);\n indexByWildcardPath[currentPatternPath] = wildcardCount; // Store wildcard's ordinal position\n wildcardPathInfos.push(getPattern(currentPatternPath));\n wildcardParentPaths.push(prevPatternPath); // Parent path is the previous cumulative path\n wildcardParentPathInfos.push(getPattern(prevPatternPath));\n wildcardPositions.push(i);\n wildcardCount++;\n }\n \n // Track all cumulative paths for hierarchical navigation (e.g., \"items\", \"items.*\", \"items.*.name\")\n cumulativePaths.push(currentPatternPath);\n cumulativePathInfos.push(getPattern(currentPatternPath));\n \n // Save current path as previous for next iteration, then add separator\n prevPatternPath = currentPatternPath;\n currentPatternPath += \".\";\n }\n \n // Determine the deepest (last) wildcard path and the parent path of the entire pattern\n const lastWildcardPath = wildcardPaths.length > 0 ? wildcardPaths[wildcardPaths.length - 1] : null;\n const parentPath = cumulativePaths.length > 1 ? cumulativePaths[cumulativePaths.length - 2] : null;\n \n // Assign all analyzed data to readonly properties\n this.path = path;\n this.segments = segments;\n this.lastSegment = segments[segments.length - 1];\n this.cumulativePaths = cumulativePaths;\n this.cumulativePathSet = new Set(cumulativePaths); // Set for fast lookup\n this.cumulativePathInfos = cumulativePathInfos;\n this.cumulativePathInfoSet = new Set(cumulativePathInfos);\n this.wildcardPaths = wildcardPaths;\n this.wildcardPathSet = new Set(wildcardPaths);\n this.indexByWildcardPath = indexByWildcardPath;\n this.wildcardPathInfos = wildcardPathInfos;\n this.wildcardPathInfoSet = new Set(wildcardPathInfos);\n this.wildcardParentPaths = wildcardParentPaths;\n this.wildcardParentPathSet = new Set(wildcardParentPaths);\n this.wildcardParentPathInfos = wildcardParentPathInfos;\n this.wildcardParentPathInfoSet = new Set(wildcardParentPathInfos);\n this.wildcardPositions = wildcardPositions;\n this.lastWildcardPath = lastWildcardPath;\n this.lastWildcardInfo = lastWildcardPath ? getPattern(lastWildcardPath) : null;\n this.parentPath = parentPath;\n this.parentPathInfo = parentPath ? getPattern(parentPath) : null;\n this.wildcardCount = wildcardCount;\n }\n}\n","/**\n * platform/devtoolsSink.ts(旧 devtools/sink.ts。core 側に置き、devtools/bridge.ts がこちらを import する)\n *\n * 計装点が参照するホットパス唯一の接点。依存ゼロの葉モジュールにすることで、\n * 計装される側(stateElementByName / setByAddress / binding / token)と\n * bridge の間の循環 import を避ける。\n *\n * コスト規範(protocol §1-1): フック未接続時、計装点のコストは\n * `devtoolsSink !== null` の分岐 1 個。イベントオブジェクトの生成は\n * 必ずこのチェックの内側で行うこと。\n */\n\nimport type { DevtoolsSink } from \"../devtools/types\";\n\n/** live binding としてエクスポート。計装点は `if (devtoolsSink !== null)` で参照する */\nexport let devtoolsSink: DevtoolsSink | null = null;\n\nexport function setDevtoolsSink(sink: DevtoolsSink | null): void {\n devtoolsSink = sink;\n}\n","/**\n * pathDiagnostics.ts — パスに関する**エラーの文言**(throw する側)と、診断の両面が共有する部品。\n *\n * 束縛時の存在検査(`user.nmae` のような打ち間違いを console.warn で知らせる開発時の診断)は\n * `features/diagnostics` へ分けた(diagnostics/pathChecks.ts)。core に残るのは、実行を止める\n * エラーの文言と、その did-you-mean が使う候補の集め方だけ。エラーは機能の有無に関わらず\n * 読める文言で落ちなければならないので、ここは core から外せない。\n *\n * 診断 code はコンソール → lint → IDE の三面で共有する(errorGuidance.ts の規約)。\n */\n\nimport { DELIMITER } from \"./define\";\nimport { didYouMean, LINT_HINT } from \"./errorGuidance\";\n\n/** `setPathInfo` の呼び出し元の種別。診断 code と適用範囲がこれで変わる */\nexport type PathInfoSource =\n /** data-wcs / mustache / コメントバインディング */\n | \"binding\"\n /** `$watch` の宣言キー */\n | \"watch\"\n /** `$scan` の `from` / `resetOn`(docs/state-scan-design.md §2-4) */\n | \"scan\"\n /** ランタイム内部のパス翻訳(mapped な bind-component の外向き伝播)。検査しない */\n | \"internal\";\n\n/**\n * `obj` 自身+プロトタイプチェーン(Object.prototype 手前まで)から descriptor を引く。\n * 打ち切り位置は getAllPropertyDescriptors と同じ — 「state が宣言したもの」だけを\n * 存在とみなし、`toString` 等の Object.prototype 由来を存在扱いしない。\n *\n * `State.findStateDescriptor`(再帰アクセサの衝突検査)も同じ走査を使う。打ち切り位置が\n * 2 本に分かれると、片方だけが `Object.prototype` を存在扱いするようなずれ方をする。\n */\nexport function findDescriptor(obj: object, key: string): PropertyDescriptor | undefined {\n let proto: object | null = obj;\n while (proto !== null && proto !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n if (typeof descriptor !== \"undefined\") {\n return descriptor;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return undefined;\n}\n\n/** `obj` 自身+プロトタイプチェーンのキー名(did-you-mean の候補集合) */\nfunction ownKeys(obj: object): string[] {\n const keys: string[] = [];\n let proto: object | null = obj;\n while (proto !== null && proto !== Object.prototype) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n keys.push(key);\n }\n proto = Object.getPrototypeOf(proto);\n }\n return keys;\n}\n\n/**\n * 失敗した階層の兄弟候補。生オブジェクトのキーに加え、その階層にフラット宣言\n * (ドットパス getter)されているものも混ぜる — `cart.items.*.subtotl` の正解\n * `subtotal` は行オブジェクトには無く getterPaths にしか居ないため。\n */\nexport function collectCandidates(\n container: object,\n parentPrefix: string,\n declaredPaths: Iterable<string>,\n): string[] {\n const candidates = ownKeys(container);\n const prefix = parentPrefix.length > 0 ? parentPrefix + DELIMITER : \"\";\n for (const declared of declaredPaths) {\n if (prefix.length > 0 && !declared.startsWith(prefix)) {\n continue;\n }\n const rest = declared.slice(prefix.length);\n // 直下の 1 セグメントだけを候補にする(孫は別階層の名前なので提案しない)\n if (rest.length > 0 && rest.indexOf(DELIMITER) === -1) {\n candidates.push(rest);\n }\n }\n return candidates;\n}\n\n/** 診断 code は lint / IDE と同一語彙(errorGuidance.ts の三面共有規約) */\nexport const DIAGNOSTIC_CODE: Readonly<Record<\"binding\" | \"watch\" | \"scan\", string>> = {\n binding: \"wcs/binding-path-missing\",\n watch: \"wcs/watch-path-missing\",\n scan: \"wcs/scan-path-missing\",\n};\n\nexport const SUBJECT: Readonly<Record<\"binding\" | \"watch\" | \"scan\", string>> = {\n binding: \"Bound path\",\n watch: \"$watch path\",\n scan: \"$scan path\",\n};\n\n/**\n * ルート直下(単一セグメント)のパスが state に無いときのエラーメッセージ。\n *\n * この形だけは親アドレスを辿れないので読み取りが throw する = 元から loud だが、\n * 文面が `address.parentAddress is undefined path: cout` という内部実装の言葉で、\n * 「打ち間違い」だと分からず did-you-mean も lint 誘導も無かった。深いパスの\n * `console.warn` と同じ語彙に揃える。\n */\nexport function missingRootPathMessage(\n path: string,\n target: object,\n declaredPaths: Iterable<string>,\n): string {\n return `[${DIAGNOSTIC_CODE.binding}] Path \"${path}\" does not exist on the state tree.` +\n `${didYouMean(path, collectCandidates(target, \"\", declaredPaths))}${LINT_HINT}`;\n}\n\n/**\n * `$resolve` / `$getAll` に渡した添字の本数がワイルドカードの本数と噛み合わない。\n *\n * 不足(`$resolve`)は元から throw していたが、**超過は両 API とも黙って無視**され、\n * 取り違えた添字のまま「もっともらしい値」を返していた。本数はパス文字列から\n * 決まるので、噛み合わないことは常にプログラマのミス。\n */\nexport function indexArityMessage(\n api: \"$resolve\" | \"$getAll\" | \"$setAll\",\n path: string,\n wildcardCount: number,\n actual: number,\n): string {\n // `$getAll` / `$setAll` の添字は前方一致の接頭辞なので上限、`$resolve` だけが厳密一致\n // (docs/state-set-all-design.md §4)。\n const requirement = api === \"$resolve\"\n ? `exactly ${wildcardCount}`\n : `at most ${wildcardCount}`;\n return `[wcs/index-arity] ${api}(\"${path}\") requires ${requirement} index(es) ` +\n `(\"*\" appears ${wildcardCount} time(s) in the path) but got ${actual}.${LINT_HINT}`;\n}\n\n/**\n * `**` を含むパスが宣言済みの再帰アンカーと合致しない(綴り違い・2 つ目の `**`)。\n * 束縛形(bind.ts)・合併形(getAllRecursive.ts)・ブロードキャスト(setAllRecursive.ts)の\n * 3 入口が同じ文面で報告する。\n */\nexport function recursionAnchorMismatchMessage(path: string, recursiveAnchor: string): string {\n return `[wcs/recursion-anchor] \"${path}\" does not match the declared recursion anchor ` +\n `\"${recursiveAnchor}\". This version supports exactly one anchor per state, and \"**\" must be followed ` +\n `by a well-formed suffix (no second \"**\", no empty segment, no bare \"*\" right after \"**\").`;\n}\n\n/**\n * `$getAll(path)`(添字省略)の既定値はループ文脈の添字 `[$1..$n]` だが、それを\n * 敷けるのは path と文脈がワイルドカード連鎖を共有している場合だけ。共有ゼロなのに\n * 文脈が添字を持っている場合、黙って全展開に倒すと「文脈で絞られている」という\n * 書き手の期待と食い違い、異なる文脈の添字の流用とも区別が付かないため throw する。\n *\n * 実行時の評価文脈に依存する(`$setAll` の spread 長と同種)ので lint へは誘導しない。\n */\nexport function getAllContextMismatchMessage(path: string, contextPath: string): string {\n return `$getAll(\"${path}\") was called without indexes inside the loop context of ` +\n `\"${contextPath}\", but the path shares no wildcard level with that context, ` +\n `so the context indexes ($1..$n) do not apply. ` +\n `Pass indexes explicitly ([] expands every level).`;\n}\n\n/**\n * `$setAll(path, indexes, values, { spread: true })` の配列長がマッチ件数と噛み合わない。\n *\n * 静的には件数が分からない(実行時のリスト長に依存する)ので lint へは誘導しない。\n * 黙って切り詰める/余りを捨てると誤配が通ってしまうため throw する\n * (docs/state-set-all-design.md §3-3)。\n */\nexport function setAllSpreadArityMessage(\n path: string,\n matched: number,\n actual: number,\n): string {\n return `$setAll(\"${path}\", …, { spread: true }) requires the values array to have ` +\n `exactly one entry per matched address (matched ${matched}) but got ${actual}. ` +\n `Did the list change between $getAll and $setAll?`;\n}\n\n/**\n * `$setAll` の値と `options` の組み合わせが意味を成さない。\n * (docs/state-set-all-design.md §3-1)\n */\nexport function setAllValueKindMessage(path: string, reason: string): string {\n return `$setAll(\"${path}\") ${reason}`;\n}\n\n/**\n * ワイルドカードを解決するループ文脈が足りない(=パスの階数 > スコープの階数)。\n *\n * `matrix.*.*` を 1 段の `for` の中で読む、`$2` を 1 段のループの中で読む、といった\n * 取り違えがこれ。元の文面は `address.listIndex?.index is undefined path: matrix.*` /\n * `Index not found at position 1 for loopContext:` という内部実装の言葉で、\n * **何を間違えたのかが書かれていなかった**。\n */\nexport function wildcardScopeMessage(subject: string, needed: number, available: number): string {\n return `[wcs/wildcard-rank] ${subject} needs ${needed} enclosing loop level(s) but the current ` +\n `scope provides ${available}. Wrap it in that many \"for\" templates, or use $resolve(path, indexes) ` +\n `to name the row explicitly.${LINT_HINT}`;\n}\n\n"],"names":["DELIMITER","WILDCARD","MAX_WILDCARD_DEPTH","MAX_LOOP_DEPTH","MAX_PROPAGATION_HOPS","MAX_WATCH_CHAIN_DEPTH","DEVTOOLS_LISTENER_PRIORITY","WATCH_LISTENER_PRIORITY","STREAM_LISTENER_PRIORITY","BINDING_SEPARATOR","PROP_VALUE_SEPARATOR","MODIFIER_SEPARATOR","FILTER_SEPARATOR","MODIFIER_PREVENT","MODIFIER_STOP","MODIFIER_READONLY","MODIFIER_KEY_INIT","MODIFIER_KEY_SYNC","ELSE_KEYWORD","SPREAD_PROP","EVENT_PROP_PREFIX","EVENT_TOKEN_NAMESPACE","VOLUME_INJECTION_PROP","COMMAND_NAMESPACE","CLASS_NAMESPACE","ATTR_NAMESPACE","STYLE_NAMESPACE","INDEX_PARAM_PREFIX","tmpIndexByIndexName","i","INDEX_BY_INDEX_NAME","Object","freeze","NO_SET_TIMEOUT","SVG_NAMESPACE","STATE_CONNECTED_CALLBACK_NAME","STATE_DISCONNECTED_CALLBACK_NAME","STATE_RENDERED_CALLBACK_NAME","STATE_ERROR_CALLBACK_NAME","WEBCOMPONENT_STATE_READY_CALLBACK_NAME","STATE_BINDABLES_NAME","STATE_COMMANDS_NAME","STATE_COMMAND_TOKENS_NAME","STATE_COMMAND_NAMESPACE_NAME","STATE_EVENT_TOKENS_NAME","STATE_ON_NAME","STATE_STREAM_NAME","STATE_WATCH_NAME","STATE_SCAN_NAME","STATE_RECURSION_NAME","RECURSION_WILDCARD","STATE_LIST_KEYS_NAME","STATE_STREAM_STATUS_NAMESPACE_NAME","STATE_STREAM_ERROR_NAMESPACE_NAME","DCC_DEFINITION_ATTRIBUTE","_cache","Map","id","getPathInfo","path","pathInfo","get","indexOf","raiseError","segmentCount","count","length","countSegments","PathInfo","set","segments","lastSegment","cumulativePaths","cumulativePathSet","cumulativePathInfos","cumulativePathInfoSet","parentPath","wildcardPaths","wildcardPathSet","indexByWildcardPath","wildcardPathInfos","wildcardPathInfoSet","wildcardParentPaths","wildcardParentPathSet","wildcardParentPathInfos","wildcardParentPathInfoSet","wildcardPositions","lastWildcardPath","lastWildcardInfo","wildcardCount","parentPathInfo","constructor","getPattern","_path","this","split","currentPatternPath","prevPatternPath","push","Set","devtoolsSink","setDevtoolsSink","sink","findDescriptor","obj","key","proto","prototype","descriptor","getOwnPropertyDescriptor","getPrototypeOf","collectCandidates","container","parentPrefix","declaredPaths","candidates","keys","getOwnPropertyNames","ownKeys","prefix","declared","startsWith","rest","slice","DIAGNOSTIC_CODE","binding","watch","scan","SUBJECT","missingRootPathMessage","target","didYouMean","LINT_HINT","indexArityMessage","api","actual","recursionAnchorMismatchMessage","recursiveAnchor","getAllContextMismatchMessage","contextPath","setAllSpreadArityMessage","matched","setAllValueKindMessage","reason","wildcardScopeMessage","subject","needed","available"],"mappings":"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"}
1
+ {"version":3,"file":"pathDiagnostics.js","sources":["../../../../../src/define.ts","../../../../../src/address/PathInfo.ts","../../../../../src/platform/devtoolsSink.ts","../../../../../src/pathDiagnostics.ts"],"sourcesContent":["export const DELIMITER = '.';\nexport const WILDCARD = '*';\nexport const MAX_WILDCARD_DEPTH = 128;\n/**\n * 1 本のパスが持てるセグメント数の上限(`getPathInfo` が初回 intern のときだけ検査する)。\n *\n * `PathInfo` は自分の**全ての接頭辞**を intern するので、深さ N のパス 1 本で N 個の\n * `PathInfo` ができ、それぞれが長さ k の配列と Set を持つ = 時間もメモリも O(N²)。\n * 実測(Node 22・パス 1 本)で depth 400 → 145ms / 61MB、800 → 1162ms / 424MB、\n * 2000 → 既定 4GB ヒープで OOM。**約 4KB の `data-wcs` 属性値 1 つでタブを落とせた。**\n * ここで打ち切ると最悪でも 256² ≒ 65k 単位に収まる。\n *\n * 値は `MAX_WILDCARD_DEPTH`(128 = `$1..$128` の表の大きさ)を**使い切れる**ことから決めた:\n * `$recursion` の展開(`recursion/expand.ts`)が深さ 128 で作るパスは `a.*.b.*.…` の形で\n * 257 セグメントを超える。そこを割ると、ドキュメント済みの再帰深さが打ち切られてしまう。\n * 512 なら最悪でも 512² ≒ 262k 単位で、上の実測の 400 段(145ms / 61MB)の延長に収まる。\n * 実用のパスは 10 段に満たない。\n */\nexport const MAX_PATH_SEGMENTS = 512;\nexport const MAX_LOOP_DEPTH = 128;\n// 因果伝播(Phase 3)の 1 transaction あたり hop 上限。超過分の未処理 record は\n// quarantine し(適用済みの値は戻さない)、updater から例外は投げない。\nexport const MAX_PROPAGATION_HOPS = 32;\n\n// `$watch` ハンドラ起点の書き込み連鎖の打ち切り深さ(docs/state-watch-hook-design.md §7-2)。\n// watch ハンドラ内の書き込みは新しい microtask バッチを作るため MAX_PROPAGATION_HOPS の\n// ガードが効かず、書き込み先が動的なので `$streams` のような静的な自己依存検出もできない。\n// 値は MAX_PROPAGATION_HOPS と同値だが、別の打ち切り機構なので定数は共有しない。\nexport const MAX_WATCH_CHAIN_DEPTH = 32;\n\n// 描画起点の書き込み連鎖の打ち切り深さ(#338)。binding の適用中に起きた書き込み(行を作るときの\n// 要素の初期同期・`$renderedCallback` など)は新しい microtask バッチを作り、その描画がまた書く —\n// 上の 2 つはどちらもこの連鎖を数えない(hop は 1 transaction の中、watch はハンドラ起点だけ)。\n// 伸ばすのは適用の最中の書き込みだけ(drain 終了リスナーの書き込みは深さを引き継ぐだけ — #353)なので、\n// `$watch` の連鎖とは重ならない(updater/updater.ts)。\n// 上の 2 つの 32 より大きいのは単位が違うから: ここの 1 段は 1 回の描画で、「描いて測って 1px 詰める」\n// 「10 行ずつ段階描画する」のような有限の連鎖が正当に 40〜50 段になる(32 では途中で切れた)。\n// 100 は Vue のスケジューラの RECURSION_LIMIT と同じ値。無限ループの打ち切りまでは Issue の形で十数 ms\n// (Chromium 実測 約 14ms・1 段あたり 0.1ms 強)。\nexport const MAX_RENDER_CHAIN_DEPTH = 100;\n\n// updater の drain 終了リスナーの実行順(昇順に呼ばれる。設計書 §3-2 層 1)。\n// watch が先なのは、watch ハンドラの書き込みが同じバッチの stream restart 判定に\n// 影響しないようにするため(watch → restart の一方向)。import 順に順序を持たせると\n// 無関係な import 整理で静かに壊れるため、明示的な優先度で固定する。\n//\n// devtools が最も先なのは、`state:update-batch` が「そのバッチに何が載ったか」の\n// 観測であり、watch / restart の副作用が乗る前の生の集合を報告すべきだから。\n// 既定値 0 のまま暗黙に先頭へ入るのに任せず、意図として定数で固定する\n// (docs/devtools-hook-protocol.md §4.3)。\nexport const DEVTOOLS_LISTENER_PRIORITY = 0;\nexport const WATCH_LISTENER_PRIORITY = 10;\nexport const STREAM_LISTENER_PRIORITY = 20;\n\n// data-wcs バインディング構文 `[prop][#mod]: [path][|filter...]` の区切り文字(単一正本・`@state` は v2 で撤去)。\n// これらは「死守の壁(構文契約)」であり値は不変。manifest.syntax.delimiters で公開される。\nexport const BINDING_SEPARATOR = ';'; // 複数バインディングの区切り\nexport const PROP_VALUE_SEPARATOR = ':'; // 左辺(prop)と右辺(path)の区切り\nexport const MODIFIER_SEPARATOR = '#'; // prop と修飾子の区切り\nexport const FILTER_SEPARATOR = '|'; // フィルタパイプの区切り\n\n// 修飾子(`#` 後)の語彙(単一正本)。manifest.syntax.modifiers で公開される。\n// フラグ形(`#prevent` — 値を取らない)とキー値形(`#init=element` — `=` で値を取る)。\n// 消費箇所(event/handler・BindingSession・twowayHandler・bindings/initialSync)は\n// この定数を参照する — 文字列リテラルの散在は tooling への収載漏れの温床だった\n// (docs/static-wiring-dx-design.md §2-2)。\nexport const MODIFIER_PREVENT = 'prevent';\nexport const MODIFIER_STOP = 'stop';\nexport const MODIFIER_READONLY = 'ro';\nexport const MODIFIER_FLAGS: readonly string[] = Object.freeze([\n MODIFIER_PREVENT, MODIFIER_STOP, MODIFIER_READONLY,\n]);\nexport const MODIFIER_KEY_INIT = 'init';\nexport const MODIFIER_KEY_SYNC = 'sync';\nexport const MODIFIER_KEYS: readonly string[] = Object.freeze([\n MODIFIER_KEY_INIT, MODIFIER_KEY_SYNC,\n]);\n\n// bindingType 判別と左辺 namespace の語彙(単一正本)。manifest.syntax.bindingTypes で\n// 公開される。パーサ(parseBindTextsForElement)とイベント層はこの定数に分岐する。\n// apply 層のディスパッチマップ(apply/applyChange.ts の applyChangeByFirstSegment)の\n// キー集合との一致は __tests__/manifest.test.ts の drift テストが強制する —\n// manifest エントリ(DOM 非依存)から apply 層を import しないための分離。\nexport const ELSE_KEYWORD = 'else';\nexport const SPREAD_PROP = '...';\nexport const EVENT_PROP_PREFIX = 'on';\nexport const EVENT_TOKEN_NAMESPACE = 'eventToken';\n/**\n * `<wcs-state mount>` の左辺 `state.<key>: path` — ボリュームの注入口(要件 B14③・3.x 計画 D28)。\n * 束縛ではなくマウントの宣言なので、束縛の収集(getParseBindTextResults)は作らず、ボリュームが接ぎ木の時に読む\n */\nexport const VOLUME_INJECTION_PROP = 'state';\nexport const COMMAND_NAMESPACE = 'command';\nexport const CLASS_NAMESPACE = 'class';\nexport const ATTR_NAMESPACE = 'attr';\nexport const STYLE_NAMESPACE = 'style';\n\n// リストインデックス参照名(`$1`..`$N`)の接頭辞(単一正本)。\n// manifest.syntax.indexParam で公開される。\nexport const INDEX_PARAM_PREFIX = '$';\n\n/**\n * stackIndexByIndexName\n * インデックス名からスタックインデックスへのマッピング\n * $1 => 0\n * $2 => 1\n * :\n * ${i + 1} => i\n * i < MAX_WILDCARD_DEPTH\n */\nconst tmpIndexByIndexName: { [key: PropertyKey]: number } = {};\nfor (let i = 0; i < MAX_WILDCARD_DEPTH; i++) {\n tmpIndexByIndexName[`${INDEX_PARAM_PREFIX}${i+1}`] = i;\n}\nexport const INDEX_BY_INDEX_NAME: { [key: PropertyKey]: number } = Object.freeze(tmpIndexByIndexName);\n\nexport const NO_SET_TIMEOUT = 60 * 1000; // 1分\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\nexport const STATE_CONNECTED_CALLBACK_NAME = \"$connectedCallback\";\nexport const STATE_DISCONNECTED_CALLBACK_NAME = \"$disconnectedCallback\";\n/** 旧名 `$updatedCallback` は 3.x の間のエイリアス(要件 B12・declarationAliases.ts) */\nexport const STATE_RENDERED_CALLBACK_NAME = \"$renderedCallback\";\nexport const STATE_ERROR_CALLBACK_NAME = \"$errorCallback\";\n\nexport const WEBCOMPONENT_STATE_READY_CALLBACK_NAME = \"$stateReadyCallback\";\n\nexport const STATE_BINDABLES_NAME = \"$bindables\";\nexport const STATE_COMMANDS_NAME = \"$commands\";\nexport const STATE_COMMAND_TOKENS_NAME = \"$commandTokens\";\nexport const STATE_COMMAND_NAMESPACE_NAME = \"$command\";\nexport const STATE_EVENT_TOKENS_NAME = \"$eventTokens\";\nexport const STATE_ON_NAME = \"$on\";\n/** 旧名 `$streams` は 3.x の間のエイリアス(要件 B12・declarationAliases.ts) */\nexport const STATE_STREAM_NAME = \"$stream\";\nexport const STATE_WATCH_NAME = \"$watch\";\nexport const STATE_SCAN_NAME = \"$scan\";\nexport const STATE_RECURSION_NAME = \"$recursion\";\n\n/**\n * 再帰ワイルドカード。オーサリング層($recursion 宣言・getter キー・API 引数)にだけ\n * 現れ、PathInfo には決して降ろさない — wildcardCount が不定になると ListIndex 連鎖長・\n * $1..$n・$resolve の厳密一致・走査の段数が同時に壊れる\n * (docs/state-recursive-path-design.md §2-1)。\n */\nexport const RECURSION_WILDCARD = \"**\";\nexport const STATE_LIST_KEYS_NAME = \"$listKeys\";\nexport const STATE_STREAM_STATUS_NAMESPACE_NAME = \"$streamStatus\";\nexport const STATE_STREAM_ERROR_NAMESPACE_NAME = \"$streamError\";\nexport const DCC_DEFINITION_ATTRIBUTE = \"data-wc-definition\";\n","import { DELIMITER, MAX_PATH_SEGMENTS, RECURSION_WILDCARD, WILDCARD } from \"../define.js\";\nimport { raiseError } from \"../raiseError.js\";\nimport { IPathInfo } from \"./types.js\";\n\nconst _cache: Map<string, IPathInfo> = new Map();\n\n/**\n * **tooling 専用**(`@wcstack/state/parser` の clearParserCaches からのみ呼ぶ)。\n * ランタイム文脈で呼んではならない — PathInfo のインスタンス同一性は正規化キー\n * (依存グラフ・アドレス比較)の前提であり、クリアすると同一パスの新旧インスタンスが\n * 併存して identity 比較が黙って壊れる。言語サーバー等の長時間プロセスが、編集中の\n * 中間パス(`user.n` 等)の恒久 intern によるメモリ単調増加を断つための出口。\n */\nexport function clearPathInfoCacheForTooling(): void {\n _cache.clear();\n}\n\nlet id: number = 0;\nexport function getPathInfo(path: string): IPathInfo {\n let pathInfo = _cache.get(path);\n if (typeof pathInfo !== \"undefined\") {\n return pathInfo;\n }\n // 再帰ワイルドカードはオーサリング層の記号で、ここへ降りてきてはならない\n // (降ろすと wildcardCount が不定になり ListIndex 連鎖長・$1..$n・$resolve の\n // 厳密一致・走査の段数が同時に壊れる。設計書 D2)。到達したということは、\n // `**` を解釈しない消費者に `**` パスが渡ったということ。通常のパスはこの検査を\n // 初回 intern のときにしか払わない(`**` パスは intern されないので読むたびに落ちる)。\n if (path.indexOf(RECURSION_WILDCARD) !== -1) {\n raiseError(\n `[wcs/recursion-unsupported] \"${path}\" uses \"${RECURSION_WILDCARD}\", which is not accepted here. ` +\n `It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path ` +\n `argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`\n );\n }\n // 深さの上限(初回 intern のときだけ払う)。`PathInfo` は**全ての接頭辞**を intern するので\n // 深さ N のパス 1 本で時間もメモリも O(N²) になり、上限が無いと約 4KB の属性値 1 つで\n // タブが落ちた(実測値は `MAX_PATH_SEGMENTS` の注記)。\n //\n // **ワイルドカードの段数はここでは見ない。** 段数の上限(`MAX_WILDCARD_DEPTH` = manifest の\n // `indexParam.maxDepth`)は `$1..$N` の表が引けるかという別の話で、`recursion/expand.ts` の\n // `[wcs/recursion-depth-exceeded]` と `proxy/traps/get.ts` の `$N` 範囲外診断が、原因を\n // 名指しできる場所で受け持っている(番人: `integration.recursionPrerequisites.test.ts` が\n // 「PathInfo 自体には段数の上限が無い」を固定している)。ここで先に落とすと、深さ超過か\n // 循環かの切り分けが効かなくなる\n const segmentCount = countSegments(path);\n if (segmentCount > MAX_PATH_SEGMENTS) {\n raiseError(\n `[wcs/binding-syntax] \"${path}\" has ${segmentCount} path segments — the limit is ${MAX_PATH_SEGMENTS}. ` +\n `Every prefix of a path is interned, so the cost grows with the square of the depth.`,\n );\n }\n pathInfo = Object.freeze(new PathInfo(path));\n _cache.set(path, pathInfo);\n return pathInfo;\n}\n\n/** `.` の数 + 1。`split` の配列を作らずに数える(初回 intern のときだけ通る) */\nfunction countSegments(path: string): number {\n let count = 1;\n for (let i = 0; i < path.length; i++) {\n if (path[i] === DELIMITER) {\n count++;\n }\n }\n return count;\n}\n\nclass PathInfo implements IPathInfo {\n readonly id: number = ++id;\n readonly path: string;\n readonly segments: string[];\n readonly lastSegment: string;\n readonly cumulativePaths: string[];\n readonly cumulativePathSet: Set<string>;\n readonly cumulativePathInfos: IPathInfo[];\n readonly cumulativePathInfoSet: Set<IPathInfo>;\n readonly parentPath: string | null;\n readonly wildcardPaths: string[];\n readonly wildcardPathSet: Set<string>;\n readonly indexByWildcardPath: Record<string, number>;\n readonly wildcardPathInfos: IPathInfo[];\n readonly wildcardPathInfoSet: Set<IPathInfo>;\n readonly wildcardParentPaths: string[];\n readonly wildcardParentPathSet: Set<string>;\n readonly wildcardParentPathInfos: IPathInfo[];\n readonly wildcardParentPathInfoSet: Set<IPathInfo>;\n readonly wildcardPositions: number[];\n readonly lastWildcardPath: string | null;\n readonly lastWildcardInfo: IPathInfo | null;\n readonly wildcardCount: number;\n readonly parentPathInfo: IPathInfo | null;\n constructor(path: string) {\n // Helper to get or create StructuredPathInfo instances, avoiding redundant creation for self-reference\n const getPattern = (_path: string): IPathInfo => {\n return (path === _path) ? this : getPathInfo(_path);\n };\n \n // Split the pattern into individual path segments (e.g., \"items.*.name\" → [\"items\", \"*\", \"name\"])\n const segments = path.split(\".\");\n \n // Arrays to track all cumulative paths from root to each segment\n const cumulativePaths = [];\n const cumulativePathInfos: IPathInfo[] = [];\n \n // Arrays to track wildcard-specific information\n const wildcardPaths = [];\n const indexByWildcardPath: Record<string, number> = {}; // Maps wildcard path to its index position\n const wildcardPathInfos = [];\n const wildcardParentPaths = []; // Paths of parent segments for each wildcard\n const wildcardParentPathInfos = [];\n const wildcardPositions = [];\n \n let currentPatternPath = \"\", prevPatternPath = \"\";\n let wildcardCount = 0;\n \n // Iterate through each segment to build cumulative paths and identify wildcards\n for(let i = 0; i < segments.length; i++) {\n currentPatternPath += segments[i];\n \n // If this segment is a wildcard, track it with all wildcard-specific metadata\n if (segments[i] === WILDCARD) {\n wildcardPaths.push(currentPatternPath);\n indexByWildcardPath[currentPatternPath] = wildcardCount; // Store wildcard's ordinal position\n wildcardPathInfos.push(getPattern(currentPatternPath));\n wildcardParentPaths.push(prevPatternPath); // Parent path is the previous cumulative path\n wildcardParentPathInfos.push(getPattern(prevPatternPath));\n wildcardPositions.push(i);\n wildcardCount++;\n }\n \n // Track all cumulative paths for hierarchical navigation (e.g., \"items\", \"items.*\", \"items.*.name\")\n cumulativePaths.push(currentPatternPath);\n cumulativePathInfos.push(getPattern(currentPatternPath));\n \n // Save current path as previous for next iteration, then add separator\n prevPatternPath = currentPatternPath;\n currentPatternPath += \".\";\n }\n \n // Determine the deepest (last) wildcard path and the parent path of the entire pattern\n const lastWildcardPath = wildcardPaths.length > 0 ? wildcardPaths[wildcardPaths.length - 1] : null;\n const parentPath = cumulativePaths.length > 1 ? cumulativePaths[cumulativePaths.length - 2] : null;\n \n // Assign all analyzed data to readonly properties\n this.path = path;\n this.segments = segments;\n this.lastSegment = segments[segments.length - 1];\n this.cumulativePaths = cumulativePaths;\n this.cumulativePathSet = new Set(cumulativePaths); // Set for fast lookup\n this.cumulativePathInfos = cumulativePathInfos;\n this.cumulativePathInfoSet = new Set(cumulativePathInfos);\n this.wildcardPaths = wildcardPaths;\n this.wildcardPathSet = new Set(wildcardPaths);\n this.indexByWildcardPath = indexByWildcardPath;\n this.wildcardPathInfos = wildcardPathInfos;\n this.wildcardPathInfoSet = new Set(wildcardPathInfos);\n this.wildcardParentPaths = wildcardParentPaths;\n this.wildcardParentPathSet = new Set(wildcardParentPaths);\n this.wildcardParentPathInfos = wildcardParentPathInfos;\n this.wildcardParentPathInfoSet = new Set(wildcardParentPathInfos);\n this.wildcardPositions = wildcardPositions;\n this.lastWildcardPath = lastWildcardPath;\n this.lastWildcardInfo = lastWildcardPath ? getPattern(lastWildcardPath) : null;\n this.parentPath = parentPath;\n this.parentPathInfo = parentPath ? getPattern(parentPath) : null;\n this.wildcardCount = wildcardCount;\n }\n}\n","/**\n * platform/devtoolsSink.ts(旧 devtools/sink.ts。core 側に置き、devtools/bridge.ts がこちらを import する)\n *\n * 計装点が参照するホットパス唯一の接点。依存ゼロの葉モジュールにすることで、\n * 計装される側(stateElementByName / setByAddress / binding / token)と\n * bridge の間の循環 import を避ける。\n *\n * コスト規範(protocol §1-1): フック未接続時、計装点のコストは\n * `devtoolsSink !== null` の分岐 1 個。イベントオブジェクトの生成は\n * 必ずこのチェックの内側で行うこと。\n */\n\nimport type { DevtoolsSink } from \"../devtools/types\";\n\n/** live binding としてエクスポート。計装点は `if (devtoolsSink !== null)` で参照する */\nexport let devtoolsSink: DevtoolsSink | null = null;\n\nexport function setDevtoolsSink(sink: DevtoolsSink | null): void {\n devtoolsSink = sink;\n}\n","/**\n * pathDiagnostics.ts — パスに関する**エラーの文言**(throw する側)と、診断の両面が共有する部品。\n *\n * 束縛時の存在検査(`user.nmae` のような打ち間違いを console.warn で知らせる開発時の診断)は\n * `features/diagnostics` へ分けた(diagnostics/pathChecks.ts)。core に残るのは、実行を止める\n * エラーの文言と、その did-you-mean が使う候補の集め方だけ。エラーは機能の有無に関わらず\n * 読める文言で落ちなければならないので、ここは core から外せない。\n *\n * 診断 code はコンソール → lint → IDE の三面で共有する(errorGuidance.ts の規約)。\n */\n\nimport { DELIMITER } from \"./define\";\nimport { didYouMean, LINT_HINT } from \"./errorGuidance\";\n\n/** `setPathInfo` の呼び出し元の種別。診断 code と適用範囲がこれで変わる */\nexport type PathInfoSource =\n /** data-wcs / mustache / コメントバインディング */\n | \"binding\"\n /** `$watch` の宣言キー */\n | \"watch\"\n /** `$scan` の `from` / `resetOn`(docs/state-scan-design.md §2-4) */\n | \"scan\"\n /** ランタイム内部のパス翻訳(mapped な bind-component の外向き伝播)。検査しない */\n | \"internal\";\n\n/**\n * `obj` 自身+プロトタイプチェーン(Object.prototype 手前まで)から descriptor を引く。\n * 打ち切り位置は getAllPropertyDescriptors と同じ — 「state が宣言したもの」だけを\n * 存在とみなし、`toString` 等の Object.prototype 由来を存在扱いしない。\n *\n * `State.findStateDescriptor`(再帰アクセサの衝突検査)も同じ走査を使う。打ち切り位置が\n * 2 本に分かれると、片方だけが `Object.prototype` を存在扱いするようなずれ方をする。\n */\nexport function findDescriptor(obj: object, key: string): PropertyDescriptor | undefined {\n let proto: object | null = obj;\n while (proto !== null && proto !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n if (typeof descriptor !== \"undefined\") {\n return descriptor;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return undefined;\n}\n\n/**\n * 数値添字の束縛の暗黙の getter(address/indexPathAccessor.ts・#332)→ その getter が読む行のパス\n * (`groups.0.items` → `groups.*.items`)。存在の診断(diagnostics/pathChecks.ts)がパスの途中で当たった\n * アクセサを作者の宣言と見分け、did-you-mean の候補から外すのに使う(#388)。診断は機能として分けてあるので、\n * core と共有するこのモジュールに置く(置き場所が別だと、分割ビルドに小さなチャンクが増える)。行のパスは\n * 定義時に core で求める — 診断から解決の部品を import すると、それも分割ビルドのチャンクになる。\n */\nexport const indexPathRowPaths: WeakMap<object, string> = new WeakMap();\n\n/** `obj` 自身+プロトタイプチェーンのキー名(did-you-mean の候補集合) */\nfunction ownKeys(obj: object): string[] {\n const keys: string[] = [];\n let proto: object | null = obj;\n while (proto !== null && proto !== Object.prototype) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n keys.push(key);\n }\n proto = Object.getPrototypeOf(proto);\n }\n return keys;\n}\n\n/**\n * 失敗した階層の兄弟候補。生オブジェクトのキーに加え、その階層にフラット宣言\n * (ドットパス getter)されているものも混ぜる — `cart.items.*.subtotl` の正解\n * `subtotal` は行オブジェクトには無く getterPaths にしか居ないため。数値添字の束縛の暗黙の\n * getter(`root` に生えている)は作者の宣言ではなく、打ち間違えた束縛のパスそのものでもあるので\n * 候補にしない(`for: users.0.frends` の行に `Did you mean \"frends\"` と出さない — #388)。\n */\nexport function collectCandidates(\n container: object,\n parentPrefix: string,\n declaredPaths: Iterable<string>,\n root: object,\n): string[] {\n const candidates = ownKeys(container);\n const prefix = parentPrefix.length > 0 ? parentPrefix + DELIMITER : \"\";\n for (const declared of declaredPaths) {\n if (prefix.length > 0 && !declared.startsWith(prefix)) {\n continue;\n }\n const rest = declared.slice(prefix.length);\n // 直下の 1 セグメントだけを候補にする(孫は別階層の名前なので提案しない)\n if (rest.length > 0 && rest.indexOf(DELIMITER) === -1 && !indexPathRowPaths.has(findDescriptor(root, declared)?.get as object)) {\n candidates.push(rest);\n }\n }\n return candidates;\n}\n\n/** 診断 code は lint / IDE と同一語彙(errorGuidance.ts の三面共有規約) */\nexport const DIAGNOSTIC_CODE: Readonly<Record<\"binding\" | \"watch\" | \"scan\", string>> = {\n binding: \"wcs/binding-path-missing\",\n watch: \"wcs/watch-path-missing\",\n scan: \"wcs/scan-path-missing\",\n};\n\nexport const SUBJECT: Readonly<Record<\"binding\" | \"watch\" | \"scan\", string>> = {\n binding: \"Bound path\",\n watch: \"$watch path\",\n scan: \"$scan path\",\n};\n\n/**\n * ルート直下(単一セグメント)のパスが state に無いときのエラーメッセージ。\n *\n * この形だけは親アドレスを辿れないので読み取りが throw する = 元から loud だが、\n * 文面が `address.parentAddress is undefined path: cout` という内部実装の言葉で、\n * 「打ち間違い」だと分からず did-you-mean も lint 誘導も無かった。深いパスの\n * `console.warn` と同じ語彙に揃える。\n */\nexport function missingRootPathMessage(\n path: string,\n target: object,\n declaredPaths: Iterable<string>,\n): string {\n return `[${DIAGNOSTIC_CODE.binding}] Path \"${path}\" does not exist on the state tree.` +\n `${didYouMean(path, collectCandidates(target, \"\", declaredPaths, target))}${LINT_HINT}`;\n}\n\n/**\n * `$resolve` / `$getAll` に渡した添字の本数がワイルドカードの本数と噛み合わない。\n *\n * 不足(`$resolve`)は元から throw していたが、**超過は両 API とも黙って無視**され、\n * 取り違えた添字のまま「もっともらしい値」を返していた。本数はパス文字列から\n * 決まるので、噛み合わないことは常にプログラマのミス。\n */\nexport function indexArityMessage(\n api: \"$resolve\" | \"$getAll\" | \"$setAll\",\n path: string,\n wildcardCount: number,\n actual: number,\n): string {\n // `$getAll` / `$setAll` の添字は前方一致の接頭辞なので上限、`$resolve` だけが厳密一致\n // (docs/state-set-all-design.md §4)。\n const requirement = api === \"$resolve\"\n ? `exactly ${wildcardCount}`\n : `at most ${wildcardCount}`;\n return `[wcs/index-arity] ${api}(\"${path}\") requires ${requirement} index(es) ` +\n `(\"*\" appears ${wildcardCount} time(s) in the path) but got ${actual}.${LINT_HINT}`;\n}\n\n/**\n * `**` を含むパスが宣言済みの再帰アンカーと合致しない(綴り違い・2 つ目の `**`)。\n * 束縛形(bind.ts)・合併形(getAllRecursive.ts)・ブロードキャスト(setAllRecursive.ts)の\n * 3 入口が同じ文面で報告する。\n */\nexport function recursionAnchorMismatchMessage(path: string, recursiveAnchor: string): string {\n return `[wcs/recursion-anchor] \"${path}\" does not match the declared recursion anchor ` +\n `\"${recursiveAnchor}\". This version supports exactly one anchor per state, and \"**\" must be followed ` +\n `by a well-formed suffix (no second \"**\", no empty segment, no bare \"*\" right after \"**\").`;\n}\n\n/**\n * `$getAll(path)`(添字省略)の既定値はループ文脈の添字 `[$1..$n]` だが、それを\n * 敷けるのは path と文脈がワイルドカード連鎖を共有している場合だけ。共有ゼロなのに\n * 文脈が添字を持っている場合、黙って全展開に倒すと「文脈で絞られている」という\n * 書き手の期待と食い違い、異なる文脈の添字の流用とも区別が付かないため throw する。\n *\n * 実行時の評価文脈に依存する(`$setAll` の spread 長と同種)ので lint へは誘導しない。\n */\nexport function getAllContextMismatchMessage(path: string, contextPath: string): string {\n return `$getAll(\"${path}\") was called without indexes inside the loop context of ` +\n `\"${contextPath}\", but the path shares no wildcard level with that context, ` +\n `so the context indexes ($1..$n) do not apply. ` +\n `Pass indexes explicitly ([] expands every level).`;\n}\n\n/**\n * `$setAll(path, indexes, values, { spread: true })` の配列長がマッチ件数と噛み合わない。\n *\n * 静的には件数が分からない(実行時のリスト長に依存する)ので lint へは誘導しない。\n * 黙って切り詰める/余りを捨てると誤配が通ってしまうため throw する\n * (docs/state-set-all-design.md §3-3)。\n */\nexport function setAllSpreadArityMessage(\n path: string,\n matched: number,\n actual: number,\n): string {\n return `$setAll(\"${path}\", …, { spread: true }) requires the values array to have ` +\n `exactly one entry per matched address (matched ${matched}) but got ${actual}. ` +\n `Did the list change between $getAll and $setAll?`;\n}\n\n/**\n * `$setAll` の値と `options` の組み合わせが意味を成さない。\n * (docs/state-set-all-design.md §3-1)\n */\nexport function setAllValueKindMessage(path: string, reason: string): string {\n return `$setAll(\"${path}\") ${reason}`;\n}\n\n/**\n * ワイルドカードを解決するループ文脈が足りない(=パスの階数 > スコープの階数)。\n *\n * `matrix.*.*` を 1 段の `for` の中で読む、`$2` を 1 段のループの中で読む、といった\n * 取り違えがこれ。元の文面は `address.listIndex?.index is undefined path: matrix.*` /\n * `Index not found at position 1 for loopContext:` という内部実装の言葉で、\n * **何を間違えたのかが書かれていなかった**。\n */\nexport function wildcardScopeMessage(subject: string, needed: number, available: number): string {\n return `[wcs/wildcard-rank] ${subject} needs ${needed} enclosing loop level(s) but the current ` +\n `scope provides ${available}. Wrap it in that many \"for\" templates, or use $resolve(path, indexes) ` +\n `to name the row explicitly.${LINT_HINT}`;\n}\n\n"],"names":["DELIMITER","WILDCARD","MAX_WILDCARD_DEPTH","MAX_LOOP_DEPTH","MAX_PROPAGATION_HOPS","MAX_WATCH_CHAIN_DEPTH","MAX_RENDER_CHAIN_DEPTH","DEVTOOLS_LISTENER_PRIORITY","WATCH_LISTENER_PRIORITY","STREAM_LISTENER_PRIORITY","BINDING_SEPARATOR","PROP_VALUE_SEPARATOR","MODIFIER_SEPARATOR","FILTER_SEPARATOR","MODIFIER_PREVENT","MODIFIER_STOP","MODIFIER_READONLY","MODIFIER_KEY_INIT","MODIFIER_KEY_SYNC","ELSE_KEYWORD","SPREAD_PROP","EVENT_PROP_PREFIX","EVENT_TOKEN_NAMESPACE","VOLUME_INJECTION_PROP","COMMAND_NAMESPACE","CLASS_NAMESPACE","ATTR_NAMESPACE","STYLE_NAMESPACE","INDEX_PARAM_PREFIX","tmpIndexByIndexName","i","INDEX_BY_INDEX_NAME","Object","freeze","NO_SET_TIMEOUT","SVG_NAMESPACE","STATE_CONNECTED_CALLBACK_NAME","STATE_DISCONNECTED_CALLBACK_NAME","STATE_RENDERED_CALLBACK_NAME","STATE_ERROR_CALLBACK_NAME","WEBCOMPONENT_STATE_READY_CALLBACK_NAME","STATE_BINDABLES_NAME","STATE_COMMANDS_NAME","STATE_COMMAND_TOKENS_NAME","STATE_COMMAND_NAMESPACE_NAME","STATE_EVENT_TOKENS_NAME","STATE_ON_NAME","STATE_STREAM_NAME","STATE_WATCH_NAME","STATE_SCAN_NAME","STATE_RECURSION_NAME","RECURSION_WILDCARD","STATE_LIST_KEYS_NAME","STATE_STREAM_STATUS_NAMESPACE_NAME","STATE_STREAM_ERROR_NAMESPACE_NAME","DCC_DEFINITION_ATTRIBUTE","_cache","Map","id","getPathInfo","path","pathInfo","get","indexOf","raiseError","segmentCount","count","length","countSegments","PathInfo","set","segments","lastSegment","cumulativePaths","cumulativePathSet","cumulativePathInfos","cumulativePathInfoSet","parentPath","wildcardPaths","wildcardPathSet","indexByWildcardPath","wildcardPathInfos","wildcardPathInfoSet","wildcardParentPaths","wildcardParentPathSet","wildcardParentPathInfos","wildcardParentPathInfoSet","wildcardPositions","lastWildcardPath","lastWildcardInfo","wildcardCount","parentPathInfo","constructor","getPattern","_path","this","split","currentPatternPath","prevPatternPath","push","Set","devtoolsSink","setDevtoolsSink","sink","findDescriptor","obj","key","proto","prototype","descriptor","getOwnPropertyDescriptor","getPrototypeOf","indexPathRowPaths","WeakMap","collectCandidates","container","parentPrefix","declaredPaths","root","candidates","keys","getOwnPropertyNames","ownKeys","prefix","declared","startsWith","rest","slice","has","DIAGNOSTIC_CODE","binding","watch","scan","SUBJECT","missingRootPathMessage","target","didYouMean","LINT_HINT","indexArityMessage","api","actual","recursionAnchorMismatchMessage","recursiveAnchor","getAllContextMismatchMessage","contextPath","setAllSpreadArityMessage","matched","setAllValueKindMessage","reason","wildcardScopeMessage","subject","needed","available"],"mappings":"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"}
@@ -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 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};
1
+ import{i as t,c as e,b 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,au as y,c as b,o as k,m as w,av as P,k as S,aw as $,ax as v,ay as C,az as x,aA as I,aB as A,aC as N,aD as E,h as z,w as D,F as R,x as j,aE as L,aF as T,aG as H,aH as O,aI as G,g as M,aJ as U,aK as F,aL as W,aM as K,aN as V}from"./binder.js";import{u as q,v as B,w as J,b as Q,x as X,q as Y,D as Z,W as tt,R as et,g as st,y as nt,z as at,A as it,o as ot,B as rt,I as lt,C as dt,M as ct,c as ht,e as ut,N as pt,m as ft,i as _t,E as mt,k as gt,S as yt,a as bt,r as kt}from"./pathDiagnostics.js";import{n as wt}from"./declarationAliases.js";import{d as Pt,n as St,w as $t,g as vt,e as Ct,r as xt,c as It,b as At,h as Nt,s as Et,a as zt,f as Dt}from"./setAll.js";import{N as Rt,g as jt,a as Lt,c as Tt,b as Ht}from"./getAllPropertyDescriptors.js";import{a as Ot,b as Gt,c as Mt,d as Ut,e as Ft,f as Wt,g as Kt,h as Vt,i as qt,j as Bt}from"./declarationHooks.js";import{g as Jt}from"./checkDependency.js";import{p as Qt}from"./diagnosticsHooks.js";class Xt{_loopContextStack=Array(q).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>=q&&p(`Exceeded maximum loop context stack depth of ${q}. 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 Yt(t,e){if("all"===Jt(e).wildcardType)return!0;const s=t.getterPaths;if(0===s.size)return!1;for(const t of st(e).cumulativePaths)if(s.has(t))return!0;return!1}const Zt=/^\$\d+$/,te=`${ht}${Z}`,ee=`${ut}${Z}`,se=new WeakMap;function ne(t,e,s,n){const a=lt[e];if(void 0===a&&"string"==typeof e&&36===e.charCodeAt(0)&&Zt.test(e)&&p(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from ${dt}1 to ${dt}${ct}, 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=w(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!==Rt)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=Jt(e),o=Pt(t,i,s,n),r=m(i.pathInfo,o),l=g(a,r),d=b();d.enqueueAbsoluteAddress(l),St(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"$trackDependency":case"$dependOn":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(Yt(n.stateElement,t))return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&P(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=Yt(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?P(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=w(a.listIndex,e-1,a.pathInfo.wildcardCount);if(null===i&&p(`$eqIndex("${t}", ${e}): no list index at that level.`),Yt(n.stateElement,t))return n.stateElement.getterPaths.has(a.pathInfo.path)&&(P(n.stateElement,t),n.stateElement.addIndexDependentGetterPath?.(a.pathInfo.path)),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?S(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"$untrackDependency":case"$untracked":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(te)&&!e.startsWith(ee))return}const i=Jt(e),o=Pt(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=se.get(t);return void 0===e&&(e=new Map,se.set(t,e)),e}(n),i=a.get(e);if(void 0!==i)return i;let o;switch(e){case D: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,at);"function"==typeof n&&await n.call(s)}(t,0,s);break;case A:o=()=>function(t,e,s){const n=Reflect.get(t,it);"function"==typeof n&&n.call(s)}(t,0,s);break;case I:o=e=>function(t,e,s,n){const a=Reflect.get(t,ot);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)}}(t.size>0||0===e.length)&&(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,rt);"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 ae{_stateElement;_addressStack=Array(q).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>=q&&(this._hasRepeatedAddress()&&p(`[wcs/getter-cycle] Exceeded maximum address stack depth of ${q}. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),p(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of ${q} 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 ne(t,e,s,this)}set(t,e,s,n){return zt(this),function(t,e,s,n,a){if("string"==typeof e){const i=Jt(e),o=Pt(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 ie="undefined"==typeof HTMLElement?class{}:HTMLElement;const oe=new Set(["for","if","elseif","else"]);function re(e,s,n){const a=new Map;for(const t of n){const e=st(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=O(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(st(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)oe.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=L("state",a);void 0!==o&&o.catch(T)}finally{H()}}const le=[[_t,"watch"],[yt,"scan"],[bt,"streams"],[kt,"recursion"]];class de extends ie{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 Xt}();_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){wt(t),function(t){for(let e=0;e<le.length;e++){const[s,n]=le[e];s in t&&!Bt(n)&&p(V(n,`"${s}"`))}}(t);const e=this.__state,s=qt();s.set("previousState",e),Ot(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),Gt(this,t,s),Mt(this,t,s),this._commandTokenNames=n,this._eventTokenNames=a,this._stateGeneration++,this.__state=t,void 0!==e&&Qt?.reset(this),this._hasUpdatedCallback=ot in t,this._hasErrorCallback=rt in t,U(this),Ut(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=jt(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);Ft(this,t,s),this._listKeys=i,this._rebuildPathInfo(),Wt(this,t,s),Kt(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")?F('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state")){return function(t){const e=document.getElementById(t);return e&&"application/json"===e.type?JSON.parse(e.textContent||"{}"):(console.warn(`[@wcstack/state] state="${t}": no <script type="application/json" id="${t}"> in the document (3.x does not look inside shadow roots), so the state starts empty.`),{})}(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.`)},pt),s=await this._setStatePromise;return clearTimeout(t),s}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){let e;try{const s=await fetch(t);if(s.ok)return await s.json();e=`HTTP ${s.status} ${s.statusText}`}catch(t){e=t}return console.error(`[@wcstack/state] Failed to load JSON file "${t}", so the state starts empty (4.0 rejects instead):`,e),{}}(t);if(t&&t.endsWith(".js"))return await n(t);p(`Unsupported src file type: ${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;this._initializeFailed=!0;const n=["state","src"].find(t=>this.hasAttribute(t));throw console.error(`[@wcstack/state] <${e.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),s&&null!==this._rootNode&&null===R(this._rootNode)&&(K(this._rootNode,t),i(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{at in t&&await t[N]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{it 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||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(ft))try{r("dcc",`a <${e.tagNames.state}> inside a [${ft}] 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 F('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Kt(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),Dt(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=>(wt(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",_t)}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 mt(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=Lt(t,e);null===this._addressHooks&&(this._addressHooks=Tt()),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",gt)}_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){if(!this._addDependency(this._dynamicDependency,t,e))return!1;const s=st(t);for(let t=s.parentPathInfo;null!==t&&t.wildcardCount>0&&t.wildcardCount===s.wildcardCount;t=t.parentPathInfo)this._addDependency(this._dynamicDependency,t.path,e);return!0}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=st(t);this._pathSet.add(t);const n=function(t,e){const s=Jt(e);return"all"===s.wildcardType&&1===s.wildcardIndexes.length&&isNaN(+s.segments[0])&&!e.includes("#")&&Object.isExtensible(t)&&!(e in t)}(this.__state,t);if(Qt?.check(this,this.__state,t,s,n),n&&function(t,e){const{segments:s,cumulativePaths:n}=st(e),a=s.length-1,i=(t,i,o)=>{let r,l=!1;for(let d=0;d<=a;d++){const c=s[d];if(l||=!(isNaN(+c)||Array.isArray(r)&&+c in r),i&&d===a)return l?r[c]=o:t[e]=o;r=l?r?.[c]:t[n[d]]}return r},o=function(){return i(this)};nt.set(o,Jt(e).pathInfo.path),t.defineTreeAccessor(e,{get:o,set(t){i(this,!0,t)},configurable:!0})}(this,t),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=st(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 ae(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(jt(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){re(this,t,this._pathRegistrations.keys())}}const ce=[],he=[];function ue(){const t=[];let e=0;for(let s=0;s<he.length;s++){const n=he[s].deref();void 0!==n&&(t.push(n),he[e++]=he[s])}return he.length=e,t}function pe(t){if(!ce.includes(t)){ce.push(t);for(const e of ue())t(e)}}function fe(t=customElements){ue().includes(t)||he.push(new WeakRef(t));for(let e=0;e<ce.length;e++)ce[e](t);t.get(e.tagNames.state)||t.define(e.tagNames.state,de)}export{ie as H,pe as a,fe as r};
2
2
  //# sourceMappingURL=registerComponents.js.map