@mindees/compiler 0.22.3 → 0.22.5

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.
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ import { Maturity, NotImplementedError, PackageInfo, notImplemented } from "@min
12
12
  /** The npm package name. */
13
13
  declare const name = "@mindees/compiler";
14
14
  /** The package version. All `@mindees/*` packages share one locked version line. */
15
- declare const VERSION = "0.22.3";
15
+ declare const VERSION = "0.22.5";
16
16
  /**
17
17
  * Current maturity. The build-time optimizer — type-check gate, TSX→createElement
18
18
  * transform, tree-flattening, per-route manifest, plugin API — is implemented
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import { NotImplementedError, notImplemented } from "@mindees/core";
10
10
  /** The npm package name. */
11
11
  const name = "@mindees/compiler";
12
12
  /** The package version. All `@mindees/*` packages share one locked version line. */
13
- const VERSION = "0.22.3";
13
+ const VERSION = "0.22.5";
14
14
  /**
15
15
  * Current maturity. The build-time optimizer — type-check gate, TSX→createElement
16
16
  * transform, tree-flattening, per-route manifest, plugin API — is implemented
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Maturity, PackageInfo } from '@mindees/core'\nimport { NotImplementedError, notImplemented } from '@mindees/core'\n\n/** TS → native AOT (research track). */\nexport { compileToNative, type NativeTarget } from './aot'\n/** Build-time performance budget (opt-in via `compileChecked(src, { budget })`) — fails the build. */\nexport { type BudgetOptions, checkBudget } from './budget'\n/** Tree-flattening optimizer pass. */\nexport { createFlattenTransformer, STATIC_MARKER } from './flatten'\n/** Build-time perf-lint (opt-in via `compileChecked(src, { perf: true })`). */\nexport { type PerfLintOptions, perfLint } from './perf-lint'\n/** Per-route code-splitting manifest + file-based route codegen. */\nexport {\n buildRouteManifest,\n chunkName,\n fileToRoute,\n type GenerateRouteModuleOptions,\n generateRouteModule,\n type RouteEntry,\n type RouteManifest,\n} from './routes'\n/** Compile pipeline (TSX → optimized JS). */\nexport { compile, compileChecked } from './transform'\n/** The type-check gate. */\nexport { hasErrors, typecheck } from './typecheck'\n/** Shared types. */\nexport type {\n CompileOptions,\n CompileResult,\n CompileStats,\n Diagnostic,\n DiagnosticSeverity,\n MdcPlugin,\n SourcePosition,\n} from './types'\n\n/** The npm package name. */\nexport const name = '@mindees/compiler'\n\n/** The package version. All `@mindees/*` packages share one locked version line. */\nexport const VERSION = '0.22.3'\n\n/**\n * Current maturity. The build-time optimizer — type-check gate, TSX→createElement\n * transform, tree-flattening, per-route manifest, plugin API — is implemented\n * and tested on the TypeScript Compiler API. TS→native AOT is a research track\n * (throws `NotImplementedError`); the working path is TS → optimized JS.\n */\nexport const maturity: Maturity = 'experimental'\n\n/**\n * Static identity + maturity metadata for this package. Frozen so the\n * self-reported identity tooling introspects cannot be mutated at runtime,\n * matching the `readonly` fields of {@link PackageInfo}.\n */\nexport const info: PackageInfo = Object.freeze({ name, version: VERSION, maturity })\n\nexport type { Maturity, PackageInfo }\nexport { NotImplementedError, notImplemented }\n"],"mappings":";;;;;;;;;;AAqCA,MAAa,OAAO;;AAGpB,MAAa,UAAU;;;;;;;AAQvB,MAAa,WAAqB;;;;;;AAOlC,MAAa,OAAoB,OAAO,OAAO;CAAE;CAAM,SAAS;CAAS;AAAS,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Maturity, PackageInfo } from '@mindees/core'\nimport { NotImplementedError, notImplemented } from '@mindees/core'\n\n/** TS → native AOT (research track). */\nexport { compileToNative, type NativeTarget } from './aot'\n/** Build-time performance budget (opt-in via `compileChecked(src, { budget })`) — fails the build. */\nexport { type BudgetOptions, checkBudget } from './budget'\n/** Tree-flattening optimizer pass. */\nexport { createFlattenTransformer, STATIC_MARKER } from './flatten'\n/** Build-time perf-lint (opt-in via `compileChecked(src, { perf: true })`). */\nexport { type PerfLintOptions, perfLint } from './perf-lint'\n/** Per-route code-splitting manifest + file-based route codegen. */\nexport {\n buildRouteManifest,\n chunkName,\n fileToRoute,\n type GenerateRouteModuleOptions,\n generateRouteModule,\n type RouteEntry,\n type RouteManifest,\n} from './routes'\n/** Compile pipeline (TSX → optimized JS). */\nexport { compile, compileChecked } from './transform'\n/** The type-check gate. */\nexport { hasErrors, typecheck } from './typecheck'\n/** Shared types. */\nexport type {\n CompileOptions,\n CompileResult,\n CompileStats,\n Diagnostic,\n DiagnosticSeverity,\n MdcPlugin,\n SourcePosition,\n} from './types'\n\n/** The npm package name. */\nexport const name = '@mindees/compiler'\n\n/** The package version. All `@mindees/*` packages share one locked version line. */\nexport const VERSION = '0.22.5'\n\n/**\n * Current maturity. The build-time optimizer — type-check gate, TSX→createElement\n * transform, tree-flattening, per-route manifest, plugin API — is implemented\n * and tested on the TypeScript Compiler API. TS→native AOT is a research track\n * (throws `NotImplementedError`); the working path is TS → optimized JS.\n */\nexport const maturity: Maturity = 'experimental'\n\n/**\n * Static identity + maturity metadata for this package. Frozen so the\n * self-reported identity tooling introspects cannot be mutated at runtime,\n * matching the `readonly` fields of {@link PackageInfo}.\n */\nexport const info: PackageInfo = Object.freeze({ name, version: VERSION, maturity })\n\nexport type { Maturity, PackageInfo }\nexport { NotImplementedError, notImplemented }\n"],"mappings":";;;;;;;;;;AAqCA,MAAa,OAAO;;AAGpB,MAAa,UAAU;;;;;;;AAQvB,MAAa,WAAqB;;;;;;AAOlC,MAAa,OAAoB,OAAO,OAAO;CAAE;CAAM,SAAS;CAAS;AAAS,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"transform.d.ts","names":[],"sources":["../src/transform.ts"],"mappings":";;;AAwGoF;AAuDpF;;;;;;;AAvDoF,iBAApE,OAAA,CAAQ,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa;;AAuDO;;;iBAA3E,cAAA,CAAe,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa"}
1
+ {"version":3,"file":"transform.d.ts","names":[],"sources":["../src/transform.ts"],"mappings":";;;AAgJoF;AA2DpF;;;;;;;AA3DoF,iBAApE,OAAA,CAAQ,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa;;AA2DO;;;iBAA3E,cAAA,CAAe,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa"}
package/dist/transform.js CHANGED
@@ -59,7 +59,29 @@ function createRuntimeImportTransformer(tsmod) {
59
59
  const missing = RUNTIME_NAMES.filter((n) => referenced.has(n) && !imported.has(n));
60
60
  if (missing.length === 0) return sourceFile;
61
61
  const importDecl = tsmod.factory.createImportDeclaration(void 0, tsmod.factory.createImportClause(false, void 0, tsmod.factory.createNamedImports(missing.map((n) => tsmod.factory.createImportSpecifier(false, void 0, tsmod.factory.createIdentifier(n))))), tsmod.factory.createStringLiteral("@mindees/core"));
62
- return context.factory.updateSourceFile(sourceFile, [importDecl, ...sourceFile.statements]);
62
+ const stmts = sourceFile.statements;
63
+ let at = 0;
64
+ while (at < stmts.length && tsmod.isExpressionStatement(stmts[at]) && tsmod.isStringLiteral(stmts[at].expression)) at++;
65
+ return context.factory.updateSourceFile(sourceFile, [
66
+ ...stmts.slice(0, at),
67
+ importDecl,
68
+ ...stmts.slice(at)
69
+ ]);
70
+ };
71
+ }
72
+ /**
73
+ * A count-only transformer: tallies post-desugar `createElement(...)` calls into `stats.totalElements`
74
+ * (matching the flattener's own count) without modifying the tree. Used when `flatten` is off, so the
75
+ * element budget is enforced regardless of the optimizer.
76
+ */
77
+ function createElementCounter(tsmod, stats) {
78
+ return () => (sourceFile) => {
79
+ const visit = (node) => {
80
+ if (tsmod.isCallExpression(node) && tsmod.isIdentifier(node.expression) && node.expression.text === "createElement") stats.totalElements++;
81
+ tsmod.forEachChild(node, visit);
82
+ };
83
+ visit(sourceFile);
84
+ return sourceFile;
63
85
  };
64
86
  }
65
87
  /**
@@ -81,7 +103,7 @@ function compile(source, options = {}) {
81
103
  const flattener = createFlattenTransformer(ts);
82
104
  after.push(flattener.factory);
83
105
  stats = flattener.stats;
84
- }
106
+ } else after.push(createElementCounter(ts, stats));
85
107
  for (const plugin of plugins) after.push(plugin.transformer(ts));
86
108
  after.push(createRuntimeImportTransformer(ts));
87
109
  const output = ts.transpileModule(source, {
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","names":[],"sources":["../src/transform.ts"],"sourcesContent":["/**\n * The MDC transform/compile pipeline.\n *\n * `compile()` lowers TSX → `createElement(...)` (matching `@mindees/core`'s\n * factory), runs the built-in optimizer passes (tree-flattening) plus any user\n * plugins, and emits JavaScript + a source map. It does **not** type-check\n * (that's {@link typecheck}); `compileChecked()` runs the gate first and refuses\n * to emit on `error` diagnostics.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport { checkBudget } from './budget'\nimport { createFlattenTransformer } from './flatten'\nimport { perfLint } from './perf-lint'\nimport { hasErrors, typecheck } from './typecheck'\nimport type { CompileOptions, CompileResult, CompileStats } from './types'\n\n/** Compiler options for emit (JSX → `createElement`/`Fragment`, which the optimizer matches). */\nfunction emitOptions(sourceMap: boolean): ts.CompilerOptions {\n return {\n jsx: ts.JsxEmit.React,\n jsxFactory: 'createElement',\n jsxFragmentFactory: 'Fragment',\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n sourceMap,\n }\n}\n\n/** Runtime names the JSX desugar references; injected from `@mindees/core` if unbound. */\nconst RUNTIME_NAMES = ['createElement', 'Fragment'] as const\n\n/**\n * Ensure the JSX runtime is in scope. Idiomatic components use **automatic JSX** and import\n * nothing, but we emit classic `createElement(...)`/`Fragment` (so the tree-flatten optimizer\n * can match them) — which would be unbound at runtime. This transformer prepends\n * `import { createElement, Fragment } from '@mindees/core'` for any runtime name that is\n * referenced but not already imported, so emitted modules run. Runs LAST (after flatten/plugins),\n * so names the optimizer removed don't get a needless import.\n */\nfunction createRuntimeImportTransformer(tsmod: typeof ts): ts.TransformerFactory<ts.SourceFile> {\n return (context) => (sourceFile) => {\n // Every name already bound at the top level — from ANY import (named/aliased/default/namespace,\n // any module) OR a local var/function/class. We must never inject a runtime import for a name that\n // already has a binding: a duplicate top-level binding is a hard SyntaxError that fails module load.\n const imported = new Set<string>()\n for (const stmt of sourceFile.statements) {\n if (tsmod.isImportDeclaration(stmt) && stmt.importClause) {\n const clause = stmt.importClause\n if (clause.name) imported.add(clause.name.text) // default import\n const named = clause.namedBindings\n if (named) {\n if (tsmod.isNamespaceImport(named)) imported.add(named.name.text)\n else for (const el of named.elements) imported.add(el.name.text) // local binding name\n }\n } else if (tsmod.isVariableStatement(stmt)) {\n for (const d of stmt.declarationList.declarations) {\n if (tsmod.isIdentifier(d.name)) imported.add(d.name.text)\n }\n } else if (tsmod.isFunctionDeclaration(stmt) || tsmod.isClassDeclaration(stmt)) {\n if (stmt.name) imported.add(stmt.name.text)\n }\n }\n const referenced = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (tsmod.isIdentifier(node) && (RUNTIME_NAMES as readonly string[]).includes(node.text)) {\n referenced.add(node.text)\n }\n tsmod.forEachChild(node, visit)\n }\n visit(sourceFile)\n const missing = RUNTIME_NAMES.filter((n) => referenced.has(n) && !imported.has(n))\n if (missing.length === 0) return sourceFile\n const importDecl = tsmod.factory.createImportDeclaration(\n undefined,\n tsmod.factory.createImportClause(\n false,\n undefined,\n tsmod.factory.createNamedImports(\n missing.map((n) =>\n tsmod.factory.createImportSpecifier(\n false,\n undefined,\n tsmod.factory.createIdentifier(n),\n ),\n ),\n ),\n ),\n tsmod.factory.createStringLiteral('@mindees/core'),\n )\n return context.factory.updateSourceFile(sourceFile, [importDecl, ...sourceFile.statements])\n }\n}\n\n/**\n * Compile a single TSX/TS module to JavaScript.\n *\n * Pipeline: JSX desugar → tree-flatten (optional) → user plugins → emit.\n * Returns emitted code, an optional source map, any (transpile-level)\n * diagnostics, and optimizer stats. Use {@link compileChecked} to gate on the\n * full type checker.\n */\nexport function compile(source: string, options: CompileOptions = {}): CompileResult {\n const { fileName = 'module.tsx', sourceMap = true, flatten = true, plugins = [] } = options\n\n // IMPORTANT: our optimizer + plugins operate on the desugared\n // `createElement(...)` call form, but `transpileModule` runs `before`\n // transformers on the *pre-desugar* JSX AST. JSX is lowered during the\n // `after` phase, so flatten/plugins must run there to see the calls.\n const after: ts.TransformerFactory<ts.SourceFile>[] = []\n let stats: CompileStats = { flattenedNodes: 0, totalElements: 0 }\n\n if (flatten) {\n const flattener = createFlattenTransformer(ts)\n after.push(flattener.factory)\n stats = flattener.stats // live object, updated during emit\n }\n\n for (const plugin of plugins) {\n after.push(plugin.transformer(ts) as ts.TransformerFactory<ts.SourceFile>)\n }\n\n // LAST: bind the JSX runtime (automatic-JSX components import nothing) so output runs.\n after.push(createRuntimeImportTransformer(ts))\n\n const output = ts.transpileModule(source, {\n compilerOptions: emitOptions(sourceMap),\n fileName,\n reportDiagnostics: true,\n transformers: { after },\n })\n\n // transpileModule only surfaces a few syntactic diagnostics; semantic ones\n // come from the type-check gate. Map each to our structured form.\n const diagnostics = (output.diagnostics ?? []).map((d) => {\n const message = ts.flattenDiagnosticMessageText(d.messageText, '\\n')\n return {\n severity:\n d.category === ts.DiagnosticCategory.Error ? ('error' as const) : ('warning' as const),\n code: `TS${d.code}`,\n message,\n }\n })\n\n const result: CompileResult = {\n code: output.outputText,\n diagnostics,\n stats,\n }\n if (sourceMap && output.sourceMapText) result.map = output.sourceMapText\n return result\n}\n\n/**\n * Type-check then compile. If the gate finds any `error` diagnostic, returns it\n * WITHOUT emitting code (`code: ''`) — the build must not ship type errors.\n */\nexport function compileChecked(source: string, options: CompileOptions = {}): CompileResult {\n const fileName = options.fileName ?? 'module.tsx'\n const diagnostics = typecheck(source, fileName)\n if (hasErrors(diagnostics)) {\n return { code: '', diagnostics, stats: { flattenedNodes: 0, totalElements: 0 } }\n }\n const compiled = compile(source, options)\n // Opt-in build-time perf-lint: warnings only (never blocks — the gate above already returned on\n // errors, and every perf diagnostic is severity 'warning').\n const perfDiagnostics = options.perf\n ? perfLint(source, fileName, typeof options.perf === 'object' ? options.perf : {})\n : []\n // Performance budget (spec §12): violations are ERRORS that refuse to emit — \"100% optimized,\n // enforced.\" Attach the budget errors to a file so editors surface them.\n const budgetDiagnostics = options.budget\n ? checkBudget(compiled, options.budget).map((d) => ({ ...d, file: fileName }))\n : []\n const allDiagnostics = [\n ...diagnostics,\n ...perfDiagnostics,\n ...budgetDiagnostics,\n ...compiled.diagnostics,\n ]\n if (hasErrors(budgetDiagnostics)) {\n // Over budget → refuse to emit (same contract as the type-check gate above).\n return { code: '', diagnostics: allDiagnostics, stats: compiled.stats }\n }\n return { ...compiled, diagnostics: allDiagnostics }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,SAAS,YAAY,WAAwC;CAC3D,OAAO;EACL,KAAK,GAAG,QAAQ;EAChB,YAAY;EACZ,oBAAoB;EACpB,QAAQ,GAAG,aAAa;EACxB,QAAQ,GAAG,WAAW;EACtB;CACF;AACF;;AAGA,MAAM,gBAAgB,CAAC,iBAAiB,UAAU;;;;;;;;;AAUlD,SAAS,+BAA+B,OAAwD;CAC9F,QAAQ,aAAa,eAAe;EAIlC,MAAM,2BAAW,IAAI,IAAY;EACjC,KAAK,MAAM,QAAQ,WAAW,YAC5B,IAAI,MAAM,oBAAoB,IAAI,KAAK,KAAK,cAAc;GACxD,MAAM,SAAS,KAAK;GACpB,IAAI,OAAO,MAAM,SAAS,IAAI,OAAO,KAAK,IAAI;GAC9C,MAAM,QAAQ,OAAO;GACrB,IAAI,OACF,IAAI,MAAM,kBAAkB,KAAK,GAAG,SAAS,IAAI,MAAM,KAAK,IAAI;QAC3D,KAAK,MAAM,MAAM,MAAM,UAAU,SAAS,IAAI,GAAG,KAAK,IAAI;EAEnE,OAAO,IAAI,MAAM,oBAAoB,IAAI;QAClC,MAAM,KAAK,KAAK,gBAAgB,cACnC,IAAI,MAAM,aAAa,EAAE,IAAI,GAAG,SAAS,IAAI,EAAE,KAAK,IAAI;EAAA,OAErD,IAAI,MAAM,sBAAsB,IAAI,KAA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AS;EACtC;EACA,mBAAmB;EACnB,cAAc,EAAE,MAAM;CACxB,CAAC;CAID,MAAM,eAAe,OAAO,eAAe,CAAC,GAAG,KAAK,MAAM;EACxD,MAAM,UAAU,GAAG,6BAA6B,EAAE,aAAa,IAAI;EACnE,OAAO;GACL,UACE,EAAE,aAAa,GAAG,mBAAmB,QAAS,UAAqB;GACrE,MAAM,KAAK,EAAE;GACb;EACF;CACF,CAAC;CAED,MAAM,SAAwB;EAC5B,MAAM,OAAO;EACb;EACA;CACF;CACA,IAAI,aAAa,OAAO,eAAe,OAAO,MAAM,OAAO;CAC3D,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,QAAgB,UAA0B,CAAC,GAAkB;CAC1F,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,cAAc,UAAU,QAAQ,QAAQ;CAC9C,IAAI,UAAU,WAAW,GACvB,OAAO;EAAE,MAAM;EAAI;EAAa,OAAO;GAAE,gBAAgB;GAAG,eAAe;EAAE;CAAE;CAEjF,MAAM,WAAW,QAAQ,QAAQ,OAAO;CAGxC,MAAM,kBAAkB,QAAQ,OAC5B,SAAS,QAAQ,UAAU,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO,CAAC,CAAC,IAC/E,CAAC;CAGL,MAAM,oBAAoB,QAAQ,SAC9B,YAAY,UAAU,QAAQ,MAAM,EAAE,KAAK,OAAO;EAAE,GAAG;EAAG,MAAM;CAAS,EAAE,IAC3E,CAAC;CACL,MAAM,iBAAiB;EACrB,GAAG;EACH,GAAG;EACH,GAAG;EACH,GAAG,SAAS;CACd;CACA,IAAI,UAAU,iBAAiB,GAE7B,OAAO;EAAE,MAAM;EAAI,aAAa;EAAgB,OAAO,SAAS;CAAM;CAExE,OAAO;EAAE,GAAG;EAAU,aAAa;CAAe;AACpD"}
1
+ {"version":3,"file":"transform.js","names":[],"sources":["../src/transform.ts"],"sourcesContent":["/**\n * The MDC transform/compile pipeline.\n *\n * `compile()` lowers TSX → `createElement(...)` (matching `@mindees/core`'s\n * factory), runs the built-in optimizer passes (tree-flattening) plus any user\n * plugins, and emits JavaScript + a source map. It does **not** type-check\n * (that's {@link typecheck}); `compileChecked()` runs the gate first and refuses\n * to emit on `error` diagnostics.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport { checkBudget } from './budget'\nimport { createFlattenTransformer } from './flatten'\nimport { perfLint } from './perf-lint'\nimport { hasErrors, typecheck } from './typecheck'\nimport type { CompileOptions, CompileResult, CompileStats } from './types'\n\n/** Compiler options for emit (JSX → `createElement`/`Fragment`, which the optimizer matches). */\nfunction emitOptions(sourceMap: boolean): ts.CompilerOptions {\n return {\n jsx: ts.JsxEmit.React,\n jsxFactory: 'createElement',\n jsxFragmentFactory: 'Fragment',\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n sourceMap,\n }\n}\n\n/** Runtime names the JSX desugar references; injected from `@mindees/core` if unbound. */\nconst RUNTIME_NAMES = ['createElement', 'Fragment'] as const\n\n/**\n * Ensure the JSX runtime is in scope. Idiomatic components use **automatic JSX** and import\n * nothing, but we emit classic `createElement(...)`/`Fragment` (so the tree-flatten optimizer\n * can match them) — which would be unbound at runtime. This transformer prepends\n * `import { createElement, Fragment } from '@mindees/core'` for any runtime name that is\n * referenced but not already imported, so emitted modules run. Runs LAST (after flatten/plugins),\n * so names the optimizer removed don't get a needless import.\n */\nfunction createRuntimeImportTransformer(tsmod: typeof ts): ts.TransformerFactory<ts.SourceFile> {\n return (context) => (sourceFile) => {\n // Every name already bound at the top level — from ANY import (named/aliased/default/namespace,\n // any module) OR a local var/function/class. We must never inject a runtime import for a name that\n // already has a binding: a duplicate top-level binding is a hard SyntaxError that fails module load.\n const imported = new Set<string>()\n for (const stmt of sourceFile.statements) {\n if (tsmod.isImportDeclaration(stmt) && stmt.importClause) {\n const clause = stmt.importClause\n if (clause.name) imported.add(clause.name.text) // default import\n const named = clause.namedBindings\n if (named) {\n if (tsmod.isNamespaceImport(named)) imported.add(named.name.text)\n else for (const el of named.elements) imported.add(el.name.text) // local binding name\n }\n } else if (tsmod.isVariableStatement(stmt)) {\n for (const d of stmt.declarationList.declarations) {\n if (tsmod.isIdentifier(d.name)) imported.add(d.name.text)\n }\n } else if (tsmod.isFunctionDeclaration(stmt) || tsmod.isClassDeclaration(stmt)) {\n if (stmt.name) imported.add(stmt.name.text)\n }\n }\n const referenced = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (tsmod.isIdentifier(node) && (RUNTIME_NAMES as readonly string[]).includes(node.text)) {\n referenced.add(node.text)\n }\n tsmod.forEachChild(node, visit)\n }\n visit(sourceFile)\n const missing = RUNTIME_NAMES.filter((n) => referenced.has(n) && !imported.has(n))\n if (missing.length === 0) return sourceFile\n const importDecl = tsmod.factory.createImportDeclaration(\n undefined,\n tsmod.factory.createImportClause(\n false,\n undefined,\n tsmod.factory.createNamedImports(\n missing.map((n) =>\n tsmod.factory.createImportSpecifier(\n false,\n undefined,\n tsmod.factory.createIdentifier(n),\n ),\n ),\n ),\n ),\n tsmod.factory.createStringLiteral('@mindees/core'),\n )\n // Insert the import AFTER any leading directive prologue (\"use client\"/\"use server\"/\"use strict\"):\n // an import before a directive demotes it to a no-op string-expression statement (breaking RSC).\n const stmts = sourceFile.statements\n let at = 0\n while (\n at < stmts.length &&\n tsmod.isExpressionStatement(stmts[at] as ts.Statement) &&\n tsmod.isStringLiteral((stmts[at] as ts.ExpressionStatement).expression)\n ) {\n at++\n }\n return context.factory.updateSourceFile(sourceFile, [\n ...stmts.slice(0, at),\n importDecl,\n ...stmts.slice(at),\n ])\n }\n}\n\n/**\n * A count-only transformer: tallies post-desugar `createElement(...)` calls into `stats.totalElements`\n * (matching the flattener's own count) without modifying the tree. Used when `flatten` is off, so the\n * element budget is enforced regardless of the optimizer.\n */\nfunction createElementCounter(\n tsmod: typeof ts,\n stats: CompileStats,\n): ts.TransformerFactory<ts.SourceFile> {\n return () => (sourceFile) => {\n const visit = (node: ts.Node): void => {\n if (\n tsmod.isCallExpression(node) &&\n tsmod.isIdentifier(node.expression) &&\n node.expression.text === 'createElement'\n ) {\n stats.totalElements++\n }\n tsmod.forEachChild(node, visit)\n }\n visit(sourceFile)\n return sourceFile\n }\n}\n\n/**\n * Compile a single TSX/TS module to JavaScript.\n *\n * Pipeline: JSX desugar → tree-flatten (optional) → user plugins → emit.\n * Returns emitted code, an optional source map, any (transpile-level)\n * diagnostics, and optimizer stats. Use {@link compileChecked} to gate on the\n * full type checker.\n */\nexport function compile(source: string, options: CompileOptions = {}): CompileResult {\n const { fileName = 'module.tsx', sourceMap = true, flatten = true, plugins = [] } = options\n\n // IMPORTANT: our optimizer + plugins operate on the desugared\n // `createElement(...)` call form, but `transpileModule` runs `before`\n // transformers on the *pre-desugar* JSX AST. JSX is lowered during the\n // `after` phase, so flatten/plugins must run there to see the calls.\n const after: ts.TransformerFactory<ts.SourceFile>[] = []\n let stats: CompileStats = { flattenedNodes: 0, totalElements: 0 }\n\n if (flatten) {\n const flattener = createFlattenTransformer(ts)\n after.push(flattener.factory)\n stats = flattener.stats // live object, updated during emit\n } else {\n // No flatten pass → still count elements so the element budget (checkBudget) applies regardless of\n // `flatten`. Counts the same thing the flattener does: post-desugar `createElement(...)` calls.\n after.push(createElementCounter(ts, stats))\n }\n\n for (const plugin of plugins) {\n after.push(plugin.transformer(ts) as ts.TransformerFactory<ts.SourceFile>)\n }\n\n // LAST: bind the JSX runtime (automatic-JSX components import nothing) so output runs.\n after.push(createRuntimeImportTransformer(ts))\n\n const output = ts.transpileModule(source, {\n compilerOptions: emitOptions(sourceMap),\n fileName,\n reportDiagnostics: true,\n transformers: { after },\n })\n\n // transpileModule only surfaces a few syntactic diagnostics; semantic ones\n // come from the type-check gate. Map each to our structured form.\n const diagnostics = (output.diagnostics ?? []).map((d) => {\n const message = ts.flattenDiagnosticMessageText(d.messageText, '\\n')\n return {\n severity:\n d.category === ts.DiagnosticCategory.Error ? ('error' as const) : ('warning' as const),\n code: `TS${d.code}`,\n message,\n }\n })\n\n const result: CompileResult = {\n code: output.outputText,\n diagnostics,\n stats,\n }\n if (sourceMap && output.sourceMapText) result.map = output.sourceMapText\n return result\n}\n\n/**\n * Type-check then compile. If the gate finds any `error` diagnostic, returns it\n * WITHOUT emitting code (`code: ''`) — the build must not ship type errors.\n */\nexport function compileChecked(source: string, options: CompileOptions = {}): CompileResult {\n const fileName = options.fileName ?? 'module.tsx'\n const diagnostics = typecheck(source, fileName)\n if (hasErrors(diagnostics)) {\n return { code: '', diagnostics, stats: { flattenedNodes: 0, totalElements: 0 } }\n }\n const compiled = compile(source, options)\n // Opt-in build-time perf-lint: warnings only (never blocks — the gate above already returned on\n // errors, and every perf diagnostic is severity 'warning').\n const perfDiagnostics = options.perf\n ? perfLint(source, fileName, typeof options.perf === 'object' ? options.perf : {})\n : []\n // Performance budget (spec §12): violations are ERRORS that refuse to emit — \"100% optimized,\n // enforced.\" Attach the budget errors to a file so editors surface them.\n const budgetDiagnostics = options.budget\n ? checkBudget(compiled, options.budget).map((d) => ({ ...d, file: fileName }))\n : []\n const allDiagnostics = [\n ...diagnostics,\n ...perfDiagnostics,\n ...budgetDiagnostics,\n ...compiled.diagnostics,\n ]\n if (hasErrors(budgetDiagnostics)) {\n // Over budget → refuse to emit (same contract as the type-check gate above).\n return { code: '', diagnostics: allDiagnostics, stats: compiled.stats }\n }\n return { ...compiled, diagnostics: allDiagnostics }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,SAAS,YAAY,WAAwC;CAC3D,OAAO;EACL,KAAK,GAAG,QAAQ;EAChB,YAAY;EACZ,oBAAoB;EACpB,QAAQ,GAAG,aAAa;EACxB,QAAQ,GAAG,WAAW;EACtB;CACF;AACF;;AAGA,MAAM,gBAAgB,CAAC,iBAAiB,UAAU;;;;;;;;;AAUlD,SAAS,+BAA+B,OAAwD;CAC9F,QAAQ,aAAa,eAAe;EAIlC,MAAM,2BAAW,IAAI,IAAY;EACjC,KAAK,MAAM,QAAQ,WAAW,YAC5B,IAAI,MAAM,oBAA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M,SAAwB;EAC5B,MAAM,OAAO;EACb;EACA;CACF;CACA,IAAI,aAAa,OAAO,eAAe,OAAO,MAAM,OAAO;CAC3D,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,QAAgB,UAA0B,CAAC,GAAkB;CAC1F,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,cAAc,UAAU,QAAQ,QAAQ;CAC9C,IAAI,UAAU,WAAW,GACvB,OAAO;EAAE,MAAM;EAAI;EAAa,OAAO;GAAE,gBAAgB;GAAG,eAAe;EAAE;CAAE;CAEjF,MAAM,WAAW,QAAQ,QAAQ,OAAO;CAGxC,MAAM,kBAAkB,QAAQ,OAC5B,SAAS,QAAQ,UAAU,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO,CAAC,CAAC,IAC/E,CAAC;CAGL,MAAM,oBAAoB,QAAQ,SAC9B,YAAY,UAAU,QAAQ,MAAM,EAAE,KAAK,OAAO;EAAE,GAAG;EAAG,MAAM;CAAS,EAAE,IAC3E,CAAC;CACL,MAAM,iBAAiB;EACrB,GAAG;EACH,GAAG;EACH,GAAG;EACH,GAAG,SAAS;CACd;CACA,IAAI,UAAU,iBAAiB,GAE7B,OAAO;EAAE,MAAM;EAAI,aAAa;EAAgB,OAAO,SAAS;CAAM;CAExE,OAAO;EAAE,GAAG;EAAU,aAAa;CAAe;AACpD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindees/compiler",
3
- "version": "0.22.3",
3
+ "version": "0.22.5",
4
4
  "description": "MindeesNative Compiler (MDC) — build-time optimizer: type-check gate, TSX→createElement transform, tree-flattening, per-route code-splitting, and a plugin API. TS→native AOT is a research track.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "type": "module",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "typescript": "6.0.3",
27
- "@mindees/core": "0.22.3"
27
+ "@mindees/core": "0.22.5"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsdown",