@twobirds/microcomponents 0.10.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +13 -3
  2. package/dist/MC.min.js +1 -1
  3. package/dist/autoload.min.js +1 -1
  4. package/dist/cli/create.d.ts.map +1 -1
  5. package/dist/cli/dev.d.ts +3 -1
  6. package/dist/cli/dev.d.ts.map +1 -1
  7. package/dist/cli/dispatch.d.ts +2 -0
  8. package/dist/cli/dispatch.d.ts.map +1 -1
  9. package/dist/cli/index.js +110 -18
  10. package/dist/cli/preview.d.ts +3 -1
  11. package/dist/cli/preview.d.ts.map +1 -1
  12. package/dist/core/MC.d.ts +1 -1
  13. package/dist/core/MC.d.ts.map +1 -1
  14. package/dist/core/elements.d.ts.map +1 -1
  15. package/dist/core/elements.js +12 -5
  16. package/dist/core/mcGuards.js +6 -1
  17. package/dist/docs/cli.d.ts +1 -1
  18. package/dist/elements.min.js +1 -1
  19. package/dist/formValues.min.js +1 -1
  20. package/dist/helpers.min.js +1 -0
  21. package/dist/mcGuards.min.js +1 -1
  22. package/dist/mcp/api.json +30 -4
  23. package/dist/mcp/concepts/mc-types.md +15 -8
  24. package/dist/mcp/docs.d.ts +55 -0
  25. package/dist/mcp/docs.d.ts.map +1 -0
  26. package/dist/mcp/index.js +320 -203
  27. package/dist/mcp/server.d.ts +43 -0
  28. package/dist/mcp/server.d.ts.map +1 -0
  29. package/dist/mcp/tools.d.ts +54 -0
  30. package/dist/mcp/tools.d.ts.map +1 -0
  31. package/dist/microcomponents.d.ts +1 -0
  32. package/dist/microcomponents.d.ts.map +1 -1
  33. package/dist/microcomponents.js +84 -39
  34. package/dist/microcomponents.min.js +1 -1
  35. package/dist/observables.min.js +1 -1
  36. package/dist/placeholders.min.js +1 -0
  37. package/dist/state/formValues.d.ts.map +1 -1
  38. package/dist/state/formValues.js +59 -31
  39. package/dist/state/index.d.ts +2 -0
  40. package/dist/state/index.d.ts.map +1 -1
  41. package/dist/state/observables.d.ts.map +1 -1
  42. package/dist/state/observables.js +55 -28
  43. package/dist/state/placeholders.d.ts +0 -1
  44. package/dist/state/placeholders.d.ts.map +1 -1
  45. package/dist/state/placeholders.js +1980 -0
  46. package/dist/utils/autoload.d.ts.map +1 -1
  47. package/dist/utils/autoload.js +1451 -0
  48. package/dist/utils/events.d.ts +1 -1
  49. package/dist/utils/events.d.ts.map +1 -1
  50. package/dist/utils/helpers.d.ts +3 -0
  51. package/dist/utils/helpers.d.ts.map +1 -1
  52. package/dist/utils/helpers.js +693 -0
  53. package/dist/utils/index.d.ts +1 -1
  54. package/dist/utils/index.d.ts.map +1 -1
  55. package/package.json +23 -5
@@ -0,0 +1,1980 @@
1
+ //#region src/utils/events.ts
2
+ /**
3
+ @module Events
4
+
5
+ This module provides event utilities for interfacing **between microcomponents and external
6
+ frameworks or native DOM/JS environments**. It is not intended for communication between
7
+ frontend microcomponents themselves — for that purpose, use the inherited methods
8
+ ( `.on()`, `.one()`, `.off()`, `.trigger()`) that exist when you extend `DC`.
9
+
10
+ Import this module when you need to exchange information with microcomponents from outside
11
+ the microcomponent system (e.g., vanilla JS, React via `useRef()`, or other frameworks).
12
+
13
+ The core feature is the ability to explicitly control event flow direction when using {@link trigger}:
14
+ - upward propagation to ancestor components ('u')
15
+ - local dispatch only ('l') [default]
16
+ - downward propagation to descendant components ('d').
17
+
18
+ @example
19
+ html:
20
+ ```html
21
+ <div class="grandparent">
22
+ <div class="parent">
23
+ <div class="child">
24
+ </div>
25
+ </div>
26
+ </div>
27
+ ```
28
+
29
+ javascript:
30
+ ```javascript
31
+ import { on, one, trigger, off } from '@twobirds/microcomponents/events';
32
+
33
+ const grandParent = document.querySelector('.grandparent');
34
+ const parent = document.querySelector('.parent');
35
+ const child = document.querySelector('.child');
36
+ if (!grandParent || !parent || !child) throw new Error('example markup missing');
37
+
38
+ const grandParentHandler = on(grandParent, 'dataReady', (ev) => console.log(ev.detail.data));
39
+
40
+ const parentHandler = on(parent, 'dataReady', (ev) => ev.detail.control.stop());
41
+
42
+ trigger(child, 'dataReady', { value: 42 }, 'u');
43
+
44
+ off(parent, 'dataReady', parentHandler);
45
+ off(grandParent, 'dataReady', grandParentHandler);
46
+ ```
47
+
48
+ The `dataReady` event bubbles upward from the innermost `div`, but `parentHandler`
49
+ calls `ev.detail.control.stop()`, so the `grandParent` handler is never reached.
50
+ Handlers are detached with `off()` once they are no longer needed.
51
+ */
52
+ /**
53
+ * Returns the correct event name to listen for on a DOM element.
54
+ *
55
+ * If `eventName` (case-insensitive) matches a native HTML event handler property
56
+ * (`'on' + eventName.toLowerCase()`) on the target, returns the lowercase native
57
+ * name so that standard DOM events like `'click'` are listened to correctly.
58
+ * Otherwise, prefixes with `_mc` for microcomponent custom events.
59
+ *
60
+ * @hidden
61
+ * @param target - The DOM element whose native event support is checked.
62
+ * @param eventName - The event name as provided by the caller (e.g., `'click'`, `'Update'`).
63
+ * @returns The resolved event name: lowercase native or `_mc`-prefixed custom.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const btn = document.createElement('button');
68
+ * console.log(trueEventName(btn, 'Click'));
69
+ * console.log(trueEventName(btn, 'Update'));
70
+ * ```
71
+ *
72
+ * `'Click'` resolves to the native `'click'` because the button has an `onclick` handler
73
+ * property; `'Update'` has no native counterpart, so it becomes the `_mc`-prefixed custom
74
+ * event name.
75
+ */
76
+ function trueEventName(target, eventName) {
77
+ const lower = eventName.toLowerCase();
78
+ if ("on" + lower in target) return lower;
79
+ return "_mc" + eventName[0].toUpperCase() + eventName.substring(1);
80
+ }
81
+ /**
82
+ Removes a previously attached event handler from the DOM node. See {@link on} and {@link one}.
83
+
84
+ Uses internal microcomponent-prefixed naming for event handlers.
85
+ This is primarily used to interface with external frameworks or vanilla JS environments.
86
+ For communication between frontend microcomponents, use the `DC.off()` method instead.
87
+
88
+ @param target - The DOM element from which to remove the listener.
89
+ @param eventName - The name of the event (e.g., 'click', 'update').
90
+ @param handler - The listener function or object to detach.
91
+
92
+ @example
93
+ ```ts
94
+ const handler = on(myElement, 'click', () => console.log('clicked'));
95
+ off(myElement, 'click', handler);
96
+ ```
97
+ @group Events
98
+ */
99
+ function off(target, eventName, handler) {
100
+ /* v8 ignore next */
101
+ if (!target) return;
102
+ if (typeof target === "string") {
103
+ document.querySelectorAll(target).forEach((el) => off(el, eventName, handler));
104
+ return;
105
+ }
106
+ target.removeEventListener(trueEventName(target, eventName), handler);
107
+ }
108
+ /**
109
+ Attaches a persistent event listener that will fire every time the specified event occurs.
110
+
111
+ This is primarily used to interface with external frameworks or vanilla JS environments.
112
+ For communication between frontend microcomponents, use the `DC.on()` method instead.
113
+
114
+ The handler receives a `CustomEvent<McDetail<D>>`: the payload sits under
115
+ `ev.detail.data`, the bubble-control handle under `ev.detail.control`.
116
+
117
+ @param target - The DOM element to attach the listener to.
118
+ @param eventName - The name of the event (e.g., 'click', 'update').
119
+ @param handler - The callback function or object to invoke on each event.
120
+ @param once - If true, remove the listener after first invocation.
121
+ @returns The attached handler reference. Useful for later deletion with {@link off}.
122
+
123
+ @example
124
+ ```ts
125
+ const handler = on<{ value: number }>(myElement, 'update', (ev) => {
126
+ console.log(ev.detail.data.value);
127
+ });
128
+ off(myElement, 'update', handler);
129
+ ```
130
+ @group Events
131
+ */
132
+ function on(target, eventName, handler, once = false) {
133
+ /* v8 ignore next */
134
+ if (!target) return;
135
+ if (typeof target === "string") {
136
+ document.querySelectorAll(target).forEach((el) => on(el, eventName, handler));
137
+ return;
138
+ }
139
+ target.addEventListener(trueEventName(target, eventName), handler, {
140
+ capture: false,
141
+ once
142
+ });
143
+ return handler;
144
+ }
145
+ /**
146
+ Attaches an event listener that will fire only once.
147
+
148
+ Internally calls {@link on} with the `once` flag set to true. The handler
149
+ is automatically removed after its first invocation.
150
+ This is primarily used to interface with external frameworks or vanilla JS environments.
151
+ For communication between frontend microcomponents, use the `DC.one()` method instead.
152
+
153
+ @param target - The DOM element to attach the listener to.
154
+ @param eventName - The name of the event (e.g., 'click', 'update').
155
+ @param handler - The callback function or object to invoke once.
156
+ @returns The attached one-time handler reference. Useful for later deletion with {@link off}.
157
+
158
+ @example
159
+ ```ts
160
+ one<{ ready: boolean }>(myElement, 'dataReady', (ev) => console.log('received:', ev.detail.data));
161
+ ```
162
+
163
+ The listener fires only once and detaches automatically.
164
+ @group Events
165
+ */
166
+ function one(target, eventName, handler) {
167
+ /* v8 ignore next */
168
+ if (!target) return;
169
+ if (typeof target === "string") {
170
+ document.querySelectorAll(target).forEach((el) => one(el, eventName, handler));
171
+ return;
172
+ }
173
+ on(target, eventName, handler, true);
174
+ return handler;
175
+ }
176
+ /**
177
+ * @hidden
178
+ * A controller object used to manage and potentially abort event bubbling.
179
+ *
180
+ * The `trigger()` function internally creates instance of this class,
181
+ * allowing the an eventual handler to call `ev.detail.control.stop()` to
182
+ * prevent further propagation in either direction (up/down).
183
+ *
184
+ * This is only used internally.
185
+ * @example
186
+ * ```ts
187
+ * trigger(myElement, 'update', { value: 42 }, 'u');
188
+ *
189
+ * onUpdate(ev) {
190
+ * ev.detail.control.stop();
191
+ * }
192
+ * ```
193
+ */
194
+ var BubbleController = class {
195
+ stopped = false;
196
+ constructor() {}
197
+ /**
198
+ * Signals that event bubbling should be halted.
199
+ *
200
+ * After calling this method, subsequent `trigger()` calls will abort
201
+ * before dispatching the event to any targets.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * trigger(myElement, 'update', { value: 42 }, 'u');
206
+ *
207
+ * onUpdate(ev) {
208
+ * ev.detail.control.stop();
209
+ * }
210
+ * ```
211
+ */
212
+ stop() {
213
+ this.stopped = true;
214
+ }
215
+ };
216
+ /**
217
+ * Creates and dispatches a custom event on the specified DOM node.
218
+ *
219
+ * The event is namespaced with an `_mc` prefix by default, unless already prefixed.
220
+ * Supports bidirectional bubbling (up/down the DOM tree) based on the `bubble` parameter:
221
+ * - 'l': local dispatch only
222
+ * - 'u': bubble up towards ancestors
223
+ * - 'd': bubble down to descendants
224
+ *
225
+ * The dispatched event is a `CustomEvent<McDetail<D>>`: handlers find the payload
226
+ * under `ev.detail.data` and can call `ev.detail.control.stop()` to cancel bubbling.
227
+ *
228
+ * Prefer a direct target over bubbling: name the receiving element in `target` and keep the
229
+ * default `'l'`, so one `querySelectorAll` reaches it in a single step. Reserve `'u'`/`'d'`
230
+ * for receivers that cannot be named in advance, since they walk the tree and re-dispatch the
231
+ * event at every level. Pass a typed object as `data` rather than a bare string, so the
232
+ * handler reads named fields from `ev.detail.data` and the flow stays readable as it grows.
233
+ *
234
+ * @param target - The DOM element on which to trigger the event, or a querySelectorAll(selector) selector string.
235
+ * @param event - The name of the event (will be prefixed if needed).
236
+ * @param data - Additional data payload attached to `event.detail.data`.
237
+ * @param bubble - Bubbling direction ('l', 'u', 'd' or combinations).
238
+ * @param controller - Optional controller for managing bubbling behavior.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * trigger(myElement, 'update', { value: 42 }, 'l');
243
+ * trigger(myElement, 'dataReady', { ready: true }, 'u');
244
+ * ```
245
+ *
246
+ * The first dispatch fires locally only; the second bubbles upward to ancestor components.
247
+ */
248
+ function trigger(target, event, data = {}, bubble = "l", controller) {
249
+ /* v8 ignore next */
250
+ if (!target) return;
251
+ if (typeof target === "string") {
252
+ document.querySelectorAll(target).forEach((el) => trigger(el, event, data, bubble));
253
+ return;
254
+ }
255
+ const eventName = /^_mc/.test(event) ? event : trueEventName(target, event), bubbleController = controller ? controller : new BubbleController(), ev = new CustomEvent(eventName, {
256
+ detail: {
257
+ data,
258
+ control: bubbleController
259
+ },
260
+ bubbles: false
261
+ });
262
+ if (bubbleController.stopped) return;
263
+ if (/l/.test(bubble)) {
264
+ target.dispatchEvent(ev);
265
+ if (bubbleController.stopped) return;
266
+ }
267
+ if (/[ud]/.test(bubble)) queueMicrotask(() => {
268
+ if (bubble.indexOf("u") > -1) trigger(target.parentElement, eventName, data, "lu", bubbleController);
269
+ if (bubble.indexOf("d") > -1) for (const child of target.children) trigger(child, eventName, data, "ld");
270
+ });
271
+ }
272
+ //#endregion
273
+ //#region src/utils/helpers.ts
274
+ /**
275
+ * Determines whether the current runtime environment is a web browser.
276
+ *
277
+ * This function works by attempting to access `this` within an anonymous function
278
+ * and checking if it refers to the global `window` object. It returns `true`
279
+ * when executed in a browser context, and `false` otherwise (e.g., Node.js).
280
+ *
281
+ * Note: While modern environments typically provide more reliable detection mechanisms,
282
+ * this fallback remains compatible across older runtimes where other detection techniques
283
+ * may be unreliable.
284
+ *
285
+ * @returns `true` if the code is running in a browser environment, `false` otherwise.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * if (isBrowser()) {
290
+ * console.log('Running in a browser');
291
+ * }
292
+ * ```
293
+ */
294
+ function isBrowser() {
295
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
296
+ }
297
+ /**
298
+ * Checks if a value is a native JavaScript object (created via {} or new Object()).
299
+ * @param value - The value to check.
300
+ * @returns True if the value is a plain object, false otherwise.
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * console.log(isNativeObject({}));
305
+ * console.log(isNativeObject(new Object()));
306
+ * console.log(isNativeObject([]));
307
+ * console.log(isNativeObject(null));
308
+ * ```
309
+ */
310
+ function isNativeObject(value) {
311
+ return typeof value === "object" && value !== null && value.constructor === Object;
312
+ }
313
+ /**
314
+ * Recursively sorts all keys in an object alphabetically, preserving nested structure.
315
+ * @param source - The object to sort.
316
+ * @returns A new object with sorted keys at all levels.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * const obj = { z: 1, a: { y: 2, b: 3 } };
321
+ * console.log(JSON.stringify(sortObject(obj)));
322
+ * ```
323
+ */
324
+ function sortObject(source) {
325
+ const result = {}, keys = Object.keys(source).sort();
326
+ for (let i = 0; i < keys.length; i++) {
327
+ const key = keys[i], value = source[key];
328
+ if (isNativeObject(value)) result[key] = sortObject(value);
329
+ else result[key] = value;
330
+ }
331
+ return result;
332
+ }
333
+ /**
334
+ * Flattens a nested object into a single-level object with dot-separated keys.
335
+ * Optionally sorts the resulting flat keys alphabetically (default: true).
336
+ * @param source - The object to flatten.
337
+ * @param doSort - Whether to sort the resulting keys (default: true).
338
+ * @returns A flattened object with dot-notation keys.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * const obj = { user: { name: 'Alice', age: 30 } };
343
+ * console.log(JSON.stringify(flattenObject(obj)));
344
+ * ```
345
+ */
346
+ function flattenObject(source, doSort = true) {
347
+ const result = {};
348
+ const record = source;
349
+ const names = Object.getOwnPropertyNames(source);
350
+ for (let i = 0; i < names.length; i++) {
351
+ const propName = names[i], value = record[propName];
352
+ if (value instanceof Object) {
353
+ const temp = flattenObject(value, false);
354
+ for (const j in temp) result[propName + "." + j] = temp[j];
355
+ } else result[propName] = value;
356
+ }
357
+ return doSort ? sortObject(result) : result;
358
+ }
359
+ /**
360
+ * Structural deep-equality using SameValueZero for primitives.
361
+ *
362
+ * See {@link https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero}.
363
+ *
364
+ * Note: `Map`/`Set` are not structurally compared.
365
+ *
366
+ * @param a - The first value to compare.
367
+ * @param b - The second value to compare.
368
+ * @returns True if the values are deeply equal, false otherwise.
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * console.log(deepEqual({ a: 1 }, { a: 1 }));
373
+ * console.log(deepEqual({ a: { b: 2 } }, { a: {} }));
374
+ * console.log(deepEqual({ a: NaN }, { a: NaN }));
375
+ * console.log(deepEqual({ a: NaN }, { a: null }));
376
+ * ```
377
+ */
378
+ function deepEqual(a, b) {
379
+ if (a === b || a !== a && b !== b) return true;
380
+ /* v8 ignore start */
381
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return false;
382
+ if (a.constructor !== b.constructor) return false;
383
+ if (a instanceof Date) return a.getTime() === b.getTime();
384
+ if (a instanceof RegExp) return a.toString() === b.toString();
385
+ /* v8 ignore end */
386
+ if (Array.isArray(a)) {
387
+ const bArr = b;
388
+ /* v8 ignore next */
389
+ if (a.length !== bArr.length) return false;
390
+ for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], bArr[i])) return false;
391
+ return true;
392
+ }
393
+ const aObj = a, bObj = b, keys = Object.keys(aObj);
394
+ if (keys.length !== Object.keys(bObj).length) return false;
395
+ for (let i = 0; i < keys.length; i++) {
396
+ const key = keys[i];
397
+ if (!Object.prototype.hasOwnProperty.call(bObj, key) || !deepEqual(aObj[key], bObj[key])) return false;
398
+ }
399
+ return true;
400
+ }
401
+ /**
402
+ * Converts a PascalCase string to kebab-case.
403
+ * Example: 'MyComponentName' -> 'my-component-name'
404
+ * @param str - The PascalCase string to convert.
405
+ * @returns The converted kebab-case string.
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * console.log(pascalToKebab('MyElement'));
410
+ * ```
411
+ */
412
+ function pascalToKebab(str) {
413
+ return str.replace(/[A-Z]/g, (m, i) => (i ? "-" : "") + m.toLowerCase());
414
+ }
415
+ /**
416
+ * Copies all getter and setter properties from a source object to a target object.
417
+ * Does not copy methods or regular data properties—only accessor properties (get/set).
418
+ * @hidden
419
+ * @param source - The source object with getters and/or setters to copy.
420
+ * @param target - The target object to which the accessors will be copied.
421
+ *
422
+ * @example
423
+ * ```ts
424
+ * const src = { get name() { return 'Alice'; } };
425
+ * const tgt = {};
426
+ * copyGettersSetters(src, tgt);
427
+ * console.log(tgt.name);
428
+ * ```
429
+ */
430
+ function copyGettersSetters(source, target) {
431
+ const descriptors = Object.getOwnPropertyDescriptors(source);
432
+ for (const [key, descriptor] of Object.entries(descriptors)) if ("get" in descriptor || "set" in descriptor) Object.defineProperty(target, key, descriptor);
433
+ }
434
+ /**
435
+ * Injects a CSS string into the given scope (document or shadow root) as an adopted stylesheet.
436
+ * Enables css-in-js so that every custom element is self-contained and importable.
437
+ *
438
+ * @hidden
439
+ * @param target - The scope to inject styles into: `document` for global styles, or a `ShadowRoot` for encapsulated component internals.
440
+ * @param css - The CSS string to inject.
441
+ * @returns The created `CSSStyleSheet` instance that was adopted into the target scope.
442
+ *
443
+ * When targeting **document**: selectors like `:host`, `::slotted()`, and shadow-internal classes are **not allowed** — they have no effect outside a shadow root. Use only global selectors, element tags, or layout presets.
444
+ * When targeting **shadowRoot**: use `:host` for the custom element itself, standard selectors (`.inner`, `#id`) for internal structure, and `::slotted()` for projected light-DOM content.
445
+ *
446
+ * @example Inject global styles into the document:
447
+ * ```ts
448
+ * import { injectCSS } from '@twobirds/mc/utils/helpers';
449
+ * injectCSS(document, 'body { display: block; }');
450
+ * ```
451
+ *
452
+ * @example Inject global styles for a micro component into the document:
453
+ * ```ts
454
+ * import { injectCSS } from '@twobirds/mc/utils/helpers';
455
+ * injectCSS(document, 'my-microcomponent { display: block; }');
456
+ * ```
457
+ *
458
+ * @example Inject scoped styles into a shadow root:
459
+ * ```ts
460
+ * const shadow = element.attachShadow({ mode: 'open' });
461
+ * injectCSS(shadow, ':host { color: var(--text); } .inner { padding: 8px; }');
462
+ * ```
463
+ * Styles can also be added using a compound innerHTML statement: `shadow.innerHTML = \`<style>${style}</style>${template}\``
464
+ */
465
+ var _injectedCSS = /* @__PURE__ */ new WeakMap();
466
+ function injectCSS(target, css) {
467
+ const injected = _injectedCSS.get(target) ?? /* @__PURE__ */ new Set();
468
+ if (injected.has(css)) return target.adoptedStyleSheets[0];
469
+ injected.add(css);
470
+ _injectedCSS.set(target, injected);
471
+ const sheet = new CSSStyleSheet();
472
+ sheet.replaceSync(css);
473
+ target.adoptedStyleSheets.push(sheet);
474
+ return sheet;
475
+ }
476
+ /**
477
+ * Processes a record of asset strings and applies them to the given target element.
478
+ * Supports injecting CSS into document or shadow root, and setting innerHTML for
479
+ * both target and shadow DOM. Automatically attaches a shadow root if any key starts
480
+ * with `'shadow'`.
481
+ *
482
+ * Recognized keys: `'css'`, `'targetCss'` (document-level styles), `'shadowCss'`
483
+ * (shadow-root styles), `'shadowHtml'` (shadow innerHTML), `'targetHtml'` (target innerHTML).
484
+ *
485
+ * @param instance - The micro component to apply assets onto.
486
+ * @param assets - A record mapping asset type keys to their string content.
487
+ *
488
+ * @example
489
+ * ```ts
490
+ * processAssets(this, {
491
+ * css: 'body { margin: 0; }',
492
+ * shadowCss: ':host { display: block; }',
493
+ * shadowHtml: '<slot></slot>'
494
+ * });
495
+ * ```
496
+ */
497
+ function processAssets(instance, assets) {
498
+ const target = instance.target;
499
+ let shadow = target.shadowRoot;
500
+ if (!shadow && Object.keys(assets).some((key) => key.indexOf("shadow") === 0)) shadow = target.attachShadow({ mode: "open" });
501
+ Object.keys(assets).forEach((key) => {
502
+ switch (key) {
503
+ case "css":
504
+ injectCSS(document, assets[key]);
505
+ break;
506
+ case "targetCss":
507
+ injectCSS(document, assets[key]);
508
+ break;
509
+ case "shadowCss":
510
+ injectCSS(shadow, assets[key]);
511
+ break;
512
+ case "shadowHtml":
513
+ shadow.innerHTML = assets[key];
514
+ bindTemplateEvents(shadow, instance);
515
+ break;
516
+ case "targetHtml":
517
+ target.innerHTML = assets[key];
518
+ bindTemplateEvents(target, instance);
519
+ break;
520
+ }
521
+ });
522
+ }
523
+ /**
524
+ * Loads companion asset files (CSS, HTML) for a given component basename from the server.
525
+ *
526
+ * Each entry in `assets` encodes an optional variant and extension in camelCase, e.g. `'shadowCss'` → `{name}.shadow.css`,
527
+ * `'targetHtml'` → `{name}.target.html`. Plain entries like `'css'` or `'html'` resolve to
528
+ * `{name}.css` / `{name}.html`.
529
+ *
530
+ * In bundled mode the Vite plugin replaces this call with an inline array literal, so `.then()`
531
+ * fires synchronously — no async overhead.
532
+ *
533
+ * @hidden
534
+ * @param name - The component basename (e.g. `'shop-catalog'`).
535
+ * @param assets - Array of asset descriptors such as `'shadowCss'`, `'targetHtml'`, `'shadowHtml'`, `'css'`, `'html'`.
536
+ * @returns A promise resolving to an array of file contents in the same order as `assets`. If a file is not found, the corresponding entry is `'file not found: ' + filename`.
537
+ *
538
+ * @example
539
+ * ```ts
540
+ * export const MyComponent = loadAssets('my-component', ['shadowCss', 'shadowHtml']).then(([shadowCss, shadowHtml]) => {
541
+ * class _MyComponent extends DC { ... }
542
+ * defineCE('my-component', _MyComponent);
543
+ * return _MyComponent;
544
+ * });
545
+ * ```
546
+ */
547
+ function loadAssets(name, assets) {
548
+ const parseAsset = (asset) => {
549
+ const m = asset.match(/^([a-z]+)([A-Z][a-z]*)$/);
550
+ if (m) return `./${name.replace(/-/g, "/")}.${m[1]}.${m[2].toLowerCase()}`;
551
+ return `./${name.replace(/-/g, "/")}.${asset.toLowerCase()}`;
552
+ };
553
+ return Promise.all(assets.map(async (asset) => {
554
+ const filename = parseAsset(asset);
555
+ try {
556
+ const resp = await fetch(filename);
557
+ if (!resp.ok) return `file not found: ${filename}`;
558
+ if (filename.endsWith("json")) {
559
+ const text = await resp.text();
560
+ try {
561
+ return JSON.parse(text);
562
+ } catch {
563
+ console.error(`could not JSON.parse() asset '${asset}' from ${filename}:\n`, text);
564
+ return null;
565
+ }
566
+ }
567
+ return resp.text();
568
+ } catch {
569
+ return `file not found: ${filename}`;
570
+ }
571
+ }));
572
+ }
573
+ /**
574
+ * Binds declarative event attributes in a template fragment to microcomponent triggers.
575
+ *
576
+ * Scans all elements under `root` for attributes whose names correspond to native DOM
577
+ * events (e.g. `click`, `submit`, `change`). The attribute value encodes the target and
578
+ * handler method in the form `target|methodName`:
579
+ *
580
+ * - `this|myHandler` — triggers locally on the component attached to this element.
581
+ * - `other-comp|submit` — resolves elements via `querySelectorAll('other-comp')` and
582
+ * triggers the event on each matched host's `_mc`.
583
+ *
584
+ * An optional sibling `payload` attribute supplies the data argument for `trigger()`.
585
+ * After binding, both the event attribute and the payload attribute are removed from the DOM.
586
+ *
587
+ * @param rootElement - The container element whose descendants should be scanned for bindings.
588
+ * @param instance - The instance to trigger events on.
589
+ *
590
+ * @example
591
+ * ```html
592
+ * <button click='this|onSubmit|{"action":"go"}'>Submit</button>
593
+ * <input change="|cart-form|refresh">
594
+ * ```
595
+ */
596
+ function bindTemplateEvents(rootElement, instance) {
597
+ const allElements = [...rootElement.querySelectorAll("*")];
598
+ for (const el of allElements) {
599
+ if (!(el instanceof HTMLElement)) continue;
600
+ const attrs = [...el.attributes];
601
+ for (const attr of attrs) {
602
+ const lowerName = attr.name.toLowerCase();
603
+ if (!("on" + lowerName in el)) continue;
604
+ const parts = attr.value.trim().split("|");
605
+ if (parts.length < 2) continue;
606
+ const [selector, event, payload] = parts;
607
+ el.removeAttribute(attr.name);
608
+ let payloadData;
609
+ if (payload) try {
610
+ payloadData = JSON.parse(payload);
611
+ } catch {
612
+ payloadData = payload;
613
+ }
614
+ if (selector === "this" || selector === "") on(el, lowerName, () => instance.trigger(event, payloadData));
615
+ else on(el, lowerName, () => trigger(selector, event, payloadData));
616
+ }
617
+ }
618
+ }
619
+ //#endregion
620
+ //#region src/core/mcGuards.ts
621
+ function isMcHost(element, key) {
622
+ if (typeof HTMLElement === "undefined" || !(element instanceof HTMLElement)) return false;
623
+ if (!("_mc" in element)) return false;
624
+ if (key === void 0) return true;
625
+ const mc = element._mc;
626
+ if (typeof mc !== "object" || mc === null) return false;
627
+ return key in mc;
628
+ }
629
+ //#endregion
630
+ //#region src/core/MC.ts
631
+ function add(targetHTMLElement, key, element = {}) {
632
+ const node = targetHTMLElement;
633
+ if (!("_mc" in targetHTMLElement)) node._mc = new DC(targetHTMLElement);
634
+ const _mc = node._mc;
635
+ if (key.length) {
636
+ _mc[key] = element;
637
+ if (targetHTMLElement instanceof HTMLElement && !targetHTMLElement.getAttribute("data-mc")) targetHTMLElement.setAttribute("data-mc", "");
638
+ }
639
+ return node;
640
+ }
641
+ /**
642
+ Removes a named microcomponent from the internal `_mc` collection of a target DOM node.
643
+
644
+ This function deletes the specified key from the element's `_mc` hash object and, if the
645
+ collection becomes empty, removes the `data-mc` attribute from the DOM node.
646
+
647
+ The bare poisoned value (`el._mc.gone` without member access) is `never`,
648
+ which is assignable to anything — only member/method use of a removed entry is caught.
649
+
650
+ @template T - A plain or already-enhanced element type.
651
+ @template K - The literal registration key; its entry is poisoned in the registry type.
652
+ @param target - The DOM element whose microcomponent should be removed.
653
+ @param key - The property name/key corresponding to the microcomponent to remove.
654
+ */
655
+ function remove(target, key) {
656
+ if (!key) return;
657
+ const _mc = target._mc;
658
+ if (!_mc) return;
659
+ if (_mc[key]) delete _mc[key];
660
+ if (!Object.keys(_mc).length && target instanceof HTMLElement && target.hasAttribute("data-mc")) target.removeAttribute("data-mc");
661
+ }
662
+ /**
663
+ Runs the "Init" lifecycle event on a DOM microcomponent instance.
664
+
665
+ This function schedules the `trigger('Init')` call in a microtask, ensuring
666
+ that all synchronous initialization is complete before the lifecycle hook
667
+ executes. The {@link DC} constructor calls it once the declared assets are in
668
+ place — synchronously in a bundled build, after the fetch resolves in a
669
+ dev/autoload build — so `oneInit()` always sees the loaded assets. Only `DC`
670
+ instances have an Init lifecycle — the `DC` constructor calls this exclusively,
671
+ so the signature encodes that invariant instead of re-checking it at runtime.
672
+
673
+ @param element - The DOM microcomponent instance on which to trigger the Init event.
674
+ */
675
+ function init(element) {
676
+ queueMicrotask(() => {
677
+ element.trigger("Init", null);
678
+ });
679
+ }
680
+ /**
681
+ Attaches event listeners to DOM elements based on method naming conventions.
682
+
683
+ Scans the prototype of the provided element and attaches listeners for methods
684
+ prefixed with `on` or `one`, corresponding to either native HTML events (e.g.,
685
+ 'onclick') or microcomponent-prefixed custom events (e.g., '_mcUpdate').
686
+
687
+ @param element - The instance whose prototype should be scanned for event handlers.
688
+ */
689
+ function autoAttachListeners(element) {
690
+ const sourceTarget = element.target;
691
+ const prototype = Object.getPrototypeOf(element);
692
+ const sourceElement = element;
693
+ const definedEventHandlerNames = Object.getOwnPropertyNames(prototype).filter((key) => /^(on[A-Z]|one[A-Z])/.test(key) && typeof prototype[key] === "function");
694
+ for (const eventHandlerName of definedEventHandlerNames) {
695
+ const once = /^one/.test(eventHandlerName);
696
+ const eventName = eventHandlerName.replace(/^one?/, "");
697
+ const listener = (ev) => sourceElement[eventHandlerName](ev);
698
+ on(sourceTarget, eventName, listener, once);
699
+ }
700
+ }
701
+ /**
702
+ Retrieves immediate child microcomponents of a DOM node.
703
+
704
+ Queries the DOM for descendant elements marked with `data-mc` that are direct
705
+ children of the provided element and returns their associated `_mc` instances.
706
+
707
+ @param domNode - The DOM element whose child microcomponents to find.
708
+ @returns An array of child microcomponent instances.
709
+ */
710
+ function getMcChildNodes(domNode) {
711
+ return Array.from(domNode.querySelectorAll("[data-mc]:not(:scope [data-mc] [data-mc])")).filter((e) => e instanceof HTMLElement && "_mc" in e).map((e) => e._mc);
712
+ }
713
+ /**
714
+ Walks up the DOM from `from`, returning the `_mc` controller of the nearest
715
+ `data-mc` ancestor — restricted, when `key` is given, to hosts whose registry
716
+ actually carries that key. Hosts marked `data-mc` but not (yet) carrying an
717
+ `_mc` record (e.g. autoload pending) are skipped rather than returned.
718
+
719
+ @param from - The element whose ancestors to search (exclusive).
720
+ @param key - Optional registry key the ancestor's `_mc` must contain.
721
+ @returns The nearest matching controller, or null.
722
+ */
723
+ function findMcAncestor(from, key) {
724
+ let el = from.parentElement?.closest("[data-mc]");
725
+ while (el instanceof HTMLElement) {
726
+ /* v8 ignore next */
727
+ if ("_mc" in el) {
728
+ const mc = el._mc;
729
+ if (key === void 0 || key in mc) return mc;
730
+ }
731
+ el = el.parentElement?.closest("[data-mc]");
732
+ }
733
+ return null;
734
+ }
735
+ /**
736
+ The base class for all microcomponents — shared root of both {@link MC} and {@link DC}.
737
+
738
+ Holds a `WeakRef` to the target (a DOM element for `DC`, or any plain object for `MC`)
739
+ to avoid circular references. It starts loading any `static assets` for `MC` and `DC`
740
+ alike (shared per class through `_assetsPromise`), read through the {@link McBase.assets}
741
+ getter. For `DC` subclasses it bootstraps one automatic behaviour:
742
+
743
+ 1. **Event listener auto-attachment** — methods whose names start with `on` or `one`
744
+ (e.g. `onClick`, `oneInit`) are wired to the target element via {@link on} / {@link one}.
745
+
746
+ The **"Init" lifecycle event** and the DOM attach of auto-attached assets are dispatched
747
+ by the {@link DC} constructor — after the declared assets are in place — so that
748
+ `oneInit()` runs once the instance is fully constructed and its assets are loaded. Plain
749
+ `MC` instances fetch their assets server-side with no DOM attach and no `Init` lifecycle,
750
+ keeping server-side usage lightweight.
751
+
752
+ ### Plugin extension points
753
+
754
+ The prototype of `McBase` is the attachment point for optional plugins that curry
755
+ additional instance methods onto every microcomponent. Two built-in plugins modify
756
+ this class at runtime:
757
+
758
+ - **{@link State.observePlugin}** — adds `notify()`, `subscribe()`, and `bind()` so that
759
+ observable properties can be controlled directly on the component instance with
760
+ fluent chaining. Call `observePlugin(DC)` once at module level to activate.
761
+
762
+ - **{@link State.formValuePlugin}** — adds `formValues()` for two-way binding between DOM
763
+ form controls and an observable property. Also pulls in all methods from
764
+ {@link State.observePlugin}, so you can chain `.subscribe()` and `.bind()` after
765
+ `.formValues()`. Call `formValuePlugin(DC)` once at module level to activate.
766
+
767
+ Both plugins are idempotent — calling them multiple times has no side effects. They
768
+ work by assigning methods onto `McBase.prototype` (reached via
769
+ `Object.getPrototypeOf(Class.prototype)`) and use TypeScript module augmentation
770
+ (`declare module`) so the added signatures appear in type-checking automatically.
771
+
772
+ @template TTarget - The concrete type of the wrapped target; preserved by the
773
+ {@link McBase.target} getter.
774
+
775
+ @example Extending with plugins at runtime
776
+
777
+ ```ts
778
+ import { DC, observePlugin, formValuePlugin } from '@twobirds/microcomponents';
779
+
780
+ observePlugin(DC);
781
+ formValuePlugin(DC);
782
+
783
+ class MyForm extends DC {
784
+ data = { name: '' };
785
+
786
+ oneInit() {
787
+ this
788
+ .formValues(this.target, 'data')
789
+ .subscribe('data', (v) => console.log(v))
790
+ .bind('data', this.target);
791
+ }
792
+ }
793
+ ```
794
+
795
+ `observePlugin(DC)` adds `notify()`, `subscribe()`, `bind()` to `McBase.prototype`;
796
+ `formValuePlugin(DC)` adds `formValues()` and re-runs `observePlugin`. `oneInit()`
797
+ runs once after the constructor.
798
+ @group Micro Components
799
+ */
800
+ var McBase = class {
801
+ #target;
802
+ /**
803
+ * Loaded asset cache, keyed by camelCase descriptor (`'targetHtml'` → `.target.html`).
804
+ * Inlined by the bundler in a bundled build, filled by `loadAssets()` in dev/autoload.
805
+ * Read through the {@link McBase.assets} getter.
806
+ */
807
+ static _assets = {};
808
+ /**
809
+ * Declares companion files for auto-loading by convention (e.g. `['targetHtml', 'json']`).
810
+ * Asset names are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
811
+ */
812
+ static assets = [];
813
+ /**
814
+ * In-flight asset request, cached per class so that instances constructed while
815
+ * the first fetch is still pending (e.g. in a loop) share a single request
816
+ * instead of each triggering their own. Resolves to the freshly loaded assets.
817
+ */
818
+ static _assetsPromise;
819
+ /**
820
+ The constructor for the base `McBase` class.
821
+
822
+ Initializes a weak reference to the target, auto-attaches listeners for `DC`
823
+ subclasses, and starts loading any `static assets` for `MC` and `DC` alike —
824
+ a server-side `MC` fetches them with no DOM, a `DC` gets them attached by its
825
+ own constructor. The load is shared per class through `_assetsPromise`.
826
+
827
+ @param target - The object or element this microcomponent represents.
828
+ */
829
+ constructor(target) {
830
+ this.#target = new WeakRef(target || {});
831
+ const ctor = this.constructor;
832
+ if (this instanceof DC && this.constructor !== DC) autoAttachListeners(this);
833
+ const remaining = (ctor.assets ?? []).filter((key) => !ctor._assets[key]);
834
+ if (remaining.length && !ctor._assetsPromise) ctor._assetsPromise = loadAssets(ctor._originalTag || (this instanceof DC ? this.target.tagName.toLowerCase() : pascalToKebab(ctor.name)), remaining).then((res) => {
835
+ const loadedAssets = {};
836
+ remaining.forEach((key, i) => {
837
+ loadedAssets[key] = res[i];
838
+ });
839
+ ctor._assets = Object.assign({}, ctor._assets, loadedAssets);
840
+ return loadedAssets;
841
+ });
842
+ }
843
+ /**
844
+ Returns the current target object (DOM node or other data) referenced by this microcomponent.
845
+
846
+ Uses a `WeakRef` internally to avoid circular references, and safely dereferences it here.
847
+
848
+ The dereference is asserted non-null: the controller is stored on its target
849
+ (`element._mc`), so any code that can reach the controller through the element is
850
+ holding the target alive. Only a controller retained independently after its element
851
+ was garbage-collected could observe a stale reference — do not cache controllers
852
+ detached from their elements.
853
+
854
+ @returns The target object.
855
+ */
856
+ get target() {
857
+ return this.#target.deref();
858
+ }
859
+ /**
860
+ The loaded assets for this component instance.
861
+
862
+ `static assets` are loaded before `oneInit()` fires on a `DC`, so this getter is
863
+ ready inside the `oneInit()` callback. A server-side `MC` fills it from `loadAssets()`;
864
+ await `MC._assetsPromise` before reading it. It returns the merged asset record keyed
865
+ by descriptor: `css` / `targetCss` / `shadowCss` / `shadowHtml` / `targetHtml` arrive
866
+ as strings, `*Json` entries arrive parsed, and a plain `html` template is returned as a
867
+ string for `parse()`. An empty object when no assets are declared.
868
+
869
+ @returns A record mapping asset keys to their content.
870
+ */
871
+ get assets() {
872
+ return this.constructor._assets || {};
873
+ }
874
+ };
875
+ /**
876
+ @class DC
877
+ ---
878
+
879
+ A DOM-centric microcomponent that operates on a specific HTML element.
880
+
881
+ Extends {@link McBase} and associates itself with an actual DOM node via the
882
+ `_target` reference. Provides methods for event handling, DOM traversal,
883
+ and interaction with sibling or ancestor microcomponents.
884
+
885
+ ---
886
+
887
+ ## Static Configuration Properties
888
+
889
+ DC classes support three static properties that configure custom elements
890
+ before any instance is constructed:
891
+
892
+ ### `static tag?: string`
893
+
894
+ Replaces the default target element with a semantic HTML element, or removes it entirely.
895
+
896
+ - **Non-empty string** (e.g., `'header'`) — the original custom element is replaced
897
+ with the specified built-in element. The original tag name is added as a CSS class.
898
+ - **Empty string `''`** — the target element is removed from the DOM entirely.
899
+ Useful for components that only inject global styles or act as style containers.
900
+
901
+ @example static tag — replace with semantic element
902
+
903
+ ```ts
904
+ class ShopHeader extends DC {
905
+ static tag = 'header';
906
+ }
907
+ defineCE('shop-header', ShopHeader);
908
+ ```
909
+
910
+ Produces `<header class="shop-header">` instead of `<shop-header>`.
911
+
912
+ @example static tag — remove element entirely
913
+
914
+ ```ts
915
+ class GlobalStyles extends DC {
916
+ static tag = '';
917
+ }
918
+ defineCE('global-styles', GlobalStyles);
919
+ ```
920
+
921
+ The element self-destructs; only side effects (e.g., injected styles) remain.
922
+
923
+ ### `static assets: string[]`
924
+
925
+ Declares companion files for auto-loading by convention. Asset names are camelCase
926
+ and translated into file extensions: `'targetHtml'` → `.target.html`, `'json'` → `.json`.
927
+
928
+ The path is derived from the custom element tag segments, and the basename is the
929
+ last segment. For `<cart-container-checkout>`, assets load from `/cart/container/checkout.*`.
930
+
931
+ **Assets are loaded before `oneInit()` fires.** The constructor applies them to the
932
+ target, then dispatches the `Init` lifecycle event — synchronously in a bundled build
933
+ (assets inlined), after the fetch resolves in a dev/autoload build. Inside `oneInit()`
934
+ the loaded assets are read through the {@link DC.assets} getter. Everything ending in
935
+ `Json` arrives parsed; all other files arrive as text.
936
+
937
+ **Auto-attached assets**: `.css`, `.target.css`, `.shadow.css`, `.target.html` and
938
+ `.shadow.html` are attached automatically by `processAssets()` — CSS is injected into
939
+ the document or shadow scope, HTML is set as `target.innerHTML` / `shadowRoot.innerHTML`,
940
+ and native event handlers in the template (`<button click="this|go">`) are wired.
941
+
942
+ **Plain `.html` is NOT auto-attached.** It is a template held in {@link DC.assets} for
943
+ components created programmatically with a `data` parameter: in `oneInit()` you compile
944
+ the target markup from template + data with `parse()`.
945
+
946
+ **One-time global styles**: Assets named `'css'` and `'targetCss'` inject CSS into the
947
+ global document scope via `injectCSS(document, ...)`. Because these are idempotent
948
+ global side effects, they are processed only once — after the first instance loads them,
949
+ the entries are dropped from `static _assets`. Subsequent instances skip re-processing
950
+ them entirely.
951
+
952
+ **CSS file roles**:
953
+
954
+ - `.css` — design tokens only (CSS custom-property presets). Injected into the document
955
+ scope once, like `targetCss`.
956
+ - `.target.css` — layout rules for the light DOM. Also document-scoped and one-time.
957
+ - `.shadow.css` — layout rules for the shadow DOM. Injected per instance into the
958
+ component's own shadow root, so each instance gets its own copy.
959
+
960
+ Every declared asset — CSS, HTML, JSON — is inlined into `static _assets` at build time by
961
+ the bundler, which replaces the `static assets` declaration with `static _assets` (the
962
+ `static assets` line is deleted from the bundled `.js`) and collapses each inlined
963
+ `.[shadow/target].css` / `.html` to a single line, so a bundled build performs no fetches.
964
+
965
+ In a bundled build the plain `.css` files are additionally concatenated into a single
966
+ `bundle.css` by the bundling script. That file is a convenience listing of the available
967
+ variables: copy the ones you want to change into your own stylesheet and override them
968
+ there. It is not required at runtime, and it cannot drift from the inlined presets — both
969
+ are read from the same source files.
970
+
971
+ The runtime decides whether an asset still needs fetching with `!ctor._assets[key]`, so an
972
+ inlined entry must never be an empty string: that would trigger a re-fetch of a file that
973
+ does not exist in a bundled build.
974
+
975
+ @example static assets read in oneInit
976
+
977
+ ```ts
978
+ class CartCheckout extends DC {
979
+ static assets = ['targetHtml', 'targetCss', 'configJson'];
980
+
981
+ oneInit() {
982
+ const { configJson } = this.assets;
983
+ console.log(configJson);
984
+ }
985
+ }
986
+ defineCE('cart-checkout', CartCheckout);
987
+ ```
988
+
989
+ `configJson` arrives already parsed into an object.
990
+
991
+ @example plain .html template compiled with data
992
+
993
+ ```ts
994
+ class UserCard extends DC {
995
+ static assets = ['html', 'targetCss'];
996
+
997
+ constructor(target: HTMLElement, data: { name: string }) {
998
+ super(target);
999
+ this.data = data;
1000
+ }
1001
+
1002
+ oneInit() {
1003
+ this.target.innerHTML = parse(this.assets.html, this.data);
1004
+ }
1005
+ }
1006
+ defineCE('user-card', UserCard);
1007
+ ```
1008
+
1009
+ `user-card.html` holds the `{name}` template; `parse()` fills it from `data`.
1010
+
1011
+ ### `static attributes?: object`
1012
+
1013
+ Sets HTML attributes on every instance automatically.
1014
+
1015
+ @example static attributes
1016
+
1017
+ ```ts
1018
+ class ProductCard extends DC {
1019
+ static attributes = { role: 'listitem' };
1020
+ }
1021
+ defineCE('product-card', ProductCard);
1022
+ ```
1023
+
1024
+ Every `<product-card>` carries `role="listitem"`.
1025
+
1026
+ ### Combined usage
1027
+
1028
+ All three can be combined in one class:
1029
+
1030
+ @example All static properties together
1031
+
1032
+ ```ts
1033
+ class ShopCatalog extends DC {
1034
+ static tag = 'section';
1035
+ static attributes = { role: 'list', 'aria-label': 'products' };
1036
+ static assets = ['targetHtml', 'targetCss'];
1037
+ }
1038
+ defineCE('shop-catalog', ShopCatalog);
1039
+ ```
1040
+
1041
+ Produces `<section role="list" aria-label="products">`.
1042
+
1043
+ ---
1044
+
1045
+ ## Event Handler Conventions
1046
+
1047
+ Methods whose names start with `on` or `one` are automatically wired as event listeners
1048
+ on the target element. The prefix determines persistence:
1049
+
1050
+ - **`on<EventName>`** — persistent listener (fires every time)
1051
+ - **`one<EventName>`** — one-time listener (fires once, then detaches)
1052
+
1053
+ ### Web Component Lifecycle Events
1054
+
1055
+ When a DC is registered via {@link defineCE}, the custom element dispatches these
1056
+ internal events that can be caught with handler methods:
1057
+
1058
+ | Method | When it fires |
1059
+ |--------|---------------|
1060
+ | `onConnected()` | Element was inserted into the DOM (`connectedCallback`) |
1061
+ | `onDisconnected()` | Element was removed from the DOM (`disconnectedCallback`) |
1062
+ | `onAdopted()` | Element was moved to a new document (`adoptedCallback`) |
1063
+ | `onAttributeChanged()` | An observed attribute changed (`attributeChangedCallback`) |
1064
+ | `oneInit()` | Constructor finished and declared assets loaded; read them via `this.assets` |
1065
+
1066
+ @example Event handlers in action
1067
+
1068
+ ```ts
1069
+ class MyElement extends DC {
1070
+ onConnected() {
1071
+ console.log('entered the DOM');
1072
+ }
1073
+
1074
+ onDisconnected() {
1075
+ console.log('left the DOM');
1076
+ }
1077
+
1078
+ onClick() {
1079
+ this.trigger('something', 'payload');
1080
+ }
1081
+
1082
+ oneSomething(ev) {
1083
+ console.log('first time only:', ev.detail.data);
1084
+ }
1085
+ }
1086
+ defineCE('my-element', MyElement);
1087
+ ```
1088
+
1089
+ ---
1090
+
1091
+ ## Construction Patterns
1092
+
1093
+ ### Template usage (declarative)
1094
+
1095
+ ```ts
1096
+ class MyElement extends DC {}
1097
+ defineCE('my-element', MyElement);
1098
+ ```
1099
+
1100
+ The registered element is then used in HTML as `<my-element></my-element>`.
1101
+
1102
+ ### Programmatic construction with data
1103
+
1104
+ When constructing programmatically via {@link getCE}, pass only the `data` payload —
1105
+ the target element is created automatically by the custom element constructor.
1106
+
1107
+ @example Programmatic construction
1108
+
1109
+ ```ts
1110
+ class MyElement extends DC {
1111
+ data = {};
1112
+
1113
+ constructor(target, data) {
1114
+ super(target);
1115
+ this.data = data;
1116
+ }
1117
+ }
1118
+ defineCE('my-element', MyElement);
1119
+
1120
+ const Ctor = getCE('my-element');
1121
+ document.body.append(new Ctor({ name: 'John' }));
1122
+ ```
1123
+
1124
+ ### Data from HTML attributes
1125
+
1126
+ @example Reading data from an attribute
1127
+
1128
+ ```ts
1129
+ class MyElement extends DC {
1130
+ data = {};
1131
+
1132
+ constructor(target) {
1133
+ super(target);
1134
+ this.data = JSON.parse(target.getAttribute('my-data'));
1135
+ }
1136
+ }
1137
+ defineCE('my-element', MyElement);
1138
+ ```
1139
+
1140
+ Used in HTML as `<my-element my-data='{"name":"John"}'></my-element>`.
1141
+
1142
+ ---
1143
+
1144
+ ## Plugin Extension Points
1145
+
1146
+ The prototype of `DC` (inherited from {@link McBase}) is extended at runtime by optional
1147
+ plugins. See the {@link McBase} documentation for details on {@link State.observePlugin} and
1148
+ {@link State.formValuePlugin}.
1149
+
1150
+ @template T - The concrete element type of the host element.
1151
+ @template EM - The component's custom event map (`event name → payload type`).
1152
+ Declaring it registers events on the type level: `trigger()` enforces the
1153
+ payload for registered names, and `on()`/`one()` handlers receive
1154
+ `CustomEvent<McDetail<Payload>>` with no annotation needed. Unregistered
1155
+ names keep the open `unknown`-payload behavior.
1156
+
1157
+ @example Typed event map
1158
+
1159
+ ```ts
1160
+ class Cart extends DC<HTMLFormElement, { CartUpdate: { count: number } }> {
1161
+ checkout() {
1162
+ this.trigger('CartUpdate', { count: 2 }, 'u');
1163
+ this.on('CartUpdate', (ev) => ev.detail.data.count);
1164
+ }
1165
+ }
1166
+ ```
1167
+
1168
+ `trigger()` checks the payload against the registered `CartUpdate` shape, and the `on()`
1169
+ handler receives a fully typed `ev`.
1170
+ @group Micro Components
1171
+ */
1172
+ var DC = class DC extends McBase {
1173
+ /**
1174
+ * Replaces the target element with a semantic HTML tag, or removes it entirely.
1175
+ * Set to `'header'` to swap `<my-element>` for `<header>`, or `''` to self-destruct.
1176
+ */
1177
+ static tag;
1178
+ /**
1179
+ * Sets HTML attributes on every instance automatically.
1180
+ * Example: `{ role: 'listitem', 'aria-label': 'nav' }`.
1181
+ */
1182
+ static attributes = {};
1183
+ /**
1184
+ * Constructs a new DC instance and applies static configuration.
1185
+ *
1186
+ * The constructor performs these steps in order:
1187
+ * 1. Calls {@link McBase} to establish the target reference and auto-attach listeners.
1188
+ * 2. If `static tag` is set and differs from the current element, replaces the target
1189
+ * with a new built-in element (or removes it if `tag === ''`).
1190
+ * 3. Applies any `static attributes` to the target element.
1191
+ * 4. Loads `static assets` (inlined in a bundled build, fetched in dev/autoload),
1192
+ * applies the auto-attached ones to the target, then fires the `Init` lifecycle
1193
+ * event — so `oneInit()` runs with the assets loaded and readable via {@link DC.assets}.
1194
+ *
1195
+ * @param target - The host DOM element this component operates on.
1196
+ */
1197
+ constructor(target) {
1198
+ super(target);
1199
+ const ctor = this.constructor;
1200
+ if (ctor === DC) return;
1201
+ const tagName = this.target.tagName.toLowerCase();
1202
+ if (ctor["tag"] !== void 0 && tagName !== ctor.tag && ctor.tag !== "") {
1203
+ const element = document.createElement(ctor.tag);
1204
+ element.classList.add(tagName);
1205
+ ctor._originalTag = tagName;
1206
+ DC.add(element, ctor.name, new ctor(element));
1207
+ delete ctor._originalTag;
1208
+ if (tagName.includes("-") && !this.target.isConnected) this.on("connected", () => this.target.replaceWith(element));
1209
+ else this.target.replaceWith(element);
1210
+ return;
1211
+ }
1212
+ const attributes = ctor.attributes;
1213
+ if (ctor.attributes) Object.keys(ctor.attributes).forEach((key) => {
1214
+ this.target.setAttribute(key, attributes[key]);
1215
+ });
1216
+ if (Object.keys(ctor._assets).length) {
1217
+ processAssets(this, ctor._assets);
1218
+ for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
1219
+ ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
1220
+ }
1221
+ if (ctor._assetsPromise) ctor._assetsPromise.then((loadedAssets) => {
1222
+ processAssets(this, loadedAssets);
1223
+ for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
1224
+ ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
1225
+ init(this);
1226
+ });
1227
+ else init(this);
1228
+ if (ctor.tag === "") {
1229
+ this.target.remove();
1230
+ return;
1231
+ }
1232
+ }
1233
+ /**
1234
+ Static helper to attach a microcomponent instance to a DOM element.
1235
+
1236
+ Wrapper around the `add()` utility function, providing a class-level API
1237
+ for adding child microcomponents to a target node.
1238
+
1239
+ @template T - The concrete element type of the target; preserved in the return type.
1240
+ @template K - The literal registration key; becomes a known entry of the returned `_mc` registry.
1241
+ @template E - The type of the attached element; retrievable as `result._mc[key]`.
1242
+ @param target - The DOM element to which to attach the microcomponent.
1243
+ @param key - The property name/key under which to store the instance in `_mc`.
1244
+ @returns The target DOM element with the attached microcomponent.
1245
+ */
1246
+ static add(target, key, element = {}) {
1247
+ return add(target, key, element);
1248
+ }
1249
+ /**
1250
+ Static helper to remove a named microcomponent from a DOM element.
1251
+
1252
+ Wrapper around the `remove()` utility function, providing a class-level API
1253
+ for removing child microcomponents.
1254
+
1255
+ @template T - A plain or already-enhanced element type.
1256
+ @template K - The literal registration key; its entry is poisoned in the registry type.
1257
+ @param target - The DOM element from which to remove the microcomponent.
1258
+ @param key - The property name/key corresponding to the microcomponent to remove.
1259
+ */
1260
+ static remove(target, key) {
1261
+ remove(target, key);
1262
+ }
1263
+ /**
1264
+ Class-verified entry lookup: returns the component stored under `key` on the
1265
+ element's `_mc` record — but only if it is an instance of `Klass`.
1266
+
1267
+ This is the *sound* retrieval primitive: presence AND type identity are both
1268
+ proven at runtime (`instanceof`), so it needs no global `McRegistry`
1269
+ declaration and stays correct even when different elements use the same key
1270
+ name for different component types. Accepts any value (including
1271
+ `querySelector` results that may be null) — every failure mode returns
1272
+ `undefined`.
1273
+
1274
+ @template E - The component type, inferred from `Klass`.
1275
+ @param element - The value to look the entry up on; anything non-host yields undefined.
1276
+ @param key - The registry key name to look under.
1277
+ @param elementMcClass - The class the entry must be an instance of.
1278
+ @returns The verified instance, or undefined.
1279
+ @example
1280
+ ```ts
1281
+ const cart = DC.get(document.querySelector('form'), 'cart', Cart);
1282
+ cart?.addItem(item);
1283
+ ```
1284
+
1285
+ `cart` is `Cart | undefined` — presence and type identity are both proven by the
1286
+ `instanceof` check inside `get()`, with no global declaration involved.
1287
+ */
1288
+ static get(element, key, elementMcClass) {
1289
+ if (!isMcHost(element)) return void 0;
1290
+ const entry = element._mc[key];
1291
+ return entry instanceof elementMcClass ? entry : void 0;
1292
+ }
1293
+ /**
1294
+ Detaches an event listener from the DOM node.
1295
+
1296
+ This is an instance method wrapper for `off()`, using the internal `_target` DOM reference.
1297
+
1298
+ @param eventName - The name of the event (e.g., 'click', 'update').
1299
+ @param handler - The previously attached callback function or object to remove.
1300
+ */
1301
+ off(eventName, handler) {
1302
+ off(this.target, eventName, handler);
1303
+ }
1304
+ /**
1305
+ Attaches a persistent event listener to the DOM node.
1306
+
1307
+ This is an instance method wrapper for `on()`, using the internal `_target` DOM reference.
1308
+
1309
+ The handler receives a `CustomEvent<McDetail<Payload>>`. For event names
1310
+ registered in the component's event map `EM` the payload is resolved from the
1311
+ map — an unannotated arrow handler is fully typed. For unregistered names the
1312
+ payload defaults to `unknown` and can be pinned via the type argument
1313
+ (`on<Payload>('Name', handler)`) or the handler's own annotation.
1314
+
1315
+ @param eventName - The name of the event (e.g., 'click', 'update').
1316
+ @param handler - The callback function or object to invoke.
1317
+ @returns The attached handler reference, unchanged — usable directly with {@link off}.
1318
+ */
1319
+ on(eventName, handler) {
1320
+ return on(this.target, eventName, handler);
1321
+ }
1322
+ /**
1323
+ Attaches a one-time event listener to the DOM node.
1324
+
1325
+ This is an instance method wrapper for `one()`, using the internal `_target` DOM reference.
1326
+ Payload typing follows the same rules as {@link DC.on}.
1327
+
1328
+ @param eventName - The name of the event (e.g., 'click', 'update').
1329
+ @param handler - The callback function or object to invoke once.
1330
+ @returns The attached one-time handler reference, unchanged — usable directly with {@link off}.
1331
+ */
1332
+ one(eventName, handler) {
1333
+ return one(this.target, eventName, handler);
1334
+ }
1335
+ /**
1336
+ Triggers a custom event on the DOM node and optionally bubbles it.
1337
+
1338
+ This is an instance method wrapper for `trigger()`, using the internal `_target` DOM reference.
1339
+
1340
+ For event names registered in the component's event map `EM` the payload type
1341
+ is enforced; unregistered names accept any payload (typed via inference or an
1342
+ explicit `trigger<Payload>(...)` argument).
1343
+
1344
+ @param eventName - The name of the event (will be prefixed if needed).
1345
+ @param data - Additional data payload attached to `event.detail.data`.
1346
+ @param bubble - Bubbling direction ('l', 'u', 'd' or combinations).
1347
+ @param controller - Optional controller for managing bubbling behavior.
1348
+ */
1349
+ trigger(eventName, data = {}, bubble = "l", controller) {
1350
+ trigger(this.target, eventName, data, bubble, controller);
1351
+ }
1352
+ /**
1353
+ Returns an array of all ancestor microcomponents up the DOM tree.
1354
+
1355
+ Traverses upward from this element's target, collecting the `_mc` instances
1356
+ of ancestor elements marked with `data-mc`. The keyed form only collects
1357
+ hosts whose registry carries `key`, typed from the global {@link McRegistry}
1358
+ binding — non-optional, since presence is checked during the walk.
1359
+
1360
+ @template R - Known registry entries of the results; pass a record to assert
1361
+ a site-specific shape: `ancestors<{ cart: Cart }>()`. Defaults to none.
1362
+ @returns An array of ancestor microcomponent instances (empty if none found).
1363
+ */
1364
+ ancestors(key) {
1365
+ const result = [];
1366
+ let current = findMcAncestor(this.target, key);
1367
+ while (current) {
1368
+ result.push(current);
1369
+ current = findMcAncestor(current.target, key);
1370
+ }
1371
+ return result;
1372
+ }
1373
+ /**
1374
+ Returns the closest ancestor microcomponent or null if none found.
1375
+
1376
+ This method is equivalent to calling `ancestors()[0]`, but more concise.
1377
+ The keyed form walks up to the nearest host whose registry carries `key`,
1378
+ typed from the global {@link McRegistry} binding — non-optional, since
1379
+ presence is checked during the walk.
1380
+
1381
+ @template R - Known registry entries of the result; pass a record to assert
1382
+ a site-specific shape: `closest<{ cart: Cart }>()?.cart.addItem(...)`.
1383
+ Defaults to none.
1384
+ @returns The nearest matching ancestor's `_mc`, or null if not found.
1385
+ */
1386
+ closest(key) {
1387
+ return findMcAncestor(this.target, key);
1388
+ }
1389
+ /**
1390
+ Returns an array of direct child microcomponents.
1391
+
1392
+ Calls `getMcChildNodes()` internally to find immediate descendants only,
1393
+ excluding nested grandchildren and deeper levels. The keyed form filters to
1394
+ hosts whose registry carries `key`; see {@link DC.closest}.
1395
+
1396
+ @template R - Known registry entries of the results; see {@link DC.closest}.
1397
+ @returns An array of child microcomponent instances (empty if none found).
1398
+ */
1399
+ children(key) {
1400
+ const kids = getMcChildNodes(this.target);
1401
+ return key === void 0 ? kids : kids.filter((mc) => key in mc);
1402
+ }
1403
+ /**
1404
+ Returns an array of all descendant microcomponents recursively.
1405
+
1406
+ Uses a `querySelectorAll` query to collect every nested element marked with
1407
+ `data-mc`, returning their associated `_mc` instances. The keyed form
1408
+ filters to hosts whose registry carries `key`; see {@link DC.closest}.
1409
+
1410
+ @template R - Known registry entries of the results; see {@link DC.closest}.
1411
+ @returns An array of descendant microcomponent instances (empty if none found).
1412
+ */
1413
+ descendants(key) {
1414
+ return Array.from(this.target.querySelectorAll("[data-mc]")).filter((e) => e instanceof HTMLElement && "_mc" in e).map((e) => e._mc).filter((mc) => key === void 0 || key in mc);
1415
+ }
1416
+ };
1417
+ //#endregion
1418
+ //#region src/state/observables.ts
1419
+ /**
1420
+ Reactive data binding via observables — object properties trigger callbacks and update
1421
+ DOM placeholders automatically when their values change. Supports primitives, nested objects,
1422
+ and deep-change detection with debounced notifications.
1423
+
1424
+ @module Observables
1425
+
1426
+ Two APIs are provided for different contexts:
1427
+
1428
+ - **`observe()`** — standalone function for general usage outside the MC ecosystem.
1429
+ Call it on any plain object to make its properties observable. You manage the resulting
1430
+ data object yourself (subscribe, bind, notify).
1431
+
1432
+ - **`observePlugin()`** — used inside MC custom elements (classes extending `DC`).
1433
+ It attaches `.notify()`, `.subscribe()`, and `.bind()` as chainable instance methods
1434
+ that implicitly create the observable wrapper for you. Just declare a plain data property
1435
+ on your component and call `this.subscribe('data', …)` — the observable is generated on demand.
1436
+
1437
+ > **Note:** `.bind()` only works with objects because their properties become the placeholder
1438
+ > names in HTML (e.g., `{name}`, `{count}`). Binding primitives to the DOM is silently ignored.
1439
+
1440
+ @example Plugin — inside an MC custom element (recommended within DC classes)
1441
+ ```ts
1442
+ import { DC, defineCE, observePlugin } from '@twobirds/microcomponents';
1443
+
1444
+ observePlugin(DC);
1445
+
1446
+ class Counter extends DC {
1447
+ data = { clicks: 1 };
1448
+
1449
+ oneInit() {
1450
+ this
1451
+ .subscribe('data', (v) => console.log('data →', v))
1452
+ .bind('data', this.target);
1453
+ }
1454
+ }
1455
+
1456
+ defineCE('mc-counter', Counter);
1457
+ ```
1458
+
1459
+ @example Standalone — outside the MC ecosystem (plain objects, vanilla JS, etc.)
1460
+ ```ts
1461
+ import { observe } from '@twobirds/microcomponents';
1462
+
1463
+ const state = observe({ count: 0, label: 'hi' });
1464
+ state.count.subscribe((v) => console.log('count is now', v));
1465
+ state.count++;
1466
+ ```
1467
+
1468
+ Incrementing `state.count` triggers the subscribed callback.
1469
+
1470
+ @example Deep change detection on a nested property
1471
+ ```ts
1472
+ import { observe } from '@twobirds/microcomponents';
1473
+
1474
+ const state = observe({ data: { name: 'John', age: 30 } });
1475
+ state.data.subscribe((d) => console.log('data changed:', d));
1476
+ state.data.name = 'Jane';
1477
+ ```
1478
+
1479
+ Writing into a nested property triggers the callback with the updated object.
1480
+
1481
+ @example DOM binding — only observable properties that hold objects can be bound
1482
+ ```ts
1483
+ import { observe } from '@twobirds/microcomponents';
1484
+
1485
+ const state = observe({ user: { name: 'Alice', count: 0 } });
1486
+ state.user.bind(document.querySelector('.model'));
1487
+ ```
1488
+
1489
+ Inside the bound model, `<span>{name}</span>` and `<span>{count}</span>` update
1490
+ automatically on every change.
1491
+
1492
+ */
1493
+ /**
1494
+ @hidden
1495
+ Determines if a value is an observable object.
1496
+
1497
+ @param value - The value to check.
1498
+ @returns `true` if the value is a non-null object, otherwise `false`.
1499
+ */
1500
+ function isObservableObject(value) {
1501
+ return value != null && typeof value === "object";
1502
+ }
1503
+ var classRepo = {};
1504
+ /**
1505
+ @hidden
1506
+ Creates a new observable wrapper class for the given value's constructor.
1507
+
1508
+ Returns a subclass of the original constructor that implements the Observable interface,
1509
+ allowing observation and notification of changes. The new class is cached in `classRepo`.
1510
+
1511
+ @param val - The value whose constructor should be wrapped with observable behavior.
1512
+ @returns A new Observable class that wraps the original constructor.
1513
+ */
1514
+ function makeObservable(val) {
1515
+ const Constructor = val.constructor, ConstructorName = Constructor.name;
1516
+ const ObservableClass = class extends Constructor {
1517
+ #notify = true;
1518
+ #callbacks = [];
1519
+ constructor(valArg) {
1520
+ super(valArg);
1521
+ const ctor = this.constructor;
1522
+ ctor.callbacks = [];
1523
+ if (isObservableObject(valArg)) Object.getOwnPropertyNames(valArg).forEach((key) => {
1524
+ this[key] = valArg[key];
1525
+ });
1526
+ }
1527
+ get callbacks() {
1528
+ return this.#callbacks;
1529
+ }
1530
+ set callbacks(callbacks) {
1531
+ this.#callbacks = callbacks;
1532
+ }
1533
+ /**
1534
+ Coerces the observable to its underlying primitive value when used in
1535
+ arithmetic, string interpolation, or other contexts requiring a primitive.
1536
+
1537
+ This allows `observable + 1` or `` `${observable}` `` to work naturally
1538
+ while still exposing `.subscribe()`, `.notify()`, etc. as methods on the object.
1539
+
1540
+ @param hint - The coercion context: 'number', 'string', or 'default'.
1541
+ @returns The underlying primitive value coerced to the requested type.
1542
+
1543
+ @example
1544
+ ```ts
1545
+ const state = observe({ count: 42 });
1546
+ console.log(state.count + 10);
1547
+ console.log(`${state.count}`);
1548
+ state.count.subscribe((v) => console.log('changed to', v));
1549
+ ```
1550
+
1551
+ Arithmetic coerces with `hint === 'number'` (logs `52`), interpolation with
1552
+ `hint === 'string'` (logs `"42"`), and `.subscribe()` stays callable on the
1553
+ wrapper.
1554
+ */
1555
+ [Symbol.toPrimitive](hint) {
1556
+ const value = this.valueOf();
1557
+ if (hint === "string") return String(value);
1558
+ if (hint === "number") return Number(value);
1559
+ return value;
1560
+ }
1561
+ /**
1562
+ Registers a callback function to be invoked when the observable object is notified.
1563
+
1564
+ @param callback - The function to invoke on notification.
1565
+ @returns This instance for chaining.
1566
+
1567
+ @example
1568
+ ```ts
1569
+ const state = observe({ count: 0 });
1570
+ state.count.subscribe((v) => console.log('count changed to', v));
1571
+ state.count++;
1572
+ ```
1573
+
1574
+ The increment fires the callback, logging `count changed to 1`.
1575
+ */
1576
+ subscribe(callback) {
1577
+ this.#callbacks.push(callback);
1578
+ return this;
1579
+ }
1580
+ /**
1581
+ Removes a previously registered callback so it no longer fires on notify.
1582
+
1583
+ Detaching by the same function reference that was passed to `subscribe()` —
1584
+ unknown callbacks are a silent no-op. Long-lived subscribers should call
1585
+ this when they are done to avoid leaking callbacks.
1586
+
1587
+ @param callback - The exact callback reference to remove.
1588
+ @returns This instance for chaining.
1589
+
1590
+ @example
1591
+ ```ts
1592
+ const state = observe({ count: 0 });
1593
+ const log = (v) => console.log(v);
1594
+ state.count.subscribe(log);
1595
+ state.count.unsubscribe(log);
1596
+ ```
1597
+
1598
+ After `unsubscribe(log)`, the callback no longer fires on changes.
1599
+ */
1600
+ unsubscribe(callback) {
1601
+ this.#callbacks = this.#callbacks.filter((registered) => registered !== callback);
1602
+ return this;
1603
+ }
1604
+ /**
1605
+ Binds the observable to a DOM target, setting up placeholder updates and
1606
+ triggering initial callbacks.
1607
+
1608
+ Scans the target and its descendants for placeholders and registers handlers
1609
+ to update them with flattened data on notification. Only works in browser environments.
1610
+
1611
+ @param target - The HTMLElement, DocumentFragment, or ShadowRoot to bind.
1612
+ @returns This instance for chaining.
1613
+
1614
+ @example
1615
+ ```ts
1616
+ const state = observe({ user: { name: 'Alice', count: 0 } });
1617
+ state.user.bind(document.querySelector('.model'));
1618
+ ```
1619
+
1620
+ Only object-valued observables can be bound: inside the model, `{name}` and
1621
+ `{count}` placeholders update on every change.
1622
+ */
1623
+ bind(target) {
1624
+ if (!isBrowser()) return this;
1625
+ if (isObservableObject(this.valueOf())) {
1626
+ makePlaceholders(target);
1627
+ const placeholders = [target, ...target.querySelectorAll("[data-mc]")].filter((e) => {
1628
+ return !!e?._mc?._placeholders;
1629
+ });
1630
+ this.#callbacks.push(function callback(data) {
1631
+ const flattenedData = flattenObject(data);
1632
+ placeholders.forEach((node) => {
1633
+ /* v8 ignore next */
1634
+ if (!node) return;
1635
+ trigger(node, "data", flattenedData);
1636
+ });
1637
+ });
1638
+ this.notify();
1639
+ } else console.warn("IGNORED - cannot bind a non-Object to the dom, IS:", typeof this.valueOf(), this);
1640
+ return this;
1641
+ }
1642
+ /**
1643
+ Notifies registered callbacks with the current observable data.
1644
+
1645
+ Clones the internal value (if it's an object and not an array) before passing
1646
+ to callbacks. Respects the internal `#notify` flag that can suppress notifications.
1647
+
1648
+ @param notify - Optional boolean override for the notification state.
1649
+ @returns This instance for chaining.
1650
+
1651
+ @example
1652
+ ```ts
1653
+ const state = observe({ count: 0 });
1654
+ state.count.subscribe((v) => console.log('notified:', v));
1655
+ state.count.notify();
1656
+ ```
1657
+
1658
+ The manual `notify()` call pushes the current value to subscribers, logging
1659
+ `notified: 0`.
1660
+ */
1661
+ notify(notify) {
1662
+ const data = isObservableObject(this.valueOf()) && this.valueOf() instanceof Array === false ? structuredClone(Object.assign({}, this)) : this.valueOf();
1663
+ if (notify !== void 0) this.#notify = notify;
1664
+ if (this.#notify) this.#callbacks.forEach((f) => {
1665
+ f(data);
1666
+ });
1667
+ return this;
1668
+ }
1669
+ };
1670
+ classRepo[ConstructorName] = ObservableClass;
1671
+ return ObservableClass;
1672
+ }
1673
+ /**
1674
+ Retrieves or creates an observable wrapper class for the given value.
1675
+
1676
+ @param val - The value whose constructor should be wrapped with observable behavior.
1677
+ @returns A class that wraps the original constructor and implements observable functionality.
1678
+ */
1679
+ function getConstructor(val) {
1680
+ return classRepo[val.constructor.name] || makeObservable(val);
1681
+ }
1682
+ /**
1683
+ @hidden
1684
+ Whether a value is already an observable wrapper — `subscribe` is reachable on its prototype chain.
1685
+ Used by {@link observe} to skip re-wrapping and to detect the "not yet observed" state on reassignment.
1686
+
1687
+ @example
1688
+ ```ts
1689
+ const state = observe({ count: 0 });
1690
+ console.log(isAlreadyObserved(state.count));
1691
+ console.log(isAlreadyObserved(42));
1692
+ ```
1693
+
1694
+ The wrapped property reports `true`, a plain primitive reports `false`.
1695
+ */
1696
+ function isAlreadyObserved(value) {
1697
+ return (typeof value === "object" || typeof value === "function") && value !== null && "subscribe" in value;
1698
+ }
1699
+ /**
1700
+ @hidden
1701
+ Makes a target object's properties observable by replacing them with wrapped values.
1702
+
1703
+ Wraps each property of `target` that is not already observable (and meets criteria)
1704
+ in an observable wrapper. Also sets up deep change detection for objects and
1705
+ debounced notifications when the data changes.
1706
+
1707
+ There are two sides to using it — pick per call site:
1708
+
1709
+ **Declarative (typed class fields).** Declare the field as `Observable<T>` up
1710
+ front, then let `observe(this, 'field')` install the live wrapper in the
1711
+ constructor. The declaration needs the double cast once (`0 as unknown as
1712
+ Observable<number>`): the field starts life as a plain value and only becomes
1713
+ the wrapper when `observe()` runs. In exchange, every later use is fully typed —
1714
+ arithmetic, `subscribe`, `bind` — with no casts anywhere else.
1715
+
1716
+ **Imperative (wrapping existing data).** Hand any object to `observe()` after
1717
+ the fact — no declarations, the return type is inferred: every property comes
1718
+ back as `Observable<PropertyType>`.
1719
+
1720
+ @param target - The object whose properties should be made observable.
1721
+ @param propertyName - Optional specific property name to make one property observable instead of all properties.
1722
+ @returns The original target object, now with observable properties.
1723
+
1724
+ @example Imperative usage — wrap an existing plain object:
1725
+ ```ts
1726
+ const state = observe({ count: 0, label: 'hi' });
1727
+ state.count.subscribe((v) => console.log('count is now', v));
1728
+ state.count++;
1729
+ ```
1730
+
1731
+ Incrementing `state.count` triggers the subscribed callback.
1732
+
1733
+ @example Declarative usage — typed class field with double cast:
1734
+ ```ts
1735
+ class Counter {
1736
+ clicks: Observable<number> = 0 as unknown as Observable<number>;
1737
+
1738
+ constructor() {
1739
+ observe(this, 'clicks');
1740
+ }
1741
+
1742
+ bump() {
1743
+ this.clicks++;
1744
+ }
1745
+ }
1746
+ ```
1747
+
1748
+ Plain arithmetic compiles because the declaration carries the observable type.
1749
+
1750
+ @example Schema-first usage — divergent read/write types via hand-declared interface:
1751
+ ```ts
1752
+ interface CounterState {
1753
+ get count(): Observable<number>;
1754
+ set count(v: number);
1755
+ }
1756
+
1757
+ const state = observe<CounterState>({ count: 0 });
1758
+ state.count.subscribe((v) => console.log(v));
1759
+ state.count = 5;
1760
+ ```
1761
+
1762
+ The seed object is validated against the schema, the subscription callback is fully
1763
+ typed, and plain assignment is legal because the declared setter type permits it.
1764
+ */
1765
+ function observe(target, propertyName) {
1766
+ const source = target;
1767
+ (propertyName ? [propertyName] : [...Object.getOwnPropertyNames(target)]).forEach((key) => {
1768
+ const current = source[key];
1769
+ if (Object.prototype.hasOwnProperty.call(target, key) && typeof current !== "function" && !isAlreadyObserved(current)) {
1770
+ if (key[0] === "_" || current === void 0) return;
1771
+ const wrappedVal = current;
1772
+ let o = new (getConstructor(wrappedVal))(wrappedVal);
1773
+ let notifyPending = false;
1774
+ const debouncedNotify = function() {
1775
+ if (notifyPending) return;
1776
+ notifyPending = true;
1777
+ queueMicrotask(function() {
1778
+ notifyPending = false;
1779
+ o.notify();
1780
+ });
1781
+ };
1782
+ Object.defineProperty(target, key, {
1783
+ enumerable: true,
1784
+ get() {
1785
+ if (isObservableObject(o.valueOf())) {
1786
+ const snapshot = structuredClone(Object.assign({}, o));
1787
+ queueMicrotask(function checkChanges() {
1788
+ if (!deepEqual(structuredClone(Object.assign({}, o)), snapshot)) debouncedNotify();
1789
+ });
1790
+ }
1791
+ return o;
1792
+ },
1793
+ set(val) {
1794
+ if (typeof val === typeof o.valueOf()) if (isObservableObject(o.valueOf()) && o.valueOf() instanceof Array === false) {
1795
+ /* v8 ignore next */
1796
+ if (!isAlreadyObserved(o)) {
1797
+ /* v8 ignore next */
1798
+ o = new (getConstructor(val))(structuredClone(Object.assign({}, val)));
1799
+ /* v8 ignore next */
1800
+ copyGettersSetters(val, o);
1801
+ }
1802
+ Object.assign(o, val);
1803
+ o.notify();
1804
+ } else {
1805
+ const old = o.valueOf(), callbacks = o.callbacks;
1806
+ if (val !== old) {
1807
+ o = new (getConstructor(val))(val);
1808
+ o.callbacks = callbacks;
1809
+ debouncedNotify();
1810
+ }
1811
+ }
1812
+ else console.warn("IGNORED - cannot change observable types, IS:", typeof o.valueOf(), o, "- CANNOT BECOME:", typeof val);
1813
+ }
1814
+ });
1815
+ source[key] = wrappedVal;
1816
+ }
1817
+ });
1818
+ return target;
1819
+ }
1820
+ //#endregion
1821
+ //#region src/state/placeholders.ts
1822
+ /**
1823
+ @hidden
1824
+ DOM placeholder binding: `{name}` templates in attributes and text nodes,
1825
+ kept up to date from observable data.
1826
+
1827
+ Split from observables.ts so the pure observable machinery carries no DOM
1828
+ scanning/decoration code. The two modules reference each other only inside
1829
+ function bodies (`Placeholders` calls `observe(this)`; `bind()` calls
1830
+ {@link makePlaceholders}), never during module evaluation, so the circular
1831
+ import is benign under ESM live bindings.
1832
+ */
1833
+ /**
1834
+ Extracts placeholder names from an HTML element's attributes and text content.
1835
+
1836
+ Placeholders are strings enclosed in curly braces `{}`. This function scans
1837
+ all attributes and direct child text nodes of the target element for placeholders
1838
+ and returns them as an array of unique names (without braces).
1839
+
1840
+ @param target - The HTMLElement to scan for placeholders.
1841
+ @returns An array of placeholder names found within the element's attributes and text content.
1842
+ */
1843
+ function getPlaceholders(target) {
1844
+ const placeholders = /* @__PURE__ */ new Set(), regEx = /\{[^\{\}]*\}/g;
1845
+ (target.getAttributeNames ? target.getAttributeNames() : []).filter((attr) => target.getAttribute(attr)?.match(regEx)).forEach((attr) => {
1846
+ new Set(target.getAttribute(attr)?.match(regEx)).forEach((attrPlaceholder) => placeholders.add(attrPlaceholder.replace(/[\{\}]/g, "")));
1847
+ });
1848
+ [...target.childNodes].filter((childNode) => {
1849
+ return childNode.nodeType === 3 && (childNode.nodeValue || "").match(regEx);
1850
+ }).forEach((childNode) => {
1851
+ (childNode?.nodeValue || "").match(regEx).forEach((textNodePlaceholder) => placeholders.add(textNodePlaceholder.replace(/[\{\}]/g, "")));
1852
+ });
1853
+ return [...placeholders];
1854
+ }
1855
+ var inputTags = [
1856
+ "INPUT",
1857
+ "SELECT",
1858
+ "TEXTAREA"
1859
+ ];
1860
+ /**
1861
+ A class that manages placeholders within an HTML element and updates them dynamically.
1862
+
1863
+ This class extends `DC` (Data Controller) and processes the target element to identify
1864
+ placeholder patterns in attributes and text nodes. It then observes changes on its internal
1865
+ data object and updates the corresponding DOM locations when notified of changes.
1866
+ */
1867
+ var Placeholders = class extends DC {
1868
+ data = {};
1869
+ #oldDisplay = "";
1870
+ #restored = false;
1871
+ /**
1872
+ Creates a new `Placeholders` instance for the given HTML element.
1873
+
1874
+ Initializes the internal data with empty strings for each placeholder
1875
+ found in the target and starts observing the data object. Attaches
1876
+ callbacks to update placeholders as needed.
1877
+
1878
+ @param target - The HTMLElement to process for placeholders.
1879
+ */
1880
+ constructor(target) {
1881
+ super(target);
1882
+ getPlaceholders(target).forEach((property) => this.data[property] = "");
1883
+ observe(this);
1884
+ this.#attachCallbacks();
1885
+ }
1886
+ /**
1887
+ Replaces every occurrence of one placeholder in a template.
1888
+ The placeholder is escaped into a global regex, so a repeated `{x}` is fully
1889
+ substituted — `String.replace` with a string pattern replaces one occurrence only.
1890
+ @param template - The template holding the placeholder.
1891
+ @param placeholder - The `{key}` token to substitute.
1892
+ @param value - The replacement value.
1893
+ @returns The template with every occurrence replaced.
1894
+ */
1895
+ #substitute(template, placeholder, value) {
1896
+ placeholder.replace(/[\{\}]/g, "");
1897
+ const escaped = placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1898
+ return template.replace(new RegExp(escaped, "g"), value);
1899
+ }
1900
+ #attachCallbacks() {
1901
+ const target = this.target;
1902
+ (target.getAttributeNames ? target.getAttributeNames() : []).filter((attr) => target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g)).forEach((attr) => {
1903
+ const placeholders = new Set(target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g));
1904
+ /* v8 ignore next -- attr passed the filter above, so its value is a non-null string */
1905
+ const attrTemplate = target.getAttribute(attr) ?? "";
1906
+ this.data.subscribe(((template) => (data) => {
1907
+ let result = template;
1908
+ placeholders.forEach((placeholder) => {
1909
+ result = this.#substitute(result, placeholder, String(data[placeholder.replace(/[\{\}]/g, "")]));
1910
+ });
1911
+ target.setAttribute(attr, result);
1912
+ })(attrTemplate));
1913
+ });
1914
+ const textNodes = [...target.childNodes].filter((childNode) => {
1915
+ return childNode.nodeType === 3 && (childNode.nodeValue || "").match(/\{[^\{\}]*\}/g);
1916
+ });
1917
+ if (textNodes.length) {
1918
+ this.#oldDisplay = target.getAttribute("style") || "";
1919
+ textNodes.forEach((childNode) => {
1920
+ /* v8 ignore next -- the filter above only admits text nodes with a non-empty
1921
+ nodeValue, so the ?? fallback is unreachable */
1922
+ const textTemplate = childNode.nodeValue ?? "";
1923
+ const placeholders = new Set(textTemplate.match(/\{[^\{\}]*\}/g));
1924
+ this.data.subscribe(((template) => (data) => {
1925
+ let result = template;
1926
+ placeholders.forEach((placeholder) => {
1927
+ result = this.#substitute(result, placeholder, String(data[placeholder.replace(/[\{\}]/g, "")]));
1928
+ });
1929
+ if (!this.#restored) {
1930
+ this.#restored = true;
1931
+ if (this.#oldDisplay) target.style = this.#oldDisplay;
1932
+ else target.removeAttribute("style");
1933
+ }
1934
+ childNode.nodeValue = result;
1935
+ })(textTemplate));
1936
+ if (!inputTags.includes(target.tagName) && target.tagName !== "FIELDSET") target.style.display = "none";
1937
+ });
1938
+ }
1939
+ }
1940
+ /**
1941
+ Handles a `data` custom event to update the internal placeholder data.
1942
+
1943
+ Extracts matching keys from the event's detail data and updates only those
1944
+ properties in the internal `data` object that were previously defined as placeholders.
1945
+
1946
+ @param ev - The CustomEvent containing new data to merge into the placeholders.
1947
+ */
1948
+ onData(ev) {
1949
+ const data = {};
1950
+ Object.keys(ev.detail.data).forEach((key) => {
1951
+ if (this.data.hasOwnProperty(key)) data[key] = ev.detail.data[key];
1952
+ });
1953
+ if (JSON.stringify(data) !== JSON.stringify(this.data)) Object.assign(this.data, data);
1954
+ }
1955
+ };
1956
+ /**
1957
+ Finds all elements within a given scope that contain placeholders.
1958
+
1959
+ @param target - The HTMLElement, DocumentFragment, or ShadowRoot to search.
1960
+ @returns An array of HTMLElements containing placeholder patterns.
1961
+ */
1962
+ function getPlaceholderElements(target) {
1963
+ return [target].concat([...target.querySelectorAll("*")]).filter((e) => !!getPlaceholders(e).length).filter((e) => e?.tagName !== "STYLE").reverse();
1964
+ }
1965
+ /**
1966
+ Applies placeholder support to an element and its descendants.
1967
+
1968
+ This function scans the provided target for elements containing placeholders
1969
+ and attaches a `Placeholders` controller instance to each one if not already present.
1970
+
1971
+ @param element - The HTMLElement, DocumentFragment, or ShadowRoot to process.
1972
+ */
1973
+ function makePlaceholders(element) {
1974
+ getPlaceholderElements(element).forEach((e) => {
1975
+ if (e?._mc?._placeholders) return;
1976
+ DC.add(e, "_placeholders", new Placeholders(e));
1977
+ });
1978
+ }
1979
+ //#endregion
1980
+ export { makePlaceholders };