@jxsuite/compiler 9.0.1 → 10.0.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.
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Compile-pack — a directory of component documents as one distributable element pack.
3
+ *
4
+ * `compileElement` compiles one definition (and the `$elements` it names). A component library is
5
+ * many definitions that name each other, shipped together and used without a site build around
6
+ * them, so the pieces a site build would have written beside the modules have to come from the same
7
+ * call: each definition's stylesheet, one entry that registers them all, and the Custom Elements
8
+ * Manifest that says what each one takes (spec.md §16.8).
9
+ *
10
+ * It writes nothing. The result is a list of files with paths relative to the pack's own directory,
11
+ * which `writeElementPack` lays out, or which a caller hands to a bundler first (the `@jxsuite/ui`
12
+ * distribution does, to compile its TypeScript behaviour modules into the pack).
13
+ *
14
+ * @docs framework/build
15
+ */
16
+
17
+ import { cemManifest, cemManifestText } from "@jxsuite/schema/cem-manifest";
18
+ import type { CemDefinition, CemPackageOut } from "@jxsuite/schema/cem-manifest";
19
+ import { isString } from "@jxsuite/schema/guards";
20
+ import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
21
+ import type { JxDocument, ProjectConfig } from "@jxsuite/schema/types";
22
+ import { resolveShadowMode } from "../shadow.ts";
23
+ import type { GeneratedFile } from "../site/well-known.ts";
24
+ import { buildComponentCSS, orderComponentTags, tagNameToClassName } from "../shared.ts";
25
+ import { compileElement } from "./compile-element.ts";
26
+ import type { CompileElementOptions } from "./compile-element.ts";
27
+
28
+ /** Options accepted by {@link compileElementPack}. */
29
+ export interface ElementPackOptions {
30
+ /**
31
+ * The component documents: a directory, of which every document directly inside is compiled, or
32
+ * the files themselves. A file with no hyphenated `tagName` is not a component and is refused.
33
+ */
34
+ components: string | readonly string[];
35
+ /**
36
+ * The pack's own directory, relative to the package root, with `/` separators: where the caller
37
+ * will serve or publish the files from. It prefixes each module path in the manifest, whose paths
38
+ * are read against the package root (spec.md §16.8). Default `"dist"`.
39
+ */
40
+ packDir?: string;
41
+ /**
42
+ * Rewrite a Function entry's `$src` specifier to the specifier the compiled module imports.
43
+ * Receives the directory of the declaring document. Identity when omitted, so a relative `$src`
44
+ * must then be reachable from the pack's directory as written.
45
+ */
46
+ rewriteSrc?: (specifier: string, docDir: string | null) => string;
47
+ /** Named media queries every definition resolves its `@--name` blocks against. */
48
+ $media?: Record<string, string>;
49
+ /** Project `defaults`, read for `defaults.shadow` (spec.md §16.6). */
50
+ defaults?: ProjectConfig["defaults"];
51
+ }
52
+
53
+ /** A compiled pack: what {@link writeElementPack} lays out. */
54
+ export interface ElementPack {
55
+ /**
56
+ * Each with its path relative to the pack's directory: `<tag>.js` per definition, `<tag>.css` per
57
+ * definition that has styles, `index.js`, `elements.css` and `custom-elements.json`.
58
+ */
59
+ files: GeneratedFile[];
60
+ /** The tags compiled, each after the tags it renders. */
61
+ tags: string[];
62
+ manifest: CemPackageOut;
63
+ /** The manifest generator's warnings (spec.md §16.8). */
64
+ warnings: string[];
65
+ }
66
+
67
+ /** The name of the module that registers every element of a pack. */
68
+ export const PACK_ENTRY = "index.js";
69
+
70
+ /** The name of the stylesheet holding every light-DOM definition's rules. */
71
+ export const PACK_STYLESHEET = "elements.css";
72
+
73
+ /** The name of the pack's Custom Elements Manifest. */
74
+ export const PACK_MANIFEST = "custom-elements.json";
75
+
76
+ /** The component documents a pack is compiled from, as absolute paths in a stable order. */
77
+ async function componentPaths(components: string | readonly string[]): Promise<string[]> {
78
+ const { readdirSync } = await import("node:fs");
79
+ const { resolve } = await import("node:path");
80
+ if (!isString(components)) {
81
+ return components.map((path) => resolve(path));
82
+ }
83
+ return readdirSync(components)
84
+ .filter((name) => isNativeDocumentPath(name))
85
+ .toSorted()
86
+ .map((name) => resolve(components, name));
87
+ }
88
+
89
+ /** A component document as its file holds it. A pack compiles native documents only. */
90
+ async function readComponent(path: string) {
91
+ const { readFileSync } = await import("node:fs");
92
+ if (!isNativeDocumentPath(path)) {
93
+ throw new Error(
94
+ `compileElementPack: ${path} is not a .json or .jxn document, the two a pack compiles`,
95
+ );
96
+ }
97
+ return parseNativeDocument(readFileSync(path, "utf8"), path);
98
+ }
99
+
100
+ /**
101
+ * Compile every component document of a library into one pack (compiler.md §4.9): a module per
102
+ * definition, a stylesheet per definition, the entry that registers them all, and their Custom
103
+ * Elements Manifest.
104
+ *
105
+ * Each module is the one `compileElement` emits, importing the definitions it names in `$elements`
106
+ * as its siblings (`./<tag>.js`), so importing one element registers what it renders, and importing
107
+ * the entry registers the pack in dependency order.
108
+ *
109
+ * @param options
110
+ */
111
+ export async function compileElementPack(options: ElementPackOptions): Promise<ElementPack> {
112
+ const { resolve } = await import("node:path");
113
+ const packDir = (options.packDir ?? "dist").replaceAll(/^\.?\/+|\/+$/gu, "");
114
+ const paths = await componentPaths(options.components);
115
+
116
+ // Every definition by tag first: a module names its siblings by tag, wherever their files are.
117
+ const definitions = new Map<string, JxDocument>();
118
+ const tagByPath = new Map<string, string>();
119
+ for (const path of paths) {
120
+ const doc = await readComponent(path);
121
+ const { tagName } = doc;
122
+ if (!isString(tagName) || !tagName.includes("-")) {
123
+ throw new Error(
124
+ `compileElementPack: ${path} is not a component: its tagName must contain a hyphen`,
125
+ );
126
+ }
127
+ const earlier = [...tagByPath].find(([, tag]) => tag === tagName);
128
+ if (earlier) {
129
+ throw new Error(
130
+ `compileElementPack: ${earlier[0]} and ${path} both declare the tagName "${tagName}"`,
131
+ );
132
+ }
133
+ definitions.set(tagName, doc);
134
+ tagByPath.set(path, tagName);
135
+ }
136
+
137
+ const elementOptions: CompileElementOptions = {
138
+ /* A pack is used with no prerender around it, so a shadow definition's root is always one its
139
+ module attaches, and the sheet it must link is the sibling written below. */
140
+ stylesheetHref: (tag) => `./${tag}.css`,
141
+ resolveElementPath: (refPath, currentDir) => {
142
+ const target = currentDir === null ? resolve(refPath) : resolve(currentDir, refPath);
143
+ const tag = tagByPath.get(target);
144
+ if (tag === undefined) {
145
+ throw new Error(
146
+ `compileElementPack: "${refPath}" names a component outside the pack (${target})`,
147
+ );
148
+ }
149
+ return `./${tag}.js`;
150
+ },
151
+ };
152
+ if (options.rewriteSrc) {
153
+ elementOptions.rewriteSrc = options.rewriteSrc;
154
+ }
155
+ if (options.$media) {
156
+ elementOptions.$media = options.$media;
157
+ }
158
+ if (options.defaults) {
159
+ elementOptions.defaults = options.defaults;
160
+ }
161
+
162
+ const modules = new Map<string, string>();
163
+ for (const path of paths) {
164
+ const { files } = await compileElement(path, elementOptions);
165
+ // A definition's `$elements` come back with it; each is the same module whoever asked.
166
+ for (const file of files) {
167
+ if (!modules.has(file.tagName)) {
168
+ modules.set(file.tagName, file.content);
169
+ }
170
+ }
171
+ }
172
+
173
+ const tags = orderComponentTags([...definitions.keys()], definitions);
174
+ const files: GeneratedFile[] = [];
175
+ const lightSheets: string[] = [];
176
+ const manifestDefinitions: CemDefinition[] = [];
177
+ for (const tag of tags) {
178
+ const doc = definitions.get(tag);
179
+ const module = modules.get(tag);
180
+ // `tags` orders `definitions`' own keys, each compiled above; the guard is for the types.
181
+ if (!doc || module === undefined) {
182
+ continue;
183
+ }
184
+ files.push({ content: module, path: `${tag}.js` });
185
+ const shadow = resolveShadowMode(doc, options.defaults);
186
+ const css = buildComponentCSS(tag, doc.style, doc, options.$media ?? doc.$media ?? {}, shadow);
187
+ if (css !== "") {
188
+ files.push({ content: css, path: `${tag}.css` });
189
+ /* A shadow definition's sheet is linked from inside its own root, where the document's
190
+ stylesheets do not reach, so it stays out of the one a page links. */
191
+ if (shadow === null) {
192
+ lightSheets.push(css);
193
+ }
194
+ }
195
+ manifestDefinitions.push({
196
+ className: tagNameToClassName(tag),
197
+ doc,
198
+ modulePath: packDir === "" ? `${tag}.js` : `${packDir}/${tag}.js`,
199
+ shadow: shadow !== null,
200
+ tagName: tag,
201
+ });
202
+ }
203
+
204
+ const { manifest, warnings } = cemManifest(manifestDefinitions);
205
+ files.push(
206
+ {
207
+ content: `// Generated by @jxsuite/compiler — do not edit manually\n${tags
208
+ .map((tag) => `import './${tag}.js';`)
209
+ .join("\n")}\n`,
210
+ path: PACK_ENTRY,
211
+ },
212
+ { content: lightSheets.join(""), path: PACK_STYLESHEET },
213
+ { content: cemManifestText(manifest), path: PACK_MANIFEST },
214
+ );
215
+ return { files, manifest, tags, warnings };
216
+ }
217
+
218
+ /**
219
+ * Write a pack's files under a directory, creating it as needed.
220
+ *
221
+ * @param pack
222
+ * @param outDir
223
+ * @returns The absolute path of each file written, in the pack's order
224
+ */
225
+ export async function writeElementPack(pack: ElementPack, outDir: string): Promise<string[]> {
226
+ const { mkdirSync, writeFileSync } = await import("node:fs");
227
+ const { dirname, resolve } = await import("node:path");
228
+ return pack.files.map((file) => {
229
+ const target = resolve(outDir, file.path);
230
+ mkdirSync(dirname(target), { recursive: true });
231
+ writeFileSync(target, file.content, "utf8");
232
+ return target;
233
+ });
234
+ }
@@ -1,26 +1,27 @@
1
1
  /**
2
2
  * Compile-static.js — Static HTML compilation
3
3
  *
4
- * Compiles fully static Jx documents to plain HTML/CSS with zero JS. Dynamic child subtrees become
5
- * hydration islands (custom elements).
4
+ * Compiles a document `isDynamic` judged static to plain HTML/CSS with zero JS. `compile()` routes
5
+ * nothing else here: a document with any dynamic node, at any depth, is compiled whole by
6
+ * `compile-client.ts` (compiler.md §8.1, §9.1).
6
7
  */
7
8
 
8
9
  import {
9
10
  buildAttrs,
10
11
  childSeparator,
12
+ contentPropertyText,
11
13
  colorSchemePrePaintScript,
12
14
  compileStyles,
13
15
  createCompileContext,
14
16
  escapeHtml,
15
- isNodeDynamic,
16
17
  PREFORMATTED_TAGS,
17
18
  pureSchemeOf,
18
19
  resolveStaticTagName,
20
+ isExpandedInstance,
19
21
  resolveStaticValue,
20
22
  SELF_CLOSING,
21
23
  } from "../shared.ts";
22
24
  import type { CompileContext } from "../shared.ts";
23
- import { emitElementModule } from "./compile-element.ts";
24
25
  import { isBoolean, isNonNullObject, isNumber, isString } from "@jxsuite/schema/guards";
25
26
  import type { JsonPrimitive, JxDocument, JxMutableNode, JxStyle } from "@jxsuite/schema/types";
26
27
 
@@ -30,67 +31,36 @@ import type { JsonPrimitive, JxDocument, JxMutableNode, JxStyle } from "@jxsuite
30
31
  */
31
32
  type StaticChild = JxMutableNode | JsonPrimitive;
32
33
 
33
- /** A dynamic subtree lifted out of the static page, emitted as its own element module. */
34
- interface Island {
35
- def: JxDocument;
34
+ /** A file a compilation emits beside its HTML; the static target emits none. */
35
+ interface EmittedFile {
36
+ path: string;
37
+ content: string;
36
38
  tagName: string;
37
- className: string;
38
39
  }
39
40
 
40
41
  /**
41
- * Compile a static document to HTML, with dynamic subtrees as islands.
42
+ * Compile a static document to HTML. The page carries no module, import map or script: `files` is
43
+ * always empty, and is returned so every route of `compile()` has one shape.
42
44
  *
43
45
  * @param {JxDocument} raw - Raw JSON document (with $ref pointers preserved)
44
- * @param opts - Page title, CDN sources, project style, pre-paint switch and island `$src`
45
- * rewriting
46
+ * @param opts - Page title, project style and pre-paint switch
46
47
  * @returns {{ html: string; files: { path: string; content: string; tagName: string }[] }}
47
48
  */
48
49
  export function compileStaticPage(
49
50
  raw: JxDocument,
50
51
  opts: {
51
52
  title?: string;
52
- reactivitySrc?: string;
53
- litHtmlSrc?: string;
54
53
  projectStyle?: JxStyle | null;
55
54
  prePaintScheme?: boolean;
56
- /** Rewrite an island's Function-def `$src` specifier to its served URL. */
57
- rewriteSrc?: (specifier: string) => string;
58
55
  },
59
56
  ) {
60
- const { title = "Jx App", reactivitySrc, litHtmlSrc } = opts;
57
+ const { title = "Jx App" } = opts;
61
58
 
62
59
  const rootContext = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {});
63
60
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
64
- const islands: Island[] = [];
65
- const bodyContent = compileNode(raw, false, rootContext, islands);
66
-
67
- /** @type {{ path: string; content: string; tagName: string }[]} */
68
- const files = [];
69
- let importMap = "";
70
- let moduleScripts = "";
71
- if (islands.length > 0) {
72
- for (const island of islands) {
73
- const moduleContent = emitElementModule(island.def, island.className, [], opts.rewriteSrc);
74
- files.push({
75
- content: moduleContent,
76
- path: `_islands/${island.tagName}.js`,
77
- tagName: island.tagName,
78
- });
79
- }
80
- importMap = `<script type="importmap">
81
- {
82
- "imports": {
83
- "@vue/reactivity": "${reactivitySrc}",
84
- "lit-html": "${litHtmlSrc}"
85
- }
86
- }
87
- </script>`;
88
- moduleScripts = files
89
- .map(
90
- (/** @type {{ path: string }} */ f) => `<script type="module" src="./${f.path}"></script>`,
91
- )
92
- .join("\n ");
93
- }
61
+ const bodyContent = compileNode(raw, rootContext);
62
+
63
+ const files: EmittedFile[] = [];
94
64
 
95
65
  // Forced-scheme contract (spec §9.5): restore the persisted scheme before any styles apply
96
66
  const prePaint =
@@ -105,12 +75,11 @@ export function compileStaticPage(
105
75
  <meta charset="utf-8">
106
76
  <meta name="viewport" content="width=device-width, initial-scale=1">
107
77
  <title>${escapeHtml(title)}</title>
108
- ${prePaint}${importMap}
78
+ ${prePaint}
109
79
  ${styleBlock}
110
80
  </head>
111
81
  <body>
112
82
  ${bodyContent}
113
- ${moduleScripts}
114
83
  </body>
115
84
  </html>`;
116
85
 
@@ -120,24 +89,13 @@ export function compileStaticPage(
120
89
  // ─── Node compilation ─────────────────────────────────────────────────────────
121
90
 
122
91
  /**
123
- * Compile a single Jx node to an HTML string. Dynamic nodes become hydration islands; static nodes
124
- * become plain HTML.
125
- *
126
- * The node is read as authored — `$ref` pointers preserved — because an island's element module
127
- * resolves them itself at runtime.
92
+ * Compile a single Jx node to an HTML string.
128
93
  *
129
94
  * @param {StaticChild} def
130
- * @param {boolean} dynamic
131
95
  * @param {CompileContext} context
132
- * @param {Island[]} islands
133
96
  * @returns {string}
134
97
  */
135
- function compileNode(
136
- def: StaticChild,
137
- dynamic: boolean,
138
- context: CompileContext,
139
- islands: Island[],
140
- ): string {
98
+ function compileNode(def: StaticChild, context: CompileContext): string {
141
99
  // String children are text nodes
142
100
  if (isString(def)) {
143
101
  return escapeHtml(def);
@@ -156,18 +114,6 @@ function compileNode(
156
114
  def.$media ?? context.media,
157
115
  );
158
116
 
159
- if (dynamic) {
160
- const n = islands.length;
161
- const tagName = `jx-island-${n}`;
162
- const className = `JxIsland${n}`;
163
- /* SAFETY: JxDocument is the element-node shape with `tagName` narrowed to a literal string,
164
- and the island's `tagName` is the literal `jx-island-N` assigned here; every other member is
165
- the authored node's own, carried over unchanged. */
166
- const elementDef = { ...def, tagName } as JxDocument;
167
- islands.push({ className, def: elementDef, tagName });
168
- return `<${tagName}></${tagName}>`;
169
- }
170
-
171
117
  // Resolved against the same scope the attributes are, so the prerendered element and its
172
118
  // Attributes come from one decision rather than two.
173
119
  const tag = resolveStaticTagName(def.tagName, nextContext.scope);
@@ -181,37 +127,41 @@ function compileNode(
181
127
 
182
128
  // `white-space` inherits, so once inside a <pre> the whole subtree stays whitespace-significant.
183
129
  const preformatted = context.preformatted === true || PREFORMATTED_TAGS.has(tag);
184
- const inner = buildInnerWithIslands(def, { ...nextContext, preformatted }, islands);
130
+ const inner = buildStaticInner(def, tag, { ...nextContext, preformatted });
185
131
 
186
132
  return `<${tag}${attrs}>${inner}</${tag}>`;
187
133
  }
188
134
 
189
135
  /**
190
- * Build the inner HTML (textContent or children) for a node. For children, emit islands only for
191
- * those that are actually dynamic.
136
+ * Build the inner HTML (textContent, innerHTML, a content property or children) for a node.
192
137
  *
193
138
  * @param {JxMutableNode} def
139
+ * @param {string} tag - The node's resolved tag
194
140
  * @param {CompileContext} context
195
- * @param {Island[]} islands
196
141
  * @returns {string}
197
142
  */
198
- function buildInnerWithIslands(
199
- def: JxMutableNode,
200
- context: CompileContext,
201
- islands: Island[],
202
- ): string {
143
+ function buildStaticInner(def: JxMutableNode, tag: string, context: CompileContext): string {
203
144
  if (def.textContent !== undefined) {
204
145
  const value = resolveStaticValue(def.textContent, context.scope);
205
146
  return value == null ? "" : escapeHtml(String(value));
206
147
  }
207
148
  if (def.innerHTML) {
149
+ // An expanded instance's markup is finished HTML, never a template (`isExpandedInstance`).
150
+ if (isExpandedInstance(def)) {
151
+ return def.innerHTML;
152
+ }
208
153
  // Raw HTML may itself be a template; one that resolves to nothing keeps its authored text.
209
154
  const resolved = resolveStaticValue(def.innerHTML, context.scope);
210
155
  return resolved == null ? def.innerHTML : String(resolved);
211
156
  }
157
+ // A content property is the element's text (spec.md §8.1).
158
+ const content = contentPropertyText(def, tag, context.scope);
159
+ if (content !== undefined) {
160
+ return content;
161
+ }
212
162
  if (Array.isArray(def.children)) {
213
163
  return def.children
214
- .map((child) => compileNode(child, isNodeDynamic(child), context, islands))
164
+ .map((child) => compileNode(child, context))
215
165
  .join(childSeparator(context.preformatted));
216
166
  }
217
167
  return "";