@jxsuite/compiler 8.6.0 → 9.0.1

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.
@@ -48,11 +48,11 @@ const DEFAULTS = {
48
48
  layout: null,
49
49
  },
50
50
  images: {
51
- formats: ["webp", "avif"],
51
+ formats: ["avif", "jpeg"],
52
52
  lazyLoad: true,
53
53
  optimize: true,
54
54
  picture: true,
55
- quality: { avif: 65, jpeg: 80, png: 80, webp: 80 },
55
+ quality: { avif: 65, jpeg: 80 },
56
56
  service: "build",
57
57
  sizes: "(max-width: 768px) 100vw, 50vw",
58
58
  widths: [320, 640, 960, 1280, 1920],
@@ -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,
@@ -44,7 +44,8 @@ import {
44
44
  pureSchemeOf,
45
45
  resolveStaticValue,
46
46
  serverCallHelperSource,
47
- srcImportBinding,
47
+ collectFunctionImports,
48
+ emitSrcImports,
48
49
  templateValueSource,
49
50
  } from "../shared.ts";
50
51
  import {
@@ -63,7 +64,7 @@ import {
63
64
  isTagExpression,
64
65
  tagNameCandidates,
65
66
  } from "@jxsuite/schema/guards";
66
- import type { CompileContext } from "../shared.ts";
67
+ import type { CompileContext, SrcImports } from "../shared.ts";
67
68
  import {
68
69
  escapeToken,
69
70
  objectKey,
@@ -154,9 +155,6 @@ export function compileClient(
154
155
  const initBlocks: string[] = []; // Lines emitted after state for prototype init
155
156
  const serverCalls: string[] = []; // One block per `timing: "server"` entry, after the computed block
156
157
 
157
- // Map $src path → Set of function names to import
158
- const srcImportMap = new Map<string, Set<string>>();
159
-
160
158
  const defs = raw.state ?? {};
161
159
  for (const [key, def] of Object.entries(defs)) {
162
160
  if (!isNonNullObject(def) || Array.isArray(def)) {
@@ -204,13 +202,6 @@ export function compileClient(
204
202
  onEntries.push([key, { args: ["state", "e"], body: compiled }]);
205
203
  }
206
204
  } else if (def.$src) {
207
- let names = srcImportMap.get(def.$src);
208
- if (!names) {
209
- names = new Set();
210
- srcImportMap.set(def.$src, names);
211
- }
212
- names.add(srcImportBinding(key, def));
213
-
214
205
  if (roles.get(key) === "computed") {
215
206
  // Only read, never called: its return value is what the page uses.
216
207
  computedEntries.push([key, `() => { return ${key}(state); }`]);
@@ -300,6 +291,7 @@ export function compileClient(
300
291
  }
301
292
 
302
293
  // Generate the JS module
294
+ const srcImports = collectFunctionImports(defs, roles);
303
295
  const moduleContent = emitClientModule(
304
296
  stateEntries,
305
297
  computedEntries,
@@ -307,7 +299,7 @@ export function compileClient(
307
299
  onEntries,
308
300
  initBlocks,
309
301
  serverCalls,
310
- srcImportMap,
302
+ srcImports,
311
303
  counter,
312
304
  reactivitySrc,
313
305
  opts.rewriteSrc,
@@ -917,7 +909,7 @@ function bareMapRefsToLit(body: string): string {
917
909
  * @param {[string, any][]} onEntries
918
910
  * @param {string[]} initBlocks
919
911
  * @param {string[]} serverCalls
920
- * @param {Map<string, Set<string>>} srcImportMap
912
+ * @param {SrcImports} srcImports
921
913
  * @param {{
922
914
  * t: number;
923
915
  * s: number;
@@ -937,7 +929,7 @@ function emitClientModule(
937
929
  onEntries: [string, HandlerDef][],
938
930
  initBlocks: string[],
939
931
  serverCalls: string[],
940
- srcImportMap: Map<string, Set<string>>,
932
+ srcImports: SrcImports,
941
933
  counter: {
942
934
  t: number;
943
935
  s: number;
@@ -970,15 +962,12 @@ function emitClientModule(
970
962
 
971
963
  // $src imports — bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/
972
964
  // Bundle URL; the site build bundles them after all documents compile (spec.md §12).
973
- for (const [src, names] of srcImportMap) {
974
- const importPath = rewriteSrc ? rewriteSrc(src) : src;
975
- lines.push(`import { ${[...names].join(", ")} } from '${importPath}';`);
976
- }
965
+ const src = emitSrcImports(srcImports, rewriteSrc);
977
966
 
978
967
  // State — reactive state
979
968
  /* The boolean-attribute rule, inlined because this module loads with `@vue/reactivity` and
980
969
  nothing else — see `attrHelperSource`. The hydration script below is its only caller. */
981
- lines.push("", attrHelperSource());
970
+ lines.push(...src.imports, ...src.loaders, "", attrHelperSource());
982
971
  if (serverCalls.length > 0) {
983
972
  lines.push("", serverCallHelperSource());
984
973
  }
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { erasedDocument } from "../erased.ts";
9
+ import { qualifyScripts } from "@jxsuite/schema/document-scripts";
9
10
  import {
10
11
  classifyFunctionEntries,
11
12
  declaresParameters,
@@ -14,6 +15,8 @@ import {
14
15
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
15
16
  import {
16
17
  ATTR_HELPER,
18
+ DEFAULT_LIT_HTML_SRC,
19
+ DEFAULT_REACTIVITY_SRC,
17
20
  attrHelperSource,
18
21
  booleanAttrValue,
19
22
  definitionHasSlot,
@@ -27,16 +30,17 @@ import {
27
30
  compileOperandSource,
28
31
  compileStatements,
29
32
  emitFormulaFn,
33
+ collectFunctionImports,
34
+ emitSrcImports,
30
35
  refuseBodyWithSrc,
31
36
  emitRequestFetch,
32
37
  emitServerCall,
33
38
  escapeHtml,
39
+ inheritProjectFormulas,
34
40
  isMutating,
35
41
  isSchemaOnly,
36
42
  rewriteState,
37
43
  serverCallHelperSource,
38
- srcExportName,
39
- srcImportBinding,
40
44
  tagNameToClassName,
41
45
  templateValueSource,
42
46
  } from "../shared.ts";
@@ -105,6 +109,20 @@ export interface CompileElementOptions {
105
109
  * so the base has to be known when it is compiled. Handed to every `$elements` dependency too.
106
110
  */
107
111
  serverBaseUrl?: string;
112
+ /**
113
+ * The project root, when the component is compiled as part of a project. With it, an entry naming
114
+ * its own document's script (`$src: "#client"`) reaches `rewriteSrc` qualified by the document's
115
+ * project-relative path (spec.md §23.2), for every `$elements` dependency too. Without it such a
116
+ * `$src` is emitted as written, and nothing can import it.
117
+ */
118
+ projectRoot?: string;
119
+ /**
120
+ * The project's `state`, when the component is compiled as part of a project. The component, and
121
+ * every `$elements` dependency, inherits the pure named formulas it reads from it (spec.md
122
+ * §13.4), each written into that component's own module. Without it a component is its own
123
+ * document.
124
+ */
125
+ projectState?: Record<string, JxStateDefinition> | undefined;
108
126
  }
109
127
 
110
128
  /**
@@ -152,6 +170,10 @@ export async function compileElement(
152
170
  }
153
171
  // Function bodies as JavaScript before anything analyses them (spec.md §23.1).
154
172
  doc = erasedDocument(doc, filePath);
173
+ if (opts.projectRoot !== undefined) {
174
+ const { relative } = await import("node:path");
175
+ doc = qualifyScripts(doc, relative(opts.projectRoot, filePath));
176
+ }
155
177
  } else {
156
178
  doc = erasedDocument(srcPath, srcPath.tagName ?? "a component");
157
179
  filePath = null;
@@ -163,6 +185,8 @@ export async function compileElement(
163
185
  }
164
186
  }
165
187
 
188
+ doc = inheritProjectFormulas(doc, opts.projectState);
189
+
166
190
  const { tagName } = doc;
167
191
  if (!tagName || !tagName.includes("-")) {
168
192
  throw new Error(`compileElement: tagName "${tagName}" must contain a hyphen`);
@@ -237,8 +261,8 @@ export async function compileElementPage(
237
261
  ) {
238
262
  const {
239
263
  title = "Jx App",
240
- reactivitySrc = "https://esm.sh/@vue/reactivity@3.5.13",
241
- litHtmlSrc = "https://esm.sh/lit-html@3.3.0",
264
+ reactivitySrc = DEFAULT_REACTIVITY_SRC,
265
+ litHtmlSrc = DEFAULT_LIT_HTML_SRC,
242
266
  } = opts;
243
267
 
244
268
  const result = await compileElement(sourcePath, opts);
@@ -338,50 +362,12 @@ export function emitElementModule(
338
362
  }
339
363
 
340
364
  // Collect $src imports from state entries before emitting other imports
341
- const srcImportMap = new Map<string, string[]>();
342
- /** `$lazy` `$src` modules → the (export, local binding) pairs each one supplies. */
343
- const lazySrcMap = new Map<string, { binding: string; exportName: string }[]>();
344
365
  const defs = doc.state ?? {};
345
366
  const roles = classifyFunctionEntries(doc);
346
- for (const [key, def] of Object.entries(defs)) {
347
- refuseBodyWithSrc(`state entry "${key}"`, def);
348
- if (isFunctionDef(def) && def.$src) {
349
- const srcPath = def.$src;
350
- if (def.$lazy === true) {
351
- /*
352
- * A computed reads its value synchronously, and a lazy binding can only ever hand back a
353
- * promise. Silently producing `computed(() => Promise)` would render "[object Promise]" in
354
- * whatever the template bound it to, so this is a build error rather than a surprise.
355
- */
356
- if (roles.get(key) === "computed") {
357
- throw new Error(
358
- `"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
359
- `A lazily loaded function resolves to a promise; a computed must resolve now. ` +
360
- `Remove "$lazy", or call ${key}() from a handler instead of binding its value.`,
361
- );
362
- }
363
- let lazyBindings = lazySrcMap.get(srcPath);
364
- if (!lazyBindings) {
365
- lazyBindings = [];
366
- lazySrcMap.set(srcPath, lazyBindings);
367
- }
368
- lazyBindings.push({ binding: key, exportName: srcExportName(key, def) });
369
- continue;
370
- }
371
- let bindings = srcImportMap.get(srcPath);
372
- if (!bindings) {
373
- bindings = [];
374
- srcImportMap.set(srcPath, bindings);
375
- }
376
- bindings.push(srcImportBinding(key, def));
377
- }
378
- }
379
- for (const [srcPath, names] of srcImportMap) {
380
- // Bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/ bundle URL;
381
- // The site build bundles them after all documents compile (spec.md §12).
382
- const importPath = rewriteSrc ? rewriteSrc(srcPath) : srcPath;
383
- lines.push(`import { ${names.join(", ")} } from '${importPath}';`);
384
- }
367
+ const srcImports = emitSrcImports(collectFunctionImports(defs, roles), rewriteSrc);
368
+ // Bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/ bundle URL;
369
+ // The site build bundles them after all documents compile (spec.md §12).
370
+ lines.push(...srcImports.imports);
385
371
 
386
372
  // `$prototype: "Request"` entries each get an auto-fetch effect in connectedCallback, plus the
387
373
  // Machinery to stop those effects again on disconnect. Both are emitted only when one exists, so
@@ -415,29 +401,9 @@ export function emitElementModule(
415
401
  lines.push(slotHelperSource());
416
402
  }
417
403
 
418
- /*
419
- * `$lazy` swaps the static import for a memoized dynamic one. A static import is a download, a
420
- * parse and an evaluate on every page that renders the component, whether or not anybody calls
421
- * the function: jxsuite.com's search client is 70 kB of MiniSearch fetched by every visitor, most
422
- * of whom never open search. The local binding keeps its name so every call site is unchanged;
423
- * what changes is that it now returns a promise.
424
- */
425
- let lazyIndex = 0;
426
- for (const [srcPath, entries] of lazySrcMap) {
427
- const importPath = rewriteSrc ? rewriteSrc(srcPath) : srcPath;
428
- const mod = `_jxLazy${lazyIndex}`;
429
- lazyIndex += 1;
430
- lines.push(
431
- `let ${mod};`,
432
- `const ${mod}Load = () => (${mod} ??= import('${importPath}'));`,
433
- ...entries.map(
434
- ({ binding, exportName }) =>
435
- `const ${binding} = (...args) => ${mod}Load().then((m) => m.${exportName}(...args));`,
436
- ),
437
- );
438
- }
439
-
404
+ // `$lazy` entries load on their first call instead of with the page (spec.md §5.3 4d).
440
405
  lines.push(
406
+ ...srcImports.loaders,
441
407
  "",
442
408
  `class ${className} extends HTMLElement {`,
443
409
  // One registry for every effect the element creates — render, dynamic host styles, Request
@@ -445,6 +411,7 @@ export function emitElementModule(
445
411
  // And a single list keeps every effect on the same lifecycle instead of leaking the ones nobody
446
412
  // Held a handle to.
447
413
  " #effects = [];",
414
+ " #rendered = false;",
448
415
  ...(shadow === null ? [] : [" #root = null;"]),
449
416
  "",
450
417
  // Constructor: build reactive state
@@ -757,8 +724,19 @@ export function emitElementModule(
757
724
  * `data-jx-prerendered` goes and before the clear: a prerendered instance's children are its
758
725
  * markup, and capture recovers what the prerender placed from its brackets instead.
759
726
  */
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;");
760
738
  if (hasSlot) {
761
- lines.push(` const _slotted = ${SLOT_CAPTURE_HELPER}(this);`);
739
+ lines.push(` const _slotted = _first ? ${SLOT_CAPTURE_HELPER}(this) : null;`);
762
740
  }
763
741
  lines.push(
764
742
  " if (this.hasAttribute('data-jx-prerendered')) {",
@@ -774,7 +752,7 @@ export function emitElementModule(
774
752
  * `require-trusted-types-for 'script'`, and this one is emitted into every light-DOM element
775
753
  * module a site ships.
776
754
  */
777
- " this.replaceChildren();",
755
+ " if (_first) this.replaceChildren();",
778
756
  " this.#effects.push(effect(() => render(this.template(), this)));",
779
757
  );
780
758
  } else {
@@ -793,15 +771,17 @@ export function emitElementModule(
793
771
  */
794
772
  lines.push(
795
773
  " const _root = this.#renderRoot();",
796
- " for (const _n of [..._root.childNodes]) {",
797
- " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
774
+ " if (_first) {",
775
+ " for (const _n of [..._root.childNodes]) {",
776
+ " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
777
+ " }",
798
778
  " }",
799
779
  " this.#effects.push(effect(() => render(this.template(), _root)));",
800
780
  );
801
781
  }
802
782
  if (hasSlot) {
803
783
  // Once, after the first render: a slot a later render draws stays literal (spec.md §8.5).
804
- lines.push(` ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
784
+ lines.push(` if (_first) ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
805
785
  }
806
786
  lines.push(
807
787
  // Lifecycle: onMount (spec §16.4) — same microtask contract as the runtime
@@ -123,12 +123,15 @@ export function compileSiteServer(
123
123
  */
124
124
  const localeBlock = localeNegotiationMiddleware(i18n);
125
125
 
126
+ const gateBlock =
127
+ entries.length === 0 && mounts.length === 0 ? "" : buildRequestGate(base, baseUrl);
128
+
126
129
  return `// Generated by @jxsuite/compiler — do not edit manually
127
130
  import { Hono } from 'hono'
128
131
  ${imports}${mountBlock.imports}
129
132
 
130
133
  const app = new Hono()
131
- ${localeBlock}${mountBlock.routes}${routes}
134
+ ${localeBlock}${gateBlock}${mountBlock.routes}${routes}
132
135
  ${adapterBlock}
133
136
  export default app
134
137
  `;
@@ -176,15 +179,59 @@ function buildMountBlock(mounts: SiteMountSpec[], connectors: SiteConnectorSpec[
176
179
  return { imports: `\n${importLines.join("\n")}`, routes: `${lines.join("\n")}\n` };
177
180
  }
178
181
 
182
+ /** The subtree every extension mount lives under (`extension-registry.ts` enforces it). */
183
+ const JX_ROUTE_ROOT = "/_jx";
184
+
185
+ /**
186
+ * Emit the request gate: middleware in front of every server function and extension mount
187
+ * (compiler.md §6.4), registered before them so a refused request never reaches a handler.
188
+ *
189
+ * It reads Fetch Metadata the way the dev server's gate does (`packages/server/src/net-guard.ts`),
190
+ * with one difference: a navigation is let through whatever its method, because an identity
191
+ * provider answering with `response_mode=form_post` is a cross-site POST navigation to the auth
192
+ * mount. A form a hostile page submits arrives the same way, and is refused one layer down: every
193
+ * route that takes a body requires `application/json`, which no HTML form can send.
194
+ *
195
+ * @param {string} base - The deployment base
196
+ * @param {string} baseUrl - The server-function prefix, already under the base
197
+ * @returns {string}
198
+ */
199
+ function buildRequestGate(base: string, baseUrl: string): string {
200
+ const root = withBase(base, JX_ROUTE_ROOT);
201
+ const prefixes = baseUrl === root || baseUrl.startsWith(`${root}/`) ? [root] : [root, baseUrl];
202
+ const uses = prefixes.map((prefix) => `app.use('${prefix}/*', jxGate)`).join("\n");
203
+ return `// Request gate (specs/compiler.md §6.4): another site may link here, never call here.
204
+ const jxGate = async (c, next) => {
205
+ const site = c.req.header('sec-fetch-site')
206
+ const foreign = site !== undefined && site !== 'same-origin' && site !== 'none'
207
+ if (foreign && c.req.header('sec-fetch-mode') !== 'navigate') {
208
+ return c.json({ ok: false, error: 'Cross-site request refused' }, 403, {
209
+ 'Cache-Control': 'no-store',
210
+ 'X-Content-Type-Options': 'nosniff',
211
+ })
212
+ }
213
+ await next()
214
+ c.header('X-Content-Type-Options', 'nosniff')
215
+ c.header('Cross-Origin-Resource-Policy', 'same-origin')
216
+ if (!c.res.headers.has('Cache-Control')) c.header('Cache-Control', 'no-store')
217
+ }
218
+ ${uses}
219
+ `;
220
+ }
221
+
179
222
  /** @param {string} exportName @param {string} baseUrl */
180
223
  function buildRoute(exportName: string, baseUrl: string) {
181
224
  return `
182
225
  app.post('${baseUrl}/${exportName}', async (c) => {
226
+ if (!/^application\\/([\\w.-]+\\+)?json\\b/i.test(c.req.header('content-type') ?? '')) {
227
+ return c.json({ ok: false, error: 'Expected an application/json body' }, 415)
228
+ }
183
229
  const args = await c.req.json().catch(() => ({}))
184
230
  try {
185
231
  return c.json((await ${exportName}(args, c.env)) ?? null)
186
232
  } catch (e) {
187
- return c.json({ ok: false, error: e?.message ?? 'Server error' }, 500)
233
+ console.error('jx: server function ${exportName} threw:', e)
234
+ return c.json({ ok: false, error: 'Server error' }, 500)
188
235
  }
189
236
  })`;
190
237
  }