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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,8 +63,7 @@ hydration writes are identical by construction.
63
63
  > ⚠️ **Do not import `@pithyjs/design-system/colors/styles` in an app that uses
64
64
  > this plugin.** Both define the same `--color-*` tokens on overlapping
65
65
  > selectors, so whichever comes last in source order wins. If that is the SCSS,
66
- > your page paints from its hardcoded literals — the ones that have drifted from
67
- > the runtime state-variant math — and your configured `seed` is ignored. Pick
66
+ > your page paints the default theme and your configured `seed` is ignored. Pick
68
67
  > one source of truth.
69
68
 
70
69
  ### pithySSR
@@ -1 +1 @@
1
- {"version":3,"file":"generateDomFactory.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EAIL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAsB3B,MAAM,WAAW,gBAAgB;IAC/B,6FAA6F;IAC7F,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,kBAAkB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAAE,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE,iBAAsB,GAC9B,gBAAgB,CAoGlB"}
1
+ {"version":3,"file":"generateDomFactory.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EAIL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAwB3B,MAAM,WAAW,gBAAgB;IAC/B,6FAA6F;IAC7F,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,kBAAkB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAAE,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE,iBAAsB,GAC9B,gBAAgB,CAoGlB"}
@@ -14,7 +14,7 @@
14
14
  }
15
15
  */
16
16
  import { componentChildDirectiveMessage, componentChildDirectives, loopConflictMessage, } from '@pithyjs/compiler';
17
- import { createSerializeContext, serializeNode, } from './serializeNode.js';
17
+ import { createSerializeContext, serializeNode, appendChildren, enterTemplate, } from './serializeNode.js';
18
18
  import { generateBindings, serializeBindings, } from './generateBindings.js';
19
19
  import { collectIfChain, stripStructuralDirective, isDefaultCase, } from './structuralCodegen.js';
20
20
  import { escapeJS } from './utils.js';
@@ -351,14 +351,10 @@ function processNodes(nodes, ctx, safeHash, scopeId, subFactoryCodeBlocks, struc
351
351
  continue;
352
352
  }
353
353
  // Recursively process children (handles nested structural directives)
354
+ const leave = enterTemplate(node, result.varName, ctx);
354
355
  const childVarNames = processNodes(node.children ?? [], ctx, safeHash, scopeId, subFactoryCodeBlocks, structuralDescriptors, options, childFactories, slotFactories);
355
- // Append children to this element
356
- if (childVarNames.length === 1) {
357
- ctx.lines.push(`${result.varName}.appendChild(${childVarNames[0]});`);
358
- }
359
- else if (childVarNames.length > 1) {
360
- ctx.lines.push(`${result.varName}.append(${childVarNames.join(',')});`);
361
- }
356
+ leave();
357
+ appendChildren(node, result.varName, childVarNames, ctx);
362
358
  varNames.push(result.varName);
363
359
  continue;
364
360
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generateDomFactory.js","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,GAEpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,aAAa,GAEd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,GAMlB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,aAAa,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAkBnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,MAAM,UAAU,kBAAkB,CAChC,KAAkB,EAClB,IAAY,EACZ,OAAgB,EAChB,UAA6B,EAAE;IAE/B,iFAAiF;IACjF,oEAAoE;IACpE,IAAI,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,KAAK,CACb,yBAAyB,OAAO,uEAAuE,CACxG,CAAC;IACJ,CAAC;IAED,iFAAiF;IACjF,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAA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AAQ,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QACzE,MAAM,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC;QAC1B,MAAM,MAAM,GAAG,CAAC,EAAE,EAAE,KAAK,SAAS,CAAC;QACnC,MAAM,QAAQ,GAAG,CAAC,EAAE,MAAM,KAAK,SAAS,IAAI,CAAC,EAAE,IAAI,KAAK,SAAS,CAAC;QAClE,MAAM,MAAM,GAAG,CAAC,EAAE,GAAG,KAAK,SAAS,CAAC;QAEpC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,IAAI,QAAQ,IAAI,MAAM,CAAC;YAC/D,OAAO,IAAI,CAAC;QAEd,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC;YAAE,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5E,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,UAAU,EAAE,GAAG,CAAC,CAAC;QACzC,OAAO,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,CAAC;IACjC,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,SAAS,oBAAoB,CAC3B,CAAuC;IAEvC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC,CAAC;IACvC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC;QACjC,CAAC,CAAE,IAAgC;QACnC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.aot.generate-dom-factory\",\n \"title\": \"AOT DOM Factory Generator\",\n \"category\": \"compiler\",\n \"description\": \"Generates a DOM factory function from parsed template nodes, producing static HTML with binding placeholders.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n loopConflictMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport {\n createSerializeContext,\n serializeNode,\n type SerializeContext,\n} from './serializeNode';\nimport {\n generateBindings,\n serializeBindings,\n type BindingDescriptor,\n type IfDescriptor,\n type ForDescriptor,\n type SwitchDescriptor,\n type ProjectionDescriptor,\n} from './generateBindings';\nimport {\n collectIfChain,\n stripStructuralDirective,\n isDefaultCase,\n} from './structuralCodegen';\nimport { escapeJS } from './utils';\n\nexport interface AotCodegenResult {\n /** Complete JS code for the factory function + bindings const (includes sub-factory code) */\n code: string;\n /** The factory function name (e.g. \"__f_a7f3\") */\n factoryName: string;\n /** The bindings variable name (e.g. \"__b_a7f3\") */\n bindingsName: string;\n}\n\nexport interface AotCodegenOptions {\n templateComponents?: ReadonlySet<string>;\n wrappable?: boolean;\n anchorSlots?: ReadonlyMap<string, string>;\n sub?: boolean;\n}\n\n/**\n * Generate AOT code from a PithyNode tree.\n *\n * Produces:\n * 1. Sub-factory code for structural directives (@if branches, @for bodies, @switch cases)\n * 2. A bindings descriptor array (const __b_{hash} = [...])\n * 3. A DOM factory function (function __f_{hash}(__ctx) { ... })\n *\n * The factory creates DOM nodes via createElement/createTextNode,\n * sets static attributes, and calls __applyBindings with the\n * pre-extracted descriptors.\n *\n * Structural directives generate sub-factory functions (via recursive calls)\n * and comment placeholders in the parent factory. Sub-factory code is prepended\n * to the output so function references resolve correctly.\n *\n * **Phase 5 gap:** AOT factories do not set runtime-only DOM properties that\n * `pithyTreeToDom` assigns (`__pithyCtx`, `__pithyNode`, `__nodeId`,\n * `__slotName`, `__fallbackFactory`). Phase 5's `applyBindings()` will need\n * to set these on the factory-created DOM before wiring reactive effects.\n *\n * @param nodes - Parsed PithyNode tree (from parse5ToPithyTree)\n * @param hash - Unique identifier for this template (used in names)\n * @param scopeId - CSS scope ID (e.g. \"pithy-abc123\")\n *\n * @example\n * ```typescript\n * const result = generateDomFactory(pithyNodes, 'a7f3', 'pithy-abc');\n * // result.code contains the full factory + bindings code\n * // result.factoryName is \"__f_a7f3\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.generate-dom-factory\",\"name\":\"generateDomFactory\",\"stability\":\"experimental\",\"signature\":\"(nodes: PithyNode[], hash: string, scopeId?: string, options?: AotCodegenOptions) => AotCodegenResult\"} */\nexport function generateDomFactory(\n nodes: PithyNode[],\n hash: string,\n scopeId?: string,\n options: AotCodegenOptions = {}\n): AotCodegenResult {\n // Validate scopeId — it's interpolated into an attribute name (data-scope-{id}),\n // so it must contain only characters valid in HTML attribute names.\n if (scopeId && !/^[a-zA-Z0-9_-]+$/.test(scopeId)) {\n throw new Error(\n `AOT: invalid scopeId \"${scopeId}\" — must contain only alphanumeric, hyphen, or underscore characters.`\n );\n }\n\n // Sanitize hash to ensure valid JS identifiers (replace non-alphanumeric with _)\n const safeHash = hash.replace(/[^a-zA-Z0-9_$]/g, '_');\n const factoryName = `__f_${safeHash}`;\n const bindingsName = `__b_${safeHash}`;\n\n // Accumulate sub-factory code blocks (emitted before this factory)\n const subFactoryCodeBlocks: string[] = [];\n\n // Accumulate structural descriptors (merged with Phase 1 descriptors)\n const structuralDescriptors: BindingDescriptor[] = [];\n\n const childFactories = new Map<string, string>();\n const slotFactories = new Map<string, Record<string, string>>();\n const subOptions: AotCodegenOptions = {\n templateComponents: options.templateComponents,\n anchorSlots: options.anchorSlots,\n };\n\n // Generate DOM factory body\n const ctx = createSerializeContext(scopeId);\n\n // Process all nodes recursively, handling structural directives at every level\n const topLevelVarNames = processNodes(\n nodes,\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n subOptions,\n childFactories,\n slotFactories\n );\n\n // Generate Phase 1 binding descriptors (non-structural)\n const phase1Descriptors = generateBindings(\n nodes,\n childFactories,\n slotFactories\n );\n\n // Merge all descriptors: structural first, then Phase 1\n const allDescriptors = [...structuralDescriptors, ...phase1Descriptors];\n const bindingsCode = serializeBindings(allDescriptors);\n\n // Build factory function body\n const bodyLines: string[] = [];\n bodyLines.push(`const f=document.createDocumentFragment();`);\n\n // Add all serialized node creation code\n bodyLines.push(...ctx.lines);\n\n // Append top-level nodes to fragment\n if (topLevelVarNames.length === 1) {\n bodyLines.push(`f.appendChild(${topLevelVarNames[0]});`);\n } else if (topLevelVarNames.length > 1) {\n bodyLines.push(`f.append(${topLevelVarNames.join(',')});`);\n }\n\n const fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';\n const bindingsArg = allDescriptors.length > 0 ? bindingsName : '[]';\n const drainArg = options.sub ? ',false' : '';\n bodyLines.push(\n `return __applyBindings(${fragment},${bindingsArg},__ctx${drainArg});`\n );\n\n // Assemble final code: sub-factories first, then this factory\n const codeLines: string[] = [];\n\n // Sub-factory code blocks (from structural directives)\n for (const block of subFactoryCodeBlocks) {\n codeLines.push(block);\n }\n\n // Bindings constant (only if non-empty)\n if (allDescriptors.length > 0) {\n codeLines.push(`const ${bindingsName}=${bindingsCode};`);\n }\n\n // Factory function\n codeLines.push(\n `function ${factoryName}(__ctx${options.wrappable ? ',__wrap' : ''}){`\n );\n codeLines.push(...bodyLines);\n codeLines.push(`}`);\n\n return {\n code: codeLines.join('\\n'),\n factoryName,\n bindingsName,\n };\n}\n\n// ─── Internal: recursive tree processing with structural awareness ───────────\n\n/**\n * Process an array of sibling nodes, handling structural directives at every level.\n * Returns the varNames of the processed top-level nodes (for parent.append()).\n *\n * This function replaces the simple for-of loop over serializeNode calls.\n * It detects structural directives (which span siblings for @if chains)\n * and delegates to sub-factory generation, creating comment placeholders\n * in the current factory for the structural nodes.\n *\n * For non-structural elements, it serializes the element shell (no children)\n * via serializeNode, then recursively processes children here.\n */\nfunction processNodes(\n nodes: PithyNode[],\n ctx: SerializeContext,\n safeHash: string,\n scopeId: string | undefined,\n subFactoryCodeBlocks: string[],\n structuralDescriptors: BindingDescriptor[],\n options: AotCodegenOptions,\n childFactories: Map<string, string>,\n slotFactories: Map<string, Record<string, string>>\n): string[] {\n const varNames: string[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n\n // ─── @if/@else-if/@else chain ────────────────────────────────────\n if (node.type === 'element' && node.directives?.if !== undefined) {\n const chain = collectIfChain(nodes, i);\n const pid = node.nodeId ?? `_${i}`;\n i += chain.length - 1; // Skip consumed siblings\n\n // Generate sub-factory for each branch\n const branches: IfDescriptor['branches'] = [];\n for (let b = 0; b < chain.length; b++) {\n const branchNode = chain[b];\n const branchHash = `${safeHash}_if_${pid}_${b}`;\n const stripped = stripStructuralDirective(branchNode);\n if (branchNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: branchNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], branchHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const branch: IfDescriptor['branches'][0] = {\n factory: sub.factoryName,\n };\n if (branchNode.directives?.if !== undefined)\n branch.expr = branchNode.directives.if;\n else if (branchNode.directives?.elseIf !== undefined)\n branch.expr = branchNode.directives.elseIf;\n branches.push(branch);\n }\n\n // Emit comment placeholder\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('if:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n structuralDescriptors.push({ t: 'if', pid, branches });\n continue;\n }\n\n // ─── Orphaned @else-if, @else, @case, @default ────────────────────\n if (\n node.type === 'element' &&\n (node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined ||\n node.directives?.case !== undefined ||\n isDefaultCase(node))\n ) {\n if (\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n )\n console.warn(\n `[pithy:aot] ${node.directives.elseIf !== undefined ? '@else-if' : '@else'} has no @if directly before it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n else\n console.warn(\n `[pithy:aot] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n continue;\n }\n\n // ─── @for loop ───────────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.for) {\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n const pid = node.nodeId ?? `_${i}`;\n const forHash = `${safeHash}_for_${pid}`;\n const stripped = stripStructuralDirective(node);\n const sub = generateDomFactory([stripped], forHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('for:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n const forDir = node.directives.for;\n const desc: ForDescriptor = {\n t: 'for',\n pid,\n item: forDir.itemVar,\n expr: forDir.collectionExpr,\n factory: sub.factoryName,\n };\n if (forDir.indexVar) desc.index = forDir.indexVar;\n if (forDir.trackBy) desc.trackBy = forDir.trackBy;\n structuralDescriptors.push(desc);\n continue;\n }\n\n // ─── @switch block ───────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.switch !== undefined) {\n const pid = node.nodeId ?? `_${i}`;\n // Ensure the original node has nodeId so generateBindings can find it too\n if (!node.nodeId) node.nodeId = pid;\n\n // Serialize the switch container (without children, without @switch directive).\n // nodeId is guaranteed set above, so data-pid is always emitted.\n const switchShell: PithyNode = {\n ...node,\n children: [],\n directives: stripSwitchDirective(node.directives),\n };\n const shellResult = serializeNode(switchShell, ctx);\n if (shellResult) varNames.push(shellResult.varName);\n\n // Generate sub-factory for each @case/@default child\n const cases: SwitchDescriptor['cases'] = [];\n let dropped: string | undefined;\n for (let c = 0; c < (node.children ?? []).length; c++) {\n const caseNode = node.children![c];\n if (\n caseNode.type !== 'element' ||\n (caseNode.directives?.case === undefined && !isDefaultCase(caseNode))\n ) {\n for (const name of caseNode.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(caseNode.originalTagName ?? caseNode.tagName ?? '', name)}`\n );\n if (caseNode.type === 'element')\n dropped ??= `<${caseNode.originalTagName ?? caseNode.tagName}>`;\n else if (caseNode.type === 'slot') dropped ??= '<slot>';\n else if (caseNode.type === 'text' && caseNode.textContent?.trim())\n dropped ??= JSON.stringify(caseNode.textContent.trim());\n continue;\n }\n\n const caseHash = `${safeHash}_sw_${pid}_${c}`;\n const stripped = stripStructuralDirective(caseNode);\n if (caseNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: caseNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], caseHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const caseDesc: SwitchDescriptor['cases'][0] = {\n factory: sub.factoryName,\n };\n if (caseNode.directives?.case !== undefined)\n caseDesc.val = caseNode.directives.case;\n cases.push(caseDesc);\n }\n\n if (dropped)\n console.warn(\n `[pithy:aot] @switch renders only its @case/@default children; ${dropped} is dropped`\n );\n\n structuralDescriptors.push({\n t: 'switch',\n pid,\n expr: node.directives.switch,\n cases,\n });\n continue;\n }\n\n // ─── Text nodes ─────────────────────────────────────────────────\n if (node.type === 'text') {\n const result = serializeNode(node, ctx);\n if (result) varNames.push(result.varName);\n continue;\n }\n\n // ─── Slot nodes (content projection) ─────────────────────────────\n if (node.type === 'slot') {\n const slotName = node.slotName ?? '';\n const pid = node.nodeId ?? `_slot_${ctx.commentCount}`;\n\n // Emit comment anchor for the slot\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('slot:${escapeJS(slotName)}');`\n );\n varNames.push(commentVar);\n\n // Build projection descriptor\n const projDesc: ProjectionDescriptor = {\n t: 'proj',\n pid,\n name: slotName,\n };\n\n // Generate sub-factory for fallback content if present\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n const fbHash = `${safeHash}_slot_${pid}`;\n // Roots of the fallback factory, so bare text binds at its root.\n const roots = node.fallbackChildren.map(child =>\n child.parentId === node.nodeId\n ? { ...child, parentId: undefined }\n : child\n );\n const sub = generateDomFactory(roots, fbHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n projDesc.fallback = sub.factoryName;\n }\n\n structuralDescriptors.push(projDesc);\n continue;\n }\n\n // ─── Regular element (no structural directive on THIS node) ──────\n // Serialize element shell (without children) via serializeNode,\n // then process children recursively with structural awareness.\n if (node.type === 'element') {\n const shell: PithyNode = { ...node, children: [] };\n const result = serializeNode(shell, ctx);\n if (!result) continue;\n\n const tag = node.originalTagName ?? node.tagName ?? '';\n for (const name of componentChildDirectives(node))\n console.warn(\n `[pithy:aot] ${componentChildDirectiveMessage(tag, name)}`\n );\n if (\n node.isComponent &&\n node.nodeId &&\n node.children?.length &&\n options.templateComponents?.has(tag)\n ) {\n const { children, anchorSlots } = asTemplateRoots(\n node.children,\n node.nodeId,\n tag\n );\n const sub = generateDomFactory(\n children,\n `${safeHash}_tpl_${node.nodeId}`,\n scopeId,\n { ...options, wrappable: true, anchorSlots }\n );\n subFactoryCodeBlocks.push(sub.code);\n childFactories.set(node.nodeId, sub.factoryName);\n varNames.push(result.varName);\n continue;\n }\n\n // Each slot mount renders and binds its content afresh, as dev does.\n if (node.isComponent && node.nodeId && node.children?.length) {\n const slots: Record<string, string> = Object.create(null);\n let n = 0;\n for (const [name, group] of groupSlots(\n node.children,\n node.nodeId,\n tag\n )) {\n const sub = generateDomFactory(\n group,\n `${safeHash}_cs_${node.nodeId}_${n++}`,\n scopeId,\n { ...options, sub: true }\n );\n subFactoryCodeBlocks.push(sub.code);\n slots[name] = sub.factoryName;\n }\n slotFactories.set(node.nodeId, slots);\n varNames.push(result.varName);\n continue;\n }\n\n // Recursively process children (handles nested structural directives)\n const childVarNames = processNodes(\n node.children ?? [],\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n options,\n childFactories,\n slotFactories\n );\n\n // Append children to this element\n if (childVarNames.length === 1) {\n ctx.lines.push(`${result.varName}.appendChild(${childVarNames[0]});`);\n } else if (childVarNames.length > 1) {\n ctx.lines.push(`${result.varName}.append(${childVarNames.join(',')});`);\n }\n\n varNames.push(result.varName);\n continue;\n }\n }\n\n return varNames;\n}\n\nfunction markAnchorSlot(\n ctx: SerializeContext,\n commentVar: string,\n slot: string | undefined\n): void {\n if (slot === undefined) return;\n ctx.lines.push(`${commentVar}.__pithyAnchorSlot='${escapeJS(slot)}';`);\n}\n\nconst BLANK = /^[ \\t\\n\\f\\r]*$/;\n\nfunction warnMixedChainSlots(\n nodes: PithyNode[],\n ownerTag: string,\n outcome: string\n): void {\n let chainSlot: string | undefined;\n let inChain = false;\n let chainWarned = false;\n for (const { directives: d } of nodes) {\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n if (d?.if !== undefined) {\n inChain = true;\n chainSlot = d.slot;\n chainWarned = false;\n } else if (!isBranch) {\n inChain = false;\n }\n if (isBranch && inChain && d.slot !== chainSlot && !chainWarned) {\n chainWarned = true;\n console.warn(\n `[pithy:aot] <${ownerTag}>: the branches of an @if chain carry different slots ` +\n `(${chainSlot ?? 'none'} and ${d.slot ?? 'none'}). ${outcome}`\n );\n }\n if (d?.else !== undefined) inChain = false;\n }\n}\n\n/** Groups a component's children by slot name, as `collectSlotMap` does. */\nfunction groupSlots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): Map<string, PithyNode[]> {\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'Each slot keeps only the branches that name it; a branch cut off from its @if is dropped.'\n );\n const groups = new Map<string, PithyNode[]>();\n for (const child of nodes) {\n const name = child.directives?.slot || '';\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const group = groups.get(name);\n if (group) group.push(root);\n else groups.set(name, [root]);\n }\n const blank = (n: PithyNode) =>\n n.type === 'text' && BLANK.test(n.textContent ?? '');\n const main = groups.get('');\n if (main) {\n let start = 0;\n let end = main.length;\n while (start < end && blank(main[start])) start++;\n while (end > start && blank(main[end - 1])) end--;\n if (start < end) groups.set('', main.slice(start, end));\n else groups.delete('');\n }\n return groups;\n}\n\nfunction asTemplateRoots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): { children: PithyNode[]; anchorSlots: Map<string, string> } {\n const anchorSlots = new Map<string, string>();\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'The whole chain is placed by its first branch.'\n );\n\n const children = nodes.map(child => {\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const d = root.directives;\n const isHead = d?.if !== undefined;\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n const isLoop = d?.for !== undefined;\n\n if (!d || d.slot === undefined || !(isHead || isBranch || isLoop))\n return root;\n\n if (root.nodeId && (isHead || isLoop)) anchorSlots.set(root.nodeId, d.slot);\n const { slot: _slot, ...directives } = d;\n return { ...root, directives };\n });\n\n return { children, anchorSlots };\n}\n\n/**\n * Remove the `switch` field from a ParsedDirectives object.\n * Used to serialize the switch container element without the @switch directive\n * (since the directive is captured in the SwitchDescriptor instead).\n */\nfunction stripSwitchDirective(\n d: NonNullable<PithyNode['directives']>\n): PithyNode['directives'] {\n const { switch: _switch, ...rest } = d;\n return Object.keys(rest).length > 0\n ? (rest as PithyNode['directives'])\n : undefined;\n}\n"]}
1
+ {"version":3,"file":"generateDomFactory.js","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAm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EAAE,UAAU,EAAE,CAAC;IACjC,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,SAAS,oBAAoB,CAC3B,CAAuC;IAEvC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC,CAAC;IACvC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC;QACjC,CAAC,CAAE,IAAgC;QACnC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.aot.generate-dom-factory\",\n \"title\": \"AOT DOM Factory Generator\",\n \"category\": \"compiler\",\n \"description\": \"Generates a DOM factory function from parsed template nodes, producing static HTML with binding placeholders.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n loopConflictMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport {\n createSerializeContext,\n serializeNode,\n appendChildren,\n enterTemplate,\n type SerializeContext,\n} from './serializeNode';\nimport {\n generateBindings,\n serializeBindings,\n type BindingDescriptor,\n type IfDescriptor,\n type ForDescriptor,\n type SwitchDescriptor,\n type ProjectionDescriptor,\n} from './generateBindings';\nimport {\n collectIfChain,\n stripStructuralDirective,\n isDefaultCase,\n} from './structuralCodegen';\nimport { escapeJS } from './utils';\n\nexport interface AotCodegenResult {\n /** Complete JS code for the factory function + bindings const (includes sub-factory code) */\n code: string;\n /** The factory function name (e.g. \"__f_a7f3\") */\n factoryName: string;\n /** The bindings variable name (e.g. \"__b_a7f3\") */\n bindingsName: string;\n}\n\nexport interface AotCodegenOptions {\n templateComponents?: ReadonlySet<string>;\n wrappable?: boolean;\n anchorSlots?: ReadonlyMap<string, string>;\n sub?: boolean;\n}\n\n/**\n * Generate AOT code from a PithyNode tree.\n *\n * Produces:\n * 1. Sub-factory code for structural directives (@if branches, @for bodies, @switch cases)\n * 2. A bindings descriptor array (const __b_{hash} = [...])\n * 3. A DOM factory function (function __f_{hash}(__ctx) { ... })\n *\n * The factory creates DOM nodes via createElement/createTextNode,\n * sets static attributes, and calls __applyBindings with the\n * pre-extracted descriptors.\n *\n * Structural directives generate sub-factory functions (via recursive calls)\n * and comment placeholders in the parent factory. Sub-factory code is prepended\n * to the output so function references resolve correctly.\n *\n * **Phase 5 gap:** AOT factories do not set runtime-only DOM properties that\n * `pithyTreeToDom` assigns (`__pithyCtx`, `__pithyNode`, `__nodeId`,\n * `__slotName`, `__fallbackFactory`). Phase 5's `applyBindings()` will need\n * to set these on the factory-created DOM before wiring reactive effects.\n *\n * @param nodes - Parsed PithyNode tree (from parse5ToPithyTree)\n * @param hash - Unique identifier for this template (used in names)\n * @param scopeId - CSS scope ID (e.g. \"pithy-abc123\")\n *\n * @example\n * ```typescript\n * const result = generateDomFactory(pithyNodes, 'a7f3', 'pithy-abc');\n * // result.code contains the full factory + bindings code\n * // result.factoryName is \"__f_a7f3\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.generate-dom-factory\",\"name\":\"generateDomFactory\",\"stability\":\"experimental\",\"signature\":\"(nodes: PithyNode[], hash: string, scopeId?: string, options?: AotCodegenOptions) => AotCodegenResult\"} */\nexport function generateDomFactory(\n nodes: PithyNode[],\n hash: string,\n scopeId?: string,\n options: AotCodegenOptions = {}\n): AotCodegenResult {\n // Validate scopeId — it's interpolated into an attribute name (data-scope-{id}),\n // so it must contain only characters valid in HTML attribute names.\n if (scopeId && !/^[a-zA-Z0-9_-]+$/.test(scopeId)) {\n throw new Error(\n `AOT: invalid scopeId \"${scopeId}\" — must contain only alphanumeric, hyphen, or underscore characters.`\n );\n }\n\n // Sanitize hash to ensure valid JS identifiers (replace non-alphanumeric with _)\n const safeHash = hash.replace(/[^a-zA-Z0-9_$]/g, '_');\n const factoryName = `__f_${safeHash}`;\n const bindingsName = `__b_${safeHash}`;\n\n // Accumulate sub-factory code blocks (emitted before this factory)\n const subFactoryCodeBlocks: string[] = [];\n\n // Accumulate structural descriptors (merged with Phase 1 descriptors)\n const structuralDescriptors: BindingDescriptor[] = [];\n\n const childFactories = new Map<string, string>();\n const slotFactories = new Map<string, Record<string, string>>();\n const subOptions: AotCodegenOptions = {\n templateComponents: options.templateComponents,\n anchorSlots: options.anchorSlots,\n };\n\n // Generate DOM factory body\n const ctx = createSerializeContext(scopeId);\n\n // Process all nodes recursively, handling structural directives at every level\n const topLevelVarNames = processNodes(\n nodes,\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n subOptions,\n childFactories,\n slotFactories\n );\n\n // Generate Phase 1 binding descriptors (non-structural)\n const phase1Descriptors = generateBindings(\n nodes,\n childFactories,\n slotFactories\n );\n\n // Merge all descriptors: structural first, then Phase 1\n const allDescriptors = [...structuralDescriptors, ...phase1Descriptors];\n const bindingsCode = serializeBindings(allDescriptors);\n\n // Build factory function body\n const bodyLines: string[] = [];\n bodyLines.push(`const f=document.createDocumentFragment();`);\n\n // Add all serialized node creation code\n bodyLines.push(...ctx.lines);\n\n // Append top-level nodes to fragment\n if (topLevelVarNames.length === 1) {\n bodyLines.push(`f.appendChild(${topLevelVarNames[0]});`);\n } else if (topLevelVarNames.length > 1) {\n bodyLines.push(`f.append(${topLevelVarNames.join(',')});`);\n }\n\n const fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';\n const bindingsArg = allDescriptors.length > 0 ? bindingsName : '[]';\n const drainArg = options.sub ? ',false' : '';\n bodyLines.push(\n `return __applyBindings(${fragment},${bindingsArg},__ctx${drainArg});`\n );\n\n // Assemble final code: sub-factories first, then this factory\n const codeLines: string[] = [];\n\n // Sub-factory code blocks (from structural directives)\n for (const block of subFactoryCodeBlocks) {\n codeLines.push(block);\n }\n\n // Bindings constant (only if non-empty)\n if (allDescriptors.length > 0) {\n codeLines.push(`const ${bindingsName}=${bindingsCode};`);\n }\n\n // Factory function\n codeLines.push(\n `function ${factoryName}(__ctx${options.wrappable ? ',__wrap' : ''}){`\n );\n codeLines.push(...bodyLines);\n codeLines.push(`}`);\n\n return {\n code: codeLines.join('\\n'),\n factoryName,\n bindingsName,\n };\n}\n\n// ─── Internal: recursive tree processing with structural awareness ───────────\n\n/**\n * Process an array of sibling nodes, handling structural directives at every level.\n * Returns the varNames of the processed top-level nodes (for parent.append()).\n *\n * This function replaces the simple for-of loop over serializeNode calls.\n * It detects structural directives (which span siblings for @if chains)\n * and delegates to sub-factory generation, creating comment placeholders\n * in the current factory for the structural nodes.\n *\n * For non-structural elements, it serializes the element shell (no children)\n * via serializeNode, then recursively processes children here.\n */\nfunction processNodes(\n nodes: PithyNode[],\n ctx: SerializeContext,\n safeHash: string,\n scopeId: string | undefined,\n subFactoryCodeBlocks: string[],\n structuralDescriptors: BindingDescriptor[],\n options: AotCodegenOptions,\n childFactories: Map<string, string>,\n slotFactories: Map<string, Record<string, string>>\n): string[] {\n const varNames: string[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n\n // ─── @if/@else-if/@else chain ────────────────────────────────────\n if (node.type === 'element' && node.directives?.if !== undefined) {\n const chain = collectIfChain(nodes, i);\n const pid = node.nodeId ?? `_${i}`;\n i += chain.length - 1; // Skip consumed siblings\n\n // Generate sub-factory for each branch\n const branches: IfDescriptor['branches'] = [];\n for (let b = 0; b < chain.length; b++) {\n const branchNode = chain[b];\n const branchHash = `${safeHash}_if_${pid}_${b}`;\n const stripped = stripStructuralDirective(branchNode);\n if (branchNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: branchNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], branchHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const branch: IfDescriptor['branches'][0] = {\n factory: sub.factoryName,\n };\n if (branchNode.directives?.if !== undefined)\n branch.expr = branchNode.directives.if;\n else if (branchNode.directives?.elseIf !== undefined)\n branch.expr = branchNode.directives.elseIf;\n branches.push(branch);\n }\n\n // Emit comment placeholder\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('if:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n structuralDescriptors.push({ t: 'if', pid, branches });\n continue;\n }\n\n // ─── Orphaned @else-if, @else, @case, @default ────────────────────\n if (\n node.type === 'element' &&\n (node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined ||\n node.directives?.case !== undefined ||\n isDefaultCase(node))\n ) {\n if (\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n )\n console.warn(\n `[pithy:aot] ${node.directives.elseIf !== undefined ? '@else-if' : '@else'} has no @if directly before it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n else\n console.warn(\n `[pithy:aot] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n continue;\n }\n\n // ─── @for loop ───────────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.for) {\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n const pid = node.nodeId ?? `_${i}`;\n const forHash = `${safeHash}_for_${pid}`;\n const stripped = stripStructuralDirective(node);\n const sub = generateDomFactory([stripped], forHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('for:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n const forDir = node.directives.for;\n const desc: ForDescriptor = {\n t: 'for',\n pid,\n item: forDir.itemVar,\n expr: forDir.collectionExpr,\n factory: sub.factoryName,\n };\n if (forDir.indexVar) desc.index = forDir.indexVar;\n if (forDir.trackBy) desc.trackBy = forDir.trackBy;\n structuralDescriptors.push(desc);\n continue;\n }\n\n // ─── @switch block ───────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.switch !== undefined) {\n const pid = node.nodeId ?? `_${i}`;\n // Ensure the original node has nodeId so generateBindings can find it too\n if (!node.nodeId) node.nodeId = pid;\n\n // Serialize the switch container (without children, without @switch directive).\n // nodeId is guaranteed set above, so data-pid is always emitted.\n const switchShell: PithyNode = {\n ...node,\n children: [],\n directives: stripSwitchDirective(node.directives),\n };\n const shellResult = serializeNode(switchShell, ctx);\n if (shellResult) varNames.push(shellResult.varName);\n\n // Generate sub-factory for each @case/@default child\n const cases: SwitchDescriptor['cases'] = [];\n let dropped: string | undefined;\n for (let c = 0; c < (node.children ?? []).length; c++) {\n const caseNode = node.children![c];\n if (\n caseNode.type !== 'element' ||\n (caseNode.directives?.case === undefined && !isDefaultCase(caseNode))\n ) {\n for (const name of caseNode.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(caseNode.originalTagName ?? caseNode.tagName ?? '', name)}`\n );\n if (caseNode.type === 'element')\n dropped ??= `<${caseNode.originalTagName ?? caseNode.tagName}>`;\n else if (caseNode.type === 'slot') dropped ??= '<slot>';\n else if (caseNode.type === 'text' && caseNode.textContent?.trim())\n dropped ??= JSON.stringify(caseNode.textContent.trim());\n continue;\n }\n\n const caseHash = `${safeHash}_sw_${pid}_${c}`;\n const stripped = stripStructuralDirective(caseNode);\n if (caseNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: caseNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], caseHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const caseDesc: SwitchDescriptor['cases'][0] = {\n factory: sub.factoryName,\n };\n if (caseNode.directives?.case !== undefined)\n caseDesc.val = caseNode.directives.case;\n cases.push(caseDesc);\n }\n\n if (dropped)\n console.warn(\n `[pithy:aot] @switch renders only its @case/@default children; ${dropped} is dropped`\n );\n\n structuralDescriptors.push({\n t: 'switch',\n pid,\n expr: node.directives.switch,\n cases,\n });\n continue;\n }\n\n // ─── Text nodes ─────────────────────────────────────────────────\n if (node.type === 'text') {\n const result = serializeNode(node, ctx);\n if (result) varNames.push(result.varName);\n continue;\n }\n\n // ─── Slot nodes (content projection) ─────────────────────────────\n if (node.type === 'slot') {\n const slotName = node.slotName ?? '';\n const pid = node.nodeId ?? `_slot_${ctx.commentCount}`;\n\n // Emit comment anchor for the slot\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('slot:${escapeJS(slotName)}');`\n );\n varNames.push(commentVar);\n\n // Build projection descriptor\n const projDesc: ProjectionDescriptor = {\n t: 'proj',\n pid,\n name: slotName,\n };\n\n // Generate sub-factory for fallback content if present\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n const fbHash = `${safeHash}_slot_${pid}`;\n // Roots of the fallback factory, so bare text binds at its root.\n const roots = node.fallbackChildren.map(child =>\n child.parentId === node.nodeId\n ? { ...child, parentId: undefined }\n : child\n );\n const sub = generateDomFactory(roots, fbHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n projDesc.fallback = sub.factoryName;\n }\n\n structuralDescriptors.push(projDesc);\n continue;\n }\n\n // ─── Regular element (no structural directive on THIS node) ──────\n // Serialize element shell (without children) via serializeNode,\n // then process children recursively with structural awareness.\n if (node.type === 'element') {\n const shell: PithyNode = { ...node, children: [] };\n const result = serializeNode(shell, ctx);\n if (!result) continue;\n\n const tag = node.originalTagName ?? node.tagName ?? '';\n for (const name of componentChildDirectives(node))\n console.warn(\n `[pithy:aot] ${componentChildDirectiveMessage(tag, name)}`\n );\n if (\n node.isComponent &&\n node.nodeId &&\n node.children?.length &&\n options.templateComponents?.has(tag)\n ) {\n const { children, anchorSlots } = asTemplateRoots(\n node.children,\n node.nodeId,\n tag\n );\n const sub = generateDomFactory(\n children,\n `${safeHash}_tpl_${node.nodeId}`,\n scopeId,\n { ...options, wrappable: true, anchorSlots }\n );\n subFactoryCodeBlocks.push(sub.code);\n childFactories.set(node.nodeId, sub.factoryName);\n varNames.push(result.varName);\n continue;\n }\n\n // Each slot mount renders and binds its content afresh, as dev does.\n if (node.isComponent && node.nodeId && node.children?.length) {\n const slots: Record<string, string> = Object.create(null);\n let n = 0;\n for (const [name, group] of groupSlots(\n node.children,\n node.nodeId,\n tag\n )) {\n const sub = generateDomFactory(\n group,\n `${safeHash}_cs_${node.nodeId}_${n++}`,\n scopeId,\n { ...options, sub: true }\n );\n subFactoryCodeBlocks.push(sub.code);\n slots[name] = sub.factoryName;\n }\n slotFactories.set(node.nodeId, slots);\n varNames.push(result.varName);\n continue;\n }\n\n // Recursively process children (handles nested structural directives)\n const leave = enterTemplate(node, result.varName, ctx);\n const childVarNames = processNodes(\n node.children ?? [],\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n options,\n childFactories,\n slotFactories\n );\n\n leave();\n appendChildren(node, result.varName, childVarNames, ctx);\n\n varNames.push(result.varName);\n continue;\n }\n }\n\n return varNames;\n}\n\nfunction markAnchorSlot(\n ctx: SerializeContext,\n commentVar: string,\n slot: string | undefined\n): void {\n if (slot === undefined) return;\n ctx.lines.push(`${commentVar}.__pithyAnchorSlot='${escapeJS(slot)}';`);\n}\n\nconst BLANK = /^[ \\t\\n\\f\\r]*$/;\n\nfunction warnMixedChainSlots(\n nodes: PithyNode[],\n ownerTag: string,\n outcome: string\n): void {\n let chainSlot: string | undefined;\n let inChain = false;\n let chainWarned = false;\n for (const { directives: d } of nodes) {\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n if (d?.if !== undefined) {\n inChain = true;\n chainSlot = d.slot;\n chainWarned = false;\n } else if (!isBranch) {\n inChain = false;\n }\n if (isBranch && inChain && d.slot !== chainSlot && !chainWarned) {\n chainWarned = true;\n console.warn(\n `[pithy:aot] <${ownerTag}>: the branches of an @if chain carry different slots ` +\n `(${chainSlot ?? 'none'} and ${d.slot ?? 'none'}). ${outcome}`\n );\n }\n if (d?.else !== undefined) inChain = false;\n }\n}\n\n/** Groups a component's children by slot name, as `collectSlotMap` does. */\nfunction groupSlots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): Map<string, PithyNode[]> {\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'Each slot keeps only the branches that name it; a branch cut off from its @if is dropped.'\n );\n const groups = new Map<string, PithyNode[]>();\n for (const child of nodes) {\n const name = child.directives?.slot || '';\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const group = groups.get(name);\n if (group) group.push(root);\n else groups.set(name, [root]);\n }\n const blank = (n: PithyNode) =>\n n.type === 'text' && BLANK.test(n.textContent ?? '');\n const main = groups.get('');\n if (main) {\n let start = 0;\n let end = main.length;\n while (start < end && blank(main[start])) start++;\n while (end > start && blank(main[end - 1])) end--;\n if (start < end) groups.set('', main.slice(start, end));\n else groups.delete('');\n }\n return groups;\n}\n\nfunction asTemplateRoots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): { children: PithyNode[]; anchorSlots: Map<string, string> } {\n const anchorSlots = new Map<string, string>();\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'The whole chain is placed by its first branch.'\n );\n\n const children = nodes.map(child => {\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const d = root.directives;\n const isHead = d?.if !== undefined;\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n const isLoop = d?.for !== undefined;\n\n if (!d || d.slot === undefined || !(isHead || isBranch || isLoop))\n return root;\n\n if (root.nodeId && (isHead || isLoop)) anchorSlots.set(root.nodeId, d.slot);\n const { slot: _slot, ...directives } = d;\n return { ...root, directives };\n });\n\n return { children, anchorSlots };\n}\n\n/**\n * Remove the `switch` field from a ParsedDirectives object.\n * Used to serialize the switch container element without the @switch directive\n * (since the directive is captured in the SwitchDescriptor instead).\n */\nfunction stripSwitchDirective(\n d: NonNullable<PithyNode['directives']>\n): PithyNode['directives'] {\n const { switch: _switch, ...rest } = d;\n return Object.keys(rest).length > 0\n ? (rest as PithyNode['directives'])\n : undefined;\n}\n"]}
@@ -24,6 +24,8 @@ export interface SerializeContext {
24
24
  commentCount: number;
25
25
  /** Scope ID for data-scope-{id} attributes (e.g. "pithy-abc123") */
26
26
  scopeId?: string;
27
+ /** The expression new nodes are created from; a `<template>`'s descendants use its inert owner document. */
28
+ doc?: string;
27
29
  /** Accumulated lines of JS code */
28
30
  lines: string[];
29
31
  }
@@ -71,4 +73,8 @@ export declare function createSerializeContext(scopeId?: string): SerializeConte
71
73
  */
72
74
  /** @codexApi {"parent":"pithy.aot.serialize-node","name":"serializeNode","stability":"experimental","signature":"(node: PithyNode, ctx: SerializeContext) => SerializedNode | null"} */
73
75
  export declare function serializeNode(node: PithyNode, ctx: SerializeContext): SerializedNode | null;
76
+ /** @codexApi {"parent":"pithy.aot.serialize-node","name":"enterTemplate","stability":"internal","signature":"(node: PithyNode, varName: string, ctx: SerializeContext) => () => void"} */
77
+ export declare function enterTemplate(node: PithyNode, varName: string, ctx: SerializeContext): () => void;
78
+ /** @codexApi {"parent":"pithy.aot.serialize-node","name":"appendChildren","stability":"internal","signature":"(node: PithyNode, varName: string, childVarNames: string[], ctx: SerializeContext) => void"} */
79
+ export declare function appendChildren(node: PithyNode, varName: string, childVarNames: string[], ctx: SerializeContext): void;
74
80
  //# sourceMappingURL=serializeNode.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serializeNode.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/serializeNode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EAIL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAG3B,wEAAwE;AACxE,MAAM,WAAW,gBAAgB;IAC/B,gDAAgD;IAChD,YAAY,EAAE,MAAM,CAAC;IACrB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,gDAAgD;IAChD,YAAY,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mCAAmC;IACnC,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,2CAA2C;AAC3C,MAAM,WAAW,cAAc;IAC7B,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,sKAAsK;AACtK,wBAAgB,sBAAsB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAQzE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wLAAwL;AACxL,wBAAgB,aAAa,CAC3B,IAAI,EAAE,SAAS,EACf,GAAG,EAAE,gBAAgB,GACpB,cAAc,GAAG,IAAI,CAWvB"}
1
+ {"version":3,"file":"serializeNode.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/serializeNode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EAKL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAG3B,wEAAwE;AACxE,MAAM,WAAW,gBAAgB;IAC/B,gDAAgD;IAChD,YAAY,EAAE,MAAM,CAAC;IACrB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,gDAAgD;IAChD,YAAY,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4GAA4G;IAC5G,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,mCAAmC;IACnC,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,2CAA2C;AAC3C,MAAM,WAAW,cAAc;IAC7B,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,sKAAsK;AACtK,wBAAgB,sBAAsB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAQzE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wLAAwL;AACxL,wBAAgB,aAAa,CAC3B,IAAI,EAAE,SAAS,EACf,GAAG,EAAE,gBAAgB,GACpB,cAAc,GAAG,IAAI,CAWvB;AA6JD,0LAA0L;AAC1L,wBAAgB,aAAa,CAC3B,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,gBAAgB,GACpB,MAAM,IAAI,CAQZ;AAED,8MAA8M;AAC9M,wBAAgB,cAAc,CAC5B,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,EAAE,EACvB,GAAG,EAAE,gBAAgB,GACpB,IAAI,CAON"}
@@ -13,7 +13,7 @@
13
13
  }
14
14
  }
15
15
  */
16
- import { SVG_TAGS, SVG_NS, forEachDomDirectiveAttr, } from '@pithyjs/compiler';
16
+ import { elementTagName, isSvgNode, SVG_NS, forEachDomDirectiveAttr, } from '@pithyjs/compiler';
17
17
  import { escapeJS } from './utils.js';
18
18
  /**
19
19
  * Create a fresh serialize context for a single factory generation pass.
@@ -72,21 +72,20 @@ export function serializeNode(node, ctx) {
72
72
  function serializeTextNode(node, ctx) {
73
73
  const varName = `t${ctx.textCount++}`;
74
74
  const content = node.textContent ?? '';
75
- ctx.lines.push(`const ${varName}=document.createTextNode('${escapeJS(content)}');`);
75
+ ctx.lines.push(`const ${varName}=${ctx.doc ?? 'document'}.createTextNode('${escapeJS(content)}');`);
76
76
  return { varName, childVarNames: [] };
77
77
  }
78
78
  function serializeElementNode(node, ctx) {
79
79
  // Guard: structural directives are not supported in Phase 1
80
80
  assertNoStructuralDirectives(node);
81
81
  const varName = `e${ctx.elementCount++}`;
82
- const tag = node.originalTagName ?? node.tagName ?? 'div';
83
- const tagLower = tag.toLowerCase();
84
- // Create element (SVG vs HTML namespace)
85
- if (SVG_TAGS.has(tagLower)) {
86
- ctx.lines.push(`const ${varName}=document.createElementNS('${SVG_NS}','${escapeJS(tag)}');`);
82
+ const tag = elementTagName(node);
83
+ const doc = ctx.doc ?? 'document';
84
+ if (isSvgNode(node)) {
85
+ ctx.lines.push(`const ${varName}=${doc}.createElementNS('${SVG_NS}','${escapeJS(tag)}');`);
87
86
  }
88
87
  else {
89
- ctx.lines.push(`const ${varName}=document.createElement('${escapeJS(tag)}');`);
88
+ ctx.lines.push(`const ${varName}=${doc}.createElement('${escapeJS(tag)}');`);
90
89
  }
91
90
  // Set static attributes (skip directive attrs, data-pid, and slot which are set separately)
92
91
  for (const [name, value] of Object.entries(node.attrs ?? {})) {
@@ -131,19 +130,15 @@ function serializeElementNode(node, ctx) {
131
130
  }
132
131
  // Recursively serialize children
133
132
  const childVarNames = [];
133
+ const leave = enterTemplate(node, varName, ctx);
134
134
  for (const child of node.children ?? []) {
135
135
  const childResult = serializeNode(child, ctx);
136
136
  if (childResult) {
137
137
  childVarNames.push(childResult.varName);
138
138
  }
139
139
  }
140
- // Append children to this element
141
- if (childVarNames.length === 1) {
142
- ctx.lines.push(`${varName}.appendChild(${childVarNames[0]});`);
143
- }
144
- else if (childVarNames.length > 1) {
145
- ctx.lines.push(`${varName}.append(${childVarNames.join(',')});`);
146
- }
140
+ leave();
141
+ appendChildren(node, varName, childVarNames, ctx);
147
142
  return { varName, childVarNames };
148
143
  }
149
144
  /**
@@ -176,4 +171,26 @@ function assertNoStructuralDirectives(node) {
176
171
  // Note: @default is stored in node.attrs['@default'], not in ParsedDirectives,
177
172
  // so it cannot be caught here. It is handled by processNodes via isDefaultCase().
178
173
  }
174
+ const isHtmlTemplate = (node) => node.tagName === 'template' && !isSvgNode(node);
175
+ /** @codexApi {"parent":"pithy.aot.serialize-node","name":"enterTemplate","stability":"internal","signature":"(node: PithyNode, varName: string, ctx: SerializeContext) => () => void"} */
176
+ export function enterTemplate(node, varName, ctx) {
177
+ if (!isHtmlTemplate(node) || !node.children?.length)
178
+ return () => { };
179
+ const outer = ctx.doc;
180
+ ctx.doc = `${varName}d`;
181
+ ctx.lines.push(`const ${ctx.doc}=${varName}.content.ownerDocument;`);
182
+ return () => {
183
+ ctx.doc = outer;
184
+ };
185
+ }
186
+ /** @codexApi {"parent":"pithy.aot.serialize-node","name":"appendChildren","stability":"internal","signature":"(node: PithyNode, varName: string, childVarNames: string[], ctx: SerializeContext) => void"} */
187
+ export function appendChildren(node, varName, childVarNames, ctx) {
188
+ const parent = isHtmlTemplate(node) ? `${varName}.content` : varName;
189
+ if (childVarNames.length === 1) {
190
+ ctx.lines.push(`${parent}.appendChild(${childVarNames[0]});`);
191
+ }
192
+ else if (childVarNames.length > 1) {
193
+ ctx.lines.push(`${parent}.append(${childVarNames.join(',')});`);
194
+ }
195
+ }
179
196
  //# sourceMappingURL=serializeNode.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serializeNode.js","sourceRoot":"","sources":["../../src/aotCodegen/serializeNode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,QAAQ,EACR,MAAM,EACN,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAwBnC;;;;;;;;;;;;;;;;GAgBG;AACH,sKAAsK;AACtK,MAAM,UAAU,sBAAsB,CAAC,OAAgB;IACrD,OAAO;QACL,YAAY,EAAE,CAAC;QACf,SAAS,EAAE,CAAC;QACZ,YAAY,EAAE,CAAC;QACf,OAAO;QACP,KAAK,EAAE,EAAE;KACV,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wLAAwL;AACxL,MAAM,UAAU,aAAa,CAC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iler\",\n \"description\": \"Serializes parsed template nodes into static HTML strings with marker comments for dynamic binding points.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n SVG_TAGS,\n SVG_NS,\n forEachDomDirectiveAttr,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { escapeJS } from './utils';\n\n/** Tracks variable counters during a single factory generation pass. */\nexport interface SerializeContext {\n /** Next element variable index (e0, e1, ...) */\n elementCount: number;\n /** Next text node variable index (t0, t1, ...) */\n textCount: number;\n /** Next comment variable index (c0, c1, ...) */\n commentCount: number;\n /** Scope ID for data-scope-{id} attributes (e.g. \"pithy-abc123\") */\n scopeId?: string;\n /** Accumulated lines of JS code */\n lines: string[];\n}\n\n/** Result of serializing a single node. */\nexport interface SerializedNode {\n /** Variable name assigned to this DOM node (e.g. \"e0\", \"t3\") */\n varName: string;\n /** Variable names of direct children (for parent.append(...children)) */\n childVarNames: string[];\n}\n\n/**\n * Create a fresh serialize context for a single factory generation pass.\n *\n * The context accumulates JS code lines and tracks variable counters\n * across recursive `serializeNode` calls. Each factory should use\n * its own context.\n *\n * @param scopeId - Optional CSS scope ID (e.g. \"pithy-abc123\").\n * When provided, every element gets a `data-scope-{scopeId}` attribute.\n *\n * @example\n * ```typescript\n * const ctx = createSerializeContext('pithy-abc123');\n * serializeNode(rootNode, ctx);\n * console.log(ctx.lines); // [\"const e0=document.createElement('div');\", ...]\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"createSerializeContext\",\"stability\":\"experimental\",\"signature\":\"(scopeId?: string) => SerializeContext\"} */\nexport function createSerializeContext(scopeId?: string): SerializeContext {\n return {\n elementCount: 0,\n textCount: 0,\n commentCount: 0,\n scopeId,\n lines: [],\n };\n}\n\n/**\n * Serialize a single PithyNode into JS code that creates the corresponding\n * DOM node. Appends code lines to `ctx.lines` and returns the variable name.\n *\n * Phase 1 scope: elements, text nodes.\n * Skips directive attributes (@, []) — those become binding descriptors.\n * Throws on structural directives (@for, @if, @switch) — those are Phase 2.\n *\n * @example\n * ```typescript\n * const ctx = createSerializeContext('pithy-abc123');\n * const result = serializeNode(node, ctx);\n * // ctx.lines now contains JS code lines\n * // result.varName is e.g. \"e0\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"serializeNode\",\"stability\":\"experimental\",\"signature\":\"(node: PithyNode, ctx: SerializeContext) => SerializedNode | null\"} */\nexport function serializeNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode | null {\n if (node.type === 'text') {\n return serializeTextNode(node, ctx);\n }\n\n if (node.type === 'element') {\n return serializeElementNode(node, ctx);\n }\n\n // Slot nodes are handled by processNodes in generateDomFactory.ts — they should not reach here.\n return null;\n}\n\nfunction serializeTextNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode {\n const varName = `t${ctx.textCount++}`;\n const content = node.textContent ?? '';\n ctx.lines.push(\n `const ${varName}=document.createTextNode('${escapeJS(content)}');`\n );\n return { varName, childVarNames: [] };\n}\n\nfunction serializeElementNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode {\n // Guard: structural directives are not supported in Phase 1\n assertNoStructuralDirectives(node);\n\n const varName = `e${ctx.elementCount++}`;\n const tag = node.originalTagName ?? node.tagName ?? 'div';\n const tagLower = tag.toLowerCase();\n\n // Create element (SVG vs HTML namespace)\n if (SVG_TAGS.has(tagLower)) {\n ctx.lines.push(\n `const ${varName}=document.createElementNS('${SVG_NS}','${escapeJS(tag)}');`\n );\n } else {\n ctx.lines.push(\n `const ${varName}=document.createElement('${escapeJS(tag)}');`\n );\n }\n\n // Set static attributes (skip directive attrs, data-pid, and slot which are set separately)\n for (const [name, value] of Object.entries(node.attrs ?? {})) {\n if (\n name.startsWith('@') ||\n name.startsWith('[') ||\n name === 'data-pid' ||\n name === 'slot'\n )\n continue;\n\n // Use original casing (important for SVG attrs like viewBox)\n const originalName = node.originalAttrs?.[name] || name;\n ctx.lines.push(\n `${varName}.setAttribute('${escapeJS(originalName)}','${escapeJS(value)}');`\n );\n }\n\n // Phase 5's applyBindings() reads from descriptors only — directive data-*\n // attributes (data-on-click, data-bind-*, data-class-toggle-*, etc.) are NOT\n // emitted in AOT output. They were transitional scaffolding removed in Phase 6.\n //\n // That holds for every directive that HAS a descriptor. The router pair does\n // not: their consumers query the DOM for the attribute, so dropping them with\n // the rest of the `@` attributes above left every built app without an outlet.\n // Emitted through the compiler's own mapping rather than re-spelled here, so\n // the two compilation paths cannot disagree about it again.\n if (node.directives) {\n forEachDomDirectiveAttr(node.directives, (attr, value) => {\n ctx.lines.push(\n `${varName}.setAttribute('${escapeJS(attr)}','${escapeJS(value)}');`\n );\n });\n }\n\n // Slot assignment is still needed as a regular HTML attribute so the runtime\n // binder can collect slot content from DOM children.\n if (node.directives?.slot !== undefined) {\n ctx.lines.push(\n `${varName}.setAttribute('slot','${escapeJS(node.directives.slot)}');`\n );\n }\n\n // Set scope ID attribute\n if (ctx.scopeId) {\n ctx.lines.push(\n `${varName}.setAttribute('data-scope-${escapeJS(ctx.scopeId)}','');`\n );\n }\n\n // Set data-pid for binding resolution (after directives, matching runtime order)\n if (node.nodeId) {\n ctx.lines.push(\n `${varName}.setAttribute('data-pid','${escapeJS(node.nodeId)}');`\n );\n } else if (node.attrs?.['data-pid']) {\n ctx.lines.push(\n `${varName}.setAttribute('data-pid','${escapeJS(node.attrs['data-pid'])}');`\n );\n }\n\n // Recursively serialize children\n const childVarNames: string[] = [];\n for (const child of node.children ?? []) {\n const childResult = serializeNode(child, ctx);\n if (childResult) {\n childVarNames.push(childResult.varName);\n }\n }\n\n // Append children to this element\n if (childVarNames.length === 1) {\n ctx.lines.push(`${varName}.appendChild(${childVarNames[0]});`);\n } else if (childVarNames.length > 1) {\n ctx.lines.push(`${varName}.append(${childVarNames.join(',')});`);\n }\n\n return { varName, childVarNames };\n}\n\n/**\n * Defense-in-depth guard: structural directives should be handled by `processNodes`\n * in `generateDomFactory.ts` and never reach `serializeNode`. If one does, it means\n * a bug in the structural codegen pipeline.\n */\nfunction assertNoStructuralDirectives(node: PithyNode): void {\n const d = node.directives;\n if (!d) return;\n\n if (d.for) {\n throw new Error(\n `AOT: @for directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.if !== undefined) {\n throw new Error(\n `AOT: @if directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.elseIf !== undefined) {\n throw new Error(\n `AOT: @else-if directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.else !== undefined) {\n throw new Error(\n `AOT: @else directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.switch !== undefined) {\n throw new Error(\n `AOT: @switch directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.case !== undefined) {\n throw new Error(\n `AOT: @case directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n // Note: @default is stored in node.attrs['@default'], not in ParsedDirectives,\n // so it cannot be caught here. It is handled by processNodes via isDefaultCase().\n}\n"]}
1
+ {"version":3,"file":"serializeNode.js","sourceRoot":"","sources":["../../src/aotCodegen/serializeNode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,cAAc,EACd,SAAS,EACT,MAAM,EACN,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AA0BnC;;;;;;;;;;;;;;;;GAgBG;AACH,sKAAsK;AACtK,MAAM,UAAU,sBAAsB,CAAC,OAAgB;IACrD,OAAO;QACL,YAAY,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CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAElD,0LAA0L;AAC1L,MAAM,UAAU,aAAa,CAC3B,IAAe,EACf,OAAe,EACf,GAAqB;IAErB,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM;QAAE,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;IACrE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC;IACtB,GAAG,CAAC,GAAG,GAAG,GAAG,OAAO,GAAG,CAAC;IACxB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,GAAG,IAAI,OAAO,yBAAyB,CAAC,CAAC;IACrE,OAAO,GAAG,EAAE;QACV,GAAG,CAAC,GAAG,GAAG,KAAK,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,8MAA8M;AAC9M,MAAM,UAAU,cAAc,CAC5B,IAAe,EACf,OAAe,EACf,aAAuB,EACvB,GAAqB;IAErB,MAAM,MAAM,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC;IACrE,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/B,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,gBAAgB,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAChE,CAAC;SAAM,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,WAAW,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.aot.serialize-node\",\n \"title\": \"AOT Node Serializer\",\n \"category\": \"compiler\",\n \"description\": \"Serializes parsed template nodes into static HTML strings with marker comments for dynamic binding points.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n elementTagName,\n isSvgNode,\n SVG_NS,\n forEachDomDirectiveAttr,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { escapeJS } from './utils';\n\n/** Tracks variable counters during a single factory generation pass. */\nexport interface SerializeContext {\n /** Next element variable index (e0, e1, ...) */\n elementCount: number;\n /** Next text node variable index (t0, t1, ...) */\n textCount: number;\n /** Next comment variable index (c0, c1, ...) */\n commentCount: number;\n /** Scope ID for data-scope-{id} attributes (e.g. \"pithy-abc123\") */\n scopeId?: string;\n /** The expression new nodes are created from; a `<template>`'s descendants use its inert owner document. */\n doc?: string;\n /** Accumulated lines of JS code */\n lines: string[];\n}\n\n/** Result of serializing a single node. */\nexport interface SerializedNode {\n /** Variable name assigned to this DOM node (e.g. \"e0\", \"t3\") */\n varName: string;\n /** Variable names of direct children (for parent.append(...children)) */\n childVarNames: string[];\n}\n\n/**\n * Create a fresh serialize context for a single factory generation pass.\n *\n * The context accumulates JS code lines and tracks variable counters\n * across recursive `serializeNode` calls. Each factory should use\n * its own context.\n *\n * @param scopeId - Optional CSS scope ID (e.g. \"pithy-abc123\").\n * When provided, every element gets a `data-scope-{scopeId}` attribute.\n *\n * @example\n * ```typescript\n * const ctx = createSerializeContext('pithy-abc123');\n * serializeNode(rootNode, ctx);\n * console.log(ctx.lines); // [\"const e0=document.createElement('div');\", ...]\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"createSerializeContext\",\"stability\":\"experimental\",\"signature\":\"(scopeId?: string) => SerializeContext\"} */\nexport function createSerializeContext(scopeId?: string): SerializeContext {\n return {\n elementCount: 0,\n textCount: 0,\n commentCount: 0,\n scopeId,\n lines: [],\n };\n}\n\n/**\n * Serialize a single PithyNode into JS code that creates the corresponding\n * DOM node. Appends code lines to `ctx.lines` and returns the variable name.\n *\n * Phase 1 scope: elements, text nodes.\n * Skips directive attributes (@, []) — those become binding descriptors.\n * Throws on structural directives (@for, @if, @switch) — those are Phase 2.\n *\n * @example\n * ```typescript\n * const ctx = createSerializeContext('pithy-abc123');\n * const result = serializeNode(node, ctx);\n * // ctx.lines now contains JS code lines\n * // result.varName is e.g. \"e0\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"serializeNode\",\"stability\":\"experimental\",\"signature\":\"(node: PithyNode, ctx: SerializeContext) => SerializedNode | null\"} */\nexport function serializeNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode | null {\n if (node.type === 'text') {\n return serializeTextNode(node, ctx);\n }\n\n if (node.type === 'element') {\n return serializeElementNode(node, ctx);\n }\n\n // Slot nodes are handled by processNodes in generateDomFactory.ts — they should not reach here.\n return null;\n}\n\nfunction serializeTextNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode {\n const varName = `t${ctx.textCount++}`;\n const content = node.textContent ?? '';\n ctx.lines.push(\n `const ${varName}=${ctx.doc ?? 'document'}.createTextNode('${escapeJS(content)}');`\n );\n return { varName, childVarNames: [] };\n}\n\nfunction serializeElementNode(\n node: PithyNode,\n ctx: SerializeContext\n): SerializedNode {\n // Guard: structural directives are not supported in Phase 1\n assertNoStructuralDirectives(node);\n\n const varName = `e${ctx.elementCount++}`;\n const tag = elementTagName(node);\n const doc = ctx.doc ?? 'document';\n\n if (isSvgNode(node)) {\n ctx.lines.push(\n `const ${varName}=${doc}.createElementNS('${SVG_NS}','${escapeJS(tag)}');`\n );\n } else {\n ctx.lines.push(\n `const ${varName}=${doc}.createElement('${escapeJS(tag)}');`\n );\n }\n\n // Set static attributes (skip directive attrs, data-pid, and slot which are set separately)\n for (const [name, value] of Object.entries(node.attrs ?? {})) {\n if (\n name.startsWith('@') ||\n name.startsWith('[') ||\n name === 'data-pid' ||\n name === 'slot'\n )\n continue;\n\n // Use original casing (important for SVG attrs like viewBox)\n const originalName = node.originalAttrs?.[name] || name;\n ctx.lines.push(\n `${varName}.setAttribute('${escapeJS(originalName)}','${escapeJS(value)}');`\n );\n }\n\n // Phase 5's applyBindings() reads from descriptors only — directive data-*\n // attributes (data-on-click, data-bind-*, data-class-toggle-*, etc.) are NOT\n // emitted in AOT output. They were transitional scaffolding removed in Phase 6.\n //\n // That holds for every directive that HAS a descriptor. The router pair does\n // not: their consumers query the DOM for the attribute, so dropping them with\n // the rest of the `@` attributes above left every built app without an outlet.\n // Emitted through the compiler's own mapping rather than re-spelled here, so\n // the two compilation paths cannot disagree about it again.\n if (node.directives) {\n forEachDomDirectiveAttr(node.directives, (attr, value) => {\n ctx.lines.push(\n `${varName}.setAttribute('${escapeJS(attr)}','${escapeJS(value)}');`\n );\n });\n }\n\n // Slot assignment is still needed as a regular HTML attribute so the runtime\n // binder can collect slot content from DOM children.\n if (node.directives?.slot !== undefined) {\n ctx.lines.push(\n `${varName}.setAttribute('slot','${escapeJS(node.directives.slot)}');`\n );\n }\n\n // Set scope ID attribute\n if (ctx.scopeId) {\n ctx.lines.push(\n `${varName}.setAttribute('data-scope-${escapeJS(ctx.scopeId)}','');`\n );\n }\n\n // Set data-pid for binding resolution (after directives, matching runtime order)\n if (node.nodeId) {\n ctx.lines.push(\n `${varName}.setAttribute('data-pid','${escapeJS(node.nodeId)}');`\n );\n } else if (node.attrs?.['data-pid']) {\n ctx.lines.push(\n `${varName}.setAttribute('data-pid','${escapeJS(node.attrs['data-pid'])}');`\n );\n }\n\n // Recursively serialize children\n const childVarNames: string[] = [];\n const leave = enterTemplate(node, varName, ctx);\n for (const child of node.children ?? []) {\n const childResult = serializeNode(child, ctx);\n if (childResult) {\n childVarNames.push(childResult.varName);\n }\n }\n\n leave();\n appendChildren(node, varName, childVarNames, ctx);\n\n return { varName, childVarNames };\n}\n\n/**\n * Defense-in-depth guard: structural directives should be handled by `processNodes`\n * in `generateDomFactory.ts` and never reach `serializeNode`. If one does, it means\n * a bug in the structural codegen pipeline.\n */\nfunction assertNoStructuralDirectives(node: PithyNode): void {\n const d = node.directives;\n if (!d) return;\n\n if (d.for) {\n throw new Error(\n `AOT: @for directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.if !== undefined) {\n throw new Error(\n `AOT: @if directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.elseIf !== undefined) {\n throw new Error(\n `AOT: @else-if directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.else !== undefined) {\n throw new Error(\n `AOT: @else directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.switch !== undefined) {\n throw new Error(\n `AOT: @switch directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n if (d.case !== undefined) {\n throw new Error(\n `AOT: @case directive reached serializeNode (node ${node.nodeId}). This is a bug — structural directives must be handled by processNodes.`\n );\n }\n // Note: @default is stored in node.attrs['@default'], not in ParsedDirectives,\n // so it cannot be caught here. It is handled by processNodes via isDefaultCase().\n}\n\nconst isHtmlTemplate = (node: PithyNode) =>\n node.tagName === 'template' && !isSvgNode(node);\n\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"enterTemplate\",\"stability\":\"internal\",\"signature\":\"(node: PithyNode, varName: string, ctx: SerializeContext) => () => void\"} */\nexport function enterTemplate(\n node: PithyNode,\n varName: string,\n ctx: SerializeContext\n): () => void {\n if (!isHtmlTemplate(node) || !node.children?.length) return () => {};\n const outer = ctx.doc;\n ctx.doc = `${varName}d`;\n ctx.lines.push(`const ${ctx.doc}=${varName}.content.ownerDocument;`);\n return () => {\n ctx.doc = outer;\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.aot.serialize-node\",\"name\":\"appendChildren\",\"stability\":\"internal\",\"signature\":\"(node: PithyNode, varName: string, childVarNames: string[], ctx: SerializeContext) => void\"} */\nexport function appendChildren(\n node: PithyNode,\n varName: string,\n childVarNames: string[],\n ctx: SerializeContext\n): void {\n const parent = isHtmlTemplate(node) ? `${varName}.content` : varName;\n if (childVarNames.length === 1) {\n ctx.lines.push(`${parent}.appendChild(${childVarNames[0]});`);\n } else if (childVarNames.length > 1) {\n ctx.lines.push(`${parent}.append(${childVarNames.join(',')});`);\n }\n}\n"]}
@@ -39,8 +39,14 @@ interface PithyBuildOptions {
39
39
  */
40
40
  routesDir?: string;
41
41
  /**
42
- * Enable source maps
43
- * @default true in development, false in production
42
+ * Emit source maps (`build.sourcemap`). Leave unset to keep the app's own
43
+ * `build.sourcemap`, or Vite's default (off).
44
+ *
45
+ * Off by default because a map embeds the original source (`sourcesContent`)
46
+ * and a production build publishes it next to the bundle. Pass `true` only
47
+ * when shipping that source is intended.
48
+ *
49
+ * @default undefined (the app's `build.sourcemap`, else off)
44
50
  */
45
51
  sourcemap?: boolean;
46
52
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/buildPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,MAAM,CAAC;AAE/C;;GAEG;AACH,UAAU,iBAAiB;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AA+ED,wBAAgB,UAAU,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CAuHlE"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/buildPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,MAAM,CAAC;AAE/C;;GAEG;AACH,UAAU,iBAAiB;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AA8ED,wBAAgB,UAAU,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CA6HlE"}
@@ -18,7 +18,6 @@ const DEFAULT_OPTIONS = {
18
18
  lazyChunkPrefix: 'lazy-',
19
19
  routeChunkPrefix: 'route-',
20
20
  routesDir: 'routes',
21
- sourcemap: true,
22
21
  target: 'esnext',
23
22
  };
24
23
  /**
@@ -170,7 +169,12 @@ export function pithyBuild(options = {}) {
170
169
  : undefined,
171
170
  },
172
171
  },
173
- sourcemap: config.sourcemap,
172
+ // Only when asked: a value here would override the app's own
173
+ // `build.sourcemap`, and a default of `true` published every app's
174
+ // original source.
175
+ ...(config.sourcemap !== undefined
176
+ ? { sourcemap: config.sourcemap }
177
+ : {}),
174
178
  target: config.target,
175
179
  },
176
180
  };
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/buildPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AA6CF,MAAM,eAAe,GAAgC;IACnD,YAAY,EAAE,IAAI;IAClB,eAAe,EAAE,OAAO;IACxB,gBAAgB,EAAE,QAAQ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ACtB;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.build-plugin\",\n \"title\": \"PithyJS Build Optimization Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Build optimization plugin providing chunk naming strategies, vendor splitting, and route-based code splitting.\",\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\nimport type { Plugin, UserConfig } from 'vite';\n\n/**\n * Build plugin options\n */\ninterface PithyBuildOptions {\n /**\n * Enable vendor chunk splitting for framework packages\n * @default true\n */\n vendorChunks?: boolean;\n\n /**\n * Prefix for lazy-loaded component chunks\n * @default \"lazy-\"\n */\n lazyChunkPrefix?: string;\n\n /**\n * Prefix for route chunks\n * @default \"route-\"\n */\n routeChunkPrefix?: string;\n\n /**\n * Routes directory name (used for route chunk detection)\n * @default \"routes\"\n */\n routesDir?: string;\n\n /**\n * Enable source maps\n * @default true in development, false in production\n */\n sourcemap?: boolean;\n\n /**\n * Build target\n * @default \"esnext\"\n */\n target?: string;\n}\n\nconst DEFAULT_OPTIONS: Required<PithyBuildOptions> = {\n vendorChunks: true,\n lazyChunkPrefix: 'lazy-',\n routeChunkPrefix: 'route-',\n routesDir: 'routes',\n sourcemap: true,\n target: 'esnext',\n};\n\n/**\n * Vite plugin for PithyJS build optimizations.\n *\n * Provides:\n * - Chunk naming strategy for lazy-loaded components\n * - Route-based chunk naming\n * - Framework vendor chunk splitting\n * - Optimized asset naming\n *\n * @param options - Build configuration options\n * @returns Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { pithyBuild } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [\n * pithyBuild(),\n * ],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.build-plugin\",\"name\":\"pithyBuild\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBuildOptions) => Plugin\"} */\n/**\n * Whether every path from an entry to `id` crosses at least one `import()`.\n *\n * This is the question the `vendor` catch-all has to ask. A module reached only\n * through a dynamic import is code the app deliberately deferred; naming a\n * chunk for it merges it into a chunk the entry preloads and the deferral is\n * undone. Shiki is the case that exposed this — its WASM engine and ~300\n * grammars — but `parse5` is the same shape, and so is every future lazy\n * dependency. Hence a general rule rather than a list of names.\n *\n * STATIC IMPORTERS ALONE ARE NOT ENOUGH, which is the subtle half: a lazy\n * package's own closure has static importers — `hast-util-to-html` is\n * statically imported by `@shikijs/core`, which is itself only dynamically\n * imported. Asking \"does it have a static importer?\" keeps the closure in\n * `vendor` and leaves the bug in place. The walk has to continue upward until\n * it reaches an entry or a dynamic boundary.\n *\n * A module with no importers at all is an entry, so not deferred. A module\n * shared with eagerly-reachable code returns false and stays in `vendor`,\n * which is what stops it being duplicated into every chunk that wants it.\n */\nfunction isDeferredOnly(\n id: string,\n getModuleInfo: (id: string) => {\n importers: readonly string[];\n dynamicImporters: readonly string[];\n } | null,\n seen: Set<string> = new Set()\n): boolean {\n if (seen.has(id)) return true;\n seen.add(id);\n\n const info = getModuleInfo(id);\n if (!info) return false;\n\n // No static importer, but something `import()`s it: a deferred root.\n if (info.importers.length === 0) return info.dynamicImporters.length > 0;\n\n return info.importers.every(importer =>\n isDeferredOnly(importer, getModuleInfo, seen)\n );\n}\n\nexport function pithyBuild(options: PithyBuildOptions = {}): Plugin {\n const config: Required<PithyBuildOptions> = {\n ...DEFAULT_OPTIONS,\n ...options,\n };\n\n return {\n name: 'pithy:build',\n // Apply only during build\n apply: 'build',\n\n config(): UserConfig {\n return {\n build: {\n rollupOptions: {\n output: {\n // Chunk naming strategy\n chunkFileNames: chunkInfo => {\n const routesPattern = `/${config.routesDir}/`;\n\n // Route chunks get route-based names\n if (chunkInfo.facadeModuleId?.includes(routesPattern)) {\n const routePath =\n chunkInfo.facadeModuleId\n .split(routesPattern)[1]\n ?.replace(/\\+page\\.(ts|js|pithy)$/, '')\n .replace(/\\//g, '-')\n .replace(/-$/, '')\n // Sanitize dynamic route segments: [id] -> _id_, [...slug] -> _slug_\n .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, '_$1_')\n .replace(/\\[([^\\]]+)\\]/g, '_$1_') || 'index';\n return `assets/${config.routeChunkPrefix}${routePath}-[hash].js`;\n }\n\n // Vendor chunks keep their names\n if (chunkInfo.name?.startsWith('vendor')) {\n return `assets/[name]-[hash].js`;\n }\n\n // Dynamic entry chunks (from dynamic imports) are lazy-loaded components\n // Detect by: isDynamicEntry=true AND not a route AND not a vendor\n if (chunkInfo.isDynamicEntry && chunkInfo.facadeModuleId) {\n const moduleId = chunkInfo.facadeModuleId;\n const isVendor =\n moduleId.includes('node_modules') ||\n moduleId.includes('@pithyjs/') ||\n moduleId.includes('packages/core/') ||\n moduleId.includes('packages/signals/') ||\n moduleId.includes('packages/router/') ||\n moduleId.includes('packages/design-system/');\n\n if (!isVendor) {\n // This is a lazy-loaded component chunk\n return `assets/${config.lazyChunkPrefix}[name]-[hash].js`;\n }\n }\n\n // Default chunk naming\n return 'assets/[name]-[hash].js';\n },\n\n // Entry chunks\n entryFileNames: 'assets/[name]-[hash].js',\n\n // Assets like CSS\n assetFileNames: 'assets/[name]-[hash].[ext]',\n\n // Manual chunk splitting for better caching\n manualChunks: config.vendorChunks\n ? (id, { getModuleInfo }) => {\n // Core framework chunks - cached long-term\n // These patterns work both for local development (packages/)\n // and npm installs (node_modules/@pithyjs/)\n if (\n id.includes('@pithyjs/core') ||\n id.includes('packages/core/')\n ) {\n return 'vendor-pithy-core';\n }\n if (\n id.includes('@pithyjs/signals') ||\n id.includes('packages/signals/')\n ) {\n return 'vendor-pithy-signals';\n }\n if (\n id.includes('@pithyjs/router') ||\n id.includes('packages/router/')\n ) {\n return 'vendor-pithy-router';\n }\n if (\n id.includes('@pithyjs/design-system') ||\n id.includes('packages/design-system/')\n ) {\n return 'vendor-pithy-design';\n }\n\n // Node modules vendor chunk — EXCEPT anything the app only\n // reaches through `import()`. `vendor` is imported by the\n // entry and preloaded by the HTML, so naming a chunk for a\n // deferred module undoes the deferral.\n if (id.includes('node_modules')) {\n return isDeferredOnly(id, getModuleInfo)\n ? undefined\n : 'vendor';\n }\n\n return undefined;\n }\n : undefined,\n },\n },\n sourcemap: config.sourcemap,\n target: config.target,\n },\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/buildPlugin/plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAmDF,MAAM,eAAe,GAAmD;IACtE,YAAY,EAAE,IAAI;IAClB,eAAe,EAAE,OAAO;IACxB,gBAAgB,EAAE,QAAQ;IAC1B,SAAS,EAAE,QAAQ;IACnB,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,oJAAoJ;AACpJ;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAS,cAAc,CACrB,EAAU,EACV,aAGQ,EACR,OAAoB,IAAI,GAAG,EAAE;IAE7B,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QAAE,OAAO,IAAI,CAAC;IAC9B,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAEb,MAAM,IAAI,GAAG,aAAa,CAAC,EAAE,CAAC,CAAC;IAC/B,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IAExB,qEAAqE;IACrE,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC;IAEzE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CACrC,cAAc,CAAC,QAAQ,EAAE,aAAa,EAAE,IAAI,CAAC,CAC9C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,UAAU,CAAC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tC,CAAC;wCACD,OAAO,qBAAqB,CAAC;oCAC/B,CAAC;oCAED,2DAA2D;oCAC3D,0DAA0D;oCAC1D,2DAA2D;oCAC3D,uCAAuC;oCACvC,IAAI,EAAE,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;wCAChC,OAAO,cAAc,CAAC,EAAE,EAAE,aAAa,CAAC;4CACtC,CAAC,CAAC,SAAS;4CACX,CAAC,CAAC,QAAQ,CAAC;oCACf,CAAC;oCAED,OAAO,SAAS,CAAC;gCACnB,CAAC;gCACH,CAAC,CAAC,SAAS;yBACd;qBACF;oBACD,6DAA6D;oBAC7D,mEAAmE;oBACnE,mBAAmB;oBACnB,GAAG,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS;wBAChC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE;wBACjC,CAAC,CAAC,EAAE,CAAC;oBACP,MAAM,EAAE,MAAM,CAAC,MAAM;iBACtB;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.build-plugin\",\n \"title\": \"PithyJS Build Optimization Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Build optimization plugin providing chunk naming strategies, vendor splitting, and route-based code splitting.\",\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\nimport type { Plugin, UserConfig } from 'vite';\n\n/**\n * Build plugin options\n */\ninterface PithyBuildOptions {\n /**\n * Enable vendor chunk splitting for framework packages\n * @default true\n */\n vendorChunks?: boolean;\n\n /**\n * Prefix for lazy-loaded component chunks\n * @default \"lazy-\"\n */\n lazyChunkPrefix?: string;\n\n /**\n * Prefix for route chunks\n * @default \"route-\"\n */\n routeChunkPrefix?: string;\n\n /**\n * Routes directory name (used for route chunk detection)\n * @default \"routes\"\n */\n routesDir?: string;\n\n /**\n * Emit source maps (`build.sourcemap`). Leave unset to keep the app's own\n * `build.sourcemap`, or Vite's default (off).\n *\n * Off by default because a map embeds the original source (`sourcesContent`)\n * and a production build publishes it next to the bundle. Pass `true` only\n * when shipping that source is intended.\n *\n * @default undefined (the app's `build.sourcemap`, else off)\n */\n sourcemap?: boolean;\n\n /**\n * Build target\n * @default \"esnext\"\n */\n target?: string;\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<PithyBuildOptions, 'sourcemap'>> = {\n vendorChunks: true,\n lazyChunkPrefix: 'lazy-',\n routeChunkPrefix: 'route-',\n routesDir: 'routes',\n target: 'esnext',\n};\n\n/**\n * Vite plugin for PithyJS build optimizations.\n *\n * Provides:\n * - Chunk naming strategy for lazy-loaded components\n * - Route-based chunk naming\n * - Framework vendor chunk splitting\n * - Optimized asset naming\n *\n * @param options - Build configuration options\n * @returns Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { pithyBuild } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [\n * pithyBuild(),\n * ],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.build-plugin\",\"name\":\"pithyBuild\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBuildOptions) => Plugin\"} */\n/**\n * Whether every path from an entry to `id` crosses at least one `import()`.\n *\n * This is the question the `vendor` catch-all has to ask. A module reached only\n * through a dynamic import is code the app deliberately deferred; naming a\n * chunk for it merges it into a chunk the entry preloads and the deferral is\n * undone. Shiki is the case that exposed this — its WASM engine and ~300\n * grammars — but `parse5` is the same shape, and so is every future lazy\n * dependency. Hence a general rule rather than a list of names.\n *\n * STATIC IMPORTERS ALONE ARE NOT ENOUGH, which is the subtle half: a lazy\n * package's own closure has static importers — `hast-util-to-html` is\n * statically imported by `@shikijs/core`, which is itself only dynamically\n * imported. Asking \"does it have a static importer?\" keeps the closure in\n * `vendor` and leaves the bug in place. The walk has to continue upward until\n * it reaches an entry or a dynamic boundary.\n *\n * A module with no importers at all is an entry, so not deferred. A module\n * shared with eagerly-reachable code returns false and stays in `vendor`,\n * which is what stops it being duplicated into every chunk that wants it.\n */\nfunction isDeferredOnly(\n id: string,\n getModuleInfo: (id: string) => {\n importers: readonly string[];\n dynamicImporters: readonly string[];\n } | null,\n seen: Set<string> = new Set()\n): boolean {\n if (seen.has(id)) return true;\n seen.add(id);\n\n const info = getModuleInfo(id);\n if (!info) return false;\n\n // No static importer, but something `import()`s it: a deferred root.\n if (info.importers.length === 0) return info.dynamicImporters.length > 0;\n\n return info.importers.every(importer =>\n isDeferredOnly(importer, getModuleInfo, seen)\n );\n}\n\nexport function pithyBuild(options: PithyBuildOptions = {}): Plugin {\n const config: Required<Omit<PithyBuildOptions, 'sourcemap'>> &\n Pick<PithyBuildOptions, 'sourcemap'> = {\n ...DEFAULT_OPTIONS,\n ...options,\n };\n\n return {\n name: 'pithy:build',\n // Apply only during build\n apply: 'build',\n\n config(): UserConfig {\n return {\n build: {\n rollupOptions: {\n output: {\n // Chunk naming strategy\n chunkFileNames: chunkInfo => {\n const routesPattern = `/${config.routesDir}/`;\n\n // Route chunks get route-based names\n if (chunkInfo.facadeModuleId?.includes(routesPattern)) {\n const routePath =\n chunkInfo.facadeModuleId\n .split(routesPattern)[1]\n ?.replace(/\\+page\\.(ts|js|pithy)$/, '')\n .replace(/\\//g, '-')\n .replace(/-$/, '')\n // Sanitize dynamic route segments: [id] -> _id_, [...slug] -> _slug_\n .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, '_$1_')\n .replace(/\\[([^\\]]+)\\]/g, '_$1_') || 'index';\n return `assets/${config.routeChunkPrefix}${routePath}-[hash].js`;\n }\n\n // Vendor chunks keep their names\n if (chunkInfo.name?.startsWith('vendor')) {\n return `assets/[name]-[hash].js`;\n }\n\n // Dynamic entry chunks (from dynamic imports) are lazy-loaded components\n // Detect by: isDynamicEntry=true AND not a route AND not a vendor\n if (chunkInfo.isDynamicEntry && chunkInfo.facadeModuleId) {\n const moduleId = chunkInfo.facadeModuleId;\n const isVendor =\n moduleId.includes('node_modules') ||\n moduleId.includes('@pithyjs/') ||\n moduleId.includes('packages/core/') ||\n moduleId.includes('packages/signals/') ||\n moduleId.includes('packages/router/') ||\n moduleId.includes('packages/design-system/');\n\n if (!isVendor) {\n // This is a lazy-loaded component chunk\n return `assets/${config.lazyChunkPrefix}[name]-[hash].js`;\n }\n }\n\n // Default chunk naming\n return 'assets/[name]-[hash].js';\n },\n\n // Entry chunks\n entryFileNames: 'assets/[name]-[hash].js',\n\n // Assets like CSS\n assetFileNames: 'assets/[name]-[hash].[ext]',\n\n // Manual chunk splitting for better caching\n manualChunks: config.vendorChunks\n ? (id, { getModuleInfo }) => {\n // Core framework chunks - cached long-term\n // These patterns work both for local development (packages/)\n // and npm installs (node_modules/@pithyjs/)\n if (\n id.includes('@pithyjs/core') ||\n id.includes('packages/core/')\n ) {\n return 'vendor-pithy-core';\n }\n if (\n id.includes('@pithyjs/signals') ||\n id.includes('packages/signals/')\n ) {\n return 'vendor-pithy-signals';\n }\n if (\n id.includes('@pithyjs/router') ||\n id.includes('packages/router/')\n ) {\n return 'vendor-pithy-router';\n }\n if (\n id.includes('@pithyjs/design-system') ||\n id.includes('packages/design-system/')\n ) {\n return 'vendor-pithy-design';\n }\n\n // Node modules vendor chunk — EXCEPT anything the app only\n // reaches through `import()`. `vendor` is imported by the\n // entry and preloaded by the HTML, so naming a chunk for a\n // deferred module undoes the deferral.\n if (id.includes('node_modules')) {\n return isDeferredOnly(id, getModuleInfo)\n ? undefined\n : 'vendor';\n }\n\n return undefined;\n }\n : undefined,\n },\n },\n // Only when asked: a value here would override the app's own\n // `build.sourcemap`, and a default of `true` published every app's\n // original source.\n ...(config.sourcemap !== undefined\n ? { sourcemap: config.sourcemap }\n : {}),\n target: config.target,\n },\n };\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithyjs/vite-plugin",
3
- "version": "0.2.0-beta.21",
3
+ "version": "0.2.0-beta.23",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/PithyJS/pithyjs.git",
@@ -34,9 +34,9 @@
34
34
  "@babel/types": "^7.27.3",
35
35
  "fast-glob": "^3.3.0",
36
36
  "parse5": "^7.3.0",
37
- "@pithyjs/compiler": "0.1.0-beta.8",
38
- "@pithyjs/design-system": "0.1.0-beta.11",
39
- "@pithyjs/router": "0.2.0-beta.20",
37
+ "@pithyjs/compiler": "0.1.0-beta.9",
38
+ "@pithyjs/design-system": "0.1.0-beta.12",
39
+ "@pithyjs/router": "0.2.0-beta.21",
40
40
  "@pithyjs/shared": "0.1.0-beta.4"
41
41
  },
42
42
  "devDependencies": {