@jxsuite/compiler 8.4.0 → 8.6.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.
@@ -11,9 +11,15 @@
11
11
  * state + computed signals), bind (DOM getters), on (event handlers), hydrate()
12
12
  */
13
13
 
14
+ import {
15
+ classifyFunctionEntries,
16
+ declaresParameters,
17
+ handlerParamNames,
18
+ } from "@jxsuite/schema/function-role";
14
19
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
15
20
  import {
16
21
  ATTR_HELPER,
22
+ refuseBodyWithSrc,
17
23
  attrHelperSource,
18
24
  booleanAttrValue,
19
25
  DEFAULT_LIT_HTML_SRC,
@@ -42,7 +48,6 @@ import {
42
48
  templateValueSource,
43
49
  } from "../shared.ts";
44
50
  import {
45
- bodyReturnsValue,
46
51
  hasStructuredBody,
47
52
  isBoolean,
48
53
  isExpandedSignal,
@@ -56,7 +61,6 @@ import {
56
61
  isServerFnDef,
57
62
  isString,
58
63
  isTagExpression,
59
- paramNames,
60
64
  tagNameCandidates,
61
65
  } from "@jxsuite/schema/guards";
62
66
  import type { CompileContext } from "../shared.ts";
@@ -87,7 +91,8 @@ type RepeaterSlot = Omit<JxMappedArray, "items"> & { items?: JxMappedArray["item
87
91
 
88
92
  /** A compiled event handler entry: parameter names + function body. */
89
93
  interface HandlerDef {
90
- args?: string[] | undefined;
94
+ /** The parameters the body is built with: `state` first, then the event under some name. */
95
+ args: string[];
91
96
  body?: string | undefined;
92
97
  }
93
98
 
@@ -132,6 +137,8 @@ export function compileClient(
132
137
  } = opts;
133
138
 
134
139
  const context = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {});
140
+ // One verdict per Function entry, from the document (spec.md §5.3 4b, 4d).
141
+ const roles = classifyFunctionEntries(raw);
135
142
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
136
143
 
137
144
  // Collectors for bindings and handlers
@@ -184,7 +191,6 @@ export function compileClient(
184
191
 
185
192
  // $prototype: "Function"
186
193
  if (isFunctionDef(def)) {
187
- const args = def.parameters ? paramNames(def.parameters) : def.arguments;
188
194
  const { body } = def;
189
195
  if (Array.isArray(body)) {
190
196
  // Structured body (spec §20) → an event handler compiled from statements.
@@ -205,14 +211,22 @@ export function compileClient(
205
211
  }
206
212
  names.add(srcImportBinding(key, def));
207
213
 
208
- // $src functions always produce computed entries (they return values)
209
- computedEntries.push([key, `() => { return ${key}(state); }`]);
210
- } else if (isString(body) && bodyReturnsValue(body)) {
214
+ if (roles.get(key) === "computed") {
215
+ // Only read, never called: its return value is what the page uses.
216
+ computedEntries.push([key, `() => { return ${key}(state); }`]);
217
+ } else {
218
+ /* Used as a callable: `state[key]` is the import, for a template or `call` site, and
219
+ `on[key]` adapts it for an event binding, which calls it `(state, event)` whatever it
220
+ declares (spec.md §4.3, §5.3 4d), as the interpreter does. */
221
+ initBlocks.push(`state[${JSON.stringify(key)}] = ${key};`);
222
+ onEntries.push([key, { args: ["state", "event"], body: `return ${key}(state, event);` }]);
223
+ }
224
+ } else if (isString(body) && roles.get(key) === "computed") {
211
225
  // Body contains return → computed
212
226
  computedEntries.push([key, `() => { ${body} }`]);
213
227
  } else {
214
228
  // No return → event handler
215
- onEntries.push([key, { args: args ?? ["state"], body }]);
229
+ onEntries.push([key, { args: handlerParamNames(def), body }]);
216
230
  }
217
231
  continue;
218
232
  }
@@ -428,6 +442,7 @@ function buildClientNode(
428
442
  if (!prop.startsWith("on") || prop === "observedAttributes") {
429
443
  continue;
430
444
  }
445
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
431
446
  const eventName = prop.slice(2).toLowerCase();
432
447
  if (isRefObject(val)) {
433
448
  const key = refToBindingKey(val.$ref);
@@ -447,9 +462,7 @@ function buildClientNode(
447
462
  body: compileStatements(body, { eventParam: "e", statePrefix: "state" }),
448
463
  }
449
464
  : {
450
- args: val.parameters
451
- ? paramNames(val.parameters)
452
- : (val.arguments ?? ["state", "event"]),
465
+ args: declaresParameters(val) ? handlerParamNames(val) : ["state", "event"],
453
466
  body,
454
467
  },
455
468
  );
@@ -760,6 +773,7 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
760
773
  if (!prop.startsWith("on") || prop === "observedAttributes") {
761
774
  continue;
762
775
  }
776
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
763
777
  const eventName = prop.slice(2).toLowerCase();
764
778
  if (isRefObject(val)) {
765
779
  const key = refToBindingKey(val.$ref);
@@ -773,8 +787,14 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
773
787
  * or absent. An absent one (a `$src` function) reaches replaceAll and throws, as it always
774
788
  * has: a repeater handler is emitted inline and needs inline source.
775
789
  */
776
- const body = mapRefsToLit(val.body as string);
777
- attrs += ` @${eventName}=\${(e) => { ${body} }}`;
790
+ const body = bareMapRefsToLit(val.body as string);
791
+ /* Published like the sibling branches, so a body reads `state.$map`; with a declaration the
792
+ body is built with the same list every tier uses and called `(state, e)`. The newline ends a
793
+ last-line comment before the brace does. */
794
+ const call = declaresParameters(val)
795
+ ? `((${handlerParamNames(val).join(", ")}) => { ${body}\n})(state, e);`
796
+ : `${body}\n`;
797
+ attrs += ` @${eventName}=\${(e) => { state.$map = { item, index }; ${call}}}`;
778
798
  } else if (isNonNullObject(val) && "$expression" in val) {
779
799
  /*
780
800
  * SAFETY: an `on*` member carrying `$expression` is a Shape 5 expression entry, whose
@@ -877,6 +897,17 @@ function mapRefsToLit(str: string) {
877
897
  return str.replaceAll("$map.", "");
878
898
  }
879
899
 
900
+ /**
901
+ * {@link mapRefsToLit} for a handler body, which also publishes `state.$map` before it runs: a bare
902
+ * `$map.item` becomes the callback's `item`, and a `state.$map.item` the author wrote is left to
903
+ * read the published context, rather than losing its `$map.` to `state.item`.
904
+ *
905
+ * @param body The handler body source.
906
+ */
907
+ function bareMapRefsToLit(body: string): string {
908
+ return body.replaceAll(/(?<![\w$.])\$map\./gu, "");
909
+ }
910
+
880
911
  // ─── JS module generation ─────────────────────────────────────────────────────
881
912
 
882
913
  /**
@@ -1002,12 +1033,9 @@ function emitClientModule(
1002
1033
  if (onEntries.length > 0) {
1003
1034
  lines.push("const on = {");
1004
1035
  for (const [key, def] of onEntries) {
1005
- const argNames = def.args ?? ["state"];
1006
- const callArgs = argNames.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
1036
+ // Every entry's list starts with `state`, and the event is the one argument after it.
1007
1037
  lines.push(
1008
- ` ${objectKey(key)}: (e) => { const fn = (${argNames.join(", ")}) => { ${def.body} }; fn(${
1009
- callArgs
1010
- }); },`,
1038
+ ` ${objectKey(key)}: (e) => { const fn = (${def.args.join(", ")}) => { ${def.body}\n}; fn(state, e); },`,
1011
1039
  );
1012
1040
  }
1013
1041
  lines.push("};");
@@ -5,6 +5,12 @@
5
5
  * state and lit-html for rendering.
6
6
  */
7
7
 
8
+ import { erasedDocument } from "../erased.ts";
9
+ import {
10
+ classifyFunctionEntries,
11
+ declaresParameters,
12
+ handlerParamNames,
13
+ } from "@jxsuite/schema/function-role";
8
14
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
9
15
  import {
10
16
  ATTR_HELPER,
@@ -21,11 +27,13 @@ import {
21
27
  compileOperandSource,
22
28
  compileStatements,
23
29
  emitFormulaFn,
30
+ refuseBodyWithSrc,
24
31
  emitRequestFetch,
25
32
  emitServerCall,
26
33
  escapeHtml,
27
34
  isMutating,
28
35
  isSchemaOnly,
36
+ rewriteState,
29
37
  serverCallHelperSource,
30
38
  srcExportName,
31
39
  srcImportBinding,
@@ -33,7 +41,6 @@ import {
33
41
  templateValueSource,
34
42
  } from "../shared.ts";
35
43
  import {
36
- bodyReturnsValue,
37
44
  hasStructuredBody,
38
45
  isExpressionDef,
39
46
  isBoolean,
@@ -47,7 +54,6 @@ import {
47
54
  isServerFnDef,
48
55
  isString,
49
56
  isTagExpression,
50
- paramNames,
51
57
  } from "@jxsuite/schema/guards";
52
58
  import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
53
59
  import { resolveShadowMode } from "../shadow.ts";
@@ -144,8 +150,10 @@ export async function compileElement(
144
150
  }
145
151
  doc = await entry.parseDocument(readFileSync(filePath, "utf8"));
146
152
  }
153
+ // Function bodies as JavaScript before anything analyses them (spec.md §23.1).
154
+ doc = erasedDocument(doc, filePath);
147
155
  } else {
148
- doc = srcPath;
156
+ doc = erasedDocument(srcPath, srcPath.tagName ?? "a component");
149
157
  filePath = null;
150
158
  if (doc.tagName && visited.has(doc.tagName)) {
151
159
  return;
@@ -303,75 +311,6 @@ function extractInitialValue(def: JxStateDefinition) {
303
311
  return JSON.stringify(def);
304
312
  }
305
313
 
306
- /** Lifecycle hooks the generated element calls itself, so they are never `$ref`'d (spec.md §16.4). */
307
- const LIFECYCLE_KEYS = new Set(["onMount", "onUnmount", "onAdopted"]);
308
-
309
- /**
310
- * Collect the state keys a document uses as a _callable_, at any depth: bound to an `on*` event,
311
- * invoked by an `$expression` `call` node, or called as `state.key(…)` from a template string or
312
- * another function's body.
313
- *
314
- * A bodyless `$src` Function carries no body to classify by, and unlike the interpreter — which
315
- * introspects the imported function — a compiler only has the document to go on. Anything not used
316
- * as a callable has its return value read reactively, and so becomes a computed (spec.md §5.3 4b).
317
- * Defaulting the other way round would turn a called helper into a value and break its call site.
318
- *
319
- * @param {JxDocument} doc
320
- * @returns {Set<string>}
321
- */
322
- function collectCallableRefs(doc: JxDocument) {
323
- const keys = new Set<string>();
324
- const seen = new Set<object>();
325
-
326
- const addStateRef = (ref: string) => {
327
- if (ref.startsWith("#/state/")) {
328
- /* SAFETY: `String.prototype.split` always returns at least one element (the whole string
329
- when the separator is absent), so index 0 is present. */
330
- keys.add(ref.slice("#/state/".length).split("/")[0] as string);
331
- }
332
- };
333
-
334
- const visit = (node: JxDocumentValue | undefined) => {
335
- if (isString(node)) {
336
- // `${state.formatDate(d)}` in a template, or `state.helper(x)` in another function's body.
337
- for (const call of node.matchAll(/\bstate\.([A-Za-z_$][\w$]*)\s*\(/g)) {
338
- /* SAFETY: the pattern's one capture group is not optional, so every match fills
339
- index 1 with the called member's name. */
340
- keys.add(call[1] as string);
341
- }
342
- return;
343
- }
344
- if (!isNonNullObject(node) || seen.has(node)) {
345
- return;
346
- }
347
- seen.add(node);
348
- if (Array.isArray(node)) {
349
- for (const item of node) {
350
- visit(item);
351
- }
352
- return;
353
- }
354
- /* SAFETY: `node` is a non-null, non-array object reached from `doc.children` or `doc.state`,
355
- and every such object in a parsed Jx document is a JSON object whose members are document
356
- values; the view only reads members, and each is checked before use. */
357
- const record = node as Readonly<Record<string, JxDocumentValue | undefined>>;
358
- // An `$expression` `call` node names its callee in `target` (spec.md §19.4c).
359
- if (record.operator === "call" && isRef(record.target)) {
360
- addStateRef(record.target.$ref);
361
- }
362
- for (const [key, val] of Object.entries(record)) {
363
- if (key.startsWith("on") && key !== "observedAttributes" && isRef(val)) {
364
- addStateRef(val.$ref);
365
- }
366
- visit(val);
367
- }
368
- };
369
-
370
- visit(doc.children);
371
- visit(doc.state);
372
- return keys;
373
- }
374
-
375
314
  /**
376
315
  * Generate a complete ES module string for a custom element.
377
316
  *
@@ -403,8 +342,9 @@ export function emitElementModule(
403
342
  /** `$lazy` `$src` modules → the (export, local binding) pairs each one supplies. */
404
343
  const lazySrcMap = new Map<string, { binding: string; exportName: string }[]>();
405
344
  const defs = doc.state ?? {};
406
- const callableRefs = collectCallableRefs(doc);
345
+ const roles = classifyFunctionEntries(doc);
407
346
  for (const [key, def] of Object.entries(defs)) {
347
+ refuseBodyWithSrc(`state entry "${key}"`, def);
408
348
  if (isFunctionDef(def) && def.$src) {
409
349
  const srcPath = def.$src;
410
350
  if (def.$lazy === true) {
@@ -413,7 +353,7 @@ export function emitElementModule(
413
353
  * promise. Silently producing `computed(() => Promise)` would render "[object Promise]" in
414
354
  * whatever the template bound it to, so this is a build error rather than a surprise.
415
355
  */
416
- if (!callableRefs.has(key) && !LIFECYCLE_KEYS.has(key)) {
356
+ if (roles.get(key) === "computed") {
417
357
  throw new Error(
418
358
  `"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
419
359
  `A lazily loaded function resolves to a promise; a computed must resolve now. ` +
@@ -529,20 +469,7 @@ export function emitElementModule(
529
469
  computedEntries.push([key, def]);
530
470
  }
531
471
  } else if (isFunctionDef(def)) {
532
- if (def.$src && !isString(def.body)) {
533
- // Bodyless `$src` entry — classify by document usage, not by an absent body. `body` and
534
- // `$src` are mutually exclusive (spec.md §5.3 4d), so this is the only shape a
535
- // Spec-conformant external Function takes.
536
- if (callableRefs.has(key) || LIFECYCLE_KEYS.has(key)) {
537
- functionEntries.push([key, def]);
538
- } else {
539
- computedEntries.push([key, def]);
540
- }
541
- } else if (isString(def.body) && bodyReturnsValue(def.body)) {
542
- computedEntries.push([key, def]);
543
- } else {
544
- functionEntries.push([key, def]);
545
- }
472
+ (roles.get(key) === "computed" ? computedEntries : functionEntries).push([key, def]);
546
473
  } else if (isString(def) && def.includes("${")) {
547
474
  /* A TEMPLATE STRING IS A COMPUTED, and the runtime has always said so — `runtime.ts`'s
548
475
  second state pass is `if (typeof def === "string" && def.includes("${")) state[key] =
@@ -603,45 +530,20 @@ export function emitElementModule(
603
530
  " };",
604
531
  );
605
532
  } else {
606
- const args = def.parameters ? paramNames(def.parameters) : (def.arguments ?? ["state"]);
607
- const paramList = args.join(", ");
608
- const body = isString(def.body) ? def.body : "";
609
- // Every call site invokes a state function as `(state, event)` — the template's
610
- // `s.fn(s, e)`, `onMount`, `onUnmount`. Declared names that already start with `state` line
611
- // Up positionally, so they are emitted directly. Any other declaration — including the
612
- // `"parameters": ["event"]` form that examples/components/{todo-app,fetch-demo}.json use — is
613
- // Mapped onto the arguments by name, the way the client target does it
614
- // (compile-client.ts), with `state` bound as the outer parameter so a body referencing bare
615
- // `state` resolves regardless of the declared arity.
616
- if (args[0] === "state") {
617
- if (def.$src) {
618
- // $src function — wrap imported function so it receives state
619
- lines.push(
620
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => ${key}(${paramList});`,
621
- );
622
- } else {
623
- lines.push(
624
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => {`,
625
- ` ${body}`,
626
- " };",
627
- );
628
- }
533
+ /* One calling convention (spec.md §4.3, §5.3 4d): every event site and lifecycle call invokes
534
+ `s.fn(s, e)`, so a string body is built with `state` first and its other declared names after
535
+ it, which binds `state` by name and the event by position. A `$src` entry is its import,
536
+ called as its call site calls it. Nothing here maps a name onto an argument. */
537
+ const target = refAccessor("this.state", escapeToken(key));
538
+ if (def.$src) {
539
+ lines.push(` ${target} = ${key};`);
629
540
  } else {
630
- const callArgs = args.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
631
- if (def.$src) {
632
- lines.push(
633
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => ${key}(${callArgs});`,
634
- );
635
- } else {
636
- lines.push(
637
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => {`,
638
- ` const _fn = (${paramList}) => {`,
639
- ` ${body}`,
640
- " };",
641
- ` return _fn(${callArgs});`,
642
- " };",
643
- );
644
- }
541
+ const body = isString(def.body) ? def.body : "";
542
+ lines.push(
543
+ ` ${target} = (${handlerParamNames(def).join(", ")}) => {`,
544
+ ` ${body}`,
545
+ " };",
546
+ );
645
547
  }
646
548
  }
647
549
  }
@@ -665,7 +567,7 @@ export function emitElementModule(
665
567
  for (const [key, template] of templateEntries) {
666
568
  lines.push(
667
569
  "",
668
- ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${templateValueSource(template.replaceAll("state.", "this.state."))});`,
570
+ ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${templateValueSource(rewriteState(template, "this.state", { code: false }))});`,
669
571
  );
670
572
  }
671
573
 
@@ -686,7 +588,7 @@ export function emitElementModule(
686
588
  );
687
589
  } else {
688
590
  lines.push(` ${refAccessor("this.state", escapeToken(key))} = computed(() => {`);
689
- const body = (isString(def.body) ? def.body : "").replaceAll("state.", "this.state.");
591
+ const body = rewriteState(isString(def.body) ? def.body : "", "this.state");
690
592
  lines.push(` ${body}`, " });");
691
593
  }
692
594
  }
@@ -839,7 +741,7 @@ export function emitElementModule(
839
741
  for (const [cssProp, value] of dynamicStyles) {
840
742
  const expr = value.replaceAll(
841
743
  /\$\{([^}]+)\}/g,
842
- (_: string, e: string) => `\${${e.replaceAll("state.", "this.state.")}}`,
744
+ (_: string, e: string) => `\${${rewriteState(e, "this.state")}}`,
843
745
  );
844
746
  lines.push(` this.style['${cssProp}'] = \`${expr}\`;`);
845
747
  }
@@ -1209,6 +1111,7 @@ ${no}
1209
1111
  if (!key.startsWith("on") || key === "observedAttributes") {
1210
1112
  continue;
1211
1113
  }
1114
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1212
1115
  const eventName = key.slice(2).toLowerCase();
1213
1116
  if (isBoundRef(val)) {
1214
1117
  parts.push(
@@ -1408,6 +1311,7 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1408
1311
  if (!key.startsWith("on")) {
1409
1312
  continue;
1410
1313
  }
1314
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1411
1315
  const eventName = key.slice(2).toLowerCase();
1412
1316
  if (isRef(val)) {
1413
1317
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${refToExpr(val.$ref)}(s, e); }}"`);
@@ -1417,6 +1321,9 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1417
1321
  statePrefix: "s",
1418
1322
  });
1419
1323
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${compiled}; }}"`);
1324
+ } else if (isFunctionDef(val)) {
1325
+ // A map root binds an inline handler as any other element does, with the iteration published.
1326
+ parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${inlineHandlerBody(val)} }}"`);
1420
1327
  }
1421
1328
  }
1422
1329
 
@@ -1521,7 +1428,7 @@ function mapRefToExpr(ref: string) {
1521
1428
  * @returns {string}
1522
1429
  */
1523
1430
  function toLitExpr(str: string) {
1524
- return str.replaceAll("state.", "s.");
1431
+ return rewriteState(str, "s", { code: false });
1525
1432
  }
1526
1433
 
1527
1434
  /**
@@ -1569,16 +1476,14 @@ function inlineHandlerBody(def: JxFunctionDef) {
1569
1476
  });
1570
1477
  }
1571
1478
  const body = isString(def.body) ? def.body : "";
1572
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
1573
- if (declared.length > 0) {
1574
- // The call site supplies only `(e)`, so map the declared names onto the arguments the handler
1575
- // Actually has — `state` to the `s` alias, anything else to the event. Binding by name means the
1576
- // Body needs no textual rewriting, and a declared `event` stops silently resolving to the
1577
- // Deprecated `window.event` global (any other declared name threw ReferenceError outright).
1578
- const args = declared.map((name: string) => (name === "state" ? "s" : "e")).join(", ");
1579
- return `((${declared.join(", ")}) => { ${body} })(${args});`;
1580
- }
1581
- return body.replaceAll(/(?<!this\.)state\./g, "s.").replaceAll(/(?<!this\.)state(?!\.)/g, "s");
1479
+ if (declaresParameters(def)) {
1480
+ /* The same list every tier builds a body with, called `(s, e)` like any other handler: `state`
1481
+ binds by name, the first other declared name is the event, and a declared `event` stops
1482
+ silently resolving to the deprecated `window.event` global. The newline ends a last-line
1483
+ comment before the brace does. */
1484
+ return `((${handlerParamNames(def).join(", ")}) => { ${body}\n})(s, e);`;
1485
+ }
1486
+ return `${rewriteState(body, "s", { bare: true })}\n`;
1582
1487
  }
1583
1488
 
1584
1489
  /**