@pithyjs/vite-plugin 0.2.0-beta.20 → 0.2.0-beta.21

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.
@@ -30,6 +30,33 @@ export interface PithyBabelPluginOptions {
30
30
  strictAot?: boolean;
31
31
  /** File path for deterministic scope ID generation (typically the Vite module id). */
32
32
  filename?: string;
33
+ /** Receives each template finding. Default: `console.warn` of its `message`. */
34
+ onFinding?: (finding: TemplateFinding) => void;
35
+ }
36
+ /**
37
+ * A component attribute that will not reach the component as the author meant:
38
+ * its value does not parse (`unparsed`, the attribute is dropped), or it reads
39
+ * names this module does not bind (`unbound`).
40
+ */
41
+ /** @codexApi {"parent":"pithy.babel.html-context-plugin","name":"TemplateFinding","stability":"experimental","signature":"interface TemplateFinding"} */
42
+ export interface TemplateFinding {
43
+ kind: 'unparsed' | 'unbound';
44
+ tag: string;
45
+ attr: string;
46
+ value: string;
47
+ /** The names read with no binding; empty for `unparsed`. */
48
+ unbound: string[];
49
+ /** The parser's error for `unparsed`; `null` otherwise. */
50
+ error: string | null;
51
+ /** The attribute quoted as a string literal, when that is the likely intent. */
52
+ fix: string | null;
53
+ file: string | null;
54
+ /** 1-based, of the template expression in the module. */
55
+ line: number | null;
56
+ /** 1-based. */
57
+ column: number | null;
58
+ /** The text the plugin warns with. */
59
+ message: string;
33
60
  }
34
61
  /**
35
62
  * Babel plugin that transforms `html\`...\`` tagged template expressions.
@@ -1 +1 @@
1
- {"version":3,"file":"babelPlugin.d.ts","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAGF,OAAO,KAAK,EAAY,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAGL,KAAK,kBAAkB,EACxB,MAAM,0BAA0B,CAAC;AAWlC,UAAU,WAAY,SAAQ,UAAU;IACtC,mBAAmB,EAAE,GAAG,CAAC,MAAM,CAA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ACb,KAAK,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,2DAA2D;IAC3D,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,gFAAgF;IAChF,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,yDAAyD;IACzD,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,eAAe;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB;AAoBD;;;;;;;GAOG;AACH,wLAAwL;AACxL,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,OAAO,CAAC,EAAE,uBAAuB,GAChC,SAAS,CAAC,WAAW,CAAC,CAqvBxB"}
@@ -651,24 +651,39 @@ export default function pithyBabelPlugin(options) {
651
651
  if (warnsOnComponentProp(attr, value))
652
652
  return;
653
653
  let outcome = `does not parse (Failed to parse expression: ${error}), so the attribute is dropped`;
654
+ let unbound = [];
654
655
  if (parsed) {
655
656
  const collected = new Set(names);
656
657
  const candidates = expression ? stringLikeNames(expression) : null;
657
- const unbound = [...new Set(candidates ?? [])].filter(name => collected.has(name) && !isDeclared(name));
658
+ unbound = [...new Set(candidates ?? [])].filter(name => collected.has(name) && !isDeclared(name));
658
659
  if (unbound.length === 0)
659
660
  return;
660
661
  outcome = `reads ${unbound.map(n => `\`${n}\``).join(', ')}, which ${unbound.length === 1 ? 'has' : 'have'} ${missing}, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime`;
661
662
  }
662
- let advice = '';
663
- if (parsed || !/[()[\]{};=]/.test(value)) {
664
- advice = ` To pass a string, quote it: ${attr}=${quote(value)}.`;
665
- }
666
- const file = sourceFile(path);
663
+ const fix = parsed || !/[()[\]{};=]/.test(value) ? `${attr}=${quote(value)}` : null;
664
+ const advice = fix ? ` To pass a string, quote it: ${fix}.` : '';
665
+ const file = sourceFile(path) ?? null;
667
666
  const loc = path.node.loc?.start;
668
667
  const where = file
669
668
  ? ` (${file}${loc ? `:${loc.line}:${loc.column + 1}` : ''})`
670
669
  : '';
671
- console.warn(`[pithy] <${tag} ${attr}="${value}">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`);
670
+ const finding = {
671
+ kind: parsed ? 'unbound' : 'unparsed',
672
+ tag,
673
+ attr,
674
+ value,
675
+ unbound,
676
+ error: parsed ? null : (error ?? null),
677
+ fix,
678
+ file,
679
+ line: loc?.line ?? null,
680
+ column: loc ? loc.column + 1 : null,
681
+ message: `[pithy] <${tag} ${attr}="${value}">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`,
682
+ };
683
+ if (options?.onFinding)
684
+ options.onFinding(finding);
685
+ else
686
+ console.warn(finding.message);
672
687
  }
673
688
  function reportJitFallback(path, reason) {
674
689
  const where = options?.filename ? ` (${options.filename})` : '';
@@ -1 +1 @@
1
- {"version":3,"file":"babelPlugin.js","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EACL,sBAAsB,GAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,aAAa,EACb,4BAA4B,EAE5B,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMnD;;;;;GAKG;AACH,6JAA6J;AAC7J,SAAS,sBAAsB,CAAC,CAAS;IACvC,6BAA6B;IAC7B,0CAA0C;IAC1C,wFAAwF;IACxF,MAAM,GAA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c,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YAEvC,qDAAqD;YACrD,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YACtC,2EAA2E;YAC3E,2EAA2E;YAC3E,wEAAwE;YACxE,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,yBAAyB,CAAC,EAAE,CAAC;gBACvD,qBAAqB,GAAG,IAAI,CAAC;YAC/B,CAAC;YAED,wBAAwB,EAAE,CAAC;YAE3B,IAAI,CAAC,WAAW,CACd,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CACjE,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,iBAAiB,CACf,IAAI,EACJ,iCAAiC;gBAC/B,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CACrD,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.babel.html-context-plugin\",\n \"title\": \"Babel HTML Context Injection Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel plugin that injects compilation context into html`…` tagged template literals and AOT-compiles both the tagged form and literal html(template, context) calls, with scope ID generation.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"babelPluginAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport * as t from '@babel/types';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport { parseFragment } from 'parse5';\nimport {\n extractUsedIdentifiers,\n type ComponentAttrReport,\n type ComponentScopesMap,\n} from './extractUsedIdentifiers';\nimport {\n parseTemplate,\n warnOnLowercaseComponentTags,\n type PithyNode,\n warnsOnComponentProp,\n} from '@pithyjs/compiler';\nimport { createHash } from 'crypto';\nimport { parse as babelParse } from '@babel/parser';\nimport { generateDomFactory } from '../aotCodegen';\n\ninterface PluginState extends PluginPass {\n importedIdentifiers: Set<string>;\n}\n\n/**\n * Extract parameter names from arrow function expressions in template strings.\n * Used to exclude event handler params (e.g., `ev`) from the hoisted context object.\n * @param s - The expression string to scan for arrow functions\n * @returns Set of parameter names found\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"extractArrowParamNames\",\"stability\":\"internal\",\"signature\":\"(s: string) => Set<string>\"} */\nfunction extractArrowParamNames(s: string): Set<string> {\n // Very conservative matcher:\n // - \"(ev) =>\", \"(ev: Event) =>\", \"ev =>\"\n // - avoids destructuring/complex params on purpose (we don't want those in ctx anyway)\n const out = new Set<string>();\n const re =\n /(?:\\(\\s*([A-Za-z_$][\\w$]*)\\s*(?::[^)]*)?\\s*\\)|\\b([A-Za-z_$][\\w$]*)\\b)\\s*=>/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(s))) {\n const name = m[1] || m[2];\n if (name) out.add(name);\n }\n return out;\n}\n\nfunction stringLikeNames(node: t.Expression): string[] | null {\n if (t.isIdentifier(node)) return [node.name];\n if (t.isNumericLiteral(node)) return [];\n if (\n t.isBinaryExpression(node) &&\n (node.operator === '-' || node.operator === '/')\n ) {\n const left = t.isExpression(node.left) ? stringLikeNames(node.left) : null;\n const right = stringLikeNames(node.right);\n return left && right ? [...left, ...right] : null;\n }\n if (\n t.isNewExpression(node) &&\n t.isIdentifier(node.callee) &&\n node.arguments.length === 0\n ) {\n return [node.callee.name];\n }\n if (\n t.isUnaryExpression(node) &&\n (node.operator === 'typeof' || node.operator === 'void')\n ) {\n return stringLikeNames(node.argument);\n }\n if (t.isSequenceExpression(node)) {\n const parts = node.expressions.map(stringLikeNames);\n return parts.every(p => p !== null) ? parts.flat() : null;\n }\n if (t.isMemberExpression(node)) {\n let root: t.Expression = node;\n while (\n t.isMemberExpression(root) &&\n !root.computed &&\n t.isIdentifier(root.property)\n ) {\n root = root.object;\n }\n if (!t.isIdentifier(root)) return null;\n return HOST_ROOTS.has(root.name) ? [] : [root.name];\n }\n return null;\n}\n\nconst HOST_ROOTS = new Set([\n 'window',\n 'document',\n 'location',\n 'navigator',\n 'history',\n 'localStorage',\n 'sessionStorage',\n 'console',\n 'performance',\n 'crypto',\n 'screen',\n]);\n\nconst typeScopedNames = new WeakMap<t.Node, Set<string>>();\n\nfunction scopeStatements(block: t.Node): t.Statement[] {\n if (\n t.isProgram(block) ||\n t.isBlockStatement(block) ||\n t.isStaticBlock(block) ||\n t.isTSModuleBlock(block)\n )\n return block.body;\n if (t.isFunction(block) && t.isBlockStatement(block.body))\n return block.body.body;\n if (t.isSwitchStatement(block)) return block.cases.flatMap(c => c.consequent);\n return [];\n}\n\nfunction declaredTsValueNames(path: NodePath): Set<string> {\n const names = new Set<string>();\n for (let scope = path.scope; scope; scope = scope.parent) {\n let declared = typeScopedNames.get(scope.block);\n if (!declared) {\n declared = new Set();\n for (const stmt of scopeStatements(scope.block)) {\n const decl =\n t.isExportNamedDeclaration(stmt) && stmt.declaration\n ? stmt.declaration\n : stmt;\n if (\n (t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) &&\n t.isIdentifier(decl.id)\n ) {\n declared.add(decl.id.name);\n }\n }\n typeScopedNames.set(scope.block, declared);\n }\n declared.forEach(name => names.add(name));\n }\n return names;\n}\n\nfunction quoteForHtmlSource(value: string): string {\n return `\"'${value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')}'\"`;\n}\n\nfunction quoteForDoubleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/[\\\\\"]/g, '\\\\$&');\n}\n\nfunction quoteForSingleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nfunction quoteForTemplateSource(value: string): string {\n return quoteForHtmlSource(value)\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/`/g, '\\\\`')\n .replace(/\\$\\{/g, '\\\\${');\n}\n\n// A private-use character: not valid in an identifier, so it cannot be collected as a name.\nconst TEMPLATE_HOLE = '';\n\ntype DeclaredName = (name: string) => boolean;\n\n// Names that should never be hoisted into ctx even if seen in expressions\nconst RESERVED_LOCAL_EVENT_NAMES = new Set([\n '$event',\n 'event',\n 'ev',\n 'e',\n 'evt',\n]);\n\n/**\n * Configuration options for the Pithy Babel HTML context injection plugin.\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"PithyBabelPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface PithyBabelPluginOptions\"} */\nexport interface PithyBabelPluginOptions {\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: false. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n /** File path for deterministic scope ID generation (typically the Vite module id). */\n filename?: string;\n}\n\n/**\n * Generate a deterministic scope ID from a file path.\n * Uses base64url-safe encoding (only [A-Za-z0-9_-]) since the ID is\n * interpolated into attribute names like data-scope-{id}.\n * Note: pithyPlugin uses raw base64 slicing — the two will diverge for\n * paths containing characters that produce +/= in base64.\n */\nfunction generateScopeId(filepath: string): string {\n const base64 = Buffer.from(filepath).toString('base64');\n // Convert to base64url-safe variant: only [A-Za-z0-9_-] allowed\n // (scopeId is interpolated into attribute names like data-scope-{id})\n const safe = base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n return 'pithy-' + safe.slice(0, 6);\n}\n\n/**\n * Babel plugin that transforms `html\\`...\\`` tagged template expressions.\n * In non-AOT mode, rewrites to `html(str, ctx)`. In AOT mode, pre-compiles\n * both the tagged form and `html(literal, context)` calls to a DOM factory\n * function eliminating runtime HTML parsing.\n * @param options - Plugin configuration (AOT mode, component scopes, filename)\n * @returns Babel plugin object\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"pithyBabelPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBabelPluginOptions) => PluginObj<PluginState>\"} */\nexport default function pithyBabelPlugin(\n options?: PithyBabelPluginOptions\n): PluginObj<PluginState> {\n const componentScopes = options?.componentScopes;\n const enableAot = options?.aot ?? false;\n const templateComponents = new Set(Object.keys(componentScopes ?? {}));\n let importedIdentifiers: Set<string>;\n\n // AOT state — accumulated per file, injected in Program.exit\n let aotFactoryBlocks: string[];\n let aotNeedsApplyBindings: boolean;\n let aotHashCounter: Map<string, number>;\n let aotDisabledByCollision: boolean;\n // Track html`` usage for dead import stripping\n let totalHtmlTagsFound: number;\n let totalHtmlTagsAotCompiled: number;\n // Local names of html imported from @pithyjs/core (handles aliased imports like `import { html as h }`)\n let pithyCoreHtmlLocalNames: Set<string>;\n // Set of local names of html imported from non-@pithyjs/core packages (e.g., lit)\n let foreignHtmlLocalNames: Set<string>;\n let rewrittenCalls: WeakSet<t.Node>;\n let contextsInHtmlCalls: WeakMap<object, boolean>;\n\n return {\n name: 'pithy:html-context-inject',\n\n pre() {\n importedIdentifiers = new Set<string>();\n aotFactoryBlocks = [];\n aotNeedsApplyBindings = false;\n aotHashCounter = new Map();\n aotDisabledByCollision = false;\n totalHtmlTagsFound = 0;\n totalHtmlTagsAotCompiled = 0;\n pithyCoreHtmlLocalNames = new Set();\n foreignHtmlLocalNames = new Set();\n rewrittenCalls = new WeakSet();\n contextsInHtmlCalls = new WeakMap();\n },\n\n visitor: {\n Program: {\n enter(path, _state) {\n for (const node of path.node.body) {\n if (t.isImportDeclaration(node) && node.importKind !== 'type') {\n for (const spec of node.specifiers) {\n // Skip type-only specifiers — they don't exist at runtime\n if (t.isImportSpecifier(spec) && spec.importKind === 'type')\n continue;\n if (\n t.isImportSpecifier(spec) ||\n t.isImportDefaultSpecifier(spec) ||\n t.isImportNamespaceSpecifier(spec)\n ) {\n importedIdentifiers.add(spec.local.name);\n }\n // Detect html imports and track their source package\n if (\n t.isImportSpecifier(spec) &&\n spec.importKind !== 'type' &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === 'html'\n ) {\n if (node.source.value === '@pithyjs/core') {\n pithyCoreHtmlLocalNames.add(spec.local.name);\n } else {\n foreignHtmlLocalNames.add(spec.local.name);\n }\n }\n }\n }\n }\n\n // Check for __applyBindings binding collision early — if a user-defined\n // binding exists, AOT factories would reference the wrong symbol.\n if (enableAot && path.scope.hasBinding('__applyBindings')) {\n aotDisabledByCollision = true;\n console.warn(\n `[pithy:aot] Disabling AOT — existing binding \"__applyBindings\" ` +\n `would shadow the runtime import.`\n );\n }\n },\n\n exit(path) {\n if (aotFactoryBlocks.length === 0) return;\n\n // 1. Add __applyBindings import (only if needed)\n if (aotNeedsApplyBindings) {\n const hasImport = path.node.body.some(\n stmt =>\n t.isImportDeclaration(stmt) &&\n stmt.importKind !== 'type' &&\n stmt.source.value === '@pithyjs/core/runtime/applyBindings' &&\n stmt.specifiers.some(\n s =>\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.local) &&\n s.local.name === '__applyBindings'\n )\n );\n\n if (!hasImport) {\n const importDecl = t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('__applyBindings'),\n t.identifier('__applyBindings')\n ),\n ],\n t.stringLiteral('@pithyjs/core/runtime/applyBindings')\n );\n // Insert after directive prologues and existing imports.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let importInsertIndex = 0;\n const body = path.node.body;\n while (\n importInsertIndex < body.length &&\n t.isExpressionStatement(body[importInsertIndex]) &&\n t.isStringLiteral(\n (body[importInsertIndex] as t.ExpressionStatement).expression\n )\n ) {\n importInsertIndex++;\n }\n while (\n importInsertIndex < body.length &&\n t.isImportDeclaration(body[importInsertIndex])\n ) {\n importInsertIndex++;\n }\n path.node.body.splice(importInsertIndex, 0, importDecl);\n }\n }\n\n // 2. Parse factory code blocks into AST and inject after last import\n const statementsToInject: t.Program['body'] = [];\n\n for (const block of aotFactoryBlocks) {\n const ast = babelParse(block, {\n sourceType: 'module',\n plugins: [],\n });\n if (ast.program?.body) {\n statementsToInject.push(...ast.program.body);\n }\n }\n\n if (statementsToInject.length === 0) return;\n\n // Find insertion point: after directive prologues and import declarations.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let insertIndex = 0;\n const bodyForFactory = path.node.body;\n while (\n insertIndex < bodyForFactory.length &&\n t.isExpressionStatement(bodyForFactory[insertIndex]) &&\n t.isStringLiteral(\n (bodyForFactory[insertIndex] as t.ExpressionStatement).expression\n )\n ) {\n insertIndex++;\n }\n while (\n insertIndex < bodyForFactory.length &&\n t.isImportDeclaration(bodyForFactory[insertIndex])\n ) {\n insertIndex++;\n }\n\n path.node.body.splice(insertIndex, 0, ...statementsToInject);\n\n // 3. Strip unused `html` import when all html`` tags were AOT-compiled.\n // This enables Rollup to tree-shake html() → parseHtml → parse5 entirely.\n // Safety: use Babel binding analysis (scope.crawl + getBinding) to verify\n // the html identifier has no remaining references after AOT transforms.\n // This covers all non-tagged-template usages: html(), const t = html, etc.\n if (\n enableAot &&\n totalHtmlTagsFound > 0 &&\n totalHtmlTagsFound === totalHtmlTagsAotCompiled &&\n pithyCoreHtmlLocalNames.size > 0\n ) {\n // Re-crawl scope to get accurate reference counts after AOT transforms\n path.scope.crawl();\n const unreferenced = new Set(\n [...pithyCoreHtmlLocalNames].filter(\n name => !(path.scope.getBinding(name)?.references ?? 0)\n )\n );\n\n for (let i = path.node.body.length - 1; i >= 0; i--) {\n const stmt = path.node.body[i];\n if (!t.isImportDeclaration(stmt) || stmt.importKind === 'type')\n continue;\n\n // Only strip html from @pithyjs/core — never touch other packages (e.g., lit)\n if (stmt.source.value !== '@pithyjs/core') continue;\n\n const kept = stmt.specifiers.filter(\n s =>\n !(\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.imported) &&\n s.imported.name === 'html' &&\n unreferenced.has(s.local.name)\n )\n );\n if (kept.length === stmt.specifiers.length) continue;\n stmt.specifiers = kept;\n // If no specifiers remain, remove the entire import declaration\n if (kept.length === 0) {\n path.node.body.splice(i, 1);\n }\n }\n }\n },\n },\n\n TaggedTemplateExpression(path) {\n // Only transform html`` from @pithyjs/core — leave other packages' html (e.g., lit) untouched.\n // When we detected a @pithyjs/core html import, match its local name (handles aliases).\n // When no @pithyjs/core import was found, fall back to matching literal \"html\" (bare usage),\n // but skip if \"html\" is known to come from a foreign package.\n const tagName = t.isIdentifier(path.node.tag)\n ? path.node.tag.name\n : null;\n if (!tagName) return;\n if (foreignHtmlLocalNames.has(tagName)) return;\n if (\n pithyCoreHtmlLocalNames.size > 0\n ? !pithyCoreHtmlLocalNames.has(tagName)\n : tagName !== 'html'\n )\n return;\n\n totalHtmlTagsFound++;\n\n const quasi = path.node.quasi;\n const templateStr = quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('');\n\n // Warn about lowercase component tags used for imported components\n if (importedIdentifiers.size > 0) {\n warnOnLowercaseComponentTags(templateStr, importedIdentifiers);\n }\n\n const trees = parseComponentTemplate(templateStr, importedIdentifiers);\n if (trees.length === 0) return;\n\n const reportTrees =\n quasi.expressions.length === 0\n ? trees\n : parseComponentTemplate(\n quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join(TEMPLATE_HOLE),\n importedIdentifiers,\n true\n );\n const contextObject = buildContextObject(\n path,\n trees,\n templateStr,\n reportTrees\n );\n\n // ── AOT codegen path ──────────────────────────────────────────────\n if (enableAot && !aotDisabledByCollision) {\n // Templates with ${expr} expressions can't be AOT-compiled safely.\n // PithyJS uses {{ expr }} syntax, not ${}, so this is an edge case guard.\n if (quasi.expressions.length > 0) {\n // Fall through to non-AOT path below\n reportJitFallback(\n path,\n `Template contains \\${expr} expressions — skipping AOT. ` +\n `Refactor to {{ expr }} syntax for AOT compilation.`\n );\n } else if (emitFactory(path, trees, templateStr, contextObject)) {\n return;\n }\n }\n\n // ── Non-AOT path (original behavior) ─────────────────────────────\n const runtimeCall = t.callExpression(path.node.tag, [\n quasi,\n contextObject,\n ]);\n rewrittenCalls.add(runtimeCall);\n path.replaceWith(runtimeCall);\n },\n\n CallExpression(path) {\n if (rewrittenCalls.has(path.node)) return;\n const callee = path.node.callee;\n if (\n !t.isIdentifier(callee) ||\n !pithyCoreHtmlLocalNames.has(callee.name)\n )\n return;\n if (path.scope.getBinding(callee.name)?.kind !== 'module') return;\n\n const [templateArg, contextArg, cssArg] = path.node.arguments;\n const templateStr = t.isStringLiteral(templateArg)\n ? templateArg.value\n : t.isTemplateLiteral(templateArg) &&\n templateArg.expressions.length === 0\n ? templateArg.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('')\n : null;\n const context = contextLiteral(path, contextArg);\n const componentNames = declaredComponents(context);\n\n if (templateStr !== null) {\n reportCallFormAttrs(\n path,\n templateStr,\n componentNames,\n contextStaysInHtmlCalls(path, contextArg) ? context : null,\n quoteForCallForm(path, templateArg)\n );\n }\n\n if (!enableAot || aotDisabledByCollision) return;\n\n totalHtmlTagsFound++;\n\n if (templateStr === null) {\n reportJitFallback(\n path,\n `html() is called with a template that is not a string literal — skipping AOT. ` +\n `Pass the template as a literal.`\n );\n return;\n }\n\n if (cssArg !== undefined && !isAbsentCss(cssArg)) {\n reportJitFallback(\n path,\n `html() is called with a css argument — skipping AOT.`\n );\n return;\n }\n\n if (contextArg && !context) {\n reportJitFallback(\n path,\n `html() is called with a second argument that is not an object literal, so it may be a css string or a context the build cannot read — skipping AOT. ` +\n `Pass the context as an object literal, inline or bound by const.`\n );\n return;\n }\n\n try {\n warnOnLowercaseComponentTags(templateStr, componentNames);\n } catch (err) {\n reportJitFallback(\n path,\n `html() template has a tag that cannot be resolved to a component at build time — skipping AOT. ` +\n `Name the component in a literal \\`__importedIdentifiers: new Set([...])\\` in the context. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return;\n }\n\n emitFactory(\n path,\n parseComponentTemplate(templateStr, componentNames),\n templateStr,\n t.isExpression(contextArg) ? contextArg : t.objectExpression([])\n );\n },\n },\n };\n\n function unwrapTs(node: t.Node | null | undefined): t.Node | null {\n let current = node ?? null;\n while (\n t.isTSAsExpression(current) ||\n t.isTSSatisfiesExpression(current) ||\n t.isTSTypeAssertion(current) ||\n t.isTSNonNullExpression(current) ||\n t.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n }\n\n function isAbsentCss(cssArg: t.Node): boolean {\n const css = unwrapTs(cssArg);\n return (\n t.isIdentifier(css, { name: 'undefined' }) ||\n t.isNullLiteral(css) ||\n t.isStringLiteral(css, { value: '' }) ||\n t.isUnaryExpression(css, { operator: 'void' })\n );\n }\n\n function contextLiteral(\n path: NodePath,\n contextArg: t.Node | undefined\n ): t.ObjectExpression | null {\n const arg = unwrapTs(contextArg);\n if (t.isObjectExpression(arg)) return arg;\n if (!t.isIdentifier(arg)) return null;\n const binding = path.scope.getBinding(arg.name);\n if (binding?.kind !== 'const' || !binding.path.isVariableDeclarator())\n return null;\n if (!t.isIdentifier(binding.path.node.id)) return null;\n const init = unwrapTs(binding.path.node.init);\n return t.isObjectExpression(init) ? init : null;\n }\n\n function declaredComponents(literal: t.ObjectExpression | null): Set<string> {\n const names = new Set<string>();\n if (!literal) return names;\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop)) {\n names.clear();\n continue;\n }\n if (prop.computed) continue;\n const key = t.isIdentifier(prop.key)\n ? prop.key.name\n : t.isStringLiteral(prop.key)\n ? prop.key.value\n : null;\n if (key !== '__importedIdentifiers') continue;\n names.clear();\n if (!t.isObjectProperty(prop)) continue;\n const value = unwrapTs(prop.value);\n if (\n !t.isNewExpression(value) ||\n !t.isIdentifier(value.callee, { name: 'Set' })\n )\n continue;\n const list = unwrapTs(value.arguments[0]);\n if (!t.isArrayExpression(list)) continue;\n for (const element of list.elements) {\n if (t.isStringLiteral(element)) names.add(element.value);\n }\n }\n return names;\n }\n\n function sourceFile(path: NodePath): string | undefined {\n return (\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename\n );\n }\n\n function contextStaysInHtmlCalls(\n path: NodePath,\n contextArg: t.Node | undefined\n ): boolean {\n const arg = unwrapTs(contextArg);\n if (!t.isIdentifier(arg)) return true;\n const binding = path.scope.getBinding(arg.name);\n if (!binding) return true;\n // AOT rewrites earlier html() calls into factory calls that receive the\n // same context, so classify the references once, before any rewrite.\n let stays = contextsInHtmlCalls.get(binding);\n if (stays === undefined) {\n stays = binding.referencePaths.every(reference => {\n if (reference.findParent(p => p.isTSTypeQuery())) return true;\n const call = reference.findParent(\n p => unwrapTs(p.node) !== reference.node\n )?.node;\n return (\n t.isCallExpression(call) &&\n t.isIdentifier(call.callee) &&\n pithyCoreHtmlLocalNames.has(call.callee.name) &&\n reference.scope.getBinding(call.callee.name)?.kind === 'module' &&\n unwrapTs(call.arguments[1]) === reference.node\n );\n });\n contextsInHtmlCalls.set(binding, stays);\n }\n return stays;\n }\n\n function contextKeys(literal: t.ObjectExpression | null): Set<string> | null {\n if (!literal) return null;\n const keys = new Set<string>();\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop) || prop.computed) return null;\n if (t.isIdentifier(prop.key)) keys.add(prop.key.name);\n else if (t.isStringLiteral(prop.key)) keys.add(prop.key.value);\n }\n return keys;\n }\n\n function parseComponentTemplate(\n templateStr: string,\n componentNames: Set<string>,\n quiet = false\n ): PithyNode[] {\n // `importedIdentifiers` is what makes component tags components at all;\n // `withSource: false` keeps interpolation scanning on parse5's decoded\n // text, because codegen locates interpolations with indexOf(interp.raw)\n // against decoded textContent and a raw source slice would carry entities.\n return parseTemplate(templateStr, parseFragment, {\n importedIdentifiers: componentNames,\n withSource: false,\n quiet,\n }).nodes;\n }\n\n function buildContextObject(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n reportTrees: PithyNode[]\n ): t.ObjectExpression {\n // Collect identifiers referenced by expressions in the template\n const { usedIdentifiers, attrReports } = collectIdentifiers(trees);\n\n // Also collect arrow-function param names appearing in attribute expressions\n // so we can remove them from usedIdentifiers (e.g., \"(ev) => ...\" or \"ev => ...\").\n const arrowParams = extractArrowParamNames(templateStr);\n\n const tsNames = declaredTsValueNames(path);\n const reports =\n reportTrees === trees\n ? attrReports\n : collectIdentifiers(reportTrees, true).attrReports.filter(\n ({ attr, value }) =>\n !attr.includes(TEMPLATE_HOLE) && !value.includes(TEMPLATE_HOLE)\n );\n for (const report of reports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n name => path.scope.hasBinding(name) || tsNames.has(name),\n quoteForTemplateSource,\n 'no binding in this module'\n );\n }\n\n // Compute which imported identifiers are actually used as components\n const usedComponents = new Set<string>();\n const collectComponents = (node: PithyNode) => {\n if (node.type === 'element' && node.isComponent && node.originalTagName) {\n usedComponents.add(node.originalTagName);\n }\n for (const child of node.children ?? []) collectComponents(child);\n };\n for (const tree of trees) collectComponents(tree);\n\n // Final filter:\n // - drop arrow params (local to inline handlers)\n // - drop common event aliases ($event, event, ev, e, evt)\n const filteredUsed = [...usedIdentifiers].filter(\n id => !arrowParams.has(id) && !RESERVED_LOCAL_EVENT_NAMES.has(id)\n );\n\n return t.objectExpression([\n // Only hoist filtered used identifiers\n ...filteredUsed.map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add only the components that are actually used in the template\n ...[...usedComponents].map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add imported identifiers as a special property for downstream checks\n t.objectProperty(\n t.identifier('__importedIdentifiers'),\n t.newExpression(t.identifier('Set'), [\n t.arrayExpression(\n [...importedIdentifiers].map(id => t.stringLiteral(id))\n ),\n ])\n ),\n ]);\n }\n\n function collectIdentifiers(\n trees: PithyNode[],\n quiet = false\n ): {\n usedIdentifiers: Set<string>;\n attrReports: ComponentAttrReport[];\n } {\n const usedIdentifiers = new Set<string>();\n const attrReports: ComponentAttrReport[] = [];\n for (const tree of trees) {\n const ids = extractUsedIdentifiers(\n tree,\n componentScopes,\n report => attrReports.push(report),\n quiet\n );\n ids.forEach(id => usedIdentifiers.add(id));\n }\n return { usedIdentifiers, attrReports };\n }\n\n function quoteForCallForm(\n path: NodePath,\n templateArg: t.Node\n ): (value: string) => string {\n if (sourceFile(path)?.endsWith('.pithy')) return quoteForHtmlSource;\n const raw = templateArg.extra?.raw;\n if (typeof raw !== 'string') return quoteForTemplateSource;\n return raw.startsWith(\"'\")\n ? quoteForSingleQuotedSource\n : quoteForDoubleQuotedSource;\n }\n\n function reportCallFormAttrs(\n path: NodePath,\n templateStr: string,\n componentNames: Set<string>,\n context: t.ObjectExpression | null,\n quote: (value: string) => string\n ): void {\n if (componentNames.size === 0) return;\n const keys = contextKeys(context);\n const isDeclared: DeclaredName = name =>\n keys === null ||\n keys.has(name) ||\n (path.scope.hasBinding(name) && !path.scope.getBinding(name));\n const trees = parseComponentTemplate(templateStr, componentNames, true);\n for (const report of collectIdentifiers(trees, true).attrReports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n isDeclared,\n quote,\n 'no entry in the html() context'\n );\n }\n }\n\n function warnOnStringLikeComponentAttr(\n path: NodePath,\n { tag, attr, value, names, parsed, expression, error }: ComponentAttrReport,\n isDeclared: DeclaredName,\n quote: (value: string) => string,\n missing: string\n ): void {\n if (warnsOnComponentProp(attr, value)) return;\n let outcome = `does not parse (Failed to parse expression: ${error}), so the attribute is dropped`;\n if (parsed) {\n const collected = new Set(names);\n const candidates = expression ? stringLikeNames(expression) : null;\n const unbound = [...new Set(candidates ?? [])].filter(\n name => collected.has(name) && !isDeclared(name)\n );\n if (unbound.length === 0) return;\n outcome = `reads ${unbound.map(n => `\\`${n}\\``).join(', ')}, which ${unbound.length === 1 ? 'has' : 'have'} ${missing}, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime`;\n }\n\n let advice = '';\n if (parsed || !/[()[\\]{};=]/.test(value)) {\n advice = ` To pass a string, quote it: ${attr}=${quote(value)}.`;\n }\n\n const file = sourceFile(path);\n const loc = path.node.loc?.start;\n const where = file\n ? ` (${file}${loc ? `:${loc.line}:${loc.column + 1}` : ''})`\n : '';\n console.warn(\n `[pithy] <${tag} ${attr}=\"${value}\">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`\n );\n }\n\n function reportJitFallback(path: NodePath, reason: string): void {\n const where = options?.filename ? ` (${options.filename})` : '';\n if (options?.strictAot) {\n throw path.buildCodeFrameError(\n `[pithy:aot:jit-fallback] ${reason}${where}`\n );\n }\n console.warn(\n `[pithy:aot:jit-fallback] ${reason} ` +\n `The template will throw at runtime unless the app calls loadJITCompiler() at startup.${where}`\n );\n }\n\n function emitFactory(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n context: t.Expression\n ): boolean {\n try {\n // Generate deterministic hash from template content\n const rawHash = createHash('sha256')\n .update(templateStr)\n .digest('hex')\n .slice(0, 8);\n const count = aotHashCounter.get(rawHash) ?? 0;\n const hash = count > 0 ? `${rawHash}_${count}` : rawHash;\n\n // Generate scope ID from filename (or fall back to hash)\n const filename =\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename ??\n '';\n const scopeId = filename\n ? generateScopeId(filename)\n : `pithy-${rawHash.slice(0, 6)}`;\n\n // Call AOT codegen\n const aotResult = generateDomFactory(trees, hash, scopeId, {\n templateComponents,\n });\n\n // Only increment counter after successful codegen — if codegen\n // throws, the hash slot stays available for the next attempt.\n aotHashCounter.set(rawHash, count + 1);\n\n // Accumulate factory code for Program.exit injection\n aotFactoryBlocks.push(aotResult.code);\n // Detect actual applyBindings call sites rather than any occurrence of the\n // identifier name. This avoids false positives from template text that may\n // contain the string \"__applyBindings\" inside HTML or attribute values.\n if (aotResult.code.includes('return __applyBindings(')) {\n aotNeedsApplyBindings = true;\n }\n\n totalHtmlTagsAotCompiled++;\n\n path.replaceWith(\n t.callExpression(t.identifier(aotResult.factoryName), [context])\n );\n return true;\n } catch (err) {\n reportJitFallback(\n path,\n `Codegen failed — skipping AOT. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return false;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"babelPlugin.js","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EACL,sBAAsB,GAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,aAAa,EACb,4BAA4B,EAE5B,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMnD;;;;;GAKG;AACH,6JAA6J;AAC7J,SAAS,sBAAsB,CAAC,CAAS;IACvC,6BAA6B;IAC7B,0CAA0C;IAC1C,wFAAwF;IACxF,MAAM,GAAG,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9B,MAAM,EAAE,GACN,6EAA6E,CAAC;IAChF,IAAI,CAAyB,CAAC;IAC9B,OAAO,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,IAAI;YAAE,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IACD,OAAO,GAAG,CAAC;AACb,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AC,eAAe,CAAC,QAAQ,CAAC;gBAC3B,CAAC,CAAC,SAAS,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YAEnC,mBAAmB;YACnB,MAAM,SAAS,GAAG,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE;gBACzD,kBAAkB;aACnB,CAAC,CAAC;YAEH,+DAA+D;YAC/D,8DAA8D;YAC9D,cAAc,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YAEvC,qDAAqD;YACrD,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YACtC,2EAA2E;YAC3E,2EAA2E;YAC3E,wEAAwE;YACxE,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,yBAAyB,CAAC,EAAE,CAAC;gBACvD,qBAAqB,GAAG,IAAI,CAAC;YAC/B,CAAC;YAED,wBAAwB,EAAE,CAAC;YAE3B,IAAI,CAAC,WAAW,CACd,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CACjE,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,iBAAiB,CACf,IAAI,EACJ,iCAAiC;gBAC/B,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CACrD,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.babel.html-context-plugin\",\n \"title\": \"Babel HTML Context Injection Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel plugin that injects compilation context into html`…` tagged template literals and AOT-compiles both the tagged form and literal html(template, context) calls, with scope ID generation.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"babelPluginAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport * as t from '@babel/types';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport { parseFragment } from 'parse5';\nimport {\n extractUsedIdentifiers,\n type ComponentAttrReport,\n type ComponentScopesMap,\n} from './extractUsedIdentifiers';\nimport {\n parseTemplate,\n warnOnLowercaseComponentTags,\n type PithyNode,\n warnsOnComponentProp,\n} from '@pithyjs/compiler';\nimport { createHash } from 'crypto';\nimport { parse as babelParse } from '@babel/parser';\nimport { generateDomFactory } from '../aotCodegen';\n\ninterface PluginState extends PluginPass {\n importedIdentifiers: Set<string>;\n}\n\n/**\n * Extract parameter names from arrow function expressions in template strings.\n * Used to exclude event handler params (e.g., `ev`) from the hoisted context object.\n * @param s - The expression string to scan for arrow functions\n * @returns Set of parameter names found\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"extractArrowParamNames\",\"stability\":\"internal\",\"signature\":\"(s: string) => Set<string>\"} */\nfunction extractArrowParamNames(s: string): Set<string> {\n // Very conservative matcher:\n // - \"(ev) =>\", \"(ev: Event) =>\", \"ev =>\"\n // - avoids destructuring/complex params on purpose (we don't want those in ctx anyway)\n const out = new Set<string>();\n const re =\n /(?:\\(\\s*([A-Za-z_$][\\w$]*)\\s*(?::[^)]*)?\\s*\\)|\\b([A-Za-z_$][\\w$]*)\\b)\\s*=>/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(s))) {\n const name = m[1] || m[2];\n if (name) out.add(name);\n }\n return out;\n}\n\nfunction stringLikeNames(node: t.Expression): string[] | null {\n if (t.isIdentifier(node)) return [node.name];\n if (t.isNumericLiteral(node)) return [];\n if (\n t.isBinaryExpression(node) &&\n (node.operator === '-' || node.operator === '/')\n ) {\n const left = t.isExpression(node.left) ? stringLikeNames(node.left) : null;\n const right = stringLikeNames(node.right);\n return left && right ? [...left, ...right] : null;\n }\n if (\n t.isNewExpression(node) &&\n t.isIdentifier(node.callee) &&\n node.arguments.length === 0\n ) {\n return [node.callee.name];\n }\n if (\n t.isUnaryExpression(node) &&\n (node.operator === 'typeof' || node.operator === 'void')\n ) {\n return stringLikeNames(node.argument);\n }\n if (t.isSequenceExpression(node)) {\n const parts = node.expressions.map(stringLikeNames);\n return parts.every(p => p !== null) ? parts.flat() : null;\n }\n if (t.isMemberExpression(node)) {\n let root: t.Expression = node;\n while (\n t.isMemberExpression(root) &&\n !root.computed &&\n t.isIdentifier(root.property)\n ) {\n root = root.object;\n }\n if (!t.isIdentifier(root)) return null;\n return HOST_ROOTS.has(root.name) ? [] : [root.name];\n }\n return null;\n}\n\nconst HOST_ROOTS = new Set([\n 'window',\n 'document',\n 'location',\n 'navigator',\n 'history',\n 'localStorage',\n 'sessionStorage',\n 'console',\n 'performance',\n 'crypto',\n 'screen',\n]);\n\nconst typeScopedNames = new WeakMap<t.Node, Set<string>>();\n\nfunction scopeStatements(block: t.Node): t.Statement[] {\n if (\n t.isProgram(block) ||\n t.isBlockStatement(block) ||\n t.isStaticBlock(block) ||\n t.isTSModuleBlock(block)\n )\n return block.body;\n if (t.isFunction(block) && t.isBlockStatement(block.body))\n return block.body.body;\n if (t.isSwitchStatement(block)) return block.cases.flatMap(c => c.consequent);\n return [];\n}\n\nfunction declaredTsValueNames(path: NodePath): Set<string> {\n const names = new Set<string>();\n for (let scope = path.scope; scope; scope = scope.parent) {\n let declared = typeScopedNames.get(scope.block);\n if (!declared) {\n declared = new Set();\n for (const stmt of scopeStatements(scope.block)) {\n const decl =\n t.isExportNamedDeclaration(stmt) && stmt.declaration\n ? stmt.declaration\n : stmt;\n if (\n (t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) &&\n t.isIdentifier(decl.id)\n ) {\n declared.add(decl.id.name);\n }\n }\n typeScopedNames.set(scope.block, declared);\n }\n declared.forEach(name => names.add(name));\n }\n return names;\n}\n\nfunction quoteForHtmlSource(value: string): string {\n return `\"'${value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')}'\"`;\n}\n\nfunction quoteForDoubleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/[\\\\\"]/g, '\\\\$&');\n}\n\nfunction quoteForSingleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nfunction quoteForTemplateSource(value: string): string {\n return quoteForHtmlSource(value)\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/`/g, '\\\\`')\n .replace(/\\$\\{/g, '\\\\${');\n}\n\n// A private-use character: not valid in an identifier, so it cannot be collected as a name.\nconst TEMPLATE_HOLE = '';\n\ntype DeclaredName = (name: string) => boolean;\n\n// Names that should never be hoisted into ctx even if seen in expressions\nconst RESERVED_LOCAL_EVENT_NAMES = new Set([\n '$event',\n 'event',\n 'ev',\n 'e',\n 'evt',\n]);\n\n/**\n * Configuration options for the Pithy Babel HTML context injection plugin.\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"PithyBabelPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface PithyBabelPluginOptions\"} */\nexport interface PithyBabelPluginOptions {\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: false. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n /** File path for deterministic scope ID generation (typically the Vite module id). */\n filename?: string;\n /** Receives each template finding. Default: `console.warn` of its `message`. */\n onFinding?: (finding: TemplateFinding) => void;\n}\n\n/**\n * A component attribute that will not reach the component as the author meant:\n * its value does not parse (`unparsed`, the attribute is dropped), or it reads\n * names this module does not bind (`unbound`).\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"TemplateFinding\",\"stability\":\"experimental\",\"signature\":\"interface TemplateFinding\"} */\nexport interface TemplateFinding {\n kind: 'unparsed' | 'unbound';\n tag: string;\n attr: string;\n value: string;\n /** The names read with no binding; empty for `unparsed`. */\n unbound: string[];\n /** The parser's error for `unparsed`; `null` otherwise. */\n error: string | null;\n /** The attribute quoted as a string literal, when that is the likely intent. */\n fix: string | null;\n file: string | null;\n /** 1-based, of the template expression in the module. */\n line: number | null;\n /** 1-based. */\n column: number | null;\n /** The text the plugin warns with. */\n message: string;\n}\n\n/**\n * Generate a deterministic scope ID from a file path.\n * Uses base64url-safe encoding (only [A-Za-z0-9_-]) since the ID is\n * interpolated into attribute names like data-scope-{id}.\n * Note: pithyPlugin uses raw base64 slicing — the two will diverge for\n * paths containing characters that produce +/= in base64.\n */\nfunction generateScopeId(filepath: string): string {\n const base64 = Buffer.from(filepath).toString('base64');\n // Convert to base64url-safe variant: only [A-Za-z0-9_-] allowed\n // (scopeId is interpolated into attribute names like data-scope-{id})\n const safe = base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n return 'pithy-' + safe.slice(0, 6);\n}\n\n/**\n * Babel plugin that transforms `html\\`...\\`` tagged template expressions.\n * In non-AOT mode, rewrites to `html(str, ctx)`. In AOT mode, pre-compiles\n * both the tagged form and `html(literal, context)` calls to a DOM factory\n * function eliminating runtime HTML parsing.\n * @param options - Plugin configuration (AOT mode, component scopes, filename)\n * @returns Babel plugin object\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"pithyBabelPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBabelPluginOptions) => PluginObj<PluginState>\"} */\nexport default function pithyBabelPlugin(\n options?: PithyBabelPluginOptions\n): PluginObj<PluginState> {\n const componentScopes = options?.componentScopes;\n const enableAot = options?.aot ?? false;\n const templateComponents = new Set(Object.keys(componentScopes ?? {}));\n let importedIdentifiers: Set<string>;\n\n // AOT state — accumulated per file, injected in Program.exit\n let aotFactoryBlocks: string[];\n let aotNeedsApplyBindings: boolean;\n let aotHashCounter: Map<string, number>;\n let aotDisabledByCollision: boolean;\n // Track html`` usage for dead import stripping\n let totalHtmlTagsFound: number;\n let totalHtmlTagsAotCompiled: number;\n // Local names of html imported from @pithyjs/core (handles aliased imports like `import { html as h }`)\n let pithyCoreHtmlLocalNames: Set<string>;\n // Set of local names of html imported from non-@pithyjs/core packages (e.g., lit)\n let foreignHtmlLocalNames: Set<string>;\n let rewrittenCalls: WeakSet<t.Node>;\n let contextsInHtmlCalls: WeakMap<object, boolean>;\n\n return {\n name: 'pithy:html-context-inject',\n\n pre() {\n importedIdentifiers = new Set<string>();\n aotFactoryBlocks = [];\n aotNeedsApplyBindings = false;\n aotHashCounter = new Map();\n aotDisabledByCollision = false;\n totalHtmlTagsFound = 0;\n totalHtmlTagsAotCompiled = 0;\n pithyCoreHtmlLocalNames = new Set();\n foreignHtmlLocalNames = new Set();\n rewrittenCalls = new WeakSet();\n contextsInHtmlCalls = new WeakMap();\n },\n\n visitor: {\n Program: {\n enter(path, _state) {\n for (const node of path.node.body) {\n if (t.isImportDeclaration(node) && node.importKind !== 'type') {\n for (const spec of node.specifiers) {\n // Skip type-only specifiers — they don't exist at runtime\n if (t.isImportSpecifier(spec) && spec.importKind === 'type')\n continue;\n if (\n t.isImportSpecifier(spec) ||\n t.isImportDefaultSpecifier(spec) ||\n t.isImportNamespaceSpecifier(spec)\n ) {\n importedIdentifiers.add(spec.local.name);\n }\n // Detect html imports and track their source package\n if (\n t.isImportSpecifier(spec) &&\n spec.importKind !== 'type' &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === 'html'\n ) {\n if (node.source.value === '@pithyjs/core') {\n pithyCoreHtmlLocalNames.add(spec.local.name);\n } else {\n foreignHtmlLocalNames.add(spec.local.name);\n }\n }\n }\n }\n }\n\n // Check for __applyBindings binding collision early — if a user-defined\n // binding exists, AOT factories would reference the wrong symbol.\n if (enableAot && path.scope.hasBinding('__applyBindings')) {\n aotDisabledByCollision = true;\n console.warn(\n `[pithy:aot] Disabling AOT — existing binding \"__applyBindings\" ` +\n `would shadow the runtime import.`\n );\n }\n },\n\n exit(path) {\n if (aotFactoryBlocks.length === 0) return;\n\n // 1. Add __applyBindings import (only if needed)\n if (aotNeedsApplyBindings) {\n const hasImport = path.node.body.some(\n stmt =>\n t.isImportDeclaration(stmt) &&\n stmt.importKind !== 'type' &&\n stmt.source.value === '@pithyjs/core/runtime/applyBindings' &&\n stmt.specifiers.some(\n s =>\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.local) &&\n s.local.name === '__applyBindings'\n )\n );\n\n if (!hasImport) {\n const importDecl = t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('__applyBindings'),\n t.identifier('__applyBindings')\n ),\n ],\n t.stringLiteral('@pithyjs/core/runtime/applyBindings')\n );\n // Insert after directive prologues and existing imports.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let importInsertIndex = 0;\n const body = path.node.body;\n while (\n importInsertIndex < body.length &&\n t.isExpressionStatement(body[importInsertIndex]) &&\n t.isStringLiteral(\n (body[importInsertIndex] as t.ExpressionStatement).expression\n )\n ) {\n importInsertIndex++;\n }\n while (\n importInsertIndex < body.length &&\n t.isImportDeclaration(body[importInsertIndex])\n ) {\n importInsertIndex++;\n }\n path.node.body.splice(importInsertIndex, 0, importDecl);\n }\n }\n\n // 2. Parse factory code blocks into AST and inject after last import\n const statementsToInject: t.Program['body'] = [];\n\n for (const block of aotFactoryBlocks) {\n const ast = babelParse(block, {\n sourceType: 'module',\n plugins: [],\n });\n if (ast.program?.body) {\n statementsToInject.push(...ast.program.body);\n }\n }\n\n if (statementsToInject.length === 0) return;\n\n // Find insertion point: after directive prologues and import declarations.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let insertIndex = 0;\n const bodyForFactory = path.node.body;\n while (\n insertIndex < bodyForFactory.length &&\n t.isExpressionStatement(bodyForFactory[insertIndex]) &&\n t.isStringLiteral(\n (bodyForFactory[insertIndex] as t.ExpressionStatement).expression\n )\n ) {\n insertIndex++;\n }\n while (\n insertIndex < bodyForFactory.length &&\n t.isImportDeclaration(bodyForFactory[insertIndex])\n ) {\n insertIndex++;\n }\n\n path.node.body.splice(insertIndex, 0, ...statementsToInject);\n\n // 3. Strip unused `html` import when all html`` tags were AOT-compiled.\n // This enables Rollup to tree-shake html() → parseHtml → parse5 entirely.\n // Safety: use Babel binding analysis (scope.crawl + getBinding) to verify\n // the html identifier has no remaining references after AOT transforms.\n // This covers all non-tagged-template usages: html(), const t = html, etc.\n if (\n enableAot &&\n totalHtmlTagsFound > 0 &&\n totalHtmlTagsFound === totalHtmlTagsAotCompiled &&\n pithyCoreHtmlLocalNames.size > 0\n ) {\n // Re-crawl scope to get accurate reference counts after AOT transforms\n path.scope.crawl();\n const unreferenced = new Set(\n [...pithyCoreHtmlLocalNames].filter(\n name => !(path.scope.getBinding(name)?.references ?? 0)\n )\n );\n\n for (let i = path.node.body.length - 1; i >= 0; i--) {\n const stmt = path.node.body[i];\n if (!t.isImportDeclaration(stmt) || stmt.importKind === 'type')\n continue;\n\n // Only strip html from @pithyjs/core — never touch other packages (e.g., lit)\n if (stmt.source.value !== '@pithyjs/core') continue;\n\n const kept = stmt.specifiers.filter(\n s =>\n !(\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.imported) &&\n s.imported.name === 'html' &&\n unreferenced.has(s.local.name)\n )\n );\n if (kept.length === stmt.specifiers.length) continue;\n stmt.specifiers = kept;\n // If no specifiers remain, remove the entire import declaration\n if (kept.length === 0) {\n path.node.body.splice(i, 1);\n }\n }\n }\n },\n },\n\n TaggedTemplateExpression(path) {\n // Only transform html`` from @pithyjs/core — leave other packages' html (e.g., lit) untouched.\n // When we detected a @pithyjs/core html import, match its local name (handles aliases).\n // When no @pithyjs/core import was found, fall back to matching literal \"html\" (bare usage),\n // but skip if \"html\" is known to come from a foreign package.\n const tagName = t.isIdentifier(path.node.tag)\n ? path.node.tag.name\n : null;\n if (!tagName) return;\n if (foreignHtmlLocalNames.has(tagName)) return;\n if (\n pithyCoreHtmlLocalNames.size > 0\n ? !pithyCoreHtmlLocalNames.has(tagName)\n : tagName !== 'html'\n )\n return;\n\n totalHtmlTagsFound++;\n\n const quasi = path.node.quasi;\n const templateStr = quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('');\n\n // Warn about lowercase component tags used for imported components\n if (importedIdentifiers.size > 0) {\n warnOnLowercaseComponentTags(templateStr, importedIdentifiers);\n }\n\n const trees = parseComponentTemplate(templateStr, importedIdentifiers);\n if (trees.length === 0) return;\n\n const reportTrees =\n quasi.expressions.length === 0\n ? trees\n : parseComponentTemplate(\n quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join(TEMPLATE_HOLE),\n importedIdentifiers,\n true\n );\n const contextObject = buildContextObject(\n path,\n trees,\n templateStr,\n reportTrees\n );\n\n // ── AOT codegen path ──────────────────────────────────────────────\n if (enableAot && !aotDisabledByCollision) {\n // Templates with ${expr} expressions can't be AOT-compiled safely.\n // PithyJS uses {{ expr }} syntax, not ${}, so this is an edge case guard.\n if (quasi.expressions.length > 0) {\n // Fall through to non-AOT path below\n reportJitFallback(\n path,\n `Template contains \\${expr} expressions — skipping AOT. ` +\n `Refactor to {{ expr }} syntax for AOT compilation.`\n );\n } else if (emitFactory(path, trees, templateStr, contextObject)) {\n return;\n }\n }\n\n // ── Non-AOT path (original behavior) ─────────────────────────────\n const runtimeCall = t.callExpression(path.node.tag, [\n quasi,\n contextObject,\n ]);\n rewrittenCalls.add(runtimeCall);\n path.replaceWith(runtimeCall);\n },\n\n CallExpression(path) {\n if (rewrittenCalls.has(path.node)) return;\n const callee = path.node.callee;\n if (\n !t.isIdentifier(callee) ||\n !pithyCoreHtmlLocalNames.has(callee.name)\n )\n return;\n if (path.scope.getBinding(callee.name)?.kind !== 'module') return;\n\n const [templateArg, contextArg, cssArg] = path.node.arguments;\n const templateStr = t.isStringLiteral(templateArg)\n ? templateArg.value\n : t.isTemplateLiteral(templateArg) &&\n templateArg.expressions.length === 0\n ? templateArg.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('')\n : null;\n const context = contextLiteral(path, contextArg);\n const componentNames = declaredComponents(context);\n\n if (templateStr !== null) {\n reportCallFormAttrs(\n path,\n templateStr,\n componentNames,\n contextStaysInHtmlCalls(path, contextArg) ? context : null,\n quoteForCallForm(path, templateArg)\n );\n }\n\n if (!enableAot || aotDisabledByCollision) return;\n\n totalHtmlTagsFound++;\n\n if (templateStr === null) {\n reportJitFallback(\n path,\n `html() is called with a template that is not a string literal — skipping AOT. ` +\n `Pass the template as a literal.`\n );\n return;\n }\n\n if (cssArg !== undefined && !isAbsentCss(cssArg)) {\n reportJitFallback(\n path,\n `html() is called with a css argument — skipping AOT.`\n );\n return;\n }\n\n if (contextArg && !context) {\n reportJitFallback(\n path,\n `html() is called with a second argument that is not an object literal, so it may be a css string or a context the build cannot read — skipping AOT. ` +\n `Pass the context as an object literal, inline or bound by const.`\n );\n return;\n }\n\n try {\n warnOnLowercaseComponentTags(templateStr, componentNames);\n } catch (err) {\n reportJitFallback(\n path,\n `html() template has a tag that cannot be resolved to a component at build time — skipping AOT. ` +\n `Name the component in a literal \\`__importedIdentifiers: new Set([...])\\` in the context. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return;\n }\n\n emitFactory(\n path,\n parseComponentTemplate(templateStr, componentNames),\n templateStr,\n t.isExpression(contextArg) ? contextArg : t.objectExpression([])\n );\n },\n },\n };\n\n function unwrapTs(node: t.Node | null | undefined): t.Node | null {\n let current = node ?? null;\n while (\n t.isTSAsExpression(current) ||\n t.isTSSatisfiesExpression(current) ||\n t.isTSTypeAssertion(current) ||\n t.isTSNonNullExpression(current) ||\n t.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n }\n\n function isAbsentCss(cssArg: t.Node): boolean {\n const css = unwrapTs(cssArg);\n return (\n t.isIdentifier(css, { name: 'undefined' }) ||\n t.isNullLiteral(css) ||\n t.isStringLiteral(css, { value: '' }) ||\n t.isUnaryExpression(css, { operator: 'void' })\n );\n }\n\n function contextLiteral(\n path: NodePath,\n contextArg: t.Node | undefined\n ): t.ObjectExpression | null {\n const arg = unwrapTs(contextArg);\n if (t.isObjectExpression(arg)) return arg;\n if (!t.isIdentifier(arg)) return null;\n const binding = path.scope.getBinding(arg.name);\n if (binding?.kind !== 'const' || !binding.path.isVariableDeclarator())\n return null;\n if (!t.isIdentifier(binding.path.node.id)) return null;\n const init = unwrapTs(binding.path.node.init);\n return t.isObjectExpression(init) ? init : null;\n }\n\n function declaredComponents(literal: t.ObjectExpression | null): Set<string> {\n const names = new Set<string>();\n if (!literal) return names;\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop)) {\n names.clear();\n continue;\n }\n if (prop.computed) continue;\n const key = t.isIdentifier(prop.key)\n ? prop.key.name\n : t.isStringLiteral(prop.key)\n ? prop.key.value\n : null;\n if (key !== '__importedIdentifiers') continue;\n names.clear();\n if (!t.isObjectProperty(prop)) continue;\n const value = unwrapTs(prop.value);\n if (\n !t.isNewExpression(value) ||\n !t.isIdentifier(value.callee, { name: 'Set' })\n )\n continue;\n const list = unwrapTs(value.arguments[0]);\n if (!t.isArrayExpression(list)) continue;\n for (const element of list.elements) {\n if (t.isStringLiteral(element)) names.add(element.value);\n }\n }\n return names;\n }\n\n function sourceFile(path: NodePath): string | undefined {\n return (\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename\n );\n }\n\n function contextStaysInHtmlCalls(\n path: NodePath,\n contextArg: t.Node | undefined\n ): boolean {\n const arg = unwrapTs(contextArg);\n if (!t.isIdentifier(arg)) return true;\n const binding = path.scope.getBinding(arg.name);\n if (!binding) return true;\n // AOT rewrites earlier html() calls into factory calls that receive the\n // same context, so classify the references once, before any rewrite.\n let stays = contextsInHtmlCalls.get(binding);\n if (stays === undefined) {\n stays = binding.referencePaths.every(reference => {\n if (reference.findParent(p => p.isTSTypeQuery())) return true;\n const call = reference.findParent(\n p => unwrapTs(p.node) !== reference.node\n )?.node;\n return (\n t.isCallExpression(call) &&\n t.isIdentifier(call.callee) &&\n pithyCoreHtmlLocalNames.has(call.callee.name) &&\n reference.scope.getBinding(call.callee.name)?.kind === 'module' &&\n unwrapTs(call.arguments[1]) === reference.node\n );\n });\n contextsInHtmlCalls.set(binding, stays);\n }\n return stays;\n }\n\n function contextKeys(literal: t.ObjectExpression | null): Set<string> | null {\n if (!literal) return null;\n const keys = new Set<string>();\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop) || prop.computed) return null;\n if (t.isIdentifier(prop.key)) keys.add(prop.key.name);\n else if (t.isStringLiteral(prop.key)) keys.add(prop.key.value);\n }\n return keys;\n }\n\n function parseComponentTemplate(\n templateStr: string,\n componentNames: Set<string>,\n quiet = false\n ): PithyNode[] {\n // `importedIdentifiers` is what makes component tags components at all;\n // `withSource: false` keeps interpolation scanning on parse5's decoded\n // text, because codegen locates interpolations with indexOf(interp.raw)\n // against decoded textContent and a raw source slice would carry entities.\n return parseTemplate(templateStr, parseFragment, {\n importedIdentifiers: componentNames,\n withSource: false,\n quiet,\n }).nodes;\n }\n\n function buildContextObject(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n reportTrees: PithyNode[]\n ): t.ObjectExpression {\n // Collect identifiers referenced by expressions in the template\n const { usedIdentifiers, attrReports } = collectIdentifiers(trees);\n\n // Also collect arrow-function param names appearing in attribute expressions\n // so we can remove them from usedIdentifiers (e.g., \"(ev) => ...\" or \"ev => ...\").\n const arrowParams = extractArrowParamNames(templateStr);\n\n const tsNames = declaredTsValueNames(path);\n const reports =\n reportTrees === trees\n ? attrReports\n : collectIdentifiers(reportTrees, true).attrReports.filter(\n ({ attr, value }) =>\n !attr.includes(TEMPLATE_HOLE) && !value.includes(TEMPLATE_HOLE)\n );\n for (const report of reports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n name => path.scope.hasBinding(name) || tsNames.has(name),\n quoteForTemplateSource,\n 'no binding in this module'\n );\n }\n\n // Compute which imported identifiers are actually used as components\n const usedComponents = new Set<string>();\n const collectComponents = (node: PithyNode) => {\n if (node.type === 'element' && node.isComponent && node.originalTagName) {\n usedComponents.add(node.originalTagName);\n }\n for (const child of node.children ?? []) collectComponents(child);\n };\n for (const tree of trees) collectComponents(tree);\n\n // Final filter:\n // - drop arrow params (local to inline handlers)\n // - drop common event aliases ($event, event, ev, e, evt)\n const filteredUsed = [...usedIdentifiers].filter(\n id => !arrowParams.has(id) && !RESERVED_LOCAL_EVENT_NAMES.has(id)\n );\n\n return t.objectExpression([\n // Only hoist filtered used identifiers\n ...filteredUsed.map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add only the components that are actually used in the template\n ...[...usedComponents].map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add imported identifiers as a special property for downstream checks\n t.objectProperty(\n t.identifier('__importedIdentifiers'),\n t.newExpression(t.identifier('Set'), [\n t.arrayExpression(\n [...importedIdentifiers].map(id => t.stringLiteral(id))\n ),\n ])\n ),\n ]);\n }\n\n function collectIdentifiers(\n trees: PithyNode[],\n quiet = false\n ): {\n usedIdentifiers: Set<string>;\n attrReports: ComponentAttrReport[];\n } {\n const usedIdentifiers = new Set<string>();\n const attrReports: ComponentAttrReport[] = [];\n for (const tree of trees) {\n const ids = extractUsedIdentifiers(\n tree,\n componentScopes,\n report => attrReports.push(report),\n quiet\n );\n ids.forEach(id => usedIdentifiers.add(id));\n }\n return { usedIdentifiers, attrReports };\n }\n\n function quoteForCallForm(\n path: NodePath,\n templateArg: t.Node\n ): (value: string) => string {\n if (sourceFile(path)?.endsWith('.pithy')) return quoteForHtmlSource;\n const raw = templateArg.extra?.raw;\n if (typeof raw !== 'string') return quoteForTemplateSource;\n return raw.startsWith(\"'\")\n ? quoteForSingleQuotedSource\n : quoteForDoubleQuotedSource;\n }\n\n function reportCallFormAttrs(\n path: NodePath,\n templateStr: string,\n componentNames: Set<string>,\n context: t.ObjectExpression | null,\n quote: (value: string) => string\n ): void {\n if (componentNames.size === 0) return;\n const keys = contextKeys(context);\n const isDeclared: DeclaredName = name =>\n keys === null ||\n keys.has(name) ||\n (path.scope.hasBinding(name) && !path.scope.getBinding(name));\n const trees = parseComponentTemplate(templateStr, componentNames, true);\n for (const report of collectIdentifiers(trees, true).attrReports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n isDeclared,\n quote,\n 'no entry in the html() context'\n );\n }\n }\n\n function warnOnStringLikeComponentAttr(\n path: NodePath,\n { tag, attr, value, names, parsed, expression, error }: ComponentAttrReport,\n isDeclared: DeclaredName,\n quote: (value: string) => string,\n missing: string\n ): void {\n if (warnsOnComponentProp(attr, value)) return;\n let outcome = `does not parse (Failed to parse expression: ${error}), so the attribute is dropped`;\n let unbound: string[] = [];\n if (parsed) {\n const collected = new Set(names);\n const candidates = expression ? stringLikeNames(expression) : null;\n unbound = [...new Set(candidates ?? [])].filter(\n name => collected.has(name) && !isDeclared(name)\n );\n if (unbound.length === 0) return;\n outcome = `reads ${unbound.map(n => `\\`${n}\\``).join(', ')}, which ${unbound.length === 1 ? 'has' : 'have'} ${missing}, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime`;\n }\n\n const fix =\n parsed || !/[()[\\]{};=]/.test(value) ? `${attr}=${quote(value)}` : null;\n const advice = fix ? ` To pass a string, quote it: ${fix}.` : '';\n\n const file = sourceFile(path) ?? null;\n const loc = path.node.loc?.start;\n const where = file\n ? ` (${file}${loc ? `:${loc.line}:${loc.column + 1}` : ''})`\n : '';\n const finding: TemplateFinding = {\n kind: parsed ? 'unbound' : 'unparsed',\n tag,\n attr,\n value,\n unbound,\n error: parsed ? null : (error ?? null),\n fix,\n file,\n line: loc?.line ?? null,\n column: loc ? loc.column + 1 : null,\n message: `[pithy] <${tag} ${attr}=\"${value}\">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`,\n };\n if (options?.onFinding) options.onFinding(finding);\n else console.warn(finding.message);\n }\n\n function reportJitFallback(path: NodePath, reason: string): void {\n const where = options?.filename ? ` (${options.filename})` : '';\n if (options?.strictAot) {\n throw path.buildCodeFrameError(\n `[pithy:aot:jit-fallback] ${reason}${where}`\n );\n }\n console.warn(\n `[pithy:aot:jit-fallback] ${reason} ` +\n `The template will throw at runtime unless the app calls loadJITCompiler() at startup.${where}`\n );\n }\n\n function emitFactory(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n context: t.Expression\n ): boolean {\n try {\n // Generate deterministic hash from template content\n const rawHash = createHash('sha256')\n .update(templateStr)\n .digest('hex')\n .slice(0, 8);\n const count = aotHashCounter.get(rawHash) ?? 0;\n const hash = count > 0 ? `${rawHash}_${count}` : rawHash;\n\n // Generate scope ID from filename (or fall back to hash)\n const filename =\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename ??\n '';\n const scopeId = filename\n ? generateScopeId(filename)\n : `pithy-${rawHash.slice(0, 6)}`;\n\n // Call AOT codegen\n const aotResult = generateDomFactory(trees, hash, scopeId, {\n templateComponents,\n });\n\n // Only increment counter after successful codegen — if codegen\n // throws, the hash slot stays available for the next attempt.\n aotHashCounter.set(rawHash, count + 1);\n\n // Accumulate factory code for Program.exit injection\n aotFactoryBlocks.push(aotResult.code);\n // Detect actual applyBindings call sites rather than any occurrence of the\n // identifier name. This avoids false positives from template text that may\n // contain the string \"__applyBindings\" inside HTML or attribute values.\n if (aotResult.code.includes('return __applyBindings(')) {\n aotNeedsApplyBindings = true;\n }\n\n totalHtmlTagsAotCompiled++;\n\n path.replaceWith(\n t.callExpression(t.identifier(aotResult.factoryName), [context])\n );\n return true;\n } catch (err) {\n reportJitFallback(\n path,\n `Codegen failed — skipping AOT. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return false;\n }\n }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ /** @codex { "id": "pithy.babel.validate-template", "title": "Template Validation", "category": "compiler", "risk": "medium" } */
2
+ import { type TemplateFinding } from './babelPlugin.js';
3
+ import type { ComponentScopesMap } from './extractUsedIdentifiers.js';
4
+ /** @codexApi {"parent":"pithy.babel.validate-template","name":"ValidateTemplateOptions","stability":"experimental","signature":"interface ValidateTemplateOptions"} */
5
+ export interface ValidateTemplateOptions {
6
+ /** The module's path or id. Without it the module is read as `.ts` and findings carry no location. */
7
+ filename?: string;
8
+ /**
9
+ * The map `htmlTransformPlugin` is given. Pass ui-kit's `componentScopes`
10
+ * for an app's findings: without it `<For>`'s loop names read as unbound.
11
+ */
12
+ componentScopes?: ComponentScopesMap;
13
+ }
14
+ /**
15
+ * The component-attribute findings the Vite plugin warns about, for one module,
16
+ * without building it.
17
+ *
18
+ * Runs the steps the plugin chain runs: a `.pithy` file is compiled and
19
+ * transpiled as `pithyPlugin` does, then the plugin's own Babel pass checks it.
20
+ * A finding's `message`, `line` and `column` are those the dev server and the
21
+ * build print; for a `.pithy` file they refer to the compiled module. Like the
22
+ * chain, it checks `.ts` and `.pithy` files only, skips a module with no `html`
23
+ * template, and returns `[]` for both.
24
+ *
25
+ * @param code - A `.ts` module using `html` templates, or a `.pithy` file.
26
+ * @param options - The filename and the component scopes.
27
+ * @returns One finding per attribute, in source order; empty when all is well.
28
+ * @throws The parser's error when a module the transform reads does not parse,
29
+ * as the build would.
30
+ */
31
+ /** @codexApi {"parent":"pithy.babel.validate-template","name":"validateTemplate","stability":"experimental","signature":"(code: string, options?: ValidateTemplateOptions) => Promise<TemplateFinding[]>"} */
32
+ export declare function validateTemplate(code: string, options?: ValidateTemplateOptions): Promise<TemplateFinding[]>;
33
+ //# sourceMappingURL=validateTemplate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateTemplate.d.ts","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAIjI,OAAyB,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAWnE,uKAAuK;AACvK,MAAM,WAAW,uBAAuB;IACtC,sGAAsG;IACtG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,eAAe,CAAC,EAAE,kBAAkB,CAAC;CACtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,8MAA8M;AAC9M,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,eAAe,EAAE,CAAC,CAoC5B"}
@@ -0,0 +1,66 @@
1
+ /** @codex { "id": "pithy.babel.validate-template", "title": "Template Validation", "category": "compiler", "risk": "medium" } */
2
+ import * as babel from '@babel/core';
3
+ import { createRequire } from 'node:module';
4
+ import pithyBabelPlugin from './babelPlugin.js';
5
+ import { compilePithyModule } from '../pithyPlugin/plugin.js';
6
+ import { readsTemplates } from '../htmlTransform/htmlTransform.js';
7
+ const presetTypescript = createRequire(import.meta.url).resolve('@babel/preset-typescript');
8
+ // Babel needs a name to pick the TS preset; it is not reported.
9
+ const UNNAMED = 'module.ts';
10
+ /**
11
+ * The component-attribute findings the Vite plugin warns about, for one module,
12
+ * without building it.
13
+ *
14
+ * Runs the steps the plugin chain runs: a `.pithy` file is compiled and
15
+ * transpiled as `pithyPlugin` does, then the plugin's own Babel pass checks it.
16
+ * A finding's `message`, `line` and `column` are those the dev server and the
17
+ * build print; for a `.pithy` file they refer to the compiled module. Like the
18
+ * chain, it checks `.ts` and `.pithy` files only, skips a module with no `html`
19
+ * template, and returns `[]` for both.
20
+ *
21
+ * @param code - A `.ts` module using `html` templates, or a `.pithy` file.
22
+ * @param options - The filename and the component scopes.
23
+ * @returns One finding per attribute, in source order; empty when all is well.
24
+ * @throws The parser's error when a module the transform reads does not parse,
25
+ * as the build would.
26
+ */
27
+ /** @codexApi {"parent":"pithy.babel.validate-template","name":"validateTemplate","stability":"experimental","signature":"(code: string, options?: ValidateTemplateOptions) => Promise<TemplateFinding[]>"} */
28
+ export async function validateTemplate(code, options = {}) {
29
+ const id = options.filename;
30
+ const filename = id?.split(/[?#]/, 1)[0] ?? UNNAMED;
31
+ const isPithy = filename.endsWith('.pithy');
32
+ if (!isPithy && !filename.endsWith('.ts'))
33
+ return [];
34
+ const source = isPithy
35
+ ? (await compilePithyModule(code, id ?? filename)).code
36
+ : code;
37
+ if (!readsTemplates(source))
38
+ return [];
39
+ const findings = [];
40
+ babel.transformSync(source, {
41
+ filename,
42
+ plugins: [
43
+ () => pithyBabelPlugin({
44
+ filename,
45
+ componentScopes: options.componentScopes,
46
+ onFinding: finding => findings.push(finding),
47
+ }),
48
+ ],
49
+ presets: [[presetTypescript, { onlyRemoveTypeImports: true }]],
50
+ parserOpts: { sourceType: 'module', plugins: ['typescript'] },
51
+ configFile: false,
52
+ babelrc: false,
53
+ code: false,
54
+ });
55
+ if (id !== undefined)
56
+ return findings;
57
+ return findings.map(f => {
58
+ const at = f.message.lastIndexOf(` (${UNNAMED}`);
59
+ return {
60
+ ...f,
61
+ file: null,
62
+ message: at < 0 ? f.message : f.message.slice(0, at),
63
+ };
64
+ });
65
+ }
66
+ //# sourceMappingURL=validateTemplate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateTemplate.js","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAEjI,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,gBAA0C,MAAM,eAAe,CAAC;AAEvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,MAAM,gBAAgB,GAAG,a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AAQ,EAAE,OAAO,EAAE,CAAC,YAAY,CAAC,EAAE;QAC7D,UAAU,EAAE,KAAK;QACjB,OAAO,EAAE,KAAK;QACd,IAAI,EAAE,KAAK;KACZ,CAAC,CAAC;IACH,IAAI,EAAE,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IACtC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;QACtB,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;QACjD,OAAO;YACL,GAAG,CAAC;YACJ,IAAI,EAAE,IAAI;YACV,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SACrD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.babel.validate-template\", \"title\": \"Template Validation\", \"category\": \"compiler\", \"risk\": \"medium\" } */\n\nimport * as babel from '@babel/core';\nimport { createRequire } from 'node:module';\nimport pithyBabelPlugin, { type TemplateFinding } from './babelPlugin';\nimport type { ComponentScopesMap } from './extractUsedIdentifiers';\nimport { compilePithyModule } from '../pithyPlugin/plugin';\nimport { readsTemplates } from '../htmlTransform/htmlTransform';\n\nconst presetTypescript = createRequire(import.meta.url).resolve(\n '@babel/preset-typescript'\n);\n\n// Babel needs a name to pick the TS preset; it is not reported.\nconst UNNAMED = 'module.ts';\n\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"ValidateTemplateOptions\",\"stability\":\"experimental\",\"signature\":\"interface ValidateTemplateOptions\"} */\nexport interface ValidateTemplateOptions {\n /** The module's path or id. Without it the module is read as `.ts` and findings carry no location. */\n filename?: string;\n /**\n * The map `htmlTransformPlugin` is given. Pass ui-kit's `componentScopes`\n * for an app's findings: without it `<For>`'s loop names read as unbound.\n */\n componentScopes?: ComponentScopesMap;\n}\n\n/**\n * The component-attribute findings the Vite plugin warns about, for one module,\n * without building it.\n *\n * Runs the steps the plugin chain runs: a `.pithy` file is compiled and\n * transpiled as `pithyPlugin` does, then the plugin's own Babel pass checks it.\n * A finding's `message`, `line` and `column` are those the dev server and the\n * build print; for a `.pithy` file they refer to the compiled module. Like the\n * chain, it checks `.ts` and `.pithy` files only, skips a module with no `html`\n * template, and returns `[]` for both.\n *\n * @param code - A `.ts` module using `html` templates, or a `.pithy` file.\n * @param options - The filename and the component scopes.\n * @returns One finding per attribute, in source order; empty when all is well.\n * @throws The parser's error when a module the transform reads does not parse,\n * as the build would.\n */\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"validateTemplate\",\"stability\":\"experimental\",\"signature\":\"(code: string, options?: ValidateTemplateOptions) => Promise<TemplateFinding[]>\"} */\nexport async function validateTemplate(\n code: string,\n options: ValidateTemplateOptions = {}\n): Promise<TemplateFinding[]> {\n const id = options.filename;\n const filename = id?.split(/[?#]/, 1)[0] ?? UNNAMED;\n const isPithy = filename.endsWith('.pithy');\n if (!isPithy && !filename.endsWith('.ts')) return [];\n\n const source = isPithy\n ? (await compilePithyModule(code, id ?? filename)).code\n : code;\n if (!readsTemplates(source)) return [];\n const findings: TemplateFinding[] = [];\n babel.transformSync(source, {\n filename,\n plugins: [\n () =>\n pithyBabelPlugin({\n filename,\n componentScopes: options.componentScopes,\n onFinding: finding => findings.push(finding),\n }),\n ],\n presets: [[presetTypescript, { onlyRemoveTypeImports: true }]],\n parserOpts: { sourceType: 'module', plugins: ['typescript'] },\n configFile: false,\n babelrc: false,\n code: false,\n });\n if (id !== undefined) return findings;\n return findings.map(f => {\n const at = f.message.lastIndexOf(` (${UNNAMED}`);\n return {\n ...f,\n file: null,\n message: at < 0 ? f.message : f.message.slice(0, at),\n };\n });\n}\n"]}
@@ -15,6 +15,15 @@
15
15
  */
16
16
  import type { PluginOption } from 'vite';
17
17
  import type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers.js';
18
+ /**
19
+ * Whether the template transform reads `code` at all: it holds an `html`
20
+ * tagged template, or imports `html` from `@pithyjs/core` (an alias included).
21
+ * Any other module skips Babel, so syntax only esbuild handles still builds.
22
+ *
23
+ * @param code - The module source.
24
+ * @returns `true` when the transform parses it.
25
+ */
26
+ export declare function readsTemplates(code: string): boolean;
18
27
  /** @codexApi {"parent":"pithy.vite.html-transform-plugin","name":"HtmlTransformPluginOptions","stability":"stable","signature":"interface HtmlTransformPluginOptions"} */
19
28
  export interface HtmlTransformPluginOptions {
20
29
  /** Map of component names to variables they inject into children's scope */
@@ -1 +1 @@
1
- {"version":3,"file":"htmlTransform.d.ts","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,MAAM,CAAC;AAIzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAShF,0KAA0K;AAC1K,MAAM,WAAW,0BAA0B;IACzC,4EAA4E;IAC5E,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,kFAAkF;IAClF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,oHAAoH;IACpH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qLAAqL;AACrL,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,0BAA0B,GACnC,YAAY,CAwEd"}
1
+ {"version":3,"file":"htmlTransform.d.ts","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,MAAM,CAAC;AAIzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAShF;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAKpD;AAED,0KAA0K;AAC1K,MAAM,WAAW,0BAA0B;IACzC,4EAA4E;IAC5E,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,kFAAkF;IAClF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,oHAAoH;IACpH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qLAAqL;AACrL,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,0BAA0B,GACnC,YAAY,CAkEd"}
@@ -18,6 +18,18 @@ import * as babel from '@babel/core';
18
18
  import { createRequire } from 'node:module';
19
19
  // Babel resolves preset names from the app, which may not see this package's deps.
20
20
  const presetTypescript = createRequire(import.meta.url).resolve('@babel/preset-typescript');
21
+ /**
22
+ * Whether the template transform reads `code` at all: it holds an `html`
23
+ * tagged template, or imports `html` from `@pithyjs/core` (an alias included).
24
+ * Any other module skips Babel, so syntax only esbuild handles still builds.
25
+ *
26
+ * @param code - The module source.
27
+ * @returns `true` when the transform parses it.
28
+ */
29
+ export function readsTemplates(code) {
30
+ return (code.includes('html`') ||
31
+ /import\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s+['"]@pithyjs\/core['"]/.test(code));
32
+ }
21
33
  /**
22
34
  * Vite plugin that transforms `html\`\`` tagged templates and literal `html()` calls
23
35
  * in `.ts` and compiled `.pithy` modules using Babel.
@@ -64,8 +76,7 @@ export function htmlTransformPlugin(options) {
64
76
  // Check for html` (common case) or aliased html import from @pithyjs/core.
65
77
  if (!normalizedId.endsWith('.ts') && !normalizedId.endsWith('.pithy'))
66
78
  return;
67
- if (!code.includes('html`') &&
68
- !/import\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s+['"]@pithyjs\/core['"]/.test(code))
79
+ if (!readsTemplates(code))
69
80
  return;
70
81
  const babelPluginOptions = {
71
82
  componentScopes: options?.componentScopes,
@@ -1 +1 @@
1
- {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AChC,2EAA2E;YAC3E,MAAM,YAAY,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5C,wDAAwD;YACxD,2EAA2E;YAC3E,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBACnE,OAAO;YACT,IACE,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;gBACvB,CAAC,iEAAiE,CAAC,IAAI,CACrE,IAAI,CACL;gBAED,OAAO;YAET,MAAM,kBAAkB,GAA4B;gBAClD,eAAe,EAAE,OAAO,EAAE,eAAe;gBACzC,GAAG,EAAE,WAAW;gBAChB,SAAS,EAAE,OAAO,EAAE,SAAS;gBAC7B,QAAQ,EAAE,YAAY;aACvB,CAAC;YAEF,MAAM,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE;gBACvC,QAAQ,EAAE,YAAY;gBACtB,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;gBACrD,OAAO,EAAE;oBACP;wBACE,gBAAgB;wBAChB;4BACE,qBAAqB,EAAE,IAAI;yBAC5B;qBACF;iBACF;gBACD,UAAU,EAAE;oBACV,UAAU,EAAE,QAAQ;oBACpB,OAAO,EAAE,CAAC,YAAY,CAAC;iBACxB;gBACD,UAAU,EAAE,KAAK;gBACjB,UAAU;aACX,CAAC,CAAC;YAEH,OAAO;gBACL,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,IAAI;gBAC1B,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,IAAI;aACzB,CAAC;QACJ,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.html-transform-plugin\",\n \"title\": \"HTML Transform Vite Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel-based Vite plugin that transforms html`…` tagged templates and literal html() calls in .ts and compiled .pithy modules, with optional AOT compilation to eliminate runtime HTML parsing.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"htmlTransformAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport type { PluginOption, ResolvedConfig } from 'vite';\nimport pithyBabelPlugin, {\n type PithyBabelPluginOptions,\n} from '../babelPlugin/babelPlugin';\nimport type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers';\nimport * as babel from '@babel/core';\nimport { createRequire } from 'node:module';\n\n// Babel resolves preset names from the app, which may not see this package's deps.\nconst presetTypescript = createRequire(import.meta.url).resolve(\n '@babel/preset-typescript'\n);\n\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"HtmlTransformPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface HtmlTransformPluginOptions\"} */\nexport interface HtmlTransformPluginOptions {\n /** Map of component names to variables they inject into children's scope */\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: true in build mode, false in dev. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n}\n\n/**\n * Vite plugin that transforms `html\\`\\`` tagged templates and literal `html()` calls\n * in `.ts` and compiled `.pithy` modules using Babel.\n *\n * In build mode, templates are AOT-compiled to eliminate runtime HTML parsing.\n * In dev mode, tagged templates only get their context injected and still render\n * through the runtime compiler, unless `aot` is explicitly enabled.\n * `pithyPlugin()` must be listed before this plugin.\n *\n * @param options - Plugin configuration for AOT mode, strict AOT, and component scopes\n * @returns A Vite plugin that transforms html tagged templates\n *\n * @example\n * ```ts\n * import { htmlTransformPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [htmlTransformPlugin({ aot: true })],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"htmlTransformPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: HtmlTransformPluginOptions) => PluginOption\"} */\nexport function htmlTransformPlugin(\n options?: HtmlTransformPluginOptions\n): PluginOption {\n let resolvedAot = false;\n let sourceMaps = true;\n\n const plugin = {\n name: 'pithy:html-transform',\n enforce: 'pre' as const,\n\n configResolved(config: ResolvedConfig) {\n // Default: AOT enabled in build, disabled in dev (for faster HMR)\n resolvedAot = options?.aot ?? config.command === 'build';\n\n sourceMaps = config.command === 'serve' || !!config.build?.sourcemap;\n\n const plugins = config.plugins ?? [];\n const sfc = plugins.findIndex(p => p.name === 'vite-plugin-pithy');\n if (sfc !== -1 && sfc > plugins.indexOf(plugin)) {\n throw new Error(\n '[pithy:html-transform] pithyPlugin() must be listed before htmlTransformPlugin(), ' +\n 'so .pithy files reach the template transform already compiled.'\n );\n }\n },\n\n transform(code: string, id: string) {\n // Strip Vite query/hash suffixes (e.g. component.ts?import → component.ts)\n const normalizedId = id.split(/[?#]/, 1)[0];\n // Fast-path: skip files with no pithy tagged templates.\n // Check for html` (common case) or aliased html import from @pithyjs/core.\n if (!normalizedId.endsWith('.ts') && !normalizedId.endsWith('.pithy'))\n return;\n if (\n !code.includes('html`') &&\n !/import\\s*\\{[^}]*\\bhtml\\b[^}]*\\}\\s*from\\s+['\"]@pithyjs\\/core['\"]/.test(\n code\n )\n )\n return;\n\n const babelPluginOptions: PithyBabelPluginOptions = {\n componentScopes: options?.componentScopes,\n aot: resolvedAot,\n strictAot: options?.strictAot,\n filename: normalizedId,\n };\n\n const result = babel.transformSync(code, {\n filename: normalizedId,\n plugins: [() => pithyBabelPlugin(babelPluginOptions)],\n presets: [\n [\n presetTypescript,\n {\n onlyRemoveTypeImports: true,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript'],\n },\n configFile: false,\n sourceMaps,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map ?? null,\n };\n },\n };\n return plugin;\n}\n"]}
1
+ {"version":3,"file":"htmlTransform.js","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAGF,OAAO,gBAEN,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,mFAAmF;AACnF,MAAM,gBAAgB,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAC7D,0BAA0B,CAC3B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,CACL,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QACtB,iEAAiE,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7E,CAAC;AACJ,CAAC;AAYD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qLAAqL;AACrL,MAAM,UAAU,mBAAmB,CACjC,OAAoC;IAEpC,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,IAAI,UAAU,GAAG,IAAI,CAAC;IAEtB,MAAM,MAAM,GAAG;QACb,IAAI,EAAE,sBAAsB;QAC5B,OAAO,EAAE,KAAc;QAEvB,cAAc,CAAC,MAAsB;YACnC,kEAAkE;YAClE,WAAW,GAAG,OAAO,EAAE,GAAG,IAAI,MAAM,CAAC,OAAO,KAAK,OAAO,CAAC;YAEzD,UAAU,GAAG,MAAM,CAAC,OAAO,KAAK,OAAO,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC;YAErE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;YACrC,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,mBAAmB,CA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ACzB,CAAC;QACJ,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.html-transform-plugin\",\n \"title\": \"HTML Transform Vite Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel-based Vite plugin that transforms html`…` tagged templates and literal html() calls in .ts and compiled .pithy modules, with optional AOT compilation to eliminate runtime HTML parsing.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"htmlTransformAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport type { PluginOption, ResolvedConfig } from 'vite';\nimport pithyBabelPlugin, {\n type PithyBabelPluginOptions,\n} from '../babelPlugin/babelPlugin';\nimport type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers';\nimport * as babel from '@babel/core';\nimport { createRequire } from 'node:module';\n\n// Babel resolves preset names from the app, which may not see this package's deps.\nconst presetTypescript = createRequire(import.meta.url).resolve(\n '@babel/preset-typescript'\n);\n\n/**\n * Whether the template transform reads `code` at all: it holds an `html`\n * tagged template, or imports `html` from `@pithyjs/core` (an alias included).\n * Any other module skips Babel, so syntax only esbuild handles still builds.\n *\n * @param code - The module source.\n * @returns `true` when the transform parses it.\n */\nexport function readsTemplates(code: string): boolean {\n return (\n code.includes('html`') ||\n /import\\s*\\{[^}]*\\bhtml\\b[^}]*\\}\\s*from\\s+['\"]@pithyjs\\/core['\"]/.test(code)\n );\n}\n\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"HtmlTransformPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface HtmlTransformPluginOptions\"} */\nexport interface HtmlTransformPluginOptions {\n /** Map of component names to variables they inject into children's scope */\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: true in build mode, false in dev. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n}\n\n/**\n * Vite plugin that transforms `html\\`\\`` tagged templates and literal `html()` calls\n * in `.ts` and compiled `.pithy` modules using Babel.\n *\n * In build mode, templates are AOT-compiled to eliminate runtime HTML parsing.\n * In dev mode, tagged templates only get their context injected and still render\n * through the runtime compiler, unless `aot` is explicitly enabled.\n * `pithyPlugin()` must be listed before this plugin.\n *\n * @param options - Plugin configuration for AOT mode, strict AOT, and component scopes\n * @returns A Vite plugin that transforms html tagged templates\n *\n * @example\n * ```ts\n * import { htmlTransformPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [htmlTransformPlugin({ aot: true })],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"htmlTransformPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: HtmlTransformPluginOptions) => PluginOption\"} */\nexport function htmlTransformPlugin(\n options?: HtmlTransformPluginOptions\n): PluginOption {\n let resolvedAot = false;\n let sourceMaps = true;\n\n const plugin = {\n name: 'pithy:html-transform',\n enforce: 'pre' as const,\n\n configResolved(config: ResolvedConfig) {\n // Default: AOT enabled in build, disabled in dev (for faster HMR)\n resolvedAot = options?.aot ?? config.command === 'build';\n\n sourceMaps = config.command === 'serve' || !!config.build?.sourcemap;\n\n const plugins = config.plugins ?? [];\n const sfc = plugins.findIndex(p => p.name === 'vite-plugin-pithy');\n if (sfc !== -1 && sfc > plugins.indexOf(plugin)) {\n throw new Error(\n '[pithy:html-transform] pithyPlugin() must be listed before htmlTransformPlugin(), ' +\n 'so .pithy files reach the template transform already compiled.'\n );\n }\n },\n\n transform(code: string, id: string) {\n // Strip Vite query/hash suffixes (e.g. component.ts?import → component.ts)\n const normalizedId = id.split(/[?#]/, 1)[0];\n // Fast-path: skip files with no pithy tagged templates.\n // Check for html` (common case) or aliased html import from @pithyjs/core.\n if (!normalizedId.endsWith('.ts') && !normalizedId.endsWith('.pithy'))\n return;\n if (!readsTemplates(code)) return;\n\n const babelPluginOptions: PithyBabelPluginOptions = {\n componentScopes: options?.componentScopes,\n aot: resolvedAot,\n strictAot: options?.strictAot,\n filename: normalizedId,\n };\n\n const result = babel.transformSync(code, {\n filename: normalizedId,\n plugins: [() => pithyBabelPlugin(babelPluginOptions)],\n presets: [\n [\n presetTypescript,\n {\n onlyRemoveTypeImports: true,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript'],\n },\n configFile: false,\n sourceMaps,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map ?? null,\n };\n },\n };\n return plugin;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -23,6 +23,8 @@
23
23
  export { pithyPlugin } from './pithyPlugin/plugin.js';
24
24
  export { htmlTransformPlugin, type HtmlTransformPluginOptions, } from './htmlTransform/htmlTransform.js';
25
25
  export type { ComponentScopesMap, ComponentScopeConfig, } from './babelPlugin/extractUsedIdentifiers.js';
26
+ export { validateTemplate, type ValidateTemplateOptions, } from './babelPlugin/validateTemplate.js';
27
+ export type { TemplateFinding } from './babelPlugin/babelPlugin.js';
26
28
  export { pithyBuild } from './buildPlugin/plugin.js';
27
29
  export { pithyRouter, type PithyRouterPluginOptions, } from './routerPlugin/plugin.js';
28
30
  export { designSystemPlugin, type DesignSystemPluginOptions, } from './designSystemPlugin/index.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF;;;;;;GAMG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGnD,OAAO,EACL,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGlD,OAAO,EACL,WAAW,EACX,KAAK,wBAAwB,GAC9B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,GAC/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,QAAQ,EAAE,KAAK,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAG1E,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF;;;;;;GAMG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGnD,OAAO,EACL,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EACL,gBAAgB,EAChB,KAAK,uBAAuB,GAC7B,MAAM,gCAAgC,CAAC;AACxC,YAAY,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAGjE,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGlD,OAAO,EACL,WAAW,EACX,KAAK,wBAAwB,GAC9B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,GAC/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,QAAQ,EAAE,KAAK,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAG1E,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -24,6 +24,8 @@
24
24
  export { pithyPlugin } from './pithyPlugin/plugin.js';
25
25
  // HTML template transform plugin (for html`` tagged templates)
26
26
  export { htmlTransformPlugin, } from './htmlTransform/htmlTransform.js';
27
+ // The plugin's component-attribute checks, callable without a build
28
+ export { validateTemplate, } from './babelPlugin/validateTemplate.js';
27
29
  // Build optimization plugin (chunk naming, vendor splitting)
28
30
  export { pithyBuild } from './buildPlugin/plugin.js';
29
31
  // Router plugin (file-based routing)
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF;;;;;;GAMG;AAEH,oCAAoC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,+DAA+D;AAC/D,OAAO,EACL,mBAAmB,GAEpB,MAAM,+BAA+B,CAAC;AAMvC,6DAA6D;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,qCAAqC;AACrC,OAAO,EACL,WAAW,GAEZ,MAAM,uBAAuB,CAAC;AAE/B,wCAAwC;AACxC,OAAO,EACL,kBAAkB,GAEnB,MAAM,sBAAsB,CAAC;AAE9B,wBAAwB;AACxB,OAAO,EAAE,QAAQ,EAA8B,MAAM,oBAAoB,CAAC;AAE1E,gCAAgC;AAChC,OAAO,EAAE,UAAU,EAA0B,MAAM,eAAe,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite-plugin\",\n \"title\": \"Vite Plugin Entry\",\n \"category\": \"plugin\",\n \"description\": \"Public entry point re-exporting all PithyJS Vite plugins.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": false, \"covered\": false },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\n/**\n * @pithyjs/vite-plugin\n *\n * Vite plugins for the PithyJS framework.\n *\n * @module @pithyjs/vite-plugin\n */\n\n// Main .pithy file transform plugin\nexport { pithyPlugin } from './pithyPlugin/plugin';\n\n// HTML template transform plugin (for html`` tagged templates)\nexport {\n htmlTransformPlugin,\n type HtmlTransformPluginOptions,\n} from './htmlTransform/htmlTransform';\nexport type {\n ComponentScopesMap,\n ComponentScopeConfig,\n} from './babelPlugin/extractUsedIdentifiers';\n\n// Build optimization plugin (chunk naming, vendor splitting)\nexport { pithyBuild } from './buildPlugin/plugin';\n\n// Router plugin (file-based routing)\nexport {\n pithyRouter,\n type PithyRouterPluginOptions,\n} from './routerPlugin/plugin';\n\n// Design system CSS tree-shaking plugin\nexport {\n designSystemPlugin,\n type DesignSystemPluginOptions,\n} from './designSystemPlugin';\n\n// SSR dev server plugin\nexport { pithySSR, type PithySSRPluginOptions } from './ssrPlugin/plugin';\n\n// Icon sprite generation plugin\nexport { pithyIcons, type PithyIconsOptions } from './iconsPlugin';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF;;;;;;GAMG;AAEH,oCAAoC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,+DAA+D;AAC/D,OAAO,EACL,mBAAmB,GAEpB,MAAM,+BAA+B,CAAC;AAMvC,oEAAoE;AACpE,OAAO,EACL,gBAAgB,GAEjB,MAAM,gCAAgC,CAAC;AAGxC,6DAA6D;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,qCAAqC;AACrC,OAAO,EACL,WAAW,GAEZ,MAAM,uBAAuB,CAAC;AAE/B,wCAAwC;AACxC,OAAO,EACL,kBAAkB,GAEnB,MAAM,sBAAsB,CAAC;AAE9B,wBAAwB;AACxB,OAAO,EAAE,QAAQ,EAA8B,MAAM,oBAAoB,CAAC;AAE1E,gCAAgC;AAChC,OAAO,EAAE,UAAU,EAA0B,MAAM,eAAe,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite-plugin\",\n \"title\": \"Vite Plugin Entry\",\n \"category\": \"plugin\",\n \"description\": \"Public entry point re-exporting all PithyJS Vite plugins.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": false, \"covered\": false },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\n/**\n * @pithyjs/vite-plugin\n *\n * Vite plugins for the PithyJS framework.\n *\n * @module @pithyjs/vite-plugin\n */\n\n// Main .pithy file transform plugin\nexport { pithyPlugin } from './pithyPlugin/plugin';\n\n// HTML template transform plugin (for html`` tagged templates)\nexport {\n htmlTransformPlugin,\n type HtmlTransformPluginOptions,\n} from './htmlTransform/htmlTransform';\nexport type {\n ComponentScopesMap,\n ComponentScopeConfig,\n} from './babelPlugin/extractUsedIdentifiers';\n\n// The plugin's component-attribute checks, callable without a build\nexport {\n validateTemplate,\n type ValidateTemplateOptions,\n} from './babelPlugin/validateTemplate';\nexport type { TemplateFinding } from './babelPlugin/babelPlugin';\n\n// Build optimization plugin (chunk naming, vendor splitting)\nexport { pithyBuild } from './buildPlugin/plugin';\n\n// Router plugin (file-based routing)\nexport {\n pithyRouter,\n type PithyRouterPluginOptions,\n} from './routerPlugin/plugin';\n\n// Design system CSS tree-shaking plugin\nexport {\n designSystemPlugin,\n type DesignSystemPluginOptions,\n} from './designSystemPlugin';\n\n// SSR dev server plugin\nexport { pithySSR, type PithySSRPluginOptions } from './ssrPlugin/plugin';\n\n// Icon sprite generation plugin\nexport { pithyIcons, type PithyIconsOptions } from './iconsPlugin';\n"]}
@@ -13,7 +13,7 @@
13
13
  }
14
14
  }
15
15
  */
16
- import { type Plugin } from 'vite';
16
+ import { transformWithEsbuild, type Plugin } from 'vite';
17
17
  /**
18
18
  * Vite plugin to support `.pithy` single-file components (SFC).
19
19
  *
@@ -35,4 +35,15 @@ import { type Plugin } from 'vite';
35
35
  */
36
36
  /** @codexApi {"parent":"pithy.vite.plugin","name":"pithyPlugin","stability":"stable","signature":"() => Plugin"} */
37
37
  export declare function pithyPlugin(): Plugin;
38
+ /**
39
+ * Compiles a `.pithy` file to the JavaScript module the rest of the chain sees.
40
+ *
41
+ * @param code - The `.pithy` source.
42
+ * @param id - Its module id; a Vite query suffix is ignored.
43
+ * @returns The JavaScript module and its source map.
44
+ */
45
+ export declare function compilePithyModule(code: string, id: string): Promise<{
46
+ code: string;
47
+ map: Awaited<ReturnType<typeof transformWithEsbuild>>['map'];
48
+ }>;
38
49
  //# sourceMappingURL=plugin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/pithyPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAIF,OAAO,EAAwB,KAAK,MAAM,EAAmB,MAAM,MAAM,CAAC;AAE1E;;;;;;;;;;;;;;;;;;GAkBG;AACH,oHAAoH;AACpH,wBAAgB,WAAW,IAAI,MAAM,CAwDpC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/pithyPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAIF,OAAO,EAAE,oBAAoB,EAAE,KAAK,MAAM,EAAmB,MAAM,MAAM,CAAC;AAE1E;;;;;;;;;;;;;;;;;;GAkBG;AACH,oHAAoH;AACpH,wBAAgB,WAAW,IAAI,MAAM,CAsCpC;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,OAAO,CAAC;IACT,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;CAC9D,CAAC,CAYD"}
@@ -54,23 +54,9 @@ export function pithyPlugin() {
54
54
  // `.pithy` modules are always transformed and the scope id is stable across
55
55
  // reloads. `#` is left intact — module ids carry queries, not URL fragments, and
56
56
  // `#` can be a legitimate path character.
57
- const filePath = id.split('?', 1)[0];
58
- if (!filePath.endsWith('.pithy'))
57
+ if (!id.split('?', 1)[0].endsWith('.pithy'))
59
58
  return;
60
- // Parse the raw .pithy file into its sections (template, script, style)
61
- const parsed = parsePithyFile(code);
62
- // Generate a short scoped ID for styles based on the file path
63
- const filename = path.basename(filePath);
64
- const scopeId = generateScopeId(filePath);
65
- // Compile the parsed content into a full TypeScript module. The <script
66
- // lang="ts"> body may contain TS-only syntax (type aliases, generics, `as`),
67
- // and Vite's esbuild pass does NOT run on `.pithy` ids — so transpile the
68
- // generated module to JS here (also yields a proper source map).
69
- const tsCode = compileToModule(parsed, { filename, scopeId });
70
- const { code: jsCode, map } = await transformWithEsbuild(tsCode, id, {
71
- loader: 'ts',
72
- });
73
- return { code: jsCode, map };
59
+ return compilePithyModule(code, id);
74
60
  },
75
61
  /**
76
62
  * Handles hot module replacement (HMR) for `.pithy` files.
@@ -88,6 +74,26 @@ export function pithyPlugin() {
88
74
  },
89
75
  };
90
76
  }
77
+ /**
78
+ * Compiles a `.pithy` file to the JavaScript module the rest of the chain sees.
79
+ *
80
+ * @param code - The `.pithy` source.
81
+ * @param id - Its module id; a Vite query suffix is ignored.
82
+ * @returns The JavaScript module and its source map.
83
+ */
84
+ export async function compilePithyModule(code, id) {
85
+ const filePath = id.split('?', 1)[0];
86
+ const parsed = parsePithyFile(code);
87
+ const filename = path.basename(filePath);
88
+ const scopeId = generateScopeId(filePath);
89
+ // The <script lang="ts"> body may hold TS-only syntax and Vite's esbuild pass
90
+ // does not run on `.pithy` ids, so transpile the generated module here.
91
+ const tsCode = compileToModule(parsed, { filename, scopeId });
92
+ const { code: jsCode, map } = await transformWithEsbuild(tsCode, id, {
93
+ loader: 'ts',
94
+ });
95
+ return { code: jsCode, map };
96
+ }
91
97
  /**
92
98
  * Generates a short, per-file-unique scope ID from a file path.
93
99
  *
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/pithyPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,IAAI,MAAM,MAAM,CAAC;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AAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAChC,KAAK,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;oBAC9B,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;gBAC/C,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAS,eAAe,CAAC,QAAgB;IACvC,IAAI,IAAI,GAAG,IAAI,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.plugin\",\n \"title\": \"Vite Pithy Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Vite plugin that transforms .pithy single-file components into compiled TypeScript modules with HMR support.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": false },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport path from 'path';\nimport { compileToModule, parsePithyFile } from '@pithyjs/compiler';\nimport { transformWithEsbuild, type Plugin, type HmrContext } from 'vite';\n\n/**\n * Vite plugin to support `.pithy` single-file components (SFC).\n *\n * - Transforms `.pithy` files into compiled JavaScript modules (the generated\n * TypeScript is transpiled to JS via esbuild before being returned).\n * - Automatically scopes styles and templates.\n * - Supports hot module replacement (HMR) for faster development.\n *\n * @returns A Vite plugin that handles .pithy file transformation and HMR\n *\n * @example\n * ```ts\n * import { pithyPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [pithyPlugin()],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.plugin\",\"name\":\"pithyPlugin\",\"stability\":\"stable\",\"signature\":\"() => Plugin\"} */\nexport function pithyPlugin(): Plugin {\n return {\n name: 'vite-plugin-pithy',\n enforce: 'pre', // Run early before other plugins\n\n /**\n * Transforms a `.pithy` file into a compiled JavaScript module: the compiler\n * emits a TypeScript module, which is transpiled to JS via esbuild here.\n *\n * @param code - Raw source code of the `.pithy` file\n * @param id - Full path or virtual ID of the file\n * @returns Compiled JavaScript code and a source map\n */\n async transform(code: string, id: string) {\n // Vite appends query suffixes to ids (e.g. `.pithy?import`, `.pithy?v=…`). Match\n // and derive the filename/scope id from the bare path (before the `?`) so\n // `.pithy` modules are always transformed and the scope id is stable across\n // reloads. `#` is left intact — module ids carry queries, not URL fragments, and\n // `#` can be a legitimate path character.\n const filePath = id.split('?', 1)[0];\n if (!filePath.endsWith('.pithy')) return;\n\n // Parse the raw .pithy file into its sections (template, script, style)\n const parsed = parsePithyFile(code);\n\n // Generate a short scoped ID for styles based on the file path\n const filename = path.basename(filePath);\n const scopeId = generateScopeId(filePath);\n\n // Compile the parsed content into a full TypeScript module. The <script\n // lang=\"ts\"> body may contain TS-only syntax (type aliases, generics, `as`),\n // and Vite's esbuild pass does NOT run on `.pithy` ids — so transpile the\n // generated module to JS here (also yields a proper source map).\n const tsCode = compileToModule(parsed, { filename, scopeId });\n const { code: jsCode, map } = await transformWithEsbuild(tsCode, id, {\n loader: 'ts',\n });\n\n return { code: jsCode, map };\n },\n\n /**\n * Handles hot module replacement (HMR) for `.pithy` files.\n *\n * Invalidates the module graph so Vite reloads updated components automatically.\n *\n * @param ctx - Vite HMR context\n */\n handleHotUpdate(ctx: HmrContext): void {\n if (ctx.file.endsWith('.pithy')) {\n for (const mod of ctx.modules) {\n ctx.server.moduleGraph.invalidateModule(mod);\n }\n }\n },\n };\n}\n\n/**\n * Generates a short, per-file-unique scope ID from a file path.\n *\n * Uses a djb2 hash of the WHOLE path rather than a base64 prefix: sibling files\n * share a long common path prefix, so slicing the first base64 chars produced\n * identical IDs for every component — making their scoped styles collide. The hash\n * spreads across the full path, and base36 keeps the id lowercase (the runtime\n * lowercases the `data-scope-<id>` attribute name, so the CSS must match).\n *\n * Example: \"src/components/Button.pithy\" → \"pithy-1a2b3c\"\n *\n * @param filepath - Full file path\n * @returns A short scope ID like `pithy-abc123`\n */\nfunction generateScopeId(filepath: string): string {\n let hash = 5381;\n for (let i = 0; i < filepath.length; i++) {\n hash = (((hash << 5) + hash) ^ filepath.charCodeAt(i)) >>> 0;\n }\n return 'pithy-' + hash.toString(36);\n}\n"]}
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/pithyPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAgC,MAAM,MAAM,CAAC;AAE1E;;;;;;;;;;;;;;;;;;GAkBG;AACH,oHAAoH;AACpH,MAAM,UAAU,WAAW;IACzB,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,KAAK,EAAE,iCAAiC;QAEjD;;;;;;;WAOG;QACH,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,EAAU;YACtC,iFAAiF;YACjF,0EAA0E;YAC1E,4EAA4E;YAC5E,iFAAiF;YACjF,0CAA0C;YAC1C,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBAAE,OAAO;YACpD,OAAO,kBAAkB,CAAC,IAAI,EAAE,EAAE,CAAC,C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,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.plugin\",\n \"title\": \"Vite Pithy Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Vite plugin that transforms .pithy single-file components into compiled TypeScript modules with HMR support.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": false },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport path from 'path';\nimport { compileToModule, parsePithyFile } from '@pithyjs/compiler';\nimport { transformWithEsbuild, type Plugin, type HmrContext } from 'vite';\n\n/**\n * Vite plugin to support `.pithy` single-file components (SFC).\n *\n * - Transforms `.pithy` files into compiled JavaScript modules (the generated\n * TypeScript is transpiled to JS via esbuild before being returned).\n * - Automatically scopes styles and templates.\n * - Supports hot module replacement (HMR) for faster development.\n *\n * @returns A Vite plugin that handles .pithy file transformation and HMR\n *\n * @example\n * ```ts\n * import { pithyPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [pithyPlugin()],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.plugin\",\"name\":\"pithyPlugin\",\"stability\":\"stable\",\"signature\":\"() => Plugin\"} */\nexport function pithyPlugin(): Plugin {\n return {\n name: 'vite-plugin-pithy',\n enforce: 'pre', // Run early before other plugins\n\n /**\n * Transforms a `.pithy` file into a compiled JavaScript module: the compiler\n * emits a TypeScript module, which is transpiled to JS via esbuild here.\n *\n * @param code - Raw source code of the `.pithy` file\n * @param id - Full path or virtual ID of the file\n * @returns Compiled JavaScript code and a source map\n */\n async transform(code: string, id: string) {\n // Vite appends query suffixes to ids (e.g. `.pithy?import`, `.pithy?v=…`). Match\n // and derive the filename/scope id from the bare path (before the `?`) so\n // `.pithy` modules are always transformed and the scope id is stable across\n // reloads. `#` is left intact — module ids carry queries, not URL fragments, and\n // `#` can be a legitimate path character.\n if (!id.split('?', 1)[0].endsWith('.pithy')) return;\n return compilePithyModule(code, id);\n },\n\n /**\n * Handles hot module replacement (HMR) for `.pithy` files.\n *\n * Invalidates the module graph so Vite reloads updated components automatically.\n *\n * @param ctx - Vite HMR context\n */\n handleHotUpdate(ctx: HmrContext): void {\n if (ctx.file.endsWith('.pithy')) {\n for (const mod of ctx.modules) {\n ctx.server.moduleGraph.invalidateModule(mod);\n }\n }\n },\n };\n}\n\n/**\n * Compiles a `.pithy` file to the JavaScript module the rest of the chain sees.\n *\n * @param code - The `.pithy` source.\n * @param id - Its module id; a Vite query suffix is ignored.\n * @returns The JavaScript module and its source map.\n */\nexport async function compilePithyModule(\n code: string,\n id: string\n): Promise<{\n code: string;\n map: Awaited<ReturnType<typeof transformWithEsbuild>>['map'];\n}> {\n const filePath = id.split('?', 1)[0];\n const parsed = parsePithyFile(code);\n const filename = path.basename(filePath);\n const scopeId = generateScopeId(filePath);\n // The <script lang=\"ts\"> body may hold TS-only syntax and Vite's esbuild pass\n // does not run on `.pithy` ids, so transpile the generated module here.\n const tsCode = compileToModule(parsed, { filename, scopeId });\n const { code: jsCode, map } = await transformWithEsbuild(tsCode, id, {\n loader: 'ts',\n });\n return { code: jsCode, map };\n}\n\n/**\n * Generates a short, per-file-unique scope ID from a file path.\n *\n * Uses a djb2 hash of the WHOLE path rather than a base64 prefix: sibling files\n * share a long common path prefix, so slicing the first base64 chars produced\n * identical IDs for every component — making their scoped styles collide. The hash\n * spreads across the full path, and base36 keeps the id lowercase (the runtime\n * lowercases the `data-scope-<id>` attribute name, so the CSS must match).\n *\n * Example: \"src/components/Button.pithy\" → \"pithy-1a2b3c\"\n *\n * @param filepath - Full file path\n * @returns A short scope ID like `pithy-abc123`\n */\nfunction generateScopeId(filepath: string): string {\n let hash = 5381;\n for (let i = 0; i < filepath.length; i++) {\n hash = (((hash << 5) + hash) ^ filepath.charCodeAt(i)) >>> 0;\n }\n return 'pithy-' + hash.toString(36);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithyjs/vite-plugin",
3
- "version": "0.2.0-beta.20",
3
+ "version": "0.2.0-beta.21",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/PithyJS/pithyjs.git",