@fictjs/vite-plugin 0.5.1 → 0.6.0
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 +3 -0
- package/dist/index.cjs +62 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +62 -22
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -29,6 +29,8 @@ export default defineConfig({
|
|
|
29
29
|
// Optional TypeScript project integration
|
|
30
30
|
useTypeScriptProject: true,
|
|
31
31
|
tsconfigPath: './tsconfig.json',
|
|
32
|
+
// Optional plugin debug logs (or set FICT_VITE_PLUGIN_DEBUG=1)
|
|
33
|
+
debug: false,
|
|
32
34
|
// Allow $state/$effect inside reactive-scope callbacks (e.g., renderHook(() => ...))
|
|
33
35
|
reactiveScopes: ['renderHook'],
|
|
34
36
|
}),
|
|
@@ -40,3 +42,4 @@ Notes:
|
|
|
40
42
|
|
|
41
43
|
- `reactiveScopes` only applies to **direct calls** and only treats the **first argument** as the reactive callback.
|
|
42
44
|
- Aliased/indirect calls are not recognized (e.g., `const rh = renderHook; rh(() => ...)`).
|
|
45
|
+
- `debug` logs are disabled by default; enable with `debug: true` or `FICT_VITE_PLUGIN_DEBUG=1`.
|
package/dist/index.cjs
CHANGED
|
@@ -58,6 +58,7 @@ function fict(options = {}) {
|
|
|
58
58
|
cache: cacheOption,
|
|
59
59
|
tsconfigPath,
|
|
60
60
|
useTypeScriptProject = true,
|
|
61
|
+
debug: debugOption,
|
|
61
62
|
...compilerOptions
|
|
62
63
|
} = options;
|
|
63
64
|
let config;
|
|
@@ -66,6 +67,12 @@ function fict(options = {}) {
|
|
|
66
67
|
let tsProject = null;
|
|
67
68
|
let tsProjectInit = null;
|
|
68
69
|
const moduleMetadata = /* @__PURE__ */ new Map();
|
|
70
|
+
const debugEnabled = debugOption === true || process.env.FICT_VITE_PLUGIN_DEBUG === "1" || process.env.FICT_VITE_PLUGIN_DEBUG === "true";
|
|
71
|
+
const debugLog = (message, details) => {
|
|
72
|
+
if (!debugEnabled) return;
|
|
73
|
+
const payload = details === void 0 ? "" : ` ${safeDebugString(details)}`;
|
|
74
|
+
config?.logger?.info(`[fict-plugin] ${message}${payload}`);
|
|
75
|
+
};
|
|
69
76
|
const ensureCache = () => {
|
|
70
77
|
if (cache) return cache;
|
|
71
78
|
const normalized = normalizeCacheOptions(cacheOption, config);
|
|
@@ -119,16 +126,16 @@ function fict(options = {}) {
|
|
|
119
126
|
return null;
|
|
120
127
|
}
|
|
121
128
|
const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length);
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
);
|
|
129
|
+
debugLog(`Loading virtual module: ${handlerId}`, {
|
|
130
|
+
registrySize: extractedHandlers.size,
|
|
131
|
+
handlers: Array.from(extractedHandlers.keys())
|
|
132
|
+
});
|
|
127
133
|
const handler = extractedHandlers.get(handlerId);
|
|
128
134
|
if (handler) {
|
|
129
135
|
const generatedCode = generateHandlerModule(handler);
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
debugLog(`Generated virtual module (${generatedCode.length} chars)`, {
|
|
137
|
+
preview: generatedCode.slice(0, 200)
|
|
138
|
+
});
|
|
132
139
|
return generatedCode;
|
|
133
140
|
}
|
|
134
141
|
if (!handler) {
|
|
@@ -314,23 +321,27 @@ function fict(options = {}) {
|
|
|
314
321
|
let finalCode = result.code;
|
|
315
322
|
let finalMap = result.map;
|
|
316
323
|
const shouldSplit = options.functionSplitting ?? (config?.command === "build" && (compilerOptions.resumable || !config?.build?.ssr));
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
324
|
+
debugLog("Function split decision", {
|
|
325
|
+
shouldSplit,
|
|
326
|
+
ssr: config?.build?.ssr,
|
|
327
|
+
resumable: compilerOptions.resumable,
|
|
328
|
+
file: filename
|
|
329
|
+
});
|
|
320
330
|
if (shouldSplit) {
|
|
321
331
|
let splitResult = null;
|
|
322
332
|
try {
|
|
323
333
|
splitResult = extractAndRewriteHandlers(finalCode, filename);
|
|
324
|
-
} catch (
|
|
325
|
-
|
|
334
|
+
} catch (error) {
|
|
335
|
+
this.warn(buildPluginMessage("extractAndRewriteHandlers failed", filename, error));
|
|
326
336
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
337
|
+
debugLog("Split result", {
|
|
338
|
+
file: filename,
|
|
339
|
+
handlers: splitResult?.handlers.length ?? 0
|
|
340
|
+
});
|
|
330
341
|
if (splitResult) {
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
);
|
|
342
|
+
debugLog(`Function splitting extracted ${splitResult.handlers.length} handlers`, {
|
|
343
|
+
file: filename
|
|
344
|
+
});
|
|
334
345
|
finalCode = splitResult.code;
|
|
335
346
|
finalMap = null;
|
|
336
347
|
if (config?.command === "build" && !config?.build?.ssr) {
|
|
@@ -581,10 +592,34 @@ var TransformCache = class {
|
|
|
581
592
|
this.memory.clear();
|
|
582
593
|
}
|
|
583
594
|
};
|
|
595
|
+
function isTypeScriptApi(value) {
|
|
596
|
+
if (!value || typeof value !== "object") return false;
|
|
597
|
+
const candidate = value;
|
|
598
|
+
return typeof candidate.findConfigFile === "function" && typeof candidate.readConfigFile === "function" && typeof candidate.parseJsonConfigFileContent === "function" && typeof candidate.createLanguageService === "function" && typeof candidate.createDocumentRegistry === "function" && typeof candidate.resolveModuleName === "function" && !!candidate.sys && typeof candidate.sys === "object" && typeof candidate.sys.fileExists === "function" && typeof candidate.sys.readFile === "function";
|
|
599
|
+
}
|
|
600
|
+
function safeDebugString(value) {
|
|
601
|
+
try {
|
|
602
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
603
|
+
} catch {
|
|
604
|
+
return String(value);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function formatError(error) {
|
|
608
|
+
if (error instanceof Error) return error.message;
|
|
609
|
+
try {
|
|
610
|
+
return JSON.stringify(error);
|
|
611
|
+
} catch {
|
|
612
|
+
return String(error);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function buildPluginMessage(context, file, error) {
|
|
616
|
+
return `[fict-plugin] ${context} (${file}): ${formatError(error)}`;
|
|
617
|
+
}
|
|
584
618
|
async function loadTypeScript() {
|
|
585
619
|
try {
|
|
586
620
|
const mod = await import("typescript");
|
|
587
|
-
|
|
621
|
+
const candidate = mod.default ?? mod;
|
|
622
|
+
return isTypeScriptApi(candidate) ? candidate : null;
|
|
588
623
|
} catch {
|
|
589
624
|
return null;
|
|
590
625
|
}
|
|
@@ -931,9 +966,14 @@ function extractAndRewriteHandlers(code, sourceModule) {
|
|
|
931
966
|
sourceType: "module",
|
|
932
967
|
plugins: ["jsx", "typescript"]
|
|
933
968
|
});
|
|
934
|
-
} catch (
|
|
935
|
-
|
|
936
|
-
|
|
969
|
+
} catch (error) {
|
|
970
|
+
throw new Error(
|
|
971
|
+
buildPluginMessage(
|
|
972
|
+
"Failed to parse transformed code for handler extraction",
|
|
973
|
+
sourceModule,
|
|
974
|
+
error
|
|
975
|
+
)
|
|
976
|
+
);
|
|
937
977
|
}
|
|
938
978
|
const topLevelDeclarations = /* @__PURE__ */ new Set();
|
|
939
979
|
const importedNames = /* @__PURE__ */ new Set();
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nimport { transformAsync } from '@babel/core'\nimport _generate from '@babel/generator'\nimport { parse } from '@babel/parser'\nimport _traverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\n// Handle ESM/CJS interop for Babel packages\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse\nconst generate = (\n typeof _generate === 'function' ? _generate : (_generate as { default: typeof _generate }).default\n) as typeof _generate\nimport { createFictPlugin, type FictCompilerOptions } from '@fictjs/compiler'\nimport type { Plugin, ResolvedConfig, TransformResult } from 'vite'\n\nexport interface FictPluginOptions extends FictCompilerOptions {\n /**\n * File patterns to include for transformation.\n * @default ['**\\/*.tsx', '**\\/*.jsx']\n */\n include?: string[]\n /**\n * File patterns to exclude from transformation.\n * @default ['**\\/node_modules\\/**']\n */\n exclude?: string[]\n /**\n * Transform cache settings (memory + optional persistent disk cache).\n * Set to false to disable caching entirely.\n */\n cache?:\n | boolean\n | {\n enabled?: boolean\n persistent?: boolean\n dir?: string\n }\n /**\n * Explicit tsconfig path for TypeScript project integration.\n * If omitted, the plugin will search from Vite root.\n */\n tsconfigPath?: string\n /**\n * Enable TypeScript project integration when TypeScript is available.\n * @default true\n */\n useTypeScriptProject?: boolean\n /**\n * Enable function-level code splitting for resumable handlers.\n * When enabled, event handlers and resume functions are extracted\n * to separate chunks for optimal lazy loading.\n * @default false for dev, true for production build\n */\n functionSplitting?: boolean\n}\n\ninterface NormalizedCacheOptions {\n enabled: boolean\n persistent: boolean\n dir?: string\n}\n\ninterface CachedTransform {\n code: string\n map: TransformResult['map']\n}\n\ninterface TypeScriptProject {\n configPath: string\n configHash: string\n readonly projectVersion: number\n updateFile: (fileName: string, code: string) => void\n getProgram: () => unknown | null\n resolveModuleName: (specifier: string, containingFile: string) => string | null\n dispose: () => void\n}\n\nconst CACHE_VERSION = 1\nconst MODULE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']\n\n// Virtual module prefix for extracted handlers\nconst VIRTUAL_HANDLER_PREFIX = '\\0fict-handler:'\nconst VIRTUAL_HANDLER_RESOLVE_PREFIX = 'virtual:fict-handler:'\n\n/**\n * Information about an extracted resumable handler\n */\ninterface ExtractedHandler {\n /** The module this handler was extracted from */\n sourceModule: string\n /** The export name in the source module */\n exportName: string\n /** Runtime helpers used by this handler */\n helpersUsed: string[]\n /** Local dependencies from source module that need to be re-exported */\n localDeps: string[]\n /** The handler function code (without export) */\n code: string\n}\n\n/**\n * Registry for extracted handlers during compilation\n */\nconst extractedHandlers = new Map<string, ExtractedHandler>()\n\n/**\n * Vite plugin for Fict reactive UI library.\n *\n * Transforms $state and $effect calls into reactive signals using the Fict compiler.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import fict from '@fictjs/vite-plugin'\n *\n * export default defineConfig({\n * plugins: [fict()],\n * })\n * ```\n */\nexport default function fict(options: FictPluginOptions = {}): Plugin {\n const {\n include = ['**/*.tsx', '**/*.jsx'],\n exclude = ['**/node_modules/**'],\n cache: cacheOption,\n tsconfigPath,\n useTypeScriptProject = true,\n ...compilerOptions\n } = options\n\n let config: ResolvedConfig | undefined\n let isDev = false\n let cache: TransformCache | null = null\n let tsProject: TypeScriptProject | null = null\n let tsProjectInit: Promise<TypeScriptProject | null> | null = null\n const moduleMetadata: FictCompilerOptions['moduleMetadata'] = new Map()\n\n const ensureCache = () => {\n if (cache) return cache\n const normalized = normalizeCacheOptions(cacheOption, config)\n cache = new TransformCache(normalized)\n return cache\n }\n\n const resetCache = () => {\n cache?.clear()\n cache = null\n }\n\n const ensureTypeScriptProject = async () => {\n if (!useTypeScriptProject) return null\n if (tsProject) return tsProject\n if (!tsProjectInit) {\n tsProjectInit = (async () => {\n const ts = await loadTypeScript()\n if (!ts) return null\n const rootDir = config?.root ?? process.cwd()\n const resolvedConfigPath = resolveTsconfigPath(ts, rootDir, tsconfigPath)\n if (!resolvedConfigPath) return null\n return createTypeScriptProject(ts, rootDir, resolvedConfigPath)\n })()\n }\n tsProject = await tsProjectInit\n return tsProject\n }\n\n const resetTypeScriptProject = () => {\n if (tsProject) {\n tsProject.dispose()\n }\n tsProject = null\n tsProjectInit = null\n }\n\n return {\n name: 'vite-plugin-fict',\n\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n config = resolvedConfig\n isDev = config.command === 'serve' || config.mode === 'development'\n // Rebuild cache with resolved config so cacheDir is available\n resetCache()\n // Clear extracted handlers from previous builds\n extractedHandlers.clear()\n },\n\n resolveId(id: string) {\n // Handle virtual handler modules\n if (id.startsWith(VIRTUAL_HANDLER_RESOLVE_PREFIX)) {\n return VIRTUAL_HANDLER_PREFIX + id.slice(VIRTUAL_HANDLER_RESOLVE_PREFIX.length)\n }\n return null\n },\n\n load(id: string) {\n // Load virtual handler modules\n if (!id.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n return null\n }\n\n const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length)\n console.log(`[fict-plugin] Loading virtual module: ${handlerId}`)\n console.log(\n `[fict-plugin] Registry has ${extractedHandlers.size} handlers:`,\n Array.from(extractedHandlers.keys()),\n )\n const handler = extractedHandlers.get(handlerId)\n if (handler) {\n const generatedCode = generateHandlerModule(handler)\n console.log(`[fict-plugin] Generated code length: ${generatedCode.length}`)\n console.log(`[fict-plugin] Generated code preview: ${generatedCode.slice(0, 200)}...`)\n return generatedCode\n }\n\n if (!handler) {\n // In dev mode or when splitting is disabled, the handler is still in the main module\n // Generate a re-export from the source module\n const [sourceModule, exportName] = parseHandlerId(handlerId)\n if (sourceModule && exportName) {\n return `export { ${exportName} as default } from '${sourceModule}'`\n }\n return null\n }\n\n // Generate the virtual module with the handler code\n return generateHandlerModule(handler)\n },\n\n config(userConfig, env) {\n const userOptimize = userConfig.optimizeDeps\n const hasUserOptimize = !!userOptimize\n const hasDisabledOptimize =\n hasUserOptimize && (userOptimize as { disabled?: boolean }).disabled === true\n\n const include = new Set(userOptimize?.include ?? [])\n const exclude = new Set(userOptimize?.exclude ?? [])\n const dedupe = new Set((userConfig.resolve?.dedupe ?? []) as string[])\n\n // Avoid duplicate runtime instances between pre-bundled deps and /@fs modules.\n // Exclude all workspace packages from prebundling to ensure changes take effect\n // immediately without requiring node_modules reinstall.\n const workspaceDeps = [\n 'fict',\n 'fict/plus',\n 'fict/advanced',\n 'fict/slim',\n 'fict/jsx-runtime',\n 'fict/jsx-dev-runtime',\n '@fictjs/runtime',\n '@fictjs/runtime/internal',\n '@fictjs/runtime/advanced',\n '@fictjs/runtime/jsx-runtime',\n '@fictjs/runtime/jsx-dev-runtime',\n '@fictjs/compiler',\n '@fictjs/devtools',\n '@fictjs/devtools/core',\n '@fictjs/devtools/vite',\n '@fictjs/router',\n '@fictjs/ssr',\n '@fictjs/testing-library',\n ]\n for (const dep of workspaceDeps) {\n include.delete(dep)\n exclude.add(dep)\n }\n // Only dedupe core runtime packages to avoid duplicate instances\n const dedupePackages = ['fict', '@fictjs/runtime', '@fictjs/runtime/internal']\n for (const dep of dedupePackages) {\n dedupe.add(dep)\n }\n\n // Determine if we're in dev mode based on command or mode\n const devMode = env.command === 'serve' || env.mode === 'development'\n\n return {\n // Define __DEV__ for runtime devtools support\n // In dev mode, enable devtools; in production, disable them for smaller bundles\n define: {\n __DEV__: String(devMode),\n ...(userConfig.define ?? {}),\n },\n esbuild: {\n // Disable esbuild JSX handling for .tsx/.jsx files\n // Our plugin will handle the full transformation\n include: /\\.(ts|js|mts|mjs|cjs)$/,\n },\n build: {\n rollupOptions: {\n // Preserve exports in entry chunks to prevent tree-shaking of handler exports\n preserveEntrySignatures: 'exports-only',\n },\n },\n resolve: {\n ...(userConfig.resolve ?? {}),\n dedupe: Array.from(dedupe),\n },\n // Watch workspace packages dist directories for changes in dev mode\n // This ensures HMR picks up rebuilt packages without needing to restart\n server: {\n watch: {\n ignored: ['!**/node_modules/@fictjs/**', '!**/node_modules/fict/**'],\n },\n },\n ...(hasDisabledOptimize\n ? { optimizeDeps: userOptimize }\n : {\n optimizeDeps: hasUserOptimize\n ? { ...userOptimize, include: Array.from(include), exclude: Array.from(exclude) }\n : { exclude: workspaceDeps },\n }),\n }\n },\n\n async transform(code: string, id: string): Promise<TransformResult | null> {\n const filename = stripQuery(id)\n\n // Skip non-matching files\n if (!shouldTransform(filename, include, exclude)) {\n return null\n }\n\n const aliasEntries = normalizeAliases(config?.resolve?.alias)\n const fictOptions: FictCompilerOptions = {\n ...compilerOptions,\n dev: compilerOptions.dev ?? isDev,\n sourcemap: compilerOptions.sourcemap ?? true,\n filename,\n moduleMetadata,\n resolveModuleMetadata: (source, importer) => {\n const userResolved = compilerOptions.resolveModuleMetadata?.(source, importer)\n if (userResolved) return userResolved\n if (!importer) return undefined\n\n const importerFile = normalizeFileName(importer, config?.root)\n const lookupMetadata = (resolved: string) => {\n const direct = moduleMetadata.get(resolved)\n if (direct) return direct\n const ext = path.extname(resolved)\n if (!ext) {\n for (const suffix of MODULE_EXTENSIONS) {\n const byExt = moduleMetadata.get(`${resolved}${suffix}`)\n if (byExt) return byExt\n }\n for (const suffix of MODULE_EXTENSIONS) {\n const byIndex = moduleMetadata.get(path.join(resolved, `index${suffix}`))\n if (byIndex) return byIndex\n }\n }\n return undefined\n }\n let resolvedSource: string | null = null\n\n if (path.isAbsolute(source)) {\n resolvedSource = normalizeFileName(source, config?.root)\n } else if (source.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), source),\n config?.root,\n )\n } else {\n const aliased = applyAlias(source, aliasEntries)\n if (aliased) {\n if (path.isAbsolute(aliased)) {\n resolvedSource = normalizeFileName(aliased, config?.root)\n } else if (aliased.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), aliased),\n config?.root,\n )\n } else if (config?.root) {\n resolvedSource = normalizeFileName(path.resolve(config.root, aliased), config?.root)\n }\n } else if (tsProject) {\n const tsResolved = tsProject.resolveModuleName(source, importerFile)\n if (tsResolved) {\n resolvedSource = normalizeFileName(tsResolved, config?.root)\n }\n }\n }\n\n if (!resolvedSource) return undefined\n return lookupMetadata(resolvedSource)\n },\n }\n\n const tsProject = await ensureTypeScriptProject()\n if (tsProject) {\n const resolvedName = normalizeFileName(filename, config?.root)\n tsProject.updateFile(resolvedName, code)\n const program = tsProject.getProgram()\n const checker =\n program && typeof (program as any).getTypeChecker === 'function'\n ? (program as any).getTypeChecker()\n : undefined\n fictOptions.typescript = {\n program: program ?? undefined,\n checker,\n projectVersion: tsProject.projectVersion,\n configPath: tsProject.configPath,\n }\n }\n\n const cacheStore = ensureCache()\n const cacheKey = cacheStore.enabled\n ? buildCacheKey(filename, code, fictOptions, tsProject)\n : null\n\n if (cacheKey) {\n const cached = await cacheStore.get(cacheKey)\n if (cached) {\n return cached\n }\n }\n\n try {\n const isTypeScript = filename.endsWith('.tsx') || filename.endsWith('.ts')\n\n const result = await transformAsync(code, {\n filename,\n sourceMaps: fictOptions.sourcemap,\n sourceFileName: filename,\n presets: isTypeScript\n ? [['@babel/preset-typescript', { isTSX: true, allExtensions: true }]]\n : [],\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [createFictPlugin, fictOptions],\n ],\n })\n\n if (!result || !result.code) {\n return null\n }\n\n let finalCode = result.code\n let finalMap = result.map as TransformResult['map']\n\n // Apply function-level code splitting in production builds\n // For SSR builds with resumable enabled, we also need to rewrite QRLs to virtual URLs\n // so they match the manifest generated by the client build\n const shouldSplit =\n options.functionSplitting ??\n (config?.command === 'build' && (compilerOptions.resumable || !config?.build?.ssr))\n\n console.log(\n `[fict-plugin] shouldSplit=${shouldSplit}, ssr=${config?.build?.ssr}, resumable=${compilerOptions.resumable}, file=${filename}`,\n )\n if (shouldSplit) {\n let splitResult: { code: string; handlers: string[] } | null = null\n try {\n splitResult = extractAndRewriteHandlers(finalCode, filename)\n } catch (e) {\n console.error('[fict-plugin] extractAndRewriteHandlers error:', e)\n }\n console.log(\n `[fict-plugin] splitResult: ${splitResult ? splitResult.handlers.length + ' handlers' : 'null'}`,\n )\n if (splitResult) {\n console.log(\n `[fict-plugin] Function splitting: ${filename} - ${splitResult.handlers.length} handlers extracted`,\n )\n finalCode = splitResult.code\n // Note: source maps are invalidated by this rewrite\n // For production builds, this is acceptable\n finalMap = null\n\n // Emit each extracted handler as a separate chunk for lazy loading\n // This ensures the virtual modules are included in the build\n if (config?.command === 'build' && !config?.build?.ssr) {\n for (const handlerName of splitResult.handlers) {\n const handlerId = createHandlerId(filename, handlerName)\n const virtualModuleId = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n this.emitFile({\n type: 'chunk',\n id: virtualModuleId,\n name: `handler-${handlerName}`,\n })\n }\n }\n }\n }\n\n const transformed: TransformResult = {\n code: finalCode,\n map: finalMap,\n }\n\n if (cacheKey) {\n await cacheStore.set(cacheKey, transformed)\n }\n\n return transformed\n } catch (error) {\n // Better error handling\n const message =\n error instanceof Error ? error.message : 'Unknown error during Fict transformation'\n\n this.error({\n message: `[fict] Transform failed for ${id}: ${message}`,\n id,\n })\n\n return null\n }\n },\n\n handleHotUpdate({ file, server }) {\n if (tsProject && file === tsProject.configPath) {\n resetTypeScriptProject()\n resetCache()\n }\n\n // Force full reload for .tsx/.jsx files to ensure reactive graph is rebuilt\n if (shouldTransform(file, include, exclude)) {\n server.ws.send({\n type: 'full-reload',\n path: '*',\n })\n }\n },\n\n generateBundle(_options, bundle) {\n if (!config || config.command !== 'build') return\n if (config.build.ssr) return\n\n const base = config.base ?? '/'\n const manifest: Record<string, string> = {}\n\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue\n const fileName = output.fileName\n const url = joinBasePath(base, fileName)\n for (const moduleId of Object.keys(output.modules)) {\n if (!moduleId) continue\n\n // Handle virtual handler modules\n if (moduleId.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n const handlerId = moduleId.slice(VIRTUAL_HANDLER_PREFIX.length)\n // Map the virtual module resolve prefix to the chunk URL\n const virtualKey = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n if (!manifest[virtualKey]) {\n manifest[virtualKey] = url\n }\n continue\n }\n\n // Skip other virtual modules\n if (moduleId.startsWith('\\0')) continue\n\n const normalized = normalizeFileName(moduleId, config.root)\n if (!path.isAbsolute(normalized)) continue\n const key = pathToFileURL(normalized).href\n if (!manifest[key]) {\n manifest[key] = url\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'fict.manifest.json',\n source: JSON.stringify(manifest),\n })\n },\n }\n}\n\n/**\n * Check if a file should be transformed based on include/exclude patterns\n */\nfunction shouldTransform(id: string, include: string[], exclude: string[]): boolean {\n // Normalize path separators\n const normalizedId = stripQuery(id).replace(/\\\\/g, '/')\n\n // Check exclude patterns first\n for (const pattern of exclude) {\n if (matchPattern(normalizedId, pattern)) {\n return false\n }\n }\n\n // Check include patterns\n for (const pattern of include) {\n if (matchPattern(normalizedId, pattern)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Simple glob pattern matching\n * Supports: **\\/*.ext, *.ext, exact matches\n */\nfunction matchPattern(id: string, pattern: string): boolean {\n // Exact match\n if (id === pattern) return true\n\n // Simple check: if pattern ends with extension like *.tsx, just check if file ends with it\n if (pattern.startsWith('**/') || pattern.startsWith('*')) {\n const ext = pattern.replace(/^\\*\\*?\\//, '')\n if (ext.startsWith('*')) {\n // **/*.tsx -> check if ends with .tsx\n const ending = ext.replace(/^\\*/, '')\n return id.endsWith(ending)\n }\n }\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\./g, '\\\\.') // Escape dots\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*') // * matches any non-slash\n\n const regex = new RegExp(`^${regexPattern}$`)\n return regex.test(id)\n}\n\n/**\n * Remove Vite query parameters (e.g. ?import, ?v=123) from an id\n */\nfunction stripQuery(id: string): string {\n const queryStart = id.indexOf('?')\n return queryStart === -1 ? id : id.slice(0, queryStart)\n}\n\nfunction normalizeCacheOptions(\n cacheOption: FictPluginOptions['cache'],\n config?: ResolvedConfig,\n): NormalizedCacheOptions {\n const defaultPersistent = config?.command === 'build'\n const defaultDir = config?.cacheDir ? path.join(config.cacheDir, 'fict') : undefined\n\n if (cacheOption === false) {\n return { enabled: false, persistent: false, dir: undefined }\n }\n\n if (cacheOption === true || cacheOption === undefined) {\n return { enabled: true, persistent: defaultPersistent, dir: defaultDir }\n }\n\n return {\n enabled: cacheOption.enabled ?? true,\n persistent: cacheOption.persistent ?? defaultPersistent,\n dir: cacheOption.dir ?? defaultDir,\n }\n}\n\nfunction normalizeFileName(id: string, root?: string): string {\n let clean = stripQuery(id)\n if (clean.startsWith('/@fs/')) {\n clean = clean.slice('/@fs/'.length)\n }\n if (clean.startsWith('file://')) {\n try {\n clean = fileURLToPath(clean)\n } catch {\n // fall through\n }\n }\n if (path.isAbsolute(clean)) return path.normalize(clean)\n if (root) return path.normalize(path.resolve(root, clean))\n return path.normalize(path.resolve(clean))\n}\n\nfunction joinBasePath(base: string, fileName: string): string {\n if (!base) return fileName\n if (base === '/') return `/${fileName}`\n const normalized = base.endsWith('/') ? base : `${base}/`\n return `${normalized}${fileName}`\n}\n\ninterface AliasEntry {\n find: string | RegExp\n replacement: string\n}\n\nfunction normalizeAliases(aliases: ResolvedConfig['resolve']['alias'] | undefined): AliasEntry[] {\n if (!aliases) return []\n if (Array.isArray(aliases)) {\n return aliases\n .map(alias => {\n if (!alias || !('find' in alias)) return null\n const replacement =\n typeof alias.replacement === 'string' ? alias.replacement : String(alias.replacement)\n return { find: alias.find, replacement } as AliasEntry\n })\n .filter((alias): alias is AliasEntry => !!alias)\n }\n return Object.entries(aliases).map(([find, replacement]) => ({\n find,\n replacement: typeof replacement === 'string' ? replacement : String(replacement),\n }))\n}\n\nfunction applyAlias(source: string, aliases: AliasEntry[]): string | null {\n for (const alias of aliases) {\n if (typeof alias.find === 'string') {\n if (source === alias.find || source.startsWith(`${alias.find}/`)) {\n return alias.replacement + source.slice(alias.find.length)\n }\n continue\n }\n if (alias.find instanceof RegExp && alias.find.test(source)) {\n return source.replace(alias.find, alias.replacement)\n }\n }\n return null\n}\n\nfunction hashString(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value)\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`\n }\n\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined && typeof v !== 'function')\n .sort(([a], [b]) => a.localeCompare(b))\n\n const body = entries\n .map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`)\n .join(',')\n\n return `{${body}}`\n}\n\nfunction normalizeOptionsForCache(options: FictCompilerOptions): Record<string, unknown> {\n const normalized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || typeof value === 'function') continue\n if (key === 'typescript') {\n const tsInfo = value as {\n projectVersion?: number\n configPath?: string\n }\n normalized.typescript = {\n projectVersion: tsInfo?.projectVersion,\n configPath: tsInfo?.configPath,\n }\n continue\n }\n normalized[key] = value\n }\n return normalized\n}\n\nfunction buildCacheKey(\n filename: string,\n code: string,\n options: FictCompilerOptions,\n tsProject: TypeScriptProject | null,\n): string {\n const codeHash = hashString(code)\n const optionsHash = hashString(stableStringify(normalizeOptionsForCache(options)))\n const tsKey = tsProject ? `${tsProject.configHash}:${tsProject.projectVersion}` : ''\n return hashString([CACHE_VERSION, filename, codeHash, optionsHash, tsKey].join('|'))\n}\n\nclass TransformCache {\n private memory = new Map<string, CachedTransform>()\n\n constructor(private options: NormalizedCacheOptions) {}\n\n get enabled(): boolean {\n return this.options.enabled\n }\n\n async get(key: string): Promise<CachedTransform | null> {\n if (!this.options.enabled) return null\n const cached = this.memory.get(key)\n if (cached) return cached\n\n if (!this.options.persistent || !this.options.dir) return null\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n const raw = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CachedTransform\n if (!parsed || typeof parsed.code !== 'string') return null\n this.memory.set(key, parsed)\n return parsed\n } catch {\n return null\n }\n }\n\n async set(key: string, value: CachedTransform): Promise<void> {\n if (!this.options.enabled) return\n this.memory.set(key, value)\n if (!this.options.persistent || !this.options.dir) return\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n await fs.mkdir(this.options.dir, { recursive: true })\n await fs.writeFile(filePath, JSON.stringify(value))\n } catch {\n // Ignore cache write failures\n }\n }\n\n clear(): void {\n this.memory.clear()\n }\n}\n\nasync function loadTypeScript(): Promise<any | null> {\n try {\n const mod = await import('typescript')\n return (mod as any).default ?? mod\n } catch {\n return null\n }\n}\n\nfunction resolveTsconfigPath(ts: any, rootDir: string, explicitPath?: string): string | null {\n if (explicitPath) {\n return path.resolve(rootDir, explicitPath)\n }\n return ts.findConfigFile(rootDir, ts.sys.fileExists, 'tsconfig.json') ?? null\n}\n\nasync function createTypeScriptProject(\n ts: any,\n rootDir: string,\n configPath: string,\n): Promise<TypeScriptProject | null> {\n const configText = ts.sys.readFile(configPath)\n if (!configText) return null\n const configHash = hashString(configText)\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n if (configFile.error) return null\n\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath))\n\n const fileSet = new Set<string>(parsed.fileNames.map((name: string) => path.normalize(name)))\n const fileVersions = new Map<string, number>()\n const fileHashes = new Map<string, string>()\n const fileCache = new Map<string, string>()\n let projectVersion = 0\n\n const normalizeName = (fileName: string) => normalizeFileName(fileName, rootDir)\n\n const serviceHost = {\n getScriptFileNames: () => Array.from(fileSet),\n getScriptVersion: (fileName: string) => {\n const normalized = normalizeName(fileName)\n return String(fileVersions.get(normalized) ?? 0)\n },\n getScriptSnapshot: (fileName: string) => {\n const normalized = normalizeName(fileName)\n const text = fileCache.get(normalized) ?? ts.sys.readFile(normalized)\n if (text === undefined) return undefined\n return ts.ScriptSnapshot.fromString(text)\n },\n getCurrentDirectory: () => rootDir,\n getCompilationSettings: () => parsed.options,\n getDefaultLibFileName: (options: unknown) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getNewLine: () => ts.sys.newLine,\n getProjectVersion: () => String(projectVersion),\n }\n\n const service = ts.createLanguageService(serviceHost, ts.createDocumentRegistry())\n\n const updateFile = (fileName: string, code: string) => {\n const normalized = normalizeName(fileName)\n const nextHash = hashString(code)\n if (fileHashes.get(normalized) === nextHash) return\n fileHashes.set(normalized, nextHash)\n fileCache.set(normalized, code)\n fileVersions.set(normalized, (fileVersions.get(normalized) ?? 0) + 1)\n fileSet.add(normalized)\n projectVersion += 1\n }\n\n return {\n configPath,\n configHash,\n get projectVersion() {\n return projectVersion\n },\n updateFile,\n getProgram: () => service.getProgram?.() ?? null,\n resolveModuleName: (specifier: string, containingFile: string) => {\n try {\n const resolved = ts.resolveModuleName(specifier, containingFile, parsed.options, ts.sys)\n return resolved?.resolvedModule?.resolvedFileName ?? null\n } catch {\n return null\n }\n },\n dispose: () => service.dispose?.(),\n }\n}\n\n// ============================================================================\n// Function-level Code Splitting Helpers\n// ============================================================================\n\n/**\n * Parse a handler ID into source module and export name.\n * Format: /path/to/module.tsx$$exportName (using $$ as separator to avoid URL fragment conflicts)\n */\nfunction parseHandlerId(handlerId: string): [string | null, string | null] {\n const separatorIndex = handlerId.lastIndexOf('$$')\n if (separatorIndex === -1) {\n return [handlerId, 'default']\n }\n return [handlerId.slice(0, separatorIndex), handlerId.slice(separatorIndex + 2)]\n}\n\n/**\n * Generate handler ID from source module and export name.\n * Uses $$ as separator to avoid conflicts with URL # fragments.\n */\nfunction createHandlerId(sourceModule: string, exportName: string): string {\n return `${sourceModule}$$${exportName}`\n}\n\n/**\n * Generate a standalone virtual module for an extracted handler.\n * The module contains the complete handler code with its own imports,\n * creating a truly independent chunk that doesn't depend on the source module.\n */\nfunction generateHandlerModule(handler: ExtractedHandler): string {\n // If no code was extracted (fallback case), use re-export\n if (!handler.code) {\n return `export { ${handler.exportName} as default } from '${handler.sourceModule}';\\n`\n }\n\n // Group imports by source module\n const importsByModule = new Map<string, string[]>()\n\n for (const helperName of handler.helpersUsed) {\n const helper = RUNTIME_HELPERS[helperName]\n if (!helper) continue\n\n const existing = importsByModule.get(helper.from) ?? []\n if (!existing.includes(helper.import)) {\n existing.push(helper.import)\n }\n importsByModule.set(helper.from, existing)\n }\n\n // Generate import statements for runtime helpers\n const imports: string[] = []\n for (const [module, names] of importsByModule) {\n imports.push(`import { ${names.join(', ')} } from '${module}';`)\n }\n\n // Import local dependencies from the source module\n // These are re-exported by the source module with __fict_dep_ prefix\n if (handler.localDeps.length > 0) {\n const depImports = handler.localDeps.map(dep => `${HANDLER_DEP_PREFIX}${dep} as ${dep}`)\n imports.push(`import { ${depImports.join(', ')} } from '${handler.sourceModule}';`)\n }\n\n // Generate the complete standalone module\n return `${imports.join('\\n')}${imports.length > 0 ? '\\n\\n' : ''}export default ${handler.code};\\n`\n}\n\n/** Prefix for re-exported handler dependencies */\nconst HANDLER_DEP_PREFIX = '__fict_dep_'\n\n/**\n * Register an extracted handler for function-level splitting.\n */\nexport function registerExtractedHandler(\n sourceModule: string,\n exportName: string,\n helpersUsed: string[],\n code: string,\n localDeps: string[] = [],\n): string {\n const handlerId = createHandlerId(sourceModule, exportName)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName,\n helpersUsed,\n localDeps,\n code,\n })\n return `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n}\n\n/**\n * Runtime helper name mappings for generating imports in virtual modules\n */\nconst RUNTIME_HELPERS: Record<string, { import: string; from: string }> = {\n __fictUseLexicalScope: { import: '__fictUseLexicalScope', from: '@fictjs/runtime/internal' },\n __fictGetScopeProps: { import: '__fictGetScopeProps', from: '@fictjs/runtime/internal' },\n __fictGetSSRScope: { import: '__fictGetSSRScope', from: '@fictjs/runtime/internal' },\n __fictEnsureScope: { import: '__fictEnsureScope', from: '@fictjs/runtime/internal' },\n __fictPrepareContext: { import: '__fictPrepareContext', from: '@fictjs/runtime/internal' },\n __fictPushContext: { import: '__fictPushContext', from: '@fictjs/runtime/internal' },\n __fictPopContext: { import: '__fictPopContext', from: '@fictjs/runtime/internal' },\n hydrateComponent: { import: 'hydrateComponent', from: '@fictjs/runtime/internal' },\n __fictQrl: { import: '__fictQrl', from: '@fictjs/runtime/internal' },\n}\n\n/** Known global identifiers that don't need to be imported */\nconst GLOBAL_IDENTIFIERS = new Set([\n // JavaScript globals\n 'undefined',\n 'null',\n 'true',\n 'false',\n 'NaN',\n 'Infinity',\n 'globalThis',\n 'window',\n 'document',\n 'console',\n 'setTimeout',\n 'setInterval',\n 'clearTimeout',\n 'clearInterval',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'fetch',\n 'URL',\n 'URLSearchParams',\n 'FormData',\n 'Headers',\n 'Request',\n 'Response',\n 'AbortController',\n 'AbortSignal',\n // Built-in constructors\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Symbol',\n 'BigInt',\n 'Date',\n 'RegExp',\n 'Error',\n 'TypeError',\n 'RangeError',\n 'SyntaxError',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Proxy',\n 'Reflect',\n 'JSON',\n 'Math',\n 'Intl',\n // Event and DOM\n 'Event',\n 'CustomEvent',\n 'Element',\n 'Node',\n 'HTMLElement',\n])\n\n/**\n * Collect identifiers referenced in an AST node that are not locally defined.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectReferencedIdentifiers(node: t.Node, localBindings: Set<string>): Set<string> {\n const referenced = new Set<string>()\n\n function visitNode(\n current: t.Node | null | undefined,\n parent: t.Node | null,\n key: string | null,\n ): void {\n if (!current) return\n\n if (t.isIdentifier(current)) {\n const name = current.name\n\n // Skip if it's a property access (obj.prop) - only the object is a reference\n if (\n parent &&\n t.isMemberExpression(parent) &&\n parent.property === current &&\n !parent.computed\n ) {\n return\n }\n\n // Skip if it's a key in object property (non-computed)\n if (parent && t.isObjectProperty(parent) && parent.key === current && !parent.computed) {\n return\n }\n\n // Skip if it's a function/variable declaration name\n if (parent && t.isVariableDeclarator(parent) && parent.id === current) {\n return\n }\n if (\n parent &&\n (t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&\n parent.id === current\n ) {\n return\n }\n\n // Skip if it's a parameter\n if (key === 'params') {\n return\n }\n\n // Skip if it's a catch clause parameter\n if (parent && t.isCatchClause(parent) && parent.param === current) {\n return\n }\n\n // Skip local bindings (locally declared variables)\n if (localBindings.has(name)) {\n return\n }\n\n // Skip globals\n if (GLOBAL_IDENTIFIERS.has(name)) {\n return\n }\n\n // Skip runtime helpers\n if (RUNTIME_HELPERS[name]) {\n return\n }\n\n referenced.add(name)\n return\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node, current, nodeKey)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node, current, nodeKey)\n }\n }\n }\n\n visitNode(node, null, null)\n return referenced\n}\n\n/**\n * Collect all bindings (variables, functions, params) defined within an AST node.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectLocalBindings(node: t.Node): Set<string> {\n const bindings = new Set<string>()\n\n function visitNode(current: t.Node | null | undefined): void {\n if (!current) return\n\n // Handle variable declarations\n if (t.isVariableDeclarator(current)) {\n if (t.isIdentifier(current.id)) {\n bindings.add(current.id.name)\n } else if (t.isObjectPattern(current.id) || t.isArrayPattern(current.id)) {\n const names = collectPatternIdentifiers(current.id)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function declarations\n if (t.isFunctionDeclaration(current)) {\n if (current.id) {\n bindings.add(current.id.name)\n }\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function expressions\n if (t.isFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle arrow function expressions\n if (t.isArrowFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle catch clauses\n if (t.isCatchClause(current)) {\n if (current.param && t.isIdentifier(current.param)) {\n bindings.add(current.param.name)\n }\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node)\n }\n }\n }\n\n visitNode(node)\n\n return bindings\n}\n\n/**\n * Collect identifier names from a pattern (for destructuring).\n */\nfunction collectPatternIdentifiers(pattern: t.LVal | t.PatternLike): string[] {\n const names: string[] = []\n\n if (t.isIdentifier(pattern)) {\n names.push(pattern.name)\n } else if (t.isObjectPattern(pattern)) {\n for (const prop of pattern.properties) {\n if (t.isObjectProperty(prop) && t.isLVal(prop.value)) {\n names.push(...collectPatternIdentifiers(prop.value))\n } else if (t.isRestElement(prop)) {\n names.push(...collectPatternIdentifiers(prop.argument))\n }\n }\n } else if (t.isArrayPattern(pattern)) {\n for (const element of pattern.elements) {\n if (element) {\n names.push(...collectPatternIdentifiers(element))\n }\n }\n } else if (t.isRestElement(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.argument))\n } else if (t.isAssignmentPattern(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.left))\n }\n\n return names\n}\n\n/**\n * Extract handlers using Babel AST and rewrite QRLs to use virtual modules.\n * This creates truly independent chunks for each handler.\n * Local dependencies are detected and re-exported for handlers to import.\n */\nfunction extractAndRewriteHandlers(\n code: string,\n sourceModule: string,\n): { code: string; handlers: string[] } | null {\n let ast: ReturnType<typeof parse>\n\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n })\n } catch (e) {\n // If parsing fails, fall back to no extraction\n console.error('[fict-plugin] Parse error in extractAndRewriteHandlers:', e)\n return null\n }\n\n // Collect all top-level declarations that could be referenced by handlers\n const topLevelDeclarations = new Set<string>()\n const importedNames = new Set<string>()\n\n for (const node of ast.program.body) {\n // Collect imports\n if (t.isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n } else if (t.isImportNamespaceSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n }\n }\n continue\n }\n\n // Collect function declarations\n if (t.isFunctionDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect variable declarations\n if (t.isVariableDeclaration(node)) {\n for (const declarator of node.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n continue\n }\n\n // Collect class declarations\n if (t.isClassDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect exported declarations\n if (t.isExportNamedDeclaration(node) && node.declaration) {\n if (t.isFunctionDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n } else if (t.isVariableDeclaration(node.declaration)) {\n for (const declarator of node.declaration.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n } else if (t.isClassDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n }\n }\n }\n\n // Merge imports into top-level declarations (they're also available at top level)\n for (const name of importedNames) {\n topLevelDeclarations.add(name)\n }\n\n const handlerNames: string[] = []\n const nodesToRemove = new Set<t.Node>()\n const allLocalDeps = new Set<string>()\n\n // First pass: find all handler exports and extract their code\n traverse(ast, {\n ExportNamedDeclaration(path) {\n const declaration = path.node.declaration\n\n // Handle: export const __fict_e0 = (scopeId, event, el) => { ... }\n if (t.isVariableDeclaration(declaration)) {\n for (const declarator of declaration.declarations) {\n if (!t.isIdentifier(declarator.id)) continue\n\n const name = declarator.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) continue\n\n if (!declarator.init) continue\n\n handlerNames.push(name)\n\n // Generate the handler function code\n const handlerCode = generate(declarator.init).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(declarator.init)\n const referencedIds = collectReferencedIdentifiers(declarator.init, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n return\n }\n\n // Handle: export function __fict_e0(scopeId, event, el) { ... }\n if (t.isFunctionDeclaration(declaration) && declaration.id) {\n const name = declaration.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) return\n\n handlerNames.push(name)\n\n // Convert to arrow function expression for the virtual module\n const params = declaration.params\n const body = declaration.body\n const arrowFn = t.arrowFunctionExpression(params, body, declaration.async)\n\n // Generate the handler function code\n const handlerCode = generate(arrowFn).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(arrowFn)\n const referencedIds = collectReferencedIdentifiers(arrowFn, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n },\n })\n\n if (handlerNames.length === 0) {\n return null\n }\n\n // Second pass: remove handler exports, rewrite QRL calls, and add re-exports for dependencies\n traverse(ast, {\n ExportNamedDeclaration(path) {\n if (nodesToRemove.has(path.node)) {\n path.remove()\n }\n },\n\n CallExpression(path) {\n // Rewrite __fictQrl(import.meta.url, \"__fict_e0\") -> \"virtual:...\"\n if (!t.isIdentifier(path.node.callee, { name: '__fictQrl' })) return\n if (path.node.arguments.length !== 2) return\n\n const secondArg = path.node.arguments[1]\n if (!t.isStringLiteral(secondArg)) return\n\n const handlerName = secondArg.value\n if (!handlerNames.includes(handlerName)) return\n\n // Replace with the virtual module URL\n const handlerId = createHandlerId(sourceModule, handlerName)\n const virtualUrl = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}#default`\n path.replaceWith(t.stringLiteral(virtualUrl))\n },\n })\n\n // Add re-exports for local dependencies used by handlers\n // This allows handlers to import them from the source module\n if (allLocalDeps.size > 0) {\n const reExports: t.ExportSpecifier[] = []\n for (const dep of allLocalDeps) {\n // Export as __fict_dep_<name> to avoid conflicts\n reExports.push(\n t.exportSpecifier(t.identifier(dep), t.identifier(`${HANDLER_DEP_PREFIX}${dep}`)),\n )\n }\n ast.program.body.push(t.exportNamedDeclaration(null, reExports))\n }\n\n // Generate the modified code\n const result = generate(ast, {\n retainLines: true,\n compact: false,\n })\n\n return { code: result.code, handlers: handlerNames }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA2B;AAC3B,qBAA+B;AAC/B,uBAAiB;AACjB,sBAA6C;AAE7C,kBAA+B;AAC/B,uBAAsB;AACtB,oBAAsB;AACtB,sBAAsB;AACtB,QAAmB;AASnB,sBAA2D;AAN3D,IAAM,WACJ,OAAO,gBAAAA,YAAc,aAAa,gBAAAA,UAAa,gBAAAA,QAA4C;AAE7F,IAAM,WACJ,OAAO,iBAAAC,YAAc,aAAa,iBAAAA,UAAa,iBAAAA,QAA4C;AAmE7F,IAAM,gBAAgB;AACtB,IAAM,oBAAoB,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,MAAM;AAGvF,IAAM,yBAAyB;AAC/B,IAAM,iCAAiC;AAqBvC,IAAM,oBAAoB,oBAAI,IAA8B;AAkB7C,SAAR,KAA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AAa;AAAA,IACb,SAAS;AAAA,EACX,CAAC;AAED,SAAO,EAAE,MAAM,OAAO,MAAM,UAAU,aAAa;AACrD;","names":["_traverse","_generate","include","exclude","path","tsProject","fs","module"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nimport { transformAsync } from '@babel/core'\nimport _generate from '@babel/generator'\nimport { parse } from '@babel/parser'\nimport _traverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { createFictPlugin, type FictCompilerOptions } from '@fictjs/compiler'\nimport type { Plugin, ResolvedConfig, TransformResult } from 'vite'\n\n// Handle ESM/CJS interop for Babel packages\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse\nconst generate = (\n typeof _generate === 'function' ? _generate : (_generate as { default: typeof _generate }).default\n) as typeof _generate\n\nexport interface FictPluginOptions extends FictCompilerOptions {\n /**\n * File patterns to include for transformation.\n * @default ['**\\/*.tsx', '**\\/*.jsx']\n */\n include?: string[]\n /**\n * File patterns to exclude from transformation.\n * @default ['**\\/node_modules\\/**']\n */\n exclude?: string[]\n /**\n * Transform cache settings (memory + optional persistent disk cache).\n * Set to false to disable caching entirely.\n */\n cache?:\n | boolean\n | {\n enabled?: boolean\n persistent?: boolean\n dir?: string\n }\n /**\n * Explicit tsconfig path for TypeScript project integration.\n * If omitted, the plugin will search from Vite root.\n */\n tsconfigPath?: string\n /**\n * Enable TypeScript project integration when TypeScript is available.\n * @default true\n */\n useTypeScriptProject?: boolean\n /**\n * Enable function-level code splitting for resumable handlers.\n * When enabled, event handlers and resume functions are extracted\n * to separate chunks for optimal lazy loading.\n * @default false for dev, true for production build\n */\n functionSplitting?: boolean\n /**\n * Enable verbose debug logs from the plugin.\n * Can also be enabled via `FICT_VITE_PLUGIN_DEBUG=1`.\n * @default false\n */\n debug?: boolean\n}\n\ninterface NormalizedCacheOptions {\n enabled: boolean\n persistent: boolean\n dir?: string\n}\n\ninterface CachedTransform {\n code: string\n map: TransformResult['map']\n}\n\ninterface TypeScriptProject {\n configPath: string\n configHash: string\n readonly projectVersion: number\n updateFile: (fileName: string, code: string) => void\n getProgram: () => TypeScriptProgram | null\n resolveModuleName: (specifier: string, containingFile: string) => string | null\n dispose: () => void\n}\n\ninterface TypeScriptProgram {\n getTypeChecker?: () => unknown\n}\n\ninterface TypeScriptSystem {\n fileExists: (path: string) => boolean\n readFile: (path: string) => string | undefined\n readDirectory: (...args: unknown[]) => string[]\n directoryExists?: (path: string) => boolean\n getDirectories?: (path: string) => string[]\n useCaseSensitiveFileNames: boolean\n newLine: string\n}\n\ninterface TypeScriptParsedConfig {\n fileNames: string[]\n options: unknown\n}\n\ninterface TypeScriptLanguageService {\n getProgram?: () => TypeScriptProgram | null\n dispose?: () => void\n}\n\ninterface TypeScriptLanguageServiceHost {\n getScriptFileNames: () => string[]\n getScriptVersion: (fileName: string) => string\n getScriptSnapshot: (fileName: string) => unknown\n getCurrentDirectory: () => string\n getCompilationSettings: () => unknown\n getDefaultLibFileName: (options: unknown) => string\n fileExists: TypeScriptSystem['fileExists']\n readFile: TypeScriptSystem['readFile']\n readDirectory: TypeScriptSystem['readDirectory']\n directoryExists?: TypeScriptSystem['directoryExists']\n getDirectories?: TypeScriptSystem['getDirectories']\n useCaseSensitiveFileNames: () => boolean\n getNewLine: () => string\n getProjectVersion: () => string\n}\n\ninterface TypeScriptApi {\n sys: TypeScriptSystem\n findConfigFile: (\n searchPath: string,\n fileExists: TypeScriptSystem['fileExists'],\n configName: string,\n ) => string | undefined\n readConfigFile: (\n configPath: string,\n readFile: TypeScriptSystem['readFile'],\n ) => { config: unknown; error?: unknown }\n parseJsonConfigFileContent: (\n config: unknown,\n host: TypeScriptSystem,\n basePath: string,\n ) => TypeScriptParsedConfig\n ScriptSnapshot: {\n fromString: (text: string) => unknown\n }\n getDefaultLibFilePath: (options: unknown) => string\n createLanguageService: (\n host: TypeScriptLanguageServiceHost,\n registry: unknown,\n ) => TypeScriptLanguageService\n createDocumentRegistry: () => unknown\n resolveModuleName: (\n specifier: string,\n containingFile: string,\n options: unknown,\n host: TypeScriptSystem,\n ) => { resolvedModule?: { resolvedFileName?: string } } | undefined\n}\n\nconst CACHE_VERSION = 1\nconst MODULE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']\n\n// Virtual module prefix for extracted handlers\nconst VIRTUAL_HANDLER_PREFIX = '\\0fict-handler:'\nconst VIRTUAL_HANDLER_RESOLVE_PREFIX = 'virtual:fict-handler:'\n\n/**\n * Information about an extracted resumable handler\n */\ninterface ExtractedHandler {\n /** The module this handler was extracted from */\n sourceModule: string\n /** The export name in the source module */\n exportName: string\n /** Runtime helpers used by this handler */\n helpersUsed: string[]\n /** Local dependencies from source module that need to be re-exported */\n localDeps: string[]\n /** The handler function code (without export) */\n code: string\n}\n\n/**\n * Registry for extracted handlers during compilation\n */\nconst extractedHandlers = new Map<string, ExtractedHandler>()\n\n/**\n * Vite plugin for Fict reactive UI library.\n *\n * Transforms $state and $effect calls into reactive signals using the Fict compiler.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import fict from '@fictjs/vite-plugin'\n *\n * export default defineConfig({\n * plugins: [fict()],\n * })\n * ```\n */\nexport default function fict(options: FictPluginOptions = {}): Plugin {\n const {\n include = ['**/*.tsx', '**/*.jsx'],\n exclude = ['**/node_modules/**'],\n cache: cacheOption,\n tsconfigPath,\n useTypeScriptProject = true,\n debug: debugOption,\n ...compilerOptions\n } = options\n\n let config: ResolvedConfig | undefined\n let isDev = false\n let cache: TransformCache | null = null\n let tsProject: TypeScriptProject | null = null\n let tsProjectInit: Promise<TypeScriptProject | null> | null = null\n const moduleMetadata: FictCompilerOptions['moduleMetadata'] = new Map()\n const debugEnabled =\n debugOption === true ||\n process.env.FICT_VITE_PLUGIN_DEBUG === '1' ||\n process.env.FICT_VITE_PLUGIN_DEBUG === 'true'\n\n const debugLog = (message: string, details?: unknown) => {\n if (!debugEnabled) return\n const payload = details === undefined ? '' : ` ${safeDebugString(details)}`\n config?.logger?.info(`[fict-plugin] ${message}${payload}`)\n }\n\n const ensureCache = () => {\n if (cache) return cache\n const normalized = normalizeCacheOptions(cacheOption, config)\n cache = new TransformCache(normalized)\n return cache\n }\n\n const resetCache = () => {\n cache?.clear()\n cache = null\n }\n\n const ensureTypeScriptProject = async () => {\n if (!useTypeScriptProject) return null\n if (tsProject) return tsProject\n if (!tsProjectInit) {\n tsProjectInit = (async () => {\n const ts = await loadTypeScript()\n if (!ts) return null\n const rootDir = config?.root ?? process.cwd()\n const resolvedConfigPath = resolveTsconfigPath(ts, rootDir, tsconfigPath)\n if (!resolvedConfigPath) return null\n return createTypeScriptProject(ts, rootDir, resolvedConfigPath)\n })()\n }\n tsProject = await tsProjectInit\n return tsProject\n }\n\n const resetTypeScriptProject = () => {\n if (tsProject) {\n tsProject.dispose()\n }\n tsProject = null\n tsProjectInit = null\n }\n\n return {\n name: 'vite-plugin-fict',\n\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n config = resolvedConfig\n isDev = config.command === 'serve' || config.mode === 'development'\n // Rebuild cache with resolved config so cacheDir is available\n resetCache()\n // Clear extracted handlers from previous builds\n extractedHandlers.clear()\n },\n\n resolveId(id: string) {\n // Handle virtual handler modules\n if (id.startsWith(VIRTUAL_HANDLER_RESOLVE_PREFIX)) {\n return VIRTUAL_HANDLER_PREFIX + id.slice(VIRTUAL_HANDLER_RESOLVE_PREFIX.length)\n }\n return null\n },\n\n load(id: string) {\n // Load virtual handler modules\n if (!id.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n return null\n }\n\n const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length)\n debugLog(`Loading virtual module: ${handlerId}`, {\n registrySize: extractedHandlers.size,\n handlers: Array.from(extractedHandlers.keys()),\n })\n const handler = extractedHandlers.get(handlerId)\n if (handler) {\n const generatedCode = generateHandlerModule(handler)\n debugLog(`Generated virtual module (${generatedCode.length} chars)`, {\n preview: generatedCode.slice(0, 200),\n })\n return generatedCode\n }\n\n if (!handler) {\n // In dev mode or when splitting is disabled, the handler is still in the main module\n // Generate a re-export from the source module\n const [sourceModule, exportName] = parseHandlerId(handlerId)\n if (sourceModule && exportName) {\n return `export { ${exportName} as default } from '${sourceModule}'`\n }\n return null\n }\n\n // Generate the virtual module with the handler code\n return generateHandlerModule(handler)\n },\n\n config(userConfig, env) {\n const userOptimize = userConfig.optimizeDeps\n const hasUserOptimize = !!userOptimize\n const hasDisabledOptimize =\n hasUserOptimize && (userOptimize as { disabled?: boolean }).disabled === true\n\n const include = new Set(userOptimize?.include ?? [])\n const exclude = new Set(userOptimize?.exclude ?? [])\n const dedupe = new Set((userConfig.resolve?.dedupe ?? []) as string[])\n\n // Avoid duplicate runtime instances between pre-bundled deps and /@fs modules.\n // Exclude all workspace packages from prebundling to ensure changes take effect\n // immediately without requiring node_modules reinstall.\n const workspaceDeps = [\n 'fict',\n 'fict/plus',\n 'fict/advanced',\n 'fict/slim',\n 'fict/jsx-runtime',\n 'fict/jsx-dev-runtime',\n '@fictjs/runtime',\n '@fictjs/runtime/internal',\n '@fictjs/runtime/advanced',\n '@fictjs/runtime/jsx-runtime',\n '@fictjs/runtime/jsx-dev-runtime',\n '@fictjs/compiler',\n '@fictjs/devtools',\n '@fictjs/devtools/core',\n '@fictjs/devtools/vite',\n '@fictjs/router',\n '@fictjs/ssr',\n '@fictjs/testing-library',\n ]\n for (const dep of workspaceDeps) {\n include.delete(dep)\n exclude.add(dep)\n }\n // Only dedupe core runtime packages to avoid duplicate instances\n const dedupePackages = ['fict', '@fictjs/runtime', '@fictjs/runtime/internal']\n for (const dep of dedupePackages) {\n dedupe.add(dep)\n }\n\n // Determine if we're in dev mode based on command or mode\n const devMode = env.command === 'serve' || env.mode === 'development'\n\n return {\n // Define __DEV__ for runtime devtools support\n // In dev mode, enable devtools; in production, disable them for smaller bundles\n define: {\n __DEV__: String(devMode),\n ...(userConfig.define ?? {}),\n },\n esbuild: {\n // Disable esbuild JSX handling for .tsx/.jsx files\n // Our plugin will handle the full transformation\n include: /\\.(ts|js|mts|mjs|cjs)$/,\n },\n build: {\n rollupOptions: {\n // Preserve exports in entry chunks to prevent tree-shaking of handler exports\n preserveEntrySignatures: 'exports-only',\n },\n },\n resolve: {\n ...(userConfig.resolve ?? {}),\n dedupe: Array.from(dedupe),\n },\n // Watch workspace packages dist directories for changes in dev mode\n // This ensures HMR picks up rebuilt packages without needing to restart\n server: {\n watch: {\n ignored: ['!**/node_modules/@fictjs/**', '!**/node_modules/fict/**'],\n },\n },\n ...(hasDisabledOptimize\n ? { optimizeDeps: userOptimize }\n : {\n optimizeDeps: hasUserOptimize\n ? { ...userOptimize, include: Array.from(include), exclude: Array.from(exclude) }\n : { exclude: workspaceDeps },\n }),\n }\n },\n\n async transform(code: string, id: string): Promise<TransformResult | null> {\n const filename = stripQuery(id)\n\n // Skip non-matching files\n if (!shouldTransform(filename, include, exclude)) {\n return null\n }\n\n const aliasEntries = normalizeAliases(config?.resolve?.alias)\n const fictOptions: FictCompilerOptions = {\n ...compilerOptions,\n dev: compilerOptions.dev ?? isDev,\n sourcemap: compilerOptions.sourcemap ?? true,\n filename,\n moduleMetadata,\n resolveModuleMetadata: (source, importer) => {\n const userResolved = compilerOptions.resolveModuleMetadata?.(source, importer)\n if (userResolved) return userResolved\n if (!importer) return undefined\n\n const importerFile = normalizeFileName(importer, config?.root)\n const lookupMetadata = (resolved: string) => {\n const direct = moduleMetadata.get(resolved)\n if (direct) return direct\n const ext = path.extname(resolved)\n if (!ext) {\n for (const suffix of MODULE_EXTENSIONS) {\n const byExt = moduleMetadata.get(`${resolved}${suffix}`)\n if (byExt) return byExt\n }\n for (const suffix of MODULE_EXTENSIONS) {\n const byIndex = moduleMetadata.get(path.join(resolved, `index${suffix}`))\n if (byIndex) return byIndex\n }\n }\n return undefined\n }\n let resolvedSource: string | null = null\n\n if (path.isAbsolute(source)) {\n resolvedSource = normalizeFileName(source, config?.root)\n } else if (source.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), source),\n config?.root,\n )\n } else {\n const aliased = applyAlias(source, aliasEntries)\n if (aliased) {\n if (path.isAbsolute(aliased)) {\n resolvedSource = normalizeFileName(aliased, config?.root)\n } else if (aliased.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), aliased),\n config?.root,\n )\n } else if (config?.root) {\n resolvedSource = normalizeFileName(path.resolve(config.root, aliased), config?.root)\n }\n } else if (tsProject) {\n const tsResolved = tsProject.resolveModuleName(source, importerFile)\n if (tsResolved) {\n resolvedSource = normalizeFileName(tsResolved, config?.root)\n }\n }\n }\n\n if (!resolvedSource) return undefined\n return lookupMetadata(resolvedSource)\n },\n }\n\n const tsProject = await ensureTypeScriptProject()\n if (tsProject) {\n const resolvedName = normalizeFileName(filename, config?.root)\n tsProject.updateFile(resolvedName, code)\n const program = tsProject.getProgram()\n const checker =\n program && typeof program.getTypeChecker === 'function'\n ? program.getTypeChecker()\n : undefined\n fictOptions.typescript = {\n program: program ?? undefined,\n checker,\n projectVersion: tsProject.projectVersion,\n configPath: tsProject.configPath,\n }\n }\n\n const cacheStore = ensureCache()\n const cacheKey = cacheStore.enabled\n ? buildCacheKey(filename, code, fictOptions, tsProject)\n : null\n\n if (cacheKey) {\n const cached = await cacheStore.get(cacheKey)\n if (cached) {\n return cached\n }\n }\n\n try {\n const isTypeScript = filename.endsWith('.tsx') || filename.endsWith('.ts')\n\n const result = await transformAsync(code, {\n filename,\n sourceMaps: fictOptions.sourcemap,\n sourceFileName: filename,\n presets: isTypeScript\n ? [['@babel/preset-typescript', { isTSX: true, allExtensions: true }]]\n : [],\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [createFictPlugin, fictOptions],\n ],\n })\n\n if (!result || !result.code) {\n return null\n }\n\n let finalCode = result.code\n let finalMap = result.map as TransformResult['map']\n\n // Apply function-level code splitting in production builds\n // For SSR builds with resumable enabled, we also need to rewrite QRLs to virtual URLs\n // so they match the manifest generated by the client build\n const shouldSplit =\n options.functionSplitting ??\n (config?.command === 'build' && (compilerOptions.resumable || !config?.build?.ssr))\n\n debugLog('Function split decision', {\n shouldSplit,\n ssr: config?.build?.ssr,\n resumable: compilerOptions.resumable,\n file: filename,\n })\n if (shouldSplit) {\n let splitResult: { code: string; handlers: string[] } | null = null\n try {\n splitResult = extractAndRewriteHandlers(finalCode, filename)\n } catch (error) {\n this.warn(buildPluginMessage('extractAndRewriteHandlers failed', filename, error))\n }\n debugLog('Split result', {\n file: filename,\n handlers: splitResult?.handlers.length ?? 0,\n })\n if (splitResult) {\n debugLog(`Function splitting extracted ${splitResult.handlers.length} handlers`, {\n file: filename,\n })\n finalCode = splitResult.code\n // Note: source maps are invalidated by this rewrite\n // For production builds, this is acceptable\n finalMap = null\n\n // Emit each extracted handler as a separate chunk for lazy loading\n // This ensures the virtual modules are included in the build\n if (config?.command === 'build' && !config?.build?.ssr) {\n for (const handlerName of splitResult.handlers) {\n const handlerId = createHandlerId(filename, handlerName)\n const virtualModuleId = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n this.emitFile({\n type: 'chunk',\n id: virtualModuleId,\n name: `handler-${handlerName}`,\n })\n }\n }\n }\n }\n\n const transformed: TransformResult = {\n code: finalCode,\n map: finalMap,\n }\n\n if (cacheKey) {\n await cacheStore.set(cacheKey, transformed)\n }\n\n return transformed\n } catch (error) {\n // Better error handling\n const message =\n error instanceof Error ? error.message : 'Unknown error during Fict transformation'\n\n this.error({\n message: `[fict] Transform failed for ${id}: ${message}`,\n id,\n })\n\n return null\n }\n },\n\n handleHotUpdate({ file, server }) {\n if (tsProject && file === tsProject.configPath) {\n resetTypeScriptProject()\n resetCache()\n }\n\n // Force full reload for .tsx/.jsx files to ensure reactive graph is rebuilt\n if (shouldTransform(file, include, exclude)) {\n server.ws.send({\n type: 'full-reload',\n path: '*',\n })\n }\n },\n\n generateBundle(_options, bundle) {\n if (!config || config.command !== 'build') return\n if (config.build.ssr) return\n\n const base = config.base ?? '/'\n const manifest: Record<string, string> = {}\n\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue\n const fileName = output.fileName\n const url = joinBasePath(base, fileName)\n for (const moduleId of Object.keys(output.modules)) {\n if (!moduleId) continue\n\n // Handle virtual handler modules\n if (moduleId.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n const handlerId = moduleId.slice(VIRTUAL_HANDLER_PREFIX.length)\n // Map the virtual module resolve prefix to the chunk URL\n const virtualKey = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n if (!manifest[virtualKey]) {\n manifest[virtualKey] = url\n }\n continue\n }\n\n // Skip other virtual modules\n if (moduleId.startsWith('\\0')) continue\n\n const normalized = normalizeFileName(moduleId, config.root)\n if (!path.isAbsolute(normalized)) continue\n const key = pathToFileURL(normalized).href\n if (!manifest[key]) {\n manifest[key] = url\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'fict.manifest.json',\n source: JSON.stringify(manifest),\n })\n },\n }\n}\n\n/**\n * Check if a file should be transformed based on include/exclude patterns\n */\nfunction shouldTransform(id: string, include: string[], exclude: string[]): boolean {\n // Normalize path separators\n const normalizedId = stripQuery(id).replace(/\\\\/g, '/')\n\n // Check exclude patterns first\n for (const pattern of exclude) {\n if (matchPattern(normalizedId, pattern)) {\n return false\n }\n }\n\n // Check include patterns\n for (const pattern of include) {\n if (matchPattern(normalizedId, pattern)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Simple glob pattern matching\n * Supports: **\\/*.ext, *.ext, exact matches\n */\nfunction matchPattern(id: string, pattern: string): boolean {\n // Exact match\n if (id === pattern) return true\n\n // Simple check: if pattern ends with extension like *.tsx, just check if file ends with it\n if (pattern.startsWith('**/') || pattern.startsWith('*')) {\n const ext = pattern.replace(/^\\*\\*?\\//, '')\n if (ext.startsWith('*')) {\n // **/*.tsx -> check if ends with .tsx\n const ending = ext.replace(/^\\*/, '')\n return id.endsWith(ending)\n }\n }\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\./g, '\\\\.') // Escape dots\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*') // * matches any non-slash\n\n const regex = new RegExp(`^${regexPattern}$`)\n return regex.test(id)\n}\n\n/**\n * Remove Vite query parameters (e.g. ?import, ?v=123) from an id\n */\nfunction stripQuery(id: string): string {\n const queryStart = id.indexOf('?')\n return queryStart === -1 ? id : id.slice(0, queryStart)\n}\n\nfunction normalizeCacheOptions(\n cacheOption: FictPluginOptions['cache'],\n config?: ResolvedConfig,\n): NormalizedCacheOptions {\n const defaultPersistent = config?.command === 'build'\n const defaultDir = config?.cacheDir ? path.join(config.cacheDir, 'fict') : undefined\n\n if (cacheOption === false) {\n return { enabled: false, persistent: false, dir: undefined }\n }\n\n if (cacheOption === true || cacheOption === undefined) {\n return { enabled: true, persistent: defaultPersistent, dir: defaultDir }\n }\n\n return {\n enabled: cacheOption.enabled ?? true,\n persistent: cacheOption.persistent ?? defaultPersistent,\n dir: cacheOption.dir ?? defaultDir,\n }\n}\n\nfunction normalizeFileName(id: string, root?: string): string {\n let clean = stripQuery(id)\n if (clean.startsWith('/@fs/')) {\n clean = clean.slice('/@fs/'.length)\n }\n if (clean.startsWith('file://')) {\n try {\n clean = fileURLToPath(clean)\n } catch {\n // fall through\n }\n }\n if (path.isAbsolute(clean)) return path.normalize(clean)\n if (root) return path.normalize(path.resolve(root, clean))\n return path.normalize(path.resolve(clean))\n}\n\nfunction joinBasePath(base: string, fileName: string): string {\n if (!base) return fileName\n if (base === '/') return `/${fileName}`\n const normalized = base.endsWith('/') ? base : `${base}/`\n return `${normalized}${fileName}`\n}\n\ninterface AliasEntry {\n find: string | RegExp\n replacement: string\n}\n\nfunction normalizeAliases(aliases: ResolvedConfig['resolve']['alias'] | undefined): AliasEntry[] {\n if (!aliases) return []\n if (Array.isArray(aliases)) {\n return aliases\n .map(alias => {\n if (!alias || !('find' in alias)) return null\n const replacement =\n typeof alias.replacement === 'string' ? alias.replacement : String(alias.replacement)\n return { find: alias.find, replacement } as AliasEntry\n })\n .filter((alias): alias is AliasEntry => !!alias)\n }\n return Object.entries(aliases).map(([find, replacement]) => ({\n find,\n replacement: typeof replacement === 'string' ? replacement : String(replacement),\n }))\n}\n\nfunction applyAlias(source: string, aliases: AliasEntry[]): string | null {\n for (const alias of aliases) {\n if (typeof alias.find === 'string') {\n if (source === alias.find || source.startsWith(`${alias.find}/`)) {\n return alias.replacement + source.slice(alias.find.length)\n }\n continue\n }\n if (alias.find instanceof RegExp && alias.find.test(source)) {\n return source.replace(alias.find, alias.replacement)\n }\n }\n return null\n}\n\nfunction hashString(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value)\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`\n }\n\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined && typeof v !== 'function')\n .sort(([a], [b]) => a.localeCompare(b))\n\n const body = entries\n .map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`)\n .join(',')\n\n return `{${body}}`\n}\n\nfunction normalizeOptionsForCache(options: FictCompilerOptions): Record<string, unknown> {\n const normalized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || typeof value === 'function') continue\n if (key === 'typescript') {\n const tsInfo = value as {\n projectVersion?: number\n configPath?: string\n }\n normalized.typescript = {\n projectVersion: tsInfo?.projectVersion,\n configPath: tsInfo?.configPath,\n }\n continue\n }\n normalized[key] = value\n }\n return normalized\n}\n\nfunction buildCacheKey(\n filename: string,\n code: string,\n options: FictCompilerOptions,\n tsProject: TypeScriptProject | null,\n): string {\n const codeHash = hashString(code)\n const optionsHash = hashString(stableStringify(normalizeOptionsForCache(options)))\n const tsKey = tsProject ? `${tsProject.configHash}:${tsProject.projectVersion}` : ''\n return hashString([CACHE_VERSION, filename, codeHash, optionsHash, tsKey].join('|'))\n}\n\nclass TransformCache {\n private memory = new Map<string, CachedTransform>()\n\n constructor(private options: NormalizedCacheOptions) {}\n\n get enabled(): boolean {\n return this.options.enabled\n }\n\n async get(key: string): Promise<CachedTransform | null> {\n if (!this.options.enabled) return null\n const cached = this.memory.get(key)\n if (cached) return cached\n\n if (!this.options.persistent || !this.options.dir) return null\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n const raw = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CachedTransform\n if (!parsed || typeof parsed.code !== 'string') return null\n this.memory.set(key, parsed)\n return parsed\n } catch {\n return null\n }\n }\n\n async set(key: string, value: CachedTransform): Promise<void> {\n if (!this.options.enabled) return\n this.memory.set(key, value)\n if (!this.options.persistent || !this.options.dir) return\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n await fs.mkdir(this.options.dir, { recursive: true })\n await fs.writeFile(filePath, JSON.stringify(value))\n } catch {\n // Ignore cache write failures\n }\n }\n\n clear(): void {\n this.memory.clear()\n }\n}\n\nfunction isTypeScriptApi(value: unknown): value is TypeScriptApi {\n if (!value || typeof value !== 'object') return false\n const candidate = value as Partial<TypeScriptApi>\n return (\n typeof candidate.findConfigFile === 'function' &&\n typeof candidate.readConfigFile === 'function' &&\n typeof candidate.parseJsonConfigFileContent === 'function' &&\n typeof candidate.createLanguageService === 'function' &&\n typeof candidate.createDocumentRegistry === 'function' &&\n typeof candidate.resolveModuleName === 'function' &&\n !!candidate.sys &&\n typeof candidate.sys === 'object' &&\n typeof candidate.sys.fileExists === 'function' &&\n typeof candidate.sys.readFile === 'function'\n )\n}\n\nfunction safeDebugString(value: unknown): string {\n try {\n return typeof value === 'string' ? value : JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatError(error: unknown): string {\n if (error instanceof Error) return error.message\n try {\n return JSON.stringify(error)\n } catch {\n return String(error)\n }\n}\n\nfunction buildPluginMessage(context: string, file: string, error: unknown): string {\n return `[fict-plugin] ${context} (${file}): ${formatError(error)}`\n}\n\nasync function loadTypeScript(): Promise<TypeScriptApi | null> {\n try {\n const mod = await import('typescript')\n const candidate = (mod as { default?: unknown }).default ?? mod\n return isTypeScriptApi(candidate) ? candidate : null\n } catch {\n return null\n }\n}\n\nfunction resolveTsconfigPath(\n ts: TypeScriptApi,\n rootDir: string,\n explicitPath?: string,\n): string | null {\n if (explicitPath) {\n return path.resolve(rootDir, explicitPath)\n }\n return ts.findConfigFile(rootDir, ts.sys.fileExists, 'tsconfig.json') ?? null\n}\n\nasync function createTypeScriptProject(\n ts: TypeScriptApi,\n rootDir: string,\n configPath: string,\n): Promise<TypeScriptProject | null> {\n const configText = ts.sys.readFile(configPath)\n if (!configText) return null\n const configHash = hashString(configText)\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n if (configFile.error) return null\n\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath))\n\n const fileSet = new Set<string>(parsed.fileNames.map((name: string) => path.normalize(name)))\n const fileVersions = new Map<string, number>()\n const fileHashes = new Map<string, string>()\n const fileCache = new Map<string, string>()\n let projectVersion = 0\n\n const normalizeName = (fileName: string) => normalizeFileName(fileName, rootDir)\n\n const serviceHost: TypeScriptLanguageServiceHost = {\n getScriptFileNames: () => Array.from(fileSet),\n getScriptVersion: (fileName: string) => {\n const normalized = normalizeName(fileName)\n return String(fileVersions.get(normalized) ?? 0)\n },\n getScriptSnapshot: (fileName: string) => {\n const normalized = normalizeName(fileName)\n const text = fileCache.get(normalized) ?? ts.sys.readFile(normalized)\n if (text === undefined) return undefined\n return ts.ScriptSnapshot.fromString(text)\n },\n getCurrentDirectory: () => rootDir,\n getCompilationSettings: () => parsed.options,\n getDefaultLibFileName: (options: unknown) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getNewLine: () => ts.sys.newLine,\n getProjectVersion: () => String(projectVersion),\n }\n\n const service = ts.createLanguageService(serviceHost, ts.createDocumentRegistry())\n\n const updateFile = (fileName: string, code: string) => {\n const normalized = normalizeName(fileName)\n const nextHash = hashString(code)\n if (fileHashes.get(normalized) === nextHash) return\n fileHashes.set(normalized, nextHash)\n fileCache.set(normalized, code)\n fileVersions.set(normalized, (fileVersions.get(normalized) ?? 0) + 1)\n fileSet.add(normalized)\n projectVersion += 1\n }\n\n return {\n configPath,\n configHash,\n get projectVersion() {\n return projectVersion\n },\n updateFile,\n getProgram: () => service.getProgram?.() ?? null,\n resolveModuleName: (specifier: string, containingFile: string) => {\n try {\n const resolved = ts.resolveModuleName(specifier, containingFile, parsed.options, ts.sys)\n return resolved?.resolvedModule?.resolvedFileName ?? null\n } catch {\n return null\n }\n },\n dispose: () => service.dispose?.(),\n }\n}\n\n// ============================================================================\n// Function-level Code Splitting Helpers\n// ============================================================================\n\n/**\n * Parse a handler ID into source module and export name.\n * Format: /path/to/module.tsx$$exportName (using $$ as separator to avoid URL fragment conflicts)\n */\nfunction parseHandlerId(handlerId: string): [string | null, string | null] {\n const separatorIndex = handlerId.lastIndexOf('$$')\n if (separatorIndex === -1) {\n return [handlerId, 'default']\n }\n return [handlerId.slice(0, separatorIndex), handlerId.slice(separatorIndex + 2)]\n}\n\n/**\n * Generate handler ID from source module and export name.\n * Uses $$ as separator to avoid conflicts with URL # fragments.\n */\nfunction createHandlerId(sourceModule: string, exportName: string): string {\n return `${sourceModule}$$${exportName}`\n}\n\n/**\n * Generate a standalone virtual module for an extracted handler.\n * The module contains the complete handler code with its own imports,\n * creating a truly independent chunk that doesn't depend on the source module.\n */\nfunction generateHandlerModule(handler: ExtractedHandler): string {\n // If no code was extracted (fallback case), use re-export\n if (!handler.code) {\n return `export { ${handler.exportName} as default } from '${handler.sourceModule}';\\n`\n }\n\n // Group imports by source module\n const importsByModule = new Map<string, string[]>()\n\n for (const helperName of handler.helpersUsed) {\n const helper = RUNTIME_HELPERS[helperName]\n if (!helper) continue\n\n const existing = importsByModule.get(helper.from) ?? []\n if (!existing.includes(helper.import)) {\n existing.push(helper.import)\n }\n importsByModule.set(helper.from, existing)\n }\n\n // Generate import statements for runtime helpers\n const imports: string[] = []\n for (const [module, names] of importsByModule) {\n imports.push(`import { ${names.join(', ')} } from '${module}';`)\n }\n\n // Import local dependencies from the source module\n // These are re-exported by the source module with __fict_dep_ prefix\n if (handler.localDeps.length > 0) {\n const depImports = handler.localDeps.map(dep => `${HANDLER_DEP_PREFIX}${dep} as ${dep}`)\n imports.push(`import { ${depImports.join(', ')} } from '${handler.sourceModule}';`)\n }\n\n // Generate the complete standalone module\n return `${imports.join('\\n')}${imports.length > 0 ? '\\n\\n' : ''}export default ${handler.code};\\n`\n}\n\n/** Prefix for re-exported handler dependencies */\nconst HANDLER_DEP_PREFIX = '__fict_dep_'\n\n/**\n * Register an extracted handler for function-level splitting.\n */\nexport function registerExtractedHandler(\n sourceModule: string,\n exportName: string,\n helpersUsed: string[],\n code: string,\n localDeps: string[] = [],\n): string {\n const handlerId = createHandlerId(sourceModule, exportName)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName,\n helpersUsed,\n localDeps,\n code,\n })\n return `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n}\n\n/**\n * Runtime helper name mappings for generating imports in virtual modules\n */\nconst RUNTIME_HELPERS: Record<string, { import: string; from: string }> = {\n __fictUseLexicalScope: { import: '__fictUseLexicalScope', from: '@fictjs/runtime/internal' },\n __fictGetScopeProps: { import: '__fictGetScopeProps', from: '@fictjs/runtime/internal' },\n __fictGetSSRScope: { import: '__fictGetSSRScope', from: '@fictjs/runtime/internal' },\n __fictEnsureScope: { import: '__fictEnsureScope', from: '@fictjs/runtime/internal' },\n __fictPrepareContext: { import: '__fictPrepareContext', from: '@fictjs/runtime/internal' },\n __fictPushContext: { import: '__fictPushContext', from: '@fictjs/runtime/internal' },\n __fictPopContext: { import: '__fictPopContext', from: '@fictjs/runtime/internal' },\n hydrateComponent: { import: 'hydrateComponent', from: '@fictjs/runtime/internal' },\n __fictQrl: { import: '__fictQrl', from: '@fictjs/runtime/internal' },\n}\n\n/** Known global identifiers that don't need to be imported */\nconst GLOBAL_IDENTIFIERS = new Set([\n // JavaScript globals\n 'undefined',\n 'null',\n 'true',\n 'false',\n 'NaN',\n 'Infinity',\n 'globalThis',\n 'window',\n 'document',\n 'console',\n 'setTimeout',\n 'setInterval',\n 'clearTimeout',\n 'clearInterval',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'fetch',\n 'URL',\n 'URLSearchParams',\n 'FormData',\n 'Headers',\n 'Request',\n 'Response',\n 'AbortController',\n 'AbortSignal',\n // Built-in constructors\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Symbol',\n 'BigInt',\n 'Date',\n 'RegExp',\n 'Error',\n 'TypeError',\n 'RangeError',\n 'SyntaxError',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Proxy',\n 'Reflect',\n 'JSON',\n 'Math',\n 'Intl',\n // Event and DOM\n 'Event',\n 'CustomEvent',\n 'Element',\n 'Node',\n 'HTMLElement',\n])\n\n/**\n * Collect identifiers referenced in an AST node that are not locally defined.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectReferencedIdentifiers(node: t.Node, localBindings: Set<string>): Set<string> {\n const referenced = new Set<string>()\n\n function visitNode(\n current: t.Node | null | undefined,\n parent: t.Node | null,\n key: string | null,\n ): void {\n if (!current) return\n\n if (t.isIdentifier(current)) {\n const name = current.name\n\n // Skip if it's a property access (obj.prop) - only the object is a reference\n if (\n parent &&\n t.isMemberExpression(parent) &&\n parent.property === current &&\n !parent.computed\n ) {\n return\n }\n\n // Skip if it's a key in object property (non-computed)\n if (parent && t.isObjectProperty(parent) && parent.key === current && !parent.computed) {\n return\n }\n\n // Skip if it's a function/variable declaration name\n if (parent && t.isVariableDeclarator(parent) && parent.id === current) {\n return\n }\n if (\n parent &&\n (t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&\n parent.id === current\n ) {\n return\n }\n\n // Skip if it's a parameter\n if (key === 'params') {\n return\n }\n\n // Skip if it's a catch clause parameter\n if (parent && t.isCatchClause(parent) && parent.param === current) {\n return\n }\n\n // Skip local bindings (locally declared variables)\n if (localBindings.has(name)) {\n return\n }\n\n // Skip globals\n if (GLOBAL_IDENTIFIERS.has(name)) {\n return\n }\n\n // Skip runtime helpers\n if (RUNTIME_HELPERS[name]) {\n return\n }\n\n referenced.add(name)\n return\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node, current, nodeKey)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node, current, nodeKey)\n }\n }\n }\n\n visitNode(node, null, null)\n return referenced\n}\n\n/**\n * Collect all bindings (variables, functions, params) defined within an AST node.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectLocalBindings(node: t.Node): Set<string> {\n const bindings = new Set<string>()\n\n function visitNode(current: t.Node | null | undefined): void {\n if (!current) return\n\n // Handle variable declarations\n if (t.isVariableDeclarator(current)) {\n if (t.isIdentifier(current.id)) {\n bindings.add(current.id.name)\n } else if (t.isObjectPattern(current.id) || t.isArrayPattern(current.id)) {\n const names = collectPatternIdentifiers(current.id)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function declarations\n if (t.isFunctionDeclaration(current)) {\n if (current.id) {\n bindings.add(current.id.name)\n }\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function expressions\n if (t.isFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle arrow function expressions\n if (t.isArrowFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle catch clauses\n if (t.isCatchClause(current)) {\n if (current.param && t.isIdentifier(current.param)) {\n bindings.add(current.param.name)\n }\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node)\n }\n }\n }\n\n visitNode(node)\n\n return bindings\n}\n\n/**\n * Collect identifier names from a pattern (for destructuring).\n */\nfunction collectPatternIdentifiers(pattern: t.LVal | t.PatternLike): string[] {\n const names: string[] = []\n\n if (t.isIdentifier(pattern)) {\n names.push(pattern.name)\n } else if (t.isObjectPattern(pattern)) {\n for (const prop of pattern.properties) {\n if (t.isObjectProperty(prop) && t.isLVal(prop.value)) {\n names.push(...collectPatternIdentifiers(prop.value))\n } else if (t.isRestElement(prop)) {\n names.push(...collectPatternIdentifiers(prop.argument))\n }\n }\n } else if (t.isArrayPattern(pattern)) {\n for (const element of pattern.elements) {\n if (element) {\n names.push(...collectPatternIdentifiers(element))\n }\n }\n } else if (t.isRestElement(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.argument))\n } else if (t.isAssignmentPattern(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.left))\n }\n\n return names\n}\n\n/**\n * Extract handlers using Babel AST and rewrite QRLs to use virtual modules.\n * This creates truly independent chunks for each handler.\n * Local dependencies are detected and re-exported for handlers to import.\n */\nfunction extractAndRewriteHandlers(\n code: string,\n sourceModule: string,\n): { code: string; handlers: string[] } | null {\n let ast: ReturnType<typeof parse>\n\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n })\n } catch (error) {\n throw new Error(\n buildPluginMessage(\n 'Failed to parse transformed code for handler extraction',\n sourceModule,\n error,\n ),\n )\n }\n\n // Collect all top-level declarations that could be referenced by handlers\n const topLevelDeclarations = new Set<string>()\n const importedNames = new Set<string>()\n\n for (const node of ast.program.body) {\n // Collect imports\n if (t.isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n } else if (t.isImportNamespaceSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n }\n }\n continue\n }\n\n // Collect function declarations\n if (t.isFunctionDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect variable declarations\n if (t.isVariableDeclaration(node)) {\n for (const declarator of node.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n continue\n }\n\n // Collect class declarations\n if (t.isClassDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect exported declarations\n if (t.isExportNamedDeclaration(node) && node.declaration) {\n if (t.isFunctionDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n } else if (t.isVariableDeclaration(node.declaration)) {\n for (const declarator of node.declaration.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n } else if (t.isClassDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n }\n }\n }\n\n // Merge imports into top-level declarations (they're also available at top level)\n for (const name of importedNames) {\n topLevelDeclarations.add(name)\n }\n\n const handlerNames: string[] = []\n const nodesToRemove = new Set<t.Node>()\n const allLocalDeps = new Set<string>()\n\n // First pass: find all handler exports and extract their code\n traverse(ast, {\n ExportNamedDeclaration(path) {\n const declaration = path.node.declaration\n\n // Handle: export const __fict_e0 = (scopeId, event, el) => { ... }\n if (t.isVariableDeclaration(declaration)) {\n for (const declarator of declaration.declarations) {\n if (!t.isIdentifier(declarator.id)) continue\n\n const name = declarator.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) continue\n\n if (!declarator.init) continue\n\n handlerNames.push(name)\n\n // Generate the handler function code\n const handlerCode = generate(declarator.init).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(declarator.init)\n const referencedIds = collectReferencedIdentifiers(declarator.init, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n return\n }\n\n // Handle: export function __fict_e0(scopeId, event, el) { ... }\n if (t.isFunctionDeclaration(declaration) && declaration.id) {\n const name = declaration.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) return\n\n handlerNames.push(name)\n\n // Convert to arrow function expression for the virtual module\n const params = declaration.params\n const body = declaration.body\n const arrowFn = t.arrowFunctionExpression(params, body, declaration.async)\n\n // Generate the handler function code\n const handlerCode = generate(arrowFn).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(arrowFn)\n const referencedIds = collectReferencedIdentifiers(arrowFn, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n },\n })\n\n if (handlerNames.length === 0) {\n return null\n }\n\n // Second pass: remove handler exports, rewrite QRL calls, and add re-exports for dependencies\n traverse(ast, {\n ExportNamedDeclaration(path) {\n if (nodesToRemove.has(path.node)) {\n path.remove()\n }\n },\n\n CallExpression(path) {\n // Rewrite __fictQrl(import.meta.url, \"__fict_e0\") -> \"virtual:...\"\n if (!t.isIdentifier(path.node.callee, { name: '__fictQrl' })) return\n if (path.node.arguments.length !== 2) return\n\n const secondArg = path.node.arguments[1]\n if (!t.isStringLiteral(secondArg)) return\n\n const handlerName = secondArg.value\n if (!handlerNames.includes(handlerName)) return\n\n // Replace with the virtual module URL\n const handlerId = createHandlerId(sourceModule, handlerName)\n const virtualUrl = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}#default`\n path.replaceWith(t.stringLiteral(virtualUrl))\n },\n })\n\n // Add re-exports for local dependencies used by handlers\n // This allows handlers to import them from the source module\n if (allLocalDeps.size > 0) {\n const reExports: t.ExportSpecifier[] = []\n for (const dep of allLocalDeps) {\n // Export as __fict_dep_<name> to avoid conflicts\n reExports.push(\n t.exportSpecifier(t.identifier(dep), t.identifier(`${HANDLER_DEP_PREFIX}${dep}`)),\n )\n }\n ast.program.body.push(t.exportNamedDeclaration(null, reExports))\n }\n\n // Generate the modified code\n const result = generate(ast, {\n retainLines: true,\n compact: false,\n })\n\n return { code: result.code, handlers: handlerNames }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA2B;AAC3B,qBAA+B;AAC/B,uBAAiB;AACjB,sBAA6C;AAE7C,kBAA+B;AAC/B,uBAAsB;AACtB,oBAAsB;AACtB,sBAAsB;AACtB,QAAmB;AACnB,sBAA2D;AAI3D,IAAM,WACJ,OAAO,gBAAAA,YAAc,aAAa,gBAAAA,UAAa,gBAAAA,QAA4C;AAE7F,IAAM,WACJ,OAAO,iBAAAC,YAAc,aAAa,iBAAAA,UAAa,iBAAAA,QAA4C;AAiJ7F,IAAM,gBAAgB;AACtB,IAAM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AA,MAClF;AAAA,IACF;AACA,QAAI,QAAQ,KAAK,KAAO,yBAAuB,MAAM,SAAS,CAAC;AAAA,EACjE;AAGA,QAAM,SAAS,SAAS,KAAK;AAAA,IAC3B,aAAa;AAAA,IACb,SAAS;AAAA,EACX,CAAC;AAED,SAAO,EAAE,MAAM,OAAO,MAAM,UAAU,aAAa;AACrD;","names":["_traverse","_generate","include","exclude","path","tsProject","fs","module"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -38,6 +38,12 @@ interface FictPluginOptions extends FictCompilerOptions {
|
|
|
38
38
|
* @default false for dev, true for production build
|
|
39
39
|
*/
|
|
40
40
|
functionSplitting?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Enable verbose debug logs from the plugin.
|
|
43
|
+
* Can also be enabled via `FICT_VITE_PLUGIN_DEBUG=1`.
|
|
44
|
+
* @default false
|
|
45
|
+
*/
|
|
46
|
+
debug?: boolean;
|
|
41
47
|
}
|
|
42
48
|
/**
|
|
43
49
|
* Vite plugin for Fict reactive UI library.
|
package/dist/index.d.ts
CHANGED
|
@@ -38,6 +38,12 @@ interface FictPluginOptions extends FictCompilerOptions {
|
|
|
38
38
|
* @default false for dev, true for production build
|
|
39
39
|
*/
|
|
40
40
|
functionSplitting?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Enable verbose debug logs from the plugin.
|
|
43
|
+
* Can also be enabled via `FICT_VITE_PLUGIN_DEBUG=1`.
|
|
44
|
+
* @default false
|
|
45
|
+
*/
|
|
46
|
+
debug?: boolean;
|
|
41
47
|
}
|
|
42
48
|
/**
|
|
43
49
|
* Vite plugin for Fict reactive UI library.
|
package/dist/index.js
CHANGED
|
@@ -23,6 +23,7 @@ function fict(options = {}) {
|
|
|
23
23
|
cache: cacheOption,
|
|
24
24
|
tsconfigPath,
|
|
25
25
|
useTypeScriptProject = true,
|
|
26
|
+
debug: debugOption,
|
|
26
27
|
...compilerOptions
|
|
27
28
|
} = options;
|
|
28
29
|
let config;
|
|
@@ -31,6 +32,12 @@ function fict(options = {}) {
|
|
|
31
32
|
let tsProject = null;
|
|
32
33
|
let tsProjectInit = null;
|
|
33
34
|
const moduleMetadata = /* @__PURE__ */ new Map();
|
|
35
|
+
const debugEnabled = debugOption === true || process.env.FICT_VITE_PLUGIN_DEBUG === "1" || process.env.FICT_VITE_PLUGIN_DEBUG === "true";
|
|
36
|
+
const debugLog = (message, details) => {
|
|
37
|
+
if (!debugEnabled) return;
|
|
38
|
+
const payload = details === void 0 ? "" : ` ${safeDebugString(details)}`;
|
|
39
|
+
config?.logger?.info(`[fict-plugin] ${message}${payload}`);
|
|
40
|
+
};
|
|
34
41
|
const ensureCache = () => {
|
|
35
42
|
if (cache) return cache;
|
|
36
43
|
const normalized = normalizeCacheOptions(cacheOption, config);
|
|
@@ -84,16 +91,16 @@ function fict(options = {}) {
|
|
|
84
91
|
return null;
|
|
85
92
|
}
|
|
86
93
|
const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length);
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
);
|
|
94
|
+
debugLog(`Loading virtual module: ${handlerId}`, {
|
|
95
|
+
registrySize: extractedHandlers.size,
|
|
96
|
+
handlers: Array.from(extractedHandlers.keys())
|
|
97
|
+
});
|
|
92
98
|
const handler = extractedHandlers.get(handlerId);
|
|
93
99
|
if (handler) {
|
|
94
100
|
const generatedCode = generateHandlerModule(handler);
|
|
95
|
-
|
|
96
|
-
|
|
101
|
+
debugLog(`Generated virtual module (${generatedCode.length} chars)`, {
|
|
102
|
+
preview: generatedCode.slice(0, 200)
|
|
103
|
+
});
|
|
97
104
|
return generatedCode;
|
|
98
105
|
}
|
|
99
106
|
if (!handler) {
|
|
@@ -279,23 +286,27 @@ function fict(options = {}) {
|
|
|
279
286
|
let finalCode = result.code;
|
|
280
287
|
let finalMap = result.map;
|
|
281
288
|
const shouldSplit = options.functionSplitting ?? (config?.command === "build" && (compilerOptions.resumable || !config?.build?.ssr));
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
289
|
+
debugLog("Function split decision", {
|
|
290
|
+
shouldSplit,
|
|
291
|
+
ssr: config?.build?.ssr,
|
|
292
|
+
resumable: compilerOptions.resumable,
|
|
293
|
+
file: filename
|
|
294
|
+
});
|
|
285
295
|
if (shouldSplit) {
|
|
286
296
|
let splitResult = null;
|
|
287
297
|
try {
|
|
288
298
|
splitResult = extractAndRewriteHandlers(finalCode, filename);
|
|
289
|
-
} catch (
|
|
290
|
-
|
|
299
|
+
} catch (error) {
|
|
300
|
+
this.warn(buildPluginMessage("extractAndRewriteHandlers failed", filename, error));
|
|
291
301
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
302
|
+
debugLog("Split result", {
|
|
303
|
+
file: filename,
|
|
304
|
+
handlers: splitResult?.handlers.length ?? 0
|
|
305
|
+
});
|
|
295
306
|
if (splitResult) {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
);
|
|
307
|
+
debugLog(`Function splitting extracted ${splitResult.handlers.length} handlers`, {
|
|
308
|
+
file: filename
|
|
309
|
+
});
|
|
299
310
|
finalCode = splitResult.code;
|
|
300
311
|
finalMap = null;
|
|
301
312
|
if (config?.command === "build" && !config?.build?.ssr) {
|
|
@@ -546,10 +557,34 @@ var TransformCache = class {
|
|
|
546
557
|
this.memory.clear();
|
|
547
558
|
}
|
|
548
559
|
};
|
|
560
|
+
function isTypeScriptApi(value) {
|
|
561
|
+
if (!value || typeof value !== "object") return false;
|
|
562
|
+
const candidate = value;
|
|
563
|
+
return typeof candidate.findConfigFile === "function" && typeof candidate.readConfigFile === "function" && typeof candidate.parseJsonConfigFileContent === "function" && typeof candidate.createLanguageService === "function" && typeof candidate.createDocumentRegistry === "function" && typeof candidate.resolveModuleName === "function" && !!candidate.sys && typeof candidate.sys === "object" && typeof candidate.sys.fileExists === "function" && typeof candidate.sys.readFile === "function";
|
|
564
|
+
}
|
|
565
|
+
function safeDebugString(value) {
|
|
566
|
+
try {
|
|
567
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
568
|
+
} catch {
|
|
569
|
+
return String(value);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
function formatError(error) {
|
|
573
|
+
if (error instanceof Error) return error.message;
|
|
574
|
+
try {
|
|
575
|
+
return JSON.stringify(error);
|
|
576
|
+
} catch {
|
|
577
|
+
return String(error);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
function buildPluginMessage(context, file, error) {
|
|
581
|
+
return `[fict-plugin] ${context} (${file}): ${formatError(error)}`;
|
|
582
|
+
}
|
|
549
583
|
async function loadTypeScript() {
|
|
550
584
|
try {
|
|
551
585
|
const mod = await import("typescript");
|
|
552
|
-
|
|
586
|
+
const candidate = mod.default ?? mod;
|
|
587
|
+
return isTypeScriptApi(candidate) ? candidate : null;
|
|
553
588
|
} catch {
|
|
554
589
|
return null;
|
|
555
590
|
}
|
|
@@ -896,9 +931,14 @@ function extractAndRewriteHandlers(code, sourceModule) {
|
|
|
896
931
|
sourceType: "module",
|
|
897
932
|
plugins: ["jsx", "typescript"]
|
|
898
933
|
});
|
|
899
|
-
} catch (
|
|
900
|
-
|
|
901
|
-
|
|
934
|
+
} catch (error) {
|
|
935
|
+
throw new Error(
|
|
936
|
+
buildPluginMessage(
|
|
937
|
+
"Failed to parse transformed code for handler extraction",
|
|
938
|
+
sourceModule,
|
|
939
|
+
error
|
|
940
|
+
)
|
|
941
|
+
);
|
|
902
942
|
}
|
|
903
943
|
const topLevelDeclarations = /* @__PURE__ */ new Set();
|
|
904
944
|
const importedNames = /* @__PURE__ */ new Set();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nimport { transformAsync } from '@babel/core'\nimport _generate from '@babel/generator'\nimport { parse } from '@babel/parser'\nimport _traverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\n// Handle ESM/CJS interop for Babel packages\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse\nconst generate = (\n typeof _generate === 'function' ? _generate : (_generate as { default: typeof _generate }).default\n) as typeof _generate\nimport { createFictPlugin, type FictCompilerOptions } from '@fictjs/compiler'\nimport type { Plugin, ResolvedConfig, TransformResult } from 'vite'\n\nexport interface FictPluginOptions extends FictCompilerOptions {\n /**\n * File patterns to include for transformation.\n * @default ['**\\/*.tsx', '**\\/*.jsx']\n */\n include?: string[]\n /**\n * File patterns to exclude from transformation.\n * @default ['**\\/node_modules\\/**']\n */\n exclude?: string[]\n /**\n * Transform cache settings (memory + optional persistent disk cache).\n * Set to false to disable caching entirely.\n */\n cache?:\n | boolean\n | {\n enabled?: boolean\n persistent?: boolean\n dir?: string\n }\n /**\n * Explicit tsconfig path for TypeScript project integration.\n * If omitted, the plugin will search from Vite root.\n */\n tsconfigPath?: string\n /**\n * Enable TypeScript project integration when TypeScript is available.\n * @default true\n */\n useTypeScriptProject?: boolean\n /**\n * Enable function-level code splitting for resumable handlers.\n * When enabled, event handlers and resume functions are extracted\n * to separate chunks for optimal lazy loading.\n * @default false for dev, true for production build\n */\n functionSplitting?: boolean\n}\n\ninterface NormalizedCacheOptions {\n enabled: boolean\n persistent: boolean\n dir?: string\n}\n\ninterface CachedTransform {\n code: string\n map: TransformResult['map']\n}\n\ninterface TypeScriptProject {\n configPath: string\n configHash: string\n readonly projectVersion: number\n updateFile: (fileName: string, code: string) => void\n getProgram: () => unknown | null\n resolveModuleName: (specifier: string, containingFile: string) => string | null\n dispose: () => void\n}\n\nconst CACHE_VERSION = 1\nconst MODULE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']\n\n// Virtual module prefix for extracted handlers\nconst VIRTUAL_HANDLER_PREFIX = '\\0fict-handler:'\nconst VIRTUAL_HANDLER_RESOLVE_PREFIX = 'virtual:fict-handler:'\n\n/**\n * Information about an extracted resumable handler\n */\ninterface ExtractedHandler {\n /** The module this handler was extracted from */\n sourceModule: string\n /** The export name in the source module */\n exportName: string\n /** Runtime helpers used by this handler */\n helpersUsed: string[]\n /** Local dependencies from source module that need to be re-exported */\n localDeps: string[]\n /** The handler function code (without export) */\n code: string\n}\n\n/**\n * Registry for extracted handlers during compilation\n */\nconst extractedHandlers = new Map<string, ExtractedHandler>()\n\n/**\n * Vite plugin for Fict reactive UI library.\n *\n * Transforms $state and $effect calls into reactive signals using the Fict compiler.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import fict from '@fictjs/vite-plugin'\n *\n * export default defineConfig({\n * plugins: [fict()],\n * })\n * ```\n */\nexport default function fict(options: FictPluginOptions = {}): Plugin {\n const {\n include = ['**/*.tsx', '**/*.jsx'],\n exclude = ['**/node_modules/**'],\n cache: cacheOption,\n tsconfigPath,\n useTypeScriptProject = true,\n ...compilerOptions\n } = options\n\n let config: ResolvedConfig | undefined\n let isDev = false\n let cache: TransformCache | null = null\n let tsProject: TypeScriptProject | null = null\n let tsProjectInit: Promise<TypeScriptProject | null> | null = null\n const moduleMetadata: FictCompilerOptions['moduleMetadata'] = new Map()\n\n const ensureCache = () => {\n if (cache) return cache\n const normalized = normalizeCacheOptions(cacheOption, config)\n cache = new TransformCache(normalized)\n return cache\n }\n\n const resetCache = () => {\n cache?.clear()\n cache = null\n }\n\n const ensureTypeScriptProject = async () => {\n if (!useTypeScriptProject) return null\n if (tsProject) return tsProject\n if (!tsProjectInit) {\n tsProjectInit = (async () => {\n const ts = await loadTypeScript()\n if (!ts) return null\n const rootDir = config?.root ?? process.cwd()\n const resolvedConfigPath = resolveTsconfigPath(ts, rootDir, tsconfigPath)\n if (!resolvedConfigPath) return null\n return createTypeScriptProject(ts, rootDir, resolvedConfigPath)\n })()\n }\n tsProject = await tsProjectInit\n return tsProject\n }\n\n const resetTypeScriptProject = () => {\n if (tsProject) {\n tsProject.dispose()\n }\n tsProject = null\n tsProjectInit = null\n }\n\n return {\n name: 'vite-plugin-fict',\n\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n config = resolvedConfig\n isDev = config.command === 'serve' || config.mode === 'development'\n // Rebuild cache with resolved config so cacheDir is available\n resetCache()\n // Clear extracted handlers from previous builds\n extractedHandlers.clear()\n },\n\n resolveId(id: string) {\n // Handle virtual handler modules\n if (id.startsWith(VIRTUAL_HANDLER_RESOLVE_PREFIX)) {\n return VIRTUAL_HANDLER_PREFIX + id.slice(VIRTUAL_HANDLER_RESOLVE_PREFIX.length)\n }\n return null\n },\n\n load(id: string) {\n // Load virtual handler modules\n if (!id.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n return null\n }\n\n const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length)\n console.log(`[fict-plugin] Loading virtual module: ${handlerId}`)\n console.log(\n `[fict-plugin] Registry has ${extractedHandlers.size} handlers:`,\n Array.from(extractedHandlers.keys()),\n )\n const handler = extractedHandlers.get(handlerId)\n if (handler) {\n const generatedCode = generateHandlerModule(handler)\n console.log(`[fict-plugin] Generated code length: ${generatedCode.length}`)\n console.log(`[fict-plugin] Generated code preview: ${generatedCode.slice(0, 200)}...`)\n return generatedCode\n }\n\n if (!handler) {\n // In dev mode or when splitting is disabled, the handler is still in the main module\n // Generate a re-export from the source module\n const [sourceModule, exportName] = parseHandlerId(handlerId)\n if (sourceModule && exportName) {\n return `export { ${exportName} as default } from '${sourceModule}'`\n }\n return null\n }\n\n // Generate the virtual module with the handler code\n return generateHandlerModule(handler)\n },\n\n config(userConfig, env) {\n const userOptimize = userConfig.optimizeDeps\n const hasUserOptimize = !!userOptimize\n const hasDisabledOptimize =\n hasUserOptimize && (userOptimize as { disabled?: boolean }).disabled === true\n\n const include = new Set(userOptimize?.include ?? [])\n const exclude = new Set(userOptimize?.exclude ?? [])\n const dedupe = new Set((userConfig.resolve?.dedupe ?? []) as string[])\n\n // Avoid duplicate runtime instances between pre-bundled deps and /@fs modules.\n // Exclude all workspace packages from prebundling to ensure changes take effect\n // immediately without requiring node_modules reinstall.\n const workspaceDeps = [\n 'fict',\n 'fict/plus',\n 'fict/advanced',\n 'fict/slim',\n 'fict/jsx-runtime',\n 'fict/jsx-dev-runtime',\n '@fictjs/runtime',\n '@fictjs/runtime/internal',\n '@fictjs/runtime/advanced',\n '@fictjs/runtime/jsx-runtime',\n '@fictjs/runtime/jsx-dev-runtime',\n '@fictjs/compiler',\n '@fictjs/devtools',\n '@fictjs/devtools/core',\n '@fictjs/devtools/vite',\n '@fictjs/router',\n '@fictjs/ssr',\n '@fictjs/testing-library',\n ]\n for (const dep of workspaceDeps) {\n include.delete(dep)\n exclude.add(dep)\n }\n // Only dedupe core runtime packages to avoid duplicate instances\n const dedupePackages = ['fict', '@fictjs/runtime', '@fictjs/runtime/internal']\n for (const dep of dedupePackages) {\n dedupe.add(dep)\n }\n\n // Determine if we're in dev mode based on command or mode\n const devMode = env.command === 'serve' || env.mode === 'development'\n\n return {\n // Define __DEV__ for runtime devtools support\n // In dev mode, enable devtools; in production, disable them for smaller bundles\n define: {\n __DEV__: String(devMode),\n ...(userConfig.define ?? {}),\n },\n esbuild: {\n // Disable esbuild JSX handling for .tsx/.jsx files\n // Our plugin will handle the full transformation\n include: /\\.(ts|js|mts|mjs|cjs)$/,\n },\n build: {\n rollupOptions: {\n // Preserve exports in entry chunks to prevent tree-shaking of handler exports\n preserveEntrySignatures: 'exports-only',\n },\n },\n resolve: {\n ...(userConfig.resolve ?? {}),\n dedupe: Array.from(dedupe),\n },\n // Watch workspace packages dist directories for changes in dev mode\n // This ensures HMR picks up rebuilt packages without needing to restart\n server: {\n watch: {\n ignored: ['!**/node_modules/@fictjs/**', '!**/node_modules/fict/**'],\n },\n },\n ...(hasDisabledOptimize\n ? { optimizeDeps: userOptimize }\n : {\n optimizeDeps: hasUserOptimize\n ? { ...userOptimize, include: Array.from(include), exclude: Array.from(exclude) }\n : { exclude: workspaceDeps },\n }),\n }\n },\n\n async transform(code: string, id: string): Promise<TransformResult | null> {\n const filename = stripQuery(id)\n\n // Skip non-matching files\n if (!shouldTransform(filename, include, exclude)) {\n return null\n }\n\n const aliasEntries = normalizeAliases(config?.resolve?.alias)\n const fictOptions: FictCompilerOptions = {\n ...compilerOptions,\n dev: compilerOptions.dev ?? isDev,\n sourcemap: compilerOptions.sourcemap ?? true,\n filename,\n moduleMetadata,\n resolveModuleMetadata: (source, importer) => {\n const userResolved = compilerOptions.resolveModuleMetadata?.(source, importer)\n if (userResolved) return userResolved\n if (!importer) return undefined\n\n const importerFile = normalizeFileName(importer, config?.root)\n const lookupMetadata = (resolved: string) => {\n const direct = moduleMetadata.get(resolved)\n if (direct) return direct\n const ext = path.extname(resolved)\n if (!ext) {\n for (const suffix of MODULE_EXTENSIONS) {\n const byExt = moduleMetadata.get(`${resolved}${suffix}`)\n if (byExt) return byExt\n }\n for (const suffix of MODULE_EXTENSIONS) {\n const byIndex = moduleMetadata.get(path.join(resolved, `index${suffix}`))\n if (byIndex) return byIndex\n }\n }\n return undefined\n }\n let resolvedSource: string | null = null\n\n if (path.isAbsolute(source)) {\n resolvedSource = normalizeFileName(source, config?.root)\n } else if (source.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), source),\n config?.root,\n )\n } else {\n const aliased = applyAlias(source, aliasEntries)\n if (aliased) {\n if (path.isAbsolute(aliased)) {\n resolvedSource = normalizeFileName(aliased, config?.root)\n } else if (aliased.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), aliased),\n config?.root,\n )\n } else if (config?.root) {\n resolvedSource = normalizeFileName(path.resolve(config.root, aliased), config?.root)\n }\n } else if (tsProject) {\n const tsResolved = tsProject.resolveModuleName(source, importerFile)\n if (tsResolved) {\n resolvedSource = normalizeFileName(tsResolved, config?.root)\n }\n }\n }\n\n if (!resolvedSource) return undefined\n return lookupMetadata(resolvedSource)\n },\n }\n\n const tsProject = await ensureTypeScriptProject()\n if (tsProject) {\n const resolvedName = normalizeFileName(filename, config?.root)\n tsProject.updateFile(resolvedName, code)\n const program = tsProject.getProgram()\n const checker =\n program && typeof (program as any).getTypeChecker === 'function'\n ? (program as any).getTypeChecker()\n : undefined\n fictOptions.typescript = {\n program: program ?? undefined,\n checker,\n projectVersion: tsProject.projectVersion,\n configPath: tsProject.configPath,\n }\n }\n\n const cacheStore = ensureCache()\n const cacheKey = cacheStore.enabled\n ? buildCacheKey(filename, code, fictOptions, tsProject)\n : null\n\n if (cacheKey) {\n const cached = await cacheStore.get(cacheKey)\n if (cached) {\n return cached\n }\n }\n\n try {\n const isTypeScript = filename.endsWith('.tsx') || filename.endsWith('.ts')\n\n const result = await transformAsync(code, {\n filename,\n sourceMaps: fictOptions.sourcemap,\n sourceFileName: filename,\n presets: isTypeScript\n ? [['@babel/preset-typescript', { isTSX: true, allExtensions: true }]]\n : [],\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [createFictPlugin, fictOptions],\n ],\n })\n\n if (!result || !result.code) {\n return null\n }\n\n let finalCode = result.code\n let finalMap = result.map as TransformResult['map']\n\n // Apply function-level code splitting in production builds\n // For SSR builds with resumable enabled, we also need to rewrite QRLs to virtual URLs\n // so they match the manifest generated by the client build\n const shouldSplit =\n options.functionSplitting ??\n (config?.command === 'build' && (compilerOptions.resumable || !config?.build?.ssr))\n\n console.log(\n `[fict-plugin] shouldSplit=${shouldSplit}, ssr=${config?.build?.ssr}, resumable=${compilerOptions.resumable}, file=${filename}`,\n )\n if (shouldSplit) {\n let splitResult: { code: string; handlers: string[] } | null = null\n try {\n splitResult = extractAndRewriteHandlers(finalCode, filename)\n } catch (e) {\n console.error('[fict-plugin] extractAndRewriteHandlers error:', e)\n }\n console.log(\n `[fict-plugin] splitResult: ${splitResult ? splitResult.handlers.length + ' handlers' : 'null'}`,\n )\n if (splitResult) {\n console.log(\n `[fict-plugin] Function splitting: ${filename} - ${splitResult.handlers.length} handlers extracted`,\n )\n finalCode = splitResult.code\n // Note: source maps are invalidated by this rewrite\n // For production builds, this is acceptable\n finalMap = null\n\n // Emit each extracted handler as a separate chunk for lazy loading\n // This ensures the virtual modules are included in the build\n if (config?.command === 'build' && !config?.build?.ssr) {\n for (const handlerName of splitResult.handlers) {\n const handlerId = createHandlerId(filename, handlerName)\n const virtualModuleId = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n this.emitFile({\n type: 'chunk',\n id: virtualModuleId,\n name: `handler-${handlerName}`,\n })\n }\n }\n }\n }\n\n const transformed: TransformResult = {\n code: finalCode,\n map: finalMap,\n }\n\n if (cacheKey) {\n await cacheStore.set(cacheKey, transformed)\n }\n\n return transformed\n } catch (error) {\n // Better error handling\n const message =\n error instanceof Error ? error.message : 'Unknown error during Fict transformation'\n\n this.error({\n message: `[fict] Transform failed for ${id}: ${message}`,\n id,\n })\n\n return null\n }\n },\n\n handleHotUpdate({ file, server }) {\n if (tsProject && file === tsProject.configPath) {\n resetTypeScriptProject()\n resetCache()\n }\n\n // Force full reload for .tsx/.jsx files to ensure reactive graph is rebuilt\n if (shouldTransform(file, include, exclude)) {\n server.ws.send({\n type: 'full-reload',\n path: '*',\n })\n }\n },\n\n generateBundle(_options, bundle) {\n if (!config || config.command !== 'build') return\n if (config.build.ssr) return\n\n const base = config.base ?? '/'\n const manifest: Record<string, string> = {}\n\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue\n const fileName = output.fileName\n const url = joinBasePath(base, fileName)\n for (const moduleId of Object.keys(output.modules)) {\n if (!moduleId) continue\n\n // Handle virtual handler modules\n if (moduleId.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n const handlerId = moduleId.slice(VIRTUAL_HANDLER_PREFIX.length)\n // Map the virtual module resolve prefix to the chunk URL\n const virtualKey = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n if (!manifest[virtualKey]) {\n manifest[virtualKey] = url\n }\n continue\n }\n\n // Skip other virtual modules\n if (moduleId.startsWith('\\0')) continue\n\n const normalized = normalizeFileName(moduleId, config.root)\n if (!path.isAbsolute(normalized)) continue\n const key = pathToFileURL(normalized).href\n if (!manifest[key]) {\n manifest[key] = url\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'fict.manifest.json',\n source: JSON.stringify(manifest),\n })\n },\n }\n}\n\n/**\n * Check if a file should be transformed based on include/exclude patterns\n */\nfunction shouldTransform(id: string, include: string[], exclude: string[]): boolean {\n // Normalize path separators\n const normalizedId = stripQuery(id).replace(/\\\\/g, '/')\n\n // Check exclude patterns first\n for (const pattern of exclude) {\n if (matchPattern(normalizedId, pattern)) {\n return false\n }\n }\n\n // Check include patterns\n for (const pattern of include) {\n if (matchPattern(normalizedId, pattern)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Simple glob pattern matching\n * Supports: **\\/*.ext, *.ext, exact matches\n */\nfunction matchPattern(id: string, pattern: string): boolean {\n // Exact match\n if (id === pattern) return true\n\n // Simple check: if pattern ends with extension like *.tsx, just check if file ends with it\n if (pattern.startsWith('**/') || pattern.startsWith('*')) {\n const ext = pattern.replace(/^\\*\\*?\\//, '')\n if (ext.startsWith('*')) {\n // **/*.tsx -> check if ends with .tsx\n const ending = ext.replace(/^\\*/, '')\n return id.endsWith(ending)\n }\n }\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\./g, '\\\\.') // Escape dots\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*') // * matches any non-slash\n\n const regex = new RegExp(`^${regexPattern}$`)\n return regex.test(id)\n}\n\n/**\n * Remove Vite query parameters (e.g. ?import, ?v=123) from an id\n */\nfunction stripQuery(id: string): string {\n const queryStart = id.indexOf('?')\n return queryStart === -1 ? id : id.slice(0, queryStart)\n}\n\nfunction normalizeCacheOptions(\n cacheOption: FictPluginOptions['cache'],\n config?: ResolvedConfig,\n): NormalizedCacheOptions {\n const defaultPersistent = config?.command === 'build'\n const defaultDir = config?.cacheDir ? path.join(config.cacheDir, 'fict') : undefined\n\n if (cacheOption === false) {\n return { enabled: false, persistent: false, dir: undefined }\n }\n\n if (cacheOption === true || cacheOption === undefined) {\n return { enabled: true, persistent: defaultPersistent, dir: defaultDir }\n }\n\n return {\n enabled: cacheOption.enabled ?? true,\n persistent: cacheOption.persistent ?? defaultPersistent,\n dir: cacheOption.dir ?? defaultDir,\n }\n}\n\nfunction normalizeFileName(id: string, root?: string): string {\n let clean = stripQuery(id)\n if (clean.startsWith('/@fs/')) {\n clean = clean.slice('/@fs/'.length)\n }\n if (clean.startsWith('file://')) {\n try {\n clean = fileURLToPath(clean)\n } catch {\n // fall through\n }\n }\n if (path.isAbsolute(clean)) return path.normalize(clean)\n if (root) return path.normalize(path.resolve(root, clean))\n return path.normalize(path.resolve(clean))\n}\n\nfunction joinBasePath(base: string, fileName: string): string {\n if (!base) return fileName\n if (base === '/') return `/${fileName}`\n const normalized = base.endsWith('/') ? base : `${base}/`\n return `${normalized}${fileName}`\n}\n\ninterface AliasEntry {\n find: string | RegExp\n replacement: string\n}\n\nfunction normalizeAliases(aliases: ResolvedConfig['resolve']['alias'] | undefined): AliasEntry[] {\n if (!aliases) return []\n if (Array.isArray(aliases)) {\n return aliases\n .map(alias => {\n if (!alias || !('find' in alias)) return null\n const replacement =\n typeof alias.replacement === 'string' ? alias.replacement : String(alias.replacement)\n return { find: alias.find, replacement } as AliasEntry\n })\n .filter((alias): alias is AliasEntry => !!alias)\n }\n return Object.entries(aliases).map(([find, replacement]) => ({\n find,\n replacement: typeof replacement === 'string' ? replacement : String(replacement),\n }))\n}\n\nfunction applyAlias(source: string, aliases: AliasEntry[]): string | null {\n for (const alias of aliases) {\n if (typeof alias.find === 'string') {\n if (source === alias.find || source.startsWith(`${alias.find}/`)) {\n return alias.replacement + source.slice(alias.find.length)\n }\n continue\n }\n if (alias.find instanceof RegExp && alias.find.test(source)) {\n return source.replace(alias.find, alias.replacement)\n }\n }\n return null\n}\n\nfunction hashString(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value)\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`\n }\n\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined && typeof v !== 'function')\n .sort(([a], [b]) => a.localeCompare(b))\n\n const body = entries\n .map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`)\n .join(',')\n\n return `{${body}}`\n}\n\nfunction normalizeOptionsForCache(options: FictCompilerOptions): Record<string, unknown> {\n const normalized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || typeof value === 'function') continue\n if (key === 'typescript') {\n const tsInfo = value as {\n projectVersion?: number\n configPath?: string\n }\n normalized.typescript = {\n projectVersion: tsInfo?.projectVersion,\n configPath: tsInfo?.configPath,\n }\n continue\n }\n normalized[key] = value\n }\n return normalized\n}\n\nfunction buildCacheKey(\n filename: string,\n code: string,\n options: FictCompilerOptions,\n tsProject: TypeScriptProject | null,\n): string {\n const codeHash = hashString(code)\n const optionsHash = hashString(stableStringify(normalizeOptionsForCache(options)))\n const tsKey = tsProject ? `${tsProject.configHash}:${tsProject.projectVersion}` : ''\n return hashString([CACHE_VERSION, filename, codeHash, optionsHash, tsKey].join('|'))\n}\n\nclass TransformCache {\n private memory = new Map<string, CachedTransform>()\n\n constructor(private options: NormalizedCacheOptions) {}\n\n get enabled(): boolean {\n return this.options.enabled\n }\n\n async get(key: string): Promise<CachedTransform | null> {\n if (!this.options.enabled) return null\n const cached = this.memory.get(key)\n if (cached) return cached\n\n if (!this.options.persistent || !this.options.dir) return null\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n const raw = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CachedTransform\n if (!parsed || typeof parsed.code !== 'string') return null\n this.memory.set(key, parsed)\n return parsed\n } catch {\n return null\n }\n }\n\n async set(key: string, value: CachedTransform): Promise<void> {\n if (!this.options.enabled) return\n this.memory.set(key, value)\n if (!this.options.persistent || !this.options.dir) return\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n await fs.mkdir(this.options.dir, { recursive: true })\n await fs.writeFile(filePath, JSON.stringify(value))\n } catch {\n // Ignore cache write failures\n }\n }\n\n clear(): void {\n this.memory.clear()\n }\n}\n\nasync function loadTypeScript(): Promise<any | null> {\n try {\n const mod = await import('typescript')\n return (mod as any).default ?? mod\n } catch {\n return null\n }\n}\n\nfunction resolveTsconfigPath(ts: any, rootDir: string, explicitPath?: string): string | null {\n if (explicitPath) {\n return path.resolve(rootDir, explicitPath)\n }\n return ts.findConfigFile(rootDir, ts.sys.fileExists, 'tsconfig.json') ?? null\n}\n\nasync function createTypeScriptProject(\n ts: any,\n rootDir: string,\n configPath: string,\n): Promise<TypeScriptProject | null> {\n const configText = ts.sys.readFile(configPath)\n if (!configText) return null\n const configHash = hashString(configText)\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n if (configFile.error) return null\n\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath))\n\n const fileSet = new Set<string>(parsed.fileNames.map((name: string) => path.normalize(name)))\n const fileVersions = new Map<string, number>()\n const fileHashes = new Map<string, string>()\n const fileCache = new Map<string, string>()\n let projectVersion = 0\n\n const normalizeName = (fileName: string) => normalizeFileName(fileName, rootDir)\n\n const serviceHost = {\n getScriptFileNames: () => Array.from(fileSet),\n getScriptVersion: (fileName: string) => {\n const normalized = normalizeName(fileName)\n return String(fileVersions.get(normalized) ?? 0)\n },\n getScriptSnapshot: (fileName: string) => {\n const normalized = normalizeName(fileName)\n const text = fileCache.get(normalized) ?? ts.sys.readFile(normalized)\n if (text === undefined) return undefined\n return ts.ScriptSnapshot.fromString(text)\n },\n getCurrentDirectory: () => rootDir,\n getCompilationSettings: () => parsed.options,\n getDefaultLibFileName: (options: unknown) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getNewLine: () => ts.sys.newLine,\n getProjectVersion: () => String(projectVersion),\n }\n\n const service = ts.createLanguageService(serviceHost, ts.createDocumentRegistry())\n\n const updateFile = (fileName: string, code: string) => {\n const normalized = normalizeName(fileName)\n const nextHash = hashString(code)\n if (fileHashes.get(normalized) === nextHash) return\n fileHashes.set(normalized, nextHash)\n fileCache.set(normalized, code)\n fileVersions.set(normalized, (fileVersions.get(normalized) ?? 0) + 1)\n fileSet.add(normalized)\n projectVersion += 1\n }\n\n return {\n configPath,\n configHash,\n get projectVersion() {\n return projectVersion\n },\n updateFile,\n getProgram: () => service.getProgram?.() ?? null,\n resolveModuleName: (specifier: string, containingFile: string) => {\n try {\n const resolved = ts.resolveModuleName(specifier, containingFile, parsed.options, ts.sys)\n return resolved?.resolvedModule?.resolvedFileName ?? null\n } catch {\n return null\n }\n },\n dispose: () => service.dispose?.(),\n }\n}\n\n// ============================================================================\n// Function-level Code Splitting Helpers\n// ============================================================================\n\n/**\n * Parse a handler ID into source module and export name.\n * Format: /path/to/module.tsx$$exportName (using $$ as separator to avoid URL fragment conflicts)\n */\nfunction parseHandlerId(handlerId: string): [string | null, string | null] {\n const separatorIndex = handlerId.lastIndexOf('$$')\n if (separatorIndex === -1) {\n return [handlerId, 'default']\n }\n return [handlerId.slice(0, separatorIndex), handlerId.slice(separatorIndex + 2)]\n}\n\n/**\n * Generate handler ID from source module and export name.\n * Uses $$ as separator to avoid conflicts with URL # fragments.\n */\nfunction createHandlerId(sourceModule: string, exportName: string): string {\n return `${sourceModule}$$${exportName}`\n}\n\n/**\n * Generate a standalone virtual module for an extracted handler.\n * The module contains the complete handler code with its own imports,\n * creating a truly independent chunk that doesn't depend on the source module.\n */\nfunction generateHandlerModule(handler: ExtractedHandler): string {\n // If no code was extracted (fallback case), use re-export\n if (!handler.code) {\n return `export { ${handler.exportName} as default } from '${handler.sourceModule}';\\n`\n }\n\n // Group imports by source module\n const importsByModule = new Map<string, string[]>()\n\n for (const helperName of handler.helpersUsed) {\n const helper = RUNTIME_HELPERS[helperName]\n if (!helper) continue\n\n const existing = importsByModule.get(helper.from) ?? []\n if (!existing.includes(helper.import)) {\n existing.push(helper.import)\n }\n importsByModule.set(helper.from, existing)\n }\n\n // Generate import statements for runtime helpers\n const imports: string[] = []\n for (const [module, names] of importsByModule) {\n imports.push(`import { ${names.join(', ')} } from '${module}';`)\n }\n\n // Import local dependencies from the source module\n // These are re-exported by the source module with __fict_dep_ prefix\n if (handler.localDeps.length > 0) {\n const depImports = handler.localDeps.map(dep => `${HANDLER_DEP_PREFIX}${dep} as ${dep}`)\n imports.push(`import { ${depImports.join(', ')} } from '${handler.sourceModule}';`)\n }\n\n // Generate the complete standalone module\n return `${imports.join('\\n')}${imports.length > 0 ? '\\n\\n' : ''}export default ${handler.code};\\n`\n}\n\n/** Prefix for re-exported handler dependencies */\nconst HANDLER_DEP_PREFIX = '__fict_dep_'\n\n/**\n * Register an extracted handler for function-level splitting.\n */\nexport function registerExtractedHandler(\n sourceModule: string,\n exportName: string,\n helpersUsed: string[],\n code: string,\n localDeps: string[] = [],\n): string {\n const handlerId = createHandlerId(sourceModule, exportName)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName,\n helpersUsed,\n localDeps,\n code,\n })\n return `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n}\n\n/**\n * Runtime helper name mappings for generating imports in virtual modules\n */\nconst RUNTIME_HELPERS: Record<string, { import: string; from: string }> = {\n __fictUseLexicalScope: { import: '__fictUseLexicalScope', from: '@fictjs/runtime/internal' },\n __fictGetScopeProps: { import: '__fictGetScopeProps', from: '@fictjs/runtime/internal' },\n __fictGetSSRScope: { import: '__fictGetSSRScope', from: '@fictjs/runtime/internal' },\n __fictEnsureScope: { import: '__fictEnsureScope', from: '@fictjs/runtime/internal' },\n __fictPrepareContext: { import: '__fictPrepareContext', from: '@fictjs/runtime/internal' },\n __fictPushContext: { import: '__fictPushContext', from: '@fictjs/runtime/internal' },\n __fictPopContext: { import: '__fictPopContext', from: '@fictjs/runtime/internal' },\n hydrateComponent: { import: 'hydrateComponent', from: '@fictjs/runtime/internal' },\n __fictQrl: { import: '__fictQrl', from: '@fictjs/runtime/internal' },\n}\n\n/** Known global identifiers that don't need to be imported */\nconst GLOBAL_IDENTIFIERS = new Set([\n // JavaScript globals\n 'undefined',\n 'null',\n 'true',\n 'false',\n 'NaN',\n 'Infinity',\n 'globalThis',\n 'window',\n 'document',\n 'console',\n 'setTimeout',\n 'setInterval',\n 'clearTimeout',\n 'clearInterval',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'fetch',\n 'URL',\n 'URLSearchParams',\n 'FormData',\n 'Headers',\n 'Request',\n 'Response',\n 'AbortController',\n 'AbortSignal',\n // Built-in constructors\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Symbol',\n 'BigInt',\n 'Date',\n 'RegExp',\n 'Error',\n 'TypeError',\n 'RangeError',\n 'SyntaxError',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Proxy',\n 'Reflect',\n 'JSON',\n 'Math',\n 'Intl',\n // Event and DOM\n 'Event',\n 'CustomEvent',\n 'Element',\n 'Node',\n 'HTMLElement',\n])\n\n/**\n * Collect identifiers referenced in an AST node that are not locally defined.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectReferencedIdentifiers(node: t.Node, localBindings: Set<string>): Set<string> {\n const referenced = new Set<string>()\n\n function visitNode(\n current: t.Node | null | undefined,\n parent: t.Node | null,\n key: string | null,\n ): void {\n if (!current) return\n\n if (t.isIdentifier(current)) {\n const name = current.name\n\n // Skip if it's a property access (obj.prop) - only the object is a reference\n if (\n parent &&\n t.isMemberExpression(parent) &&\n parent.property === current &&\n !parent.computed\n ) {\n return\n }\n\n // Skip if it's a key in object property (non-computed)\n if (parent && t.isObjectProperty(parent) && parent.key === current && !parent.computed) {\n return\n }\n\n // Skip if it's a function/variable declaration name\n if (parent && t.isVariableDeclarator(parent) && parent.id === current) {\n return\n }\n if (\n parent &&\n (t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&\n parent.id === current\n ) {\n return\n }\n\n // Skip if it's a parameter\n if (key === 'params') {\n return\n }\n\n // Skip if it's a catch clause parameter\n if (parent && t.isCatchClause(parent) && parent.param === current) {\n return\n }\n\n // Skip local bindings (locally declared variables)\n if (localBindings.has(name)) {\n return\n }\n\n // Skip globals\n if (GLOBAL_IDENTIFIERS.has(name)) {\n return\n }\n\n // Skip runtime helpers\n if (RUNTIME_HELPERS[name]) {\n return\n }\n\n referenced.add(name)\n return\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node, current, nodeKey)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node, current, nodeKey)\n }\n }\n }\n\n visitNode(node, null, null)\n return referenced\n}\n\n/**\n * Collect all bindings (variables, functions, params) defined within an AST node.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectLocalBindings(node: t.Node): Set<string> {\n const bindings = new Set<string>()\n\n function visitNode(current: t.Node | null | undefined): void {\n if (!current) return\n\n // Handle variable declarations\n if (t.isVariableDeclarator(current)) {\n if (t.isIdentifier(current.id)) {\n bindings.add(current.id.name)\n } else if (t.isObjectPattern(current.id) || t.isArrayPattern(current.id)) {\n const names = collectPatternIdentifiers(current.id)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function declarations\n if (t.isFunctionDeclaration(current)) {\n if (current.id) {\n bindings.add(current.id.name)\n }\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function expressions\n if (t.isFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle arrow function expressions\n if (t.isArrowFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle catch clauses\n if (t.isCatchClause(current)) {\n if (current.param && t.isIdentifier(current.param)) {\n bindings.add(current.param.name)\n }\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node)\n }\n }\n }\n\n visitNode(node)\n\n return bindings\n}\n\n/**\n * Collect identifier names from a pattern (for destructuring).\n */\nfunction collectPatternIdentifiers(pattern: t.LVal | t.PatternLike): string[] {\n const names: string[] = []\n\n if (t.isIdentifier(pattern)) {\n names.push(pattern.name)\n } else if (t.isObjectPattern(pattern)) {\n for (const prop of pattern.properties) {\n if (t.isObjectProperty(prop) && t.isLVal(prop.value)) {\n names.push(...collectPatternIdentifiers(prop.value))\n } else if (t.isRestElement(prop)) {\n names.push(...collectPatternIdentifiers(prop.argument))\n }\n }\n } else if (t.isArrayPattern(pattern)) {\n for (const element of pattern.elements) {\n if (element) {\n names.push(...collectPatternIdentifiers(element))\n }\n }\n } else if (t.isRestElement(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.argument))\n } else if (t.isAssignmentPattern(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.left))\n }\n\n return names\n}\n\n/**\n * Extract handlers using Babel AST and rewrite QRLs to use virtual modules.\n * This creates truly independent chunks for each handler.\n * Local dependencies are detected and re-exported for handlers to import.\n */\nfunction extractAndRewriteHandlers(\n code: string,\n sourceModule: string,\n): { code: string; handlers: string[] } | null {\n let ast: ReturnType<typeof parse>\n\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n })\n } catch (e) {\n // If parsing fails, fall back to no extraction\n console.error('[fict-plugin] Parse error in extractAndRewriteHandlers:', e)\n return null\n }\n\n // Collect all top-level declarations that could be referenced by handlers\n const topLevelDeclarations = new Set<string>()\n const importedNames = new Set<string>()\n\n for (const node of ast.program.body) {\n // Collect imports\n if (t.isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n } else if (t.isImportNamespaceSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n }\n }\n continue\n }\n\n // Collect function declarations\n if (t.isFunctionDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect variable declarations\n if (t.isVariableDeclaration(node)) {\n for (const declarator of node.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n continue\n }\n\n // Collect class declarations\n if (t.isClassDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect exported declarations\n if (t.isExportNamedDeclaration(node) && node.declaration) {\n if (t.isFunctionDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n } else if (t.isVariableDeclaration(node.declaration)) {\n for (const declarator of node.declaration.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n } else if (t.isClassDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n }\n }\n }\n\n // Merge imports into top-level declarations (they're also available at top level)\n for (const name of importedNames) {\n topLevelDeclarations.add(name)\n }\n\n const handlerNames: string[] = []\n const nodesToRemove = new Set<t.Node>()\n const allLocalDeps = new Set<string>()\n\n // First pass: find all handler exports and extract their code\n traverse(ast, {\n ExportNamedDeclaration(path) {\n const declaration = path.node.declaration\n\n // Handle: export const __fict_e0 = (scopeId, event, el) => { ... }\n if (t.isVariableDeclaration(declaration)) {\n for (const declarator of declaration.declarations) {\n if (!t.isIdentifier(declarator.id)) continue\n\n const name = declarator.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) continue\n\n if (!declarator.init) continue\n\n handlerNames.push(name)\n\n // Generate the handler function code\n const handlerCode = generate(declarator.init).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(declarator.init)\n const referencedIds = collectReferencedIdentifiers(declarator.init, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n return\n }\n\n // Handle: export function __fict_e0(scopeId, event, el) { ... }\n if (t.isFunctionDeclaration(declaration) && declaration.id) {\n const name = declaration.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) return\n\n handlerNames.push(name)\n\n // Convert to arrow function expression for the virtual module\n const params = declaration.params\n const body = declaration.body\n const arrowFn = t.arrowFunctionExpression(params, body, declaration.async)\n\n // Generate the handler function code\n const handlerCode = generate(arrowFn).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(arrowFn)\n const referencedIds = collectReferencedIdentifiers(arrowFn, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n },\n })\n\n if (handlerNames.length === 0) {\n return null\n }\n\n // Second pass: remove handler exports, rewrite QRL calls, and add re-exports for dependencies\n traverse(ast, {\n ExportNamedDeclaration(path) {\n if (nodesToRemove.has(path.node)) {\n path.remove()\n }\n },\n\n CallExpression(path) {\n // Rewrite __fictQrl(import.meta.url, \"__fict_e0\") -> \"virtual:...\"\n if (!t.isIdentifier(path.node.callee, { name: '__fictQrl' })) return\n if (path.node.arguments.length !== 2) return\n\n const secondArg = path.node.arguments[1]\n if (!t.isStringLiteral(secondArg)) return\n\n const handlerName = secondArg.value\n if (!handlerNames.includes(handlerName)) return\n\n // Replace with the virtual module URL\n const handlerId = createHandlerId(sourceModule, handlerName)\n const virtualUrl = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}#default`\n path.replaceWith(t.stringLiteral(virtualUrl))\n },\n })\n\n // Add re-exports for local dependencies used by handlers\n // This allows handlers to import them from the source module\n if (allLocalDeps.size > 0) {\n const reExports: t.ExportSpecifier[] = []\n for (const dep of allLocalDeps) {\n // Export as __fict_dep_<name> to avoid conflicts\n reExports.push(\n t.exportSpecifier(t.identifier(dep), t.identifier(`${HANDLER_DEP_PREFIX}${dep}`)),\n )\n }\n ast.program.body.push(t.exportNamedDeclaration(null, reExports))\n }\n\n // Generate the modified code\n const result = generate(ast, {\n retainLines: true,\n compact: false,\n })\n\n return { code: result.code, handlers: handlerNames }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AACjB,SAAS,eAAe,qBAAqB;AAE7C,SAAS,sBAAsB;AAC/B,OAAO,eAAe;AACtB,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,YAAY,OAAO;AASnB,SAAS,wBAAkD;AAN3D,IAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAA4C;AAE7F,IAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAA4C;AAmE7F,IAAM,gBAAgB;AACtB,IAAM,oBAAoB,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,QAAQ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","tsProject","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nimport { transformAsync } from '@babel/core'\nimport _generate from '@babel/generator'\nimport { parse } from '@babel/parser'\nimport _traverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { createFictPlugin, type FictCompilerOptions } from '@fictjs/compiler'\nimport type { Plugin, ResolvedConfig, TransformResult } from 'vite'\n\n// Handle ESM/CJS interop for Babel packages\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse\nconst generate = (\n typeof _generate === 'function' ? _generate : (_generate as { default: typeof _generate }).default\n) as typeof _generate\n\nexport interface FictPluginOptions extends FictCompilerOptions {\n /**\n * File patterns to include for transformation.\n * @default ['**\\/*.tsx', '**\\/*.jsx']\n */\n include?: string[]\n /**\n * File patterns to exclude from transformation.\n * @default ['**\\/node_modules\\/**']\n */\n exclude?: string[]\n /**\n * Transform cache settings (memory + optional persistent disk cache).\n * Set to false to disable caching entirely.\n */\n cache?:\n | boolean\n | {\n enabled?: boolean\n persistent?: boolean\n dir?: string\n }\n /**\n * Explicit tsconfig path for TypeScript project integration.\n * If omitted, the plugin will search from Vite root.\n */\n tsconfigPath?: string\n /**\n * Enable TypeScript project integration when TypeScript is available.\n * @default true\n */\n useTypeScriptProject?: boolean\n /**\n * Enable function-level code splitting for resumable handlers.\n * When enabled, event handlers and resume functions are extracted\n * to separate chunks for optimal lazy loading.\n * @default false for dev, true for production build\n */\n functionSplitting?: boolean\n /**\n * Enable verbose debug logs from the plugin.\n * Can also be enabled via `FICT_VITE_PLUGIN_DEBUG=1`.\n * @default false\n */\n debug?: boolean\n}\n\ninterface NormalizedCacheOptions {\n enabled: boolean\n persistent: boolean\n dir?: string\n}\n\ninterface CachedTransform {\n code: string\n map: TransformResult['map']\n}\n\ninterface TypeScriptProject {\n configPath: string\n configHash: string\n readonly projectVersion: number\n updateFile: (fileName: string, code: string) => void\n getProgram: () => TypeScriptProgram | null\n resolveModuleName: (specifier: string, containingFile: string) => string | null\n dispose: () => void\n}\n\ninterface TypeScriptProgram {\n getTypeChecker?: () => unknown\n}\n\ninterface TypeScriptSystem {\n fileExists: (path: string) => boolean\n readFile: (path: string) => string | undefined\n readDirectory: (...args: unknown[]) => string[]\n directoryExists?: (path: string) => boolean\n getDirectories?: (path: string) => string[]\n useCaseSensitiveFileNames: boolean\n newLine: string\n}\n\ninterface TypeScriptParsedConfig {\n fileNames: string[]\n options: unknown\n}\n\ninterface TypeScriptLanguageService {\n getProgram?: () => TypeScriptProgram | null\n dispose?: () => void\n}\n\ninterface TypeScriptLanguageServiceHost {\n getScriptFileNames: () => string[]\n getScriptVersion: (fileName: string) => string\n getScriptSnapshot: (fileName: string) => unknown\n getCurrentDirectory: () => string\n getCompilationSettings: () => unknown\n getDefaultLibFileName: (options: unknown) => string\n fileExists: TypeScriptSystem['fileExists']\n readFile: TypeScriptSystem['readFile']\n readDirectory: TypeScriptSystem['readDirectory']\n directoryExists?: TypeScriptSystem['directoryExists']\n getDirectories?: TypeScriptSystem['getDirectories']\n useCaseSensitiveFileNames: () => boolean\n getNewLine: () => string\n getProjectVersion: () => string\n}\n\ninterface TypeScriptApi {\n sys: TypeScriptSystem\n findConfigFile: (\n searchPath: string,\n fileExists: TypeScriptSystem['fileExists'],\n configName: string,\n ) => string | undefined\n readConfigFile: (\n configPath: string,\n readFile: TypeScriptSystem['readFile'],\n ) => { config: unknown; error?: unknown }\n parseJsonConfigFileContent: (\n config: unknown,\n host: TypeScriptSystem,\n basePath: string,\n ) => TypeScriptParsedConfig\n ScriptSnapshot: {\n fromString: (text: string) => unknown\n }\n getDefaultLibFilePath: (options: unknown) => string\n createLanguageService: (\n host: TypeScriptLanguageServiceHost,\n registry: unknown,\n ) => TypeScriptLanguageService\n createDocumentRegistry: () => unknown\n resolveModuleName: (\n specifier: string,\n containingFile: string,\n options: unknown,\n host: TypeScriptSystem,\n ) => { resolvedModule?: { resolvedFileName?: string } } | undefined\n}\n\nconst CACHE_VERSION = 1\nconst MODULE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']\n\n// Virtual module prefix for extracted handlers\nconst VIRTUAL_HANDLER_PREFIX = '\\0fict-handler:'\nconst VIRTUAL_HANDLER_RESOLVE_PREFIX = 'virtual:fict-handler:'\n\n/**\n * Information about an extracted resumable handler\n */\ninterface ExtractedHandler {\n /** The module this handler was extracted from */\n sourceModule: string\n /** The export name in the source module */\n exportName: string\n /** Runtime helpers used by this handler */\n helpersUsed: string[]\n /** Local dependencies from source module that need to be re-exported */\n localDeps: string[]\n /** The handler function code (without export) */\n code: string\n}\n\n/**\n * Registry for extracted handlers during compilation\n */\nconst extractedHandlers = new Map<string, ExtractedHandler>()\n\n/**\n * Vite plugin for Fict reactive UI library.\n *\n * Transforms $state and $effect calls into reactive signals using the Fict compiler.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import fict from '@fictjs/vite-plugin'\n *\n * export default defineConfig({\n * plugins: [fict()],\n * })\n * ```\n */\nexport default function fict(options: FictPluginOptions = {}): Plugin {\n const {\n include = ['**/*.tsx', '**/*.jsx'],\n exclude = ['**/node_modules/**'],\n cache: cacheOption,\n tsconfigPath,\n useTypeScriptProject = true,\n debug: debugOption,\n ...compilerOptions\n } = options\n\n let config: ResolvedConfig | undefined\n let isDev = false\n let cache: TransformCache | null = null\n let tsProject: TypeScriptProject | null = null\n let tsProjectInit: Promise<TypeScriptProject | null> | null = null\n const moduleMetadata: FictCompilerOptions['moduleMetadata'] = new Map()\n const debugEnabled =\n debugOption === true ||\n process.env.FICT_VITE_PLUGIN_DEBUG === '1' ||\n process.env.FICT_VITE_PLUGIN_DEBUG === 'true'\n\n const debugLog = (message: string, details?: unknown) => {\n if (!debugEnabled) return\n const payload = details === undefined ? '' : ` ${safeDebugString(details)}`\n config?.logger?.info(`[fict-plugin] ${message}${payload}`)\n }\n\n const ensureCache = () => {\n if (cache) return cache\n const normalized = normalizeCacheOptions(cacheOption, config)\n cache = new TransformCache(normalized)\n return cache\n }\n\n const resetCache = () => {\n cache?.clear()\n cache = null\n }\n\n const ensureTypeScriptProject = async () => {\n if (!useTypeScriptProject) return null\n if (tsProject) return tsProject\n if (!tsProjectInit) {\n tsProjectInit = (async () => {\n const ts = await loadTypeScript()\n if (!ts) return null\n const rootDir = config?.root ?? process.cwd()\n const resolvedConfigPath = resolveTsconfigPath(ts, rootDir, tsconfigPath)\n if (!resolvedConfigPath) return null\n return createTypeScriptProject(ts, rootDir, resolvedConfigPath)\n })()\n }\n tsProject = await tsProjectInit\n return tsProject\n }\n\n const resetTypeScriptProject = () => {\n if (tsProject) {\n tsProject.dispose()\n }\n tsProject = null\n tsProjectInit = null\n }\n\n return {\n name: 'vite-plugin-fict',\n\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n config = resolvedConfig\n isDev = config.command === 'serve' || config.mode === 'development'\n // Rebuild cache with resolved config so cacheDir is available\n resetCache()\n // Clear extracted handlers from previous builds\n extractedHandlers.clear()\n },\n\n resolveId(id: string) {\n // Handle virtual handler modules\n if (id.startsWith(VIRTUAL_HANDLER_RESOLVE_PREFIX)) {\n return VIRTUAL_HANDLER_PREFIX + id.slice(VIRTUAL_HANDLER_RESOLVE_PREFIX.length)\n }\n return null\n },\n\n load(id: string) {\n // Load virtual handler modules\n if (!id.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n return null\n }\n\n const handlerId = id.slice(VIRTUAL_HANDLER_PREFIX.length)\n debugLog(`Loading virtual module: ${handlerId}`, {\n registrySize: extractedHandlers.size,\n handlers: Array.from(extractedHandlers.keys()),\n })\n const handler = extractedHandlers.get(handlerId)\n if (handler) {\n const generatedCode = generateHandlerModule(handler)\n debugLog(`Generated virtual module (${generatedCode.length} chars)`, {\n preview: generatedCode.slice(0, 200),\n })\n return generatedCode\n }\n\n if (!handler) {\n // In dev mode or when splitting is disabled, the handler is still in the main module\n // Generate a re-export from the source module\n const [sourceModule, exportName] = parseHandlerId(handlerId)\n if (sourceModule && exportName) {\n return `export { ${exportName} as default } from '${sourceModule}'`\n }\n return null\n }\n\n // Generate the virtual module with the handler code\n return generateHandlerModule(handler)\n },\n\n config(userConfig, env) {\n const userOptimize = userConfig.optimizeDeps\n const hasUserOptimize = !!userOptimize\n const hasDisabledOptimize =\n hasUserOptimize && (userOptimize as { disabled?: boolean }).disabled === true\n\n const include = new Set(userOptimize?.include ?? [])\n const exclude = new Set(userOptimize?.exclude ?? [])\n const dedupe = new Set((userConfig.resolve?.dedupe ?? []) as string[])\n\n // Avoid duplicate runtime instances between pre-bundled deps and /@fs modules.\n // Exclude all workspace packages from prebundling to ensure changes take effect\n // immediately without requiring node_modules reinstall.\n const workspaceDeps = [\n 'fict',\n 'fict/plus',\n 'fict/advanced',\n 'fict/slim',\n 'fict/jsx-runtime',\n 'fict/jsx-dev-runtime',\n '@fictjs/runtime',\n '@fictjs/runtime/internal',\n '@fictjs/runtime/advanced',\n '@fictjs/runtime/jsx-runtime',\n '@fictjs/runtime/jsx-dev-runtime',\n '@fictjs/compiler',\n '@fictjs/devtools',\n '@fictjs/devtools/core',\n '@fictjs/devtools/vite',\n '@fictjs/router',\n '@fictjs/ssr',\n '@fictjs/testing-library',\n ]\n for (const dep of workspaceDeps) {\n include.delete(dep)\n exclude.add(dep)\n }\n // Only dedupe core runtime packages to avoid duplicate instances\n const dedupePackages = ['fict', '@fictjs/runtime', '@fictjs/runtime/internal']\n for (const dep of dedupePackages) {\n dedupe.add(dep)\n }\n\n // Determine if we're in dev mode based on command or mode\n const devMode = env.command === 'serve' || env.mode === 'development'\n\n return {\n // Define __DEV__ for runtime devtools support\n // In dev mode, enable devtools; in production, disable them for smaller bundles\n define: {\n __DEV__: String(devMode),\n ...(userConfig.define ?? {}),\n },\n esbuild: {\n // Disable esbuild JSX handling for .tsx/.jsx files\n // Our plugin will handle the full transformation\n include: /\\.(ts|js|mts|mjs|cjs)$/,\n },\n build: {\n rollupOptions: {\n // Preserve exports in entry chunks to prevent tree-shaking of handler exports\n preserveEntrySignatures: 'exports-only',\n },\n },\n resolve: {\n ...(userConfig.resolve ?? {}),\n dedupe: Array.from(dedupe),\n },\n // Watch workspace packages dist directories for changes in dev mode\n // This ensures HMR picks up rebuilt packages without needing to restart\n server: {\n watch: {\n ignored: ['!**/node_modules/@fictjs/**', '!**/node_modules/fict/**'],\n },\n },\n ...(hasDisabledOptimize\n ? { optimizeDeps: userOptimize }\n : {\n optimizeDeps: hasUserOptimize\n ? { ...userOptimize, include: Array.from(include), exclude: Array.from(exclude) }\n : { exclude: workspaceDeps },\n }),\n }\n },\n\n async transform(code: string, id: string): Promise<TransformResult | null> {\n const filename = stripQuery(id)\n\n // Skip non-matching files\n if (!shouldTransform(filename, include, exclude)) {\n return null\n }\n\n const aliasEntries = normalizeAliases(config?.resolve?.alias)\n const fictOptions: FictCompilerOptions = {\n ...compilerOptions,\n dev: compilerOptions.dev ?? isDev,\n sourcemap: compilerOptions.sourcemap ?? true,\n filename,\n moduleMetadata,\n resolveModuleMetadata: (source, importer) => {\n const userResolved = compilerOptions.resolveModuleMetadata?.(source, importer)\n if (userResolved) return userResolved\n if (!importer) return undefined\n\n const importerFile = normalizeFileName(importer, config?.root)\n const lookupMetadata = (resolved: string) => {\n const direct = moduleMetadata.get(resolved)\n if (direct) return direct\n const ext = path.extname(resolved)\n if (!ext) {\n for (const suffix of MODULE_EXTENSIONS) {\n const byExt = moduleMetadata.get(`${resolved}${suffix}`)\n if (byExt) return byExt\n }\n for (const suffix of MODULE_EXTENSIONS) {\n const byIndex = moduleMetadata.get(path.join(resolved, `index${suffix}`))\n if (byIndex) return byIndex\n }\n }\n return undefined\n }\n let resolvedSource: string | null = null\n\n if (path.isAbsolute(source)) {\n resolvedSource = normalizeFileName(source, config?.root)\n } else if (source.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), source),\n config?.root,\n )\n } else {\n const aliased = applyAlias(source, aliasEntries)\n if (aliased) {\n if (path.isAbsolute(aliased)) {\n resolvedSource = normalizeFileName(aliased, config?.root)\n } else if (aliased.startsWith('.')) {\n resolvedSource = normalizeFileName(\n path.resolve(path.dirname(importerFile), aliased),\n config?.root,\n )\n } else if (config?.root) {\n resolvedSource = normalizeFileName(path.resolve(config.root, aliased), config?.root)\n }\n } else if (tsProject) {\n const tsResolved = tsProject.resolveModuleName(source, importerFile)\n if (tsResolved) {\n resolvedSource = normalizeFileName(tsResolved, config?.root)\n }\n }\n }\n\n if (!resolvedSource) return undefined\n return lookupMetadata(resolvedSource)\n },\n }\n\n const tsProject = await ensureTypeScriptProject()\n if (tsProject) {\n const resolvedName = normalizeFileName(filename, config?.root)\n tsProject.updateFile(resolvedName, code)\n const program = tsProject.getProgram()\n const checker =\n program && typeof program.getTypeChecker === 'function'\n ? program.getTypeChecker()\n : undefined\n fictOptions.typescript = {\n program: program ?? undefined,\n checker,\n projectVersion: tsProject.projectVersion,\n configPath: tsProject.configPath,\n }\n }\n\n const cacheStore = ensureCache()\n const cacheKey = cacheStore.enabled\n ? buildCacheKey(filename, code, fictOptions, tsProject)\n : null\n\n if (cacheKey) {\n const cached = await cacheStore.get(cacheKey)\n if (cached) {\n return cached\n }\n }\n\n try {\n const isTypeScript = filename.endsWith('.tsx') || filename.endsWith('.ts')\n\n const result = await transformAsync(code, {\n filename,\n sourceMaps: fictOptions.sourcemap,\n sourceFileName: filename,\n presets: isTypeScript\n ? [['@babel/preset-typescript', { isTSX: true, allExtensions: true }]]\n : [],\n plugins: [\n ['@babel/plugin-syntax-jsx', {}],\n [createFictPlugin, fictOptions],\n ],\n })\n\n if (!result || !result.code) {\n return null\n }\n\n let finalCode = result.code\n let finalMap = result.map as TransformResult['map']\n\n // Apply function-level code splitting in production builds\n // For SSR builds with resumable enabled, we also need to rewrite QRLs to virtual URLs\n // so they match the manifest generated by the client build\n const shouldSplit =\n options.functionSplitting ??\n (config?.command === 'build' && (compilerOptions.resumable || !config?.build?.ssr))\n\n debugLog('Function split decision', {\n shouldSplit,\n ssr: config?.build?.ssr,\n resumable: compilerOptions.resumable,\n file: filename,\n })\n if (shouldSplit) {\n let splitResult: { code: string; handlers: string[] } | null = null\n try {\n splitResult = extractAndRewriteHandlers(finalCode, filename)\n } catch (error) {\n this.warn(buildPluginMessage('extractAndRewriteHandlers failed', filename, error))\n }\n debugLog('Split result', {\n file: filename,\n handlers: splitResult?.handlers.length ?? 0,\n })\n if (splitResult) {\n debugLog(`Function splitting extracted ${splitResult.handlers.length} handlers`, {\n file: filename,\n })\n finalCode = splitResult.code\n // Note: source maps are invalidated by this rewrite\n // For production builds, this is acceptable\n finalMap = null\n\n // Emit each extracted handler as a separate chunk for lazy loading\n // This ensures the virtual modules are included in the build\n if (config?.command === 'build' && !config?.build?.ssr) {\n for (const handlerName of splitResult.handlers) {\n const handlerId = createHandlerId(filename, handlerName)\n const virtualModuleId = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n this.emitFile({\n type: 'chunk',\n id: virtualModuleId,\n name: `handler-${handlerName}`,\n })\n }\n }\n }\n }\n\n const transformed: TransformResult = {\n code: finalCode,\n map: finalMap,\n }\n\n if (cacheKey) {\n await cacheStore.set(cacheKey, transformed)\n }\n\n return transformed\n } catch (error) {\n // Better error handling\n const message =\n error instanceof Error ? error.message : 'Unknown error during Fict transformation'\n\n this.error({\n message: `[fict] Transform failed for ${id}: ${message}`,\n id,\n })\n\n return null\n }\n },\n\n handleHotUpdate({ file, server }) {\n if (tsProject && file === tsProject.configPath) {\n resetTypeScriptProject()\n resetCache()\n }\n\n // Force full reload for .tsx/.jsx files to ensure reactive graph is rebuilt\n if (shouldTransform(file, include, exclude)) {\n server.ws.send({\n type: 'full-reload',\n path: '*',\n })\n }\n },\n\n generateBundle(_options, bundle) {\n if (!config || config.command !== 'build') return\n if (config.build.ssr) return\n\n const base = config.base ?? '/'\n const manifest: Record<string, string> = {}\n\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk') continue\n const fileName = output.fileName\n const url = joinBasePath(base, fileName)\n for (const moduleId of Object.keys(output.modules)) {\n if (!moduleId) continue\n\n // Handle virtual handler modules\n if (moduleId.startsWith(VIRTUAL_HANDLER_PREFIX)) {\n const handlerId = moduleId.slice(VIRTUAL_HANDLER_PREFIX.length)\n // Map the virtual module resolve prefix to the chunk URL\n const virtualKey = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n if (!manifest[virtualKey]) {\n manifest[virtualKey] = url\n }\n continue\n }\n\n // Skip other virtual modules\n if (moduleId.startsWith('\\0')) continue\n\n const normalized = normalizeFileName(moduleId, config.root)\n if (!path.isAbsolute(normalized)) continue\n const key = pathToFileURL(normalized).href\n if (!manifest[key]) {\n manifest[key] = url\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'fict.manifest.json',\n source: JSON.stringify(manifest),\n })\n },\n }\n}\n\n/**\n * Check if a file should be transformed based on include/exclude patterns\n */\nfunction shouldTransform(id: string, include: string[], exclude: string[]): boolean {\n // Normalize path separators\n const normalizedId = stripQuery(id).replace(/\\\\/g, '/')\n\n // Check exclude patterns first\n for (const pattern of exclude) {\n if (matchPattern(normalizedId, pattern)) {\n return false\n }\n }\n\n // Check include patterns\n for (const pattern of include) {\n if (matchPattern(normalizedId, pattern)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Simple glob pattern matching\n * Supports: **\\/*.ext, *.ext, exact matches\n */\nfunction matchPattern(id: string, pattern: string): boolean {\n // Exact match\n if (id === pattern) return true\n\n // Simple check: if pattern ends with extension like *.tsx, just check if file ends with it\n if (pattern.startsWith('**/') || pattern.startsWith('*')) {\n const ext = pattern.replace(/^\\*\\*?\\//, '')\n if (ext.startsWith('*')) {\n // **/*.tsx -> check if ends with .tsx\n const ending = ext.replace(/^\\*/, '')\n return id.endsWith(ending)\n }\n }\n\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\./g, '\\\\.') // Escape dots\n .replace(/\\*\\*/g, '.*') // ** matches any path\n .replace(/\\*/g, '[^/]*') // * matches any non-slash\n\n const regex = new RegExp(`^${regexPattern}$`)\n return regex.test(id)\n}\n\n/**\n * Remove Vite query parameters (e.g. ?import, ?v=123) from an id\n */\nfunction stripQuery(id: string): string {\n const queryStart = id.indexOf('?')\n return queryStart === -1 ? id : id.slice(0, queryStart)\n}\n\nfunction normalizeCacheOptions(\n cacheOption: FictPluginOptions['cache'],\n config?: ResolvedConfig,\n): NormalizedCacheOptions {\n const defaultPersistent = config?.command === 'build'\n const defaultDir = config?.cacheDir ? path.join(config.cacheDir, 'fict') : undefined\n\n if (cacheOption === false) {\n return { enabled: false, persistent: false, dir: undefined }\n }\n\n if (cacheOption === true || cacheOption === undefined) {\n return { enabled: true, persistent: defaultPersistent, dir: defaultDir }\n }\n\n return {\n enabled: cacheOption.enabled ?? true,\n persistent: cacheOption.persistent ?? defaultPersistent,\n dir: cacheOption.dir ?? defaultDir,\n }\n}\n\nfunction normalizeFileName(id: string, root?: string): string {\n let clean = stripQuery(id)\n if (clean.startsWith('/@fs/')) {\n clean = clean.slice('/@fs/'.length)\n }\n if (clean.startsWith('file://')) {\n try {\n clean = fileURLToPath(clean)\n } catch {\n // fall through\n }\n }\n if (path.isAbsolute(clean)) return path.normalize(clean)\n if (root) return path.normalize(path.resolve(root, clean))\n return path.normalize(path.resolve(clean))\n}\n\nfunction joinBasePath(base: string, fileName: string): string {\n if (!base) return fileName\n if (base === '/') return `/${fileName}`\n const normalized = base.endsWith('/') ? base : `${base}/`\n return `${normalized}${fileName}`\n}\n\ninterface AliasEntry {\n find: string | RegExp\n replacement: string\n}\n\nfunction normalizeAliases(aliases: ResolvedConfig['resolve']['alias'] | undefined): AliasEntry[] {\n if (!aliases) return []\n if (Array.isArray(aliases)) {\n return aliases\n .map(alias => {\n if (!alias || !('find' in alias)) return null\n const replacement =\n typeof alias.replacement === 'string' ? alias.replacement : String(alias.replacement)\n return { find: alias.find, replacement } as AliasEntry\n })\n .filter((alias): alias is AliasEntry => !!alias)\n }\n return Object.entries(aliases).map(([find, replacement]) => ({\n find,\n replacement: typeof replacement === 'string' ? replacement : String(replacement),\n }))\n}\n\nfunction applyAlias(source: string, aliases: AliasEntry[]): string | null {\n for (const alias of aliases) {\n if (typeof alias.find === 'string') {\n if (source === alias.find || source.startsWith(`${alias.find}/`)) {\n return alias.replacement + source.slice(alias.find.length)\n }\n continue\n }\n if (alias.find instanceof RegExp && alias.find.test(source)) {\n return source.replace(alias.find, alias.replacement)\n }\n }\n return null\n}\n\nfunction hashString(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value)\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`\n }\n\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined && typeof v !== 'function')\n .sort(([a], [b]) => a.localeCompare(b))\n\n const body = entries\n .map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`)\n .join(',')\n\n return `{${body}}`\n}\n\nfunction normalizeOptionsForCache(options: FictCompilerOptions): Record<string, unknown> {\n const normalized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || typeof value === 'function') continue\n if (key === 'typescript') {\n const tsInfo = value as {\n projectVersion?: number\n configPath?: string\n }\n normalized.typescript = {\n projectVersion: tsInfo?.projectVersion,\n configPath: tsInfo?.configPath,\n }\n continue\n }\n normalized[key] = value\n }\n return normalized\n}\n\nfunction buildCacheKey(\n filename: string,\n code: string,\n options: FictCompilerOptions,\n tsProject: TypeScriptProject | null,\n): string {\n const codeHash = hashString(code)\n const optionsHash = hashString(stableStringify(normalizeOptionsForCache(options)))\n const tsKey = tsProject ? `${tsProject.configHash}:${tsProject.projectVersion}` : ''\n return hashString([CACHE_VERSION, filename, codeHash, optionsHash, tsKey].join('|'))\n}\n\nclass TransformCache {\n private memory = new Map<string, CachedTransform>()\n\n constructor(private options: NormalizedCacheOptions) {}\n\n get enabled(): boolean {\n return this.options.enabled\n }\n\n async get(key: string): Promise<CachedTransform | null> {\n if (!this.options.enabled) return null\n const cached = this.memory.get(key)\n if (cached) return cached\n\n if (!this.options.persistent || !this.options.dir) return null\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n const raw = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CachedTransform\n if (!parsed || typeof parsed.code !== 'string') return null\n this.memory.set(key, parsed)\n return parsed\n } catch {\n return null\n }\n }\n\n async set(key: string, value: CachedTransform): Promise<void> {\n if (!this.options.enabled) return\n this.memory.set(key, value)\n if (!this.options.persistent || !this.options.dir) return\n\n const filePath = path.join(this.options.dir, `${key}.json`)\n try {\n await fs.mkdir(this.options.dir, { recursive: true })\n await fs.writeFile(filePath, JSON.stringify(value))\n } catch {\n // Ignore cache write failures\n }\n }\n\n clear(): void {\n this.memory.clear()\n }\n}\n\nfunction isTypeScriptApi(value: unknown): value is TypeScriptApi {\n if (!value || typeof value !== 'object') return false\n const candidate = value as Partial<TypeScriptApi>\n return (\n typeof candidate.findConfigFile === 'function' &&\n typeof candidate.readConfigFile === 'function' &&\n typeof candidate.parseJsonConfigFileContent === 'function' &&\n typeof candidate.createLanguageService === 'function' &&\n typeof candidate.createDocumentRegistry === 'function' &&\n typeof candidate.resolveModuleName === 'function' &&\n !!candidate.sys &&\n typeof candidate.sys === 'object' &&\n typeof candidate.sys.fileExists === 'function' &&\n typeof candidate.sys.readFile === 'function'\n )\n}\n\nfunction safeDebugString(value: unknown): string {\n try {\n return typeof value === 'string' ? value : JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatError(error: unknown): string {\n if (error instanceof Error) return error.message\n try {\n return JSON.stringify(error)\n } catch {\n return String(error)\n }\n}\n\nfunction buildPluginMessage(context: string, file: string, error: unknown): string {\n return `[fict-plugin] ${context} (${file}): ${formatError(error)}`\n}\n\nasync function loadTypeScript(): Promise<TypeScriptApi | null> {\n try {\n const mod = await import('typescript')\n const candidate = (mod as { default?: unknown }).default ?? mod\n return isTypeScriptApi(candidate) ? candidate : null\n } catch {\n return null\n }\n}\n\nfunction resolveTsconfigPath(\n ts: TypeScriptApi,\n rootDir: string,\n explicitPath?: string,\n): string | null {\n if (explicitPath) {\n return path.resolve(rootDir, explicitPath)\n }\n return ts.findConfigFile(rootDir, ts.sys.fileExists, 'tsconfig.json') ?? null\n}\n\nasync function createTypeScriptProject(\n ts: TypeScriptApi,\n rootDir: string,\n configPath: string,\n): Promise<TypeScriptProject | null> {\n const configText = ts.sys.readFile(configPath)\n if (!configText) return null\n const configHash = hashString(configText)\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n if (configFile.error) return null\n\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath))\n\n const fileSet = new Set<string>(parsed.fileNames.map((name: string) => path.normalize(name)))\n const fileVersions = new Map<string, number>()\n const fileHashes = new Map<string, string>()\n const fileCache = new Map<string, string>()\n let projectVersion = 0\n\n const normalizeName = (fileName: string) => normalizeFileName(fileName, rootDir)\n\n const serviceHost: TypeScriptLanguageServiceHost = {\n getScriptFileNames: () => Array.from(fileSet),\n getScriptVersion: (fileName: string) => {\n const normalized = normalizeName(fileName)\n return String(fileVersions.get(normalized) ?? 0)\n },\n getScriptSnapshot: (fileName: string) => {\n const normalized = normalizeName(fileName)\n const text = fileCache.get(normalized) ?? ts.sys.readFile(normalized)\n if (text === undefined) return undefined\n return ts.ScriptSnapshot.fromString(text)\n },\n getCurrentDirectory: () => rootDir,\n getCompilationSettings: () => parsed.options,\n getDefaultLibFileName: (options: unknown) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getNewLine: () => ts.sys.newLine,\n getProjectVersion: () => String(projectVersion),\n }\n\n const service = ts.createLanguageService(serviceHost, ts.createDocumentRegistry())\n\n const updateFile = (fileName: string, code: string) => {\n const normalized = normalizeName(fileName)\n const nextHash = hashString(code)\n if (fileHashes.get(normalized) === nextHash) return\n fileHashes.set(normalized, nextHash)\n fileCache.set(normalized, code)\n fileVersions.set(normalized, (fileVersions.get(normalized) ?? 0) + 1)\n fileSet.add(normalized)\n projectVersion += 1\n }\n\n return {\n configPath,\n configHash,\n get projectVersion() {\n return projectVersion\n },\n updateFile,\n getProgram: () => service.getProgram?.() ?? null,\n resolveModuleName: (specifier: string, containingFile: string) => {\n try {\n const resolved = ts.resolveModuleName(specifier, containingFile, parsed.options, ts.sys)\n return resolved?.resolvedModule?.resolvedFileName ?? null\n } catch {\n return null\n }\n },\n dispose: () => service.dispose?.(),\n }\n}\n\n// ============================================================================\n// Function-level Code Splitting Helpers\n// ============================================================================\n\n/**\n * Parse a handler ID into source module and export name.\n * Format: /path/to/module.tsx$$exportName (using $$ as separator to avoid URL fragment conflicts)\n */\nfunction parseHandlerId(handlerId: string): [string | null, string | null] {\n const separatorIndex = handlerId.lastIndexOf('$$')\n if (separatorIndex === -1) {\n return [handlerId, 'default']\n }\n return [handlerId.slice(0, separatorIndex), handlerId.slice(separatorIndex + 2)]\n}\n\n/**\n * Generate handler ID from source module and export name.\n * Uses $$ as separator to avoid conflicts with URL # fragments.\n */\nfunction createHandlerId(sourceModule: string, exportName: string): string {\n return `${sourceModule}$$${exportName}`\n}\n\n/**\n * Generate a standalone virtual module for an extracted handler.\n * The module contains the complete handler code with its own imports,\n * creating a truly independent chunk that doesn't depend on the source module.\n */\nfunction generateHandlerModule(handler: ExtractedHandler): string {\n // If no code was extracted (fallback case), use re-export\n if (!handler.code) {\n return `export { ${handler.exportName} as default } from '${handler.sourceModule}';\\n`\n }\n\n // Group imports by source module\n const importsByModule = new Map<string, string[]>()\n\n for (const helperName of handler.helpersUsed) {\n const helper = RUNTIME_HELPERS[helperName]\n if (!helper) continue\n\n const existing = importsByModule.get(helper.from) ?? []\n if (!existing.includes(helper.import)) {\n existing.push(helper.import)\n }\n importsByModule.set(helper.from, existing)\n }\n\n // Generate import statements for runtime helpers\n const imports: string[] = []\n for (const [module, names] of importsByModule) {\n imports.push(`import { ${names.join(', ')} } from '${module}';`)\n }\n\n // Import local dependencies from the source module\n // These are re-exported by the source module with __fict_dep_ prefix\n if (handler.localDeps.length > 0) {\n const depImports = handler.localDeps.map(dep => `${HANDLER_DEP_PREFIX}${dep} as ${dep}`)\n imports.push(`import { ${depImports.join(', ')} } from '${handler.sourceModule}';`)\n }\n\n // Generate the complete standalone module\n return `${imports.join('\\n')}${imports.length > 0 ? '\\n\\n' : ''}export default ${handler.code};\\n`\n}\n\n/** Prefix for re-exported handler dependencies */\nconst HANDLER_DEP_PREFIX = '__fict_dep_'\n\n/**\n * Register an extracted handler for function-level splitting.\n */\nexport function registerExtractedHandler(\n sourceModule: string,\n exportName: string,\n helpersUsed: string[],\n code: string,\n localDeps: string[] = [],\n): string {\n const handlerId = createHandlerId(sourceModule, exportName)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName,\n helpersUsed,\n localDeps,\n code,\n })\n return `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}`\n}\n\n/**\n * Runtime helper name mappings for generating imports in virtual modules\n */\nconst RUNTIME_HELPERS: Record<string, { import: string; from: string }> = {\n __fictUseLexicalScope: { import: '__fictUseLexicalScope', from: '@fictjs/runtime/internal' },\n __fictGetScopeProps: { import: '__fictGetScopeProps', from: '@fictjs/runtime/internal' },\n __fictGetSSRScope: { import: '__fictGetSSRScope', from: '@fictjs/runtime/internal' },\n __fictEnsureScope: { import: '__fictEnsureScope', from: '@fictjs/runtime/internal' },\n __fictPrepareContext: { import: '__fictPrepareContext', from: '@fictjs/runtime/internal' },\n __fictPushContext: { import: '__fictPushContext', from: '@fictjs/runtime/internal' },\n __fictPopContext: { import: '__fictPopContext', from: '@fictjs/runtime/internal' },\n hydrateComponent: { import: 'hydrateComponent', from: '@fictjs/runtime/internal' },\n __fictQrl: { import: '__fictQrl', from: '@fictjs/runtime/internal' },\n}\n\n/** Known global identifiers that don't need to be imported */\nconst GLOBAL_IDENTIFIERS = new Set([\n // JavaScript globals\n 'undefined',\n 'null',\n 'true',\n 'false',\n 'NaN',\n 'Infinity',\n 'globalThis',\n 'window',\n 'document',\n 'console',\n 'setTimeout',\n 'setInterval',\n 'clearTimeout',\n 'clearInterval',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'fetch',\n 'URL',\n 'URLSearchParams',\n 'FormData',\n 'Headers',\n 'Request',\n 'Response',\n 'AbortController',\n 'AbortSignal',\n // Built-in constructors\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Symbol',\n 'BigInt',\n 'Date',\n 'RegExp',\n 'Error',\n 'TypeError',\n 'RangeError',\n 'SyntaxError',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Proxy',\n 'Reflect',\n 'JSON',\n 'Math',\n 'Intl',\n // Event and DOM\n 'Event',\n 'CustomEvent',\n 'Element',\n 'Node',\n 'HTMLElement',\n])\n\n/**\n * Collect identifiers referenced in an AST node that are not locally defined.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectReferencedIdentifiers(node: t.Node, localBindings: Set<string>): Set<string> {\n const referenced = new Set<string>()\n\n function visitNode(\n current: t.Node | null | undefined,\n parent: t.Node | null,\n key: string | null,\n ): void {\n if (!current) return\n\n if (t.isIdentifier(current)) {\n const name = current.name\n\n // Skip if it's a property access (obj.prop) - only the object is a reference\n if (\n parent &&\n t.isMemberExpression(parent) &&\n parent.property === current &&\n !parent.computed\n ) {\n return\n }\n\n // Skip if it's a key in object property (non-computed)\n if (parent && t.isObjectProperty(parent) && parent.key === current && !parent.computed) {\n return\n }\n\n // Skip if it's a function/variable declaration name\n if (parent && t.isVariableDeclarator(parent) && parent.id === current) {\n return\n }\n if (\n parent &&\n (t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&\n parent.id === current\n ) {\n return\n }\n\n // Skip if it's a parameter\n if (key === 'params') {\n return\n }\n\n // Skip if it's a catch clause parameter\n if (parent && t.isCatchClause(parent) && parent.param === current) {\n return\n }\n\n // Skip local bindings (locally declared variables)\n if (localBindings.has(name)) {\n return\n }\n\n // Skip globals\n if (GLOBAL_IDENTIFIERS.has(name)) {\n return\n }\n\n // Skip runtime helpers\n if (RUNTIME_HELPERS[name]) {\n return\n }\n\n referenced.add(name)\n return\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node, current, nodeKey)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node, current, nodeKey)\n }\n }\n }\n\n visitNode(node, null, null)\n return referenced\n}\n\n/**\n * Collect all bindings (variables, functions, params) defined within an AST node.\n * Uses simple recursive traversal instead of Babel's traverse to work on sub-nodes.\n */\nfunction collectLocalBindings(node: t.Node): Set<string> {\n const bindings = new Set<string>()\n\n function visitNode(current: t.Node | null | undefined): void {\n if (!current) return\n\n // Handle variable declarations\n if (t.isVariableDeclarator(current)) {\n if (t.isIdentifier(current.id)) {\n bindings.add(current.id.name)\n } else if (t.isObjectPattern(current.id) || t.isArrayPattern(current.id)) {\n const names = collectPatternIdentifiers(current.id)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function declarations\n if (t.isFunctionDeclaration(current)) {\n if (current.id) {\n bindings.add(current.id.name)\n }\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle function expressions\n if (t.isFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle arrow function expressions\n if (t.isArrowFunctionExpression(current)) {\n for (const param of current.params) {\n const names = collectPatternIdentifiers(param)\n for (const name of names) {\n bindings.add(name)\n }\n }\n }\n\n // Handle catch clauses\n if (t.isCatchClause(current)) {\n if (current.param && t.isIdentifier(current.param)) {\n bindings.add(current.param.name)\n }\n }\n\n // Recursively visit child nodes\n for (const nodeKey of Object.keys(current)) {\n // Skip metadata keys that aren't child nodes\n if (\n nodeKey === 'loc' ||\n nodeKey === 'start' ||\n nodeKey === 'end' ||\n nodeKey === 'extra' ||\n nodeKey === 'comments' ||\n nodeKey === 'leadingComments' ||\n nodeKey === 'trailingComments' ||\n nodeKey === 'innerComments'\n ) {\n continue\n }\n const child = (current as unknown as Record<string, unknown>)[nodeKey]\n if (Array.isArray(child)) {\n for (const item of child) {\n if (\n item &&\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n typeof (item as Record<string, unknown>).type === 'string'\n ) {\n visitNode(item as t.Node)\n }\n }\n } else if (\n child &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as Record<string, unknown>).type === 'string'\n ) {\n visitNode(child as t.Node)\n }\n }\n }\n\n visitNode(node)\n\n return bindings\n}\n\n/**\n * Collect identifier names from a pattern (for destructuring).\n */\nfunction collectPatternIdentifiers(pattern: t.LVal | t.PatternLike): string[] {\n const names: string[] = []\n\n if (t.isIdentifier(pattern)) {\n names.push(pattern.name)\n } else if (t.isObjectPattern(pattern)) {\n for (const prop of pattern.properties) {\n if (t.isObjectProperty(prop) && t.isLVal(prop.value)) {\n names.push(...collectPatternIdentifiers(prop.value))\n } else if (t.isRestElement(prop)) {\n names.push(...collectPatternIdentifiers(prop.argument))\n }\n }\n } else if (t.isArrayPattern(pattern)) {\n for (const element of pattern.elements) {\n if (element) {\n names.push(...collectPatternIdentifiers(element))\n }\n }\n } else if (t.isRestElement(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.argument))\n } else if (t.isAssignmentPattern(pattern)) {\n names.push(...collectPatternIdentifiers(pattern.left))\n }\n\n return names\n}\n\n/**\n * Extract handlers using Babel AST and rewrite QRLs to use virtual modules.\n * This creates truly independent chunks for each handler.\n * Local dependencies are detected and re-exported for handlers to import.\n */\nfunction extractAndRewriteHandlers(\n code: string,\n sourceModule: string,\n): { code: string; handlers: string[] } | null {\n let ast: ReturnType<typeof parse>\n\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n })\n } catch (error) {\n throw new Error(\n buildPluginMessage(\n 'Failed to parse transformed code for handler extraction',\n sourceModule,\n error,\n ),\n )\n }\n\n // Collect all top-level declarations that could be referenced by handlers\n const topLevelDeclarations = new Set<string>()\n const importedNames = new Set<string>()\n\n for (const node of ast.program.body) {\n // Collect imports\n if (t.isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n } else if (t.isImportNamespaceSpecifier(specifier)) {\n importedNames.add(specifier.local.name)\n }\n }\n continue\n }\n\n // Collect function declarations\n if (t.isFunctionDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect variable declarations\n if (t.isVariableDeclaration(node)) {\n for (const declarator of node.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n continue\n }\n\n // Collect class declarations\n if (t.isClassDeclaration(node) && node.id) {\n topLevelDeclarations.add(node.id.name)\n continue\n }\n\n // Collect exported declarations\n if (t.isExportNamedDeclaration(node) && node.declaration) {\n if (t.isFunctionDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n } else if (t.isVariableDeclaration(node.declaration)) {\n for (const declarator of node.declaration.declarations) {\n if (t.isIdentifier(declarator.id)) {\n topLevelDeclarations.add(declarator.id.name)\n }\n }\n } else if (t.isClassDeclaration(node.declaration) && node.declaration.id) {\n topLevelDeclarations.add(node.declaration.id.name)\n }\n }\n }\n\n // Merge imports into top-level declarations (they're also available at top level)\n for (const name of importedNames) {\n topLevelDeclarations.add(name)\n }\n\n const handlerNames: string[] = []\n const nodesToRemove = new Set<t.Node>()\n const allLocalDeps = new Set<string>()\n\n // First pass: find all handler exports and extract their code\n traverse(ast, {\n ExportNamedDeclaration(path) {\n const declaration = path.node.declaration\n\n // Handle: export const __fict_e0 = (scopeId, event, el) => { ... }\n if (t.isVariableDeclaration(declaration)) {\n for (const declarator of declaration.declarations) {\n if (!t.isIdentifier(declarator.id)) continue\n\n const name = declarator.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) continue\n\n if (!declarator.init) continue\n\n handlerNames.push(name)\n\n // Generate the handler function code\n const handlerCode = generate(declarator.init).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(declarator.init)\n const referencedIds = collectReferencedIdentifiers(declarator.init, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n return\n }\n\n // Handle: export function __fict_e0(scopeId, event, el) { ... }\n if (t.isFunctionDeclaration(declaration) && declaration.id) {\n const name = declaration.id.name\n // Only extract event handlers (__fict_e*), not resume handlers (__fict_r*)\n // Resume handlers have complex component dependencies that can't be easily extracted\n if (!name.match(/^__fict_e\\d+$/)) return\n\n handlerNames.push(name)\n\n // Convert to arrow function expression for the virtual module\n const params = declaration.params\n const body = declaration.body\n const arrowFn = t.arrowFunctionExpression(params, body, declaration.async)\n\n // Generate the handler function code\n const handlerCode = generate(arrowFn).code\n\n // Detect which runtime helpers are used\n const helpersUsed: string[] = []\n for (const helperName of Object.keys(RUNTIME_HELPERS)) {\n if (handlerCode.includes(helperName)) {\n helpersUsed.push(helperName)\n }\n }\n\n // Detect local dependencies\n const localBindings = collectLocalBindings(arrowFn)\n const referencedIds = collectReferencedIdentifiers(arrowFn, localBindings)\n const localDeps: string[] = []\n for (const ref of referencedIds) {\n // Only include if it's a top-level declaration (not a handler itself)\n if (topLevelDeclarations.has(ref) && !ref.match(/^__fict_[er]\\d+$/)) {\n localDeps.push(ref)\n allLocalDeps.add(ref)\n }\n }\n\n // Register the handler with its full code\n const handlerId = createHandlerId(sourceModule, name)\n extractedHandlers.set(handlerId, {\n sourceModule,\n exportName: name,\n helpersUsed,\n localDeps,\n code: handlerCode,\n })\n\n // Mark this export for removal\n nodesToRemove.add(path.node)\n }\n },\n })\n\n if (handlerNames.length === 0) {\n return null\n }\n\n // Second pass: remove handler exports, rewrite QRL calls, and add re-exports for dependencies\n traverse(ast, {\n ExportNamedDeclaration(path) {\n if (nodesToRemove.has(path.node)) {\n path.remove()\n }\n },\n\n CallExpression(path) {\n // Rewrite __fictQrl(import.meta.url, \"__fict_e0\") -> \"virtual:...\"\n if (!t.isIdentifier(path.node.callee, { name: '__fictQrl' })) return\n if (path.node.arguments.length !== 2) return\n\n const secondArg = path.node.arguments[1]\n if (!t.isStringLiteral(secondArg)) return\n\n const handlerName = secondArg.value\n if (!handlerNames.includes(handlerName)) return\n\n // Replace with the virtual module URL\n const handlerId = createHandlerId(sourceModule, handlerName)\n const virtualUrl = `${VIRTUAL_HANDLER_RESOLVE_PREFIX}${handlerId}#default`\n path.replaceWith(t.stringLiteral(virtualUrl))\n },\n })\n\n // Add re-exports for local dependencies used by handlers\n // This allows handlers to import them from the source module\n if (allLocalDeps.size > 0) {\n const reExports: t.ExportSpecifier[] = []\n for (const dep of allLocalDeps) {\n // Export as __fict_dep_<name> to avoid conflicts\n reExports.push(\n t.exportSpecifier(t.identifier(dep), t.identifier(`${HANDLER_DEP_PREFIX}${dep}`)),\n )\n }\n ast.program.body.push(t.exportNamedDeclaration(null, reExports))\n }\n\n // Generate the modified code\n const result = generate(ast, {\n retainLines: true,\n compact: false,\n })\n\n return { code: result.code, handlers: handlerNames }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AACjB,SAAS,eAAe,qBAAqB;AAE7C,SAAS,sBAAsB;AAC/B,OAAO,eAAe;AACtB,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,YAAY,OAAO;AACnB,SAAS,wBAAkD;AAI3D,IAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAA4C;AAE7F,IAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAA4C;AAiJ7F,IAAM,gBAAgB;AACtB,IAAM,oBAAoB,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,MAAM;AAGvF,IAAM,yBAAyB;AAC/B,IAAM,iCAAiC;AAqBvC,IAAM,oBAAoB,oBAAI,IAA8B;AAkB7C,SAAR,KAAsB,UAA6B,CA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description": "Vite plugin for Fict",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"@babel/preset-typescript": "^7.26.0",
|
|
38
38
|
"@babel/traverse": "^7.28.6",
|
|
39
39
|
"@babel/types": "^7.28.6",
|
|
40
|
-
"@fictjs/compiler": "0.
|
|
40
|
+
"@fictjs/compiler": "0.6.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/babel__core": "^7.20.5",
|