@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
@@ -170,17 +170,70 @@ function createModuleIntrinsicBindings(sourceFile, options = {}) {
170
170
  const modules = typeof module === "string" ? [module] : module;
171
171
  const bindings = imports.get(localName) ?? [];
172
172
  return bindings.length === 1 && bindings[0].form === "named" && modules.includes(bindings[0].module) && bindings[0].imported === imported && !bindings[0].typeOnly;
173
+ },
174
+ hasModuleScopeBinding(localName) {
175
+ return locals.has(localName) || imports.has(localName);
173
176
  }
174
177
  };
175
178
  }
176
179
  function isCustomElementTag(value) {
177
180
  return /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(value);
178
181
  }
182
+ /**
183
+ * The exported name of a function declaration / single-declarator variable
184
+ * statement that {@link isExportedServerComponentDeclaration} admitted.
185
+ */
186
+ function serverComponentName(statement) {
187
+ if (ts.isFunctionDeclaration(statement)) return statement.name?.text ?? "";
188
+ const declaration = statement.declarationList.declarations[0];
189
+ return ts.isIdentifier(declaration.name) ? declaration.name.text : "";
190
+ }
191
+ function returnsJsx(expression) {
192
+ const value = expression && ts.isParenthesizedExpression(expression) ? expression.expression : expression;
193
+ return value !== void 0 && (ts.isJsxElement(value) || ts.isJsxSelfClosingElement(value));
194
+ }
195
+ /**
196
+ * The structural server function component shapes the fact scan reports:
197
+ * a named `export function` whose body is exactly one `return <jsx>` or an
198
+ * `export const` arrow whose expression body is JSX. The compile entry
199
+ * (`compileServerComponentModule`) re-derives the same shapes with
200
+ * fail-closed diagnostics; this scan only answers "is there something to
201
+ * compile here" for the module graph walker.
202
+ */
203
+ function isExportedServerComponentDeclaration(statement) {
204
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];
205
+ if (!modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false;
206
+ if (ts.isFunctionDeclaration(statement)) {
207
+ if (statement.name === void 0 || modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) || statement.body === void 0 || !ts.isBlock(statement.body)) return false;
208
+ const returns = statement.body.statements.filter(ts.isReturnStatement);
209
+ return statement.body.statements.length === 1 && returns.length === 1 && returnsJsx(returns[0].expression);
210
+ }
211
+ if (ts.isVariableStatement(statement)) {
212
+ const declarations = statement.declarationList.declarations;
213
+ if (declarations.length !== 1 || !ts.isIdentifier(declarations[0].name)) return false;
214
+ const initializer = declarations[0].initializer;
215
+ return initializer !== void 0 && ts.isArrowFunction(initializer) && !ts.isBlock(initializer.body) && returnsJsx(initializer.body);
216
+ }
217
+ return false;
218
+ }
179
219
  function stringArgument(call, index = 0) {
180
220
  const argument = call.arguments[index];
181
221
  return argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : void 0;
182
222
  }
183
223
  /**
224
+ * Whether a `.define(...)` callee object is the platform CustomElementRegistry:
225
+ * a bare module-unbound `customElements` global, or the registry reached
226
+ * through an unambiguous unbound global qualifier
227
+ * (`window.`/`globalThis.`/`self.`). Raw text matching misfires both ways — a
228
+ * module-scope `customElements` binding (import or local) is a shadow, not the
229
+ * registry, while a qualified global spelling is the registry and must count.
230
+ */
231
+ function isCustomElementsRegistry(object, imports) {
232
+ if (ts.isIdentifier(object)) return object.text === "customElements" && !imports.hasModuleScopeBinding(object.text);
233
+ if (ts.isPropertyAccessExpression(object) && object.name.text === "customElements" && ts.isIdentifier(object.expression) && !imports.hasModuleScopeBinding(object.expression.text)) return object.expression.text === "window" || object.expression.text === "globalThis" || object.expression.text === "self";
234
+ return false;
235
+ }
236
+ /**
184
237
  * Parse one module source and report the semantic facts the compiler boundary
185
238
  * and the Vite graph adapters branch on. Pure: it never resolves imports from
186
239
  * disk and never throws on foreign or invalid syntax — an unparsable module
@@ -197,24 +250,38 @@ function analyzeModuleSemantics(source, fileName, options = {}) {
197
250
  const pageDefinitionBindings = vocabulary.filter((descriptor) => descriptor.kind === "page-definition");
198
251
  const registrationBindings = vocabulary.filter((descriptor) => descriptor.kind === "element-registration");
199
252
  const relativeImports = /* @__PURE__ */ new Set();
200
- for (const statement of sourceFile.statements) if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text.startsWith(".")) relativeImports.add(statement.moduleSpecifier.text);
253
+ const moduleSpecifiers = /* @__PURE__ */ new Set();
254
+ for (const statement of sourceFile.statements) if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
255
+ moduleSpecifiers.add(statement.moduleSpecifier.text);
256
+ if (statement.moduleSpecifier.text.startsWith(".")) relativeImports.add(statement.moduleSpecifier.text);
257
+ }
201
258
  let exportedTagName;
202
259
  let compiledElementDecorator = false;
203
260
  let unsupportedElementDecorator;
204
261
  let definePage = fileName.endsWith(".mdx");
262
+ let pageComponentName;
205
263
  let usesExportedTagName = false;
206
264
  let enhancedForm = false;
207
265
  let defaultCompiledTag;
208
266
  const defined = /* @__PURE__ */ new Set();
209
267
  const referenced = /* @__PURE__ */ new Set();
210
268
  const interactionEvents = /* @__PURE__ */ new Set();
269
+ const serverComponents = /* @__PURE__ */ new Set();
270
+ for (const statement of sourceFile.statements) if (isExportedServerComponentDeclaration(statement)) serverComponents.add(serverComponentName(statement));
211
271
  for (const statement of sourceFile.statements) {
212
272
  if (ts.isVariableStatement(statement) && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
213
273
  for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === "tagName" && declaration.initializer && (ts.isStringLiteral(declaration.initializer) || ts.isNoSubstitutionTemplateLiteral(declaration.initializer))) exportedTagName = declaration.initializer.text;
214
274
  }
215
275
  if (ts.isExportAssignment(statement) && ts.isCallExpression(statement.expression) && ts.isIdentifier(statement.expression.expression)) {
216
276
  const pageFactory = statement.expression.expression.text;
217
- if (pageDefinitionBindings.some((descriptor) => imports.isRuntimeNamedImport(pageFactory, descriptor.moduleSpecifier, descriptor.exportName))) definePage = true;
277
+ const matchedPageBinding = pageDefinitionBindings.find((descriptor) => imports.isRuntimeNamedImport(pageFactory, descriptor.moduleSpecifier, descriptor.exportName));
278
+ if (matchedPageBinding) {
279
+ definePage = true;
280
+ if (matchedPageBinding.kind === "page-definition" && matchedPageBinding.exportName === "definePage") {
281
+ const firstArgument = statement.expression.arguments[0];
282
+ if (firstArgument !== void 0 && ts.isIdentifier(firstArgument) && serverComponents.has(firstArgument.text)) pageComponentName = firstArgument.text;
283
+ }
284
+ }
218
285
  }
219
286
  if (!ts.isClassDeclaration(statement)) continue;
220
287
  const isDefault = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
@@ -249,7 +316,7 @@ function analyzeModuleSemantics(source, fileName, options = {}) {
249
316
  const tag = stringArgument(node);
250
317
  if (tag && isCustomElementTag(tag)) referenced.add(tag);
251
318
  }
252
- } else if (ts.isPropertyAccessExpression(expression) && expression.expression.getText(sourceFile) === "customElements" && expression.name.text === "define") {
319
+ } else if (ts.isPropertyAccessExpression(expression) && expression.name.text === "define" && isCustomElementsRegistry(expression.expression, imports)) {
253
320
  const tag = stringArgument(node);
254
321
  if (tag && isCustomElementTag(tag)) defined.add(tag);
255
322
  if (tag !== void 0 && tag === exportedTagName) usesExportedTagName = true;
@@ -277,10 +344,13 @@ function analyzeModuleSemantics(source, fileName, options = {}) {
277
344
  visit(sourceFile);
278
345
  return {
279
346
  relativeImports: [...relativeImports],
347
+ ...options.collectSpecifiers === true ? { moduleSpecifiers: [...moduleSpecifiers] } : {},
280
348
  compiledElementDecorator,
281
349
  ...unsupportedElementDecorator === void 0 ? {} : { unsupportedElementDecorator },
282
350
  ...exportedTagName === void 0 ? {} : { exportedTagName },
283
351
  definePage,
352
+ ...pageComponentName === void 0 ? {} : { pageComponentName },
353
+ serverFunctionComponents: [...serverComponents].sort(),
284
354
  usesExportedTagName,
285
355
  enhancedForm,
286
356
  ...defaultCompiledTag === void 0 ? {} : { defaultCompiledTag },
@@ -290,4 +360,4 @@ function analyzeModuleSemantics(source, fileName, options = {}) {
290
360
  };
291
361
  }
292
362
  //#endregion
293
- export { CANONICAL_BASE_CLASS_INTRINSICS, analyzeModuleSemantics, createModuleIntrinsicBindings, isCompileTimeOnlyImport, resolveCanonicalBaseClass };
363
+ export { CANONICAL_BASE_CLASS_INTRINSICS, analyzeModuleSemantics, createModuleIntrinsicBindings, isCompileTimeOnlyImport, isExportedServerComponentDeclaration, resolveCanonicalBaseClass, serverComponentName };
@@ -0,0 +1,114 @@
1
+ import { CompiledElementSourceMap } from "./source-map.js";
2
+ import { CompilerFail } from "./compiler-diagnostics.js";
3
+ import { Lowering } from "./lower-program.js";
4
+ import ts from "typescript";
5
+ import { ProgramTreeNode } from "@openelement/protocol/part-program";
6
+ //#region src/internal/compiler/semantic-core/server-component.d.ts
7
+ /** Host-supplied inputs for the server function component compile. */
8
+ export interface ServerComponentCompileOptions {
9
+ /**
10
+ * Resolve one authored import specifier to that module's SOURCE, so a
11
+ * nested server function component composes by direct call to the imported
12
+ * binding (compile-time resolved, deterministic). Absent or returning
13
+ * undefined: importing components from that specifier is a coded rejection.
14
+ * Resolution of specifiers to files stays the host's job — the compiler
15
+ * never reads the filesystem.
16
+ */
17
+ readonly resolveModule?: (specifier: string) => string | undefined;
18
+ /**
19
+ * The custom-element host tags the host build admitted as @element
20
+ * compiled components: those JSX children ride `__ssr(tag, props)`.
21
+ * Unadmitted hosts (islands, foreign tags) emit their tag as-is.
22
+ */
23
+ readonly compiledTags?: readonly string[];
24
+ }
25
+ /** The compiled server function component module. */
26
+ export interface CompileServerComponentResult {
27
+ /** The generated TS module: verbatim authored content + constructor functions. */
28
+ code: string;
29
+ /** Real Source Map v3 for the generated component functions. */
30
+ map: CompiledElementSourceMap;
31
+ /** The compiled component names, sorted. */
32
+ components: string[];
33
+ /**
34
+ * The statically admitted class tokens (alpha15 S lane), unioned over the
35
+ * compiled components — the host build forwards them to the official
36
+ * Tailwind compiler as explicit candidates.
37
+ */
38
+ classCandidates?: string[];
39
+ }
40
+ /**
41
+ * Compile one authored TSX module's server function components into the
42
+ * generative constructor module. Returns null for modules with no exported
43
+ * JSX-returning function (nothing to admit). Fails closed with a
44
+ * {@link CompiledElementError} carrying the ordered OEC diagnostics.
45
+ */
46
+ export declare function compileServerComponentModule(source: string, fileName: string, options?: ServerComponentCompileOptions): CompileServerComponentResult | null;
47
+ /**
48
+ * The host-build admission bridge: compile `code` through the server function
49
+ * component lane when — and only when — this module belongs to it.
50
+ *
51
+ * - a module carrying a compiled-element decorator (or an unsupported
52
+ * decorator spelling, which the class lane compiles so it fails closed with
53
+ * OEC9027) belongs to the class lane: null;
54
+ * - a module with no discovered server function component has nothing to
55
+ * admit: null;
56
+ * - a non-`.tsx` id can never carry the JSX grammar: null;
57
+ * - the cheap `export` + `<` prefilter (the same conservative superset idea
58
+ * the class lane's prefilter uses) keeps plainly inert modules off the
59
+ * parse.
60
+ *
61
+ * Everything else goes through {@link compileServerComponentModule}, whose
62
+ * diagnostics fail the build closed.
63
+ */
64
+ export declare function compileServerComponentIfAdmitted(code: string, id: string, options?: ServerComponentCompileOptions): CompileServerComponentResult | null;
65
+ /**
66
+ * The generated-constructor expression builder: one walk over the lowered
67
+ * tree that turns admitted nodes into `__h`/`__t`/`__ssr`/direct-call code.
68
+ * Static attribute values are compile-time literals; every dynamic value
69
+ * enters through a helper boundary.
70
+ *
71
+ * Code-construction boundary (CodeQL js/bad-code-sanitization #4238, FRM-05):
72
+ * every value this class splices into the generated module is either an
73
+ * `JSON.stringify`-quoted string literal (the ECMAScript QuoteJSONString
74
+ * escaping for a TS string literal) or a name validated by `identifier()`
75
+ * below; ordering-comparison operands are finite numeric literals only
76
+ * (protocol `conditionLiteralAllowed`). The artifact is a standalone TS module
77
+ * returned to the host build's transform — never inlined into HTML — so the
78
+ * query's script-embedding model does not apply. Evidence and the hostile-input
79
+ * regression live in this batch's REL-02 CodeQL disposition record and in the
80
+ * server-component-codegen-boundary regression test.
81
+ */
82
+ declare class ConstructorEmitter {
83
+ private readonly sf;
84
+ private readonly lowering;
85
+ private readonly parameter;
86
+ private readonly fail;
87
+ constructor(sf: ts.SourceFile, lowering: Lowering, parameter: string, fail: CompilerFail);
88
+ /**
89
+ * The codegen identifier boundary: every lowering-produced name the emitter
90
+ * splices into an IDENTIFIER position of the generated module
91
+ * (`props.<signal>`, `item.<field>`, the component binding) must be a plain
92
+ * ES identifier. Anything else would leave its slot and inject arbitrary
93
+ * source into the artifact, so a non-identifier fails the compile CLOSED —
94
+ * same diagnostic shape as the lowering's own "must be a plain identifier"
95
+ * refusals, never a silent fallback or a dropped sink. The lowering
96
+ * validates most names on the way in; this is the one boundary every
97
+ * emitted name passes, so a future lowering change cannot silently widen
98
+ * the splice.
99
+ */
100
+ private identifier;
101
+ emit(root: ProgramTreeNode): string;
102
+ private sinksOf;
103
+ /**
104
+ * The slot-name expression for one child of a `__ssr` host: the child's
105
+ * static `slot` attribute as a literal, else its dynamic attr sink named
106
+ * `slot` (the same props read the emitted attribute takes), else `''` — the
107
+ * default slot. Text and Part children are always default-slot: the class
108
+ * path's own `slotNameOf` reads exactly these sources.
109
+ */
110
+ private slotNameExpressionOf;
111
+ private conditionText;
112
+ private node;
113
+ }
114
+ //#endregion