@wcstack/state 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +47 -17
- package/README.md +47 -17
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/define.d.ts +11 -7
- package/dist/index.d.ts +15 -7
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.d.ts +14 -1
- package/dist/manifest.esm.js +91 -35
- package/dist/parser.esm.js +25 -0
- package/dist/split/chunks/binder.js +1 -1
- package/dist/split/chunks/binder.js.map +1 -1
- package/dist/split/chunks/checkDependency.js +1 -1
- package/dist/split/chunks/declarationAliases.js +2 -0
- package/dist/split/chunks/declarationAliases.js.map +1 -0
- package/dist/split/chunks/filterRegistry.js +1 -1
- package/dist/split/chunks/filterRegistry.js.map +1 -1
- package/dist/split/chunks/mount.js +1 -1
- package/dist/split/chunks/mount.js.map +1 -1
- package/dist/split/chunks/pathDiagnostics.js +1 -1
- package/dist/split/chunks/pathDiagnostics.js.map +1 -1
- package/dist/split/chunks/registerComponents.js +1 -1
- package/dist/split/chunks/registerComponents.js.map +1 -1
- package/dist/split/chunks/setAll.js +1 -1
- package/dist/split/chunks/version.js +1 -1
- package/dist/split/chunks/watchRuntime.js +1 -1
- package/dist/split/core.d.ts +11 -7
- package/dist/split/core.js +1 -1
- package/dist/split/core.js.map +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/devtools.js.map +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/formats.js +1 -1
- package/dist/split/features/formats.js.map +1 -1
- package/dist/split/features/recursion.js +1 -1
- package/dist/split/features/scopes.js +1 -1
- package/dist/split/features/scopes.js.map +1 -1
- package/dist/split/features/ssr.js +1 -1
- package/dist/split/features/ssr.js.map +1 -1
- package/dist/split/features/temporal.js +1 -1
- package/dist/split/features/temporal.js.map +1 -1
- package/dist/wcs-manifest.json +65 -25
- 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;\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';\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\";\nexport const STATE_UPDATED_CALLBACK_NAME = \"$updatedCallback\";\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\";\nexport const STATE_STREAMS_NAME = \"$streams\";\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 { 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 pathInfo = Object.freeze(new PathInfo(path));\n _cache.set(path, pathInfo);\n return pathInfo;\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","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_UPDATED_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_STREAMS_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","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","length","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":"qDAAO,MAAMA,EAAY,IACZC,EAAW,IACXC,EAAqB,IACrBC,EAAiB,IAGjBC,EAAuB,GAMvBC,EAAwB,GAWxBC,EAA6B,EAC7BC,EAA0B,GAC1BC,EAA2B,GAI3BC,EAAoB,IACpBC,EAAuB,IACvBC,EAAqB,IACrBC,EAAmB,IAOnBC,EAAmB,UACnBC,EAAgB,OAChBC,EAAoB,KAIpBC,EAAoB,OACpBC,EAAoB,OAUpBC,EAAe,OACfC,EAAc,MACdC,EAAoB,KACpBC,EAAwB,aACxBC,EAAoB,UACpBC,EAAkB,QAClBC,EAAiB,OACjBC,EAAkB,QAIlBC,EAAqB,IAW5BC,EAAsD,CAAA,EAC5D,IAAK,IAAIC,EAAI,EAAGA,EA7EkB,IA6EMA,IACtCD,EAAoB,IAAwBC,EAAE,KAAOA,EAEhD,MAAMC,EAAsDC,OAAOC,OAAOJ,GAEpEK,EAAiB,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ASgBC,GACd9E,EACA+E,EACAN,GAEA,MAAO,YAAYzE,6GACiC+E,cAAoBN,qDAE1E,CAMM,SAAUO,GAAuBhF,EAAciF,GACnD,MAAO,YAAYjF,OAAUiF,GAC/B,UAUgBC,GAAqBC,EAAiBC,EAAgBC,GACpE,MAAO,uBAAuBF,WAAiBC,4DAC3BC,sGACYf,GAClC"}
|
|
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;\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_UPDATED_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_STREAMS_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 { 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 pathInfo = Object.freeze(new PathInfo(path));\n _cache.set(path, pathInfo);\n return pathInfo;\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_UPDATED_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_STREAMS_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","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","length","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":"qDAAO,MAAMA,EAAY,IACZC,EAAW,IACXC,EAAqB,IACrBC,EAAiB,IAGjB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CACrFC,QAAS,2BACTC,MAAO,yBACPC,KAAM,yBAGKC,GAAkE,CAC7EH,QAAS,aACTC,MAAO,cACPC,KAAM,uBAWQE,GACdnE,EACAoE,EACAhB,GAEA,MAAO,IAAIU,GAAgBC,kBAAkB/D,uCACxCqE,EAAWrE,EAAMiD,GAAkBmB,EAAQ,GAAIhB,MAAkBkB,GACxE,CASM,SAAUC,GACdC,EACAxE,EACA0B,EACA+C,GAOA,MAAO,qBAAqBD,MAAQxE,gBAHR,aAARwE,EAChB,WAAW9C,IACX,WAAWA,8BAEGA,kCAA8C+C,KAAUH,GAC5E,CAOM,SAAUI,GAA+B1E,EAAc2E,GAC3D,MAAO,2BAA2B3E,oDAC5B2E,6KAER,CAUM,SAAUC,GAA6B5E,EAAc6E,GACzD,MAAO,YAAY7E,8DACb6E,8JAGR,UASgBC,GACd9E,EACA+E,EACAN,GAEA,MAAO,YAAYzE,6GACiC+E,cAAoBN,qDAE1E,CAMM,SAAUO,GAAuBhF,EAAciF,GACnD,MAAO,YAAYjF,OAAUiF,GAC/B,UAUgBC,GAAqBC,EAAiBC,EAAgBC,GACpE,MAAO,uBAAuBF,WAAiBC,4DAC3BC,sGACYf,GAClC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as t,c as e,a as s}from"./filterRegistry.js";import{l as n,a,b as i,c as o,d as r,e as l,f as d,g as h,h as c,i as u}from"./lifecycleHooks.js";import{r as p,d as f}from"./errorGuidance.js";import{d as _,k as m,l as g,af as y,c as b,x as k,H as S,ag as w,G as P,ah as v,ai as $,aj as C,ak as x,al as I,am as A,an as N,ao as E,ap as z,F as D,j as L,y as R,o as j,aq as H,ar as O,as as T,at as G,au as M,g as F,av as U,aw as W,ax as V,ay as q}from"./binder.js";import{t as K,u as B,v as J,b as Q,w as X,l as Y,D as Z,W as tt,R as et,x as st,y as nt,n as at,z as it,I as ot,A as rt,M as lt,c as dt,d as ht,g as ct,N as ut,i as pt,k as ft,B as _t,f as mt}from"./pathDiagnostics.js";import{d as gt,e as yt,w as bt,f as kt,r as St,c as wt,b as Pt,g as vt,s as $t,h as Ct,a as xt,i as It}from"./setAll.js";import{N as At,g as Nt,b as Et,c as zt,d as Dt,e as Lt,f as Rt,h as jt,i as Ht,j as Ot,k as Tt,l as Gt,m as Mt,n as Ft}from"./getAllPropertyDescriptors.js";import{p as Ut}from"./diagnosticsHooks.js";class Wt{_loopContextStack=Array(K).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&p("Cannot create loop context for a state address that does not have a list index.");const s=t;this._length>=K&&p(`Exceeded maximum loop context stack depth of ${K}. Possible infinite loop.`);const n=this._loopContextStack[this._length-1];if(void 0!==n){n.pathInfo.wildcardCount+1!==s.pathInfo.wildcardCount&&p("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=s.pathInfo.wildcardPathInfos[s.pathInfo.wildcardPathInfos.length-2];n.pathInfo!==t&&p("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else s.listIndex.length!==s.pathInfo.wildcardCount&&p(`Cannot push loop context when there is no active loop context: the list index chain (length ${s.listIndex.length}) does not cover the wildcard path (wildcard count ${s.pathInfo.wildcardCount}).`);let a;this._loopContextStack[this._length]=s,this._length++;try{a=e(s)}finally{a instanceof Promise?a.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return a}}function Vt(t,e){const s=t.getterPaths;if(0===s.size)return!1;for(const t of ct(e).cumulativePaths)if(s.has(t))return!0;return!1}const qt=/^\$\d+$/,Kt=`${dt}${Z}`,Bt=`${ht}${Z}`,Jt=new WeakMap;function Qt(t,e,s,n){const a=ot[e];if(void 0===a&&"string"==typeof e&&36===e.charCodeAt(0)&&qt.test(e)&&p(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from ${rt}1 to ${rt}${lt}, with no leading zeros.`),void 0!==a){0===n.addressStackLength&&p(`No active state reference to get list index for "${e.toString()}".`);const t=n.lastAddressStack,s=t?.pathInfo;s&&!n.untracking&&n.stateElement?.getterPaths.has(s.path)&&n.stateElement.addIndexDependentGetterPath?.(s.path);const i=t?.listIndex;null==i&&p(`ListIndex not found: ${e.toString()}`);let o=a;const r=t.pathInfo,l=n.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let s=0;s<e.length;s++)o+=e[s](n,t)}const d=S(i,o,r.wildcardCount);return d?.index??p(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const a=n.stateElement?.addressHooks;if(a){const i=a.get;for(let a=0;a<i.length;a++){const o=i[a](n,e,s,t);if(o!==At)return o}}if("$"===e[0]){switch(e){case"$stateElement":return n.stateElement;case"$getAll":return(a,i)=>Pt(t,e,s,n)(a,i);case"$setAll":return(a,i,o,r)=>wt(t,e,s,n)(a,i,o,r);case"$postUpdate":return e=>function(t,e,s,n){const a=n.stateElement;return e=>{const i=gt(e),o=yt(t,i,s,n),r=m(i.pathInfo,o),l=g(a,r),d=b();d.enqueueAbsoluteAddress(l),bt(n.stateElement,r,n.stateElement.staticDependency,n.stateElement.dynamicDependency,n.stateElement.listPaths,s,"new",t=>{const e=g(a,t);y(e),d.enqueueAbsoluteAddress(e)});const h=a.addressHooks;if(h){const t=h.written;for(let e=0;e<t.length;e++)t[e](a,r.pathInfo)}}}(t,0,s,n)(e);case"$resolve":return(a,i,...o)=>St(t,e,s,n)(a,i,...o);case"$trackDependency":return t=>function(t,e,s,n){return t=>{-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===n.addressStackLength&&p(`No active state reference to track dependency for path "${t}".`);const e=n.lastAddressStack?.pathInfo??p("Internal error: lastAddressStack is null"),s=n.stateElement;n.stateElement.getterPaths.has(e.path)&&e.path!==t&&s.addDynamicDependency(t,e.path)}}(0,0,0,n)(t);case"$eq":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;if(Vt(n.stateElement,t))return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],e);let i;n.beginUntrack();try{i=s[t]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&C(n.stateElement,t,e,g(n.stateElement,a),i),Object.is(i,e)};case"$eqPath":return(t,e)=>{const a=n.addressStackLength>0?n.lastAddressStack:null,i=Vt(n.stateElement,t);let o,r=i?s[t]:void 0;n.beginUntrack();try{i||(r=s[t]),o=s[e]}finally{n.endUntrack()}return null!==a&&n.stateElement.getterPaths.has(a.pathInfo.path)&&(i?w(n.stateElement,t):C(n.stateElement,t,o,g(n.stateElement,a),r)),Object.is(r,o)};case"$eqIndex":return(t,e=1)=>{const a=n.addressStackLength>0?n.lastAddressStack:null;null!==a&&null!==a.listIndex||p(`$eqIndex("${t}") needs a list row scope.`);const i=S(a.listIndex,e-1,a.pathInfo.wildcardCount);if(null===i&&p(`$eqIndex("${t}", ${e}): no list index at that level.`),Vt(n.stateElement,t))return n.stateElement.getterPaths.has(a.pathInfo.path)&&w(n.stateElement,t),Object.is(s[t],i.index);const o=e===a.pathInfo.wildcardCount;let r,l;n.beginUntrack();try{r=s[t],o&&(l=s[a.pathInfo.wildcardParentPaths[e-1]])}finally{n.endUntrack()}if(n.stateElement.getterPaths.has(a.pathInfo.path)){const e=o?P(l):null;null!==e?v(n.stateElement,t,a.pathInfo,e,r):$(n.stateElement,t,i,g(n.stateElement,a),r)}return Object.is(r,i.index)};case"$untrackDependency":return t=>function(t,e,s,n){return t=>{n.beginUntrack();try{return t()}finally{n.endUntrack()}}}(0,0,0,n)(t);case J:return kt(n.stateElement)}if(!e.startsWith(Kt)&&!e.startsWith(Bt))return}const i=gt(e),o=yt(t,i,s,n),r=m(i.pathInfo,o);return vt(t,r,s,n)}if("symbol"==typeof e){const a=function(t){let e=Jt.get(t);return void 0===e&&(e=new Map,Jt.set(t,e)),e}(n),i=a.get(e);if(void 0!==i)return i;let o;switch(e){case L:o=(t,e=()=>{})=>function(t,e,s){void 0!==t.loopContext&&p("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return s()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(n,t,e);break;case D:o=e=>vt(t,e,s,n);break;case z:o=e=>Ct(t,e,s,n);break;case E:o=(e,a)=>$t(t,e,a,s,n);break;case N:o=()=>async function(t,e,s){const n=Reflect.get(t,st);"function"==typeof n&&await n.call(s)}(t,0,s);break;case A:o=()=>function(t,e,s){const n=Reflect.get(t,nt);"function"==typeof n&&n.call(s)}(t,0,s);break;case I:o=e=>function(t,e,s,n){const a=Reflect.get(t,at);let i;if("function"==typeof a){const t=new Set,o={};for(const s of e){if(s.absolutePathInfo.stateElement!==n.stateElement)continue;const e=s.absolutePathInfo.pathInfo,a=e.path;if(-1===a.indexOf("#")&&(t.add(a),e.wildcardCount>0)){const t=k(s.listIndex,e.wildcardCount),n=o[a];void 0===n?o[a]=[t]:n.push(t)}}i=a.call(s,Array.from(t),o)}const o=n.stateElement?.addressHooks;if(o){const t=o.updated;for(let a=0;a<t.length;a++)t[a](n.stateElement,e,s)}return i}(t,e,s,n);break;case x:o=(e,n)=>function(t,e,s,n){const a=Reflect.get(t,it);"function"==typeof a&&a.call(n,e,s)}(t,e,n,s);break;default:return Reflect.get(t,e,s)}return a.set(e,o),o}}class Xt{_stateElement;_addressStack=Array(K).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const s=R(t);null===s&&p("StateHandler: no state tree found on this root."),this._stateElement=s,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&p("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=K&&(this._hasRepeatedAddress()&&p(`[wcs/getter-cycle] Exceeded maximum address stack depth of ${K}. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),p(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of ${K} with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const s=this._addressStack[e];if(s){if(t.has(s))return!0;t.add(s)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const s=this._addressStack[e];s&&t.push(s.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&p(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,s){return Qt(t,e,s,this)}set(t,e,s,n){return xt(this),function(t,e,s,n,a){if("string"==typeof e){const i=gt(e),o=yt(t,i,n,a),r=m(i.pathInfo,o);return $t(t,r,s,n,a)}return Reflect.set(t,e,s,n)}(t,e,s,n,this)}has(t,e){return Reflect.has(t,e)}}const Yt="undefined"==typeof HTMLElement?class{}:HTMLElement;const Zt=new Set(["for","if","elseif","else"]);function te(e,s,n){const a=new Map;for(const t of n){const e=ct(t);if(null===e.lastWildcardPath)continue;const s=a.get(e.lastWildcardPath);void 0===s?a.set(e.lastWildcardPath,[e]):s.push(e)}const i=[],o=new Set,r=t=>{const s=g(e,t);if(o.has(s))return;o.add(s);const n=G(s);if(n instanceof Set?i.push(...n):void 0!==n&&i.push(n),null!==t.listIndex){const e=a.get(t.pathInfo.path);if(void 0!==e)for(const s of e)r(m(s,t.listIndex))}};M();try{if(e.createState("readonly",t=>{for(const n of s){const s=m(ct(n),null);r(s);try{bt(e,s,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",r)}catch{}}}),0===i.length)return;const n=function(t){const e=[],s=[];for(const n of t)Zt.has(n.bindingType)?e.push(n):s.push(n);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(s)}(i),a=()=>{j(n,void 0,{updatedCallback:!1})};if(t())return void a();const o=H("state",a);void 0!==o&&o.catch(O)}finally{T()}}class ee extends Yt{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return F(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Wt}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&p(`${e.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const e=this.__state,s=Ft();s.set("previousState",e),Et(this,t,s);const n=function(t){const e=new Set,s=t[B];if(void 0===s)return e;Array.isArray(s)||p(`${B} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${B} entries must be non-empty strings.`),t===J&&p(`${B} entry "${t}" conflicts with the reserved namespace name "${J}".`),e.has(t)&&p(`${B} entry "${t}" is duplicated.`),e.add(t);return e}(t),a=function(t){const e=new Set,s=t[Q];if(void 0===s)return e;Array.isArray(s)||p(`${Q} must be an array of strings.`);for(const t of s)"string"==typeof t&&0!==t.length||p(`${Q} entries must be non-empty strings.`),e.has(t)&&p(`${Q} entry "${t}" is duplicated.`),e.add(t);return e}(t),i=function(t){const e=t[Y];if(void 0===e)return null;"object"==typeof e&&null!==e||p(`${Y} must be an object mapping list paths to key specs.`);const s=new Map;for(const[t,n]of Object.entries(e)){0===t.length&&p(`${Y} entry path must be a non-empty string.`);const e=t.split(Z);e.some(t=>0===t.length)&&p(`${Y} entry "${t}" must not contain empty path segments.`),e[e.length-1]===tt&&p(`${Y} entry "${t}" must be the list path itself, not the element path (drop the trailing "${Z}${tt}").`),-1!==t.indexOf(et)&&p(`[wcs/recursion-unsupported] ${Y} entry "${t}" uses "${et}", which ${Y} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${Z}${tt}${Z}children").`),"function"!=typeof n?("string"!=typeof n&&p(`${Y} entry "${t}" key spec must be a field name (string) or a function.`),0===n.length&&p(`${Y} entry "${t}" key field name must be a non-empty string.`),(n.includes(Z)||n.includes(tt))&&p(`${Y} entry "${t}" key field name "${n}" must be a flat property name ("${Z}" / "${tt}" are not allowed).`),n in Object.prototype&&p(`${Y} entry "${t}" key field name "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),s.set(t,n)):s.set(t,n)}return s.size>0?s:null}(t);s.set("eventTokenNames",a),zt(this,t,s),Dt(this,t,s),this._commandTokenNames=n,this._eventTokenNames=a,this._stateGeneration++,this.__state=t,void 0!==e&&Ut?.reset(this),this._hasUpdatedCallback=at in t,this._hasErrorCallback=it in t,U(this),Lt(this,t,s),function(t,e,s){const n=e[X];if(void 0!==n){"object"==typeof n&&null!==n||p(`${X} must be an object mapping event-token names to handler functions.`);for(const[e,a]of Object.entries(n))s.has(e)||p(`${X} entry "${e}" is not declared in $eventTokens.${f(e,s)}`),"function"!=typeof a&&p(`${X} entry "${e}" must be a function.`),_(t,e).subscribe(a)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const o=function(t){const e=new Set,s=new Set,n=Nt(t);for(const[t,a]of Object.entries(n))"function"==typeof a.get&&e.add(t),"function"==typeof a.set&&s.add(t);return{getterPaths:e,setterPaths:s}}(t);for(const t of o.getterPaths)this._getterPaths.add(t);for(const t of o.setterPaths)this._setterPaths.add(t);Rt(this,t,s),this._listKeys=i,this._rebuildPathInfo(),jt(this,t,s),Ht(this,null),this._resolveLoading?.()}attributeChangedCallback(t,s,n){this._initialized&&s!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===s?"absent":`"${s}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${e.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?W('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){p("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await a(t,e.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${e.tagNames.state}> element.`)},ut),s=await this._setStatePromise;return clearTimeout(t),s}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||p(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await n(t);p(`Unsupported src file type: ${t}`)}}catch(t){p(`Failed to initialize state: ${t}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,s]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=s}return await this._loadingPromise,null!==this._rootNode&&(V(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),p(t)}_failInitializeLoudly(t,s=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${e.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),s&&null!==this._rootNode&&null===R(this._rootNode)&&(q(this._rootNode,t),i(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{st in t&&await t[N]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{nt in t&&t[A]()})}async connectedCallback(){this._rootNode=this.getRootNode();const n=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(d(this))return void this._resolveConnectedCallback?.();this._treeless||R(this._rootNode)===this||V(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const t=o(this);if(null!==t)return void await t;const s=this.parentNode;if(s instanceof ShadowRoot&&s.host.hasAttribute(pt))try{r("dcc",`a <${e.tagNames.state}> inside a [${pt}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{r("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let n=!1;try{const t=l(this);null===t&&this.hasAttribute("bind-component")&&r("scopes",'the "bind-component" attribute'),n=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(n)return;let a=!1;try{a=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!a)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!t()||n!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!s())try{await W('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Ht(this,n),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!h(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&c(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{V(this.rootNode,null),It(this),Ot(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource()}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const s of t)e.add(s);this._watchPaths=e,this.attachAddressHooks("watch",ft)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[s,n]of t)e.has(s)&&p(`$listKeys entry "${s}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(s,n);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return _t(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&p("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const s=Tt(t,e);null===this._addressHooks&&(this._addressHooks=Gt()),Mt(this._addressHooks,s)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",mt)}_addDependency(t,e,s){const n=t.get(e);return void 0===n?(t.set(e,[s]),!0):!n.includes(s)&&(n.push(s),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,s="binding"){if("internal"!==s){const n=this._pathRegistrations.get(t);void 0===n?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===s}):"for"!==n.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:n.bound||"binding"===s})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+tt)),!this._pathSet.has(t)){const e=ct(t);if(this._pathSet.add(t),Ut?.check(this,this.__state,t,s),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ct(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,s){try{const n=function(t,e,s){const n=new Xt(t,s);return new Proxy(e,n)}(t,this._state,e);return s(n)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&p(`<${e.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);u(this),(this._hasGraftedVolumes||this._hasMounts)&&p("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const s=this.__state;this._state=t;const n=function(t){const e=new Set;for(const s of t)if(void 0!==s)for(const[t,n]of Object.entries(Nt(s)))t.startsWith("$")||t.includes(tt)||"function"==typeof n.value||e.add(t);return e}([s,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){te(this,t,this._pathRegistrations.keys())}}const se=[];function ne(t){se.includes(t)||se.push(t)}function ae(t=customElements){for(let e=0;e<se.length;e++)se[e](t);t.get(e.tagNames.state)||t.define(e.tagNames.state,ee)}export{Yt as H,ne as a,ae as r};
|
|
1
|
+
import{i as t,c as e,a as s}from"./filterRegistry.js";import{l as n,a,b as i,c as o,d as r,e as l,f as d,g as c,h,i as u}from"./lifecycleHooks.js";import{r as p,d as f}from"./errorGuidance.js";import{d as _,k as m,l as g,af as y,c as b,x as k,I as S,ag as w,H as P,ah as $,ai as v,aj as C,ak as x,al as I,am as A,an as N,ao as E,ap as z,G as D,j as L,y as R,o as j,aq as O,ar as H,as as T,at as G,au as M,g as F,av as U,aw as W,ax as V,ay as q}from"./binder.js";import{u as K,v as B,w as J,b as Q,x as X,m as Y,D as Z,W as tt,R as et,y as st,z as nt,o as at,A as it,I as ot,B as rt,M as lt,c as dt,d as ct,g as ht,N as ut,i as pt,l as ft,C as _t,f as mt}from"./pathDiagnostics.js";import{n as gt}from"./declarationAliases.js";import{d as yt,e as bt,w as kt,f as St,r as wt,c as Pt,b as $t,g as vt,s as Ct,h as xt,a as It,i as At}from"./setAll.js";import{N as Nt,g as Et,b as zt,c as Dt,d as Lt,e as Rt,f as jt,h as Ot,i as Ht,j as Tt,k as Gt,l as Mt,m as Ft,n as Ut}from"./getAllPropertyDescriptors.js";import{p as Wt}from"./diagnosticsHooks.js";class Vt{_loopContextStack=Array(K).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&p("Cannot create loop context for a state address that does not have a list index.");const s=t;this._length>=K&&p(`Exceeded maximum loop context stack depth of ${K}. Possible infinite loop.`);const n=this._loopContextStack[this._length-1];if(void 0!==n){n.pathInfo.wildcardCount+1!==s.pathInfo.wildcardCount&&p("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=s.pathInfo.wildcardPathInfos[s.pathInfo.wildcardPathInfos.length-2];n.pathInfo!==t&&p("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else s.listIndex.length!==s.pathInfo.wildcardCount&&p(`Cannot push loop context when there is no active loop context: the list index chain (length ${s.listIndex.length}) does not cover the wildcard path (wildcard count ${s.pathInfo.wildcardCount}).`);let a;this._loopContextStack[this._length]=s,this._length++;try{a=e(s)}finally{a instanceof Promise?a.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return a}}function qt(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 Kt=/^\$\d+$/,Bt=`${dt}${Z}`,Jt=`${ct}${Z}`,Qt=new WeakMap;function Xt(t,e,s,n){const a=ot[e];if(void 0===a&&"string"==typeof e&&36===e.charCodeAt(0)&&Kt.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!==Nt)return o}}if("$"===e[0]){switch(e){case"$stateElement":return n.stateElement;case"$getAll":return(a,i)=>$t(t,e,s,n)(a,i);case"$setAll":return(a,i,o,r)=>Pt(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=yt(e),o=bt(t,i,s,n),r=m(i.pathInfo,o),l=g(a,r),d=b();d.enqueueAbsoluteAddress(l),kt(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)=>wt(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(qt(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=qt(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.`),qt(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 St(n.stateElement)}if(!e.startsWith(Bt)&&!e.startsWith(Jt))return}const i=yt(e),o=bt(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=Qt.get(t);return void 0===e&&(e=new Map,Qt.set(t,e)),e}(n),i=a.get(e);if(void 0!==i)return i;let o;switch(e){case L:o=(t,e=()=>{})=>function(t,e,s){void 0!==t.loopContext&&p("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return s()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(n,t,e);break;case D:o=e=>vt(t,e,s,n);break;case z:o=e=>xt(t,e,s,n);break;case E:o=(e,a)=>Ct(t,e,a,s,n);break;case N:o=()=>async function(t,e,s){const n=Reflect.get(t,st);"function"==typeof n&&await n.call(s)}(t,0,s);break;case A:o=()=>function(t,e,s){const n=Reflect.get(t,nt);"function"==typeof n&&n.call(s)}(t,0,s);break;case I:o=e=>function(t,e,s,n){const a=Reflect.get(t,at);let i;if("function"==typeof a){const t=new Set,o={};for(const s of e){if(s.absolutePathInfo.stateElement!==n.stateElement)continue;const e=s.absolutePathInfo.pathInfo,a=e.path;if(-1===a.indexOf("#")&&(t.add(a),e.wildcardCount>0)){const t=k(s.listIndex,e.wildcardCount),n=o[a];void 0===n?o[a]=[t]:n.push(t)}}i=a.call(s,Array.from(t),o)}const o=n.stateElement?.addressHooks;if(o){const t=o.updated;for(let a=0;a<t.length;a++)t[a](n.stateElement,e,s)}return i}(t,e,s,n);break;case x:o=(e,n)=>function(t,e,s,n){const a=Reflect.get(t,it);"function"==typeof a&&a.call(n,e,s)}(t,e,n,s);break;default:return Reflect.get(t,e,s)}return a.set(e,o),o}}class Yt{_stateElement;_addressStack=Array(K).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const s=R(t);null===s&&p("StateHandler: no state tree found on this root."),this._stateElement=s,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&p("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=K&&(this._hasRepeatedAddress()&&p(`[wcs/getter-cycle] Exceeded maximum address stack depth of ${K}. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),p(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of ${K} with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const s=this._addressStack[e];if(s){if(t.has(s))return!0;t.add(s)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const s=this._addressStack[e];s&&t.push(s.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&p(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,s){return Xt(t,e,s,this)}set(t,e,s,n){return It(this),function(t,e,s,n,a){if("string"==typeof e){const i=yt(e),o=bt(t,i,n,a),r=m(i.pathInfo,o);return Ct(t,r,s,n,a)}return Reflect.set(t,e,s,n)}(t,e,s,n,this)}has(t,e){return Reflect.has(t,e)}}const Zt="undefined"==typeof HTMLElement?class{}:HTMLElement;const te=new Set(["for","if","elseif","else"]);function ee(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=G(s);if(n instanceof Set?i.push(...n):void 0!==n&&i.push(n),null!==t.listIndex){const e=a.get(t.pathInfo.path);if(void 0!==e)for(const s of e)r(m(s,t.listIndex))}};M();try{if(e.createState("readonly",t=>{for(const n of s){const s=m(ht(n),null);r(s);try{kt(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)te.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=O("state",a);void 0!==o&&o.catch(H)}finally{T()}}class se extends Zt{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return F(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Vt}();_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){gt(t);const e=this.__state,s=Ut();s.set("previousState",e),zt(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),Dt(this,t,s),Lt(this,t,s),this._commandTokenNames=n,this._eventTokenNames=a,this._stateGeneration++,this.__state=t,void 0!==e&&Wt?.reset(this),this._hasUpdatedCallback=at in t,this._hasErrorCallback=it in t,U(this),Rt(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=Et(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);jt(this,t,s),this._listKeys=i,this._rebuildPathInfo(),Ot(this,t,s),Ht(this,null),this._resolveLoading?.()}attributeChangedCallback(t,s,n){this._initialized&&s!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===s?"absent":`"${s}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${e.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?W('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){p("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await a(t,e.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${e.tagNames.state}> element.`)},ut),s=await this._setStatePromise;return clearTimeout(t),s}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||p(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await n(t);p(`Unsupported src file type: ${t}`)}}catch(t){p(`Failed to initialize state: ${t}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,s]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=s}return await this._loadingPromise,null!==this._rootNode&&(V(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),p(t)}_failInitializeLoudly(t,s=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${e.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),s&&null!==this._rootNode&&null===R(this._rootNode)&&(q(this._rootNode,t),i(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{st in t&&await t[N]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{nt in t&&t[A]()})}async connectedCallback(){this._rootNode=this.getRootNode();const n=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(d(this))return void this._resolveConnectedCallback?.();this._treeless||R(this._rootNode)===this||V(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const t=o(this);if(null!==t)return void await t;const s=this.parentNode;if(s instanceof ShadowRoot&&s.host.hasAttribute(pt))try{r("dcc",`a <${e.tagNames.state}> inside a [${pt}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{r("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let n=!1;try{const t=l(this);null===t&&this.hasAttribute("bind-component")&&r("scopes",'the "bind-component" attribute'),n=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(n)return;let a=!1;try{a=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!a)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!t()||n!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!s())try{await W('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Ht(this,n),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!c(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&h(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{V(this.rootNode,null),At(this),Tt(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=>(gt(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=Gt(t,e);null===this._addressHooks&&(this._addressHooks=Mt()),Ft(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),Wt?.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 Yt(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(Et(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){ee(this,t,this._pathRegistrations.keys())}}const ne=[];function ae(t){ne.includes(t)||ne.push(t)}function ie(t=customElements){for(let e=0;e<ne.length;e++)ne[e](t);t.get(e.tagNames.state)||t.define(e.tagNames.state,se)}export{Zt as H,ae as a,ie as r};
|
|
2
2
|
//# sourceMappingURL=registerComponents.js.map
|