@jxsuite/compiler 11.1.2 → 11.2.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.
@@ -9,11 +9,14 @@
9
9
  * compile those documents;
10
10
  * 2. `project.json` against the generated entry schema (validateProjectFile), and every
11
11
  * `#/$defs/<Name>` type reference in its own `$defs` against those definitions alone
12
- * (site-architecture.md §3.1);
12
+ * (site-architecture.md §3.1), and its `state` for a named formula that reaches itself, and
13
+ * against the expression rules (spec.md §19.3 to §19.5);
13
14
  * 3. Every document under `components/`, `pages/`, and `layouts/` against the bundled document schema
14
15
  * (core + extension `$paths` union — the same schema the studio consumes), and every type
15
16
  * reference a well-formed one carries against its own `$defs` and then the project's
16
- * (site-architecture.md §3.1);
17
+ * (site-architecture.md §3.1), and that no named formula reaches itself through `call` (spec.md
18
+ * §19.4c), a page judged together with `project.json`'s `state` as the build merges them, and
19
+ * that none breaks an expression rule (spec.md §19.3 to §19.5);
17
20
  * 4. Every project-local `*.class.json` against the generated class schema;
18
21
  * 5. Every enabled extension's schema fragments compile standalone against the shipped default union
19
22
  * resources.
@@ -23,7 +26,9 @@
23
26
 
24
27
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
25
28
  import { isJxnPath, isNativeDocumentPath, lintJxn, parseJxn } from "@jxsuite/schema/jxn";
26
- import { errorMessage } from "@jxsuite/schema/parse";
29
+ import { errorMessage, parseClassDef, parseJson, parseJxDocument } from "@jxsuite/schema/parse";
30
+ import { findCallCycles } from "@jxsuite/runtime/expression";
31
+ import { callCycleMessage } from "../shared.ts";
27
32
  import { eraseDocument } from "@jxsuite/erase";
28
33
  import type { EraseWarning } from "@jxsuite/erase";
29
34
  import { createRequire } from "node:module";
@@ -37,11 +42,20 @@ import {
37
42
  import { validateProjectFile } from "@jxsuite/schema/validate-project";
38
43
  import { findA11yDefects } from "@jxsuite/schema/a11y";
39
44
  import { findDialogDefects } from "@jxsuite/schema/dialogs";
45
+ import { findTagExpressionDefects } from "@jxsuite/schema/tag-expressions";
46
+ import { findExpressionDefects } from "@jxsuite/schema/expressions";
47
+ import type { ExpressionSource } from "@jxsuite/schema/expressions";
40
48
  import { findScriptAdvice } from "@jxsuite/schema/document-scripts";
41
49
  import { findPopoverDefects, overlayScopeFor } from "@jxsuite/schema/overlays";
42
50
  import type { OverlayScope } from "@jxsuite/schema/overlays";
43
51
  import { isJsonObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
44
- import type { JsonObject, JsonValue, JxElement } from "@jxsuite/schema/types";
52
+ import type {
53
+ JsonObject,
54
+ JsonValue,
55
+ JxElement,
56
+ JxStateDefinition,
57
+ ProjectConfig,
58
+ } from "@jxsuite/schema/types";
45
59
  import { buildProjectExtensionRegistry } from "./format-host.ts";
46
60
  import { loadProjectConfig } from "./site-loader.ts";
47
61
  import { readBundledProjectSchemas } from "./schema-command.ts";
@@ -78,11 +92,19 @@ export interface ProjectTreeLintFinding {
78
92
  /** The node's path inside the document. */
79
93
  path: (string | number)[];
80
94
  /**
81
- * Which lint: `popover`, `dialog`, `accessibility`, `notation` for a `.jxn` file's text,
82
- * `function-body` for a body whose meaning reading it as TypeScript changes (`spec.md` §23.1), or
83
- * `module` for advice about how a document names its modules (`spec.md` §23.2).
95
+ * Which lint: `popover`, `dialog`, `accessibility`, `expression` for a chosen tag the document
96
+ * writes (`spec.md` §19.6), `notation` for a `.jxn` file's text, `function-body` for a body whose
97
+ * meaning reading it as TypeScript changes (`spec.md` §23.1), or `module` for advice about how a
98
+ * document names its modules (`spec.md` §23.2).
84
99
  */
85
- source: "popover" | "dialog" | "accessibility" | "notation" | "function-body" | "module";
100
+ source:
101
+ | "popover"
102
+ | "dialog"
103
+ | "accessibility"
104
+ | "expression"
105
+ | "notation"
106
+ | "function-body"
107
+ | "module";
86
108
  rule: string;
87
109
  message: string;
88
110
  detail: string;
@@ -217,6 +239,27 @@ export async function validateProjectTree(
217
239
  }
218
240
  }
219
241
 
242
+ const projectFile = readProjectFile(root);
243
+ const projectState = projectFile?.state ?? {};
244
+ if (projectFile !== undefined) {
245
+ const projectRules = expressionErrors(projectFile);
246
+ if (projectRules.length > 0) {
247
+ const reported = issues.find((issue) => issue.file === projectResult.file);
248
+ if (reported === undefined) {
249
+ issues.push({ errors: projectRules, file: projectResult.file });
250
+ } else {
251
+ reported.errors.unshift(...projectRules);
252
+ }
253
+ }
254
+ }
255
+ const projectCycles = findCallCycles(projectState).map((cycle) => ({
256
+ instancePath: `/state/${cycle[0]}`,
257
+ message: callCycleMessage(cycle),
258
+ }));
259
+ if (projectCycles.length > 0) {
260
+ issues.push({ errors: projectCycles, file: projectResult.file });
261
+ }
262
+
220
263
  const { addFormats, Ajv } = await loadAjv();
221
264
 
222
265
  // 3. Documents against the bundled document schema (the same schema the studio consumes).
@@ -238,7 +281,14 @@ export async function validateProjectTree(
238
281
  * reads `tagName` through isString (a primitive or array has none, so it is skipped), and
239
282
  * reads `observedAttributes` through Array.isArray.
240
283
  */
241
- return [JSON.parse(readFileSync(file, "utf8")) as JxElement];
284
+ return [
285
+ // SAFETY: a class definition is an object, and the scope reads it as the element it renders.
286
+ parseJson(
287
+ readFileSync(file, "utf8"),
288
+ relative(root, file),
289
+ "class definition",
290
+ ) as JxElement,
291
+ ];
242
292
  } catch {
243
293
  // A malformed definition is reported by the class-schema pass below, not here.
244
294
  return [];
@@ -264,7 +314,11 @@ export async function validateProjectTree(
264
314
  issues.push(bodies.failure);
265
315
  continue;
266
316
  }
317
+ const rules = expressionErrors(doc);
267
318
  if (validateDoc(doc)) {
319
+ if (rules.length > 0) {
320
+ issues.push({ errors: rules, file: relative(root, file) });
321
+ }
268
322
  /*
269
323
  * Only a well-formed document is judged; a schema error is the report for the rest.
270
324
  * SAFETY: validateDoc just accepted `doc` against the bundled document schema, which is
@@ -272,6 +326,16 @@ export async function validateProjectTree(
272
326
  */
273
327
  const wellFormed = doc as JxElement;
274
328
  lint.push(...lintDocument(wellFormed, relative(root, file), scope));
329
+ const cycles = documentCallCycles(wellFormed, dir === "pages", projectState);
330
+ if (cycles.length > 0) {
331
+ issues.push({
332
+ errors: cycles.map((cycle) => ({
333
+ instancePath: `/state/${cycle[0]}`,
334
+ message: callCycleMessage(cycle),
335
+ })),
336
+ file: relative(root, file),
337
+ });
338
+ }
275
339
  const dangling = findDanglingTypeRefs(wellFormed, projectDefs);
276
340
  if (dangling.length > 0) {
277
341
  issues.push({
@@ -283,7 +347,10 @@ export async function validateProjectTree(
283
347
  });
284
348
  }
285
349
  } else {
286
- issues.push({ errors: validateDoc.errors ?? [], file: relative(root, file) });
350
+ issues.push({
351
+ errors: [...rules, ...(validateDoc.errors ?? [])],
352
+ file: relative(root, file),
353
+ });
287
354
  }
288
355
  }
289
356
  }
@@ -294,7 +361,14 @@ export async function validateProjectTree(
294
361
  const validateClass = classAjv.compile(generateClassSchema());
295
362
  for (const file of walkClassFiles(root)) {
296
363
  checked += 1;
297
- const doc = readJson(file);
364
+ let doc: JsonValue;
365
+ try {
366
+ // SAFETY: a parsed class definition is a JSON object, which is a JsonValue.
367
+ doc = parseClassDef(readFileSync(file, "utf8"), relative(root, file)) as JsonObject;
368
+ } catch (error) {
369
+ issues.push({ errors: [{ message: errorMessage(error) }], file: relative(root, file) });
370
+ continue;
371
+ }
298
372
  const bodies = checkBodies(doc, relative(root, file));
299
373
  lint.push(...bodies.warnings);
300
374
  if (bodies.failure !== null) {
@@ -336,6 +410,50 @@ export async function validateProjectTree(
336
410
  return { checked, issues, lint, valid: issues.length === 0 && !fatalLint };
337
411
  }
338
412
 
413
+ /** The expression-rule findings of a document as issue errors (spec.md §19.3 to §19.5). */
414
+ function expressionErrors(doc: ExpressionSource): { instancePath: string; message: string }[] {
415
+ return findExpressionDefects(doc).map(({ message, pointer }) => ({
416
+ instancePath: pointer,
417
+ message,
418
+ }));
419
+ }
420
+
421
+ /**
422
+ * `project.json` as a config, or `undefined` when it is absent or does not parse: walk 2 reports
423
+ * the file, so this hides nothing.
424
+ */
425
+ function readProjectFile(root: string): ProjectConfig | undefined {
426
+ try {
427
+ return loadProjectConfig(root).config;
428
+ } catch {
429
+ return undefined;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * The call cycles a document's `state` carries (spec.md §19.4c). A page is judged as the build
435
+ * merges it, in `injectContext`'s order: its own entries, then each project entry it does not
436
+ * declare, `$site` and `$page` excluded. Only a cycle through a key the page declares is the page's
437
+ * to report, so a cycle made of project entries alone is reported once, on `project.json`.
438
+ */
439
+ function documentCallCycles(
440
+ doc: JxElement,
441
+ isPage: boolean,
442
+ projectState: Record<string, JxStateDefinition>,
443
+ ): string[][] {
444
+ const own = doc.state ?? {};
445
+ if (!isPage) {
446
+ return findCallCycles(own);
447
+ }
448
+ const merged = { ...own };
449
+ for (const [key, value] of Object.entries(projectState)) {
450
+ if (key !== "$site" && key !== "$page" && !(key in own)) {
451
+ merged[key] = value;
452
+ }
453
+ }
454
+ return findCallCycles(merged).filter((cycle) => cycle.some((key) => key in own));
455
+ }
456
+
339
457
  /**
340
458
  * The project's `$defs`, when `project.json` loads and declares an object. A project file the
341
459
  * loader refuses answers `undefined` and hides nothing: walk 2 has already reported it, and walk 5
@@ -364,7 +482,20 @@ interface ReadDocumentFile {
364
482
  */
365
483
  function readDocumentFile(file: string, name: string): ReadDocumentFile {
366
484
  if (!isJxnPath(file)) {
367
- return { document: readJson(file), failure: null, warnings: [] };
485
+ try {
486
+ return {
487
+ // SAFETY: `parseJxDocument` answers a JSON object, which is a JsonValue.
488
+ document: parseJxDocument(readFileSync(file, "utf8"), name) as JsonObject,
489
+ failure: null,
490
+ warnings: [],
491
+ };
492
+ } catch (error) {
493
+ return {
494
+ document: null,
495
+ failure: { errors: [{ message: errorMessage(error) }], file: name },
496
+ warnings: [],
497
+ };
498
+ }
368
499
  }
369
500
  const text = readFileSync(file, "utf8");
370
501
  const warnings = lintJxn(text).map((warning): ProjectTreeLintFinding => ({
@@ -443,6 +574,9 @@ function lintDocument(doc: JxElement, file: string, scope: OverlayScope): Projec
443
574
  for (const defect of findA11yDefects(doc)) {
444
575
  findings.push({ ...pick(defect), criterion: defect.criterion, file, source: "accessibility" });
445
576
  }
577
+ for (const defect of findTagExpressionDefects(doc)) {
578
+ findings.push({ ...pick(defect), file, source: "expression" });
579
+ }
446
580
  for (const advice of findScriptAdvice(doc)) {
447
581
  findings.push({ ...pick({ ...advice, severity: "info" }), file, source: "module" });
448
582
  }
@@ -12,7 +12,7 @@
12
12
  import { siteBasePath, withBase } from "@jxsuite/schema/asset-paths";
13
13
  import { mkdirSync, writeFileSync } from "node:fs";
14
14
  import { dirname, join } from "node:path";
15
- import { canonicalizeLocale } from "@jxsuite/schema/locale";
15
+ import { canonicalizeLocale, malformedLocaleError } from "@jxsuite/schema/locale";
16
16
  import { isString } from "@jxsuite/schema/guards";
17
17
  import type { ManifestConfig, ProjectConfig, SecurityTxtConfig } from "@jxsuite/schema/types";
18
18
 
@@ -211,7 +211,7 @@ export function buildSecurityTxt(projectConfig: ProjectConfig, now: Date): WellK
211
211
  for (const tag of config.preferredLanguages ?? []) {
212
212
  const canonical = canonicalizeLocale(tag);
213
213
  if (canonical === null) {
214
- errors.push(`securityTxt.preferredLanguages: "${tag}" is not a well-formed language tag.`);
214
+ errors.push(malformedLocaleError("securityTxt.preferredLanguages", tag));
215
215
  } else {
216
216
  languages.push(canonical);
217
217
  }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * External `$switch` cases in a site build (spec.md §14.1).
3
+ *
4
+ * An interpreter fetches an external `{ "$ref" }` case when its key first becomes active. A built
5
+ * page ships no runtime to fetch a document, so the site build compiles each referenced file to an
6
+ * element module of its own and rewrites the case, in memory and before any merge or compile, to an
7
+ * instance of that element (`lowerExternalCases`). Both targets then render it like any other case,
8
+ * and load its module through the one helper `caseLoaderSource()` (`shared.ts`).
9
+ *
10
+ * Everything here is pure: the build supplies the files it accepted, and this module only names
11
+ * them, finds the references and rewrites a copy.
12
+ *
13
+ * @docs framework/concepts/switching
14
+ */
15
+
16
+ import { createHash } from "node:crypto";
17
+ import { relative, resolve } from "node:path";
18
+ import { isJsonObject, isRef } from "@jxsuite/schema/guards";
19
+ import type { JsonObject, JsonValue, JxDocument } from "@jxsuite/schema/types";
20
+
21
+ /**
22
+ * The custom-element name an external case compiles to: `jx-case-<slug>-<hash>`. The slug is the
23
+ * file's basename, lowercased, with each run outside `[a-z0-9]` collapsed to `-` (`doc` when
24
+ * nothing is left), and the hash is the first 8 hex digits of the SHA-256 of the file's
25
+ * `/`-separated project-relative path. A valid custom-element name, stable across builds, distinct
26
+ * for two `home.json` in different directories, and readable in a diagnostic.
27
+ *
28
+ * @param {string} projectRoot - The project root the path is made relative to
29
+ * @param {string} casePath - Absolute path of the case document
30
+ * @returns {string}
31
+ */
32
+ export function caseTagName(projectRoot: string, casePath: string): string {
33
+ const rel = relative(projectRoot, casePath).replaceAll("\\", "/");
34
+ const base = rel.slice(rel.lastIndexOf("/") + 1).replace(/\.[^.]*$/u, "");
35
+ const slug =
36
+ base
37
+ .toLowerCase()
38
+ .replaceAll(/[^a-z0-9]+/gu, "-")
39
+ .replaceAll(/^-+|-+$/gu, "") || "doc";
40
+ const hash = createHash("sha256").update(rel, "utf8").digest("hex").slice(0, 8);
41
+ return `jx-case-${slug}-${hash}`;
42
+ }
43
+
44
+ /** Visit one node of a document tree and everything a `$switch` case can reach below it. */
45
+ function walkNode(node: JsonValue | JxDocument | undefined, visit: (cases: JsonObject) => void) {
46
+ if (Array.isArray(node)) {
47
+ for (const child of node) {
48
+ walkNode(child, visit);
49
+ }
50
+ return;
51
+ }
52
+ if (!isJsonObject(node)) {
53
+ return;
54
+ }
55
+ const { cases } = node;
56
+ if (isJsonObject(cases) && node.$switch !== undefined) {
57
+ visit(cases);
58
+ }
59
+ walkNode(node.children, visit);
60
+ // A repeater's row template.
61
+ walkNode(node.map, visit);
62
+ }
63
+
64
+ /**
65
+ * Call `visit(key, ref)` for each external `{ "$ref" }` case a document reaches: through `children`
66
+ * (array items, and a mapped array's `map`) and through every `$switch` node's `cases`, recursing
67
+ * into an inline case. It does not enter `state`, `$defs` or `$props`.
68
+ *
69
+ * @param {JxDocument} doc
70
+ * @param {(key: string, ref: string) => void} visit
71
+ */
72
+ export function forEachExternalCase(
73
+ doc: JxDocument,
74
+ visit: (key: string, ref: string) => void,
75
+ ): void {
76
+ const walkCases = (cases: JsonObject): void => {
77
+ for (const [key, caseDef] of Object.entries(cases)) {
78
+ if (isRef(caseDef)) {
79
+ visit(key, caseDef.$ref);
80
+ } else {
81
+ walkNode(caseDef, walkCases);
82
+ }
83
+ }
84
+ };
85
+ walkNode(doc, walkCases);
86
+ }
87
+
88
+ /**
89
+ * A copy of `doc` in which each external case whose resolved path has a tag becomes `{ "tagName":
90
+ * <tag> }` and each other external case is deleted. The input is never mutated: one parsed document
91
+ * feeds the component set, the CSS and the compile. A document with no external case is returned as
92
+ * it is.
93
+ *
94
+ * @param {JxDocument} doc
95
+ * @param {string} docDir - Directory the document's references are relative to
96
+ * @param {(absPath: string) => string | undefined} tagFor - The tag the build compiled a path to
97
+ * @returns {JxDocument}
98
+ */
99
+ export function lowerExternalCases(
100
+ doc: JxDocument,
101
+ docDir: string,
102
+ tagFor: (absPath: string) => string | undefined,
103
+ ): JxDocument {
104
+ const refs: string[] = [];
105
+ forEachExternalCase(doc, (_key, ref) => {
106
+ refs.push(ref);
107
+ });
108
+ if (refs.length === 0) {
109
+ return doc;
110
+ }
111
+ const copy = structuredClone(doc);
112
+ const lowerCases = (cases: JsonObject): void => {
113
+ for (const [key, caseDef] of Object.entries(cases)) {
114
+ if (isRef(caseDef)) {
115
+ const tag = tagFor(resolve(docDir, caseDef.$ref));
116
+ if (tag === undefined) {
117
+ delete cases[key];
118
+ } else {
119
+ cases[key] = { tagName: tag };
120
+ }
121
+ } else {
122
+ walkNode(caseDef, lowerCases);
123
+ }
124
+ }
125
+ };
126
+ walkNode(copy, lowerCases);
127
+ return copy;
128
+ }
129
+
130
+ /**
131
+ * The element document a case compiles as: a host `{ tagName, $shadow: false, display: contents }`
132
+ * holding the case document's root as its one child. The document-level keys (`state`, `$defs`,
133
+ * `imports`, `$elements`, `$media`, `$id`) move to the host; the root is the document minus those
134
+ * keys and `$schema`, `$head` and `$layout`.
135
+ *
136
+ * @param {JxDocument} doc
137
+ * @param {string} tagName
138
+ * @returns {JxDocument}
139
+ */
140
+ export function wrapCaseDocument(doc: JxDocument, tagName: string): JxDocument {
141
+ const root = { ...doc };
142
+ delete root.state;
143
+ delete root.$defs;
144
+ delete root.imports;
145
+ delete root.$elements;
146
+ delete root.$media;
147
+ delete root.$id;
148
+ delete root.$schema;
149
+ delete root.$head;
150
+ delete root.$layout;
151
+ const host: JxDocument = {
152
+ $shadow: false,
153
+ children: [root],
154
+ style: { display: "contents" },
155
+ tagName,
156
+ };
157
+ if (doc.state !== undefined) {
158
+ host.state = doc.state;
159
+ }
160
+ if (doc.$defs !== undefined) {
161
+ host.$defs = doc.$defs;
162
+ }
163
+ if (doc.imports !== undefined) {
164
+ host.imports = doc.imports;
165
+ }
166
+ if (doc.$elements !== undefined) {
167
+ host.$elements = doc.$elements;
168
+ }
169
+ if (doc.$media !== undefined) {
170
+ host.$media = doc.$media;
171
+ }
172
+ if (doc.$id !== undefined) {
173
+ host.$id = doc.$id;
174
+ }
175
+ return host;
176
+ }