@wcstack/worker 1.16.0 → 1.18.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 CHANGED
@@ -156,6 +156,57 @@ DOM トリガは**常に文字列を post します** — リテラルの `data-
156
156
  <wcs-worker src="./compute.js" data-wcs="command.post: $command.run"></wcs-worker>
157
157
  ```
158
158
 
159
+ ## `:state()` による CSS スタイリング
160
+
161
+ `<wcs-worker>` は 2 つの boolean 出力ステートを
162
+ [`ElementInternals` の `CustomStateSet`](https://developer.mozilla.org/ja/docs/Web/API/CustomStateSet)
163
+ に反映します。そのため `data-wcs` バインディングやクラスの手動トグルなしに、CSS の
164
+ `:state()` 疑似クラスで直接スタイリングできます。
165
+
166
+ | ステート | on になる条件 |
167
+ |----------|----------------|
168
+ | `running` | `wcs-worker:running-changed` が `true` で発火(`false` でクリア) |
169
+ | `error` | `wcs-worker:error` が非 `null` の detail で発火(`null` でクリア) |
170
+
171
+ ```css
172
+ wcs-worker:state(running) ~ .busy-indicator { display: block; }
173
+ wcs-worker:state(running) ~ .busy-indicator { display: none; } /* デフォルト */
174
+
175
+ form:has(wcs-worker:state(error)) .banner { display: block; }
176
+ ```
177
+
178
+ 属性やクラスと異なり `:state()` は要素の外部から書き込めないため、この出力ステートが
179
+ 入力と混同される心配がありません。
180
+
181
+ **対応ブラウザ**(新構文 `:state(x)`): Chrome/Edge 125+、Safari 17.4+、Firefox 126+。
182
+ 非対応の環境ではステートが一切 set されないだけです — `:state()` セレクタがマッチしなく
183
+ なりますが、`<wcs-worker>` 自体は通常どおり動作し続けます(graceful degradation・never-throw)。
184
+
185
+ **SSR:** `:state()` は HTML にシリアライズできないため、サーバーレンダリングされた
186
+ マークアップの初期ペイントにはこれらのステートは乗りません(`@wcstack/server` は無改変)。
187
+ ハイドレーション前の見た目を制御したい場合は、代わりに `wcs-worker:not(:defined)` と組み合わせてください。
188
+
189
+ ### デバッグ
190
+
191
+ カスタムステートは DevTools の Elements パネルには表示されず、`attachInternals()`
192
+ は同一要素に 2 回呼べないため、コンソールから直接覗く手段がありません。そのための
193
+ デバッグ専用の補助を 2 つ用意しています:
194
+
195
+ - `el.debugStates` — 現在 on になっているステート名の**スナップショット**配列
196
+ (例: `["running"]`)。`wc-bindable` の一部ではなく(バインド対象ではない)、
197
+ 形状も契約として保証されません — デバッグ用途にのみ使ってください。
198
+ - `debug-states` 属性(opt-in・既定 OFF)は、ステート変化を要素の
199
+ `data-wcs-state-running` / `data-wcs-state-error` 属性にミラーします。
200
+ Elements パネルを開いておけば、トグルのたびにハイライトされます:
201
+
202
+ ```html
203
+ <wcs-worker src="./compute.js" debug-states></wcs-worker>
204
+ ```
205
+
206
+ **CSS は `data-wcs-state-*` ではなく `:state()` に書いてください。** ミラーされた
207
+ 属性は、DevTools を開いた状態でステート変化を可視化するためだけのものであり、
208
+ スタイリング用の正式なフックではありません。
209
+
159
210
  ## 注意点と制約
160
211
 
161
212
  - **バス型メッセージモデル。** リクエスト/レスポンスの相関付けは組み込まれていません。`post` は fire-and-forget で、返信は `message` に届きます。命令的利用向けの RPC 風 `request(data): Promise` は将来追加され得ます。
package/README.md CHANGED
@@ -156,6 +156,59 @@ State-driven invocation uses the command-token protocol:
156
156
  <wcs-worker src="./compute.js" data-wcs="command.post: $command.run"></wcs-worker>
157
157
  ```
158
158
 
159
+ ## CSS styling with `:state()`
160
+
161
+ `<wcs-worker>` reflects two boolean output states onto its
162
+ [`ElementInternals` `CustomStateSet`](https://developer.mozilla.org/en-US/docs/Web/API/CustomStateSet),
163
+ so you can style it directly from CSS with the `:state()` pseudo-class — no
164
+ `data-wcs` binding or extra class toggling required.
165
+
166
+ | State | On when |
167
+ |-------|---------|
168
+ | `running` | `wcs-worker:running-changed` fires with `true` (cleared on `false`) |
169
+ | `error` | `wcs-worker:error` fires with a non-`null` detail (cleared on `null`) |
170
+
171
+ ```css
172
+ wcs-worker:state(running) ~ .busy-indicator { display: block; }
173
+ wcs-worker:state(running) ~ .busy-indicator { display: none; } /* default */
174
+
175
+ form:has(wcs-worker:state(error)) .banner { display: block; }
176
+ ```
177
+
178
+ Unlike attributes or classes, `:state()` cannot be written from outside the
179
+ element, so there is no risk of confusing this output state with an input.
180
+
181
+ **Browser support** (`:state(x)` syntax): Chrome/Edge 125+, Safari 17.4+,
182
+ Firefox 126+. In older browsers the states are simply never set — `:state()`
183
+ selectors never match, but `<wcs-worker>` itself keeps working normally
184
+ (graceful degradation, never-throw).
185
+
186
+ **SSR**: `:state()` cannot be serialized into HTML, so server-rendered markup
187
+ never carries these states on first paint (`@wcstack/server` is unaffected).
188
+ If you need to style the pre-hydration gap, pair your rule with
189
+ `wcs-worker:not(:defined)` instead.
190
+
191
+ ### Debugging
192
+
193
+ Custom states are invisible in DevTools' Elements panel and `attachInternals()`
194
+ cannot be called twice, so there is no console way to inspect them directly.
195
+ Two debug-only aids are provided for that:
196
+
197
+ - `el.debugStates` — a **snapshot** array of the currently-on state names
198
+ (e.g. `["running"]`). It is not part of `wc-bindable` (not a bind target)
199
+ and its shape is not a guaranteed contract — use it for debugging only.
200
+ - The `debug-states` attribute (opt-in, default off) mirrors state changes
201
+ onto `data-wcs-state-running` / `data-wcs-state-error` attributes on the
202
+ element, so the Elements panel highlights them as they toggle:
203
+
204
+ ```html
205
+ <wcs-worker src="./compute.js" debug-states></wcs-worker>
206
+ ```
207
+
208
+ **Write your CSS against `:state()`, not `data-wcs-state-*`.** The mirrored
209
+ attributes exist purely to make state changes visible while debugging with
210
+ DevTools open; they are not a supported styling hook.
211
+
159
212
  ## Notes & limitations
160
213
 
161
214
  - **Bus-style message model.** No request/response correlation is built in; `post` is fire-and-forget and replies arrive on `message`. An RPC-style `request(data): Promise` is a possible future addition for imperative use.
package/dist/index.d.ts CHANGED
@@ -227,8 +227,12 @@ declare class WcsWorker extends HTMLElement {
227
227
  static get observedAttributes(): string[];
228
228
  private _core;
229
229
  private _connectedCallbackPromise;
230
+ private _internals;
230
231
  constructor();
231
232
  get connectedCallbackPromise(): Promise<void>;
233
+ get debugStates(): string[];
234
+ private _initInternals;
235
+ private _wireStates;
232
236
  get src(): string;
233
237
  set src(value: string);
234
238
  get type(): WorkerType;
package/dist/index.esm.js CHANGED
@@ -464,13 +464,67 @@ class WcsWorker extends HTMLElement {
464
464
  static get observedAttributes() { return ["src"]; }
465
465
  _core;
466
466
  _connectedCallbackPromise = Promise.resolve();
467
+ _internals = null;
467
468
  constructor() {
468
469
  super();
469
470
  this._core = new WorkerCore(this);
471
+ this._internals = this._initInternals();
472
+ this._wireStates({
473
+ "wcs-worker:running-changed": (d) => ({ running: d === true }),
474
+ "wcs-worker:error": (d) => ({ error: d != null }),
475
+ });
470
476
  }
471
477
  get connectedCallbackPromise() {
472
478
  return this._connectedCallbackPromise;
473
479
  }
480
+ // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of
481
+ // wc-bindable (not a bind target); see README "CSS styling with :state()".
482
+ // MUST NOT return the live CustomStateSet (that would let callers write
483
+ // states from outside, defeating the point of :state() being read-only).
484
+ get debugStates() {
485
+ return this._internals ? [...this._internals.states] : [];
486
+ }
487
+ _initInternals() {
488
+ // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent
489
+ // in happy-dom / older environments, and pre-125 Chromium rejects
490
+ // non-dashed state names from states.add() (probed and discarded here).
491
+ // Either case silently disables reflection — the component still works,
492
+ // it just doesn't expose :state() selectors.
493
+ try {
494
+ if (typeof this.attachInternals !== "function")
495
+ return null;
496
+ const internals = this.attachInternals();
497
+ internals.states.add("wcs-probe");
498
+ internals.states.delete("wcs-probe");
499
+ return internals;
500
+ }
501
+ catch {
502
+ return null;
503
+ }
504
+ }
505
+ _wireStates(map) {
506
+ if (this._internals === null)
507
+ return;
508
+ const states = this._internals.states;
509
+ for (const [event, toStates] of Object.entries(map)) {
510
+ this.addEventListener(event, (e) => {
511
+ const debug = this.hasAttribute("debug-states");
512
+ for (const [name, on] of Object.entries(toStates(e.detail))) {
513
+ try {
514
+ if (on) {
515
+ states.add(name);
516
+ }
517
+ else {
518
+ states.delete(name);
519
+ }
520
+ }
521
+ catch { /* never-throw */ }
522
+ if (debug)
523
+ this.toggleAttribute(`data-wcs-state-${name}`, on);
524
+ }
525
+ });
526
+ }
527
+ }
474
528
  // --- Attribute accessors ---
475
529
  get src() {
476
530
  return this.getAttribute("src") || "";
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/registerComponents.ts","../src/bootstrapWorker.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\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\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\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","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\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). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\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 workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\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","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\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 keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MAAM,OAAO,GAAoB;AAC/B,IAAA,WAAW,EAAE,IAAI;AACjB,IAAA,gBAAgB,EAAE,oBAAoB;AACtC,IAAA,QAAQ,EAAE;AACR,QAAA,MAAM,EAAE,YAAY;AACrB,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM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,"file":"index.esm.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/registerComponents.ts","../src/bootstrapWorker.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\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\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\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","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\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). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\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 workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\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","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-worker:running-changed\": (d) => ({ running: d === true }),\n \"wcs-worker:error\": (d) => ({ error: d != null }),\n });\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\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 // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\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 keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MAAM,OAAO,GAAoB;AAC/B,IAAA,WAAW,EAAE,IAAI;AACjB,IAAA,gBAAgB,EAAE,oBAAoB;AACtC,IAAA,QAAQ,EAAE;AACR,QAAA,MAAM,EAAE,YAAY;AACrB,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAClC,QAAA,UAAU,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IACnD;AACA,IAAA,OAAO,GAAG;AACZ;AAEA,SAAS,SAAS,CAAI,GAAM,EAAA;AAC1B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;IACvD,MAAM,KAAK,GAA4B,EAAE;IACzC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClC,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IAC/D;AACA,IAAA,OAAO,KAAU;AACnB;AAEA,IAAI,YAAY,GAAmB,IAAI;AAEvC;AACA;AACA;AACA;AACO,MAAM,MAAM,GAAY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||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const s of Object.keys(t))e[s]=r(t[s]);return e}let s=null;const n=t;function a(){return s||(s=e(r(t))),s}class i extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"message",event:"wcs-worker:message"},{name:"error",event:"wcs-worker:error"},{name:"running",event:"wcs-worker:running-changed"}],commands:[{name:"start"},{name:"post"},{name:"terminate"}]};_target;_worker=null;_message=null;_error=null;_running=!1;_src="";_type="module";_name="";_restartOnError=!1;_maxRestarts=1/0;_restartInterval=0;_restartCount=0;_restartTimer=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}get message(){return this._message}get error(){return this._error}get running(){return this._running}_setMessage(t){this._message=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:message",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:error",{detail:t,bubbles:!0})))}_setRunning(t){this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:running-changed",{detail:t,bubbles:!0}))}start(t,e={}){t?this._worker&&this._src===t||(this._clearRestartTimer(),this._terminateWorker(),this._src=t,this._type=e.type??"module",this._name=e.name??"",this._restartOnError=e.restartOnError??!1,this._maxRestarts=e.maxRestarts??1/0,this._restartInterval=e.restartInterval??0,this._restartCount=0,this._setError(null),this._spawn()):this._setError({name:"TypeError",message:"src is required."})}post(t,e){if(this._worker)try{e&&e.length>0?this._worker.postMessage(t,e):this._worker.postMessage(t)}catch(t){this._setError(this._normalizeError(t))}else this._setError({name:"InvalidStateError",message:"Worker is not running. Call start(src) before post()."})}terminate(){this._clearRestartTimer(),this._terminateWorker()}dispose(){this._gen++,this._clearRestartTimer(),this._terminateWorker(),this._error=null}_spawn(){try{this._worker=new Worker(this._src,{type:this._type,name:this._name||void 0})}catch(t){return void this._setError(this._normalizeError(t))}this._worker.addEventListener("message",this._onMessage),this._worker.addEventListener("messageerror",this._onMessageError),this._worker.addEventListener("error",this._onError),this._setRunning(!0)}_onMessage=t=>{this._setMessage(t.data)};_onMessageError=()=>{this._setError({name:"DataError",message:"Failed to deserialize a message received from the worker."})};_onError=t=>{this._setError({name:"Error",message:t.message||"Worker script error.",filename:t.filename,lineno:t.lineno,colno:t.colno}),this._restartOnError&&this._restartCount<this._maxRestarts&&this._scheduleRestart()};_scheduleRestart(){this._clearRestartTimer();const t=this._gen;this._restartTimer=setTimeout(()=>{t===this._gen&&(this._restartTimer=null,this._restartCount++,this._terminateWorker(),this._setError(null),this._spawn())},this._restartInterval)}_clearRestartTimer(){null!==this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=null)}_terminateWorker(){this._worker&&(this._worker.removeEventListener("message",this._onMessage),this._worker.removeEventListener("messageerror",this._onMessageError),this._worker.removeEventListener("error",this._onError),this._worker.terminate(),this._worker=null,this._setRunning(!1))}_normalizeError(t){return t instanceof Error?{name:t.name,message:t.message}:{name:"Error",message:String(t)}}}let o=!1;const u="data-worker-text";function m(t){const e=t.target;if(!(e instanceof Element))return;const r=e.closest(`[${n.triggerAttribute}]`);if(!r)return;const s=r.getAttribute(n.triggerAttribute);if(!s)return;const a=customElements.get(n.tagNames.worker),i=document.getElementById(s);if(!(a&&i instanceof a))return;const o=function(t){if(t.hasAttribute(u))return t.getAttribute(u)??"";const e=t.getAttribute("data-worker-from");if(!e)return null;let r;try{r=document.querySelector(e)}catch{return null}return r?r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?r.value:r.textContent??"":null}(r);null!==o&&(t.preventDefault(),i.post(o))}class l extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...i.wcBindable,inputs:[{name:"src",attribute:"src"},{name:"type",attribute:"type"},{name:"name",attribute:"name"},{name:"manual",attribute:"manual"},{name:"keepAlive",attribute:"keep-alive"},{name:"restartOnError",attribute:"restart-on-error"},{name:"maxRestarts",attribute:"max-restarts"},{name:"restartInterval",attribute:"restart-interval"}],commands:i.wcBindable.commands};static get observedAttributes(){return["src"]}_core;_connectedCallbackPromise=Promise.resolve();constructor(){super(),this._core=new i(this)}get connectedCallbackPromise(){return this._connectedCallbackPromise}get src(){return this.getAttribute("src")||""}set src(t){this.setAttribute("src",t)}get type(){return"classic"===this.getAttribute("type")?"classic":"module"}set type(t){this.setAttribute("type",t)}get name(){return this.getAttribute("name")||""}set name(t){this.setAttribute("name",t)}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get keepAlive(){return this.hasAttribute("keep-alive")}set keepAlive(t){t?this.setAttribute("keep-alive",""):this.removeAttribute("keep-alive")}get restartOnError(){return this.hasAttribute("restart-on-error")}set restartOnError(t){t?this.setAttribute("restart-on-error",""):this.removeAttribute("restart-on-error")}get maxRestarts(){const t=this.getAttribute("max-restarts");if("Infinity"===t)return 1/0;const e=t?parseInt(t,10):1/0;return Number.isNaN(e)?1/0:e}set maxRestarts(t){this.setAttribute("max-restarts",String(t))}get restartInterval(){const t=this.getAttribute("restart-interval"),e=t?parseInt(t,10):0;return Number.isNaN(e)?0:e}set restartInterval(t){this.setAttribute("restart-interval",String(t))}get message(){return this._core.message}get error(){return this._core.error}get running(){return this._core.running}start(){this._core.start(this.src,{type:this.type,name:this.name,restartOnError:this.restartOnError,maxRestarts:this.maxRestarts,restartInterval:this.restartInterval})}post(t,e){this._core.post(t,e)}terminate(){this._core.terminate()}attributeChangedCallback(t,e,r){"src"===t&&this.isConnected&&!this.manual&&r&&this.start()}connectedCallback(){this.style.display="none",n.autoTrigger&&(o||(o=!0,document.addEventListener("click",m))),this._connectedCallbackPromise=this._core.observe(),!this.manual&&this.src&&this.start()}disconnectedCallback(){this.keepAlive||this._core.dispose()}}function c(e){var r;e&&("boolean"==typeof(r=e).autoTrigger&&(t.autoTrigger=r.autoTrigger),"string"==typeof r.triggerAttribute&&(t.triggerAttribute=r.triggerAttribute),r.tagNames&&Object.assign(t.tagNames,r.tagNames),s=null),customElements.get(n.tagNames.worker)||customElements.define(n.tagNames.worker,l)}export{l as WcsWorker,i as WorkerCore,c as bootstrapWorker,a as getConfig};
1
+ const t={autoTrigger:!0,triggerAttribute:"data-worker-target",tagNames:{worker:"wcs-worker"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const s of Object.keys(t))e[s]=r(t[s]);return e}let s=null;const n=t;function a(){return s||(s=e(r(t))),s}class i extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"message",event:"wcs-worker:message"},{name:"error",event:"wcs-worker:error"},{name:"running",event:"wcs-worker:running-changed"}],commands:[{name:"start"},{name:"post"},{name:"terminate"}]};_target;_worker=null;_message=null;_error=null;_running=!1;_src="";_type="module";_name="";_restartOnError=!1;_maxRestarts=1/0;_restartInterval=0;_restartCount=0;_restartTimer=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}get message(){return this._message}get error(){return this._error}get running(){return this._running}_setMessage(t){this._message=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:message",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:error",{detail:t,bubbles:!0})))}_setRunning(t){this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:running-changed",{detail:t,bubbles:!0}))}start(t,e={}){t?this._worker&&this._src===t||(this._clearRestartTimer(),this._terminateWorker(),this._src=t,this._type=e.type??"module",this._name=e.name??"",this._restartOnError=e.restartOnError??!1,this._maxRestarts=e.maxRestarts??1/0,this._restartInterval=e.restartInterval??0,this._restartCount=0,this._setError(null),this._spawn()):this._setError({name:"TypeError",message:"src is required."})}post(t,e){if(this._worker)try{e&&e.length>0?this._worker.postMessage(t,e):this._worker.postMessage(t)}catch(t){this._setError(this._normalizeError(t))}else this._setError({name:"InvalidStateError",message:"Worker is not running. Call start(src) before post()."})}terminate(){this._clearRestartTimer(),this._terminateWorker()}dispose(){this._gen++,this._clearRestartTimer(),this._terminateWorker(),this._error=null}_spawn(){try{this._worker=new Worker(this._src,{type:this._type,name:this._name||void 0})}catch(t){return void this._setError(this._normalizeError(t))}this._worker.addEventListener("message",this._onMessage),this._worker.addEventListener("messageerror",this._onMessageError),this._worker.addEventListener("error",this._onError),this._setRunning(!0)}_onMessage=t=>{this._setMessage(t.data)};_onMessageError=()=>{this._setError({name:"DataError",message:"Failed to deserialize a message received from the worker."})};_onError=t=>{this._setError({name:"Error",message:t.message||"Worker script error.",filename:t.filename,lineno:t.lineno,colno:t.colno}),this._restartOnError&&this._restartCount<this._maxRestarts&&this._scheduleRestart()};_scheduleRestart(){this._clearRestartTimer();const t=this._gen;this._restartTimer=setTimeout(()=>{t===this._gen&&(this._restartTimer=null,this._restartCount++,this._terminateWorker(),this._setError(null),this._spawn())},this._restartInterval)}_clearRestartTimer(){null!==this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=null)}_terminateWorker(){this._worker&&(this._worker.removeEventListener("message",this._onMessage),this._worker.removeEventListener("messageerror",this._onMessageError),this._worker.removeEventListener("error",this._onError),this._worker.terminate(),this._worker=null,this._setRunning(!1))}_normalizeError(t){return t instanceof Error?{name:t.name,message:t.message}:{name:"Error",message:String(t)}}}let o=!1;const u="data-worker-text";function l(t){const e=t.target;if(!(e instanceof Element))return;const r=e.closest(`[${n.triggerAttribute}]`);if(!r)return;const s=r.getAttribute(n.triggerAttribute);if(!s)return;const a=customElements.get(n.tagNames.worker),i=document.getElementById(s);if(!(a&&i instanceof a))return;const o=function(t){if(t.hasAttribute(u))return t.getAttribute(u)??"";const e=t.getAttribute("data-worker-from");if(!e)return null;let r;try{r=document.querySelector(e)}catch{return null}return r?r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?r.value:r.textContent??"":null}(r);null!==o&&(t.preventDefault(),i.post(o))}class c extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...i.wcBindable,inputs:[{name:"src",attribute:"src"},{name:"type",attribute:"type"},{name:"name",attribute:"name"},{name:"manual",attribute:"manual"},{name:"keepAlive",attribute:"keep-alive"},{name:"restartOnError",attribute:"restart-on-error"},{name:"maxRestarts",attribute:"max-restarts"},{name:"restartInterval",attribute:"restart-interval"}],commands:i.wcBindable.commands};static get observedAttributes(){return["src"]}_core;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new i(this),this._internals=this._initInternals(),this._wireStates({"wcs-worker:running-changed":t=>({running:!0===t}),"wcs-worker:error":t=>({error:null!=t})})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[r,s]of Object.entries(t))this.addEventListener(r,t=>{const r=this.hasAttribute("debug-states");for(const[n,a]of Object.entries(s(t.detail))){try{a?e.add(n):e.delete(n)}catch{}r&&this.toggleAttribute(`data-wcs-state-${n}`,a)}})}get src(){return this.getAttribute("src")||""}set src(t){this.setAttribute("src",t)}get type(){return"classic"===this.getAttribute("type")?"classic":"module"}set type(t){this.setAttribute("type",t)}get name(){return this.getAttribute("name")||""}set name(t){this.setAttribute("name",t)}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get keepAlive(){return this.hasAttribute("keep-alive")}set keepAlive(t){t?this.setAttribute("keep-alive",""):this.removeAttribute("keep-alive")}get restartOnError(){return this.hasAttribute("restart-on-error")}set restartOnError(t){t?this.setAttribute("restart-on-error",""):this.removeAttribute("restart-on-error")}get maxRestarts(){const t=this.getAttribute("max-restarts");if("Infinity"===t)return 1/0;const e=t?parseInt(t,10):1/0;return Number.isNaN(e)?1/0:e}set maxRestarts(t){this.setAttribute("max-restarts",String(t))}get restartInterval(){const t=this.getAttribute("restart-interval"),e=t?parseInt(t,10):0;return Number.isNaN(e)?0:e}set restartInterval(t){this.setAttribute("restart-interval",String(t))}get message(){return this._core.message}get error(){return this._core.error}get running(){return this._core.running}start(){this._core.start(this.src,{type:this.type,name:this.name,restartOnError:this.restartOnError,maxRestarts:this.maxRestarts,restartInterval:this.restartInterval})}post(t,e){this._core.post(t,e)}terminate(){this._core.terminate()}attributeChangedCallback(t,e,r){"src"===t&&this.isConnected&&!this.manual&&r&&this.start()}connectedCallback(){this.style.display="none",n.autoTrigger&&(o||(o=!0,document.addEventListener("click",l))),this._connectedCallbackPromise=this._core.observe(),!this.manual&&this.src&&this.start()}disconnectedCallback(){this.keepAlive||this._core.dispose()}}function h(e){var r;e&&("boolean"==typeof(r=e).autoTrigger&&(t.autoTrigger=r.autoTrigger),"string"==typeof r.triggerAttribute&&(t.triggerAttribute=r.triggerAttribute),r.tagNames&&Object.assign(t.tagNames,r.tagNames),s=null),customElements.get(n.tagNames.worker)||customElements.define(n.tagNames.worker,c)}export{c as WcsWorker,i as WorkerCore,h as bootstrapWorker,a as getConfig};
2
2
  //# sourceMappingURL=index.esm.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/bootstrapWorker.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 worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\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\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\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","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\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). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\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 workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\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","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\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 keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","worker","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","WorkerCore","EventTarget","static","protocol","version","properties","name","event","commands","_target","_worker","_message","_error","_running","_src","_type","_name","_restartOnError","_maxRestarts","Infinity","_restartInterval","_restartCount","_restartTimer","_gen","_ready","Promise","resolve","constructor","target","super","this","ready","observe","message","error","running","_setMessage","dispatchEvent","CustomEvent","detail","bubbles","_setError","_setRunning","start","src","options","_clearRestartTimer","_terminateWorker","type","restartOnError","maxRestarts","restartInterval","_spawn","post","data","transfer","length","postMessage","err","_normalizeError","terminate","dispose","Worker","undefined","addEventListener","_onMessage","_onMessageError","_onError","filename","lineno","colno","_scheduleRestart","gen","setTimeout","clearTimeout","removeEventListener","Error","String","registered","TEXT_ATTRIBUTE","handleClick","Element","triggerElement","closest","workerId","getAttribute","WorkerCtor","customElements","get","workerElement","document","getElementById","text","hasAttribute","selector","source","querySelector","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","value","textContent","resolveText","preventDefault","WcsWorker","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","_connectedCallbackPromise","connectedCallbackPromise","setAttribute","manual","removeAttribute","keepAlive","attr","parsed","parseInt","Number","isNaN","attributeChangedCallback","_oldValue","newValue","isConnected","connectedCallback","style","display","disconnectedCallback","bootstrapWorker","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,qBAClBC,SAAU,CACRC,OAAQ,eAIZ,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAO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NI,SAAUqE,EAAgBC,GJ+C1B,IAAoBC,EI9CpBD,IJ+CqC,kBADjBC,EI7CZD,GJ8CalJ,cACvBD,EAAQC,YAAcmJ,EAAcnJ,aAEQ,iBAAnCmJ,EAAclJ,mBACvBF,EAAQE,iBAAmBkJ,EAAclJ,kBAEvCkJ,EAAcjJ,UAChBI,OAAO8I,OAAOrJ,EAAQG,SAAUiJ,EAAcjJ,UAEhDU,EAAe,MKzDV0F,eAAeC,IAAI1F,EAAOX,SAASC,SACtCmG,eAAe+C,OAAOxI,EAAOX,SAASC,OAAQoH,EDIlD"}
1
+ {"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/bootstrapWorker.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 worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\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\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\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","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\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). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\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 workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\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","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-worker:running-changed\": (d) => ({ running: d === true }),\n \"wcs-worker:error\": (d) => ({ error: d != null }),\n });\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\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 // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\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 keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","worker","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","WorkerCore","EventTarget","static","protocol","version","properties","name","event","commands","_target","_worker","_message","_error","_running","_src","_type","_name","_restartOnError","_maxRestarts","Infinity","_restartInterval","_restartCount","_restartTimer","_gen","_ready","Promise","resolve","constructor","target","super","this","ready","observe","message","error","running","_setMessage","dispatchEvent","CustomEvent","detail","bubbles","_setError","_setRunning","start","src","options","_clearRestartTimer","_terminateWorker","type","restartOnError","maxRestarts","restartInterval","_spawn","post","data","transfer","length","postMessage","err","_normalizeError","terminate","dispose","Worker","undefined","addEventListener","_onMessage","_onMessageError","_onError","filename","lineno","colno","_scheduleRestart","gen","setTimeout","clearTimeout","removeEventListener","Error","String","registered","TEXT_ATTRIBUTE","handleClick","Element","triggerElement","closest","workerId","getAttribute","WorkerCtor","customElements","get","workerElement","document","getElementById","text","hasAttribute","selector","source","querySelector","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","value","textContent","resolveText","preventDefault","WcsWorker","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","_connectedCallbackPromise","_internals","_initInternals","_wireStates","d","connectedCallbackPromise","debugStates","states","attachInternals","internals","add","delete","map","toStates","entries","e","debug","on","toggleAttribute","setAttribute","manual","removeAttribute","keepAlive","attr","parsed","parseInt","Number","isNaN","attributeChangedCallback","_oldValue","newValue","isConnected","connectedCallback","style","display","disconnectedCallback","bootstrapWorker","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,qBAClBC,SAAU,CACRC,OAAQ,eAIZ,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH,CACT,CAEA,SAASK,EAAaL,GACpB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpD,MAAMM,EAAiC,CAAA,EACvC,IAAK,MAAMH,KAAOF,OAAOG,KAAKJ,GAC5BM,EAAMH,GAAOE,EAAWL,EAAgCG,IAE1D,OAAOG,CACT,CAEA,IAAIC,EAA+B,KAM5B,MAAMC,EAAkBd,WAEfe,IAId,OAHKF,IACHA,EAAeR,EAAWM,EAAUX,KAE/Ba,CACT,CC5BM,MAAOG,UAAmBC,YAC9BC,kBAAiC,CAC/BC,SAAU,cACVC,QAAS,EACTC,WAAY,CACV,CAAEC,KAAM,UAAWC,MAAO,sBAC1B,CAAED,KAAM,QAASC,MAAO,oBACxB,CAAED,KAAM,UAAWC,MAAO,+BAE5BC,SAAU,CACR,CAAEF,KAAM,SACR,CAAEA,KAAM,QACR,CAAEA,KAAM,eAIJG,QACAC,QAAyB,KACzBC,SAAgB,KAChBC,OAAsC,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ACbY,SAAS1B,iBAAiB,QAASgB,KCyJjClD,KAAKiF,0BAA4BjF,KAAKgF,MAAM9E,WACvCF,KAAKqG,QAAUrG,KAAKc,KACvBd,KAAKa,OAET,CAEA,oBAAAuG,GAeOpH,KAAKuG,WACRvG,KAAKgF,MAAMjD,SAEf,ECrQI,SAAUsF,EAAgBC,GJ+C1B,IAAoBC,EI9CpBD,IJ+CqC,kBADjBC,EI7CZD,GJ8CanK,cACvBD,EAAQC,YAAcoK,EAAcpK,aAEQ,iBAAnCoK,EAAcnK,mBACvBF,EAAQE,iBAAmBmK,EAAcnK,kBAEvCmK,EAAclK,UAChBI,OAAO+J,OAAOtK,EAAQG,SAAUkK,EAAclK,UAEhDU,EAAe,MKzDV0F,eAAeC,IAAI1F,EAAOX,SAASC,SACtCmG,eAAegE,OAAOzJ,EAAOX,SAASC,OAAQoH,EDIlD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wcstack/worker",
3
- "version": "1.16.0",
3
+ "version": "1.18.0",
4
4
  "description": "Declarative Web Worker component for Web Components. Framework-agnostic Dedicated Worker primitive via wc-bindable-protocol.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.esm.js",