@wcstack/fetch 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +2 -0
- package/README.md +2 -0
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.esm.js +33 -0
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
package/dist/auto.min.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto.min.js","sources":["../src/config.ts","../src/core/operationLane.ts","../src/core/platformCapability.ts","../src/core/fetchCapabilities.ts","../src/core/FetchCore.ts","../src/autoTrigger.ts","../src/protocol/upgradeProperties.ts","../src/trustedTypes.ts","../src/components/Fetch.ts","../src/components/FetchHeader.ts","../src/components/FetchBody.ts","../src/components/InfiniteScroll.ts","../src/bootstrapFetch.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n fetch: string;\n fetchHeader: string;\n fetchBody: string;\n infiniteScroll: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-fetchtarget\",\n tagNames: {\n fetch: \"wcs-fetch\",\n fetchHeader: \"wcs-fetch-header\",\n fetchBody: \"wcs-fetch-body\",\n infiniteScroll: \"wcs-infinite-scroll\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /io-core/operation-lane.ts by scripts/sync-io-core.mjs.\n// Run `node scripts/sync-io-core.mjs` after editing the source.\n// ===========================================================================\n\n/**\n * operationLane.ts\n *\n * Phase 4 (docs/architecture-hardening/09-remediation-design.md §5, §5.1) の\n * OperationTicket / CommitGuard / terminal CAS を型付き実装した lane プリミティブ。\n * docs/async-execution-model.md §5 が既に規範化した排他モード\n * (latest / queue / exhaust / overlap) を、`AbortController` だけでは防げない\n * 「取消不能な Promise・abort と同時に完了した結果の commit」から守るための\n * 実行時ガードとして具体化する。\n *\n * 配置方針 (§5): 本ファイルは /io-core/ の単一正典であり、scripts/sync-io-core.mjs が\n * 各 IO ノードの src/core/ へ生成コピー (AUTO-GENERATED, 編集禁止) を配布する。\n * `protocol/wcBindable.ts` と同じ copy-distribution 方式で、ランタイム依存を導入せず\n * 各パッケージのバンドルへ inline される (zero-runtime-dep / 自己完結 CDN を維持)。\n * 編集はこの正典に対して行い、`node scripts/sync-io-core.mjs` で再配布する。\n *\n * 初期 PoC は fetch の `latest` policy から開始した。現在は4 policy 全てを\n * `operationLane.test.ts` が直接検証し、生成コピーを fetch / upload / share /\n * contacts / credential / eyedropper が利用する。lane 自体は promise を実行せず、\n * bookkeeping と guard の状態機械に徹する — 実際の非同期処理は Core が駆動し\n * lane に照合する。\n */\n\n/** §5: 排他モードの語彙。async-execution-model.md §5 の 4 モードに対応 (parallel は予約語・スコープ外)。 */\nexport type LanePolicy = \"latest\" | \"queue\" | \"exhaust\" | \"overlap\";\n\n/** §5: 各 operation の一回限りの終端結果。 */\nexport type TerminalOutcome = \"success\" | \"error\" | \"timeout\" | \"aborted\" | \"stale\";\n\n/** §5: 論理操作 1 件の identity。retry は同じ operationId を再利用する。 */\nexport interface OperationTicket {\n readonly operationId: number;\n /** 発行時に捕捉した I/O Core の observe / reconnect / dispose lifecycle 世代。 */\n readonly ownerGeneration: number;\n readonly laneKey: string;\n readonly policy: LanePolicy;\n /** supersede bookkeeping に使う epoch (latest policy のみ)。 */\n readonly supersedeEpoch?: number;\n}\n\n/** §5: operation の 1 回の試行。retry で attempt++ と resource signal だけ差し替える。 */\nexport interface OperationAttempt {\n readonly operationId: number;\n readonly attempt: number;\n readonly signal?: AbortSignal;\n}\n\n/** §6: DevTools 側 channel へ流す trace(fetch では既定 off・zero-cost)。 */\nexport type OperationTraceEvent =\n | { readonly type: \"io:operation-started\"; readonly operationId: number; readonly laneKey: string; readonly policy: LanePolicy }\n | { readonly type: \"io:operation-retried\"; readonly operationId: number; readonly laneKey: string; readonly attempt: number }\n | { readonly type: \"io:operation-settled\"; readonly operationId: number; readonly laneKey: string; readonly outcome: TerminalOutcome }\n | { readonly type: \"io:stale-dropped\"; readonly operationId: number; readonly laneKey: string };\n\nexport interface OperationLaneOptions {\n /** attempt ごとに AbortController を発行し signal を渡す (fetch/upload 系)。 */\n readonly withSignal?: boolean;\n /**\n * trace subscriber。undefined なら trace record を一切生成しない\n * (§10.3 hook-off zero allocation の gate)。\n */\n readonly trace?: (event: OperationTraceEvent) => void;\n}\n\n/** 内部の終端状態。absence = pending。'committing' は multi-setter commit 中の中間状態。 */\ntype TerminalStatus = \"committing\" | TerminalOutcome;\n\n/**\n * 1 レーン = 独立した排他単位。Core が 1 つ以上所有する (module singleton にしない —\n * 複数 <wcs-fetch> 間で漏れるため)。\n */\nexport class OperationLane {\n readonly laneKey: string;\n readonly policy: LanePolicy;\n\n private _ownerGeneration = 0;\n private _latestEpoch = 0;\n private _nextOperationId = 1;\n // latest / queue / exhaust の単一 active。queue は head を指す。\n private _activeOperationId: number | undefined = undefined;\n // overlap の active set (§5: 内部 bookkeeping のみ・observable 公開はしない)。\n private readonly _activeOperationIds = new Set<number>();\n // queue policy の FIFO。\n private readonly _queue: OperationTicket[] = [];\n private _inFlightCount = 0;\n // opId → 終端状態 (absence = pending)。\n private readonly _terminal = new Map<number, TerminalStatus>();\n // claimTerminal で確定した outcome (finalize が 'committing' を最終値へ移す)。\n private readonly _claimedOutcome = new Map<number, TerminalOutcome>();\n // opId → AbortController (identity は opId が保証。cross-op clobber は構造上起きない)。\n private readonly _controllers = new Map<number, AbortController>();\n // opId → attempt 数。\n private readonly _attempts = new Map<number, number>();\n private readonly _withSignal: boolean;\n private readonly _trace?: (event: OperationTraceEvent) => void;\n\n constructor(laneKey: string, policy: LanePolicy, options: OperationLaneOptions = {}) {\n this.laneKey = laneKey;\n this.policy = policy;\n this._withSignal = options.withSignal ?? false;\n this._trace = options.trace;\n }\n\n get ownerGeneration(): number {\n return this._ownerGeneration;\n }\n\n get inFlightCount(): number {\n return this._inFlightCount;\n }\n\n get latestEpoch(): number {\n return this._latestEpoch;\n }\n\n get activeOperationId(): number | undefined {\n return this._activeOperationId;\n }\n\n /**\n * 新しい要求の到着。arrival policy を適用し ticket + 最初の attempt を発行する。\n * exhaust で実行中の場合だけ null を返す (新要求を ticket 化せず拒否 = 冪等 no-op)。\n */\n begin(): { ticket: OperationTicket; attempt: OperationAttempt } | null {\n let supersedeEpoch: number | undefined;\n switch (this.policy) {\n case \"latest\": {\n // latestEpoch を進め、旧 active を abort (可能なら)。旧 ticket は settle 時に\n // eligibility 不一致で stale となる。\n supersedeEpoch = ++this._latestEpoch;\n if (this._activeOperationId !== undefined) {\n this._abortController(this._activeOperationId);\n }\n break;\n }\n case \"exhaust\": {\n // 実行中なら新要求を拒否 (呼び出し側は既存結果へ合流)。\n if (this._activeOperationId !== undefined) {\n return null;\n }\n break;\n }\n case \"queue\":\n case \"overlap\":\n break;\n }\n\n const operationId = this._nextOperationId++;\n const ticket: OperationTicket = {\n operationId,\n ownerGeneration: this._ownerGeneration,\n laneKey: this.laneKey,\n policy: this.policy,\n supersedeEpoch,\n };\n\n switch (this.policy) {\n case \"latest\":\n case \"exhaust\":\n this._activeOperationId = operationId;\n break;\n case \"queue\":\n this._queue.push(ticket);\n // 先頭だけを active にする (先行が完了するまで待つ)。\n if (this._activeOperationId === undefined) {\n this._activeOperationId = operationId;\n }\n break;\n case \"overlap\":\n this._activeOperationIds.add(operationId);\n break;\n }\n\n this._inFlightCount += 1;\n this._attempts.set(operationId, 1);\n const attempt = this._makeAttempt(operationId, 1);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:operation-started\", operationId, laneKey: this.laneKey, policy: this.policy });\n }\n return { ticket, attempt };\n }\n\n /**\n * retry: 同じ operationId に新しい attempt を作る。attempt number と resource signal\n * だけを更新する (§5)。既に終端した operation には作れない (null)。\n */\n retry(ticket: OperationTicket): OperationAttempt | null {\n if (ticket.ownerGeneration !== this._ownerGeneration) return null;\n if (this._terminal.has(ticket.operationId)) return null;\n const previous = this._attempts.get(ticket.operationId);\n if (previous === undefined) return null;\n const attemptNo = previous + 1;\n this._attempts.set(ticket.operationId, attemptNo);\n // 前の attempt の signal は破棄し、新しい controller を張る。\n this._releaseController(ticket.operationId);\n const attempt = this._makeAttempt(ticket.operationId, attemptNo);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:operation-retried\", operationId: ticket.operationId, laneKey: this.laneKey, attempt: attemptNo });\n }\n return attempt;\n }\n\n /**\n * CommitGuard (§5.1)。外部可視の setter / event dispatch の直前に呼ぶ。\n * (1) owner lifecycle generation 一致 (2) terminal settle 前 (3) policy eligibility。\n */\n canCommit(ticket: OperationTicket): boolean {\n if (ticket.ownerGeneration !== this._ownerGeneration) return false;\n const status = this._terminal.get(ticket.operationId);\n // absence = pending / 'committing' = multi-setter commit 中。どちらも settle 前。\n if (status !== undefined && status !== \"committing\") return false;\n return this._isEligible(ticket);\n }\n\n /**\n * terminal CAS (§5.1): pending → committing を claim する。勝者だけが true。\n * eligibility / owner gen を満たさない場合も false。claim 後は commit 中となり、\n * canCommit は各 setter の直前で再検査する (setter が同期 supersede しても取りこぼさない)。\n */\n claimTerminal(ticket: OperationTicket, outcome: TerminalOutcome): boolean {\n if (ticket.ownerGeneration !== this._ownerGeneration) return false;\n if (this._terminal.has(ticket.operationId)) return false; // 既に committing / 終端\n if (!this._isEligible(ticket)) return false;\n this._terminal.set(ticket.operationId, \"committing\");\n this._claimedOutcome.set(ticket.operationId, outcome);\n return true;\n }\n\n /** claim 済み outcome (timer が claim → catch が読む等)。未 claim なら undefined。 */\n claimedOutcome(ticket: OperationTicket): TerminalOutcome | undefined {\n return this._claimedOutcome.get(ticket.operationId);\n }\n\n /**\n * operation の後始末。claim 済みなら outcome を確定し、未 claim なら stale-drop。\n * controller を解放し in-flight を減らし、policy の bookkeeping を進める。冪等。\n */\n finalize(ticket: OperationTicket): void {\n const operationId = ticket.operationId;\n const status = this._terminal.get(operationId);\n if (status !== undefined && status !== \"committing\") {\n // 既に確定済み。冪等に return。\n return;\n }\n let outcome: TerminalOutcome;\n if (status === \"committing\") {\n outcome = this._claimedOutcome.get(operationId) ?? \"stale\";\n } else {\n // 一度も claim されなかった (supersede / dispose で eligibility を失った)。\n outcome = \"stale\";\n }\n this._terminal.set(operationId, outcome);\n this._claimedOutcome.delete(operationId);\n this._releaseController(operationId);\n this._attempts.delete(operationId);\n if (this._inFlightCount > 0) this._inFlightCount -= 1;\n this._advanceBookkeeping(operationId);\n if (this._trace !== undefined) {\n if (outcome === \"stale\") {\n this._trace({ type: \"io:stale-dropped\", operationId, laneKey: this.laneKey });\n } else {\n this._trace({ type: \"io:operation-settled\", operationId, laneKey: this.laneKey, outcome });\n }\n }\n }\n\n /** operation の signal (resource 解放用)。withSignal でなければ undefined。 */\n signalOf(ticket: OperationTicket): AbortSignal | undefined {\n return this._controllers.get(ticket.operationId)?.signal;\n }\n\n /** best-effort な resource 中断。正しさは owner gen / eligibility / terminal CAS が担う。 */\n abort(ticket: OperationTicket): void {\n this._abortController(ticket.operationId);\n }\n\n /**\n * 現在 active な operation を中断する (利用者による明示キャンセル)。epoch は進めない —\n * 中断された operation は eligibility を保ったまま 'aborted' を claim できる\n * (loading をクリアしつつ in-flight 状態を残す)。\n */\n abortActive(): void {\n if (this._activeOperationId !== undefined) {\n this._abortController(this._activeOperationId);\n }\n for (const operationId of this._activeOperationIds) {\n this._abortController(operationId);\n }\n }\n\n /**\n * dispose (§4.1 world generation)。owner generation を bump して全 ticket を無効化し、\n * 生きている controller を全て abort する。dispose 後に settle した operation は\n * owner gen 不一致で外部 commit しない。retention gate (§10.3) のため live な\n * 全 operation を即時に stale として finalize し、controller / attempt を解放する。\n */\n disposeOwner(): void {\n this._ownerGeneration += 1;\n for (const operationId of Array.from(this._controllers.keys())) {\n this._abortController(operationId);\n // finalize は dispose 後 (terminal='stale') に early-return するため controller を\n // 解放しない。retention gate (§10.3) を満たすためここで明示的に解放する。\n this._releaseController(operationId);\n }\n for (const operationId of Array.from(this._attempts.keys())) {\n if (!this._terminal.has(operationId)) {\n this._terminal.set(operationId, \"stale\");\n }\n this._claimedOutcome.delete(operationId);\n this._attempts.delete(operationId);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:stale-dropped\", operationId, laneKey: this.laneKey });\n }\n }\n this._activeOperationId = undefined;\n this._activeOperationIds.clear();\n this._queue.length = 0;\n this._inFlightCount = 0;\n }\n\n // --- internal ---\n\n private _makeAttempt(operationId: number, attemptNo: number): OperationAttempt {\n let signal: AbortSignal | undefined;\n // AbortController 不在環境(古い runtime / 一部 SSR)では degraded: signal なしで進む。\n // 正しさは owner generation / eligibility / terminal CAS が担うため、native 中断が\n // 無くても supersede / dispose は機能する(best-effort resource 中断が省かれるだけ)。\n if (this._withSignal && typeof AbortController === \"function\") {\n const controller = new AbortController();\n this._controllers.set(operationId, controller);\n signal = controller.signal;\n }\n return { operationId, attempt: attemptNo, signal };\n }\n\n private _isEligible(ticket: OperationTicket): boolean {\n switch (this.policy) {\n case \"latest\":\n return ticket.supersedeEpoch === this._latestEpoch;\n case \"queue\":\n case \"exhaust\":\n return this._activeOperationId === ticket.operationId;\n case \"overlap\":\n return this._activeOperationIds.has(ticket.operationId);\n }\n }\n\n private _advanceBookkeeping(operationId: number): void {\n switch (this.policy) {\n case \"latest\":\n case \"exhaust\":\n if (this._activeOperationId === operationId) {\n this._activeOperationId = undefined;\n }\n break;\n case \"queue\": {\n // 完了した ticket を FIFO から取り除き、次の先頭を active にする。filter で\n // 「先頭 / 非先頭 / 不在」を一様に扱う (finalize は冪等ガードを通った op のみ到達)。\n const remaining = this._queue.filter((t) => t.operationId !== operationId);\n this._queue.length = 0;\n this._queue.push(...remaining);\n this._activeOperationId = this._queue.length > 0 ? this._queue[0].operationId : undefined;\n break;\n }\n case \"overlap\":\n this._activeOperationIds.delete(operationId);\n break;\n }\n }\n\n private _abortController(operationId: number): void {\n const controller = this._controllers.get(operationId);\n if (controller !== undefined && !controller.signal.aborted) {\n controller.abort();\n }\n }\n\n private _releaseController(operationId: number): void {\n this._controllers.delete(operationId);\n }\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /io-core/platform-capability.ts by scripts/sync-io-core.mjs.\n// Run `node scripts/sync-io-core.mjs` after editing the source.\n// ===========================================================================\n\n/**\n * platform-capability.ts\n *\n * Phase 6(docs/architecture-hardening/09-remediation-design.md §7.2 /\n * 07-browser-capability-variance.md)の browser capability 判定と error taxonomy の\n * 汎用プリミティブ。node 固有の capability registry / error code は各パッケージが\n * 別ファイルで宣言し、この汎用層(型 + assess 機構)を import する。\n *\n * 原則:\n * - feature detection は境界(利用直前)で行う。module 評価時に browser global を\n * 参照しない(SSR / worker で import が失敗しない)。\n * - capability ID(`web.fetch` 等)は文字列を global property path として eval せず、\n * registry が ID ごとに副作用のない presence probe を対応付ける。\n * - availability / permission / readiness / activity / operation error を 1 つの\n * `ready / unsupported / error` enum に畳まない。required 欠如は開始しない、\n * optional 欠如は宣言済み fallback で readiness を `degraded` にする。\n *\n * 配置: 本ファイルは /io-core/ の単一正典であり、scripts/sync-io-core.mjs が\n * 各 IO ノードの src/core/ へ生成コピー (AUTO-GENERATED, 編集禁止) を配布する。\n * `protocol/wcBindable.ts` と同じ copy-distribution 方式で、ランタイム依存を導入せず\n * 各パッケージのバンドルへ inline される (zero-runtime-dep / 自己完結 CDN を維持)。\n * 編集はこの正典に対して行い、`node scripts/sync-io-core.mjs` で再配布する。\n *\n * pure(module 評価時に browser global 非参照)。\n */\n\nexport type Availability = \"available\" | \"missing\" | \"unknown\";\nexport type PermissionState = \"granted\" | \"denied\" | \"prompt\" | \"not-applicable\" | \"unknown\";\nexport type Readiness = \"idle\" | \"ready\" | \"degraded\";\nexport type Activity = \"inactive\" | \"active\";\nexport type PreconditionState = \"satisfied\" | \"required\" | \"not-applicable\";\n\n/** operation error の phase(taxonomy)。 */\nexport type WcsIoErrorPhase = \"probe\" | \"start\" | \"execute\" | \"decode\" | \"commit\" | \"dispose\";\n\n/** serializable な error info(non-cloneable な cause とは分離。DevTools / remote へは info のみ)。 */\nexport interface WcsIoErrorInfo {\n readonly code: string;\n readonly phase: WcsIoErrorPhase;\n readonly recoverable: boolean;\n readonly capabilityId?: string;\n readonly message: string;\n}\n\nexport interface PlatformAssessment {\n readonly availability: ReadonlyMap<string, Availability>;\n readonly permission: PermissionState;\n readonly readiness: Readiness;\n readonly activity: Activity;\n readonly preconditions: {\n readonly secureContext: PreconditionState;\n readonly userActivation: PreconditionState;\n };\n readonly epoch: number;\n readonly lastError?: WcsIoErrorInfo;\n}\n\n/** capability 1 件の仕様。probe は副作用なく presence を返す(利用直前に呼ぶ)。 */\nexport interface CapabilitySpec {\n readonly probe: () => boolean;\n readonly requiresSecureContext?: boolean;\n readonly requiresUserActivation?: boolean;\n /** browser compatibility dataset のキー(任意・診断用)。 */\n readonly compatKey?: string;\n}\n\nexport type CapabilityRegistry = ReadonlyMap<string, CapabilitySpec>;\n\nexport interface AssessOptions {\n readonly required: readonly string[];\n readonly optional?: readonly string[];\n readonly permission?: PermissionState;\n readonly activity?: Activity;\n readonly epoch?: number;\n readonly lastError?: WcsIoErrorInfo;\n}\n\nfunction isSecureContext(): boolean {\n return (globalThis as { isSecureContext?: unknown }).isSecureContext === true;\n}\n\n/**\n * capability を利用直前に評価して PlatformAssessment を作る。\n * required が 1 つでも欠ければ readiness は \"idle\"(開始不可)、\n * required 揃い + optional 欠けは \"degraded\"、全揃いは \"ready\"。\n */\nexport function assessCapabilities(registry: CapabilityRegistry, options: AssessOptions): PlatformAssessment {\n const availability = new Map<string, Availability>();\n const evaluate = (id: string): Availability => {\n const spec = registry.get(id);\n if (spec === undefined) return \"unknown\";\n return spec.probe() ? \"available\" : \"missing\";\n };\n\n let requiredAllAvailable = true;\n for (const id of options.required) {\n const a = evaluate(id);\n availability.set(id, a);\n if (a !== \"available\") requiredAllAvailable = false;\n }\n let optionalAllAvailable = true;\n for (const id of options.optional ?? []) {\n const a = evaluate(id);\n availability.set(id, a);\n if (a !== \"available\") optionalAllAvailable = false;\n }\n\n const readiness: Readiness = !requiredAllAvailable ? \"idle\" : (optionalAllAvailable ? \"ready\" : \"degraded\");\n\n // preconditions: 対象 capability のいずれかが要求する場合だけ評価する。\n const allIds = [...options.required, ...(options.optional ?? [])];\n const needsSecure = allIds.some((id) => registry.get(id)?.requiresSecureContext === true);\n const needsActivation = allIds.some((id) => registry.get(id)?.requiresUserActivation === true);\n const secureContext: PreconditionState = needsSecure ? (isSecureContext() ? \"satisfied\" : \"required\") : \"not-applicable\";\n const userActivation: PreconditionState = needsActivation ? \"required\" : \"not-applicable\";\n\n return {\n availability,\n permission: options.permission ?? \"not-applicable\",\n readiness,\n activity: options.activity ?? \"inactive\",\n preconditions: { secureContext, userActivation },\n epoch: options.epoch ?? 0,\n lastError: options.lastError,\n };\n}\n\n/** availability から「required がすべて available か」を判定するヘルパ(supported の最低条件)。 */\nexport function requiredCapabilitiesAvailable(assessment: PlatformAssessment, required: readonly string[]): boolean {\n return required.every((id) => assessment.availability.get(id) === \"available\");\n}\n","/**\n * fetchCapabilities.ts\n *\n * fetch node 固有の capability registry と error code。汎用の assess 機構・型は\n * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から\n * import する。node 固有の宣言はこのハンドライトファイルに置き、生成コピーとは分離する。\n */\n\nimport { CapabilityRegistry, CapabilitySpec } from \"./platformCapability.js\";\n\n/** 安定した fetch error code(taxonomy)。値は公開キーとして固定。 */\nexport const WCS_FETCH_ERROR_CODE = {\n CapabilityMissing: \"capability-missing\",\n InvalidArgument: \"invalid-argument\",\n Network: \"network\",\n HttpError: \"http-error\",\n Timeout: \"timeout\",\n Aborted: \"aborted\",\n} as const;\n\n/** fetch node の capability registry。文字列 ID を eval せず明示 probe を持つ。 */\nexport const FETCH_CAPABILITIES: CapabilityRegistry = new Map<string, CapabilitySpec>([\n [\"web.fetch\", { probe: () => typeof (globalThis as { fetch?: unknown }).fetch === \"function\", compatKey: \"api.fetch\" }],\n [\"web.abort-controller\", { probe: () => typeof (globalThis as { AbortController?: unknown }).AbortController === \"function\", compatKey: \"api.AbortController\" }],\n]);\n","import { IWcBindable } from \"../types.js\";\nimport { OperationLane, OperationTicket } from \"./operationLane.js\";\nimport {\n PlatformAssessment,\n WcsIoErrorInfo,\n WcsIoErrorPhase,\n assessCapabilities,\n requiredCapabilitiesAvailable,\n} from \"./platformCapability.js\";\nimport { FETCH_CAPABILITIES, WCS_FETCH_ERROR_CODE } from \"./fetchCapabilities.js\";\n\nexport type FetchResponseType = \"auto\" | \"json\" | \"text\" | \"blob\" | \"arrayBuffer\";\n\nexport interface FetchRequestOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit | null;\n contentType?: string | null;\n forceText?: boolean;\n // How to read the response body. \"auto\" (default) sniffs Content-Type (JSON or\n // text). \"blob\"/\"arrayBuffer\" enable binary downloads; \"blob\" additionally\n // publishes a managed `objectURL`. `forceText` (HTML-replace mode) takes\n // priority over this.\n responseType?: FetchResponseType;\n // Request timeout in ms. When elapsed, the request lane claims a `timeout`\n // terminal, commits a `{ name: \"TimeoutError\" }` error envelope (guarded), then\n // aborts the native request (async-execution-model.md §7 / 09 §5.1). Absent or\n // <= 0 → no timeout (unchanged behaviour, the default).\n timeout?: number;\n}\n\nexport class FetchCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"value\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.value },\n { name: \"loading\", event: \"wcs-fetch:loading-changed\", semantics: \"state\" },\n { name: \"error\", event: \"wcs-fetch:error\", semantics: \"state\" },\n { name: \"status\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.status },\n // Managed object URL for a `responseType: \"blob\"` response (null otherwise).\n // The Core revokes the previous URL on each new response and on dispose, so\n // a consumer can bind it straight into <img src> without lifecycle glue.\n { name: \"objectURL\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.objectURL },\n // Serializable failure taxonomy (stable code / phase / recoverable), or null.\n // Additive bindable output — the existing `error` property/event are unchanged.\n // Fires on its own `wcs-fetch:error-info-changed` event; no getter, so the\n // bound value is the event detail (mirrors `error` / `loading`).\n { name: \"errorInfo\", event: \"wcs-fetch:error-info-changed\", semantics: \"state\" },\n ],\n inputs: [\n { name: \"url\" },\n { name: \"method\" },\n ],\n commands: [\n { name: \"fetch\", async: true },\n { name: \"abort\" },\n ],\n };\n\n private _target: EventTarget;\n private _value: any = null;\n private _loading: boolean = false;\n private _error: any = null;\n private _status: number = 0;\n private _objectURL: string | null = null;\n private _promise: Promise<any> = Promise.resolve(null);\n // Phase 4 (09-remediation-design.md §5): the request lane. `latest` policy —\n // a new fetch supersedes the in-flight one (switchMap). The lane owns the\n // per-operation AbortController, the owner generation (dispose lifecycle) and\n // the terminal CAS / CommitGuard that decide which completion may write state.\n // This replaces the ad-hoc `_gen` counter + single `_abortController`: a\n // superseded operation now fails the CommitGuard's epoch check instead of\n // relying on a coarse generation recheck, closing the \"completion racing an\n // abort commits stale state\" gap during body reads.\n private _lane = new OperationLane(\"fetch\", \"latest\", { withSignal: true });\n // SSR (§3.8): no asynchronous probe to await, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n // Phase 6 (§7.2): error taxonomy. The existing `error` property/event shape is\n // unchanged; `errorInfo` projects the serializable WcsIoErrorInfo as an additive\n // wc-bindable output (event `wcs-fetch:error-info-changed`) so DevTools / adopters\n // can classify failures without a breaking change.\n private _errorInfo: WcsIoErrorInfo | null = null;\n\n // Capability IDs (probed at call time, never at module eval / never eval'd as a\n // global path). `web.fetch` required; `web.abort-controller` optional (its\n // absence degrades to a fetch without an abort signal).\n private static readonly REQUIRED_CAPABILITIES = [\"web.fetch\"] as const;\n private static readonly OPTIONAL_CAPABILITIES = [\"web.abort-controller\"] as const;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). Fetch is command-driven with no subscription to\n // establish, so observe() is an idempotent no-op that resolves once ready;\n // dispose() invalidates any in-flight request and aborts it.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n // world generation bump (§4.1): invalidates + aborts every in-flight request.\n this._lane.disposeOwner();\n // Release any outstanding blob object URL on teardown (the other revoke point\n // is _setResponse, which drops the previous URL when a new response arrives).\n if (this._objectURL !== null) {\n this._revokeObjectURL(this._objectURL);\n this._objectURL = null;\n }\n }\n\n get value(): any {\n return this._value;\n }\n\n get loading(): boolean {\n return this._loading;\n }\n\n get error(): any {\n return this._error;\n }\n\n get status(): number {\n return this._status;\n }\n\n get objectURL(): string | null {\n return this._objectURL;\n }\n\n get promise(): Promise<any> {\n return this._promise;\n }\n\n /**\n * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /\n * `recoverable` / `capabilityId`), or null. Exposed as an additive wc-bindable\n * property (event `wcs-fetch:error-info-changed`); the existing `error`\n * property/event are unchanged.\n */\n get errorInfo(): WcsIoErrorInfo | null {\n return this._errorInfo;\n }\n\n /**\n * Whether the required platform capabilities (`web.fetch`) are available right\n * now — the minimal \"supported\" signal, decided by call-time feature detection,\n * not User-Agent. Additive.\n */\n get supported(): boolean {\n return requiredCapabilitiesAvailable(this.platformAssessment, FetchCore.REQUIRED_CAPABILITIES);\n }\n\n /**\n * Full platform assessment (availability / readiness / preconditions), probed\n * at call time. `readiness` is `degraded` when only the optional\n * `web.abort-controller` is missing. Dev / sidecar view.\n */\n get platformAssessment(): PlatformAssessment {\n return assessCapabilities(FETCH_CAPABILITIES, {\n required: FetchCore.REQUIRED_CAPABILITIES,\n optional: FetchCore.OPTIONAL_CAPABILITIES,\n activity: this._loading ? \"active\" : \"inactive\",\n lastError: this._errorInfo ?? undefined,\n });\n }\n\n private _setErrorInfo(code: string, phase: WcsIoErrorPhase, recoverable: boolean, message: string, capabilityId?: string): void {\n this._commitErrorInfo({ code, phase, recoverable, message, ...(capabilityId === undefined ? {} : { capabilityId }) });\n }\n\n // Single mutation point for `errorInfo`, mirroring `_setError`'s same-value guard\n // and event dispatch so the additive `errorInfo` wc-bindable property stays in sync\n // with `error`. Each failure builds a fresh object (reference guard passes); the\n // clear path passes null (suppresses a redundant null→null per successful fetch).\n private _commitErrorInfo(info: WcsIoErrorInfo | null): void {\n if (this._errorInfo === info) return;\n this._errorInfo = info;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:error-info-changed\", {\n detail: info,\n bubbles: true,\n }));\n }\n\n private _setLoading(loading: boolean): void {\n this._loading = loading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:loading-changed\", {\n detail: loading,\n bubbles: true,\n }));\n }\n\n private _setError(error: any): void {\n // Same-value guard (async-io-node-guidelines.md §3.3). `error` is state-ish,\n // so suppressing redundant null→null dispatches (every fetch start clears a\n // usually-already-null error) avoids a spurious wcs-fetch:error per successful\n // request. Reference identity is sufficient: each failure builds a fresh\n // object, and the clear path always passes null.\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n private _setResponse(value: any, status: number, objectURL: string | null = null): void {\n // Revoke the previous blob object URL before replacing it. Any new response\n // (success, HTTP error, or network error all funnel through here) supersedes\n // the prior one, so the old URL is no longer needed; this plus dispose()\n // revocation keeps blob downloads leak-free.\n if (this._objectURL !== null) {\n this._revokeObjectURL(this._objectURL);\n }\n this._objectURL = objectURL;\n this._value = value;\n this._status = status;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:response\", {\n detail: { value, status, objectURL },\n bubbles: true,\n }));\n }\n\n // Object URL lifecycle for responseType: \"blob\". The Core owns the blob's\n // object URL (mirrors RecorderCore) so a consumer can bind `objectURL` straight\n // into <img src>/<a href> without managing createObjectURL/revokeObjectURL. Both\n // helpers tolerate environments without URL.createObjectURL (SSR / headless).\n private _createObjectURL(blob: Blob): string | null {\n if (typeof URL !== \"undefined\" && typeof URL.createObjectURL === \"function\") {\n return URL.createObjectURL(blob);\n }\n return null;\n }\n\n private _revokeObjectURL(url: string): void {\n if (typeof URL !== \"undefined\" && typeof URL.revokeObjectURL === \"function\") {\n URL.revokeObjectURL(url);\n }\n }\n\n abort(): void {\n // Explicit user cancel: abort the active operation WITHOUT advancing the lane\n // epoch, so the aborted operation stays eligible and its AbortError branch may\n // commit loading=false (leaving the in-flight value/status). A superseding\n // fetch() instead advances the epoch (via the lane's begin()), which makes the\n // predecessor ineligible so its abort commits nothing (loading does not flicker).\n this._lane.abortActive();\n }\n\n // Run one guarded commit step (§5.1). The CommitGuard is re-checked before every\n // setter because a setter that synchronously dispatches an event can supersede\n // the same lane; an invalidation between setters stops the remaining commits\n // without rolling back what already fired.\n private _commitStep(ticket: OperationTicket, step: () => void): void {\n if (this._lane.canCommit(ticket)) {\n step();\n }\n }\n\n async fetch(url: string, options: FetchRequestOptions = {}): Promise<any> {\n // never-throw (§3.6): 引数バリデーション失敗は例外ではなく error プロパティに\n // 流し、サニタイズ値(null)を返す。command-token 経路からの呼び出しが unhandled\n // rejection にならず、「fetch() は全終了ケースで resolve」契約とも整合する。\n if (!url) {\n // Existing `error` shape is unchanged (§7.2 / 07 §互換性); the taxonomy is\n // projected only through the additive `errorInfo`.\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.InvalidArgument, \"start\", false, \"url attribute is required.\");\n this._setError({ message: \"url attribute is required.\" });\n return null;\n }\n\n // Phase 6 (§7.2): probe required capabilities just before starting. If the\n // `web.fetch` API is absent (SSR / headless / very old runtime), do NOT start\n // the operation — surface a stable `capability-missing` taxonomy without\n // attempting the call (and without the generic network-error path).\n const assessment = this.platformAssessment;\n if (!requiredCapabilitiesAvailable(assessment, FetchCore.REQUIRED_CAPABILITIES)) {\n const missing = FetchCore.REQUIRED_CAPABILITIES.find((id) => assessment.availability.get(id) !== \"available\");\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.CapabilityMissing, \"start\", false, `Required capability \"${missing}\" is unavailable.`, missing);\n this._setError({ message: `Required capability \"${missing}\" is unavailable.` });\n return null;\n }\n\n const p = this._doFetch(url, options);\n this._promise = p;\n return p;\n }\n\n private async _doFetch(url: string, options: FetchRequestOptions): Promise<any> {\n // Issue a lane ticket. For the `latest` policy this advances the epoch and\n // aborts the previous in-flight request (supersede), returning a ticket +\n // attempt whose `signal` is the lane-owned AbortController for this operation.\n // `attempt.signal` is undefined when `web.abort-controller` is missing\n // (degraded): the request runs without a native abort signal.\n const started = this._lane.begin();\n // `latest` begin never returns null (exhaust is the only rejecting policy).\n const { ticket, attempt } = started!;\n const signal = attempt.signal;\n\n this._commitStep(ticket, () => this._setLoading(true));\n this._commitStep(ticket, () => { this._commitErrorInfo(null); this._setError(null); });\n\n const {\n method = \"GET\",\n body = null,\n contentType = null,\n forceText = false,\n responseType = \"auto\",\n timeout = 0,\n } = options;\n\n // Timeout terminal (§5.1 / §7): a timer claims the `timeout` outcome via the\n // same terminal CAS as success/error, commits a guarded TimeoutError, THEN\n // aborts the native request and releases the lane — never \"invalidate first\".\n // A completion that arrives after the timer loses the CAS and writes nothing.\n let timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n if (timeout > 0) {\n timeoutTimer = setTimeout(() => {\n if (!this._lane.claimTerminal(ticket, \"timeout\")) return;\n const message = `Request timed out after ${timeout}ms.`;\n this._commitStep(ticket, () => {\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.Timeout, \"execute\", true, message);\n this._setError({ name: \"TimeoutError\", message });\n });\n this._commitStep(ticket, () => this._setResponse(null, 0));\n this._commitStep(ticket, () => this._setLoading(false));\n this._lane.abort(ticket);\n this._lane.finalize(ticket);\n }, timeout);\n }\n\n // Copy the caller's headers so the contentType injection below never mutates\n // the object passed in by a headless consumer (the Shell already builds a\n // fresh object, but direct FetchCore users may reuse theirs).\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n\n try {\n if (contentType && !headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = contentType;\n }\n\n const requestInit: RequestInit = {\n method,\n headers,\n signal,\n };\n\n if (method !== \"GET\" && method !== \"HEAD\" && body !== null) {\n requestInit.body = body;\n }\n\n const response = await globalThis.fetch(url, requestInit);\n\n // Read the body first, then atomically claim the terminal at the commit\n // point. Claiming AFTER the body read closes the stale-write race: a fetch\n // that was superseded (or timed out) during the body read fails the\n // CommitGuard's epoch/CAS check and writes nothing, even if the body still\n // resolved. HEAD carries no body by spec.\n let value: any = null;\n if (method === \"HEAD\") {\n // HEAD responses carry no body — reading it would throw a parse error.\n } else if (!response.ok) {\n // HTTP error: read the body text for the error envelope. Handled below.\n } else if (forceText) {\n // HTML-replace mode (the Shell sets forceText when `target` is present)\n // always reads text and takes priority over responseType.\n value = await response.text();\n } else if (responseType === \"blob\") {\n // Only buffer the Blob here; the managed object URL is created AFTER the\n // terminal claim wins (below). Creating it before the claim would leak a\n // blob: URL when this operation loses the claim (supersede / timeout /\n // dispose during the body read) — it would never reach _setResponse and\n // never be revoked.\n value = await response.blob();\n } else if (responseType === \"arrayBuffer\") {\n value = await response.arrayBuffer();\n } else if (responseType === \"text\") {\n value = await response.text();\n } else if (responseType === \"json\") {\n value = await response.json();\n } else {\n // \"auto\" (default): sniff Content-Type — JSON when it says so, else text.\n const responseContentType = response.headers.get(\"Content-Type\") || \"\";\n if (responseContentType.includes(\"application/json\")) {\n value = await response.json();\n } else {\n value = await response.text();\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const error = { status: response.status, statusText: response.statusText, body: errorBody };\n if (!this._lane.claimTerminal(ticket, \"error\")) {\n return null;\n }\n this._commitStep(ticket, () => {\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.HttpError, \"execute\", true, `HTTP ${response.status} ${response.statusText}`);\n this._setError(error);\n });\n // Notify `status` observers on HTTP errors too. The `status` property is\n // surfaced via the `wcs-fetch:response` event (getter reads detail.status),\n // so without dispatching it here a bind() subscriber would never see the\n // error status (404, 500, ...). `value` is reset to null on error.\n this._commitStep(ticket, () => this._setResponse(null, response.status));\n this._commitStep(ticket, () => this._setLoading(false));\n return null;\n }\n\n if (!this._lane.claimTerminal(ticket, \"success\")) {\n return null;\n }\n // Create the blob object URL only now that this operation owns the terminal,\n // so a dropped operation never allocates one (leak-free). HEAD/non-blob keep\n // value non-Blob → objectURL stays null.\n const objectURL = value instanceof Blob ? this._createObjectURL(value) : null;\n this._commitStep(ticket, () => this._setResponse(value, response.status, objectURL));\n this._commitStep(ticket, () => this._setLoading(false));\n return this._value;\n } catch (e: any) {\n if (e && e.name === \"AbortError\") {\n // AbortError with a still-eligible ticket is an explicit user abort() of\n // the current request: claim the `aborted` terminal and clear loading,\n // leaving the in-flight value/status untouched. A superseding fetch or\n // dispose() advanced the epoch / owner generation, so their predecessors\n // fail the claim (return without writing = stale-drop). A timeout already\n // claimed the terminal in its timer, so this branch also no-ops there.\n if (this._lane.claimTerminal(ticket, \"aborted\")) {\n this._commitStep(ticket, () => this._setLoading(false));\n }\n return null;\n }\n // Network error. A superseded/disposed request fails the claim and drops.\n if (!this._lane.claimTerminal(ticket, \"error\")) {\n return null;\n }\n this._commitStep(ticket, () => {\n const message = String(e?.message ?? \"Network request failed.\");\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.Network, \"execute\", true, message);\n // Coalesce a falsy rejection (Promise.reject(null)/throw null) to a non-null\n // envelope so the `error` same-value guard (cleared to null at start) cannot\n // suppress a genuine terminal error — keeping `error`/`wcs-fetch:error` in sync\n // with `errorInfo`. Truthy errors (real TypeErrors) pass through unchanged.\n this._setError(e ?? { message });\n });\n // Reset value/status on network errors too, mirroring the HTTP-error path.\n // Without this, a prior successful request's value/status would linger while\n // `error` is non-null. status=0 is the web-platform convention for \"no HTTP\n // response\" (matches XMLHttpRequest.status on network failure).\n this._commitStep(ticket, () => this._setResponse(null, 0));\n this._commitStep(ticket, () => this._setLoading(false));\n return null;\n } finally {\n if (timeoutTimer !== null) {\n clearTimeout(timeoutTimer);\n }\n // Release the operation (identity-safe: keyed by operationId, so a\n // late-settling superseded request never disarms the successor). Idempotent\n // with the timeout timer's own finalize().\n this._lane.finalize(ticket);\n }\n }\n}\n","import { config } from \"./config.js\";\nimport type { Fetch } from \"./components/Fetch.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const fetchId = triggerElement.getAttribute(config.triggerAttribute);\n if (!fetchId) return;\n\n // Resolve the registered constructor at call time instead of importing Fetch\n // as a value. The value import created a components/Fetch.ts ⇄ autoTrigger.ts\n // cycle (Fetch.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-fetch> class matches — without the import cycle.\n const FetchCtor = customElements.get(config.tagNames.fetch);\n const el = document.getElementById(fetchId);\n if (!FetchCtor || !(el instanceof FetchCtor)) return;\n const fetchElement = el as Fetch;\n\n // Skip when the target has no url. fetch() is fire-and-forget here (its returned\n // promise is intentionally not awaited), and FetchCore.fetch() rejects synchronously\n // on an empty url. Without this guard that rejection would surface as an unhandled\n // promise rejection. Treat a url-less target as \"nothing to do\", consistent with the\n // other early returns above.\n if (!fetchElement.url) return;\n\n // Suppress the element's default action so a fetch can fire without navigating.\n // Intentional: do not attach data-fetchtarget to an element whose default action\n // you also want (real <a href> link, form-submit button) — it will be cancelled.\n // See README \"Optional DOM Triggering\".\n event.preventDefault();\n fetchElement.fetch();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/upgrade-properties.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// custom element の property upgrade — `static wcBindable.inputs` に宣言した入力のうち、\n// 要素が upgrade される前に代入された own データプロパティを取り込み直す。\n//\n// なぜ必要か:\n// 未定義タグの要素は素の HTMLElement なので、`el.url = \"...\"` は own データプロパティを作る。\n// upgrade 後にクラスの accessor が prototype へ入っても own プロパティが優先されるため、\n// setter は二度と呼ばれず、値は要素へ届かないまま消える(エラーも警告も出ない)。\n// 常にプロパティ代入を行う framework(Angular の `[prop]`、Lit の `.prop=`、\n// Solid の `prop:`、Vue の `.prop` 修飾子)× 遅延定義(autoloader / CDN / code-split)で\n// 常態的に起きる。docs/architecture-hardening/13-framework-adapter-binding-constraints.md §1.2。\n//\n// 安全側の判定:\n// own プロパティがあっても、prototype チェーンに accessor が無ければ「シャドウ」ではなく\n// その own プロパティ自体が正規の格納先なので触らない(public class field を壊さない)。\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/upgrade-properties.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/upgradeProperties.ts). Those copies are generated — do not edit them.\nimport { IWcBindable } from \"./wcBindable.js\";\n\nfunction hasAccessorOnPrototype(target: object, name: string): boolean {\n let proto = Object.getPrototypeOf(target);\n while (proto !== null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name);\n if (descriptor !== undefined) {\n return typeof descriptor.get === \"function\" || typeof descriptor.set === \"function\";\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n}\n\n/**\n * `connectedCallback` の先頭で呼ぶ。宣言済み input のうち upgrade 前の代入で\n * accessor をシャドウしている own プロパティを、delete → 再代入で setter に通し直す。\n *\n * - 冪等: 再代入は accessor を通るので own プロパティは残らず、2 回目以降は no-op。\n * - 宣言に `inputs` が無い要素、`wcBindable` を持たない要素では何もしない。\n * - 値の意味は変えない。今まで捨てられていた代入が届くようになる一方向の変化。\n */\nexport function upgradeProperties(element: object): void {\n const declaration = (element as { constructor?: { wcBindable?: IWcBindable } }).constructor?.wcBindable;\n const inputs = declaration?.inputs;\n if (inputs === undefined) return;\n for (const input of inputs) {\n const name = input.name;\n if (!Object.prototype.hasOwnProperty.call(element, name)) continue;\n if (!hasAccessorOnPrototype(element, name)) continue;\n const record = element as Record<string, unknown>;\n const value = record[name];\n delete record[name];\n record[name] = value;\n }\n}\n","/**\n * Trusted Types (`require-trusted-types-for 'script'`) 対応。正本は docs/csp.md §7。\n *\n * `<wcs-fetch target=\"...\">` の HTML 置換モードが innerHTML に流すのは **レスポンス**\n * = TT がまさに止めたい値そのもの。ここに identity policy を噛ませて通すのは\n * 「TT 対応」ではなく「TT の無効化」なので、fetch は自前の policy を作らない。\n * Angular が DomSanitizer を必須にしているのと同じ立て付けで、利用側が sanitizer を\n * 持つ policy を注入したときだけ通す。\n *\n * 注入口は全 @wcstack パッケージ共通のグローバルスロット。buildless(CDN 一発)でも\n * inline script 1 本で差し込める:\n *\n * ```js\n * globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\n * trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\n * ```\n *\n * policy があるときは TT 非対応ブラウザでも通す。sanitizer が Chromium でだけ効いて\n * Firefox では素通し、という差が出るほうが危ないため。\n */\n\nexport interface IWcsTrustedTypesPolicy {\n createHTML?(input: string): unknown;\n createScriptURL?(input: string): unknown;\n}\n\n/** 利用側が policy を差し込むグローバルスロット(全 @wcstack パッケージ共通)。 */\nexport const TRUSTED_TYPES_POLICY_SLOT = Symbol.for(\"wcstack.trustedTypes.policy\");\n\ntype SymbolSlotHolder = { [key: symbol]: unknown };\n\n/** 利用側が注入した policy。fetch は identity policy にフォールバックしない。 */\nexport function getTrustedTypesPolicy(): IWcsTrustedTypesPolicy | null {\n const value = (globalThis as SymbolSlotHolder)[TRUSTED_TYPES_POLICY_SLOT];\n if (value === null || typeof value !== \"object\") return null;\n return value as IWcsTrustedTypesPolicy;\n}\n\n/** 利用側 policy を設定する(`null` で解除)。 */\nexport function setTrustedTypesPolicy(policy: IWcsTrustedTypesPolicy | null): void {\n (globalThis as SymbolSlotHolder)[TRUSTED_TYPES_POLICY_SLOT] = policy;\n}\n\n/**\n * レスポンスを利用側 policy に通す。policy が無ければ素通し= TT 有効下では\n * ブラウザが弾く(意図どおり)。\n */\nexport function trustHtmlValue(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n const policy = getTrustedTypesPolicy();\n const createHTML = policy?.createHTML;\n if (typeof createHTML !== \"function\") return value;\n return createHTML.call(policy, value);\n}\n\nlet _enforced: boolean | undefined = undefined;\nlet _reported = false;\n\n/** テスト用: 実測キャッシュと一度きりの診断をリセットする。 */\nexport function _resetTrustedTypesDiagnostics(): void {\n _enforced = undefined;\n _reported = false;\n}\n\n/**\n * TT が実際に強制されているかを実測する。エラーメッセージの文言に依存しないよう、\n * 使い捨ての要素へ実際に書いて確かめる。`default` policy がある場合は書き込みが\n * 通る=我々の書き込みも通るので、正しく false になる。\n */\nexport function isTrustedTypesEnforced(): boolean {\n if (_enforced !== undefined) return _enforced;\n if (!(\"trustedTypes\" in globalThis)) {\n _enforced = false;\n return _enforced;\n }\n try {\n document.createElement(\"div\").innerHTML = \"<i></i>\";\n _enforced = false;\n } catch {\n _enforced = true;\n }\n return _enforced;\n}\n\n// 呼び出し元(writeTargetHTML)が isTrustedTypesEnforced() を確認してから呼ぶ。\nfunction reportTrustedTypesBlock(): void {\n if (_reported) return;\n _reported = true;\n const hasPolicy = typeof getTrustedTypesPolicy()?.createHTML === \"function\";\n const cause = hasPolicy\n ? \"The injected policy's createHTML() did not return a TrustedHTML.\"\n : \"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass \"\n + \"responses through an identity policy — that would defeat the CSP.\";\n console.error(\n `[@wcstack/fetch] The \"target\" HTML replace mode was blocked by Trusted Types `\n + `(require-trusted-types-for 'script'). ${cause}\\n`\n + `Install a sanitizing policy before the first fetch:\\n`\n + ` globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\\n`\n + ` trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\\n`\n + `Or drop \"target\" and bind the response through @wcstack/state. See docs/csp.md section 7.`,\n );\n}\n\n/**\n * HTML 置換モードの書き込み。\n *\n * TT に弾かれたときは直し方を 1 度だけ報告して**投げ返さない**(never-throw §3.6)。\n * 自動 fetch 経路(connect / url 変更 / trigger)は `fetch()` の rejection を受け取る先が\n * 無く、投げ返すと未処理 rejection として page error になる — 実 Chromium の e2e で\n * 確認した。報告が信号であり、黙って握り潰すのとは違う。TT 以外の失敗(innerHTML の\n * setter が別の理由で throw した等)は従来どおり呼び出し元へ投げ返す。\n */\nexport function writeTargetHTML(element: Element, html: unknown): void {\n try {\n element.innerHTML = trustHtmlValue(html) as string;\n } catch (error) {\n if (isTrustedTypesEnforced()) {\n reportTrustedTypesBlock();\n return;\n }\n throw error;\n }\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { FetchCore, FetchResponseType } from \"../core/FetchCore.js\";\nimport { WcsIoErrorInfo } from \"../core/platformCapability.js\";\nimport { FetchHeader } from \"./FetchHeader.js\";\nimport { FetchBody } from \"./FetchBody.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\nimport { upgradeProperties } from \"../protocol/upgradeProperties.js\";\nimport { writeTargetHTML } from \"../trustedTypes.js\";\n\nexport class Fetch extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...FetchCore.wcBindable,\n properties: [\n ...FetchCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-fetch:trigger-changed\", semantics: \"state\" },\n ],\n // Shell-level input surface. The Core declares only the portable `url` / `method`;\n // the Shell adds the DOM-driven settable surface. No `attribute` hints are given:\n // these setters already reflect to their attributes themselves, so a binding system\n // that mirrors inputs[].attribute would set the attribute twice. `commands`\n // (fetch / abort) are inherited unchanged from the Core via the spread above.\n inputs: [\n { name: \"url\" },\n { name: \"method\" },\n { name: \"target\" },\n { name: \"manual\" },\n { name: \"body\" },\n { name: \"responseType\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"url\"]; }\n\n private _core: FetchCore;\n private _body: any = null;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n // Auto-fetch coalescing state (see _scheduleAutoFetch).\n private _autoPending: boolean = false;\n private _connectResolve: (() => void) | null = null;\n private _lastFetchedUrl: string | null = null;\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n // State reflection is wired BEFORE the Core is constructed (canonical\n // order): a Core that dispatches synchronously from its constructor\n // (e.g. speech's unsupported-changed) would otherwise fire before the\n // listeners exist. FetchCore doesn't do that, so this is equivalent here,\n // but every Shell keeps the same order.\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-fetch:loading-changed\": (d) => ({ loading: d === true }),\n \"wcs-fetch:error\": (d) => ({ error: d != null }),\n });\n this._core = new FetchCore(this);\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // Input setters normalize null/undefined to attribute removal instead of\n // letting setAttribute stringify them (\"undefined\" url would auto-fetch\n // /undefined, \"undefined\" method is an invalid HTTP method). The binder\n // already skips undefined writes; this guards direct JS assignment too.\n get url(): string {\n return this.getAttribute(\"url\") || \"\";\n }\n\n set url(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"url\");\n } else {\n this.setAttribute(\"url\", value);\n }\n }\n\n get method(): string {\n return (this.getAttribute(\"method\") || \"GET\").toUpperCase();\n }\n\n set method(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"method\");\n } else {\n this.setAttribute(\"method\", value);\n }\n }\n\n get target(): string | null {\n return this.getAttribute(\"target\");\n }\n\n set target(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"target\");\n } else {\n this.setAttribute(\"target\", value);\n }\n }\n\n // Response body interpretation. Backed by the `response-type` attribute so it is\n // settable from HTML, JS, or a binding. An unknown value falls through to the\n // Core's \"auto\" branch. `target` (HTML-replace mode) overrides this.\n get responseType(): FetchResponseType {\n return (this.getAttribute(\"response-type\") as FetchResponseType) || \"auto\";\n }\n\n set responseType(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"response-type\");\n } else {\n this.setAttribute(\"response-type\", value);\n }\n }\n\n get value(): any {\n return this._core.value;\n }\n\n get loading(): boolean {\n return this._core.loading;\n }\n\n get error(): any {\n return this._core.error;\n }\n\n get status(): number {\n return this._core.status;\n }\n\n get objectURL(): string | null {\n return this._core.objectURL;\n }\n\n get errorInfo(): WcsIoErrorInfo | null {\n return this._core.errorInfo;\n }\n\n get promise(): Promise<any> {\n return this._core.promise;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get body(): any {\n return this._body;\n }\n\n set body(value: any) {\n // Normalize undefined to null: _collectBody treats \"!== null\" as \"body was\n // provided\", so a raw undefined would serialize as a JSON request body.\n this._body = value ?? null;\n }\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n const v = !!value;\n if (v) {\n // Skip when url is empty. fetch() is fire-and-forget here (its returned\n // promise is intentionally only chained with .finally() to reset the flag,\n // never .catch()'d), and FetchCore.fetch() rejects on an empty url. Without\n // this guard that rejection — re-thrown by .finally() — surfaces as an\n // unhandled promise rejection. Mirrors the url-less guard in autoTrigger.\n //\n // Leave `_trigger` false (do not set it) and emit no event: nothing ran, so\n // surfacing a `wcs-fetch:trigger-changed` \"completion\" would lie to observers.\n // Keeping the flag false also avoids stalling — once url is provided, writing\n // `true` again is a real false→true transition that triggers the fetch.\n if (!this.url) return;\n this._trigger = true;\n this.fetch().finally(() => {\n this._trigger = false;\n this.dispatchEvent(new CustomEvent(\"wcs-fetch:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n });\n }\n }\n\n private _collectHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const headerElements = this.querySelectorAll<FetchHeader>(config.tagNames.fetchHeader);\n for (const el of headerElements) {\n const name = el.headerName;\n const value = el.headerValue;\n if (name) {\n headers[name] = value;\n }\n }\n return headers;\n }\n\n // fetch がネイティブに扱える BodyInit か判定する。これらは JSON.stringify せず\n // 素通しし、Content-Type をブラウザに委ねる (FormData の multipart boundary、\n // Blob の type、URLSearchParams の application/x-www-form-urlencoded を自動付与\n // させるため、_collectBody は contentType に null を返す)。ReadableStream は\n // RequestInit.duplex: 'half' を要するため初版では対象外とし、従来どおり扱う。\n private _isNativeBodyInit(value: unknown): value is BodyInit {\n return value instanceof Blob // File は Blob のサブクラス\n || value instanceof FormData\n || value instanceof URLSearchParams\n || value instanceof ArrayBuffer\n || ArrayBuffer.isView(value); // TypedArray / DataView\n }\n\n private _collectBody(bodySnapshot: any): { body: BodyInit | null; contentType: string | null } {\n // JS API経由のbodyが優先\n if (bodySnapshot !== null) {\n // 文字列はそのまま。Content-Type はユーザーのヘッダ指定に委ねる。\n if (typeof bodySnapshot === \"string\") {\n return { body: bodySnapshot, contentType: null };\n }\n // ネイティブ BodyInit (Blob/File/FormData/URLSearchParams/ArrayBuffer/TypedArray)\n // は素通し。Content-Type はブラウザに委ねるため null を返す。\n if (this._isNativeBodyInit(bodySnapshot)) {\n return { body: bodySnapshot, contentType: null };\n }\n // それ以外のオブジェクトは JSON 化する。\n return { body: JSON.stringify(bodySnapshot), contentType: \"application/json\" };\n }\n\n // サブタグからbodyを取得\n const bodyElement = this.querySelector<FetchBody>(config.tagNames.fetchBody);\n if (bodyElement) {\n return {\n body: bodyElement.bodyContent || null,\n contentType: bodyElement.contentType,\n };\n }\n\n return { body: null, contentType: null };\n }\n\n abort(): void {\n this._core.abort();\n }\n\n /**\n * Coalesce auto-fetch requests in the current task into a single microtask.\n *\n * Multiple synchronous input writes in the same tick — e.g. a `...` spread\n * writing `url` before `manual` — collapse into one decision made against the\n * FINAL element state, so the spread application order can no longer trigger a\n * stray fetch. The microtask re-reads `isConnected` / `manual` / `url` at fire\n * time; whatever was written last wins.\n *\n * Only the implicit auto-fetch (url attribute change, connect-time) is routed\n * here. Explicit triggers — the `trigger` setter, the `fetch` command, and\n * autoTrigger (data-fetchtarget clicks) — must fire immediately and stay on\n * their own synchronous paths.\n *\n * The connect-time promise (connectedCallbackPromise) is resolved here in\n * EVERY exit path, including the no-fetch branch, so awaiting it never hangs\n * when the final state turns out to be manual / url-less / disconnected.\n */\n private _scheduleAutoFetch(): void {\n if (this._autoPending) {\n return;\n }\n this._autoPending = true;\n queueMicrotask(() => {\n this._autoPending = false;\n const resolveConnect = this._connectResolve;\n this._connectResolve = null;\n const url = this.url;\n // Same-value guard (Phase 4): skip a redundant auto-fetch for the url we\n // last fetched. A spread re-evaluation rewrites every input each cycle, so\n // the `url` setter calls setAttribute with an unchanged value and fires\n // attributeChangedCallback again; without this guard an unrelated state\n // change would refetch. Auto-path only — explicit fetch()/trigger/command\n // stay unconditional (a manual refresh of the same url must work), and\n // `_lastFetchedUrl` is reset on disconnect so a remount refetches.\n if (this.isConnected && !this.manual && url && url !== this._lastFetchedUrl) {\n // fetch() cannot reject here: FetchCore swallows network/HTTP errors and\n // only rejects on an empty url, which the `url` guard above rules out.\n this.fetch().finally(() => resolveConnect?.());\n } else {\n resolveConnect?.();\n }\n });\n }\n\n async fetch(): Promise<any> {\n // Record the url for the auto-fetch same-value guard. Every fetch (explicit\n // included) updates it so a later auto-write of the same url is treated as a\n // no-op rather than a duplicate request.\n this._lastFetchedUrl = this.url;\n const headers = this._collectHeaders();\n\n // Snapshot and reset `body` synchronously, before any await. The body is a\n // one-shot input; resetting it after the await (when another caller may have\n // already set a new body for the next request) would silently drop that value.\n const bodySnapshot = this._body;\n this._body = null;\n const { body, contentType } = this._collectBody(bodySnapshot);\n\n // FormData に手動で Content-Type を付けると、ブラウザが付与するはずの multipart\n // boundary が失われてサーバー側でパースできなくなる。ヘッダはユーザー指定を\n // 尊重して素通しするが、この典型的な誤設定は警告する。\n if (body instanceof FormData &&\n Object.keys(headers).some((name) => name.toLowerCase() === \"content-type\")) {\n console.warn(\n \"[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. \" +\n \"This drops the multipart boundary the browser adds automatically; remove the \" +\n \"Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.\",\n );\n }\n\n const result = await this._core.fetch(this.url, {\n method: this.method,\n headers,\n body,\n contentType,\n forceText: !!this.target,\n responseType: this.responseType,\n });\n\n // HTML置換モード\n // Security: the response is injected as raw innerHTML without sanitization.\n // This is an opt-in convenience for trusted fragments only; the primary,\n // recommended path is state-driven binding via @wcstack/state. Do not point\n // `target` at an untrusted endpoint (XSS risk). See README \"HTML Replace Mode\".\n //\n // Under Trusted Types this is the one sink in wcstack whose input is remote\n // data, so it is routed through an *adopter-supplied* sanitizing policy only —\n // fetch never signs the response with an identity policy (docs/csp.md §7).\n if (this.target && result !== null) {\n const targetElement = document.getElementById(this.target);\n if (targetElement) {\n writeTargetHTML(targetElement, result);\n }\n }\n\n return result;\n }\n\n attributeChangedCallback(name: string, _oldValue: string | null, _newValue: string | null): void {\n // Re-fetch on url changes, but intentionally do NOT update\n // `_connectedCallbackPromise`. Per the wc-bindable connectedCallbackPromise\n // protocol that promise represents the one-shot \"connect-time initialization\n // is done\" signal; it resolves once and is not re-armed for later url-driven\n // requests. Await `promise` if you need to track a specific re-fetch.\n //\n // Defer the decision to a microtask (see _scheduleAutoFetch) instead of\n // fetching synchronously here: a `...` spread writes `url` before `manual`,\n // so a synchronous fetch would fire before `manual` is applied. The final\n // state (isConnected / manual / url) is re-read at microtask time.\n if (name === \"url\") {\n this._scheduleAutoFetch();\n }\n }\n\n connectedCallback(): void {\n // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)\n upgradeProperties(this);\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Only the initial connect-time fetch is tracked by connectedCallbackPromise.\n // Arm a deferred here when an auto-fetch looks likely; the scheduled\n // microtask resolves it (in every exit path, so awaiting never hangs). The\n // actual fetch decision is re-evaluated at microtask time against the final\n // state, so a spread that sets `manual` after `url` still suppresses it.\n if (!this.manual && this.url) {\n this._connectedCallbackPromise = new Promise<void>((resolve) => {\n this._connectResolve = resolve;\n });\n }\n this._scheduleAutoFetch();\n }\n\n disconnectedCallback(): void {\n this.abort();\n // Reset the same-value guard so a remount (reconnect with the same url)\n // refetches rather than being skipped as a duplicate.\n this._lastFetchedUrl = null;\n // Resolve any armed connect-time deferred before detaching. A synchronous\n // remove()→append() before the scheduled microtask fires would otherwise let\n // the second connectedCallback overwrite _connectResolve, orphaning the first\n // deferred and hanging any caller that already awaited connectedCallbackPromise.\n // Disconnection makes connect-time init moot, so resolving (never hanging) is\n // correct; the pending microtask then sees _connectResolve === null and no-ops.\n this._connectResolve?.();\n this._connectResolve = null;\n }\n}\n","export class FetchHeader extends HTMLElement {\n connectedCallback(): void {\n this.style.display = \"none\";\n }\n\n get headerName(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n get headerValue(): string {\n return this.getAttribute(\"value\") || \"\";\n }\n}\n","export class FetchBody extends HTMLElement {\n constructor() {\n super();\n // スロットなしのShadow DOMでlight DOM(bodyテキスト)の描画を抑制\n this.attachShadow({ mode: \"open\" });\n }\n\n get contentType(): string {\n return this.getAttribute(\"type\") || \"application/json\";\n }\n\n get bodyContent(): string {\n return this.textContent?.trim() || \"\";\n }\n}\n","import { Fetch } from \"./Fetch.js\";\n\nexport class InfiniteScroll extends HTMLElement {\n static get observedAttributes(): string[] {\n return [\"target\", \"root\", \"root-margin\", \"threshold\", \"disabled\"];\n }\n\n private _observer: IntersectionObserver | null = null;\n private _done: boolean = false;\n\n get target(): string {\n return this.getAttribute(\"target\") || \"\";\n }\n\n set target(value: string) {\n this.setAttribute(\"target\", value);\n }\n\n get root(): string | null {\n return this.getAttribute(\"root\");\n }\n\n set root(value: string | null) {\n if (value === null) {\n this.removeAttribute(\"root\");\n } else {\n this.setAttribute(\"root\", value);\n }\n }\n\n get rootMargin(): string {\n return this.getAttribute(\"root-margin\") || \"0px\";\n }\n\n set rootMargin(value: string) {\n this.setAttribute(\"root-margin\", value);\n }\n\n get threshold(): number {\n const value = Number(this.getAttribute(\"threshold\") ?? \"0\");\n return Number.isFinite(value) ? value : 0;\n }\n\n set threshold(value: number) {\n this.setAttribute(\"threshold\", String(value));\n }\n\n get disabled(): boolean {\n return this.hasAttribute(\"disabled\");\n }\n\n set disabled(value: boolean) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n } else {\n this.removeAttribute(\"disabled\");\n }\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n connectedCallback(): void {\n this._observe();\n }\n\n disconnectedCallback(): void {\n this._disconnectObserver();\n }\n\n attributeChangedCallback(): void {\n if (this.isConnected) {\n this._observe();\n }\n }\n\n private _observe(): void {\n this._disconnectObserver();\n\n if (this._done || this.disabled || !this.target || typeof IntersectionObserver === \"undefined\") {\n return;\n }\n\n this._observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n this._triggerFetch();\n }\n }, {\n root: this._resolveRoot(),\n rootMargin: this.rootMargin,\n threshold: this.threshold,\n });\n this._observer.observe(this);\n }\n\n private _disconnectObserver(): void {\n if (this._observer) {\n this._observer.disconnect();\n this._observer = null;\n }\n }\n\n private _resolveRoot(): Element | Document | null {\n if (!this.root) return null;\n return document.getElementById(this.root) || null;\n }\n\n private _triggerFetch(): void {\n const target = document.getElementById(this.target);\n if (!(target instanceof Fetch)) {\n return;\n }\n\n if (target.loading) {\n return;\n }\n\n target.trigger = true;\n\n if (this.once) {\n this._done = true;\n this._disconnectObserver();\n }\n }\n}","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapFetch(userConfig?: IWritableConfig, registry?: CustomElementRegistry): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents(registry);\n}\n","import { Fetch } from \"./components/Fetch.js\";\nimport { FetchHeader } from \"./components/FetchHeader.js\";\nimport { FetchBody } from \"./components/FetchBody.js\";\nimport { InfiniteScroll } from \"./components/InfiniteScroll.js\";\nimport { config } from \"./config.js\";\n\n/**\n * Register this package's tags. Pass a scoped `CustomElementRegistry` to define\n * them for a single shadow tree -- scoped registries do not inherit the global\n * one, so a tree using one needs its own definitions.\n */\nexport function registerComponents(registry: CustomElementRegistry = customElements): void {\n if (!registry.get(config.tagNames.fetch)) {\n registry.define(config.tagNames.fetch, Fetch);\n }\n if (!registry.get(config.tagNames.fetchHeader)) {\n registry.define(config.tagNames.fetchHeader, FetchHeader);\n }\n if (!registry.get(config.tagNames.fetchBody)) {\n registry.define(config.tagNames.fetchBody, FetchBody);\n }\n if (!registry.get(config.tagNames.infiniteScroll)) {\n registry.define(config.tagNames.infiniteScroll, InfiniteScroll);\n }\n}\n"],"names":["config","triggerAttribute","tagNames","fetch","fetchHeader","fetchBody","infiniteScroll","OperationLane","laneKey","policy","_ownerGeneration","_latestEpoch","_nextOperationId","_activeOperationId","undefined","_activeOperationIds","Set","_queue","_inFlightCount","_terminal","Map","_claimedOutcome","_controllers","_attempts","_withSignal","_trace","constructor","options","this","withSignal","trace","ownerGeneration","inFlightCount","latestEpoch","activeOperationId","begin","supersedeEpoch","_abortController","operationId","ticket","push","add","set","attempt","_makeAttempt","type","retry","has","previous","get","attemptNo","_releaseController","canCommit","status","_isEligible","claimTerminal","outcome","claimedOutcome","finalize","delete","_advanceBookkeeping","signalOf","signal","abort","abortActive","disposeOwner","Array","from","keys","clear","length","AbortController","controller","remaining","filter","t","aborted","assessCapabilities","registry","availability","evaluate","id","spec","probe","requiredAllAvailable","required","a","optionalAllAvailable","optional","readiness","allIds","needsSecure","some","requiresSecureContext","needsActivation","requiresUserActivation","secureContext","globalThis","isSecureContext","userActivation","permission","activity","preconditions","epoch","lastError","requiredCapabilitiesAvailable","assessment","every","WCS_FETCH_ERROR_CODE","FETCH_CAPABILITIES","compatKey","FetchCore","EventTarget","static","protocol","version","properties","name","event","semantics","getter","e","detail","value","objectURL","inputs","commands","async","_target","_value","_loading","_error","_status","_objectURL","_promise","Promise","resolve","_lane","_ready","_errorInfo","target","super","ready","observe","dispose","_revokeObjectURL","loading","error","promise","errorInfo","supported","platformAssessment","REQUIRED_CAPABILITIES","OPTIONAL_CAPABILITIES","_setErrorInfo","code","phase","recoverable","message","capabilityId","_commitErrorInfo","info","dispatchEvent","CustomEvent","bubbles","_setLoading","_setError","_setResponse","_createObjectURL","blob","URL","createObjectURL","url","revokeObjectURL","_commitStep","step","missing","find","p","_doFetch","started","method","body","contentType","forceText","responseType","timeout","timeoutTimer","setTimeout","headers","requestInit","response","ok","text","arrayBuffer","json","responseContentType","includes","errorBody","catch","statusText","Blob","String","clearTimeout","registered","handleClick","Element","triggerElement","closest","fetchId","getAttribute","FetchCtor","customElements","el","document","getElementById","fetchElement","preventDefault","hasAccessorOnPrototype","proto","Object","getPrototypeOf","descriptor","getOwnPropertyDescriptor","TRUSTED_TYPES_POLICY_SLOT","Symbol","for","getTrustedTypesPolicy","_enforced","_reported","writeTargetHTML","element","html","innerHTML","createHTML","call","trustHtmlValue","createElement","isTrustedTypesEnforced","cause","console","reportTrustedTypesBlock","Fetch","HTMLElement","wcBindable","observedAttributes","_core","_body","_trigger","_connectedCallbackPromise","_autoPending","_connectResolve","_lastFetchedUrl","_internals","_initInternals","_wireStates","d","debugStates","states","attachInternals","internals","map","toStates","entries","addEventListener","debug","hasAttribute","on","toggleAttribute","removeAttribute","setAttribute","toUpperCase","connectedCallbackPromise","manual","trigger","finally","_collectHeaders","headerElements","querySelectorAll","headerName","headerValue","_isNativeBodyInit","FormData","URLSearchParams","ArrayBuffer","isView","_collectBody","bodySnapshot","JSON","stringify","bodyElement","querySelector","bodyContent","_scheduleAutoFetch","queueMicrotask","resolveConnect","isConnected","toLowerCase","warn","result","targetElement","attributeChangedCallback","_oldValue","_newValue","connectedCallback","declaration","input","prototype","hasOwnProperty","record","upgradeProperties","style","display","disconnectedCallback","FetchHeader","FetchBody","attachShadow","mode","textContent","trim","InfiniteScroll","_observer","_done","root","rootMargin","threshold","Number","isFinite","disabled","once","_observe","_disconnectObserver","IntersectionObserver","entry","isIntersecting","_triggerFetch","_resolveRoot","disconnect","define","registerComponents"],"mappings":"AAaA,MA+BaA,EA/BoB,CAE/BC,iBAAkB,mBAClBC,SAAU,CACRC,MAAO,YACPC,YAAa,mBACbC,UAAW,iBACXC,eAAgB,8BCyDPC,EACFC,QACAC,OAEDC,iBAAmB,EACnBC,aAAe,EACfC,iBAAmB,EAEnBC,wBAAyCC,EAEhCC,oBAAsB,IAAIC,IAE1BC,OAA4B,GACrCC,eAAiB,EAERC,UAAY,IAAIC,IAEhBC,gBAAkB,IAAID,IAEtBE,aAAe,IAAIF,IAEnBG,UAAY,IAAIH,IAChBI,YACAC,OAEjB,WAAAC,CAAYlB,EAAiBC,EAAoBkB,EAAgC,CAAA,GAC/EC,KAAKpB,QAAUA,EACfoB,KAAKnB,OAASA,EACdmB,KAAKJ,YAAcG,EAAQE,aAAc,EACzCD,KAAKH,OAASE,EAAQG,KACxB,CAEA,mBAAIC,GACF,OAAOH,KAAKlB,gBACd,CAEA,iBAAIsB,GACF,OAAOJ,KAAKV,cACd,CAEA,eAAIe,GACF,OAAOL,KAAKjB,YACd,CA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B,CAEQ,aAAAY,GACN,MAAMnM,EAAS0E,SAASC,eAAe3L,KAAKgH,QACtCA,aAAkBsG,IAIpBtG,EAAOM,UAIXN,EAAOsI,SAAU,EAEbtP,KAAK6S,OACP7S,KAAKsS,OAAQ,EACbtS,KAAK+S,wBAET,EChII,IAAuD7P,GCOvD,SAA6BA,EAAkCsI,gBAC9DtI,EAAS7B,IAAIjD,EAAOE,SAASC,QAChC2E,EAASoQ,OAAOlV,EAAOE,SAASC,MAAO+O,GAEpCpK,EAAS7B,IAAIjD,EAAOE,SAASE,cAChC0E,EAASoQ,OAAOlV,EAAOE,SAASE,YAAasT,GAE1C5O,EAAS7B,IAAIjD,EAAOE,SAASG,YAChCyE,EAASoQ,OAAOlV,EAAOE,SAASG,UAAWsT,GAExC7O,EAAS7B,IAAIjD,EAAOE,SAASI,iBAChCwE,EAASoQ,OAAOlV,EAAOE,SAASI,eAAgB0T,EAEpD,CDhBEmB,CAAmBrQ"}
|
|
1
|
+
{"version":3,"file":"auto.min.js","sources":["../src/config.ts","../src/core/operationLane.ts","../src/core/platformCapability.ts","../src/core/fetchCapabilities.ts","../src/core/FetchCore.ts","../src/autoTrigger.ts","../src/protocol/upgradeProperties.ts","../src/trustedTypes.ts","../src/components/Fetch.ts","../src/components/FetchHeader.ts","../src/components/FetchBody.ts","../src/components/InfiniteScroll.ts","../src/bootstrapFetch.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n fetch: string;\n fetchHeader: string;\n fetchBody: string;\n infiniteScroll: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-fetchtarget\",\n tagNames: {\n fetch: \"wcs-fetch\",\n fetchHeader: \"wcs-fetch-header\",\n fetchBody: \"wcs-fetch-body\",\n infiniteScroll: \"wcs-infinite-scroll\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\n// The defaults as shipped, for warnInvalid: a value 3.x lets through unchecked must not change\n// what a later call is compared against.\nconst defaults: Record<string, unknown> = { ..._config, tagNames: { ..._config.tagNames } };\nconst warned = new Set<string>();\n\n/**\n * 3.5 forward-compat check. Warns, once per key per page, about an option that 4.0's bootstrapFetch\n * throws on: one this package does not have, a value of another type than its default (null, or an\n * array for an object, included), or a tag name it does not define or that is not a string. An\n * undefined value is left out, as in 4.0. It only warns: setConfig then goes on exactly as in 3.x.\n * Bootstrap-time only, never on a hot path.\n */\nfunction warnInvalid(given: Record<string, unknown>, known: Record<string, unknown>, path = \"\"): void {\n for (const [key, value] of Object.entries(given)) {\n const name = path + key;\n const current = known[key];\n if (value === undefined) {\n continue;\n }\n if (\n !Object.prototype.hasOwnProperty.call(known, key) ||\n value === null ||\n typeof value !== typeof current ||\n Array.isArray(value) !== Array.isArray(current)\n ) {\n if (!warned.has(name)) {\n warned.add(name);\n console.warn(`[@wcstack/fetch] bootstrapFetch: \"${name}\" is not one of its options, or not of the option's type. 3.x ignores it or applies it unchecked; 4.0 throws on it.`);\n }\n } else if (name === \"tagNames\") {\n warnInvalid(value as Record<string, unknown>, current as Record<string, unknown>, \"tagNames.\");\n }\n }\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n warnInvalid(partialConfig as Record<string, unknown>, defaults);\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /io-core/operation-lane.ts by scripts/sync-io-core.mjs.\n// Run `node scripts/sync-io-core.mjs` after editing the source.\n// ===========================================================================\n\n/**\n * operationLane.ts\n *\n * Phase 4 (docs/architecture-hardening/09-remediation-design.md §5, §5.1) の\n * OperationTicket / CommitGuard / terminal CAS を型付き実装した lane プリミティブ。\n * docs/async-execution-model.md §5 が既に規範化した排他モード\n * (latest / queue / exhaust / overlap) を、`AbortController` だけでは防げない\n * 「取消不能な Promise・abort と同時に完了した結果の commit」から守るための\n * 実行時ガードとして具体化する。\n *\n * 配置方針 (§5): 本ファイルは /io-core/ の単一正典であり、scripts/sync-io-core.mjs が\n * 各 IO ノードの src/core/ へ生成コピー (AUTO-GENERATED, 編集禁止) を配布する。\n * `protocol/wcBindable.ts` と同じ copy-distribution 方式で、ランタイム依存を導入せず\n * 各パッケージのバンドルへ inline される (zero-runtime-dep / 自己完結 CDN を維持)。\n * 編集はこの正典に対して行い、`node scripts/sync-io-core.mjs` で再配布する。\n *\n * 初期 PoC は fetch の `latest` policy から開始した。現在は4 policy 全てを\n * `operationLane.test.ts` が直接検証し、生成コピーを fetch / upload / share /\n * contacts / credential / eyedropper が利用する。lane 自体は promise を実行せず、\n * bookkeeping と guard の状態機械に徹する — 実際の非同期処理は Core が駆動し\n * lane に照合する。\n */\n\n/** §5: 排他モードの語彙。async-execution-model.md §5 の 4 モードに対応 (parallel は予約語・スコープ外)。 */\nexport type LanePolicy = \"latest\" | \"queue\" | \"exhaust\" | \"overlap\";\n\n/** §5: 各 operation の一回限りの終端結果。 */\nexport type TerminalOutcome = \"success\" | \"error\" | \"timeout\" | \"aborted\" | \"stale\";\n\n/** §5: 論理操作 1 件の identity。retry は同じ operationId を再利用する。 */\nexport interface OperationTicket {\n readonly operationId: number;\n /** 発行時に捕捉した I/O Core の observe / reconnect / dispose lifecycle 世代。 */\n readonly ownerGeneration: number;\n readonly laneKey: string;\n readonly policy: LanePolicy;\n /** supersede bookkeeping に使う epoch (latest policy のみ)。 */\n readonly supersedeEpoch?: number;\n}\n\n/** §5: operation の 1 回の試行。retry で attempt++ と resource signal だけ差し替える。 */\nexport interface OperationAttempt {\n readonly operationId: number;\n readonly attempt: number;\n readonly signal?: AbortSignal;\n}\n\n/** §6: DevTools 側 channel へ流す trace(fetch では既定 off・zero-cost)。 */\nexport type OperationTraceEvent =\n | { readonly type: \"io:operation-started\"; readonly operationId: number; readonly laneKey: string; readonly policy: LanePolicy }\n | { readonly type: \"io:operation-retried\"; readonly operationId: number; readonly laneKey: string; readonly attempt: number }\n | { readonly type: \"io:operation-settled\"; readonly operationId: number; readonly laneKey: string; readonly outcome: TerminalOutcome }\n | { readonly type: \"io:stale-dropped\"; readonly operationId: number; readonly laneKey: string };\n\nexport interface OperationLaneOptions {\n /** attempt ごとに AbortController を発行し signal を渡す (fetch/upload 系)。 */\n readonly withSignal?: boolean;\n /**\n * trace subscriber。undefined なら trace record を一切生成しない\n * (§10.3 hook-off zero allocation の gate)。\n */\n readonly trace?: (event: OperationTraceEvent) => void;\n}\n\n/** 内部の終端状態。absence = pending。'committing' は multi-setter commit 中の中間状態。 */\ntype TerminalStatus = \"committing\" | TerminalOutcome;\n\n/**\n * 1 レーン = 独立した排他単位。Core が 1 つ以上所有する (module singleton にしない —\n * 複数 <wcs-fetch> 間で漏れるため)。\n */\nexport class OperationLane {\n readonly laneKey: string;\n readonly policy: LanePolicy;\n\n private _ownerGeneration = 0;\n private _latestEpoch = 0;\n private _nextOperationId = 1;\n // latest / queue / exhaust の単一 active。queue は head を指す。\n private _activeOperationId: number | undefined = undefined;\n // overlap の active set (§5: 内部 bookkeeping のみ・observable 公開はしない)。\n private readonly _activeOperationIds = new Set<number>();\n // queue policy の FIFO。\n private readonly _queue: OperationTicket[] = [];\n private _inFlightCount = 0;\n // opId → 終端状態 (absence = pending)。\n private readonly _terminal = new Map<number, TerminalStatus>();\n // claimTerminal で確定した outcome (finalize が 'committing' を最終値へ移す)。\n private readonly _claimedOutcome = new Map<number, TerminalOutcome>();\n // opId → AbortController (identity は opId が保証。cross-op clobber は構造上起きない)。\n private readonly _controllers = new Map<number, AbortController>();\n // opId → attempt 数。\n private readonly _attempts = new Map<number, number>();\n private readonly _withSignal: boolean;\n private readonly _trace?: (event: OperationTraceEvent) => void;\n\n constructor(laneKey: string, policy: LanePolicy, options: OperationLaneOptions = {}) {\n this.laneKey = laneKey;\n this.policy = policy;\n this._withSignal = options.withSignal ?? false;\n this._trace = options.trace;\n }\n\n get ownerGeneration(): number {\n return this._ownerGeneration;\n }\n\n get inFlightCount(): number {\n return this._inFlightCount;\n }\n\n get latestEpoch(): number {\n return this._latestEpoch;\n }\n\n get activeOperationId(): number | undefined {\n return this._activeOperationId;\n }\n\n /**\n * 新しい要求の到着。arrival policy を適用し ticket + 最初の attempt を発行する。\n * exhaust で実行中の場合だけ null を返す (新要求を ticket 化せず拒否 = 冪等 no-op)。\n */\n begin(): { ticket: OperationTicket; attempt: OperationAttempt } | null {\n let supersedeEpoch: number | undefined;\n switch (this.policy) {\n case \"latest\": {\n // latestEpoch を進め、旧 active を abort (可能なら)。旧 ticket は settle 時に\n // eligibility 不一致で stale となる。\n supersedeEpoch = ++this._latestEpoch;\n if (this._activeOperationId !== undefined) {\n this._abortController(this._activeOperationId);\n }\n break;\n }\n case \"exhaust\": {\n // 実行中なら新要求を拒否 (呼び出し側は既存結果へ合流)。\n if (this._activeOperationId !== undefined) {\n return null;\n }\n break;\n }\n case \"queue\":\n case \"overlap\":\n break;\n }\n\n const operationId = this._nextOperationId++;\n const ticket: OperationTicket = {\n operationId,\n ownerGeneration: this._ownerGeneration,\n laneKey: this.laneKey,\n policy: this.policy,\n supersedeEpoch,\n };\n\n switch (this.policy) {\n case \"latest\":\n case \"exhaust\":\n this._activeOperationId = operationId;\n break;\n case \"queue\":\n this._queue.push(ticket);\n // 先頭だけを active にする (先行が完了するまで待つ)。\n if (this._activeOperationId === undefined) {\n this._activeOperationId = operationId;\n }\n break;\n case \"overlap\":\n this._activeOperationIds.add(operationId);\n break;\n }\n\n this._inFlightCount += 1;\n this._attempts.set(operationId, 1);\n const attempt = this._makeAttempt(operationId, 1);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:operation-started\", operationId, laneKey: this.laneKey, policy: this.policy });\n }\n return { ticket, attempt };\n }\n\n /**\n * retry: 同じ operationId に新しい attempt を作る。attempt number と resource signal\n * だけを更新する (§5)。既に終端した operation には作れない (null)。\n */\n retry(ticket: OperationTicket): OperationAttempt | null {\n if (ticket.ownerGeneration !== this._ownerGeneration) return null;\n if (this._terminal.has(ticket.operationId)) return null;\n const previous = this._attempts.get(ticket.operationId);\n if (previous === undefined) return null;\n const attemptNo = previous + 1;\n this._attempts.set(ticket.operationId, attemptNo);\n // 前の attempt の signal は破棄し、新しい controller を張る。\n this._releaseController(ticket.operationId);\n const attempt = this._makeAttempt(ticket.operationId, attemptNo);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:operation-retried\", operationId: ticket.operationId, laneKey: this.laneKey, attempt: attemptNo });\n }\n return attempt;\n }\n\n /**\n * CommitGuard (§5.1)。外部可視の setter / event dispatch の直前に呼ぶ。\n * (1) owner lifecycle generation 一致 (2) terminal settle 前 (3) policy eligibility。\n */\n canCommit(ticket: OperationTicket): boolean {\n if (ticket.ownerGeneration !== this._ownerGeneration) return false;\n const status = this._terminal.get(ticket.operationId);\n // absence = pending / 'committing' = multi-setter commit 中。どちらも settle 前。\n if (status !== undefined && status !== \"committing\") return false;\n return this._isEligible(ticket);\n }\n\n /**\n * terminal CAS (§5.1): pending → committing を claim する。勝者だけが true。\n * eligibility / owner gen を満たさない場合も false。claim 後は commit 中となり、\n * canCommit は各 setter の直前で再検査する (setter が同期 supersede しても取りこぼさない)。\n */\n claimTerminal(ticket: OperationTicket, outcome: TerminalOutcome): boolean {\n if (ticket.ownerGeneration !== this._ownerGeneration) return false;\n if (this._terminal.has(ticket.operationId)) return false; // 既に committing / 終端\n if (!this._isEligible(ticket)) return false;\n this._terminal.set(ticket.operationId, \"committing\");\n this._claimedOutcome.set(ticket.operationId, outcome);\n return true;\n }\n\n /** claim 済み outcome (timer が claim → catch が読む等)。未 claim なら undefined。 */\n claimedOutcome(ticket: OperationTicket): TerminalOutcome | undefined {\n return this._claimedOutcome.get(ticket.operationId);\n }\n\n /**\n * operation の後始末。claim 済みなら outcome を確定し、未 claim なら stale-drop。\n * controller を解放し in-flight を減らし、policy の bookkeeping を進める。冪等。\n */\n finalize(ticket: OperationTicket): void {\n const operationId = ticket.operationId;\n const status = this._terminal.get(operationId);\n if (status !== undefined && status !== \"committing\") {\n // 既に確定済み。冪等に return。\n return;\n }\n let outcome: TerminalOutcome;\n if (status === \"committing\") {\n outcome = this._claimedOutcome.get(operationId) ?? \"stale\";\n } else {\n // 一度も claim されなかった (supersede / dispose で eligibility を失った)。\n outcome = \"stale\";\n }\n this._terminal.set(operationId, outcome);\n this._claimedOutcome.delete(operationId);\n this._releaseController(operationId);\n this._attempts.delete(operationId);\n if (this._inFlightCount > 0) this._inFlightCount -= 1;\n this._advanceBookkeeping(operationId);\n if (this._trace !== undefined) {\n if (outcome === \"stale\") {\n this._trace({ type: \"io:stale-dropped\", operationId, laneKey: this.laneKey });\n } else {\n this._trace({ type: \"io:operation-settled\", operationId, laneKey: this.laneKey, outcome });\n }\n }\n }\n\n /** operation の signal (resource 解放用)。withSignal でなければ undefined。 */\n signalOf(ticket: OperationTicket): AbortSignal | undefined {\n return this._controllers.get(ticket.operationId)?.signal;\n }\n\n /** best-effort な resource 中断。正しさは owner gen / eligibility / terminal CAS が担う。 */\n abort(ticket: OperationTicket): void {\n this._abortController(ticket.operationId);\n }\n\n /**\n * 現在 active な operation を中断する (利用者による明示キャンセル)。epoch は進めない —\n * 中断された operation は eligibility を保ったまま 'aborted' を claim できる\n * (loading をクリアしつつ in-flight 状態を残す)。\n */\n abortActive(): void {\n if (this._activeOperationId !== undefined) {\n this._abortController(this._activeOperationId);\n }\n for (const operationId of this._activeOperationIds) {\n this._abortController(operationId);\n }\n }\n\n /**\n * dispose (§4.1 world generation)。owner generation を bump して全 ticket を無効化し、\n * 生きている controller を全て abort する。dispose 後に settle した operation は\n * owner gen 不一致で外部 commit しない。retention gate (§10.3) のため live な\n * 全 operation を即時に stale として finalize し、controller / attempt を解放する。\n */\n disposeOwner(): void {\n this._ownerGeneration += 1;\n for (const operationId of Array.from(this._controllers.keys())) {\n this._abortController(operationId);\n // finalize は dispose 後 (terminal='stale') に early-return するため controller を\n // 解放しない。retention gate (§10.3) を満たすためここで明示的に解放する。\n this._releaseController(operationId);\n }\n for (const operationId of Array.from(this._attempts.keys())) {\n if (!this._terminal.has(operationId)) {\n this._terminal.set(operationId, \"stale\");\n }\n this._claimedOutcome.delete(operationId);\n this._attempts.delete(operationId);\n if (this._trace !== undefined) {\n this._trace({ type: \"io:stale-dropped\", operationId, laneKey: this.laneKey });\n }\n }\n this._activeOperationId = undefined;\n this._activeOperationIds.clear();\n this._queue.length = 0;\n this._inFlightCount = 0;\n }\n\n // --- internal ---\n\n private _makeAttempt(operationId: number, attemptNo: number): OperationAttempt {\n let signal: AbortSignal | undefined;\n // AbortController 不在環境(古い runtime / 一部 SSR)では degraded: signal なしで進む。\n // 正しさは owner generation / eligibility / terminal CAS が担うため、native 中断が\n // 無くても supersede / dispose は機能する(best-effort resource 中断が省かれるだけ)。\n if (this._withSignal && typeof AbortController === \"function\") {\n const controller = new AbortController();\n this._controllers.set(operationId, controller);\n signal = controller.signal;\n }\n return { operationId, attempt: attemptNo, signal };\n }\n\n private _isEligible(ticket: OperationTicket): boolean {\n switch (this.policy) {\n case \"latest\":\n return ticket.supersedeEpoch === this._latestEpoch;\n case \"queue\":\n case \"exhaust\":\n return this._activeOperationId === ticket.operationId;\n case \"overlap\":\n return this._activeOperationIds.has(ticket.operationId);\n }\n }\n\n private _advanceBookkeeping(operationId: number): void {\n switch (this.policy) {\n case \"latest\":\n case \"exhaust\":\n if (this._activeOperationId === operationId) {\n this._activeOperationId = undefined;\n }\n break;\n case \"queue\": {\n // 完了した ticket を FIFO から取り除き、次の先頭を active にする。filter で\n // 「先頭 / 非先頭 / 不在」を一様に扱う (finalize は冪等ガードを通った op のみ到達)。\n const remaining = this._queue.filter((t) => t.operationId !== operationId);\n this._queue.length = 0;\n this._queue.push(...remaining);\n this._activeOperationId = this._queue.length > 0 ? this._queue[0].operationId : undefined;\n break;\n }\n case \"overlap\":\n this._activeOperationIds.delete(operationId);\n break;\n }\n }\n\n private _abortController(operationId: number): void {\n const controller = this._controllers.get(operationId);\n if (controller !== undefined && !controller.signal.aborted) {\n controller.abort();\n }\n }\n\n private _releaseController(operationId: number): void {\n this._controllers.delete(operationId);\n }\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /io-core/platform-capability.ts by scripts/sync-io-core.mjs.\n// Run `node scripts/sync-io-core.mjs` after editing the source.\n// ===========================================================================\n\n/**\n * platform-capability.ts\n *\n * Phase 6(docs/architecture-hardening/09-remediation-design.md §7.2 /\n * 07-browser-capability-variance.md)の browser capability 判定と error taxonomy の\n * 汎用プリミティブ。node 固有の capability registry / error code は各パッケージが\n * 別ファイルで宣言し、この汎用層(型 + assess 機構)を import する。\n *\n * 原則:\n * - feature detection は境界(利用直前)で行う。module 評価時に browser global を\n * 参照しない(SSR / worker で import が失敗しない)。\n * - capability ID(`web.fetch` 等)は文字列を global property path として eval せず、\n * registry が ID ごとに副作用のない presence probe を対応付ける。\n * - availability / permission / readiness / activity / operation error を 1 つの\n * `ready / unsupported / error` enum に畳まない。required 欠如は開始しない、\n * optional 欠如は宣言済み fallback で readiness を `degraded` にする。\n *\n * 配置: 本ファイルは /io-core/ の単一正典であり、scripts/sync-io-core.mjs が\n * 各 IO ノードの src/core/ へ生成コピー (AUTO-GENERATED, 編集禁止) を配布する。\n * `protocol/wcBindable.ts` と同じ copy-distribution 方式で、ランタイム依存を導入せず\n * 各パッケージのバンドルへ inline される (zero-runtime-dep / 自己完結 CDN を維持)。\n * 編集はこの正典に対して行い、`node scripts/sync-io-core.mjs` で再配布する。\n *\n * pure(module 評価時に browser global 非参照)。\n */\n\nexport type Availability = \"available\" | \"missing\" | \"unknown\";\nexport type PermissionState = \"granted\" | \"denied\" | \"prompt\" | \"not-applicable\" | \"unknown\";\nexport type Readiness = \"idle\" | \"ready\" | \"degraded\";\nexport type Activity = \"inactive\" | \"active\";\nexport type PreconditionState = \"satisfied\" | \"required\" | \"not-applicable\";\n\n/** operation error の phase(taxonomy)。 */\nexport type WcsIoErrorPhase = \"probe\" | \"start\" | \"execute\" | \"decode\" | \"commit\" | \"dispose\";\n\n/** serializable な error info(non-cloneable な cause とは分離。DevTools / remote へは info のみ)。 */\nexport interface WcsIoErrorInfo {\n readonly code: string;\n readonly phase: WcsIoErrorPhase;\n readonly recoverable: boolean;\n readonly capabilityId?: string;\n readonly message: string;\n}\n\nexport interface PlatformAssessment {\n readonly availability: ReadonlyMap<string, Availability>;\n readonly permission: PermissionState;\n readonly readiness: Readiness;\n readonly activity: Activity;\n readonly preconditions: {\n readonly secureContext: PreconditionState;\n readonly userActivation: PreconditionState;\n };\n readonly epoch: number;\n readonly lastError?: WcsIoErrorInfo;\n}\n\n/** capability 1 件の仕様。probe は副作用なく presence を返す(利用直前に呼ぶ)。 */\nexport interface CapabilitySpec {\n readonly probe: () => boolean;\n readonly requiresSecureContext?: boolean;\n readonly requiresUserActivation?: boolean;\n /** browser compatibility dataset のキー(任意・診断用)。 */\n readonly compatKey?: string;\n}\n\nexport type CapabilityRegistry = ReadonlyMap<string, CapabilitySpec>;\n\nexport interface AssessOptions {\n readonly required: readonly string[];\n readonly optional?: readonly string[];\n readonly permission?: PermissionState;\n readonly activity?: Activity;\n readonly epoch?: number;\n readonly lastError?: WcsIoErrorInfo;\n}\n\nfunction isSecureContext(): boolean {\n return (globalThis as { isSecureContext?: unknown }).isSecureContext === true;\n}\n\n/**\n * capability を利用直前に評価して PlatformAssessment を作る。\n * required が 1 つでも欠ければ readiness は \"idle\"(開始不可)、\n * required 揃い + optional 欠けは \"degraded\"、全揃いは \"ready\"。\n */\nexport function assessCapabilities(registry: CapabilityRegistry, options: AssessOptions): PlatformAssessment {\n const availability = new Map<string, Availability>();\n const evaluate = (id: string): Availability => {\n const spec = registry.get(id);\n if (spec === undefined) return \"unknown\";\n return spec.probe() ? \"available\" : \"missing\";\n };\n\n let requiredAllAvailable = true;\n for (const id of options.required) {\n const a = evaluate(id);\n availability.set(id, a);\n if (a !== \"available\") requiredAllAvailable = false;\n }\n let optionalAllAvailable = true;\n for (const id of options.optional ?? []) {\n const a = evaluate(id);\n availability.set(id, a);\n if (a !== \"available\") optionalAllAvailable = false;\n }\n\n const readiness: Readiness = !requiredAllAvailable ? \"idle\" : (optionalAllAvailable ? \"ready\" : \"degraded\");\n\n // preconditions: 対象 capability のいずれかが要求する場合だけ評価する。\n const allIds = [...options.required, ...(options.optional ?? [])];\n const needsSecure = allIds.some((id) => registry.get(id)?.requiresSecureContext === true);\n const needsActivation = allIds.some((id) => registry.get(id)?.requiresUserActivation === true);\n const secureContext: PreconditionState = needsSecure ? (isSecureContext() ? \"satisfied\" : \"required\") : \"not-applicable\";\n const userActivation: PreconditionState = needsActivation ? \"required\" : \"not-applicable\";\n\n return {\n availability,\n permission: options.permission ?? \"not-applicable\",\n readiness,\n activity: options.activity ?? \"inactive\",\n preconditions: { secureContext, userActivation },\n epoch: options.epoch ?? 0,\n lastError: options.lastError,\n };\n}\n\n/** availability から「required がすべて available か」を判定するヘルパ(supported の最低条件)。 */\nexport function requiredCapabilitiesAvailable(assessment: PlatformAssessment, required: readonly string[]): boolean {\n return required.every((id) => assessment.availability.get(id) === \"available\");\n}\n","/**\n * fetchCapabilities.ts\n *\n * fetch node 固有の capability registry と error code。汎用の assess 機構・型は\n * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から\n * import する。node 固有の宣言はこのハンドライトファイルに置き、生成コピーとは分離する。\n */\n\nimport { CapabilityRegistry, CapabilitySpec } from \"./platformCapability.js\";\n\n/** 安定した fetch error code(taxonomy)。値は公開キーとして固定。 */\nexport const WCS_FETCH_ERROR_CODE = {\n CapabilityMissing: \"capability-missing\",\n InvalidArgument: \"invalid-argument\",\n Network: \"network\",\n HttpError: \"http-error\",\n Timeout: \"timeout\",\n Aborted: \"aborted\",\n} as const;\n\n/** fetch node の capability registry。文字列 ID を eval せず明示 probe を持つ。 */\nexport const FETCH_CAPABILITIES: CapabilityRegistry = new Map<string, CapabilitySpec>([\n [\"web.fetch\", { probe: () => typeof (globalThis as { fetch?: unknown }).fetch === \"function\", compatKey: \"api.fetch\" }],\n [\"web.abort-controller\", { probe: () => typeof (globalThis as { AbortController?: unknown }).AbortController === \"function\", compatKey: \"api.AbortController\" }],\n]);\n","import { IWcBindable } from \"../types.js\";\nimport { OperationLane, OperationTicket } from \"./operationLane.js\";\nimport {\n PlatformAssessment,\n WcsIoErrorInfo,\n WcsIoErrorPhase,\n assessCapabilities,\n requiredCapabilitiesAvailable,\n} from \"./platformCapability.js\";\nimport { FETCH_CAPABILITIES, WCS_FETCH_ERROR_CODE } from \"./fetchCapabilities.js\";\n\nexport type FetchResponseType = \"auto\" | \"json\" | \"text\" | \"blob\" | \"arrayBuffer\";\n\nexport interface FetchRequestOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit | null;\n contentType?: string | null;\n forceText?: boolean;\n // How to read the response body. \"auto\" (default) sniffs Content-Type (JSON or\n // text). \"blob\"/\"arrayBuffer\" enable binary downloads; \"blob\" additionally\n // publishes a managed `objectURL`. `forceText` (HTML-replace mode) takes\n // priority over this.\n responseType?: FetchResponseType;\n // Request timeout in ms. When elapsed, the request lane claims a `timeout`\n // terminal, commits a `{ name: \"TimeoutError\" }` error envelope (guarded), then\n // aborts the native request (async-execution-model.md §7 / 09 §5.1). Absent or\n // <= 0 → no timeout (unchanged behaviour, the default).\n timeout?: number;\n}\n\nexport class FetchCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"value\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.value },\n { name: \"loading\", event: \"wcs-fetch:loading-changed\", semantics: \"state\" },\n { name: \"error\", event: \"wcs-fetch:error\", semantics: \"state\" },\n { name: \"status\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.status },\n // Managed object URL for a `responseType: \"blob\"` response (null otherwise).\n // The Core revokes the previous URL on each new response and on dispose, so\n // a consumer can bind it straight into <img src> without lifecycle glue.\n { name: \"objectURL\", event: \"wcs-fetch:response\", semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail.objectURL },\n // Serializable failure taxonomy (stable code / phase / recoverable), or null.\n // Additive bindable output — the existing `error` property/event are unchanged.\n // Fires on its own `wcs-fetch:error-info-changed` event; no getter, so the\n // bound value is the event detail (mirrors `error` / `loading`).\n { name: \"errorInfo\", event: \"wcs-fetch:error-info-changed\", semantics: \"state\" },\n ],\n inputs: [\n { name: \"url\" },\n { name: \"method\" },\n ],\n commands: [\n { name: \"fetch\", async: true },\n { name: \"abort\" },\n ],\n };\n\n private _target: EventTarget;\n private _value: any = null;\n private _loading: boolean = false;\n private _error: any = null;\n private _status: number = 0;\n private _objectURL: string | null = null;\n private _promise: Promise<any> = Promise.resolve(null);\n // Phase 4 (09-remediation-design.md §5): the request lane. `latest` policy —\n // a new fetch supersedes the in-flight one (switchMap). The lane owns the\n // per-operation AbortController, the owner generation (dispose lifecycle) and\n // the terminal CAS / CommitGuard that decide which completion may write state.\n // This replaces the ad-hoc `_gen` counter + single `_abortController`: a\n // superseded operation now fails the CommitGuard's epoch check instead of\n // relying on a coarse generation recheck, closing the \"completion racing an\n // abort commits stale state\" gap during body reads.\n private _lane = new OperationLane(\"fetch\", \"latest\", { withSignal: true });\n // SSR (§3.8): no asynchronous probe to await, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n // Phase 6 (§7.2): error taxonomy. The existing `error` property/event shape is\n // unchanged; `errorInfo` projects the serializable WcsIoErrorInfo as an additive\n // wc-bindable output (event `wcs-fetch:error-info-changed`) so DevTools / adopters\n // can classify failures without a breaking change.\n private _errorInfo: WcsIoErrorInfo | null = null;\n\n // Capability IDs (probed at call time, never at module eval / never eval'd as a\n // global path). `web.fetch` required; `web.abort-controller` optional (its\n // absence degrades to a fetch without an abort signal).\n private static readonly REQUIRED_CAPABILITIES = [\"web.fetch\"] as const;\n private static readonly OPTIONAL_CAPABILITIES = [\"web.abort-controller\"] as const;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). Fetch is command-driven with no subscription to\n // establish, so observe() is an idempotent no-op that resolves once ready;\n // dispose() invalidates any in-flight request and aborts it.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n // world generation bump (§4.1): invalidates + aborts every in-flight request.\n this._lane.disposeOwner();\n // Release any outstanding blob object URL on teardown (the other revoke point\n // is _setResponse, which drops the previous URL when a new response arrives).\n if (this._objectURL !== null) {\n this._revokeObjectURL(this._objectURL);\n this._objectURL = null;\n }\n }\n\n get value(): any {\n return this._value;\n }\n\n get loading(): boolean {\n return this._loading;\n }\n\n get error(): any {\n return this._error;\n }\n\n get status(): number {\n return this._status;\n }\n\n get objectURL(): string | null {\n return this._objectURL;\n }\n\n get promise(): Promise<any> {\n return this._promise;\n }\n\n /**\n * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /\n * `recoverable` / `capabilityId`), or null. Exposed as an additive wc-bindable\n * property (event `wcs-fetch:error-info-changed`); the existing `error`\n * property/event are unchanged.\n */\n get errorInfo(): WcsIoErrorInfo | null {\n return this._errorInfo;\n }\n\n /**\n * Whether the required platform capabilities (`web.fetch`) are available right\n * now — the minimal \"supported\" signal, decided by call-time feature detection,\n * not User-Agent. Additive.\n */\n get supported(): boolean {\n return requiredCapabilitiesAvailable(this.platformAssessment, FetchCore.REQUIRED_CAPABILITIES);\n }\n\n /**\n * Full platform assessment (availability / readiness / preconditions), probed\n * at call time. `readiness` is `degraded` when only the optional\n * `web.abort-controller` is missing. Dev / sidecar view.\n */\n get platformAssessment(): PlatformAssessment {\n return assessCapabilities(FETCH_CAPABILITIES, {\n required: FetchCore.REQUIRED_CAPABILITIES,\n optional: FetchCore.OPTIONAL_CAPABILITIES,\n activity: this._loading ? \"active\" : \"inactive\",\n lastError: this._errorInfo ?? undefined,\n });\n }\n\n private _setErrorInfo(code: string, phase: WcsIoErrorPhase, recoverable: boolean, message: string, capabilityId?: string): void {\n this._commitErrorInfo({ code, phase, recoverable, message, ...(capabilityId === undefined ? {} : { capabilityId }) });\n }\n\n // Single mutation point for `errorInfo`, mirroring `_setError`'s same-value guard\n // and event dispatch so the additive `errorInfo` wc-bindable property stays in sync\n // with `error`. Each failure builds a fresh object (reference guard passes); the\n // clear path passes null (suppresses a redundant null→null per successful fetch).\n private _commitErrorInfo(info: WcsIoErrorInfo | null): void {\n if (this._errorInfo === info) return;\n this._errorInfo = info;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:error-info-changed\", {\n detail: info,\n bubbles: true,\n }));\n }\n\n private _setLoading(loading: boolean): void {\n this._loading = loading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:loading-changed\", {\n detail: loading,\n bubbles: true,\n }));\n }\n\n private _setError(error: any): void {\n // Same-value guard (async-io-node-guidelines.md §3.3). `error` is state-ish,\n // so suppressing redundant null→null dispatches (every fetch start clears a\n // usually-already-null error) avoids a spurious wcs-fetch:error per successful\n // request. Reference identity is sufficient: each failure builds a fresh\n // object, and the clear path always passes null.\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n private _setResponse(value: any, status: number, objectURL: string | null = null): void {\n // Revoke the previous blob object URL before replacing it. Any new response\n // (success, HTTP error, or network error all funnel through here) supersedes\n // the prior one, so the old URL is no longer needed; this plus dispose()\n // revocation keeps blob downloads leak-free.\n if (this._objectURL !== null) {\n this._revokeObjectURL(this._objectURL);\n }\n this._objectURL = objectURL;\n this._value = value;\n this._status = status;\n this._target.dispatchEvent(new CustomEvent(\"wcs-fetch:response\", {\n detail: { value, status, objectURL },\n bubbles: true,\n }));\n }\n\n // Object URL lifecycle for responseType: \"blob\". The Core owns the blob's\n // object URL (mirrors RecorderCore) so a consumer can bind `objectURL` straight\n // into <img src>/<a href> without managing createObjectURL/revokeObjectURL. Both\n // helpers tolerate environments without URL.createObjectURL (SSR / headless).\n private _createObjectURL(blob: Blob): string | null {\n if (typeof URL !== \"undefined\" && typeof URL.createObjectURL === \"function\") {\n return URL.createObjectURL(blob);\n }\n return null;\n }\n\n private _revokeObjectURL(url: string): void {\n if (typeof URL !== \"undefined\" && typeof URL.revokeObjectURL === \"function\") {\n URL.revokeObjectURL(url);\n }\n }\n\n abort(): void {\n // Explicit user cancel: abort the active operation WITHOUT advancing the lane\n // epoch, so the aborted operation stays eligible and its AbortError branch may\n // commit loading=false (leaving the in-flight value/status). A superseding\n // fetch() instead advances the epoch (via the lane's begin()), which makes the\n // predecessor ineligible so its abort commits nothing (loading does not flicker).\n this._lane.abortActive();\n }\n\n // Run one guarded commit step (§5.1). The CommitGuard is re-checked before every\n // setter because a setter that synchronously dispatches an event can supersede\n // the same lane; an invalidation between setters stops the remaining commits\n // without rolling back what already fired.\n private _commitStep(ticket: OperationTicket, step: () => void): void {\n if (this._lane.canCommit(ticket)) {\n step();\n }\n }\n\n async fetch(url: string, options: FetchRequestOptions = {}): Promise<any> {\n // never-throw (§3.6): 引数バリデーション失敗は例外ではなく error プロパティに\n // 流し、サニタイズ値(null)を返す。command-token 経路からの呼び出しが unhandled\n // rejection にならず、「fetch() は全終了ケースで resolve」契約とも整合する。\n if (!url) {\n // Existing `error` shape is unchanged (§7.2 / 07 §互換性); the taxonomy is\n // projected only through the additive `errorInfo`.\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.InvalidArgument, \"start\", false, \"url attribute is required.\");\n this._setError({ message: \"url attribute is required.\" });\n return null;\n }\n\n // Phase 6 (§7.2): probe required capabilities just before starting. If the\n // `web.fetch` API is absent (SSR / headless / very old runtime), do NOT start\n // the operation — surface a stable `capability-missing` taxonomy without\n // attempting the call (and without the generic network-error path).\n const assessment = this.platformAssessment;\n if (!requiredCapabilitiesAvailable(assessment, FetchCore.REQUIRED_CAPABILITIES)) {\n const missing = FetchCore.REQUIRED_CAPABILITIES.find((id) => assessment.availability.get(id) !== \"available\");\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.CapabilityMissing, \"start\", false, `Required capability \"${missing}\" is unavailable.`, missing);\n this._setError({ message: `Required capability \"${missing}\" is unavailable.` });\n return null;\n }\n\n const p = this._doFetch(url, options);\n this._promise = p;\n return p;\n }\n\n private async _doFetch(url: string, options: FetchRequestOptions): Promise<any> {\n // Issue a lane ticket. For the `latest` policy this advances the epoch and\n // aborts the previous in-flight request (supersede), returning a ticket +\n // attempt whose `signal` is the lane-owned AbortController for this operation.\n // `attempt.signal` is undefined when `web.abort-controller` is missing\n // (degraded): the request runs without a native abort signal.\n const started = this._lane.begin();\n // `latest` begin never returns null (exhaust is the only rejecting policy).\n const { ticket, attempt } = started!;\n const signal = attempt.signal;\n\n this._commitStep(ticket, () => this._setLoading(true));\n this._commitStep(ticket, () => { this._commitErrorInfo(null); this._setError(null); });\n\n const {\n method = \"GET\",\n body = null,\n contentType = null,\n forceText = false,\n responseType = \"auto\",\n timeout = 0,\n } = options;\n\n // Timeout terminal (§5.1 / §7): a timer claims the `timeout` outcome via the\n // same terminal CAS as success/error, commits a guarded TimeoutError, THEN\n // aborts the native request and releases the lane — never \"invalidate first\".\n // A completion that arrives after the timer loses the CAS and writes nothing.\n let timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n if (timeout > 0) {\n timeoutTimer = setTimeout(() => {\n if (!this._lane.claimTerminal(ticket, \"timeout\")) return;\n const message = `Request timed out after ${timeout}ms.`;\n this._commitStep(ticket, () => {\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.Timeout, \"execute\", true, message);\n this._setError({ name: \"TimeoutError\", message });\n });\n this._commitStep(ticket, () => this._setResponse(null, 0));\n this._commitStep(ticket, () => this._setLoading(false));\n this._lane.abort(ticket);\n this._lane.finalize(ticket);\n }, timeout);\n }\n\n // Copy the caller's headers so the contentType injection below never mutates\n // the object passed in by a headless consumer (the Shell already builds a\n // fresh object, but direct FetchCore users may reuse theirs).\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n\n try {\n if (contentType && !headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = contentType;\n }\n\n const requestInit: RequestInit = {\n method,\n headers,\n signal,\n };\n\n if (method !== \"GET\" && method !== \"HEAD\" && body !== null) {\n requestInit.body = body;\n }\n\n const response = await globalThis.fetch(url, requestInit);\n\n // Read the body first, then atomically claim the terminal at the commit\n // point. Claiming AFTER the body read closes the stale-write race: a fetch\n // that was superseded (or timed out) during the body read fails the\n // CommitGuard's epoch/CAS check and writes nothing, even if the body still\n // resolved. HEAD carries no body by spec.\n let value: any = null;\n if (method === \"HEAD\") {\n // HEAD responses carry no body — reading it would throw a parse error.\n } else if (!response.ok) {\n // HTTP error: read the body text for the error envelope. Handled below.\n } else if (forceText) {\n // HTML-replace mode (the Shell sets forceText when `target` is present)\n // always reads text and takes priority over responseType.\n value = await response.text();\n } else if (responseType === \"blob\") {\n // Only buffer the Blob here; the managed object URL is created AFTER the\n // terminal claim wins (below). Creating it before the claim would leak a\n // blob: URL when this operation loses the claim (supersede / timeout /\n // dispose during the body read) — it would never reach _setResponse and\n // never be revoked.\n value = await response.blob();\n } else if (responseType === \"arrayBuffer\") {\n value = await response.arrayBuffer();\n } else if (responseType === \"text\") {\n value = await response.text();\n } else if (responseType === \"json\") {\n value = await response.json();\n } else {\n // \"auto\" (default): sniff Content-Type — JSON when it says so, else text.\n const responseContentType = response.headers.get(\"Content-Type\") || \"\";\n if (responseContentType.includes(\"application/json\")) {\n value = await response.json();\n } else {\n value = await response.text();\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const error = { status: response.status, statusText: response.statusText, body: errorBody };\n if (!this._lane.claimTerminal(ticket, \"error\")) {\n return null;\n }\n this._commitStep(ticket, () => {\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.HttpError, \"execute\", true, `HTTP ${response.status} ${response.statusText}`);\n this._setError(error);\n });\n // Notify `status` observers on HTTP errors too. The `status` property is\n // surfaced via the `wcs-fetch:response` event (getter reads detail.status),\n // so without dispatching it here a bind() subscriber would never see the\n // error status (404, 500, ...). `value` is reset to null on error.\n this._commitStep(ticket, () => this._setResponse(null, response.status));\n this._commitStep(ticket, () => this._setLoading(false));\n return null;\n }\n\n if (!this._lane.claimTerminal(ticket, \"success\")) {\n return null;\n }\n // Create the blob object URL only now that this operation owns the terminal,\n // so a dropped operation never allocates one (leak-free). HEAD/non-blob keep\n // value non-Blob → objectURL stays null.\n const objectURL = value instanceof Blob ? this._createObjectURL(value) : null;\n this._commitStep(ticket, () => this._setResponse(value, response.status, objectURL));\n this._commitStep(ticket, () => this._setLoading(false));\n return this._value;\n } catch (e: any) {\n if (e && e.name === \"AbortError\") {\n // AbortError with a still-eligible ticket is an explicit user abort() of\n // the current request: claim the `aborted` terminal and clear loading,\n // leaving the in-flight value/status untouched. A superseding fetch or\n // dispose() advanced the epoch / owner generation, so their predecessors\n // fail the claim (return without writing = stale-drop). A timeout already\n // claimed the terminal in its timer, so this branch also no-ops there.\n if (this._lane.claimTerminal(ticket, \"aborted\")) {\n this._commitStep(ticket, () => this._setLoading(false));\n }\n return null;\n }\n // Network error. A superseded/disposed request fails the claim and drops.\n if (!this._lane.claimTerminal(ticket, \"error\")) {\n return null;\n }\n this._commitStep(ticket, () => {\n const message = String(e?.message ?? \"Network request failed.\");\n this._setErrorInfo(WCS_FETCH_ERROR_CODE.Network, \"execute\", true, message);\n // Coalesce a falsy rejection (Promise.reject(null)/throw null) to a non-null\n // envelope so the `error` same-value guard (cleared to null at start) cannot\n // suppress a genuine terminal error — keeping `error`/`wcs-fetch:error` in sync\n // with `errorInfo`. Truthy errors (real TypeErrors) pass through unchanged.\n this._setError(e ?? { message });\n });\n // Reset value/status on network errors too, mirroring the HTTP-error path.\n // Without this, a prior successful request's value/status would linger while\n // `error` is non-null. status=0 is the web-platform convention for \"no HTTP\n // response\" (matches XMLHttpRequest.status on network failure).\n this._commitStep(ticket, () => this._setResponse(null, 0));\n this._commitStep(ticket, () => this._setLoading(false));\n return null;\n } finally {\n if (timeoutTimer !== null) {\n clearTimeout(timeoutTimer);\n }\n // Release the operation (identity-safe: keyed by operationId, so a\n // late-settling superseded request never disarms the successor). Idempotent\n // with the timeout timer's own finalize().\n this._lane.finalize(ticket);\n }\n }\n}\n","import { config } from \"./config.js\";\nimport type { Fetch } from \"./components/Fetch.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const fetchId = triggerElement.getAttribute(config.triggerAttribute);\n if (!fetchId) return;\n\n // Resolve the registered constructor at call time instead of importing Fetch\n // as a value. The value import created a components/Fetch.ts ⇄ autoTrigger.ts\n // cycle (Fetch.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-fetch> class matches — without the import cycle.\n const FetchCtor = customElements.get(config.tagNames.fetch);\n const el = document.getElementById(fetchId);\n if (!FetchCtor || !(el instanceof FetchCtor)) return;\n const fetchElement = el as Fetch;\n\n // Skip when the target has no url. fetch() is fire-and-forget here (its returned\n // promise is intentionally not awaited), and FetchCore.fetch() rejects synchronously\n // on an empty url. Without this guard that rejection would surface as an unhandled\n // promise rejection. Treat a url-less target as \"nothing to do\", consistent with the\n // other early returns above.\n if (!fetchElement.url) return;\n\n // Suppress the element's default action so a fetch can fire without navigating.\n // Intentional: do not attach data-fetchtarget to an element whose default action\n // you also want (real <a href> link, form-submit button) — it will be cancelled.\n // See README \"Optional DOM Triggering\".\n event.preventDefault();\n fetchElement.fetch();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/upgrade-properties.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// custom element の property upgrade — `static wcBindable.inputs` に宣言した入力のうち、\n// 要素が upgrade される前に代入された own データプロパティを取り込み直す。\n//\n// なぜ必要か:\n// 未定義タグの要素は素の HTMLElement なので、`el.url = \"...\"` は own データプロパティを作る。\n// upgrade 後にクラスの accessor が prototype へ入っても own プロパティが優先されるため、\n// setter は二度と呼ばれず、値は要素へ届かないまま消える(エラーも警告も出ない)。\n// 常にプロパティ代入を行う framework(Angular の `[prop]`、Lit の `.prop=`、\n// Solid の `prop:`、Vue の `.prop` 修飾子)× 遅延定義(autoloader / CDN / code-split)で\n// 常態的に起きる。docs/architecture-hardening/13-framework-adapter-binding-constraints.md §1.2。\n//\n// 安全側の判定:\n// own プロパティがあっても、prototype チェーンに accessor が無ければ「シャドウ」ではなく\n// その own プロパティ自体が正規の格納先なので触らない(public class field を壊さない)。\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/upgrade-properties.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/upgradeProperties.ts). Those copies are generated — do not edit them.\nimport { IWcBindable } from \"./wcBindable.js\";\n\nfunction hasAccessorOnPrototype(target: object, name: string): boolean {\n let proto = Object.getPrototypeOf(target);\n while (proto !== null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name);\n if (descriptor !== undefined) {\n return typeof descriptor.get === \"function\" || typeof descriptor.set === \"function\";\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n}\n\n/**\n * `connectedCallback` の先頭で呼ぶ。宣言済み input のうち upgrade 前の代入で\n * accessor をシャドウしている own プロパティを、delete → 再代入で setter に通し直す。\n *\n * - 冪等: 再代入は accessor を通るので own プロパティは残らず、2 回目以降は no-op。\n * - 宣言に `inputs` が無い要素、`wcBindable` を持たない要素では何もしない。\n * - 値の意味は変えない。今まで捨てられていた代入が届くようになる一方向の変化。\n */\nexport function upgradeProperties(element: object): void {\n const declaration = (element as { constructor?: { wcBindable?: IWcBindable } }).constructor?.wcBindable;\n const inputs = declaration?.inputs;\n if (inputs === undefined) return;\n for (const input of inputs) {\n const name = input.name;\n if (!Object.prototype.hasOwnProperty.call(element, name)) continue;\n if (!hasAccessorOnPrototype(element, name)) continue;\n const record = element as Record<string, unknown>;\n const value = record[name];\n delete record[name];\n record[name] = value;\n }\n}\n","/**\n * Trusted Types (`require-trusted-types-for 'script'`) 対応。正本は docs/csp.md §7。\n *\n * `<wcs-fetch target=\"...\">` の HTML 置換モードが innerHTML に流すのは **レスポンス**\n * = TT がまさに止めたい値そのもの。ここに identity policy を噛ませて通すのは\n * 「TT 対応」ではなく「TT の無効化」なので、fetch は自前の policy を作らない。\n * Angular が DomSanitizer を必須にしているのと同じ立て付けで、利用側が sanitizer を\n * 持つ policy を注入したときだけ通す。\n *\n * 注入口は全 @wcstack パッケージ共通のグローバルスロット。buildless(CDN 一発)でも\n * inline script 1 本で差し込める:\n *\n * ```js\n * globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\n * trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\n * ```\n *\n * policy があるときは TT 非対応ブラウザでも通す。sanitizer が Chromium でだけ効いて\n * Firefox では素通し、という差が出るほうが危ないため。\n */\n\nexport interface IWcsTrustedTypesPolicy {\n createHTML?(input: string): unknown;\n createScriptURL?(input: string): unknown;\n}\n\n/** 利用側が policy を差し込むグローバルスロット(全 @wcstack パッケージ共通)。 */\nexport const TRUSTED_TYPES_POLICY_SLOT = Symbol.for(\"wcstack.trustedTypes.policy\");\n\ntype SymbolSlotHolder = { [key: symbol]: unknown };\n\n/** 利用側が注入した policy。fetch は identity policy にフォールバックしない。 */\nexport function getTrustedTypesPolicy(): IWcsTrustedTypesPolicy | null {\n const value = (globalThis as SymbolSlotHolder)[TRUSTED_TYPES_POLICY_SLOT];\n if (value === null || typeof value !== \"object\") return null;\n return value as IWcsTrustedTypesPolicy;\n}\n\n/** 利用側 policy を設定する(`null` で解除)。 */\nexport function setTrustedTypesPolicy(policy: IWcsTrustedTypesPolicy | null): void {\n (globalThis as SymbolSlotHolder)[TRUSTED_TYPES_POLICY_SLOT] = policy;\n}\n\n/**\n * レスポンスを利用側 policy に通す。policy が無ければ素通し= TT 有効下では\n * ブラウザが弾く(意図どおり)。\n */\nexport function trustHtmlValue(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n const policy = getTrustedTypesPolicy();\n const createHTML = policy?.createHTML;\n if (typeof createHTML !== \"function\") return value;\n return createHTML.call(policy, value);\n}\n\nlet _enforced: boolean | undefined = undefined;\nlet _reported = false;\n\n/** テスト用: 実測キャッシュと一度きりの診断をリセットする。 */\nexport function _resetTrustedTypesDiagnostics(): void {\n _enforced = undefined;\n _reported = false;\n}\n\n/**\n * TT が実際に強制されているかを実測する。エラーメッセージの文言に依存しないよう、\n * 使い捨ての要素へ実際に書いて確かめる。`default` policy がある場合は書き込みが\n * 通る=我々の書き込みも通るので、正しく false になる。\n */\nexport function isTrustedTypesEnforced(): boolean {\n if (_enforced !== undefined) return _enforced;\n if (!(\"trustedTypes\" in globalThis)) {\n _enforced = false;\n return _enforced;\n }\n try {\n document.createElement(\"div\").innerHTML = \"<i></i>\";\n _enforced = false;\n } catch {\n _enforced = true;\n }\n return _enforced;\n}\n\n// 呼び出し元(writeTargetHTML)が isTrustedTypesEnforced() を確認してから呼ぶ。\nfunction reportTrustedTypesBlock(): void {\n if (_reported) return;\n _reported = true;\n const hasPolicy = typeof getTrustedTypesPolicy()?.createHTML === \"function\";\n const cause = hasPolicy\n ? \"The injected policy's createHTML() did not return a TrustedHTML.\"\n : \"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass \"\n + \"responses through an identity policy — that would defeat the CSP.\";\n console.error(\n `[@wcstack/fetch] The \"target\" HTML replace mode was blocked by Trusted Types `\n + `(require-trusted-types-for 'script'). ${cause}\\n`\n + `Install a sanitizing policy before the first fetch:\\n`\n + ` globalThis[Symbol.for(\"wcstack.trustedTypes.policy\")] =\\n`\n + ` trustedTypes.createPolicy(\"my-app\", { createHTML: (s) => DOMPurify.sanitize(s) });\\n`\n + `Or drop \"target\" and bind the response through @wcstack/state. See docs/csp.md section 7.`,\n );\n}\n\n/**\n * HTML 置換モードの書き込み。\n *\n * TT に弾かれたときは直し方を 1 度だけ報告して**投げ返さない**(never-throw §3.6)。\n * 自動 fetch 経路(connect / url 変更 / trigger)は `fetch()` の rejection を受け取る先が\n * 無く、投げ返すと未処理 rejection として page error になる — 実 Chromium の e2e で\n * 確認した。報告が信号であり、黙って握り潰すのとは違う。TT 以外の失敗(innerHTML の\n * setter が別の理由で throw した等)は従来どおり呼び出し元へ投げ返す。\n */\nexport function writeTargetHTML(element: Element, html: unknown): void {\n try {\n element.innerHTML = trustHtmlValue(html) as string;\n } catch (error) {\n if (isTrustedTypesEnforced()) {\n reportTrustedTypesBlock();\n return;\n }\n throw error;\n }\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { FetchCore, FetchResponseType } from \"../core/FetchCore.js\";\nimport { WcsIoErrorInfo } from \"../core/platformCapability.js\";\nimport { FetchHeader } from \"./FetchHeader.js\";\nimport { FetchBody } from \"./FetchBody.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\nimport { upgradeProperties } from \"../protocol/upgradeProperties.js\";\nimport { writeTargetHTML } from \"../trustedTypes.js\";\n\nexport class Fetch extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...FetchCore.wcBindable,\n properties: [\n ...FetchCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-fetch:trigger-changed\", semantics: \"state\" },\n ],\n // Shell-level input surface. The Core declares only the portable `url` / `method`;\n // the Shell adds the DOM-driven settable surface. No `attribute` hints are given:\n // these setters already reflect to their attributes themselves, so a binding system\n // that mirrors inputs[].attribute would set the attribute twice. `commands`\n // (fetch / abort) are inherited unchanged from the Core via the spread above.\n inputs: [\n { name: \"url\" },\n { name: \"method\" },\n { name: \"target\" },\n { name: \"manual\" },\n { name: \"body\" },\n { name: \"responseType\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"url\"]; }\n\n private _core: FetchCore;\n private _body: any = null;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n // Auto-fetch coalescing state (see _scheduleAutoFetch).\n private _autoPending: boolean = false;\n private _connectResolve: (() => void) | null = null;\n private _lastFetchedUrl: string | null = null;\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n // State reflection is wired BEFORE the Core is constructed (canonical\n // order): a Core that dispatches synchronously from its constructor\n // (e.g. speech's unsupported-changed) would otherwise fire before the\n // listeners exist. FetchCore doesn't do that, so this is equivalent here,\n // but every Shell keeps the same order.\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-fetch:loading-changed\": (d) => ({ loading: d === true }),\n \"wcs-fetch:error\": (d) => ({ error: d != null }),\n });\n this._core = new FetchCore(this);\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // Input setters normalize null/undefined to attribute removal instead of\n // letting setAttribute stringify them (\"undefined\" url would auto-fetch\n // /undefined, \"undefined\" method is an invalid HTTP method). The binder\n // already skips undefined writes; this guards direct JS assignment too.\n get url(): string {\n return this.getAttribute(\"url\") || \"\";\n }\n\n set url(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"url\");\n } else {\n this.setAttribute(\"url\", value);\n }\n }\n\n get method(): string {\n return (this.getAttribute(\"method\") || \"GET\").toUpperCase();\n }\n\n set method(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"method\");\n } else {\n this.setAttribute(\"method\", value);\n }\n }\n\n get target(): string | null {\n return this.getAttribute(\"target\");\n }\n\n set target(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"target\");\n } else {\n this.setAttribute(\"target\", value);\n }\n }\n\n // Response body interpretation. Backed by the `response-type` attribute so it is\n // settable from HTML, JS, or a binding. An unknown value falls through to the\n // Core's \"auto\" branch. `target` (HTML-replace mode) overrides this.\n get responseType(): FetchResponseType {\n return (this.getAttribute(\"response-type\") as FetchResponseType) || \"auto\";\n }\n\n set responseType(value: string | null) {\n if (value == null) {\n this.removeAttribute(\"response-type\");\n } else {\n this.setAttribute(\"response-type\", value);\n }\n }\n\n get value(): any {\n return this._core.value;\n }\n\n get loading(): boolean {\n return this._core.loading;\n }\n\n get error(): any {\n return this._core.error;\n }\n\n get status(): number {\n return this._core.status;\n }\n\n get objectURL(): string | null {\n return this._core.objectURL;\n }\n\n get errorInfo(): WcsIoErrorInfo | null {\n return this._core.errorInfo;\n }\n\n get promise(): Promise<any> {\n return this._core.promise;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get body(): any {\n return this._body;\n }\n\n set body(value: any) {\n // Normalize undefined to null: _collectBody treats \"!== null\" as \"body was\n // provided\", so a raw undefined would serialize as a JSON request body.\n this._body = value ?? null;\n }\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n const v = !!value;\n if (v) {\n // Skip when url is empty. fetch() is fire-and-forget here (its returned\n // promise is intentionally only chained with .finally() to reset the flag,\n // never .catch()'d), and FetchCore.fetch() rejects on an empty url. Without\n // this guard that rejection — re-thrown by .finally() — surfaces as an\n // unhandled promise rejection. Mirrors the url-less guard in autoTrigger.\n //\n // Leave `_trigger` false (do not set it) and emit no event: nothing ran, so\n // surfacing a `wcs-fetch:trigger-changed` \"completion\" would lie to observers.\n // Keeping the flag false also avoids stalling — once url is provided, writing\n // `true` again is a real false→true transition that triggers the fetch.\n if (!this.url) return;\n this._trigger = true;\n this.fetch().finally(() => {\n this._trigger = false;\n this.dispatchEvent(new CustomEvent(\"wcs-fetch:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n });\n }\n }\n\n private _collectHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const headerElements = this.querySelectorAll<FetchHeader>(config.tagNames.fetchHeader);\n for (const el of headerElements) {\n const name = el.headerName;\n const value = el.headerValue;\n if (name) {\n headers[name] = value;\n }\n }\n return headers;\n }\n\n // fetch がネイティブに扱える BodyInit か判定する。これらは JSON.stringify せず\n // 素通しし、Content-Type をブラウザに委ねる (FormData の multipart boundary、\n // Blob の type、URLSearchParams の application/x-www-form-urlencoded を自動付与\n // させるため、_collectBody は contentType に null を返す)。ReadableStream は\n // RequestInit.duplex: 'half' を要するため初版では対象外とし、従来どおり扱う。\n private _isNativeBodyInit(value: unknown): value is BodyInit {\n return value instanceof Blob // File は Blob のサブクラス\n || value instanceof FormData\n || value instanceof URLSearchParams\n || value instanceof ArrayBuffer\n || ArrayBuffer.isView(value); // TypedArray / DataView\n }\n\n private _collectBody(bodySnapshot: any): { body: BodyInit | null; contentType: string | null } {\n // JS API経由のbodyが優先\n if (bodySnapshot !== null) {\n // 文字列はそのまま。Content-Type はユーザーのヘッダ指定に委ねる。\n if (typeof bodySnapshot === \"string\") {\n return { body: bodySnapshot, contentType: null };\n }\n // ネイティブ BodyInit (Blob/File/FormData/URLSearchParams/ArrayBuffer/TypedArray)\n // は素通し。Content-Type はブラウザに委ねるため null を返す。\n if (this._isNativeBodyInit(bodySnapshot)) {\n return { body: bodySnapshot, contentType: null };\n }\n // それ以外のオブジェクトは JSON 化する。\n return { body: JSON.stringify(bodySnapshot), contentType: \"application/json\" };\n }\n\n // サブタグからbodyを取得\n const bodyElement = this.querySelector<FetchBody>(config.tagNames.fetchBody);\n if (bodyElement) {\n return {\n body: bodyElement.bodyContent || null,\n contentType: bodyElement.contentType,\n };\n }\n\n return { body: null, contentType: null };\n }\n\n abort(): void {\n this._core.abort();\n }\n\n /**\n * Coalesce auto-fetch requests in the current task into a single microtask.\n *\n * Multiple synchronous input writes in the same tick — e.g. a `...` spread\n * writing `url` before `manual` — collapse into one decision made against the\n * FINAL element state, so the spread application order can no longer trigger a\n * stray fetch. The microtask re-reads `isConnected` / `manual` / `url` at fire\n * time; whatever was written last wins.\n *\n * Only the implicit auto-fetch (url attribute change, connect-time) is routed\n * here. Explicit triggers — the `trigger` setter, the `fetch` command, and\n * autoTrigger (data-fetchtarget clicks) — must fire immediately and stay on\n * their own synchronous paths.\n *\n * The connect-time promise (connectedCallbackPromise) is resolved here in\n * EVERY exit path, including the no-fetch branch, so awaiting it never hangs\n * when the final state turns out to be manual / url-less / disconnected.\n */\n private _scheduleAutoFetch(): void {\n if (this._autoPending) {\n return;\n }\n this._autoPending = true;\n queueMicrotask(() => {\n this._autoPending = false;\n const resolveConnect = this._connectResolve;\n this._connectResolve = null;\n const url = this.url;\n // Same-value guard (Phase 4): skip a redundant auto-fetch for the url we\n // last fetched. A spread re-evaluation rewrites every input each cycle, so\n // the `url` setter calls setAttribute with an unchanged value and fires\n // attributeChangedCallback again; without this guard an unrelated state\n // change would refetch. Auto-path only — explicit fetch()/trigger/command\n // stay unconditional (a manual refresh of the same url must work), and\n // `_lastFetchedUrl` is reset on disconnect so a remount refetches.\n if (this.isConnected && !this.manual && url && url !== this._lastFetchedUrl) {\n // fetch() cannot reject here: FetchCore swallows network/HTTP errors and\n // only rejects on an empty url, which the `url` guard above rules out.\n this.fetch().finally(() => resolveConnect?.());\n } else {\n resolveConnect?.();\n }\n });\n }\n\n async fetch(): Promise<any> {\n // Record the url for the auto-fetch same-value guard. Every fetch (explicit\n // included) updates it so a later auto-write of the same url is treated as a\n // no-op rather than a duplicate request.\n this._lastFetchedUrl = this.url;\n const headers = this._collectHeaders();\n\n // Snapshot and reset `body` synchronously, before any await. The body is a\n // one-shot input; resetting it after the await (when another caller may have\n // already set a new body for the next request) would silently drop that value.\n const bodySnapshot = this._body;\n this._body = null;\n const { body, contentType } = this._collectBody(bodySnapshot);\n\n // FormData に手動で Content-Type を付けると、ブラウザが付与するはずの multipart\n // boundary が失われてサーバー側でパースできなくなる。ヘッダはユーザー指定を\n // 尊重して素通しするが、この典型的な誤設定は警告する。\n if (body instanceof FormData &&\n Object.keys(headers).some((name) => name.toLowerCase() === \"content-type\")) {\n console.warn(\n \"[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. \" +\n \"This drops the multipart boundary the browser adds automatically; remove the \" +\n \"Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.\",\n );\n }\n\n const result = await this._core.fetch(this.url, {\n method: this.method,\n headers,\n body,\n contentType,\n forceText: !!this.target,\n responseType: this.responseType,\n });\n\n // HTML置換モード\n // Security: the response is injected as raw innerHTML without sanitization.\n // This is an opt-in convenience for trusted fragments only; the primary,\n // recommended path is state-driven binding via @wcstack/state. Do not point\n // `target` at an untrusted endpoint (XSS risk). See README \"HTML Replace Mode\".\n //\n // Under Trusted Types this is the one sink in wcstack whose input is remote\n // data, so it is routed through an *adopter-supplied* sanitizing policy only —\n // fetch never signs the response with an identity policy (docs/csp.md §7).\n if (this.target && result !== null) {\n const targetElement = document.getElementById(this.target);\n if (targetElement) {\n writeTargetHTML(targetElement, result);\n }\n }\n\n return result;\n }\n\n attributeChangedCallback(name: string, _oldValue: string | null, _newValue: string | null): void {\n // Re-fetch on url changes, but intentionally do NOT update\n // `_connectedCallbackPromise`. Per the wc-bindable connectedCallbackPromise\n // protocol that promise represents the one-shot \"connect-time initialization\n // is done\" signal; it resolves once and is not re-armed for later url-driven\n // requests. Await `promise` if you need to track a specific re-fetch.\n //\n // Defer the decision to a microtask (see _scheduleAutoFetch) instead of\n // fetching synchronously here: a `...` spread writes `url` before `manual`,\n // so a synchronous fetch would fire before `manual` is applied. The final\n // state (isConnected / manual / url) is re-read at microtask time.\n if (name === \"url\") {\n this._scheduleAutoFetch();\n }\n }\n\n connectedCallback(): void {\n // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)\n upgradeProperties(this);\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Only the initial connect-time fetch is tracked by connectedCallbackPromise.\n // Arm a deferred here when an auto-fetch looks likely; the scheduled\n // microtask resolves it (in every exit path, so awaiting never hangs). The\n // actual fetch decision is re-evaluated at microtask time against the final\n // state, so a spread that sets `manual` after `url` still suppresses it.\n if (!this.manual && this.url) {\n this._connectedCallbackPromise = new Promise<void>((resolve) => {\n this._connectResolve = resolve;\n });\n }\n this._scheduleAutoFetch();\n }\n\n disconnectedCallback(): void {\n this.abort();\n // Reset the same-value guard so a remount (reconnect with the same url)\n // refetches rather than being skipped as a duplicate.\n this._lastFetchedUrl = null;\n // Resolve any armed connect-time deferred before detaching. A synchronous\n // remove()→append() before the scheduled microtask fires would otherwise let\n // the second connectedCallback overwrite _connectResolve, orphaning the first\n // deferred and hanging any caller that already awaited connectedCallbackPromise.\n // Disconnection makes connect-time init moot, so resolving (never hanging) is\n // correct; the pending microtask then sees _connectResolve === null and no-ops.\n this._connectResolve?.();\n this._connectResolve = null;\n }\n}\n","export class FetchHeader extends HTMLElement {\n connectedCallback(): void {\n this.style.display = \"none\";\n }\n\n get headerName(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n get headerValue(): string {\n return this.getAttribute(\"value\") || \"\";\n }\n}\n","export class FetchBody extends HTMLElement {\n constructor() {\n super();\n // スロットなしのShadow DOMでlight DOM(bodyテキスト)の描画を抑制\n this.attachShadow({ mode: \"open\" });\n }\n\n get contentType(): string {\n return this.getAttribute(\"type\") || \"application/json\";\n }\n\n get bodyContent(): string {\n return this.textContent?.trim() || \"\";\n }\n}\n","import { Fetch } from \"./Fetch.js\";\n\nexport class InfiniteScroll extends HTMLElement {\n static get observedAttributes(): string[] {\n return [\"target\", \"root\", \"root-margin\", \"threshold\", \"disabled\"];\n }\n\n private _observer: IntersectionObserver | null = null;\n private _done: boolean = false;\n\n get target(): string {\n return this.getAttribute(\"target\") || \"\";\n }\n\n set target(value: string) {\n this.setAttribute(\"target\", value);\n }\n\n get root(): string | null {\n return this.getAttribute(\"root\");\n }\n\n set root(value: string | null) {\n if (value === null) {\n this.removeAttribute(\"root\");\n } else {\n this.setAttribute(\"root\", value);\n }\n }\n\n get rootMargin(): string {\n return this.getAttribute(\"root-margin\") || \"0px\";\n }\n\n set rootMargin(value: string) {\n this.setAttribute(\"root-margin\", value);\n }\n\n get threshold(): number {\n const value = Number(this.getAttribute(\"threshold\") ?? \"0\");\n return Number.isFinite(value) ? value : 0;\n }\n\n set threshold(value: number) {\n this.setAttribute(\"threshold\", String(value));\n }\n\n get disabled(): boolean {\n return this.hasAttribute(\"disabled\");\n }\n\n set disabled(value: boolean) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n } else {\n this.removeAttribute(\"disabled\");\n }\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n connectedCallback(): void {\n this._observe();\n }\n\n disconnectedCallback(): void {\n this._disconnectObserver();\n }\n\n attributeChangedCallback(): void {\n if (this.isConnected) {\n this._observe();\n }\n }\n\n private _observe(): void {\n this._disconnectObserver();\n\n if (this._done || this.disabled || !this.target || typeof IntersectionObserver === \"undefined\") {\n return;\n }\n\n this._observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n this._triggerFetch();\n }\n }, {\n root: this._resolveRoot(),\n rootMargin: this.rootMargin,\n threshold: this.threshold,\n });\n this._observer.observe(this);\n }\n\n private _disconnectObserver(): void {\n if (this._observer) {\n this._observer.disconnect();\n this._observer = null;\n }\n }\n\n private _resolveRoot(): Element | Document | null {\n if (!this.root) return null;\n return document.getElementById(this.root) || null;\n }\n\n private _triggerFetch(): void {\n const target = document.getElementById(this.target);\n if (!(target instanceof Fetch)) {\n return;\n }\n\n if (target.loading) {\n return;\n }\n\n target.trigger = true;\n\n if (this.once) {\n this._done = true;\n this._disconnectObserver();\n }\n }\n}","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapFetch(userConfig?: IWritableConfig, registry?: CustomElementRegistry): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents(registry);\n}\n","import { Fetch } from \"./components/Fetch.js\";\nimport { FetchHeader } from \"./components/FetchHeader.js\";\nimport { FetchBody } from \"./components/FetchBody.js\";\nimport { InfiniteScroll } from \"./components/InfiniteScroll.js\";\nimport { config } from \"./config.js\";\n\n/**\n * Register this package's tags. Pass a scoped `CustomElementRegistry` to define\n * them for a single shadow tree -- scoped registries do not inherit the global\n * one, so a tree using one needs its own definitions.\n */\nexport function registerComponents(registry: CustomElementRegistry = customElements): void {\n if (!registry.get(config.tagNames.fetch)) {\n registry.define(config.tagNames.fetch, Fetch);\n }\n if (!registry.get(config.tagNames.fetchHeader)) {\n registry.define(config.tagNames.fetchHeader, FetchHeader);\n }\n if (!registry.get(config.tagNames.fetchBody)) {\n registry.define(config.tagNames.fetchBody, FetchBody);\n }\n if (!registry.get(config.tagNames.infiniteScroll)) {\n registry.define(config.tagNames.infiniteScroll, InfiniteScroll);\n }\n}\n"],"names":["_config","triggerAttribute","tagNames","fetch","fetchHeader","fetchBody","infiniteScroll","config","OperationLane","laneKey","policy","_ownerGeneration","_latestEpoch","_nextOperationId","_activeOperationId","undefined","_activeOperationIds","Set","_queue","_inFlightCount","_terminal","Map","_claimedOutcome","_controllers","_attempts","_withSignal","_trace","constructor","options","this","withSignal","trace","ownerGeneration","inFlightCount","latestEpoch","activeOperationId","begin","supersedeEpoch","_abortController","operationId","ticket","push","add","set","attempt","_makeAttempt","type","retry","has","previous","get","attemptNo","_releaseController","canCommit","status","_isEligible","claimTerminal","outcome","claimedOutcome","finalize","delete","_advanceBookkeeping","signalOf","signal","abort","abortActive","disposeOwner","Array","from","keys","clear","length","AbortController","controller","remaining","filter","t","aborted","assessCapabilities","registry","availability","evaluate","id","spec","probe","requiredAllAvailable","required","a","optionalAllAvailable","optional","readiness","allIds","needsSecure","some","requiresSecureContext","needsActivation","requiresUserActivation","secureContext","globalThis","isSecureContext","userActivation","permission","activity","preconditions","epoch","lastError","requiredCapabilitiesAvailable","assessment","every","WCS_FETCH_ERROR_CODE","FETCH_CAPABILITIES","compatKey","FetchCore","EventTarget","static","protocol","version","properties","name","event","semantics","getter","e","detail","value","objectURL","inputs","commands","async","_target","_value","_loading","_error","_status","_objectURL","_promise","Promise","resolve","_lane","_ready","_errorInfo","target","super","ready","observe","dispose","_revokeObjectURL","loading","error","promise","errorInfo","supported","platformAssessment","REQUIRED_CAPABILITIES","OPTIONAL_CAPABILITIES","_setErrorInfo","code","phase","recoverable","message","capabilityId","_commitErrorInfo","info","dispatchEvent","CustomEvent","bubbles","_setLoading","_setError","_setResponse","_createObjectURL","blob","URL","createObjectURL","url","revokeObjectURL","_commitStep","step","missing","find","p","_doFetch","started","method","body","contentType","forceText","responseType","timeout","timeoutTimer","setTimeout","headers","requestInit","response","ok","text","arrayBuffer","json","responseContentType","includes","errorBody","catch","statusText","Blob","String","clearTimeout","registered","handleClick","Element","triggerElement","closest","fetchId","getAttribute","FetchCtor","customElements","el","document","getElementById","fetchElement","preventDefault","hasAccessorOnPrototype","proto","Object","getPrototypeOf","descriptor","getOwnPropertyDescriptor","TRUSTED_TYPES_POLICY_SLOT","Symbol","for","getTrustedTypesPolicy","_enforced","_reported","writeTargetHTML","element","html","innerHTML","createHTML","call","trustHtmlValue","createElement","isTrustedTypesEnforced","cause","console","reportTrustedTypesBlock","Fetch","HTMLElement","wcBindable","observedAttributes","_core","_body","_trigger","_connectedCallbackPromise","_autoPending","_connectResolve","_lastFetchedUrl","_internals","_initInternals","_wireStates","d","debugStates","states","attachInternals","internals","map","toStates","entries","addEventListener","debug","hasAttribute","on","toggleAttribute","removeAttribute","setAttribute","toUpperCase","connectedCallbackPromise","manual","trigger","finally","_collectHeaders","headerElements","querySelectorAll","headerName","headerValue","_isNativeBodyInit","FormData","URLSearchParams","ArrayBuffer","isView","_collectBody","bodySnapshot","JSON","stringify","bodyElement","querySelector","bodyContent","_scheduleAutoFetch","queueMicrotask","resolveConnect","isConnected","toLowerCase","warn","result","targetElement","attributeChangedCallback","_oldValue","_newValue","connectedCallback","declaration","input","prototype","hasOwnProperty","record","upgradeProperties","style","display","disconnectedCallback","FetchHeader","FetchBody","attachShadow","mode","textContent","trim","InfiniteScroll","_observer","_done","root","rootMargin","threshold","Number","isFinite","disabled","once","_observe","_disconnectObserver","IntersectionObserver","entry","isIntersecting","_triggerFetch","_resolveRoot","disconnect","define","registerComponents"],"mappings":"AAaA,MAAMA,EAA2B,CAE/BC,iBAAkB,mBAClBC,SAAU,CACRC,MAAO,YACPC,YAAa,mBACbC,UAAW,iBACXC,eAAgB,wBAwBPC,EAAkBP,QCiClBQ,EACFC,QACAC,OAEDC,iBAAmB,EACnBC,aAAe,EACfC,iBAAmB,EAEnBC,wBAAyCC,EAEhCC,oBAAsB,IAAIC,IAE1BC,OAA4B,GACrCC,eAAiB,EAERC,UAAY,IAAIC,IAEhBC,gBAAkB,IAAID,IAEtBE,aAAe,IAAIF,IAEnBG,UAAY,IAAIH,IAChBI,YACAC,OAEjB,WAAAC,CAAYlB,EAAiBC,EAAoBkB,EAAgC,CAAA,GAC/EC,KAAKpB,QAAUA,EACfoB,KAAKnB,OAASA,EACdmB,KAAKJ,YAAcG,EAAQE,aAAc,EACzCD,KAAKH,OAASE,EAAQG,KACxB,CAEA,mBAAIC,GACF,OAAOH,KAAKlB,gBACd,CAEA,iBAAIsB,GACF,OAAOJ,KAAKV,cACd,CAEA,eAAIe,GACF,OAAOL,KAAKjB,YACd,CAEA,qBAAIuB,GACF,OAAON,KAAKf,kBACd,CAMA,KAAAsB,GACE,IAAIC,EACJ,OAAQR,KAAKnB,QACX,IAAK,SAGH2B,IAAmBR,KAAKjB,k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P,KAAK6S,OACP7S,KAAKsS,OAAQ,EACbtS,KAAK+S,wBAET,EChII,IAAuD7P,GCOvD,SAA6BA,EAAkCsI,gBAC9DtI,EAAS7B,IAAI3C,EAAOL,SAASC,QAChC4E,EAASoQ,OAAO5U,EAAOL,SAASC,MAAOgP,GAEpCpK,EAAS7B,IAAI3C,EAAOL,SAASE,cAChC2E,EAASoQ,OAAO5U,EAAOL,SAASE,YAAauT,GAE1C5O,EAAS7B,IAAI3C,EAAOL,SAASG,YAChC0E,EAASoQ,OAAO5U,EAAOL,SAASG,UAAWuT,GAExC7O,EAAS7B,IAAI3C,EAAOL,SAASI,iBAChCyE,EAASoQ,OAAO5U,EAAOL,SAASI,eAAgB2T,EAEpD,CDhBEmB,CAAmBrQ"}
|
package/dist/index.esm.js
CHANGED
|
@@ -34,7 +34,40 @@ function getConfig() {
|
|
|
34
34
|
}
|
|
35
35
|
return frozenConfig;
|
|
36
36
|
}
|
|
37
|
+
// The defaults as shipped, for warnInvalid: a value 3.x lets through unchecked must not change
|
|
38
|
+
// what a later call is compared against.
|
|
39
|
+
const defaults = { ..._config, tagNames: { ..._config.tagNames } };
|
|
40
|
+
const warned = new Set();
|
|
41
|
+
/**
|
|
42
|
+
* 3.5 forward-compat check. Warns, once per key per page, about an option that 4.0's bootstrapFetch
|
|
43
|
+
* throws on: one this package does not have, a value of another type than its default (null, or an
|
|
44
|
+
* array for an object, included), or a tag name it does not define or that is not a string. An
|
|
45
|
+
* undefined value is left out, as in 4.0. It only warns: setConfig then goes on exactly as in 3.x.
|
|
46
|
+
* Bootstrap-time only, never on a hot path.
|
|
47
|
+
*/
|
|
48
|
+
function warnInvalid(given, known, path = "") {
|
|
49
|
+
for (const [key, value] of Object.entries(given)) {
|
|
50
|
+
const name = path + key;
|
|
51
|
+
const current = known[key];
|
|
52
|
+
if (value === undefined) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!Object.prototype.hasOwnProperty.call(known, key) ||
|
|
56
|
+
value === null ||
|
|
57
|
+
typeof value !== typeof current ||
|
|
58
|
+
Array.isArray(value) !== Array.isArray(current)) {
|
|
59
|
+
if (!warned.has(name)) {
|
|
60
|
+
warned.add(name);
|
|
61
|
+
console.warn(`[@wcstack/fetch] bootstrapFetch: "${name}" is not one of its options, or not of the option's type. 3.x ignores it or applies it unchecked; 4.0 throws on it.`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
else if (name === "tagNames") {
|
|
65
|
+
warnInvalid(value, current, "tagNames.");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
37
69
|
function setConfig(partialConfig) {
|
|
70
|
+
warnInvalid(partialConfig, defaults);
|
|
38
71
|
if (typeof partialConfig.autoTrigger === "boolean") {
|
|
39
72
|
_config.autoTrigger = partialConfig.autoTrigger;
|
|
40
73
|
}
|