import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { compileFixtureSource, type CompiledFixtureArtifact, type CompiledFixtureTarget, } from './compiledFixtureCompiler.js'; import { primeCompiledFixtureTemplates } from './compiledFixtureRegistry.js'; import type { ElementTemplateEnvManager } from './envManager.js'; export interface CompiledFixtureModuleExports { App: (props?: Record) => JSX.Element; mainProps?: Record; backgroundProps?: Record; } export async function loadCompiledFixtureModule( artifact: CompiledFixtureArtifact, ): Promise { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lynx-compiled-fixture-')); const tempImportPath = path.join(tempDir, 'app.js'); fs.writeFileSync(tempImportPath, artifact.code); try { return await import(`${pathToFileURL(tempImportPath).href}?t=${Date.now()}`) as T; } finally { fs.rmSync(tempDir, { recursive: true, force: true }); } } interface LoadCompiledFixturePairOptions { backgroundTarget?: CompiledFixtureTarget; enableWorkletTransform?: boolean; envManager?: ElementTemplateEnvManager; isDynamicComponent?: boolean; mainTarget?: CompiledFixtureTarget; registerMainTemplates?: boolean; } export async function loadCompiledFixturePair( sourcePath: string, options: LoadCompiledFixturePairOptions = {}, ): Promise<{ backgroundModule: T; mainModule: T; }> { const { backgroundTarget = 'JS', enableWorkletTransform = false, envManager, isDynamicComponent = false, mainTarget = 'LEPUS', registerMainTemplates = true, } = options; const mainArtifact = await compileFixtureSource(sourcePath, { enableWorkletTransform, isDynamicComponent, target: mainTarget, }); if (registerMainTemplates) { primeCompiledFixtureTemplates(mainArtifact); } envManager?.switchToMainThread(); const mainModule = await loadCompiledFixtureModule(mainArtifact); const backgroundArtifact = await compileFixtureSource(sourcePath, { enableWorkletTransform, isDynamicComponent, target: backgroundTarget, }); envManager?.switchToBackground(); const backgroundModule = await loadCompiledFixtureModule(backgroundArtifact); return { backgroundModule, mainModule }; }