@openelement/compiler 1.0.0-alpha.13 → 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
@@ -1,7 +1,7 @@
1
1
  import { resolveCanonicalBaseClass } from "./module-analysis.js";
2
2
  import { admitStylesInitializer, collectSheetImports } from "./style-imports.js";
3
3
  import ts from "typescript";
4
- import { camelToKebab, isSafeAttributeName } from "@openelement/protocol/forbidden-sinks";
4
+ import { FORBIDDEN_PROPERTY_NAMES, camelToKebab, isSafeAttributeName } from "@openelement/protocol/forbidden-sinks";
5
5
  //#region src/internal/compiler/semantic-core/analyze-module.ts
6
6
  /**
7
7
  * Module/class-shape analysis for the compiled grammar (#1473 split): the
@@ -105,15 +105,31 @@ const COMPUTED_FIELD_SUBJECTS = {
105
105
  * fields, and nested non-arrow functions fail closed (OEC9024). Returns the
106
106
  * source-signal dependency list (declaration order) and the body text with
107
107
  * every `this.<field>` read rewritten to `__s.<field>.value`.
108
+ *
109
+ * `binding` (alpha15 server lane) switches the read accessor from
110
+ * `this.<field>` to `<parameter>.<field>` (a server function component's
111
+ * props parameter): the same declared-field table and the same messages —
112
+ * only the accessor spelling differs, and no signal-record rewrite applies
113
+ * (the generated constructor reads the props object directly). The default
114
+ * keeps the class path's behavior and messages byte-identical.
108
115
  */
109
- function validateComputedExpressionBody(body, sf, plainFieldNames, computedFieldNames, fail, subjects = COMPUTED_FIELD_SUBJECTS) {
116
+ function validateComputedExpressionBody(body, sf, plainFieldNames, computedFieldNames, fail, subjects = COMPUTED_FIELD_SUBJECTS, binding) {
110
117
  const deps = [];
111
118
  const replacements = [];
112
119
  const visit = (node) => {
113
- if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) fail(node, "OEC9024", `${subjects.actor} may not nest non-arrow functions`);
120
+ if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) fail(node, "OEC9024", `${subjects.actor} may not nest non-arrow functions — hoist the function to module scope and import it`);
121
+ if (binding !== void 0) {
122
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === binding.parameter) {
123
+ const name = node.name.text;
124
+ if (computedFieldNames.has(name)) fail(node, "OEC9024", `${subjects.single} may not read computed field "${name}" — read its source ${binding.parameter}.<property> inputs instead (computed fields cannot chain)`);
125
+ if (!plainFieldNames.has(name)) fail(node, "OEC9024", `${subjects.plural} may only read ${binding.parameter}.<declared property> (found ${binding.parameter}.${name})`);
126
+ if (!deps.includes(name)) deps.push(name);
127
+ return;
128
+ }
129
+ }
114
130
  if (ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword) {
115
131
  const name = node.name.text;
116
- if (computedFieldNames.has(name)) fail(node, "OEC9024", `${subjects.single} may not read computed field "${name}"`);
132
+ if (computedFieldNames.has(name)) fail(node, "OEC9024", `${subjects.single} may not read computed field "${name}" — read its source this.<property> inputs instead (computed fields cannot chain)`);
117
133
  if (!plainFieldNames.has(name)) fail(node, "OEC9024", `${subjects.plural} may only read this.<declared property> (found this.${name})`);
118
134
  if (!deps.includes(name)) deps.push(name);
119
135
  replacements.push({
@@ -244,9 +260,10 @@ function propertyFields(sf, classNode, intrinsics, fail) {
244
260
  fail(decorator, "OEC9004", "unknown decorator on an OpenElement member; use only @property imported from '@openelement/element'");
245
261
  }
246
262
  if (!ts.isIdentifier(member.name)) fail(member, "OEC9005", "property names must be identifiers");
263
+ if (FORBIDDEN_PROPERTY_NAMES.has(member.name.text.toLowerCase())) fail(member, "OEC9005", `property name "${member.name.text}" is unsafe — prototype-pollution primitives are on the shared deny list; rename the property`);
247
264
  if (names.has(member.name.text)) fail(member, "OEC9005", `duplicate property "${member.name.text}"`);
248
265
  names.add(member.name.text);
249
- if (!member.initializer) fail(member, "OEC9005", "compiled fields require a literal initializer");
266
+ if (!member.initializer) fail(member, "OEC9005", "compiled fields require an admitted initializer — a serializable literal, computed(...), or trustedHtml(...)");
250
267
  const computedFieldNames = new Set(fields.filter((f) => f.computed).map((f) => f.name));
251
268
  const computedInit = parseComputedInitializer(member.initializer, sf, intrinsics, new Set(fields.filter((f) => !f.computed).map((f) => f.name)), computedFieldNames, fail);
252
269
  const trustedHtmlInit = !computedInit && isTrustedHtmlInitializer(member.initializer, intrinsics, fail);
@@ -273,7 +290,7 @@ function propertyFields(sf, classNode, intrinsics, fail) {
273
290
  if (entry.initializer.kind === ts.SyntaxKind.FalseKeyword) attribute = null;
274
291
  else if (ts.isStringLiteral(entry.initializer)) {
275
292
  attribute = camelToKebab(entry.initializer.text);
276
- if (!isSafeAttributeName$1(attribute)) fail(entry, "OEC9023", "property attribute name is unsafe");
293
+ if (!isSafeAttributeName$1(attribute)) fail(entry, "OEC9023", `property attribute name "${attribute}" is unsafe — use a valid HTML attribute name (no on* handlers, no forbidden sinks)`);
277
294
  } else fail(entry, "OEC9023", "property attribute must be a string literal or false");
278
295
  continue;
279
296
  }
@@ -283,7 +300,7 @@ function propertyFields(sf, classNode, intrinsics, fail) {
283
300
  else explicitConverter = type.label;
284
301
  continue;
285
302
  }
286
- fail(entry, "OEC9022", `unsupported @property option "${optionName}"`);
303
+ fail(entry, "OEC9022", `unsupported @property option "${optionName}" — admitted options are type, converter, reflect and attribute`);
287
304
  }
288
305
  const inferred = explicitType ?? inferPropertyType(member, defaultValue, sf);
289
306
  const converter = explicitConverter ?? inferred.label;
@@ -329,7 +346,7 @@ function propertyFields(sf, classNode, intrinsics, fail) {
329
346
  } else methods.push(member);
330
347
  continue;
331
348
  }
332
- fail(member, "OEC9006", "constructors, accessors and undecorated fields are outside the compiler grammar");
349
+ fail(member, "OEC9006", "constructors, accessors and undecorated fields are outside the compiler grammar — declare state as @property fields and behavior as methods");
333
350
  }
334
351
  if (!render) fail(classNode, "OEC9007", "compiled classes must declare render()");
335
352
  return {
@@ -372,6 +389,27 @@ function isIslandConfigStatement(statement, intrinsics) {
372
389
  return true;
373
390
  }
374
391
  /**
392
+ * The root family an admitted island config declares, or `undefined` when the
393
+ * descriptor does not pin one. The config speaks the user-facing
394
+ * `'light' | 'shadow'` pair while the decorator keeps the precise
395
+ * `shadow-open`/`shadow-closed` modes. Validated here so the cross-check below
396
+ * can trust the value it compares.
397
+ */
398
+ function islandConfigDeclaredRoot(statement, sf, fail) {
399
+ if (!ts.isVariableStatement(statement)) return void 0;
400
+ const initializer = statement.declarationList.declarations[0]?.initializer;
401
+ if (!initializer || !ts.isCallExpression(initializer)) return void 0;
402
+ const descriptor = initializer.arguments[0];
403
+ if (!descriptor || !ts.isObjectLiteralExpression(descriptor)) return void 0;
404
+ for (const entry of descriptor.properties) {
405
+ if (!ts.isPropertyAssignment(entry) || entry.name.getText(sf) !== "root") continue;
406
+ if (!ts.isStringLiteral(entry.initializer)) fail(entry, "OEC9030", "island config root must be a string literal");
407
+ const value = entry.initializer.text;
408
+ if (value !== "light" && value !== "shadow") fail(entry, "OEC9030", `island config root "${value}" is unsupported; use "light" or "shadow"`);
409
+ return value;
410
+ }
411
+ }
412
+ /**
375
413
  * Admit one parsed module to the compiled grammar and lift its shape
376
414
  * (#1473 split): the top-level
377
415
  * statement admission (OEC9008 fail-closed, island policy passthrough), the
@@ -383,13 +421,15 @@ function isIslandConfigStatement(statement, intrinsics) {
383
421
  function analyzeCompiledModule(sf, intrinsics, fail) {
384
422
  const sheetImports = collectSheetImports(sf, fail);
385
423
  const passthroughStatements = [];
424
+ let islandConfigStatement;
386
425
  for (const statement of sf.statements) {
387
426
  if (ts.isImportDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isModuleDeclaration(statement) || isDeclareStatement(statement)) continue;
388
427
  if (isIslandConfigStatement(statement, intrinsics)) {
389
428
  passthroughStatements.push(statement);
429
+ islandConfigStatement = statement;
390
430
  continue;
391
431
  }
392
- fail(statement, "OEC9008", "runtime top-level statements are outside the compiled module grammar");
432
+ fail(statement, "OEC9008", "runtime top-level statements are outside the compiled module grammar — keep shared state in a plain module and import it; the island policy statement (export const openElement = defineIslandConfig(...)) is the one admitted runtime statement");
393
433
  }
394
434
  const classes = sf.statements.filter(ts.isClassDeclaration);
395
435
  const decorated = classes.filter((node) => (ts.getDecorators(node) ?? []).some((decorator) => {
@@ -417,7 +457,7 @@ function analyzeCompiledModule(sf, intrinsics, fail) {
417
457
  if (!ts.isCallExpression(expr) || !intrinsics.resolveIntrinsic(expr.expression, "element").canonical) fail(decorator, "OEC9004", "unknown decorator on an OpenElement class; use only @element");
418
458
  if (expr.arguments.length < 1 || expr.arguments.length > 2 || !ts.isStringLiteral(expr.arguments[0])) fail(decorator, "OEC9002", "@element requires a string tag name plus an optional options object");
419
459
  tag = expr.arguments[0].text;
420
- if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(tag)) fail(decorator, "OEC9002", `@element tag "${tag}" is not a custom-element name`);
460
+ if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(tag)) fail(decorator, "OEC9002", `@element tag "${tag}" is not a custom-element name — use a lowercase name with at least one dash (my-element)`);
421
461
  let rootKind = "light";
422
462
  let delegatesFocus = false;
423
463
  let formAssociated = false;
@@ -447,6 +487,11 @@ function analyzeCompiledModule(sf, intrinsics, fail) {
447
487
  fail(entry, "OEC9002", "@element options support only root, delegatesFocus and formAssociated");
448
488
  }
449
489
  }
490
+ if (islandConfigStatement !== void 0) {
491
+ const declaredRoot = islandConfigDeclaredRoot(islandConfigStatement, sf, fail);
492
+ const compiledRoot = rootKind === "light" ? "light" : "shadow";
493
+ if (declaredRoot !== void 0 && declaredRoot !== compiledRoot) fail(islandConfigStatement, "OEC9030", `the island config declares root "${declaredRoot}" but @element('${tag}', { root: '${rootKind}' }) compiles a ${compiledRoot}-rooted program. The @element decorator owns the root — point the config at the light component (@element(tag, { root: 'light' })) or drop the config's root field so the two agree.`);
494
+ }
450
495
  const heritage = classNode.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);
451
496
  const heritageExpression = heritage?.types.length === 1 ? unwrapExpression(heritage.types[0].expression) : void 0;
452
497
  const heritageResolution = resolveCanonicalBaseClass(intrinsics, heritageExpression);
@@ -1,7 +1,7 @@
1
1
  import { SemanticCoreOptions } from "./module-analysis.js";
2
2
  import { CompiledElementSourceMap } from "./source-map.js";
3
3
  import { CompiledElementError, ElementCompilerDiagnostic } from "./compiler-diagnostics.js";
4
- import { PartProgramV1 } from "@openelement/protocol/part-program";
4
+ import { PartProgramV2 } from "@openelement/protocol/part-program";
5
5
  //#region src/internal/compiler/semantic-core/compile.d.ts
6
6
  /**
7
7
  * The compiled module the transform emits for one authored TSX source: the
@@ -17,7 +17,7 @@ export interface CompileElementResult {
17
17
  * as its `map` output for downstream composition (#1210).
18
18
  */
19
19
  map: CompiledElementSourceMap;
20
- program: PartProgramV1;
20
+ program: PartProgramV2;
21
21
  /**
22
22
  * The module's style edges (#1558): the authored `.css` specifiers the
23
23
  * class's `static styles` arrays, in authored order. The host build's
@@ -25,6 +25,14 @@ export interface CompileElementResult {
25
25
  * plugin fails at import resolution, never by silently inlining.
26
26
  */
27
27
  styleRequests?: readonly string[];
28
+ /**
29
+ * The component's statically admitted class tokens (alpha15 S lane): every
30
+ * whitespace-separated token of a compile-time `class` value the lowering
31
+ * admitted. Opaque strings — the compiler attaches no Tailwind meaning to
32
+ * them; the host build forwards them to the official Tailwind compiler as
33
+ * explicit candidates and emits the generated CSS as an external asset.
34
+ */
35
+ classCandidates?: readonly string[];
28
36
  }
29
37
  /**
30
38
  * Compile one authored TSX module into the compiled Part Program module.
@@ -8,10 +8,10 @@ import { typescriptParser } from "./parse-module.js";
8
8
  import ts from "typescript";
9
9
  //#region src/internal/compiler/semantic-core/compile.ts
10
10
  /**
11
- * @openelement/element — TSX-to-Part Program v1 compiler (#1161–#1163).
11
+ * @openelement/element — TSX-to-Part Program v2 compiler (#1161–#1163).
12
12
  *
13
13
  * The compiler accepts one deliberately bounded authoring grammar. It lowers
14
- * every accepted dynamic expression to a typed fixed Part or Region with a
14
+ * every accepted dynamic expression to a typed fixed Part or Block with a
15
15
  * stable compiler-owned location. Anything outside that grammar produces a
16
16
  * source-located diagnostic; no runtime discovery or fallback renderer is
17
17
  * emitted.
@@ -55,7 +55,7 @@ function compileElementProgram(source, fileName, options = {}) {
55
55
  const parsed = typescriptParser.parseModule(source, fileName);
56
56
  const sf = parsed.sourceFile;
57
57
  const syntaxDiagnostics = parsed.syntaxDiagnostics;
58
- if (syntaxDiagnostics.length > 0) throw new CompiledElementError([parseDiagnostic(sf, syntaxDiagnostics[0])]);
58
+ if (syntaxDiagnostics.length > 0) throw new CompiledElementError(syntaxDiagnostics.map((diagnostic) => parseDiagnostic(sf, diagnostic)));
59
59
  const fail = failAt(sf);
60
60
  const intrinsics = createModuleIntrinsicBindings(sf, options);
61
61
  const analyzed = analyzeCompiledModule(sf, intrinsics, fail);
@@ -87,11 +87,13 @@ function compileElementProgram(source, fileName, options = {}) {
87
87
  observedJson
88
88
  });
89
89
  const { styleRequests } = analyzed;
90
+ const classCandidates = [...lowering.classCandidates];
90
91
  return {
91
92
  code,
92
93
  map,
93
94
  program,
94
- ...styleRequests.length === 0 ? {} : { styleRequests }
95
+ ...styleRequests.length === 0 ? {} : { styleRequests },
96
+ ...classCandidates.length === 0 ? {} : { classCandidates }
95
97
  };
96
98
  }
97
99
  //#endregion
@@ -1,5 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { OpenElementError } from "@openelement/protocol/errors";
3
+ import { DiagnosticEnvelope } from "@openelement/protocol/diagnostics";
3
4
  //#region src/internal/compiler/semantic-core/diagnostics/index.d.ts
4
5
  export interface CompilerDiagnostic {
5
6
  code: string;
@@ -26,6 +27,25 @@ export declare class CompilerDiagnosticError extends OpenElementError {
26
27
  declare function diagnosticAt(sourceFile: ts.SourceFile, node: ts.Node, code: string, message: string): CompilerDiagnostic;
27
28
  /** Flatten a TypeScript parse diagnostic without leaking compiler internals. */
28
29
  declare function diagnosticMessage(diagnostic: ts.Diagnostic): string;
30
+ /**
31
+ * The record fields the envelope projection reads — the structural subset
32
+ * both a full {@linkcode CompilerDiagnostic} and the build-carried record
33
+ * (the `this.error()` projection, which drops the compiler-internal range)
34
+ * satisfy.
35
+ */
36
+ export type ProjectableCompilerDiagnostic = Pick<CompilerDiagnostic, 'code' | 'message' | 'file' | 'line' | 'character'>;
37
+ /**
38
+ * Project the compiler's already-structured diagnostics onto the protocol's
39
+ * {@linkcode DiagnosticEnvelope} shape. An empty list projects to an empty
40
+ * list — the caller keeps its own fallback rather than inventing a record.
41
+ */
42
+ export declare function compilerDiagnosticsToEnvelopes(diagnostics: ReadonlyArray<ProjectableCompilerDiagnostic>): DiagnosticEnvelope[];
43
+ /** Record one compile failure's envelopes for the build exit (#1612). */
44
+ export declare function recordCompilerDiagnostics(diagnostics: ReadonlyArray<ProjectableCompilerDiagnostic>): void;
45
+ /** Drain the recorded envelopes: the exit reads them exactly once. */
46
+ export declare function takeCompilerDiagnostics(): DiagnosticEnvelope[];
47
+ /** Clear without reading — the hygiene a fresh build invocation starts with. */
48
+ export declare function clearCompilerDiagnostics(): void;
29
49
  /** Rollup-compatible error shape emitted by the Vite adapter boundary. */
30
50
  export interface PluginDiagnosticError {
31
51
  id: string;
@@ -50,5 +70,5 @@ declare function formatDiagnosticFrame(source: string, diagnostic: CompilerDiagn
50
70
  * for an empty diagnostics list: there is nothing to locate or render, and
51
71
  * the caller keeps its own fallback rather than inventing a location.
52
72
  */
53
- declare function diagnosticPluginError(diagnostics: CompilerDiagnostic[], source: string, id: string): PluginDiagnosticError | null;
73
+ export declare function diagnosticPluginError(diagnostics: CompilerDiagnostic[], source: string, id: string): PluginDiagnosticError | null;
54
74
  //#endregion
@@ -49,6 +49,37 @@ function diagnosticMessage(diagnostic) {
49
49
  return ts.flattenDiagnosticMessageText(diagnostic.messageText, " ");
50
50
  }
51
51
  /**
52
+ * Project the compiler's already-structured diagnostics onto the protocol's
53
+ * {@linkcode DiagnosticEnvelope} shape. An empty list projects to an empty
54
+ * list — the caller keeps its own fallback rather than inventing a record.
55
+ */
56
+ function compilerDiagnosticsToEnvelopes(diagnostics) {
57
+ return diagnostics.map((diagnostic) => ({
58
+ code: diagnostic.code,
59
+ severity: "error",
60
+ phase: "build",
61
+ message: diagnostic.message,
62
+ file: diagnostic.file,
63
+ line: diagnostic.line,
64
+ column: diagnostic.character
65
+ }));
66
+ }
67
+ let exitRecord = [];
68
+ /** Record one compile failure's envelopes for the build exit (#1612). */
69
+ function recordCompilerDiagnostics(diagnostics) {
70
+ exitRecord.push(...compilerDiagnosticsToEnvelopes(diagnostics));
71
+ }
72
+ /** Drain the recorded envelopes: the exit reads them exactly once. */
73
+ function takeCompilerDiagnostics() {
74
+ const drained = exitRecord;
75
+ exitRecord = [];
76
+ return drained;
77
+ }
78
+ /** Clear without reading — the hygiene a fresh build invocation starts with. */
79
+ function clearCompilerDiagnostics() {
80
+ exitRecord = [];
81
+ }
82
+ /**
52
83
  * Render the authored line and its neighbours with a caret under the recorded
53
84
  * range — the frame field a build overlay consumes. Multi-line ranges caret
54
85
  * only the first line (Rollup's own frames do the same); an empty or
@@ -94,4 +125,4 @@ function diagnosticPluginError(diagnostics, source, id) {
94
125
  };
95
126
  }
96
127
  //#endregion
97
- export { CompilerDiagnosticError, diagnosticAt, diagnosticMessage, diagnosticPluginError, formatDiagnosticFrame };
128
+ export { CompilerDiagnosticError, clearCompilerDiagnostics, compilerDiagnosticsToEnvelopes, diagnosticAt, diagnosticMessage, diagnosticPluginError, formatDiagnosticFrame, recordCompilerDiagnostics, takeCompilerDiagnostics };
@@ -206,6 +206,10 @@ function emitCompiledModule(input) {
206
206
  ].join("\n"));
207
207
  if (delegatesFocus) push(" static override delegatesFocus: boolean = true;");
208
208
  if (formAssociated) push(" static override formAssociated: boolean = true;");
209
+ if (analyzed.rootKind !== "light" && lowering.classCandidates.size > 0) {
210
+ push(" static __oeUtilityClasses: boolean = true;");
211
+ push(` static __oeClassCandidates: readonly string[] = ${JSON.stringify([...lowering.classCandidates])};`);
212
+ }
209
213
  const computedFields = fields.filter((field) => field.computed);
210
214
  if (computedFields.length > 0) {
211
215
  const plainFieldByName = new Map(fields.filter((field) => !field.computed).map((field) => [field.name, field]));
@@ -1,5 +1,5 @@
1
1
  import { CompiledElementError, sourceRange } from "./compiler-diagnostics.js";
2
- import { validatePartProgram } from "@openelement/protocol/part-program";
2
+ import { PART_PROGRAM_VERSION, validatePartProgram } from "@openelement/protocol/part-program";
3
3
  //#region src/internal/compiler/semantic-core/emit-program.ts
4
4
  /**
5
5
  * Path-addressed fixed Parts can use DOM child indexes only before any dynamic
@@ -7,10 +7,23 @@ import { validatePartProgram } from "@openelement/protocol/part-program";
7
7
  * after one would make server output, fresh creation and claim address
8
8
  * different nodes. The v1 location id remains the identity; this guard keeps
9
9
  * the path retained for seed consumers safe until they consume that id.
10
+ *
11
+ * A when-branch sink is exempt: its path is branch-relative, and the branch
12
+ * tree holds no anchors of its own (the lowering rejects them), so the
13
+ * branch's own node list is a stable address space. Attribution is by the
14
+ * branch element's globally unique location id.
10
15
  */
11
16
  function assertPathSafety(program) {
17
+ const branchNodeIds = /* @__PURE__ */ new Set();
18
+ for (const part of program.parts) {
19
+ if (part.k !== "when") continue;
20
+ collectElementIds(part.on, branchNodeIds);
21
+ collectElementIds(part.off, branchNodeIds);
22
+ }
12
23
  for (const part of program.parts) {
13
24
  if (part.k === "text" || part.k === "when" || part.k === "each") continue;
25
+ const nodeId = part.location.node;
26
+ if (nodeId !== void 0 && branchNodeIds.has(nodeId)) continue;
14
27
  let nodes = program.template;
15
28
  for (const target of part.path) {
16
29
  for (let sibling = 0; sibling < target; sibling++) if (nodes[sibling]?.k === "part") {
@@ -30,6 +43,13 @@ function assertPathSafety(program) {
30
43
  }
31
44
  }
32
45
  }
46
+ /** Every element id a node list declares (branch trees are the branch set). */
47
+ function collectElementIds(nodes, out) {
48
+ for (const node of nodes) if (node.k === "el") {
49
+ out.add(node.id);
50
+ collectElementIds(node.children, out);
51
+ }
52
+ }
33
53
  /** Assemble, path-check and validate the Part Program; derive the serialized payloads. */
34
54
  function buildPartProgram(input) {
35
55
  const { sf, fileName, analyzed, root, lowering } = input;
@@ -87,7 +107,7 @@ function buildPartProgram(input) {
87
107
  ...lowering.sourceRecords
88
108
  ];
89
109
  const program = {
90
- version: 1,
110
+ version: PART_PROGRAM_VERSION,
91
111
  tag,
92
112
  root: {
93
113
  id: "root",
@@ -96,7 +116,7 @@ function buildPartProgram(input) {
96
116
  },
97
117
  template: [root],
98
118
  parts: lowering.parts,
99
- regions: lowering.regions,
119
+ blocks: lowering.blocks,
100
120
  dependencies: lowering.dependencies,
101
121
  locations: lowering.locations,
102
122
  sourceMap: {
@@ -0,0 +1,169 @@
1
+ import { CompiledField } from "./analyze-module.js";
2
+ import ts from "typescript";
3
+ import { ProgramBlockRecord, ProgramDependencyRecord, ProgramEventAction, ProgramLocationRecord, ProgramPart, ProgramSourceRecord, ProgramTreeNode, PropertyValueType } from "@openelement/protocol/part-program";
4
+ //#region src/internal/compiler/semantic-core/lower-program.d.ts
5
+ export interface GeneratedHandler {
6
+ name: string;
7
+ action: ProgramEventAction;
8
+ node: ts.ArrowFunction;
9
+ }
10
+ /**
11
+ * Local name the generated module binds the canonical `computed` import to
12
+ * when a synthesized conditional-class field (#1556) exists but the authored
13
+ * module never imported computed. The synthesized name cannot collide with an
14
+ * authored binding the compiler would have resolved (a canonical computed
15
+ * import is reused by name instead), and the emitter adds the import
16
+ * alongside it.
17
+ */
18
+ declare const SYNTHESIZED_COMPUTED_LOCAL = "__openelementComputed";
19
+ /**
20
+ * The server function component binding surface (alpha15 server lane): when
21
+ * set, the ONE lowering walk reads component state from the component
22
+ * function's `props` parameter instead of `this`, resolves uppercase JSX tags
23
+ * against the imported server function components, and records which
24
+ * custom-element hosts the host build admitted as compiled components
25
+ * (rendered through `__ssr`). Every other rule — attribute-name safety, sink
26
+ * denial, the trustedHtml boundary, the single-return grammar, the OEC
27
+ * diagnostics — is exactly the @element class path's: one semantic authority.
28
+ */
29
+ export interface ServerComponentBindings {
30
+ /** The component function's single parameter (fixed `props` by admission). */
31
+ readonly parameter: string;
32
+ /** JSX identifier tag → the local binding the generated call targets. */
33
+ readonly components: ReadonlyMap<string, string>;
34
+ /** Custom-element host tags the build admitted as compiled components (`__ssr`). */
35
+ readonly compiledTags: ReadonlySet<string>;
36
+ }
37
+ /** Lowering inputs beyond the analyzed module shape. */
38
+ export interface LoweringOptions {
39
+ /**
40
+ * The authored module's canonical `computed` local binding (aliases
41
+ * followed), when present. Synthesized conditional-class factories
42
+ * reference it; when null the emitter binds
43
+ * {@linkcode SYNTHESIZED_COMPUTED_LOCAL} and adds the import.
44
+ */
45
+ readonly computedLocal: string | null;
46
+ /**
47
+ * Server function component mode (alpha15 server lane). Absent: the walk
48
+ * behaves byte-identically to the @element class path.
49
+ */
50
+ readonly server?: ServerComponentBindings;
51
+ }
52
+ export declare class Lowering {
53
+ readonly parts: ProgramPart[];
54
+ readonly blocks: ProgramBlockRecord[];
55
+ readonly dependencies: ProgramDependencyRecord[];
56
+ readonly locations: ProgramLocationRecord[];
57
+ readonly sourceRecords: ProgramSourceRecord[];
58
+ readonly generatedHandlers: GeneratedHandler[];
59
+ readonly fieldNames: Set<string>;
60
+ readonly methodNames: Set<string>;
61
+ readonly computedNames: Set<string>;
62
+ readonly fieldTypes: Map<string, PropertyValueType>;
63
+ /**
64
+ * Compiler-synthesized computed fields (#1556): one per inline conditional
65
+ * class. The caller appends them to the analyzed fields after lowering so
66
+ * the metadata, `__compiledProps` and `__computedFields` emission treat
67
+ * them exactly like authored computeds — the Part Program IR itself stays
68
+ * v1 (one class Part bound to the synthesized signal).
69
+ */
70
+ readonly synthesizedFields: CompiledField[];
71
+ /** True when the authored module binds the canonical `computed` import. */
72
+ readonly sourceBindsComputed: boolean;
73
+ /**
74
+ * The component's statically admitted class tokens (alpha15 S lane): every
75
+ * whitespace-separated token of every compile-time `class` value the
76
+ * lowering admits — static literals, primitive-literal attributes, both
77
+ * branches of an admitted conditional class, and `each` item-template
78
+ * literals. The compiler collects them as OPAQUE STRINGS: it never
79
+ * interprets Tailwind's class grammar, and the build layer hands the list
80
+ * to the official Tailwind compiler as explicit candidates.
81
+ */
82
+ readonly classCandidates: Set<string>;
83
+ /**
84
+ * Server mode side tables (alpha15 server lane): the nested server function
85
+ * component calls (element id → the recorded call shape, props entries as
86
+ * verbatim value texts) and the custom-element hosts the build admitted as
87
+ * compiled components (`__ssr`). The tree stays Part Program vocabulary —
88
+ * the code generator consumes these alongside it.
89
+ */
90
+ readonly componentCalls: Map<string, {
91
+ component: string;
92
+ propsEntries: Array<[string, string]>;
93
+ children: ProgramTreeNode[];
94
+ }>;
95
+ readonly ssrCalls: Set<string>;
96
+ private readonly server?;
97
+ private readonly plainFieldNames;
98
+ private readonly computedFieldNames;
99
+ private readonly sf;
100
+ private readonly options;
101
+ private elementSerial;
102
+ private conditionalClassSerial;
103
+ constructor(sf: ts.SourceFile, fields: CompiledField[], methodNames: string[], options?: LoweringOptions);
104
+ fail(node: ts.Node, code: string, message: string): never;
105
+ /**
106
+ * Record one compile-time class value's whitespace-separated tokens as
107
+ * Tailwind candidates (alpha15 S lane). The values are provably finite at
108
+ * compile time — the compiler's grammar admits no other shape — so the
109
+ * tokens are FACTS, not guesses: no runtime class interpolation ever
110
+ * contributes, and the compiler attaches no Tailwind semantics to them.
111
+ */
112
+ private collectClassCandidates;
113
+ private addSource;
114
+ private reserveElement;
115
+ private addElement;
116
+ private addPart;
117
+ private fieldAccess;
118
+ private methodAccess;
119
+ lowerRoot(expr: ts.Expression): ProgramTreeNode;
120
+ private normalizeAttributeName;
121
+ private lowerElement;
122
+ /**
123
+ * The one children walk both the class path and the server component
124
+ * branch share: JSX text cleaning, expression children (field read /
125
+ * literal / when / each), nested elements, and the fragments-and-spreads
126
+ * rejection. `elementPath` is the owning element's own address.
127
+ */
128
+ private lowerChildren;
129
+ /**
130
+ * Server function components: one uppercase JSX tag — a nested server
131
+ * function component reference. The call composes by DIRECT function call
132
+ * to the imported binding: attribute values cross as raw props (literals
133
+ * or `props.<field>` reads — the callee's own compiled body escapes at its
134
+ * sinks), and JSX children compose the `children` prop through the same
135
+ * children walk every other element takes.
136
+ */
137
+ private lowerComponentElement;
138
+ private lowerEvent;
139
+ private eventAction;
140
+ private parseEventMutation;
141
+ /**
142
+ * Inline conditional class (#1556): `class={this.<cond> ? 'a' : 'b'}` is
143
+ * authoring sugar for a computed field bound to the element's class Part —
144
+ * exactly the shape the author would hand-write as
145
+ * `@property({ reflect: false, attribute: false }) x = computed(() => ...)`
146
+ * plus `class={x}`. The lowering therefore reuses the computed-field
147
+ * machinery end to end: the condition validates under the same body grammar
148
+ * (only `this.<declared plain property>` reads; module-scope values pass
149
+ * through), the synthesized factory rides the existing `__computedFields`
150
+ * emission, and the Part Program stays v1 — one `class` Part whose signal
151
+ * is the synthesized computed signal. No runtime or IR shape changes; the
152
+ * serialized class value and its reactivity are the existing class-Part
153
+ * and computed-signal semantics on every execution mode.
154
+ *
155
+ * Both branches must be string literals (the class-attribute text); an
156
+ * empty string is the idiomatic off-branch. Everything else fails closed
157
+ * with OEC9011 — no runtime fallback (P2). A condition reading no declared
158
+ * property would emit a computed entry with an empty dep list, which the
159
+ * wire validator rejects, so it fails here at the source.
160
+ */
161
+ private lowerConditionalClass;
162
+ private lowerDynamicAttribute;
163
+ private lowerExpressionChild;
164
+ private parseCondition;
165
+ private lowerStaticBranch;
166
+ private lowerEach;
167
+ private lowerItemElement;
168
+ }
169
+ //#endregion