@jxsuite/compiler 9.0.1 → 10.0.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.
@@ -12,7 +12,7 @@ import {
12
12
  declaresParameters,
13
13
  handlerParamNames,
14
14
  } from "@jxsuite/schema/function-role";
15
- import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
15
+ import { RESERVED_KEYS, camelToKebab, derivedStateKeys, formStateKeys } from "@jxsuite/runtime";
16
16
  import {
17
17
  ATTR_HELPER,
18
18
  DEFAULT_LIT_HTML_SRC,
@@ -20,12 +20,40 @@ import {
20
20
  attrHelperSource,
21
21
  booleanAttrValue,
22
22
  definitionHasSlot,
23
+ KEYED_LIST_HELPER,
24
+ KEYED_LIST_IMPORTS,
25
+ keyedListDirectiveSource,
26
+ keyPath,
27
+ LIST_LITERAL_HELPER,
28
+ LIST_ITEMS_HELPER,
29
+ listHelperSource,
30
+ mappedArrayFeatures,
31
+ pageImportMap,
32
+ readsBareState,
33
+ refuseTemplateItems,
23
34
  LIT_PART_GUARD,
35
+ NATIVE_SETTER_HELPER,
36
+ OBSERVED_ATTR_HELPER,
24
37
  PREFORMATTED_TAGS,
38
+ PROP_SUPPLY_HELPER,
39
+ propSupplyHelperSource,
40
+ observedAttrHelperSource,
41
+ collectClientClasses,
42
+ emitExternalClassResolution,
43
+ externalClassHelperSource,
44
+ isClientExternalClass,
45
+ observedAttributeNames,
46
+ observedDefaultsSource,
25
47
  SLOT_CAPTURE_HELPER,
26
48
  SLOT_DISTRIBUTE_HELPER,
49
+ FORM_ASSOCIATION_HELPER,
50
+ formAssociationHelperSource,
27
51
  slotHelperSource,
28
- collectStyles,
52
+ assignStyleHandles,
53
+ authorClassValue,
54
+ styleChildren,
55
+ styleHandleOf,
56
+ writesMergedClass,
29
57
  compileExpression,
30
58
  compileOperandSource,
31
59
  compileStatements,
@@ -53,6 +81,7 @@ import {
53
81
  isNamedFormulaDef,
54
82
  isNonNullObject,
55
83
  isNumber,
84
+ isPrivateStateKey,
56
85
  isPrototypeDef,
57
86
  isRef,
58
87
  isServerFnDef,
@@ -63,11 +92,18 @@ import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
63
92
  import { resolveShadowMode } from "../shadow.ts";
64
93
  import type { ShadowMode } from "../shadow.ts";
65
94
  import type { FormatRegistry } from "@jxsuite/schema/format-registry";
66
- import { escapeToken, objectKey, refAccessor, refSegments } from "@jxsuite/runtime/pointer";
95
+ import {
96
+ canonicalMapRef,
97
+ escapeToken,
98
+ objectKey,
99
+ refAccessor,
100
+ refSegments,
101
+ } from "@jxsuite/runtime/pointer";
67
102
  import type {
68
103
  JsonPrimitive,
69
104
  JxDocument,
70
105
  JxDocumentValue,
106
+ JxElement,
71
107
  JxExpressionDef,
72
108
  JxExpressionNode,
73
109
  JxFunctionDef,
@@ -88,6 +124,27 @@ import type {
88
124
  */
89
125
  type LitChild = JxMutableNode | JsonPrimitive;
90
126
 
127
+ /**
128
+ * The names the emitted class defines itself. A state key with one of these names still arrives
129
+ * through `data-jx-props` and `props.*`, which write `this.state[key]`, but is neither merged from
130
+ * a property nor given a forwarding accessor (compiler.md §4.4): reading `this.state` as a prop
131
+ * would merge state into itself, and an accessor named `template` or `connectedCallback` would
132
+ * replace the member the element runs on. The interpreter's element class has no such members, so
133
+ * this is the compiled tier's one exception. A change that adds a public member to the emitted
134
+ * class adds its name here.
135
+ */
136
+ const ELEMENT_MEMBERS: ReadonlySet<string> = new Set([
137
+ "state",
138
+ "template",
139
+ "constructor",
140
+ "connectedCallback",
141
+ "disconnectedCallback",
142
+ "adoptedCallback",
143
+ "attributeChangedCallback",
144
+ "formResetCallback",
145
+ "formDisabledCallback",
146
+ ]);
147
+
91
148
  /** Options accepted by compileElement. */
92
149
  export interface CompileElementOptions {
93
150
  /** Resolve an `$elements` ref path to its emitted JS module path. */
@@ -123,6 +180,41 @@ export interface CompileElementOptions {
123
180
  * document.
124
181
  */
125
182
  projectState?: Record<string, JxStateDefinition> | undefined;
183
+ /**
184
+ * Called with each document as it is read, the component's own and every `$elements`
185
+ * dependency's, before anything is compiled from it. A site build resolves the document's
186
+ * build-time external classes here (compiler.md §3), so the module is compiled from state that
187
+ * already holds their values. `filePath` is `null` for a document passed as an object.
188
+ */
189
+ prepareDocument?: (doc: JxDocument, filePath: string | null) => Promise<void>;
190
+ /**
191
+ * The URL a `timing: "client"` external class's module is served at (compiler.md §3, §12), given
192
+ * the entry, the directory of the document that declares it and that document's `imports`. Only a
193
+ * site build has one; without it such an entry is a compile error.
194
+ */
195
+ resolveClass?: (
196
+ def: JxPrototypeDef,
197
+ docDir: string | null,
198
+ imports: Record<string, string>,
199
+ ) => string;
200
+ /**
201
+ * The URL of a shadow component's stylesheet, by tag, or `null` for a component whose sheet the
202
+ * caller does not write (spec.md §16.6). A root the module attaches itself, for an instance no
203
+ * prerender drew, links it, because the document's sheets cannot reach into the root. A result
204
+ * opening with `./` or `../` is resolved against the module's own URL, which is how a pack names
205
+ * the sibling it ships; anything else is linked as written. Without the option nothing is linked.
206
+ * Read for every `$elements` dependency too, and never for a light-DOM component.
207
+ */
208
+ stylesheetHref?: (tagName: string) => string | null;
209
+ }
210
+
211
+ /**
212
+ * The source of a stylesheet link's `href`: a module-relative reference resolved against the
213
+ * module's own URL when it runs, anything else as a literal.
214
+ */
215
+ function stylesheetHrefSource(href: string): string {
216
+ const literal = JSON.stringify(href);
217
+ return /^\.{1,2}\//u.test(href) ? `new URL(${literal}, import.meta.url).href` : literal;
126
218
  }
127
219
 
128
220
  /**
@@ -185,6 +277,9 @@ export async function compileElement(
185
277
  }
186
278
  }
187
279
 
280
+ await opts.prepareDocument?.(doc, filePath);
281
+
282
+ const declaredState = doc.state ?? {};
188
283
  doc = inheritProjectFormulas(doc, opts.projectState);
189
284
 
190
285
  const { tagName } = doc;
@@ -220,7 +315,8 @@ export async function compileElement(
220
315
  if (optsMedia) {
221
316
  doc.$media = { ...optsMedia, ...doc.$media };
222
317
  }
223
- const { rewriteSrc } = opts;
318
+ const { resolveClass, rewriteSrc } = opts;
319
+ const classImports = doc.imports ?? {};
224
320
  const jsContent = emitElementModule(
225
321
  doc,
226
322
  className,
@@ -228,6 +324,11 @@ export async function compileElement(
228
324
  rewriteSrc ? (spec: string) => rewriteSrc(spec, currentDir) : undefined,
229
325
  resolveShadowMode(doc, opts.defaults),
230
326
  opts.serverBaseUrl,
327
+ Object.keys(doc.state ?? {}).filter((key) => !(key in declaredState)),
328
+ resolveClass
329
+ ? (def: JxPrototypeDef) => resolveClass(def, currentDir, classImports)
330
+ : undefined,
331
+ opts.stylesheetHref?.(tagName) ?? null,
231
332
  );
232
333
  const outputPath = filePath ? filePath.replace(/\.(?:json|jxn)$/i, ".js") : `${tagName}.js`;
233
334
  files.push({ content: jsContent, path: outputPath, tagName });
@@ -242,6 +343,8 @@ export interface CompileElementPageOptions extends CompileElementOptions {
242
343
  title?: string;
243
344
  reactivitySrc?: string;
244
345
  litHtmlSrc?: string;
346
+ /** The build's whole import map, written in place of the two sources above (compiler.md §12). */
347
+ runtimeImports?: Record<string, string>;
245
348
  }
246
349
 
247
350
  /**
@@ -280,14 +383,7 @@ export async function compileElementPage(
280
383
  <meta charset="utf-8">
281
384
  <meta name="viewport" content="width=device-width, initial-scale=1">
282
385
  <title>${escapeHtml(title)}</title>
283
- <script type="importmap">
284
- {
285
- "imports": {
286
- "@vue/reactivity": "${reactivitySrc}",
287
- "lit-html": "${litHtmlSrc}"
288
- }
289
- }
290
- </script>
386
+ ${pageImportMap({ litHtmlSrc, reactivitySrc, runtimeImports: opts.runtimeImports })}
291
387
  </head>
292
388
  <body>
293
389
  <${root.tagName}></${root.tagName}>
@@ -327,6 +423,10 @@ function extractInitialValue(def: JxStateDefinition) {
327
423
  if (def.$prototype === "Request") {
328
424
  return "null";
329
425
  }
426
+ // A `timing: "client"` external class holds nothing until its class resolves (compiler.md §3)
427
+ if (isClientExternalClass(def)) {
428
+ return "null";
429
+ }
330
430
  // A `timing: "server"` entry holds nothing until the site worker's route answers (§6.1)
331
431
  if (isServerFnDef(def)) {
332
432
  return "null";
@@ -350,6 +450,9 @@ export function emitElementModule(
350
450
  rewriteSrc?: (specifier: string) => string,
351
451
  shadow: ShadowMode | null = null,
352
452
  serverBaseUrl = "/_jx/server",
453
+ inherited: readonly string[] = [],
454
+ resolveClass?: (def: JxPrototypeDef) => string,
455
+ stylesheetHref: string | null = null,
353
456
  ) {
354
457
  const lines: string[] = ["// Generated by @jxsuite/compiler — do not edit manually"];
355
458
 
@@ -369,6 +472,14 @@ export function emitElementModule(
369
472
  // The site build bundles them after all documents compile (spec.md §12).
370
473
  lines.push(...srcImports.imports);
371
474
 
475
+ /* `timing: "client"` external classes (compiler.md §3): each class module is imported here, and
476
+ the instance constructs and resolves them before it first renders. Everything below that
477
+ exists for them is emitted only when the document has one, so a document without a client
478
+ class compiles to exactly the module it did before. */
479
+ const clientClasses = collectClientClasses(defs, resolveClass);
480
+ const waitsForClasses = clientClasses.entries.length > 0;
481
+ lines.push(...clientClasses.imports);
482
+
372
483
  // `$prototype: "Request"` entries each get an auto-fetch effect in connectedCallback, plus the
373
484
  // Machinery to stop those effects again on disconnect. Both are emitted only when one exists, so
374
485
  // Documents without a Request produce exactly the same module as before.
@@ -382,17 +493,68 @@ export function emitElementModule(
382
493
  isServerFnDef(def) ? [[key, def]] : [],
383
494
  );
384
495
 
496
+ /* What the document's lists need (compiler.md §4.7), decided before anything is emitted. A
497
+ module with no filtered, sorted or keyed list carries none of it. */
498
+ const lists = mappedArrayFeatures(doc);
385
499
  lines.push(
386
- `import { reactive, computed, effect, stop } from '@vue/reactivity';`,
500
+ lists.keyed
501
+ ? `import { reactive, computed, effect, stop, shallowRef } from '@vue/reactivity';`
502
+ : `import { reactive, computed, effect, stop } from '@vue/reactivity';`,
387
503
  /* `nothing` is what REMOVES an attribute in a lit template, and it is the only way to express a
388
504
  false presence attribute: writing `open="false"` produces an OPEN <details>. See
389
505
  `attrHelperSource`. */
390
506
  `import { render, html, nothing } from 'lit-html';`,
507
+ ...(lists.keyed ? KEYED_LIST_IMPORTS : []),
391
508
  attrHelperSource(),
392
509
  );
510
+ if (lists.arranged || lists.keyed) {
511
+ lines.push(listHelperSource());
512
+ }
513
+ if (lists.keyed) {
514
+ lines.push(keyedListDirectiveSource());
515
+ }
516
+
517
+ /* The property bridge's key sets, taken from the DEFINITION (spec.md §13.2, §16.2). Not from
518
+ `this.state`: a pure type definition (`{ "type": "string" }`) holds no value, so it is not in
519
+ the reactive object until a prop sets it, and a membership test against state refused the most
520
+ common way to declare a prop. `__jxProps` is what the two attribute sources accept; the
521
+ bridged keys are those that can also be a property of the element. */
522
+ const propKeys = Object.keys(defs).filter((key) => !isPrivateStateKey(key));
523
+ const bridgedKeys = propKeys.filter((key) => !ELEMENT_MEMBERS.has(key));
524
+ /* An inherited project formula is in the scope and not in the element's interface (spec.md
525
+ §13.4): it is bridged only on an instance that was given a prop of that name. */
526
+ const inheritedKeys = bridgedKeys.filter((key) => inherited.includes(key));
527
+ const tracksGiven = inheritedKeys.length > 0;
528
+ lines.push(`const __jxProps = ${JSON.stringify(propKeys)};`);
529
+ /* The bridged keys the scope DERIVES (spec.md §16.2): each gets a getter and no setter, from
530
+ the verdict the interpreter reads, and is never merged from a property. */
531
+ const derived = derivedStateKeys(doc);
532
+ const derivedKeys = bridgedKeys.filter((key) => derived.has(key));
533
+ if (bridgedKeys.length > 0) {
534
+ lines.push(`const __jxBridged = ${JSON.stringify(bridgedKeys)};`, propSupplyHelperSource());
535
+ }
536
+ if (derivedKeys.length > 0) {
537
+ lines.push(`const __jxDerived = new Set(${JSON.stringify(derivedKeys)});`);
538
+ }
539
+ if (tracksGiven) {
540
+ lines.push(`const __jxInherited = new Set(${JSON.stringify(inheritedKeys)});`);
541
+ }
542
+ /* Observed attributes (spec.md §16.5), emitted only when the definition declares any: the rule,
543
+ the list the platform reads, and the observed keys' declared defaults. */
544
+ const observed = observedAttributeNames(doc);
545
+ if (observed.length > 0) {
546
+ lines.push(
547
+ observedAttrHelperSource(),
548
+ `const __jxObserved = ${JSON.stringify(observed)};`,
549
+ `const __jxObservedDefaults = () => ${observedDefaultsSource(doc)};`,
550
+ );
551
+ }
393
552
  if (serverEntries.length > 0) {
394
553
  lines.push(serverCallHelperSource());
395
554
  }
555
+ if (waitsForClasses) {
556
+ lines.push(externalClassHelperSource());
557
+ }
396
558
  /* Light-DOM slot distribution, by the rule the interpreter applies (spec.md §8.5): only a module
397
559
  whose template draws a slot carries it, and a shadow component never does — its light children
398
560
  ARE the slotted content, and a real `<slot>` distributes them. */
@@ -401,6 +563,13 @@ export function emitElementModule(
401
563
  lines.push(slotHelperSource());
402
564
  }
403
565
 
566
+ /* Form association (spec.md §16.11). Everything it adds is emitted only for a definition that
567
+ declares `formAssociated: true`, so every other module is the one it was. */
568
+ const formAssociated = doc.formAssociated === true;
569
+ if (formAssociated) {
570
+ lines.push(formAssociationHelperSource());
571
+ }
572
+
404
573
  // `$lazy` entries load on their first call instead of with the page (spec.md §5.3 4d).
405
574
  lines.push(
406
575
  ...srcImports.loaders,
@@ -412,8 +581,44 @@ export function emitElementModule(
412
581
  // Held a handle to.
413
582
  " #effects = [];",
414
583
  " #rendered = false;",
584
+ /* The part lit's `render()` returns, kept by a module with a keyed list so the element can
585
+ tell lit when its host leaves and returns: standalone `render()` never disconnects an
586
+ `AsyncDirective` on its own, and the list's effect would keep a removed element subscribed
587
+ to an array its parent owns. */
588
+ ...(lists.keyed ? [" #part = null;"] : []),
415
589
  ...(shadow === null ? [] : [" #root = null;"]),
590
+ /* The one `attachInternals()` an element may make, shared by a closed root's adoption and the
591
+ form binding, and the binding itself. `undefined` is "not asked yet"; `null`, a platform
592
+ with no `ElementInternals`, where the element is simply not associated. */
593
+ ...(formAssociated ? [" #internals;", " #form = null;"] : []),
594
+ /* A component with client classes draws in `#jxRender()`, once they have resolved: the
595
+ instances by state key, the one resolution an instance ever starts, the connection a pending
596
+ draw belongs to, and whether a draw has happened yet. */
597
+ ...(waitsForClasses
598
+ ? [
599
+ " #jxInstances = new Map();",
600
+ " #jxReady = null;",
601
+ " #jxConnection = 0;",
602
+ " #jxDrawn = false;",
603
+ ]
604
+ : []),
416
605
  "",
606
+ ...(observed.length > 0
607
+ ? [" static get observedAttributes() { return __jxObserved; }", ""]
608
+ : []),
609
+ ...(formAssociated
610
+ ? [
611
+ " static formAssociated = true;",
612
+ "",
613
+ " #attach() {",
614
+ " if (this.#internals === undefined) {",
615
+ " this.#internals = typeof this.attachInternals === 'function' ? this.attachInternals() : null;",
616
+ " }",
617
+ " return this.#internals;",
618
+ " }",
619
+ "",
620
+ ]
621
+ : []),
417
622
  // Constructor: build reactive state
418
623
  " constructor() {",
419
624
  " super();",
@@ -532,9 +737,15 @@ export function emitElementModule(
532
737
  runtime and the build-time scope evaluate it (spec.md §5.3), so a component reads the same
533
738
  value hydrated as it did prerendered. */
534
739
  for (const [key, template] of templateEntries) {
740
+ const rewritten = rewriteState(template, "this.state", { code: false });
741
+ const value = templateValueSource(rewritten);
742
+ /* A template may hand the scope itself to a helper (`${state.applySelection(state)}`), which
743
+ the interpreter binds as a parameter. Here it is declared for the computed that reads it. */
535
744
  lines.push(
536
745
  "",
537
- ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${templateValueSource(rewriteState(template, "this.state", { code: false }))});`,
746
+ holesReadBareState(rewritten)
747
+ ? ` ${refAccessor("this.state", escapeToken(key))} = computed(() => { const state = this.state; return ${value}; });`
748
+ : ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${value});`,
538
749
  );
539
750
  }
540
751
 
@@ -560,15 +771,28 @@ export function emitElementModule(
560
771
  }
561
772
  }
562
773
 
774
+ /* Root-level handlers listen on the host (spec.md §16.1, §4.3). They have no node in the
775
+ template, so the constructor attaches each to the element, lowered as a child's binding is. It
776
+ runs once per instance, which is the once-only the interpreter gets from its initialized flag:
777
+ no options, the element's own lifetime, never removed. The block keeps `s` out of the
778
+ constructor's scope, where a `$src` import could share the name. */
779
+ const listeners = hostHandlers(doc);
780
+ if (listeners.length > 0) {
781
+ lines.push("", " {", " const s = this.state;");
782
+ for (const { type, source } of listeners) {
783
+ lines.push(` this.addEventListener(${JSON.stringify(type)}, ${source});`);
784
+ }
785
+ lines.push(" }");
786
+ }
787
+
563
788
  lines.push(" }", ""); // End constructor
564
789
 
565
- // Collect CSS rules from children tree (assigns .jx-N classes to defs)
566
- const cssRules: string[] = [];
567
- if (Array.isArray(doc.children)) {
568
- const counter = { n: 0 };
569
- for (const child of doc.children) {
570
- collectStyles(child, cssRules, doc.$media ?? {}, "", counter, doc.tagName);
571
- }
790
+ /* Give the template's styled nodes the handles the component's sheet selects (spec.md §9.2).
791
+ The sheet itself is `buildComponentCSS`'s; this walk makes the same traversal over this parse,
792
+ so the two number the same nodes alike, and it builds no rule. */
793
+ const handleCounter = { n: 0 };
794
+ for (const child of styleChildren(doc)) {
795
+ assignStyleHandles(child, handleCounter, doc.tagName ?? "jx");
572
796
  }
573
797
 
574
798
  // Subtrees a branching construct would otherwise repeat are lifted into `const _cN = html`…``
@@ -585,10 +809,16 @@ export function emitElementModule(
585
809
  ? ` ${toLitTextContent(doc.textContent)}`
586
810
  : emitLitChildren(doc.children, doc.style, " ", false, false, hoistScope);
587
811
 
812
+ /* `state` on its own inside a template hole (a helper handed the scope) reads the same object
813
+ `s` does; declared only for a template that names it. */
814
+ const templateNamesState = [templateBody, ...hoistScope.decls].some((text) =>
815
+ holesReadBareState(text),
816
+ );
588
817
  lines.push(
589
818
  // Template method
590
819
  " template() {",
591
820
  " const s = this.state;",
821
+ ...(templateNamesState ? [" const state = s;"] : []),
592
822
  ...hoistScope.decls,
593
823
  " return html`",
594
824
  templateBody,
@@ -611,21 +841,66 @@ export function emitElementModule(
611
841
  " #renderRoot() {",
612
842
  " if (this.#root) return this.#root;",
613
843
  shadow === "closed"
614
- ? " this.#root = this.attachInternals().shadowRoot ?? this.attachShadow({ mode: 'closed' });"
615
- : " this.#root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });",
844
+ ? formAssociated
845
+ ? " const _a = this.#attach()?.shadowRoot ?? null;"
846
+ : " const _a = this.attachInternals().shadowRoot;"
847
+ : " const _a = this.shadowRoot;",
848
+ ` this.#root = _a ?? this.attachShadow({ mode: '${shadow}' });`,
849
+ /* A root the parser made carries the link its prerender wrote. One attached here, for
850
+ an instance a list, a `$switch` case or a script created, has none, and the
851
+ document's sheets cannot reach in, so the module links the same sheet itself. */
852
+ ...(stylesheetHref === null
853
+ ? []
854
+ : [
855
+ " if (!_a) this.#root.append(Object.assign(document.createElement('link'), " +
856
+ `{ rel: 'stylesheet', href: ${stylesheetHrefSource(stylesheetHref)} }));`,
857
+ ]),
616
858
  " return this.#root;",
617
859
  " }",
618
860
  "",
619
861
  ]),
620
862
  // ConnectedCallback
621
863
  " connectedCallback() {",
864
+ /*
865
+ * What happens to an instance ONCE is decided by this flag, read before anything else.
866
+ * `connectedCallback` runs again each time the element is put back in a document (a list
867
+ * reordered with `append`, a panel moved between containers), and `disconnectedCallback` only
868
+ * stopped the effects: the tree lit drew is still there, and so is the part lit cached on the
869
+ * container for it. Clearing the container a second time removed the nodes that part still
870
+ * points at, so the render that followed updated a detached tree and the element stayed empty
871
+ * for good. A second slot capture is wrong for its own reason: by then the host's children are
872
+ * the component's own render, not what the author slotted. And a second property merge would
873
+ * read the element's own accessors back into the state they forward to.
874
+ */
875
+ " const _first = !this.#rendered;",
876
+ " this.#rendered = true;",
877
+ ...(lists.keyed ? [" this.#part?.setConnected(true);"] : []),
878
+ ...(tracksGiven ? [" const _given = new Set();"] : []),
879
+ /*
880
+ * Observed attributes already on the element, read first so that `$props` and a property a
881
+ * parent set still win (spec.md §16.5), and on the first connection only: a re-insertion must
882
+ * not put an attribute's value back over state a handler has changed since. A browser has
883
+ * already delivered these through `attributeChangedCallback` when the element was created or
884
+ * upgraded, so the read repeats it there; it is kept because it is the interpreter's shape,
885
+ * and because it does not depend on that delivery.
886
+ */
887
+ ...(observed.length > 0
888
+ ? [
889
+ " if (_first) {",
890
+ " const _d = __jxObservedDefaults();",
891
+ " for (const _a of __jxObserved) {",
892
+ ` if (this.hasAttribute(_a)) ${OBSERVED_ATTR_HELPER}(this.state, _a, this.getAttribute(_a), _d);`,
893
+ " }",
894
+ " }",
895
+ ]
896
+ : []),
622
897
  /*
623
898
  * Each of the three absorption paths below skips a `#`-prefixed key: private state is not part
624
- * of the component's interface and is never settable through $props (spec.md §5.6). Emitted as
625
- * a runtime check rather than resolved at build time because all three read keys that arrive
626
- * with the instance — an attribute payload, an attribute name, a property a parent set — none
627
- * of which the compiler can see. The interpreter enforces the same rule in `runtime.ts`; the
628
- * two tiers agreeing is the point, since a document is authored against whichever runs.
899
+ * of the component's interface and is never settable through $props (spec.md §5.6). The two
900
+ * attribute paths check at run time because they read keys that arrive with the instance — an
901
+ * attribute payload, an attribute name — which the compiler cannot see; the property path reads
902
+ * a list that never held one. The interpreter enforces the same rule in `runtime.ts`; the two
903
+ * tiers agreeing is the point, since a document is authored against whichever runs.
629
904
  */
630
905
  // Read $props from data-jx-props attribute (set by compiler for pre-rendered instances)
631
906
  " const _pa = this.getAttribute('data-jx-props');",
@@ -634,7 +909,9 @@ export function emitElementModule(
634
909
  " const _p = JSON.parse(_pa);",
635
910
  " for (const [k, v] of Object.entries(_p)) {",
636
911
  " if (k.startsWith('#')) continue;",
637
- " if (k in this.state) this.state[k] = v;",
912
+ tracksGiven
913
+ ? " if (__jxProps.includes(k)) { this.state[k] = v; _given.add(k); }"
914
+ : " if (__jxProps.includes(k)) this.state[k] = v;",
638
915
  " }",
639
916
  " } catch {}",
640
917
  " this.removeAttribute('data-jx-props');",
@@ -646,21 +923,89 @@ export function emitElementModule(
646
923
  " for (const _n of _pn) {",
647
924
  " const _k = _n.slice(6);",
648
925
  " if (_k.startsWith('#')) { this.removeAttribute(_n); continue; }",
649
- " if (_k in this.state) {",
926
+ " if (__jxProps.includes(_k)) {",
650
927
  " this.state[_k] = this.getAttribute(_n);",
928
+ ...(tracksGiven ? [" _given.add(_k);"] : []),
651
929
  " this.removeAttribute(_n);",
652
930
  " }",
653
931
  " }",
654
- // Merge JS properties set before connection (by parent runtime).
655
- // Only check own properties to avoid inherited DOM properties like `title`.
656
- " for (const key of Object.keys(this.state)) {",
657
- " if (key.startsWith('#')) continue;",
658
- " if (this.hasOwnProperty(key) && this[key] !== undefined) {",
659
- " this.state[key] = this[key];",
660
- " }",
661
- " }",
662
932
  );
663
933
 
934
+ if (bridgedKeys.length > 0) {
935
+ lines.push(
936
+ /*
937
+ * The property bridge (spec.md §13.2, §16.2), on the first connection only, as the
938
+ * interpreter does it. First the merge: a property the instance genuinely carries, by the
939
+ * supply rule, so a reflected name nobody set (`title` answering "") does not beat the
940
+ * declared default, and a parent's `.title=`, which creates no own property, is not dropped.
941
+ * Then the accessors, on the INSTANCE and after the merge: a write before connection made an
942
+ * own property the merge has just read, and the accessor now replaces it. On the prototype it
943
+ * would have put that early write straight into state, where the two attribute reads above
944
+ * would then overwrite it, and a property is the source that wins.
945
+ */
946
+ " if (_first) {",
947
+ " for (const _k of __jxBridged) {",
948
+ // A derived key has no cell to merge into; the property a parent wrote is discarded below.
949
+ ...(derivedKeys.length > 0 ? [" if (__jxDerived.has(_k)) continue;"] : []),
950
+ ` if (_k in this && this[_k] !== undefined && ${PROP_SUPPLY_HELPER}(this, _k)) {`,
951
+ " this.state[_k] = this[_k];",
952
+ ...(tracksGiven ? [" _given.add(_k);"] : []),
953
+ " }",
954
+ " }",
955
+ " for (const _k of __jxBridged) {",
956
+ ...(tracksGiven ? [" if (__jxInherited.has(_k) && !_given.has(_k)) continue;"] : []),
957
+ // A derived key is read-only: a getter and no setter, as a read-only IDL attribute has.
958
+ ...(derivedKeys.length > 0
959
+ ? [
960
+ " if (__jxDerived.has(_k)) {",
961
+ " Object.defineProperty(this, _k, { configurable: true, get: () => this.state[_k] });",
962
+ " continue;",
963
+ " }",
964
+ ]
965
+ : []),
966
+ // A name the platform owns keeps reflecting: its own setter runs first, then state.
967
+ ` const _set = ${NATIVE_SETTER_HELPER}(this, _k);`,
968
+ " Object.defineProperty(this, _k, {",
969
+ " configurable: true,",
970
+ " get: () => this.state[_k],",
971
+ " set: (v) => { if (_set) _set.call(this, v); this.state[_k] = v; },",
972
+ " });",
973
+ " }",
974
+ " }",
975
+ );
976
+ }
977
+
978
+ if (waitsForClasses) {
979
+ lines.push(
980
+ /*
981
+ * The classes are constructed once per instance, after the merge above so a class reads the
982
+ * props the instance arrived with, and the first draw waits for them: a template that reads
983
+ * a class's value (`${state.forecast.days.length}`) sees the value, as it does under the
984
+ * interpreter, which awaits every class before it renders. The prerendered markup stays in
985
+ * place meanwhile. A draw belongs to the connection that asked for it: an instance removed
986
+ * before its classes settle does not draw, and one put back draws once, for the connection
987
+ * it now has.
988
+ */
989
+ ` this.#jxReady ??= ${emitExternalClassResolution(clientClasses.entries, {
990
+ indent: " ",
991
+ instances: "this.#jxInstances",
992
+ statePrefix: "this.state",
993
+ })};`,
994
+ " const _c = ++this.#jxConnection;",
995
+ " this.#jxReady.then(() => {",
996
+ " if (_c === this.#jxConnection && this.isConnected) this.#jxRender();",
997
+ " });",
998
+ " }",
999
+ "",
1000
+ /* Everything a connection does once its classes have resolved. `_first` is the first DRAW
1001
+ here, not the first connection: an instance removed and put back before its classes
1002
+ settled has connected twice and drawn nothing. */
1003
+ " #jxRender() {",
1004
+ " const _first = !this.#jxDrawn;",
1005
+ " this.#jxDrawn = true;",
1006
+ );
1007
+ }
1008
+
664
1009
  // `$prototype: "Request"` entries fetch on connect — after the `$props`/property merge above, so
665
1010
  // A template `url` interpolates the values the parent passed in rather than the initial ones.
666
1011
  // Runners are collected so disconnectedCallback can stop them: a reactive URL would otherwise
@@ -686,6 +1031,9 @@ export function emitElementModule(
686
1031
  }),
687
1032
  );
688
1033
  }
1034
+ /* The definition's root `attributes`, written on the host (spec.md §16.1) after the props merge
1035
+ and before the render, as the interpreter's `applyAttributes(this, def.attributes)` is. */
1036
+ lines.push(...hostAttributeLines(doc));
689
1037
  if (isNonNullObject(doc.style)) {
690
1038
  const dynamicStyles: [string, string][] = [];
691
1039
  for (const [prop, value] of Object.entries(doc.style)) {
@@ -724,17 +1072,6 @@ export function emitElementModule(
724
1072
  * `data-jx-prerendered` goes and before the clear: a prerendered instance's children are its
725
1073
  * markup, and capture recovers what the prerender placed from its brackets instead.
726
1074
  */
727
- /*
728
- * Everything from here to the render effect happens to an instance ONCE. `connectedCallback` runs
729
- * again each time the element is put back in a document (a list reordered with `append`, a panel
730
- * moved between containers), and `disconnectedCallback` only stopped the effects: the tree lit
731
- * drew is still there, and so is the part lit cached on the container for it. Clearing the
732
- * container a second time removed the nodes that part still points at, so the render that
733
- * followed updated a detached tree and the element stayed empty for good. A second capture is
734
- * wrong for its own reason: by then the host's children are the component's own render, not
735
- * what the author slotted.
736
- */
737
- lines.push(" const _first = !this.#rendered;", " this.#rendered = true;");
738
1075
  if (hasSlot) {
739
1076
  lines.push(` const _slotted = _first ? ${SLOT_CAPTURE_HELPER}(this) : null;`);
740
1077
  }
@@ -753,7 +1090,9 @@ export function emitElementModule(
753
1090
  * module a site ships.
754
1091
  */
755
1092
  " if (_first) this.replaceChildren();",
756
- " this.#effects.push(effect(() => render(this.template(), this)));",
1093
+ lists.keyed
1094
+ ? " this.#effects.push(effect(() => { this.#part = render(this.template(), this); }));"
1095
+ : " this.#effects.push(effect(() => render(this.template(), this)));",
757
1096
  );
758
1097
  } else {
759
1098
  /*
@@ -776,31 +1115,77 @@ export function emitElementModule(
776
1115
  " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
777
1116
  " }",
778
1117
  " }",
779
- " this.#effects.push(effect(() => render(this.template(), _root)));",
1118
+ lists.keyed
1119
+ ? " this.#effects.push(effect(() => { this.#part = render(this.template(), _root); }));"
1120
+ : " this.#effects.push(effect(() => render(this.template(), _root)));",
780
1121
  );
781
1122
  }
782
1123
  if (hasSlot) {
783
1124
  // Once, after the first render: a slot a later render draws stays literal (spec.md §8.5).
784
1125
  lines.push(` if (_first) ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
785
1126
  }
1127
+ if (formAssociated) {
1128
+ /* Bound once, after the first render, so the element's control is in its tree; the reactive
1129
+ half starts again on every connection, with effects `disconnectedCallback` stops. */
1130
+ lines.push(
1131
+ " if (_first) {",
1132
+ " const _i = this.#attach();",
1133
+ " if (_i) {",
1134
+ ` this.#form = ${FORM_ASSOCIATION_HELPER}(this, _i, this.state, ${JSON.stringify(formStateKeys(doc))}, ` +
1135
+ `() => ${shadow === null ? "this" : "this.#renderRoot()"}, ${formValueSource(doc.formValue)}, ` +
1136
+ "(fn) => { this.#effects.push(effect(fn)); });",
1137
+ " }",
1138
+ " }",
1139
+ " if (this.#form) this.#form.start();",
1140
+ );
1141
+ }
786
1142
  lines.push(
787
- // Lifecycle: onMount (spec §16.4) — same microtask contract as the runtime
788
- " if (typeof this.state.onMount === 'function') {",
789
- " queueMicrotask(() => this.state.onMount(this.state));",
1143
+ /* Lifecycle: onMount (spec.md §16.4), by the interpreter's contract. On a microtask after the
1144
+ render; with the scope and the HOST, and the host as its receiver, so a sidecar reaches the
1145
+ element it belongs to; and on the first connection only, like everything else that happens
1146
+ to an instance once. A parent's slot distribution moves a slotted element straight after it
1147
+ rendered, and a hook that ran per connection handed every slotted component its host twice. */
1148
+ " if (_first && typeof this.state.onMount === 'function') {",
1149
+ " queueMicrotask(() => this.state.onMount.call(this, this.state, this));",
790
1150
  " }",
791
1151
  " }",
792
1152
  "",
793
1153
  // DisconnectedCallback
794
1154
  " disconnectedCallback() {",
1155
+ ...(lists.keyed ? [" this.#part?.setConnected(false);"] : []),
795
1156
  " for (const _e of this.#effects) { stop(_e); }",
796
1157
  " this.#effects.length = 0;",
797
1158
  " if (typeof this.state.onUnmount === 'function') { this.state.onUnmount(this.state); }",
798
1159
  " }",
799
- "}",
800
- "",
801
- `customElements.define('${doc.tagName}', ${className});`,
802
- "",
803
1160
  );
1161
+ if ("onAdopted" in defs) {
1162
+ lines.push(
1163
+ "",
1164
+ " adoptedCallback() {",
1165
+ " if (typeof this.state.onAdopted === 'function') { this.state.onAdopted(this.state); }",
1166
+ " }",
1167
+ );
1168
+ }
1169
+ if (formAssociated) {
1170
+ lines.push(
1171
+ "",
1172
+ " formResetCallback() { if (this.#form) this.#form.reset(); }",
1173
+ "",
1174
+ " formDisabledCallback(disabled) { if (this.#form) this.#form.disabled(disabled); }",
1175
+ );
1176
+ }
1177
+ if (observed.length > 0) {
1178
+ lines.push(
1179
+ "",
1180
+ /* The constructor built the state, so unlike the interpreter this needs no state guard and
1181
+ hears a change made before connection too. */
1182
+ " attributeChangedCallback(name, oldVal, newVal) {",
1183
+ " if (oldVal === newVal) return;",
1184
+ ` ${OBSERVED_ATTR_HELPER}(this.state, name, newVal, __jxObservedDefaults());`,
1185
+ " }",
1186
+ );
1187
+ }
1188
+ lines.push("}", "", `customElements.define('${doc.tagName}', ${className});`, "");
804
1189
 
805
1190
  return lines.join("\n");
806
1191
  }
@@ -1000,8 +1385,14 @@ ${no}
1000
1385
 
1001
1386
  const parts: string[] = [];
1002
1387
 
1388
+ const classAttr = litClassAttr(def, toLitExpr, refToExpr);
1389
+
1003
1390
  if (def.attributes) {
1004
1391
  for (const [key, val] of Object.entries(def.attributes)) {
1392
+ // Written once below, merged with the style handle.
1393
+ if (key === "class" && classAttr !== null) {
1394
+ continue;
1395
+ }
1005
1396
  /* Every branch here answers the same question the runtime's `applyAttributes` answers, and
1006
1397
  must answer it the same way or a prerendered page changes meaning as it hydrates (spec.md
1007
1398
  §8.3). A LITERAL boolean is decided now; a BOUND one cannot be, because its resolved type
@@ -1034,8 +1425,8 @@ ${no}
1034
1425
  if (def.id) {
1035
1426
  parts.push(`id="${toLitExpr(String(def.id))}"`);
1036
1427
  }
1037
- if (def.className) {
1038
- parts.push(`class="${toLitExpr(String(def.className))}"`);
1428
+ if (classAttr !== null) {
1429
+ parts.push(classAttr);
1039
1430
  }
1040
1431
 
1041
1432
  for (const [key, val] of Object.entries(def)) {
@@ -1093,23 +1484,9 @@ ${no}
1093
1484
  }
1094
1485
  refuseBodyWithSrc(`inline "${key}" handler`, val);
1095
1486
  const eventName = key.slice(2).toLowerCase();
1096
- if (isBoundRef(val)) {
1097
- parts.push(
1098
- mapCtx
1099
- ? `@${eventName}="\${(e) => { ${mapCtx}${refToExpr(val.$ref)}(s, e); }}"`
1100
- : `@${eventName}="\${(e) => ${refToExpr(val.$ref)}(s, e)}"`,
1101
- );
1102
- } else if (isNonNullObject(val) && "$expression" in val) {
1103
- /* SAFETY: an `on*` binding object carrying `$expression` is a declarative handler, and the
1104
- document schema types that member as an expression node (spec.md §19). It is passed on
1105
- unvalidated, exactly as authored, so a malformed node fails inside compileExpression. */
1106
- const compiled = compileExpression(val.$expression as JxExpressionNode, {
1107
- eventParam: "e",
1108
- statePrefix: "s",
1109
- });
1110
- parts.push(`@${eventName}="\${(e) => { ${mapCtx}${compiled}; }}"`);
1111
- } else if (isFunctionDef(val)) {
1112
- parts.push(`@${eventName}="\${(e) => { ${mapCtx}${inlineHandlerBody(val)} }}"`);
1487
+ const handler = handlerSource(val, mapCtx);
1488
+ if (handler !== null) {
1489
+ parts.push(`@${eventName}="\${${handler}}"`);
1113
1490
  }
1114
1491
  }
1115
1492
 
@@ -1207,7 +1584,21 @@ function emitNodeInner(
1207
1584
  * @returns {string}
1208
1585
  */
1209
1586
  function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1210
- const itemsExpr = isRef(arrayDef.items) ? refToExpr(arrayDef.items.$ref) : "ITEMS";
1587
+ /* A literal `items` is written into the module as JSON, as the client target writes it. A
1588
+ pointer that reads nothing is an empty list, as in the interpreter, not a `TypeError` thrown
1589
+ inside the render effect after the prerender has been cleared. */
1590
+ refuseTemplateItems(arrayDef);
1591
+ const keyed = isRef(arrayDef.key);
1592
+ const literal = JSON.stringify(Array.isArray(arrayDef.items) ? arrayDef.items : []);
1593
+ let itemsExpr = keyed ? `${LIST_LITERAL_HELPER}(${JSON.stringify(literal)})` : literal;
1594
+ if (isRef(arrayDef.items)) {
1595
+ itemsExpr = `(${refToExpr(arrayDef.items.$ref)} ?? [])`;
1596
+ }
1597
+ /* `filter` and `sort` are each a `$ref` to a callable (spec.md §10.3); anything else is ignored,
1598
+ as the interpreter ignores it. */
1599
+ const filterExpr = isRef(arrayDef.filter) ? refToExpr(arrayDef.filter.$ref) : "undefined";
1600
+ const sortExpr = isRef(arrayDef.sort) ? refToExpr(arrayDef.sort.$ref) : "undefined";
1601
+ const arranged = isRef(arrayDef.filter) || isRef(arrayDef.sort);
1211
1602
  const mapDef = arrayDef.map;
1212
1603
 
1213
1604
  if (!mapDef) {
@@ -1219,8 +1610,13 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1219
1610
 
1220
1611
  // The map root gets the same attribute treatment as any other element (emitLitNode above);
1221
1612
  // `${item…}`/`${index…}` templates resolve against the map callback's own parameters.
1613
+ const classAttr = litClassAttr(mapDef, toLitExpr, mapRefToExpr);
1222
1614
  if (mapDef.attributes) {
1223
1615
  for (const [key, val] of Object.entries(mapDef.attributes)) {
1616
+ // Written once below, merged with the style handle.
1617
+ if (key === "class" && classAttr !== null) {
1618
+ continue;
1619
+ }
1224
1620
  if (isRef(val)) {
1225
1621
  parts.push(`${key}="\${${mapRefToExpr(val.$ref)}}"`);
1226
1622
  } else if (isString(val) && val.includes("${")) {
@@ -1234,8 +1630,8 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1234
1630
  if (mapDef.id) {
1235
1631
  parts.push(`id="${toLitExpr(String(mapDef.id))}"`);
1236
1632
  }
1237
- if (mapDef.className) {
1238
- parts.push(`class="${toLitExpr(String(mapDef.className))}"`);
1633
+ if (classAttr !== null) {
1634
+ parts.push(classAttr);
1239
1635
  }
1240
1636
 
1241
1637
  // IDL properties (`value`, `checked`, `selected`, …) go straight on the element, exactly as they
@@ -1293,17 +1689,10 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1293
1689
  }
1294
1690
  refuseBodyWithSrc(`inline "${key}" handler`, val);
1295
1691
  const eventName = key.slice(2).toLowerCase();
1296
- if (isRef(val)) {
1297
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${refToExpr(val.$ref)}(s, e); }}"`);
1298
- } else if (isExpressionDef(val)) {
1299
- const compiled = compileExpression(val.$expression, {
1300
- eventParam: "e",
1301
- statePrefix: "s",
1302
- });
1303
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${compiled}; }}"`);
1304
- } else if (isFunctionDef(val)) {
1305
- // A map root binds an inline handler as any other element does, with the iteration published.
1306
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${inlineHandlerBody(val)} }}"`);
1692
+ // A map root binds a handler as any other element does, with the iteration published.
1693
+ const handler = handlerSource(val, "s.$map = $map; ");
1694
+ if (handler !== null) {
1695
+ parts.push(`@${eventName}="\${${handler}}"`);
1307
1696
  }
1308
1697
  }
1309
1698
 
@@ -1336,7 +1725,58 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1336
1725
  ? `(item, index) => { ${prelude}return ${body}; }`
1337
1726
  : `(item, index) => ${body}`;
1338
1727
 
1339
- return `${indent}\${${itemsExpr}.map(${callback})}`;
1728
+ /* Three lowerings (spec.md §10.3, §10.4, compiler.md §4.7). A keyed list goes through the
1729
+ directive, which shapes it, keys it and hands lit's `repeat()` a snapshot. An unkeyed list has
1730
+ no identity but its position, which is what lit's own array rendering reconciles by, so it is a
1731
+ plain `.map()`, over `__jxListItems(…)` when it filters or sorts and over `items` as written when
1732
+ it declares neither, which is every list compiled before either existed. */
1733
+ if (isRef(arrayDef.key)) {
1734
+ const pointer = arrayDef.key.$ref;
1735
+ const args = [
1736
+ itemsExpr,
1737
+ filterExpr,
1738
+ sortExpr,
1739
+ JSON.stringify(keyPath(pointer)),
1740
+ JSON.stringify(pointer),
1741
+ callback,
1742
+ ];
1743
+ return `${indent}\${${KEYED_LIST_HELPER}(${args.join(", ")})}`;
1744
+ }
1745
+ const listExpr = arranged
1746
+ ? `${LIST_ITEMS_HELPER}(${itemsExpr}, ${filterExpr}, ${sortExpr})`
1747
+ : itemsExpr;
1748
+ return `${indent}\${${listExpr}.map(${callback})}`;
1749
+ }
1750
+
1751
+ /**
1752
+ * An element's one `class` attribute for a lit template: the author's classes, then the style
1753
+ * handle (spec.md §9.2). `null` for an element with neither a handle nor a `className`, whose
1754
+ * `attributes.class` is then emitted by the attributes loop as it always was.
1755
+ *
1756
+ * @param {JxMutableNode | JxElement} def
1757
+ * @param {(template: string) => string} templ - Rewrites a string's `${…}` for the template
1758
+ * @param {(ref: string) => string} ref - Lowers a `$ref` to the expression that reads it
1759
+ * @returns {string | null}
1760
+ */
1761
+ function litClassAttr(
1762
+ def: JxMutableNode | JxElement,
1763
+ templ: (template: string) => string,
1764
+ ref: (pointer: string) => string,
1765
+ ): string | null {
1766
+ if (!writesMergedClass(def)) {
1767
+ return null;
1768
+ }
1769
+ const author = authorClassValue(def);
1770
+ let authorText = "";
1771
+ if (isRef(author)) {
1772
+ authorText = `\${${ref(author.$ref)} ?? ""}`;
1773
+ } else if (isString(author)) {
1774
+ authorText = templ(author);
1775
+ } else if (isNumber(author)) {
1776
+ authorText = String(author);
1777
+ }
1778
+ const handle = styleHandleOf(def) ?? "";
1779
+ return `class="${[authorText, handle].filter((token) => token !== "").join(" ")}"`;
1340
1780
  }
1341
1781
 
1342
1782
  /**
@@ -1356,7 +1796,8 @@ function isBoundRef(value: JxDocumentValue | undefined): value is JxRef {
1356
1796
  * @param {string} ref
1357
1797
  * @returns {string}
1358
1798
  */
1359
- function refToExpr(ref: string) {
1799
+ function refToExpr(written: string) {
1800
+ const ref = canonicalMapRef(written);
1360
1801
  if (ref.startsWith("#/state/")) {
1361
1802
  return refAccessor("s", ref.slice("#/state/".length));
1362
1803
  }
@@ -1396,7 +1837,8 @@ function mapVarAccessor(path: string) {
1396
1837
  * @param {string} ref
1397
1838
  * @returns {string}
1398
1839
  */
1399
- function mapRefToExpr(ref: string) {
1840
+ function mapRefToExpr(written: string) {
1841
+ const ref = canonicalMapRef(written);
1400
1842
  if (ref.startsWith("$map/")) {
1401
1843
  return mapVarAccessor(ref.slice("$map/".length));
1402
1844
  }
@@ -1443,6 +1885,166 @@ function toLitTextContent(value: string | null | JxRef) {
1443
1885
  return String(value);
1444
1886
  }
1445
1887
 
1888
+ /**
1889
+ * Whether any `${…}` hole of emitted lit template text names `state` on its own ({@link
1890
+ * readsBareState}). Only the holes are read: the word in a template's literal text is text.
1891
+ *
1892
+ * @param {string} text - Emitted template source
1893
+ * @returns {boolean}
1894
+ */
1895
+ function holesReadBareState(text: string): boolean {
1896
+ let depth = 0;
1897
+ let hole = "";
1898
+ for (let at = 0; at < text.length; at++) {
1899
+ const char = text.charAt(at);
1900
+ if (depth === 0) {
1901
+ if (char === "$" && text.charAt(at + 1) === "{") {
1902
+ depth = 1;
1903
+ hole = "";
1904
+ at += 1;
1905
+ }
1906
+ continue;
1907
+ }
1908
+ if (char === "{") {
1909
+ depth += 1;
1910
+ } else if (char === "}") {
1911
+ depth -= 1;
1912
+ if (depth === 0) {
1913
+ if (readsBareState(hole)) {
1914
+ return true;
1915
+ }
1916
+ continue;
1917
+ }
1918
+ }
1919
+ hole += char;
1920
+ }
1921
+ return false;
1922
+ }
1923
+
1924
+ /**
1925
+ * The arrow an `on*` value lowers to, in each of the spellings a handler has (spec.md §4.3), or
1926
+ * `null` for a value that is none of them. One lowering for every place a handler binds: a child's
1927
+ * `@event` binding, a map root's, and a listener on the host (spec.md §16.1), which says a root
1928
+ * handler attaches "exactly as they would to an element inside a document".
1929
+ *
1930
+ * @param {JxDocumentValue | undefined} val - The `on*` value as the document holds it
1931
+ * @param {string} mapCtx - The statement that publishes the iteration inside a map, or `""`
1932
+ * @returns {string | null}
1933
+ */
1934
+ function handlerSource(val: JxDocumentValue | undefined, mapCtx: string): string | null {
1935
+ if (isBoundRef(val)) {
1936
+ return mapCtx
1937
+ ? `(e) => { ${mapCtx}${refToExpr(val.$ref)}(s, e); }`
1938
+ : `(e) => ${refToExpr(val.$ref)}(s, e)`;
1939
+ }
1940
+ if (isNonNullObject(val) && "$expression" in val) {
1941
+ /* SAFETY: an `on*` binding object carrying `$expression` is a declarative handler, and the
1942
+ document schema types that member as an expression node (spec.md §19). It is passed on
1943
+ unvalidated, exactly as authored, so a malformed node fails inside compileExpression. */
1944
+ const compiled = compileExpression(val.$expression as JxExpressionNode, {
1945
+ eventParam: "e",
1946
+ statePrefix: "s",
1947
+ });
1948
+ return `(e) => { ${mapCtx}${compiled}; }`;
1949
+ }
1950
+ if (isFunctionDef(val)) {
1951
+ return `(e) => { ${mapCtx}${inlineHandlerBody(val)} }`;
1952
+ }
1953
+ return null;
1954
+ }
1955
+
1956
+ /**
1957
+ * A definition's root-level event handlers (spec.md §16.1), as the listeners the constructor
1958
+ * attaches to the host: every root key that passes the interpreter's test (`bindDefinitionHandlers`
1959
+ * in `@jxsuite/runtime`: it starts with `on` and is not reserved) and holds a handler.
1960
+ *
1961
+ * @param {JxDocument} doc
1962
+ * @returns {{ type: string; source: string }[]}
1963
+ */
1964
+ function hostHandlers(doc: JxDocument): { type: string; source: string }[] {
1965
+ const listeners: { type: string; source: string }[] = [];
1966
+ for (const [key, val] of Object.entries(doc)) {
1967
+ if (!key.startsWith("on") || RESERVED_KEYS.has(key)) {
1968
+ continue;
1969
+ }
1970
+ refuseBodyWithSrc(`root "${key}" handler`, val);
1971
+ const source = handlerSource(val, "");
1972
+ if (source !== null) {
1973
+ listeners.push({ source, type: key.slice(2).toLowerCase() });
1974
+ }
1975
+ }
1976
+ return listeners;
1977
+ }
1978
+
1979
+ /**
1980
+ * The statements that write a definition's root `attributes` on the host (spec.md §16.1), by the
1981
+ * rule the interpreter's `applyAttributes` applies to them: a value that resolves to nothing takes
1982
+ * the attribute off, a boolean is presence or text by its attribute's family (spec.md §8.3), and
1983
+ * anything else is its string form. A literal is written once, on the first connection; a `$ref` or
1984
+ * a template is an effect, registered with the element's others so it stops when the host leaves.
1985
+ *
1986
+ * In `connectedCallback` and never the constructor: a custom element constructor must not add
1987
+ * attributes, and the values read state the props merge has just filled.
1988
+ *
1989
+ * @param {JxDocument} doc
1990
+ * @returns {string[]} Lines for `connectedCallback`, at its indentation
1991
+ */
1992
+ function hostAttributeLines(doc: JxDocument): string[] {
1993
+ const lines: string[] = [];
1994
+ const write = (name: string, expr: string, namesState: boolean): string[] => [
1995
+ " this.#effects.push(effect(() => {",
1996
+ namesState ? " const s = this.state, state = s;" : " const s = this.state;",
1997
+ ` const _v = ${ATTR_HELPER}(${name}, ${expr});`,
1998
+ ` if (_v === null || _v === undefined) this.removeAttribute(${name});`,
1999
+ ` else this.setAttribute(${name}, String(_v));`,
2000
+ " }));",
2001
+ ];
2002
+ for (const [key, val] of Object.entries(doc.attributes ?? {})) {
2003
+ const name = JSON.stringify(key);
2004
+ if (isRef(val)) {
2005
+ lines.push(...write(name, refToExpr(val.$ref), false));
2006
+ } else if (isString(val) && isWholeTemplate(val)) {
2007
+ const template = toLitExpr(val);
2008
+ lines.push(...write(name, template.slice(2, -1), holesReadBareState(template)));
2009
+ } else if (isString(val) && val.includes("${")) {
2010
+ const template = toLitExpr(val);
2011
+ lines.push(...write(name, `\`${template}\``, holesReadBareState(template)));
2012
+ } else if (isBoolean(val)) {
2013
+ const text = booleanAttrValue(key, val);
2014
+ if (text !== null) {
2015
+ lines.push(` if (_first) this.setAttribute(${name}, ${JSON.stringify(text)});`);
2016
+ }
2017
+ } else if (isString(val) || isNumber(val)) {
2018
+ // A document is JSON, so anything else here (a `null`) names no attribute.
2019
+ lines.push(` if (_first) this.setAttribute(${name}, ${JSON.stringify(String(val))});`);
2020
+ }
2021
+ }
2022
+ return lines;
2023
+ }
2024
+
2025
+ /**
2026
+ * A definition's declared `formValue` (spec.md §16.11) as the source of the function the form
2027
+ * binding reads it through, or `null` when it declares none: a `$ref`, a `${…}` template, which
2028
+ * submits nothing while its expression throws, or a literal.
2029
+ *
2030
+ * @param {JxDocument["formValue"]} value
2031
+ * @returns {string}
2032
+ */
2033
+ function formValueSource(value: JxDocument["formValue"]): string {
2034
+ if (value === undefined) {
2035
+ return "null";
2036
+ }
2037
+ if (isRef(value)) {
2038
+ return `() => { const s = this.state; return ${refToExpr(value.$ref)}; }`;
2039
+ }
2040
+ if (isString(value) && value.includes("${")) {
2041
+ const template = toLitExpr(value);
2042
+ const expr = isWholeTemplate(value) ? template.slice(2, -1) : `\`${template}\``;
2043
+ return `() => { const s = this.state, state = s; try { return ${expr}; } catch { return null; } }`;
2044
+ }
2045
+ return `() => ${JSON.stringify(value)}`;
2046
+ }
2047
+
1446
2048
  /**
1447
2049
  * @param {import("@jxsuite/schema/types").JxFunctionDef} def
1448
2050
  * @returns {string}