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

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 (28) hide show
  1. package/package.json +3 -2
  2. package/src/compiler.d.ts +8 -4
  3. package/src/compiler.js +8 -4
  4. package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +36 -0
  5. package/src/internal/compiler/compiled-artifact-class-candidates.js +60 -0
  6. package/src/internal/compiler/compiled-artifact-style-requests.d.ts +17 -0
  7. package/src/internal/compiler/compiled-artifact-style-requests.js +48 -2
  8. package/src/internal/compiler/plugin.d.ts +47 -9
  9. package/src/internal/compiler/plugin.js +102 -24
  10. package/src/internal/compiler/semantic-core/analyze-module.d.ts +117 -0
  11. package/src/internal/compiler/semantic-core/analyze-module.js +55 -10
  12. package/src/internal/compiler/semantic-core/compile.d.ts +10 -2
  13. package/src/internal/compiler/semantic-core/compile.js +6 -4
  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/emit-module.js +4 -0
  17. package/src/internal/compiler/semantic-core/emit-program.js +23 -3
  18. package/src/internal/compiler/semantic-core/lower-program.d.ts +169 -0
  19. package/src/internal/compiler/semantic-core/lower-program.js +168 -56
  20. package/src/internal/compiler/semantic-core/module-analysis.d.ts +55 -0
  21. package/src/internal/compiler/semantic-core/module-analysis.js +74 -4
  22. package/src/internal/compiler/semantic-core/server-component.d.ts +114 -0
  23. package/src/internal/compiler/semantic-core/server-component.js +481 -0
  24. package/src/internal/compiler/semantic-core/type-check.js +1 -1
  25. package/src/internal/compiler/style-requests.d.ts +43 -7
  26. package/src/internal/compiler/style-requests.js +70 -11
  27. package/src/internal/compiler/tailwind-candidates.d.ts +84 -0
  28. package/src/internal/compiler/tailwind-candidates.js +54 -0
@@ -0,0 +1,481 @@
1
+ import { analyzeModuleSemantics, createModuleIntrinsicBindings, isExportedServerComponentDeclaration, serverComponentName } from "./module-analysis.js";
2
+ import { CompiledElementError, failAt } from "./compiler-diagnostics.js";
3
+ import { Lowering } from "./lower-program.js";
4
+ import { SourceMapSegmentBuilder } from "./source-map.js";
5
+ import { typescriptParser } from "./parse-module.js";
6
+ import ts from "typescript";
7
+ //#region src/internal/compiler/semantic-core/server-component.ts
8
+ /**
9
+ * Server-only TSX function components (alpha15 server lane): the admission
10
+ * and generative lowering entry.
11
+ *
12
+ * A server function component is an exported function whose body is a single
13
+ * return of JSX — the compiled render() grammar's own subset (one semantic
14
+ * authority: the SAME `Lowering` walk the @element class path runs, with the
15
+ * props parameter as the field accessor; the same attribute-name safety, sink
16
+ * denial, trustedHtml boundary and OEC diagnostics — no parallel checker
17
+ * exists). What differs is only the OUTPUT: instead of a Part Program, the
18
+ * admitted JSX lowers to a plain exported TS function whose body composes the
19
+ * element server runtime's constructor helpers:
20
+ *
21
+ * __h("article", { class: "card" }, [__h("h2", {}, [__t(props.name)])])
22
+ *
23
+ * - dynamic text rides `__t` (the ONE DSD-serializer escapeText);
24
+ * - attribute values cross `__h`'s one `escapeAttr` + shared URL screen;
25
+ * - a build-admitted @element compiled host rides `__ssr(tag, props)` — the
26
+ * component path's literal runtime function;
27
+ * - an island or foreign custom host emits its tag as-is (the existing island
28
+ * admission pipeline owns it);
29
+ * - a nested server function component composes by DIRECT function call to
30
+ * the imported binding, resolved from the authored imports at compile time
31
+ * (deterministic — the host hands the compiler the imported sources).
32
+ *
33
+ * The artifact is generated TS — not an IR, not an interpreter, no Part
34
+ * Program, no element class, no client graph edge.
35
+ *
36
+ * Discovery is compiler-exclusive: `analyzeModuleSemantics` reports the
37
+ * module's exported JSX functions (the cheap fact a graph walker reads); THIS
38
+ * entry is the admission authority the host build calls for the modules it
39
+ * finds reachable from its page modules. Route-side wiring is a later lane.
40
+ */
41
+ /** The helper names the generated module binds from '@openelement/element/server'. */
42
+ const SERVER_HELPERS = [
43
+ "__h",
44
+ "__t",
45
+ "__ssr"
46
+ ];
47
+ /** The one identifier shape the generated module may carry (see `identifier`). */
48
+ const CODEGEN_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
49
+ const SERVER_HELPER_SPECIFIER = "@openelement/element/server";
50
+ /** Map one inline props-type member annotation to the walk's property-type labels. */
51
+ function propsTypeOf(type) {
52
+ if (type === void 0) return "string";
53
+ const text = type.getText().replace(/\s/g, "");
54
+ if (text === "string" || text === "String") return "string";
55
+ if (text === "number" || text === "Number") return "number";
56
+ if (text === "boolean" || text === "Boolean") return "boolean";
57
+ if (text.includes("TrustedHtml")) return "object";
58
+ if (/^(Array|ReadonlyArray|Set)</.test(text) || text.endsWith("[]")) return "array";
59
+ if (/^(Record|Map|Object)</.test(text)) return "object";
60
+ return "string";
61
+ }
62
+ /** Build the synthetic field table one props type literal admits. */
63
+ function fieldsOfPropsType(typeNode, fail) {
64
+ if (typeNode === void 0) return [];
65
+ let literal = typeNode;
66
+ while (ts.isParenthesizedTypeNode(literal)) literal = literal.type;
67
+ 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");
68
+ const fields = [];
69
+ for (const member of literal.members) {
70
+ if (!ts.isPropertySignature(member) || !ts.isIdentifier(member.name)) fail(member, "OEC9032", "the props type admits property signatures only");
71
+ const label = propsTypeOf(member.type);
72
+ fields.push({
73
+ name: member.name.text,
74
+ reflect: false,
75
+ attribute: null,
76
+ type: label,
77
+ converter: label,
78
+ typeConstructor: "String",
79
+ accessibility: "",
80
+ typeText: member.type ? `: ${member.type.getText()}` : "",
81
+ initializerText: "",
82
+ defaultValue: null,
83
+ node: member
84
+ });
85
+ }
86
+ return fields;
87
+ }
88
+ /** One component's admitted shape, with the diagnostics every other shape rejects. */
89
+ function admitComponent(statement, fail) {
90
+ const name = serverComponentName(statement);
91
+ if (ts.isFunctionDeclaration(statement)) {
92
+ if ((ts.getModifiers(statement) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) fail(statement, "OEC9032", `server function component ${name} may not be async — a component returns its HTML synchronously; async data belongs in the route loader`);
93
+ if (statement.typeParameters?.length) fail(statement, "OEC9032", `server function component ${name} may not declare type parameters`);
94
+ if (statement.body === void 0 || !ts.isBlock(statement.body)) fail(statement, "OEC9032", `server function component ${name} must have a body`);
95
+ const returns = statement.body.statements.filter(ts.isReturnStatement);
96
+ 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");
97
+ const parameters = statement.parameters;
98
+ if (parameters.length > 1) fail(parameters[1], "OEC9032", `server function component ${name} takes at most one props parameter`);
99
+ let parameter = null;
100
+ let fields = [];
101
+ if (parameters.length === 1) {
102
+ if (!ts.isIdentifier(parameters[0].name)) fail(parameters[0], "OEC9032", "the props parameter must be a plain identifier");
103
+ parameter = parameters[0].name.text;
104
+ fields = fieldsOfPropsType(parameters[0].type, fail);
105
+ }
106
+ return {
107
+ statement,
108
+ name,
109
+ parameter,
110
+ fields,
111
+ returned: returns[0].expression,
112
+ isArrow: false
113
+ };
114
+ }
115
+ const arrow = statement.declarationList.declarations[0].initializer;
116
+ if (arrow.parameters.length > 1) fail(arrow.parameters[1], "OEC9032", `${name} takes at most one props parameter`);
117
+ let parameter = null;
118
+ let fields = [];
119
+ if (arrow.parameters.length === 1) {
120
+ if (!ts.isIdentifier(arrow.parameters[0].name)) fail(arrow.parameters[0], "OEC9032", "the props parameter must be a plain identifier");
121
+ parameter = arrow.parameters[0].name.text;
122
+ fields = fieldsOfPropsType(arrow.parameters[0].type, fail);
123
+ }
124
+ return {
125
+ statement,
126
+ name,
127
+ parameter,
128
+ fields,
129
+ returned: arrow.body,
130
+ isArrow: true
131
+ };
132
+ }
133
+ /** True when the component body touches `this` — a class-path-only binding. */
134
+ function assertNoThisReads(fn, fail) {
135
+ const visit = (node) => {
136
+ 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");
137
+ ts.forEachChild(node, visit);
138
+ };
139
+ visit(fn.body);
140
+ }
141
+ /** The authored props parameter text, verbatim (annotation included). */
142
+ function parameterTextOf(component) {
143
+ if (component.parameter === null) return "";
144
+ const found = (component.isArrow ? component.statement.declarationList.declarations[0].initializer : component.statement).parameters.find((candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === component.parameter);
145
+ return found ? found.getText() : component.parameter ?? "";
146
+ }
147
+ /** The exported server function component names of one (host-resolved) module source. */
148
+ function exportedServerComponentNames(source, fileName) {
149
+ const parsed = typescriptParser.parseModule(source, fileName);
150
+ const names = /* @__PURE__ */ new Set();
151
+ if (parsed.syntaxDiagnostics.length === 0) {
152
+ for (const statement of parsed.sourceFile.statements) if (isExportedServerComponentDeclaration(statement)) names.add(serverComponentName(statement));
153
+ }
154
+ return names;
155
+ }
156
+ /**
157
+ * Compile one authored TSX module's server function components into the
158
+ * generative constructor module. Returns null for modules with no exported
159
+ * JSX-returning function (nothing to admit). Fails closed with a
160
+ * {@link CompiledElementError} carrying the ordered OEC diagnostics.
161
+ */
162
+ function compileServerComponentModule(source, fileName, options = {}) {
163
+ const parsed = typescriptParser.parseModule(source, fileName);
164
+ const sf = parsed.sourceFile;
165
+ if (parsed.syntaxDiagnostics.length > 0) throw new CompiledElementError(parsed.syntaxDiagnostics.map((diagnostic) => {
166
+ const start = diagnostic.start ?? 0;
167
+ const position = sf.getLineAndCharacterOfPosition(start);
168
+ return {
169
+ code: "OEC9000",
170
+ message: String(diagnostic.messageText),
171
+ file: fileName,
172
+ line: position.line + 1,
173
+ character: position.character + 1,
174
+ start,
175
+ end: start + (diagnostic.length ?? 0)
176
+ };
177
+ }));
178
+ const fail = failAt(sf);
179
+ const candidates = sf.statements.filter(isExportedServerComponentDeclaration);
180
+ const containsJsx = (node) => {
181
+ let found = false;
182
+ const visit = (child) => {
183
+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child)) found = true;
184
+ ts.forEachChild(child, visit);
185
+ };
186
+ visit(node);
187
+ return found;
188
+ };
189
+ for (const statement of sf.statements) {
190
+ if (candidates.includes(statement)) continue;
191
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];
192
+ if (!modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue;
193
+ if (modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)) continue;
194
+ let body;
195
+ if (ts.isFunctionDeclaration(statement)) body = statement.body;
196
+ 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;
197
+ if (body !== void 0 && containsJsx(body)) fail(statement, "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");
198
+ }
199
+ if (candidates.length === 0) return null;
200
+ const intrinsics = createModuleIntrinsicBindings(sf);
201
+ 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`);
202
+ const componentBindings = /* @__PURE__ */ new Map();
203
+ if (options.resolveModule !== void 0) for (const statement of sf.statements) {
204
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
205
+ const specifier = statement.moduleSpecifier.text;
206
+ if (specifier === SERVER_HELPER_SPECIFIER) continue;
207
+ const importedSource = options.resolveModule(specifier);
208
+ if (importedSource === void 0) continue;
209
+ const importedNames = exportedServerComponentNames(importedSource, `${fileName}→${specifier}`);
210
+ const bindings = statement.importClause?.namedBindings;
211
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
212
+ for (const element of bindings.elements) {
213
+ const imported = element.propertyName?.text ?? element.name.text;
214
+ if (importedNames.has(imported)) componentBindings.set(element.name.text, element.name.text);
215
+ }
216
+ }
217
+ const serverBinding = {
218
+ parameter: "props",
219
+ components: componentBindings,
220
+ compiledTags: new Set(options.compiledTags ?? [])
221
+ };
222
+ const generatedByStatement = /* @__PURE__ */ new Map();
223
+ const classCandidates = /* @__PURE__ */ new Set();
224
+ for (const statement of candidates) {
225
+ const component = admitComponent(statement, fail);
226
+ assertNoThisReads(component.isArrow ? statement.declarationList.declarations[0].initializer : statement, fail);
227
+ const lowering = new Lowering(sf, component.fields, [], {
228
+ computedLocal: null,
229
+ server: serverBinding
230
+ });
231
+ const root = lowering.lowerRoot(component.returned);
232
+ if (root.k !== "el") fail(component.returned, "OEC9007", "a server function component must return one element");
233
+ for (const token of lowering.classCandidates) classCandidates.add(token);
234
+ const body = new ConstructorEmitter(sf, lowering, serverBinding.parameter, fail).emit(root);
235
+ const parameterText = parameterTextOf(component);
236
+ const piece = {
237
+ statement,
238
+ name: component.name,
239
+ signatureNode: statement,
240
+ bodyNode: component.returned
241
+ };
242
+ if (component.isArrow) piece.single = `export const ${component.name} = (${parameterText}) => ${body};`;
243
+ else {
244
+ piece.signature = `export function ${component.name}(${parameterText}) {`;
245
+ piece.bodyLine = ` return ${body};`;
246
+ piece.closing = "}";
247
+ }
248
+ generatedByStatement.set(statement, piece);
249
+ }
250
+ const used = /* @__PURE__ */ new Set();
251
+ for (const piece of generatedByStatement.values()) {
252
+ const text = piece.single ?? `${piece.signature}\n${piece.bodyLine}\n${piece.closing}`;
253
+ for (const helper of SERVER_HELPERS) if (text.includes(`${helper}(`)) used.add(helper);
254
+ }
255
+ const segments = new SourceMapSegmentBuilder();
256
+ const positionOf = (node) => {
257
+ const position = sf.getLineAndCharacterOfPosition(node.getStart(sf));
258
+ return {
259
+ line: position.line + 1,
260
+ column: position.character
261
+ };
262
+ };
263
+ const mapLine = (generatedLine, node, name) => {
264
+ const source = positionOf(node);
265
+ segments.add({
266
+ generatedLine,
267
+ generatedColumn: 0,
268
+ sourceLine: source.line,
269
+ sourceColumn: source.column,
270
+ ...name === void 0 ? {} : { name }
271
+ });
272
+ };
273
+ const codeLines = [
274
+ "/**",
275
+ ` * Generated by @openelement/compiler — the server function components of ${fileName}.`,
276
+ " * The admitted JSX lowered to the element server constructor helpers",
277
+ ` * (${SERVER_HELPER_SPECIFIER}); pure server output — no Part Program, no`,
278
+ " * element registration, no client graph edge.",
279
+ " */"
280
+ ];
281
+ if (used.size > 0) codeLines.push(`import { ${[...used].sort().join(", ")} } from '${SERVER_HELPER_SPECIFIER}';`);
282
+ for (const statement of sf.statements) {
283
+ const piece = generatedByStatement.get(statement);
284
+ if (piece === void 0) {
285
+ codeLines.push(statement.getText(sf));
286
+ continue;
287
+ }
288
+ if (piece.single !== void 0) {
289
+ mapLine(codeLines.length + 1, piece.signatureNode, piece.name);
290
+ codeLines.push(piece.single);
291
+ continue;
292
+ }
293
+ mapLine(codeLines.length + 1, piece.signatureNode, piece.name);
294
+ codeLines.push(piece.signature);
295
+ mapLine(codeLines.length + 1, piece.bodyNode);
296
+ codeLines.push(piece.bodyLine);
297
+ codeLines.push(piece.closing);
298
+ }
299
+ return {
300
+ code: `${codeLines.join("\n")}\n`,
301
+ map: segments.build(fileName, source),
302
+ components: candidates.map(serverComponentName).sort(),
303
+ ...classCandidates.size === 0 ? {} : { classCandidates: [...classCandidates].sort() }
304
+ };
305
+ }
306
+ /**
307
+ * The host-build admission bridge: compile `code` through the server function
308
+ * component lane when — and only when — this module belongs to it.
309
+ *
310
+ * - a module carrying a compiled-element decorator (or an unsupported
311
+ * decorator spelling, which the class lane compiles so it fails closed with
312
+ * OEC9027) belongs to the class lane: null;
313
+ * - a module with no discovered server function component has nothing to
314
+ * admit: null;
315
+ * - a non-`.tsx` id can never carry the JSX grammar: null;
316
+ * - the cheap `export` + `<` prefilter (the same conservative superset idea
317
+ * the class lane's prefilter uses) keeps plainly inert modules off the
318
+ * parse.
319
+ *
320
+ * Everything else goes through {@link compileServerComponentModule}, whose
321
+ * diagnostics fail the build closed.
322
+ */
323
+ function compileServerComponentIfAdmitted(code, id, options = {}) {
324
+ if (!/\.tsx(?:\?|$)/.test(id)) return null;
325
+ if (!code.includes("export") || !code.includes("<")) return null;
326
+ const facts = analyzeModuleSemantics(code, id);
327
+ if (facts.compiledElementDecorator || facts.unsupportedElementDecorator !== void 0) return null;
328
+ if (facts.serverFunctionComponents.length === 0) return null;
329
+ return compileServerComponentModule(code, id, options);
330
+ }
331
+ /**
332
+ * The generated-constructor expression builder: one walk over the lowered
333
+ * tree that turns admitted nodes into `__h`/`__t`/`__ssr`/direct-call code.
334
+ * Static attribute values are compile-time literals; every dynamic value
335
+ * enters through a helper boundary.
336
+ *
337
+ * Code-construction boundary (CodeQL js/bad-code-sanitization #4238, FRM-05):
338
+ * every value this class splices into the generated module is either an
339
+ * `JSON.stringify`-quoted string literal (the ECMAScript QuoteJSONString
340
+ * escaping for a TS string literal) or a name validated by `identifier()`
341
+ * below; ordering-comparison operands are finite numeric literals only
342
+ * (protocol `conditionLiteralAllowed`). The artifact is a standalone TS module
343
+ * returned to the host build's transform — never inlined into HTML — so the
344
+ * query's script-embedding model does not apply. Evidence and the hostile-input
345
+ * regression live in this batch's REL-02 CodeQL disposition record and in the
346
+ * server-component-codegen-boundary regression test.
347
+ */
348
+ var ConstructorEmitter = class {
349
+ sf;
350
+ lowering;
351
+ parameter;
352
+ fail;
353
+ constructor(sf, lowering, parameter, fail) {
354
+ this.sf = sf;
355
+ this.lowering = lowering;
356
+ this.parameter = parameter;
357
+ this.fail = fail;
358
+ this.identifier(parameter, "the props parameter");
359
+ }
360
+ /**
361
+ * The codegen identifier boundary: every lowering-produced name the emitter
362
+ * splices into an IDENTIFIER position of the generated module
363
+ * (`props.<signal>`, `item.<field>`, the component binding) must be a plain
364
+ * ES identifier. Anything else would leave its slot and inject arbitrary
365
+ * source into the artifact, so a non-identifier fails the compile CLOSED —
366
+ * same diagnostic shape as the lowering's own "must be a plain identifier"
367
+ * refusals, never a silent fallback or a dropped sink. The lowering
368
+ * validates most names on the way in; this is the one boundary every
369
+ * emitted name passes, so a future lowering change cannot silently widen
370
+ * the splice.
371
+ */
372
+ identifier(name, what) {
373
+ 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`);
374
+ return name;
375
+ }
376
+ emit(root) {
377
+ return this.node(root);
378
+ }
379
+ sinksOf(elementId) {
380
+ return this.lowering.parts.filter((part) => part.location?.node === elementId);
381
+ }
382
+ /**
383
+ * The slot-name expression for one child of a `__ssr` host: the child's
384
+ * static `slot` attribute as a literal, else its dynamic attr sink named
385
+ * `slot` (the same props read the emitted attribute takes), else `''` — the
386
+ * default slot. Text and Part children are always default-slot: the class
387
+ * path's own `slotNameOf` reads exactly these sources.
388
+ */
389
+ slotNameExpressionOf(child) {
390
+ if (child.k !== "el") return "''";
391
+ const staticSlot = child.attrs.find(([name]) => name === "slot")?.[1];
392
+ if (staticSlot !== void 0) return JSON.stringify(staticSlot);
393
+ for (const sink of this.sinksOf(child.id)) if (sink.k === "attr" && sink.name === "slot") {
394
+ const signal = sink.signal;
395
+ return `${this.parameter}.${this.identifier(signal, "the slot sink")}`;
396
+ }
397
+ return "''";
398
+ }
399
+ conditionText(test) {
400
+ const ref = `${this.parameter}.${this.identifier(test.signal, "the condition signal")}`;
401
+ switch (test.op) {
402
+ case "truthy": return test.value ? ref : `!${ref}`;
403
+ case "equals": return `${ref} === ${JSON.stringify(test.value)}`;
404
+ case "not-equals": return `${ref} !== ${JSON.stringify(test.value)}`;
405
+ case "greater-than": return `${ref} > ${String(test.value)}`;
406
+ case "greater-or-equal": return `${ref} >= ${String(test.value)}`;
407
+ case "less-than": return `${ref} < ${String(test.value)}`;
408
+ case "less-or-equal": return `${ref} <= ${String(test.value)}`;
409
+ }
410
+ return this.fail(this.sf, "OEC9013", `unsupported condition ${String(test.op)}`);
411
+ }
412
+ node(node) {
413
+ if (node.k === "text") return `__t(${JSON.stringify(node.value)})`;
414
+ if (node.k === "ival") return `__t(item.${this.identifier(node.field ?? "item", "the item field")})`;
415
+ if (node.k === "part") {
416
+ const part = this.lowering.parts[node.index];
417
+ if (part.k === "text") {
418
+ if (part.signal === "children") return `(${this.parameter}.children ?? '')`;
419
+ return `__t(${this.parameter}.${this.identifier(part.signal, "the text sink")})`;
420
+ }
421
+ if (part.k === "when") {
422
+ const on = this.node(part.on[0]);
423
+ const off = this.node(part.off[0]);
424
+ return `(${this.conditionText(part.test)} ? ${on} : ${off})`;
425
+ }
426
+ if (part.k === "each") {
427
+ const signal = this.identifier(part.signal, "the list sink");
428
+ return `${this.parameter}.${signal}.map((item) => ${this.node(part.item[0])}).join('')`;
429
+ }
430
+ return this.fail(this.sf, "OEC9013", `sink ${part.k} cannot anchor in server function output`);
431
+ }
432
+ const componentCall = this.lowering.componentCalls.get(node.id);
433
+ if (componentCall !== void 0) {
434
+ const entries = componentCall.propsEntries.map(([name, value]) => `${JSON.stringify(name)}: ${value}`);
435
+ if (componentCall.children.length > 0) entries.push(`${JSON.stringify("children")}: [${componentCall.children.map((child) => this.node(child)).join(", ")}].join('')`);
436
+ return `${this.identifier(componentCall.component, "the nested component binding")}({ ${entries.join(", ")} })`;
437
+ }
438
+ const sinks = this.sinksOf(node.id);
439
+ const isSsr = this.lowering.ssrCalls.has(node.id);
440
+ const attrEntries = [];
441
+ for (const [name, value] of node.attrs) attrEntries.push(`${JSON.stringify(name)}: ${JSON.stringify(value)}`);
442
+ for (const part of sinks) {
443
+ if (part.k === "event" || part.k === "ref") continue;
444
+ if (part.k === "html") {
445
+ 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");
446
+ const signal = this.identifier(part.signal, "the innerHTML sink");
447
+ attrEntries.push(`${JSON.stringify("innerHTML")}: ${this.parameter}.${signal}`);
448
+ continue;
449
+ }
450
+ if (part.k === "class") {
451
+ const signal = this.identifier(part.signal, "the class sink");
452
+ const synthesized = this.lowering.synthesizedFields.find((field) => field.name === signal);
453
+ const value = synthesized ? `(${synthesized.computed.body.getText(this.sf)})` : `${this.parameter}.${signal}`;
454
+ attrEntries.push(`${JSON.stringify("class")}: ${value}`);
455
+ continue;
456
+ }
457
+ if (part.k === "style") {
458
+ const signal = this.identifier(part.signal, "the style sink");
459
+ attrEntries.push(`${JSON.stringify("style")}: ${this.parameter}.${signal}`);
460
+ continue;
461
+ }
462
+ const signal = this.identifier(part.signal, "the attribute sink");
463
+ attrEntries.push(`${JSON.stringify(part.name)}: ${this.parameter}.${signal}`);
464
+ }
465
+ for (const [name, field] of node.iattrs ?? []) {
466
+ const itemField = this.identifier(field, "the item attribute field");
467
+ attrEntries.push(`${JSON.stringify(name)}: item.${itemField}`);
468
+ }
469
+ const attrsText = `{ ${attrEntries.join(", ")}${attrEntries.length > 0 ? " " : ""}}`;
470
+ if (isSsr) {
471
+ const childNodes = node.children;
472
+ if (childNodes.length === 0) return `__ssr(${JSON.stringify(node.tag)}, ${attrsText})`;
473
+ const groupEntries = childNodes.map((child) => `[${this.slotNameExpressionOf(child)}, ${this.node(child)}]`);
474
+ return `__ssr(${JSON.stringify(node.tag)}, ${attrsText}, undefined, { groups: [${groupEntries.join(", ")}] })`;
475
+ }
476
+ const children = node.children.map((child) => this.node(child));
477
+ return `__h(${JSON.stringify(node.tag)}, ${attrsText}, [${children.join(", ")}])`;
478
+ }
479
+ };
480
+ //#endregion
481
+ export { ConstructorEmitter, compileServerComponentIfAdmitted, compileServerComponentModule };
@@ -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
@@ -10,7 +10,8 @@
10
10
  * text. This registry is how an edge travels from the compiled-element
11
11
  * transform (the one writer) to the intercepting plugin (the one reader)
12
12
  * within a build process — keyed by the edge's resolved module id (the
13
- * importing module's directory plus the sheet's file name), the same id the
13
+ * importing module's directory plus the sheet's file name, plus the
14
+ * component's light-root scope tag when it has one), the same id the
14
15
  * bundler's resolver lands on. A `.css` import from a module with no
15
16
  * registered edges is a plain app stylesheet and rides vite's own CSS
16
17
  * channel; a `.css` import from a tracked module with no edge entry is a
@@ -26,6 +27,15 @@ export interface RegisteredStyleRequest {
26
27
  readonly specifier: string;
27
28
  /** The sheet file's absolute path — where the intercepting build reads the bytes. */
28
29
  readonly file: string;
30
+ /**
31
+ * The light-root component tag this edge's emitted asset is scoped to
32
+ * (alpha15 S lane, S-C1.2). A light root has no shadow boundary, so its
33
+ * sheets leave the build wrapped in native `@scope (<tag>)`; the tag is
34
+ * therefore part of the edge's identity, not a detail of its bytes — two
35
+ * components sharing one sheet file are two resources with two scopes.
36
+ * Absent for a shadow-root edge, whose bytes ship exactly as authored.
37
+ */
38
+ readonly scopeTag?: string;
29
39
  }
30
40
  /** Register one generated edge (idempotent per module id — recompiles overwrite). */
31
41
  export declare function registerStyleRequest(request: RegisteredStyleRequest): void;
@@ -35,19 +45,45 @@ export declare function getStyleRequest(moduleId: string): RegisteredStyleReques
35
45
  export declare function hasStyleImporter(importerId: string): boolean;
36
46
  /** Every edge whose sheet file is the given path — the dev HMR reverse lookup. */
37
47
  export declare function styleEdgesForFile(file: string): RegisteredStyleRequest[];
48
+ /**
49
+ * Every edge one importing module declared. The host build uses it to emit the
50
+ * style resources of modules it admitted for their edges alone (S-C1.4: a Page
51
+ * or Layout the server renders and no island imports).
52
+ */
53
+ export declare function styleRequestsForImporter(importerId: string): RegisteredStyleRequest[];
38
54
  /** Drop every registered edge (a build's bookkeeping is its own lifetime). */
39
55
  export declare function clearStyleRequests(): void;
40
56
  /**
41
- * The registry key for one authored edge: the sheet file's resolved path.
42
- * Query suffixes on the importer id (dev-time cache busting) are stripped,
43
- * so recompiles re-register under one key; the full relative path keeps
44
- * same-named sheets in sibling subdirectories distinct edges.
57
+ * The registry key for one authored edge: the sheet file's resolved path,
58
+ * plus the importing component's light-root scope tag when it has one. Query
59
+ * suffixes on the importer id (dev-time cache busting) are stripped, so
60
+ * recompiles re-register under one key; the full relative path keeps
61
+ * same-named sheets in sibling subdirectories distinct edges. The scope
62
+ * tag rides the key because the emitted asset is a different resource per
63
+ * scope: a light root's sheet is served wrapped in `@scope (<tag>)`.
64
+ *
65
+ * Registering an edge passes the tag explicitly (the caller is the compile
66
+ * that just proved it); the intercept resolves a `.css` import from
67
+ * `(importer, specifier)` alone, so it reads the same fact back through the
68
+ * importer index. Both paths land on one key for one edge, and a disagreement
69
+ * can only fail closed at the intercept — never emit an unscoped asset.
70
+ */
71
+ export declare function styleRequestModuleId(importerId: string, specifier: string, scopeTag?: string): string;
72
+ /**
73
+ * The light-root scope tag of a compiled Part Program — undefined for a
74
+ * shadow-root program, whose sheets ship exactly as authored (they already
75
+ * have a boundary). One reader for the fact, shared by both host bindings of
76
+ * the compiled-element transform (the build plugin and the dev/HMR plugin)
77
+ * and by the compiled-artifact read.
45
78
  */
46
- export declare function styleRequestModuleId(importerId: string, specifier: string): string;
79
+ export declare function lightRootScopeTag(program: unknown): string | undefined;
47
80
  /**
48
81
  * The sheet file's absolute path for one authored edge: the importing
49
82
  * module's directory joined with the authored specifier. Relative specifiers
50
- * only (the compiler refuses bare ones), so the join is total.
83
+ * only (the compiler refuses bare ones), so the join is total. Parent
84
+ * segments (`../theme.css`) resolve lexically against the directory — the key
85
+ * must be the path the bundler's resolver lands on, never a verbatim `..`
86
+ * id no lookup can match.
51
87
  */
52
88
  export declare function styleRequestFile(importerId: string, specifier: string): string;
53
89
  //#endregion