@openelement/compiler 1.0.0-alpha.14 → 1.0.0-alpha.16

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.
Files changed (56) hide show
  1. package/package.json +4 -2
  2. package/src/compiler.d.ts +12 -6
  3. package/src/compiler.js +11 -6
  4. package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +11 -0
  5. package/src/internal/compiler/compiled-artifact-class-candidates.js +46 -0
  6. package/src/internal/compiler/compiled-artifact-style-requests.d.ts +26 -7
  7. package/src/internal/compiler/compiled-artifact-style-requests.js +57 -9
  8. package/src/internal/compiler/plugin.d.ts +68 -49
  9. package/src/internal/compiler/plugin.js +93 -82
  10. package/src/internal/compiler/semantic-core/analyze-module.d.ts +73 -0
  11. package/src/internal/compiler/semantic-core/analyze-module.js +29 -379
  12. package/src/internal/compiler/semantic-core/attribute-classification.js +92 -0
  13. package/src/internal/compiler/semantic-core/compiler-diagnostics.js +2 -16
  14. package/src/internal/compiler/semantic-core/diagnostics/index.d.ts +21 -1
  15. package/src/internal/compiler/semantic-core/diagnostics/index.js +32 -1
  16. package/src/internal/compiler/semantic-core/expression-lowering.js +469 -0
  17. package/src/internal/compiler/semantic-core/expression-registry.js +165 -0
  18. package/src/internal/compiler/semantic-core/function-frontend.js +1229 -0
  19. package/src/internal/compiler/semantic-core/island-policy-statement.js +52 -0
  20. package/src/internal/compiler/semantic-core/jsx-module-id.d.ts +4 -0
  21. package/src/internal/compiler/semantic-core/jsx-module-id.js +7 -0
  22. package/src/internal/compiler/semantic-core/lower-program.d.ts +220 -0
  23. package/src/internal/compiler/semantic-core/lower-program.js +350 -142
  24. package/src/internal/compiler/semantic-core/module-analysis.d.ts +82 -4
  25. package/src/internal/compiler/semantic-core/module-analysis.js +88 -19
  26. package/src/internal/compiler/semantic-core/parse-module.js +16 -16
  27. package/src/internal/compiler/semantic-core/scope-resolution.d.ts +208 -0
  28. package/src/internal/compiler/semantic-core/scope-resolution.js +1121 -0
  29. package/src/internal/compiler/semantic-core/server-component.d.ts +129 -0
  30. package/src/internal/compiler/semantic-core/server-component.js +587 -0
  31. package/src/internal/compiler/semantic-core/type-check.js +1 -1
  32. package/src/internal/compiler/semantic-core/type-erasure.js +156 -0
  33. package/src/internal/compiler/semantic-ir/generated-element/compile.d.ts +61 -0
  34. package/src/internal/compiler/semantic-ir/generated-element/compile.js +137 -0
  35. package/src/internal/compiler/semantic-ir/generated-element/contract.d.ts +201 -0
  36. package/src/internal/compiler/semantic-ir/generated-element/contract.js +147 -0
  37. package/src/internal/compiler/semantic-ir/generated-element/emit.js +452 -0
  38. package/src/internal/compiler/semantic-ir/generated-element/site.js +1195 -0
  39. package/src/internal/compiler/semantic-ir/generated-leaf/claim-emission.js +1372 -0
  40. package/src/internal/compiler/semantic-ir/generated-leaf/codegen-literals.js +31 -0
  41. package/src/internal/compiler/semantic-ir/generated-leaf/component-emission.js +647 -0
  42. package/src/internal/compiler/semantic-ir/generated-leaf/emission.js +388 -0
  43. package/src/internal/compiler/semantic-ir/generated-leaf/generate.js +395 -0
  44. package/src/internal/compiler/semantic-ir/generated-leaf/instance-emission.js +865 -0
  45. package/src/internal/compiler/semantic-ir/generated-leaf/mount-emission.js +960 -0
  46. package/src/internal/compiler/semantic-ir/generated-leaf/server-emission.js +1011 -0
  47. package/src/internal/compiler/semantic-ir/generated-leaf/structure.js +714 -0
  48. package/src/internal/compiler/style-requests.d.ts +35 -7
  49. package/src/internal/compiler/style-requests.js +57 -11
  50. package/src/internal/compiler/tailwind-candidates.d.ts +84 -0
  51. package/src/internal/compiler/tailwind-candidates.js +54 -0
  52. package/src/internal/compiler/semantic-core/compile.d.ts +0 -39
  53. package/src/internal/compiler/semantic-core/compile.js +0 -98
  54. package/src/internal/compiler/semantic-core/emit-module.js +0 -313
  55. package/src/internal/compiler/semantic-core/emit-program.js +0 -121
  56. package/src/internal/compiler/semantic-core/style-imports.js +0 -87
@@ -0,0 +1,587 @@
1
+ import { CompiledElementError, failAt } from "./compiler-diagnostics.js";
2
+ import { isJsxModuleId } from "./jsx-module-id.js";
3
+ import { analyzeModuleSemantics, createModuleIntrinsicBindings, isExportedServerComponentDeclaration, serverComponentName } from "./module-analysis.js";
4
+ import { Lowering } from "./lower-program.js";
5
+ import { SourceMapSegmentBuilder } from "./source-map.js";
6
+ import { authoredPropsType, typescriptParser } from "./parse-module.js";
7
+ import ts from "typescript";
8
+ //#region src/internal/compiler/semantic-core/server-component.ts
9
+ /**
10
+ * Server-only TSX function components (alpha15 server lane): the admission
11
+ * and generative lowering entry.
12
+ *
13
+ * A server function component is an exported function whose body is a single
14
+ * return of JSX — the compiled render() grammar's own subset (one semantic
15
+ * authority: the SAME `Lowering` walk the @element class path runs, with the
16
+ * props parameter as the field accessor; the same attribute-name safety, sink
17
+ * denial, trustedHtml boundary and OEC diagnostics — no parallel checker
18
+ * exists). What differs is only the OUTPUT: instead of a Part Program, the
19
+ * admitted JSX lowers to a plain exported TS function whose body composes the
20
+ * element server runtime's constructor helpers:
21
+ *
22
+ * __h("article", { class: "card" }, [__h("h2", {}, [__t(props.name)])])
23
+ *
24
+ * - dynamic text rides `__t` (the ONE DSD-serializer escapeText);
25
+ * - attribute values cross `__h`'s one `escapeAttr` + shared URL screen;
26
+ * - a build-admitted @element compiled host rides `__ssr(tag, props)` — the
27
+ * component path's literal runtime function;
28
+ * - an island or foreign custom host emits its tag as-is (the existing island
29
+ * admission pipeline owns it);
30
+ * - a nested server function component composes by DIRECT function call to
31
+ * the imported binding, resolved from the authored imports at compile time
32
+ * (deterministic — the host hands the compiler the imported sources).
33
+ * An async child is awaited by an async parent; a synchronous parent of an
34
+ * async child is refused. Await inside the single returned JSX is admitted
35
+ * only in the bounded full-await grammar (text children and nested props).
36
+ *
37
+ * The artifact is generated TS — not an IR, not an interpreter, no Part
38
+ * Program, no element class, no client graph edge.
39
+ *
40
+ * Discovery is compiler-exclusive: `analyzeModuleSemantics` reports the
41
+ * module's exported JSX functions (the cheap fact a graph walker reads); THIS
42
+ * entry is the admission authority the host build calls for the modules it
43
+ * finds reachable from its page modules. Route-side wiring is a later lane.
44
+ */
45
+ /** The helper names the generated module binds from '@openelement/element/server'. */
46
+ const SERVER_HELPERS = [
47
+ "__h",
48
+ "__t",
49
+ "__ssr"
50
+ ];
51
+ /** The one identifier shape the generated module may carry (see `identifier`). */
52
+ const CODEGEN_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
53
+ const SERVER_HELPER_SPECIFIER = "@openelement/element/server";
54
+ /** Map one inline props-type member annotation to the walk's property-type labels. */
55
+ function propsTypeOf(type) {
56
+ if (type === void 0) return "string";
57
+ const text = type.getText().replace(/\s/g, "");
58
+ if (text === "string" || text === "String") return "string";
59
+ if (text === "number" || text === "Number") return "number";
60
+ if (text === "boolean" || text === "Boolean") return "boolean";
61
+ if (text.includes("TrustedHtml")) return "object";
62
+ if (/^(Array|ReadonlyArray|Set)</.test(text) || text.endsWith("[]")) return "array";
63
+ if (/^(Record|Map|Object)</.test(text)) return "object";
64
+ return "string";
65
+ }
66
+ /**
67
+ * True when the annotation is exactly `Promise<...>` (M14-2: "a Promise is not
68
+ * a normal child"). The only type fact this lane reads — it is NOT a type
69
+ * checker: `Promise<T>[]`, aliases and conditional types stay unknown.
70
+ */
71
+ function isPromiseAnnotation(type) {
72
+ if (type === void 0) return false;
73
+ let node = type;
74
+ while (ts.isParenthesizedTypeNode(node)) node = node.type;
75
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.text === "Promise";
76
+ }
77
+ /** Build the synthetic field table one props type literal admits. */
78
+ function fieldsOfPropsType(typeNode, fail) {
79
+ if (typeNode === void 0) return {
80
+ fields: [],
81
+ promiseFields: /* @__PURE__ */ new Set()
82
+ };
83
+ let literal = typeNode;
84
+ while (ts.isParenthesizedTypeNode(literal)) literal = literal.type;
85
+ if (!ts.isTypeLiteralNode(literal)) fail(typeNode, "OEC9032", "the props parameter must be annotated inline as an object type literal (props: { name: string }) — type aliases and interfaces are outside the server function grammar");
86
+ const fields = [];
87
+ const promiseFields = /* @__PURE__ */ new Set();
88
+ for (const member of literal.members) {
89
+ if (!ts.isPropertySignature(member) || !ts.isIdentifier(member.name)) fail(member, "OEC9032", "the props type admits property signatures only");
90
+ if (isPromiseAnnotation(member.type)) promiseFields.add(member.name.text);
91
+ const label = propsTypeOf(member.type);
92
+ fields.push({
93
+ name: member.name.text,
94
+ reflect: false,
95
+ attribute: null,
96
+ type: label,
97
+ converter: label,
98
+ typeConstructor: "String",
99
+ accessibility: "",
100
+ typeText: member.type ? `: ${member.type.getText()}` : "",
101
+ initializerText: "",
102
+ defaultValue: null,
103
+ node: member
104
+ });
105
+ }
106
+ return {
107
+ fields,
108
+ promiseFields
109
+ };
110
+ }
111
+ /** One component's admitted shape, with the diagnostics every other shape rejects. */
112
+ function admitComponent(statement, fail) {
113
+ const name = serverComponentName(statement);
114
+ if (ts.isFunctionDeclaration(statement)) {
115
+ const isAsync = (ts.getModifiers(statement) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword);
116
+ if (statement.typeParameters?.length) fail(statement, "OEC9032", `server function component ${name} may not declare type parameters`);
117
+ if (statement.body === void 0 || !ts.isBlock(statement.body)) fail(statement, "OEC9032", `server function component ${name} must have a body`);
118
+ const returns = statement.body.statements.filter(ts.isReturnStatement);
119
+ if (statement.body.statements.length !== 1 || returns.length !== 1 || !returns[0].expression) fail(statement.body ?? statement, "OEC9007", "a server function component must be a single return of one JSX element");
120
+ const parameters = statement.parameters;
121
+ if (parameters.length > 1) fail(parameters[1], "OEC9032", `server function component ${name} takes at most one props parameter`);
122
+ let parameter = null;
123
+ let fields = [];
124
+ let promiseFields = /* @__PURE__ */ new Set();
125
+ if (parameters.length === 1) {
126
+ if (!ts.isIdentifier(parameters[0].name)) fail(parameters[0], "OEC9032", "the props parameter must be a plain identifier");
127
+ parameter = parameters[0].name.text;
128
+ const facts = fieldsOfPropsType(authoredPropsType(parameters[0]), fail);
129
+ fields = facts.fields;
130
+ promiseFields = facts.promiseFields;
131
+ }
132
+ return {
133
+ statement,
134
+ name,
135
+ parameter,
136
+ fields,
137
+ returned: returns[0].expression,
138
+ isArrow: false,
139
+ isAsync,
140
+ promiseFields
141
+ };
142
+ }
143
+ const arrow = statement.declarationList.declarations[0].initializer;
144
+ if (arrow.parameters.length > 1) fail(arrow.parameters[1], "OEC9032", `${name} takes at most one props parameter`);
145
+ let parameter = null;
146
+ let fields = [];
147
+ let promiseFields = /* @__PURE__ */ new Set();
148
+ if (arrow.parameters.length === 1) {
149
+ if (!ts.isIdentifier(arrow.parameters[0].name)) fail(arrow.parameters[0], "OEC9032", "the props parameter must be a plain identifier");
150
+ parameter = arrow.parameters[0].name.text;
151
+ const facts = fieldsOfPropsType(authoredPropsType(arrow.parameters[0]), fail);
152
+ fields = facts.fields;
153
+ promiseFields = facts.promiseFields;
154
+ }
155
+ const arrowModifiers = ts.canHaveModifiers(arrow) ? ts.getModifiers(arrow) ?? [] : [];
156
+ return {
157
+ statement,
158
+ name,
159
+ parameter,
160
+ fields,
161
+ returned: arrow.body,
162
+ isArrow: true,
163
+ isAsync: arrowModifiers.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword),
164
+ promiseFields
165
+ };
166
+ }
167
+ /** True when the component body touches `this` — a class-path-only binding. */
168
+ function assertNoThisReads(fn, fail) {
169
+ const visit = (node) => {
170
+ if (node.kind === ts.SyntaxKind.ThisKeyword || node.kind === ts.SyntaxKind.SuperKeyword) fail(node, "OEC9032", "a server function component has no this — read the props parameter (props.<field>) instead; `this` belongs to the @element class path");
171
+ ts.forEachChild(node, visit);
172
+ };
173
+ visit(fn.body);
174
+ }
175
+ /** The authored props parameter text, verbatim (annotation included). */
176
+ function parameterTextOf(component) {
177
+ if (component.parameter === null) return "";
178
+ const found = (component.isArrow ? component.statement.declarationList.declarations[0].initializer : component.statement).parameters.find((candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === component.parameter);
179
+ return found ? found.getText() : component.parameter ?? "";
180
+ }
181
+ /** Exported server function components of one module: name → whether it is async. */
182
+ function exportedServerComponents(source, fileName) {
183
+ const parsed = typescriptParser.parseModule(source, fileName);
184
+ const components = /* @__PURE__ */ new Map();
185
+ if (parsed.syntaxDiagnostics.length === 0) for (const statement of parsed.sourceFile.statements) {
186
+ if (!isExportedServerComponentDeclaration(statement)) continue;
187
+ components.set(serverComponentName(statement), statementIsAsync(statement));
188
+ }
189
+ return components;
190
+ }
191
+ /** Static named value imports are the only candidates for direct server JSX calls. */
192
+ function* serverComponentValueImports(sourceFile) {
193
+ for (const statement of sourceFile.statements) {
194
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
195
+ const clause = statement.importClause;
196
+ const bindings = clause?.namedBindings;
197
+ if (clause?.isTypeOnly || bindings === void 0 || !ts.isNamedImports(bindings)) continue;
198
+ const specifier = statement.moduleSpecifier.text;
199
+ const elements = bindings.elements.filter((element) => !element.isTypeOnly);
200
+ if (specifier !== SERVER_HELPER_SPECIFIER && elements.length > 0) yield {
201
+ specifier,
202
+ elements
203
+ };
204
+ }
205
+ }
206
+ /** Resolve the compiler's static source candidates through an asynchronous host. */
207
+ async function prepareServerComponentImports(source, fileName, resolve) {
208
+ if (!isJsxModuleId(fileName) || !source.includes("export") || !source.includes("import") || !source.includes("<")) return;
209
+ const { sourceFile, syntaxDiagnostics } = typescriptParser.parseModule(source, fileName);
210
+ if (syntaxDiagnostics.length > 0) return void 0;
211
+ const tags = /* @__PURE__ */ new Set();
212
+ const visit = (node) => {
213
+ if ((ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) && ts.isIdentifier(node.tagName)) tags.add(node.tagName.text);
214
+ ts.forEachChild(node, visit);
215
+ };
216
+ for (const statement of sourceFile.statements) if (isExportedServerComponentDeclaration(statement)) visit(statement);
217
+ const specifiers = /* @__PURE__ */ new Set();
218
+ for (const { specifier, elements } of serverComponentValueImports(sourceFile)) if (elements.some((element) => tags.has(element.name.text))) specifiers.add(specifier);
219
+ if (specifiers.size === 0) return void 0;
220
+ const modules = new Map(await Promise.all([...specifiers].map(async (specifier) => [specifier, await resolve(specifier)])));
221
+ return (specifier) => modules.get(specifier);
222
+ }
223
+ function statementIsAsync(statement) {
224
+ if (ts.isFunctionDeclaration(statement)) return (ts.getModifiers(statement) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword);
225
+ const initializer = statement.declarationList.declarations[0].initializer;
226
+ if (initializer === void 0 || !ts.isArrowFunction(initializer)) return false;
227
+ return (ts.canHaveModifiers(initializer) ? ts.getModifiers(initializer) ?? [] : []).some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword);
228
+ }
229
+ /**
230
+ * Compile one authored TSX module's server function components into the
231
+ * generative constructor module. Returns null for modules with no exported
232
+ * JSX-returning function (nothing to admit). Fails closed with a
233
+ * {@link CompiledElementError} carrying the ordered OEC diagnostics.
234
+ */
235
+ function compileServerComponentModule(source, fileName, options = {}) {
236
+ const parsed = typescriptParser.parseModule(source, fileName);
237
+ const sf = parsed.sourceFile;
238
+ if (parsed.syntaxDiagnostics.length > 0) throw new CompiledElementError(parsed.syntaxDiagnostics.map((diagnostic) => {
239
+ const start = diagnostic.start ?? 0;
240
+ const position = sf.getLineAndCharacterOfPosition(start);
241
+ return {
242
+ code: "OEC9000",
243
+ message: String(diagnostic.messageText),
244
+ file: fileName,
245
+ line: position.line + 1,
246
+ character: position.character + 1,
247
+ start,
248
+ end: start + (diagnostic.length ?? 0)
249
+ };
250
+ }));
251
+ const fail = failAt(sf);
252
+ const candidates = sf.statements.filter(isExportedServerComponentDeclaration);
253
+ const nearMiss = serverComponentNearMiss(sf, candidates);
254
+ if (nearMiss !== void 0) fail(nearMiss, "OEC9032", "this exported function renders JSX but is not an admitted server function component (a component is a single return of one JSX element) — runtime JSX has no interpreter in the server lane; fix the shape or move it out of the module");
255
+ if (candidates.length === 0) return null;
256
+ const intrinsics = createModuleIntrinsicBindings(sf);
257
+ for (const helper of SERVER_HELPERS) if (intrinsics.hasModuleScopeBinding(helper)) fail(sf, "OEC9032", `"${helper}" is reserved for the generated constructor imports (${SERVER_HELPER_SPECIFIER}) — remove or rename the module-scope binding`);
258
+ const componentBindings = /* @__PURE__ */ new Map();
259
+ const asyncComponents = /* @__PURE__ */ new Set();
260
+ if (options.resolveModule !== void 0) for (const { specifier, elements } of serverComponentValueImports(sf)) {
261
+ const importedModule = options.resolveModule(specifier);
262
+ if (importedModule === void 0) continue;
263
+ if (typeof importedModule !== "string" && !isJsxModuleId(importedModule.fileName)) continue;
264
+ const importedComponents = exportedServerComponents(typeof importedModule === "string" ? importedModule : importedModule.source, typeof importedModule === "string" ? `${fileName}→${specifier}` : importedModule.fileName);
265
+ for (const element of elements) {
266
+ const imported = element.propertyName?.text ?? element.name.text;
267
+ if (!importedComponents.has(imported)) continue;
268
+ componentBindings.set(element.name.text, element.name.text);
269
+ if (importedComponents.get(imported) === true) asyncComponents.add(element.name.text);
270
+ }
271
+ }
272
+ const serverBinding = {
273
+ parameter: "props",
274
+ components: componentBindings,
275
+ compiledTags: new Set(options.compiledTags ?? []),
276
+ asyncComponents
277
+ };
278
+ const generatedByStatement = /* @__PURE__ */ new Map();
279
+ const classCandidates = /* @__PURE__ */ new Set();
280
+ for (const statement of candidates) {
281
+ const component = admitComponent(statement, fail);
282
+ assertNoThisReads(component.isArrow ? statement.declarationList.declarations[0].initializer : statement, fail);
283
+ const lowering = new Lowering(sf, component.fields, [], {
284
+ computedLocal: null,
285
+ server: {
286
+ ...serverBinding,
287
+ asyncFunction: component.isAsync,
288
+ promiseFields: component.promiseFields
289
+ }
290
+ });
291
+ const root = lowering.lowerRoot(component.returned);
292
+ if (root.k !== "el") fail(component.returned, "OEC9007", "a server function component must return one element");
293
+ for (const token of lowering.classCandidates) classCandidates.add(token);
294
+ const body = new ConstructorEmitter(sf, lowering, serverBinding.parameter, fail).emit(root);
295
+ const parameterText = parameterTextOf(component);
296
+ const piece = {
297
+ statement,
298
+ name: component.name,
299
+ signatureNode: statement,
300
+ bodyNode: component.returned
301
+ };
302
+ const asyncKeyword = component.isAsync ? "async " : "";
303
+ if (component.isArrow) piece.single = `export const ${component.name} = ${asyncKeyword}(${parameterText}) => ${body};`;
304
+ else {
305
+ piece.signature = `export ${asyncKeyword}function ${component.name}(${parameterText}) {`;
306
+ piece.bodyLine = ` return ${body};`;
307
+ piece.closing = "}";
308
+ }
309
+ generatedByStatement.set(statement, piece);
310
+ }
311
+ const used = /* @__PURE__ */ new Set();
312
+ for (const piece of generatedByStatement.values()) {
313
+ const text = piece.single ?? `${piece.signature}\n${piece.bodyLine}\n${piece.closing}`;
314
+ for (const helper of SERVER_HELPERS) if (text.includes(`${helper}(`)) used.add(helper);
315
+ }
316
+ const segments = new SourceMapSegmentBuilder();
317
+ const positionOf = (node) => {
318
+ const position = sf.getLineAndCharacterOfPosition(node.getStart(sf));
319
+ return {
320
+ line: position.line + 1,
321
+ column: position.character
322
+ };
323
+ };
324
+ const mapLine = (generatedLine, node, name) => {
325
+ const source = positionOf(node);
326
+ segments.add({
327
+ generatedLine,
328
+ generatedColumn: 0,
329
+ sourceLine: source.line,
330
+ sourceColumn: source.column,
331
+ ...name === void 0 ? {} : { name }
332
+ });
333
+ };
334
+ const codeLines = [
335
+ "/**",
336
+ ` * Generated by @openelement/compiler — the server function components of ${fileName}.`,
337
+ " * The admitted JSX lowered to the element server constructor helpers",
338
+ ` * (${SERVER_HELPER_SPECIFIER}); pure server output — no Part Program, no`,
339
+ " * element registration, no client graph edge.",
340
+ " */"
341
+ ];
342
+ if (used.size > 0) codeLines.push(`import { ${[...used].sort().join(", ")} } from '${SERVER_HELPER_SPECIFIER}';`);
343
+ for (const statement of sf.statements) {
344
+ const piece = generatedByStatement.get(statement);
345
+ if (piece === void 0) {
346
+ codeLines.push(statement.getText(sf));
347
+ continue;
348
+ }
349
+ if (piece.single !== void 0) {
350
+ mapLine(codeLines.length + 1, piece.signatureNode, piece.name);
351
+ codeLines.push(piece.single);
352
+ continue;
353
+ }
354
+ mapLine(codeLines.length + 1, piece.signatureNode, piece.name);
355
+ codeLines.push(piece.signature);
356
+ mapLine(codeLines.length + 1, piece.bodyNode);
357
+ codeLines.push(piece.bodyLine);
358
+ codeLines.push(piece.closing);
359
+ }
360
+ return {
361
+ code: `${codeLines.join("\n")}\n`,
362
+ map: segments.build(fileName, source),
363
+ components: candidates.map(serverComponentName).sort(),
364
+ ...classCandidates.size === 0 ? {} : { classCandidates: [...classCandidates].sort() }
365
+ };
366
+ }
367
+ /**
368
+ * An exported function or arrow whose body contains JSX but is not the
369
+ * admitted single-return shape. Statements before the return and a
370
+ * block-bodied arrow are the shapes authors actually write; both carry JSX
371
+ * the server lane cannot leave for a runtime JSX transform. Default exports
372
+ * stay out: they are page/route surface, not composed components. The fact
373
+ * scan ({@link isExportedServerComponentDeclaration}) does not count these,
374
+ * so an admission bridge that stops on an empty component list would return
375
+ * null and the host would pass the module through unchanged.
376
+ */
377
+ function serverComponentNearMiss(sf, candidates) {
378
+ const containsJsx = (node) => {
379
+ let found = false;
380
+ const visit = (child) => {
381
+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child)) found = true;
382
+ ts.forEachChild(child, visit);
383
+ };
384
+ visit(node);
385
+ return found;
386
+ };
387
+ for (const statement of sf.statements) {
388
+ if (candidates.includes(statement)) continue;
389
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];
390
+ if (!modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue;
391
+ if (modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)) continue;
392
+ let body;
393
+ if (ts.isFunctionDeclaration(statement)) body = statement.body;
394
+ else if (ts.isVariableStatement(statement) && statement.declarationList.declarations.length === 1 && statement.declarationList.declarations[0].initializer !== void 0 && ts.isArrowFunction(statement.declarationList.declarations[0].initializer)) body = statement.declarationList.declarations[0].initializer;
395
+ if (body !== void 0 && containsJsx(body)) return statement;
396
+ }
397
+ }
398
+ /**
399
+ * The host-build admission bridge: compile `code` through the server function
400
+ * component lane when — and only when — this module belongs to it.
401
+ *
402
+ * - a module carrying a compiled-element decorator (or an unsupported
403
+ * decorator spelling, which the class lane compiles so it fails closed with
404
+ * OEC9027) belongs to the class lane: null;
405
+ * - a module with no admitted server function component and no near-miss
406
+ * exported JSX function has nothing to admit: null;
407
+ * - a near-miss (statements before the return, a block-bodied arrow, or any
408
+ * other exported function/arrow whose body contains JSX but is not the
409
+ * single-return shape) is NOT null: it goes through
410
+ * {@link compileServerComponentModule}, which fails closed with OEC9032.
411
+ * Returning null would hand the authored module to another lane unchanged;
412
+ * - a plain script id never carries the JSX grammar: null;
413
+ * - the cheap `export` + `<` prefilter (the same conservative superset idea
414
+ * the class lane's prefilter uses) keeps plainly inert modules off the
415
+ * parse. A module that does not parse stays null so the host reports the
416
+ * syntax error.
417
+ *
418
+ * Everything else goes through {@link compileServerComponentModule}, whose
419
+ * diagnostics fail the build closed.
420
+ */
421
+ function compileServerComponentIfAdmitted(code, id, options = {}) {
422
+ if (!isJsxModuleId(id)) return null;
423
+ if (!code.includes("export") || !code.includes("<")) return null;
424
+ const facts = analyzeModuleSemantics(code, id);
425
+ if (facts.compiledElementDecorator || facts.unsupportedElementDecorator !== void 0) return null;
426
+ if (facts.serverFunctionComponents.length === 0) {
427
+ const parsed = typescriptParser.parseModule(code, id);
428
+ if (parsed.syntaxDiagnostics.length > 0) return null;
429
+ if (serverComponentNearMiss(parsed.sourceFile, []) === void 0) return null;
430
+ }
431
+ return compileServerComponentModule(code, id, options);
432
+ }
433
+ /**
434
+ * The generated-constructor expression builder: one walk over the lowered
435
+ * tree that turns admitted nodes into `__h`/`__t`/`__ssr`/direct-call code.
436
+ * Static attribute values are compile-time literals; every dynamic value
437
+ * enters through a helper boundary.
438
+ *
439
+ * Code-construction boundary (CodeQL js/bad-code-sanitization #4238, FRM-05):
440
+ * every value this class splices into the generated module is either an
441
+ * `JSON.stringify`-quoted string literal (the ECMAScript QuoteJSONString
442
+ * escaping for a TS string literal) or a name validated by `identifier()`
443
+ * below; ordering-comparison operands are finite numeric literals only
444
+ * (protocol `conditionLiteralAllowed`). The artifact is a standalone TS module
445
+ * returned to the host build's transform — never inlined into HTML — so the
446
+ * query's script-embedding model does not apply. Evidence and the hostile-input
447
+ * regression live in this batch's REL-02 CodeQL disposition record and in the
448
+ * server-component-codegen-boundary regression test.
449
+ */
450
+ var ConstructorEmitter = class {
451
+ sf;
452
+ lowering;
453
+ parameter;
454
+ fail;
455
+ constructor(sf, lowering, parameter, fail) {
456
+ this.sf = sf;
457
+ this.lowering = lowering;
458
+ this.parameter = parameter;
459
+ this.fail = fail;
460
+ this.identifier(parameter, "the props parameter");
461
+ }
462
+ /**
463
+ * The codegen identifier boundary: every lowering-produced name the emitter
464
+ * splices into an IDENTIFIER position of the generated module
465
+ * (`props.<signal>`, `item.<field>`, the component binding) must be a plain
466
+ * ES identifier. Anything else would leave its slot and inject arbitrary
467
+ * source into the artifact, so a non-identifier fails the compile CLOSED —
468
+ * same diagnostic shape as the lowering's own "must be a plain identifier"
469
+ * refusals, never a silent fallback or a dropped sink. The lowering
470
+ * validates most names on the way in; this is the one boundary every
471
+ * emitted name passes, so a future lowering change cannot silently widen
472
+ * the splice.
473
+ */
474
+ identifier(name, what) {
475
+ if (!CODEGEN_IDENTIFIER.test(name)) this.fail(this.sf, "OEC9032", `${what} "${name}" is not a plain identifier — the generated module writes it into an identifier position, so the compiler refuses to emit it`);
476
+ return name;
477
+ }
478
+ emit(root) {
479
+ return this.node(root);
480
+ }
481
+ sinksOf(elementId) {
482
+ return this.lowering.parts.filter((part) => part.location?.node === elementId);
483
+ }
484
+ /**
485
+ * The slot-name expression for one child of a `__ssr` host: the child's
486
+ * static `slot` attribute as a literal, else its dynamic attr sink named
487
+ * `slot` (the same props read the emitted attribute takes), else `''` — the
488
+ * default slot. Text and Part children are always default-slot: the class
489
+ * path's own `slotNameOf` reads exactly these sources.
490
+ */
491
+ slotNameExpressionOf(child) {
492
+ if (child.k !== "el") return "''";
493
+ const staticSlot = child.attrs.find(([name]) => name === "slot")?.[1];
494
+ if (staticSlot !== void 0) return JSON.stringify(staticSlot);
495
+ for (const sink of this.sinksOf(child.id)) if (sink.k === "attr" && sink.name === "slot") {
496
+ const signal = sink.signal;
497
+ return `${this.parameter}.${this.identifier(signal, "the slot sink")}`;
498
+ }
499
+ return "''";
500
+ }
501
+ conditionText(test) {
502
+ const ref = `${this.parameter}.${this.identifier(test.signal, "the condition signal")}`;
503
+ switch (test.op) {
504
+ case "truthy": return test.value ? ref : `!${ref}`;
505
+ case "equals": return `${ref} === ${JSON.stringify(test.value)}`;
506
+ case "not-equals": return `${ref} !== ${JSON.stringify(test.value)}`;
507
+ case "greater-than": return `${ref} > ${String(test.value)}`;
508
+ case "greater-or-equal": return `${ref} >= ${String(test.value)}`;
509
+ case "less-than": return `${ref} < ${String(test.value)}`;
510
+ case "less-or-equal": return `${ref} <= ${String(test.value)}`;
511
+ }
512
+ return this.fail(this.sf, "OEC9013", `unsupported condition ${String(test.op)}`);
513
+ }
514
+ node(node) {
515
+ if (node.k === "text") return `__t(${JSON.stringify(node.value)})`;
516
+ if (node.k === "ival") return `__t(item.${this.identifier(node.field ?? "item", "the item field")})`;
517
+ if (node.k === "part") {
518
+ const part = this.lowering.parts[node.index];
519
+ if (part.k === "text") {
520
+ if (part.signal === "children") return `(${this.parameter}.children ?? '')`;
521
+ return `__t(${this.parameter}.${this.identifier(part.signal, "the text sink")})`;
522
+ }
523
+ if (part.k === "when") {
524
+ const on = this.node(part.on[0]);
525
+ const off = this.node(part.off[0]);
526
+ return `(${this.conditionText(part.test)} ? ${on} : ${off})`;
527
+ }
528
+ if (part.k === "each") {
529
+ const signal = this.identifier(part.signal, "the list sink");
530
+ return `${this.parameter}.${signal}.map((item) => ${this.node(part.item[0])}).join('')`;
531
+ }
532
+ return this.fail(this.sf, "OEC9013", `sink ${part.k} cannot anchor in server function output`);
533
+ }
534
+ const awaitedSlot = this.lowering.serverExpressionSlots?.get(node.id);
535
+ if (awaitedSlot !== void 0) return awaitedSlot;
536
+ const componentCall = this.lowering.componentCalls.get(node.id);
537
+ if (componentCall !== void 0) {
538
+ const entries = componentCall.propsEntries.map(([name, value]) => `${JSON.stringify(name)}: ${value}`);
539
+ if (componentCall.children.length > 0) entries.push(`${JSON.stringify("children")}: [${componentCall.children.map((child) => this.node(child)).join(", ")}].join('')`);
540
+ const component = this.identifier(componentCall.component, "the nested component binding");
541
+ const call = `${component}({ ${entries.join(", ")} })`;
542
+ return this.lowering.isServerAsyncComponent?.(component) === true ? `await ${call}` : call;
543
+ }
544
+ const sinks = this.sinksOf(node.id);
545
+ const isSsr = this.lowering.ssrCalls.has(node.id);
546
+ const attrEntries = [];
547
+ for (const [name, value] of node.attrs) attrEntries.push(`${JSON.stringify(name)}: ${JSON.stringify(value)}`);
548
+ for (const part of sinks) {
549
+ if (part.k === "event" || part.k === "ref") continue;
550
+ if (part.k === "html") {
551
+ if (isSsr) this.fail(this.sf, "OEC9032", "a trustedHtml sink cannot cross a __ssr host — pass the trusted value as the component's own property instead");
552
+ const signal = this.identifier(part.signal, "the innerHTML sink");
553
+ attrEntries.push(`${JSON.stringify("innerHTML")}: ${this.parameter}.${signal}`);
554
+ continue;
555
+ }
556
+ if (part.k === "class") {
557
+ const signal = this.identifier(part.signal, "the class sink");
558
+ const synthesized = this.lowering.synthesizedFields.find((field) => field.name === signal);
559
+ const value = synthesized ? `(${synthesized.computed.body.getText(this.sf)})` : `${this.parameter}.${signal}`;
560
+ attrEntries.push(`${JSON.stringify("class")}: ${value}`);
561
+ continue;
562
+ }
563
+ if (part.k === "style") {
564
+ const signal = this.identifier(part.signal, "the style sink");
565
+ attrEntries.push(`${JSON.stringify("style")}: ${this.parameter}.${signal}`);
566
+ continue;
567
+ }
568
+ const signal = this.identifier(part.signal, "the attribute sink");
569
+ attrEntries.push(`${JSON.stringify(part.name)}: ${this.parameter}.${signal}`);
570
+ }
571
+ for (const [name, field] of node.iattrs ?? []) {
572
+ const itemField = this.identifier(field, "the item attribute field");
573
+ attrEntries.push(`${JSON.stringify(name)}: item.${itemField}`);
574
+ }
575
+ const attrsText = `{ ${attrEntries.join(", ")}${attrEntries.length > 0 ? " " : ""}}`;
576
+ if (isSsr) {
577
+ const childNodes = node.children;
578
+ if (childNodes.length === 0) return `__ssr(${JSON.stringify(node.tag)}, ${attrsText})`;
579
+ const groupEntries = childNodes.map((child) => `[${this.slotNameExpressionOf(child)}, ${this.node(child)}]`);
580
+ return `__ssr(${JSON.stringify(node.tag)}, ${attrsText}, undefined, { groups: [${groupEntries.join(", ")}] })`;
581
+ }
582
+ const children = node.children.map((child) => this.node(child));
583
+ return `__h(${JSON.stringify(node.tag)}, ${attrsText}, [${children.join(", ")}])`;
584
+ }
585
+ };
586
+ //#endregion
587
+ export { ConstructorEmitter, compileServerComponentIfAdmitted, compileServerComponentModule, prepareServerComponentImports };
@@ -9,7 +9,7 @@ import { CompilerErrorCode, frameworkError } from "@openelement/protocol/errors"
9
9
  * that text: a compiler change could emit a program that fails `tsc` or a
10
10
  * consumer's `tsgo` run, and the first evidence was a consumer's
11
11
  * build — the reason the "strict emission" corpus in
12
- * `__tests__/compiled-element-v1.test.ts` had to pin individual `static`
12
+ * `__tests__/compiled-element-v2.test.ts` had to pin individual `static`
13
13
  * annotations by string match.
14
14
  *
15
15
  * The check compiles the emitted text as a real TypeScript program and returns