@wc-bindable/composite 0.8.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.
@@ -0,0 +1,162 @@
1
+ import type { WcBindableDeclaration } from "@wc-bindable/core";
2
+ import { CompositeEngine, type CompositionPlan } from "./engine.js";
3
+ import { type Logger } from "./logger.js";
4
+ import { type CompositeTierClaim, type ExposeConfig } from "./types.js";
5
+ /** An ordered source spec: a stable id paired with a source custom-element tag. */
6
+ export interface SourceSpec {
7
+ id: string;
8
+ /** The source custom-element tag name (e.g. `"s3-uploader"`). */
9
+ tag: string;
10
+ }
11
+ /**
12
+ * Options shared by {@link defineCompositeClass} and {@link defineComposite}.
13
+ * Everything needed to synthesize the composed surface *except* the tag name —
14
+ * {@link defineCompositeClass} returns an unregistered base class the caller
15
+ * names itself, while {@link defineComposite} also takes a `tagName` and
16
+ * registers the class.
17
+ */
18
+ export interface DefineCompositeClassOptions {
19
+ /** Ordered source specs: a stable id paired with a source custom-element tag. */
20
+ sources: SourceSpec[];
21
+ /**
22
+ * What the shell exposes. Defaults to `"all-prefixed"` (every source member
23
+ * under its `<sourceId>.<sourceName>` default name).
24
+ */
25
+ expose?: ExposeConfig;
26
+ /** Materialize a T2 local facade. Defaults to true when inputs/commands exist. */
27
+ localFacade?: boolean;
28
+ /** Set the `remoteCompatible` tier-claim flag. */
29
+ remoteCompatible?: boolean;
30
+ logger?: Logger;
31
+ }
32
+ export interface DefineCompositeOptions extends DefineCompositeClassOptions {
33
+ /** The custom-element tag name to register for the composed shell. */
34
+ tagName: string;
35
+ }
36
+ /**
37
+ * The generated composite custom-element constructor. Instances carry the
38
+ * composed surface (property getters, optional T2 facade members, the tier
39
+ * claim) and an idempotent `dispose()` terminal teardown. Returned by
40
+ * {@link defineComposite} (already registered) and by {@link defineCompositeClass}
41
+ * (an unregistered base class to subclass).
42
+ */
43
+ export type CompositeElementConstructor = (new (...args: unknown[]) => HTMLElement & {
44
+ dispose(): void;
45
+ }) & {
46
+ wcBindable: WcBindableDeclaration;
47
+ };
48
+ /**
49
+ * Define a composed custom element programmatically.
50
+ *
51
+ * Per the § Declarative custom element API precondition, this awaits
52
+ * `customElements.whenDefined()` for **every** source tag before synthesizing
53
+ * the declaration and registering the composite element — a shell instance is
54
+ * never observable with a provisional declaration. Resolves with the generated
55
+ * constructor once it is registered.
56
+ *
57
+ * Concurrency-safe and idempotent per tag: concurrent or repeated calls for the
58
+ * same `tagName` share one registration (no `define()` race), and a re-call
59
+ * returns the existing composite constructor without re-validating `options`. A
60
+ * tag already occupied by a *non-composite* element is reported as an error.
61
+ *
62
+ * Each instance builds its own shadow root (`mode: "open"`) containing one
63
+ * freshly-created instance of every source tag, binds an engine to those source
64
+ * instances, and exposes the composed surface. Source listeners are installed on
65
+ * first connect and kept for the element's lifetime (no detach-on-disconnect, so
66
+ * there is no reconnect re-sync gap, § 10); call `element.dispose()` for terminal
67
+ * teardown.
68
+ */
69
+ export declare function defineComposite(options: DefineCompositeOptions): Promise<CompositeElementConstructor>;
70
+ /**
71
+ * The resolved, immutable composition derived from a set of source tags:
72
+ * everything needed to build a composite element class and to set up each
73
+ * instance. Produced by {@link synthesizeComposite}.
74
+ *
75
+ * @internal Shared between the vanilla custom-element path and the Lit subpath
76
+ * (`@wc-bindable/composite/lit`); not part of the public package surface.
77
+ */
78
+ export interface SynthesizedComposite {
79
+ plan: CompositionPlan;
80
+ claimTemplate: CompositeTierClaim;
81
+ sourceSpecs: SourceSpec[];
82
+ logger: Logger;
83
+ }
84
+ /**
85
+ * Await every source tag's `customElements.whenDefined`, read each source's
86
+ * `static wcBindable`, and plan the composition — so the synthesized declaration
87
+ * and tier claim are fully determined before any class is built or any instance
88
+ * is observable (§ Declarative precondition / § 11 finalize-before-observe).
89
+ *
90
+ * @internal
91
+ */
92
+ export declare function synthesizeComposite(options: DefineCompositeClassOptions): Promise<SynthesizedComposite>;
93
+ /**
94
+ * Set up one composite element instance: create a fresh source element per spec
95
+ * inside `shadow`, install the composed surface (property getters, optional T2
96
+ * facade, tier claim) on `host`, and bind the engine to the sources. Returns the
97
+ * installed engine. On an `install()` failure it rolls the sources back and
98
+ * rethrows, leaving `host` clean enough for a reconnect retry.
99
+ *
100
+ * Only the source elements this package owns (`[data-wc-source]`) are touched —
101
+ * any other shadow content (e.g. a Lit-rendered UI) is left intact.
102
+ *
103
+ * @internal
104
+ */
105
+ export declare function setupCompositeInstance(host: HTMLElement, shadow: ShadowRoot, synth: SynthesizedComposite): CompositeEngine;
106
+ /**
107
+ * Build a composite custom-element **base class** without registering it, so a
108
+ * caller can subclass it to add their own behavior (methods, light-DOM
109
+ * rendering, extra lifecycle work) and then register it themselves with
110
+ * `customElements.define`. This is the class-authoring counterpart to
111
+ * {@link defineComposite}, which returns an opaque, already-registered class.
112
+ *
113
+ * ```ts
114
+ * const Base = await defineCompositeClass({
115
+ * sources: [{ id: "s3", tag: "s3-uploader" }, { id: "ai", tag: "ai-agent" }],
116
+ * });
117
+ * class MyWorkbench extends Base {
118
+ * reset() { this["ai.prompt"] = ""; } // your own behavior on top of the composite
119
+ * }
120
+ * customElements.define("my-ai-workbench", MyWorkbench);
121
+ * ```
122
+ *
123
+ * Like {@link defineComposite}, this awaits `customElements.whenDefined()` for
124
+ * every source tag before resolving, so the synthesized `static wcBindable` is
125
+ * fully determined on the returned class (and statically inherited by any
126
+ * subclass, keeping `target.constructor.wcBindable` discovery intact).
127
+ *
128
+ * The base class owns its shadow root for the source instances and sets them up
129
+ * in `connectedCallback`. A subclass that overrides `connectedCallback` MUST call
130
+ * `super.connectedCallback()` (and SHOULD do so before adding its own shadow
131
+ * content, which the base only initializes — never wipes — once). Unlike
132
+ * {@link defineComposite}, no tag-level caching or self-reference guard applies
133
+ * here — the caller owns the `customElements.define` call.
134
+ */
135
+ export declare function defineCompositeClass(options: DefineCompositeClassOptions): Promise<CompositeElementConstructor>;
136
+ /**
137
+ * Scan `root` for declarative composite definitions and register each.
138
+ *
139
+ * A definition element carries `data-wc-composite-definition`; its tag name
140
+ * becomes the composed custom element, and its Declarative Shadow DOM
141
+ * (`<template shadowrootmode="open">`) wraps the source elements, each marked
142
+ * with `data-wc-source="<id>"` and optionally `data-wc-expose="..."`:
143
+ *
144
+ * ```html
145
+ * <my-ai-workbench data-wc-composite-definition>
146
+ * <template shadowrootmode="open">
147
+ * <s3-uploader data-wc-source="s3"></s3-uploader>
148
+ * <ai-agent data-wc-source="ai"></ai-agent>
149
+ * </template>
150
+ * </my-ai-workbench>
151
+ * ```
152
+ *
153
+ * Resolves once every discovered definition has been registered (awaiting each
154
+ * definition's source tags via `customElements.whenDefined`). Returns the
155
+ * generated constructors in document order.
156
+ */
157
+ export declare function registerCompositeDefinitions(root?: ParentNode, options?: {
158
+ localFacade?: boolean;
159
+ remoteCompatible?: boolean;
160
+ logger?: Logger;
161
+ }): Promise<CompositeElementConstructor[]>;
162
+ //# sourceMappingURL=declarative.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"declarative.d.ts","sourceRoot":"","sources":["../src/declarative.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAmB,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACrF,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAGL,KAAK,kBAAkB,EACvB,KAAK,YAAY,EAGlB,MAAM,YAAY,CAAC;AAEpB,mFAAmF;AACnF,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;GAMG;AACH,MAAM,WAAW,2BAA2B;IAC1C,iFAAiF;IACjF,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB;;;OAGG;IACH,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,kFAAkF;IAClF,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,kDAAkD;IAClD,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAuB,SAAQ,2BAA2B;IACzE,sEAAsE;IACtE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG,CAAC,KACzC,GAAG,IAAI,EAAE,OAAO,EAAE,KACf,WAAW,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CAAE,CAAC,GAAG;IACxC,UAAU,EAAE,qBAAqB,CAAC;CACnC,CAAC;AA0GF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,2BAA2B,CAAC,CAiEtC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,eAAe,CAAC;IACtB,aAAa,EAAE,kBAAkB,CAAC;IAClC,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,oBAAoB,CAAC,CA2B/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,oBAAoB,GAC1B,eAAe,CA8CjB;AA6CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,2BAA2B,CAAC,CAStC;AAoHD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,4BAA4B,CAChD,IAAI,GAAE,UAAiD,EACvD,OAAO,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC/E,OAAO,CAAC,2BAA2B,EAAE,CAAC,CAuCxC"}
@@ -0,0 +1,491 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
+ if (kind === "m") throw new TypeError("Private method is not writable");
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
+ };
12
+ import { CompositeEngine, planComposition } from "./engine.js";
13
+ import { consoleLogger } from "./logger.js";
14
+ import { COMPOSITE_PROFILE_VERSION, COMPOSITE_TIERS_SYMBOL, } from "./types.js";
15
+ const customElementsRef = typeof customElements !== "undefined" ? customElements : undefined;
16
+ const documentRef = typeof document !== "undefined" ? document : undefined;
17
+ /**
18
+ * Brand stamped on every generated composite element class. Lets a re-call
19
+ * recognize a tag this package already defined even after {@link registrations}
20
+ * is lost (e.g. an HMR module re-evaluation, where the `CustomElementRegistry`
21
+ * persists but module state resets), so it returns the existing constructor
22
+ * idempotently instead of mistaking it for a foreign collision.
23
+ */
24
+ const COMPOSITE_ELEMENT_BRAND = Symbol.for("wc-bindable.composite.element");
25
+ /**
26
+ * In-flight / settled registrations keyed by tag name. Populated synchronously
27
+ * (before the first `await` in {@link defineComposite}) so concurrent same-tick
28
+ * calls for one tag share a single registration instead of racing to
29
+ * `customElements.define()` — only one `define()` ever runs per tag.
30
+ */
31
+ const registrations = new Map();
32
+ /**
33
+ * Read a source custom element's static `wcBindable` declaration from its
34
+ * registered constructor. The constructor MUST already be defined (the caller
35
+ * awaits `customElements.whenDefined`).
36
+ */
37
+ function readSourceDeclaration(tag) {
38
+ const ctor = customElementsRef?.get(tag);
39
+ const decl = ctor?.wcBindable;
40
+ if (!decl || decl.protocol !== "wc-bindable" || !Array.isArray(decl.properties)) {
41
+ throw new Error(`@wc-bindable/composite: source tag <${tag}> does not expose a static wcBindable declaration`);
42
+ }
43
+ return decl;
44
+ }
45
+ /**
46
+ * Remove the source elements this package created in a shadow root (marked with
47
+ * `data-wc-source`), leaving any other shadow content a subclass rendered
48
+ * intact. Used to de-duplicate sources on a retry without wiping the whole tree.
49
+ */
50
+ function removeOwnedSources(shadow) {
51
+ for (const stray of Array.from(shadow.querySelectorAll("[data-wc-source]"))) {
52
+ stray.remove();
53
+ }
54
+ }
55
+ /**
56
+ * Install the per-instance composed surface (T1 property getters, and the T2
57
+ * input setters / command members when the facade is enabled) plus the tier
58
+ * claim, on a concrete shell element instance.
59
+ *
60
+ * Unlike the headless {@link createCompositeTarget} Proxy shell, a custom
61
+ * element is handed to the DOM directly and cannot be Proxy-wrapped, so composed
62
+ * members are materialized with `Object.defineProperty`. Consequently `N in
63
+ * element` is `true` for every declared property (the § 5 "remote source reports
64
+ * `in === false` until synced" nuance does not apply to synchronous DSD custom
65
+ * element sources). `element[N]` still returns the engine's current value.
66
+ */
67
+ function installInstanceSurface(element, engine, plan, claim) {
68
+ for (const prop of plan.properties) {
69
+ Object.defineProperty(element, prop.composedName, {
70
+ get: () => engine.getValue(prop.composedName),
71
+ configurable: true,
72
+ enumerable: true,
73
+ });
74
+ }
75
+ if (plan.localFacade) {
76
+ for (const input of plan.inputs) {
77
+ Object.defineProperty(element, input.composedName, {
78
+ get: () => undefined,
79
+ set: (value) => engine.setInput(input.composedName, value),
80
+ configurable: true,
81
+ enumerable: true,
82
+ });
83
+ }
84
+ for (const command of plan.commands) {
85
+ Object.defineProperty(element, command.composedName, {
86
+ value: engine.getCommand(command.composedName),
87
+ configurable: true,
88
+ enumerable: true,
89
+ writable: false,
90
+ });
91
+ }
92
+ }
93
+ // configurable so a connectedCallback retry (after a prior install() failure)
94
+ // can re-apply the surface without an "already defined" TypeError. The claim
95
+ // value itself is frozen, so read-only-ness is preserved.
96
+ Object.defineProperty(element, COMPOSITE_TIERS_SYMBOL, {
97
+ value: claim,
98
+ enumerable: false,
99
+ configurable: true,
100
+ writable: false,
101
+ });
102
+ }
103
+ /**
104
+ * Define a composed custom element programmatically.
105
+ *
106
+ * Per the § Declarative custom element API precondition, this awaits
107
+ * `customElements.whenDefined()` for **every** source tag before synthesizing
108
+ * the declaration and registering the composite element — a shell instance is
109
+ * never observable with a provisional declaration. Resolves with the generated
110
+ * constructor once it is registered.
111
+ *
112
+ * Concurrency-safe and idempotent per tag: concurrent or repeated calls for the
113
+ * same `tagName` share one registration (no `define()` race), and a re-call
114
+ * returns the existing composite constructor without re-validating `options`. A
115
+ * tag already occupied by a *non-composite* element is reported as an error.
116
+ *
117
+ * Each instance builds its own shadow root (`mode: "open"`) containing one
118
+ * freshly-created instance of every source tag, binds an engine to those source
119
+ * instances, and exposes the composed surface. Source listeners are installed on
120
+ * first connect and kept for the element's lifetime (no detach-on-disconnect, so
121
+ * there is no reconnect re-sync gap, § 10); call `element.dispose()` for terminal
122
+ * teardown.
123
+ */
124
+ export function defineComposite(options) {
125
+ // defineComposite always returns a Promise, so every error — including the
126
+ // synchronous precondition failures below — surfaces as a rejection, letting
127
+ // callers handle them uniformly with `await` / `.catch`.
128
+ if (!customElementsRef || !documentRef) {
129
+ return Promise.reject(new Error("@wc-bindable/composite: defineComposite requires a DOM (customElements/document)"));
130
+ }
131
+ const { tagName } = options;
132
+ // Direct self-reference guard. If a source tag equals this composite's own
133
+ // tag, registerCompositeElement would `await customElements.whenDefined(tag)`
134
+ // for a tag that is only `define()`d at the very end of that same call — a
135
+ // promise that can never resolve, so the registration would hang silently.
136
+ // The composition graph MUST be acyclic (SPEC-extensions.md § Composition /
137
+ // COMPOSITE.md § 4: "a cyclic composition has no conformant construction
138
+ // order"); fail fast with a clear synchronous rejection instead of
139
+ // deadlocking. (Transitive tag cycles are undetectable at define() time and
140
+ // are intentionally out of scope.)
141
+ if (options.sources.some((spec) => spec.tag === tagName)) {
142
+ return Promise.reject(new Error(`@wc-bindable/composite: composite <${tagName}> cannot list its own tag as a source ` +
143
+ `— a cyclic composition has no conformant construction order`));
144
+ }
145
+ // Fast path: an in-flight or settled registration for this tag is shared
146
+ // verbatim, so concurrent same-tick calls never race to define() and a
147
+ // re-call is idempotent. NOTE: re-registering an already-defined tag returns
148
+ // the existing constructor WITHOUT re-validating that `options` still matches
149
+ // — configuration drift across calls is the caller's responsibility (the
150
+ // synthesized declaration is immutable per § 11).
151
+ const cached = registrations.get(tagName);
152
+ if (cached)
153
+ return cached;
154
+ const existing = customElementsRef.get(tagName);
155
+ if (existing) {
156
+ if (existing[COMPOSITE_ELEMENT_BRAND]) {
157
+ // Already defined by this package (e.g. registrations was reset by HMR).
158
+ const resolved = Promise.resolve(existing);
159
+ registrations.set(tagName, resolved);
160
+ return resolved;
161
+ }
162
+ // The tag is occupied by a non-composite element; returning it typed as a
163
+ // composite constructor would be a lie, so fail loudly instead.
164
+ return Promise.reject(new Error(`@wc-bindable/composite: custom element <${tagName}> is already defined by another (non-composite) element`));
165
+ }
166
+ // Populate the cache BEFORE the first await so a second same-tick call hits
167
+ // the fast path above. A failed registration is evicted so it can be retried.
168
+ const promise = registerCompositeElement(options);
169
+ registrations.set(tagName, promise);
170
+ promise.catch(() => {
171
+ if (registrations.get(tagName) === promise)
172
+ registrations.delete(tagName);
173
+ });
174
+ return promise;
175
+ }
176
+ /**
177
+ * Await every source tag's `customElements.whenDefined`, read each source's
178
+ * `static wcBindable`, and plan the composition — so the synthesized declaration
179
+ * and tier claim are fully determined before any class is built or any instance
180
+ * is observable (§ Declarative precondition / § 11 finalize-before-observe).
181
+ *
182
+ * @internal
183
+ */
184
+ export async function synthesizeComposite(options) {
185
+ const logger = options.logger ?? consoleLogger;
186
+ // § Declarative precondition: every source tag must be defined before the
187
+ // declaration can be read. Adopt the async-registration model.
188
+ await Promise.all(options.sources.map((spec) => customElementsRef.whenDefined(spec.tag)));
189
+ const sourceDecls = new Map();
190
+ for (const spec of options.sources)
191
+ sourceDecls.set(spec.id, readSourceDeclaration(spec.tag));
192
+ let localFacade = options.localFacade;
193
+ if (localFacade === undefined) {
194
+ const probe = planComposition(sourceDecls, options.expose ?? "all-prefixed", { localFacade: false });
195
+ localFacade = probe.inputs.length > 0 || probe.commands.length > 0;
196
+ }
197
+ const plan = planComposition(sourceDecls, options.expose ?? "all-prefixed", { localFacade });
198
+ const claimTemplate = {
199
+ protocol: "wc-bindable.composite",
200
+ version: COMPOSITE_PROFILE_VERSION,
201
+ localFacade: plan.localFacade,
202
+ extension1: false,
203
+ };
204
+ if (options.remoteCompatible)
205
+ claimTemplate.remoteCompatible = true;
206
+ Object.freeze(claimTemplate);
207
+ return { plan, claimTemplate, sourceSpecs: options.sources.slice(), logger };
208
+ }
209
+ /**
210
+ * Set up one composite element instance: create a fresh source element per spec
211
+ * inside `shadow`, install the composed surface (property getters, optional T2
212
+ * facade, tier claim) on `host`, and bind the engine to the sources. Returns the
213
+ * installed engine. On an `install()` failure it rolls the sources back and
214
+ * rethrows, leaving `host` clean enough for a reconnect retry.
215
+ *
216
+ * Only the source elements this package owns (`[data-wc-source]`) are touched —
217
+ * any other shadow content (e.g. a Lit-rendered UI) is left intact.
218
+ *
219
+ * @internal
220
+ */
221
+ export function setupCompositeInstance(host, shadow, synth) {
222
+ // Defensive backstop against a direct self-reference. `defineComposite()`
223
+ // rejects a source tag equal to the composite's own tag at registration time;
224
+ // the class-authoring paths (`defineCompositeClass` / `CompositeLitElement`)
225
+ // do not know the tag the caller will register the class under, so the check
226
+ // is repeated here where `host.localName` is known. In practice this never
227
+ // fires through the public API — a caller cannot register a class under one of
228
+ // its own source tags: that tag is either already defined (so
229
+ // `customElements.define` throws "already defined") or not yet defined (so
230
+ // `synthesizeComposite`'s `whenDefined()` never resolves and the class is
231
+ // never produced). It is kept because the failure it prevents — recursively
232
+ // creating a host-typed element inside its own shadow root on every connect,
233
+ // i.e. unbounded re-entry / stack overflow — is catastrophic, and the guard
234
+ // is free.
235
+ const selfTag = host.localName;
236
+ if (selfTag && synth.sourceSpecs.some((spec) => spec.tag === selfTag)) {
237
+ throw new Error(`@wc-bindable/composite: composite <${selfTag}> cannot list its own tag as a source ` +
238
+ `— a cyclic composition has no conformant construction order`);
239
+ }
240
+ removeOwnedSources(shadow);
241
+ const sources = new Map();
242
+ for (const spec of synth.sourceSpecs) {
243
+ const sourceEl = documentRef.createElement(spec.tag);
244
+ sourceEl.setAttribute("data-wc-source", spec.id);
245
+ shadow.appendChild(sourceEl);
246
+ sources.set(spec.id, sourceEl);
247
+ }
248
+ const engine = new CompositeEngine(synth.plan, sources, host, synth.logger);
249
+ // The instance surface (defined with configurable members) is safe to
250
+ // (re)apply on a retry. install() is the only fallible step here; if it
251
+ // throws, roll the sources back so a reconnect can retry cleanly rather than
252
+ // stranding a half-initialized element.
253
+ installInstanceSurface(host, engine, synth.plan, synth.claimTemplate);
254
+ try {
255
+ engine.install();
256
+ }
257
+ catch (err) {
258
+ engine.dispose();
259
+ removeOwnedSources(shadow);
260
+ throw err;
261
+ }
262
+ return engine;
263
+ }
264
+ /**
265
+ * Build (but do not register) the composite element class for `options`.
266
+ *
267
+ * Shared by {@link defineComposite} (which then calls `customElements.define`)
268
+ * and {@link defineCompositeClass} (which returns the class for the caller to
269
+ * subclass and register).
270
+ */
271
+ async function buildCompositeClass(options) {
272
+ var _CompositeElement_engine, _CompositeElement_setup, _a;
273
+ const synth = await synthesizeComposite(options);
274
+ class CompositeElement extends HTMLElement {
275
+ constructor() {
276
+ super(...arguments);
277
+ _CompositeElement_engine.set(this, void 0);
278
+ _CompositeElement_setup.set(this, false);
279
+ }
280
+ connectedCallback() {
281
+ if (__classPrivateFieldGet(this, _CompositeElement_setup, "f"))
282
+ return; // reconnect: listeners were kept, nothing to do
283
+ const shadow = this.shadowRoot ?? this.attachShadow({ mode: "open" });
284
+ __classPrivateFieldSet(this, _CompositeElement_engine, setupCompositeInstance(this, shadow, synth), "f");
285
+ __classPrivateFieldSet(this, _CompositeElement_setup, true, "f");
286
+ }
287
+ /** Idempotent terminal teardown (§ 10). Does not dispose the source elements. */
288
+ dispose() {
289
+ __classPrivateFieldGet(this, _CompositeElement_engine, "f")?.dispose();
290
+ }
291
+ }
292
+ _CompositeElement_engine = new WeakMap(), _CompositeElement_setup = new WeakMap(), _a = COMPOSITE_ELEMENT_BRAND;
293
+ CompositeElement.wcBindable = synth.plan.declaration;
294
+ CompositeElement[_a] = true;
295
+ return CompositeElement;
296
+ }
297
+ async function registerCompositeElement(options) {
298
+ const CompositeElement = await buildCompositeClass(options);
299
+ customElementsRef.define(options.tagName, CompositeElement);
300
+ return CompositeElement;
301
+ }
302
+ /**
303
+ * Build a composite custom-element **base class** without registering it, so a
304
+ * caller can subclass it to add their own behavior (methods, light-DOM
305
+ * rendering, extra lifecycle work) and then register it themselves with
306
+ * `customElements.define`. This is the class-authoring counterpart to
307
+ * {@link defineComposite}, which returns an opaque, already-registered class.
308
+ *
309
+ * ```ts
310
+ * const Base = await defineCompositeClass({
311
+ * sources: [{ id: "s3", tag: "s3-uploader" }, { id: "ai", tag: "ai-agent" }],
312
+ * });
313
+ * class MyWorkbench extends Base {
314
+ * reset() { this["ai.prompt"] = ""; } // your own behavior on top of the composite
315
+ * }
316
+ * customElements.define("my-ai-workbench", MyWorkbench);
317
+ * ```
318
+ *
319
+ * Like {@link defineComposite}, this awaits `customElements.whenDefined()` for
320
+ * every source tag before resolving, so the synthesized `static wcBindable` is
321
+ * fully determined on the returned class (and statically inherited by any
322
+ * subclass, keeping `target.constructor.wcBindable` discovery intact).
323
+ *
324
+ * The base class owns its shadow root for the source instances and sets them up
325
+ * in `connectedCallback`. A subclass that overrides `connectedCallback` MUST call
326
+ * `super.connectedCallback()` (and SHOULD do so before adding its own shadow
327
+ * content, which the base only initializes — never wipes — once). Unlike
328
+ * {@link defineComposite}, no tag-level caching or self-reference guard applies
329
+ * here — the caller owns the `customElements.define` call.
330
+ */
331
+ export function defineCompositeClass(options) {
332
+ if (!customElementsRef || !documentRef) {
333
+ return Promise.reject(new Error("@wc-bindable/composite: defineCompositeClass requires a DOM (customElements/document)"));
334
+ }
335
+ return buildCompositeClass(options);
336
+ }
337
+ /**
338
+ * Parse a `data-wc-expose` attribute into per-source expose entries.
339
+ *
340
+ * Grammar (whitespace-insensitive):
341
+ * `properties: a, b; inputs: c; commands: d`
342
+ * Singular kind keywords (`property` / `input` / `command`) are also accepted.
343
+ */
344
+ function parseExposeAttribute(value, sourceId) {
345
+ const result = {
346
+ properties: [],
347
+ inputs: [],
348
+ commands: [],
349
+ };
350
+ for (const segment of value.split(";")) {
351
+ const trimmed = segment.trim();
352
+ if (!trimmed)
353
+ continue;
354
+ const colon = trimmed.indexOf(":");
355
+ if (colon === -1) {
356
+ throw new Error(`@wc-bindable/composite: malformed data-wc-expose segment ${JSON.stringify(trimmed)}`);
357
+ }
358
+ const kind = trimmed.slice(0, colon).trim().toLowerCase();
359
+ const names = trimmed
360
+ .slice(colon + 1)
361
+ .split(",")
362
+ .map((n) => n.trim())
363
+ .filter((n) => n.length > 0);
364
+ const bucket = kind === "properties" || kind === "property"
365
+ ? result.properties
366
+ : kind === "inputs" || kind === "input"
367
+ ? result.inputs
368
+ : kind === "commands" || kind === "command"
369
+ ? result.commands
370
+ : undefined;
371
+ if (!bucket) {
372
+ throw new Error(`@wc-bindable/composite: unknown data-wc-expose kind ${JSON.stringify(kind)}`);
373
+ }
374
+ for (const name of names) {
375
+ bucket.push([`${sourceId}.${name}`, { source: sourceId, name }]);
376
+ }
377
+ }
378
+ return result;
379
+ }
380
+ /**
381
+ * Resolve the shadow content of a definition element. Handles both a parsed
382
+ * Declarative Shadow DOM (`element.shadowRoot` populated by the HTML parser) and
383
+ * the unparsed-template fallback (a `<template shadowrootmode="open">` /
384
+ * legacy `shadowroot="open"` child whose `.content` carries the sources) so the
385
+ * API works in browsers without DSD parsing and in test environments.
386
+ */
387
+ function getDefinitionContent(def) {
388
+ if (def.shadowRoot)
389
+ return def.shadowRoot;
390
+ for (const child of Array.from(def.children)) {
391
+ if (child.tagName === "TEMPLATE" &&
392
+ (child.hasAttribute("shadowrootmode") || child.hasAttribute("shadowroot"))) {
393
+ return child.content;
394
+ }
395
+ }
396
+ return null;
397
+ }
398
+ /**
399
+ * Read source specs and an optional expose map from a definition element's
400
+ * shadow content (the `<template shadowroot[mode]>` that wraps the composed
401
+ * source elements). Returns `null` if no shadow content / source elements are
402
+ * found.
403
+ */
404
+ function parseDefinition(def) {
405
+ const content = getDefinitionContent(def);
406
+ if (!content)
407
+ return null;
408
+ const sourceEls = Array.from(content.querySelectorAll("[data-wc-source]"));
409
+ if (sourceEls.length === 0)
410
+ return null;
411
+ const sources = [];
412
+ const exposeMap = {};
413
+ let sawExpose = false;
414
+ for (const el of sourceEls) {
415
+ const id = el.getAttribute("data-wc-source");
416
+ // An element matched `[data-wc-source]` but carries an empty value — a
417
+ // markup typo. Fail loudly rather than silently dropping the source (the
418
+ // JavaScript API rejects invalid source ids too; this keeps the declarative
419
+ // path from quietly accepting a malformed definition).
420
+ if (!id) {
421
+ throw new Error(`@wc-bindable/composite: <${el.localName}> has an empty data-wc-source (a non-empty source id is required)`);
422
+ }
423
+ sources.push({ id, tag: el.localName });
424
+ const exposeAttr = el.getAttribute("data-wc-expose");
425
+ if (exposeAttr !== null) {
426
+ sawExpose = true;
427
+ const parsed = parseExposeAttribute(exposeAttr, id);
428
+ for (const [name, ref] of parsed.properties)
429
+ (exposeMap.properties ?? (exposeMap.properties = {}))[name] = ref;
430
+ for (const [name, ref] of parsed.inputs)
431
+ (exposeMap.inputs ?? (exposeMap.inputs = {}))[name] = ref;
432
+ for (const [name, ref] of parsed.commands)
433
+ (exposeMap.commands ?? (exposeMap.commands = {}))[name] = ref;
434
+ }
435
+ }
436
+ return { sources, expose: sawExpose ? exposeMap : undefined };
437
+ }
438
+ /**
439
+ * Scan `root` for declarative composite definitions and register each.
440
+ *
441
+ * A definition element carries `data-wc-composite-definition`; its tag name
442
+ * becomes the composed custom element, and its Declarative Shadow DOM
443
+ * (`<template shadowrootmode="open">`) wraps the source elements, each marked
444
+ * with `data-wc-source="<id>"` and optionally `data-wc-expose="..."`:
445
+ *
446
+ * ```html
447
+ * <my-ai-workbench data-wc-composite-definition>
448
+ * <template shadowrootmode="open">
449
+ * <s3-uploader data-wc-source="s3"></s3-uploader>
450
+ * <ai-agent data-wc-source="ai"></ai-agent>
451
+ * </template>
452
+ * </my-ai-workbench>
453
+ * ```
454
+ *
455
+ * Resolves once every discovered definition has been registered (awaiting each
456
+ * definition's source tags via `customElements.whenDefined`). Returns the
457
+ * generated constructors in document order.
458
+ */
459
+ export async function registerCompositeDefinitions(root = documentRef, options) {
460
+ if (!customElementsRef || !documentRef) {
461
+ throw new Error("@wc-bindable/composite: registerCompositeDefinitions requires a DOM (customElements/document)");
462
+ }
463
+ if (!root) {
464
+ throw new Error("@wc-bindable/composite: no root provided and no global document available");
465
+ }
466
+ // Include `root` itself when it is a matching definition element, not only its
467
+ // descendants (`querySelectorAll` searches descendants only), so passing a
468
+ // definition element directly works as a caller would expect.
469
+ const definitions = Array.from(root.querySelectorAll("[data-wc-composite-definition]"));
470
+ if (root instanceof Element &&
471
+ root.matches("[data-wc-composite-definition]") &&
472
+ !definitions.includes(root)) {
473
+ definitions.unshift(root);
474
+ }
475
+ const results = [];
476
+ for (const def of definitions) {
477
+ const parsed = parseDefinition(def);
478
+ if (!parsed)
479
+ continue;
480
+ results.push(defineComposite({
481
+ tagName: def.localName,
482
+ sources: parsed.sources,
483
+ expose: parsed.expose,
484
+ localFacade: options?.localFacade,
485
+ remoteCompatible: options?.remoteCompatible,
486
+ logger: options?.logger,
487
+ }));
488
+ }
489
+ return Promise.all(results);
490
+ }
491
+ //# sourceMappingURL=declarative.js.map