next-live 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/LiveContext.tsx","../src/core/builtin-specifiers.ts","../src/core/builtins.ts","../src/core/errors.ts","../src/core/transpile.ts","../src/core/evaluate.ts","../src/core/inject-render-budget.ts","../src/core/resolver.ts","../src/core/stacks.ts","../src/core/compile.ts","../src/core/guards.ts","../src/hooks/useCompileTask.ts","../src/hooks/useLiveRunner.ts","../src/components/LiveProvider.tsx","../src/components/LiveErrorBoundary.tsx","../src/hooks/useLiveContext.ts","../src/components/LivePreview.tsx","../src/core/positions.ts","../src/components/LiveError.tsx","../src/hooks/useLiveModule.ts","../src/core/registry.ts"],"names":["createContext","React","JsxRuntime","JsxDevRuntime","require","useState","useRef","useEffect","useMemo","useCallback","jsx","Component","useContext","createElement","isValidElement","LiveError","Fragment","jsxs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAM,WAAA,mBAAc,MAAA,CAAO,GAAA,CAAI,uBAAuB,CAAA;AAMtD,SAAS,iBAAA,GAAsD;AAC7D,EAAA,MAAM,KAAA,GAAQ,UAAA;AACd,EAAA,MAAM,QAAA,GAAW,MAAM,WAAW,CAAA;AAClC,EAAA,IAAI,UAAU,OAAO,QAAA;AAMrB,EAAA,MAAM,OAAA,GAAUA,oBAAuC,IAAI,CAAA;AAC3D,EAAA,OAAA,CAAQ,WAAA,GAAc,aAAA;AACtB,EAAA,KAAA,CAAM,WAAW,CAAA,GAAI,OAAA;AACrB,EAAA,OAAO,OAAA;AACT;AAEO,IAAM,cAAc,iBAAA;;;ACpCpB,IAAM,kBAAA,GAAqB;AAAA,EAChC,OAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAAA;;;ACWO,IAAM,cAAA,GAAiC;AAAA,EAC5C,CAAC,kBAAA,CAAmB,CAAC,CAAC,GAAGC,gBAAA;AAAA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ACvD,EAAA,OAAO,MAAA;AACT;AA6BO,SAAS,gBAAA,CACd,MACA,WAAA,EACgB;AAChB,EAAA,MAAM,WAA2B,EAAC;AAElC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,IAAI,KAAK,MAAA,CAAO,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC/C,IAAA,MAAM,SAAA,GAAY,YAAY,IAAI,CAAA;AAClC,IAAA,IAAI,cAAc,IAAA,EAAM;AAExB,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,IAAgB,aAAa,QAAA,EAAU;AAClE,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,qDAAqD,SAAS,CAAA,iDAAA;AAAA,OAEhE;AAAA,IACF;AAEA,IAAA,QAAA,CAAS,SAAS,CAAA,GAAI,YAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,QAAA;AACT","file":"index.cjs","sourcesContent":["'use client';\n\nimport { createContext } from 'react';\nimport type { Context } from 'react';\nimport type { LiveContextValue } from '../core/types';\n\n/**\n * One context, however many copies of this module exist.\n *\n * The context is cached on a global symbol rather than being a plain\n * module-level constant, because a plain one is only unique per module\n * instance, and there are realistic ways to end up with more than one:\n *\n * - The CommonJS build cannot code-split, so `index.cjs` and `editor.cjs` each\n * inline their own copy. Without this, `<LiveEditor>` from `next-live/editor`\n * would read a different context than `<LiveProvider>` provides and throw\n * \"useLiveContext must be called inside a <LiveProvider>\".\n * - npm can install two versions of the package side by side.\n *\n * Keying on a symbol means every copy resolves to whichever created it first,\n * so provider and consumer always meet.\n */\nconst CONTEXT_KEY = Symbol.for('next-live.LiveContext');\n\ntype GlobalWithContext = typeof globalThis & {\n [CONTEXT_KEY]?: Context<LiveContextValue | null>;\n};\n\nfunction createLiveContext(): Context<LiveContextValue | null> {\n const store = globalThis as GlobalWithContext;\n const existing = store[CONTEXT_KEY];\n if (existing) return existing;\n\n /**\n * Null rather than a default value, so `useLiveContext` can tell \"outside a\n * provider\" apart from \"inside a provider that has not compiled yet\".\n */\n const context = createContext<LiveContextValue | null>(null);\n context.displayName = 'LiveContext';\n store[CONTEXT_KEY] = context;\n return context;\n}\n\nexport const LiveContext = createLiveContext();\n","/**\n * The specifiers `next-live` registers for every snippet.\n *\n * Kept apart from `builtins.ts` because that module imports React, and the\n * validator must be usable in a CI script or a Route Handler where pulling in\n * React would be pointless. Names only, no values.\n */\nexport const BUILTIN_SPECIFIERS = [\n 'react',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n] as const;\n","import * as React from 'react';\nimport * as JsxRuntime from 'react/jsx-runtime';\nimport * as JsxDevRuntime from 'react/jsx-dev-runtime';\nimport { BUILTIN_SPECIFIERS } from './builtin-specifiers';\nimport type { ModuleRegistry } from './types';\n\n/**\n * Modules every snippet can import without the host registering anything.\n *\n * The two JSX runtimes are not optional: with `jsxRuntime: 'automatic'`\n * Sucrase compiles every JSX element into a `react/jsx-runtime` (or\n * `react/jsx-dev-runtime`) call, so without these entries *every* snippet\n * fails on its first tag.\n *\n * These are static imports so evaluated code shares the host's single React\n * instance - hooks and context work across the boundary, which is the whole\n * point of evaluating in the host realm. Host `modules` merge over these, so\n * a React shim can still be substituted.\n *\n * `react-dom` is deliberately absent: snippets rarely need it, and a host that\n * does can register it explicitly.\n */\nexport const builtinModules: ModuleRegistry = {\n [BUILTIN_SPECIFIERS[0]]: React,\n [BUILTIN_SPECIFIERS[1]]: JsxRuntime,\n [BUILTIN_SPECIFIERS[2]]: JsxDevRuntime,\n};\n","/** Base class for every error next-live raises. */\nexport class LiveError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = new.target.name;\n if (options?.cause !== undefined) this.cause = options.cause;\n // Restores the prototype chain when compiled down to ES5 by a consumer.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** The snippet could not be parsed or transpiled. */\nexport class LiveCompileError extends LiveError {\n readonly line: number | undefined;\n readonly column: number | undefined;\n\n constructor(message: string, position?: { line?: number; column?: number }, cause?: unknown) {\n super(message, { cause });\n this.line = position?.line;\n this.column = position?.column;\n }\n}\n\n/** The snippet threw while being evaluated or rendered. */\nexport class LiveRuntimeError extends LiveError {}\n\n/** A render loop was detected and stopped. */\nexport class RenderLoopError extends LiveRuntimeError {}\n\n/** `import` referenced a specifier that is not in the registry. */\nexport class ModuleNotFoundError extends LiveError {\n constructor(\n readonly specifier: string,\n readonly available: readonly string[],\n ) {\n super(buildModuleNotFoundMessage(specifier, available));\n }\n}\n\n/** The snippet compiled and ran but produced nothing renderable. */\nexport class NoComponentError extends LiveError {}\n\n/** Sucrase could not be loaded (usually a chunk-load failure). */\nexport class TranspilerLoadError extends LiveError {\n constructor(cause: unknown) {\n super(\n 'next-live could not load its transpiler (sucrase). This is usually a ' +\n 'network or code-splitting failure - check that the chunk is reachable.',\n { cause },\n );\n }\n}\n\nconst MAX_LISTED = 12;\n\nfunction buildModuleNotFoundMessage(specifier: string, available: readonly string[]): string {\n const lines = [`Module '${specifier}' is not registered in the next-live scope.`];\n\n const suggestion = nearestSpecifier(specifier, available);\n if (suggestion) lines.push('', `Did you mean '${suggestion}'?`);\n\n if (available.length > 0) {\n const sorted = [...available].sort();\n const shown = sorted.slice(0, MAX_LISTED);\n const rest = sorted.length - shown.length;\n lines.push(\n '',\n `Registered modules (${sorted.length}): ${shown.join(', ')}` +\n (rest > 0 ? `, …and ${rest} more` : ''),\n );\n } else {\n lines.push('', 'No modules are registered.');\n }\n\n // Bare specifiers are overwhelmingly the \"I expected npm to work\" case.\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n lines.push(\n '',\n 'next-live does not bundle npm packages - pass them in explicitly:',\n ` <LiveProvider modules={{ '${specifier}': theModule }} />`,\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Closest registered specifier by edit distance, or undefined if nothing is\n * close enough to be worth suggesting.\n */\nexport function nearestSpecifier(\n specifier: string,\n available: readonly string[],\n): string | undefined {\n const lower = specifier.toLowerCase();\n\n // A pure casing slip is always the intended match.\n const caseMatch = available.find((key) => key.toLowerCase() === lower);\n if (caseMatch) return caseMatch;\n\n const threshold = Math.max(1, Math.min(3, Math.floor(specifier.length / 3)));\n let best: string | undefined;\n let bestDistance = threshold + 1;\n\n for (const key of available) {\n // Length alone can rule a candidate out before doing any real work.\n if (Math.abs(key.length - specifier.length) > threshold) continue;\n const distance = editDistance(lower, key.toLowerCase(), bestDistance);\n if (distance < bestDistance) {\n bestDistance = distance;\n best = key;\n }\n }\n\n return bestDistance <= threshold ? best : undefined;\n}\n\n/**\n * Levenshtein distance, abandoning the walk as soon as every cell in a row\n * exceeds `limit` - the common case is \"nothing is close\", and that exits fast.\n */\nfunction editDistance(a: string, b: string, limit: number): number {\n if (a === b) return 0;\n let previous = new Array<number>(b.length + 1);\n let current = new Array<number>(b.length + 1);\n\n for (let j = 0; j <= b.length; j++) previous[j] = j;\n\n for (let i = 1; i <= a.length; i++) {\n current[0] = i;\n let rowMin = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;\n const value = Math.min(\n (current[j - 1] as number) + 1,\n (previous[j] as number) + 1,\n (previous[j - 1] as number) + cost,\n );\n current[j] = value;\n if (value < rowMin) rowMin = value;\n }\n if (rowMin > limit) return limit + 1;\n const swap = previous;\n previous = current;\n current = swap;\n }\n\n return previous[b.length] as number;\n}\n","import { LiveCompileError, TranspilerLoadError } from './errors';\nimport type { TransformResult, TranspileOptions } from './types';\n\ntype SucraseModule = typeof import('sucrase');\n\nlet transpilerPromise: Promise<SucraseModule> | null = null;\n\n/**\n * Loads Sucrase on first use.\n *\n * The *promise* is cached rather than the resolved module, so concurrent\n * callers share one chunk fetch; a rejected load clears the cache so a\n * transient network failure can be retried.\n */\nexport function loadTranspiler(): Promise<SucraseModule> {\n if (transpilerPromise === null) {\n transpilerPromise = import('sucrase').catch((cause: unknown) => {\n transpilerPromise = null;\n throw new TranspilerLoadError(cause);\n });\n }\n return transpilerPromise;\n}\n\n/**\n * Starts fetching the transpiler chunk ahead of time. Worth calling on idle or\n * on route prefetch so the first compile is not gated on a network round trip.\n */\nexport function preloadTranspiler(): void {\n void loadTranspiler().catch(() => {\n // Preloading is best-effort; the real compile reports the failure.\n });\n}\n\n/** Replaces the loaded transpiler. Intended for tests and custom backends. */\nexport function setTranspiler(module: SucraseModule | null): void {\n transpilerPromise = module === null ? null : Promise.resolve(module);\n}\n\nexport const defaultTranspileOptions: Required<TranspileOptions> = {\n filePath: 'LiveCode.tsx',\n production: true,\n jsxRuntime: 'automatic',\n jsxImportSource: 'react',\n};\n\n/** Top-level `import`/`export`, ignoring matches that are not line-initial. */\nconst MODULE_SYNTAX_RE = /^[ \\t]*(?:export\\b|import\\s*[({'\"*]|import\\s+[A-Za-z_$])/m;\n\n/** A call to the injected `render()` helper (react-live's \"noInline\" style). */\nconst RENDER_CALL_RE = /(^|[^.\\w$])render\\s*\\(/m;\n\n/**\n * Whether a snippet is a module body rather than a bare expression.\n *\n * Imports and exports are unambiguous; a `render(...)` call is a statement, so\n * it is one too. Anything else may be a lone expression like `<div/>`, which is\n * not a valid module body and has to be wrapped.\n */\nexport function isModuleSource(source: string): boolean {\n return MODULE_SYNTAX_RE.test(source) || RENDER_CALL_RE.test(source);\n}\n\n/**\n * Whether a snippet carries no code at all - empty, whitespace, or only\n * comments.\n *\n * Such a snippet must not go down the bare-expression path: wrapping it\n * produces `export default ( )`, which Sucrase happily emits because it is a\n * token-based transform rather than a validating parser. The invalid code then\n * survives all the way to `new Function`, where the author sees a bare\n * `Unexpected token ')'` instead of being told the snippet is empty. Routing it\n * through module mode yields an empty module, and the normal \"did not produce a\n * component\" message.\n *\n * Only line-initial `//` is treated as a comment, so a URL inside a string on a\n * line of real code cannot make that line look blank. The check errs towards\n * \"has content\", which is the safe direction: it only ever restores the\n * previous behaviour.\n */\nexport function isBlankSource(source: string): boolean {\n const withoutComments = source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, ' ')\n .replace(/^[ \\t]*\\/\\/.*$/gm, ' ');\n return withoutComments.trim() === '';\n}\n\n/** The Sucrase options every entry point uses, so they cannot drift apart. */\nexport function sucraseOptions(options: Required<TranspileOptions>) {\n return {\n transforms: ['jsx', 'typescript', 'imports'] as Array<'jsx' | 'typescript' | 'imports'>,\n jsxRuntime: options.jsxRuntime,\n jsxImportSource: options.jsxImportSource,\n production: options.production,\n filePath: options.filePath,\n // Leaving native `import()` intact would resolve against the *page* URL\n // and 404 on './utils'; routing it through our shim is the only sane\n // behaviour inside an evaluated snippet.\n preserveDynamicImport: false,\n };\n}\n\n/**\n * Applies the transpile pass, wrapping a bare expression so it becomes a valid\n * module body. Shared by the async browser path and the sync server path.\n */\nexport function runTranspile(\n transformFn: (input: string, opts: ReturnType<typeof sucraseOptions>) => { code: string },\n source: string,\n options: Required<TranspileOptions>,\n): TransformResult {\n const opts = sucraseOptions(options);\n\n if (!isModuleSource(source) && !isBlankSource(source)) {\n // The newlines matter: they shift the user's code down exactly one line,\n // which `linePrefixOffset` corrects, whereas inlining would destroy line\n // mapping for the whole snippet.\n try {\n return {\n code: transformFn(`export default (\\n${source}\\n)`, opts).code,\n linePrefixOffset: 1,\n expression: true,\n };\n } catch {\n // Multi-statement code with no exports - fall through to module mode.\n }\n }\n\n return { code: transformFn(source, opts).code, linePrefixOffset: 0, expression: false };\n}\n\n/**\n * Transpiles a snippet to CommonJS that `new Function` can evaluate.\n *\n * Three authoring styles are supported, resolved without ever asking the user\n * which one they used:\n *\n * 1. A real module - `export default function App() {}`.\n * 2. A bare expression, `<div/>` or `() => <div/>`.\n * 3. Bare statements with no export, `function App() {}`, or `render(<App/>)`.\n *\n * Styles 1 and 3 are compiled as-is; the component is recovered after\n * evaluation (see `evaluate.ts`). Style 2 is not a valid module body on its\n * own, so it is wrapped in `export default (...)`.\n */\nexport async function transpile(\n source: string,\n options: TranspileOptions = {},\n transform?: import('./types').TransformFn,\n): Promise<TransformResult> {\n const resolved = { ...defaultTranspileOptions, ...options };\n\n if (transform) return transform(source, resolved);\n\n const { transform: sucraseTransform } = await loadTranspiler();\n\n try {\n return runTranspile(sucraseTransform, source, resolved);\n } catch (cause) {\n throw toCompileError(cause);\n }\n}\n\n/** Sucrase parse errors carry a `(line:column)` suffix worth surfacing. */\nfunction toCompileError(cause: unknown): LiveCompileError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const match = /\\((\\d+):(\\d+)\\)\\s*$/.exec(message);\n if (!match) return new LiveCompileError(message, undefined, cause);\n\n return new LiveCompileError(\n message.slice(0, match.index).trim(),\n { line: Number(match[1]), column: Number(match[2]) },\n cause,\n );\n}\n\n/**\n * Names declared at the top level of compiled output, used to recover a\n * component from a snippet that never exported one.\n *\n * Matched at the start of a line *or* just after a `;`. Column zero alone is\n * not enough: Sucrase prepends its own preamble - `\"use strict\";var _jsxruntime\n * = require(...)` - to line 1, so a component declared on the snippet's first\n * line no longer sits at column zero and was silently skipped. The snippet\n * below then exported `y`, and the author was told the default export was a\n * number:\n *\n * ```js\n * const App = () => <b/>; // invisible: shares line 1 with the preamble\n * const y = 2; // found, and wrongly chosen\n * ```\n *\n * Matching after `;` also admits declarations nested inside a function body,\n * which is harmless by the same reasoning as any other false positive: the\n * generated epilogue guards every name with `typeof`, and a block-scoped name\n * is `undefined` at module level, so it is skipped.\n */\nexport function scanTopLevelDeclarations(code: string): string[] {\n const names: string[] = [];\n const patterns = [\n /(?:^|;)\\s*(?:async\\s+)?function\\s*\\*?\\s*([A-Za-z_$][\\w$]*)/gm,\n /(?:^|;)\\s*class\\s+([A-Za-z_$][\\w$]*)/gm,\n /(?:^|;)\\s*(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*=/gm,\n ];\n\n for (const pattern of patterns) {\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(code)) !== null) {\n const name = match[1];\n if (name !== undefined && !names.includes(name)) names.push(name);\n }\n }\n return names;\n}\n\n/**\n * Wraps an already-compiled result as a `transform` function, so the client\n * skips loading Sucrase entirely:\n *\n * ```tsx\n * <LiveProvider code={source} transform={precompiledTransform(compiled)} />\n * ```\n *\n * Lives here rather than next-live/server on purpose. It is a pure closure over\n * a value and needs no transpiler - but importing it from the server entry\n * would pull Sucrase statically into the page bundle, which is the exact cost\n * precompiling exists to avoid.\n */\nexport function precompiledTransform(result: TransformResult): () => TransformResult {\n return () => result;\n}\n","import * as React from 'react';\nimport { LiveCompileError, LiveRuntimeError, NoComponentError } from './errors';\nimport { scanTopLevelDeclarations } from './transpile';\nimport type {\n ExtractionSource,\n LiveRenderable,\n LiveScope,\n NormalizedModule,\n} from './types';\n\n/** Wrapper parameters a scope key may not shadow. */\nconst RESERVED = new Set(['module', 'exports', 'require', 'React', 'render', '__liveTick']);\n\nconst JS_RESERVED_WORDS = new Set([\n 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default',\n 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally',\n 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null',\n 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof',\n 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements',\n 'interface', 'package', 'private', 'protected', 'public', 'arguments', 'eval',\n]);\n\nconst IDENTIFIER_RE = /^[A-Za-z_$][\\w$]*$/;\n\n/**\n * Scope keys that can legally become function parameters, sorted so the\n * generated source - and therefore any cache key built from it, is stable\n * regardless of object key order.\n *\n * Unusable keys are warned about rather than thrown on: a host merging a large\n * scope object should not lose the whole preview over one bad key.\n */\nexport function usableScopeKeys(scope: LiveScope): string[] {\n const keys: string[] = [];\n for (const key of Object.keys(scope)) {\n if (!IDENTIFIER_RE.test(key) || JS_RESERVED_WORDS.has(key)) {\n warn(`next-live: scope key ${JSON.stringify(key)} is not a valid identifier and was skipped.`);\n continue;\n }\n if (RESERVED.has(key)) {\n warn(`next-live: scope key \"${key}\" is reserved by next-live and was skipped.`);\n continue;\n }\n keys.push(key);\n }\n return keys.sort();\n}\n\nfunction warn(message: string): void {\n if (typeof console !== 'undefined') console.warn(message);\n}\n\nexport interface EvaluateOptions {\n code: string;\n filePath: string;\n require: (specifier: string) => NormalizedModule;\n scope: LiveScope;\n /** Injected as `__liveTick` when the source was instrumented for render budgeting. */\n liveTick?: () => void;\n}\n\nexport interface EvaluateResult {\n renderable: LiveRenderable;\n via: ExtractionSource;\n}\n\n/**\n * Evaluates compiled snippet code in the host realm and extracts something\n * renderable from it.\n *\n * The wrapper contributes **zero characters before the user's code**, which is\n * what keeps error line numbers a simple subtraction: everything the snippet\n * needs arrives as a function parameter, and parameters cost no lines. The\n * epilogue and `sourceURL` comment go after the code, where added lines are\n * harmless.\n */\nexport function evaluate(options: EvaluateOptions): EvaluateResult {\n const { exports, rendered, recovered } = runModule(options);\n\n return pickRenderable(exports, rendered, recovered);\n}\n\nexport interface ModuleResult {\n /** Everything the snippet exported. */\n exports: Record<string, unknown>;\n /** Present only when the snippet called the injected `render()` helper. */\n rendered?: { rendered: unknown };\n /**\n * True when the default export came from the recovery epilogue rather than\n * from the author. Recorded on the module object, which never leaves this\n * function, so a snippet's own `exports` stay clean for `compileModule`.\n */\n recovered?: boolean;\n}\n\n/**\n * Runs a snippet and returns its raw exports, without insisting that it\n * produced a React component.\n *\n * Plenty of stored code is not UI - validators, transformers, calculated\n * fields, config builders. Those are perfectly good modules, and asking them\n * to export a component would be nonsense.\n */\nexport function runModule(options: EvaluateOptions): ModuleResult {\n const { code, filePath, require: requireFn, scope, liveTick } = options;\n const tick =\n liveTick ?? (code.includes('__liveTick') ? () => {} : undefined);\n\n const scopeKeys = usableScopeKeys(scope);\n const epilogue = buildEpilogue(code);\n // `sourceURL` makes every frame from this snippet identifiable, so stacks can\n // be filtered down to user code and DevTools shows a stable file name.\n const body = `${code}\\n${epilogue}\\n//# sourceURL=next-live:///${filePath}`;\n\n const moduleObject: { exports: Record<string, unknown>; __nextLiveRecovered?: boolean } = {\n exports: Object.create(null) as Record<string, unknown>,\n };\n\n let rendered: unknown;\n let didRender = false;\n const render = (node: unknown): void => {\n rendered = node;\n didRender = true;\n };\n\n const paramNames = ['module', 'exports', 'require', 'React', 'render'];\n const paramValues: unknown[] = [\n moduleObject,\n moduleObject.exports,\n requireFn,\n React,\n render,\n ];\n\n if (tick) {\n paramNames.push('__liveTick');\n paramValues.push(tick);\n }\n\n paramNames.push(...scopeKeys);\n paramValues.push(...scopeKeys.map((key) => scope[key]));\n\n let factory: (...args: unknown[]) => void;\n try {\n factory = new Function(...paramNames, body) as (...args: unknown[]) => void;\n } catch (cause) {\n if (isCspEvalBlock(cause)) throw cspError(cause);\n throw new LiveRuntimeError(\n cause instanceof Error ? cause.message : String(cause),\n { cause },\n );\n }\n\n factory(...paramValues);\n\n return {\n exports: moduleObject.exports,\n ...(didRender ? { rendered: { rendered } } : {}),\n ...(moduleObject.__nextLiveRecovered === true ? { recovered: true } : {}),\n };\n}\n\n/**\n * Recovers `export default` for snippets that declare a component without\n * exporting it - the `react-live` inline style.\n *\n * Emitted only when the code exports nothing, and every name is `typeof`\n * guarded so a false positive from the declaration scan cannot throw.\n * Candidates are tried in reverse declaration order so the last component\n * defined wins, which matches how people write these snippets.\n */\nfunction buildEpilogue(code: string): string {\n if (/\\bexports\\./.test(code)) return '';\n\n const declarations = scanTopLevelDeclarations(code);\n if (declarations.length === 0) return '';\n\n const ranked = rankCandidates(declarations);\n return ranked\n .map(\n (name) =>\n `;if(!('default' in exports)){try{if(typeof ${name}!=='undefined'){exports.default=${name};module.__nextLiveRecovered=true}}catch(e){}}`,\n )\n .join('');\n}\n\nconst PREFERRED_NAMES = ['App', 'Component', 'Main', 'Demo', 'Example', 'Page'];\n\nfunction rankCandidates(names: string[]): string[] {\n const preferred = names.filter((name) => PREFERRED_NAMES.includes(name));\n // PascalCase is React's own convention for components, so prefer those over\n // helper functions that happen to be declared later.\n const pascal = names.filter(\n (name) => !preferred.includes(name) && /^[A-Z]/.test(name),\n );\n const rest = names.filter(\n (name) => !preferred.includes(name) && !pascal.includes(name),\n );\n return [...preferred, ...pascal.reverse(), ...rest.reverse()];\n}\n\n/**\n * Chooses what to render from a snippet's exports, in the order a reader would\n * expect it to be found.\n */\nexport function pickRenderable(\n exports: Record<string, unknown>,\n renderCall?: { rendered: unknown },\n recovered?: boolean,\n): EvaluateResult {\n if (renderCall) {\n const found = asRenderable(renderCall.rendered);\n if (found) return { renderable: found, via: 'render()' };\n throw new NoComponentError(\n 'render() was called with something React cannot render.',\n );\n }\n\n // `module.exports = Component` replaces the exports object wholesale, so the\n // record handed in here *is* the component. Sucrase's ESM output never does\n // that, which is why this is checked ahead of the named-export scan rather\n // than as part of it - and why `ExtractionSource` has a 'module.exports'\n // member at all.\n const asCommonJs = asRenderable(exports);\n if (asCommonJs) return { renderable: asCommonJs, via: 'module.exports' };\n\n const defaultExport = exports['default'];\n if (defaultExport !== undefined) {\n const found = asRenderable(defaultExport);\n // A recovered default was synthesised by the epilogue, not written by the\n // author - saying 'export default' would misreport it in error messages.\n if (found) return { renderable: found, via: recovered ? 'declaration' : 'export default' };\n throw new NoComponentError(\n `The default export is ${describe(defaultExport)}, which React cannot render. ` +\n 'Export a component or an element instead.',\n );\n }\n\n const named = Object.keys(exports).filter((key) => key !== '__esModule');\n const renderableNames = named.filter((key) => asRenderable(exports[key]) !== null);\n\n if (renderableNames.length === 1) {\n const only = renderableNames[0] as string;\n return { renderable: asRenderable(exports[only]) as LiveRenderable, via: 'named export' };\n }\n\n if (renderableNames.length > 1) {\n const preferred = PREFERRED_NAMES.find((name) => renderableNames.includes(name));\n if (preferred) {\n return {\n renderable: asRenderable(exports[preferred]) as LiveRenderable,\n via: 'named export',\n };\n }\n throw new NoComponentError(\n `Several components were exported (${renderableNames.join(', ')}) and none is the ` +\n 'default. Add `export default` to the one you want rendered.',\n );\n }\n\n throw new NoComponentError(\n named.length > 0\n ? `Nothing renderable was exported. Found: ${named.join(', ')}. ` +\n 'Add `export default YourComponent`.'\n : 'The snippet did not produce a component. Add `export default YourComponent`, ' +\n 'or end the snippet with a single JSX expression.',\n );\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n return `a ${typeof value}`;\n}\n\nfunction asRenderable(value: unknown): LiveRenderable | null {\n if (isReactElement(value)) return { kind: 'element', element: value };\n if (isRenderableComponent(value)) {\n return { kind: 'component', component: value as React.ComponentType<Record<string, unknown>> };\n }\n return null;\n}\n\nconst symbolFor = (name: string): symbol | string =>\n typeof Symbol === 'function' && Symbol.for ? Symbol.for(name) : name;\n\n/** Exotic component objects that are valid as a JSX element type. */\nconst COMPONENT_TYPES = new Set<unknown>([\n symbolFor('react.memo'),\n symbolFor('react.forward_ref'),\n symbolFor('react.lazy'),\n symbolFor('react.provider'),\n symbolFor('react.context'),\n symbolFor('react.suspense'),\n symbolFor('react.suspense_list'),\n symbolFor('react.fragment'),\n symbolFor('react.profiler'),\n symbolFor('react.client.reference'),\n]);\n\nconst ELEMENT_TYPES = new Set<unknown>([\n symbolFor('react.transitional.element'), // React 19\n symbolFor('react.element'), // React 18 and interop\n symbolFor('react.portal'),\n]);\n\n/**\n * Whether React can use this as a component type.\n *\n * Plain functions pass, which means a utility function is indistinguishable\n * from a component here - that case fails loudly at render with React's own\n * error, which is clearer than anything we could say. The check exists mainly\n * so `export default memo(App)` and `forwardRef` components are not rejected.\n */\nexport function isRenderableComponent(value: unknown): boolean {\n if (typeof value === 'function') return true;\n if (typeof value !== 'object' || value === null) return false;\n return COMPONENT_TYPES.has((value as { $$typeof?: unknown }).$$typeof);\n}\n\nexport function isReactElement(value: unknown): value is React.ReactElement {\n if (typeof value !== 'object' || value === null) return false;\n return ELEMENT_TYPES.has((value as { $$typeof?: unknown }).$$typeof);\n}\n\n/**\n * Whether a thrown value is the browser refusing `new Function` under a\n * Content Security Policy.\n *\n * Checked by type *and* message: `EvalError` is what every current engine\n * throws, but the wording differs between them, and a future engine could pick\n * a different error type. Either signal is enough.\n */\nfunction isCspEvalBlock(cause: unknown): boolean {\n if (cause instanceof EvalError) return true;\n const message = cause instanceof Error ? cause.message : String(cause);\n return /unsafe-eval|Refused to evaluate|call to eval/i.test(message);\n}\n\n/**\n * The raw engine message (\"Refused to evaluate a string as JavaScript…\") says\n * nothing about what to change, and this is the single most likely thing to go\n * wrong on a first production deploy - so it gets an explicit fix.\n */\nfunction cspError(cause: unknown): LiveCompileError {\n return new LiveCompileError(\n \"next-live could not evaluate this snippet: the page's Content Security \" +\n \"Policy blocks eval.\\n\\n\" +\n \"Add 'unsafe-eval' to script-src for the routes that run snippets \" +\n '(in proxy.ts). This is expected - next-live compiles code at runtime, ' +\n 'so there is no way around the directive.\\n\\n' +\n \"Note that 'unsafe-eval' does not allow loading external scripts, and it \" +\n 'does not need to apply to your whole application.',\n undefined,\n cause,\n );\n}\n","/**\n * Inserts `__liveTick()` at the top of component function bodies so the render\n * budget counts every render without calling components as plain functions\n * (which breaks hooks under React 19).\n */\nexport function injectRenderBudgetTick(source: string): string {\n let out = source;\n\n out = out.replace(\n /export\\s+default\\s+function\\s+(\\w*)\\s*\\([^)]*\\)\\s*\\{/g,\n (match) => `${match}\\n __liveTick();`,\n );\n\n out = out.replace(\n /export\\s+default\\s*(?:async\\s+)?(?:function\\s*)?\\([^)]*\\)\\s*=>\\s*\\{/g,\n (match) => `${match}\\n __liveTick();`,\n );\n\n out = out.replace(\n /^export\\s+function\\s+([A-Z]\\w*)\\s*\\([^)]*\\)\\s*\\{/gm,\n (match) => `${match}\\n __liveTick();`,\n );\n\n return out;\n}\n","import { ModuleNotFoundError } from './errors';\nimport type { ModuleLoader, ModuleRegistry, ModuleValue, NormalizedModule } from './types';\n\n/** Marks a record that has already been through {@link normalizeModule}. */\nconst NORMALIZED = Symbol.for('next-live.normalized');\n\n/** Marks a function as a lazy loader rather than the module value itself. */\nconst LOADER = Symbol.for('next-live.loader');\n\n/** Assets a snippet may import for side effects only; resolved to empty modules. */\nconst ASSET_RE = /\\.(css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|woff2?)$/i;\n\n/**\n * Wraps a function so the registry treats it as a lazy loader instead of as\n * the module value. Without this a registered component function would be\n * indistinguishable from a loader.\n *\n * ```ts\n * { 'heavy-chart': defineLoader(() => import('heavy-chart')) }\n * ```\n */\nexport function defineLoader(load: ModuleLoader): ModuleLoader {\n return Object.defineProperty(load, LOADER, { value: true }) as ModuleLoader;\n}\n\nfunction isLoader(value: unknown): value is ModuleLoader {\n return typeof value === 'function' && (value as { [LOADER]?: boolean })[LOADER] === true;\n}\n\n/**\n * Builds an explicit module record, for the shape that cannot be inferred.\n *\n * {@link normalizeModule} unwraps any registered object that has its own\n * `default` key, because that is almost always a module wrapper. When it is\n * not - a config object that happens to contain the word `default`, say so:\n *\n * ```ts\n * { './theme': defineModule({ default: { default: 'dark', light: '#fff' } }) }\n * // import theme from './theme' → the whole object\n * ```\n *\n * `default` and `exports.default` address the same slot, because ESM makes no\n * distinction between a default export and a named export called `default`.\n * A top-level `default` wins if both are given.\n */\nexport function defineModule(shape: {\n default?: unknown;\n exports?: Record<string, unknown>;\n}): NormalizedModule {\n const record = Object.create(null) as Record<string | symbol, unknown>;\n Object.defineProperty(record, '__esModule', { value: true });\n Object.defineProperty(record, NORMALIZED, { value: true });\n\n const defaultExport = 'default' in shape ? shape.default : shape.exports?.['default'];\n Object.defineProperty(record, 'default', { value: defaultExport, enumerable: true });\n\n for (const [key, value] of Object.entries(shape.exports ?? {})) {\n if (key === 'default') continue;\n Object.defineProperty(record, key, { value, enumerable: true });\n }\n return record as unknown as NormalizedModule;\n}\n\n/**\n * Converts a registered value into a record Sucrase's interop helpers accept.\n *\n * The trick that makes this total: both helpers Sucrase emits are identity\n * functions when the required value carries `__esModule === true` -\n * `_interopRequireDefault` is literally `obj && obj.__esModule ? obj : {default: obj}`.\n * By always returning such a record we neutralise both helpers, so this\n * function becomes the single source of truth for what `default` and each\n * named import resolve to.\n *\n * Named exports are exposed as *getters* over the original value rather than\n * copied. That preserves ES module live bindings, and - more importantly in\n * practice, avoids eagerly invoking the lazy namespace getters that packages\n * like icon sets and large UI barrels use, which a naive spread would trigger\n * on every single compile.\n */\nexport function normalizeModule(value: ModuleValue): NormalizedModule {\n if (isNormalized(value)) return value;\n\n if (value === null || value === undefined) {\n // A registered `undefined` is almost always a broken import on the host\n // side; surfacing it as an empty module beats a confusing downstream crash.\n return defineModule({ default: value });\n }\n\n if (typeof value !== 'object' && typeof value !== 'function') {\n return defineModule({ default: value });\n }\n\n const source = value as Record<string, unknown>;\n const record = Object.create(null) as Record<string | symbol, unknown>;\n Object.defineProperty(record, '__esModule', { value: true });\n Object.defineProperty(record, NORMALIZED, { value: true });\n\n // `in` rather than hasOwnProperty: bundler namespace objects can expose\n // `default` further up the chain. When a value carries its own `default`\n // it is module-shaped, so unwrap it; otherwise the value *is* the default.\n const defaultExport = 'default' in source ? source['default'] : source;\n Object.defineProperty(record, 'default', {\n get: () => defaultExport,\n enumerable: true,\n configurable: true,\n });\n\n for (const key of ownEnumerableKeys(source)) {\n if (key === 'default' || key === '__esModule') continue;\n Object.defineProperty(record, key, {\n get: () => source[key],\n enumerable: true,\n configurable: true,\n });\n }\n\n return record as unknown as NormalizedModule;\n}\n\nfunction isNormalized(value: unknown): value is NormalizedModule {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { [NORMALIZED]?: boolean })[NORMALIZED] === true\n );\n}\n\n/**\n * Enumerable string keys, without invoking any getters. `Object.keys` alone\n * misses inherited enumerables on some bundlers' namespace objects.\n */\nfunction ownEnumerableKeys(source: object): string[] {\n const keys = new Set<string>();\n for (const key of Object.keys(source)) keys.add(key);\n for (const key in source) keys.add(key);\n return [...keys];\n}\n\n/** The resolved, synchronously-readable module table handed to a snippet. */\nexport interface ResolvedModules {\n get(specifier: string): NormalizedModule | undefined;\n readonly keys: readonly string[];\n}\n\nexport interface ResolveOptions {\n registry: ModuleRegistry;\n /** Specifiers found in the compiled output. */\n specifiers: Iterable<string>;\n /**\n * Resolve `@scope/pkg/Sub` against a registered `@scope/pkg` by walking the\n * remaining segments as property accesses. Correct for barrel-shaped\n * packages, wrong for those whose subpaths are not re-exported - so it is\n * opt-in rather than a silent guess. Default false.\n */\n resolveSubpaths?: boolean;\n signal?: AbortSignal;\n}\n\n/**\n * Resolves every specifier a snippet needs *before* evaluation, because\n * Sucrase emits synchronous `require()` calls that cannot await anything.\n */\nexport async function resolveModules(options: ResolveOptions): Promise<ResolvedModules> {\n const { registry, specifiers, resolveSubpaths = false, signal } = options;\n const resolved = new Map<string, NormalizedModule>();\n\n const pending: Array<Promise<void>> = [];\n\n for (const specifier of specifiers) {\n if (resolved.has(specifier)) continue;\n\n const found = lookup(registry, specifier, resolveSubpaths);\n if (found === MISSING) {\n // Side-effect asset imports are a no-op rather than an error, so a\n // snippet copied out of a real file with `import './styles.css'` runs.\n if (ASSET_RE.test(specifier)) resolved.set(specifier, defineModule({}));\n // Anything else stays unresolved. We deliberately do not throw here:\n // the specifier scan is deliberately over-inclusive, so only an actual\n // require() at runtime is proof the snippet really needs it.\n continue;\n }\n\n if (isLoader(found)) {\n pending.push(\n Promise.resolve(found(specifier)).then((value) => {\n resolved.set(specifier, normalizeModule(value));\n }),\n );\n } else {\n resolved.set(specifier, normalizeModule(found));\n }\n }\n\n if (pending.length > 0) await Promise.all(pending);\n signal?.throwIfAborted();\n\n const keys = Object.keys(registry);\n return {\n get: (specifier) => resolved.get(specifier),\n keys,\n };\n}\n\n/** Sentinel distinguishing \"not registered\" from a registered `undefined`. */\nconst MISSING = Symbol('missing');\n\n/** Specifiers resolved to an empty module rather than an error. */\nexport function isIgnoredSpecifier(specifier: string): boolean {\n return ASSET_RE.test(specifier);\n}\n\n/**\n * The registry key that would serve a specifier, or undefined if none would.\n *\n * Key matching only - no values, no loaders, nothing executed. That is what\n * lets a snippet be checked on a server, or in CI, without running it.\n */\nexport function matchRegistryKey(\n specifier: string,\n keys: readonly string[],\n): string | undefined {\n if (keys.includes(specifier)) return specifier;\n\n let best: string | undefined;\n for (const key of keys) {\n if (!key.endsWith('/') || !specifier.startsWith(key)) continue;\n if (best === undefined || key.length > best.length) best = key;\n }\n return best;\n}\n\nfunction lookup(\n registry: ModuleRegistry,\n specifier: string,\n resolveSubpaths: boolean,\n): ModuleValue | ModuleLoader | typeof MISSING {\n if (Object.prototype.hasOwnProperty.call(registry, specifier)) {\n return registry[specifier];\n }\n\n // Prefix entries: a key ending in '/' claims the whole subtree and receives\n // the full specifier, letting a host route a whole package subtree through\n // one loader.\n let bestPrefix: string | undefined;\n for (const key of Object.keys(registry)) {\n if (!key.endsWith('/')) continue;\n if (!specifier.startsWith(key)) continue;\n if (bestPrefix === undefined || key.length > bestPrefix.length) bestPrefix = key;\n }\n if (bestPrefix !== undefined) {\n // No wrapping needed: the caller invokes the loader with the full\n // specifier, which is exactly what a prefix entry wants.\n return registry[bestPrefix];\n }\n\n if (resolveSubpaths) {\n const walked = walkSubpath(registry, specifier);\n if (walked !== MISSING) return walked;\n }\n\n return MISSING;\n}\n\n/**\n * `pkg/Sub` against a registered `pkg` namespace, by reading\n * the remaining path segments as properties.\n */\nfunction walkSubpath(\n registry: ModuleRegistry,\n specifier: string,\n): ModuleValue | typeof MISSING {\n let base: string | undefined;\n for (const key of Object.keys(registry)) {\n if (!specifier.startsWith(key + '/')) continue;\n if (base === undefined || key.length > base.length) base = key;\n }\n if (base === undefined) return MISSING;\n\n let current = registry[base];\n if (isLoader(current)) return MISSING; // cannot walk without awaiting\n\n for (const segment of specifier.slice(base.length + 1).split('/')) {\n if (current === null || current === undefined) return MISSING;\n if (typeof current !== 'object' && typeof current !== 'function') return MISSING;\n const next = (current as Record<string, unknown>)[segment];\n if (next === undefined) return MISSING;\n current = next;\n }\n return current;\n}\n\n/**\n * The synchronous `require` shim handed to compiled snippets. Sucrase emits\n * `var _react = require('react')` at module top level, so this must never\n * return a promise.\n */\nexport function createRequire(\n resolved: ResolvedModules,\n): (specifier: string) => NormalizedModule {\n return function require(specifier: string): NormalizedModule {\n const found = resolved.get(specifier);\n if (found === undefined) {\n throw new ModuleNotFoundError(specifier, resolved.keys);\n }\n return found;\n };\n}\n\n/**\n * Every `require()` target in compiled output.\n *\n * Deliberately over-inclusive: a match inside a string literal costs one\n * needless registry lookup, whereas a miss would mean a loader never runs and\n * evaluation fails. Unresolvable matches are dropped silently by\n * {@link resolveModules}.\n */\nexport function scanRequires(code: string): Set<string> {\n const found = new Set<string>();\n const re = /\\brequire\\s*\\(\\s*(['\"])((?:(?!\\1)[^\\\\]|\\\\.)*)\\1\\s*\\)/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(code)) !== null) {\n const specifier = match[2];\n if (specifier) found.add(specifier);\n }\n return found;\n}\n","let cachedOffset: number | null = null;\n\n/**\n * How many lines the engine inserts above a `new Function` body.\n *\n * V8 reports 2, but this is engine-specific, so it is measured once rather\n * than assumed: throw from body line 1 and see what line the stack claims.\n */\nexport function getFunctionLineOffset(): number {\n if (cachedOffset !== null) return cachedOffset;\n\n cachedOffset = 2; // V8's value, used if the probe cannot read a line.\n try {\n new Function('throw new Error(\"next-live-probe\")')();\n } catch (error) {\n const line = firstFrameLine(error);\n if (line !== null) cachedOffset = line - 1;\n }\n return cachedOffset;\n}\n\nconst FRAME_PATTERNS = [\n /(?::|@)(\\d+):(\\d+)\\)?\\s*$/, // V8 \"at x (file:LINE:COL)\" and SpiderMonkey \"x@file:LINE:COL\"\n];\n\nfunction firstFrameLine(error: unknown): number | null {\n const stack = error instanceof Error ? error.stack : undefined;\n if (!stack) return null;\n for (const raw of stack.split('\\n').slice(1)) {\n for (const pattern of FRAME_PATTERNS) {\n const match = pattern.exec(raw.trim());\n if (match?.[1]) return Number(match[1]);\n }\n }\n return null;\n}\n\nexport interface MappedPosition {\n line: number;\n column?: number;\n}\n\n/**\n * Maps a position inside evaluated code back to the snippet the user wrote.\n *\n * No source map is consulted, because none is needed: Sucrase does not move\n * code between lines - a multi-line import collapses onto line 1 but leaves\n * the intervening lines blank - so generated line N is source line N. The only\n * adjustments are the engine's `new Function` offset and, for a snippet\n * compiled as a bare expression, the one line the wrapper added.\n *\n * `sourceLineCount` is a safety net: if a custom `transform` backend *did*\n * change the line count, the mapping is untrustworthy and is dropped rather\n * than reported wrongly.\n */\nexport function mapPosition(\n position: MappedPosition,\n meta: { linePrefixOffset: number; generatedLineCount: number; sourceLineCount: number },\n): MappedPosition | null {\n if (meta.generatedLineCount !== meta.sourceLineCount + meta.linePrefixOffset * 2) {\n return null;\n }\n\n const line = position.line - getFunctionLineOffset() - meta.linePrefixOffset;\n if (line < 1 || line > meta.sourceLineCount) return null;\n\n // Line 1 holds Sucrase's entire prologue, so a column there is meaningless.\n return line === 1 ? { line } : { line, column: position.column };\n}\n\n/** Identifies stack frames that came from evaluated snippet code. */\nexport const SOURCE_URL_PREFIX = 'next-live:///';\n\n/**\n * Drops host and React frames from a stack, leaving only the snippet's own.\n * Returns undefined when nothing in the stack came from user code.\n */\nexport function filterUserFrames(stack: string | undefined): string | undefined {\n if (!stack) return undefined;\n const frames = stack\n .split('\\n')\n .filter((line) => line.includes(SOURCE_URL_PREFIX));\n return frames.length > 0 ? frames.join('\\n') : undefined;\n}\n","import { builtinModules } from './builtins';\nimport { LiveCompileError, LiveError, LiveRuntimeError } from './errors';\nimport { evaluate, runModule } from './evaluate';\nimport { injectRenderBudgetTick } from './inject-render-budget';\nimport { createRequire, resolveModules, scanRequires } from './resolver';\nimport { filterUserFrames, mapPosition } from './stacks';\nimport { defaultTranspileOptions, transpile } from './transpile';\nimport type { CompileModuleResult, CompileOptions, CompileResult } from './types';\n\nexport interface CompileInput extends CompileOptions {\n code: string;\n /** Reports each render of the compiled component to the loop breaker. */\n onRender?: () => void;\n}\n\n/**\n * Compiles and evaluates a snippet, returning something renderable.\n *\n * The stages run in a fixed order for one reason: Sucrase emits synchronous\n * `require()` calls, so every module - including any registered as an async\n * loader, must be resolved *before* evaluation begins.\n */\nexport async function compile(input: CompileInput): Promise<CompileResult> {\n const prepared = await prepare(input);\n try {\n const { renderable, via } = evaluate(prepared.evaluateOptions);\n return { renderable, via, code: prepared.code, imports: prepared.imports };\n } catch (cause) {\n throw enrichRuntimeError(cause, prepared.meta);\n }\n}\n\n/**\n * Everything up to evaluation: transpile, then resolve every specifier the\n * output requires.\n *\n * Resolution has to finish first because Sucrase emits synchronous `require()`\n * calls, which cannot await an async loader.\n */\nasync function prepare(input: CompileInput) {\n const {\n code: source,\n modules,\n scope = {},\n transform,\n signal,\n onRender,\n resolveSubpaths = false,\n ...transpileOptions\n } = input;\n\n const options = { ...defaultTranspileOptions, ...transpileOptions };\n\n const budgetedSource = onRender ? injectRenderBudgetTick(source) : source;\n const transformed = await transpile(budgetedSource, options, transform);\n signal?.throwIfAborted();\n\n // Host modules merge over the built-ins so React itself can be substituted,\n // while `react/jsx-runtime` stays available without anyone registering it.\n const registry = { ...builtinModules, ...modules };\n\n const imports = [...scanRequires(transformed.code)].sort();\n\n const resolved = await resolveModules({\n registry,\n specifiers: imports,\n resolveSubpaths,\n ...(signal ? { signal } : {}),\n });\n signal?.throwIfAborted();\n\n return {\n code: transformed.code,\n imports,\n evaluateOptions: {\n code: transformed.code,\n filePath: options.filePath,\n require: createRequire(resolved),\n scope,\n ...(onRender ? { liveTick: onRender } : {}),\n },\n meta: {\n linePrefixOffset: transformed.linePrefixOffset,\n generatedLineCount: countLines(transformed.code),\n sourceLineCount: countLines(source),\n },\n };\n}\n\n/**\n * Compiles and runs a snippet, returning its exports rather than a component.\n *\n * Use this for stored code that is not UI, a validator, a data transformer, a\n * calculated field. {@link compile} is the right call when you need something\n * to render; this one makes no such demand and will happily return\n * `{ validate, schema }`.\n */\nexport async function compileModule(input: CompileInput): Promise<CompileModuleResult> {\n const prepared = await prepare(input);\n try {\n const { exports } = runModule(prepared.evaluateOptions);\n return { exports, code: prepared.code, imports: prepared.imports };\n } catch (cause) {\n throw enrichRuntimeError(cause, prepared.meta);\n }\n}\n\nfunction countLines(text: string): number {\n let count = 1;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) === 10) count++;\n }\n return count;\n}\n\n/**\n * Attaches the snippet's own line number to an error thrown during evaluation,\n * and strips host/React frames so the stack shows only user code.\n */\nfunction enrichRuntimeError(\n cause: unknown,\n meta: { linePrefixOffset: number; generatedLineCount: number; sourceLineCount: number },\n): Error {\n if (!(cause instanceof Error)) {\n return new LiveRuntimeError(String(cause), { cause });\n }\n\n // next-live's own errors already carry good messages and need no mapping.\n if (cause instanceof LiveError) return cause;\n\n const position = positionFromStack(cause.stack);\n const mapped = position ? mapPosition(position, meta) : null;\n\n const error = new LiveRuntimeError(cause.message, { cause });\n error.stack = filterUserFrames(cause.stack) ?? cause.stack;\n if (mapped) {\n Object.defineProperty(error, 'line', { value: mapped.line, enumerable: true });\n if (mapped.column !== undefined) {\n Object.defineProperty(error, 'column', { value: mapped.column, enumerable: true });\n }\n }\n return error;\n}\n\nfunction positionFromStack(stack: string | undefined): { line: number; column?: number } | null {\n if (!stack) return null;\n for (const raw of stack.split('\\n')) {\n if (!raw.includes('next-live:///')) continue;\n const match = /:(\\d+):(\\d+)\\)?\\s*$/.exec(raw.trim());\n if (match?.[1]) {\n return { line: Number(match[1]), column: match[2] ? Number(match[2]) : undefined };\n }\n }\n return null;\n}\n\nexport type { CompileModuleResult } from './types';\nexport { LiveCompileError };\n\n","import { RenderLoopError } from './errors';\n\nexport interface RenderBudgetOptions {\n /** Renders allowed inside one window before the breaker trips. Default 1000. */\n maxRenders?: number;\n /** Length of the rolling window in milliseconds. Default 1000. */\n windowMs?: number;\n}\n\n/**\n * A circuit breaker for runaway re-renders.\n *\n * This is the one class of hang that *can* be caught in the host realm. A\n * synchronous `while (true)` blocks the main thread and nothing - no timer, no\n * AbortController, will ever run again. But the common real failure in\n * authored code is not that: it is `setState` during render, or an effect with\n * a bad dependency array, which React executes as a rapid *sequence* of\n * renders. Between them the breaker gets to run, so it can stop the loop.\n *\n * The throw happens during render so the nearest error boundary catches it and\n * the host application stays alive.\n */\nexport function createRenderBudget(options: RenderBudgetOptions = {}): () => void {\n // Chosen from measurement, not taste. A real runaway loop was observed at\n // ~33,000 renders/second. Legitimate UI is bounded by the display refresh\n // rate (60-120Hz), doubled by React's development double-render - so ~240/s\n // is the realistic ceiling for correct code. 1000 sits comfortably above\n // anything legitimate and far below a true loop, which still trips in ~30ms.\n // An earlier default of 60 was below the legitimate ceiling and could fire on\n // a fast slider drag or an animated snippet.\n const maxRenders = options.maxRenders ?? 1000;\n const windowMs = options.windowMs ?? 1000;\n\n const message =\n `This component rendered more than ${maxRenders} times in ${windowMs}ms, ` +\n 'so next-live stopped it to keep the page responsive.\\n\\n' +\n 'The usual causes are calling a state setter during render, or a ' +\n 'useEffect that updates state without a correct dependency array.';\n\n let windowStart = 0;\n let count = 0;\n let tripped = false;\n\n return function tick(): void {\n // Once tripped, stay tripped. React retries a failed render before handing\n // the error to a boundary, so a breaker that cleared its own counter would\n // let every retry succeed - the error would never surface and the loop\n // would run on forever. A fixed snippet recovers because each compile\n // builds a fresh budget, not because this one forgives.\n if (tripped) throw new RenderLoopError(message);\n\n const now = Date.now();\n if (now - windowStart > windowMs) {\n windowStart = now;\n count = 0;\n }\n count += 1;\n if (count > maxRenders) {\n tripped = true;\n throw new RenderLoopError(message);\n }\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { CompileInput, CompileModuleResult } from '../core/compile';\nimport type { CompileResult, CompileSuccessInfo, UseLiveRunnerOptions } from '../core/types';\n\n/** Separator that cannot appear in an import specifier or identifier. */\nconst KEY_SEP = '\\0';\n\nexport interface CompileTaskState<T> {\n code: string;\n setCode: (code: string) => void;\n result: T | null;\n error: Error | null;\n isCompiling: boolean;\n compileId: number;\n}\n\ninterface InternalState<T> {\n result: T | null;\n error: Error | null;\n compileId: number;\n}\n\nfunction compileSuccessInfo(result: unknown, compileId: number, durationMs: number): CompileSuccessInfo | null {\n if (!result || typeof result !== 'object' || !('imports' in result)) return null;\n const typed = result as CompileResult | CompileModuleResult;\n return {\n compileId,\n imports: typed.imports,\n ...('via' in typed && typed.via !== undefined ? { via: typed.via } : {}),\n durationMs,\n };\n}\n\n/**\n * The scheduling shared by every live hook: debounce, cancellation, spinner\n * delay, and keep-last-good.\n */\nexport function useCompileTask<T>(\n options: Omit<UseLiveRunnerOptions, 'maxRendersPerSecond'>,\n run: (input: CompileInput) => Promise<T>,\n): CompileTaskState<T> {\n const {\n code: initialCode,\n debounce = 150,\n keepLastGood = true,\n onCodeChange,\n onCompileSuccess,\n modules,\n scope,\n transform,\n ...transpileOptions\n } = options;\n\n const [code, setCode] = useState(initialCode);\n const [state, setState] = useState<InternalState<T>>({\n result: null,\n error: null,\n compileId: 0,\n });\n const [isCompiling, setIsCompiling] = useState(false);\n const compileIdRef = useRef(0);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n setCode(initialCode);\n }, [initialCode]);\n\n const modulesKey = useMemo(\n () => Object.keys(modules ?? {}).sort().join(KEY_SEP),\n [modules],\n );\n const scopeKey = useMemo(\n () => Object.keys(scope ?? {}).sort().join(KEY_SEP),\n [scope],\n );\n\n const latest = useRef({\n modules,\n scope,\n transform,\n transpileOptions,\n run,\n onCodeChange,\n onCompileSuccess,\n });\n latest.current = {\n modules,\n scope,\n transform,\n transpileOptions,\n run,\n onCodeChange,\n onCompileSuccess,\n };\n\n const { filePath, production, jsxRuntime, jsxImportSource } = transpileOptions;\n const prevFilePath = useRef(filePath);\n\n // Tab switches often change filePath before code catches up. Dropping the\n // stale renderable immediately avoids mounting the previous snippet's\n // component while the next one compiles.\n useEffect(() => {\n if (filePath === prevFilePath.current) return;\n prevFilePath.current = filePath;\n compileIdRef.current += 1;\n if (!mountedRef.current) return;\n setState({ result: null, error: null, compileId: compileIdRef.current });\n }, [filePath]);\n\n useEffect(() => {\n const controller = new AbortController();\n let cancelled = false;\n\n const spinnerTimer = setTimeout(() => {\n if (!cancelled && mountedRef.current) setIsCompiling(true);\n }, 200);\n\n const timer = setTimeout(() => {\n const current = latest.current;\n const startedAt = performance.now();\n\n current\n .run({\n code,\n signal: controller.signal,\n ...current.transpileOptions,\n ...(current.modules ? { modules: current.modules } : {}),\n ...(current.scope ? { scope: current.scope } : {}),\n ...(current.transform ? { transform: current.transform } : {}),\n })\n .then((result) => {\n if (cancelled || !mountedRef.current) return;\n const nextCompileId = compileIdRef.current + 1;\n compileIdRef.current = nextCompileId;\n setState({\n result,\n error: null,\n compileId: nextCompileId,\n });\n\n const info = compileSuccessInfo(result, nextCompileId, performance.now() - startedAt);\n if (info && current.onCompileSuccess) {\n try {\n current.onCompileSuccess(info);\n } catch {\n // A throwing host callback must not become a compile error.\n }\n }\n })\n .catch((error: unknown) => {\n if (cancelled || !mountedRef.current) return;\n const asError = error instanceof Error ? error : new Error(String(error));\n if (keepLastGood) {\n setState((previous) => ({ ...previous, error: asError }));\n } else {\n const nextCompileId = compileIdRef.current + 1;\n compileIdRef.current = nextCompileId;\n setState({ result: null, error: asError, compileId: nextCompileId });\n }\n })\n .finally(() => {\n if (cancelled || !mountedRef.current) return;\n clearTimeout(spinnerTimer);\n setIsCompiling(false);\n });\n }, debounce);\n\n return () => {\n cancelled = true;\n controller.abort();\n clearTimeout(timer);\n clearTimeout(spinnerTimer);\n };\n }, [\n code,\n debounce,\n keepLastGood,\n modulesKey,\n scopeKey,\n filePath,\n production,\n jsxRuntime,\n jsxImportSource,\n transform,\n ]);\n\n const setCodeStable = useCallback((next: string) => {\n setCode(next);\n latest.current.onCodeChange?.(next);\n }, []);\n\n return {\n code,\n setCode: setCodeStable,\n result: state.result,\n error: state.error,\n isCompiling,\n compileId: state.compileId,\n };\n}\n","'use client';\n\nimport { useCallback } from 'react';\nimport { compile } from '../core/compile';\nimport type { CompileInput } from '../core/compile';\nimport type { CompileResult } from '../core/types';\nimport { createRenderBudget } from '../core/guards';\nimport { useCompileTask } from './useCompileTask';\nimport type { LiveRunnerState, UseLiveRunnerOptions } from '../core/types';\n\n/**\n * The headless engine behind `<LiveProvider>` - compiles a snippet and hands\n * back a component, for hosts building their own UI.\n *\n * Compilation never runs during render or on the server. The first client\n * render produces exactly what the server produced (no component, no error),\n * so there is nothing for React to find mismatched during hydration; the\n * compile starts afterwards, in an effect.\n *\n * For snippets that are not components, use {@link useLiveModule}.\n */\nexport function useLiveRunner(options: UseLiveRunnerOptions): LiveRunnerState {\n const { maxRendersPerSecond = 1000, ...taskOptions } = options;\n\n const run = useCallback(\n (input: CompileInput): Promise<CompileResult> =>\n // A fresh budget per compile, so fixing a snippet clears a tripped\n // breaker without the user having to reload the page.\n compile({ ...input, onRender: createRenderBudget({ maxRenders: maxRendersPerSecond }) }),\n [maxRendersPerSecond],\n );\n\n const task = useCompileTask(taskOptions, run);\n const renderable = task.result?.renderable ?? null;\n\n return {\n code: task.code,\n setCode: task.setCode,\n Component: renderable?.kind === 'component' ? renderable.component : null,\n element: renderable?.kind === 'element' ? renderable.element : null,\n error: task.error,\n isCompiling: task.isCompiling,\n compileId: task.compileId,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { LiveContext } from '../context/LiveContext';\nimport { useLiveRunner } from '../hooks/useLiveRunner';\nimport type { UseLiveRunnerOptions } from '../core/types';\n\nexport interface LiveProviderProps extends Omit<UseLiveRunnerOptions, 'code'> {\n /**\n * The snippet to run. Treated as controlled: when it changes - because a new\n * app was fetched from an API, say, the preview follows.\n */\n code: string;\n /** Props forwarded into the rendered component. Passed by reference. */\n props?: Record<string, unknown>;\n /** Language hint for `<LiveEditor>` highlighting. Default 'tsx'. */\n language?: string;\n /** Notified on every compile and runtime error. */\n onError?: (error: Error) => void;\n /** Rendered by `<LivePreview>` until the first compile finishes. */\n fallback?: ReactNode;\n children?: ReactNode;\n}\n\n/** Stable identity so an omitted `props` never invalidates the context. */\nconst EMPTY_PROPS: Record<string, unknown> = {};\n\n/**\n * Provides a compiled snippet to `<LiveEditor>`, `<LivePreview>`, and\n * `<LiveError>`.\n *\n * Safe to render from a Server Component: nothing is compiled during the\n * server pass, and the first client render matches the server output exactly.\n */\nexport function LiveProvider(props: LiveProviderProps): ReactNode {\n const {\n code,\n props: componentProps,\n language = 'tsx',\n onError,\n fallback = null,\n children,\n ...runnerOptions\n } = props;\n\n const runner = useLiveRunner({ code, ...runnerOptions });\n\n // Errors thrown while *rendering* the snippet arrive from the error boundary\n // rather than the compiler, so they are tracked here and merged below. That\n // keeps <LiveError> a single place to look regardless of which phase failed.\n //\n // The error is tagged with the compile it belongs to rather than cleared by\n // an effect: `componentDidCatch` fires during commit and passive effects run\n // after it, so an effect keyed on `compileId` would wipe the very error the\n // boundary had just reported. Comparing ids makes staleness a render-time\n // question instead, with no ordering to get wrong.\n const [runtimeError, setRuntimeError] = useState<{\n error: Error;\n compileId: number;\n } | null>(null);\n\n const compileIdRef = useRef(runner.compileId);\n compileIdRef.current = runner.compileId;\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n const lastRuntimeReport = useRef<{ compileId: number; message: string } | null>(null);\n\n const reportRuntimeError = useCallback(\n (error: Error) => {\n if (!mountedRef.current) return;\n const compileId = compileIdRef.current;\n const last = lastRuntimeReport.current;\n if (last !== null && last.compileId === compileId && last.message === error.message) {\n return;\n }\n lastRuntimeReport.current = { compileId, message: error.message };\n setRuntimeError({ error, compileId });\n onError?.(error);\n },\n [onError],\n );\n\n const activeRuntimeError =\n runtimeError !== null && runtimeError.compileId === runner.compileId\n ? runtimeError.error\n : null;\n\n const compileError = runner.error;\n useEffect(() => {\n if (compileError) onError?.(compileError);\n }, [compileError, onError]);\n\n const forwardedProps = componentProps ?? EMPTY_PROPS;\n\n const value = useMemo(\n () => ({\n ...runner,\n error: runner.error ?? activeRuntimeError,\n props: forwardedProps,\n language,\n fallback,\n reportRuntimeError,\n }),\n [runner, activeRuntimeError, forwardedProps, language, fallback, reportRuntimeError],\n );\n\n return <LiveContext.Provider value={value}>{children}</LiveContext.Provider>;\n}\n","'use client';\n\nimport { Component } from 'react';\nimport type { ErrorInfo, ReactNode } from 'react';\n\nexport interface LiveErrorBoundaryProps {\n children: ReactNode;\n onError: (error: Error) => void;\n /**\n * Changing this resets the boundary. Wire it to the compile id so fixing a\n * broken snippet recovers on its own, with no manual retry.\n */\n resetKey: unknown;\n fallback?: ReactNode;\n}\n\ninterface State {\n error: Error | null;\n resetKey: unknown;\n /** True after resetKey changes — allows one render attempt before falling back again. */\n recovering: boolean;\n}\n\n/**\n * Contains failures in evaluated code so a bad snippet cannot take down the\n * host application.\n *\n * React recovers from an error by client-rendering the whole nearest boundary,\n * so this one is kept as tight around the preview as possible - anything else\n * on the page is unaffected.\n */\nexport class LiveErrorBoundary extends Component<LiveErrorBoundaryProps, State> {\n private mounted = true;\n\n constructor(props: LiveErrorBoundaryProps) {\n super(props);\n this.state = { error: null, resetKey: props.resetKey, recovering: false };\n }\n\n static getDerivedStateFromError(error: Error): Partial<State> {\n return { error, recovering: false };\n }\n\n static getDerivedStateFromProps(\n props: LiveErrorBoundaryProps,\n state: State,\n ): Partial<State> | null {\n // New code compiled — try one render. Only clear a prior error when\n // recovering succeeds; a still-broken snippet keeps the fallback.\n if (props.resetKey !== state.resetKey) {\n return { resetKey: props.resetKey, recovering: true };\n }\n return null;\n }\n\n override componentDidCatch(error: Error, info: ErrorInfo): void {\n if (!this.mounted) return;\n this.props.onError(error);\n if (process.env.NODE_ENV !== 'production') {\n console.error('next-live: error in evaluated code\\n', error, info.componentStack);\n }\n }\n\n override componentDidUpdate(_prevProps: LiveErrorBoundaryProps, prevState: State): void {\n if (prevState.recovering && this.state.recovering && this.state.error !== null) {\n // Recovery render succeeded — drop the stale error from the previous compile.\n this.setState({ error: null, recovering: false });\n }\n }\n\n override componentWillUnmount(): void {\n this.mounted = false;\n }\n\n override render(): ReactNode {\n if (this.state.error !== null && !this.state.recovering) {\n return this.props.fallback ?? null;\n }\n return this.props.children;\n }\n}\n","'use client';\n\nimport { useContext } from 'react';\nimport { LiveContext } from '../context/LiveContext';\nimport type { LiveContextValue } from '../core/types';\n\n/**\n * Reads the surrounding `<LiveProvider>`. Use it to build custom editors,\n * toolbars, or status indicators that stay in sync with the preview.\n */\nexport function useLiveContext(): LiveContextValue {\n const value = useContext(LiveContext);\n if (value === null) {\n throw new Error(\n 'useLiveContext must be called inside a <LiveProvider>. If you want to run ' +\n 'code without the provider, use the useLiveRunner hook directly.',\n );\n }\n return value;\n}\n","'use client';\n\nimport { createElement, isValidElement } from 'react';\nimport type { ComponentType, ElementType, ReactNode } from 'react';\nimport { isRenderableComponent } from '../core/evaluate';\nimport { LiveErrorBoundary } from './LiveErrorBoundary';\nimport { useLiveContext } from '../hooks/useLiveContext';\n\nexport interface LivePreviewProps {\n /** Element to wrap the preview in. Default 'div'. */\n as?: ElementType;\n className?: string;\n style?: React.CSSProperties;\n /**\n * Props handed to the compiled component, merged over the provider's.\n * Passed by reference, so live objects - a map view, a store, the active\n * user, arrive intact rather than serialized.\n */\n props?: Record<string, unknown>;\n /** Shown until the first compile finishes. Overrides the provider's. */\n fallback?: ReactNode;\n}\n\n/**\n * Renders the compiled component.\n *\n * Until the first compile lands this renders `fallback` - on the server and on\n * the client's first pass alike, which is precisely why hydration cannot\n * mismatch. Give it a skeleton of roughly the right size to avoid layout shift.\n */\nexport function LivePreview(props: LivePreviewProps): ReactNode {\n const { as: Wrapper = 'div', className, style, props: extraProps, fallback } = props;\n const live = useLiveContext();\n\n const merged = extraProps ? { ...live.props, ...extraProps } : live.props;\n const placeholder = fallback !== undefined ? fallback : live.fallback;\n\n let content: ReactNode;\n if (live.Component && isRenderableComponent(live.Component)) {\n content = createElement(live.Component as ComponentType<Record<string, unknown>>, merged);\n } else if (live.element && isValidElement(live.element)) {\n content = live.element;\n } else {\n content = placeholder;\n }\n\n return (\n <Wrapper className={className} style={style}>\n <LiveErrorBoundary\n // Remounting on each successful compile is deliberate: a recompiled\n // component is a new function identity, so its state cannot be carried\n // over, and a stale tree would be worse than a clean one.\n resetKey={live.compileId}\n onError={live.reportRuntimeError}\n // Nothing, rather than the placeholder: a crashed snippet is not\n // \"still loading\", and <LiveError> is what explains what happened.\n fallback={null}\n >\n {content}\n </LiveErrorBoundary>\n </Wrapper>\n );\n}\n","export interface PositionedError extends Error {\n line?: number;\n column?: number;\n}\n\n/**\n * Reads a 1-based line/column from a compile or runtime error, if present.\n *\n * Accepts a nullish value and returns null for it. The state this is meant to\n * be fed from - `LiveRunnerState.error` and `LiveContextValue.error` - is\n * `Error | null`, so `errorPosition(error)` is the natural thing to write in a\n * custom editor. TypeScript rejects that, but a JavaScript host would have hit\n * a TypeError instead of the \"no position\" answer the name promises.\n */\nexport function errorPosition(error: Error | null | undefined): { line: number; column?: number } | null {\n if (error === null || error === undefined) return null;\n const positioned = error as PositionedError;\n if (positioned.line === undefined || positioned.line < 1) return null;\n return {\n line: positioned.line,\n ...(positioned.column !== undefined ? { column: positioned.column } : {}),\n };\n}\n","'use client';\n\nimport type { ElementType, ReactNode } from 'react';\nimport { errorPosition } from '../core/positions';\nimport { useLiveContext } from '../hooks/useLiveContext';\n\nexport interface LiveErrorProps {\n as?: ElementType;\n className?: string;\n style?: React.CSSProperties;\n /** Replaces the default rendering entirely. */\n children?: (error: Error) => ReactNode;\n}\n\n/**\n * Displays the current compile or runtime error, and renders nothing when the\n * snippet is healthy.\n */\nexport function LiveError(props: LiveErrorProps): ReactNode {\n const { as: Wrapper = 'pre', className, style, children } = props;\n const live = useLiveContext();\n\n if (!live.error) return null;\n if (children) return <>{children(live.error)}</>;\n\n const position = errorPosition(live.error);\n const location =\n position !== null\n ? `Line ${position.line}${position.column !== undefined ? `:${position.column}` : ''} - `\n : '';\n\n return (\n <Wrapper\n className={className}\n role=\"alert\"\n style={{\n margin: 0,\n padding: '0.75rem 1rem',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n fontFamily:\n 'ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace',\n fontSize: '0.8125rem',\n lineHeight: 1.5,\n color: '#fff',\n background: '#b3261e',\n ...style,\n }}\n >\n {location}\n {live.error.message}\n </Wrapper>\n );\n}\n","'use client';\n\nimport { useCallback } from 'react';\nimport { compileModule } from '../core/compile';\nimport type { CompileInput, CompileModuleResult } from '../core/compile';\nimport { useCompileTask } from './useCompileTask';\nimport type { UseLiveRunnerOptions } from '../core/types';\n\nexport interface UseLiveModuleOptions\n extends Omit<UseLiveRunnerOptions, 'maxRendersPerSecond'> {}\n\nexport interface LiveModuleState<T extends Record<string, unknown> = Record<string, unknown>> {\n code: string;\n setCode: (code: string) => void;\n /** Everything the snippet exported. Null until the first successful run. */\n exports: T | null;\n /** Shorthand for `exports?.default`. */\n value: unknown;\n error: Error | null;\n isCompiling: boolean;\n /** Increments on every successful run. */\n compileId: number;\n}\n\n/**\n * Runs a snippet and returns its exports, without requiring a React component.\n *\n * Use it for stored code that is not UI - a validator, a data transformer, a\n * calculated field, a config builder:\n *\n * ```ts\n * const { exports } = useLiveModule({ code: rule.source, modules });\n * const isValid = exports?.validate?.(input);\n * ```\n *\n * Shares its scheduling with `useLiveRunner`, so the SSR, debounce, and\n * keep-last-good behaviour is identical: nothing runs during the server pass,\n * and a failed recompile leaves the previous exports in place.\n *\n * The same caveat applies as everywhere else in this library, the snippet runs\n * with your page's full authority, so its author must be someone you trust.\n */\nexport function useLiveModule<T extends Record<string, unknown> = Record<string, unknown>>(\n options: UseLiveModuleOptions,\n): LiveModuleState<T> {\n const run = useCallback(\n (input: CompileInput): Promise<CompileModuleResult> => compileModule(input),\n [],\n );\n\n const task = useCompileTask(options, run);\n const exports = (task.result?.exports as T | undefined) ?? null;\n\n return {\n code: task.code,\n setCode: task.setCode,\n exports,\n value: exports?.['default'],\n error: task.error,\n isCompiling: task.isCompiling,\n compileId: task.compileId,\n };\n}\n","import { defineLoader } from './resolver';\nimport type { ModuleRegistry } from './types';\n\n/**\n * Merges registry groups into one, later groups winning.\n *\n * A large SDK surface is best kept as several small files - one per domain -\n * rather than a single object that grows without bound. This composes them.\n *\n * ```ts\n * export const liveModules = createRegistry(vendorModules, storeModules, uiModules);\n * ```\n *\n * A key defined by two groups is almost always a mistake rather than an\n * intentional override, and it fails silently otherwise, so it warns in\n * development.\n */\nexport function createRegistry(...groups: ModuleRegistry[]): ModuleRegistry {\n const merged: ModuleRegistry = {};\n\n if (process.env.NODE_ENV !== 'production') {\n const seen = new Map<string, number>();\n groups.forEach((group, index) => {\n for (const key of Object.keys(group)) {\n const previous = seen.get(key);\n if (previous !== undefined) {\n console.warn(\n `next-live: module '${key}' is defined in more than one registry group ` +\n `(group ${previous} and group ${index}). The later one wins.`,\n );\n }\n seen.set(key, index);\n }\n });\n }\n\n for (const group of groups) Object.assign(merged, group);\n return merged;\n}\n\n/** The lazy shape `import.meta.glob()` returns: path → thunk. */\nexport type GlobResult = Record<string, () => Promise<unknown>>;\n\n/**\n * Builds a registry from a directory of files, so the registry stops needing\n * hand-maintenance as the codebase grows.\n *\n * Pass the *result* of `import.meta.glob` - the call has to stay in your own\n * code, because bundlers resolve the pattern statically at the call site.\n * (`import.meta.glob` requires Turbopack; under webpack, build an equivalent\n * `{ path: () => import(path) }` object yourself.)\n *\n * ```ts\n * export const storeModules = registryFromGlob(\n * import.meta.glob('../stores/*.ts'),\n * (path) => `@app/store/${path.split('/').pop()!.replace(/\\.tsx?$/, '')}`,\n * );\n * // → { '@app/store/cart': <loader>, '@app/store/user': <loader>, … }\n * ```\n *\n * Every entry is a loader, so none of these files is fetched until a snippet\n * imports it.\n *\n * @param glob Result of `import.meta.glob(pattern)`, left lazy.\n * @param toSpecifier Maps a file path to the specifier snippet authors write.\n * Return `null` to leave a file out of the registry.\n */\nexport function registryFromGlob(\n glob: GlobResult,\n toSpecifier: (path: string) => string | null,\n): ModuleRegistry {\n const registry: ModuleRegistry = {};\n\n for (const [path, load] of Object.entries(glob)) {\n const specifier = toSpecifier(path);\n if (specifier === null) continue;\n\n if (process.env.NODE_ENV !== 'production' && specifier in registry) {\n console.warn(\n `next-live: two files map to the module specifier '${specifier}'. ` +\n 'Check the toSpecifier function for collisions.',\n );\n }\n\n registry[specifier] = defineLoader(() => load());\n }\n\n return registry;\n}\n"]}