@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/compiler",
3
- "version": "8.4.0",
3
+ "version": "8.6.0",
4
4
  "description": "Jx static HTML compiler, island detector, and site builder",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,10 +52,11 @@
52
52
  "upgrade": "bun update --latest && bun install"
53
53
  },
54
54
  "dependencies": {
55
- "@jxsuite/create": "^1.6.0",
56
- "@jxsuite/runtime": "^6.2.1",
57
- "@jxsuite/schema": "^5.4.0",
58
- "@jxsuite/site": "^2.5.0",
55
+ "@jxsuite/create": "^1.8.0",
56
+ "@jxsuite/erase": "^0.2.0",
57
+ "@jxsuite/runtime": "^6.3.0",
58
+ "@jxsuite/schema": "^5.6.0",
59
+ "@jxsuite/site": "^2.6.0",
59
60
  "@vue/reactivity": "3.5.44",
60
61
  "esbuild": "^0.28.2",
61
62
  "lit-html": "^3.3.3",
@@ -63,8 +64,8 @@
63
64
  },
64
65
  "devDependencies": {
65
66
  "@happy-dom/global-registrator": "^21.0.4",
66
- "@jxsuite/connector": "^0.8.6",
67
- "@jxsuite/parser": "^4.3.2",
67
+ "@jxsuite/connector": "^0.8.8",
68
+ "@jxsuite/parser": "^4.3.4",
68
69
  "@jxsuite/test-support": "^0.0.0",
69
70
  "@types/mdast": "^4.0.4"
70
71
  }
package/src/compiler.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  * @version 3.0.0
14
14
  */
15
15
 
16
+ import { erasedDocument } from "./erased.ts";
16
17
  import { readFileSync } from "node:fs";
17
18
  import {
18
19
  DEFAULT_LIT_HTML_SRC,
@@ -109,6 +110,8 @@ export async function compile(sourcePath: string | JxDocument, opts: CompileOpti
109
110
  } else {
110
111
  raw = sourcePath;
111
112
  }
113
+ // Function bodies as JavaScript before anything analyses them (spec.md §23.1).
114
+ raw = erasedDocument(raw, isString(sourcePath) ? sourcePath : "the document");
112
115
 
113
116
  // Route 0: .class.json schema-defined class → JS class module
114
117
  if (isClassDef(raw)) {
package/src/erased.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Documents as the compiler reads them: with the TypeScript in their function bodies erased, once,
3
+ * as each is read (`spec.md` §23.1, `compiler.md` §2.3). Everything after this, the analysis that
4
+ * classifies a body and every emitter, sees JavaScript, so none of it changes.
5
+ *
6
+ * A body that was already JavaScript and reads differently as TypeScript (`a < b > (c)`) is said
7
+ * once per place, on stderr, and the build goes on with the TypeScript reading.
8
+ *
9
+ * @docs framework/concepts/functions
10
+ */
11
+ import { eraseClass, eraseDocument } from "@jxsuite/erase";
12
+ import type { EraseWarning } from "@jxsuite/erase";
13
+ import type { JsonValue, JxClassDef, JxDocument } from "@jxsuite/schema/types";
14
+
15
+ /** Every warning already printed, so a document read twice says each thing once. */
16
+ const said = new Set<string>();
17
+
18
+ /** Print what erasing found that did not stop it. */
19
+ function report(warnings: readonly EraseWarning[]): void {
20
+ for (const { path, pointer, problem } of warnings) {
21
+ const line = `${path}${pointer} (line ${problem.line}, column ${problem.column}): ${problem.message}`;
22
+ if (!said.has(line)) {
23
+ said.add(line);
24
+ console.warn(`Warning: ${line}`);
25
+ }
26
+ }
27
+ }
28
+
29
+ /**
30
+ * A document with its function bodies as JavaScript.
31
+ *
32
+ * @param document The document as read.
33
+ * @param path Where it was read from, which names it in a message.
34
+ * @throws {import("@jxsuite/erase").EraseError} When a body uses TypeScript that cannot be erased.
35
+ */
36
+ export function erasedDocument<T extends JsonValue | JxDocument | JxClassDef>(
37
+ document: T,
38
+ path: string,
39
+ ): T {
40
+ const warnings: EraseWarning[] = [];
41
+ const erased = eraseDocument(document, path, warnings);
42
+ report(warnings);
43
+ return erased;
44
+ }
45
+
46
+ /**
47
+ * A class definition with its members' bodies as JavaScript.
48
+ *
49
+ * @param definition The class definition as read.
50
+ * @param path Where it was read from.
51
+ */
52
+ export function erasedClass<T extends JsonValue | JxDocument | JxClassDef>(
53
+ definition: T,
54
+ path: string,
55
+ ): T {
56
+ const warnings: EraseWarning[] = [];
57
+ const erased = eraseClass(definition, path, warnings);
58
+ report(warnings);
59
+ return erased;
60
+ }
package/src/shared.ts CHANGED
@@ -6,6 +6,11 @@
6
6
  * compilation targets (static, client, element, server).
7
7
  */
8
8
 
9
+ import {
10
+ classifyFunctionEntries,
11
+ declaresBodyAndSrc,
12
+ handlerParamNames,
13
+ } from "@jxsuite/schema/function-role";
9
14
  import {
10
15
  COLOR_SCHEME_ATTR,
11
16
  COLOR_SCHEME_STORAGE_KEY,
@@ -28,7 +33,6 @@ import { compileOperandSource, evaluateExpression, isMutating } from "@jxsuite/r
28
33
  import { runStatements } from "@jxsuite/runtime/statements";
29
34
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
30
35
  import {
31
- bodyReturnsValue,
32
36
  childrenContainArray,
33
37
  hasStructuredBody,
34
38
  isExpressionDef,
@@ -47,8 +51,8 @@ import {
47
51
  isString,
48
52
  isTagExpression,
49
53
  isTemplateString,
50
- paramNames,
51
54
  tagNameCandidates,
55
+ maskCode,
52
56
  } from "@jxsuite/schema/guards";
53
57
  import type { TagNameSlot } from "@jxsuite/schema/guards";
54
58
  import { resolveShadowMode, styleScopePrefix } from "./shadow.ts";
@@ -604,6 +608,62 @@ const STATE_ASSIGNMENT_RE =
604
608
  const STATE_MUTATING_METHOD_RE =
605
609
  /\bstate\.([A-Za-z_$][\w$]*)\s*\.\s*(?:push|pop|shift|unshift|splice|sort|reverse|fill|copyWithin)\s*\(/g;
606
610
 
611
+ /** A character that continues an identifier, or a `.` that makes `state` someone's member. */
612
+ const JOINS_STATE = /[\w$.]/u;
613
+
614
+ /** A character that continues an identifier. */
615
+ const CONTINUES_NAME = /[\w$]/u;
616
+
617
+ /** Whether `state` at `at` in `read` is the one to move: standalone, and a member read unless bare. */
618
+ function movesState(read: string, at: number, bare: boolean): boolean {
619
+ if (at > 0 && JOINS_STATE.test(read.charAt(at - 1))) {
620
+ return false;
621
+ }
622
+ let next = at + "state".length;
623
+ if (bare) {
624
+ return !CONTINUES_NAME.test(read.charAt(next));
625
+ }
626
+ while (/\s/u.test(read.charAt(next))) {
627
+ next += 1;
628
+ }
629
+ return read.charAt(next) === ".";
630
+ }
631
+
632
+ /**
633
+ * Rewrite `state` in emitted code to what holds it there (`this.state`, `s`): the one way every
634
+ * target does it (`spec.md` §23.1). Only a standalone `state` moves, so `prevstate.n` stays itself,
635
+ * and in a body only code moves, so a string or a comment that mentions `state.` is left as
636
+ * written.
637
+ *
638
+ * @param text The body, or an expression.
639
+ * @param to What `state` becomes.
640
+ * @param options `bare` moves `state` alone too, not only `state.member`; `code: false` reads text
641
+ * that is not a body (an attribute's template), where nothing is a string or a comment.
642
+ */
643
+ export function rewriteState(
644
+ text: string,
645
+ to: string,
646
+ options: { bare?: boolean; code?: boolean } = {},
647
+ ): string {
648
+ // Most text never names `state`, and every emitter calls this on every body and template.
649
+ if (!text.includes("state")) {
650
+ return text;
651
+ }
652
+ const bare = options.bare === true;
653
+ const read = options.code === false ? text : maskCode(text);
654
+ /* A scan rather than a lookbehind pattern: every emitter runs this on every body and template,
655
+ and JavaScriptCore runs `(?<!…)` on its slow path, which a compile benchmark measured. */
656
+ let out = "";
657
+ let last = 0;
658
+ for (let at = read.indexOf("state"); at !== -1; at = read.indexOf("state", at + 1)) {
659
+ if (movesState(read, at, bare)) {
660
+ out += text.slice(last, at) + to;
661
+ last = at + "state".length;
662
+ }
663
+ }
664
+ return out + text.slice(last);
665
+ }
666
+
607
667
  /**
608
668
  * Collect every state key a handler writes to, across all the forms a body can take: a string body,
609
669
  * a structured body (spec §20), and an `$expression` node with a mutating operator.
@@ -618,11 +678,16 @@ const STATE_MUTATING_METHOD_RE =
618
678
  */
619
679
  function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<string>) {
620
680
  if (isString(node)) {
621
- for (const m of node.matchAll(STATE_ASSIGNMENT_RE)) {
681
+ if (!node.includes("state.")) {
682
+ return;
683
+ }
684
+ // Code only: an assignment a comment or a string mentions writes nothing (spec.md §23.1).
685
+ const code = maskCode(node);
686
+ for (const m of code.matchAll(STATE_ASSIGNMENT_RE)) {
622
687
  // SAFETY: the pattern's one capture group is outside any optional part, so a match has it.
623
688
  into.add(m[1] as string);
624
689
  }
625
- for (const m of node.matchAll(STATE_MUTATING_METHOD_RE)) {
690
+ for (const m of code.matchAll(STATE_MUTATING_METHOD_RE)) {
626
691
  // SAFETY: the pattern's one capture group is outside any optional part, so a match has it.
627
692
  into.add(m[1] as string);
628
693
  }
@@ -656,6 +721,27 @@ function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<s
656
721
  }
657
722
  }
658
723
 
724
+ /**
725
+ * Refuse a Function declaration that names both a `body` and a `$src` (spec.md §5.3 4d). The pair
726
+ * has no meaning: each tier used to keep a different half, so a document that built in one target
727
+ * did something else in another. Every place the compiler lowers a Function declaration calls this
728
+ * first, so no target lets the pair through, and `where` names the declaration for the build
729
+ * error.
730
+ *
731
+ * @param where What the declaration is, for the message: `state entry "save"`.
732
+ * @param def The value found there; anything but a Function declaration is left alone.
733
+ */
734
+ export function refuseBodyWithSrc(
735
+ where: string,
736
+ def: JxDocumentValue | JxStateDefinition | undefined,
737
+ ): void {
738
+ if (isFunctionDef(def) && declaresBodyAndSrc(def)) {
739
+ throw new Error(
740
+ `${where} declares both "body" and "$src"; they are mutually exclusive (spec.md §5.3 4d). Keep one.`,
741
+ );
742
+ }
743
+ }
744
+
659
745
  /**
660
746
  * @param {Record<string, JxStateDefinition>} [defs]
661
747
  * @param {JxScope | null} [parentScope]
@@ -695,6 +781,9 @@ export function buildInitialScope(
695
781
  }
696
782
  }
697
783
 
784
+ // The same verdict every other tier reads (spec.md §5.3 4b, 4d).
785
+ const roles = classifyFunctionEntries({ state: defs });
786
+
698
787
  for (const [key, def] of Object.entries(defs)) {
699
788
  if (!isNonNullObject(def) || Array.isArray(def)) {
700
789
  setOwnScopeValue(scope, key, cloneValue(def));
@@ -718,7 +807,7 @@ export function buildInitialScope(
718
807
  // Template-string entries are deferred to a third pass: whether one is resolvable depends on the
719
808
  // Runtime-only marks the loop below adds, and key order must not decide the answer.
720
809
  const templateDefs: [string, string][] = [];
721
- // Computed (`bodyReturnsValue`) entries are deferred for the same reason. A computed is stored in
810
+ // Entries the classifier calls computed are deferred for the same reason. A computed is stored in
722
811
  // The scope as its already-evaluated *result*, so a template reading it sees an ordinary string
723
812
  // And prerender bakes it — destroying the binding rather than merely staling it (issue #124).
724
813
  const computedBodies: [string, string][] = [];
@@ -758,6 +847,7 @@ export function buildInitialScope(
758
847
  continue;
759
848
  }
760
849
  if (isFunctionDef(def)) {
850
+ refuseBodyWithSrc(`state entry "${key}"`, def);
761
851
  if (hasStructuredBody(def)) {
762
852
  // Structured body (spec §20): a side-effecting handler in the build-time scope. Build-time
763
853
  // Code may call it bare, so the scope it runs against falls back to this one.
@@ -766,27 +856,19 @@ export function buildInitialScope(
766
856
  void runStatements(body, s ?? scope, event ?? null);
767
857
  });
768
858
  } else if (isString(def.body)) {
769
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
770
859
  const { body } = def;
771
- // Declared names bind by name, not by position (spec.md §5.3 4d): a parameter literally
772
- // Named `state` receives the scope, anything else receives the event. `state` is prepended
773
- // When undeclared so a body may always reference it. Unconditionally prepending it instead —
774
- // The older behaviour here — produced a duplicate parameter for the `["state", "event"]`
775
- // Form that examples/components/task-manager.json uses, leaving `state` undefined.
776
- const params = declared.includes("state") ? declared : ["state", ...declared];
777
- /* SAFETY: `new Function` returns an ordinary function of exactly `params`; `invoke` below is
778
- its only caller and passes the scope or the event in each position, and what the body
779
- returns is one more scope member. */
780
- const fn = new Function(...params, body) as (
860
+ // One parameter list in every tier (spec.md §5.3 4d): `state` first, then the other declared
861
+ // Names in order, so a call site's `(state, event)` binds by position.
862
+ /* SAFETY: `new Function` returns an ordinary function of exactly those parameters; a call
863
+ never checks its arguments, and what the body returns is one more scope member. */
864
+ const fn = new Function(...handlerParamNames(def), body) as (
781
865
  ...args: (JxScope | Event | undefined)[]
782
866
  ) => JxScope[string];
783
- const invoke = (state: JxScope, event?: Event) =>
784
- fn(...params.map((name) => (name === "state" ? state : event)));
785
- if (bodyReturnsValue(body)) {
786
- defineLazyScopeValue(scope, key, () => invoke(scope));
867
+ if (roles.get(key) === "computed") {
868
+ defineLazyScopeValue(scope, key, () => fn(scope));
787
869
  computedBodies.push([key, body]);
788
870
  } else {
789
- setOwnScopeValue(scope, key, invoke);
871
+ setOwnScopeValue(scope, key, fn);
790
872
  }
791
873
  } else {
792
874
  // Bodyless `$src` Function — the real implementation is only loaded in the browser, so this
@@ -9,9 +9,13 @@
9
9
  * in every project, because deciding not to optimize an image says nothing about when to fetch it.
10
10
  * The **variant** pass (`images.optimize`) is the expensive half and is the one the master switch
11
11
  * turns off.
12
+ *
13
+ * A third, cheap pass runs on every image too: a picture whose own file names a **focal point**
14
+ * (studio.md §22.6, an IPTC Image Region read by `@jxsuite/site/xmp-packet`) is given it as its
15
+ * `object-position`, unless the author set one, so any `object-fit` crop keeps that point in view.
12
16
  */
13
17
 
14
- import { existsSync } from "node:fs";
18
+ import { existsSync, readFileSync, statSync } from "node:fs";
15
19
  import { basename, extname, resolve } from "node:path";
16
20
  import {
17
21
  buildSrcset,
@@ -25,6 +29,8 @@ import { imgLoadingAttrs } from "./img-loading.ts";
25
29
  import { resolveAssetUrl } from "@jxsuite/schema/asset-paths";
26
30
  import { isNodeObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
27
31
  import { errorMessage } from "@jxsuite/schema/parse";
32
+ import { extractXmp, xmpFormatOf } from "@jxsuite/site/xmp-containers";
33
+ import { readMediaRecord } from "@jxsuite/site/xmp-packet";
28
34
 
29
35
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
30
36
  import type { ImageConfig, ImageManifest, ImageVariant } from "./image-optimizer.ts";
@@ -234,6 +240,78 @@ function resolveImagePath(src: string, projectRoot: string, mounts?: readonly As
234
240
  return resolve(projectRoot, src);
235
241
  }
236
242
 
243
+ /** Focal points already read, keyed by the file's path, modified time and size. */
244
+ const focusCache = new Map<string, string | null>();
245
+
246
+ /** A fraction as a CSS percentage, to one decimal place. */
247
+ function percent(fraction: number): string {
248
+ return `${Math.round(fraction * 1000) / 10}%`;
249
+ }
250
+
251
+ /**
252
+ * The `object-position` a picture's own focal point asks for, or `null` when the file names none,
253
+ * cannot hold one, or cannot be read. A file whose metadata does not parse is a picture, not a
254
+ * broken build: it is drawn as it was before it had a focal point.
255
+ */
256
+ function focusPosition(absolute: string): string | null {
257
+ const format = xmpFormatOf(absolute);
258
+ if (format === null) {
259
+ return null;
260
+ }
261
+ let stamp: string;
262
+ try {
263
+ const stat = statSync(absolute);
264
+ stamp = `${absolute}|${stat.mtimeMs}|${stat.size}`;
265
+ } catch {
266
+ return null;
267
+ }
268
+ const cached = focusCache.get(stamp);
269
+ if (cached !== undefined) {
270
+ return cached;
271
+ }
272
+ let position: string | null = null;
273
+ try {
274
+ const bytes = new Uint8Array(readFileSync(absolute));
275
+ const { focus } = readMediaRecord(extractXmp(bytes, format));
276
+ position = focus === null ? null : `${percent(focus.x)} ${percent(focus.y)}`;
277
+ } catch {
278
+ position = null;
279
+ }
280
+ focusCache.set(stamp, position);
281
+ return position;
282
+ }
283
+
284
+ /**
285
+ * Give an `<img>` its file's focal point as `object-position`. The author's own `objectPosition`
286
+ * wins, a style written as something other than an object is left alone, and a bound, remote or
287
+ * inline `src` names no file to read.
288
+ */
289
+ function applyFocalPoint(
290
+ node: JxMutableNode | JxDocument,
291
+ src: JxAttributeValue | undefined,
292
+ projectRoot: string,
293
+ mounts: readonly AssetMount[],
294
+ ): void {
295
+ if (!isString(src) || src === "" || src.includes("${")) {
296
+ return;
297
+ }
298
+ if (EXTERNAL_PREFIXES.some((prefix) => src.startsWith(prefix))) {
299
+ return;
300
+ }
301
+ const { style } = node;
302
+ if (style !== undefined && !isNonNullObject(style)) {
303
+ return;
304
+ }
305
+ if (style?.objectPosition !== undefined) {
306
+ return;
307
+ }
308
+ const [path = ""] = src.split(/[?#]/);
309
+ const position = focusPosition(resolveImagePath(path, projectRoot, mounts));
310
+ if (position !== null) {
311
+ node.style = { ...style, objectPosition: position };
312
+ }
313
+ }
314
+
237
315
  /**
238
316
  * Transform image nodes in a Jx document tree.
239
317
  *
@@ -576,6 +654,7 @@ async function transformImgNode(
576
654
  attrs.src = node.src;
577
655
  delete node.src;
578
656
  }
657
+ applyFocalPoint(node, attrs.src, projectRoot, mounts);
579
658
 
580
659
  const variants = config.optimize
581
660
  ? await resolveVariants(
@@ -8,6 +8,7 @@
8
8
  * and saying which file was wrong when it is.
9
9
  */
10
10
 
11
+ import { erasedDocument } from "../erased.ts";
11
12
  import { existsSync, readFileSync } from "node:fs";
12
13
  import { parseNativeDocument } from "@jxsuite/schema/jxn";
13
14
  import { errorMessage } from "@jxsuite/schema/parse";
@@ -27,7 +28,10 @@ export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => Jx
27
28
  throw new Error(`Layout not found: ${layoutRef} (resolved to ${layoutPath})`);
28
29
  }
29
30
  try {
30
- return parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath);
31
+ return erasedDocument(
32
+ parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath),
33
+ layoutPath,
34
+ );
31
35
  } catch (error) {
32
36
  throw new Error(`Invalid layout at ${layoutPath}: ${errorMessage(error)}`, {
33
37
  cause: error,
@@ -16,6 +16,7 @@
16
16
  * genuinely needs a filesystem: the walk, the `$layout` peek, and `$paths` expansion.
17
17
  */
18
18
 
19
+ import { erasedDocument } from "../erased.ts";
19
20
  import { readFileSync, readdirSync, statSync } from "node:fs";
20
21
  import { isJsonObject, isString } from "@jxsuite/schema/guards";
21
22
  import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
@@ -82,7 +83,7 @@ export async function readPageDocument(
82
83
  ): Promise<JxDocument> {
83
84
  const source = readFileSync(filePath, "utf8");
84
85
  if (isNativeDocumentPath(filePath)) {
85
- return parseNativeDocument(source, filePath);
86
+ return erasedDocument(parseNativeDocument(source, filePath), filePath);
86
87
  }
87
88
  const ext = extname(filePath).toLowerCase();
88
89
  const entry = registry?.byExtension(ext, "parse");
@@ -93,7 +94,8 @@ export async function readPageDocument(
93
94
  `e.g. "@jxsuite/parser".`,
94
95
  );
95
96
  }
96
- return await entry.parseDocument(source);
97
+ // A format's page holds function bodies too (spec.md §23.1).
98
+ return erasedDocument(await entry.parseDocument(source), filePath);
97
99
  }
98
100
 
99
101
  /**
@@ -20,6 +20,8 @@
20
20
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
21
21
  import { isJxnPath, isNativeDocumentPath, lintJxn, parseJxn } from "@jxsuite/schema/jxn";
22
22
  import { errorMessage } from "@jxsuite/schema/parse";
23
+ import { eraseDocument } from "@jxsuite/erase";
24
+ import type { EraseWarning } from "@jxsuite/erase";
23
25
  import { createRequire } from "node:module";
24
26
  import { join, relative, resolve } from "node:path";
25
27
  import { generateClassSchema } from "@jxsuite/schema";
@@ -65,8 +67,11 @@ export interface ProjectTreeLintFinding {
65
67
  file: string;
66
68
  /** The node's path inside the document. */
67
69
  path: (string | number)[];
68
- /** Which lint: `popover`, `dialog`, `accessibility`, or `notation` for a `.jxn` file's text. */
69
- source: "popover" | "dialog" | "accessibility" | "notation";
70
+ /**
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).
73
+ */
74
+ source: "popover" | "dialog" | "accessibility" | "notation" | "function-body";
70
75
  rule: string;
71
76
  message: string;
72
77
  detail: string;
@@ -221,6 +226,12 @@ export async function validateProjectTree(
221
226
  continue;
222
227
  }
223
228
  const doc = read.document;
229
+ const bodies = checkBodies(doc, relative(root, file));
230
+ lint.push(...bodies.warnings);
231
+ if (bodies.failure !== null) {
232
+ issues.push(bodies.failure);
233
+ continue;
234
+ }
224
235
  if (validateDoc(doc)) {
225
236
  /*
226
237
  * Only a well-formed document is judged; a schema error is the report for the rest.
@@ -241,7 +252,11 @@ export async function validateProjectTree(
241
252
  for (const file of walkClassFiles(root)) {
242
253
  checked += 1;
243
254
  const doc = readJson(file);
244
- if (!validateClass(doc)) {
255
+ const bodies = checkBodies(doc, relative(root, file));
256
+ lint.push(...bodies.warnings);
257
+ if (bodies.failure !== null) {
258
+ issues.push(bodies.failure);
259
+ } else if (!validateClass(doc)) {
245
260
  issues.push({ errors: validateClass.errors ?? [], file: relative(root, file) });
246
261
  }
247
262
  }
@@ -315,6 +330,36 @@ function readDocumentFile(file: string, name: string): ReadDocumentFile {
315
330
  }
316
331
  }
317
332
 
333
+ /** What checking a document's function bodies found: an issue that stops it, and warnings. */
334
+ interface BodyCheck {
335
+ failure: ProjectTreeIssue | null;
336
+ warnings: ProjectTreeLintFinding[];
337
+ }
338
+
339
+ /**
340
+ * Whether every function body in a document is TypeScript that can be erased (`spec.md` §23.1): a
341
+ * body that cannot is an issue, as it stops `jx build`, and one that reads differently as
342
+ * TypeScript than as the JavaScript it already was is a warning.
343
+ */
344
+ function checkBodies(document: JsonValue, name: string): BodyCheck {
345
+ const found: EraseWarning[] = [];
346
+ try {
347
+ eraseDocument(document, name, found);
348
+ } catch (error) {
349
+ return { failure: { errors: [{ message: errorMessage(error) }], file: name }, warnings: [] };
350
+ }
351
+ const warnings = found.map(({ pointer, problem }): ProjectTreeLintFinding => ({
352
+ detail: problem.message,
353
+ file: name,
354
+ message: `${pointer} (line ${problem.line}, column ${problem.column}): ${problem.message}`,
355
+ path: pointer.split("/").slice(1),
356
+ rule: "typescript-reading",
357
+ severity: "warn",
358
+ source: "function-body",
359
+ }));
360
+ return { failure: null, warnings };
361
+ }
362
+
318
363
  /** A `.jxn` file's document, as the JSON value it is. */
319
364
  function readJxnValue(text: string): JsonValue {
320
365
  const document = parseJxn(text);
@@ -5,6 +5,7 @@
5
5
  * Schema 2020-12 class definition.
6
6
  */
7
7
 
8
+ import { erasedClass } from "../erased.ts";
8
9
  import type {
9
10
  JxClassCtorDef,
10
11
  JxClassDef,
@@ -20,7 +21,9 @@ import { isString } from "@jxsuite/schema/guards";
20
21
  * @param {JxClassDef} classDef - Parsed .class.json content (must have $prototype: "Class")
21
22
  * @returns {string} JavaScript module source code
22
23
  */
23
- export function compileClassJson(classDef: JxClassDef) {
24
+ export function compileClassJson(authored: JxClassDef) {
25
+ // Member bodies as JavaScript before anything splices them (spec.md §23.1).
26
+ const classDef = erasedClass(authored, authored.title ?? "a class");
24
27
  const className = classDef.title;
25
28
  if (!className) {
26
29
  throw new Error("compileClassJson: missing title (class name)");