@jxsuite/compiler 8.5.0 → 8.7.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.
@@ -28,6 +28,7 @@ import { generateClassSchema } from "@jxsuite/schema";
28
28
  import { validateProjectFile } from "@jxsuite/schema/validate-project";
29
29
  import { findA11yDefects } from "@jxsuite/schema/a11y";
30
30
  import { findDialogDefects } from "@jxsuite/schema/dialogs";
31
+ import { findScriptAdvice } from "@jxsuite/schema/document-scripts";
31
32
  import { findPopoverDefects, overlayScopeFor } from "@jxsuite/schema/overlays";
32
33
  import type { OverlayScope } from "@jxsuite/schema/overlays";
33
34
  import { isJsonObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
@@ -68,14 +69,19 @@ export interface ProjectTreeLintFinding {
68
69
  /** The node's path inside the document. */
69
70
  path: (string | number)[];
70
71
  /**
71
- * Which lint: `popover`, `dialog`, `accessibility`, `notation` for a `.jxn` file's text, or
72
- * `function-body` for a body whose meaning reading it as TypeScript changes (`spec.md` §23.1).
72
+ * Which lint: `popover`, `dialog`, `accessibility`, `notation` for a `.jxn` file's text,
73
+ * `function-body` for a body whose meaning reading it as TypeScript changes (`spec.md` §23.1), or
74
+ * `module` for advice about how a document names its modules (`spec.md` §23.2).
73
75
  */
74
- source: "popover" | "dialog" | "accessibility" | "notation" | "function-body";
76
+ source: "popover" | "dialog" | "accessibility" | "notation" | "function-body" | "module";
75
77
  rule: string;
76
78
  message: string;
77
79
  detail: string;
78
- severity: "error" | "warn";
80
+ /**
81
+ * `error` is certainly broken and `warn` very probably not what was meant. `info` is advice about
82
+ * a document that is right as it stands, and no option makes it fail a tree.
83
+ */
84
+ severity: "error" | "warn" | "info";
79
85
  /** The WCAG success criterion, for accessibility findings. */
80
86
  criterion?: string;
81
87
  }
@@ -374,7 +380,7 @@ function readJson(path: string): JsonValue {
374
380
  return JSON.parse(readFileSync(path, "utf8"));
375
381
  }
376
382
 
377
- /** The three lints over one document, as findings that name their file. */
383
+ /** The lints over one document, and the advice about its modules, as findings that name their file. */
378
384
  function lintDocument(doc: JxElement, file: string, scope: OverlayScope): ProjectTreeLintFinding[] {
379
385
  const findings: ProjectTreeLintFinding[] = [];
380
386
  for (const defect of findPopoverDefects(doc, scope)) {
@@ -386,6 +392,9 @@ function lintDocument(doc: JxElement, file: string, scope: OverlayScope): Projec
386
392
  for (const defect of findA11yDefects(doc)) {
387
393
  findings.push({ ...pick(defect), criterion: defect.criterion, file, source: "accessibility" });
388
394
  }
395
+ for (const advice of findScriptAdvice(doc)) {
396
+ findings.push({ ...pick({ ...advice, severity: "info" }), file, source: "module" });
397
+ }
389
398
  return findings;
390
399
  }
391
400
 
@@ -395,7 +404,7 @@ function pick(defect: {
395
404
  path: (string | number)[];
396
405
  message: string;
397
406
  detail: string;
398
- severity: "error" | "warn";
407
+ severity: "error" | "warn" | "info";
399
408
  }): Pick<ProjectTreeLintFinding, "rule" | "path" | "message" | "detail" | "severity"> {
400
409
  return {
401
410
  detail: defect.detail,
@@ -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,
@@ -38,11 +44,11 @@ import {
38
44
  pureSchemeOf,
39
45
  resolveStaticValue,
40
46
  serverCallHelperSource,
41
- srcImportBinding,
47
+ collectFunctionImports,
48
+ emitSrcImports,
42
49
  templateValueSource,
43
50
  } from "../shared.ts";
44
51
  import {
45
- bodyReturnsValue,
46
52
  hasStructuredBody,
47
53
  isBoolean,
48
54
  isExpandedSignal,
@@ -56,10 +62,9 @@ import {
56
62
  isServerFnDef,
57
63
  isString,
58
64
  isTagExpression,
59
- paramNames,
60
65
  tagNameCandidates,
61
66
  } from "@jxsuite/schema/guards";
62
- import type { CompileContext } from "../shared.ts";
67
+ import type { CompileContext, SrcImports } from "../shared.ts";
63
68
  import {
64
69
  escapeToken,
65
70
  objectKey,
@@ -87,7 +92,8 @@ type RepeaterSlot = Omit<JxMappedArray, "items"> & { items?: JxMappedArray["item
87
92
 
88
93
  /** A compiled event handler entry: parameter names + function body. */
89
94
  interface HandlerDef {
90
- args?: string[] | undefined;
95
+ /** The parameters the body is built with: `state` first, then the event under some name. */
96
+ args: string[];
91
97
  body?: string | undefined;
92
98
  }
93
99
 
@@ -132,6 +138,8 @@ export function compileClient(
132
138
  } = opts;
133
139
 
134
140
  const context = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {});
141
+ // One verdict per Function entry, from the document (spec.md §5.3 4b, 4d).
142
+ const roles = classifyFunctionEntries(raw);
135
143
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
136
144
 
137
145
  // Collectors for bindings and handlers
@@ -147,9 +155,6 @@ export function compileClient(
147
155
  const initBlocks: string[] = []; // Lines emitted after state for prototype init
148
156
  const serverCalls: string[] = []; // One block per `timing: "server"` entry, after the computed block
149
157
 
150
- // Map $src path → Set of function names to import
151
- const srcImportMap = new Map<string, Set<string>>();
152
-
153
158
  const defs = raw.state ?? {};
154
159
  for (const [key, def] of Object.entries(defs)) {
155
160
  if (!isNonNullObject(def) || Array.isArray(def)) {
@@ -184,7 +189,6 @@ export function compileClient(
184
189
 
185
190
  // $prototype: "Function"
186
191
  if (isFunctionDef(def)) {
187
- const args = def.parameters ? paramNames(def.parameters) : def.arguments;
188
192
  const { body } = def;
189
193
  if (Array.isArray(body)) {
190
194
  // Structured body (spec §20) → an event handler compiled from statements.
@@ -198,21 +202,22 @@ export function compileClient(
198
202
  onEntries.push([key, { args: ["state", "e"], body: compiled }]);
199
203
  }
200
204
  } else if (def.$src) {
201
- let names = srcImportMap.get(def.$src);
202
- if (!names) {
203
- names = new Set();
204
- srcImportMap.set(def.$src, names);
205
+ if (roles.get(key) === "computed") {
206
+ // Only read, never called: its return value is what the page uses.
207
+ computedEntries.push([key, `() => { return ${key}(state); }`]);
208
+ } else {
209
+ /* Used as a callable: `state[key]` is the import, for a template or `call` site, and
210
+ `on[key]` adapts it for an event binding, which calls it `(state, event)` whatever it
211
+ declares (spec.md §4.3, §5.3 4d), as the interpreter does. */
212
+ initBlocks.push(`state[${JSON.stringify(key)}] = ${key};`);
213
+ onEntries.push([key, { args: ["state", "event"], body: `return ${key}(state, event);` }]);
205
214
  }
206
- names.add(srcImportBinding(key, def));
207
-
208
- // $src functions always produce computed entries (they return values)
209
- computedEntries.push([key, `() => { return ${key}(state); }`]);
210
- } else if (isString(body) && bodyReturnsValue(body)) {
215
+ } else if (isString(body) && roles.get(key) === "computed") {
211
216
  // Body contains return → computed
212
217
  computedEntries.push([key, `() => { ${body} }`]);
213
218
  } else {
214
219
  // No return → event handler
215
- onEntries.push([key, { args: args ?? ["state"], body }]);
220
+ onEntries.push([key, { args: handlerParamNames(def), body }]);
216
221
  }
217
222
  continue;
218
223
  }
@@ -286,6 +291,7 @@ export function compileClient(
286
291
  }
287
292
 
288
293
  // Generate the JS module
294
+ const srcImports = collectFunctionImports(defs, roles);
289
295
  const moduleContent = emitClientModule(
290
296
  stateEntries,
291
297
  computedEntries,
@@ -293,7 +299,7 @@ export function compileClient(
293
299
  onEntries,
294
300
  initBlocks,
295
301
  serverCalls,
296
- srcImportMap,
302
+ srcImports,
297
303
  counter,
298
304
  reactivitySrc,
299
305
  opts.rewriteSrc,
@@ -428,6 +434,7 @@ function buildClientNode(
428
434
  if (!prop.startsWith("on") || prop === "observedAttributes") {
429
435
  continue;
430
436
  }
437
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
431
438
  const eventName = prop.slice(2).toLowerCase();
432
439
  if (isRefObject(val)) {
433
440
  const key = refToBindingKey(val.$ref);
@@ -447,9 +454,7 @@ function buildClientNode(
447
454
  body: compileStatements(body, { eventParam: "e", statePrefix: "state" }),
448
455
  }
449
456
  : {
450
- args: val.parameters
451
- ? paramNames(val.parameters)
452
- : (val.arguments ?? ["state", "event"]),
457
+ args: declaresParameters(val) ? handlerParamNames(val) : ["state", "event"],
453
458
  body,
454
459
  },
455
460
  );
@@ -760,6 +765,7 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
760
765
  if (!prop.startsWith("on") || prop === "observedAttributes") {
761
766
  continue;
762
767
  }
768
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
763
769
  const eventName = prop.slice(2).toLowerCase();
764
770
  if (isRefObject(val)) {
765
771
  const key = refToBindingKey(val.$ref);
@@ -773,9 +779,14 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
773
779
  * or absent. An absent one (a `$src` function) reaches replaceAll and throws, as it always
774
780
  * has: a repeater handler is emitted inline and needs inline source.
775
781
  */
776
- const body = mapRefsToLit(val.body as string);
777
- // The newline ends a last-line comment before the brace does.
778
- attrs += ` @${eventName}=\${(e) => { ${body}\n}}`;
782
+ const body = bareMapRefsToLit(val.body as string);
783
+ /* Published like the sibling branches, so a body reads `state.$map`; with a declaration the
784
+ body is built with the same list every tier uses and called `(state, e)`. The newline ends a
785
+ last-line comment before the brace does. */
786
+ const call = declaresParameters(val)
787
+ ? `((${handlerParamNames(val).join(", ")}) => { ${body}\n})(state, e);`
788
+ : `${body}\n`;
789
+ attrs += ` @${eventName}=\${(e) => { state.$map = { item, index }; ${call}}}`;
779
790
  } else if (isNonNullObject(val) && "$expression" in val) {
780
791
  /*
781
792
  * SAFETY: an `on*` member carrying `$expression` is a Shape 5 expression entry, whose
@@ -878,6 +889,17 @@ function mapRefsToLit(str: string) {
878
889
  return str.replaceAll("$map.", "");
879
890
  }
880
891
 
892
+ /**
893
+ * {@link mapRefsToLit} for a handler body, which also publishes `state.$map` before it runs: a bare
894
+ * `$map.item` becomes the callback's `item`, and a `state.$map.item` the author wrote is left to
895
+ * read the published context, rather than losing its `$map.` to `state.item`.
896
+ *
897
+ * @param body The handler body source.
898
+ */
899
+ function bareMapRefsToLit(body: string): string {
900
+ return body.replaceAll(/(?<![\w$.])\$map\./gu, "");
901
+ }
902
+
881
903
  // ─── JS module generation ─────────────────────────────────────────────────────
882
904
 
883
905
  /**
@@ -887,7 +909,7 @@ function mapRefsToLit(str: string) {
887
909
  * @param {[string, any][]} onEntries
888
910
  * @param {string[]} initBlocks
889
911
  * @param {string[]} serverCalls
890
- * @param {Map<string, Set<string>>} srcImportMap
912
+ * @param {SrcImports} srcImports
891
913
  * @param {{
892
914
  * t: number;
893
915
  * s: number;
@@ -907,7 +929,7 @@ function emitClientModule(
907
929
  onEntries: [string, HandlerDef][],
908
930
  initBlocks: string[],
909
931
  serverCalls: string[],
910
- srcImportMap: Map<string, Set<string>>,
932
+ srcImports: SrcImports,
911
933
  counter: {
912
934
  t: number;
913
935
  s: number;
@@ -940,15 +962,12 @@ function emitClientModule(
940
962
 
941
963
  // $src imports — bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/
942
964
  // Bundle URL; the site build bundles them after all documents compile (spec.md §12).
943
- for (const [src, names] of srcImportMap) {
944
- const importPath = rewriteSrc ? rewriteSrc(src) : src;
945
- lines.push(`import { ${[...names].join(", ")} } from '${importPath}';`);
946
- }
965
+ const src = emitSrcImports(srcImports, rewriteSrc);
947
966
 
948
967
  // State — reactive state
949
968
  /* The boolean-attribute rule, inlined because this module loads with `@vue/reactivity` and
950
969
  nothing else — see `attrHelperSource`. The hydration script below is its only caller. */
951
- lines.push("", attrHelperSource());
970
+ lines.push(...src.imports, ...src.loaders, "", attrHelperSource());
952
971
  if (serverCalls.length > 0) {
953
972
  lines.push("", serverCallHelperSource());
954
973
  }
@@ -1003,12 +1022,9 @@ function emitClientModule(
1003
1022
  if (onEntries.length > 0) {
1004
1023
  lines.push("const on = {");
1005
1024
  for (const [key, def] of onEntries) {
1006
- const argNames = def.args ?? ["state"];
1007
- const callArgs = argNames.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
1025
+ // Every entry's list starts with `state`, and the event is the one argument after it.
1008
1026
  lines.push(
1009
- ` ${objectKey(key)}: (e) => { const fn = (${argNames.join(", ")}) => { ${def.body}\n}; fn(${
1010
- callArgs
1011
- }); },`,
1027
+ ` ${objectKey(key)}: (e) => { const fn = (${def.args.join(", ")}) => { ${def.body}\n}; fn(state, e); },`,
1012
1028
  );
1013
1029
  }
1014
1030
  lines.push("};");