@luckystack/devkit 0.2.7 → 0.3.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/typeMap/discovery.ts","../src/routingRules.ts","../src/typeMap/routeMeta.ts","../src/routeConventions.ts","../src/typeMap/apiMeta.ts","../src/typeMap/emitterArtifacts.ts","../src/internal/mapUtils.ts","../src/typeMap/zodEmitter.ts","../src/typeMap/extractors.ts","../src/typeMap/tsProgram.ts","../src/typeMap/functionsMeta.ts","../src/typeMap/typeContext.ts","../src/typeMapGenerator.ts","../src/routeNamingValidation.ts","../src/templateRegistry.ts","../src/loader.ts","../src/runtimeTypeResolver.ts","../src/hotReload.ts","../src/templateInjector.ts","../src/importDependencyGraph.ts","../src/prismaClientCheck.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR } from '@luckystack/core';\nimport {\n getRoutingRules,\n isApiFileName,\n isSyncClientFileName,\n isSyncServerFileName,\n apiMarkerSegment,\n syncMarkerSegment,\n} from '../routingRules';\n\nconst toForwardSlashRelative = (absolute: string): string => {\n const rel = path.relative(ROOT_DIR, absolute);\n return rel.replaceAll('\\\\', '/');\n};\n\nconst walkFiles = (\n dir: string,\n matcher: (fullPath: string, entryName: string) => boolean,\n results: string[] = [],\n visited = new Set<string>()\n): string[] => {\n // Resolve the real path to detect symlink cycles before descending.\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch {\n return results;\n }\n if (visited.has(realDir)) return results;\n visited.add(realDir);\n\n const { ignore } = getRoutingRules();\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = toForwardSlashRelative(fullPath);\n\n if (ignore(relativePath)) continue;\n\n if (entry.isDirectory() || entry.isSymbolicLink()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;\n // Only recurse if this is actually a directory (resolves symlinks).\n try {\n if (fs.statSync(fullPath).isDirectory()) {\n walkFiles(fullPath, matcher, results, visited);\n }\n } catch {\n // Broken symlink — skip.\n }\n continue;\n }\n\n if (entry.isFile() && matcher(fullPath, entry.name)) {\n results.push(fullPath);\n }\n }\n } catch (error) {\n console.error(`[TypeMapDiscovery] Error scanning directory ${dir}:`, error);\n }\n\n return results;\n};\n\nexport const findAllApiFiles = (srcDir: string): string[] => {\n const apiSegment = apiMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isApiFileName(entryName) && normalized.includes(apiSegment);\n });\n};\n\nexport const findAllSyncServerFiles = (srcDir: string): string[] => {\n const syncSegment = syncMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isSyncServerFileName(entryName) && normalized.includes(syncSegment);\n });\n};\n\nexport const findAllSyncClientFiles = (srcDir: string): string[] => {\n const syncSegment = syncMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isSyncClientFileName(entryName) && normalized.includes(syncSegment);\n });\n};\n","//? Routing rule registry. Lets consumers customize the file-based routing\n//? conventions that devkit uses to discover APIs, sync events, and ignored\n//? folders.\n//?\n//? Defaults preserve the framework's original `_api`/`_sync` markers and the\n//? `_v{N}.ts` / `_server_v{N}.ts` / `_client_v{N}.ts` filename suffixes. The\n//? `ignore` predicate is called for each candidate path during discovery; a\n//? consumer can return `true` to skip e.g. `__tests__` folders, vendor\n//? directories, or any other custom rule.\n\nexport interface RoutingRules {\n /** Folder name that marks an API directory. Default: `_api`. */\n apiMarker: string;\n /** Folder name that marks a sync directory. Default: `_sync`. */\n syncMarker: string;\n /** Suffix matcher for API files: must end with `_v<number>.ts`. */\n apiVersionRegex: RegExp;\n /** Suffix matcher for sync server files: must end with `_server_v<number>.ts`. */\n syncServerVersionRegex: RegExp;\n /** Suffix matcher for sync client files: must end with `_client_v<number>.ts`. */\n syncClientVersionRegex: RegExp;\n /** Combined sync regex (server or client). */\n syncVersionRegex: RegExp;\n /**\n * Predicate called for each candidate file/folder during discovery.\n * Return `true` to skip. Path is provided as a forward-slash relative\n * string from the workspace root (e.g. `src/dashboard/__tests__/foo_v1.ts`).\n */\n ignore: (relativePath: string) => boolean;\n /**\n * Single-character prefix that marks a folder as **invisible-parent** for\n * page routing: `src/_housing/renting/page.tsx` resolves to `/renting`\n * (the `_housing` segment is stripped from the URL). A `page.tsx` placed\n * directly inside an `_<name>` folder is invalid (no URL segment left).\n *\n * Default: `'_'`. Override only if you need a different prefix scheme.\n */\n privateFolderPrefix: string;\n /**\n * Folder names that are reserved for framework-internal use and may NEVER\n * host a `page.tsx`. Scaffold + page-discovery emit a hard error when a\n * page is placed inside one. Extend (do not replace) the defaults if you\n * add your own internal folder convention.\n *\n * Defaults: `_api`, `_sync`, `_function(s)`, `_component(s)`, `_provider(s)`,\n * `_locale(s)`, `_socket(s)`, `_shared`, `_server`. The semantic markers\n * (`_api`, `_sync`) are also reserved by the API/sync routers.\n */\n scaffoldIgnoredFolders: string[];\n /**\n * Optional predicate. Return `true` for a given absolute file path to\n * disable template injection entirely for that file. Useful when a\n * consumer wants to opt some part of the tree out of the scaffold\n * (e.g. `/src/migrations/**` lives by hand). The argument is the\n * absolute path the chokidar watcher provides; the predicate is\n * called BEFORE the `isInApiFolder` / `isPageFile` checks fire.\n */\n disableTemplateInjection?: (filePath: string) => boolean;\n}\n\nconst DEFAULT_RULES: RoutingRules = {\n apiMarker: '_api',\n syncMarker: '_sync',\n apiVersionRegex: /_v(\\d+)$/,\n syncServerVersionRegex: /_server_v(\\d+)$/,\n syncClientVersionRegex: /_client_v(\\d+)$/,\n syncVersionRegex: /_(server|client)_v(\\d+)$/,\n ignore: () => false,\n privateFolderPrefix: '_',\n scaffoldIgnoredFolders: [\n '_api',\n '_sync',\n '_function',\n '_functions',\n '_component',\n '_components',\n '_provider',\n '_providers',\n '_locale',\n '_locales',\n '_socket',\n '_sockets',\n '_shared',\n '_server',\n ],\n};\n\nlet activeRules: RoutingRules = DEFAULT_RULES;\n\nexport const registerRoutingRules = (overrides: Partial<RoutingRules>): RoutingRules => {\n activeRules = { ...DEFAULT_RULES, ...overrides };\n return activeRules;\n};\n\nexport const getRoutingRules = (): RoutingRules => activeRules;\n\n//? Convenience helpers built on top of the active rules — used by\n//? loader/hotReload/discovery so call sites don't have to compose the\n//? marker name into a path-segment check themselves.\nexport const apiMarkerSegment = (): string => `/${getRoutingRules().apiMarker}/`;\nexport const syncMarkerSegment = (): string => `/${getRoutingRules().syncMarker}/`;\n\nexport const isApiFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().apiVersionRegex.test(stem);\n};\n\nexport const isSyncServerFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncServerVersionRegex.test(stem);\n};\n\nexport const isSyncClientFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncClientVersionRegex.test(stem);\n};\n\nexport const isSyncFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncVersionRegex.test(stem);\n};\n\n//? Per-route business-logic test files (`<name>_v<N>.tests.ts` and\n//? `<name>_server_v<N>.tests.ts`) live INSIDE `_api/` and `_sync/` folders\n//? alongside the route they cover. Loaders, validators, and template\n//? injectors must skip them — they are picked up separately by\n//? `@luckystack/test-runner`.\nexport const isRouteTestFile = (fileNameOrPath: string): boolean => {\n return fileNameOrPath.endsWith('.tests.ts');\n};\n\n//? Re-export the core page-route validator + bind it to the active\n//? `RoutingRules` (so a consumer that calls `registerRoutingRules({\n//? scaffoldIgnoredFolders: [...] })` to add a custom private folder\n//? sees the override applied here too). The pure helper lives in\n//? `@luckystack/core/pageRouteValidation.ts` so the client-side router\n//? in `src/main.tsx` can import it without dragging devkit into the\n//? Vite bundle.\nimport { validatePagePath as corePagePath, type PagePathValidationResult as CoreResult, type PageRouteRules } from '@luckystack/core';\n\nexport type PagePathValidationResult = CoreResult;\n\nexport const validatePagePath = (srcRelativePath: string): PagePathValidationResult => {\n const rules = getRoutingRules();\n const pageRules: PageRouteRules = {\n privateFolderPrefix: rules.privateFolderPrefix,\n scaffoldIgnoredFolders: rules.scaffoldIgnoredFolders,\n };\n return corePagePath(srcRelativePath, pageRules);\n};\n","import path from 'node:path';\nimport { getSrcDir } from '@luckystack/core';\nimport { API_VERSION_TOKEN_REGEX, SYNC_VERSION_TOKEN_REGEX } from '../routeConventions';\n\nconst VERSION_SUFFIX_REGEX = API_VERSION_TOKEN_REGEX;\n\nconst stripVersionSuffix = (name: string): string => {\n // VERSION_SUFFIX_REGEX is anchored (`$`) so it matches at most once — `.replace` is correct here.\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return name.replace(VERSION_SUFFIX_REGEX, '');\n};\n\nconst extractVersionFromName = (name: string): string | null => {\n const match = VERSION_SUFFIX_REGEX.exec(name);\n if (!match) return null;\n return `v${match[1]}`;\n};\n\nexport const extractPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n // Anchor on the configured srcDir so non-`src` layouts are handled correctly.\n const srcDirNormalized = getSrcDir().replaceAll('\\\\', '/');\n const rel = path.posix.relative(srcDirNormalized, normalized);\n // If the file is outside the srcDir the relative path starts with '..';\n // throw so callers know this file should not have been discovered.\n if (rel.startsWith('..')) {\n throw new Error(`[routeMeta] file is outside srcDir — cannot extract page path: ${filePath}`);\n }\n const match = /^(?:(.+?)\\/)_api\\//.exec(rel);\n if (match) {\n return match[1] ?? 'system';\n }\n if (rel.startsWith('_api/')) {\n return 'system';\n }\n return '';\n};\n\nexport const extractApiName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_api\\/(.+)\\.ts$/.exec(normalized);\n const rawName = match?.[1] ?? path.basename(filePath, '.ts');\n return stripVersionSuffix(rawName);\n};\n\nexport const extractApiVersion = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_api\\/(.+)\\.ts$/.exec(normalized);\n const rawName = match?.[1] ?? path.basename(filePath, '.ts');\n return extractVersionFromName(rawName) ?? 'v1';\n};\n\nexport const extractSyncPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n //? A sync directly under `src/_sync/` gets the `'system'` sentinel, matching\n //? `extractPagePath` (API side) AND the dev loader's root-sync route key.\n //? Using `'root'` here made the type-map key + generated `FullSyncPath`\n //? (`sync/root/<name>/v1`) disagree with the loader's runtime registration\n //? AND the wire name the typed `syncRequest` actually sends\n //? (`sync/system/<name>/v1`) — so a root sync silently never dispatched.\n const srcDirNormalized = getSrcDir().replaceAll('\\\\', '/');\n const rel = path.posix.relative(srcDirNormalized, normalized);\n const match = /^(?:(.+?)\\/)_sync\\//.exec(rel);\n if (match) {\n return match[1] ?? 'system';\n }\n if (rel.startsWith('_sync/')) {\n return 'system';\n }\n return '';\n};\n\nexport const extractSyncName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_sync\\/(.+)\\.ts$/.exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n // SYNC_VERSION_TOKEN_REGEX is anchored (`$`) — matches at most once.\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return basename.replace(SYNC_VERSION_TOKEN_REGEX, '');\n }\n\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return (match[1] ?? '').replace(SYNC_VERSION_TOKEN_REGEX, '');\n};\n\nexport const extractSyncVersion = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_sync\\/(.+)\\.ts$/.exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n const versionMatch = SYNC_VERSION_TOKEN_REGEX.exec(basename);\n return versionMatch ? `v${versionMatch[2] ?? '1'}` : 'v1';\n }\n\n const versionMatch = SYNC_VERSION_TOKEN_REGEX.exec(match[1] ?? '');\n return versionMatch ? `v${versionMatch[2] ?? '1'}` : 'v1';\n};\n","//? Static convention defaults. These remain exported for backwards\n//? compatibility with code that accesses them as RegExp/string literals\n//? (e.g. `name.replace(API_VERSION_TOKEN_REGEX, '')`). Call sites that\n//? must honor consumer-overridden conventions read from\n//? `getRoutingRules()` (in `./routingRules.ts`) instead.\n\nimport {\n isApiFileName as isApi,\n isSyncFileName as isSync,\n isSyncServerFileName as isSyncServer,\n isSyncClientFileName as isSyncClient,\n} from './routingRules';\n\nexport const API_VERSION_TOKEN_REGEX = /_v(\\d+)$/;\nexport const SYNC_VERSION_TOKEN_REGEX = /_(server|client)_v(\\d+)$/;\n\nexport const API_VERSIONED_FILE_REGEX = /_v\\d+\\.ts$/;\nexport const SYNC_SERVER_VERSIONED_FILE_REGEX = /_server_v\\d+\\.ts$/;\nexport const SYNC_CLIENT_VERSIONED_FILE_REGEX = /_client_v\\d+\\.ts$/;\nexport const SYNC_VERSIONED_FILE_REGEX = /_(?:server|client)_v\\d+\\.ts$/;\n\nexport const ROUTE_NAMING_RULES = {\n api: '<name>_v<number>.ts',\n syncServer: '<name>_server_v<number>.ts',\n syncClient: '<name>_client_v<number>.ts',\n} as const;\n\nexport const ROUTE_NAMING_EXAMPLES = {\n api: 'updateUser_v1.ts',\n syncServer: 'updateCounter_server_v1.ts',\n syncClient: 'updateCounter_client_v1.ts',\n} as const;\n\n//? These checks honor `registerRoutingRules({...})` overrides because they\n//? delegate to the registry-aware functions in `./routingRules`.\nexport const isVersionedApiFileName = (fileName: string): boolean => isApi(fileName);\nexport const isVersionedSyncFileName = (fileName: string): boolean => isSync(fileName);\nexport const isVersionedSyncServerFileName = (fileName: string): boolean => isSyncServer(fileName);\nexport const isVersionedSyncClientFileName = (fileName: string): boolean => isSyncClient(fileName);\n","import * as ts from 'typescript';\nimport fs from 'node:fs';\nimport { inferHttpMethod, tryCatchSync } from '@luckystack/core';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n// Finds an exported const declaration by name in a source file's top-level statements.\nconst findExportedConst = (sourceFile: ts.SourceFile, name: string): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n const hasExport = statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n if (!hasExport) continue;\n\n for (const decl of statement.declarationList.declarations) {\n if (ts.isIdentifier(decl.name) && decl.name.text === name) return decl;\n }\n }\n return null;\n};\n\n//? Unwrap `as const` / `as T` / `satisfies T` / parenthesized wrappers so an\n//? initializer like `'DELETE' as const` is read as its underlying literal.\n//? The TS AST wraps these in AsExpression / SatisfiesExpression /\n//? ParenthesizedExpression nodes that the literal-type guards below would\n//? otherwise skip — silently dropping the authored value and falling back to\n//? an inferred default. Solving the wrapper class once covers every extractor.\nconst unwrapExpression = (node: ts.Expression): ts.Expression => {\n let current = node;\n while (\n ts.isAsExpression(current)\n || ts.isSatisfiesExpression(current)\n || ts.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n};\n\nexport const extractHttpMethod = (filePath: string, apiName: string): HttpMethod => {\n const [error, method] = tryCatchSync((): HttpMethod | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'httpMethod');\n\n const initializer = decl?.initializer ? unwrapExpression(decl.initializer) : undefined;\n if (initializer && ts.isStringLiteral(initializer)) {\n const candidate = initializer.text.toUpperCase() as HttpMethod;\n if (['GET', 'POST', 'PUT', 'DELETE'].includes(candidate)) return candidate;\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting httpMethod from ${filePath}:`, error);\n }\n\n return method ?? inferHttpMethod(apiName);\n};\n\nexport const extractRateLimit = (filePath: string): number | false | undefined => {\n const [error, rateLimit] = tryCatchSync((): number | false | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'rateLimit');\n\n if (decl?.initializer) {\n const initializer = unwrapExpression(decl.initializer);\n if (initializer.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (ts.isNumericLiteral(initializer)) return Number(initializer.text);\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting rateLimit from ${filePath}:`, error);\n }\n\n return rateLimit ?? undefined;\n};\n\n/**\n * Reads the `export const validation` declaration from an API/sync source\n * file. Supports `'strict'`, `'relaxed'`, and `{ input: 'skip' | 'strict' }`.\n * Returns undefined when the export is absent (consumer hasn't opted out).\n */\nexport type ApiValidationMode = 'strict' | 'relaxed' | { input: 'skip' | 'strict' };\n\nexport const extractValidation = (filePath: string): ApiValidationMode | undefined => {\n const [error, validation] = tryCatchSync((): ApiValidationMode | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'validation');\n\n if (!decl?.initializer) return undefined;\n const initializer = unwrapExpression(decl.initializer);\n\n if (ts.isStringLiteral(initializer)) {\n const text = initializer.text;\n if (text === 'strict' || text === 'relaxed') return text;\n }\n\n if (ts.isObjectLiteralExpression(initializer)) {\n for (const prop of initializer.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n if (prop.name.text !== 'input') continue;\n const propInit = unwrapExpression(prop.initializer);\n if (!ts.isStringLiteral(propInit)) continue;\n const input = propInit.text;\n if (input === 'skip' || input === 'strict') return { input };\n }\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting validation from ${filePath}:`, error);\n }\n\n return validation ?? undefined;\n};\n\n// Reads a primitive value from an AST expression node.\nconst readPrimitive = (rawNode: ts.Expression): string | number | boolean | undefined => {\n const node = unwrapExpression(rawNode);\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNumericLiteral(node)) return Number(node.text);\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n return undefined;\n};\n\nconst parseAdditionalItem = (objectLiteral: ts.ObjectLiteralExpression): Record<string, unknown> | null => {\n const item: Record<string, unknown> = {};\n\n for (const prop of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const value = readPrimitive(prop.initializer);\n if (value !== undefined) item[prop.name.text] = value;\n }\n\n return item.key ? item : null;\n};\n\n/**\n * AST-extracted JSDoc `@docs` metadata for a route file. Parsed from JSDoc\n * blocks attached to top-level statements (typically the `main` export).\n *\n * Convention (matches docs-ui renderer in `packages/docs-ui/src/docsHtml.ts`):\n *\n * /\\*\\*\n * * Description sentence.\n * * @docs owner @mathijs\n * * @docs tags admin, internal, deprecated-soon\n * * @docs deprecated use api/billing/getInvoice/v2 instead\n * *\\/\n * export const main = async (...) => {...};\n *\n * `@docs deprecated` without a reason -> `true` (renders as red \"deprecated\"\n * badge without explanation). With a reason -> `string` (renders the\n * explanation). `@docs tags` is comma-split + trimmed. Unknown sub-keys are\n * silently ignored so future tags don't break the parser.\n */\nexport interface DocsMeta {\n owner?: string;\n tags?: string[];\n deprecated?: string | true;\n}\n\n//? Flatten a JSDoc tag comment (string or `ts.NodeArray` of comment parts) to text.\nconst commentToString = (commentValue: unknown): string => {\n if (typeof commentValue === 'string') return commentValue;\n if (Array.isArray(commentValue)) {\n return commentValue\n .map((part) => {\n if (part && typeof part === 'object' && 'text' in part && typeof (part as { text: unknown }).text === 'string') {\n return (part as { text: string }).text;\n }\n return '';\n })\n .join('');\n }\n return '';\n};\n\nexport const extractDocsMeta = (filePath: string): DocsMeta | undefined => {\n const [error, docsMeta] = tryCatchSync((): DocsMeta | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const result: DocsMeta = {};\n\n const consumeTag = (tag: ts.JSDocTag): void => {\n if (tag.tagName.text !== 'docs') return;\n const commentText = commentToString(tag.comment).trim();\n if (commentText.length === 0) return;\n\n const spaceIdx = commentText.search(/\\s/);\n const subkey = (spaceIdx === -1 ? commentText : commentText.slice(0, spaceIdx)).toLowerCase();\n const value = spaceIdx === -1 ? '' : commentText.slice(spaceIdx + 1).trim();\n\n if (subkey === 'owner' && value.length > 0) {\n result.owner = value;\n } else if (subkey === 'tags' && value.length > 0) {\n const tags = value.split(',').map((s) => s.trim()).filter((s) => s.length > 0);\n if (tags.length > 0) result.tags = tags;\n } else if (subkey === 'deprecated') {\n result.deprecated = value.length > 0 ? value : true;\n }\n //? unknown sub-keys: ignore (forward-compat for future @docs <key> tags)\n };\n\n //? Walk every top-level statement and collect JSDoc tags. This catches\n //? JSDoc on the `main` export, on the `auth`/`rateLimit` consts, or on\n //? any other top-level declaration — wherever the author wrote it.\n for (const statement of sourceFile.statements) {\n for (const tag of ts.getJSDocTags(statement)) {\n consumeTag(tag);\n }\n }\n\n if (result.owner === undefined && result.tags === undefined && result.deprecated === undefined) {\n return undefined;\n }\n return result;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting @docs metadata from ${filePath}:`, error);\n return undefined;\n }\n\n return docsMeta ?? undefined;\n};\n\nexport const extractAuth = (filePath: string): { login: boolean; additional?: Record<string, unknown>[] } => {\n const [, auth] = tryCatchSync((): { login: boolean; additional?: Record<string, unknown>[] } => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'auth');\n const authInitializer = decl?.initializer ? unwrapExpression(decl.initializer) : undefined;\n //? DK-05 (public-by-default): a route that omits `export const auth` — OR\n //? whose `auth` omits / non-literally sets `login` — extracts as PUBLIC\n //? (`login: false`), matching the dev runtime loader (`auth.login || false`),\n //? the generated `apiMetaMap`, and the test-runner auth sweep. The defect\n //? this closes was the runtime↔tooling DISAGREEMENT: the loader defaulted to\n //? public while this extractor defaulted to protected, so the generated meta\n //? + auth sweep disagreed with what actually ran. A route that needs auth\n //? MUST declare a literal `auth: { login: true }`.\n if (!authInitializer || !ts.isObjectLiteralExpression(authInitializer)) return { login: false };\n\n let login = false;\n let additional: Record<string, unknown>[] | undefined;\n\n for (const prop of authInitializer.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const propInit = unwrapExpression(prop.initializer);\n\n if (prop.name.text === 'login') {\n login = propInit.kind === ts.SyntaxKind.TrueKeyword;\n }\n\n if (prop.name.text === 'additional' && ts.isArrayLiteralExpression(propInit)) {\n additional = [];\n for (const element of propInit.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue;\n const item = parseAdditionalItem(element);\n if (item) additional.push(item);\n }\n }\n }\n\n return additional && additional.length > 0 ? { login, additional } : { login };\n });\n\n //? Parse failure falls through to PUBLIC, consistent with the public-by-default\n //? policy above (and the runtime loader). A route needing auth declares a\n //? literal `auth: { login: true }`.\n return auth ?? { login: false };\n};\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport * as ts from 'typescript';\nimport { getGeneratedApiDocsPath, getGeneratedApiSchemasPath, getGeneratedSocketTypesPath } from '@luckystack/core';\n\nimport { mustGet } from '../internal/mapUtils';\nimport { typeTextToZodSource } from './zodEmitter';\n\n//? `auth` is consumer-defined opaque — each project exports its own\n//? `AuthProps` shape from `config.ts`. The emitter passes the parsed value\n//? through to the generated JSON.\n//? Forward declaration mirrored from `apiMeta.ts:DocsMeta`. Kept local to\n//? avoid a circular import between the type-map collectors and the emitter.\nexport interface DocsMetaSnapshot {\n\towner?: string;\n\ttags?: string[];\n\tdeprecated?: string | true;\n}\n\nexport interface ApiTypeEntry {\n\tinput: string;\n\toutput: string;\n\tstream: string;\n\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\trateLimit: number | false | undefined;\n\tauth: unknown;\n\tversion: string;\n\t//? Optional `@docs owner/tags/deprecated` metadata. Set when the route\n\t//? file declares any of these JSDoc sub-keys. Surfaced in\n\t//? `apiDocs.generated.json` so `@luckystack/docs-ui` can render it.\n\tmeta?: DocsMetaSnapshot;\n}\n\ninterface ApiDocsEntry {\n\tpage: string;\n\tname: string;\n\tversion: string;\n\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\tinput: string;\n\toutput: string;\n\tstream: string;\n\trateLimit: number | false | undefined;\n\tauth: unknown;\n\tpath: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\ninterface SyncDocsEntry {\n\tpage: string;\n\tname: string;\n\tversion: string;\n\tclientInput: string;\n\tserverOutput: string;\n\tclientOutput: string;\n\tserverStream: string;\n\tclientStream: string;\n\tpath: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\nexport interface GeneratedDocsData {\n\tapis: Record<string, ApiDocsEntry[]>;\n\tsyncs: Record<string, SyncDocsEntry[]>;\n}\n\nexport interface SyncTypeEntry {\n\tclientInput: string;\n\tserverOutput: string;\n\tclientOutput: string;\n\tserverStream: string;\n\tclientStream: string;\n\tversion: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\nconst buildImportStatements = ({\n\tnamedImports,\n\tdefaultImports,\n}: {\n\tnamedImports: Map<string, Set<string>>;\n\tdefaultImports: Map<string, string>;\n}): string => {\n\tlet importStatements = '';\n\tfor (const [importPath, types] of namedImports) {\n\t\timportStatements += `import { ${[...types].join(', ')} } from \"${importPath}\";\\n`;\n\t}\n\tfor (const [importPath, defaultName] of defaultImports) {\n\t\timportStatements += `import ${defaultName} from \"${importPath}\";\\n`;\n\t}\n\treturn importStatements;\n};\n\nconst splitVersionedKey = (value: string): { name: string; version: string } => {\n\tconst [name, version] = value.split('@');\n\treturn { name: name ?? '', version: version ?? 'v1' };\n};\n\nconst writeFileIfChanged = (filePath: string, content: string): boolean => {\n\tif (fs.existsSync(filePath)) {\n\t\tconst currentContent = fs.readFileSync(filePath, 'utf8');\n\t\tif (currentContent === content) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfs.writeFileSync(filePath, content, 'utf8');\n\treturn true;\n};\n\nconst indentStr = (str: string, indentText: string): string => {\n\treturn str.split('\\n').map((line, i) => i === 0 ? line : indentText + line).join('\\n');\n};\n\nconst validateGeneratedTypeIdentifiers = (content: string): void => {\n\tconst sourceFile = ts.createSourceFile('apiTypes.generated.ts', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst knownSymbols = new Set<string>();\n\tconst referencedSymbols = new Set<string>();\n\n\tconst builtIns = new Set([\n\t\t'string', 'number', 'boolean', 'null', 'undefined', 'unknown', 'any', 'never', 'void', 'object', 'bigint', 'symbol',\n\t\t'Record', 'Partial', 'Required', 'Pick', 'Omit', 'Readonly', 'Exclude', 'Extract', 'NonNullable', 'ReturnType',\n\t\t'Awaited', 'Promise', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Array', 'ReadonlyArray', 'Date', 'Error', 'RegExp',\n\t\t'True', 'False', 'JsonPrimitive', 'JsonValue', 'JsonObject', 'JsonArray',\n\t]);\n\n\tconst addDeclaredName = (name?: ts.Identifier): void => {\n\t\tif (!name?.text) return;\n\t\tknownSymbols.add(name.text);\n\t};\n\n\tconst collectTypeParams = (node: ts.Node): void => {\n\t\tif (!('typeParameters' in node)) return;\n\t\tconst maybeTypeParameters = (node as ts.Node & { typeParameters?: ts.NodeArray<ts.TypeParameterDeclaration> }).typeParameters;\n\t\tif (!maybeTypeParameters) return;\n\t\tfor (const typeParameter of maybeTypeParameters) {\n\t\t\tknownSymbols.add(typeParameter.name.text);\n\t\t}\n\t};\n\n\tconst collectKnownSymbols = (node: ts.Node): void => {\n\t\tif (ts.isInferTypeNode(node)) {\n\t\t\tknownSymbols.add(node.typeParameter.name.text);\n\t\t}\n\n\t\tif (ts.isMappedTypeNode(node)) {\n\t\t\tknownSymbols.add(node.typeParameter.name.text);\n\t\t}\n\n\t\tif (ts.isImportDeclaration(node)) {\n\t\t\tconst importClause = node.importClause;\n\t\t\tif (importClause?.name) knownSymbols.add(importClause.name.text);\n\t\t\tif (importClause?.namedBindings && ts.isNamedImports(importClause.namedBindings)) {\n\t\t\t\tfor (const importElement of importClause.namedBindings.elements) {\n\t\t\t\t\tknownSymbols.add((importElement.propertyName ?? importElement.name).text);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (importClause?.namedBindings && ts.isNamespaceImport(importClause.namedBindings)) {\n\t\t\t\tknownSymbols.add(importClause.namedBindings.name.text);\n\t\t\t}\n\t\t}\n\n\t\tif (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node) || ts.isFunctionDeclaration(node)) {\n\t\t\taddDeclaredName(node.name);\n\t\t\tcollectTypeParams(node);\n\t\t}\n\n\t\tif (ts.isTypeReferenceNode(node)) {\n\t\t\tconst typeName = node.typeName;\n\t\t\tif (ts.isIdentifier(typeName)) {\n\t\t\t\treferencedSymbols.add(typeName.text);\n\t\t\t}\n\t\t\tif (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left)) {\n\t\t\t\treferencedSymbols.add(typeName.left.text);\n\t\t\t}\n\t\t}\n\n\t\tts.forEachChild(node, collectKnownSymbols);\n\t};\n\n\tcollectKnownSymbols(sourceFile);\n\n\tconst unknown = [...referencedSymbols]\n\t\t.filter((name) => !knownSymbols.has(name) && !builtIns.has(name))\n\t\t.toSorted();\n\n\tif (unknown.length > 0) {\n\t\tthrow new Error(`[TypeMapGenerator] Generated type map has unresolved type identifiers: ${unknown.join(', ')}`);\n\t}\n};\n\nexport interface DiagnosticsEntry {\n\troute: string;\n\tkind: 'api' | 'sync';\n\tfield: string;\n\tfallback: string;\n\treason: string;\n}\n\nexport interface GeneratedDiagnosticsData {\n\tgeneratedAt: string;\n\ttotalRoutes: number;\n\tfallbackCount: number;\n\tfallbacks: DiagnosticsEntry[];\n}\n\n//? Detects type fields that fell back to a degraded default. Three signals:\n//? 1. `{ }` on input/clientInput — getSourceFile miss or missing ApiParams.data.\n//? 2. `{ status: string }` on output — main function has no typed return shape.\n//? 3. `z.any()` in the Zod schema source — zodEmitter hit an unsupported TypeNode.\n//? These are not hard errors but lose type safety on the affected routes.\nconst collectFallbacks = (\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>,\n\tsyncTypesByPage: Map<string, Map<string, SyncTypeEntry>>,\n): DiagnosticsEntry[] => {\n\tconst entries: DiagnosticsEntry[] = [];\n\n\tconst flagField = (route: string, kind: 'api' | 'sync', field: string, value: string): void => {\n\t\tif (value === '{ }' || value === '{ status: string }') {\n\t\t\tentries.push({ route, kind, field, fallback: value, reason: 'default-fallback' });\n\t\t\treturn;\n\t\t}\n\t\tconst zodSrc = typeTextToZodSource(value);\n\t\tif (zodSrc?.includes('z.any()')) {\n\t\t\tentries.push({ route, kind, field, fallback: value.slice(0, 80), reason: 'zod-any-fallback' });\n\t\t}\n\t};\n\n\tfor (const [pagePath, apis] of typesByPage) {\n\t\tfor (const [apiKey, entry] of apis) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tconst route = `${pagePath}/${name}@${version}`;\n\t\t\tflagField(route, 'api', 'input', entry.input);\n\t\t\tflagField(route, 'api', 'output', entry.output);\n\t\t}\n\t}\n\n\tfor (const [pagePath, syncs] of syncTypesByPage) {\n\t\tfor (const [syncKey, entry] of syncs) {\n\t\t\tconst { name, version } = splitVersionedKey(syncKey);\n\t\t\tconst route = `${pagePath}/${name}@${version}`;\n\t\t\tflagField(route, 'sync', 'clientInput', entry.clientInput);\n\t\t\tflagField(route, 'sync', 'serverOutput', entry.serverOutput);\n\t\t\tflagField(route, 'sync', 'clientOutput', entry.clientOutput);\n\t\t}\n\t}\n\n\treturn entries;\n};\n\nexport const buildTypeMapArtifacts = ({\n\ttypesByPage,\n\tsyncTypesByPage,\n\tnamedImports,\n\tdefaultImports,\n\tfunctionsInterface,\n}: {\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>;\n\tsyncTypesByPage: Map<string, Map<string, SyncTypeEntry>>;\n\tnamedImports: Map<string, Set<string>>;\n\tdefaultImports: Map<string, string>;\n\tfunctionsInterface: string;\n}) => {\n\tconst importStatements = buildImportStatements({ namedImports, defaultImports });\n\n\tlet content = `/* eslint-disable @typescript-eslint/no-unnecessary-condition */\n/* eslint-disable @typescript-eslint/ban-types */\n\n/**\n * Auto-generated type map for all API and Sync endpoints.\n * Enables type-safe apiRequest and syncRequest calls.\n */\n\n${importStatements}\nexport interface Functions {\n${functionsInterface}\n};\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\nexport interface JsonObject {\n\t[key: string]: JsonValue | undefined;\n}\nexport type JsonArray = JsonValue[];\nexport type MaybePromise<T> = T | Promise<T>;\n\nexport type StreamPayload = {\n\t[key: string]: unknown;\n};\n\nexport type ApiStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\nexport type SyncServerStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\nexport type SyncClientStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\n//? Broadcast — fan-out to every socket in the receiver room (cross-instance via the Redis adapter).\nexport type SyncBroadcastStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void;\n//? Targeted — emit only to the listed session tokens (each token is its own room).\nexport type SyncStreamToEmitter<T extends StreamPayload = StreamPayload> = (\n\ttokens: string | string[],\n\tpayload?: T,\n) => void;\n\n// \n// API Type Definitions\n// \n\nexport type ApiResponse<T = unknown> =\n\t| ({ status: 'success'; httpStatus?: number; APINAME?: never; [key: string]: unknown } & T)\n\t| { status: 'error'; httpStatus?: number; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[]; APINAME?: never };\n\nexport type ApiNetworkResponse<T = unknown> =\n\t| ({ status: 'success'; httpStatus: number; APINAME?: never; [key: string]: unknown } & T)\n\t| { status: 'error'; httpStatus: number; message: string; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[]; APINAME?: never };\n\n//\n// API Type Map\n//\n\ntype _ProjectApiTypeMap = {\n`;\n\n\tconst sortedPages = [...typesByPage.keys()].toSorted();\n\tconst sortedSyncPages = [...syncTypesByPage.keys()].toSorted();\n\tconst docsData: GeneratedDocsData = { apis: {}, syncs: {} };\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tdocsData.apis[pagePath] = [];\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tdocsData.apis[pagePath].push({\n\t\t\t\t\tpage: pagePath,\n\t\t\t\t\tname: apiName,\n\t\t\t\t\tversion,\n\t\t\t\t\tmethod: entry.method,\n\t\t\t\t\tinput: entry.input,\n\t\t\t\t\toutput: entry.output,\n\t\t\t\t\tstream: entry.stream,\n\t\t\t\t\trateLimit: entry.rateLimit,\n\t\t\t\t\tauth: entry.auth,\n\t\t\t\t\tpath: pagePath === 'root' ? `api/${apiName}/${version}` : `api/${pagePath}/${apiName}/${version}`,\n\t\t\t\t\t...(entry.meta ? { meta: entry.meta } : {}),\n\t\t\t\t});\n\n\t\t\t\tcontent += ` '${version}': {\\n`;\n\t\t\t\tcontent += ` input: ${indentStr(entry.input, ' ')};\\n`;\n\t\t\t\t//? Union the framework error envelope so ApiOutput<P,N,V> covers the\n\t\t\t\t//? error branch without a Rule-21-forbidden cast at every call site.\n\t\t\t\t//? The index signature mirrors ApiErrorResponse so property accesses\n\t\t\t\t//? that do not narrow on status first remain compile-clean.\n\t\t\t\tcontent += ` output: ${indentStr(entry.output, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` stream: ${indentStr(entry.stream, ' ')};\\n`;\n\t\t\t\tcontent += ` method: '${entry.method}';\\n`;\n\t\t\t\tif (entry.rateLimit !== undefined) {\n\t\t\t\t\tcontent += ` rateLimit: ${entry.rateLimit};\\n`;\n\t\t\t\t}\n\t\t\t\tcontent += ` };\\n`;\n\t\t\t}\n\t\t\tcontent += ` };\\n`;\n\t\t}\n\t\tcontent += ` };\\n`;\n\t}\n\n\tcontent += `};\n\nexport interface ApiTypeMap extends _ProjectApiTypeMap {}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport type PagePath = keyof ApiTypeMap;\nexport type ApiName<P extends PagePath> = keyof ApiTypeMap[P];\nexport type ApiVersion<P extends PagePath, N extends ApiName<P>> = keyof ApiTypeMap[P][N];\nexport type ApiInput<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { input: infer I } ? I : never;\nexport type ApiOutput<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { output: infer O } ? O : never;\nexport type ApiStream<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { stream: infer S } ? S : never;\nexport type ApiMethod<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { method: infer M } ? M : never;\n\nexport type FullApiPath<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N>> = \\`api/\\${P}/\\${N & string}/\\${V & string}\\`;\n\nexport const apiMethodMap: Record<string, Record<string, Record<string, HttpMethod>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; method: string }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, method: entry.method });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {`;\n\t\t\tconst methods = mustGet(grouped, apiName, 'grouped')\n\t\t\t\t.toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))\n\t\t\t\t.map((item) => ` '${item.version}': '${item.method}'`)\n\t\t\t\t.join(',');\n\t\t\tcontent += `${methods} },\\n`;\n\t\t}\n\t\tcontent += ` },\\n`;\n\t}\n\n\tcontent += `};\n\nexport const getApiMethod = (pagePath: string, apiName: string, version: string): HttpMethod | undefined => {\n\treturn apiMethodMap[pagePath]?.[apiName]?.[version];\n};\n\nexport interface ApiMetaEntry {\n\tmethod: HttpMethod;\n\tauth: { login: boolean; additional?: Record<string, unknown>[] };\n\trateLimit?: number | false;\n}\n\nexport const apiMetaMap: Record<string, Record<string, Record<string, ApiMetaEntry>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tconst auth = entry.auth && typeof entry.auth === 'object'\n\t\t\t\t\t? entry.auth as { login: boolean; additional?: Record<string, unknown>[] }\n\t\t\t\t\t: { login: true };\n\t\t\t\tconst rateLimitPart = entry.rateLimit === undefined\n\t\t\t\t\t? ''\n\t\t\t\t\t: `, rateLimit: ${entry.rateLimit === false ? 'false' : String(entry.rateLimit)}`;\n\t\t\t\tconst additionalPart = auth.additional && auth.additional.length > 0\n\t\t\t\t\t? `, additional: ${JSON.stringify(auth.additional)}`\n\t\t\t\t\t: '';\n\t\t\t\tcontent += ` '${version}': { method: '${entry.method}', auth: { login: ${auth.login ? 'true' : 'false'}${additionalPart} }${rateLimitPart} },\\n`;\n\t\t\t}\n\t\t\tcontent += ` },\\n`;\n\t\t}\n\t\tcontent += ` },\\n`;\n\t}\n\n\tcontent += `};\n\nexport const getApiMeta = (pagePath: string, apiName: string, version: string): ApiMetaEntry | undefined => {\n\treturn apiMetaMap[pagePath]?.[apiName]?.[version];\n};\n\n// Sync Type Definitions\n// \n\nexport type SyncServerResponse<T = unknown> =\n\t| ({ status: 'success'; [key: string]: unknown } & T)\n\t| { status: 'error'; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[] };\n\nexport type SyncClientResponse<T = unknown> =\n\t| ({ status: 'success'; [key: string]: unknown } & T)\n\t| { status: 'error'; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[] };\n\n//\n// Sync Type Map\n//\n\ntype _ProjectSyncTypeMap = {\n`;\n\n\tfor (const pagePath of sortedSyncPages) {\n\t\tconst syncs = mustGet(syncTypesByPage, pagePath, 'syncTypesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: SyncTypeEntry }[]>();\n\t\tdocsData.syncs[pagePath] = [];\n\n\t\tfor (const [syncKey, entry] of syncs.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(syncKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const syncName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${syncName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, syncName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tdocsData.syncs[pagePath].push({\n\t\t\t\t\tpage: pagePath,\n\t\t\t\t\tname: syncName,\n\t\t\t\t\tversion,\n\t\t\t\t\tclientInput: entry.clientInput,\n\t\t\t\t\tserverOutput: entry.serverOutput,\n\t\t\t\t\tclientOutput: entry.clientOutput,\n\t\t\t\t\tserverStream: entry.serverStream,\n\t\t\t\t\tclientStream: entry.clientStream,\n\t\t\t\t\t//? `extractSyncPagePath` returns the `'system'` sentinel (NOT\n\t\t\t\t\t//? `'root'`) for a src-root sync, matching the loader's runtime key\n\t\t\t\t\t//? (`sync/system/<name>/<version>`) AND the wire name the typed\n\t\t\t\t\t//? `syncRequest` sends. The old `pagePath === 'root'` branch is now\n\t\t\t\t\t//? dead and would emit a non-matching path, so it is removed.\n\t\t\t\t\tpath: `sync/${pagePath}/${syncName}/${version}`,\n\t\t\t\t\t...(entry.meta ? { meta: entry.meta } : {}),\n\t\t\t\t});\n\n\t\t\t\tcontent += ` '${version}': {\\n`;\n\t\t\t\tcontent += ` clientInput: ${indentStr(entry.clientInput, ' ')};\\n`;\n\t\t\t\t//? Same error-envelope union as API output — makes SyncServerOutput /\n\t\t\t\t//? SyncClientOutput cover the error branch without casts.\n\t\t\t\tcontent += ` serverOutput: ${indentStr(entry.serverOutput, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` clientOutput: ${indentStr(entry.clientOutput, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` serverStream: ${indentStr(entry.serverStream, ' ')};\\n`;\n\t\t\t\tcontent += ` clientStream: ${indentStr(entry.clientStream, ' ')};\\n`;\n\t\t\t\tcontent += ` };\\n`;\n\t\t\t}\n\t\t\tcontent += ` };\\n`;\n\t\t}\n\t\tcontent += ` };\\n`;\n\t}\n\n\tcontent += `};\n\nexport interface SyncTypeMap extends _ProjectSyncTypeMap {}\n\nexport type SyncPagePath = keyof SyncTypeMap;\nexport type SyncName<P extends SyncPagePath> = keyof SyncTypeMap[P];\nexport type SyncVersion<P extends SyncPagePath, N extends SyncName<P>> = keyof SyncTypeMap[P][N];\nexport type SyncClientInput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientInput: infer C } ? C : never;\nexport type SyncServerOutput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { serverOutput: infer S } ? S : never;\nexport type SyncClientOutput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientOutput: infer O } ? O : never;\nexport type SyncServerStream<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { serverStream: infer S } ? S : never;\nexport type SyncClientStream<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientStream: infer O } ? O : never;\n\nexport type FullSyncPath<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N>> = \\`sync/\\${P}/\\${N & string}/\\${V & string}\\`;\n\n//\n// Type-level augmentation — merges the project's concrete ApiTypeMap / SyncTypeMap\n// into the @luckystack/core/typemap stub-declaration module so framework code\n// (apiRequest / syncRequest) sees the project routes without deep-relative\n// imports. Augmenting the module that DECLARES the stubs (not the re-exporting\n// barrel) is what makes the merge land for consumers installing the built dist.\n//\ndeclare module '@luckystack/core/typemap' {\n\tinterface ApiTypeMap extends _ProjectApiTypeMap {}\n\tinterface SyncTypeMap extends _ProjectSyncTypeMap {}\n}\n`;\n\n\tvalidateGeneratedTypeIdentifiers(content);\n\n\t//? Zod schemas for every API input. Runtime validators + test-runner fuzz\n\t//? use this file. Emitted alongside the type map so the two always track.\n\tconst schemasContent = buildSchemasContent({ typesByPage });\n\n\t//? Diagnostics: collect routes with degraded type extraction so the\n\t//? generator exposes them in a machine-readable file rather than only\n\t//? logging to stderr. Consumers and CI can grep this file for fallbacks\n\t//? without parsing the generated TS source.\n\tconst fallbacks = collectFallbacks(typesByPage, syncTypesByPage);\n\tconst totalRoutes = [...typesByPage.values()].reduce((n, m) => n + m.size, 0)\n\t\t+ [...syncTypesByPage.values()].reduce((n, m) => n + m.size, 0);\n\tconst diagnosticsData: GeneratedDiagnosticsData = {\n\t\tgeneratedAt: new Date().toISOString(),\n\t\ttotalRoutes,\n\t\tfallbackCount: fallbacks.length,\n\t\tfallbacks,\n\t};\n\n\treturn { content, docsData, schemasContent, diagnosticsData };\n};\n\nconst buildSchemasContent = ({\n\ttypesByPage,\n}: {\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>;\n}): string => {\n\tconst sortedPages = [...typesByPage.keys()].toSorted();\n\n\tlet body = `/* eslint-disable */\n//? Auto-generated Zod schemas for every API input. Driven by the same walk\n//? as apiTypes.generated.ts; see @luckystack/devkit/src/typeMap/zodEmitter.ts\n//? for the TS-AST → Zod converter. Types that fall outside the converter's\n//? scope emit \\`z.any()\\` with a TODO comment.\n\nimport { z } from 'zod';\n\nexport const apiInputSchemas: Record<string, Record<string, Record<string, z.ZodTypeAny>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tbody += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tbody += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted(\n\t\t\t\t(a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }),\n\t\t\t)) {\n\t\t\t\tconst schemaSrc = typeTextToZodSource(entry.input) ?? 'z.any() /* unparseable input type */';\n\t\t\t\tbody += ` '${version}': ${schemaSrc},\\n`;\n\t\t\t}\n\t\t\tbody += ` },\\n`;\n\t\t}\n\t\tbody += ` },\\n`;\n\t}\n\n\tbody += `};\n\nexport const getApiInputSchema = (\n\tpagePath: string,\n\tapiName: string,\n\tversion: string,\n): z.ZodTypeAny | undefined => {\n\treturn apiInputSchemas[pagePath]?.[apiName]?.[version];\n};\n`;\n\n\treturn body;\n};\n\nexport const writeTypeMapArtifacts = ({\n\tcontent,\n\tdocsData,\n\tschemasContent,\n\tdiagnosticsData,\n}: {\n\tcontent: string;\n\tdocsData: GeneratedDocsData;\n\tschemasContent?: string;\n\tdiagnosticsData?: GeneratedDiagnosticsData;\n}) => {\n\ttry {\n\t\tconst outputPath = getGeneratedSocketTypesPath();\n\t\tconst hasUpdatedTypeMap = writeFileIfChanged(outputPath, content);\n\t\tif (hasUpdatedTypeMap) {\n\t\t\tconsole.log('[TypeMapGenerator] Generated apiTypes.generated.ts');\n\t\t}\n\n\t\tif (schemasContent !== undefined) {\n\t\t\tconst hasUpdatedSchemas = writeFileIfChanged(getGeneratedApiSchemasPath(), schemasContent);\n\t\t\tif (hasUpdatedSchemas) {\n\t\t\t\tconsole.log('[TypeMapGenerator] Generated apiInputSchemas.generated.ts');\n\t\t\t}\n\t\t}\n\n\t\tconst docsPath = getGeneratedApiDocsPath();\n\t\tconst docsDir = path.dirname(docsPath);\n\t\tif (!fs.existsSync(docsDir)) {\n\t\t\tfs.mkdirSync(docsDir, { recursive: true });\n\t\t}\n\t\tconst docsContent = JSON.stringify(docsData, null, 2);\n\t\tconst hasUpdatedDocs = writeFileIfChanged(docsPath, docsContent);\n\t\tif (hasUpdatedDocs) {\n\t\t\tconsole.log('[TypeMapGenerator] Generated apiDocs.generated.json');\n\t\t}\n\n\t\tif (diagnosticsData !== undefined) {\n\t\t\t//? Placed next to apiDocs.generated.json so the same docs dir is reused.\n\t\t\t//? Routes listed here have degraded type extraction (see DiagnosticsEntry.reason).\n\t\t\tconst diagnosticsPath = path.join(path.dirname(docsPath), 'apiTypeDiagnostics.generated.json');\n\t\t\tconst diagnosticsContent = JSON.stringify(diagnosticsData, null, 2);\n\t\t\tconst hasUpdatedDiagnostics = writeFileIfChanged(diagnosticsPath, diagnosticsContent);\n\t\t\tif (hasUpdatedDiagnostics) {\n\t\t\t\tconsole.log('[TypeMapGenerator] Generated apiTypeDiagnostics.generated.json');\n\t\t\t}\n\t\t\tif (diagnosticsData.fallbackCount > 0) {\n\t\t\t\tconsole.warn(`[TypeMapGenerator] ${diagnosticsData.fallbackCount} route(s) have degraded type extraction (see apiTypeDiagnostics.generated.json)`);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconsole.error('[TypeMapGenerator] Error writing type map or docs:', error);\n\t}\n};\n\n","//? Internal map utilities for devkit. Replace the `map.get(key)!` pattern\n//? (banned by the strict-typing policy) with helpers that either\n//? lazily initialize an entry (`getOrInit`) or throw a labelled error\n//? when the invariant breaks (`mustGet`). Both surface the actual\n//? failure site instead of silently producing `undefined`.\n\nexport const getOrInit = <K, V>(map: Map<K, V>, key: K, factory: () => V): V => {\n const existing = map.get(key);\n if (existing !== undefined) return existing;\n const fresh = factory();\n map.set(key, fresh);\n return fresh;\n};\n\nexport const mustGet = <K, V>(map: Map<K, V>, key: K, label: string): V => {\n const value = map.get(key);\n if (value === undefined) {\n throw new Error(`[devkit] invariant violation: '${String(key)}' missing from ${label}`);\n }\n return value;\n};\n","import * as ts from 'typescript';\n\n//? Converts a TypeScript type expression into Zod schema source text.\n//?\n//? Scope today — handles the shapes used by LuckyStack API/sync inputs:\n//? - Primitives: string, number, boolean, null, undefined, any, unknown\n//? - String/number literal types\n//? - Union types (including `| undefined` for optional fields)\n//? - Array types: `T[]` and `Array<T>`\n//? - Object types with property signatures and optional modifier\n//? - Index signatures: `Record<string, T>` and `{ [key: string]: T }`\n//? - `Partial`, `Required`, `Pick`, `Omit`, `Record` as best-effort (TypeRef)\n//?\n//? Out of scope — falls back to `z.any()` with a TODO comment:\n//? - Intersections (A & B) — needs shape merging\n//? - Generic parameters beyond Record/Partial/etc.\n//? - Mapped types, conditional types\n//? - Interface references (A from another file) — resolve at call site\n//?\n//? Why write our own instead of `ts-to-zod`: the input here is a bare type\n//? expression string, not a file with declarations. ts-to-zod expects the\n//? latter. Also: no codegen tool handles `{ [key: string]: never }` — the\n//? LuckyStack \"no input\" convention — without special-casing.\n//?\n//? Strict-vs-loose policy (DD-DEVKIT-D2 decision):\n//? Object literals → `.strict()` (rejects unknown keys, fail-closed posture).\n//? Routes that need to accept extra keys can declare `export const validation\n//? = 'relaxed'` (stripped by the Zod layer, future opt-out hook). All other\n//? fallback paths (`z.any()`, `z.record(...)`) remain loose because we have\n//? no structural shape to enforce. The `z.any()` fallback count is surfaced\n//? in `apiTypeDiagnostics.generated.json` so degraded routes are visible.\n\nconst wrapOptional = (inner: string): string => `${inner}.optional()`;\nconst anyFallback = (reason: string): string => `z.any() /* ${reason} */`;\n\nconst convertTypeNode = (node: ts.TypeNode): string => {\n // Primitives\n if (node.kind === ts.SyntaxKind.StringKeyword) return 'z.string()';\n if (node.kind === ts.SyntaxKind.NumberKeyword) return 'z.number()';\n if (node.kind === ts.SyntaxKind.BooleanKeyword) return 'z.boolean()';\n if (node.kind === ts.SyntaxKind.NullKeyword) return 'z.null()';\n if (node.kind === ts.SyntaxKind.UndefinedKeyword) return 'z.undefined()';\n if (node.kind === ts.SyntaxKind.AnyKeyword) return 'z.any()';\n if (node.kind === ts.SyntaxKind.UnknownKeyword) return 'z.unknown()';\n if (node.kind === ts.SyntaxKind.NeverKeyword) return 'z.never()';\n\n // Literal types: 'foo', 42, true, false\n if (ts.isLiteralTypeNode(node)) {\n const literal = node.literal;\n if (ts.isStringLiteral(literal)) return `z.literal(${JSON.stringify(literal.text)})`;\n if (ts.isNumericLiteral(literal)) return `z.literal(${literal.text})`;\n if (literal.kind === ts.SyntaxKind.TrueKeyword) return 'z.literal(true)';\n if (literal.kind === ts.SyntaxKind.FalseKeyword) return 'z.literal(false)';\n if (literal.kind === ts.SyntaxKind.NullKeyword) return 'z.null()';\n return anyFallback('unknown literal');\n }\n\n // Array: T[]\n if (ts.isArrayTypeNode(node)) {\n return `z.array(${convertTypeNode(node.elementType)})`;\n }\n\n // Union: A | B | undefined\n if (ts.isUnionTypeNode(node)) {\n const members = node.types;\n //? If `undefined` appears, treat as `.optional()` on the remaining union.\n const hasUndefined = members.some(m => m.kind === ts.SyntaxKind.UndefinedKeyword);\n const nonUndef = members.filter(m => m.kind !== ts.SyntaxKind.UndefinedKeyword);\n\n if (nonUndef.length === 0) return 'z.undefined()';\n\n const firstNonUndef = nonUndef[0];\n const innerSchema =\n nonUndef.length === 1 && firstNonUndef\n ? convertTypeNode(firstNonUndef)\n : `z.union([${nonUndef.map((m) => convertTypeNode(m)).join(', ')}])`;\n\n return hasUndefined ? wrapOptional(innerSchema) : innerSchema;\n }\n\n // Type reference: Record<K, V>, Partial<T>, etc.\n if (ts.isTypeReferenceNode(node)) {\n const name = node.typeName.getText();\n const args = node.typeArguments ?? [];\n\n switch (name) {\n case 'Record': {\n //? Record<string, T> → z.record(z.string(), convert(T))\n const arg0 = args[0];\n const arg1 = args[1];\n if (args.length === 2 && arg0 && arg1) {\n return `z.record(${convertTypeNode(arg0)}, ${convertTypeNode(arg1)})`;\n }\n return anyFallback('Record with unexpected arity');\n }\n case 'Partial': {\n //? Partial<{...}> flattens into making each property optional. Without\n //? resolving the referenced type we emit a best-effort record — the\n //? runtime validator on the server still enforces full correctness.\n const arg0 = args[0];\n return args.length === 1 && arg0\n ? `${convertTypeNode(arg0)}.partial()`\n : anyFallback('Partial without type arg');\n }\n case 'Array': {\n const arg0 = args[0];\n return args.length === 1 && arg0\n ? `z.array(${convertTypeNode(arg0)})`\n : anyFallback('Array without element type');\n }\n case 'Date': {\n return 'z.date()';\n }\n default: {\n return anyFallback(`unresolved TypeReference '${name}'`);\n }\n }\n }\n\n // Object literal type: { key: T; key2?: T2; [k: string]: T3 }\n if (ts.isTypeLiteralNode(node)) {\n const indexSignatures = node.members.filter((m) => ts.isIndexSignatureDeclaration(m));\n const propertySignatures = node.members.filter((m) => ts.isPropertySignature(m));\n\n //? LuckyStack's \"no input\" convention: `{ [key: string]: never }` → empty\n //? object schema. Zod's `.passthrough()` isn't right because we actually\n //? want to reject extra fields.\n if (\n indexSignatures.length === 1\n && propertySignatures.length === 0\n && indexSignatures[0]?.type.kind === ts.SyntaxKind.NeverKeyword\n ) {\n return 'z.object({}).strict()';\n }\n\n if (indexSignatures.length > 0 && propertySignatures.length === 0) {\n //? Pure index signature → z.record(keyType, valueType).\n const sig = indexSignatures[0];\n const keyType = sig?.parameters[0]?.type;\n const valueType = sig?.type;\n if (sig && keyType && valueType) {\n return `z.record(${convertTypeNode(keyType)}, ${convertTypeNode(valueType)})`;\n }\n }\n\n //? Regular object with property signatures.\n const entries = propertySignatures.map((prop) => {\n if (!ts.isIdentifier(prop.name)) return null;\n if (!prop.type) return null;\n\n const name = prop.name.text;\n let schema = convertTypeNode(prop.type);\n\n //? `?` on the property makes it optional, regardless of whether the\n //? type itself includes `| undefined`.\n if (prop.questionToken && !schema.endsWith('.optional()')) {\n schema = wrapOptional(schema);\n }\n\n return `${JSON.stringify(name)}: ${schema}`;\n }).filter((entry): entry is string => entry !== null);\n\n //? `.strict()` rejects unknown keys, matching the framework's fail-closed\n //? input validation posture. Consumers can opt out per-route via\n //? `export const validation = 'relaxed'`.\n return `z.object({ ${entries.join(', ')} }).strict()`;\n }\n\n // Parenthesized: (T)\n if (ts.isParenthesizedTypeNode(node)) {\n return convertTypeNode(node.type);\n }\n\n // Intersection: A & B — best-effort merge via z.object().extend() isn't\n // possible without both sides being objects. Fall back for now.\n if (ts.isIntersectionTypeNode(node)) {\n return anyFallback('intersection not yet supported');\n }\n\n return anyFallback(`unsupported TypeNode kind=${String(node.kind)}`);\n};\n\n/**\n * Convert a TypeScript type expression string (as emitted into the generated\n * file) into a Zod schema source string.\n *\n * Returns `null` when the input can't be parsed as a type — callers should\n * fall back to `z.any()` in that case.\n */\nexport const typeTextToZodSource = (typeText: string): string | null => {\n const trimmed = typeText.trim();\n if (!trimmed) return null;\n\n //? Parse as a top-level `type __ = <expr>;` so ts.createSourceFile gives us\n //? back a TypeAliasDeclaration whose `type` property is the TypeNode we\n //? want. No module/file loader involved.\n const synthetic = `type __X = ${trimmed};`;\n const source = ts.createSourceFile('__zod.ts', synthetic, ts.ScriptTarget.Latest, true);\n\n const statement = source.statements[0];\n if (!statement || !ts.isTypeAliasDeclaration(statement)) return null;\n\n return convertTypeNode(statement.type);\n};\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { getServerProgram, expandTypeDetailed, ExpandedTypeResult, UnresolvedTypeSymbol } from './tsProgram';\nimport { getGeneratedSocketTypesPath } from '@luckystack/core';\n\nexport type TypeExtractionResult = ExpandedTypeResult;\n\nconst TYPE_NAME_PATTERN = /\\b[A-Z][A-Za-z0-9_]*\\b/g;\n\nconst KNOWN_GLOBAL_TYPE_NAMES = new Set([\n 'String', 'Number', 'Boolean', 'Object', 'Array', 'ReadonlyArray', 'Promise', 'Map', 'Set', 'WeakMap', 'WeakSet',\n 'Date', 'RegExp', 'Error', 'Record', 'Partial', 'Required', 'Pick', 'Omit', 'Readonly', 'Exclude', 'Extract',\n 'NonNullable', 'ReturnType', 'Awaited', 'JsonValue', 'JsonObject', 'JsonArray', 'JsonPrimitive',\n]);\n\nconst normalizeImportPath = (targetFilePath: string): string => {\n // Derive fromDir from the configured generated socket types path so\n // non-`src` srcDir layouts produce correct relative import paths.\n const fromDir = path.dirname(getGeneratedSocketTypesPath());\n const from = fromDir.replaceAll('\\\\', '/');\n const to = targetFilePath.replaceAll('\\\\', '/');\n const normalized = path.posix.relative(from, to).replaceAll('\\\\', '/');\n const withoutExtension = normalized.replace(/(\\.d)?\\.(ts|tsx|js|jsx)$/i, '');\n if (withoutExtension.startsWith('.')) return withoutExtension;\n return `./${withoutExtension}`;\n};\n\nconst mergeUnresolvedSymbols = (\n left: UnresolvedTypeSymbol[],\n right: UnresolvedTypeSymbol[],\n): UnresolvedTypeSymbol[] => {\n const merged = [...left];\n const seen = new Set(merged.map((symbol) => `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`));\n\n for (const symbol of right) {\n const key = `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(symbol);\n }\n\n return merged;\n};\n\nconst collectFallbackSymbolsFromTypeText = (\n typeText: string,\n scopeNode: ts.Node,\n checker: ts.TypeChecker,\n): UnresolvedTypeSymbol[] => {\n const names = new Set((typeText.match(TYPE_NAME_PATTERN) ?? []).filter((name) => !KNOWN_GLOBAL_TYPE_NAMES.has(name)));\n const symbolsInScope = checker.getSymbolsInScope(\n scopeNode,\n ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum | ts.SymbolFlags.Alias,\n );\n\n const unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n for (const name of names) {\n const localSymbol = symbolsInScope.find((symbol) => symbol.name === name);\n if (!localSymbol) continue;\n\n const targetSymbol = (localSymbol.flags & ts.SymbolFlags.Alias) === 0\n ? localSymbol\n : checker.getAliasedSymbol(localSymbol);\n const declaration = targetSymbol.declarations?.[0];\n\n if (!declaration) {\n unresolvedSymbols.push({ name });\n continue;\n }\n\n const sourceFile = declaration.getSourceFile().fileName;\n if (!sourceFile || sourceFile.includes('/node_modules/') || sourceFile.includes('\\\\node_modules\\\\')) {\n continue;\n }\n\n unresolvedSymbols.push({\n name,\n sourceFile,\n importPath: normalizeImportPath(sourceFile),\n });\n }\n\n return unresolvedSymbols;\n};\n\n// shared helpers\n\n// Finds a top-level interface declaration by name in a source file's statements.\nconst findInterface = (sourceFile: ts.SourceFile, name: string): ts.InterfaceDeclaration | null => {\n for (const stmt of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === name) return stmt;\n }\n return null;\n};\n\n// Reads the type of a named property inside an interface declaration.\nconst getInterfacePropertyType = (\n iface: ts.InterfaceDeclaration,\n propertyName: string,\n checker: ts.TypeChecker,\n): ts.Type | null => {\n for (const member of iface.members) {\n if (\n ts.isPropertySignature(member)\n && ts.isIdentifier(member.name)\n && member.name.text === propertyName\n && member.type\n ) {\n return checker.getTypeFromTypeNode(member.type);\n }\n }\n return null;\n};\n\n// Finds the function-like initializer of `const main = ...` in a source file.\nconst findMainFunction = (sourceFile: ts.SourceFile): ts.FunctionLikeDeclaration | null => {\n for (const stmt of sourceFile.statements) {\n if (ts.isVariableStatement(stmt)) {\n for (const decl of stmt.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name)\n && decl.name.text === 'main'\n && decl.initializer\n && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n }\n\n if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === 'main') {\n return stmt;\n }\n }\n return null;\n};\n\n// Collects the expanded type strings of all object-literal return statements\n// in a function body, without descending into nested function definitions.\nconst collectReturnObjectTypeDetails = (\n funcNode: ts.FunctionLikeDeclaration,\n checker: ts.TypeChecker,\n): TypeExtractionResult => {\n const types: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n const visit = (node: ts.Node) => {\n if (ts.isReturnStatement(node) && node.expression && ts.isObjectLiteralExpression(node.expression)) {\n const type = checker.getTypeAtLocation(node.expression);\n const expanded = expandTypeDetailed(type, checker);\n types.push(expanded.text);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(\n unresolvedSymbols,\n collectFallbackSymbolsFromTypeText(expanded.text, node.expression, checker),\n );\n }\n\n // Recurse into control flow but not into nested function bodies\n if (\n !ts.isArrowFunction(node)\n && !ts.isFunctionExpression(node)\n && !ts.isFunctionDeclaration(node)\n ) {\n ts.forEachChild(node, visit);\n }\n };\n\n ts.forEachChild(funcNode, visit);\n return { text: unionTypes(types), unresolvedSymbols };\n};\n\n// Collects the expanded payload type strings of stream(...) /\n// broadcastStream(...) / streamTo(tokens, ...) calls in a function body,\n// without descending into nested function definitions.\n//\n// `stream` and `broadcastStream` take the payload as the FIRST argument.\n// `streamTo` takes `(tokens, payload)` so the payload is the SECOND argument.\nconst STREAM_EMIT_NAMES = new Set(['stream', 'broadcastStream', 'streamTo']);\n\nconst collectStreamCallPayloadTypeDetails = (\n funcNode: ts.FunctionLikeDeclaration,\n checker: ts.TypeChecker,\n): TypeExtractionResult => {\n const types: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n const visit = (node: ts.Node) => {\n if (\n ts.isCallExpression(node)\n && ts.isIdentifier(node.expression)\n && STREAM_EMIT_NAMES.has(node.expression.text)\n ) {\n const callName = node.expression.text;\n //? streamTo(tokens, payload) — payload is at index 1; everything else\n //? puts the payload at index 0.\n const payloadIndex = callName === 'streamTo' ? 1 : 0;\n const payloadArg = node.arguments[payloadIndex];\n\n if (payloadArg) {\n const argType = checker.getTypeAtLocation(payloadArg);\n const nonNullableArgType = checker.getNonNullableType(argType);\n const expanded = expandTypeDetailed(nonNullableArgType, checker);\n\n if (expanded.text.trim().length > 0) {\n types.push(expanded.text);\n }\n\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(\n unresolvedSymbols,\n collectFallbackSymbolsFromTypeText(expanded.text, payloadArg, checker),\n );\n }\n }\n\n // Recurse into control flow but not into nested function bodies\n if (\n !ts.isArrowFunction(node)\n && !ts.isFunctionExpression(node)\n && !ts.isFunctionDeclaration(node)\n ) {\n ts.forEachChild(node, visit);\n }\n };\n\n ts.forEachChild(funcNode, visit);\n return { text: unionTypes(types), unresolvedSymbols };\n};\n\n// Returns the deduplicated union of an array of type strings.\nconst unionTypes = (types: string[]): string => {\n const unique = [...new Set(types)];\n return unique.length > 0 ? unique.join(' | ') : '';\n};\n\n// public API \n\nexport const getInputTypeFromFile = (filePath: string): string => {\n return getInputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getInputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) {\n //? Marker-contract (DD-DEVKIT-D1): a getSourceFile miss is always a loud\n //? warning, never silent. The generator invalidates the TS Program cache\n //? before every upsert, so a miss here means the file is genuinely absent\n //? from the Program (e.g. added to disk but tsconfig globs not updated).\n //? The route falls back to `{ }` (empty input) until the next full rebuild.\n //? The fallback is surfaced in `apiTypeDiagnostics.generated.json` so it\n //? is visible without parsing console output.\n console.warn(`[TypeMapGenerator] getSourceFile miss for ${filePath} — input types will default to { }`);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n\n const checker = program.getTypeChecker();\n const iface = findInterface(sourceFile, 'ApiParams');\n if (!iface) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const dataType = getInterfacePropertyType(iface, 'data', checker);\n if (!dataType) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const expanded = expandTypeDetailed(dataType, checker);\n return { text: expanded.text || DEFAULT, unresolvedSymbols: expanded.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting input type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getOutputTypeFromFile = (filePath: string): string => {\n return getOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getApiStreamPayloadTypeFromFile = (filePath: string): string => {\n return getApiStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getApiStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting API stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ status: string }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting output type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientDataType = (filePath: string): string => {\n return getSyncClientDataTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientDataTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const iface = findInterface(sourceFile, 'SyncParams');\n if (!iface) return { text: DEFAULT, unresolvedSymbols: [] };\n\n // Try clientInput first, then clientData (legacy name)\n const dataType =\n getInterfacePropertyType(iface, 'clientInput', checker)\n ?? getInterfacePropertyType(iface, 'clientData', checker);\n if (!dataType) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const expanded = expandTypeDetailed(dataType, checker);\n return { text: expanded.text || DEFAULT, unresolvedSymbols: expanded.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync clientData type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncServerOutputType = (filePath: string): string => {\n return getSyncServerOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncServerStreamPayloadTypeFromFile = (filePath: string): string => {\n return getSyncServerStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncServerStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync server stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncServerOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ status: string }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync serverOutput type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientOutputType = (filePath: string): string => {\n return getSyncClientOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientStreamPayloadTypeFromFile = (filePath: string): string => {\n return getSyncClientStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync client stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync clientOutput type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { ROOT_DIR, getGeneratedSocketTypesPath } from '@luckystack/core';\n\nlet cachedProgram: ts.Program | null = null;\n\nexport const getServerProgram = (): ts.Program => {\n if (cachedProgram) return cachedProgram;\n\n const tsconfigPath = ts.findConfigFile(ROOT_DIR, ts.sys.fileExists.bind(ts.sys), 'tsconfig.server.json');\n if (!tsconfigPath) throw new Error('[TypeProgram] tsconfig.server.json not found');\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ts.readConfigFile returns { config: any }\n const { config } = ts.readConfigFile(tsconfigPath, ts.sys.readFile.bind(ts.sys));\n const { options, fileNames } = ts.parseJsonConfigFileContent(\n config,\n ts.sys,\n path.dirname(tsconfigPath),\n );\n\n cachedProgram = ts.createProgram(fileNames, options);\n return cachedProgram;\n};\n\nexport const invalidateProgramCache = (): void => {\n cachedProgram = null;\n};\n\nconst DEPTH_LIMIT = 12;\n\nexport interface UnresolvedTypeSymbol {\n name: string;\n sourceFile?: string;\n importPath?: string;\n}\n\nexport interface ExpandedTypeResult {\n text: string;\n unresolvedSymbols: UnresolvedTypeSymbol[];\n}\n\nconst JSON_TYPE_NAMES = new Set([\n 'Json',\n 'JsonValue',\n 'JsonObject',\n 'JsonArray',\n 'InputJsonValue',\n 'InputJsonObject',\n 'InputJsonArray',\n]);\n\n// Generic containers we never recursively expand (their internal shape is irrelevant to API types)\nconst SKIP_EXPANSION = new Set([\n 'Promise', 'Map', 'WeakMap', 'Set', 'WeakSet',\n 'Error', 'Date', 'RegExp', 'Buffer', 'ArrayBuffer', 'ReadonlyArray',\n]);\n\nconst isJsonLikeType = (type: ts.Type, checker: ts.TypeChecker): boolean => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- ts.Type.symbol is typed non-nullable but absent at runtime for primitive types\n const symbolName = type.symbol?.name ?? '';\n const aliasName = type.aliasSymbol?.name ?? '';\n\n if (JSON_TYPE_NAMES.has(symbolName) || JSON_TYPE_NAMES.has(aliasName)) return true;\n\n const rendered = checker.typeToString(type);\n return /(\\bPrisma\\.)?(Input)?Json(Value|Object|Array)\\b/.test(rendered);\n};\n\nconst getLiteralTypeFromExpression = (\n expression: ts.Expression,\n checker: ts.TypeChecker,\n depth: number,\n): string | null => {\n if (ts.isParenthesizedExpression(expression)) {\n return getLiteralTypeFromExpression(expression.expression, checker, depth);\n }\n\n if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {\n return getLiteralTypeFromExpression(expression.expression, checker, depth);\n }\n\n if (expression.kind === ts.SyntaxKind.TrueKeyword) return 'true';\n if (expression.kind === ts.SyntaxKind.FalseKeyword) return 'false';\n if (expression.kind === ts.SyntaxKind.NullKeyword) return 'null';\n\n if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {\n return `'${expression.text.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\'', String.raw`\\'`)}'`;\n }\n\n if (ts.isNumericLiteral(expression)) {\n return expression.text;\n }\n\n if (\n ts.isPrefixUnaryExpression(expression)\n && expression.operator === ts.SyntaxKind.MinusToken\n && ts.isNumericLiteral(expression.operand)\n ) {\n return `-${expression.operand.text}`;\n }\n\n if (ts.isIdentifier(expression)) {\n const identifierType = checker.getTypeAtLocation(expression);\n const isLiteralType = (identifierType.flags & (\n ts.TypeFlags.StringLiteral\n | ts.TypeFlags.NumberLiteral\n | ts.TypeFlags.BooleanLiteral\n | ts.TypeFlags.Null\n | ts.TypeFlags.Undefined\n )) !== 0;\n\n if (isLiteralType || identifierType.isUnion()) {\n const expanded = expandTypeDetailed(identifierType, checker, depth).text;\n if (expanded.includes(\"'\") || /\\btrue\\b|\\bfalse\\b|\\bnull\\b|\\bundefined\\b/.test(expanded)) {\n return expanded;\n }\n }\n }\n\n return null;\n};\n\nconst getLiteralTypeFromPropertySymbol = (\n symbol: ts.Symbol,\n checker: ts.TypeChecker,\n depth: number,\n): string | null => {\n const declarations = symbol.declarations ?? [];\n\n for (const declaration of declarations) {\n if (ts.isPropertyAssignment(declaration)) {\n const literal = getLiteralTypeFromExpression(declaration.initializer, checker, depth);\n if (literal) return literal;\n }\n\n if (ts.isShorthandPropertyAssignment(declaration)) {\n const literal = getLiteralTypeFromExpression(declaration.name, checker, depth);\n if (literal) return literal;\n }\n }\n\n return null;\n};\n\nconst normalizeImportPath = (targetFilePath: string): string => {\n // Derive fromDir from the configured generated socket types path so\n // non-`src` srcDir layouts produce correct relative import paths.\n const fromDir = path.dirname(getGeneratedSocketTypesPath());\n const from = fromDir.replaceAll('\\\\', '/');\n const to = targetFilePath.replaceAll('\\\\', '/');\n\n const normalized = path.posix.relative(from, to).replaceAll('\\\\', '/');\n const withoutExtension = normalized.replace(/(\\.d)?\\.(ts|tsx|js|jsx)$/i, '');\n\n if (withoutExtension.startsWith('.')) return withoutExtension;\n return `./${withoutExtension}`;\n};\n\nconst mergeUnresolvedSymbols = (\n left: UnresolvedTypeSymbol[],\n right: UnresolvedTypeSymbol[],\n): UnresolvedTypeSymbol[] => {\n const merged = [...left];\n const seen = new Set(merged.map((symbol) => `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`));\n for (const symbol of right) {\n const key = `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(symbol);\n }\n return merged;\n};\n\nconst collectTypeSymbolFallback = (type: ts.Type): UnresolvedTypeSymbol[] => {\n const symbol = type.aliasSymbol ?? type.getSymbol();\n if (!symbol) return [];\n\n const name = symbol.getName();\n if (!name || name.startsWith('__')) return [];\n\n const declaration = symbol.declarations?.[0];\n if (!declaration) return [{ name }];\n\n const sourceFile = declaration.getSourceFile().fileName;\n if (!sourceFile || sourceFile.includes('/node_modules/') || sourceFile.includes('\\\\node_modules\\\\')) {\n return [{ name }];\n }\n\n return [{\n name,\n sourceFile,\n importPath: normalizeImportPath(sourceFile),\n }];\n};\n\ninterface ExpandState {\n stackTypeIds: Set<number>;\n}\n\n// Recursively expand a TypeScript type to an inline type string with no named references.\n// The result is self-contained and requires no imports.\nexport const expandTypeDetailed = (\n type: ts.Type,\n checker: ts.TypeChecker,\n depth = 0,\n state?: ExpandState,\n): ExpandedTypeResult => {\n const expandState: ExpandState = state ?? { stackTypeIds: new Set<number>() };\n const typeId = (type as ts.Type & { id?: number }).id;\n\n if (typeId !== undefined) {\n if (expandState.stackTypeIds.has(typeId)) {\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n }\n expandState.stackTypeIds.add(typeId);\n }\n\n try {\n if (depth > DEPTH_LIMIT) {\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n }\n\n if (isJsonLikeType(type, checker)) return { text: 'JsonValue', unresolvedSymbols: [] };\n\n // String literals ('hello') use single quotes for consistency with the codebase\n if (type.isStringLiteral()) return { text: `'${type.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\'', String.raw`\\'`)}'`, unresolvedSymbols: [] };\n\n // Number literals (42, 3.14)\n if (type.isNumberLiteral()) return { text: String(type.value), unresolvedSymbols: [] };\n\n // Primitives and special types (string, number, boolean, true, false, null, undefined, any, unknown, never, void)\n if (\n type.flags\n & (\n ts.TypeFlags.String\n | ts.TypeFlags.Number\n | ts.TypeFlags.Boolean\n | ts.TypeFlags.BooleanLiteral\n | ts.TypeFlags.Undefined\n | ts.TypeFlags.Null\n | ts.TypeFlags.Any\n | ts.TypeFlags.Unknown\n | ts.TypeFlags.Never\n | ts.TypeFlags.Void\n )\n ) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n\n // Union types (A | B | C)\n if (type.isUnion()) {\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const expandedTypes = type.types.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: expandedTypes.join(' | '), unresolvedSymbols };\n }\n\n // Intersection types (A & B)\n if (type.isIntersection()) {\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const expandedTypes = type.types.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: expandedTypes.join(' & '), unresolvedSymbols };\n }\n\n // Object types (interfaces, type literals, generic instances)\n if (type.flags & ts.TypeFlags.Object) {\n const objectType = type as ts.ObjectType;\n\n // Tuple types [A, B, C]\n if (objectType.objectFlags & ts.ObjectFlags.Tuple) {\n const typeArgs = checker.getTypeArguments(objectType as ts.TypeReference);\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const tupleTypes = typeArgs.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: `[${tupleTypes.join(', ')}]`, unresolvedSymbols };\n }\n\n if (objectType.objectFlags & ts.ObjectFlags.Reference) {\n const refType = objectType as ts.TypeReference;\n const targetName = refType.target.symbol.name;\n\n // Array<T> / ReadonlyArray<T> T[]\n if (targetName === 'Array' || targetName === 'ReadonlyArray') {\n const typeArgs = checker.getTypeArguments(refType);\n const firstArg = typeArgs[0];\n if (firstArg) {\n const expanded = expandTypeDetailed(firstArg, checker, depth + 1, expandState);\n const elementType = /\\s[|&]\\s/.test(expanded.text)\n ? `(${expanded.text})`\n : expanded.text;\n return {\n text: `${elementType}[]`,\n unresolvedSymbols: expanded.unresolvedSymbols,\n };\n }\n }\n\n // Known opaque containers return as-is without expanding internals\n if (SKIP_EXPANSION.has(targetName)) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n }\n\n // Known non-generic opaque containers (Date, Error, Buffer, etc.)\n const symbolName = type.symbol.name || (type.aliasSymbol?.name ?? '');\n if (SKIP_EXPANSION.has(symbolName)) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n\n const props = checker.getPropertiesOfType(type);\n const indexInfos = checker.getIndexInfosOfType(type);\n\n if (props.length > 0 || indexInfos.length > 0) {\n const fields: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n for (const prop of props) {\n const propType = checker.getTypeOfSymbol(prop);\n const literalType = getLiteralTypeFromPropertySymbol(prop, checker, depth + 1);\n const isOptional = (prop.flags & ts.SymbolFlags.Optional) !== 0;\n\n if (literalType) {\n fields.push(`${prop.name}${isOptional ? '?' : ''}: ${literalType}`);\n continue;\n }\n\n const expandedProp = expandTypeDetailed(propType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expandedProp.unresolvedSymbols);\n fields.push(`${prop.name}${isOptional ? '?' : ''}: ${expandedProp.text}`);\n }\n\n for (const indexInfo of indexInfos) {\n const keyType = expandTypeDetailed(indexInfo.keyType, checker, depth + 1, expandState);\n const valueType = expandTypeDetailed(indexInfo.type, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, keyType.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, valueType.unresolvedSymbols);\n fields.push(`[key: ${keyType.text}]: ${valueType.text}`);\n }\n\n const indent = ' '.repeat(depth + 1);\n const outerIndent = ' '.repeat(depth);\n return {\n text: `{\\n${indent}${fields.join(`;\\n${indent}`)}\\n${outerIndent}}`,\n unresolvedSymbols,\n };\n }\n\n return { text: '{ }', unresolvedSymbols: [] };\n }\n\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n } finally {\n if (typeId !== undefined) {\n expandState.stackTypeIds.delete(typeId);\n }\n }\n};\n\nexport const expandType = (type: ts.Type, checker: ts.TypeChecker, depth = 0): string => {\n return expandTypeDetailed(type, checker, depth).text;\n};\n\n","import * as ts from 'typescript';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { FileImport, ImportCollectors, parseFileTypeContext, sanitizeTypeAndCollectImports } from './typeContext';\nimport { getGeneratedSocketTypesPath, getServerFunctionDirs } from '@luckystack/core';\nimport { expandType, getServerProgram } from './tsProgram';\n\n// Strips default parameter values from argument lists so the generated interface\n// is a clean type signature without runtime values.\nconst stripDefaultValues = (params: string): string => {\n // Replace default values (= expr) while preserving arrow functions (=>)\n return params.replaceAll(/\\s*=(?!>)[^,)]+/g, '');\n};\n\n// Strips `//` line comments from a raw type fragment while leaving string and\n// template literals (which can legitimately contain `//`, e.g. a URL literal\n// type) intact. Uses the TS scanner so `'https://x'` is never mistaken for a\n// comment — a plain regex strip can't tell the two apart.\nexport const stripLineComments = (value: string): string => {\n const scanner = ts.createScanner(\n ts.ScriptTarget.Latest,\n /* skipTrivia */ false,\n ts.LanguageVariant.Standard,\n value,\n );\n let result = '';\n let token = scanner.scan();\n while (token !== ts.SyntaxKind.EndOfFileToken) {\n // Replace `//` comments with a space so neighbouring tokens don't glue\n // together; keep everything else verbatim, including block comments.\n result += token === ts.SyntaxKind.SingleLineCommentTrivia ? ' ' : scanner.getTokenText();\n token = scanner.scan();\n }\n return result;\n};\n\n// Collapses a multi-line type fragment to a single clean line. Inline `//`\n// comments MUST be stripped first: once the newlines are gone a surviving `//`\n// would comment out the rest of the line and produce malformed generated\n// TypeScript (later caught by validateGeneratedTypeIdentifiers).\nexport const normalizeInlineType = (value: string): string => {\n return stripLineComments(value).replaceAll(/\\s+/g, ' ').trim();\n};\n\nconst simplifyInferredType = (value: string): string => {\n if (/\\bPrismaClient\\b/.test(value)) return 'PrismaClient';\n if (/\\bRedis\\b/.test(value)) return 'Redis';\n return value;\n};\n\n//? Rewrites a relative module specifier so it resolves correctly when emitted\n//? into `src/_sockets/apiTypes.generated.ts`. The specifier is relative to\n//? `sourceFilePath` (the shim file); after this, it becomes relative to the\n//? generated file's directory. Non-relative specifiers (package aliases,\n//? node built-ins) pass through untouched.\n//?\n//? Before this lived, emitted paths were preserved verbatim and only worked\n//? when the shim file shared a depth with the generated file (depth 2 from\n//? repo root). Shims at other depths produced unresolvable type imports.\nconst getGeneratedFileDir = (): string => path.dirname(getGeneratedSocketTypesPath());\n\nconst relativizeModuleSpecifier = (specifier: string, sourceFilePath: string): string => {\n if (!specifier.startsWith('./') && !specifier.startsWith('../')) {\n return specifier;\n }\n\n const absolute = path.resolve(path.dirname(sourceFilePath), specifier);\n const rel = path.relative(getGeneratedFileDir(), absolute);\n const normalized = rel.split(path.sep).join('/');\n return normalized.startsWith('.') ? normalized : `./${normalized}`;\n};\n\nconst findProgramVariableDeclaration = (\n sourceFile: ts.SourceFile,\n exportName: string,\n): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === exportName) {\n return declaration;\n }\n }\n }\n\n return null;\n};\n\nconst findProgramTypeDeclaration = (\n sourceFile: ts.SourceFile,\n typeName: string,\n): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | ts.ClassDeclaration | ts.EnumDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(statement) && statement.name.text === typeName) return statement;\n if (ts.isTypeAliasDeclaration(statement) && statement.name.text === typeName) return statement;\n if (ts.isClassDeclaration(statement) && statement.name?.text === typeName) return statement;\n if (ts.isEnumDeclaration(statement) && statement.name.text === typeName) return statement;\n }\n\n return null;\n};\n\nconst resolveLocalExportedTypes = ({\n type,\n availableExports,\n checker,\n programSource,\n}: {\n type: string;\n availableExports: Set<string>;\n checker: ts.TypeChecker;\n programSource: ts.SourceFile;\n}): string => {\n if (availableExports.size === 0) return type;\n\n let resolved = type;\n\n for (const exportName of availableExports) {\n const hasReference = new RegExp(String.raw`\\b${exportName}\\b`).test(resolved);\n if (!hasReference) continue;\n\n const declaration = findProgramTypeDeclaration(programSource, exportName);\n if (!declaration) continue;\n\n const declarationNode = (\n ts.isClassDeclaration(declaration)\n ? (declaration.name ?? declaration)\n : (ts.isTypeAliasDeclaration(declaration)\n ? declaration.type\n : declaration)\n );\n\n const declarationType = checker.getTypeAtLocation(declarationNode);\n const expanded = normalizeInlineType(expandType(declarationType, checker));\n\n resolved = resolved.replaceAll(new RegExp(String.raw`\\b${exportName}\\b`, 'g'), expanded);\n }\n\n return resolved;\n};\n\nconst findSourceVariableDeclaration = (\n sourceFile: ts.SourceFile,\n exportName: string,\n): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === exportName) {\n return declaration;\n }\n }\n }\n\n return null;\n};\n\nconst inferValueTypeForExport = ({\n exportName,\n declaration,\n rawContent,\n filePath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource,\n}: {\n exportName: string;\n declaration: ts.VariableDeclaration;\n rawContent: string;\n filePath: string;\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n collectors: ImportCollectors;\n checker?: ts.TypeChecker;\n programSource?: ts.SourceFile;\n}): string => {\n const resolvedChecker = checker ?? getServerProgram().getTypeChecker();\n const resolvedSource = programSource ?? getServerProgram().getSourceFile(filePath);\n\n if (declaration.type) {\n const rawType = normalizeInlineType(rawContent.slice(declaration.type.pos, declaration.type.end).trim());\n const localResolvedType = resolvedSource\n ? resolveLocalExportedTypes({\n type: rawType,\n availableExports,\n checker: resolvedChecker,\n programSource: resolvedSource,\n })\n : rawType;\n\n return sanitizeTypeAndCollectImports({\n type: localResolvedType,\n filePath,\n availableExports,\n fileImports,\n collectors,\n });\n }\n\n try {\n if (!resolvedSource) return 'any';\n\n const programDeclaration = findProgramVariableDeclaration(resolvedSource, exportName);\n if (!programDeclaration) return 'any';\n\n const inferred = resolvedChecker.typeToString(resolvedChecker.getTypeAtLocation(programDeclaration.name));\n const simplified = simplifyInferredType(normalizeInlineType(inferred));\n const localResolvedType = resolveLocalExportedTypes({\n type: simplified,\n availableExports,\n checker: resolvedChecker,\n programSource: resolvedSource,\n });\n\n return sanitizeTypeAndCollectImports({\n type: localResolvedType,\n filePath,\n availableExports,\n fileImports,\n collectors,\n });\n } catch {\n return 'any';\n }\n};\n\n// Extracts a function signature string from an AST function-like node.\nconst extractSignatureFromNode = (\n node: ts.FunctionLikeDeclaration,\n rawContent: string,\n filePath: string,\n availableExports: Set<string>,\n fileImports: Map<string, FileImport>,\n collectors: ImportCollectors,\n checker?: ts.TypeChecker,\n programSource?: ts.SourceFile,\n): string => {\n // Collect generic type parameter names to avoid replacing them with 'any'\n const knownGenerics = new Set<string>();\n if (node.typeParameters) {\n for (const typeParam of node.typeParameters) {\n knownGenerics.add(typeParam.name.text);\n }\n }\n\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n\n // Generic clause text (<T, U extends string>)\n const genericsClause = node.typeParameters\n ? `<${normalizeInlineType(rawContent.slice(node.typeParameters.pos, node.typeParameters.end))}>`\n : '';\n\n // Parameter list text with default values removed\n const rawParams = node.parameters\n .map(p => normalizeInlineType(rawContent.slice(p.pos, p.end).trim()))\n .join(', ');\n const cleanParams = normalizeInlineType(stripDefaultValues(`(${rawParams})`));\n const localResolvedParams = (checker && programSource)\n ? resolveLocalExportedTypes({\n type: cleanParams,\n availableExports,\n checker,\n programSource,\n })\n : cleanParams;\n\n const sanitizedParams = sanitizeTypeAndCollectImports({\n type: localResolvedParams,\n filePath,\n availableExports,\n fileImports,\n knownGenerics,\n collectors,\n });\n\n // Return type annotation — emitted into generated type strings. Use\n // `unknown` (not `any`) so consumers must narrow at call sites.\n let returnTypeStr = isAsync ? 'Promise<unknown>' : 'unknown';\n if (node.type) {\n const rawReturnType = normalizeInlineType(rawContent.slice(node.type.pos, node.type.end).trim());\n const localResolvedReturnType = (checker && programSource)\n ? resolveLocalExportedTypes({\n type: rawReturnType,\n availableExports,\n checker,\n programSource,\n })\n : rawReturnType;\n\n returnTypeStr = sanitizeTypeAndCollectImports({\n type: localResolvedReturnType,\n filePath,\n availableExports,\n fileImports,\n knownGenerics,\n collectors,\n });\n if (isAsync && !returnTypeStr.startsWith('Promise')) {\n returnTypeStr = `Promise<${returnTypeStr}>`;\n }\n }\n\n return `${genericsClause}${sanitizedParams} => ${returnTypeStr}`;\n};\n\n// Finds and returns the signature for a named export within a parsed source file.\nconst findSignatureForExport = (\n name: string,\n sourceFile: ts.SourceFile,\n rawContent: string,\n filePath: string,\n availableExports: Set<string>,\n fileImports: Map<string, FileImport>,\n collectors: ImportCollectors,\n checker?: ts.TypeChecker,\n programSource?: ts.SourceFile,\n): string => {\n for (const statement of sourceFile.statements) {\n if (ts.isVariableStatement(statement)) {\n for (const decl of statement.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || decl.name.text !== name || !decl.initializer) continue;\n if (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer)) {\n return extractSignatureFromNode(decl.initializer, rawContent, filePath, availableExports, fileImports, collectors, checker, programSource);\n }\n }\n }\n\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) {\n return extractSignatureFromNode(statement, rawContent, filePath, availableExports, fileImports, collectors, checker, programSource);\n }\n }\n\n return 'any';\n};\n\n//? IR node shapes used by the multi-directory merge. Each root directory\n//? produces an `IRDirNode` tree; multiple trees are merged with conflict\n//? detection before final serialization to a TypeScript interface body.\ninterface IRFileNode {\n kind: 'file';\n exports: Map<string, string>;\n defaultExportName: string | null;\n //? Set when the file contains `export * from '<module>'` (wildcard\n //? re-export). When present and no other exports exist, the file is\n //? emitted as a single `name: typeof import('<module>')` so consumers\n //? get the full module shape on `functions.<name>.<...>`.\n wildcardReExport: string | null;\n sourcePath: string;\n}\n\ninterface IRDirNode {\n kind: 'dir';\n children: Map<string, IRFileNode | IRDirNode>;\n sourcePath: string;\n}\n\nconst parseFunctionFile = (fullPath: string, collectors: ImportCollectors): IRFileNode | null => {\n try {\n const rawContent = fs.readFileSync(fullPath, 'utf8');\n const sourceFile = ts.createSourceFile(fullPath, rawContent, ts.ScriptTarget.Latest, true);\n const { availableExports, fileImports } = parseFileTypeContext(rawContent);\n const program = getServerProgram();\n const checker = program.getTypeChecker();\n const programSource = program.getSourceFile(fullPath);\n const exports = new Map<string, string>();\n let defaultExportName: string | null = null;\n let wildcardReExport: string | null = null;\n\n for (const statement of sourceFile.statements) {\n const hasExport = (statement as ts.HasModifiers).modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n\n if (ts.isVariableStatement(statement) && hasExport) {\n for (const decl of statement.declarationList.declarations) {\n if (ts.isIdentifier(decl.name)) {\n const exportName = decl.name.text;\n\n if (decl.initializer && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))) {\n exports.set(exportName, findSignatureForExport(exportName, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined));\n continue;\n }\n\n exports.set(exportName, inferValueTypeForExport({\n exportName,\n declaration: decl,\n rawContent,\n filePath: fullPath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource: programSource ?? undefined,\n }));\n }\n }\n }\n\n if (ts.isFunctionDeclaration(statement) && hasExport && statement.name) {\n exports.set(statement.name.text, findSignatureForExport(statement.name.text, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined));\n }\n\n // export { a, b as c } [from 'module']\n if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n // `export { x } from 'module'` — extract the source module so we can\n // emit `typeof import('module')['x']` and let TypeScript resolve the\n // real type at compile time (instead of falling back to `any`).\n const moduleSpecifier =\n statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)\n ? statement.moduleSpecifier.text\n : null;\n\n for (const specifier of statement.exportClause.elements) {\n const exportName = specifier.name.text;\n const originalName = specifier.propertyName ? specifier.propertyName.text : exportName;\n\n if (moduleSpecifier) {\n // Re-export from another module. `typeof import(...)` resolves\n // through package aliases (`@luckystack/*`) and relative paths.\n // Relative paths are rewritten to be relative to the generated\n // file location, so shims at any depth produce working imports.\n // Package aliases (starting with `@` or a word char but no\n // `.` / `/`) pass through. Wildcard re-exports (`export * from\n // ...`) are not handled here and fall through.\n const resolvedSpecifier = relativizeModuleSpecifier(moduleSpecifier, fullPath);\n exports.set(exportName, `typeof import('${resolvedSpecifier}')['${originalName}']`);\n continue;\n }\n\n const signature = findSignatureForExport(originalName, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined);\n if (signature !== 'any') {\n exports.set(exportName, signature);\n continue;\n }\n\n const exportDeclaration = findSourceVariableDeclaration(sourceFile, originalName);\n if (exportDeclaration && ts.isIdentifier(exportDeclaration.name)) {\n exports.set(exportName, inferValueTypeForExport({\n exportName: originalName,\n declaration: exportDeclaration,\n rawContent,\n filePath: fullPath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource: programSource ?? undefined,\n }));\n continue;\n }\n\n exports.set(exportName, 'any');\n }\n }\n\n // export default someIdentifier\n if (ts.isExportAssignment(statement) && !statement.isExportEquals && ts.isIdentifier(statement.expression)) {\n defaultExportName = statement.expression.text;\n }\n\n // export * from 'module' — wildcard re-export. Stash the resolved\n // module specifier; serialization decides whether to emit it.\n if (\n ts.isExportDeclaration(statement)\n && !statement.exportClause\n && statement.moduleSpecifier\n && ts.isStringLiteral(statement.moduleSpecifier)\n ) {\n wildcardReExport = relativizeModuleSpecifier(statement.moduleSpecifier.text, fullPath);\n }\n }\n\n return { kind: 'file', exports, defaultExportName, wildcardReExport, sourcePath: fullPath };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error parsing functions file ${fullPath}:`, error);\n return null;\n }\n};\n\nconst walkDirToIR = (dir: string, collectors: ImportCollectors): IRDirNode | null => {\n if (!fs.existsSync(dir)) return null;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const children = new Map<string, IRFileNode | IRDirNode>();\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n const subDir = walkDirToIR(fullPath, collectors);\n if (subDir && subDir.children.size > 0) {\n children.set(entry.name, subDir);\n }\n continue;\n }\n\n if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;\n\n const fileName = entry.name.replace('.ts', '');\n const parsed = parseFunctionFile(fullPath, collectors);\n if (parsed && (parsed.exports.size > 0 || parsed.defaultExportName !== null || parsed.wildcardReExport !== null)) {\n children.set(fileName, parsed);\n }\n }\n\n return { kind: 'dir', children, sourcePath: dir };\n};\n\nconst formatConflict = (keyPath: string[], a: IRFileNode | IRDirNode, b: IRFileNode | IRDirNode): string => {\n const dottedKey = keyPath.join('.');\n return (\n `[function-injection] Conflict at \\`functions.${dottedKey}\\`: ` +\n `defined in both \\`${a.sourcePath}\\` and \\`${b.sourcePath}\\`. ` +\n `Delete one — \\`shared/\\` is the canonical location for framework re-exports.`\n );\n};\n\n//? Merge `source` INTO `target` in place, throwing on conflicts. A \"conflict\"\n//? is one of:\n//? - same key path mapped to a file in both roots\n//? - same key path mapped to a file in one root and a directory in another\n//? Two directories with the same name merge recursively without warning so\n//? that `functions/admin/users.ts` + `shared/admin/roles.ts` produce\n//? `functions.admin.{users, roles}` cleanly.\nconst mergeIR = (target: IRDirNode, source: IRDirNode, prefix: string[] = []): void => {\n for (const [name, sourceChild] of source.children) {\n const targetChild = target.children.get(name);\n if (!targetChild) {\n target.children.set(name, sourceChild);\n continue;\n }\n const keyPath = [...prefix, name];\n if (targetChild.kind !== sourceChild.kind) {\n throw new Error(formatConflict(keyPath, targetChild, sourceChild));\n }\n if (targetChild.kind === 'file' || sourceChild.kind === 'file') {\n throw new Error(formatConflict(keyPath, targetChild, sourceChild));\n }\n mergeIR(targetChild, sourceChild, keyPath);\n }\n};\n\nconst serializeIRDir = (dir: IRDirNode, indent: string): string => {\n let output = '';\n for (const [name, child] of dir.children) {\n if (child.kind === 'dir') {\n const subOutput = serializeIRDir(child, `${indent} `);\n if (subOutput.trim()) {\n output += `${indent}${name}: {\\n${subOutput}${indent}};\\n`;\n }\n continue;\n }\n\n const exportsCopy = new Map(child.exports);\n const defaultExportName = child.defaultExportName;\n const defaultSig = defaultExportName ? exportsCopy.get(defaultExportName) : undefined;\n if (defaultSig && defaultExportName) exportsCopy.delete(defaultExportName);\n\n //? Wildcard re-export (`export * from '<module>'`) — emit the file as a\n //? single `name: typeof import('<module>')` so the full module surface\n //? becomes typed under `functions.<name>.<exportFromSource>`. When the\n //? file ALSO has named/default exports, the wildcard is dropped (this\n //? combined form is rare; the named exports take precedence to avoid an\n //? awkward intersection type).\n if (child.wildcardReExport && exportsCopy.size === 0 && !defaultSig) {\n output += `${indent}${name}: typeof import('${child.wildcardReExport}');\\n`;\n continue;\n }\n\n //? Default-only re-exports (`export { default } from '...'`) end up as a\n //? single 'default' key with no `export default <identifier>` statement.\n //? Alias it to the filename so consumers can call `functions.<name>.<name>()`\n //? instead of the awkward `functions.<name>.default()`.\n if (!defaultSig && exportsCopy.size === 1 && exportsCopy.has('default')) {\n const reExportSig = exportsCopy.get('default');\n if (reExportSig) {\n exportsCopy.delete('default');\n exportsCopy.set(name, reExportSig);\n }\n }\n\n let fileOutput = '';\n for (const [exportName, sig] of exportsCopy) {\n fileOutput += `${indent} ${exportName}: ${sig};\\n`;\n }\n if (defaultSig && !fileOutput.trim()) {\n fileOutput += `${indent} ${name}: ${defaultSig};\\n`;\n }\n if (fileOutput) {\n output += `${indent}${name}: {\\n${fileOutput}${indent}};\\n`;\n }\n }\n return output;\n};\n\nexport const generateServerFunctions = (collectors: ImportCollectors): string => {\n const dirs = getServerFunctionDirs();\n if (dirs.length === 0) return '';\n\n const merged: IRDirNode = { kind: 'dir', children: new Map(), sourcePath: '<merged>' };\n for (const dir of dirs) {\n const ir = walkDirToIR(dir, collectors);\n if (!ir) continue;\n mergeIR(merged, ir);\n }\n\n return serializeIRDir(merged, '\\t');\n};\n\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { getGeneratedSocketTypesPath } from '@luckystack/core';\n\nimport { getOrInit } from '../internal/mapUtils';\n\nexport interface FileImport {\n source: string;\n isDefault: boolean;\n originalName?: string;\n}\n\nexport interface ImportCollectors {\n namedImports: Map<string, Set<string>>;\n defaultImports: Map<string, string>;\n}\n\nconst toGeneratedImportPath = (source: string, filePath: string): string => {\n if (!source.startsWith('.')) return source;\n\n const outputDir = path.dirname(getGeneratedSocketTypesPath());\n const absoluteSource = path.resolve(path.dirname(filePath), source);\n let relPath = path.relative(outputDir, absoluteSource).replaceAll('\\\\', '/');\n relPath = relPath.replace(/\\.tsx?$/, '');\n if (!relPath.startsWith('.')) relPath = `./${relPath}`;\n return relPath;\n};\n\n// Parses a source file's AST to collect exported type names and import bindings.\n// Uses ts.createSourceFile (no TypeChecker needed) for fast structural discovery.\nexport const parseFileTypeContext = (content: string): {\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n} => {\n const availableExports = new Set<string>();\n const fileImports = new Map<string, FileImport>();\n\n const sourceFile = ts.createSourceFile(\n '__temp__.ts',\n content,\n ts.ScriptTarget.Latest,\n true,\n );\n\n for (const statement of sourceFile.statements) {\n // Collect exported type/interface/class/enum declarations\n if (\n ts.isInterfaceDeclaration(statement)\n || ts.isTypeAliasDeclaration(statement)\n || ts.isClassDeclaration(statement)\n || ts.isEnumDeclaration(statement)\n ) {\n const hasExport = statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n if (hasExport && statement.name) {\n availableExports.add(statement.name.text);\n }\n continue;\n }\n\n if (!ts.isImportDeclaration(statement)) continue;\n\n const moduleSpecifier = statement.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n const source = moduleSpecifier.text;\n\n const importClause = statement.importClause;\n if (!importClause) continue;\n\n // Default import: import Foo from './foo'\n if (importClause.name) {\n fileImports.set(importClause.name.text, { source, isDefault: true });\n }\n\n const namedBindings = importClause.namedBindings;\n if (!namedBindings) continue;\n\n // Namespace import: import * as Foo from './foo'\n if (ts.isNamespaceImport(namedBindings)) {\n fileImports.set(namedBindings.name.text, { source, isDefault: true });\n continue;\n }\n\n // Named imports: import { Foo, Bar as Baz } from './foo'\n if (ts.isNamedImports(namedBindings)) {\n for (const specifier of namedBindings.elements) {\n const localName = specifier.name.text;\n const originalName = specifier.propertyName?.text ?? localName;\n fileImports.set(localName, { source, isDefault: false, originalName });\n }\n }\n }\n\n return { availableExports, fileImports };\n};\n\nexport const sanitizeTypeAndCollectImports = ({\n type,\n filePath,\n availableExports,\n fileImports,\n collectors,\n knownGenerics = new Set<string>(),\n}: {\n type: string;\n filePath: string;\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n collectors: ImportCollectors;\n knownGenerics?: Set<string>;\n}): string => {\n const { namedImports, defaultImports } = collectors;\n\n return type.replaceAll(/\\b([A-Z][a-zA-Z0-9_]*)(<[^>]+>)?(\\[\\])?\\b/g, (match: string, typeName: string, _generics: string | undefined, isArray: string | undefined) => {\n const builtins = ['Promise', 'Date', 'Function', 'Array', 'Record', 'Partial', 'Pick', 'Omit', 'Error', 'Map', 'Set', 'Buffer', 'Uint8Array', 'Object'];\n const existingImports = ['SessionLayout'];\n\n if (builtins.includes(typeName) || existingImports.includes(typeName) || knownGenerics.has(typeName)) {\n return match;\n }\n\n const importConfig = fileImports.get(typeName);\n if (importConfig) {\n\n // If the import is from a package (not relative and not an internal alias), we can keep it\n // Internal aliases often start with 'src/' or 'shared/' or '@/'\n const isInternal = importConfig.source.startsWith('.') ||\n importConfig.source.startsWith('/') ||\n importConfig.source.startsWith('src/') ||\n importConfig.source.startsWith('shared/') ||\n importConfig.source.startsWith('server/');\n\n if (!isInternal) {\n const importPath = toGeneratedImportPath(importConfig.source, filePath);\n\n if (importConfig.isDefault) {\n if (!defaultImports.has(importPath) || defaultImports.get(importPath) === typeName) {\n defaultImports.set(importPath, typeName);\n return match;\n }\n } else {\n getOrInit(namedImports, importPath, () => new Set<string>()).add(importConfig.originalName ?? typeName);\n return match;\n }\n }\n }\n\n if (availableExports.has(typeName)) {\n // If it's exported locally in the same file, we used to add a relative import here,\n // but the user wants to flatten out our own types, so we don't import them anymore.\n // (The tsProgram.ts expandType handles API inputs/outputs deeply, \n // but for functionsMeta.ts we just map them to `any` or leave them if they are built-ins).\n // If we *really* wanted to deeply flatten, we'd need to invoke the type checker. \n // For now, mapping non-npm imports to `any` (the fallback below) handles the prompt.\n }\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- `isArray` is `'[]' | false`; false must coerce to empty string\n return `any${isArray || ''}`;\n });\n};\n\n","import { findAllApiFiles, findAllSyncClientFiles, findAllSyncServerFiles } from './typeMap/discovery';\nimport { extractApiName, extractApiVersion, extractPagePath, extractSyncName, extractSyncPagePath, extractSyncVersion } from './typeMap/routeMeta';\nimport { extractAuth, extractDocsMeta, extractHttpMethod, extractRateLimit } from './typeMap/apiMeta';\nimport { buildTypeMapArtifacts, writeTypeMapArtifacts, ApiTypeEntry, SyncTypeEntry } from './typeMap/emitterArtifacts';\nimport {\n getApiStreamPayloadTypeDetailsFromFile,\n getInputTypeDetailsFromFile,\n getOutputTypeDetailsFromFile,\n getSyncClientDataTypeDetailsFromFile,\n getSyncClientOutputTypeDetailsFromFile,\n getSyncClientStreamPayloadTypeDetailsFromFile,\n getSyncServerOutputTypeDetailsFromFile,\n getSyncServerStreamPayloadTypeDetailsFromFile,\n} from './typeMap/extractors';\nimport { generateServerFunctions } from './typeMap/functionsMeta';\nimport { invalidateProgramCache } from './typeMap/tsProgram';\nimport { getSrcDir } from '@luckystack/core';\nimport { assertNoDuplicateNormalizedRouteKeys, assertNoDuplicatePageRoutes, assertValidRouteNaming } from './routeNamingValidation';\nimport { getOrInit } from './internal/mapUtils';\n\ninterface GenerateTypeMapOptions {\n quiet?: boolean;\n}\n\n//? Per-page map of versioned API entries, keyed by `pagePath -> `${name}@${version}``.\ntype TypesByPage = Map<string, Map<string, ApiTypeEntry>>;\n//? Per-page map of versioned sync entries, keyed by `pagePath -> `${name}@${version}``.\ntype SyncTypesByPage = Map<string, Map<string, SyncTypeEntry>>;\n\n//? Shared mutable collectors threaded through both collection passes. Holding\n//? the import maps + unresolved-alias set by reference (rather than returning +\n//? merging) preserves the EXACT population order the inline loops had: API\n//? symbols are registered before sync symbols, in file-discovery order.\ninterface TypeMapCollectors {\n namedImports: Map<string, Set<string>>;\n unresolvedTypeAliases: Set<string>;\n quiet: boolean;\n}\n\n//? Walks every discovered `_api/` file, runs the TypeChecker-backed extractors,\n//? registers unresolved import symbols into the shared collectors, and returns\n//? the per-page API type map. Side-effects (console logging, `namedImports` /\n//? `unresolvedTypeAliases` mutation) occur in the same order as the original\n//? inline loop — this is a pure code-motion extraction, not a behavior change.\nconst collectApiTypes = (apiFiles: string[], collectors: TypeMapCollectors): TypesByPage => {\n const { namedImports, unresolvedTypeAliases, quiet } = collectors;\n const typesByPage: TypesByPage = new Map();\n\n if (!quiet) {\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(`[TypeMapGenerator] Found ${apiFiles.length} API files`, 'cyan');\n }\n\n for (const filePath of apiFiles) {\n const pagePath = extractPagePath(filePath);\n const apiName = extractApiName(filePath);\n const apiVersion = extractApiVersion(filePath);\n\n if (!pagePath || !apiName) continue;\n\n // TypeChecker-based extractors return fully-expanded inline types.\n // No import collection or sanitization is needed for API types.\n const inputTypeResult = getInputTypeDetailsFromFile(filePath);\n const outputTypeResult = getOutputTypeDetailsFromFile(filePath);\n const streamTypeResult = getApiStreamPayloadTypeDetailsFromFile(filePath);\n const inputType = inputTypeResult.text;\n const outputType = outputTypeResult.text;\n const streamType = streamTypeResult.text;\n const httpMethod = extractHttpMethod(filePath, apiName);\n const rateLimit = extractRateLimit(filePath);\n const auth = extractAuth(filePath);\n const meta = extractDocsMeta(filePath);\n\n for (const symbol of [...inputTypeResult.unresolvedSymbols, ...outputTypeResult.unresolvedSymbols, ...streamTypeResult.unresolvedSymbols]) {\n if (!symbol.importPath) {\n unresolvedTypeAliases.add(symbol.name);\n console.error(`[TypeMapGenerator] Unresolved API type (${pagePath}/${apiName}/${apiVersion}): ${symbol.name}`);\n continue;\n }\n getOrInit(namedImports, symbol.importPath, () => new Set<string>()).add(symbol.name);\n }\n\n if (!quiet) {\n console.log(`[TypeMapGenerator] API: ${pagePath}/${apiName}/${apiVersion} (${httpMethod}${rateLimit === undefined ? '' : `, rateLimit: ${rateLimit}`})`);\n }\n\n getOrInit(typesByPage, pagePath, () => new Map()).set(`${apiName}@${apiVersion}`, { input: inputType, output: outputType, stream: streamType, method: httpMethod, rateLimit, auth, version: apiVersion, ...(meta ? { meta } : {}) });\n }\n\n return typesByPage;\n};\n\n//? Pairs `_sync/` server + client files into one entry per route, runs the\n//? TypeChecker-backed extractors for each present side, registers unresolved\n//? import symbols into the shared collectors, and returns the per-page sync\n//? type map. The `allSyncs` Map keeps insertion order (servers first, then\n//? clients) so the downstream iteration + logging order is identical to the\n//? original inline loop. Pure code-motion extraction — no behavior change.\nconst collectSyncTypes = (\n syncServerFiles: string[],\n syncClientFiles: string[],\n collectors: TypeMapCollectors,\n): SyncTypesByPage => {\n const { namedImports, unresolvedTypeAliases, quiet } = collectors;\n const syncTypesByPage: SyncTypesByPage = new Map();\n\n if (!quiet) {\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(`[TypeMapGenerator] Found ${syncServerFiles.length} Sync server files, ${syncClientFiles.length} Sync client files`, 'cyan');\n }\n\n const allSyncs = new Map<string, {\n pagePath: string;\n syncName: string;\n serverFile?: string;\n clientFile?: string;\n }>();\n\n for (const serverFile of syncServerFiles) {\n const pagePath = extractSyncPagePath(serverFile);\n const syncName = extractSyncName(serverFile);\n const syncVersion = extractSyncVersion(serverFile);\n if (!pagePath || !syncName) continue;\n\n const key = `${pagePath}/${syncName}/${syncVersion}`;\n const existing = allSyncs.get(key) ?? { pagePath, syncName };\n existing.serverFile = serverFile;\n allSyncs.set(key, existing);\n }\n\n for (const clientFile of syncClientFiles) {\n const pagePath = extractSyncPagePath(clientFile);\n const syncName = extractSyncName(clientFile);\n const syncVersion = extractSyncVersion(clientFile);\n if (!pagePath || !syncName) continue;\n\n const key = `${pagePath}/${syncName}/${syncVersion}`;\n const existing = allSyncs.get(key) ?? { pagePath, syncName };\n existing.clientFile = clientFile;\n allSyncs.set(key, existing);\n }\n\n for (const [, { pagePath, syncName, serverFile, clientFile }] of allSyncs) {\n const syncVersion = extractSyncVersion(serverFile ?? clientFile ?? '');\n\n const clientInputTypeResult = serverFile\n ? getSyncClientDataTypeDetailsFromFile(serverFile)\n : (clientFile\n ? getSyncClientDataTypeDetailsFromFile(clientFile)\n : { text: '{ }', unresolvedSymbols: [] });\n\n const serverOutputTypeResult = serverFile\n ? getSyncServerOutputTypeDetailsFromFile(serverFile)\n : { text: '{ }', unresolvedSymbols: [] };\n const clientOutputTypeResult = clientFile\n ? getSyncClientOutputTypeDetailsFromFile(clientFile)\n : { text: '{ }', unresolvedSymbols: [] };\n const serverStreamTypeResult = serverFile\n ? getSyncServerStreamPayloadTypeDetailsFromFile(serverFile)\n : { text: 'never', unresolvedSymbols: [] };\n const clientStreamTypeResult = clientFile\n ? getSyncClientStreamPayloadTypeDetailsFromFile(clientFile)\n : { text: 'never', unresolvedSymbols: [] };\n\n const clientInputType = clientInputTypeResult.text;\n const serverOutputType = serverOutputTypeResult.text;\n const clientOutputType = clientOutputTypeResult.text;\n const serverStreamType = serverStreamTypeResult.text;\n const clientStreamType = clientStreamTypeResult.text;\n\n const allSyncUnresolvedSymbols = [\n ...clientInputTypeResult.unresolvedSymbols,\n ...serverOutputTypeResult.unresolvedSymbols,\n ...clientOutputTypeResult.unresolvedSymbols,\n ...serverStreamTypeResult.unresolvedSymbols,\n ...clientStreamTypeResult.unresolvedSymbols,\n ];\n\n for (const symbol of allSyncUnresolvedSymbols) {\n if (!symbol.importPath) {\n unresolvedTypeAliases.add(symbol.name);\n console.error(`[TypeMapGenerator] Unresolved Sync type (${pagePath}/${syncName}/${syncVersion}): ${symbol.name}`);\n continue;\n }\n getOrInit(namedImports, symbol.importPath, () => new Set<string>()).add(symbol.name);\n }\n\n if (!quiet) {\n console.log(`[TypeMapGenerator] Sync: ${pagePath}/${syncName}/${syncVersion} (server: ${!!serverFile}, client: ${!!clientFile})`);\n }\n\n //? Prefer @docs metadata from the server file; fall back to client file.\n //? Server is the canonical \"owns the route\" file when both exist.\n const syncMeta = serverFile ? extractDocsMeta(serverFile) : (clientFile ? extractDocsMeta(clientFile) : undefined);\n\n getOrInit(syncTypesByPage, pagePath, () => new Map()).set(`${syncName}@${syncVersion}`, {\n clientInput: clientInputType,\n serverOutput: serverOutputType,\n clientOutput: clientOutputType,\n serverStream: serverStreamType,\n clientStream: clientStreamType,\n version: syncVersion,\n ...(syncMeta ? { meta: syncMeta } : {}),\n });\n }\n\n return syncTypesByPage;\n};\n\nexport const generateTypeMapFile = (options: GenerateTypeMapOptions = {}): void => {\n const { quiet = false } = options;\n assertValidRouteNaming({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n assertNoDuplicateNormalizedRouteKeys({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n //? Hard-fail on duplicate page routes at build time. Dev startup only\n //? warns (so a misplaced file doesn't block the entire dev server);\n //? builds throw so collisions can never ship to production.\n assertNoDuplicatePageRoutes({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n\n // Rebuild the TypeScript Program on each generation to pick up file changes.\n invalidateProgramCache();\n\n //? Local per-call maps — previously module-level mutable state, which\n //? meant a second call (e.g. from a test or a race) would share and corrupt\n //? state across calls. Moved here so each invocation gets a fresh set.\n const namedImports = new Map<string, Set<string>>();\n const defaultImports = new Map<string, string>();\n\n const unresolvedTypeAliases = new Set<string>();\n const collectors: TypeMapCollectors = { namedImports, unresolvedTypeAliases, quiet };\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Collect API Types\n // ═══════════════════════════════════════════════════════════════════════════\n const apiFiles = findAllApiFiles(getSrcDir());\n const typesByPage = collectApiTypes(apiFiles, collectors);\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Collect Sync Types\n // ═══════════════════════════════════════════════════════════════════════════\n const syncServerFiles = findAllSyncServerFiles(getSrcDir());\n const syncClientFiles = findAllSyncClientFiles(getSrcDir());\n const syncTypesByPage = collectSyncTypes(syncServerFiles, syncClientFiles, collectors);\n\n const functionsInterface = generateServerFunctions({ namedImports, defaultImports });\n\n if (unresolvedTypeAliases.size > 0) {\n const unresolvedList = [...unresolvedTypeAliases].toSorted().join(', ');\n throw new Error(`[TypeMapGenerator] Aborting generation because unresolved type symbols were found: ${unresolvedList}`);\n }\n\n const { content, docsData, schemasContent, diagnosticsData } = buildTypeMapArtifacts({\n typesByPage,\n syncTypesByPage,\n namedImports,\n defaultImports,\n functionsInterface,\n });\n\n writeTypeMapArtifacts({ content, docsData, schemasContent, diagnosticsData });\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR, validatePagePath } from '@luckystack/core';\nimport {\n isVersionedApiFileName,\n isVersionedSyncFileName,\n ROUTE_NAMING_RULES,\n} from './routeConventions';\nimport {\n apiMarkerSegment,\n syncMarkerSegment,\n getRoutingRules,\n isRouteTestFile,\n} from './routingRules';\nimport { getOrInit } from './internal/mapUtils';\n\nexport interface RouteNamingIssue {\n kind: 'api' | 'sync';\n filePath: string;\n reason: string;\n expected: string;\n}\n\nexport interface DuplicateRouteKeyIssue {\n kind: 'api' | 'sync';\n routeKey: string;\n filePaths: string[];\n}\n\nconst normalizePath = (value: string): string => {\n return value.replaceAll('\\\\', '/');\n};\n\nconst toRel = (absolute: string): string =>\n path.relative(ROOT_DIR, absolute).replaceAll('\\\\', '/');\n\nconst walkRouteFiles = (dir: string, results: string[] = []): string[] => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n const { ignore } = getRoutingRules();\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const normalizedFullPath = normalizePath(fullPath);\n\n if (ignore(toRel(fullPath))) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') {\n continue;\n }\n\n walkRouteFiles(fullPath, results);\n continue;\n }\n\n if (!entry.isFile() || !entry.name.endsWith('.ts')) {\n continue;\n }\n\n if (isRouteTestFile(entry.name)) {\n continue;\n }\n\n if (normalizedFullPath.includes(apiSeg) || normalizedFullPath.includes(syncSeg)) {\n results.push(fullPath);\n }\n }\n\n return results;\n};\n\nconst getFileRouteToken = ({\n normalizedFilePath,\n marker,\n}: {\n normalizedFilePath: string;\n marker: string;\n}): string => {\n const markerIndex = normalizedFilePath.indexOf(marker);\n if (markerIndex === -1) {\n return '';\n }\n\n const tokenStart = markerIndex + marker.length;\n return normalizedFilePath.slice(tokenStart, normalizedFilePath.length - '.ts'.length);\n};\n\nconst validateRouteFilePath = (filePath: string): RouteNamingIssue[] => {\n const issues: RouteNamingIssue[] = [];\n const normalizedFilePath = normalizePath(path.resolve(filePath));\n const fileName = path.basename(filePath);\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n\n if (normalizedFilePath.includes(apiSeg)) {\n const apiRouteToken = getFileRouteToken({ normalizedFilePath, marker: apiSeg });\n if (apiRouteToken.includes('/')) {\n issues.push({\n kind: 'api',\n filePath: normalizedFilePath,\n reason: 'API route token cannot contain nested path segments (\"/\").',\n expected: ROUTE_NAMING_RULES.api,\n });\n }\n\n if (!isVersionedApiFileName(fileName)) {\n issues.push({\n kind: 'api',\n filePath: normalizedFilePath,\n reason: 'API filename does not match versioned naming.',\n expected: ROUTE_NAMING_RULES.api,\n });\n }\n }\n\n if (normalizedFilePath.includes(syncSeg)) {\n const syncRouteToken = getFileRouteToken({ normalizedFilePath, marker: syncSeg });\n if (syncRouteToken.includes('/')) {\n issues.push({\n kind: 'sync',\n filePath: normalizedFilePath,\n reason: 'Sync route token cannot contain nested path segments (\"/\").',\n expected: `${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n });\n }\n\n if (!isVersionedSyncFileName(fileName)) {\n issues.push({\n kind: 'sync',\n filePath: normalizedFilePath,\n reason: 'Sync filename does not match versioned naming.',\n expected: `${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n });\n }\n }\n\n return issues;\n};\n\nconst resolveApiRouteKey = ({\n srcDir,\n filePath,\n}: {\n srcDir: string;\n filePath: string;\n}): string | null => {\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(srcDir, filePath));\n const segments = relativePath.split('/');\n const apiIndex = segments.indexOf(rules.apiMarker);\n if (apiIndex === -1 || apiIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, apiIndex).join('/');\n const apiFilePath = segments.slice(apiIndex + 1).join('/');\n const rawApiName = apiFilePath.replace(/\\.ts$/, '');\n const versionMatch = rawApiName.match(rules.apiVersionRegex);\n if (!versionMatch) {\n return null;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(rules.apiVersionRegex, '');\n const mappedPageLocation = pageLocation || 'system';\n return `api/${mappedPageLocation}/${apiName}/${version}`;\n};\n\nconst resolveSyncRouteKey = ({\n srcDir,\n filePath,\n}: {\n srcDir: string;\n filePath: string;\n}): string | null => {\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(srcDir, filePath));\n const segments = relativePath.split('/');\n const syncIndex = segments.indexOf(rules.syncMarker);\n if (syncIndex === -1 || syncIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, syncIndex).join('/');\n const syncFilePath = segments.slice(syncIndex + 1).join('/');\n const rawSyncName = syncFilePath.replace(/\\.ts$/, '');\n const syncMatch = rawSyncName.match(rules.syncVersionRegex);\n if (!syncMatch) {\n return null;\n }\n\n const kind = syncMatch[1];\n const version = `v${syncMatch[2]}`;\n const syncName = rawSyncName.replace(rules.syncVersionRegex, '');\n const routeBaseKey = pageLocation\n ? `sync/${pageLocation}/${syncName}/${version}`\n : `sync/${syncName}/${version}`;\n\n return `${routeBaseKey}_${kind}`;\n};\n\nexport const collectInvalidRouteNamingIssues = (srcDir: string): RouteNamingIssue[] => {\n const allRouteFiles = walkRouteFiles(srcDir);\n const issues: RouteNamingIssue[] = [];\n\n for (const filePath of allRouteFiles) {\n issues.push(...validateRouteFilePath(filePath));\n }\n\n return issues.toSorted((a, b) => a.filePath.localeCompare(b.filePath));\n};\n\nexport const collectDuplicateNormalizedRouteKeyIssues = (srcDir: string): DuplicateRouteKeyIssue[] => {\n const allRouteFiles = walkRouteFiles(srcDir);\n const routeKeyToFilePaths = new Map<string, string[]>();\n const routeKeyKinds = new Map<string, 'api' | 'sync'>();\n\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n for (const filePath of allRouteFiles) {\n const normalizedFilePath = normalizePath(path.resolve(filePath));\n\n if (normalizedFilePath.includes(apiSeg)) {\n const routeKey = resolveApiRouteKey({ srcDir, filePath });\n if (!routeKey) {\n continue;\n }\n\n getOrInit(routeKeyToFilePaths, routeKey, () => []).push(normalizedFilePath);\n routeKeyKinds.set(routeKey, 'api');\n continue;\n }\n\n if (normalizedFilePath.includes(syncSeg)) {\n const routeKey = resolveSyncRouteKey({ srcDir, filePath });\n if (!routeKey) {\n continue;\n }\n\n getOrInit(routeKeyToFilePaths, routeKey, () => []).push(normalizedFilePath);\n routeKeyKinds.set(routeKey, 'sync');\n }\n }\n\n const issues: DuplicateRouteKeyIssue[] = [];\n for (const [routeKey, filePaths] of routeKeyToFilePaths.entries()) {\n if (filePaths.length < 2) {\n continue;\n }\n\n issues.push({\n kind: routeKeyKinds.get(routeKey) ?? 'api',\n routeKey,\n filePaths: filePaths.toSorted((a, b) => a.localeCompare(b)),\n });\n }\n\n return issues.toSorted((a, b) => a.routeKey.localeCompare(b.routeKey));\n};\n\nexport const formatRouteNamingIssues = ({\n issues,\n context,\n}: {\n issues: RouteNamingIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} invalid API/sync route file${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n return `${index + 1}. [${issue.kind.toUpperCase()}] ${issue.filePath}\\n reason: ${issue.reason}\\n expected: ${issue.expected}`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const formatDuplicateRouteKeyIssues = ({\n issues,\n context,\n}: {\n issues: DuplicateRouteKeyIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} duplicate normalized route key${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n const fileList = issue.filePaths.map((filePath) => ` - ${filePath}`).join('\\n');\n return `${index + 1}. [${issue.kind.toUpperCase()}] ${issue.routeKey}\\n files:\\n${fileList}`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const assertValidRouteNaming = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectInvalidRouteNamingIssues(srcDir);\n if (issues.length === 0) {\n return;\n }\n\n throw new Error(formatRouteNamingIssues({ issues, context }));\n};\n\nexport const assertNoDuplicateNormalizedRouteKeys = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectDuplicateNormalizedRouteKeyIssues(srcDir);\n if (issues.length === 0) {\n return;\n }\n\n throw new Error(formatDuplicateRouteKeyIssues({ issues, context }));\n};\n\n//? --- Duplicate-page-route detection ----------------------------------------\n//? `validatePagePath` in @luckystack/core normalizes a `page.tsx` path into a\n//? URL route by stripping invisible-parent folders (`_<name>`). Two files in\n//? DIFFERENT folder trees can therefore compute the SAME route — e.g.\n//? `src/_test/admin/page.tsx` AND `src/admin/page.tsx` both yield `/admin`.\n//? React Router silently keeps the first registration; the second page is\n//? lost without an error. This validator catches the collision at startup\n//? + build time.\n\nexport interface DuplicatePageRouteIssue {\n /** Computed route after invisible-parent stripping (e.g. `/admin`). */\n route: string;\n /** All page.tsx files that resolve to this same route. */\n filePaths: string[];\n}\n\nconst walkPageFiles = (dir: string, results: string[] = []): string[] => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return results;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;\n walkPageFiles(fullPath, results);\n continue;\n }\n if (!entry.isFile()) continue;\n if (entry.name === 'page.tsx' || entry.name === 'page.jsx') {\n results.push(fullPath);\n }\n }\n return results;\n};\n\nexport const collectDuplicatePageRoutes = (srcDir: string): DuplicatePageRouteIssue[] => {\n //? `validatePagePath` is a pure function (no registry side-effects) so\n //? top-level importing it is safe and doesn't drag any boot ordering.\n //? Previously this was a lazy `require()` call which crashed under ESM\n //? (`ReferenceError: require is not defined`); the import-at-the-top\n //? form works in both runtimes the package targets.\n const pageFiles = walkPageFiles(srcDir);\n const routeToFiles = new Map<string, string[]>();\n\n for (const absoluteFilePath of pageFiles) {\n const relative = normalizePath(path.relative(srcDir, absoluteFilePath));\n const result = validatePagePath(relative);\n if (!result.valid || !result.route) continue;\n const list = routeToFiles.get(result.route) ?? [];\n list.push(normalizePath(path.relative(ROOT_DIR, absoluteFilePath)));\n routeToFiles.set(result.route, list);\n }\n\n const issues: DuplicatePageRouteIssue[] = [];\n for (const [route, filePaths] of routeToFiles) {\n if (filePaths.length > 1) {\n issues.push({ route, filePaths });\n }\n }\n return issues;\n};\n\nexport const formatDuplicatePageRouteIssues = ({\n issues,\n context,\n}: {\n issues: DuplicatePageRouteIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} duplicate page route${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n const fileList = issue.filePaths.map((filePath) => ` - ${filePath}`).join('\\n');\n return `${index + 1}. ${issue.route}\\n files:\\n${fileList}\\n fix: rename or move one of the files so only one page.tsx resolves to \"${issue.route}\". Remember that \"_<folder>\" segments are stripped from the URL (invisible-parent rule).`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const assertNoDuplicatePageRoutes = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectDuplicatePageRoutes(srcDir);\n if (issues.length === 0) return;\n throw new Error(formatDuplicatePageRouteIssues({ issues, context }));\n};","//? Consumer-facing registry for scaffold templates AND the selection logic\n//? that decides WHICH template a newly-created file receives.\n//?\n//? Two layers live here:\n//? 1. Content overrides — `registerTemplate(kind, content)`: replace the body\n//? of a template kind with a custom string.\n//? 2. Selection rules — `registerTemplateRule(...)` / `registerTemplateKind(...)`:\n//? decide, given a classified file context, which kind to inject. The\n//? built-in defaults below ARE expressed as rules, so a consumer can\n//? inspect, edit, remove, or extend them from a single overlay file\n//? (`.luckystack/templates/templateRules.ts`, auto-loaded by devkit in dev).\n//?\n//? `templateInjector.ts` reads from this module: it classifies the file\n//? (api / sync_server / sync_client / page), asks `resolveTemplateKind(ctx)`\n//? for the kind, then resolves content (consumer file → override → bundled).\n\n/**\n * The six template kinds the framework ships out of the box. Consumers may\n * register additional kinds (e.g. `page_marketing`) via `registerTemplateKind`.\n */\nexport type BuiltInTemplateKind =\n | 'api'\n | 'sync_server'\n | 'sync_client_paired'\n | 'sync_client_standalone'\n | 'page_plain'\n | 'page_dashboard';\n\n//? `(string & {})` keeps editor autocomplete for the built-in literals while\n//? still accepting arbitrary consumer-defined kind names.\nexport type TemplateKind = BuiltInTemplateKind | (string & {});\n\nexport const BUILT_IN_TEMPLATE_KINDS: readonly BuiltInTemplateKind[] = [\n 'api',\n 'sync_server',\n 'sync_client_paired',\n 'sync_client_standalone',\n 'page_plain',\n 'page_dashboard',\n];\n\n//? Page templates are `.tsx` (they contain JSX); the rest are `.ts`. The\n//? injector reads them as plain text, so the extension is cosmetic at runtime\n//? but load-bearing for the package's own `tsc` program.\nexport const BUILT_IN_TEMPLATE_FILENAMES: Record<BuiltInTemplateKind, string> = {\n api: 'api.template.ts',\n sync_server: 'sync_server.template.ts',\n sync_client_paired: 'sync_client_paired.template.ts',\n sync_client_standalone: 'sync_client_standalone.template.ts',\n page_plain: 'page_plain.template.tsx',\n page_dashboard: 'page_dashboard.template.tsx',\n};\n\n/**\n * Structural classification of the file an injection is being computed for.\n * `templateInjector.ts` derives this from the folder + filename conventions\n * (controlled separately via `registerRoutingRules`). Selection rules match\n * against it to choose a template kind.\n */\nexport interface TemplateMatchContext {\n /** Absolute path of the file being created. */\n filePath: string;\n /** Structural kind derived from the route conventions. */\n fileKind: 'api' | 'sync_server' | 'sync_client' | 'page';\n /** For `sync_client`: whether a paired `_server_v<N>.ts` exists on disk. */\n hasPairedServer: boolean;\n /** Path relative to `src/` (forward slashes), or `null` if outside src. */\n srcRelativePath: string | null;\n}\n\n/** A single template-selection rule. First matching rule (by priority) wins. */\nexport interface TemplateRule {\n kind: TemplateKind;\n match: (ctx: TemplateMatchContext) => boolean;\n /** Higher runs first. Built-in defaults use 10 (specific) / 0 (catch-all). */\n priority: number;\n}\n\ninterface StoredRule extends TemplateRule {\n /** Insertion sequence — later registrations win ties (consumer over default). */\n order: number;\n}\n\nexport interface RegisterTemplateKindOptions {\n /** Predicate deciding when this kind is chosen. */\n match: (ctx: TemplateMatchContext) => boolean;\n /** Optional inline template body (same as calling `registerTemplate`). */\n content?: string;\n /** Higher runs first. Defaults to 100 so consumer kinds beat the built-ins. */\n priority?: number;\n}\n\nconst overrides = new Map<TemplateKind, string>();\nconst rules: StoredRule[] = [];\nlet insertionCounter = 0;\n\n//? Dashboard-flavor heuristic for `page.tsx`. Exported so the scaffolded\n//? consumer `templateRules.ts` can reuse the exact same regex when it\n//? re-declares the default rule (and edit it in place).\nexport const DEFAULT_DASHBOARD_PATH_PATTERN = /\\/(admin|dashboard|settings|billing|account|profile)(\\/|$)/;\n\n// ---------------------------------------------------------------------------\n// Content overrides (v1 API — unchanged surface)\n// ---------------------------------------------------------------------------\n\n/**\n * Override the template body for a given kind. Subsequent injections emit the\n * supplied content with the standard `{{REL_PATH}}` / `{{PAGE_PATH}}` /\n * `{{SYNC_NAME}}` placeholder substitution. Resolution order in the injector\n * is: consumer file (`.luckystack/templates/<kind>.template.*`) → this\n * override → bundled disk template.\n */\nexport const registerTemplate = (kind: TemplateKind, content: string): void => {\n overrides.set(kind, content);\n};\n\n/** Read the registered content override for a kind, or `null` when none. */\nexport const getRegisteredTemplate = (kind: TemplateKind): string | null => {\n return overrides.get(kind) ?? null;\n};\n\n/** Drop every content override. Test-only. */\nexport const clearTemplateOverrides = (): void => {\n overrides.clear();\n};\n\n/** Diagnostic: kinds that currently have a content override. */\nexport const listRegisteredTemplateKinds = (): readonly TemplateKind[] => {\n return [...overrides.keys()];\n};\n\n// ---------------------------------------------------------------------------\n// Selection rules (decide WHICH kind a file gets)\n// ---------------------------------------------------------------------------\n\n/**\n * Register a selection rule. Rules are evaluated by descending `priority`,\n * ties broken by descending registration order (so a later registration —\n * e.g. a consumer overlay — beats an earlier same-priority default).\n */\nexport const registerTemplateRule = (rule: TemplateRule): void => {\n rules.push({ ...rule, order: insertionCounter++ });\n};\n\n/**\n * Register a brand-new template kind: its selection predicate plus (optionally)\n * its inline content. Equivalent to `registerTemplateRule` + `registerTemplate`\n * in one call. Default priority 100 so custom kinds win over the built-ins.\n */\nexport const registerTemplateKind = (kind: TemplateKind, options: RegisterTemplateKindOptions): void => {\n registerTemplateRule({ kind, match: options.match, priority: options.priority ?? 100 });\n if (typeof options.content === 'string') {\n registerTemplate(kind, options.content);\n }\n};\n\n/** Drop every selection rule (including the built-in defaults). */\nexport const clearTemplateRules = (): void => {\n rules.length = 0;\n};\n\n/** Read the active rules in evaluation order (priority desc, then newest first). */\nexport const getTemplateRules = (): readonly TemplateRule[] => {\n return rules\n .toSorted((a, b) => (b.priority - a.priority) || (b.order - a.order))\n .map(({ kind, match, priority }) => ({ kind, match, priority }));\n};\n\n/** Evaluate the active rules against a context; returns the first matching kind. */\nexport const resolveTemplateKind = (ctx: TemplateMatchContext): TemplateKind | null => {\n for (const rule of getTemplateRules()) {\n //? `rule.match` is a user-supplied predicate, NOT String.prototype.match —\n //? the prefer-regexp-test rule is a false positive on this member call.\n // eslint-disable-next-line unicorn/prefer-regexp-test\n if (rule.match(ctx)) return rule.kind;\n }\n return null;\n};\n\n/**\n * Register the framework's built-in default selection rules. Expressed as\n * ordinary rules so a consumer can replace them: call `clearTemplateRules()`\n * then re-register a subset (the scaffolded `templateRules.ts` does exactly\n * this). Idempotent guard prevents double-registration on repeated imports.\n */\nlet defaultsRegistered = false;\nexport const registerDefaultTemplateRules = (): void => {\n if (defaultsRegistered) return;\n defaultsRegistered = true;\n registerTemplateRule({ kind: 'api', priority: 10, match: (c) => c.fileKind === 'api' });\n registerTemplateRule({ kind: 'sync_server', priority: 10, match: (c) => c.fileKind === 'sync_server' });\n registerTemplateRule({ kind: 'sync_client_paired', priority: 10, match: (c) => c.fileKind === 'sync_client' && c.hasPairedServer });\n registerTemplateRule({ kind: 'sync_client_standalone', priority: 10, match: (c) => c.fileKind === 'sync_client' && !c.hasPairedServer });\n registerTemplateRule({\n kind: 'page_dashboard',\n priority: 10,\n match: (c) => c.fileKind === 'page' && DEFAULT_DASHBOARD_PATH_PATTERN.test(c.filePath.replaceAll('\\\\', '/').toLowerCase()),\n });\n //? Catch-all for pages — lowest priority so the dashboard rule wins first.\n registerTemplateRule({ kind: 'page_plain', priority: 0, match: (c) => c.fileKind === 'page' });\n};\n\n/**\n * Test-only: clear rules + content overrides AND re-arm the defaults guard so\n * `registerDefaultTemplateRules()` can repopulate a clean baseline.\n */\nexport const resetTemplateRegistryForTests = (): void => {\n clearTemplateRules();\n clearTemplateOverrides();\n defaultsRegistered = false;\n};\n\n//? Arm the built-in defaults on module load so any importer (the injector,\n//? unit tests, a host without a consumer overlay) has a working baseline.\nregisterDefaultTemplateRules();\n","// Dynamic `import()` of user route modules returns `any` at the JS boundary —\n// there is no safe way to type these without codegen. The unsafe-*, no-dynamic-delete,\n// and prefer-nullish-coalescing rules are suppressed file-wide (falsy defaults on `any`\n// values from module imports); all other rules remain active.\n/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-dynamic-delete, @typescript-eslint/prefer-nullish-coalescing */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from 'node:url';\nimport { tryCatch, getServerFunctionDirs, getSrcDir } from '@luckystack/core';\nimport { getInputTypeFromFile, getSyncClientDataType } from './typeMap/extractors';\nimport { invalidateProgramCache } from './typeMap/tsProgram';\nimport { clearRuntimeTypeResolverCache } from './runtimeTypeResolver';\nimport { getRoutingRules, isRouteTestFile } from './routingRules';\nimport { assertValidRouteNaming, collectDuplicatePageRoutes, formatDuplicatePageRouteIssues } from './routeNamingValidation';\n\nexport const devApis: Record<string, unknown> = {};\nexport const devSyncs: Record<string, unknown> = {};\nexport const devFunctions: Record<string, unknown> = {};\n\nconst normalizePath = (value: string): string => value.replaceAll('\\\\', '/');\n\nconst mapApiPageLocation = (pageLocation: string): string => {\n return pageLocation || 'system';\n};\n\n//? Root-level sync routes (directly under `src/_sync/`) get the SAME `'system'`\n//? sentinel as root-level APIs. Without it the loader registered `sync/<name>/v1`\n//? (two segments) while the typed `syncRequest` sends `sync/system/<name>/v1`\n//? and the wire parser (`parseTransportRouteName`) REQUIRES a\n//? `{service}/{name}/{version}` triple — so a root sync silently never\n//? dispatched. Mirrors `mapApiPageLocation` + `extractSyncPagePath`.\nconst mapSyncPageLocation = (pageLocation: string): string => {\n return pageLocation || 'system';\n};\n\nconst resolveApiRouteMetaFromPath = (filePath: string): { routeKey: string; absolutePath: string } | null => {\n const absolutePath = path.resolve(filePath);\n const normalizedAbsolutePath = normalizePath(absolutePath);\n const normalizedSrcDir = normalizePath(getSrcDir());\n\n if (!normalizedAbsolutePath.startsWith(normalizedSrcDir) || !normalizedAbsolutePath.endsWith('.ts')) {\n return null;\n }\n\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(getSrcDir(), absolutePath));\n const segments = relativePath.split('/');\n const apiIndex = segments.indexOf(rules.apiMarker);\n if (apiIndex === -1 || apiIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, apiIndex).join('/');\n const apiFilePath = segments.slice(apiIndex + 1).join('/');\n const rawApiName = apiFilePath.replace(/\\.ts$/, '');\n const versionMatch = rawApiName.match(rules.apiVersionRegex);\n\n if (!versionMatch) {\n return null;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(rules.apiVersionRegex, '');\n const mappedPageLocation = mapApiPageLocation(pageLocation);\n const routeKey = `api/${mappedPageLocation}/${apiName}/${version}`;\n\n return { routeKey, absolutePath };\n};\n\nconst resolveSyncRouteMetaFromPath = (\n filePath: string,\n): { routeKey: string; kind: 'server' | 'client'; absolutePath: string } | null => {\n const absolutePath = path.resolve(filePath);\n const normalizedAbsolutePath = normalizePath(absolutePath);\n const normalizedSrcDir = normalizePath(getSrcDir());\n\n if (!normalizedAbsolutePath.startsWith(normalizedSrcDir) || !normalizedAbsolutePath.endsWith('.ts')) {\n return null;\n }\n\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(getSrcDir(), absolutePath));\n const segments = relativePath.split('/');\n const syncIndex = segments.indexOf(rules.syncMarker);\n if (syncIndex === -1 || syncIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, syncIndex).join('/');\n const syncFilePath = segments.slice(syncIndex + 1).join('/');\n const rawSyncName = syncFilePath.replace(/\\.ts$/, '');\n const match = rawSyncName.match(rules.syncVersionRegex);\n\n if (!match) {\n return null;\n }\n\n const kind = match[1] as 'server' | 'client';\n const version = `v${match[2]}`;\n const syncName = rawSyncName.replace(rules.syncVersionRegex, '');\n const mappedPageLocation = mapSyncPageLocation(pageLocation);\n const routeBaseKey = `sync/${mappedPageLocation}/${syncName}/${version}`;\n\n return {\n routeKey: `${routeBaseKey}_${kind}`,\n kind,\n absolutePath,\n };\n};\n\nexport const initializeAll = async () => {\n assertValidRouteNaming({\n srcDir: getSrcDir(),\n context: 'starting dev server (npm run server)',\n });\n\n //? Soft-warn on duplicate page routes — DON'T throw on startup so a\n //? misplaced page.tsx doesn't block the entire dev server. The build\n //? path (typeMapGenerator + scripts/generateServerRequests) DOES throw,\n //? so collisions still block release. Same dev-vs-build escalation as\n //? page-placement warnings in `src/main.tsx getRoutes()`.\n const pageRouteIssues = collectDuplicatePageRoutes(getSrcDir());\n if (pageRouteIssues.length > 0) {\n console.warn(formatDuplicatePageRouteIssues({\n issues: pageRouteIssues,\n context: 'starting dev server (npm run server)',\n }));\n }\n\n await Promise.all([initializeApis(), initializeSyncs(), initializeFunctions()]);\n};\n\n// Dev hot-reload uses dynamic `import()` so module load yields to the event\n// loop instead of blocking it the way CommonJS `require()` did. The `?v=...`\n// query is a cachebust so the ESM loader returns a fresh evaluation each save.\nconst importFile = async (absolutePath: string) => {\n const url = `${pathToFileURL(absolutePath).href}?v=${Date.now()}`;\n return import(url);\n};\n\nconst collectTsFiles = (dir: string, relativeTo = \"\"): string[] => {\n const results: string[] = [];\n const entries = fs.readdirSync(dir);\n for (const entry of entries) {\n // Skip node_modules to avoid crawling installed packages (relevant when\n // the src dir contains symlinked packages or nested node_modules trees).\n if (entry === 'node_modules') continue;\n const entryPath = path.join(dir, entry);\n const relPath = relativeTo ? `${relativeTo}/${entry}` : entry;\n if (fs.statSync(entryPath).isDirectory()) {\n results.push(...collectTsFiles(entryPath, relPath));\n } else if (entry.endsWith(\".ts\") && !isRouteTestFile(entry)) {\n results.push(relPath);\n }\n }\n return results;\n};\n\nconst isMergeable = (value: unknown): value is Record<string, unknown> | ((...args: unknown[]) => unknown) => {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n};\n\nconst resolveFunctionModule = (loadedModule: unknown, fileName: string) => {\n if (!loadedModule || typeof loadedModule !== 'object' || !(\"default\" in loadedModule)) {\n return isMergeable(loadedModule) ? loadedModule : {};\n }\n\n const moduleRecord = loadedModule as Record<string, unknown>;\n const { default: defaultExport, ...namedExports } = moduleRecord;\n const filteredNamedExports = Object.fromEntries(\n Object.entries(namedExports).filter(([key]) => key !== '__esModule')\n );\n\n if (Object.keys(filteredNamedExports).length > 0) {\n return filteredNamedExports;\n }\n\n if (defaultExport !== undefined) {\n return { [fileName]: defaultExport };\n }\n\n return {};\n};\n\nexport const initializeApis = async () => {\n for (const key of Object.keys(devApis)) delete devApis[key];\n //? No invalidateProgramCache() here — cachedProgram starts as null on\n //? module-load (tsProgram.ts), so the first getServerProgram() call\n //? builds it from scratch. With initializeApis + initializeSyncs running\n //? in parallel via Promise.all, invalidating here forced a redundant\n //? double-build (~3-4s waste). Hot-reload paths (upsertApiFromFile,\n //? removeApiFromFile etc.) DO invalidate — that's where it's needed.\n clearRuntimeTypeResolverCache();\n const srcFolder = fs.readdirSync(getSrcDir());\n\n for (const file of srcFolder) {\n await scanApiFolder(file);\n }\n};\n\nexport const upsertApiFromFile = async (filePath: string): Promise<void> => {\n const routeMeta = resolveApiRouteMetaFromPath(filePath);\n if (!routeMeta) {\n const normalized = normalizePath(path.resolve(filePath));\n if (normalized.includes('/_api/') && normalized.endsWith('.ts') && !isRouteTestFile(normalized)) {\n console.log(\n `[loader][api] invalid filename: ${normalized}. Expected <name>_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n }\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n\n const [err, module] = await tryCatch(async () => importFile(routeMeta.absolutePath));\n if (err) {\n console.log(`[loader][api] failed to import ${routeMeta.routeKey} from ${routeMeta.absolutePath}:`, err, 'red');\n return;\n }\n\n const resolvedModule = module?.default ? { ...module.default, ...module } : module;\n const { auth = {}, main, rateLimit, httpMethod, schema, validation, errorFormatter } = resolvedModule;\n\n if (!main || typeof main !== 'function') {\n delete devApis[routeMeta.routeKey];\n return;\n }\n\n const inputType = getInputTypeFromFile(routeMeta.absolutePath);\n\n devApis[routeMeta.routeKey] = {\n main,\n auth: {\n login: auth.login || false,\n additional: auth.additional || [],\n },\n rateLimit,\n httpMethod,\n schema,\n inputType,\n inputTypeFilePath: routeMeta.absolutePath,\n validation,\n errorFormatter,\n };\n};\n\nexport const removeApiFromFile = (filePath: string): void => {\n const routeMeta = resolveApiRouteMetaFromPath(filePath);\n if (!routeMeta) {\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n delete devApis[routeMeta.routeKey];\n};\n\nconst scanApiFolder = async (file: string, basePath = \"\") => {\n const fullPath = path.join(getSrcDir(), basePath, file);\n if (!fs.statSync(fullPath).isDirectory()) return;\n\n if (!file.toLowerCase().endsWith(\"api\")) {\n const subFolders = fs.readdirSync(fullPath);\n for (const sub of subFolders) {\n await scanApiFolder(sub, path.join(basePath, file));\n }\n return;\n }\n\n const pageLocation = basePath.replaceAll('\\\\', '/');\n const mappedPageLocation = mapApiPageLocation(pageLocation);\n const tsFiles = collectTsFiles(fullPath);\n\n const apiRules = getRoutingRules();\n for (const relFile of tsFiles) {\n const rawApiName = relFile.replace(/\\.ts$/, \"\").replaceAll('\\\\', '/');\n const versionMatch = rawApiName.match(apiRules.apiVersionRegex);\n if (!versionMatch) {\n console.log(\n `[loader][api] invalid filename: ${path.join(fullPath, relFile)}. Expected <name>_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n continue;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(apiRules.apiVersionRegex, '');\n const routeKey = `api/${mappedPageLocation}/${apiName}/${version}`;\n\n const modulePath = path.resolve(path.join(fullPath, relFile));\n const [err, module] = await tryCatch(async () => importFile(modulePath));\n if (err) {\n console.log(`[loader][api] failed to import ${routeKey} from ${modulePath}:`, err, 'red');\n continue;\n }\n\n const resolvedModule = module?.default ? { ...module.default, ...module } : module;\n const { auth = {}, main, rateLimit, httpMethod, schema, validation, errorFormatter } = resolvedModule;\n if (!main || typeof main !== \"function\") continue;\n const inputType = getInputTypeFromFile(modulePath);\n\n devApis[routeKey] = {\n main,\n auth: {\n login: auth.login || false,\n additional: auth.additional || [],\n },\n rateLimit,\n httpMethod,\n schema,\n inputType,\n inputTypeFilePath: modulePath,\n validation,\n errorFormatter,\n };\n }\n};\n\nexport const initializeSyncs = async () => {\n for (const key of Object.keys(devSyncs)) delete devSyncs[key];\n //? See initializeApis above — no invalidation on the boot path. Hot-reload\n //? paths (upsertSyncFromFile / removeSyncFromFile) handle invalidation\n //? when a file actually changes.\n clearRuntimeTypeResolverCache();\n const srcFolder = fs.readdirSync(getSrcDir());\n\n for (const file of srcFolder) {\n await scanSyncFolder(file);\n }\n};\n\nexport const upsertSyncFromFile = async (filePath: string): Promise<void> => {\n const routeMeta = resolveSyncRouteMetaFromPath(filePath);\n if (!routeMeta) {\n const normalized = normalizePath(path.resolve(filePath));\n if (normalized.includes(`/${getRoutingRules().syncMarker}/`) && normalized.endsWith('.ts') && !isRouteTestFile(normalized)) {\n console.log(\n `[loader][sync] invalid filename: ${normalized}. Expected <name>_server_v<number>.ts or <name>_client_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n }\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n\n const [err, module] = await tryCatch(async () => importFile(routeMeta.absolutePath));\n if (err) {\n console.log(`[loader][sync] failed to import ${routeMeta.absolutePath}:`, err, 'red');\n return;\n }\n\n const resolvedSyncModule = module?.default\n ? { ...module.default, ...module }\n : module;\n\n if (routeMeta.kind === 'server') {\n if (!resolvedSyncModule.main || typeof resolvedSyncModule.main !== 'function') {\n delete devSyncs[routeMeta.routeKey];\n return;\n }\n\n const inputType = getSyncClientDataType(routeMeta.absolutePath);\n\n devSyncs[routeMeta.routeKey] = {\n main: resolvedSyncModule.main,\n auth: resolvedSyncModule.auth || {},\n inputType,\n inputTypeFilePath: routeMeta.absolutePath,\n //? Forward the per-route `validation` toggle + `errorFormatter` so the dev\n //? loader's sync entry shape matches the prod generator's. Dropping them\n //? made `validation: { input: 'skip' }` / a per-route errorFormatter work\n //? in prod but silently no-op in dev (QUA-013 / QUA-044).\n validation: resolvedSyncModule.validation,\n errorFormatter: resolvedSyncModule.errorFormatter,\n };\n\n return;\n }\n\n if (!resolvedSyncModule.main || typeof resolvedSyncModule.main !== 'function') {\n delete devSyncs[routeMeta.routeKey];\n return;\n }\n\n devSyncs[routeMeta.routeKey] = resolvedSyncModule.main;\n};\n\nexport const removeSyncFromFile = (filePath: string): void => {\n const routeMeta = resolveSyncRouteMetaFromPath(filePath);\n if (!routeMeta) {\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n delete devSyncs[routeMeta.routeKey];\n};\n\nconst scanSyncFolder = async (file: string, basePath = \"\") => {\n const fullPath = path.join(getSrcDir(), basePath, file);\n if (!fs.statSync(fullPath).isDirectory()) return;\n\n if (!file.toLowerCase().endsWith(\"sync\")) {\n const subFolders = fs.readdirSync(fullPath);\n for (const sub of subFolders) {\n await scanSyncFolder(sub, path.join(basePath, file));\n }\n return;\n }\n\n const pageLocation = basePath.replaceAll('\\\\', '/');\n const tsFiles = collectTsFiles(fullPath);\n\n const syncRules = getRoutingRules();\n for (const relFile of tsFiles) {\n const rawSyncFileName = relFile.replace(/\\.ts$/, \"\").replaceAll('\\\\', '/');\n const syncMatch = rawSyncFileName.match(syncRules.syncVersionRegex);\n if (!syncMatch) {\n console.log(\n `[loader][sync] invalid filename: ${path.join(fullPath, relFile)}. Expected <name>_server_v<number>.ts or <name>_client_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n continue;\n }\n\n const kind = syncMatch[1];\n const version = `v${syncMatch[2]}`;\n const syncName = rawSyncFileName.replace(syncRules.syncVersionRegex, '');\n const mappedPageLocation = mapSyncPageLocation(pageLocation);\n const routeBaseKey = `sync/${mappedPageLocation}/${syncName}/${version}`;\n\n const filePath = path.resolve(path.join(fullPath, relFile));\n const [fileError, fileResult] = await tryCatch(async () => importFile(filePath));\n if (fileError) {\n console.log(`[loader][sync] failed to import ${filePath}:`, fileError, 'red');\n continue;\n }\n\n const resolvedSyncModule = fileResult?.default\n ? { ...fileResult.default, ...fileResult }\n : fileResult;\n const inputType = getSyncClientDataType(filePath);\n\n if (kind === 'server') {\n devSyncs[`${routeBaseKey}_server`] = {\n main: resolvedSyncModule.main,\n auth: resolvedSyncModule.auth || {},\n inputType,\n inputTypeFilePath: filePath,\n //? Forward `validation` + `errorFormatter` so the dev loader matches the\n //? prod generator's sync entry shape (QUA-013 / QUA-044).\n validation: resolvedSyncModule.validation,\n errorFormatter: resolvedSyncModule.errorFormatter,\n };\n } else {\n devSyncs[`${routeBaseKey}_client`] = resolvedSyncModule.main;\n }\n }\n};\n\n//? Tracks which root directory claimed each key-path so we can detect\n//? cross-root collisions (e.g. `functions/sleep.ts` AND `shared/sleep.ts`)\n//? and surface the same error the codegen emits, instead of silently\n//? merging exports across roots.\nconst functionClaimMap = new Map<string, string>();\n\nexport const initializeFunctions = async () => {\n for (const key of Object.keys(devFunctions)) delete devFunctions[key];\n functionClaimMap.clear();\n\n const dirs = getServerFunctionDirs();\n for (const dir of dirs) {\n if (fs.existsSync(dir)) {\n await scanFunctionsFolder(dir, dir);\n }\n }\n};\n\nconst scanFunctionsFolder = async (dir: string, rootDir: string, basePath: string[] = []) => {\n const entries = fs.readdirSync(dir);\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n const stat = fs.statSync(fullPath);\n\n if (stat.isDirectory()) {\n await scanFunctionsFolder(fullPath, rootDir, [...basePath, entry]);\n continue;\n }\n\n if (!entry.endsWith(\".ts\")) {\n continue;\n }\n\n const [err, module] = await tryCatch(async () => importFile(fullPath));\n if (err) {\n console.log(`[loader][function] failed to import ${fullPath}:`, err, 'red');\n continue;\n }\n\n const fileName = entry.replace(\".ts\", \"\");\n const resolvedFunctionModule = resolveFunctionModule(module, fileName);\n if (!isMergeable(resolvedFunctionModule)) continue;\n\n const keyPath = [...basePath, fileName].join('.');\n const previousRoot = functionClaimMap.get(keyPath);\n if (previousRoot !== undefined && previousRoot !== rootDir) {\n //? Cross-root collision. Mirror the codegen-time error so dev mode\n //? surfaces the same diagnostic. Skip the import so the previous\n //? claim wins; the next type-map regen will fail the build with the\n //? full message.\n console.log(\n `[loader][function] Conflict at \\`functions.${keyPath}\\`: defined in both \\`${previousRoot}\\` and \\`${rootDir}\\`. Skipping the second copy; fix the duplicate (delete one — \\`shared/\\` is the canonical location for framework re-exports).`,\n 'red',\n );\n continue;\n }\n functionClaimMap.set(keyPath, rootDir);\n\n //? Walk into devFunctions tree, creating nested Record<string, unknown>\n //? subtrees on demand. Each level is structurally a record but typed as\n //? `unknown` after one level of indexing — re-narrow before descent.\n let target: Record<string, unknown> = devFunctions;\n for (const part of basePath) {\n const existing = target[part];\n if (!existing || typeof existing !== 'object') {\n target[part] = {};\n }\n target = target[part] as Record<string, unknown>;\n }\n\n const existingAtFileName = target[fileName];\n if (\n existingAtFileName !== undefined\n && isMergeable(resolvedFunctionModule)\n && isMergeable(existingAtFileName)\n ) {\n Object.assign(resolvedFunctionModule, existingAtFileName);\n }\n\n target[fileName] = resolvedFunctionModule;\n }\n};\n","import * as ts from 'typescript';\nimport { getServerProgram, expandType } from './typeMap/tsProgram';\n\ntype ResolveResult =\n | { status: 'success'; typeText: string }\n | { status: 'error'; message: string };\n\ninterface ObjectField {\n key: string;\n optional: boolean;\n type: string;\n}\n\ninterface ObjectIndexSignature {\n keyName: string;\n keyType: string;\n type: string;\n}\n\ninterface ResolveState {\n stack: Set<string>;\n}\n\nconst MAX_DEPTH = 20;\nconst unresolvedPrefix = '__RUNTIME_UNRESOLVED__::';\n\nconst PRIMITIVE_TYPES = new Set([\n 'string', 'number', 'boolean', 'true', 'false', 'null', 'undefined', 'any', 'unknown', 'void', 'never',\n]);\n\n// These types are structurally opaque — return them as-is without expansion.\nconst SKIP_EXPANSION = new Set([\n 'Date', 'Promise', 'Array', 'Record', 'Partial', 'Required', 'Pick', 'Omit',\n 'Function', 'Map', 'Set', 'Buffer', 'Uint8Array', 'Object', 'WeakMap', 'WeakSet',\n]);\n\nconst toUnresolved = (message: string): string => `${unresolvedPrefix}${message}`;\nexport const isUnresolvedTypeMarker = (value: string): boolean => value.startsWith(unresolvedPrefix);\nexport const getUnresolvedTypeMessage = (value: string): string => value.slice(unresolvedPrefix.length).trim();\n\nconst resolvedTypeCache = new Map<string, ResolveResult>();\n\nexport const clearRuntimeTypeResolverCache = () => {\n resolvedTypeCache.clear();\n};\n\n// ─── string helpers ───────────────────────────────────────────────────────────\n\nconst splitTopLevel = (value: string, splitter: '|' | '&' | ','): string[] => {\n const items: string[] = [];\n let depthParen = 0;\n let depthBrace = 0;\n let depthBracket = 0;\n let depthAngle = 0;\n let quote: \"'\" | '\"' | '`' | null = null;\n let token = '';\n\n for (const char of value) {\n //? Inside a string-literal type (`'a|b'`, `\"x,y\"`) the splitter + brackets\n //? must be ignored — otherwise `'a|b' | number` mis-splits into 3 parts.\n if (quote !== null) {\n if (char === quote) quote = null;\n token += char;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n token += char;\n continue;\n }\n\n if (char === '(') depthParen += 1;\n if (char === ')') depthParen -= 1;\n if (char === '{') depthBrace += 1;\n if (char === '}') depthBrace -= 1;\n if (char === '[') depthBracket += 1;\n if (char === ']') depthBracket -= 1;\n if (char === '<') depthAngle += 1;\n //? Clamp at 0: a function type's `=>` (and `>=`) contributes a `>` with no\n //? matching `<`, which would otherwise drive depthAngle negative and stop\n //? later top-level splits from ever firing.\n if (char === '>') depthAngle = Math.max(0, depthAngle - 1);\n\n if (\n char === splitter\n && depthParen === 0\n && depthBrace === 0\n && depthBracket === 0\n && depthAngle === 0\n ) {\n if (token.trim()) items.push(token.trim());\n token = '';\n continue;\n }\n\n token += char;\n }\n\n if (token.trim()) items.push(token.trim());\n return items;\n};\n\n// Parses a type-expression string into a `ts.TypeNode` by wrapping it in a\n// synthetic `type __X = <expr>;` alias and inspecting the parsed declaration.\n// Returns `null` when the input does not parse as a type alias.\nconst parseTypeNode = (typeText: string): ts.TypeNode | null => {\n const synthetic = `type __RT = ${typeText};`;\n const source = ts.createSourceFile('__runtime_type.ts', synthetic, ts.ScriptTarget.Latest, true);\n const statement = source.statements[0];\n if (!statement || !ts.isTypeAliasDeclaration(statement)) return null;\n return statement.type;\n};\n\nconst parseObjectFields = (typeText: string): { fields: ObjectField[]; indexSignatures: ObjectIndexSignature[] } => {\n const clean = typeText.trim();\n if (!clean.startsWith('{') || !clean.endsWith('}')) {\n return { fields: [], indexSignatures: [] };\n }\n\n const typeNode = parseTypeNode(clean);\n if (!typeNode || !ts.isTypeLiteralNode(typeNode)) {\n return { fields: [], indexSignatures: [] };\n }\n\n const fields: ObjectField[] = [];\n const indexSignatures: ObjectIndexSignature[] = [];\n\n for (const member of typeNode.members) {\n if (ts.isPropertySignature(member) && member.type) {\n let key: string | null = null;\n if (ts.isIdentifier(member.name)) {\n key = member.name.text;\n } else if (ts.isStringLiteral(member.name)) {\n key = member.name.text;\n }\n if (key === null) continue;\n\n fields.push({\n key,\n optional: Boolean(member.questionToken),\n type: member.type.getText().trim(),\n });\n continue;\n }\n\n if (ts.isIndexSignatureDeclaration(member)) {\n const param = member.parameters[0];\n if (!param || !ts.isIdentifier(param.name) || !param.type) continue;\n indexSignatures.push({\n keyName: param.name.text,\n keyType: param.type.getText().trim(),\n type: member.type.getText().trim(),\n });\n }\n }\n\n return { fields, indexSignatures };\n};\n\nconst serializeObjectFields = ({\n fields,\n indexSignatures,\n}: {\n fields: ObjectField[];\n indexSignatures: ObjectIndexSignature[];\n}): string => {\n const segments: string[] = [];\n\n for (const field of fields) {\n segments.push(`${field.key}${field.optional ? '?' : ''}: ${field.type}`);\n }\n\n for (const indexSignature of indexSignatures) {\n segments.push(`[${indexSignature.keyName}: ${indexSignature.keyType}]: ${indexSignature.type}`);\n }\n\n if (segments.length === 0) return '{ }';\n return `{ ${segments.join('; ')} }`;\n};\n\nconst extractStringLiteralKey = (node: ts.TypeNode): string | null => {\n if (!ts.isLiteralTypeNode(node)) return null;\n const literal = node.literal;\n if (!ts.isStringLiteral(literal)) return null;\n return literal.text;\n};\n\nconst parseLiteralUnionKeys = (value: string): string[] | null => {\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n const typeNode = parseTypeNode(trimmed);\n if (!typeNode) return null;\n\n if (ts.isUnionTypeNode(typeNode)) {\n const keys: string[] = [];\n for (const member of typeNode.types) {\n const key = extractStringLiteralKey(member);\n if (key === null) return null;\n keys.push(key);\n }\n return keys.length > 0 ? keys : null;\n }\n\n const singleKey = extractStringLiteralKey(typeNode);\n return singleKey === null ? null : [singleKey];\n};\n\n// ─── TypeChecker-based identifier resolution ──────────────────────────────────\n\n// Resolves a named type identifier to its expanded inline type string using\n// the TypeScript compiler API, following imports across files automatically.\nconst resolveIdentifier = (identifier: string, filePath: string): string => {\n if (PRIMITIVE_TYPES.has(identifier.toLowerCase())) return identifier.toLowerCase();\n if (SKIP_EXPANSION.has(identifier)) return identifier;\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return toUnresolved(`unresolved type ${identifier}`);\n\n const checker = program.getTypeChecker();\n\n for (const stmt of sourceFile.statements) {\n // Local interface / type alias / enum\n if (\n (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt) || ts.isEnumDeclaration(stmt))\n && stmt.name.text === identifier\n ) {\n const symbol = checker.getSymbolAtLocation(stmt.name);\n if (symbol) {\n return expandType(checker.getDeclaredTypeOfSymbol(symbol), checker);\n }\n }\n\n // Import declarations — follow the alias to the original symbol\n if (ts.isImportDeclaration(stmt) && stmt.importClause) {\n const { namedBindings, name: defaultName } = stmt.importClause;\n\n if (namedBindings && ts.isNamedImports(namedBindings)) {\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === identifier) {\n const symbol = checker.getSymbolAtLocation(specifier.name);\n if (symbol) {\n const target = symbol.flags & ts.SymbolFlags.Alias\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n return expandType(checker.getDeclaredTypeOfSymbol(target), checker);\n }\n }\n }\n }\n\n if (defaultName?.text === identifier) {\n const symbol = checker.getSymbolAtLocation(defaultName);\n if (symbol) {\n const target = symbol.flags & ts.SymbolFlags.Alias\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n return expandType(checker.getDeclaredTypeOfSymbol(target), checker);\n }\n }\n }\n }\n\n return toUnresolved(`unresolved type ${identifier}`);\n } catch {\n return toUnresolved(`unresolved type ${identifier}`);\n }\n};\n\n// ─── utility type application ─────────────────────────────────────────────────\n\nconst applyUtilityType = ({\n utilityName,\n utilityArgs,\n filePath,\n depth,\n state,\n}: {\n utilityName: string;\n utilityArgs: string[];\n filePath: string;\n depth: number;\n state: ResolveState;\n}): string => {\n if (utilityName === 'Partial' || utilityName === 'Required') {\n const arg0 = utilityArgs[0];\n if (utilityArgs.length !== 1 || arg0 === undefined) return toUnresolved(`unresolved utility ${utilityName}<...>`);\n const target = resolveExpression(arg0, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(target)) return target;\n const parsed = parseObjectFields(target);\n const fields = parsed.fields;\n if (fields.length === 0) return toUnresolved(`unresolved utility ${utilityName}<${arg0}>`);\n return serializeObjectFields({\n fields: fields.map((f) => ({ ...f, optional: utilityName === 'Partial' })),\n indexSignatures: parsed.indexSignatures,\n });\n }\n\n if (utilityName === 'Pick' || utilityName === 'Omit') {\n const arg0 = utilityArgs[0];\n const arg1 = utilityArgs[1];\n if (utilityArgs.length !== 2 || arg0 === undefined || arg1 === undefined) return toUnresolved(`unresolved utility ${utilityName}<...>`);\n const target = resolveExpression(arg0, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(target)) return target;\n const keys = parseLiteralUnionKeys(arg1);\n if (!keys) return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n const parsed = parseObjectFields(target);\n const fields = parsed.fields;\n if (fields.length === 0) return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n const keySet = new Set(keys);\n const filtered = fields.filter((f) => (utilityName === 'Pick' ? keySet.has(f.key) : !keySet.has(f.key)));\n return serializeObjectFields({ fields: filtered, indexSignatures: parsed.indexSignatures });\n }\n\n if (utilityName === 'Record') {\n const arg0 = utilityArgs[0];\n const arg1 = utilityArgs[1];\n if (utilityArgs.length !== 2 || arg0 === undefined || arg1 === undefined) return toUnresolved('unresolved utility Record<...>');\n const resolvedKey = resolveExpression(arg0, filePath, depth + 1, state);\n const resolvedValue = resolveExpression(arg1, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedKey)) return resolvedKey;\n if (isUnresolvedTypeMarker(resolvedValue)) return resolvedValue;\n const keys = parseLiteralUnionKeys(resolvedKey);\n if (!keys) return `Record<${resolvedKey}, ${resolvedValue}>`;\n return serializeObjectFields({\n fields: keys.map((key) => ({ key, optional: false, type: resolvedValue })),\n indexSignatures: [],\n });\n }\n\n return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n};\n\n// ─── expression resolver ──────────────────────────────────────────────────────\n\nconst resolveExpression = (typeText: string, filePath: string, depth: number, state: ResolveState): string => {\n const type = typeText.trim();\n if (!type) return type;\n\n const visitKey = `${filePath}::${type}`;\n if (state.stack.has(visitKey)) return toUnresolved(`cyclic type reference ${type}`);\n if (depth > MAX_DEPTH) return toUnresolved(`resolution depth exceeded for ${type}`);\n\n state.stack.add(visitKey);\n\n let result: string;\n\n if (isUnresolvedTypeMarker(type)) {\n result = type;\n } else if (type.startsWith('(') && type.endsWith(')')) {\n const inner = resolveExpression(type.slice(1, -1), filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `(${inner})`;\n } else {\n const unionParts = splitTopLevel(type, '|');\n if (unionParts.length > 1) {\n const resolved = unionParts.map((p) => resolveExpression(p, filePath, depth + 1, state));\n const unresolved = resolved.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? resolved.join(' | ');\n } else {\n const intersectionParts = splitTopLevel(type, '&');\n if (intersectionParts.length > 1) {\n const resolved = intersectionParts.map((p) => resolveExpression(p, filePath, depth + 1, state));\n const unresolved = resolved.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? resolved.join(' & ');\n } else if (type.endsWith('[]')) {\n const inner = resolveExpression(type.slice(0, -2), filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `${inner}[]`;\n } else if (type.startsWith('{') && type.endsWith('}')) {\n const parsed = parseObjectFields(type);\n const fields = parsed.fields;\n const indexSignatures = parsed.indexSignatures;\n const resolvedFields: ObjectField[] = [];\n const resolvedIndexSignatures: ObjectIndexSignature[] = [];\n let hadError: string | undefined;\n\n if (fields.length === 0 && indexSignatures.length === 0) {\n result = type;\n state.stack.delete(visitKey);\n return result;\n }\n\n for (const field of fields) {\n const resolvedType = resolveExpression(field.type, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedType)) { hadError = resolvedType; break; }\n resolvedFields.push({ ...field, type: resolvedType });\n }\n\n for (const indexSignature of indexSignatures) {\n const resolvedKeyType = resolveExpression(indexSignature.keyType, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedKeyType)) { hadError = resolvedKeyType; break; }\n\n const resolvedValueType = resolveExpression(indexSignature.type, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedValueType)) { hadError = resolvedValueType; break; }\n\n resolvedIndexSignatures.push({\n ...indexSignature,\n keyType: resolvedKeyType,\n type: resolvedValueType,\n });\n }\n\n result = hadError ?? serializeObjectFields({\n fields: resolvedFields,\n indexSignatures: resolvedIndexSignatures,\n });\n } else {\n const typeNode = parseTypeNode(type);\n const referenceInfo = typeNode && ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)\n ? { name: typeNode.typeName.text, args: typeNode.typeArguments }\n : null;\n\n if (referenceInfo?.args && referenceInfo.args.length > 0) {\n const { name: genericName, args: argNodes } = referenceInfo;\n const args = argNodes.map((arg) => arg.getText().trim());\n const firstArg = args[0];\n\n if (genericName === 'Array' && args.length === 1 && firstArg !== undefined) {\n const inner = resolveExpression(firstArg, filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `${inner}[]`;\n } else if (['Partial', 'Required', 'Pick', 'Omit', 'Record'].includes(genericName)) {\n result = applyUtilityType({ utilityName: genericName, utilityArgs: args, filePath, depth, state });\n } else {\n const resolvedArgs = args.map((a) => resolveExpression(a, filePath, depth + 1, state));\n const unresolved = resolvedArgs.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? `${genericName}<${resolvedArgs.join(', ')}>`;\n }\n } else if (referenceInfo && (!referenceInfo.args || referenceInfo.args.length === 0)) {\n result = resolveIdentifier(referenceInfo.name, filePath);\n } else {\n result = type;\n }\n }\n }\n }\n\n state.stack.delete(visitKey);\n return result;\n};\n\n// ─── public API ───────────────────────────────────────────────────────────────\n\nexport const resolveRuntimeTypeText = ({\n typeText,\n filePath,\n}: {\n typeText: string;\n filePath?: string;\n}): ResolveResult => {\n const cleanType = typeText.trim();\n if (!cleanType || !filePath) {\n return { status: 'success', typeText: cleanType };\n }\n\n const cacheKey = `${filePath}::${cleanType}`;\n const cached = resolvedTypeCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const resolved = resolveExpression(cleanType, filePath, 0, { stack: new Set() });\n const result: ResolveResult = isUnresolvedTypeMarker(resolved)\n ? { status: 'error', message: getUnresolvedTypeMessage(resolved) }\n : { status: 'success', typeText: resolved };\n\n resolvedTypeCache.set(cacheKey, result);\n return result;\n};\n","import { watch } from \"chokidar\";\nimport fs from \"node:fs\";\nimport path from 'node:path';\nimport {\n initializeFunctions,\n upsertApiFromFile,\n removeApiFromFile,\n upsertSyncFromFile,\n removeSyncFromFile,\n} from \"./loader\";\nimport {\n shouldInjectTemplate,\n injectTemplate,\n isSyncServerFile,\n getPairedSyncFile,\n getRouteFilenameValidationMessage,\n extractClientInputFromFile,\n extractClientInputFromGeneratedTypes,\n extractSyncPagePath,\n extractSyncName,\n injectServerTemplateWithClientInput,\n updateClientFileForPairedServer,\n updateClientFileForDeletedServer,\n isEmptyFile\n} from \"./templateInjector\";\nimport {\n generateTypeMapFile,\n} from \"./typeMapGenerator.js\";\nimport { findDependentRouteFiles, invalidateGraphForFile } from \"./importDependencyGraph\";\nimport { isPrismaClientMissing, runPrismaGenerate } from \"./prismaClientCheck\";\nimport { tryCatch, getProjectConfig, getLocaleReloader } from \"@luckystack/core\";\nimport { getRoutingRules } from './routingRules';\n\n// ----------------------------\n// Watcher for Hot Reload + Type Generation\n// ----------------------------\n\nconst normalizeFsPath = (value: string): string => path.resolve(value).replaceAll('\\\\', '/');\n\nconst isGeneratedPath = (normalizedPath: string): boolean => {\n return (\n normalizedPath.includes('apiTypes.generated.ts')\n || normalizedPath.includes('apiDocs.generated.json')\n );\n};\n\n// ---------------------------------------------------------------------------\n// Type-map queue\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a self-contained type-map regeneration queue that coalesces\n * concurrent save bursts into a single background run via setImmediate.\n */\nconst createTypeMapQueue = () => {\n const queue = { pending: false, running: false };\n\n const run = () => {\n queue.running = true;\n queue.pending = false;\n const startedAt = Date.now();\n setImmediate(() => {\n void (async () => {\n const [err] = await tryCatch(() => { generateTypeMapFile({ quiet: true }); });\n if (err) {\n console.log(`[HotReload] type map regeneration failed: ${String(err)}`, 'red');\n } else {\n console.log(`[HotReload] type map ready in ${Date.now() - startedAt}ms`, 'green');\n }\n queue.running = false;\n if (queue.pending) {\n run();\n }\n })();\n });\n };\n\n const request = () => {\n if (queue.running) {\n queue.pending = true;\n return;\n }\n run();\n };\n\n return { request };\n};\n\n// ---------------------------------------------------------------------------\n// Pending change sets\n// ---------------------------------------------------------------------------\n\n/**\n * Bundles the four mutable sets that track pending API/Sync add/delete\n * operations so they travel as a single value rather than four separate\n * variables inside the watcher closure.\n */\nconst createPendingChangeSets = () => ({\n apiUpserts: new Set<string>(),\n apiDeletes: new Set<string>(),\n syncUpserts: new Set<string>(),\n syncDeletes: new Set<string>(),\n});\n\n// ---------------------------------------------------------------------------\n// Path classifiers\n// ---------------------------------------------------------------------------\n\n/**\n * Holds path-segment constants derived from the project config.\n * Computed once per `setupWatchers` call.\n */\ninterface PathSegments {\n apiMarkerSlash: string;\n syncMarkerSlash: string;\n apiMarkerNoLead: string;\n syncMarkerNoLead: string;\n srcSegment: string;\n sharedSegment: string;\n localesSegment: string;\n serverFunctionsSegments: string[];\n}\n\nconst buildPathSegments = (): PathSegments => {\n const rules = getRoutingRules();\n const pathsCfg = getProjectConfig().paths;\n const srcSegment = `/${pathsCfg.srcDir.replaceAll('\\\\', '/')}/`;\n const sharedSegment = `/${pathsCfg.sharedDir.replaceAll('\\\\', '/')}/`;\n return {\n apiMarkerSlash: `/${rules.apiMarker}/`,\n syncMarkerSlash: `/${rules.syncMarker}/`,\n apiMarkerNoLead: `${rules.apiMarker}/`,\n syncMarkerNoLead: `${rules.syncMarker}/`,\n srcSegment,\n sharedSegment,\n localesSegment: `${srcSegment}_locales/`,\n serverFunctionsSegments: pathsCfg.serverFunctionDirs.map(\n (dir) => `/${dir.replaceAll('\\\\', '/')}/`,\n ),\n };\n};\n\nconst makeIsInServerFunctionsDir = (segments: PathSegments) =>\n (normalizedPath: string): boolean =>\n segments.serverFunctionsSegments.some((seg) => normalizedPath.includes(seg));\n\nconst makeIsRouteDependencyFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean => {\n if (!normalizedPath.endsWith('.ts') && !normalizedPath.endsWith('.tsx')) return false;\n if (!normalizedPath.includes(segments.srcSegment)) return false;\n if (normalizedPath.includes(segments.apiMarkerSlash) || normalizedPath.includes(segments.syncMarkerSlash)) return false;\n if (isGeneratedPath(normalizedPath)) return false;\n return true;\n };\n\nconst makeIsSharedDependencyFile = (\n segments: PathSegments,\n isInServerFunctionsDir: (p: string) => boolean,\n) =>\n (normalizedPath: string): boolean => {\n if (!(normalizedPath.endsWith('.ts') || normalizedPath.endsWith('.tsx'))) return false;\n if (normalizedPath.includes(segments.sharedSegment)) return true;\n return isInServerFunctionsDir(normalizedPath);\n };\n\nconst makeIsTypeMapRelevantFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean => {\n if (isGeneratedPath(normalizedPath)) return false;\n if (!(normalizedPath.endsWith('.ts') || normalizedPath.endsWith('.tsx'))) return false;\n if (normalizedPath.includes(segments.apiMarkerSlash) || normalizedPath.includes(segments.syncMarkerSlash)) return false;\n return (\n normalizedPath.includes(segments.srcSegment)\n || normalizedPath.endsWith('/config.ts')\n || normalizedPath.includes(segments.sharedSegment)\n );\n };\n\nconst makeIsLocaleFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean =>\n normalizedPath.includes(segments.localesSegment) && normalizedPath.endsWith('.json');\n\n// ---------------------------------------------------------------------------\n// Reload scheduler\n// ---------------------------------------------------------------------------\n\ntype ReloadKey = 'api' | 'sync' | 'functions' | 'typemap' | 'locales';\n\n/**\n * Creates a debounced task scheduler keyed by reload category.\n * Multiple requests for the same key within the debounce window collapse\n * into a single execution.\n */\nconst createReloadScheduler = (debounceMs: () => number) => {\n const timers = new Map<ReloadKey, NodeJS.Timeout>();\n\n return (\n key: ReloadKey,\n task: () => Promise<void> | void,\n delay = debounceMs(),\n ) => {\n const active = timers.get(key);\n if (active) clearTimeout(active);\n\n const timer = setTimeout(() => {\n timers.delete(key);\n // Errors in async tasks must be caught here — an unhandled rejection\n // from a chokidar-triggered async callback crashes the dev server.\n Promise.resolve(task()).catch((error: unknown) => {\n console.log(`[HotReload] Scheduled task threw an error: ${String(error)}`, 'red');\n });\n }, delay);\n\n timers.set(key, timer);\n };\n};\n\n// ---------------------------------------------------------------------------\n// Watcher mounting\n// ---------------------------------------------------------------------------\n\n/**\n * Attaches chokidar watchers to all configured source and function directories.\n * Kept separate from the event-handler setup so the two concerns don't collapse\n * into a single function body.\n */\nconst mountWatchers = (\n onAdd: (p: string) => void,\n onChange: (p: string) => void,\n onDelete: (p: string) => void,\n onFunctionChange: (p: string) => void,\n) => {\n const devConfig = getProjectConfig().dev;\n const pathsConfig = getProjectConfig().paths;\n\n watch(pathsConfig.srcDir, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: devConfig.watcherStabilityThresholdMs,\n pollInterval: devConfig.watcherPollIntervalMs,\n },\n })\n .on('add', onAdd)\n .on('change', onChange)\n .on('unlink', onDelete);\n\n // Watch every configured server-function directory (the multi-dir injection roots).\n for (const dir of pathsConfig.serverFunctionDirs) {\n watch(dir, { ignoreInitial: true })\n .on('add', onFunctionChange)\n .on('change', onFunctionChange)\n .on('unlink', onFunctionChange);\n }\n\n // Watch shared modules separately (changes here cascade to dependent\n // routes via the import-dependency graph). NOTE: `shared/` is also one\n // of the default function-injection roots, so the watcher above already\n // covers it — but consumers can override `serverFunctionDirs` without\n // dropping `shared/`, so we keep this explicit watcher for the cascade\n // behavior. Duplicate add/change events are coalesced downstream.\n watch(pathsConfig.sharedDir, { ignoreInitial: true })\n .on('add', onFunctionChange)\n .on('change', onFunctionChange)\n .on('unlink', onFunctionChange);\n};\n\n// ---------------------------------------------------------------------------\n// Public entry point\n// ---------------------------------------------------------------------------\n\nexport const setupWatchers = () => {\n const isDevMode = process.env.NODE_ENV !== 'production';\n if (!isDevMode) return;\n\n const segments = buildPathSegments();\n const isInServerFunctionsDir = makeIsInServerFunctionsDir(segments);\n const isRouteDependencyFile = makeIsRouteDependencyFile(segments);\n const isSharedDependencyFile = makeIsSharedDependencyFile(segments, isInServerFunctionsDir);\n const isTypeMapRelevantFile = makeIsTypeMapRelevantFile(segments);\n const isLocaleFile = makeIsLocaleFile(segments);\n\n const typeMap = createTypeMapQueue();\n const pending = createPendingChangeSets();\n const scheduleReload = createReloadScheduler(() => getProjectConfig().dev.hotReloadDebounceMs);\n\n const processPendingApiChanges = async ({ regenerateTypeMap = false }: { regenerateTypeMap?: boolean } = {}) => {\n const deletePaths = [...pending.apiDeletes];\n const upsertPaths = [...pending.apiUpserts];\n pending.apiDeletes.clear();\n pending.apiUpserts.clear();\n\n if (regenerateTypeMap) {\n console.log(`[HotReload] API routes changed (add/delete), scheduling type map regeneration`, 'blue');\n typeMap.request();\n }\n\n for (const deletePath of deletePaths) {\n removeApiFromFile(deletePath);\n console.log(`[HotReload] API removed: ${deletePath}`, 'yellow');\n }\n\n for (const upsertPath of upsertPaths) {\n await upsertApiFromFile(upsertPath);\n console.log(`[HotReload] API reloaded: ${upsertPath}`, 'green');\n }\n };\n\n const processPendingSyncChanges = async ({ regenerateTypeMap = false }: { regenerateTypeMap?: boolean } = {}) => {\n const deletePaths = [...pending.syncDeletes];\n const upsertPaths = [...pending.syncUpserts];\n pending.syncDeletes.clear();\n pending.syncUpserts.clear();\n\n if (regenerateTypeMap) {\n console.log(`[HotReload] Sync routes changed (add/delete), scheduling type map regeneration`, 'blue');\n typeMap.request();\n }\n\n for (const deletePath of deletePaths) {\n removeSyncFromFile(deletePath);\n console.log(`[HotReload] Sync removed: ${deletePath}`, 'yellow');\n }\n\n for (const upsertPath of upsertPaths) {\n await upsertSyncFromFile(upsertPath);\n console.log(`[HotReload] Sync reloaded: ${upsertPath}`, 'green');\n }\n };\n\n const enqueueAffectedRoutesFromDependency = (changedPath: string) => {\n const affectedRoutes = findDependentRouteFiles(changedPath);\n\n if (affectedRoutes.size === 0) {\n console.log(`[HotReload] No API/Sync routes depend on: ${changedPath}`, 'yellow');\n return;\n }\n\n //? With dynamic `import()` + per-load `?v=` cachebust in loader.ts there is\n //? nothing to invalidate on the main thread; the next upsert will fetch a\n //? fresh module instance.\n\n let queuedApiCount = 0;\n let queuedSyncCount = 0;\n\n for (const routePath of affectedRoutes) {\n if (routePath.includes(segments.apiMarkerSlash)) {\n pending.apiDeletes.delete(routePath);\n pending.apiUpserts.add(routePath);\n queuedApiCount += 1;\n } else if (routePath.includes(segments.syncMarkerSlash)) {\n pending.syncDeletes.delete(routePath);\n pending.syncUpserts.add(routePath);\n queuedSyncCount += 1;\n }\n }\n\n console.log(\n `[HotReload] Dependency changed: ${changedPath} -> queued ${queuedApiCount} API and ${queuedSyncCount} Sync route reloads`,\n 'blue'\n );\n\n if (queuedApiCount > 0) {\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n }\n\n if (queuedSyncCount > 0) {\n scheduleReload('sync', async () => {\n await processPendingSyncChanges();\n });\n }\n };\n\n const handleAdd = async (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n const routeValidationMessage = getRouteFilenameValidationMessage(normalizedPath);\n if (routeValidationMessage) {\n if (shouldInjectTemplate(filePath, { isNewFile: true })) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n console.log(`[HotReload] ${routeValidationMessage}`, 'yellow');\n return;\n }\n\n // Check if this is a new empty file that needs a template\n if (shouldInjectTemplate(filePath, { isNewFile: true })) {\n // Special handling for sync server files when client already exists\n if (isSyncServerFile(normalizedPath)) {\n const clientPath = getPairedSyncFile(normalizedPath);\n if (clientPath && fs.existsSync(clientPath) && !isEmptyFile(clientPath)) {\n // Extract clientInput types from existing client file\n const clientInputTypes = extractClientInputFromFile(clientPath);\n if (clientInputTypes) {\n // Inject server template with pre-filled clientInput from client\n await injectServerTemplateWithClientInput(filePath, clientInputTypes);\n // Schedule type regeneration in the background; the client file\n // update + sync upserts below don't depend on the artifact.\n typeMap.request();\n // Update client file to use imported types + add serverOutput.\n // If the rewrite fails (returns false) skip upserts — the client\n // still has the old type shape and registering it now would give\n // the server a mis-matched handler contract.\n const clientRewritten = await updateClientFileForPairedServer(clientPath);\n if (!clientRewritten) {\n console.log(`[HotReload] Paired client rewrite failed, skipping upsert for: ${clientPath}`, 'yellow');\n return;\n }\n await upsertSyncFromFile(filePath);\n await upsertSyncFromFile(clientPath);\n return;\n }\n }\n }\n\n // Default template injection\n const injected = await injectTemplate(filePath);\n if (injected) {\n // Don't continue processing - the template was just injected\n // The next 'change' event will handle it\n return;\n }\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n pending.apiDeletes.delete(normalizedPath);\n pending.apiUpserts.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges({ regenerateTypeMap: true });\n });\n return;\n }\n\n if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n pending.syncDeletes.delete(normalizedPath);\n pending.syncUpserts.add(normalizedPath);\n scheduleReload('sync', async () => {\n await processPendingSyncChanges({ regenerateTypeMap: true });\n });\n return;\n }\n\n // Handle normal file additions\n handleChange(filePath).catch((error: unknown) => {\n console.log(`[HotReload] handleChange threw an error: ${String(error)}`, 'red');\n });\n };\n\n const handleChange = async (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n const routeValidationMessage = getRouteFilenameValidationMessage(normalizedPath);\n if (routeValidationMessage) {\n if (shouldInjectTemplate(filePath)) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n console.log(`[HotReload] ${routeValidationMessage}`, 'yellow');\n return;\n }\n\n if (shouldInjectTemplate(filePath)) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n if (isGeneratedPath(normalizedPath)) {\n return;\n }\n\n if (isLocaleFile(normalizedPath)) {\n scheduleReload('locales', async () => {\n await getLocaleReloader()?.();\n });\n return;\n }\n\n if (isRouteDependencyFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n enqueueAffectedRoutesFromDependency(normalizedPath);\n return;\n }\n\n if (isTypeMapRelevantFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] API changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.apiDeletes.delete(normalizedPath);\n pending.apiUpserts.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n } else if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Sync changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.syncDeletes.delete(normalizedPath);\n pending.syncUpserts.add(normalizedPath);\n scheduleReload('sync', async () => {\n await processPendingSyncChanges();\n });\n }\n };\n\n const handleFunctionChange = (changedPath: string) => {\n const normalizedPath = normalizeFsPath(changedPath);\n invalidateGraphForFile(normalizedPath);\n\n scheduleReload('functions', async () => {\n typeMap.request();\n await initializeFunctions();\n });\n\n if (isSharedDependencyFile(normalizedPath)) {\n enqueueAffectedRoutesFromDependency(normalizedPath);\n }\n };\n\n const handleDelete = (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n if (isGeneratedPath(normalizedPath)) {\n return;\n }\n\n if (isLocaleFile(normalizedPath)) {\n scheduleReload('locales', async () => {\n await getLocaleReloader()?.();\n });\n return;\n }\n\n if (isRouteDependencyFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n enqueueAffectedRoutesFromDependency(normalizedPath);\n return;\n }\n\n if (isTypeMapRelevantFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] API deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.apiUpserts.delete(normalizedPath);\n pending.apiDeletes.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n } else if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Sync deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.syncUpserts.delete(normalizedPath);\n pending.syncDeletes.add(normalizedPath);\n scheduleReload('sync', async () => {\n // Special handling for sync server file deletion when client exists\n if (isSyncServerFile(normalizedPath)) {\n const clientPath = getPairedSyncFile(normalizedPath);\n if (clientPath && fs.existsSync(clientPath)) {\n // Extract clientInput types from generated types file (server file is already deleted)\n const pagePath = extractSyncPagePath(normalizedPath);\n const syncName = extractSyncName(normalizedPath);\n const clientInputTypes = extractClientInputFromGeneratedTypes(pagePath, syncName);\n\n // Fall back to a placeholder block when types couldn't be extracted from generated file.\n await updateClientFileForDeletedServer(\n clientPath,\n clientInputTypes ?? '{\\n // Types were in _server.ts - please add them here\\n }',\n );\n }\n }\n\n await processPendingSyncChanges();\n });\n }\n };\n\n // Chokidar silently discards the promise returned by async listeners.\n // Wrap each handler so a thrown error is caught instead of becoming an\n // unhandled rejection that would crash the dev server.\n const safeHandleAdd = (p: string): void => { void handleAdd(p).catch((error: unknown) => { console.log(`[HotReload] handleAdd threw an error: ${String(error)}`, 'red'); }); };\n const safeHandleChange = (p: string): void => { void handleChange(p).catch((error: unknown) => { console.log(`[HotReload] handleChange threw an error: ${String(error)}`, 'red'); }); };\n // handleDelete is sync; errors surface inside the scheduleReload callbacks, not at call-site.\n const safeHandleDelete = (p: string): void => { handleDelete(p); };\n\n mountWatchers(safeHandleAdd, safeHandleChange, safeHandleDelete, handleFunctionChange);\n\n //? Generate initial type map on startup — fire-and-forget on the next\n //? event-loop tick so server.listen() happens first. Runtime reads from\n //? the in-memory devApis/devSyncs maps (already populated by\n //? initializeAll() before setupWatchers runs); the on-disk type-map is\n //? purely for IDE IntelliSense + Zod schema files. Deferring drops boot\n //? time ~6-8s on a 54-API project.\n setImmediate(() => {\n void (async () => {\n //? A scaffolded project whose consumer hasn't run `prisma generate` yet\n //? has a schema on disk but no generated `@prisma/client`. The type-map\n //? generator then throws on unresolved model identifiers (e.g. `User`).\n //? Auto-generate ONCE on boot — `prisma generate` only reads the schema,\n //? so it needs no DB credentials and is safe to run unattended.\n if (isPrismaClientMissing()) {\n console.log(`[HotReload] @prisma/client not generated yet — running prisma generate (no DB needed)…`, 'blue');\n const [generateErr, exitCode] = await runPrismaGenerate();\n if (generateErr || exitCode !== 0) {\n console.log(`[HotReload] prisma generate failed${generateErr ? `: ${String(generateErr)}` : ` (exit code ${String(exitCode)})`} — run \\`npm run prisma:generate\\` manually and restart`, 'red');\n } else {\n console.log(`[HotReload] prisma generate complete`, 'green');\n }\n }\n\n const [err] = await tryCatch(() => { generateTypeMapFile({ quiet: true }); });\n if (err) {\n //? Gate the hint on the actual failure CLASS, not the client-dir probe: an\n //? \"unresolved type identifiers\" error is almost always an un-generated\n //? @prisma/client (missing model types). Tying it to the error text means\n //? the hint always shows when it's relevant, even if the dir-probe is\n //? fooled by a stub, while staying quiet for unrelated failures.\n const hint = /unresolved type identifiers/i.test(String(err))\n ? '\\n → This usually means @prisma/client is not generated. Run `npm run prisma:generate` (no database needed) and restart.'\n : '';\n console.log(`[HotReload] initial type map generation failed: ${String(err)}${hint}`, 'red');\n } else {\n console.log(`[HotReload] type map ready in background`, 'green');\n }\n })();\n });\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport * as ts from 'typescript';\nimport { ROOT_DIR, getGeneratedSocketTypesPath, getSrcDir, validatePagePath } from '@luckystack/core';\nimport {\n ROUTE_NAMING_EXAMPLES,\n ROUTE_NAMING_RULES,\n isVersionedApiFileName,\n isVersionedSyncClientFileName,\n isVersionedSyncFileName,\n isVersionedSyncServerFileName,\n} from './routeConventions';\nimport { getRoutingRules, isRouteTestFile } from './routingRules';\nimport {\n BUILT_IN_TEMPLATE_FILENAMES,\n getRegisteredTemplate,\n resolveTemplateKind,\n type BuiltInTemplateKind,\n type TemplateKind,\n type TemplateMatchContext,\n} from './templateRegistry';\n\n/**\n * Template Injector\n *\n * Injects default templates into new empty files in _api and _sync folders.\n * Handles sync file pairing with context-aware template selection.\n */\n\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst templatesDir = path.join(__dirname, 'templates');\n\n//? Consumer-side template overrides + selection rules live here (created by the\n//? scaffold). Resolved relative to the project root so it is stable regardless\n//? of the srcDir layout.\nconst getConsumerTemplatesDir = (): string => path.join(ROOT_DIR, '.luckystack', 'templates');\n\n//? Candidate content filenames for a kind: built-ins have a fixed name; custom\n//? kinds resolve to `<kind>.template.tsx` then `<kind>.template.ts`.\nconst templateContentFilenames = (kind: TemplateKind): string[] => {\n const builtIn = BUILT_IN_TEMPLATE_FILENAMES[kind as BuiltInTemplateKind];\n if (builtIn) return [builtIn];\n return [`${kind}.template.tsx`, `${kind}.template.ts`];\n};\n\n//? Resolve raw template content for a kind. Order: consumer file (editable,\n//? shipped to `.luckystack/templates/`) -> registered string override ->\n//? bundled dist template (built-in kinds only). Returns null when nothing\n//? resolves (e.g. a custom kind with no content provided).\nconst resolveTemplateContent = (kind: TemplateKind): string | null => {\n const consumerDir = getConsumerTemplatesDir();\n for (const fileName of templateContentFilenames(kind)) {\n const consumerFile = path.join(consumerDir, fileName);\n if (fs.existsSync(consumerFile)) {\n try {\n return fs.readFileSync(consumerFile, 'utf8');\n } catch (error) {\n console.error(`[TemplateInjector] Could not read consumer template: ${consumerFile}`, error);\n }\n }\n }\n\n const override = getRegisteredTemplate(kind);\n if (override !== null) return override;\n\n const builtInName = BUILT_IN_TEMPLATE_FILENAMES[kind as BuiltInTemplateKind];\n if (builtInName) {\n const bundled = path.join(templatesDir, builtInName);\n try {\n return fs.readFileSync(bundled, 'utf8');\n } catch (error) {\n console.error(`[TemplateInjector] Could not read bundled template: ${bundled}`, error);\n return null;\n }\n }\n\n console.warn(`[TemplateInjector] No content for custom template kind \"${kind}\" — add .luckystack/templates/${kind}.template.tsx or call registerTemplate('${kind}', ...).`);\n return null;\n};\n\n//? Dev-only: load the consumer's `.luckystack/templates/templateRules.ts` once,\n//? so their register* calls configure the injector before the first injection.\n//? Absent file => built-in defaults apply. Never imported in prod (devkit is a\n//? devDependency, and this only runs from the dev watcher path).\nlet consumerTemplateConfig: Promise<void> | null = null;\nconst ensureConsumerTemplateConfigLoaded = (): Promise<void> => {\n consumerTemplateConfig ??= (async () => {\n const dir = getConsumerTemplatesDir();\n for (const fileName of ['templateRules.ts', 'templateRules.mjs', 'templateRules.js']) {\n const rulesFile = path.join(dir, fileName);\n if (!fs.existsSync(rulesFile)) continue;\n\n //? Safety net: verify the resolved path stays within ROOT_DIR before\n //? dynamic-importing it. In practice `dir` is always\n //? `path.join(ROOT_DIR, '.luckystack', 'templates')` (see\n //? `getConsumerTemplatesDir`), so this check can only fail if ROOT_DIR\n //? itself is misconfigured or a symlink escapes the tree.\n const resolvedRulesFile = path.resolve(rulesFile);\n const resolvedRoot = path.resolve(ROOT_DIR);\n if (\n !resolvedRulesFile.startsWith(resolvedRoot + path.sep)\n && resolvedRulesFile !== resolvedRoot\n ) {\n console.warn(\n `[TemplateInjector] Template rules file resolves outside project root — skipping: ${rulesFile}`,\n );\n continue;\n }\n\n try {\n await import(pathToFileURL(rulesFile).href);\n } catch (error) {\n console.error(`[TemplateInjector] Failed to load consumer template rules: ${rulesFile}`, error);\n }\n return;\n }\n })();\n return consumerTemplateConfig;\n};\n\nexport const isEmptyFile = (filePath: string): boolean => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n return content.trim().length === 0;\n } catch {\n return false;\n }\n};\n\nconst isCommentOnlyFile = (filePath: string): boolean => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n const withoutBlockComments = content.replaceAll(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const withoutLineComments = withoutBlockComments.replaceAll(/(^|\\s)\\/\\/.*$/gm, '$1');\n return withoutLineComments.trim().length === 0;\n } catch {\n return false;\n }\n};\n\nexport const isInApiFolder = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n return normalized.includes('/_api/') && filePath.endsWith('.ts') && !isRouteTestFile(filePath);\n};\n\nexport const isInSyncFolder = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n return normalized.includes('/_sync/') && filePath.endsWith('.ts') && !isRouteTestFile(filePath);\n};\n\nexport const isPageFile = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const filename = normalized.split('/').pop() ?? '';\n return filename === 'page.tsx' || filename === 'page.jsx';\n};\n\nexport const isSyncServerFile = (filePath: string): boolean => {\n return isVersionedSyncServerFileName(filePath);\n};\n\nexport const isSyncClientFile = (filePath: string): boolean => {\n return isVersionedSyncClientFileName(filePath);\n};\n\nconst isVersionedApiFile = (filePath: string): boolean => {\n return isVersionedApiFileName(filePath);\n};\n\nconst isVersionedSyncFile = (filePath: string): boolean => {\n return isVersionedSyncFileName(filePath);\n};\n\nconst getFileName = (filePath: string): string => {\n return path.basename(filePath.replaceAll('\\\\', '/'));\n};\n\nconst stripTsExtension = (fileName: string): string => {\n return fileName.replace(/\\.ts$/, '');\n};\n\nconst toApiBaseName = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n const withoutVersion = withoutExtension.replace(/_v\\d+$/, '');\n return withoutVersion || 'myApi';\n};\n\nconst toSyncBaseName = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n const withoutVersionedKind = withoutExtension.replace(/_(?:server|client)_v\\d+$/, '');\n const withoutKindOnly = withoutVersionedKind.replace(/_(?:server|client)$/, '');\n const withoutVersionOnly = withoutKindOnly.replace(/_v\\d+$/, '');\n return withoutVersionOnly || 'mySync';\n};\n\nconst getApiFilenameReason = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n\n if (/_v\\d+$/.test(withoutExtension)) {\n return 'The filename already looks versioned.';\n }\n\n if (/_v\\d+/.test(withoutExtension)) {\n return 'The version token must be at the end of the filename.';\n }\n\n if (/_server|_client/.test(withoutExtension)) {\n return 'API files do not use _server/_client suffixes.';\n }\n\n return 'Missing required version suffix.';\n};\n\nconst getSyncFilenameReason = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n\n if (/_(?:server|client)_v\\d+$/.test(withoutExtension)) {\n return 'The filename already looks versioned.';\n }\n\n if (/_(?:server|client)$/.test(withoutExtension)) {\n return 'Sync files with _server/_client must include a version suffix like _v1.';\n }\n\n if (/_v\\d+$/.test(withoutExtension)) {\n return 'Sync files with versions must also include _server or _client.';\n }\n\n return 'Missing required sync kind and version suffix.';\n};\n\nexport const getRouteFilenameValidationMessage = (filePath: string): string | null => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const fileName = getFileName(normalized);\n\n if (isInApiFolder(normalized) && !isVersionedApiFile(normalized)) {\n const base = toApiBaseName(fileName);\n return [\n `Invalid API filename: ${fileName}`,\n `Reason: ${getApiFilenameReason(fileName)}`,\n `Expected: ${ROUTE_NAMING_RULES.api}`,\n `Example: ${base}_v1.ts (for example ${ROUTE_NAMING_EXAMPLES.api})`,\n 'This file is ignored by route loading and type generation until it is renamed.'\n ].join(' ');\n }\n\n if (isInSyncFolder(normalized) && !isVersionedSyncFile(normalized)) {\n const base = toSyncBaseName(fileName);\n return [\n `Invalid sync filename: ${fileName}`,\n `Reason: ${getSyncFilenameReason(fileName)}`,\n `Expected: ${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n `Examples: ${base}_server_v1.ts, ${base}_client_v1.ts (for example ${ROUTE_NAMING_EXAMPLES.syncServer})`,\n 'This file is ignored by route loading and type generation until it is renamed.'\n ].join(' ');\n }\n\n return null;\n};\n\nconst getInvalidVersionMessage = (filePath: string): string => {\n const validationMessage = getRouteFilenameValidationMessage(filePath) ?? 'Invalid route filename.';\n return `// ${validationMessage}\\n`;\n};\n\n//? Compute the validator-friendly path (relative to `src/`, forward slashes)\n//? for a page file. Returns `null` if the file is outside `getSrcDir()`.\nconst computeSrcRelativePath = (filePath: string): string | null => {\n try {\n const srcDir = getSrcDir();\n const absolute = path.resolve(filePath);\n const normalizedSrc = srcDir.replaceAll('\\\\', '/');\n const normalizedAbs = absolute.replaceAll('\\\\', '/');\n if (!normalizedAbs.startsWith(`${normalizedSrc}/`)) return null;\n return normalizedAbs.slice(normalizedSrc.length + 1);\n } catch {\n return null;\n }\n};\n\n//? Mirror of `getInvalidVersionMessage` for page.tsx files placed in\n//? locations the framework router will silently skip. Instead of writing\n//? the plain/dashboard template (which would render fine but never get\n//? routed), we write a commented diagnostic block so the developer\n//? immediately sees WHY their page isn't appearing.\nconst getInvalidPagePlacementMessage = (_filePath: string, reason: string, srcRelative: string): string => {\n const lines = [\n '//? --- LUCKYSTACK PLACEMENT WARNING ---',\n '//? This page.tsx is in a location the file-based router will not route.',\n `//? Reason: ${reason}`,\n `//? Path: ${srcRelative}`,\n '//?',\n '//? Common fixes:',\n \"//? - Move the file up so a visible (non-underscore) folder segment remains:\",\n \"//? e.g. src/_marketing/page.tsx -> src/_marketing/landing/page.tsx\",\n \"//? (the new file routes at /landing — `_marketing` stays invisible).\",\n \"//? - Or move the file OUT of a reserved framework folder (_api, _sync,\",\n \"//? _components, _functions, _shared, _providers, _locales, _sockets, _server).\",\n '//?',\n '//? Delete the file or move it to fix; the dev server will re-inject a',\n '//? real page template once the placement is valid.',\n '',\n //? Named export instead of `export {};` so the file satisfies\n //? `unicorn/require-module-specifiers` (and stays a valid ES module\n //? without dragging in side-effect-only semantics). Reads back as a\n //? cheap runtime tag for tooling that wants to detect the warning.\n \"export const __luckystackPlacementWarning = true;\",\n '',\n ];\n return lines.join('\\n');\n};\n\n/**\n * Get the paired sync file path (server -> client or client -> server)\n */\nexport const getPairedSyncFile = (filePath: string): string | null => {\n const normalized = filePath.replaceAll('\\\\', '/');\n if (isSyncServerFile(normalized)) {\n return normalized.replace(/_server_v(\\d+)\\.ts$/, '_client_v$1.ts');\n }\n if (isSyncClientFile(normalized)) {\n return normalized.replace(/_client_v(\\d+)\\.ts$/, '_server_v$1.ts');\n }\n return null;\n};\n\n/**\n * Check if a paired sync file exists\n */\nexport const hasPairedFile = (filePath: string): boolean => {\n const pairedPath = getPairedSyncFile(filePath);\n if (!pairedPath) return false;\n return fs.existsSync(pairedPath);\n};\n\n/**\n * Extract page path from a sync file path (e.g., \"examples\" from \"src/examples/_sync/test_server_v1.ts\")\n */\nexport const extractSyncPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /src\\/(.+?)\\/_sync\\//.exec(normalized);\n if (match?.[1]) return match[1];\n //? A sync directly under `src/_sync/` resolves to the `'system'` sentinel —\n //? the SAME page key the type-map generator (`routeMeta.extractSyncPagePath`)\n //? and the dev loader use for root syncs. Returning `''` here injected\n //? `type PagePath = '';` into the paired client/server template, which then\n //? failed to index `SyncTypeMap['system']` — a broken generated reference.\n if (/(?:^|\\/)src\\/_sync\\//.test(normalized)) return 'system';\n return '';\n};\n\n/**\n * Extract sync name from a sync file path (e.g., \"test\" from \"src/examples/_sync/test_server_v1.ts\")\n */\nexport const extractSyncName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_sync\\/(.+)\\.ts$/.exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n return basename.replace(/_server_v\\d+$/, '').replace(/_client_v\\d+$/, '');\n }\n\n return (match[1] ?? '').replace(/_server_v\\d+$/, '').replace(/_client_v\\d+$/, '');\n};\n\n/**\n * Extract clientInput type body from a sync file's SyncParams interface\n * Returns the content between the braces of clientInput: { ... }\n */\nexport const extractClientInputFromFile = (filePath: string): string | null => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n\n // Find interface SyncParams\n const syncParamsMatch = /interface\\s+SyncParams\\s*\\{/.exec(content);\n if (!syncParamsMatch) return null;\n\n //? Scope the `clientInput` search to the region AFTER the `SyncParams`\n //? declaration. An unscoped global search could match a `clientInput:` in\n //? an earlier comment, a different interface, or a destructure above the\n //? `SyncParams` body and extract the wrong block.\n const searchRegion = content.slice(syncParamsMatch.index + syncParamsMatch[0].length);\n const clientInputMatch = /clientInput\\s*:\\s*\\{/.exec(searchRegion);\n if (!clientInputMatch) return null;\n\n // Extract balanced braces\n const startIndex = content.indexOf(\n '{',\n syncParamsMatch.index + syncParamsMatch[0].length + clientInputMatch.index,\n );\n if (startIndex === -1) return null;\n let depth = 0;\n let endIndex = -1;\n\n for (let i = startIndex; i < content.length; i++) {\n if (content[i] === '{') depth++;\n else if (content[i] === '}') depth--;\n\n if (depth === 0) {\n endIndex = i;\n break;\n }\n }\n\n //? Braces never balanced (truncated / malformed file) — return null rather\n //? than a single `{` of garbage that a truthiness-checking caller would\n //? splice into user source.\n if (endIndex === -1) return null;\n\n return content.slice(startIndex, endIndex + 1);\n } catch (error) {\n console.error(`[TemplateInjector] Error extracting clientInput from ${filePath}:`, error);\n return null;\n }\n};\n\n/**\n * Extract clientInput type from the generated apiTypes.generated.ts file\n * Used when the server file is already deleted but we need to migrate types to client\n */\nexport const extractClientInputFromGeneratedTypes = (pagePath: string, syncName: string): string | null => {\n try {\n const generatedTypesPath = getGeneratedSocketTypesPath();\n const content = fs.readFileSync(generatedTypesPath, 'utf8');\n\n const escapeRegex = (value: string) => value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n const escapedPagePath = escapeRegex(pagePath);\n const escapedSyncName = escapeRegex(syncName);\n\n const pageBlockRegex = new RegExp(String.raw`'${escapedPagePath}'\\s*:\\s*\\{([\\s\\S]*?)\\n\\s{2}\\};`, 'm');\n const pageBlockMatch = content.match(pageBlockRegex);\n if (!pageBlockMatch?.[1]) {\n console.log(`[TemplateInjector] Could not find page block for ${pagePath}`);\n return null;\n }\n\n const pageBlock = pageBlockMatch[1];\n\n const syncEntryPattern = new RegExp(String.raw`'${escapedSyncName}':\\s*\\{\\s*clientInput:\\s*`);\n const match = pageBlock.match(syncEntryPattern);\n\n if (!match || typeof match.index !== 'number') {\n console.log(`[TemplateInjector] Could not find sync entry for ${pagePath}/${syncName}`);\n return null;\n }\n\n const pageStart = content.indexOf(pageBlock);\n const globalMatchIndex = pageStart + match.index;\n\n // Find the start of clientInput value (the opening brace)\n const searchStart = globalMatchIndex + match[0].length;\n const braceStart = content.indexOf('{', searchStart - 1);\n\n if (braceStart === -1) return null;\n\n // Extract balanced braces\n let depth = 0;\n let endIndex = -1;\n\n for (let i = braceStart; i < content.length; i++) {\n if (content[i] === '{') depth++;\n else if (content[i] === '}') depth--;\n\n if (depth === 0) {\n endIndex = i;\n break;\n }\n }\n\n //? Braces never balanced — return null instead of a lone `{` of garbage.\n if (endIndex === -1) return null;\n\n const extracted = content.slice(braceStart, endIndex + 1);\n console.log(`[TemplateInjector] Extracted clientInput types: ${extracted}`);\n return extracted;\n } catch (error) {\n console.error(`[TemplateInjector] Error extracting clientInput from generated types:`, error);\n return null;\n }\n};\n\n/**\n * Calculate the relative path prefix (e.g., '../../../') to reach project root from a file\n * @param filePath - Absolute or relative path to the file\n * @returns The relative path prefix to reach project root\n */\nexport const calculateRelativePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n\n //? Anchor on the CONFIGURED srcDir, not the literal substring `src/`. A\n //? non-`src` layout (`srcDir: 'app'`) or a root path that itself contains\n //? `src/` (`C:/work/srcrepo/...`) computed the wrong depth with the old\n //? `indexOf('src/')`, breaking the injected `{{REL_PATH}}` import. Reuse the\n //? same srcDir-driven anchoring the rest of the package uses (mirrors\n //? `computeSrcRelativePath`). For the standard `src` layout this is\n //? byte-identical to the old heuristic.\n const srcRelative = computeSrcRelativePath(filePath);\n if (srcRelative !== null) {\n try {\n const srcDepthFromRoot = path\n .relative(ROOT_DIR, getSrcDir())\n .replaceAll('\\\\', '/')\n .split('/')\n .filter((segment) => segment.length > 0).length;\n //? `srcRelative` is `<dirs.../file.ts>` relative to srcDir. The number of\n //? `../` to climb from the FILE's directory up to srcDir is the count of\n //? its DIRECTORY segments (drop the trailing filename). Adding srcDir's\n //? own depth below the project root gives the climb to root — the template\n //? then re-descends via the literal `src/` it appends after `{{REL_PATH}}`.\n const dirSegmentsAfterSrc = Math.max(\n 0,\n srcRelative.split('/').filter((segment) => segment.length > 0).length - 1,\n );\n return '../'.repeat(srcDepthFromRoot + dirSegmentsAfterSrc);\n } catch {\n //? Fall through to the literal-`src/` heuristic below.\n }\n }\n\n // Fallback (relative path the watcher handed us, or srcDir unresolvable):\n // Find the 'src/' part of the path\n const srcIndex = normalized.indexOf('src/');\n if (srcIndex === -1) {\n // Fallback: count from beginning if src not found\n console.warn(`[TemplateInjector] Could not find /src/ in path: ${filePath}`);\n return '../../../'; // default fallback\n }\n\n // Get path after 'src/' (e.g., 'examples/examples2/_api/file.ts')\n const relativePath = normalized.slice(Math.max(0, srcIndex + 4)); // +4 to skip 'src/'\n\n // Count segments (directories + filename)\n const segments = relativePath.split('/').filter(s => s.length > 0).length;\n\n // We need to go up `segments` levels to reach project root\n // e.g., 'examples/_api/file.ts' = 3 segments -> '../../../'\n return '../'.repeat(segments);\n};\n\n// ---------------------------------------------------------------------------\n// File classification helpers\n// ---------------------------------------------------------------------------\n\ntype FileClassification =\n | { fileKind: 'api'; hasPairedServer: false; srcRelativePath: null }\n | { fileKind: 'sync_server'; hasPairedServer: false; srcRelativePath: null }\n | { fileKind: 'sync_client'; hasPairedServer: boolean; srcRelativePath: null }\n | { fileKind: 'page'; hasPairedServer: false; srcRelativePath: string | null }\n | null;\n\n/**\n * Determines the structural file kind and paired-server presence for template selection.\n * Returns null for files that should not receive a template.\n */\nconst classifyFile = (filePath: string): FileClassification => {\n if (isInApiFolder(filePath)) {\n return { fileKind: 'api', hasPairedServer: false, srcRelativePath: null };\n }\n\n if (isInSyncFolder(filePath)) {\n if (isSyncServerFile(filePath)) {\n return { fileKind: 'sync_server', hasPairedServer: false, srcRelativePath: null };\n }\n if (isSyncClientFile(filePath)) {\n return { fileKind: 'sync_client', hasPairedServer: hasPairedFile(filePath), srcRelativePath: null };\n }\n console.log(`[TemplateInjector] Unknown sync file type: ${filePath}`);\n return null;\n }\n\n if (isPageFile(filePath)) {\n return { fileKind: 'page', hasPairedServer: false, srcRelativePath: computeSrcRelativePath(filePath) };\n }\n\n return null;\n};\n\n/**\n * Validates page placement for a classified page file.\n * Returns the placement-warning content when the page is un-routable, null when valid.\n */\nconst checkPagePlacement = (filePath: string, srcRelativePath: string | null): string | null => {\n if (srcRelativePath === null) return null;\n const placement = validatePagePath(srcRelativePath);\n if (!placement.valid) {\n return getInvalidPagePlacementMessage(filePath, placement.reason ?? 'invalid placement', srcRelativePath);\n }\n return null;\n};\n\n/**\n * Substitutes `{{REL_PATH}}`, `{{PAGE_PATH}}`, and `{{SYNC_NAME}}` placeholders\n * in a raw template string. Also strips `@ts-ignore`/`@ts-expect-error` pragma\n * lines that guard `{{REL_PATH}}` imports in built-in templates.\n */\nconst applyTemplatePlaceholders = (\n content: string,\n filePath: string,\n fileKind: TemplateMatchContext['fileKind'],\n): string => {\n const relPath = calculateRelativePath(filePath);\n const pragmaPattern = /\\/\\/\\s*@ts-(?:ignore|expect-error).*\\r?\\n(.*)\\{\\{REL_PATH\\}\\}/g;\n let result = content.replaceAll(pragmaPattern, (_, prefix) => `${prefix}${relPath}`);\n result = result.replaceAll('{{REL_PATH}}', relPath);\n\n //? Sync templates may carry PAGE_PATH / SYNC_NAME placeholders (paired client\n //? + server). Substitute for any sync file — a no-op when the placeholders\n //? are absent (e.g. standalone client).\n if (fileKind === 'sync_client' || fileKind === 'sync_server') {\n const pagePath = extractSyncPagePath(filePath);\n const syncName = extractSyncName(filePath);\n result = result.replaceAll('{{PAGE_PATH}}', pagePath);\n result = result.replaceAll('{{SYNC_NAME}}', syncName);\n }\n\n return result;\n};\n\nconst getTemplate = (filePath: string): string | null => {\n //? Classify the file structurally; the registered selection RULES then decide\n //? the kind (consumer-editable via `.luckystack/templates/templateRules.ts`).\n const classification = classifyFile(filePath);\n if (!classification) return null;\n\n const { fileKind, hasPairedServer, srcRelativePath } = classification;\n\n //? Validate page placement BEFORE rule selection. A page inside a reserved\n //? framework folder (`_api`, `_sync`, ...) or with no URL segment left\n //? after stripping invisible-parent folders is silently un-routed — so we\n //? emit a commented diagnostic instead of a dead plain/dashboard skeleton.\n if (fileKind === 'page') {\n const placementWarning = checkPagePlacement(filePath, srcRelativePath);\n if (placementWarning !== null) return placementWarning;\n }\n\n const ctx: TemplateMatchContext = { filePath, fileKind, hasPairedServer, srcRelativePath };\n const templateKind = resolveTemplateKind(ctx);\n if (!templateKind) {\n console.log(`[TemplateInjector] No template rule matched for ${filePath} (fileKind=${fileKind})`);\n return null;\n }\n\n const rawContent = resolveTemplateContent(templateKind);\n if (rawContent === null) return null;\n\n return applyTemplatePlaceholders(rawContent, filePath, fileKind);\n};\n\nexport const injectTemplate = async (filePath: string): Promise<boolean> => {\n await ensureConsumerTemplateConfigLoaded();\n\n if (getRouteFilenameValidationMessage(filePath)) {\n fs.writeFileSync(filePath, getInvalidVersionMessage(filePath), 'utf8');\n console.log(`[TemplateInjector] Invalid route filename, injected guidance: ${filePath}`);\n return true;\n }\n\n const template = getTemplate(filePath);\n\n if (!template) {\n return false;\n }\n\n try {\n fs.writeFileSync(filePath, template, 'utf8');\n console.log(`[TemplateInjector] Injected template into: ${filePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to inject template: ${filePath}`, error);\n return false;\n }\n};\n\nexport const shouldInjectTemplate = (\n filePath: string,\n options: { isNewFile?: boolean } = {},\n): boolean => {\n //? Consumer disable hook — if `registerRoutingRules({ disableTemplateInjection })`\n //? was called with a predicate that returns true for this path, skip the\n //? injection entirely. Useful for files the consumer manages by hand\n //? (e.g. a generated migrations tree).\n const { disableTemplateInjection } = getRoutingRules();\n if (disableTemplateInjection?.(filePath)) {\n return false;\n }\n\n if (!(isInApiFolder(filePath) || isInSyncFolder(filePath) || isPageFile(filePath))) {\n return false;\n }\n\n //? An EMPTY file is always safe to template (there is nothing to lose).\n if (isEmptyFile(filePath)) return true;\n\n //? A COMMENT-ONLY file is only templated when it is genuinely NEW (the `add`\n //? event). Commenting out an entire EXISTING `_api`/`_sync`/`page` file and\n //? saving it (a common debugging move) fires a `change` event with\n //? comment-only content — injecting the starter template there silently\n //? OVERWRITES the user's commented-out code with no undo (data loss). On\n //? `add` there is no prior route entry to clobber, so it stays safe.\n if (options.isNewFile) return isCommentOnlyFile(filePath);\n\n return false;\n};\n\n// ---------------------------------------------------------------------------\n// Paired-client rewrite helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Ensures `SyncClientInput` and `SyncServerOutput` are imported from the\n * generated types file. Prepends a new import line when the single-line\n * regex misses multi-line or namespace variants.\n */\nconst ensureImportedTypes = (content: string, clientFilePath: string): string => {\n if (content.includes('SyncClientInput')) return content;\n\n let result = content.replace(\n /import \\{([^}]+)\\} from ['\"]([^'\"]*apiTypes\\.generated)['\"]/,\n (_match, imports: string, importPath: string) => {\n return `import {${imports}, SyncClientInput, SyncServerOutput } from '${importPath}'`;\n }\n );\n\n //? Safety net: the single-line regex above misses multi-line, `type`-only,\n //? or namespace imports. When it misses, prepend a fresh import so the\n //? rewritten `clientInput`/`serverOutput` references always resolve.\n if (!result.includes('SyncClientInput')) {\n const relPath = calculateRelativePath(clientFilePath);\n result = `import { SyncClientInput, SyncServerOutput } from '${relPath}src/_sockets/apiTypes.generated';\\n` + result;\n }\n\n return result;\n};\n\n/**\n * Inserts `PagePath` and `SyncName` type aliases after the last import\n * statement, when they are not already present.\n */\nconst insertTypeAliases = (content: string, pagePath: string, syncName: string): string => {\n if (content.includes('type PagePath')) return content;\n\n const importEndMatch = content.match(/import .+?;[\\r\\n]+/g);\n if (!importEndMatch) return content;\n\n const lastImport = importEndMatch.at(-1);\n if (!lastImport) return content;\n\n const lastImportEnd = content.lastIndexOf(lastImport) + lastImport.length;\n const typeAliases = `\\n// Types are imported from the generated file based on the _server.ts definition\\ntype PagePath = '${pagePath}';\\ntype SyncName = '${syncName}';\\n`;\n return content.slice(0, lastImportEnd) + typeAliases + content.slice(lastImportEnd);\n};\n\n/**\n * Regex fallback: replaces the inline `clientInput: { ... }` type block with\n * the generated type reference `SyncClientInput<PagePath, SyncName>`.\n * Only handles single-line object types; multi-line types require the AST path.\n */\nconst rewriteClientInputType = (content: string): string => {\n return content.replace(\n /^(\\s*)clientInput:\\s*\\{[^}]*\\}/m,\n '$1clientInput: SyncClientInput<PagePath, SyncName>'\n );\n};\n\n/**\n * Replaces the `clientInput` property type in the `SyncParams` interface using\n * the TypeScript AST. Locates the `clientInput` `PropertySignature` inside\n * `SyncParams` via the parser, extracts its type node's source span, and\n * performs a targeted character-position replacement — preserving the rest of\n * the source text verbatim (whitespace, comments, etc.).\n *\n * Returns the rewritten source on success, or `null` when:\n * - the file cannot be parsed\n * - `SyncParams` or `clientInput` is not found\n * - the existing type is not a `TypeLiteralNode` (already migrated → skip)\n * - the re-parsed result still contains a type literal (rewrite did not take)\n *\n * Callers must leave the file untouched and log the failure when `null` is\n * returned.\n */\nconst rewriteClientInputTypeAst = (content: string, sourceFileName: string): string | null => {\n // Parse to an AST (syntactic only — no type-checker needed).\n const parseSource = (src: string) =>\n ts.createSourceFile(\n sourceFileName,\n src,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n const sourceFile = parseSource(content);\n\n // Locate `SyncParams` interface.\n let syncParamsInterface: ts.InterfaceDeclaration | undefined;\n for (const stmt of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SyncParams') {\n syncParamsInterface = stmt;\n break;\n }\n }\n\n if (!syncParamsInterface) return null;\n\n // Locate `clientInput` property signature.\n let clientInputMember: ts.PropertySignature | undefined;\n for (const member of syncParamsInterface.members) {\n if (\n ts.isPropertySignature(member)\n && ts.isIdentifier(member.name)\n && member.name.text === 'clientInput'\n ) {\n clientInputMember = member;\n break;\n }\n }\n\n if (!clientInputMember?.type) return null;\n\n //? Only replace object-literal type nodes ( `{ ... }` ) — already-migrated\n //? files that carry `SyncClientInput<PagePath, SyncName>` are left untouched.\n if (!ts.isTypeLiteralNode(clientInputMember.type)) return null;\n\n // Use the type node's AST span for a targeted position replacement so the\n // rest of the file's whitespace and comments are preserved verbatim.\n const typeNode = clientInputMember.type;\n const start = typeNode.getStart(sourceFile);\n const end = typeNode.getEnd();\n\n const rewritten = `${content.slice(0, start)}SyncClientInput<PagePath, SyncName>${content.slice(end)}`;\n\n // Re-parse the rewritten source to verify it is syntactically valid before\n // handing it back to the caller (who will write it to disk).\n // Use a throw-away single-file program so we can call the public\n // `getSyntacticDiagnostics` API (instead of the private `parseDiagnostics`).\n const reparsedFile = parseSource(rewritten);\n const verifyProgram = ts.createProgram({\n rootNames: [sourceFileName],\n options: { noResolve: true, skipLibCheck: true },\n // Supply the in-memory source so `ts.createProgram` never touches the disk.\n host: {\n ...ts.createCompilerHost({}),\n getSourceFile: (name) => (name === sourceFileName ? reparsedFile : undefined),\n fileExists: (name) => name === sourceFileName,\n readFile: (name) => (name === sourceFileName ? rewritten : undefined),\n },\n });\n const syntaxErrors = verifyProgram.getSyntacticDiagnostics(reparsedFile);\n if (syntaxErrors.length > 0) {\n console.log(\n `[TemplateInjector] AST rewrite produced invalid TypeScript for ${sourceFileName} — leaving untouched`,\n 'yellow',\n );\n return null;\n }\n\n return rewritten;\n};\n\n/**\n * Adds `serverOutput: SyncServerOutput<PagePath, SyncName>` to the SyncParams\n * interface when not already present.\n */\nconst addServerOutputToParams = (content: string): string => {\n if (content.includes('serverOutput:')) return content;\n return content.replace(\n /^(\\s*)(clientInput:\\s*SyncClientInput<PagePath, SyncName>);?\\s*$/m,\n '$1$2;\\n$1serverOutput: SyncServerOutput<PagePath, SyncName>;'\n );\n};\n\n/**\n * Adds `serverOutput` to the main function destructuring when not already present.\n */\nconst addServerOutputToDestructuring = (content: string): string => {\n if (!content.includes('main') || /\\{\\s*[^}]*serverOutput[^}]*\\}\\s*:\\s*SyncParams/.test(content)) {\n return content;\n }\n return content.replace(\n /\\{\\s*([^}]*?clientInput)([^}]*)\\}\\s*:\\s*SyncParams/,\n '{ $1, serverOutput$2 }: SyncParams'\n );\n};\n\n/**\n * Update a client file to use the paired template (imports types from generated file)\n * Called when a _server.ts is created and _client.ts already exists\n * PRESERVES user's main function code!\n */\n// eslint-disable-next-line @typescript-eslint/require-await -- async signature keeps the public interface awaitable for future I/O expansion\nexport const updateClientFileForPairedServer = async (clientFilePath: string): Promise<boolean> => {\n try {\n const pagePath = extractSyncPagePath(clientFilePath);\n const syncName = extractSyncName(clientFilePath);\n\n let content = fs.readFileSync(clientFilePath, 'utf8');\n\n content = ensureImportedTypes(content, clientFilePath);\n content = insertTypeAliases(content, pagePath, syncName);\n\n // Prefer AST-based rewrite (type-aware, handles multi-line object types).\n // Fall back to the regex path only when the AST cannot locate the node\n // (e.g. non-standard structure) so the most common cases always benefit\n // from the precise position replacement.\n const astResult = rewriteClientInputTypeAst(content, path.basename(clientFilePath));\n if (astResult === null) {\n console.log(\n `[TemplateInjector] AST clientInput rewrite unavailable for ${clientFilePath} — using regex fallback`,\n 'yellow',\n );\n content = rewriteClientInputType(content);\n } else {\n content = astResult;\n }\n\n content = addServerOutputToParams(content);\n content = addServerOutputToDestructuring(content);\n\n fs.writeFileSync(clientFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Updated client file to use paired types (preserved code): ${clientFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to update client file: ${clientFilePath}`, error);\n return false;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Deleted-server cleanup helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Replaces the `clientInput` type (either a generated reference or an inline block)\n * with the supplied inline type block.\n */\nconst inlineClientInputType = (content: string, clientInputTypes: string): string => {\n // Use replacer functions so `$`-sequences in `clientInputTypes` (Prisma `$Enums.Role`,\n // template-literal `${...}` types) are spliced verbatim, not re-interpreted as backrefs.\n return content\n .replace(\n /^(\\s*)clientInput:\\s*SyncClientInput<[^>]+>/m,\n (_match, indent: string) => `${indent}clientInput: ${clientInputTypes}`\n )\n .replace(\n /^(\\s*)clientInput:\\s*\\{[^}]*\\}/m,\n (_match, indent: string) => `${indent}clientInput: ${clientInputTypes}`\n );\n};\n\n/**\n * Removes `serverOutput` lines from the SyncParams interface body.\n */\nconst removeServerOutputFromParams = (content: string): string => {\n return content\n .replace(/^[ \\t]*serverOutput:\\s*SyncServerOutput<[^>]+>;?\\s*\\r?\\n?/m, '')\n .replace(/^[ \\t]*serverOutput:\\s*\\{[^}]*\\};?\\s*\\r?\\n?/m, '');\n};\n\n/**\n * Removes `serverOutput` from the main function destructuring.\n */\nconst removeServerOutputFromDestructuring = (content: string): string => {\n return content\n .replaceAll(/,\\s*serverOutput(?=\\s*[,}])/g, '')\n .replaceAll(/serverOutput\\s*,\\s*/g, '');\n};\n\n/**\n * Strips `SyncClientInput` and `SyncServerOutput` from import statements.\n */\nconst removeGeneratedTypeImports = (content: string): string => {\n return content\n .replaceAll(/,\\s*SyncClientInput(?=\\s*[,}])/g, '')\n .replaceAll(/,\\s*SyncServerOutput(?=\\s*[,}])/g, '');\n};\n\n/**\n * Removes the injected `PagePath` / `SyncName` type alias comment and declarations.\n */\nconst removeTypeAliases = (content: string): string => {\n let result = content.replaceAll(/\\/\\/\\s*Types are imported.*\\n?/g, '');\n result = result.replaceAll(/type PagePath = '[^']*';\\s*\\n?/g, '');\n return result.replaceAll(/type SyncName = '[^']*';\\s*\\n?/g, '');\n};\n\n/**\n * Update a client file when the paired server file is deleted\n * Preserves user's main function code while:\n * - Inlining clientInput types\n * - Removing serverOutput from SyncParams and main function params\n */\n/* eslint-disable @typescript-eslint/require-await -- async signature keeps the public interface awaitable for future I/O expansion */\nexport const updateClientFileForDeletedServer = async (\n clientFilePath: string,\n clientInputTypes: string\n): Promise<boolean> => {\n try {\n let content = fs.readFileSync(clientFilePath, 'utf8');\n\n // Order matters: replace type references BEFORE removing imports/aliases.\n content = inlineClientInputType(content, clientInputTypes);\n content = removeServerOutputFromParams(content);\n content = removeServerOutputFromDestructuring(content);\n content = removeGeneratedTypeImports(content);\n content = removeTypeAliases(content);\n\n // Collapse runs of 3+ blank lines left by the removals.\n content = content.replaceAll(/\\n{3,}/g, '\\n\\n');\n\n fs.writeFileSync(clientFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Updated client file for deleted server (preserved code): ${clientFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to update client file: ${clientFilePath}`, error);\n return false;\n }\n};\n/* eslint-enable @typescript-eslint/require-await */\n\n/**\n * Inject server template with pre-filled clientInput types (from existing client file)\n */\nexport const injectServerTemplateWithClientInput = async (\n serverFilePath: string,\n clientInputTypes: string\n): Promise<boolean> => {\n try {\n await ensureConsumerTemplateConfigLoaded();\n const relPath = calculateRelativePath(serverFilePath);\n\n //? Honor consumer overrides for the sync_server kind here too (consumer\n //? file -> registered override -> bundled), then fill in the clientInput.\n let content = resolveTemplateContent('sync_server');\n if (content === null) {\n console.error(`[TemplateInjector] No sync_server template content available for: ${serverFilePath}`);\n return false;\n }\n\n //? Replace placeholders — same pragma union + literal-fallback pattern\n //? as `getTemplate` above. Keep these two regexes in sync.\n const pragmaPattern = /\\/\\/\\s*@ts-(?:ignore|expect-error).*\\r?\\n(.*)\\{\\{REL_PATH\\}\\}/g;\n content = content.replaceAll(pragmaPattern, (_, prefix) => {\n return `${prefix}${relPath}`;\n });\n content = content.replaceAll('{{REL_PATH}}', relPath);\n\n // Replace the empty clientInput with the provided types.\n // Use a replacer function so `$`-sequences in `clientInputTypes`\n // (Prisma `$Enums.Role`, template-literal `${...}` types) are spliced\n // verbatim instead of being re-interpreted as backreferences.\n content = content.replace(\n /clientInput:\\s*\\{[^}]*\\}/s,\n (_match) => `clientInput: ${clientInputTypes}`\n );\n\n fs.writeFileSync(serverFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Injected server template with clientInput: ${serverFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to inject server template: ${serverFilePath}`, error);\n return false;\n }\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR, getServerFunctionDirs, getSharedDir, getSrcDir } from '@luckystack/core';\n\nimport { getOrInit } from './internal/mapUtils';\n\nconst SUPPORTED_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts'];\n\nconst normalizePath = (value: string): string => path.resolve(value).replaceAll('\\\\', '/');\n\nconst isSupportedScriptFile = (value: string): boolean => {\n return SUPPORTED_EXTENSIONS.some((extension) => value.endsWith(extension));\n};\n\nconst existsFile = (value: string): boolean => {\n try {\n return fs.existsSync(value) && fs.statSync(value).isFile();\n } catch {\n return false;\n }\n};\n\nconst existsDirectory = (value: string): boolean => {\n try {\n return fs.existsSync(value) && fs.statSync(value).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectScriptFiles = (dir: string, output: Set<string>, visited = new Set<string>()): void => {\n if (!existsDirectory(dir)) {\n return;\n }\n\n // Resolve the real path to detect symlink cycles before descending.\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch {\n return;\n }\n if (visited.has(realDir)) return;\n visited.add(realDir);\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n // Skip node_modules to avoid crawling installed packages.\n if (entry.name === 'node_modules') continue;\n\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory() || entry.isSymbolicLink()) {\n if (existsDirectory(fullPath)) {\n collectScriptFiles(fullPath, output, visited);\n }\n continue;\n }\n\n const normalizedPath = normalizePath(fullPath);\n if (isSupportedScriptFile(normalizedPath)) {\n output.add(normalizedPath);\n }\n }\n};\n\ninterface CachedSpecifiers {\n mtimeMs: number;\n specifiers: string[];\n}\n\n//? Reverse-dependency lookups happen on every file save. Re-reading + regex-\n//? parsing every file in src/shared/serverFunctions per save adds tens of ms\n//? of synchronous IO. Cache per-file by mtime so unchanged files reuse the\n//? prior parse.\nconst specifiersCache = new Map<string, CachedSpecifiers>();\nlet scopedFilesCache: { files: Set<string>; expiresAt: number } | null = null;\nconst SCOPED_FILES_TTL_MS = 1000;\n\nconst extractImportSpecifiers = (filePath: string): string[] => {\n let mtimeMs = 0;\n try {\n mtimeMs = fs.statSync(filePath).mtimeMs;\n } catch {\n specifiersCache.delete(filePath);\n return [];\n }\n\n const cached = specifiersCache.get(filePath);\n if (cached?.mtimeMs === mtimeMs) {\n return cached.specifiers;\n }\n\n try {\n const source = fs.readFileSync(filePath, 'utf8');\n const specifiers = new Set<string>();\n\n // The `[\\s\\S]*?` allows the import clause to span multiple lines\n // (e.g. named imports broken across lines). The `[^'\"]+` keeps the\n // specifier itself single-line so malformed source can't over-greedily\n // consume closing quotes from later imports.\n const importExportRegex = /(?:import|export)\\s+(?:[\\s\\S]*?\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n const dynamicImportRegex = /import\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n let match: RegExpExecArray | null = null;\n\n while ((match = importExportRegex.exec(source)) !== null) {\n if (match[1]) specifiers.add(match[1]);\n }\n\n while ((match = dynamicImportRegex.exec(source)) !== null) {\n if (match[1]) specifiers.add(match[1]);\n }\n\n const result = [...specifiers];\n specifiersCache.set(filePath, { mtimeMs, specifiers: result });\n return result;\n } catch {\n specifiersCache.delete(filePath);\n return [];\n }\n};\n\nexport const invalidateGraphForFile = (absolutePath: string): void => {\n specifiersCache.delete(normalizePath(absolutePath));\n scopedFilesCache = null;\n};\n\nconst tryResolveWithExtensions = (basePath: string): string | null => {\n if (existsFile(basePath)) {\n return normalizePath(basePath);\n }\n\n for (const extension of SUPPORTED_EXTENSIONS) {\n const withExtension = `${basePath}${extension}`;\n if (existsFile(withExtension)) {\n return normalizePath(withExtension);\n }\n }\n\n if (existsDirectory(basePath)) {\n for (const extension of SUPPORTED_EXTENSIONS) {\n const indexFile = path.join(basePath, `index${extension}`);\n if (existsFile(indexFile)) {\n return normalizePath(indexFile);\n }\n }\n }\n\n return null;\n};\n\nconst resolveImportToFile = (importerPath: string, specifier: string): string | null => {\n if (!specifier || specifier.startsWith('node:')) {\n return null;\n }\n\n if (specifier === 'config') {\n return tryResolveWithExtensions(path.join(ROOT_DIR, 'config'));\n }\n\n if (specifier.startsWith('./') || specifier.startsWith('../')) {\n const relativeBase = path.resolve(path.dirname(importerPath), specifier);\n return tryResolveWithExtensions(relativeBase);\n }\n\n if (specifier.startsWith('src/') || specifier.startsWith('@/')) {\n const sourcePath = specifier.startsWith('@/') ? specifier.slice(2) : specifier.slice(4);\n return tryResolveWithExtensions(path.join(getSrcDir(), sourcePath));\n }\n\n if (specifier.startsWith('shared/')) {\n return tryResolveWithExtensions(path.join(getSharedDir(), specifier.slice(7)));\n }\n\n return null;\n};\n\nconst isRouteFile = (filePath: string): boolean => {\n return filePath.includes('/src/') && (filePath.includes('/_api/') || filePath.includes('/_sync/'));\n};\n\nconst collectScopedFiles = (): Set<string> => {\n const now = Date.now();\n if (scopedFilesCache && scopedFilesCache.expiresAt > now) {\n return scopedFilesCache.files;\n }\n\n const files = new Set<string>();\n collectScriptFiles(getSrcDir(), files);\n collectScriptFiles(getSharedDir(), files);\n for (const dir of getServerFunctionDirs()) {\n collectScriptFiles(dir, files);\n }\n\n const configFile = tryResolveWithExtensions(path.join(ROOT_DIR, 'config'));\n if (configFile) {\n files.add(configFile);\n }\n\n scopedFilesCache = { files, expiresAt: now + SCOPED_FILES_TTL_MS };\n return files;\n};\n\nexport const findDependentRouteFiles = (changedFilePath: string): Set<string> => {\n const scopedFiles = collectScopedFiles();\n const changedAbsolutePath = normalizePath(changedFilePath);\n\n const reverseDependencies = new Map<string, Set<string>>();\n\n for (const filePath of scopedFiles) {\n const specifiers = extractImportSpecifiers(filePath);\n\n for (const specifier of specifiers) {\n const resolvedImport = resolveImportToFile(filePath, specifier);\n if (!resolvedImport || !scopedFiles.has(resolvedImport)) {\n continue;\n }\n\n getOrInit(reverseDependencies, resolvedImport, () => new Set<string>()).add(filePath);\n }\n }\n\n const affectedRoutes = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [changedAbsolutePath];\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined) break;\n if (visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n const importers = reverseDependencies.get(current);\n if (!importers) {\n continue;\n }\n\n for (const importer of importers) {\n if (isRouteFile(importer)) {\n affectedRoutes.add(importer);\n }\n\n if (!visited.has(importer)) {\n queue.push(importer);\n }\n }\n }\n\n return affectedRoutes;\n};\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { ROOT_DIR, tryCatch } from '@luckystack/core';\n\n//? Where the Prisma generator writes its client by default: `node_modules/.prisma/\n//? client`. The DIRECTORY existing is NOT proof of generation — `@prisma/client`'s\n//? own postinstall writes an un-generated STUB there on a plain `npm install` (a\n//? throwing `PrismaClient` + no model types, no schema, no query engine). So we\n//? probe a marker that ONLY a real `prisma generate` produces: it copies the\n//? schema into the output dir as `.prisma/client/schema.prisma` (absent in the\n//? stub). That distinguishes \"generated\" from \"stub-only\".\nconst GENERATED_CLIENT_DIR = path.join(ROOT_DIR, 'node_modules', '.prisma', 'client');\nconst GENERATED_CLIENT_MARKER = path.join(GENERATED_CLIENT_DIR, 'schema.prisma');\n\n//? Default schema location in a scaffolded LuckyStack project. `prisma generate`\n//? auto-discovers `prisma/schema.prisma` from the project root, so no explicit\n//? `--schema` flag is needed when this path exists.\nconst DEFAULT_SCHEMA_PATH = path.join(ROOT_DIR, 'prisma', 'schema.prisma');\n\n/**\n * True when a Prisma schema exists in the consumer project but the generated\n * client output is absent — i.e. the consumer has not run `prisma generate`\n * yet. This is the only condition under which we auto-generate (or surface the\n * \"run prisma:generate\" hint), so an unrelated type-map failure never triggers\n * the Prisma-specific path.\n */\nexport const isPrismaClientMissing = (): boolean =>\n\tfs.existsSync(DEFAULT_SCHEMA_PATH) && !fs.existsSync(GENERATED_CLIENT_MARKER);\n\n/**\n * Runs `prisma generate` once. `prisma generate` only reads the schema —\n * it needs NO database credentials — so this is safe to run on dev boot without\n * any `.env` loading. Resolves to the child's exit code (0 on success). Spawn\n * failures (ENOENT/EACCES) surface through the `tryCatch` tuple, not a throw.\n *\n * Uses the local `node_modules/.bin/prisma` binary directly (shell: false) to\n * avoid shell invocation on Windows. Falls back to `npx prisma` with\n * shell: false when the local binary is absent (e.g. prisma not yet installed).\n */\nexport const runPrismaGenerate = async (): Promise<[Error | null, number | null]> =>\n\ttryCatch(\n\t\t() =>\n\t\t\tnew Promise<number>((resolve, reject) => {\n\t\t\t\t//? Prefer the local binary over `npx` — avoids shell invocation on\n\t\t\t\t//? Windows and is faster (no npx resolution overhead). On Windows the\n\t\t\t\t//? `.cmd` wrapper is what `PATH` resolves to from cmd.exe, but spawn\n\t\t\t\t//? with shell:false needs the real script path, not the .cmd shim.\n\t\t\t\t//? The actual JS CLI lives at `node_modules/prisma/build/index.js`\n\t\t\t\t//? but the cross-platform entry is the `.bin` shim.\n\t\t\t\tconst localBinName = process.platform === 'win32' ? 'prisma.cmd' : 'prisma';\n\t\t\t\tconst localBin = path.join(ROOT_DIR, 'node_modules', '.bin', localBinName);\n\t\t\t\tconst useLocal = fs.existsSync(localBin);\n\n\t\t\t\t//? shell: false in both branches — argv is fully static (no user input).\n\t\t\t\tconst [cmd, args] = useLocal\n\t\t\t\t\t? [localBin, ['generate']]\n\t\t\t\t\t: [process.platform === 'win32' ? 'npx.cmd' : 'npx', ['prisma', 'generate']];\n\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: ROOT_DIR,\n\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t\tshell: false,\n\t\t\t\t});\n\t\t\t\tchild.on('error', reject);\n\t\t\t\tchild.on('exit', (code) => { resolve(code ?? 0); });\n\t\t\t}),\n\t);\n"],"mappings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F,OAAO;AACL,gBAAQ,IAAI,4CAA4C,OAAO;AAAA,MACjE;AAAA,IACF,GAAG;AAAA,EACL,CAAC;AACH;","names":["overrides","path","path","versionMatch","fs","fs","fs","path","ts","ts","fs","path","ts","path","ts","path","ROOT_DIR","getGeneratedSocketTypesPath","getGeneratedSocketTypesPath","normalizeImportPath","path","mergeUnresolvedSymbols","ts","fs","path","ts","path","getGeneratedSocketTypesPath","path","getGeneratedSocketTypesPath","getGeneratedSocketTypesPath","path","getGeneratedSocketTypesPath","fs","getSrcDir","fs","path","ROOT_DIR","path","ROOT_DIR","fs","rules","getSrcDir","fs","path","getServerFunctionDirs","getSrcDir","ts","SKIP_EXPANSION","normalizePath","path","getSrcDir","rules","fs","getServerFunctionDirs","fs","path","fs","path","pathToFileURL","ts","ROOT_DIR","getGeneratedSocketTypesPath","getSrcDir","validatePagePath","path","ROOT_DIR","fs","pathToFileURL","getSrcDir","extractSyncPagePath","extractSyncName","getGeneratedSocketTypesPath","validatePagePath","fs","path","ROOT_DIR","getServerFunctionDirs","getSrcDir","normalizePath","path","fs","ROOT_DIR","getSrcDir","getServerFunctionDirs","fs","path","ROOT_DIR","tryCatch","tryCatch","path","tryCatch","rules","fs","extractSyncPagePath","extractSyncName"]}
1
+ {"version":3,"sources":["../src/typeMap/discovery.ts","../src/routingRules.ts","../src/typeMap/routeMeta.ts","../src/routeConventions.ts","../src/typeMap/apiMeta.ts","../src/typeMap/emitterArtifacts.ts","../src/internal/mapUtils.ts","../src/typeMap/zodEmitter.ts","../src/typeMap/extractors.ts","../src/typeMap/tsProgram.ts","../src/typeMap/functionsMeta.ts","../src/typeMap/typeContext.ts","../src/typeMapGenerator.ts","../src/routeNamingValidation.ts","../src/templateRegistry.ts","../src/loader.ts","../src/runtimeTypeResolver.ts","../src/hotReload.ts","../src/templateInjector.ts","../src/importDependencyGraph.ts","../src/prismaClientCheck.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR } from '@luckystack/core';\nimport {\n getRoutingRules,\n isApiFileName,\n isSyncClientFileName,\n isSyncServerFileName,\n apiMarkerSegment,\n syncMarkerSegment,\n} from '../routingRules';\n\nconst toForwardSlashRelative = (absolute: string): string => {\n const rel = path.relative(ROOT_DIR, absolute);\n return rel.replaceAll('\\\\', '/');\n};\n\nconst walkFiles = (\n dir: string,\n matcher: (fullPath: string, entryName: string) => boolean,\n results: string[] = [],\n visited = new Set<string>()\n): string[] => {\n // Resolve the real path to detect symlink cycles before descending.\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch {\n return results;\n }\n if (visited.has(realDir)) return results;\n visited.add(realDir);\n\n const { ignore } = getRoutingRules();\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = toForwardSlashRelative(fullPath);\n\n if (ignore(relativePath)) continue;\n\n if (entry.isDirectory() || entry.isSymbolicLink()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;\n // Only recurse if this is actually a directory (resolves symlinks).\n try {\n if (fs.statSync(fullPath).isDirectory()) {\n walkFiles(fullPath, matcher, results, visited);\n }\n } catch {\n // Broken symlink — skip.\n }\n continue;\n }\n\n if (entry.isFile() && matcher(fullPath, entry.name)) {\n results.push(fullPath);\n }\n }\n } catch (error) {\n console.error(`[TypeMapDiscovery] Error scanning directory ${dir}:`, error);\n }\n\n return results;\n};\n\nexport const findAllApiFiles = (srcDir: string): string[] => {\n const apiSegment = apiMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isApiFileName(entryName) && normalized.includes(apiSegment);\n });\n};\n\nexport const findAllSyncServerFiles = (srcDir: string): string[] => {\n const syncSegment = syncMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isSyncServerFileName(entryName) && normalized.includes(syncSegment);\n });\n};\n\nexport const findAllSyncClientFiles = (srcDir: string): string[] => {\n const syncSegment = syncMarkerSegment();\n return walkFiles(srcDir, (fullPath, entryName) => {\n const normalized = fullPath.replaceAll('\\\\', '/');\n return isSyncClientFileName(entryName) && normalized.includes(syncSegment);\n });\n};\n","//? Routing rule registry. Lets consumers customize the file-based routing\n//? conventions that devkit uses to discover APIs, sync events, and ignored\n//? folders.\n//?\n//? Defaults preserve the framework's original `_api`/`_sync` markers and the\n//? `_v{N}.ts` / `_server_v{N}.ts` / `_client_v{N}.ts` filename suffixes. The\n//? `ignore` predicate is called for each candidate path during discovery; a\n//? consumer can return `true` to skip e.g. `__tests__` folders, vendor\n//? directories, or any other custom rule.\n\nexport interface RoutingRules {\n /** Folder name that marks an API directory. Default: `_api`. */\n apiMarker: string;\n /** Folder name that marks a sync directory. Default: `_sync`. */\n syncMarker: string;\n /** Suffix matcher for API files: must end with `_v<number>.ts`. */\n apiVersionRegex: RegExp;\n /** Suffix matcher for sync server files: must end with `_server_v<number>.ts`. */\n syncServerVersionRegex: RegExp;\n /** Suffix matcher for sync client files: must end with `_client_v<number>.ts`. */\n syncClientVersionRegex: RegExp;\n /** Combined sync regex (server or client). */\n syncVersionRegex: RegExp;\n /**\n * Predicate called for each candidate file/folder during discovery.\n * Return `true` to skip. Path is provided as a forward-slash relative\n * string from the workspace root (e.g. `src/dashboard/__tests__/foo_v1.ts`).\n */\n ignore: (relativePath: string) => boolean;\n /**\n * Single-character prefix that marks a folder as **invisible-parent** for\n * page routing: `src/_housing/renting/page.tsx` resolves to `/renting`\n * (the `_housing` segment is stripped from the URL). A `page.tsx` placed\n * directly inside an `_<name>` folder is invalid (no URL segment left).\n *\n * Default: `'_'`. Override only if you need a different prefix scheme.\n */\n privateFolderPrefix: string;\n /**\n * Folder names that are reserved for framework-internal use and may NEVER\n * host a `page.tsx`. Scaffold + page-discovery emit a hard error when a\n * page is placed inside one. Extend (do not replace) the defaults if you\n * add your own internal folder convention.\n *\n * Defaults: `_api`, `_sync`, `_function(s)`, `_component(s)`, `_provider(s)`,\n * `_locale(s)`, `_socket(s)`, `_shared`, `_server`. The semantic markers\n * (`_api`, `_sync`) are also reserved by the API/sync routers.\n */\n scaffoldIgnoredFolders: string[];\n /**\n * Optional predicate. Return `true` for a given absolute file path to\n * disable template injection entirely for that file. Useful when a\n * consumer wants to opt some part of the tree out of the scaffold\n * (e.g. `/src/migrations/**` lives by hand). The argument is the\n * absolute path the chokidar watcher provides; the predicate is\n * called BEFORE the `isInApiFolder` / `isPageFile` checks fire.\n */\n disableTemplateInjection?: (filePath: string) => boolean;\n}\n\nconst DEFAULT_RULES: RoutingRules = {\n apiMarker: '_api',\n syncMarker: '_sync',\n apiVersionRegex: /_v(\\d+)$/,\n syncServerVersionRegex: /_server_v(\\d+)$/,\n syncClientVersionRegex: /_client_v(\\d+)$/,\n syncVersionRegex: /_(server|client)_v(\\d+)$/,\n ignore: () => false,\n privateFolderPrefix: '_',\n scaffoldIgnoredFolders: [\n '_api',\n '_sync',\n '_function',\n '_functions',\n '_component',\n '_components',\n '_provider',\n '_providers',\n '_locale',\n '_locales',\n '_socket',\n '_sockets',\n '_shared',\n '_server',\n ],\n};\n\nlet activeRules: RoutingRules = DEFAULT_RULES;\n\nexport const registerRoutingRules = (overrides: Partial<RoutingRules>): RoutingRules => {\n activeRules = { ...DEFAULT_RULES, ...overrides };\n return activeRules;\n};\n\nexport const getRoutingRules = (): RoutingRules => activeRules;\n\n//? Convenience helpers built on top of the active rules — used by\n//? loader/hotReload/discovery so call sites don't have to compose the\n//? marker name into a path-segment check themselves.\nexport const apiMarkerSegment = (): string => `/${getRoutingRules().apiMarker}/`;\nexport const syncMarkerSegment = (): string => `/${getRoutingRules().syncMarker}/`;\n\nexport const isApiFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().apiVersionRegex.test(stem);\n};\n\nexport const isSyncServerFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncServerVersionRegex.test(stem);\n};\n\nexport const isSyncClientFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncClientVersionRegex.test(stem);\n};\n\nexport const isSyncFileName = (fileName: string): boolean => {\n if (!fileName.endsWith('.ts')) return false;\n const stem = fileName.slice(0, -3);\n return getRoutingRules().syncVersionRegex.test(stem);\n};\n\n//? Per-route business-logic test files (`<name>_v<N>.tests.ts` and\n//? `<name>_server_v<N>.tests.ts`) live INSIDE `_api/` and `_sync/` folders\n//? alongside the route they cover. Loaders, validators, and template\n//? injectors must skip them — they are picked up separately by\n//? `@luckystack/test-runner`.\nexport const isRouteTestFile = (fileNameOrPath: string): boolean => {\n return fileNameOrPath.endsWith('.tests.ts');\n};\n\n//? Re-export the core page-route validator + bind it to the active\n//? `RoutingRules` (so a consumer that calls `registerRoutingRules({\n//? scaffoldIgnoredFolders: [...] })` to add a custom private folder\n//? sees the override applied here too). The pure helper lives in\n//? `@luckystack/core/pageRouteValidation.ts` so the client-side router\n//? in `src/main.tsx` can import it without dragging devkit into the\n//? Vite bundle.\nimport { validatePagePath as corePagePath, type PagePathValidationResult as CoreResult, type PageRouteRules } from '@luckystack/core';\n\nexport type PagePathValidationResult = CoreResult;\n\nexport const validatePagePath = (srcRelativePath: string): PagePathValidationResult => {\n const rules = getRoutingRules();\n const pageRules: PageRouteRules = {\n privateFolderPrefix: rules.privateFolderPrefix,\n scaffoldIgnoredFolders: rules.scaffoldIgnoredFolders,\n };\n return corePagePath(srcRelativePath, pageRules);\n};\n","import path from 'node:path';\nimport { getSrcDir } from '@luckystack/core';\nimport { API_VERSION_TOKEN_REGEX, SYNC_VERSION_TOKEN_REGEX } from '../routeConventions';\nimport { getRoutingRules } from '../routingRules';\n\nconst VERSION_SUFFIX_REGEX = API_VERSION_TOKEN_REGEX;\n\n//? Marker segments are configurable via `registerRoutingRules`; escape the\n//? active marker before splicing it into a RegExp so a marker containing regex\n//? metacharacters can't change the pattern's meaning. For the default markers\n//? (`_api` / `_sync`) escaping is a no-op, so the compiled patterns are\n//? byte-identical to the previous literal regexes.\nconst escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\nconst stripVersionSuffix = (name: string): string => {\n // VERSION_SUFFIX_REGEX is anchored (`$`) so it matches at most once — `.replace` is correct here.\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return name.replace(VERSION_SUFFIX_REGEX, '');\n};\n\nconst extractVersionFromName = (name: string): string | null => {\n const match = VERSION_SUFFIX_REGEX.exec(name);\n if (!match) return null;\n return `v${match[1]}`;\n};\n\nexport const extractPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n // Anchor on the configured srcDir so non-`src` layouts are handled correctly.\n const srcDirNormalized = getSrcDir().replaceAll('\\\\', '/');\n const rel = path.posix.relative(srcDirNormalized, normalized);\n // If the file is outside the srcDir the relative path starts with '..';\n // throw so callers know this file should not have been discovered.\n if (rel.startsWith('..')) {\n throw new Error(`[routeMeta] file is outside srcDir — cannot extract page path: ${filePath}`);\n }\n const { apiMarker } = getRoutingRules();\n const match = new RegExp(String.raw`^(?:(.+?)\\/)${escapeRegExp(apiMarker)}\\/`).exec(rel);\n if (match) {\n return match[1] ?? 'system';\n }\n if (rel.startsWith(`${apiMarker}/`)) {\n return 'system';\n }\n return '';\n};\n\nexport const extractApiName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const { apiMarker } = getRoutingRules();\n const match = new RegExp(String.raw`${escapeRegExp(apiMarker)}\\/(.+)\\.ts$`).exec(normalized);\n const rawName = match?.[1] ?? path.basename(filePath, '.ts');\n return stripVersionSuffix(rawName);\n};\n\nexport const extractApiVersion = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const { apiMarker } = getRoutingRules();\n const match = new RegExp(String.raw`${escapeRegExp(apiMarker)}\\/(.+)\\.ts$`).exec(normalized);\n const rawName = match?.[1] ?? path.basename(filePath, '.ts');\n return extractVersionFromName(rawName) ?? 'v1';\n};\n\nexport const extractSyncPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n //? A sync directly under `src/_sync/` gets the `'system'` sentinel, matching\n //? `extractPagePath` (API side) AND the dev loader's root-sync route key.\n //? Using `'root'` here made the type-map key + generated `FullSyncPath`\n //? (`sync/root/<name>/v1`) disagree with the loader's runtime registration\n //? AND the wire name the typed `syncRequest` actually sends\n //? (`sync/system/<name>/v1`) — so a root sync silently never dispatched.\n const srcDirNormalized = getSrcDir().replaceAll('\\\\', '/');\n const rel = path.posix.relative(srcDirNormalized, normalized);\n const { syncMarker } = getRoutingRules();\n const match = new RegExp(String.raw`^(?:(.+?)\\/)${escapeRegExp(syncMarker)}\\/`).exec(rel);\n if (match) {\n return match[1] ?? 'system';\n }\n if (rel.startsWith(`${syncMarker}/`)) {\n return 'system';\n }\n return '';\n};\n\nexport const extractSyncName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const { syncMarker } = getRoutingRules();\n const match = new RegExp(String.raw`${escapeRegExp(syncMarker)}\\/(.+)\\.ts$`).exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n // SYNC_VERSION_TOKEN_REGEX is anchored (`$`) — matches at most once.\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return basename.replace(SYNC_VERSION_TOKEN_REGEX, '');\n }\n\n // eslint-disable-next-line unicorn/prefer-string-replace-all\n return (match[1] ?? '').replace(SYNC_VERSION_TOKEN_REGEX, '');\n};\n\nexport const extractSyncVersion = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const { syncMarker } = getRoutingRules();\n const match = new RegExp(String.raw`${escapeRegExp(syncMarker)}\\/(.+)\\.ts$`).exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n const versionMatch = SYNC_VERSION_TOKEN_REGEX.exec(basename);\n return versionMatch ? `v${versionMatch[2] ?? '1'}` : 'v1';\n }\n\n const versionMatch = SYNC_VERSION_TOKEN_REGEX.exec(match[1] ?? '');\n return versionMatch ? `v${versionMatch[2] ?? '1'}` : 'v1';\n};\n","//? Static convention defaults. These remain exported for backwards\n//? compatibility with code that accesses them as RegExp/string literals\n//? (e.g. `name.replace(API_VERSION_TOKEN_REGEX, '')`). Call sites that\n//? must honor consumer-overridden conventions read from\n//? `getRoutingRules()` (in `./routingRules.ts`) instead.\n\nimport {\n isApiFileName as isApi,\n isSyncFileName as isSync,\n isSyncServerFileName as isSyncServer,\n isSyncClientFileName as isSyncClient,\n} from './routingRules';\n\nexport const API_VERSION_TOKEN_REGEX = /_v(\\d+)$/;\nexport const SYNC_VERSION_TOKEN_REGEX = /_(server|client)_v(\\d+)$/;\n\nexport const API_VERSIONED_FILE_REGEX = /_v\\d+\\.ts$/;\nexport const SYNC_SERVER_VERSIONED_FILE_REGEX = /_server_v\\d+\\.ts$/;\nexport const SYNC_CLIENT_VERSIONED_FILE_REGEX = /_client_v\\d+\\.ts$/;\nexport const SYNC_VERSIONED_FILE_REGEX = /_(?:server|client)_v\\d+\\.ts$/;\n\nexport const ROUTE_NAMING_RULES = {\n api: '<name>_v<number>.ts',\n syncServer: '<name>_server_v<number>.ts',\n syncClient: '<name>_client_v<number>.ts',\n} as const;\n\nexport const ROUTE_NAMING_EXAMPLES = {\n api: 'updateUser_v1.ts',\n syncServer: 'updateCounter_server_v1.ts',\n syncClient: 'updateCounter_client_v1.ts',\n} as const;\n\n//? These checks honor `registerRoutingRules({...})` overrides because they\n//? delegate to the registry-aware functions in `./routingRules`.\nexport const isVersionedApiFileName = (fileName: string): boolean => isApi(fileName);\nexport const isVersionedSyncFileName = (fileName: string): boolean => isSync(fileName);\nexport const isVersionedSyncServerFileName = (fileName: string): boolean => isSyncServer(fileName);\nexport const isVersionedSyncClientFileName = (fileName: string): boolean => isSyncClient(fileName);\n","import * as ts from 'typescript';\nimport fs from 'node:fs';\nimport { inferHttpMethod, tryCatchSync } from '@luckystack/core';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n// Finds an exported const declaration by name in a source file's top-level statements.\nconst findExportedConst = (sourceFile: ts.SourceFile, name: string): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n const hasExport = statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n if (!hasExport) continue;\n\n for (const decl of statement.declarationList.declarations) {\n if (ts.isIdentifier(decl.name) && decl.name.text === name) return decl;\n }\n }\n return null;\n};\n\n//? Unwrap `as const` / `as T` / `satisfies T` / parenthesized wrappers so an\n//? initializer like `'DELETE' as const` is read as its underlying literal.\n//? The TS AST wraps these in AsExpression / SatisfiesExpression /\n//? ParenthesizedExpression nodes that the literal-type guards below would\n//? otherwise skip — silently dropping the authored value and falling back to\n//? an inferred default. Solving the wrapper class once covers every extractor.\nconst unwrapExpression = (node: ts.Expression): ts.Expression => {\n let current = node;\n while (\n ts.isAsExpression(current)\n || ts.isSatisfiesExpression(current)\n || ts.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n};\n\nexport const extractHttpMethod = (filePath: string, apiName: string): HttpMethod => {\n const [error, method] = tryCatchSync((): HttpMethod | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'httpMethod');\n\n const initializer = decl?.initializer ? unwrapExpression(decl.initializer) : undefined;\n if (initializer && ts.isStringLiteral(initializer)) {\n const candidate = initializer.text.toUpperCase() as HttpMethod;\n if (['GET', 'POST', 'PUT', 'DELETE'].includes(candidate)) return candidate;\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting httpMethod from ${filePath}:`, error);\n }\n\n return method ?? inferHttpMethod(apiName);\n};\n\nexport const extractRateLimit = (filePath: string): number | false | undefined => {\n const [error, rateLimit] = tryCatchSync((): number | false | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'rateLimit');\n\n if (decl?.initializer) {\n const initializer = unwrapExpression(decl.initializer);\n if (initializer.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (ts.isNumericLiteral(initializer)) return Number(initializer.text);\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting rateLimit from ${filePath}:`, error);\n }\n\n return rateLimit ?? undefined;\n};\n\n/**\n * Reads the `export const validation` declaration from an API/sync source\n * file. Supports `'strict'`, `'relaxed'`, and `{ input: 'skip' | 'strict' }`.\n * Returns undefined when the export is absent (consumer hasn't opted out).\n */\nexport type ApiValidationMode = 'strict' | 'relaxed' | { input: 'skip' | 'strict' };\n\nexport const extractValidation = (filePath: string): ApiValidationMode | undefined => {\n const [error, validation] = tryCatchSync((): ApiValidationMode | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'validation');\n\n if (!decl?.initializer) return undefined;\n const initializer = unwrapExpression(decl.initializer);\n\n if (ts.isStringLiteral(initializer)) {\n const text = initializer.text;\n if (text === 'strict' || text === 'relaxed') return text;\n }\n\n if (ts.isObjectLiteralExpression(initializer)) {\n for (const prop of initializer.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n if (prop.name.text !== 'input') continue;\n const propInit = unwrapExpression(prop.initializer);\n if (!ts.isStringLiteral(propInit)) continue;\n const input = propInit.text;\n if (input === 'skip' || input === 'strict') return { input };\n }\n }\n return undefined;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting validation from ${filePath}:`, error);\n }\n\n return validation ?? undefined;\n};\n\n// Reads a primitive value from an AST expression node.\nconst readPrimitive = (rawNode: ts.Expression): string | number | boolean | undefined => {\n const node = unwrapExpression(rawNode);\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNumericLiteral(node)) return Number(node.text);\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n return undefined;\n};\n\nconst parseAdditionalItem = (objectLiteral: ts.ObjectLiteralExpression): Record<string, unknown> | null => {\n const item: Record<string, unknown> = {};\n\n for (const prop of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const value = readPrimitive(prop.initializer);\n if (value !== undefined) item[prop.name.text] = value;\n }\n\n return item.key ? item : null;\n};\n\n/**\n * AST-extracted JSDoc `@docs` metadata for a route file. Parsed from JSDoc\n * blocks attached to top-level statements (typically the `main` export).\n *\n * Convention (matches docs-ui renderer in `packages/docs-ui/src/docsHtml.ts`):\n *\n * /\\*\\*\n * * Description sentence.\n * * @docs owner @mathijs\n * * @docs tags admin, internal, deprecated-soon\n * * @docs deprecated use api/billing/getInvoice/v2 instead\n * *\\/\n * export const main = async (...) => {...};\n *\n * `@docs deprecated` without a reason -> `true` (renders as red \"deprecated\"\n * badge without explanation). With a reason -> `string` (renders the\n * explanation). `@docs tags` is comma-split + trimmed. Unknown sub-keys are\n * silently ignored so future tags don't break the parser.\n */\nexport interface DocsMeta {\n owner?: string;\n tags?: string[];\n deprecated?: string | true;\n}\n\n//? Flatten a JSDoc tag comment (string or `ts.NodeArray` of comment parts) to text.\nconst commentToString = (commentValue: unknown): string => {\n if (typeof commentValue === 'string') return commentValue;\n if (Array.isArray(commentValue)) {\n return commentValue\n .map((part) => {\n if (part && typeof part === 'object' && 'text' in part && typeof (part as { text: unknown }).text === 'string') {\n return (part as { text: string }).text;\n }\n return '';\n })\n .join('');\n }\n return '';\n};\n\nexport const extractDocsMeta = (filePath: string): DocsMeta | undefined => {\n const [error, docsMeta] = tryCatchSync((): DocsMeta | undefined => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const result: DocsMeta = {};\n\n const consumeTag = (tag: ts.JSDocTag): void => {\n if (tag.tagName.text !== 'docs') return;\n const commentText = commentToString(tag.comment).trim();\n if (commentText.length === 0) return;\n\n const spaceIdx = commentText.search(/\\s/);\n const subkey = (spaceIdx === -1 ? commentText : commentText.slice(0, spaceIdx)).toLowerCase();\n const value = spaceIdx === -1 ? '' : commentText.slice(spaceIdx + 1).trim();\n\n if (subkey === 'owner' && value.length > 0) {\n result.owner = value;\n } else if (subkey === 'tags' && value.length > 0) {\n const tags = value.split(',').map((s) => s.trim()).filter((s) => s.length > 0);\n if (tags.length > 0) result.tags = tags;\n } else if (subkey === 'deprecated') {\n result.deprecated = value.length > 0 ? value : true;\n }\n //? unknown sub-keys: ignore (forward-compat for future @docs <key> tags)\n };\n\n //? Walk every top-level statement and collect JSDoc tags. This catches\n //? JSDoc on the `main` export, on the `auth`/`rateLimit` consts, or on\n //? any other top-level declaration — wherever the author wrote it.\n for (const statement of sourceFile.statements) {\n for (const tag of ts.getJSDocTags(statement)) {\n consumeTag(tag);\n }\n }\n\n if (result.owner === undefined && result.tags === undefined && result.deprecated === undefined) {\n return undefined;\n }\n return result;\n });\n\n if (error) {\n console.error(`[TypeMapGenerator] Error extracting @docs metadata from ${filePath}:`, error);\n return undefined;\n }\n\n return docsMeta ?? undefined;\n};\n\nexport const extractAuth = (filePath: string): { login: boolean; additional?: Record<string, unknown>[]; hasAdditional: boolean } => {\n const [, auth] = tryCatchSync((): { login: boolean; additional?: Record<string, unknown>[]; hasAdditional: boolean } => {\n const content = fs.readFileSync(filePath, 'utf8');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const decl = findExportedConst(sourceFile, 'auth');\n const authInitializer = decl?.initializer ? unwrapExpression(decl.initializer) : undefined;\n //? DK-05 (public-by-default): a route that omits `export const auth` — OR\n //? whose `auth` omits / non-literally sets `login` — extracts as PUBLIC\n //? (`login: false`), matching the dev runtime loader (`auth.login || false`),\n //? the generated `apiMetaMap`, and the test-runner auth sweep. The defect\n //? this closes was the runtime↔tooling DISAGREEMENT: the loader defaulted to\n //? public while this extractor defaulted to protected, so the generated meta\n //? + auth sweep disagreed with what actually ran. A route that needs auth\n //? MUST declare a literal `auth: { login: true }`.\n if (!authInitializer || !ts.isObjectLiteralExpression(authInitializer)) return { login: false, hasAdditional: false };\n\n let login = false;\n let additional: Record<string, unknown>[] | undefined;\n //? Whether the route DECLARED a non-empty `additional: [...]` array — tracked\n //? from the raw element count BEFORE parseAdditionalItem (which drops non-object\n //? predicates like `additional: [adminOnly]` function refs). The test-runner's\n //? auth sweep gates on this so additional[]-only (login:false) authz routes are\n //? still probed, even when the predicates aren't serialisable into `additional`.\n let hasAdditional = false;\n\n for (const prop of authInitializer.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const propInit = unwrapExpression(prop.initializer);\n\n if (prop.name.text === 'login') {\n login = propInit.kind === ts.SyntaxKind.TrueKeyword;\n }\n\n if (prop.name.text === 'additional' && ts.isArrayLiteralExpression(propInit)) {\n hasAdditional = propInit.elements.length > 0;\n additional = [];\n for (const element of propInit.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue;\n const item = parseAdditionalItem(element);\n if (item) additional.push(item);\n }\n }\n }\n\n return additional && additional.length > 0\n ? { login, additional, hasAdditional }\n : { login, hasAdditional };\n });\n\n //? Parse failure falls through to PUBLIC, consistent with the public-by-default\n //? policy above (and the runtime loader). A route needing auth declares a\n //? literal `auth: { login: true }`.\n return auth ?? { login: false, hasAdditional: false };\n};\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport * as ts from 'typescript';\nimport { getGeneratedApiDocsPath, getGeneratedApiSchemasPath, getGeneratedSocketTypesPath } from '@luckystack/core';\n\nimport { mustGet } from '../internal/mapUtils';\nimport { typeTextToZodSource } from './zodEmitter';\n\n//? `auth` is consumer-defined opaque — each project exports its own\n//? `AuthProps` shape from `config.ts`. The emitter passes the parsed value\n//? through to the generated JSON.\n//? Forward declaration mirrored from `apiMeta.ts:DocsMeta`. Kept local to\n//? avoid a circular import between the type-map collectors and the emitter.\nexport interface DocsMetaSnapshot {\n\towner?: string;\n\ttags?: string[];\n\tdeprecated?: string | true;\n}\n\nexport interface ApiTypeEntry {\n\tinput: string;\n\toutput: string;\n\tstream: string;\n\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\trateLimit: number | false | undefined;\n\tauth: unknown;\n\tversion: string;\n\t//? Optional `@docs owner/tags/deprecated` metadata. Set when the route\n\t//? file declares any of these JSDoc sub-keys. Surfaced in\n\t//? `apiDocs.generated.json` so `@luckystack/docs-ui` can render it.\n\tmeta?: DocsMetaSnapshot;\n}\n\ninterface ApiDocsEntry {\n\tpage: string;\n\tname: string;\n\tversion: string;\n\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\tinput: string;\n\toutput: string;\n\tstream: string;\n\trateLimit: number | false | undefined;\n\tauth: unknown;\n\tpath: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\ninterface SyncDocsEntry {\n\tpage: string;\n\tname: string;\n\tversion: string;\n\tclientInput: string;\n\tserverOutput: string;\n\tclientOutput: string;\n\tserverStream: string;\n\tclientStream: string;\n\tpath: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\nexport interface GeneratedDocsData {\n\tapis: Record<string, ApiDocsEntry[]>;\n\tsyncs: Record<string, SyncDocsEntry[]>;\n}\n\nexport interface SyncTypeEntry {\n\tclientInput: string;\n\tserverOutput: string;\n\tclientOutput: string;\n\tserverStream: string;\n\tclientStream: string;\n\tversion: string;\n\tmeta?: DocsMetaSnapshot;\n}\n\nconst buildImportStatements = ({\n\tnamedImports,\n\tdefaultImports,\n}: {\n\tnamedImports: Map<string, Set<string>>;\n\tdefaultImports: Map<string, string>;\n}): string => {\n\tlet importStatements = '';\n\tfor (const [importPath, types] of namedImports) {\n\t\timportStatements += `import { ${[...types].join(', ')} } from \"${importPath}\";\\n`;\n\t}\n\tfor (const [importPath, defaultName] of defaultImports) {\n\t\timportStatements += `import ${defaultName} from \"${importPath}\";\\n`;\n\t}\n\treturn importStatements;\n};\n\nconst splitVersionedKey = (value: string): { name: string; version: string } => {\n\tconst [name, version] = value.split('@');\n\treturn { name: name ?? '', version: version ?? 'v1' };\n};\n\nconst writeFileIfChanged = (filePath: string, content: string): boolean => {\n\tif (fs.existsSync(filePath)) {\n\t\tconst currentContent = fs.readFileSync(filePath, 'utf8');\n\t\tif (currentContent === content) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfs.writeFileSync(filePath, content, 'utf8');\n\treturn true;\n};\n\nconst indentStr = (str: string, indentText: string): string => {\n\treturn str.split('\\n').map((line, i) => i === 0 ? line : indentText + line).join('\\n');\n};\n\nconst validateGeneratedTypeIdentifiers = (content: string): void => {\n\tconst sourceFile = ts.createSourceFile('apiTypes.generated.ts', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst knownSymbols = new Set<string>();\n\tconst referencedSymbols = new Set<string>();\n\n\tconst builtIns = new Set([\n\t\t'string', 'number', 'boolean', 'null', 'undefined', 'unknown', 'any', 'never', 'void', 'object', 'bigint', 'symbol',\n\t\t'Record', 'Partial', 'Required', 'Pick', 'Omit', 'Readonly', 'Exclude', 'Extract', 'NonNullable', 'ReturnType',\n\t\t'Awaited', 'Promise', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Array', 'ReadonlyArray', 'Date', 'Error', 'RegExp',\n\t\t'True', 'False', 'JsonPrimitive', 'JsonValue', 'JsonObject', 'JsonArray',\n\t]);\n\n\tconst addDeclaredName = (name?: ts.Identifier): void => {\n\t\tif (!name?.text) return;\n\t\tknownSymbols.add(name.text);\n\t};\n\n\tconst collectTypeParams = (node: ts.Node): void => {\n\t\tif (!('typeParameters' in node)) return;\n\t\tconst maybeTypeParameters = (node as ts.Node & { typeParameters?: ts.NodeArray<ts.TypeParameterDeclaration> }).typeParameters;\n\t\tif (!maybeTypeParameters) return;\n\t\tfor (const typeParameter of maybeTypeParameters) {\n\t\t\tknownSymbols.add(typeParameter.name.text);\n\t\t}\n\t};\n\n\tconst collectKnownSymbols = (node: ts.Node): void => {\n\t\tif (ts.isInferTypeNode(node)) {\n\t\t\tknownSymbols.add(node.typeParameter.name.text);\n\t\t}\n\n\t\tif (ts.isMappedTypeNode(node)) {\n\t\t\tknownSymbols.add(node.typeParameter.name.text);\n\t\t}\n\n\t\tif (ts.isImportDeclaration(node)) {\n\t\t\tconst importClause = node.importClause;\n\t\t\tif (importClause?.name) knownSymbols.add(importClause.name.text);\n\t\t\tif (importClause?.namedBindings && ts.isNamedImports(importClause.namedBindings)) {\n\t\t\t\tfor (const importElement of importClause.namedBindings.elements) {\n\t\t\t\t\tknownSymbols.add((importElement.propertyName ?? importElement.name).text);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (importClause?.namedBindings && ts.isNamespaceImport(importClause.namedBindings)) {\n\t\t\t\tknownSymbols.add(importClause.namedBindings.name.text);\n\t\t\t}\n\t\t}\n\n\t\tif (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node) || ts.isFunctionDeclaration(node)) {\n\t\t\taddDeclaredName(node.name);\n\t\t\tcollectTypeParams(node);\n\t\t}\n\n\t\tif (ts.isTypeReferenceNode(node)) {\n\t\t\tconst typeName = node.typeName;\n\t\t\tif (ts.isIdentifier(typeName)) {\n\t\t\t\treferencedSymbols.add(typeName.text);\n\t\t\t}\n\t\t\tif (ts.isQualifiedName(typeName) && ts.isIdentifier(typeName.left)) {\n\t\t\t\treferencedSymbols.add(typeName.left.text);\n\t\t\t}\n\t\t}\n\n\t\tts.forEachChild(node, collectKnownSymbols);\n\t};\n\n\tcollectKnownSymbols(sourceFile);\n\n\tconst unknown = [...referencedSymbols]\n\t\t.filter((name) => !knownSymbols.has(name) && !builtIns.has(name))\n\t\t.toSorted();\n\n\tif (unknown.length > 0) {\n\t\tthrow new Error(`[TypeMapGenerator] Generated type map has unresolved type identifiers: ${unknown.join(', ')}`);\n\t}\n};\n\nexport interface DiagnosticsEntry {\n\troute: string;\n\tkind: 'api' | 'sync';\n\tfield: string;\n\tfallback: string;\n\treason: string;\n}\n\nexport interface GeneratedDiagnosticsData {\n\tgeneratedAt: string;\n\ttotalRoutes: number;\n\tfallbackCount: number;\n\tfallbacks: DiagnosticsEntry[];\n}\n\n//? Detects type fields that fell back to a degraded default. Three signals:\n//? 1. `{ }` on input/clientInput — getSourceFile miss or missing ApiParams.data.\n//? 2. `{ status: string }` on output — main function has no typed return shape.\n//? 3. `z.any()` in the Zod schema source — zodEmitter hit an unsupported TypeNode.\n//? These are not hard errors but lose type safety on the affected routes.\nconst collectFallbacks = (\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>,\n\tsyncTypesByPage: Map<string, Map<string, SyncTypeEntry>>,\n): DiagnosticsEntry[] => {\n\tconst entries: DiagnosticsEntry[] = [];\n\n\tconst flagField = (route: string, kind: 'api' | 'sync', field: string, value: string): void => {\n\t\tif (value === '{ }' || value === '{ status: string }') {\n\t\t\tentries.push({ route, kind, field, fallback: value, reason: 'default-fallback' });\n\t\t\treturn;\n\t\t}\n\t\tconst zodSrc = typeTextToZodSource(value);\n\t\tif (zodSrc?.includes('z.any()')) {\n\t\t\tentries.push({ route, kind, field, fallback: value.slice(0, 80), reason: 'zod-any-fallback' });\n\t\t}\n\t};\n\n\tfor (const [pagePath, apis] of typesByPage) {\n\t\tfor (const [apiKey, entry] of apis) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tconst route = `${pagePath}/${name}@${version}`;\n\t\t\tflagField(route, 'api', 'input', entry.input);\n\t\t\tflagField(route, 'api', 'output', entry.output);\n\t\t}\n\t}\n\n\tfor (const [pagePath, syncs] of syncTypesByPage) {\n\t\tfor (const [syncKey, entry] of syncs) {\n\t\t\tconst { name, version } = splitVersionedKey(syncKey);\n\t\t\tconst route = `${pagePath}/${name}@${version}`;\n\t\t\tflagField(route, 'sync', 'clientInput', entry.clientInput);\n\t\t\tflagField(route, 'sync', 'serverOutput', entry.serverOutput);\n\t\t\tflagField(route, 'sync', 'clientOutput', entry.clientOutput);\n\t\t}\n\t}\n\n\treturn entries;\n};\n\nexport const buildTypeMapArtifacts = ({\n\ttypesByPage,\n\tsyncTypesByPage,\n\tnamedImports,\n\tdefaultImports,\n\tfunctionsInterface,\n}: {\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>;\n\tsyncTypesByPage: Map<string, Map<string, SyncTypeEntry>>;\n\tnamedImports: Map<string, Set<string>>;\n\tdefaultImports: Map<string, string>;\n\tfunctionsInterface: string;\n}) => {\n\tconst importStatements = buildImportStatements({ namedImports, defaultImports });\n\n\tlet content = `/* eslint-disable @typescript-eslint/no-unnecessary-condition */\n/* eslint-disable @typescript-eslint/ban-types */\n\n/**\n * Auto-generated type map for all API and Sync endpoints.\n * Enables type-safe apiRequest and syncRequest calls.\n */\n\n${importStatements}\nexport interface Functions {\n${functionsInterface}\n};\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\nexport interface JsonObject {\n\t[key: string]: JsonValue | undefined;\n}\nexport type JsonArray = JsonValue[];\nexport type MaybePromise<T> = T | Promise<T>;\n\nexport type StreamPayload = {\n\t[key: string]: unknown;\n};\n\nexport type ApiStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\nexport type SyncServerStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\nexport type SyncClientStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void | Promise<void>;\n//? Broadcast — fan-out to every socket in the receiver room (cross-instance via the Redis adapter).\nexport type SyncBroadcastStreamEmitter<T extends StreamPayload = StreamPayload> = (payload?: T) => void;\n//? Targeted — emit only to the listed session tokens (each token is its own room).\nexport type SyncStreamToEmitter<T extends StreamPayload = StreamPayload> = (\n\ttokens: string | string[],\n\tpayload?: T,\n) => void;\n\n// \n// API Type Definitions\n// \n\nexport type ApiResponse<T = unknown> =\n\t| ({ status: 'success'; httpStatus?: number; APINAME?: never; [key: string]: unknown } & T)\n\t| { status: 'error'; httpStatus?: number; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[]; APINAME?: never };\n\nexport type ApiNetworkResponse<T = unknown> =\n\t| ({ status: 'success'; httpStatus: number; APINAME?: never; [key: string]: unknown } & T)\n\t| { status: 'error'; httpStatus: number; message: string; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[]; APINAME?: never };\n\n//\n// API Type Map\n//\n\ntype _ProjectApiTypeMap = {\n`;\n\n\tconst sortedPages = [...typesByPage.keys()].toSorted();\n\tconst sortedSyncPages = [...syncTypesByPage.keys()].toSorted();\n\tconst docsData: GeneratedDocsData = { apis: {}, syncs: {} };\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tdocsData.apis[pagePath] = [];\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tdocsData.apis[pagePath].push({\n\t\t\t\t\tpage: pagePath,\n\t\t\t\t\tname: apiName,\n\t\t\t\t\tversion,\n\t\t\t\t\tmethod: entry.method,\n\t\t\t\t\tinput: entry.input,\n\t\t\t\t\toutput: entry.output,\n\t\t\t\t\tstream: entry.stream,\n\t\t\t\t\trateLimit: entry.rateLimit,\n\t\t\t\t\tauth: entry.auth,\n\t\t\t\t\t//? extractPagePath never yields 'root' for the src-root (it yields 'system'),\n\t\t\t\t\t//? and a page folder literally named `root` must route as `api/root/...` — so\n\t\t\t\t\t//? the old `pagePath === 'root'` special-case emitted a non-matching docs path.\n\t\t\t\t\t//? Always use the full path (mirrors the already-fixed sync side).\n\t\t\t\t\tpath: `api/${pagePath}/${apiName}/${version}`,\n\t\t\t\t\t...(entry.meta ? { meta: entry.meta } : {}),\n\t\t\t\t});\n\n\t\t\t\tcontent += ` '${version}': {\\n`;\n\t\t\t\tcontent += ` input: ${indentStr(entry.input, ' ')};\\n`;\n\t\t\t\t//? Union the framework error envelope so ApiOutput<P,N,V> covers the\n\t\t\t\t//? error branch without a Rule-21-forbidden cast at every call site.\n\t\t\t\t//? The index signature mirrors ApiErrorResponse so property accesses\n\t\t\t\t//? that do not narrow on status first remain compile-clean.\n\t\t\t\tcontent += ` output: ${indentStr(entry.output, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` stream: ${indentStr(entry.stream, ' ')};\\n`;\n\t\t\t\tcontent += ` method: '${entry.method}';\\n`;\n\t\t\t\tif (entry.rateLimit !== undefined) {\n\t\t\t\t\tcontent += ` rateLimit: ${entry.rateLimit};\\n`;\n\t\t\t\t}\n\t\t\t\tcontent += ` };\\n`;\n\t\t\t}\n\t\t\tcontent += ` };\\n`;\n\t\t}\n\t\tcontent += ` };\\n`;\n\t}\n\n\tcontent += `};\n\nexport interface ApiTypeMap extends _ProjectApiTypeMap {}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport type PagePath = keyof ApiTypeMap;\nexport type ApiName<P extends PagePath> = keyof ApiTypeMap[P];\nexport type ApiVersion<P extends PagePath, N extends ApiName<P>> = keyof ApiTypeMap[P][N];\nexport type ApiInput<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { input: infer I } ? I : never;\nexport type ApiOutput<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { output: infer O } ? O : never;\nexport type ApiStream<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { stream: infer S } ? S : never;\nexport type ApiMethod<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N> = ApiVersion<P, N>> = ApiTypeMap[P][N][V] extends { method: infer M } ? M : never;\n\nexport type FullApiPath<P extends PagePath, N extends ApiName<P>, V extends ApiVersion<P, N>> = \\`api/\\${P}/\\${N & string}/\\${V & string}\\`;\n\nexport const apiMethodMap: Record<string, Record<string, Record<string, HttpMethod>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; method: string }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, method: entry.method });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {`;\n\t\t\tconst methods = mustGet(grouped, apiName, 'grouped')\n\t\t\t\t.toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))\n\t\t\t\t.map((item) => ` '${item.version}': '${item.method}'`)\n\t\t\t\t.join(',');\n\t\t\tcontent += `${methods} },\\n`;\n\t\t}\n\t\tcontent += ` },\\n`;\n\t}\n\n\tcontent += `};\n\nexport const getApiMethod = (pagePath: string, apiName: string, version: string): HttpMethod | undefined => {\n\treturn apiMethodMap[pagePath]?.[apiName]?.[version];\n};\n\nexport interface ApiMetaEntry {\n\tmethod: HttpMethod;\n\tauth: { login: boolean; additional?: Record<string, unknown>[]; hasAdditional?: boolean };\n\trateLimit?: number | false;\n}\n\nexport const apiMetaMap: Record<string, Record<string, Record<string, ApiMetaEntry>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tconst auth = entry.auth && typeof entry.auth === 'object'\n\t\t\t\t\t? entry.auth as { login: boolean; additional?: Record<string, unknown>[]; hasAdditional?: boolean }\n\t\t\t\t\t: { login: false, hasAdditional: false };\n\t\t\t\tconst rateLimitPart = entry.rateLimit === undefined\n\t\t\t\t\t? ''\n\t\t\t\t\t: `, rateLimit: ${entry.rateLimit === false ? 'false' : String(entry.rateLimit)}`;\n\t\t\t\tconst additionalPart = auth.additional && auth.additional.length > 0\n\t\t\t\t\t? `, additional: ${JSON.stringify(auth.additional)}`\n\t\t\t\t\t: '';\n\t\t\t\tcontent += ` '${version}': { method: '${entry.method}', auth: { login: ${auth.login ? 'true' : 'false'}${additionalPart}${auth.hasAdditional ? ', hasAdditional: true' : ''} }${rateLimitPart} },\\n`;\n\t\t\t}\n\t\t\tcontent += ` },\\n`;\n\t\t}\n\t\tcontent += ` },\\n`;\n\t}\n\n\tcontent += `};\n\nexport const getApiMeta = (pagePath: string, apiName: string, version: string): ApiMetaEntry | undefined => {\n\treturn apiMetaMap[pagePath]?.[apiName]?.[version];\n};\n\n// Sync Type Definitions\n// \n\nexport type SyncServerResponse<T = unknown> =\n\t| ({ status: 'success'; [key: string]: unknown } & T)\n\t| { status: 'error'; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[] };\n\nexport type SyncClientResponse<T = unknown> =\n\t| ({ status: 'success'; [key: string]: unknown } & T)\n\t| { status: 'error'; errorCode: string; errorParams?: { key: string; value: string | number | boolean; }[] };\n\n//\n// Sync Type Map\n//\n\ntype _ProjectSyncTypeMap = {\n`;\n\n\tfor (const pagePath of sortedSyncPages) {\n\t\tconst syncs = mustGet(syncTypesByPage, pagePath, 'syncTypesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: SyncTypeEntry }[]>();\n\t\tdocsData.syncs[pagePath] = [];\n\n\t\tfor (const [syncKey, entry] of syncs.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(syncKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tcontent += ` '${pagePath}': {\\n`;\n\t\tfor (const syncName of [...grouped.keys()].toSorted()) {\n\t\t\tcontent += ` '${syncName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, syncName, 'grouped').toSorted((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }))) {\n\t\t\t\tdocsData.syncs[pagePath].push({\n\t\t\t\t\tpage: pagePath,\n\t\t\t\t\tname: syncName,\n\t\t\t\t\tversion,\n\t\t\t\t\tclientInput: entry.clientInput,\n\t\t\t\t\tserverOutput: entry.serverOutput,\n\t\t\t\t\tclientOutput: entry.clientOutput,\n\t\t\t\t\tserverStream: entry.serverStream,\n\t\t\t\t\tclientStream: entry.clientStream,\n\t\t\t\t\t//? `extractSyncPagePath` returns the `'system'` sentinel (NOT\n\t\t\t\t\t//? `'root'`) for a src-root sync, matching the loader's runtime key\n\t\t\t\t\t//? (`sync/system/<name>/<version>`) AND the wire name the typed\n\t\t\t\t\t//? `syncRequest` sends. The old `pagePath === 'root'` branch is now\n\t\t\t\t\t//? dead and would emit a non-matching path, so it is removed.\n\t\t\t\t\tpath: `sync/${pagePath}/${syncName}/${version}`,\n\t\t\t\t\t...(entry.meta ? { meta: entry.meta } : {}),\n\t\t\t\t});\n\n\t\t\t\tcontent += ` '${version}': {\\n`;\n\t\t\t\tcontent += ` clientInput: ${indentStr(entry.clientInput, ' ')};\\n`;\n\t\t\t\t//? Same error-envelope union as API output — makes SyncServerOutput /\n\t\t\t\t//? SyncClientOutput cover the error branch without casts.\n\t\t\t\tcontent += ` serverOutput: ${indentStr(entry.serverOutput, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` clientOutput: ${indentStr(entry.clientOutput, ' ')} | { status: 'error'; errorCode: string; [key: string]: unknown };\\n`;\n\t\t\t\tcontent += ` serverStream: ${indentStr(entry.serverStream, ' ')};\\n`;\n\t\t\t\tcontent += ` clientStream: ${indentStr(entry.clientStream, ' ')};\\n`;\n\t\t\t\tcontent += ` };\\n`;\n\t\t\t}\n\t\t\tcontent += ` };\\n`;\n\t\t}\n\t\tcontent += ` };\\n`;\n\t}\n\n\tcontent += `};\n\nexport interface SyncTypeMap extends _ProjectSyncTypeMap {}\n\nexport type SyncPagePath = keyof SyncTypeMap;\nexport type SyncName<P extends SyncPagePath> = keyof SyncTypeMap[P];\nexport type SyncVersion<P extends SyncPagePath, N extends SyncName<P>> = keyof SyncTypeMap[P][N];\nexport type SyncClientInput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientInput: infer C } ? C : never;\nexport type SyncServerOutput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { serverOutput: infer S } ? S : never;\nexport type SyncClientOutput<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientOutput: infer O } ? O : never;\nexport type SyncServerStream<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { serverStream: infer S } ? S : never;\nexport type SyncClientStream<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N> = SyncVersion<P, N>> = SyncTypeMap[P][N][V] extends { clientStream: infer O } ? O : never;\n\nexport type FullSyncPath<P extends SyncPagePath, N extends SyncName<P>, V extends SyncVersion<P, N>> = \\`sync/\\${P}/\\${N & string}/\\${V & string}\\`;\n\n//\n// Type-level augmentation — merges the project's concrete ApiTypeMap / SyncTypeMap\n// into the @luckystack/core/typemap stub-declaration module so framework code\n// (apiRequest / syncRequest) sees the project routes without deep-relative\n// imports. Augmenting the module that DECLARES the stubs (not the re-exporting\n// barrel) is what makes the merge land for consumers installing the built dist.\n//\ndeclare module '@luckystack/core/typemap' {\n\tinterface ApiTypeMap extends _ProjectApiTypeMap {}\n\tinterface SyncTypeMap extends _ProjectSyncTypeMap {}\n}\n`;\n\n\tvalidateGeneratedTypeIdentifiers(content);\n\n\t//? Zod schemas for every API input. Runtime validators + test-runner fuzz\n\t//? use this file. Emitted alongside the type map so the two always track.\n\tconst schemasContent = buildSchemasContent({ typesByPage });\n\n\t//? Diagnostics: collect routes with degraded type extraction so the\n\t//? generator exposes them in a machine-readable file rather than only\n\t//? logging to stderr. Consumers and CI can grep this file for fallbacks\n\t//? without parsing the generated TS source.\n\tconst fallbacks = collectFallbacks(typesByPage, syncTypesByPage);\n\tconst totalRoutes = [...typesByPage.values()].reduce((n, m) => n + m.size, 0)\n\t\t+ [...syncTypesByPage.values()].reduce((n, m) => n + m.size, 0);\n\tconst diagnosticsData: GeneratedDiagnosticsData = {\n\t\tgeneratedAt: new Date().toISOString(),\n\t\ttotalRoutes,\n\t\tfallbackCount: fallbacks.length,\n\t\tfallbacks,\n\t};\n\n\treturn { content, docsData, schemasContent, diagnosticsData };\n};\n\nconst buildSchemasContent = ({\n\ttypesByPage,\n}: {\n\ttypesByPage: Map<string, Map<string, ApiTypeEntry>>;\n}): string => {\n\tconst sortedPages = [...typesByPage.keys()].toSorted();\n\n\tlet body = `/* eslint-disable */\n//? Auto-generated Zod schemas for every API input. Driven by the same walk\n//? as apiTypes.generated.ts; see @luckystack/devkit/src/typeMap/zodEmitter.ts\n//? for the TS-AST → Zod converter. Types that fall outside the converter's\n//? scope emit \\`z.any()\\` with a TODO comment.\n\nimport { z } from 'zod';\n\nexport const apiInputSchemas: Record<string, Record<string, Record<string, z.ZodTypeAny>>> = {\n`;\n\n\tfor (const pagePath of sortedPages) {\n\t\tconst apis = mustGet(typesByPage, pagePath, 'typesByPage');\n\t\tconst grouped = new Map<string, { version: string; entry: ApiTypeEntry }[]>();\n\n\t\tfor (const [apiKey, entry] of apis.entries()) {\n\t\t\tconst { name, version } = splitVersionedKey(apiKey);\n\t\t\tif (!grouped.has(name)) grouped.set(name, []);\n\t\t\tmustGet(grouped, name, 'grouped').push({ version, entry });\n\t\t}\n\n\t\tbody += ` '${pagePath}': {\\n`;\n\t\tfor (const apiName of [...grouped.keys()].toSorted()) {\n\t\t\tbody += ` '${apiName}': {\\n`;\n\t\t\tfor (const { version, entry } of mustGet(grouped, apiName, 'grouped').toSorted(\n\t\t\t\t(a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }),\n\t\t\t)) {\n\t\t\t\tconst schemaSrc = typeTextToZodSource(entry.input) ?? 'z.any() /* unparseable input type */';\n\t\t\t\tbody += ` '${version}': ${schemaSrc},\\n`;\n\t\t\t}\n\t\t\tbody += ` },\\n`;\n\t\t}\n\t\tbody += ` },\\n`;\n\t}\n\n\tbody += `};\n\nexport const getApiInputSchema = (\n\tpagePath: string,\n\tapiName: string,\n\tversion: string,\n): z.ZodTypeAny | undefined => {\n\treturn apiInputSchemas[pagePath]?.[apiName]?.[version];\n};\n`;\n\n\treturn body;\n};\n\nexport const writeTypeMapArtifacts = ({\n\tcontent,\n\tdocsData,\n\tschemasContent,\n\tdiagnosticsData,\n}: {\n\tcontent: string;\n\tdocsData: GeneratedDocsData;\n\tschemasContent?: string;\n\tdiagnosticsData?: GeneratedDiagnosticsData;\n}) => {\n\ttry {\n\t\tconst outputPath = getGeneratedSocketTypesPath();\n\t\tconst hasUpdatedTypeMap = writeFileIfChanged(outputPath, content);\n\t\tif (hasUpdatedTypeMap) {\n\t\t\tconsole.log('[TypeMapGenerator] Generated apiTypes.generated.ts');\n\t\t}\n\n\t\tif (schemasContent !== undefined) {\n\t\t\tconst hasUpdatedSchemas = writeFileIfChanged(getGeneratedApiSchemasPath(), schemasContent);\n\t\t\tif (hasUpdatedSchemas) {\n\t\t\t\tconsole.log('[TypeMapGenerator] Generated apiInputSchemas.generated.ts');\n\t\t\t}\n\t\t}\n\n\t\tconst docsPath = getGeneratedApiDocsPath();\n\t\tconst docsDir = path.dirname(docsPath);\n\t\tif (!fs.existsSync(docsDir)) {\n\t\t\tfs.mkdirSync(docsDir, { recursive: true });\n\t\t}\n\t\tconst docsContent = JSON.stringify(docsData, null, 2);\n\t\tconst hasUpdatedDocs = writeFileIfChanged(docsPath, docsContent);\n\t\tif (hasUpdatedDocs) {\n\t\t\tconsole.log('[TypeMapGenerator] Generated apiDocs.generated.json');\n\t\t}\n\n\t\tif (diagnosticsData !== undefined) {\n\t\t\t//? Placed next to apiDocs.generated.json so the same docs dir is reused.\n\t\t\t//? Routes listed here have degraded type extraction (see DiagnosticsEntry.reason).\n\t\t\tconst diagnosticsPath = path.join(path.dirname(docsPath), 'apiTypeDiagnostics.generated.json');\n\t\t\tconst diagnosticsContent = JSON.stringify(diagnosticsData, null, 2);\n\t\t\tconst hasUpdatedDiagnostics = writeFileIfChanged(diagnosticsPath, diagnosticsContent);\n\t\t\tif (hasUpdatedDiagnostics) {\n\t\t\t\tconsole.log('[TypeMapGenerator] Generated apiTypeDiagnostics.generated.json');\n\t\t\t}\n\t\t\tif (diagnosticsData.fallbackCount > 0) {\n\t\t\t\tconsole.warn(`[TypeMapGenerator] ${diagnosticsData.fallbackCount} route(s) have degraded type extraction (see apiTypeDiagnostics.generated.json)`);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconsole.error('[TypeMapGenerator] Error writing type map or docs:', error);\n\t}\n};\n\n","//? Internal map utilities for devkit. Replace the `map.get(key)!` pattern\n//? (banned by the strict-typing policy) with helpers that either\n//? lazily initialize an entry (`getOrInit`) or throw a labelled error\n//? when the invariant breaks (`mustGet`). Both surface the actual\n//? failure site instead of silently producing `undefined`.\n\nexport const getOrInit = <K, V>(map: Map<K, V>, key: K, factory: () => V): V => {\n const existing = map.get(key);\n if (existing !== undefined) return existing;\n const fresh = factory();\n map.set(key, fresh);\n return fresh;\n};\n\nexport const mustGet = <K, V>(map: Map<K, V>, key: K, label: string): V => {\n const value = map.get(key);\n if (value === undefined) {\n throw new Error(`[devkit] invariant violation: '${String(key)}' missing from ${label}`);\n }\n return value;\n};\n","import * as ts from 'typescript';\n\n//? Converts a TypeScript type expression into Zod schema source text.\n//?\n//? Scope today — handles the shapes used by LuckyStack API/sync inputs:\n//? - Primitives: string, number, boolean, null, undefined, any, unknown\n//? - String/number literal types\n//? - Union types (including `| undefined` for optional fields)\n//? - Array types: `T[]` and `Array<T>`\n//? - Object types with property signatures and optional modifier\n//? - Index signatures: `Record<string, T>` and `{ [key: string]: T }`\n//? - `Partial`, `Required`, `Pick`, `Omit`, `Record` as best-effort (TypeRef)\n//?\n//? Out of scope — falls back to `z.any()` with a TODO comment:\n//? - Intersections (A & B) — needs shape merging\n//? - Generic parameters beyond Record/Partial/etc.\n//? - Mapped types, conditional types\n//? - Interface references (A from another file) — resolve at call site\n//?\n//? Why write our own instead of `ts-to-zod`: the input here is a bare type\n//? expression string, not a file with declarations. ts-to-zod expects the\n//? latter. Also: no codegen tool handles `{ [key: string]: never }` — the\n//? LuckyStack \"no input\" convention — without special-casing.\n//?\n//? Strict-vs-loose policy (DD-DEVKIT-D2 decision):\n//? Object literals → `.strict()` (rejects unknown keys, fail-closed posture).\n//? Routes that need to accept extra keys can declare `export const validation\n//? = 'relaxed'` (stripped by the Zod layer, future opt-out hook). All other\n//? fallback paths (`z.any()`, `z.record(...)`) remain loose because we have\n//? no structural shape to enforce. The `z.any()` fallback count is surfaced\n//? in `apiTypeDiagnostics.generated.json` so degraded routes are visible.\n\nconst wrapOptional = (inner: string): string => `${inner}.optional()`;\nconst anyFallback = (reason: string): string => `z.any() /* ${reason} */`;\n\nconst convertTypeNode = (node: ts.TypeNode): string => {\n // Primitives\n if (node.kind === ts.SyntaxKind.StringKeyword) return 'z.string()';\n if (node.kind === ts.SyntaxKind.NumberKeyword) return 'z.number()';\n if (node.kind === ts.SyntaxKind.BooleanKeyword) return 'z.boolean()';\n if (node.kind === ts.SyntaxKind.NullKeyword) return 'z.null()';\n if (node.kind === ts.SyntaxKind.UndefinedKeyword) return 'z.undefined()';\n if (node.kind === ts.SyntaxKind.AnyKeyword) return 'z.any()';\n if (node.kind === ts.SyntaxKind.UnknownKeyword) return 'z.unknown()';\n if (node.kind === ts.SyntaxKind.NeverKeyword) return 'z.never()';\n\n // Literal types: 'foo', 42, true, false\n if (ts.isLiteralTypeNode(node)) {\n const literal = node.literal;\n if (ts.isStringLiteral(literal)) return `z.literal(${JSON.stringify(literal.text)})`;\n if (ts.isNumericLiteral(literal)) return `z.literal(${literal.text})`;\n if (literal.kind === ts.SyntaxKind.TrueKeyword) return 'z.literal(true)';\n if (literal.kind === ts.SyntaxKind.FalseKeyword) return 'z.literal(false)';\n if (literal.kind === ts.SyntaxKind.NullKeyword) return 'z.null()';\n return anyFallback('unknown literal');\n }\n\n // Array: T[]\n if (ts.isArrayTypeNode(node)) {\n return `z.array(${convertTypeNode(node.elementType)})`;\n }\n\n // Union: A | B | undefined\n if (ts.isUnionTypeNode(node)) {\n const members = node.types;\n //? If `undefined` appears, treat as `.optional()` on the remaining union.\n const hasUndefined = members.some(m => m.kind === ts.SyntaxKind.UndefinedKeyword);\n const nonUndef = members.filter(m => m.kind !== ts.SyntaxKind.UndefinedKeyword);\n\n if (nonUndef.length === 0) return 'z.undefined()';\n\n const firstNonUndef = nonUndef[0];\n const innerSchema =\n nonUndef.length === 1 && firstNonUndef\n ? convertTypeNode(firstNonUndef)\n : `z.union([${nonUndef.map((m) => convertTypeNode(m)).join(', ')}])`;\n\n return hasUndefined ? wrapOptional(innerSchema) : innerSchema;\n }\n\n // Type reference: Record<K, V>, Partial<T>, etc.\n if (ts.isTypeReferenceNode(node)) {\n const name = node.typeName.getText();\n const args = node.typeArguments ?? [];\n\n switch (name) {\n case 'Record': {\n //? Record<string, T> → z.record(z.string(), convert(T))\n const arg0 = args[0];\n const arg1 = args[1];\n if (args.length === 2 && arg0 && arg1) {\n return `z.record(${convertTypeNode(arg0)}, ${convertTypeNode(arg1)})`;\n }\n return anyFallback('Record with unexpected arity');\n }\n case 'Partial': {\n //? Partial<{...}> flattens into making each property optional. Without\n //? resolving the referenced type we emit a best-effort record — the\n //? runtime validator on the server still enforces full correctness.\n const arg0 = args[0];\n return args.length === 1 && arg0\n ? `${convertTypeNode(arg0)}.partial()`\n : anyFallback('Partial without type arg');\n }\n case 'Array': {\n const arg0 = args[0];\n return args.length === 1 && arg0\n ? `z.array(${convertTypeNode(arg0)})`\n : anyFallback('Array without element type');\n }\n case 'Date': {\n return 'z.date()';\n }\n default: {\n return anyFallback(`unresolved TypeReference '${name}'`);\n }\n }\n }\n\n // Object literal type: { key: T; key2?: T2; [k: string]: T3 }\n if (ts.isTypeLiteralNode(node)) {\n const indexSignatures = node.members.filter((m) => ts.isIndexSignatureDeclaration(m));\n const propertySignatures = node.members.filter((m) => ts.isPropertySignature(m));\n\n //? LuckyStack's \"no input\" convention: `{ [key: string]: never }` → empty\n //? object schema. Zod's `.passthrough()` isn't right because we actually\n //? want to reject extra fields.\n if (\n indexSignatures.length === 1\n && propertySignatures.length === 0\n && indexSignatures[0]?.type.kind === ts.SyntaxKind.NeverKeyword\n ) {\n return 'z.object({}).strict()';\n }\n\n if (indexSignatures.length > 0 && propertySignatures.length === 0) {\n //? Pure index signature → z.record(keyType, valueType).\n const sig = indexSignatures[0];\n const keyType = sig?.parameters[0]?.type;\n const valueType = sig?.type;\n if (sig && keyType && valueType) {\n return `z.record(${convertTypeNode(keyType)}, ${convertTypeNode(valueType)})`;\n }\n }\n\n //? Regular object with property signatures.\n const entries = propertySignatures.map((prop) => {\n if (!ts.isIdentifier(prop.name)) return null;\n if (!prop.type) return null;\n\n const name = prop.name.text;\n let schema = convertTypeNode(prop.type);\n\n //? `?` on the property makes it optional, regardless of whether the\n //? type itself includes `| undefined`.\n if (prop.questionToken && !schema.endsWith('.optional()')) {\n schema = wrapOptional(schema);\n }\n\n return `${JSON.stringify(name)}: ${schema}`;\n }).filter((entry): entry is string => entry !== null);\n\n //? `.strict()` rejects unknown keys, matching the framework's fail-closed\n //? input validation posture. Consumers can opt out per-route via\n //? `export const validation = 'relaxed'`.\n return `z.object({ ${entries.join(', ')} }).strict()`;\n }\n\n // Parenthesized: (T)\n if (ts.isParenthesizedTypeNode(node)) {\n return convertTypeNode(node.type);\n }\n\n // Intersection: A & B — best-effort merge via z.object().extend() isn't\n // possible without both sides being objects. Fall back for now.\n if (ts.isIntersectionTypeNode(node)) {\n return anyFallback('intersection not yet supported');\n }\n\n return anyFallback(`unsupported TypeNode kind=${String(node.kind)}`);\n};\n\n/**\n * Convert a TypeScript type expression string (as emitted into the generated\n * file) into a Zod schema source string.\n *\n * Returns `null` when the input can't be parsed as a type — callers should\n * fall back to `z.any()` in that case.\n */\nexport const typeTextToZodSource = (typeText: string): string | null => {\n const trimmed = typeText.trim();\n if (!trimmed) return null;\n\n //? Parse as a top-level `type __ = <expr>;` so ts.createSourceFile gives us\n //? back a TypeAliasDeclaration whose `type` property is the TypeNode we\n //? want. No module/file loader involved.\n const synthetic = `type __X = ${trimmed};`;\n const source = ts.createSourceFile('__zod.ts', synthetic, ts.ScriptTarget.Latest, true);\n\n const statement = source.statements[0];\n if (!statement || !ts.isTypeAliasDeclaration(statement)) return null;\n\n return convertTypeNode(statement.type);\n};\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { getServerProgram, expandTypeDetailed, ExpandedTypeResult, UnresolvedTypeSymbol } from './tsProgram';\nimport { getGeneratedSocketTypesPath } from '@luckystack/core';\n\nexport type TypeExtractionResult = ExpandedTypeResult;\n\nconst TYPE_NAME_PATTERN = /\\b[A-Z][A-Za-z0-9_]*\\b/g;\n\nconst KNOWN_GLOBAL_TYPE_NAMES = new Set([\n 'String', 'Number', 'Boolean', 'Object', 'Array', 'ReadonlyArray', 'Promise', 'Map', 'Set', 'WeakMap', 'WeakSet',\n 'Date', 'RegExp', 'Error', 'Record', 'Partial', 'Required', 'Pick', 'Omit', 'Readonly', 'Exclude', 'Extract',\n 'NonNullable', 'ReturnType', 'Awaited', 'JsonValue', 'JsonObject', 'JsonArray', 'JsonPrimitive',\n]);\n\nconst normalizeImportPath = (targetFilePath: string): string => {\n // Derive fromDir from the configured generated socket types path so\n // non-`src` srcDir layouts produce correct relative import paths.\n const fromDir = path.dirname(getGeneratedSocketTypesPath());\n const from = fromDir.replaceAll('\\\\', '/');\n const to = targetFilePath.replaceAll('\\\\', '/');\n const normalized = path.posix.relative(from, to).replaceAll('\\\\', '/');\n const withoutExtension = normalized.replace(/(\\.d)?\\.(ts|tsx|js|jsx)$/i, '');\n if (withoutExtension.startsWith('.')) return withoutExtension;\n return `./${withoutExtension}`;\n};\n\nconst mergeUnresolvedSymbols = (\n left: UnresolvedTypeSymbol[],\n right: UnresolvedTypeSymbol[],\n): UnresolvedTypeSymbol[] => {\n const merged = [...left];\n const seen = new Set(merged.map((symbol) => `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`));\n\n for (const symbol of right) {\n const key = `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(symbol);\n }\n\n return merged;\n};\n\nconst collectFallbackSymbolsFromTypeText = (\n typeText: string,\n scopeNode: ts.Node,\n checker: ts.TypeChecker,\n): UnresolvedTypeSymbol[] => {\n const names = new Set((typeText.match(TYPE_NAME_PATTERN) ?? []).filter((name) => !KNOWN_GLOBAL_TYPE_NAMES.has(name)));\n const symbolsInScope = checker.getSymbolsInScope(\n scopeNode,\n ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum | ts.SymbolFlags.Alias,\n );\n\n const unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n for (const name of names) {\n const localSymbol = symbolsInScope.find((symbol) => symbol.name === name);\n if (!localSymbol) continue;\n\n const targetSymbol = (localSymbol.flags & ts.SymbolFlags.Alias) === 0\n ? localSymbol\n : checker.getAliasedSymbol(localSymbol);\n const declaration = targetSymbol.declarations?.[0];\n\n if (!declaration) {\n unresolvedSymbols.push({ name });\n continue;\n }\n\n const sourceFile = declaration.getSourceFile().fileName;\n if (!sourceFile || sourceFile.includes('/node_modules/') || sourceFile.includes('\\\\node_modules\\\\')) {\n continue;\n }\n\n unresolvedSymbols.push({\n name,\n sourceFile,\n importPath: normalizeImportPath(sourceFile),\n });\n }\n\n return unresolvedSymbols;\n};\n\n// shared helpers\n\n// Finds a top-level interface declaration by name in a source file's statements.\nconst findInterface = (sourceFile: ts.SourceFile, name: string): ts.InterfaceDeclaration | null => {\n for (const stmt of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === name) return stmt;\n }\n return null;\n};\n\n// Reads the type of a named property inside an interface declaration.\nconst getInterfacePropertyType = (\n iface: ts.InterfaceDeclaration,\n propertyName: string,\n checker: ts.TypeChecker,\n): ts.Type | null => {\n for (const member of iface.members) {\n if (\n ts.isPropertySignature(member)\n && ts.isIdentifier(member.name)\n && member.name.text === propertyName\n && member.type\n ) {\n return checker.getTypeFromTypeNode(member.type);\n }\n }\n return null;\n};\n\n// Finds the function-like initializer of `const main = ...` in a source file.\nconst findMainFunction = (sourceFile: ts.SourceFile): ts.FunctionLikeDeclaration | null => {\n for (const stmt of sourceFile.statements) {\n if (ts.isVariableStatement(stmt)) {\n for (const decl of stmt.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name)\n && decl.name.text === 'main'\n && decl.initializer\n && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n }\n\n if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === 'main') {\n return stmt;\n }\n }\n return null;\n};\n\n// Collects the expanded type strings of all object-literal return statements\n// in a function body, without descending into nested function definitions.\nconst collectReturnObjectTypeDetails = (\n funcNode: ts.FunctionLikeDeclaration,\n checker: ts.TypeChecker,\n): TypeExtractionResult => {\n const types: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n const visit = (node: ts.Node) => {\n if (ts.isReturnStatement(node) && node.expression && ts.isObjectLiteralExpression(node.expression)) {\n const type = checker.getTypeAtLocation(node.expression);\n const expanded = expandTypeDetailed(type, checker);\n types.push(expanded.text);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(\n unresolvedSymbols,\n collectFallbackSymbolsFromTypeText(expanded.text, node.expression, checker),\n );\n }\n\n // Recurse into control flow but not into nested function bodies\n if (\n !ts.isArrowFunction(node)\n && !ts.isFunctionExpression(node)\n && !ts.isFunctionDeclaration(node)\n ) {\n ts.forEachChild(node, visit);\n }\n };\n\n ts.forEachChild(funcNode, visit);\n return { text: unionTypes(types), unresolvedSymbols };\n};\n\n// Collects the expanded payload type strings of stream(...) /\n// broadcastStream(...) / streamTo(tokens, ...) calls in a function body,\n// without descending into nested function definitions.\n//\n// `stream` and `broadcastStream` take the payload as the FIRST argument.\n// `streamTo` takes `(tokens, payload)` so the payload is the SECOND argument.\nconst STREAM_EMIT_NAMES = new Set(['stream', 'broadcastStream', 'streamTo']);\n\nconst collectStreamCallPayloadTypeDetails = (\n funcNode: ts.FunctionLikeDeclaration,\n checker: ts.TypeChecker,\n): TypeExtractionResult => {\n const types: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n const visit = (node: ts.Node) => {\n if (\n ts.isCallExpression(node)\n && ts.isIdentifier(node.expression)\n && STREAM_EMIT_NAMES.has(node.expression.text)\n ) {\n const callName = node.expression.text;\n //? streamTo(tokens, payload) — payload is at index 1; everything else\n //? puts the payload at index 0.\n const payloadIndex = callName === 'streamTo' ? 1 : 0;\n const payloadArg = node.arguments[payloadIndex];\n\n if (payloadArg) {\n const argType = checker.getTypeAtLocation(payloadArg);\n const nonNullableArgType = checker.getNonNullableType(argType);\n const expanded = expandTypeDetailed(nonNullableArgType, checker);\n\n if (expanded.text.trim().length > 0) {\n types.push(expanded.text);\n }\n\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(\n unresolvedSymbols,\n collectFallbackSymbolsFromTypeText(expanded.text, payloadArg, checker),\n );\n }\n }\n\n // Recurse into control flow but not into nested function bodies\n if (\n !ts.isArrowFunction(node)\n && !ts.isFunctionExpression(node)\n && !ts.isFunctionDeclaration(node)\n ) {\n ts.forEachChild(node, visit);\n }\n };\n\n ts.forEachChild(funcNode, visit);\n return { text: unionTypes(types), unresolvedSymbols };\n};\n\n// Returns the deduplicated union of an array of type strings.\nconst unionTypes = (types: string[]): string => {\n const unique = [...new Set(types)];\n return unique.length > 0 ? unique.join(' | ') : '';\n};\n\n// public API \n\nexport const getInputTypeFromFile = (filePath: string): string => {\n return getInputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getInputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) {\n //? Marker-contract (DD-DEVKIT-D1): a getSourceFile miss is always a loud\n //? warning, never silent. The generator invalidates the TS Program cache\n //? before every upsert, so a miss here means the file is genuinely absent\n //? from the Program (e.g. added to disk but tsconfig globs not updated).\n //? The route falls back to `{ }` (empty input) until the next full rebuild.\n //? The fallback is surfaced in `apiTypeDiagnostics.generated.json` so it\n //? is visible without parsing console output.\n console.warn(`[TypeMapGenerator] getSourceFile miss for ${filePath} — input types will default to { }`);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n\n const checker = program.getTypeChecker();\n const iface = findInterface(sourceFile, 'ApiParams');\n if (!iface) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const dataType = getInterfacePropertyType(iface, 'data', checker);\n if (!dataType) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const expanded = expandTypeDetailed(dataType, checker);\n return { text: expanded.text || DEFAULT, unresolvedSymbols: expanded.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting input type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getOutputTypeFromFile = (filePath: string): string => {\n return getOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getApiStreamPayloadTypeFromFile = (filePath: string): string => {\n return getApiStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getApiStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting API stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ status: string }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting output type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientDataType = (filePath: string): string => {\n return getSyncClientDataTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientDataTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const iface = findInterface(sourceFile, 'SyncParams');\n if (!iface) return { text: DEFAULT, unresolvedSymbols: [] };\n\n // Try clientInput first, then clientData (legacy name)\n const dataType =\n getInterfacePropertyType(iface, 'clientInput', checker)\n ?? getInterfacePropertyType(iface, 'clientData', checker);\n if (!dataType) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const expanded = expandTypeDetailed(dataType, checker);\n return { text: expanded.text || DEFAULT, unresolvedSymbols: expanded.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync clientData type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncServerOutputType = (filePath: string): string => {\n return getSyncServerOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncServerStreamPayloadTypeFromFile = (filePath: string): string => {\n return getSyncServerStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncServerStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync server stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncServerOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ status: string }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync serverOutput type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientOutputType = (filePath: string): string => {\n return getSyncClientOutputTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientStreamPayloadTypeFromFile = (filePath: string): string => {\n return getSyncClientStreamPayloadTypeDetailsFromFile(filePath).text;\n};\n\nexport const getSyncClientStreamPayloadTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = 'never';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectStreamCallPayloadTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync client stream payload type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\nexport const getSyncClientOutputTypeDetailsFromFile = (filePath: string): TypeExtractionResult => {\n const DEFAULT = '{ }';\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const checker = program.getTypeChecker();\n const mainFn = findMainFunction(sourceFile);\n if (!mainFn) return { text: DEFAULT, unresolvedSymbols: [] };\n\n const details = collectReturnObjectTypeDetails(mainFn, checker);\n return { text: details.text || DEFAULT, unresolvedSymbols: details.unresolvedSymbols };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error extracting sync clientOutput type from ${filePath}:`, error);\n return { text: DEFAULT, unresolvedSymbols: [] };\n }\n};\n\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { ROOT_DIR, getGeneratedSocketTypesPath } from '@luckystack/core';\n\nlet cachedProgram: ts.Program | null = null;\n\nexport const getServerProgram = (): ts.Program => {\n if (cachedProgram) return cachedProgram;\n\n const tsconfigPath = ts.findConfigFile(ROOT_DIR, ts.sys.fileExists.bind(ts.sys), 'tsconfig.server.json');\n if (!tsconfigPath) throw new Error('[TypeProgram] tsconfig.server.json not found');\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ts.readConfigFile returns { config: any }\n const { config } = ts.readConfigFile(tsconfigPath, ts.sys.readFile.bind(ts.sys));\n const { options, fileNames } = ts.parseJsonConfigFileContent(\n config,\n ts.sys,\n path.dirname(tsconfigPath),\n );\n\n cachedProgram = ts.createProgram(fileNames, options);\n return cachedProgram;\n};\n\nexport const invalidateProgramCache = (): void => {\n cachedProgram = null;\n};\n\nconst DEPTH_LIMIT = 12;\n\nexport interface UnresolvedTypeSymbol {\n name: string;\n sourceFile?: string;\n importPath?: string;\n}\n\nexport interface ExpandedTypeResult {\n text: string;\n unresolvedSymbols: UnresolvedTypeSymbol[];\n}\n\nconst JSON_TYPE_NAMES = new Set([\n 'Json',\n 'JsonValue',\n 'JsonObject',\n 'JsonArray',\n 'InputJsonValue',\n 'InputJsonObject',\n 'InputJsonArray',\n]);\n\n// Generic containers we never recursively expand (their internal shape is irrelevant to API types)\nconst SKIP_EXPANSION = new Set([\n 'Promise', 'Map', 'WeakMap', 'Set', 'WeakSet',\n 'Error', 'Date', 'RegExp', 'Buffer', 'ArrayBuffer', 'ReadonlyArray',\n]);\n\nconst isJsonLikeType = (type: ts.Type, checker: ts.TypeChecker): boolean => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- ts.Type.symbol is typed non-nullable but absent at runtime for primitive types\n const symbolName = type.symbol?.name ?? '';\n const aliasName = type.aliasSymbol?.name ?? '';\n\n if (JSON_TYPE_NAMES.has(symbolName) || JSON_TYPE_NAMES.has(aliasName)) return true;\n\n const rendered = checker.typeToString(type);\n return /(\\bPrisma\\.)?(Input)?Json(Value|Object|Array)\\b/.test(rendered);\n};\n\nconst getLiteralTypeFromExpression = (\n expression: ts.Expression,\n checker: ts.TypeChecker,\n depth: number,\n): string | null => {\n if (ts.isParenthesizedExpression(expression)) {\n return getLiteralTypeFromExpression(expression.expression, checker, depth);\n }\n\n if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {\n return getLiteralTypeFromExpression(expression.expression, checker, depth);\n }\n\n if (expression.kind === ts.SyntaxKind.TrueKeyword) return 'true';\n if (expression.kind === ts.SyntaxKind.FalseKeyword) return 'false';\n if (expression.kind === ts.SyntaxKind.NullKeyword) return 'null';\n\n if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {\n return `'${expression.text.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\'', String.raw`\\'`)}'`;\n }\n\n if (ts.isNumericLiteral(expression)) {\n return expression.text;\n }\n\n if (\n ts.isPrefixUnaryExpression(expression)\n && expression.operator === ts.SyntaxKind.MinusToken\n && ts.isNumericLiteral(expression.operand)\n ) {\n return `-${expression.operand.text}`;\n }\n\n if (ts.isIdentifier(expression)) {\n const identifierType = checker.getTypeAtLocation(expression);\n const isLiteralType = (identifierType.flags & (\n ts.TypeFlags.StringLiteral\n | ts.TypeFlags.NumberLiteral\n | ts.TypeFlags.BooleanLiteral\n | ts.TypeFlags.Null\n | ts.TypeFlags.Undefined\n )) !== 0;\n\n if (isLiteralType || identifierType.isUnion()) {\n const expanded = expandTypeDetailed(identifierType, checker, depth).text;\n if (expanded.includes(\"'\") || /\\btrue\\b|\\bfalse\\b|\\bnull\\b|\\bundefined\\b/.test(expanded)) {\n return expanded;\n }\n }\n }\n\n return null;\n};\n\nconst getLiteralTypeFromPropertySymbol = (\n symbol: ts.Symbol,\n checker: ts.TypeChecker,\n depth: number,\n): string | null => {\n const declarations = symbol.declarations ?? [];\n\n for (const declaration of declarations) {\n if (ts.isPropertyAssignment(declaration)) {\n const literal = getLiteralTypeFromExpression(declaration.initializer, checker, depth);\n if (literal) return literal;\n }\n\n if (ts.isShorthandPropertyAssignment(declaration)) {\n const literal = getLiteralTypeFromExpression(declaration.name, checker, depth);\n if (literal) return literal;\n }\n }\n\n return null;\n};\n\nconst normalizeImportPath = (targetFilePath: string): string => {\n // Derive fromDir from the configured generated socket types path so\n // non-`src` srcDir layouts produce correct relative import paths.\n const fromDir = path.dirname(getGeneratedSocketTypesPath());\n const from = fromDir.replaceAll('\\\\', '/');\n const to = targetFilePath.replaceAll('\\\\', '/');\n\n const normalized = path.posix.relative(from, to).replaceAll('\\\\', '/');\n const withoutExtension = normalized.replace(/(\\.d)?\\.(ts|tsx|js|jsx)$/i, '');\n\n if (withoutExtension.startsWith('.')) return withoutExtension;\n return `./${withoutExtension}`;\n};\n\nconst mergeUnresolvedSymbols = (\n left: UnresolvedTypeSymbol[],\n right: UnresolvedTypeSymbol[],\n): UnresolvedTypeSymbol[] => {\n const merged = [...left];\n const seen = new Set(merged.map((symbol) => `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`));\n for (const symbol of right) {\n const key = `${symbol.name}|${symbol.importPath ?? ''}|${symbol.sourceFile ?? ''}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(symbol);\n }\n return merged;\n};\n\nconst collectTypeSymbolFallback = (type: ts.Type): UnresolvedTypeSymbol[] => {\n const symbol = type.aliasSymbol ?? type.getSymbol();\n if (!symbol) return [];\n\n const name = symbol.getName();\n if (!name || name.startsWith('__')) return [];\n\n const declaration = symbol.declarations?.[0];\n if (!declaration) return [{ name }];\n\n const sourceFile = declaration.getSourceFile().fileName;\n if (!sourceFile || sourceFile.includes('/node_modules/') || sourceFile.includes('\\\\node_modules\\\\')) {\n return [{ name }];\n }\n\n return [{\n name,\n sourceFile,\n importPath: normalizeImportPath(sourceFile),\n }];\n};\n\ninterface ExpandState {\n stackTypeIds: Set<number>;\n}\n\n// Recursively expand a TypeScript type to an inline type string with no named references.\n// The result is self-contained and requires no imports.\nexport const expandTypeDetailed = (\n type: ts.Type,\n checker: ts.TypeChecker,\n depth = 0,\n state?: ExpandState,\n): ExpandedTypeResult => {\n const expandState: ExpandState = state ?? { stackTypeIds: new Set<number>() };\n const typeId = (type as ts.Type & { id?: number }).id;\n\n if (typeId !== undefined) {\n if (expandState.stackTypeIds.has(typeId)) {\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n }\n expandState.stackTypeIds.add(typeId);\n }\n\n try {\n if (depth > DEPTH_LIMIT) {\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n }\n\n if (isJsonLikeType(type, checker)) return { text: 'JsonValue', unresolvedSymbols: [] };\n\n // String literals ('hello') use single quotes for consistency with the codebase\n if (type.isStringLiteral()) return { text: `'${type.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\'', String.raw`\\'`)}'`, unresolvedSymbols: [] };\n\n // Number literals (42, 3.14)\n if (type.isNumberLiteral()) return { text: String(type.value), unresolvedSymbols: [] };\n\n // Primitives and special types (string, number, boolean, true, false, null, undefined, any, unknown, never, void)\n if (\n type.flags\n & (\n ts.TypeFlags.String\n | ts.TypeFlags.Number\n | ts.TypeFlags.Boolean\n | ts.TypeFlags.BooleanLiteral\n | ts.TypeFlags.Undefined\n | ts.TypeFlags.Null\n | ts.TypeFlags.Any\n | ts.TypeFlags.Unknown\n | ts.TypeFlags.Never\n | ts.TypeFlags.Void\n )\n ) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n\n // Union types (A | B | C)\n if (type.isUnion()) {\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const expandedTypes = type.types.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: expandedTypes.join(' | '), unresolvedSymbols };\n }\n\n // Intersection types (A & B)\n if (type.isIntersection()) {\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const expandedTypes = type.types.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: expandedTypes.join(' & '), unresolvedSymbols };\n }\n\n // Object types (interfaces, type literals, generic instances)\n if (type.flags & ts.TypeFlags.Object) {\n const objectType = type as ts.ObjectType;\n\n // Tuple types [A, B, C]\n if (objectType.objectFlags & ts.ObjectFlags.Tuple) {\n const typeArgs = checker.getTypeArguments(objectType as ts.TypeReference);\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n const tupleTypes = typeArgs.map((innerType) => {\n const expanded = expandTypeDetailed(innerType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expanded.unresolvedSymbols);\n return expanded.text;\n });\n return { text: `[${tupleTypes.join(', ')}]`, unresolvedSymbols };\n }\n\n if (objectType.objectFlags & ts.ObjectFlags.Reference) {\n const refType = objectType as ts.TypeReference;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- ts.Type.symbol is typed non-nullable but absent at runtime for anonymous reference targets\n const targetName = refType.target.symbol?.name ?? '';\n\n // Array<T> / ReadonlyArray<T> T[]\n if (targetName === 'Array' || targetName === 'ReadonlyArray') {\n const typeArgs = checker.getTypeArguments(refType);\n const firstArg = typeArgs[0];\n if (firstArg) {\n const expanded = expandTypeDetailed(firstArg, checker, depth + 1, expandState);\n const elementType = /\\s[|&]\\s/.test(expanded.text)\n ? `(${expanded.text})`\n : expanded.text;\n return {\n text: `${elementType}[]`,\n unresolvedSymbols: expanded.unresolvedSymbols,\n };\n }\n }\n\n // Known opaque containers return as-is without expanding internals\n if (SKIP_EXPANSION.has(targetName)) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n }\n\n // Known non-generic opaque containers (Date, Error, Buffer, etc.)\n const symbolName = type.symbol.name || (type.aliasSymbol?.name ?? '');\n if (SKIP_EXPANSION.has(symbolName)) {\n return { text: checker.typeToString(type), unresolvedSymbols: [] };\n }\n\n const props = checker.getPropertiesOfType(type);\n const indexInfos = checker.getIndexInfosOfType(type);\n\n if (props.length > 0 || indexInfos.length > 0) {\n const fields: string[] = [];\n let unresolvedSymbols: UnresolvedTypeSymbol[] = [];\n\n for (const prop of props) {\n const propType = checker.getTypeOfSymbol(prop);\n const literalType = getLiteralTypeFromPropertySymbol(prop, checker, depth + 1);\n const isOptional = (prop.flags & ts.SymbolFlags.Optional) !== 0;\n\n if (literalType) {\n fields.push(`${prop.name}${isOptional ? '?' : ''}: ${literalType}`);\n continue;\n }\n\n const expandedProp = expandTypeDetailed(propType, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, expandedProp.unresolvedSymbols);\n fields.push(`${prop.name}${isOptional ? '?' : ''}: ${expandedProp.text}`);\n }\n\n for (const indexInfo of indexInfos) {\n const keyType = expandTypeDetailed(indexInfo.keyType, checker, depth + 1, expandState);\n const valueType = expandTypeDetailed(indexInfo.type, checker, depth + 1, expandState);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, keyType.unresolvedSymbols);\n unresolvedSymbols = mergeUnresolvedSymbols(unresolvedSymbols, valueType.unresolvedSymbols);\n fields.push(`[key: ${keyType.text}]: ${valueType.text}`);\n }\n\n const indent = ' '.repeat(depth + 1);\n const outerIndent = ' '.repeat(depth);\n return {\n text: `{\\n${indent}${fields.join(`;\\n${indent}`)}\\n${outerIndent}}`,\n unresolvedSymbols,\n };\n }\n\n return { text: '{ }', unresolvedSymbols: [] };\n }\n\n return {\n text: checker.typeToString(type),\n unresolvedSymbols: collectTypeSymbolFallback(type),\n };\n } finally {\n if (typeId !== undefined) {\n expandState.stackTypeIds.delete(typeId);\n }\n }\n};\n\nexport const expandType = (type: ts.Type, checker: ts.TypeChecker, depth = 0): string => {\n return expandTypeDetailed(type, checker, depth).text;\n};\n\n","import * as ts from 'typescript';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { FileImport, ImportCollectors, parseFileTypeContext, sanitizeTypeAndCollectImports } from './typeContext';\nimport { getGeneratedSocketTypesPath, getServerFunctionDirs } from '@luckystack/core';\nimport { expandType, getServerProgram } from './tsProgram';\n\n// Strips default parameter values from argument lists so the generated interface\n// is a clean type signature without runtime values.\nconst stripDefaultValues = (params: string): string => {\n // Replace default values (= expr) while preserving arrow functions (=>)\n return params.replaceAll(/\\s*=(?!>)[^,)]+/g, '');\n};\n\n// Strips `//` line comments from a raw type fragment while leaving string and\n// template literals (which can legitimately contain `//`, e.g. a URL literal\n// type) intact. Uses the TS scanner so `'https://x'` is never mistaken for a\n// comment — a plain regex strip can't tell the two apart.\nexport const stripLineComments = (value: string): string => {\n const scanner = ts.createScanner(\n ts.ScriptTarget.Latest,\n /* skipTrivia */ false,\n ts.LanguageVariant.Standard,\n value,\n );\n let result = '';\n let token = scanner.scan();\n while (token !== ts.SyntaxKind.EndOfFileToken) {\n // Replace `//` comments with a space so neighbouring tokens don't glue\n // together; keep everything else verbatim, including block comments.\n result += token === ts.SyntaxKind.SingleLineCommentTrivia ? ' ' : scanner.getTokenText();\n token = scanner.scan();\n }\n return result;\n};\n\n// Collapses a multi-line type fragment to a single clean line. Inline `//`\n// comments MUST be stripped first: once the newlines are gone a surviving `//`\n// would comment out the rest of the line and produce malformed generated\n// TypeScript (later caught by validateGeneratedTypeIdentifiers).\nexport const normalizeInlineType = (value: string): string => {\n return stripLineComments(value).replaceAll(/\\s+/g, ' ').trim();\n};\n\nconst simplifyInferredType = (value: string): string => {\n if (/\\bPrismaClient\\b/.test(value)) return 'PrismaClient';\n if (/\\bRedis\\b/.test(value)) return 'Redis';\n return value;\n};\n\n//? Rewrites a relative module specifier so it resolves correctly when emitted\n//? into `src/_sockets/apiTypes.generated.ts`. The specifier is relative to\n//? `sourceFilePath` (the shim file); after this, it becomes relative to the\n//? generated file's directory. Non-relative specifiers (package aliases,\n//? node built-ins) pass through untouched.\n//?\n//? Before this lived, emitted paths were preserved verbatim and only worked\n//? when the shim file shared a depth with the generated file (depth 2 from\n//? repo root). Shims at other depths produced unresolvable type imports.\nconst getGeneratedFileDir = (): string => path.dirname(getGeneratedSocketTypesPath());\n\nconst relativizeModuleSpecifier = (specifier: string, sourceFilePath: string): string => {\n if (!specifier.startsWith('./') && !specifier.startsWith('../')) {\n return specifier;\n }\n\n const absolute = path.resolve(path.dirname(sourceFilePath), specifier);\n const rel = path.relative(getGeneratedFileDir(), absolute);\n const normalized = rel.split(path.sep).join('/');\n return normalized.startsWith('.') ? normalized : `./${normalized}`;\n};\n\nconst findProgramVariableDeclaration = (\n sourceFile: ts.SourceFile,\n exportName: string,\n): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === exportName) {\n return declaration;\n }\n }\n }\n\n return null;\n};\n\nconst findProgramTypeDeclaration = (\n sourceFile: ts.SourceFile,\n typeName: string,\n): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | ts.ClassDeclaration | ts.EnumDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(statement) && statement.name.text === typeName) return statement;\n if (ts.isTypeAliasDeclaration(statement) && statement.name.text === typeName) return statement;\n if (ts.isClassDeclaration(statement) && statement.name?.text === typeName) return statement;\n if (ts.isEnumDeclaration(statement) && statement.name.text === typeName) return statement;\n }\n\n return null;\n};\n\nconst resolveLocalExportedTypes = ({\n type,\n availableExports,\n checker,\n programSource,\n}: {\n type: string;\n availableExports: Set<string>;\n checker: ts.TypeChecker;\n programSource: ts.SourceFile;\n}): string => {\n if (availableExports.size === 0) return type;\n\n let resolved = type;\n\n for (const exportName of availableExports) {\n const hasReference = new RegExp(String.raw`\\b${exportName}\\b`).test(resolved);\n if (!hasReference) continue;\n\n const declaration = findProgramTypeDeclaration(programSource, exportName);\n if (!declaration) continue;\n\n const declarationNode = (\n ts.isClassDeclaration(declaration)\n ? (declaration.name ?? declaration)\n : (ts.isTypeAliasDeclaration(declaration)\n ? declaration.type\n : declaration)\n );\n\n const declarationType = checker.getTypeAtLocation(declarationNode);\n const expanded = normalizeInlineType(expandType(declarationType, checker));\n\n resolved = resolved.replaceAll(new RegExp(String.raw`\\b${exportName}\\b`, 'g'), expanded);\n }\n\n return resolved;\n};\n\nconst findSourceVariableDeclaration = (\n sourceFile: ts.SourceFile,\n exportName: string,\n): ts.VariableDeclaration | null => {\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === exportName) {\n return declaration;\n }\n }\n }\n\n return null;\n};\n\nconst inferValueTypeForExport = ({\n exportName,\n declaration,\n rawContent,\n filePath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource,\n}: {\n exportName: string;\n declaration: ts.VariableDeclaration;\n rawContent: string;\n filePath: string;\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n collectors: ImportCollectors;\n checker?: ts.TypeChecker;\n programSource?: ts.SourceFile;\n}): string => {\n const resolvedChecker = checker ?? getServerProgram().getTypeChecker();\n const resolvedSource = programSource ?? getServerProgram().getSourceFile(filePath);\n\n if (declaration.type) {\n const rawType = normalizeInlineType(rawContent.slice(declaration.type.pos, declaration.type.end).trim());\n const localResolvedType = resolvedSource\n ? resolveLocalExportedTypes({\n type: rawType,\n availableExports,\n checker: resolvedChecker,\n programSource: resolvedSource,\n })\n : rawType;\n\n return sanitizeTypeAndCollectImports({\n type: localResolvedType,\n filePath,\n availableExports,\n fileImports,\n collectors,\n });\n }\n\n try {\n if (!resolvedSource) return 'any';\n\n const programDeclaration = findProgramVariableDeclaration(resolvedSource, exportName);\n if (!programDeclaration) return 'any';\n\n const inferred = resolvedChecker.typeToString(resolvedChecker.getTypeAtLocation(programDeclaration.name));\n const simplified = simplifyInferredType(normalizeInlineType(inferred));\n const localResolvedType = resolveLocalExportedTypes({\n type: simplified,\n availableExports,\n checker: resolvedChecker,\n programSource: resolvedSource,\n });\n\n return sanitizeTypeAndCollectImports({\n type: localResolvedType,\n filePath,\n availableExports,\n fileImports,\n collectors,\n });\n } catch {\n return 'any';\n }\n};\n\n// Extracts a function signature string from an AST function-like node.\nconst extractSignatureFromNode = (\n node: ts.FunctionLikeDeclaration,\n rawContent: string,\n filePath: string,\n availableExports: Set<string>,\n fileImports: Map<string, FileImport>,\n collectors: ImportCollectors,\n checker?: ts.TypeChecker,\n programSource?: ts.SourceFile,\n): string => {\n // Collect generic type parameter names to avoid replacing them with 'any'\n const knownGenerics = new Set<string>();\n if (node.typeParameters) {\n for (const typeParam of node.typeParameters) {\n knownGenerics.add(typeParam.name.text);\n }\n }\n\n const isAsync = node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;\n\n // Generic clause text (<T, U extends string>)\n const genericsClause = node.typeParameters\n ? `<${normalizeInlineType(rawContent.slice(node.typeParameters.pos, node.typeParameters.end))}>`\n : '';\n\n // Parameter list text with default values removed\n const rawParams = node.parameters\n .map(p => normalizeInlineType(rawContent.slice(p.pos, p.end).trim()))\n .join(', ');\n const cleanParams = normalizeInlineType(stripDefaultValues(`(${rawParams})`));\n const localResolvedParams = (checker && programSource)\n ? resolveLocalExportedTypes({\n type: cleanParams,\n availableExports,\n checker,\n programSource,\n })\n : cleanParams;\n\n const sanitizedParams = sanitizeTypeAndCollectImports({\n type: localResolvedParams,\n filePath,\n availableExports,\n fileImports,\n knownGenerics,\n collectors,\n });\n\n // Return type annotation — emitted into generated type strings. Use\n // `unknown` (not `any`) so consumers must narrow at call sites.\n let returnTypeStr = isAsync ? 'Promise<unknown>' : 'unknown';\n if (node.type) {\n const rawReturnType = normalizeInlineType(rawContent.slice(node.type.pos, node.type.end).trim());\n const localResolvedReturnType = (checker && programSource)\n ? resolveLocalExportedTypes({\n type: rawReturnType,\n availableExports,\n checker,\n programSource,\n })\n : rawReturnType;\n\n returnTypeStr = sanitizeTypeAndCollectImports({\n type: localResolvedReturnType,\n filePath,\n availableExports,\n fileImports,\n knownGenerics,\n collectors,\n });\n if (isAsync && !returnTypeStr.startsWith('Promise')) {\n returnTypeStr = `Promise<${returnTypeStr}>`;\n }\n }\n\n return `${genericsClause}${sanitizedParams} => ${returnTypeStr}`;\n};\n\n// Finds and returns the signature for a named export within a parsed source file.\nconst findSignatureForExport = (\n name: string,\n sourceFile: ts.SourceFile,\n rawContent: string,\n filePath: string,\n availableExports: Set<string>,\n fileImports: Map<string, FileImport>,\n collectors: ImportCollectors,\n checker?: ts.TypeChecker,\n programSource?: ts.SourceFile,\n): string => {\n for (const statement of sourceFile.statements) {\n if (ts.isVariableStatement(statement)) {\n for (const decl of statement.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || decl.name.text !== name || !decl.initializer) continue;\n if (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer)) {\n return extractSignatureFromNode(decl.initializer, rawContent, filePath, availableExports, fileImports, collectors, checker, programSource);\n }\n }\n }\n\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) {\n return extractSignatureFromNode(statement, rawContent, filePath, availableExports, fileImports, collectors, checker, programSource);\n }\n }\n\n return 'any';\n};\n\n//? IR node shapes used by the multi-directory merge. Each root directory\n//? produces an `IRDirNode` tree; multiple trees are merged with conflict\n//? detection before final serialization to a TypeScript interface body.\ninterface IRFileNode {\n kind: 'file';\n exports: Map<string, string>;\n defaultExportName: string | null;\n //? Set when the file contains `export * from '<module>'` (wildcard\n //? re-export). When present and no other exports exist, the file is\n //? emitted as a single `name: typeof import('<module>')` so consumers\n //? get the full module shape on `functions.<name>.<...>`.\n wildcardReExport: string | null;\n sourcePath: string;\n}\n\ninterface IRDirNode {\n kind: 'dir';\n children: Map<string, IRFileNode | IRDirNode>;\n sourcePath: string;\n}\n\nconst parseFunctionFile = (fullPath: string, collectors: ImportCollectors): IRFileNode | null => {\n try {\n const rawContent = fs.readFileSync(fullPath, 'utf8');\n const sourceFile = ts.createSourceFile(fullPath, rawContent, ts.ScriptTarget.Latest, true);\n const { availableExports, fileImports } = parseFileTypeContext(rawContent);\n const program = getServerProgram();\n const checker = program.getTypeChecker();\n const programSource = program.getSourceFile(fullPath);\n const exports = new Map<string, string>();\n let defaultExportName: string | null = null;\n let wildcardReExport: string | null = null;\n\n for (const statement of sourceFile.statements) {\n const hasExport = (statement as ts.HasModifiers).modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n\n if (ts.isVariableStatement(statement) && hasExport) {\n for (const decl of statement.declarationList.declarations) {\n if (ts.isIdentifier(decl.name)) {\n const exportName = decl.name.text;\n\n if (decl.initializer && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))) {\n exports.set(exportName, findSignatureForExport(exportName, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined));\n continue;\n }\n\n exports.set(exportName, inferValueTypeForExport({\n exportName,\n declaration: decl,\n rawContent,\n filePath: fullPath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource: programSource ?? undefined,\n }));\n }\n }\n }\n\n if (ts.isFunctionDeclaration(statement) && hasExport && statement.name) {\n exports.set(statement.name.text, findSignatureForExport(statement.name.text, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined));\n }\n\n // export { a, b as c } [from 'module']\n if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n // `export { x } from 'module'` — extract the source module so we can\n // emit `typeof import('module')['x']` and let TypeScript resolve the\n // real type at compile time (instead of falling back to `any`).\n const moduleSpecifier =\n statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)\n ? statement.moduleSpecifier.text\n : null;\n\n for (const specifier of statement.exportClause.elements) {\n const exportName = specifier.name.text;\n const originalName = specifier.propertyName ? specifier.propertyName.text : exportName;\n\n if (moduleSpecifier) {\n // Re-export from another module. `typeof import(...)` resolves\n // through package aliases (`@luckystack/*`) and relative paths.\n // Relative paths are rewritten to be relative to the generated\n // file location, so shims at any depth produce working imports.\n // Package aliases (starting with `@` or a word char but no\n // `.` / `/`) pass through. Wildcard re-exports (`export * from\n // ...`) are not handled here and fall through.\n const resolvedSpecifier = relativizeModuleSpecifier(moduleSpecifier, fullPath);\n exports.set(exportName, `typeof import('${resolvedSpecifier}')['${originalName}']`);\n continue;\n }\n\n const signature = findSignatureForExport(originalName, sourceFile, rawContent, fullPath, availableExports, fileImports, collectors, checker, programSource ?? undefined);\n if (signature !== 'any') {\n exports.set(exportName, signature);\n continue;\n }\n\n const exportDeclaration = findSourceVariableDeclaration(sourceFile, originalName);\n if (exportDeclaration && ts.isIdentifier(exportDeclaration.name)) {\n exports.set(exportName, inferValueTypeForExport({\n exportName: originalName,\n declaration: exportDeclaration,\n rawContent,\n filePath: fullPath,\n availableExports,\n fileImports,\n collectors,\n checker,\n programSource: programSource ?? undefined,\n }));\n continue;\n }\n\n exports.set(exportName, 'any');\n }\n }\n\n // export default someIdentifier\n if (ts.isExportAssignment(statement) && !statement.isExportEquals && ts.isIdentifier(statement.expression)) {\n defaultExportName = statement.expression.text;\n }\n\n // export * from 'module' — wildcard re-export. Stash the resolved\n // module specifier; serialization decides whether to emit it.\n if (\n ts.isExportDeclaration(statement)\n && !statement.exportClause\n && statement.moduleSpecifier\n && ts.isStringLiteral(statement.moduleSpecifier)\n ) {\n wildcardReExport = relativizeModuleSpecifier(statement.moduleSpecifier.text, fullPath);\n }\n }\n\n return { kind: 'file', exports, defaultExportName, wildcardReExport, sourcePath: fullPath };\n } catch (error) {\n console.error(`[TypeMapGenerator] Error parsing functions file ${fullPath}:`, error);\n return null;\n }\n};\n\nconst walkDirToIR = (dir: string, collectors: ImportCollectors): IRDirNode | null => {\n if (!fs.existsSync(dir)) return null;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const children = new Map<string, IRFileNode | IRDirNode>();\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n const subDir = walkDirToIR(fullPath, collectors);\n if (subDir && subDir.children.size > 0) {\n children.set(entry.name, subDir);\n }\n continue;\n }\n\n if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;\n\n const fileName = entry.name.replace('.ts', '');\n const parsed = parseFunctionFile(fullPath, collectors);\n if (parsed && (parsed.exports.size > 0 || parsed.defaultExportName !== null || parsed.wildcardReExport !== null)) {\n children.set(fileName, parsed);\n }\n }\n\n return { kind: 'dir', children, sourcePath: dir };\n};\n\nconst formatConflict = (keyPath: string[], a: IRFileNode | IRDirNode, b: IRFileNode | IRDirNode): string => {\n const dottedKey = keyPath.join('.');\n return (\n `[function-injection] Conflict at \\`functions.${dottedKey}\\`: ` +\n `defined in both \\`${a.sourcePath}\\` and \\`${b.sourcePath}\\`. ` +\n `Delete one — \\`shared/\\` is the canonical location for framework re-exports.`\n );\n};\n\n//? Merge `source` INTO `target` in place, throwing on conflicts. A \"conflict\"\n//? is one of:\n//? - same key path mapped to a file in both roots\n//? - same key path mapped to a file in one root and a directory in another\n//? Two directories with the same name merge recursively without warning so\n//? that `functions/admin/users.ts` + `shared/admin/roles.ts` produce\n//? `functions.admin.{users, roles}` cleanly.\nconst mergeIR = (target: IRDirNode, source: IRDirNode, prefix: string[] = []): void => {\n for (const [name, sourceChild] of source.children) {\n const targetChild = target.children.get(name);\n if (!targetChild) {\n target.children.set(name, sourceChild);\n continue;\n }\n const keyPath = [...prefix, name];\n if (targetChild.kind !== sourceChild.kind) {\n throw new Error(formatConflict(keyPath, targetChild, sourceChild));\n }\n if (targetChild.kind === 'file' || sourceChild.kind === 'file') {\n throw new Error(formatConflict(keyPath, targetChild, sourceChild));\n }\n mergeIR(targetChild, sourceChild, keyPath);\n }\n};\n\nconst serializeIRDir = (dir: IRDirNode, indent: string): string => {\n let output = '';\n for (const [name, child] of dir.children) {\n if (child.kind === 'dir') {\n const subOutput = serializeIRDir(child, `${indent} `);\n if (subOutput.trim()) {\n output += `${indent}${name}: {\\n${subOutput}${indent}};\\n`;\n }\n continue;\n }\n\n const exportsCopy = new Map(child.exports);\n const defaultExportName = child.defaultExportName;\n const defaultSig = defaultExportName ? exportsCopy.get(defaultExportName) : undefined;\n if (defaultSig && defaultExportName) exportsCopy.delete(defaultExportName);\n\n //? Wildcard re-export (`export * from '<module>'`) — emit the file as a\n //? single `name: typeof import('<module>')` so the full module surface\n //? becomes typed under `functions.<name>.<exportFromSource>`. When the\n //? file ALSO has named/default exports, the wildcard is dropped (this\n //? combined form is rare; the named exports take precedence to avoid an\n //? awkward intersection type).\n if (child.wildcardReExport && exportsCopy.size === 0 && !defaultSig) {\n output += `${indent}${name}: typeof import('${child.wildcardReExport}');\\n`;\n continue;\n }\n\n //? Default-only re-exports (`export { default } from '...'`) end up as a\n //? single 'default' key with no `export default <identifier>` statement.\n //? Alias it to the filename so consumers can call `functions.<name>.<name>()`\n //? instead of the awkward `functions.<name>.default()`.\n if (!defaultSig && exportsCopy.size === 1 && exportsCopy.has('default')) {\n const reExportSig = exportsCopy.get('default');\n if (reExportSig) {\n exportsCopy.delete('default');\n exportsCopy.set(name, reExportSig);\n }\n }\n\n let fileOutput = '';\n for (const [exportName, sig] of exportsCopy) {\n fileOutput += `${indent} ${exportName}: ${sig};\\n`;\n }\n if (defaultSig && !fileOutput.trim()) {\n fileOutput += `${indent} ${name}: ${defaultSig};\\n`;\n }\n if (fileOutput) {\n output += `${indent}${name}: {\\n${fileOutput}${indent}};\\n`;\n }\n }\n return output;\n};\n\nexport const generateServerFunctions = (collectors: ImportCollectors): string => {\n const dirs = getServerFunctionDirs();\n if (dirs.length === 0) return '';\n\n const merged: IRDirNode = { kind: 'dir', children: new Map(), sourcePath: '<merged>' };\n for (const dir of dirs) {\n const ir = walkDirToIR(dir, collectors);\n if (!ir) continue;\n mergeIR(merged, ir);\n }\n\n return serializeIRDir(merged, '\\t');\n};\n\n","import * as ts from 'typescript';\nimport path from 'node:path';\nimport { getGeneratedSocketTypesPath } from '@luckystack/core';\n\nimport { getOrInit } from '../internal/mapUtils';\n\nexport interface FileImport {\n source: string;\n isDefault: boolean;\n originalName?: string;\n}\n\nexport interface ImportCollectors {\n namedImports: Map<string, Set<string>>;\n defaultImports: Map<string, string>;\n}\n\nconst toGeneratedImportPath = (source: string, filePath: string): string => {\n if (!source.startsWith('.')) return source;\n\n const outputDir = path.dirname(getGeneratedSocketTypesPath());\n const absoluteSource = path.resolve(path.dirname(filePath), source);\n let relPath = path.relative(outputDir, absoluteSource).replaceAll('\\\\', '/');\n relPath = relPath.replace(/\\.tsx?$/, '');\n if (!relPath.startsWith('.')) relPath = `./${relPath}`;\n return relPath;\n};\n\n// Parses a source file's AST to collect exported type names and import bindings.\n// Uses ts.createSourceFile (no TypeChecker needed) for fast structural discovery.\nexport const parseFileTypeContext = (content: string): {\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n} => {\n const availableExports = new Set<string>();\n const fileImports = new Map<string, FileImport>();\n\n const sourceFile = ts.createSourceFile(\n '__temp__.ts',\n content,\n ts.ScriptTarget.Latest,\n true,\n );\n\n for (const statement of sourceFile.statements) {\n // Collect exported type/interface/class/enum declarations\n if (\n ts.isInterfaceDeclaration(statement)\n || ts.isTypeAliasDeclaration(statement)\n || ts.isClassDeclaration(statement)\n || ts.isEnumDeclaration(statement)\n ) {\n const hasExport = statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);\n if (hasExport && statement.name) {\n availableExports.add(statement.name.text);\n }\n continue;\n }\n\n if (!ts.isImportDeclaration(statement)) continue;\n\n const moduleSpecifier = statement.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n const source = moduleSpecifier.text;\n\n const importClause = statement.importClause;\n if (!importClause) continue;\n\n // Default import: import Foo from './foo'\n if (importClause.name) {\n fileImports.set(importClause.name.text, { source, isDefault: true });\n }\n\n const namedBindings = importClause.namedBindings;\n if (!namedBindings) continue;\n\n // Namespace import: import * as Foo from './foo'\n if (ts.isNamespaceImport(namedBindings)) {\n fileImports.set(namedBindings.name.text, { source, isDefault: true });\n continue;\n }\n\n // Named imports: import { Foo, Bar as Baz } from './foo'\n if (ts.isNamedImports(namedBindings)) {\n for (const specifier of namedBindings.elements) {\n const localName = specifier.name.text;\n const originalName = specifier.propertyName?.text ?? localName;\n fileImports.set(localName, { source, isDefault: false, originalName });\n }\n }\n }\n\n return { availableExports, fileImports };\n};\n\nexport const sanitizeTypeAndCollectImports = ({\n type,\n filePath,\n availableExports,\n fileImports,\n collectors,\n knownGenerics = new Set<string>(),\n}: {\n type: string;\n filePath: string;\n availableExports: Set<string>;\n fileImports: Map<string, FileImport>;\n collectors: ImportCollectors;\n knownGenerics?: Set<string>;\n}): string => {\n const { namedImports, defaultImports } = collectors;\n\n return type.replaceAll(/\\b([A-Z][a-zA-Z0-9_]*)(<[^>]+>)?(\\[\\])?\\b/g, (match: string, typeName: string, _generics: string | undefined, isArray: string | undefined) => {\n const builtins = ['Promise', 'Date', 'Function', 'Array', 'Record', 'Partial', 'Pick', 'Omit', 'Error', 'Map', 'Set', 'Buffer', 'Uint8Array', 'Object'];\n const existingImports = ['SessionLayout'];\n\n if (builtins.includes(typeName) || existingImports.includes(typeName) || knownGenerics.has(typeName)) {\n return match;\n }\n\n const importConfig = fileImports.get(typeName);\n if (importConfig) {\n\n // If the import is from a package (not relative and not an internal alias), we can keep it\n // Internal aliases often start with 'src/' or 'shared/' or '@/'\n const isInternal = importConfig.source.startsWith('.') ||\n importConfig.source.startsWith('/') ||\n importConfig.source.startsWith('src/') ||\n importConfig.source.startsWith('shared/') ||\n importConfig.source.startsWith('server/');\n\n if (!isInternal) {\n const importPath = toGeneratedImportPath(importConfig.source, filePath);\n\n if (importConfig.isDefault) {\n if (!defaultImports.has(importPath) || defaultImports.get(importPath) === typeName) {\n defaultImports.set(importPath, typeName);\n return match;\n }\n } else {\n getOrInit(namedImports, importPath, () => new Set<string>()).add(importConfig.originalName ?? typeName);\n return match;\n }\n }\n }\n\n if (availableExports.has(typeName)) {\n // If it's exported locally in the same file, we used to add a relative import here,\n // but the user wants to flatten out our own types, so we don't import them anymore.\n // (The tsProgram.ts expandType handles API inputs/outputs deeply, \n // but for functionsMeta.ts we just map them to `any` or leave them if they are built-ins).\n // If we *really* wanted to deeply flatten, we'd need to invoke the type checker. \n // For now, mapping non-npm imports to `any` (the fallback below) handles the prompt.\n }\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- `isArray` is `'[]' | false`; false must coerce to empty string\n return `any${isArray || ''}`;\n });\n};\n\n","import { findAllApiFiles, findAllSyncClientFiles, findAllSyncServerFiles } from './typeMap/discovery';\nimport { extractApiName, extractApiVersion, extractPagePath, extractSyncName, extractSyncPagePath, extractSyncVersion } from './typeMap/routeMeta';\nimport { extractAuth, extractDocsMeta, extractHttpMethod, extractRateLimit } from './typeMap/apiMeta';\nimport { buildTypeMapArtifacts, writeTypeMapArtifacts, ApiTypeEntry, SyncTypeEntry } from './typeMap/emitterArtifacts';\nimport {\n getApiStreamPayloadTypeDetailsFromFile,\n getInputTypeDetailsFromFile,\n getOutputTypeDetailsFromFile,\n getSyncClientDataTypeDetailsFromFile,\n getSyncClientOutputTypeDetailsFromFile,\n getSyncClientStreamPayloadTypeDetailsFromFile,\n getSyncServerOutputTypeDetailsFromFile,\n getSyncServerStreamPayloadTypeDetailsFromFile,\n} from './typeMap/extractors';\nimport { generateServerFunctions } from './typeMap/functionsMeta';\nimport { invalidateProgramCache } from './typeMap/tsProgram';\nimport { getSrcDir } from '@luckystack/core';\nimport { assertNoDuplicateNormalizedRouteKeys, assertNoDuplicatePageRoutes, assertValidRouteNaming } from './routeNamingValidation';\nimport { getOrInit } from './internal/mapUtils';\n\ninterface GenerateTypeMapOptions {\n quiet?: boolean;\n}\n\n//? Per-page map of versioned API entries, keyed by `pagePath -> `${name}@${version}``.\ntype TypesByPage = Map<string, Map<string, ApiTypeEntry>>;\n//? Per-page map of versioned sync entries, keyed by `pagePath -> `${name}@${version}``.\ntype SyncTypesByPage = Map<string, Map<string, SyncTypeEntry>>;\n\n//? Shared mutable collectors threaded through both collection passes. Holding\n//? the import maps + unresolved-alias set by reference (rather than returning +\n//? merging) preserves the EXACT population order the inline loops had: API\n//? symbols are registered before sync symbols, in file-discovery order.\ninterface TypeMapCollectors {\n namedImports: Map<string, Set<string>>;\n unresolvedTypeAliases: Set<string>;\n quiet: boolean;\n}\n\n//? Walks every discovered `_api/` file, runs the TypeChecker-backed extractors,\n//? registers unresolved import symbols into the shared collectors, and returns\n//? the per-page API type map. Side-effects (console logging, `namedImports` /\n//? `unresolvedTypeAliases` mutation) occur in the same order as the original\n//? inline loop — this is a pure code-motion extraction, not a behavior change.\nconst collectApiTypes = (apiFiles: string[], collectors: TypeMapCollectors): TypesByPage => {\n const { namedImports, unresolvedTypeAliases, quiet } = collectors;\n const typesByPage: TypesByPage = new Map();\n\n if (!quiet) {\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(`[TypeMapGenerator] Found ${apiFiles.length} API files`, 'cyan');\n }\n\n for (const filePath of apiFiles) {\n const pagePath = extractPagePath(filePath);\n const apiName = extractApiName(filePath);\n const apiVersion = extractApiVersion(filePath);\n\n if (!pagePath || !apiName) continue;\n\n // TypeChecker-based extractors return fully-expanded inline types.\n // No import collection or sanitization is needed for API types.\n const inputTypeResult = getInputTypeDetailsFromFile(filePath);\n const outputTypeResult = getOutputTypeDetailsFromFile(filePath);\n const streamTypeResult = getApiStreamPayloadTypeDetailsFromFile(filePath);\n const inputType = inputTypeResult.text;\n const outputType = outputTypeResult.text;\n const streamType = streamTypeResult.text;\n const httpMethod = extractHttpMethod(filePath, apiName);\n const rateLimit = extractRateLimit(filePath);\n const auth = extractAuth(filePath);\n const meta = extractDocsMeta(filePath);\n\n for (const symbol of [...inputTypeResult.unresolvedSymbols, ...outputTypeResult.unresolvedSymbols, ...streamTypeResult.unresolvedSymbols]) {\n if (!symbol.importPath) {\n unresolvedTypeAliases.add(symbol.name);\n console.error(`[TypeMapGenerator] Unresolved API type (${pagePath}/${apiName}/${apiVersion}): ${symbol.name}`);\n continue;\n }\n getOrInit(namedImports, symbol.importPath, () => new Set<string>()).add(symbol.name);\n }\n\n if (!quiet) {\n console.log(`[TypeMapGenerator] API: ${pagePath}/${apiName}/${apiVersion} (${httpMethod}${rateLimit === undefined ? '' : `, rateLimit: ${rateLimit}`})`);\n }\n\n getOrInit(typesByPage, pagePath, () => new Map()).set(`${apiName}@${apiVersion}`, { input: inputType, output: outputType, stream: streamType, method: httpMethod, rateLimit, auth, version: apiVersion, ...(meta ? { meta } : {}) });\n }\n\n return typesByPage;\n};\n\n//? Pairs `_sync/` server + client files into one entry per route, runs the\n//? TypeChecker-backed extractors for each present side, registers unresolved\n//? import symbols into the shared collectors, and returns the per-page sync\n//? type map. The `allSyncs` Map keeps insertion order (servers first, then\n//? clients) so the downstream iteration + logging order is identical to the\n//? original inline loop. Pure code-motion extraction — no behavior change.\nconst collectSyncTypes = (\n syncServerFiles: string[],\n syncClientFiles: string[],\n collectors: TypeMapCollectors,\n): SyncTypesByPage => {\n const { namedImports, unresolvedTypeAliases, quiet } = collectors;\n const syncTypesByPage: SyncTypesByPage = new Map();\n\n if (!quiet) {\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(' ═══════════════════════════════════════════════════════════════════════════');\n console.log(`[TypeMapGenerator] Found ${syncServerFiles.length} Sync server files, ${syncClientFiles.length} Sync client files`, 'cyan');\n }\n\n const allSyncs = new Map<string, {\n pagePath: string;\n syncName: string;\n serverFile?: string;\n clientFile?: string;\n }>();\n\n for (const serverFile of syncServerFiles) {\n const pagePath = extractSyncPagePath(serverFile);\n const syncName = extractSyncName(serverFile);\n const syncVersion = extractSyncVersion(serverFile);\n if (!pagePath || !syncName) continue;\n\n const key = `${pagePath}/${syncName}/${syncVersion}`;\n const existing = allSyncs.get(key) ?? { pagePath, syncName };\n existing.serverFile = serverFile;\n allSyncs.set(key, existing);\n }\n\n for (const clientFile of syncClientFiles) {\n const pagePath = extractSyncPagePath(clientFile);\n const syncName = extractSyncName(clientFile);\n const syncVersion = extractSyncVersion(clientFile);\n if (!pagePath || !syncName) continue;\n\n const key = `${pagePath}/${syncName}/${syncVersion}`;\n const existing = allSyncs.get(key) ?? { pagePath, syncName };\n existing.clientFile = clientFile;\n allSyncs.set(key, existing);\n }\n\n for (const [, { pagePath, syncName, serverFile, clientFile }] of allSyncs) {\n const syncVersion = extractSyncVersion(serverFile ?? clientFile ?? '');\n\n const clientInputTypeResult = serverFile\n ? getSyncClientDataTypeDetailsFromFile(serverFile)\n : (clientFile\n ? getSyncClientDataTypeDetailsFromFile(clientFile)\n : { text: '{ }', unresolvedSymbols: [] });\n\n const serverOutputTypeResult = serverFile\n ? getSyncServerOutputTypeDetailsFromFile(serverFile)\n : { text: '{ }', unresolvedSymbols: [] };\n const clientOutputTypeResult = clientFile\n ? getSyncClientOutputTypeDetailsFromFile(clientFile)\n : { text: '{ }', unresolvedSymbols: [] };\n const serverStreamTypeResult = serverFile\n ? getSyncServerStreamPayloadTypeDetailsFromFile(serverFile)\n : { text: 'never', unresolvedSymbols: [] };\n const clientStreamTypeResult = clientFile\n ? getSyncClientStreamPayloadTypeDetailsFromFile(clientFile)\n : { text: 'never', unresolvedSymbols: [] };\n\n const clientInputType = clientInputTypeResult.text;\n const serverOutputType = serverOutputTypeResult.text;\n const clientOutputType = clientOutputTypeResult.text;\n const serverStreamType = serverStreamTypeResult.text;\n const clientStreamType = clientStreamTypeResult.text;\n\n const allSyncUnresolvedSymbols = [\n ...clientInputTypeResult.unresolvedSymbols,\n ...serverOutputTypeResult.unresolvedSymbols,\n ...clientOutputTypeResult.unresolvedSymbols,\n ...serverStreamTypeResult.unresolvedSymbols,\n ...clientStreamTypeResult.unresolvedSymbols,\n ];\n\n for (const symbol of allSyncUnresolvedSymbols) {\n if (!symbol.importPath) {\n unresolvedTypeAliases.add(symbol.name);\n console.error(`[TypeMapGenerator] Unresolved Sync type (${pagePath}/${syncName}/${syncVersion}): ${symbol.name}`);\n continue;\n }\n getOrInit(namedImports, symbol.importPath, () => new Set<string>()).add(symbol.name);\n }\n\n if (!quiet) {\n console.log(`[TypeMapGenerator] Sync: ${pagePath}/${syncName}/${syncVersion} (server: ${!!serverFile}, client: ${!!clientFile})`);\n }\n\n //? Prefer @docs metadata from the server file; fall back to client file.\n //? Server is the canonical \"owns the route\" file when both exist.\n const syncMeta = serverFile ? extractDocsMeta(serverFile) : (clientFile ? extractDocsMeta(clientFile) : undefined);\n\n getOrInit(syncTypesByPage, pagePath, () => new Map()).set(`${syncName}@${syncVersion}`, {\n clientInput: clientInputType,\n serverOutput: serverOutputType,\n clientOutput: clientOutputType,\n serverStream: serverStreamType,\n clientStream: clientStreamType,\n version: syncVersion,\n ...(syncMeta ? { meta: syncMeta } : {}),\n });\n }\n\n return syncTypesByPage;\n};\n\nexport const generateTypeMapFile = (options: GenerateTypeMapOptions = {}): void => {\n const { quiet = false } = options;\n assertValidRouteNaming({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n assertNoDuplicateNormalizedRouteKeys({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n //? Hard-fail on duplicate page routes at build time. Dev startup only\n //? warns (so a misplaced file doesn't block the entire dev server);\n //? builds throw so collisions can never ship to production.\n assertNoDuplicatePageRoutes({\n srcDir: getSrcDir(),\n context: 'generating API/sync type maps',\n });\n\n // Rebuild the TypeScript Program on each generation to pick up file changes.\n invalidateProgramCache();\n\n //? Local per-call maps — previously module-level mutable state, which\n //? meant a second call (e.g. from a test or a race) would share and corrupt\n //? state across calls. Moved here so each invocation gets a fresh set.\n const namedImports = new Map<string, Set<string>>();\n const defaultImports = new Map<string, string>();\n\n const unresolvedTypeAliases = new Set<string>();\n const collectors: TypeMapCollectors = { namedImports, unresolvedTypeAliases, quiet };\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Collect API Types\n // ═══════════════════════════════════════════════════════════════════════════\n const apiFiles = findAllApiFiles(getSrcDir());\n const typesByPage = collectApiTypes(apiFiles, collectors);\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Collect Sync Types\n // ═══════════════════════════════════════════════════════════════════════════\n const syncServerFiles = findAllSyncServerFiles(getSrcDir());\n const syncClientFiles = findAllSyncClientFiles(getSrcDir());\n const syncTypesByPage = collectSyncTypes(syncServerFiles, syncClientFiles, collectors);\n\n const functionsInterface = generateServerFunctions({ namedImports, defaultImports });\n\n if (unresolvedTypeAliases.size > 0) {\n const unresolvedList = [...unresolvedTypeAliases].toSorted().join(', ');\n throw new Error(`[TypeMapGenerator] Aborting generation because unresolved type symbols were found: ${unresolvedList}`);\n }\n\n const { content, docsData, schemasContent, diagnosticsData } = buildTypeMapArtifacts({\n typesByPage,\n syncTypesByPage,\n namedImports,\n defaultImports,\n functionsInterface,\n });\n\n writeTypeMapArtifacts({ content, docsData, schemasContent, diagnosticsData });\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR } from '@luckystack/core';\nimport {\n isVersionedApiFileName,\n isVersionedSyncFileName,\n ROUTE_NAMING_RULES,\n} from './routeConventions';\nimport {\n apiMarkerSegment,\n syncMarkerSegment,\n getRoutingRules,\n isRouteTestFile,\n validatePagePath,\n} from './routingRules';\nimport { getOrInit } from './internal/mapUtils';\n\nexport interface RouteNamingIssue {\n kind: 'api' | 'sync';\n filePath: string;\n reason: string;\n expected: string;\n}\n\nexport interface DuplicateRouteKeyIssue {\n kind: 'api' | 'sync';\n routeKey: string;\n filePaths: string[];\n}\n\nconst normalizePath = (value: string): string => {\n return value.replaceAll('\\\\', '/');\n};\n\nconst toRel = (absolute: string): string =>\n path.relative(ROOT_DIR, absolute).replaceAll('\\\\', '/');\n\nconst walkRouteFiles = (dir: string, results: string[] = []): string[] => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n const { ignore } = getRoutingRules();\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const normalizedFullPath = normalizePath(fullPath);\n\n if (ignore(toRel(fullPath))) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') {\n continue;\n }\n\n walkRouteFiles(fullPath, results);\n continue;\n }\n\n if (!entry.isFile() || !entry.name.endsWith('.ts')) {\n continue;\n }\n\n if (isRouteTestFile(entry.name)) {\n continue;\n }\n\n if (normalizedFullPath.includes(apiSeg) || normalizedFullPath.includes(syncSeg)) {\n results.push(fullPath);\n }\n }\n\n return results;\n};\n\nconst getFileRouteToken = ({\n normalizedFilePath,\n marker,\n}: {\n normalizedFilePath: string;\n marker: string;\n}): string => {\n const markerIndex = normalizedFilePath.indexOf(marker);\n if (markerIndex === -1) {\n return '';\n }\n\n const tokenStart = markerIndex + marker.length;\n return normalizedFilePath.slice(tokenStart, normalizedFilePath.length - '.ts'.length);\n};\n\nconst validateRouteFilePath = (filePath: string): RouteNamingIssue[] => {\n const issues: RouteNamingIssue[] = [];\n const normalizedFilePath = normalizePath(path.resolve(filePath));\n const fileName = path.basename(filePath);\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n\n if (normalizedFilePath.includes(apiSeg)) {\n const apiRouteToken = getFileRouteToken({ normalizedFilePath, marker: apiSeg });\n if (apiRouteToken.includes('/')) {\n issues.push({\n kind: 'api',\n filePath: normalizedFilePath,\n reason: 'API route token cannot contain nested path segments (\"/\").',\n expected: ROUTE_NAMING_RULES.api,\n });\n }\n\n if (!isVersionedApiFileName(fileName)) {\n issues.push({\n kind: 'api',\n filePath: normalizedFilePath,\n reason: 'API filename does not match versioned naming.',\n expected: ROUTE_NAMING_RULES.api,\n });\n }\n }\n\n if (normalizedFilePath.includes(syncSeg)) {\n const syncRouteToken = getFileRouteToken({ normalizedFilePath, marker: syncSeg });\n if (syncRouteToken.includes('/')) {\n issues.push({\n kind: 'sync',\n filePath: normalizedFilePath,\n reason: 'Sync route token cannot contain nested path segments (\"/\").',\n expected: `${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n });\n }\n\n if (!isVersionedSyncFileName(fileName)) {\n issues.push({\n kind: 'sync',\n filePath: normalizedFilePath,\n reason: 'Sync filename does not match versioned naming.',\n expected: `${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n });\n }\n }\n\n return issues;\n};\n\nconst resolveApiRouteKey = ({\n srcDir,\n filePath,\n}: {\n srcDir: string;\n filePath: string;\n}): string | null => {\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(srcDir, filePath));\n const segments = relativePath.split('/');\n const apiIndex = segments.indexOf(rules.apiMarker);\n if (apiIndex === -1 || apiIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, apiIndex).join('/');\n const apiFilePath = segments.slice(apiIndex + 1).join('/');\n const rawApiName = apiFilePath.replace(/\\.ts$/, '');\n const versionMatch = rawApiName.match(rules.apiVersionRegex);\n if (!versionMatch) {\n return null;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(rules.apiVersionRegex, '');\n const mappedPageLocation = pageLocation || 'system';\n return `api/${mappedPageLocation}/${apiName}/${version}`;\n};\n\nconst resolveSyncRouteKey = ({\n srcDir,\n filePath,\n}: {\n srcDir: string;\n filePath: string;\n}): string | null => {\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(srcDir, filePath));\n const segments = relativePath.split('/');\n const syncIndex = segments.indexOf(rules.syncMarker);\n if (syncIndex === -1 || syncIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, syncIndex).join('/');\n const syncFilePath = segments.slice(syncIndex + 1).join('/');\n const rawSyncName = syncFilePath.replace(/\\.ts$/, '');\n const syncMatch = rawSyncName.match(rules.syncVersionRegex);\n if (!syncMatch) {\n return null;\n }\n\n const kind = syncMatch[1];\n const version = `v${syncMatch[2]}`;\n const syncName = rawSyncName.replace(rules.syncVersionRegex, '');\n const routeBaseKey = pageLocation\n ? `sync/${pageLocation}/${syncName}/${version}`\n : `sync/${syncName}/${version}`;\n\n return `${routeBaseKey}_${kind}`;\n};\n\nexport const collectInvalidRouteNamingIssues = (srcDir: string): RouteNamingIssue[] => {\n const allRouteFiles = walkRouteFiles(srcDir);\n const issues: RouteNamingIssue[] = [];\n\n for (const filePath of allRouteFiles) {\n issues.push(...validateRouteFilePath(filePath));\n }\n\n return issues.toSorted((a, b) => a.filePath.localeCompare(b.filePath));\n};\n\nexport const collectDuplicateNormalizedRouteKeyIssues = (srcDir: string): DuplicateRouteKeyIssue[] => {\n const allRouteFiles = walkRouteFiles(srcDir);\n const routeKeyToFilePaths = new Map<string, string[]>();\n const routeKeyKinds = new Map<string, 'api' | 'sync'>();\n\n const apiSeg = apiMarkerSegment();\n const syncSeg = syncMarkerSegment();\n for (const filePath of allRouteFiles) {\n const normalizedFilePath = normalizePath(path.resolve(filePath));\n\n if (normalizedFilePath.includes(apiSeg)) {\n const routeKey = resolveApiRouteKey({ srcDir, filePath });\n if (!routeKey) {\n continue;\n }\n\n getOrInit(routeKeyToFilePaths, routeKey, () => []).push(normalizedFilePath);\n routeKeyKinds.set(routeKey, 'api');\n continue;\n }\n\n if (normalizedFilePath.includes(syncSeg)) {\n const routeKey = resolveSyncRouteKey({ srcDir, filePath });\n if (!routeKey) {\n continue;\n }\n\n getOrInit(routeKeyToFilePaths, routeKey, () => []).push(normalizedFilePath);\n routeKeyKinds.set(routeKey, 'sync');\n }\n }\n\n const issues: DuplicateRouteKeyIssue[] = [];\n for (const [routeKey, filePaths] of routeKeyToFilePaths.entries()) {\n if (filePaths.length < 2) {\n continue;\n }\n\n issues.push({\n kind: routeKeyKinds.get(routeKey) ?? 'api',\n routeKey,\n filePaths: filePaths.toSorted((a, b) => a.localeCompare(b)),\n });\n }\n\n return issues.toSorted((a, b) => a.routeKey.localeCompare(b.routeKey));\n};\n\nexport const formatRouteNamingIssues = ({\n issues,\n context,\n}: {\n issues: RouteNamingIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} invalid API/sync route file${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n return `${index + 1}. [${issue.kind.toUpperCase()}] ${issue.filePath}\\n reason: ${issue.reason}\\n expected: ${issue.expected}`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const formatDuplicateRouteKeyIssues = ({\n issues,\n context,\n}: {\n issues: DuplicateRouteKeyIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} duplicate normalized route key${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n const fileList = issue.filePaths.map((filePath) => ` - ${filePath}`).join('\\n');\n return `${index + 1}. [${issue.kind.toUpperCase()}] ${issue.routeKey}\\n files:\\n${fileList}`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const assertValidRouteNaming = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectInvalidRouteNamingIssues(srcDir);\n if (issues.length === 0) {\n return;\n }\n\n throw new Error(formatRouteNamingIssues({ issues, context }));\n};\n\nexport const assertNoDuplicateNormalizedRouteKeys = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectDuplicateNormalizedRouteKeyIssues(srcDir);\n if (issues.length === 0) {\n return;\n }\n\n throw new Error(formatDuplicateRouteKeyIssues({ issues, context }));\n};\n\n//? --- Duplicate-page-route detection ----------------------------------------\n//? `validatePagePath` in @luckystack/core normalizes a `page.tsx` path into a\n//? URL route by stripping invisible-parent folders (`_<name>`). Two files in\n//? DIFFERENT folder trees can therefore compute the SAME route — e.g.\n//? `src/_test/admin/page.tsx` AND `src/admin/page.tsx` both yield `/admin`.\n//? React Router silently keeps the first registration; the second page is\n//? lost without an error. This validator catches the collision at startup\n//? + build time.\n\nexport interface DuplicatePageRouteIssue {\n /** Computed route after invisible-parent stripping (e.g. `/admin`). */\n route: string;\n /** All page.tsx files that resolve to this same route. */\n filePaths: string[];\n}\n\nconst walkPageFiles = (dir: string, results: string[] = []): string[] => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return results;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;\n walkPageFiles(fullPath, results);\n continue;\n }\n if (!entry.isFile()) continue;\n if (entry.name === 'page.tsx' || entry.name === 'page.jsx') {\n results.push(fullPath);\n }\n }\n return results;\n};\n\nexport const collectDuplicatePageRoutes = (srcDir: string): DuplicatePageRouteIssue[] => {\n //? `validatePagePath` is a pure function (no registry side-effects) so\n //? top-level importing it is safe and doesn't drag any boot ordering.\n //? Previously this was a lazy `require()` call which crashed under ESM\n //? (`ReferenceError: require is not defined`); the import-at-the-top\n //? form works in both runtimes the package targets.\n const pageFiles = walkPageFiles(srcDir);\n const routeToFiles = new Map<string, string[]>();\n\n for (const absoluteFilePath of pageFiles) {\n const relative = normalizePath(path.relative(srcDir, absoluteFilePath));\n const result = validatePagePath(relative);\n if (!result.valid || !result.route) continue;\n const list = routeToFiles.get(result.route) ?? [];\n list.push(normalizePath(path.relative(ROOT_DIR, absoluteFilePath)));\n routeToFiles.set(result.route, list);\n }\n\n const issues: DuplicatePageRouteIssue[] = [];\n for (const [route, filePaths] of routeToFiles) {\n if (filePaths.length > 1) {\n issues.push({ route, filePaths });\n }\n }\n return issues;\n};\n\nexport const formatDuplicatePageRouteIssues = ({\n issues,\n context,\n}: {\n issues: DuplicatePageRouteIssue[];\n context: string;\n}): string => {\n const plural = issues.length === 1 ? '' : 's';\n const header = `[RouteNaming] Found ${issues.length} duplicate page route${plural} while ${context}.`;\n const details = issues\n .map((issue, index) => {\n const fileList = issue.filePaths.map((filePath) => ` - ${filePath}`).join('\\n');\n return `${index + 1}. ${issue.route}\\n files:\\n${fileList}\\n fix: rename or move one of the files so only one page.tsx resolves to \"${issue.route}\". Remember that \"_<folder>\" segments are stripped from the URL (invisible-parent rule).`;\n })\n .join('\\n');\n\n return `${header}\\n${details}`;\n};\n\nexport const assertNoDuplicatePageRoutes = ({\n srcDir,\n context,\n}: {\n srcDir: string;\n context: string;\n}): void => {\n const issues = collectDuplicatePageRoutes(srcDir);\n if (issues.length === 0) return;\n throw new Error(formatDuplicatePageRouteIssues({ issues, context }));\n};","//? Consumer-facing registry for scaffold templates AND the selection logic\n//? that decides WHICH template a newly-created file receives.\n//?\n//? Two layers live here:\n//? 1. Content overrides — `registerTemplate(kind, content)`: replace the body\n//? of a template kind with a custom string.\n//? 2. Selection rules — `registerTemplateRule(...)` / `registerTemplateKind(...)`:\n//? decide, given a classified file context, which kind to inject. The\n//? built-in defaults below ARE expressed as rules, so a consumer can\n//? inspect, edit, remove, or extend them from a single overlay file\n//? (`.luckystack/templates/templateRules.ts`, auto-loaded by devkit in dev).\n//?\n//? `templateInjector.ts` reads from this module: it classifies the file\n//? (api / sync_server / sync_client / page), asks `resolveTemplateKind(ctx)`\n//? for the kind, then resolves content (consumer file → override → bundled).\n\n/**\n * The six template kinds the framework ships out of the box. Consumers may\n * register additional kinds (e.g. `page_marketing`) via `registerTemplateKind`.\n */\nexport type BuiltInTemplateKind =\n | 'api'\n | 'sync_server'\n | 'sync_client_paired'\n | 'sync_client_standalone'\n | 'page_plain'\n | 'page_dashboard';\n\n//? `(string & {})` keeps editor autocomplete for the built-in literals while\n//? still accepting arbitrary consumer-defined kind names.\nexport type TemplateKind = BuiltInTemplateKind | (string & {});\n\nexport const BUILT_IN_TEMPLATE_KINDS: readonly BuiltInTemplateKind[] = [\n 'api',\n 'sync_server',\n 'sync_client_paired',\n 'sync_client_standalone',\n 'page_plain',\n 'page_dashboard',\n];\n\n//? Page templates are `.tsx` (they contain JSX); the rest are `.ts`. The\n//? injector reads them as plain text, so the extension is cosmetic at runtime\n//? but load-bearing for the package's own `tsc` program.\nexport const BUILT_IN_TEMPLATE_FILENAMES: Record<BuiltInTemplateKind, string> = {\n api: 'api.template.ts',\n sync_server: 'sync_server.template.ts',\n sync_client_paired: 'sync_client_paired.template.ts',\n sync_client_standalone: 'sync_client_standalone.template.ts',\n page_plain: 'page_plain.template.tsx',\n page_dashboard: 'page_dashboard.template.tsx',\n};\n\n/**\n * Structural classification of the file an injection is being computed for.\n * `templateInjector.ts` derives this from the folder + filename conventions\n * (controlled separately via `registerRoutingRules`). Selection rules match\n * against it to choose a template kind.\n */\nexport interface TemplateMatchContext {\n /** Absolute path of the file being created. */\n filePath: string;\n /** Structural kind derived from the route conventions. */\n fileKind: 'api' | 'sync_server' | 'sync_client' | 'page';\n /** For `sync_client`: whether a paired `_server_v<N>.ts` exists on disk. */\n hasPairedServer: boolean;\n /** Path relative to `src/` (forward slashes), or `null` if outside src. */\n srcRelativePath: string | null;\n}\n\n/** A single template-selection rule. First matching rule (by priority) wins. */\nexport interface TemplateRule {\n kind: TemplateKind;\n match: (ctx: TemplateMatchContext) => boolean;\n /** Higher runs first. Built-in defaults use 10 (specific) / 0 (catch-all). */\n priority: number;\n}\n\ninterface StoredRule extends TemplateRule {\n /** Insertion sequence — later registrations win ties (consumer over default). */\n order: number;\n}\n\nexport interface RegisterTemplateKindOptions {\n /** Predicate deciding when this kind is chosen. */\n match: (ctx: TemplateMatchContext) => boolean;\n /** Optional inline template body (same as calling `registerTemplate`). */\n content?: string;\n /** Higher runs first. Defaults to 100 so consumer kinds beat the built-ins. */\n priority?: number;\n}\n\nconst overrides = new Map<TemplateKind, string>();\nconst rules: StoredRule[] = [];\nlet insertionCounter = 0;\n\n//? Dashboard-flavor heuristic for `page.tsx`. Exported so the scaffolded\n//? consumer `templateRules.ts` can reuse the exact same regex when it\n//? re-declares the default rule (and edit it in place).\nexport const DEFAULT_DASHBOARD_PATH_PATTERN = /\\/(admin|dashboard|settings|billing|account|profile)(\\/|$)/;\n\n// ---------------------------------------------------------------------------\n// Content overrides (v1 API — unchanged surface)\n// ---------------------------------------------------------------------------\n\n/**\n * Override the template body for a given kind. Subsequent injections emit the\n * supplied content with the standard `{{REL_PATH}}` / `{{PAGE_PATH}}` /\n * `{{SYNC_NAME}}` placeholder substitution. Resolution order in the injector\n * is: consumer file (`.luckystack/templates/<kind>.template.*`) → this\n * override → bundled disk template.\n */\nexport const registerTemplate = (kind: TemplateKind, content: string): void => {\n overrides.set(kind, content);\n};\n\n/** Read the registered content override for a kind, or `null` when none. */\nexport const getRegisteredTemplate = (kind: TemplateKind): string | null => {\n return overrides.get(kind) ?? null;\n};\n\n/** Drop every content override. Test-only. */\nexport const clearTemplateOverrides = (): void => {\n overrides.clear();\n};\n\n/** Diagnostic: kinds that currently have a content override. */\nexport const listRegisteredTemplateKinds = (): readonly TemplateKind[] => {\n return [...overrides.keys()];\n};\n\n// ---------------------------------------------------------------------------\n// Selection rules (decide WHICH kind a file gets)\n// ---------------------------------------------------------------------------\n\n/**\n * Register a selection rule. Rules are evaluated by descending `priority`,\n * ties broken by descending registration order (so a later registration —\n * e.g. a consumer overlay — beats an earlier same-priority default).\n */\nexport const registerTemplateRule = (rule: TemplateRule): void => {\n rules.push({ ...rule, order: insertionCounter++ });\n};\n\n/**\n * Register a brand-new template kind: its selection predicate plus (optionally)\n * its inline content. Equivalent to `registerTemplateRule` + `registerTemplate`\n * in one call. Default priority 100 so custom kinds win over the built-ins.\n */\nexport const registerTemplateKind = (kind: TemplateKind, options: RegisterTemplateKindOptions): void => {\n registerTemplateRule({ kind, match: options.match, priority: options.priority ?? 100 });\n if (typeof options.content === 'string') {\n registerTemplate(kind, options.content);\n }\n};\n\n/** Drop every selection rule (including the built-in defaults). */\nexport const clearTemplateRules = (): void => {\n rules.length = 0;\n};\n\n/** Read the active rules in evaluation order (priority desc, then newest first). */\nexport const getTemplateRules = (): readonly TemplateRule[] => {\n return rules\n .toSorted((a, b) => (b.priority - a.priority) || (b.order - a.order))\n .map(({ kind, match, priority }) => ({ kind, match, priority }));\n};\n\n/** Evaluate the active rules against a context; returns the first matching kind. */\nexport const resolveTemplateKind = (ctx: TemplateMatchContext): TemplateKind | null => {\n for (const rule of getTemplateRules()) {\n //? `rule.match` is a user-supplied predicate, NOT String.prototype.match —\n //? the prefer-regexp-test rule is a false positive on this member call.\n // eslint-disable-next-line unicorn/prefer-regexp-test\n if (rule.match(ctx)) return rule.kind;\n }\n return null;\n};\n\n/**\n * Register the framework's built-in default selection rules. Expressed as\n * ordinary rules so a consumer can replace them: call `clearTemplateRules()`\n * then re-register a subset (the scaffolded `templateRules.ts` does exactly\n * this). Idempotent guard prevents double-registration on repeated imports.\n */\nlet defaultsRegistered = false;\nexport const registerDefaultTemplateRules = (): void => {\n if (defaultsRegistered) return;\n defaultsRegistered = true;\n registerTemplateRule({ kind: 'api', priority: 10, match: (c) => c.fileKind === 'api' });\n registerTemplateRule({ kind: 'sync_server', priority: 10, match: (c) => c.fileKind === 'sync_server' });\n registerTemplateRule({ kind: 'sync_client_paired', priority: 10, match: (c) => c.fileKind === 'sync_client' && c.hasPairedServer });\n registerTemplateRule({ kind: 'sync_client_standalone', priority: 10, match: (c) => c.fileKind === 'sync_client' && !c.hasPairedServer });\n registerTemplateRule({\n kind: 'page_dashboard',\n priority: 10,\n match: (c) => c.fileKind === 'page' && DEFAULT_DASHBOARD_PATH_PATTERN.test(c.filePath.replaceAll('\\\\', '/').toLowerCase()),\n });\n //? Catch-all for pages — lowest priority so the dashboard rule wins first.\n registerTemplateRule({ kind: 'page_plain', priority: 0, match: (c) => c.fileKind === 'page' });\n};\n\n/**\n * Test-only: clear rules + content overrides AND re-arm the defaults guard so\n * `registerDefaultTemplateRules()` can repopulate a clean baseline.\n */\nexport const resetTemplateRegistryForTests = (): void => {\n clearTemplateRules();\n clearTemplateOverrides();\n defaultsRegistered = false;\n};\n\n//? Arm the built-in defaults on module load so any importer (the injector,\n//? unit tests, a host without a consumer overlay) has a working baseline.\nregisterDefaultTemplateRules();\n","// Dynamic `import()` of user route modules returns `any` at the JS boundary —\n// there is no safe way to type these without codegen. The unsafe-*, no-dynamic-delete,\n// and prefer-nullish-coalescing rules are suppressed file-wide (falsy defaults on `any`\n// values from module imports); all other rules remain active.\n/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-dynamic-delete, @typescript-eslint/prefer-nullish-coalescing */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from 'node:url';\nimport { tryCatch, getServerFunctionDirs, getSrcDir, ROOT_DIR } from '@luckystack/core';\nimport { getInputTypeFromFile, getSyncClientDataType } from './typeMap/extractors';\nimport { invalidateProgramCache } from './typeMap/tsProgram';\nimport { clearRuntimeTypeResolverCache } from './runtimeTypeResolver';\nimport { getRoutingRules, isRouteTestFile } from './routingRules';\nimport { assertValidRouteNaming, collectDuplicatePageRoutes, formatDuplicatePageRouteIssues } from './routeNamingValidation';\n\nexport const devApis: Record<string, unknown> = {};\nexport const devSyncs: Record<string, unknown> = {};\nexport const devFunctions: Record<string, unknown> = {};\n\nconst normalizePath = (value: string): string => value.replaceAll('\\\\', '/');\n\n//? Mirror build-time discovery (`typeMap/discovery.ts`): consult the active\n//? `RoutingRules.ignore` predicate so the dev loader (boot scan, hot reload,\n//? functions) skips the SAME paths the type-map generator skips. The predicate\n//? receives a forward-slash path relative to the workspace root. The default\n//? rule is `() => false`, so default discovery is unchanged.\nconst isIgnoredPath = (absolutePath: string): boolean => {\n const relativeFromRoot = normalizePath(path.relative(ROOT_DIR, absolutePath));\n return getRoutingRules().ignore(relativeFromRoot);\n};\n\nconst mapApiPageLocation = (pageLocation: string): string => {\n return pageLocation || 'system';\n};\n\n//? Root-level sync routes (directly under `src/_sync/`) get the SAME `'system'`\n//? sentinel as root-level APIs. Without it the loader registered `sync/<name>/v1`\n//? (two segments) while the typed `syncRequest` sends `sync/system/<name>/v1`\n//? and the wire parser (`parseTransportRouteName`) REQUIRES a\n//? `{service}/{name}/{version}` triple — so a root sync silently never\n//? dispatched. Mirrors `mapApiPageLocation` + `extractSyncPagePath`.\nconst mapSyncPageLocation = (pageLocation: string): string => {\n return pageLocation || 'system';\n};\n\nconst resolveApiRouteMetaFromPath = (filePath: string): { routeKey: string; absolutePath: string } | null => {\n const absolutePath = path.resolve(filePath);\n const normalizedAbsolutePath = normalizePath(absolutePath);\n const normalizedSrcDir = normalizePath(getSrcDir());\n\n if (!normalizedAbsolutePath.startsWith(normalizedSrcDir) || !normalizedAbsolutePath.endsWith('.ts')) {\n return null;\n }\n\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(getSrcDir(), absolutePath));\n const segments = relativePath.split('/');\n const apiIndex = segments.indexOf(rules.apiMarker);\n if (apiIndex === -1 || apiIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, apiIndex).join('/');\n const apiFilePath = segments.slice(apiIndex + 1).join('/');\n const rawApiName = apiFilePath.replace(/\\.ts$/, '');\n const versionMatch = rawApiName.match(rules.apiVersionRegex);\n\n if (!versionMatch) {\n return null;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(rules.apiVersionRegex, '');\n const mappedPageLocation = mapApiPageLocation(pageLocation);\n const routeKey = `api/${mappedPageLocation}/${apiName}/${version}`;\n\n return { routeKey, absolutePath };\n};\n\nconst resolveSyncRouteMetaFromPath = (\n filePath: string,\n): { routeKey: string; kind: 'server' | 'client'; absolutePath: string } | null => {\n const absolutePath = path.resolve(filePath);\n const normalizedAbsolutePath = normalizePath(absolutePath);\n const normalizedSrcDir = normalizePath(getSrcDir());\n\n if (!normalizedAbsolutePath.startsWith(normalizedSrcDir) || !normalizedAbsolutePath.endsWith('.ts')) {\n return null;\n }\n\n const rules = getRoutingRules();\n const relativePath = normalizePath(path.relative(getSrcDir(), absolutePath));\n const segments = relativePath.split('/');\n const syncIndex = segments.indexOf(rules.syncMarker);\n if (syncIndex === -1 || syncIndex === segments.length - 1) {\n return null;\n }\n\n const pageLocation = segments.slice(0, syncIndex).join('/');\n const syncFilePath = segments.slice(syncIndex + 1).join('/');\n const rawSyncName = syncFilePath.replace(/\\.ts$/, '');\n const match = rawSyncName.match(rules.syncVersionRegex);\n\n if (!match) {\n return null;\n }\n\n const kind = match[1] as 'server' | 'client';\n const version = `v${match[2]}`;\n const syncName = rawSyncName.replace(rules.syncVersionRegex, '');\n const mappedPageLocation = mapSyncPageLocation(pageLocation);\n const routeBaseKey = `sync/${mappedPageLocation}/${syncName}/${version}`;\n\n return {\n routeKey: `${routeBaseKey}_${kind}`,\n kind,\n absolutePath,\n };\n};\n\nexport const initializeAll = async () => {\n assertValidRouteNaming({\n srcDir: getSrcDir(),\n context: 'starting dev server (npm run server)',\n });\n\n //? Soft-warn on duplicate page routes — DON'T throw on startup so a\n //? misplaced page.tsx doesn't block the entire dev server. The build\n //? path (typeMapGenerator + scripts/generateServerRequests) DOES throw,\n //? so collisions still block release. Same dev-vs-build escalation as\n //? page-placement warnings in `src/main.tsx getRoutes()`.\n const pageRouteIssues = collectDuplicatePageRoutes(getSrcDir());\n if (pageRouteIssues.length > 0) {\n console.warn(formatDuplicatePageRouteIssues({\n issues: pageRouteIssues,\n context: 'starting dev server (npm run server)',\n }));\n }\n\n await Promise.all([initializeApis(), initializeSyncs(), initializeFunctions()]);\n};\n\n// Dev hot-reload uses dynamic `import()` so module load yields to the event\n// loop instead of blocking it the way CommonJS `require()` did. The `?v=...`\n// query is a cachebust so the ESM loader returns a fresh evaluation each save.\nconst importFile = async (absolutePath: string) => {\n const url = `${pathToFileURL(absolutePath).href}?v=${Date.now()}`;\n return import(url);\n};\n\nconst collectTsFiles = (dir: string, relativeTo = \"\"): string[] => {\n const results: string[] = [];\n const entries = fs.readdirSync(dir);\n for (const entry of entries) {\n // Skip node_modules to avoid crawling installed packages (relevant when\n // the src dir contains symlinked packages or nested node_modules trees).\n if (entry === 'node_modules') continue;\n const entryPath = path.join(dir, entry);\n if (isIgnoredPath(entryPath)) continue;\n const relPath = relativeTo ? `${relativeTo}/${entry}` : entry;\n if (fs.statSync(entryPath).isDirectory()) {\n results.push(...collectTsFiles(entryPath, relPath));\n } else if (entry.endsWith(\".ts\") && !isRouteTestFile(entry)) {\n results.push(relPath);\n }\n }\n return results;\n};\n\nconst isMergeable = (value: unknown): value is Record<string, unknown> | ((...args: unknown[]) => unknown) => {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n};\n\nconst resolveFunctionModule = (loadedModule: unknown, fileName: string) => {\n if (!loadedModule || typeof loadedModule !== 'object' || !(\"default\" in loadedModule)) {\n return isMergeable(loadedModule) ? loadedModule : {};\n }\n\n const moduleRecord = loadedModule as Record<string, unknown>;\n const { default: defaultExport, ...namedExports } = moduleRecord;\n const filteredNamedExports = Object.fromEntries(\n Object.entries(namedExports).filter(([key]) => key !== '__esModule')\n );\n\n if (Object.keys(filteredNamedExports).length > 0) {\n return filteredNamedExports;\n }\n\n if (defaultExport !== undefined) {\n return { [fileName]: defaultExport };\n }\n\n return {};\n};\n\nexport const initializeApis = async () => {\n for (const key of Object.keys(devApis)) delete devApis[key];\n //? No invalidateProgramCache() here — cachedProgram starts as null on\n //? module-load (tsProgram.ts), so the first getServerProgram() call\n //? builds it from scratch. With initializeApis + initializeSyncs running\n //? in parallel via Promise.all, invalidating here forced a redundant\n //? double-build (~3-4s waste). Hot-reload paths (upsertApiFromFile,\n //? removeApiFromFile etc.) DO invalidate — that's where it's needed.\n clearRuntimeTypeResolverCache();\n const srcFolder = fs.readdirSync(getSrcDir());\n\n for (const file of srcFolder) {\n await scanApiFolder(file);\n }\n};\n\nexport const upsertApiFromFile = async (filePath: string): Promise<void> => {\n if (isIgnoredPath(path.resolve(filePath))) return;\n const routeMeta = resolveApiRouteMetaFromPath(filePath);\n if (!routeMeta) {\n const normalized = normalizePath(path.resolve(filePath));\n if (normalized.includes('/_api/') && normalized.endsWith('.ts') && !isRouteTestFile(normalized)) {\n console.log(\n `[loader][api] invalid filename: ${normalized}. Expected <name>_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n }\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n\n const [err, module] = await tryCatch(async () => importFile(routeMeta.absolutePath));\n if (err) {\n console.log(`[loader][api] failed to import ${routeMeta.routeKey} from ${routeMeta.absolutePath}:`, err, 'red');\n return;\n }\n\n const resolvedModule = module?.default ? { ...module.default, ...module } : module;\n const { auth = {}, main, rateLimit, httpMethod, schema, validation, errorFormatter } = resolvedModule;\n\n if (!main || typeof main !== 'function') {\n delete devApis[routeMeta.routeKey];\n return;\n }\n\n const inputType = getInputTypeFromFile(routeMeta.absolutePath);\n\n devApis[routeMeta.routeKey] = {\n main,\n auth: {\n login: auth.login || false,\n additional: auth.additional || [],\n },\n rateLimit,\n httpMethod,\n schema,\n inputType,\n inputTypeFilePath: routeMeta.absolutePath,\n validation,\n errorFormatter,\n };\n};\n\nexport const removeApiFromFile = (filePath: string): void => {\n const routeMeta = resolveApiRouteMetaFromPath(filePath);\n if (!routeMeta) {\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n delete devApis[routeMeta.routeKey];\n};\n\nconst scanApiFolder = async (file: string, basePath = \"\") => {\n const fullPath = path.join(getSrcDir(), basePath, file);\n if (isIgnoredPath(fullPath)) return;\n if (!fs.statSync(fullPath).isDirectory()) return;\n\n if (!file.toLowerCase().endsWith(\"api\")) {\n const subFolders = fs.readdirSync(fullPath);\n for (const sub of subFolders) {\n await scanApiFolder(sub, path.join(basePath, file));\n }\n return;\n }\n\n const pageLocation = basePath.replaceAll('\\\\', '/');\n const mappedPageLocation = mapApiPageLocation(pageLocation);\n const tsFiles = collectTsFiles(fullPath);\n\n const apiRules = getRoutingRules();\n for (const relFile of tsFiles) {\n const rawApiName = relFile.replace(/\\.ts$/, \"\").replaceAll('\\\\', '/');\n const versionMatch = rawApiName.match(apiRules.apiVersionRegex);\n if (!versionMatch) {\n console.log(\n `[loader][api] invalid filename: ${path.join(fullPath, relFile)}. Expected <name>_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n continue;\n }\n\n const version = `v${versionMatch[1]}`;\n const apiName = rawApiName.replace(apiRules.apiVersionRegex, '');\n const routeKey = `api/${mappedPageLocation}/${apiName}/${version}`;\n\n const modulePath = path.resolve(path.join(fullPath, relFile));\n const [err, module] = await tryCatch(async () => importFile(modulePath));\n if (err) {\n console.log(`[loader][api] failed to import ${routeKey} from ${modulePath}:`, err, 'red');\n continue;\n }\n\n const resolvedModule = module?.default ? { ...module.default, ...module } : module;\n const { auth = {}, main, rateLimit, httpMethod, schema, validation, errorFormatter } = resolvedModule;\n if (!main || typeof main !== \"function\") continue;\n const inputType = getInputTypeFromFile(modulePath);\n\n devApis[routeKey] = {\n main,\n auth: {\n login: auth.login || false,\n additional: auth.additional || [],\n },\n rateLimit,\n httpMethod,\n schema,\n inputType,\n inputTypeFilePath: modulePath,\n validation,\n errorFormatter,\n };\n }\n};\n\nexport const initializeSyncs = async () => {\n for (const key of Object.keys(devSyncs)) delete devSyncs[key];\n //? See initializeApis above — no invalidation on the boot path. Hot-reload\n //? paths (upsertSyncFromFile / removeSyncFromFile) handle invalidation\n //? when a file actually changes.\n clearRuntimeTypeResolverCache();\n const srcFolder = fs.readdirSync(getSrcDir());\n\n for (const file of srcFolder) {\n await scanSyncFolder(file);\n }\n};\n\nexport const upsertSyncFromFile = async (filePath: string): Promise<void> => {\n if (isIgnoredPath(path.resolve(filePath))) return;\n const routeMeta = resolveSyncRouteMetaFromPath(filePath);\n if (!routeMeta) {\n const normalized = normalizePath(path.resolve(filePath));\n if (normalized.includes(`/${getRoutingRules().syncMarker}/`) && normalized.endsWith('.ts') && !isRouteTestFile(normalized)) {\n console.log(\n `[loader][sync] invalid filename: ${normalized}. Expected <name>_server_v<number>.ts or <name>_client_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n }\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n\n const [err, module] = await tryCatch(async () => importFile(routeMeta.absolutePath));\n if (err) {\n console.log(`[loader][sync] failed to import ${routeMeta.absolutePath}:`, err, 'red');\n return;\n }\n\n const resolvedSyncModule = module?.default\n ? { ...module.default, ...module }\n : module;\n\n if (routeMeta.kind === 'server') {\n if (!resolvedSyncModule.main || typeof resolvedSyncModule.main !== 'function') {\n delete devSyncs[routeMeta.routeKey];\n return;\n }\n\n const inputType = getSyncClientDataType(routeMeta.absolutePath);\n\n devSyncs[routeMeta.routeKey] = {\n main: resolvedSyncModule.main,\n auth: resolvedSyncModule.auth || {},\n inputType,\n inputTypeFilePath: routeMeta.absolutePath,\n //? Forward the per-route `validation` toggle + `errorFormatter` so the dev\n //? loader's sync entry shape matches the prod generator's. Dropping them\n //? made `validation: { input: 'skip' }` / a per-route errorFormatter work\n //? in prod but silently no-op in dev (QUA-013 / QUA-044).\n validation: resolvedSyncModule.validation,\n errorFormatter: resolvedSyncModule.errorFormatter,\n };\n\n return;\n }\n\n if (!resolvedSyncModule.main || typeof resolvedSyncModule.main !== 'function') {\n delete devSyncs[routeMeta.routeKey];\n return;\n }\n\n devSyncs[routeMeta.routeKey] = resolvedSyncModule.main;\n};\n\nexport const removeSyncFromFile = (filePath: string): void => {\n const routeMeta = resolveSyncRouteMetaFromPath(filePath);\n if (!routeMeta) {\n return;\n }\n\n invalidateProgramCache();\n clearRuntimeTypeResolverCache();\n delete devSyncs[routeMeta.routeKey];\n};\n\nconst scanSyncFolder = async (file: string, basePath = \"\") => {\n const fullPath = path.join(getSrcDir(), basePath, file);\n if (isIgnoredPath(fullPath)) return;\n if (!fs.statSync(fullPath).isDirectory()) return;\n\n if (!file.toLowerCase().endsWith(\"sync\")) {\n const subFolders = fs.readdirSync(fullPath);\n for (const sub of subFolders) {\n await scanSyncFolder(sub, path.join(basePath, file));\n }\n return;\n }\n\n const pageLocation = basePath.replaceAll('\\\\', '/');\n const tsFiles = collectTsFiles(fullPath);\n\n const syncRules = getRoutingRules();\n for (const relFile of tsFiles) {\n const rawSyncFileName = relFile.replace(/\\.ts$/, \"\").replaceAll('\\\\', '/');\n const syncMatch = rawSyncFileName.match(syncRules.syncVersionRegex);\n if (!syncMatch) {\n console.log(\n `[loader][sync] invalid filename: ${path.join(fullPath, relFile)}. Expected <name>_server_v<number>.ts or <name>_client_v<number>.ts. File will not be loaded.`,\n 'red'\n );\n continue;\n }\n\n const kind = syncMatch[1];\n const version = `v${syncMatch[2]}`;\n const syncName = rawSyncFileName.replace(syncRules.syncVersionRegex, '');\n const mappedPageLocation = mapSyncPageLocation(pageLocation);\n const routeBaseKey = `sync/${mappedPageLocation}/${syncName}/${version}`;\n\n const filePath = path.resolve(path.join(fullPath, relFile));\n const [fileError, fileResult] = await tryCatch(async () => importFile(filePath));\n if (fileError) {\n console.log(`[loader][sync] failed to import ${filePath}:`, fileError, 'red');\n continue;\n }\n\n const resolvedSyncModule = fileResult?.default\n ? { ...fileResult.default, ...fileResult }\n : fileResult;\n const inputType = getSyncClientDataType(filePath);\n\n if (kind === 'server') {\n devSyncs[`${routeBaseKey}_server`] = {\n main: resolvedSyncModule.main,\n auth: resolvedSyncModule.auth || {},\n inputType,\n inputTypeFilePath: filePath,\n //? Forward `validation` + `errorFormatter` so the dev loader matches the\n //? prod generator's sync entry shape (QUA-013 / QUA-044).\n validation: resolvedSyncModule.validation,\n errorFormatter: resolvedSyncModule.errorFormatter,\n };\n } else {\n devSyncs[`${routeBaseKey}_client`] = resolvedSyncModule.main;\n }\n }\n};\n\n//? Tracks which root directory claimed each key-path so we can detect\n//? cross-root collisions (e.g. `functions/sleep.ts` AND `shared/sleep.ts`)\n//? and surface the same error the codegen emits, instead of silently\n//? merging exports across roots.\nconst functionClaimMap = new Map<string, string>();\n\nexport const initializeFunctions = async () => {\n for (const key of Object.keys(devFunctions)) delete devFunctions[key];\n functionClaimMap.clear();\n\n const dirs = getServerFunctionDirs();\n for (const dir of dirs) {\n if (fs.existsSync(dir)) {\n await scanFunctionsFolder(dir, dir);\n }\n }\n};\n\nconst scanFunctionsFolder = async (dir: string, rootDir: string, basePath: string[] = []) => {\n const entries = fs.readdirSync(dir);\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n if (isIgnoredPath(fullPath)) continue;\n const stat = fs.statSync(fullPath);\n\n if (stat.isDirectory()) {\n await scanFunctionsFolder(fullPath, rootDir, [...basePath, entry]);\n continue;\n }\n\n if (!entry.endsWith(\".ts\")) {\n continue;\n }\n\n const [err, module] = await tryCatch(async () => importFile(fullPath));\n if (err) {\n console.log(`[loader][function] failed to import ${fullPath}:`, err, 'red');\n continue;\n }\n\n const fileName = entry.replace(\".ts\", \"\");\n const resolvedFunctionModule = resolveFunctionModule(module, fileName);\n if (!isMergeable(resolvedFunctionModule)) continue;\n\n const keyPath = [...basePath, fileName].join('.');\n const previousRoot = functionClaimMap.get(keyPath);\n if (previousRoot !== undefined && previousRoot !== rootDir) {\n //? Cross-root collision. Mirror the codegen-time error so dev mode\n //? surfaces the same diagnostic. Skip the import so the previous\n //? claim wins; the next type-map regen will fail the build with the\n //? full message.\n console.log(\n `[loader][function] Conflict at \\`functions.${keyPath}\\`: defined in both \\`${previousRoot}\\` and \\`${rootDir}\\`. Skipping the second copy; fix the duplicate (delete one — \\`shared/\\` is the canonical location for framework re-exports).`,\n 'red',\n );\n continue;\n }\n functionClaimMap.set(keyPath, rootDir);\n\n //? Walk into devFunctions tree, creating nested Record<string, unknown>\n //? subtrees on demand. Each level is structurally a record but typed as\n //? `unknown` after one level of indexing — re-narrow before descent.\n let target: Record<string, unknown> = devFunctions;\n for (const part of basePath) {\n const existing = target[part];\n if (!existing || typeof existing !== 'object') {\n target[part] = {};\n }\n target = target[part] as Record<string, unknown>;\n }\n\n const existingAtFileName = target[fileName];\n if (\n existingAtFileName !== undefined\n && isMergeable(resolvedFunctionModule)\n && isMergeable(existingAtFileName)\n ) {\n Object.assign(resolvedFunctionModule, existingAtFileName);\n }\n\n target[fileName] = resolvedFunctionModule;\n }\n};\n","import * as ts from 'typescript';\nimport { getServerProgram, expandType } from './typeMap/tsProgram';\n\ntype ResolveResult =\n | { status: 'success'; typeText: string }\n | { status: 'error'; message: string };\n\ninterface ObjectField {\n key: string;\n optional: boolean;\n type: string;\n}\n\ninterface ObjectIndexSignature {\n keyName: string;\n keyType: string;\n type: string;\n}\n\ninterface ResolveState {\n stack: Set<string>;\n}\n\nconst MAX_DEPTH = 20;\nconst unresolvedPrefix = '__RUNTIME_UNRESOLVED__::';\n\nconst PRIMITIVE_TYPES = new Set([\n 'string', 'number', 'boolean', 'true', 'false', 'null', 'undefined', 'any', 'unknown', 'void', 'never',\n]);\n\n// These types are structurally opaque — return them as-is without expansion.\nconst SKIP_EXPANSION = new Set([\n 'Date', 'Promise', 'Array', 'Record', 'Partial', 'Required', 'Pick', 'Omit',\n 'Function', 'Map', 'Set', 'Buffer', 'Uint8Array', 'Object', 'WeakMap', 'WeakSet',\n]);\n\nconst toUnresolved = (message: string): string => `${unresolvedPrefix}${message}`;\nexport const isUnresolvedTypeMarker = (value: string): boolean => value.startsWith(unresolvedPrefix);\nexport const getUnresolvedTypeMessage = (value: string): string => value.slice(unresolvedPrefix.length).trim();\n\nconst resolvedTypeCache = new Map<string, ResolveResult>();\n\nexport const clearRuntimeTypeResolverCache = () => {\n resolvedTypeCache.clear();\n};\n\n// ─── string helpers ───────────────────────────────────────────────────────────\n\nconst splitTopLevel = (value: string, splitter: '|' | '&' | ','): string[] => {\n const items: string[] = [];\n let depthParen = 0;\n let depthBrace = 0;\n let depthBracket = 0;\n let depthAngle = 0;\n let quote: \"'\" | '\"' | '`' | null = null;\n let token = '';\n\n for (const char of value) {\n //? Inside a string-literal type (`'a|b'`, `\"x,y\"`) the splitter + brackets\n //? must be ignored — otherwise `'a|b' | number` mis-splits into 3 parts.\n if (quote !== null) {\n if (char === quote) quote = null;\n token += char;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n token += char;\n continue;\n }\n\n if (char === '(') depthParen += 1;\n if (char === ')') depthParen -= 1;\n if (char === '{') depthBrace += 1;\n if (char === '}') depthBrace -= 1;\n if (char === '[') depthBracket += 1;\n if (char === ']') depthBracket -= 1;\n if (char === '<') depthAngle += 1;\n //? Clamp at 0: a function type's `=>` (and `>=`) contributes a `>` with no\n //? matching `<`, which would otherwise drive depthAngle negative and stop\n //? later top-level splits from ever firing.\n if (char === '>') depthAngle = Math.max(0, depthAngle - 1);\n\n if (\n char === splitter\n && depthParen === 0\n && depthBrace === 0\n && depthBracket === 0\n && depthAngle === 0\n ) {\n if (token.trim()) items.push(token.trim());\n token = '';\n continue;\n }\n\n token += char;\n }\n\n if (token.trim()) items.push(token.trim());\n return items;\n};\n\n// Parses a type-expression string into a `ts.TypeNode` by wrapping it in a\n// synthetic `type __X = <expr>;` alias and inspecting the parsed declaration.\n// Returns `null` when the input does not parse as a type alias.\nconst parseTypeNode = (typeText: string): ts.TypeNode | null => {\n const synthetic = `type __RT = ${typeText};`;\n const source = ts.createSourceFile('__runtime_type.ts', synthetic, ts.ScriptTarget.Latest, true);\n const statement = source.statements[0];\n if (!statement || !ts.isTypeAliasDeclaration(statement)) return null;\n return statement.type;\n};\n\nconst parseObjectFields = (typeText: string): { fields: ObjectField[]; indexSignatures: ObjectIndexSignature[] } => {\n const clean = typeText.trim();\n if (!clean.startsWith('{') || !clean.endsWith('}')) {\n return { fields: [], indexSignatures: [] };\n }\n\n const typeNode = parseTypeNode(clean);\n if (!typeNode || !ts.isTypeLiteralNode(typeNode)) {\n return { fields: [], indexSignatures: [] };\n }\n\n const fields: ObjectField[] = [];\n const indexSignatures: ObjectIndexSignature[] = [];\n\n for (const member of typeNode.members) {\n if (ts.isPropertySignature(member) && member.type) {\n let key: string | null = null;\n if (ts.isIdentifier(member.name)) {\n key = member.name.text;\n } else if (ts.isStringLiteral(member.name)) {\n key = member.name.text;\n }\n if (key === null) continue;\n\n fields.push({\n key,\n optional: Boolean(member.questionToken),\n type: member.type.getText().trim(),\n });\n continue;\n }\n\n if (ts.isIndexSignatureDeclaration(member)) {\n const param = member.parameters[0];\n if (!param || !ts.isIdentifier(param.name) || !param.type) continue;\n indexSignatures.push({\n keyName: param.name.text,\n keyType: param.type.getText().trim(),\n type: member.type.getText().trim(),\n });\n }\n }\n\n return { fields, indexSignatures };\n};\n\nconst serializeObjectFields = ({\n fields,\n indexSignatures,\n}: {\n fields: ObjectField[];\n indexSignatures: ObjectIndexSignature[];\n}): string => {\n const segments: string[] = [];\n\n for (const field of fields) {\n segments.push(`${field.key}${field.optional ? '?' : ''}: ${field.type}`);\n }\n\n for (const indexSignature of indexSignatures) {\n segments.push(`[${indexSignature.keyName}: ${indexSignature.keyType}]: ${indexSignature.type}`);\n }\n\n if (segments.length === 0) return '{ }';\n return `{ ${segments.join('; ')} }`;\n};\n\nconst extractStringLiteralKey = (node: ts.TypeNode): string | null => {\n if (!ts.isLiteralTypeNode(node)) return null;\n const literal = node.literal;\n if (!ts.isStringLiteral(literal)) return null;\n return literal.text;\n};\n\nconst parseLiteralUnionKeys = (value: string): string[] | null => {\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n const typeNode = parseTypeNode(trimmed);\n if (!typeNode) return null;\n\n if (ts.isUnionTypeNode(typeNode)) {\n const keys: string[] = [];\n for (const member of typeNode.types) {\n const key = extractStringLiteralKey(member);\n if (key === null) return null;\n keys.push(key);\n }\n return keys.length > 0 ? keys : null;\n }\n\n const singleKey = extractStringLiteralKey(typeNode);\n return singleKey === null ? null : [singleKey];\n};\n\n// ─── TypeChecker-based identifier resolution ──────────────────────────────────\n\n// Resolves a named type identifier to its expanded inline type string using\n// the TypeScript compiler API, following imports across files automatically.\nconst resolveIdentifier = (identifier: string, filePath: string): string => {\n if (PRIMITIVE_TYPES.has(identifier.toLowerCase())) return identifier.toLowerCase();\n if (SKIP_EXPANSION.has(identifier)) return identifier;\n\n try {\n const program = getServerProgram();\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return toUnresolved(`unresolved type ${identifier}`);\n\n const checker = program.getTypeChecker();\n\n for (const stmt of sourceFile.statements) {\n // Local interface / type alias / enum\n if (\n (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt) || ts.isEnumDeclaration(stmt))\n && stmt.name.text === identifier\n ) {\n const symbol = checker.getSymbolAtLocation(stmt.name);\n if (symbol) {\n return expandType(checker.getDeclaredTypeOfSymbol(symbol), checker);\n }\n }\n\n // Import declarations — follow the alias to the original symbol\n if (ts.isImportDeclaration(stmt) && stmt.importClause) {\n const { namedBindings, name: defaultName } = stmt.importClause;\n\n if (namedBindings && ts.isNamedImports(namedBindings)) {\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === identifier) {\n const symbol = checker.getSymbolAtLocation(specifier.name);\n if (symbol) {\n const target = symbol.flags & ts.SymbolFlags.Alias\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n return expandType(checker.getDeclaredTypeOfSymbol(target), checker);\n }\n }\n }\n }\n\n if (defaultName?.text === identifier) {\n const symbol = checker.getSymbolAtLocation(defaultName);\n if (symbol) {\n const target = symbol.flags & ts.SymbolFlags.Alias\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n return expandType(checker.getDeclaredTypeOfSymbol(target), checker);\n }\n }\n }\n }\n\n return toUnresolved(`unresolved type ${identifier}`);\n } catch {\n return toUnresolved(`unresolved type ${identifier}`);\n }\n};\n\n// ─── utility type application ─────────────────────────────────────────────────\n\nconst applyUtilityType = ({\n utilityName,\n utilityArgs,\n filePath,\n depth,\n state,\n}: {\n utilityName: string;\n utilityArgs: string[];\n filePath: string;\n depth: number;\n state: ResolveState;\n}): string => {\n if (utilityName === 'Partial' || utilityName === 'Required') {\n const arg0 = utilityArgs[0];\n if (utilityArgs.length !== 1 || arg0 === undefined) return toUnresolved(`unresolved utility ${utilityName}<...>`);\n const target = resolveExpression(arg0, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(target)) return target;\n const parsed = parseObjectFields(target);\n const fields = parsed.fields;\n if (fields.length === 0) return toUnresolved(`unresolved utility ${utilityName}<${arg0}>`);\n return serializeObjectFields({\n fields: fields.map((f) => ({ ...f, optional: utilityName === 'Partial' })),\n indexSignatures: parsed.indexSignatures,\n });\n }\n\n if (utilityName === 'Pick' || utilityName === 'Omit') {\n const arg0 = utilityArgs[0];\n const arg1 = utilityArgs[1];\n if (utilityArgs.length !== 2 || arg0 === undefined || arg1 === undefined) return toUnresolved(`unresolved utility ${utilityName}<...>`);\n const target = resolveExpression(arg0, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(target)) return target;\n const keys = parseLiteralUnionKeys(arg1);\n if (!keys) return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n const parsed = parseObjectFields(target);\n const fields = parsed.fields;\n if (fields.length === 0) return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n const keySet = new Set(keys);\n const filtered = fields.filter((f) => (utilityName === 'Pick' ? keySet.has(f.key) : !keySet.has(f.key)));\n return serializeObjectFields({ fields: filtered, indexSignatures: parsed.indexSignatures });\n }\n\n if (utilityName === 'Record') {\n const arg0 = utilityArgs[0];\n const arg1 = utilityArgs[1];\n if (utilityArgs.length !== 2 || arg0 === undefined || arg1 === undefined) return toUnresolved('unresolved utility Record<...>');\n const resolvedKey = resolveExpression(arg0, filePath, depth + 1, state);\n const resolvedValue = resolveExpression(arg1, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedKey)) return resolvedKey;\n if (isUnresolvedTypeMarker(resolvedValue)) return resolvedValue;\n const keys = parseLiteralUnionKeys(resolvedKey);\n if (!keys) return `Record<${resolvedKey}, ${resolvedValue}>`;\n return serializeObjectFields({\n fields: keys.map((key) => ({ key, optional: false, type: resolvedValue })),\n indexSignatures: [],\n });\n }\n\n return toUnresolved(`unresolved utility ${utilityName}<${utilityArgs.join(', ')}>`);\n};\n\n// ─── expression resolver ──────────────────────────────────────────────────────\n\nconst resolveExpression = (typeText: string, filePath: string, depth: number, state: ResolveState): string => {\n const type = typeText.trim();\n if (!type) return type;\n\n const visitKey = `${filePath}::${type}`;\n if (state.stack.has(visitKey)) return toUnresolved(`cyclic type reference ${type}`);\n if (depth > MAX_DEPTH) return toUnresolved(`resolution depth exceeded for ${type}`);\n\n state.stack.add(visitKey);\n\n let result: string;\n\n if (isUnresolvedTypeMarker(type)) {\n result = type;\n } else if (type.startsWith('(') && type.endsWith(')')) {\n const inner = resolveExpression(type.slice(1, -1), filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `(${inner})`;\n } else {\n const unionParts = splitTopLevel(type, '|');\n if (unionParts.length > 1) {\n const resolved = unionParts.map((p) => resolveExpression(p, filePath, depth + 1, state));\n const unresolved = resolved.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? resolved.join(' | ');\n } else {\n const intersectionParts = splitTopLevel(type, '&');\n if (intersectionParts.length > 1) {\n const resolved = intersectionParts.map((p) => resolveExpression(p, filePath, depth + 1, state));\n const unresolved = resolved.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? resolved.join(' & ');\n } else if (type.endsWith('[]')) {\n const inner = resolveExpression(type.slice(0, -2), filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `${inner}[]`;\n } else if (type.startsWith('{') && type.endsWith('}')) {\n const parsed = parseObjectFields(type);\n const fields = parsed.fields;\n const indexSignatures = parsed.indexSignatures;\n const resolvedFields: ObjectField[] = [];\n const resolvedIndexSignatures: ObjectIndexSignature[] = [];\n let hadError: string | undefined;\n\n if (fields.length === 0 && indexSignatures.length === 0) {\n result = type;\n state.stack.delete(visitKey);\n return result;\n }\n\n for (const field of fields) {\n const resolvedType = resolveExpression(field.type, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedType)) { hadError = resolvedType; break; }\n resolvedFields.push({ ...field, type: resolvedType });\n }\n\n for (const indexSignature of indexSignatures) {\n const resolvedKeyType = resolveExpression(indexSignature.keyType, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedKeyType)) { hadError = resolvedKeyType; break; }\n\n const resolvedValueType = resolveExpression(indexSignature.type, filePath, depth + 1, state);\n if (isUnresolvedTypeMarker(resolvedValueType)) { hadError = resolvedValueType; break; }\n\n resolvedIndexSignatures.push({\n ...indexSignature,\n keyType: resolvedKeyType,\n type: resolvedValueType,\n });\n }\n\n result = hadError ?? serializeObjectFields({\n fields: resolvedFields,\n indexSignatures: resolvedIndexSignatures,\n });\n } else {\n const typeNode = parseTypeNode(type);\n const referenceInfo = typeNode && ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)\n ? { name: typeNode.typeName.text, args: typeNode.typeArguments }\n : null;\n\n if (referenceInfo?.args && referenceInfo.args.length > 0) {\n const { name: genericName, args: argNodes } = referenceInfo;\n const args = argNodes.map((arg) => arg.getText().trim());\n const firstArg = args[0];\n\n if (genericName === 'Array' && args.length === 1 && firstArg !== undefined) {\n const inner = resolveExpression(firstArg, filePath, depth + 1, state);\n result = isUnresolvedTypeMarker(inner) ? inner : `${inner}[]`;\n } else if (['Partial', 'Required', 'Pick', 'Omit', 'Record'].includes(genericName)) {\n result = applyUtilityType({ utilityName: genericName, utilityArgs: args, filePath, depth, state });\n } else {\n const resolvedArgs = args.map((a) => resolveExpression(a, filePath, depth + 1, state));\n const unresolved = resolvedArgs.find((item) => isUnresolvedTypeMarker(item));\n result = unresolved ?? `${genericName}<${resolvedArgs.join(', ')}>`;\n }\n } else if (referenceInfo && (!referenceInfo.args || referenceInfo.args.length === 0)) {\n result = resolveIdentifier(referenceInfo.name, filePath);\n } else {\n result = type;\n }\n }\n }\n }\n\n state.stack.delete(visitKey);\n return result;\n};\n\n// ─── public API ───────────────────────────────────────────────────────────────\n\nexport const resolveRuntimeTypeText = ({\n typeText,\n filePath,\n}: {\n typeText: string;\n filePath?: string;\n}): ResolveResult => {\n const cleanType = typeText.trim();\n if (!cleanType || !filePath) {\n return { status: 'success', typeText: cleanType };\n }\n\n const cacheKey = `${filePath}::${cleanType}`;\n const cached = resolvedTypeCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const resolved = resolveExpression(cleanType, filePath, 0, { stack: new Set() });\n const result: ResolveResult = isUnresolvedTypeMarker(resolved)\n ? { status: 'error', message: getUnresolvedTypeMessage(resolved) }\n : { status: 'success', typeText: resolved };\n\n resolvedTypeCache.set(cacheKey, result);\n return result;\n};\n","import { watch } from \"chokidar\";\nimport fs from \"node:fs\";\nimport path from 'node:path';\nimport {\n initializeFunctions,\n upsertApiFromFile,\n removeApiFromFile,\n upsertSyncFromFile,\n removeSyncFromFile,\n} from \"./loader\";\nimport {\n shouldInjectTemplate,\n injectTemplate,\n isSyncServerFile,\n getPairedSyncFile,\n getRouteFilenameValidationMessage,\n extractClientInputFromFile,\n extractClientInputFromGeneratedTypes,\n extractSyncPagePath,\n extractSyncName,\n injectServerTemplateWithClientInput,\n updateClientFileForPairedServer,\n updateClientFileForDeletedServer,\n isEmptyFile\n} from \"./templateInjector\";\nimport {\n generateTypeMapFile,\n} from \"./typeMapGenerator.js\";\nimport { findDependentRouteFiles, invalidateGraphForFile } from \"./importDependencyGraph\";\nimport { isPrismaClientMissing, runPrismaGenerate } from \"./prismaClientCheck\";\nimport { tryCatch, getProjectConfig, getLocaleReloader, resolveEnvKey } from \"@luckystack/core\";\nimport { getRoutingRules } from './routingRules';\n\n// ----------------------------\n// Watcher for Hot Reload + Type Generation\n// ----------------------------\n\nconst normalizeFsPath = (value: string): string => path.resolve(value).replaceAll('\\\\', '/');\n\nconst isGeneratedPath = (normalizedPath: string): boolean => {\n return (\n normalizedPath.includes('apiTypes.generated.ts')\n || normalizedPath.includes('apiDocs.generated.json')\n );\n};\n\n// ---------------------------------------------------------------------------\n// Type-map queue\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a self-contained type-map regeneration queue that coalesces\n * concurrent save bursts into a single background run via setImmediate.\n */\nconst createTypeMapQueue = () => {\n const queue = { pending: false, running: false };\n\n const run = () => {\n queue.running = true;\n queue.pending = false;\n const startedAt = Date.now();\n setImmediate(() => {\n void (async () => {\n const [err] = await tryCatch(() => { generateTypeMapFile({ quiet: true }); });\n if (err) {\n console.log(`[HotReload] type map regeneration failed: ${String(err)}`, 'red');\n } else {\n console.log(`[HotReload] type map ready in ${Date.now() - startedAt}ms`, 'green');\n }\n queue.running = false;\n if (queue.pending) {\n run();\n }\n })();\n });\n };\n\n const request = () => {\n if (queue.running) {\n queue.pending = true;\n return;\n }\n run();\n };\n\n return { request };\n};\n\n// ---------------------------------------------------------------------------\n// Pending change sets\n// ---------------------------------------------------------------------------\n\n/**\n * Bundles the four mutable sets that track pending API/Sync add/delete\n * operations so they travel as a single value rather than four separate\n * variables inside the watcher closure.\n */\nconst createPendingChangeSets = () => ({\n apiUpserts: new Set<string>(),\n apiDeletes: new Set<string>(),\n syncUpserts: new Set<string>(),\n syncDeletes: new Set<string>(),\n});\n\n// ---------------------------------------------------------------------------\n// Path classifiers\n// ---------------------------------------------------------------------------\n\n/**\n * Holds path-segment constants derived from the project config.\n * Computed once per `setupWatchers` call.\n */\ninterface PathSegments {\n apiMarkerSlash: string;\n syncMarkerSlash: string;\n apiMarkerNoLead: string;\n syncMarkerNoLead: string;\n srcSegment: string;\n sharedSegment: string;\n localesSegment: string;\n serverFunctionsSegments: string[];\n}\n\nconst buildPathSegments = (): PathSegments => {\n const rules = getRoutingRules();\n const pathsCfg = getProjectConfig().paths;\n const srcSegment = `/${pathsCfg.srcDir.replaceAll('\\\\', '/')}/`;\n const sharedSegment = `/${pathsCfg.sharedDir.replaceAll('\\\\', '/')}/`;\n return {\n apiMarkerSlash: `/${rules.apiMarker}/`,\n syncMarkerSlash: `/${rules.syncMarker}/`,\n apiMarkerNoLead: `${rules.apiMarker}/`,\n syncMarkerNoLead: `${rules.syncMarker}/`,\n srcSegment,\n sharedSegment,\n localesSegment: `${srcSegment}_locales/`,\n serverFunctionsSegments: pathsCfg.serverFunctionDirs.map(\n (dir) => `/${dir.replaceAll('\\\\', '/')}/`,\n ),\n };\n};\n\nconst makeIsInServerFunctionsDir = (segments: PathSegments) =>\n (normalizedPath: string): boolean =>\n segments.serverFunctionsSegments.some((seg) => normalizedPath.includes(seg));\n\nconst makeIsRouteDependencyFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean => {\n if (!normalizedPath.endsWith('.ts') && !normalizedPath.endsWith('.tsx')) return false;\n if (!normalizedPath.includes(segments.srcSegment)) return false;\n if (normalizedPath.includes(segments.apiMarkerSlash) || normalizedPath.includes(segments.syncMarkerSlash)) return false;\n if (isGeneratedPath(normalizedPath)) return false;\n return true;\n };\n\nconst makeIsSharedDependencyFile = (\n segments: PathSegments,\n isInServerFunctionsDir: (p: string) => boolean,\n) =>\n (normalizedPath: string): boolean => {\n if (!(normalizedPath.endsWith('.ts') || normalizedPath.endsWith('.tsx'))) return false;\n if (normalizedPath.includes(segments.sharedSegment)) return true;\n return isInServerFunctionsDir(normalizedPath);\n };\n\nconst makeIsTypeMapRelevantFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean => {\n if (isGeneratedPath(normalizedPath)) return false;\n if (!(normalizedPath.endsWith('.ts') || normalizedPath.endsWith('.tsx'))) return false;\n if (normalizedPath.includes(segments.apiMarkerSlash) || normalizedPath.includes(segments.syncMarkerSlash)) return false;\n return (\n normalizedPath.includes(segments.srcSegment)\n || normalizedPath.endsWith('/config.ts')\n || normalizedPath.includes(segments.sharedSegment)\n );\n };\n\nconst makeIsLocaleFile = (segments: PathSegments) =>\n (normalizedPath: string): boolean =>\n normalizedPath.includes(segments.localesSegment) && normalizedPath.endsWith('.json');\n\n// ---------------------------------------------------------------------------\n// Reload scheduler\n// ---------------------------------------------------------------------------\n\ntype ReloadKey = 'api' | 'sync' | 'functions' | 'typemap' | 'locales';\n\n/**\n * Creates a debounced task scheduler keyed by reload category.\n * Multiple requests for the same key within the debounce window collapse\n * into a single execution.\n */\nconst createReloadScheduler = (debounceMs: () => number) => {\n const timers = new Map<ReloadKey, NodeJS.Timeout>();\n\n return (\n key: ReloadKey,\n task: () => Promise<void> | void,\n delay = debounceMs(),\n ) => {\n const active = timers.get(key);\n if (active) clearTimeout(active);\n\n const timer = setTimeout(() => {\n timers.delete(key);\n // Errors in async tasks must be caught here — an unhandled rejection\n // from a chokidar-triggered async callback crashes the dev server.\n Promise.resolve(task()).catch((error: unknown) => {\n console.log(`[HotReload] Scheduled task threw an error: ${String(error)}`, 'red');\n });\n }, delay);\n\n timers.set(key, timer);\n };\n};\n\n// ---------------------------------------------------------------------------\n// Watcher mounting\n// ---------------------------------------------------------------------------\n\n/**\n * Attaches chokidar watchers to all configured source and function directories.\n * Kept separate from the event-handler setup so the two concerns don't collapse\n * into a single function body.\n */\nconst mountWatchers = (\n onAdd: (p: string) => void,\n onChange: (p: string) => void,\n onDelete: (p: string) => void,\n onFunctionChange: (p: string) => void,\n) => {\n const devConfig = getProjectConfig().dev;\n const pathsConfig = getProjectConfig().paths;\n\n watch(pathsConfig.srcDir, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: devConfig.watcherStabilityThresholdMs,\n pollInterval: devConfig.watcherPollIntervalMs,\n },\n })\n .on('add', onAdd)\n .on('change', onChange)\n .on('unlink', onDelete);\n\n // Watch every configured server-function directory (the multi-dir injection roots).\n for (const dir of pathsConfig.serverFunctionDirs) {\n watch(dir, { ignoreInitial: true })\n .on('add', onFunctionChange)\n .on('change', onFunctionChange)\n .on('unlink', onFunctionChange);\n }\n\n // Watch shared modules separately (changes here cascade to dependent\n // routes via the import-dependency graph). NOTE: `shared/` is also one\n // of the default function-injection roots, so the watcher above already\n // covers it — but consumers can override `serverFunctionDirs` without\n // dropping `shared/`, so we keep this explicit watcher for the cascade\n // behavior. Duplicate add/change events are coalesced downstream.\n watch(pathsConfig.sharedDir, { ignoreInitial: true })\n .on('add', onFunctionChange)\n .on('change', onFunctionChange)\n .on('unlink', onFunctionChange);\n};\n\n// ---------------------------------------------------------------------------\n// Public entry point\n// ---------------------------------------------------------------------------\n\nexport const setupWatchers = () => {\n const isDevMode = resolveEnvKey() !== 'production';\n if (!isDevMode) return;\n\n const segments = buildPathSegments();\n const isInServerFunctionsDir = makeIsInServerFunctionsDir(segments);\n const isRouteDependencyFile = makeIsRouteDependencyFile(segments);\n const isSharedDependencyFile = makeIsSharedDependencyFile(segments, isInServerFunctionsDir);\n const isTypeMapRelevantFile = makeIsTypeMapRelevantFile(segments);\n const isLocaleFile = makeIsLocaleFile(segments);\n\n const typeMap = createTypeMapQueue();\n const pending = createPendingChangeSets();\n const scheduleReload = createReloadScheduler(() => getProjectConfig().dev.hotReloadDebounceMs);\n\n const processPendingApiChanges = async ({ regenerateTypeMap = false }: { regenerateTypeMap?: boolean } = {}) => {\n const deletePaths = [...pending.apiDeletes];\n const upsertPaths = [...pending.apiUpserts];\n pending.apiDeletes.clear();\n pending.apiUpserts.clear();\n\n if (regenerateTypeMap) {\n console.log(`[HotReload] API routes changed (add/delete), scheduling type map regeneration`, 'blue');\n typeMap.request();\n }\n\n for (const deletePath of deletePaths) {\n removeApiFromFile(deletePath);\n console.log(`[HotReload] API removed: ${deletePath}`, 'yellow');\n }\n\n for (const upsertPath of upsertPaths) {\n await upsertApiFromFile(upsertPath);\n console.log(`[HotReload] API reloaded: ${upsertPath}`, 'green');\n }\n };\n\n const processPendingSyncChanges = async ({ regenerateTypeMap = false }: { regenerateTypeMap?: boolean } = {}) => {\n const deletePaths = [...pending.syncDeletes];\n const upsertPaths = [...pending.syncUpserts];\n pending.syncDeletes.clear();\n pending.syncUpserts.clear();\n\n if (regenerateTypeMap) {\n console.log(`[HotReload] Sync routes changed (add/delete), scheduling type map regeneration`, 'blue');\n typeMap.request();\n }\n\n for (const deletePath of deletePaths) {\n removeSyncFromFile(deletePath);\n console.log(`[HotReload] Sync removed: ${deletePath}`, 'yellow');\n }\n\n for (const upsertPath of upsertPaths) {\n await upsertSyncFromFile(upsertPath);\n console.log(`[HotReload] Sync reloaded: ${upsertPath}`, 'green');\n }\n };\n\n const enqueueAffectedRoutesFromDependency = (changedPath: string) => {\n const affectedRoutes = findDependentRouteFiles(changedPath);\n\n if (affectedRoutes.size === 0) {\n console.log(`[HotReload] No API/Sync routes depend on: ${changedPath}`, 'yellow');\n return;\n }\n\n //? With dynamic `import()` + per-load `?v=` cachebust in loader.ts there is\n //? nothing to invalidate on the main thread; the next upsert will fetch a\n //? fresh module instance.\n\n let queuedApiCount = 0;\n let queuedSyncCount = 0;\n\n for (const routePath of affectedRoutes) {\n if (routePath.includes(segments.apiMarkerSlash)) {\n pending.apiDeletes.delete(routePath);\n pending.apiUpserts.add(routePath);\n queuedApiCount += 1;\n } else if (routePath.includes(segments.syncMarkerSlash)) {\n pending.syncDeletes.delete(routePath);\n pending.syncUpserts.add(routePath);\n queuedSyncCount += 1;\n }\n }\n\n console.log(\n `[HotReload] Dependency changed: ${changedPath} -> queued ${queuedApiCount} API and ${queuedSyncCount} Sync route reloads`,\n 'blue'\n );\n\n if (queuedApiCount > 0) {\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n }\n\n if (queuedSyncCount > 0) {\n scheduleReload('sync', async () => {\n await processPendingSyncChanges();\n });\n }\n };\n\n const handleAdd = async (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n const routeValidationMessage = getRouteFilenameValidationMessage(normalizedPath);\n if (routeValidationMessage) {\n if (shouldInjectTemplate(filePath, { isNewFile: true })) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n console.log(`[HotReload] ${routeValidationMessage}`, 'yellow');\n return;\n }\n\n // Check if this is a new empty file that needs a template\n if (shouldInjectTemplate(filePath, { isNewFile: true })) {\n // Special handling for sync server files when client already exists\n if (isSyncServerFile(normalizedPath)) {\n const clientPath = getPairedSyncFile(normalizedPath);\n if (clientPath && fs.existsSync(clientPath) && !isEmptyFile(clientPath)) {\n // Extract clientInput types from existing client file\n const clientInputTypes = extractClientInputFromFile(clientPath);\n if (clientInputTypes) {\n // Inject server template with pre-filled clientInput from client\n await injectServerTemplateWithClientInput(filePath, clientInputTypes);\n // Schedule type regeneration in the background; the client file\n // update + sync upserts below don't depend on the artifact.\n typeMap.request();\n // Update client file to use imported types + add serverOutput.\n // If the rewrite fails (returns false) skip upserts — the client\n // still has the old type shape and registering it now would give\n // the server a mis-matched handler contract.\n const clientRewritten = await updateClientFileForPairedServer(clientPath);\n if (!clientRewritten) {\n console.log(`[HotReload] Paired client rewrite failed, skipping upsert for: ${clientPath}`, 'yellow');\n return;\n }\n await upsertSyncFromFile(filePath);\n await upsertSyncFromFile(clientPath);\n return;\n }\n }\n }\n\n // Default template injection\n const injected = await injectTemplate(filePath);\n if (injected) {\n // Don't continue processing - the template was just injected\n // The next 'change' event will handle it\n return;\n }\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n pending.apiDeletes.delete(normalizedPath);\n pending.apiUpserts.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges({ regenerateTypeMap: true });\n });\n return;\n }\n\n if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n pending.syncDeletes.delete(normalizedPath);\n pending.syncUpserts.add(normalizedPath);\n scheduleReload('sync', async () => {\n await processPendingSyncChanges({ regenerateTypeMap: true });\n });\n return;\n }\n\n // Handle normal file additions\n handleChange(filePath).catch((error: unknown) => {\n console.log(`[HotReload] handleChange threw an error: ${String(error)}`, 'red');\n });\n };\n\n const handleChange = async (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n const routeValidationMessage = getRouteFilenameValidationMessage(normalizedPath);\n if (routeValidationMessage) {\n if (shouldInjectTemplate(filePath)) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n console.log(`[HotReload] ${routeValidationMessage}`, 'yellow');\n return;\n }\n\n if (shouldInjectTemplate(filePath)) {\n const injected = await injectTemplate(filePath);\n if (injected) {\n return;\n }\n }\n\n if (isGeneratedPath(normalizedPath)) {\n return;\n }\n\n if (isLocaleFile(normalizedPath)) {\n scheduleReload('locales', async () => {\n await getLocaleReloader()?.();\n });\n return;\n }\n\n if (isRouteDependencyFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n enqueueAffectedRoutesFromDependency(normalizedPath);\n return;\n }\n\n if (isTypeMapRelevantFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] API changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.apiDeletes.delete(normalizedPath);\n pending.apiUpserts.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n } else if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Sync changed, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.syncDeletes.delete(normalizedPath);\n pending.syncUpserts.add(normalizedPath);\n scheduleReload('sync', async () => {\n await processPendingSyncChanges();\n });\n }\n };\n\n const handleFunctionChange = (changedPath: string) => {\n const normalizedPath = normalizeFsPath(changedPath);\n invalidateGraphForFile(normalizedPath);\n\n scheduleReload('functions', async () => {\n typeMap.request();\n await initializeFunctions();\n });\n\n if (isSharedDependencyFile(normalizedPath)) {\n enqueueAffectedRoutesFromDependency(normalizedPath);\n }\n };\n\n const handleDelete = (filePath: string) => {\n const normalizedPath = normalizeFsPath(filePath);\n invalidateGraphForFile(normalizedPath);\n\n if (isGeneratedPath(normalizedPath)) {\n return;\n }\n\n if (isLocaleFile(normalizedPath)) {\n scheduleReload('locales', async () => {\n await getLocaleReloader()?.();\n });\n return;\n }\n\n if (isRouteDependencyFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n enqueueAffectedRoutesFromDependency(normalizedPath);\n return;\n }\n\n if (isTypeMapRelevantFile(normalizedPath)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Route dependency deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n }\n\n if (normalizedPath.includes(segments.apiMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] API deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.apiUpserts.delete(normalizedPath);\n pending.apiDeletes.add(normalizedPath);\n scheduleReload('api', async () => {\n await processPendingApiChanges();\n });\n } else if (normalizedPath.includes(segments.syncMarkerNoLead)) {\n scheduleReload('typemap', () => {\n console.log(`[HotReload] Sync deleted, scheduling type map regeneration`, 'blue');\n typeMap.request();\n });\n pending.syncUpserts.delete(normalizedPath);\n pending.syncDeletes.add(normalizedPath);\n scheduleReload('sync', async () => {\n // Special handling for sync server file deletion when client exists\n if (isSyncServerFile(normalizedPath)) {\n const clientPath = getPairedSyncFile(normalizedPath);\n if (clientPath && fs.existsSync(clientPath)) {\n // Extract clientInput types from generated types file (server file is already deleted)\n const pagePath = extractSyncPagePath(normalizedPath);\n const syncName = extractSyncName(normalizedPath);\n const clientInputTypes = extractClientInputFromGeneratedTypes(pagePath, syncName);\n\n // Fall back to a placeholder block when types couldn't be extracted from generated file.\n await updateClientFileForDeletedServer(\n clientPath,\n clientInputTypes ?? '{\\n // Types were in _server.ts - please add them here\\n }',\n );\n }\n }\n\n await processPendingSyncChanges();\n });\n }\n };\n\n // Chokidar silently discards the promise returned by async listeners.\n // Wrap each handler so a thrown error is caught instead of becoming an\n // unhandled rejection that would crash the dev server.\n const safeHandleAdd = (p: string): void => { void handleAdd(p).catch((error: unknown) => { console.log(`[HotReload] handleAdd threw an error: ${String(error)}`, 'red'); }); };\n const safeHandleChange = (p: string): void => { void handleChange(p).catch((error: unknown) => { console.log(`[HotReload] handleChange threw an error: ${String(error)}`, 'red'); }); };\n // handleDelete is sync; errors surface inside the scheduleReload callbacks, not at call-site.\n const safeHandleDelete = (p: string): void => { handleDelete(p); };\n\n mountWatchers(safeHandleAdd, safeHandleChange, safeHandleDelete, handleFunctionChange);\n\n //? Generate initial type map on startup — fire-and-forget on the next\n //? event-loop tick so server.listen() happens first. Runtime reads from\n //? the in-memory devApis/devSyncs maps (already populated by\n //? initializeAll() before setupWatchers runs); the on-disk type-map is\n //? purely for IDE IntelliSense + Zod schema files. Deferring drops boot\n //? time ~6-8s on a 54-API project.\n setImmediate(() => {\n void (async () => {\n //? A scaffolded project whose consumer hasn't run `prisma generate` yet\n //? has a schema on disk but no generated `@prisma/client`. The type-map\n //? generator then throws on unresolved model identifiers (e.g. `User`).\n //? Auto-generate ONCE on boot — `prisma generate` only reads the schema,\n //? so it needs no DB credentials and is safe to run unattended.\n if (isPrismaClientMissing()) {\n console.log(`[HotReload] @prisma/client not generated yet — running prisma generate (no DB needed)…`, 'blue');\n const [generateErr, exitCode] = await runPrismaGenerate();\n if (generateErr || exitCode !== 0) {\n console.log(`[HotReload] prisma generate failed${generateErr ? `: ${String(generateErr)}` : ` (exit code ${String(exitCode)})`} — run \\`npm run prisma:generate\\` manually and restart`, 'red');\n } else {\n console.log(`[HotReload] prisma generate complete`, 'green');\n }\n }\n\n const [err] = await tryCatch(() => { generateTypeMapFile({ quiet: true }); });\n if (err) {\n //? Gate the hint on the actual failure CLASS, not the client-dir probe: an\n //? \"unresolved type identifiers\" error is almost always an un-generated\n //? @prisma/client (missing model types). Tying it to the error text means\n //? the hint always shows when it's relevant, even if the dir-probe is\n //? fooled by a stub, while staying quiet for unrelated failures.\n const hint = /unresolved type identifiers/i.test(String(err))\n ? '\\n → This usually means @prisma/client is not generated. Run `npm run prisma:generate` (no database needed) and restart.'\n : '';\n console.log(`[HotReload] initial type map generation failed: ${String(err)}${hint}`, 'red');\n } else {\n console.log(`[HotReload] type map ready in background`, 'green');\n }\n })();\n });\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport * as ts from 'typescript';\nimport { ROOT_DIR, getGeneratedSocketTypesPath, getSrcDir } from '@luckystack/core';\nimport {\n ROUTE_NAMING_EXAMPLES,\n ROUTE_NAMING_RULES,\n isVersionedApiFileName,\n isVersionedSyncClientFileName,\n isVersionedSyncFileName,\n isVersionedSyncServerFileName,\n} from './routeConventions';\nimport { apiMarkerSegment, getRoutingRules, isRouteTestFile, syncMarkerSegment, validatePagePath } from './routingRules';\nimport {\n BUILT_IN_TEMPLATE_FILENAMES,\n getRegisteredTemplate,\n resolveTemplateKind,\n type BuiltInTemplateKind,\n type TemplateKind,\n type TemplateMatchContext,\n} from './templateRegistry';\n\n/**\n * Template Injector\n *\n * Injects default templates into new empty files in _api and _sync folders.\n * Handles sync file pairing with context-aware template selection.\n */\n\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst templatesDir = path.join(__dirname, 'templates');\n\n//? Consumer-side template overrides + selection rules live here (created by the\n//? scaffold). Resolved relative to the project root so it is stable regardless\n//? of the srcDir layout.\nconst getConsumerTemplatesDir = (): string => path.join(ROOT_DIR, '.luckystack', 'templates');\n\n//? Candidate content filenames for a kind: built-ins have a fixed name; custom\n//? kinds resolve to `<kind>.template.tsx` then `<kind>.template.ts`.\nconst templateContentFilenames = (kind: TemplateKind): string[] => {\n const builtIn = BUILT_IN_TEMPLATE_FILENAMES[kind as BuiltInTemplateKind];\n if (builtIn) return [builtIn];\n return [`${kind}.template.tsx`, `${kind}.template.ts`];\n};\n\n//? Resolve raw template content for a kind. Order: consumer file (editable,\n//? shipped to `.luckystack/templates/`) -> registered string override ->\n//? bundled dist template (built-in kinds only). Returns null when nothing\n//? resolves (e.g. a custom kind with no content provided).\nconst resolveTemplateContent = (kind: TemplateKind): string | null => {\n const consumerDir = getConsumerTemplatesDir();\n for (const fileName of templateContentFilenames(kind)) {\n const consumerFile = path.join(consumerDir, fileName);\n if (fs.existsSync(consumerFile)) {\n try {\n return fs.readFileSync(consumerFile, 'utf8');\n } catch (error) {\n console.error(`[TemplateInjector] Could not read consumer template: ${consumerFile}`, error);\n }\n }\n }\n\n const override = getRegisteredTemplate(kind);\n if (override !== null) return override;\n\n const builtInName = BUILT_IN_TEMPLATE_FILENAMES[kind as BuiltInTemplateKind];\n if (builtInName) {\n const bundled = path.join(templatesDir, builtInName);\n try {\n return fs.readFileSync(bundled, 'utf8');\n } catch (error) {\n console.error(`[TemplateInjector] Could not read bundled template: ${bundled}`, error);\n return null;\n }\n }\n\n console.warn(`[TemplateInjector] No content for custom template kind \"${kind}\" — add .luckystack/templates/${kind}.template.tsx or call registerTemplate('${kind}', ...).`);\n return null;\n};\n\n//? Dev-only: load the consumer's `.luckystack/templates/templateRules.ts` once,\n//? so their register* calls configure the injector before the first injection.\n//? Absent file => built-in defaults apply. Never imported in prod (devkit is a\n//? devDependency, and this only runs from the dev watcher path).\nlet consumerTemplateConfig: Promise<void> | null = null;\nconst ensureConsumerTemplateConfigLoaded = (): Promise<void> => {\n consumerTemplateConfig ??= (async () => {\n const dir = getConsumerTemplatesDir();\n for (const fileName of ['templateRules.ts', 'templateRules.mjs', 'templateRules.js']) {\n const rulesFile = path.join(dir, fileName);\n if (!fs.existsSync(rulesFile)) continue;\n\n //? Safety net: verify the resolved path stays within ROOT_DIR before\n //? dynamic-importing it. In practice `dir` is always\n //? `path.join(ROOT_DIR, '.luckystack', 'templates')` (see\n //? `getConsumerTemplatesDir`), so this check can only fail if ROOT_DIR\n //? itself is misconfigured or a symlink escapes the tree.\n const resolvedRulesFile = path.resolve(rulesFile);\n const resolvedRoot = path.resolve(ROOT_DIR);\n if (\n !resolvedRulesFile.startsWith(resolvedRoot + path.sep)\n && resolvedRulesFile !== resolvedRoot\n ) {\n console.warn(\n `[TemplateInjector] Template rules file resolves outside project root — skipping: ${rulesFile}`,\n );\n continue;\n }\n\n try {\n await import(pathToFileURL(rulesFile).href);\n } catch (error) {\n console.error(`[TemplateInjector] Failed to load consumer template rules: ${rulesFile}`, error);\n }\n return;\n }\n })();\n return consumerTemplateConfig;\n};\n\nexport const isEmptyFile = (filePath: string): boolean => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n return content.trim().length === 0;\n } catch {\n return false;\n }\n};\n\nconst isCommentOnlyFile = (filePath: string): boolean => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n const withoutBlockComments = content.replaceAll(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const withoutLineComments = withoutBlockComments.replaceAll(/(^|\\s)\\/\\/.*$/gm, '$1');\n return withoutLineComments.trim().length === 0;\n } catch {\n return false;\n }\n};\n\nexport const isInApiFolder = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n return normalized.includes(apiMarkerSegment()) && filePath.endsWith('.ts') && !isRouteTestFile(filePath);\n};\n\nexport const isInSyncFolder = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n return normalized.includes(syncMarkerSegment()) && filePath.endsWith('.ts') && !isRouteTestFile(filePath);\n};\n\nexport const isPageFile = (filePath: string): boolean => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const filename = normalized.split('/').pop() ?? '';\n return filename === 'page.tsx' || filename === 'page.jsx';\n};\n\nexport const isSyncServerFile = (filePath: string): boolean => {\n return isVersionedSyncServerFileName(filePath);\n};\n\nexport const isSyncClientFile = (filePath: string): boolean => {\n return isVersionedSyncClientFileName(filePath);\n};\n\nconst isVersionedApiFile = (filePath: string): boolean => {\n return isVersionedApiFileName(filePath);\n};\n\nconst isVersionedSyncFile = (filePath: string): boolean => {\n return isVersionedSyncFileName(filePath);\n};\n\nconst getFileName = (filePath: string): string => {\n return path.basename(filePath.replaceAll('\\\\', '/'));\n};\n\nconst stripTsExtension = (fileName: string): string => {\n return fileName.replace(/\\.ts$/, '');\n};\n\nconst toApiBaseName = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n const withoutVersion = withoutExtension.replace(/_v\\d+$/, '');\n return withoutVersion || 'myApi';\n};\n\nconst toSyncBaseName = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n const withoutVersionedKind = withoutExtension.replace(/_(?:server|client)_v\\d+$/, '');\n const withoutKindOnly = withoutVersionedKind.replace(/_(?:server|client)$/, '');\n const withoutVersionOnly = withoutKindOnly.replace(/_v\\d+$/, '');\n return withoutVersionOnly || 'mySync';\n};\n\nconst getApiFilenameReason = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n\n if (/_v\\d+$/.test(withoutExtension)) {\n return 'The filename already looks versioned.';\n }\n\n if (/_v\\d+/.test(withoutExtension)) {\n return 'The version token must be at the end of the filename.';\n }\n\n if (/_server|_client/.test(withoutExtension)) {\n return 'API files do not use _server/_client suffixes.';\n }\n\n return 'Missing required version suffix.';\n};\n\nconst getSyncFilenameReason = (fileName: string): string => {\n const withoutExtension = stripTsExtension(fileName);\n\n if (/_(?:server|client)_v\\d+$/.test(withoutExtension)) {\n return 'The filename already looks versioned.';\n }\n\n if (/_(?:server|client)$/.test(withoutExtension)) {\n return 'Sync files with _server/_client must include a version suffix like _v1.';\n }\n\n if (/_v\\d+$/.test(withoutExtension)) {\n return 'Sync files with versions must also include _server or _client.';\n }\n\n return 'Missing required sync kind and version suffix.';\n};\n\nexport const getRouteFilenameValidationMessage = (filePath: string): string | null => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const fileName = getFileName(normalized);\n\n if (isInApiFolder(normalized) && !isVersionedApiFile(normalized)) {\n const base = toApiBaseName(fileName);\n return [\n `Invalid API filename: ${fileName}`,\n `Reason: ${getApiFilenameReason(fileName)}`,\n `Expected: ${ROUTE_NAMING_RULES.api}`,\n `Example: ${base}_v1.ts (for example ${ROUTE_NAMING_EXAMPLES.api})`,\n 'This file is ignored by route loading and type generation until it is renamed.'\n ].join(' ');\n }\n\n if (isInSyncFolder(normalized) && !isVersionedSyncFile(normalized)) {\n const base = toSyncBaseName(fileName);\n return [\n `Invalid sync filename: ${fileName}`,\n `Reason: ${getSyncFilenameReason(fileName)}`,\n `Expected: ${ROUTE_NAMING_RULES.syncServer} or ${ROUTE_NAMING_RULES.syncClient}`,\n `Examples: ${base}_server_v1.ts, ${base}_client_v1.ts (for example ${ROUTE_NAMING_EXAMPLES.syncServer})`,\n 'This file is ignored by route loading and type generation until it is renamed.'\n ].join(' ');\n }\n\n return null;\n};\n\nconst getInvalidVersionMessage = (filePath: string): string => {\n const validationMessage = getRouteFilenameValidationMessage(filePath) ?? 'Invalid route filename.';\n return `// ${validationMessage}\\n`;\n};\n\n//? Compute the validator-friendly path (relative to `src/`, forward slashes)\n//? for a page file. Returns `null` if the file is outside `getSrcDir()`.\nconst computeSrcRelativePath = (filePath: string): string | null => {\n try {\n const srcDir = getSrcDir();\n const absolute = path.resolve(filePath);\n const normalizedSrc = srcDir.replaceAll('\\\\', '/');\n const normalizedAbs = absolute.replaceAll('\\\\', '/');\n if (!normalizedAbs.startsWith(`${normalizedSrc}/`)) return null;\n return normalizedAbs.slice(normalizedSrc.length + 1);\n } catch {\n return null;\n }\n};\n\n//? Mirror of `getInvalidVersionMessage` for page.tsx files placed in\n//? locations the framework router will silently skip. Instead of writing\n//? the plain/dashboard template (which would render fine but never get\n//? routed), we write a commented diagnostic block so the developer\n//? immediately sees WHY their page isn't appearing.\nconst getInvalidPagePlacementMessage = (_filePath: string, reason: string, srcRelative: string): string => {\n const lines = [\n '//? --- LUCKYSTACK PLACEMENT WARNING ---',\n '//? This page.tsx is in a location the file-based router will not route.',\n `//? Reason: ${reason}`,\n `//? Path: ${srcRelative}`,\n '//?',\n '//? Common fixes:',\n \"//? - Move the file up so a visible (non-underscore) folder segment remains:\",\n \"//? e.g. src/_marketing/page.tsx -> src/_marketing/landing/page.tsx\",\n \"//? (the new file routes at /landing — `_marketing` stays invisible).\",\n \"//? - Or move the file OUT of a reserved framework folder (_api, _sync,\",\n \"//? _components, _functions, _shared, _providers, _locales, _sockets, _server).\",\n '//?',\n '//? Delete the file or move it to fix; the dev server will re-inject a',\n '//? real page template once the placement is valid.',\n '',\n //? Named export instead of `export {};` so the file satisfies\n //? `unicorn/require-module-specifiers` (and stays a valid ES module\n //? without dragging in side-effect-only semantics). Reads back as a\n //? cheap runtime tag for tooling that wants to detect the warning.\n \"export const __luckystackPlacementWarning = true;\",\n '',\n ];\n return lines.join('\\n');\n};\n\n/**\n * Get the paired sync file path (server -> client or client -> server)\n */\nexport const getPairedSyncFile = (filePath: string): string | null => {\n const normalized = filePath.replaceAll('\\\\', '/');\n if (isSyncServerFile(normalized)) {\n return normalized.replace(/_server_v(\\d+)\\.ts$/, '_client_v$1.ts');\n }\n if (isSyncClientFile(normalized)) {\n return normalized.replace(/_client_v(\\d+)\\.ts$/, '_server_v$1.ts');\n }\n return null;\n};\n\n/**\n * Check if a paired sync file exists\n */\nexport const hasPairedFile = (filePath: string): boolean => {\n const pairedPath = getPairedSyncFile(filePath);\n if (!pairedPath) return false;\n return fs.existsSync(pairedPath);\n};\n\n/**\n * Extract page path from a sync file path (e.g., \"examples\" from \"src/examples/_sync/test_server_v1.ts\")\n */\nexport const extractSyncPagePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /src\\/(.+?)\\/_sync\\//.exec(normalized);\n if (match?.[1]) return match[1];\n //? A sync directly under `src/_sync/` resolves to the `'system'` sentinel —\n //? the SAME page key the type-map generator (`routeMeta.extractSyncPagePath`)\n //? and the dev loader use for root syncs. Returning `''` here injected\n //? `type PagePath = '';` into the paired client/server template, which then\n //? failed to index `SyncTypeMap['system']` — a broken generated reference.\n if (/(?:^|\\/)src\\/_sync\\//.test(normalized)) return 'system';\n return '';\n};\n\n/**\n * Extract sync name from a sync file path (e.g., \"test\" from \"src/examples/_sync/test_server_v1.ts\")\n */\nexport const extractSyncName = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n const match = /_sync\\/(.+)\\.ts$/.exec(normalized);\n if (!match) {\n const basename = path.basename(filePath, '.ts');\n return basename.replace(/_server_v\\d+$/, '').replace(/_client_v\\d+$/, '');\n }\n\n return (match[1] ?? '').replace(/_server_v\\d+$/, '').replace(/_client_v\\d+$/, '');\n};\n\n/**\n * Extract clientInput type body from a sync file's SyncParams interface\n * Returns the content between the braces of clientInput: { ... }\n */\nexport const extractClientInputFromFile = (filePath: string): string | null => {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n\n // Find interface SyncParams\n const syncParamsMatch = /interface\\s+SyncParams\\s*\\{/.exec(content);\n if (!syncParamsMatch) return null;\n\n //? Scope the `clientInput` search to the region AFTER the `SyncParams`\n //? declaration. An unscoped global search could match a `clientInput:` in\n //? an earlier comment, a different interface, or a destructure above the\n //? `SyncParams` body and extract the wrong block.\n const searchRegion = content.slice(syncParamsMatch.index + syncParamsMatch[0].length);\n const clientInputMatch = /clientInput\\s*:\\s*\\{/.exec(searchRegion);\n if (!clientInputMatch) return null;\n\n // Extract balanced braces\n const startIndex = content.indexOf(\n '{',\n syncParamsMatch.index + syncParamsMatch[0].length + clientInputMatch.index,\n );\n if (startIndex === -1) return null;\n let depth = 0;\n let endIndex = -1;\n\n for (let i = startIndex; i < content.length; i++) {\n if (content[i] === '{') depth++;\n else if (content[i] === '}') depth--;\n\n if (depth === 0) {\n endIndex = i;\n break;\n }\n }\n\n //? Braces never balanced (truncated / malformed file) — return null rather\n //? than a single `{` of garbage that a truthiness-checking caller would\n //? splice into user source.\n if (endIndex === -1) return null;\n\n return content.slice(startIndex, endIndex + 1);\n } catch (error) {\n console.error(`[TemplateInjector] Error extracting clientInput from ${filePath}:`, error);\n return null;\n }\n};\n\n/**\n * Extract clientInput type from the generated apiTypes.generated.ts file\n * Used when the server file is already deleted but we need to migrate types to client\n */\nexport const extractClientInputFromGeneratedTypes = (pagePath: string, syncName: string): string | null => {\n try {\n const generatedTypesPath = getGeneratedSocketTypesPath();\n const content = fs.readFileSync(generatedTypesPath, 'utf8');\n\n const escapeRegex = (value: string) => value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n const escapedPagePath = escapeRegex(pagePath);\n const escapedSyncName = escapeRegex(syncName);\n\n const pageBlockRegex = new RegExp(String.raw`'${escapedPagePath}'\\s*:\\s*\\{([\\s\\S]*?)\\n\\s{2}\\};`, 'm');\n const pageBlockMatch = content.match(pageBlockRegex);\n if (!pageBlockMatch?.[1]) {\n console.log(`[TemplateInjector] Could not find page block for ${pagePath}`);\n return null;\n }\n\n const pageBlock = pageBlockMatch[1];\n\n const syncEntryPattern = new RegExp(String.raw`'${escapedSyncName}':\\s*\\{\\s*clientInput:\\s*`);\n const match = pageBlock.match(syncEntryPattern);\n\n if (!match || typeof match.index !== 'number') {\n console.log(`[TemplateInjector] Could not find sync entry for ${pagePath}/${syncName}`);\n return null;\n }\n\n const pageStart = content.indexOf(pageBlock);\n const globalMatchIndex = pageStart + match.index;\n\n // Find the start of clientInput value (the opening brace)\n const searchStart = globalMatchIndex + match[0].length;\n const braceStart = content.indexOf('{', searchStart - 1);\n\n if (braceStart === -1) return null;\n\n // Extract balanced braces\n let depth = 0;\n let endIndex = -1;\n\n for (let i = braceStart; i < content.length; i++) {\n if (content[i] === '{') depth++;\n else if (content[i] === '}') depth--;\n\n if (depth === 0) {\n endIndex = i;\n break;\n }\n }\n\n //? Braces never balanced — return null instead of a lone `{` of garbage.\n if (endIndex === -1) return null;\n\n const extracted = content.slice(braceStart, endIndex + 1);\n console.log(`[TemplateInjector] Extracted clientInput types: ${extracted}`);\n return extracted;\n } catch (error) {\n console.error(`[TemplateInjector] Error extracting clientInput from generated types:`, error);\n return null;\n }\n};\n\n/**\n * Calculate the relative path prefix (e.g., '../../../') to reach project root from a file\n * @param filePath - Absolute or relative path to the file\n * @returns The relative path prefix to reach project root\n */\nexport const calculateRelativePath = (filePath: string): string => {\n const normalized = filePath.replaceAll('\\\\', '/');\n\n //? Anchor on the CONFIGURED srcDir, not the literal substring `src/`. A\n //? non-`src` layout (`srcDir: 'app'`) or a root path that itself contains\n //? `src/` (`C:/work/srcrepo/...`) computed the wrong depth with the old\n //? `indexOf('src/')`, breaking the injected `{{REL_PATH}}` import. Reuse the\n //? same srcDir-driven anchoring the rest of the package uses (mirrors\n //? `computeSrcRelativePath`). For the standard `src` layout this is\n //? byte-identical to the old heuristic.\n const srcRelative = computeSrcRelativePath(filePath);\n if (srcRelative !== null) {\n try {\n const srcDepthFromRoot = path\n .relative(ROOT_DIR, getSrcDir())\n .replaceAll('\\\\', '/')\n .split('/')\n .filter((segment) => segment.length > 0).length;\n //? `srcRelative` is `<dirs.../file.ts>` relative to srcDir. The number of\n //? `../` to climb from the FILE's directory up to srcDir is the count of\n //? its DIRECTORY segments (drop the trailing filename). Adding srcDir's\n //? own depth below the project root gives the climb to root — the template\n //? then re-descends via the literal `src/` it appends after `{{REL_PATH}}`.\n const dirSegmentsAfterSrc = Math.max(\n 0,\n srcRelative.split('/').filter((segment) => segment.length > 0).length - 1,\n );\n return '../'.repeat(srcDepthFromRoot + dirSegmentsAfterSrc);\n } catch {\n //? Fall through to the literal-`src/` heuristic below.\n }\n }\n\n // Fallback (relative path the watcher handed us, or srcDir unresolvable):\n // Find the 'src/' part of the path\n const srcIndex = normalized.indexOf('src/');\n if (srcIndex === -1) {\n // Fallback: count from beginning if src not found\n console.warn(`[TemplateInjector] Could not find /src/ in path: ${filePath}`);\n return '../../../'; // default fallback\n }\n\n // Get path after 'src/' (e.g., 'examples/examples2/_api/file.ts')\n const relativePath = normalized.slice(Math.max(0, srcIndex + 4)); // +4 to skip 'src/'\n\n // Count segments (directories + filename)\n const segments = relativePath.split('/').filter(s => s.length > 0).length;\n\n // We need to go up `segments` levels to reach project root\n // e.g., 'examples/_api/file.ts' = 3 segments -> '../../../'\n return '../'.repeat(segments);\n};\n\n// ---------------------------------------------------------------------------\n// File classification helpers\n// ---------------------------------------------------------------------------\n\ntype FileClassification =\n | { fileKind: 'api'; hasPairedServer: false; srcRelativePath: null }\n | { fileKind: 'sync_server'; hasPairedServer: false; srcRelativePath: null }\n | { fileKind: 'sync_client'; hasPairedServer: boolean; srcRelativePath: null }\n | { fileKind: 'page'; hasPairedServer: false; srcRelativePath: string | null }\n | null;\n\n/**\n * Determines the structural file kind and paired-server presence for template selection.\n * Returns null for files that should not receive a template.\n */\nconst classifyFile = (filePath: string): FileClassification => {\n if (isInApiFolder(filePath)) {\n return { fileKind: 'api', hasPairedServer: false, srcRelativePath: null };\n }\n\n if (isInSyncFolder(filePath)) {\n if (isSyncServerFile(filePath)) {\n return { fileKind: 'sync_server', hasPairedServer: false, srcRelativePath: null };\n }\n if (isSyncClientFile(filePath)) {\n return { fileKind: 'sync_client', hasPairedServer: hasPairedFile(filePath), srcRelativePath: null };\n }\n console.log(`[TemplateInjector] Unknown sync file type: ${filePath}`);\n return null;\n }\n\n if (isPageFile(filePath)) {\n return { fileKind: 'page', hasPairedServer: false, srcRelativePath: computeSrcRelativePath(filePath) };\n }\n\n return null;\n};\n\n/**\n * Validates page placement for a classified page file.\n * Returns the placement-warning content when the page is un-routable, null when valid.\n */\nconst checkPagePlacement = (filePath: string, srcRelativePath: string | null): string | null => {\n if (srcRelativePath === null) return null;\n const placement = validatePagePath(srcRelativePath);\n if (!placement.valid) {\n return getInvalidPagePlacementMessage(filePath, placement.reason ?? 'invalid placement', srcRelativePath);\n }\n return null;\n};\n\n/**\n * Substitutes `{{REL_PATH}}`, `{{PAGE_PATH}}`, and `{{SYNC_NAME}}` placeholders\n * in a raw template string. Also strips `@ts-ignore`/`@ts-expect-error` pragma\n * lines that guard `{{REL_PATH}}` imports in built-in templates.\n */\nconst applyTemplatePlaceholders = (\n content: string,\n filePath: string,\n fileKind: TemplateMatchContext['fileKind'],\n): string => {\n const relPath = calculateRelativePath(filePath);\n const pragmaPattern = /\\/\\/\\s*@ts-(?:ignore|expect-error).*\\r?\\n(.*)\\{\\{REL_PATH\\}\\}/g;\n let result = content.replaceAll(pragmaPattern, (_, prefix) => `${prefix}${relPath}`);\n result = result.replaceAll('{{REL_PATH}}', relPath);\n\n //? Sync templates may carry PAGE_PATH / SYNC_NAME placeholders (paired client\n //? + server). Substitute for any sync file — a no-op when the placeholders\n //? are absent (e.g. standalone client).\n if (fileKind === 'sync_client' || fileKind === 'sync_server') {\n const pagePath = extractSyncPagePath(filePath);\n const syncName = extractSyncName(filePath);\n result = result.replaceAll('{{PAGE_PATH}}', pagePath);\n result = result.replaceAll('{{SYNC_NAME}}', syncName);\n }\n\n return result;\n};\n\nconst getTemplate = (filePath: string): string | null => {\n //? Classify the file structurally; the registered selection RULES then decide\n //? the kind (consumer-editable via `.luckystack/templates/templateRules.ts`).\n const classification = classifyFile(filePath);\n if (!classification) return null;\n\n const { fileKind, hasPairedServer, srcRelativePath } = classification;\n\n //? Validate page placement BEFORE rule selection. A page inside a reserved\n //? framework folder (`_api`, `_sync`, ...) or with no URL segment left\n //? after stripping invisible-parent folders is silently un-routed — so we\n //? emit a commented diagnostic instead of a dead plain/dashboard skeleton.\n if (fileKind === 'page') {\n const placementWarning = checkPagePlacement(filePath, srcRelativePath);\n if (placementWarning !== null) return placementWarning;\n }\n\n const ctx: TemplateMatchContext = { filePath, fileKind, hasPairedServer, srcRelativePath };\n const templateKind = resolveTemplateKind(ctx);\n if (!templateKind) {\n console.log(`[TemplateInjector] No template rule matched for ${filePath} (fileKind=${fileKind})`);\n return null;\n }\n\n const rawContent = resolveTemplateContent(templateKind);\n if (rawContent === null) return null;\n\n return applyTemplatePlaceholders(rawContent, filePath, fileKind);\n};\n\nexport const injectTemplate = async (filePath: string): Promise<boolean> => {\n await ensureConsumerTemplateConfigLoaded();\n\n if (getRouteFilenameValidationMessage(filePath)) {\n fs.writeFileSync(filePath, getInvalidVersionMessage(filePath), 'utf8');\n console.log(`[TemplateInjector] Invalid route filename, injected guidance: ${filePath}`);\n return true;\n }\n\n const template = getTemplate(filePath);\n\n if (!template) {\n return false;\n }\n\n try {\n fs.writeFileSync(filePath, template, 'utf8');\n console.log(`[TemplateInjector] Injected template into: ${filePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to inject template: ${filePath}`, error);\n return false;\n }\n};\n\nexport const shouldInjectTemplate = (\n filePath: string,\n options: { isNewFile?: boolean } = {},\n): boolean => {\n //? Consumer disable hook — if `registerRoutingRules({ disableTemplateInjection })`\n //? was called with a predicate that returns true for this path, skip the\n //? injection entirely. Useful for files the consumer manages by hand\n //? (e.g. a generated migrations tree).\n const { disableTemplateInjection } = getRoutingRules();\n if (disableTemplateInjection?.(filePath)) {\n return false;\n }\n\n if (!(isInApiFolder(filePath) || isInSyncFolder(filePath) || isPageFile(filePath))) {\n return false;\n }\n\n //? An EMPTY file is always safe to template (there is nothing to lose).\n if (isEmptyFile(filePath)) return true;\n\n //? A COMMENT-ONLY file is only templated when it is genuinely NEW (the `add`\n //? event). Commenting out an entire EXISTING `_api`/`_sync`/`page` file and\n //? saving it (a common debugging move) fires a `change` event with\n //? comment-only content — injecting the starter template there silently\n //? OVERWRITES the user's commented-out code with no undo (data loss). On\n //? `add` there is no prior route entry to clobber, so it stays safe.\n if (options.isNewFile) return isCommentOnlyFile(filePath);\n\n return false;\n};\n\n// ---------------------------------------------------------------------------\n// Paired-client rewrite helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Ensures `SyncClientInput` and `SyncServerOutput` are imported from the\n * generated types file. Prepends a new import line when the single-line\n * regex misses multi-line or namespace variants.\n */\nconst ensureImportedTypes = (content: string, clientFilePath: string): string => {\n if (content.includes('SyncClientInput')) return content;\n\n let result = content.replace(\n /import \\{([^}]+)\\} from ['\"]([^'\"]*apiTypes\\.generated)['\"]/,\n (_match, imports: string, importPath: string) => {\n return `import {${imports}, SyncClientInput, SyncServerOutput } from '${importPath}'`;\n }\n );\n\n //? Safety net: the single-line regex above misses multi-line, `type`-only,\n //? or namespace imports. When it misses, prepend a fresh import so the\n //? rewritten `clientInput`/`serverOutput` references always resolve.\n if (!result.includes('SyncClientInput')) {\n const relPath = calculateRelativePath(clientFilePath);\n result = `import { SyncClientInput, SyncServerOutput } from '${relPath}src/_sockets/apiTypes.generated';\\n` + result;\n }\n\n return result;\n};\n\n/**\n * Inserts `PagePath` and `SyncName` type aliases after the last import\n * statement, when they are not already present.\n */\nconst insertTypeAliases = (content: string, pagePath: string, syncName: string): string => {\n if (content.includes('type PagePath')) return content;\n\n const importEndMatch = content.match(/import .+?;[\\r\\n]+/g);\n if (!importEndMatch) return content;\n\n const lastImport = importEndMatch.at(-1);\n if (!lastImport) return content;\n\n const lastImportEnd = content.lastIndexOf(lastImport) + lastImport.length;\n const typeAliases = `\\n// Types are imported from the generated file based on the _server.ts definition\\ntype PagePath = '${pagePath}';\\ntype SyncName = '${syncName}';\\n`;\n return content.slice(0, lastImportEnd) + typeAliases + content.slice(lastImportEnd);\n};\n\n/**\n * Regex fallback: replaces the inline `clientInput: { ... }` type block with\n * the generated type reference `SyncClientInput<PagePath, SyncName>`.\n * Only handles single-line object types; multi-line types require the AST path.\n */\nconst rewriteClientInputType = (content: string): string => {\n return content.replace(\n /^(\\s*)clientInput:\\s*\\{[^}]*\\}/m,\n '$1clientInput: SyncClientInput<PagePath, SyncName>'\n );\n};\n\n/**\n * Replaces the `clientInput` property type in the `SyncParams` interface using\n * the TypeScript AST. Locates the `clientInput` `PropertySignature` inside\n * `SyncParams` via the parser, extracts its type node's source span, and\n * performs a targeted character-position replacement — preserving the rest of\n * the source text verbatim (whitespace, comments, etc.).\n *\n * Returns the rewritten source on success, or `null` when:\n * - the file cannot be parsed\n * - `SyncParams` or `clientInput` is not found\n * - the existing type is not a `TypeLiteralNode` (already migrated → skip)\n * - the re-parsed result still contains a type literal (rewrite did not take)\n *\n * Callers must leave the file untouched and log the failure when `null` is\n * returned.\n */\nconst rewriteClientInputTypeAst = (content: string, sourceFileName: string): string | null => {\n // Parse to an AST (syntactic only — no type-checker needed).\n const parseSource = (src: string) =>\n ts.createSourceFile(\n sourceFileName,\n src,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n const sourceFile = parseSource(content);\n\n // Locate `SyncParams` interface.\n let syncParamsInterface: ts.InterfaceDeclaration | undefined;\n for (const stmt of sourceFile.statements) {\n if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SyncParams') {\n syncParamsInterface = stmt;\n break;\n }\n }\n\n if (!syncParamsInterface) return null;\n\n // Locate `clientInput` property signature.\n let clientInputMember: ts.PropertySignature | undefined;\n for (const member of syncParamsInterface.members) {\n if (\n ts.isPropertySignature(member)\n && ts.isIdentifier(member.name)\n && member.name.text === 'clientInput'\n ) {\n clientInputMember = member;\n break;\n }\n }\n\n if (!clientInputMember?.type) return null;\n\n //? Only replace object-literal type nodes ( `{ ... }` ) — already-migrated\n //? files that carry `SyncClientInput<PagePath, SyncName>` are left untouched.\n if (!ts.isTypeLiteralNode(clientInputMember.type)) return null;\n\n // Use the type node's AST span for a targeted position replacement so the\n // rest of the file's whitespace and comments are preserved verbatim.\n const typeNode = clientInputMember.type;\n const start = typeNode.getStart(sourceFile);\n const end = typeNode.getEnd();\n\n const rewritten = `${content.slice(0, start)}SyncClientInput<PagePath, SyncName>${content.slice(end)}`;\n\n // Re-parse the rewritten source to verify it is syntactically valid before\n // handing it back to the caller (who will write it to disk).\n // Use a throw-away single-file program so we can call the public\n // `getSyntacticDiagnostics` API (instead of the private `parseDiagnostics`).\n const reparsedFile = parseSource(rewritten);\n const verifyProgram = ts.createProgram({\n rootNames: [sourceFileName],\n options: { noResolve: true, skipLibCheck: true },\n // Supply the in-memory source so `ts.createProgram` never touches the disk.\n host: {\n ...ts.createCompilerHost({}),\n getSourceFile: (name) => (name === sourceFileName ? reparsedFile : undefined),\n fileExists: (name) => name === sourceFileName,\n readFile: (name) => (name === sourceFileName ? rewritten : undefined),\n },\n });\n const syntaxErrors = verifyProgram.getSyntacticDiagnostics(reparsedFile);\n if (syntaxErrors.length > 0) {\n console.log(\n `[TemplateInjector] AST rewrite produced invalid TypeScript for ${sourceFileName} — leaving untouched`,\n 'yellow',\n );\n return null;\n }\n\n return rewritten;\n};\n\n/**\n * Adds `serverOutput: SyncServerOutput<PagePath, SyncName>` to the SyncParams\n * interface when not already present.\n */\nconst addServerOutputToParams = (content: string): string => {\n if (content.includes('serverOutput:')) return content;\n return content.replace(\n /^(\\s*)(clientInput:\\s*SyncClientInput<PagePath, SyncName>);?\\s*$/m,\n '$1$2;\\n$1serverOutput: SyncServerOutput<PagePath, SyncName>;'\n );\n};\n\n/**\n * Adds `serverOutput` to the main function destructuring when not already present.\n */\nconst addServerOutputToDestructuring = (content: string): string => {\n if (!content.includes('main') || /\\{\\s*[^}]*serverOutput[^}]*\\}\\s*:\\s*SyncParams/.test(content)) {\n return content;\n }\n return content.replace(\n /\\{\\s*([^}]*?clientInput)([^}]*)\\}\\s*:\\s*SyncParams/,\n '{ $1, serverOutput$2 }: SyncParams'\n );\n};\n\n/**\n * Update a client file to use the paired template (imports types from generated file)\n * Called when a _server.ts is created and _client.ts already exists\n * PRESERVES user's main function code!\n */\n// eslint-disable-next-line @typescript-eslint/require-await -- async signature keeps the public interface awaitable for future I/O expansion\nexport const updateClientFileForPairedServer = async (clientFilePath: string): Promise<boolean> => {\n try {\n const pagePath = extractSyncPagePath(clientFilePath);\n const syncName = extractSyncName(clientFilePath);\n\n let content = fs.readFileSync(clientFilePath, 'utf8');\n\n content = ensureImportedTypes(content, clientFilePath);\n content = insertTypeAliases(content, pagePath, syncName);\n\n // Prefer AST-based rewrite (type-aware, handles multi-line object types).\n // Fall back to the regex path only when the AST cannot locate the node\n // (e.g. non-standard structure) so the most common cases always benefit\n // from the precise position replacement.\n const astResult = rewriteClientInputTypeAst(content, path.basename(clientFilePath));\n if (astResult === null) {\n console.log(\n `[TemplateInjector] AST clientInput rewrite unavailable for ${clientFilePath} — using regex fallback`,\n 'yellow',\n );\n content = rewriteClientInputType(content);\n } else {\n content = astResult;\n }\n\n content = addServerOutputToParams(content);\n content = addServerOutputToDestructuring(content);\n\n fs.writeFileSync(clientFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Updated client file to use paired types (preserved code): ${clientFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to update client file: ${clientFilePath}`, error);\n return false;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Deleted-server cleanup helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Replaces the `clientInput` type (either a generated reference or an inline block)\n * with the supplied inline type block.\n */\nconst inlineClientInputType = (content: string, clientInputTypes: string): string => {\n // Use replacer functions so `$`-sequences in `clientInputTypes` (Prisma `$Enums.Role`,\n // template-literal `${...}` types) are spliced verbatim, not re-interpreted as backrefs.\n return content\n .replace(\n /^(\\s*)clientInput:\\s*SyncClientInput<[^>]+>/m,\n (_match, indent: string) => `${indent}clientInput: ${clientInputTypes}`\n )\n .replace(\n /^(\\s*)clientInput:\\s*\\{[^}]*\\}/m,\n (_match, indent: string) => `${indent}clientInput: ${clientInputTypes}`\n );\n};\n\n/**\n * Removes `serverOutput` lines from the SyncParams interface body.\n */\nconst removeServerOutputFromParams = (content: string): string => {\n return content\n .replace(/^[ \\t]*serverOutput:\\s*SyncServerOutput<[^>]+>;?\\s*\\r?\\n?/m, '')\n .replace(/^[ \\t]*serverOutput:\\s*\\{[^}]*\\};?\\s*\\r?\\n?/m, '');\n};\n\n/**\n * Removes `serverOutput` from the main function destructuring.\n */\nconst removeServerOutputFromDestructuring = (content: string): string => {\n return content\n .replaceAll(/,\\s*serverOutput(?=\\s*[,}])/g, '')\n .replaceAll(/serverOutput\\s*,\\s*/g, '');\n};\n\n/**\n * Strips `SyncClientInput` and `SyncServerOutput` from import statements.\n */\nconst removeGeneratedTypeImports = (content: string): string => {\n return content\n .replaceAll(/,\\s*SyncClientInput(?=\\s*[,}])/g, '')\n .replaceAll(/,\\s*SyncServerOutput(?=\\s*[,}])/g, '');\n};\n\n/**\n * Removes the injected `PagePath` / `SyncName` type alias comment and declarations.\n */\nconst removeTypeAliases = (content: string): string => {\n let result = content.replaceAll(/\\/\\/\\s*Types are imported.*\\n?/g, '');\n result = result.replaceAll(/type PagePath = '[^']*';\\s*\\n?/g, '');\n return result.replaceAll(/type SyncName = '[^']*';\\s*\\n?/g, '');\n};\n\n/**\n * Splits a sync-client file into `[header, body]` at the start of `main`'s\n * function body (the `=> {` opener). `serverOutput` only legitimately appears\n * in the `SyncParams` interface and in `main`'s parameter destructuring — both\n * of which live in the header. Scoping the serverOutput-stripping regexes to\n * the header keeps user body code that coincidentally contains `serverOutput`\n * (e.g. `{ x: serverOutput, y }`) untouched. If the `: SyncParams` annotation\n * or the body opener can't be found, falls back to treating the whole file as\n * header (the previous whole-file behavior).\n */\nconst splitAtMainBody = (content: string): [header: string, body: string] => {\n const paramsAnchor = content.indexOf(': SyncParams');\n if (paramsAnchor === -1) return [content, ''];\n const bodyOpener = content.indexOf('=> {', paramsAnchor);\n if (bodyOpener === -1) return [content, ''];\n const splitIndex = bodyOpener + '=> {'.length;\n return [content.slice(0, splitIndex), content.slice(splitIndex)];\n};\n\n/**\n * Update a client file when the paired server file is deleted\n * Preserves user's main function code while:\n * - Inlining clientInput types\n * - Removing serverOutput from SyncParams and main function params\n */\n/* eslint-disable @typescript-eslint/require-await -- async signature keeps the public interface awaitable for future I/O expansion */\nexport const updateClientFileForDeletedServer = async (\n clientFilePath: string,\n clientInputTypes: string\n): Promise<boolean> => {\n try {\n let content = fs.readFileSync(clientFilePath, 'utf8');\n\n // Order matters: replace type references BEFORE removing imports/aliases.\n content = inlineClientInputType(content, clientInputTypes);\n // Scope serverOutput removal to the header (interface + main's params) so\n // it can never corrupt user body code that mentions `serverOutput`.\n const [header, body] = splitAtMainBody(content);\n const cleanedHeader = removeServerOutputFromDestructuring(removeServerOutputFromParams(header));\n content = `${cleanedHeader}${body}`;\n content = removeGeneratedTypeImports(content);\n content = removeTypeAliases(content);\n\n // Collapse runs of 3+ blank lines left by the removals.\n content = content.replaceAll(/\\n{3,}/g, '\\n\\n');\n\n fs.writeFileSync(clientFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Updated client file for deleted server (preserved code): ${clientFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to update client file: ${clientFilePath}`, error);\n return false;\n }\n};\n/* eslint-enable @typescript-eslint/require-await */\n\n/**\n * Inject server template with pre-filled clientInput types (from existing client file)\n */\nexport const injectServerTemplateWithClientInput = async (\n serverFilePath: string,\n clientInputTypes: string\n): Promise<boolean> => {\n try {\n await ensureConsumerTemplateConfigLoaded();\n const relPath = calculateRelativePath(serverFilePath);\n\n //? Honor consumer overrides for the sync_server kind here too (consumer\n //? file -> registered override -> bundled), then fill in the clientInput.\n let content = resolveTemplateContent('sync_server');\n if (content === null) {\n console.error(`[TemplateInjector] No sync_server template content available for: ${serverFilePath}`);\n return false;\n }\n\n //? Replace placeholders — same pragma union + literal-fallback pattern\n //? as `getTemplate` above. Keep these two regexes in sync.\n const pragmaPattern = /\\/\\/\\s*@ts-(?:ignore|expect-error).*\\r?\\n(.*)\\{\\{REL_PATH\\}\\}/g;\n content = content.replaceAll(pragmaPattern, (_, prefix) => {\n return `${prefix}${relPath}`;\n });\n content = content.replaceAll('{{REL_PATH}}', relPath);\n\n // Replace the empty clientInput with the provided types.\n // Use a replacer function so `$`-sequences in `clientInputTypes`\n // (Prisma `$Enums.Role`, template-literal `${...}` types) are spliced\n // verbatim instead of being re-interpreted as backreferences.\n content = content.replace(\n /clientInput:\\s*\\{[^}]*\\}/s,\n (_match) => `clientInput: ${clientInputTypes}`\n );\n\n fs.writeFileSync(serverFilePath, content, 'utf8');\n console.log(`[TemplateInjector] Injected server template with clientInput: ${serverFilePath}`);\n return true;\n } catch (error) {\n console.error(`[TemplateInjector] Failed to inject server template: ${serverFilePath}`, error);\n return false;\n }\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { ROOT_DIR, getServerFunctionDirs, getSharedDir, getSrcDir } from '@luckystack/core';\n\nimport { getOrInit } from './internal/mapUtils';\n\nconst SUPPORTED_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts'];\n\nconst normalizePath = (value: string): string => path.resolve(value).replaceAll('\\\\', '/');\n\nconst isSupportedScriptFile = (value: string): boolean => {\n return SUPPORTED_EXTENSIONS.some((extension) => value.endsWith(extension));\n};\n\nconst existsFile = (value: string): boolean => {\n try {\n return fs.existsSync(value) && fs.statSync(value).isFile();\n } catch {\n return false;\n }\n};\n\nconst existsDirectory = (value: string): boolean => {\n try {\n return fs.existsSync(value) && fs.statSync(value).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectScriptFiles = (dir: string, output: Set<string>, visited = new Set<string>()): void => {\n if (!existsDirectory(dir)) {\n return;\n }\n\n // Resolve the real path to detect symlink cycles before descending.\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch {\n return;\n }\n if (visited.has(realDir)) return;\n visited.add(realDir);\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n // Skip node_modules to avoid crawling installed packages.\n if (entry.name === 'node_modules') continue;\n\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory() || entry.isSymbolicLink()) {\n if (existsDirectory(fullPath)) {\n collectScriptFiles(fullPath, output, visited);\n }\n continue;\n }\n\n const normalizedPath = normalizePath(fullPath);\n if (isSupportedScriptFile(normalizedPath)) {\n output.add(normalizedPath);\n }\n }\n};\n\ninterface CachedSpecifiers {\n mtimeMs: number;\n specifiers: string[];\n}\n\n//? Reverse-dependency lookups happen on every file save. Re-reading + regex-\n//? parsing every file in src/shared/serverFunctions per save adds tens of ms\n//? of synchronous IO. Cache per-file by mtime so unchanged files reuse the\n//? prior parse.\nconst specifiersCache = new Map<string, CachedSpecifiers>();\nlet scopedFilesCache: { files: Set<string>; expiresAt: number } | null = null;\nconst SCOPED_FILES_TTL_MS = 1000;\n\nconst extractImportSpecifiers = (filePath: string): string[] => {\n let mtimeMs = 0;\n try {\n mtimeMs = fs.statSync(filePath).mtimeMs;\n } catch {\n specifiersCache.delete(filePath);\n return [];\n }\n\n const cached = specifiersCache.get(filePath);\n if (cached?.mtimeMs === mtimeMs) {\n return cached.specifiers;\n }\n\n try {\n const source = fs.readFileSync(filePath, 'utf8');\n const specifiers = new Set<string>();\n\n // The `[\\s\\S]*?` allows the import clause to span multiple lines\n // (e.g. named imports broken across lines). The `[^'\"]+` keeps the\n // specifier itself single-line so malformed source can't over-greedily\n // consume closing quotes from later imports.\n const importExportRegex = /(?:import|export)\\s+(?:[\\s\\S]*?\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n const dynamicImportRegex = /import\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n let match: RegExpExecArray | null = null;\n\n while ((match = importExportRegex.exec(source)) !== null) {\n if (match[1]) specifiers.add(match[1]);\n }\n\n while ((match = dynamicImportRegex.exec(source)) !== null) {\n if (match[1]) specifiers.add(match[1]);\n }\n\n const result = [...specifiers];\n specifiersCache.set(filePath, { mtimeMs, specifiers: result });\n return result;\n } catch {\n specifiersCache.delete(filePath);\n return [];\n }\n};\n\nexport const invalidateGraphForFile = (absolutePath: string): void => {\n specifiersCache.delete(normalizePath(absolutePath));\n scopedFilesCache = null;\n};\n\nconst tryResolveWithExtensions = (basePath: string): string | null => {\n if (existsFile(basePath)) {\n return normalizePath(basePath);\n }\n\n for (const extension of SUPPORTED_EXTENSIONS) {\n const withExtension = `${basePath}${extension}`;\n if (existsFile(withExtension)) {\n return normalizePath(withExtension);\n }\n }\n\n if (existsDirectory(basePath)) {\n for (const extension of SUPPORTED_EXTENSIONS) {\n const indexFile = path.join(basePath, `index${extension}`);\n if (existsFile(indexFile)) {\n return normalizePath(indexFile);\n }\n }\n }\n\n return null;\n};\n\nconst resolveImportToFile = (importerPath: string, specifier: string): string | null => {\n if (!specifier || specifier.startsWith('node:')) {\n return null;\n }\n\n if (specifier === 'config') {\n return tryResolveWithExtensions(path.join(ROOT_DIR, 'config'));\n }\n\n if (specifier.startsWith('./') || specifier.startsWith('../')) {\n const relativeBase = path.resolve(path.dirname(importerPath), specifier);\n return tryResolveWithExtensions(relativeBase);\n }\n\n if (specifier.startsWith('src/') || specifier.startsWith('@/')) {\n const sourcePath = specifier.startsWith('@/') ? specifier.slice(2) : specifier.slice(4);\n return tryResolveWithExtensions(path.join(getSrcDir(), sourcePath));\n }\n\n if (specifier.startsWith('shared/')) {\n return tryResolveWithExtensions(path.join(getSharedDir(), specifier.slice(7)));\n }\n\n return null;\n};\n\nconst isRouteFile = (filePath: string): boolean => {\n return filePath.includes('/src/') && (filePath.includes('/_api/') || filePath.includes('/_sync/'));\n};\n\nconst collectScopedFiles = (): Set<string> => {\n const now = Date.now();\n if (scopedFilesCache && scopedFilesCache.expiresAt > now) {\n return scopedFilesCache.files;\n }\n\n const files = new Set<string>();\n collectScriptFiles(getSrcDir(), files);\n collectScriptFiles(getSharedDir(), files);\n for (const dir of getServerFunctionDirs()) {\n collectScriptFiles(dir, files);\n }\n\n const configFile = tryResolveWithExtensions(path.join(ROOT_DIR, 'config'));\n if (configFile) {\n files.add(configFile);\n }\n\n scopedFilesCache = { files, expiresAt: now + SCOPED_FILES_TTL_MS };\n return files;\n};\n\nexport const findDependentRouteFiles = (changedFilePath: string): Set<string> => {\n const scopedFiles = collectScopedFiles();\n const changedAbsolutePath = normalizePath(changedFilePath);\n\n const reverseDependencies = new Map<string, Set<string>>();\n\n for (const filePath of scopedFiles) {\n const specifiers = extractImportSpecifiers(filePath);\n\n for (const specifier of specifiers) {\n const resolvedImport = resolveImportToFile(filePath, specifier);\n if (!resolvedImport || !scopedFiles.has(resolvedImport)) {\n continue;\n }\n\n getOrInit(reverseDependencies, resolvedImport, () => new Set<string>()).add(filePath);\n }\n }\n\n const affectedRoutes = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [changedAbsolutePath];\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined) break;\n if (visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n const importers = reverseDependencies.get(current);\n if (!importers) {\n continue;\n }\n\n for (const importer of importers) {\n if (isRouteFile(importer)) {\n affectedRoutes.add(importer);\n }\n\n if (!visited.has(importer)) {\n queue.push(importer);\n }\n }\n }\n\n return affectedRoutes;\n};\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { ROOT_DIR, tryCatch } from '@luckystack/core';\n\n//? Where the Prisma generator writes its client by default: `node_modules/.prisma/\n//? client`. The DIRECTORY existing is NOT proof of generation — `@prisma/client`'s\n//? own postinstall writes an un-generated STUB there on a plain `npm install` (a\n//? throwing `PrismaClient` + no model types, no schema, no query engine). So we\n//? probe a marker that ONLY a real `prisma generate` produces: it copies the\n//? schema into the output dir as `.prisma/client/schema.prisma` (absent in the\n//? stub). That distinguishes \"generated\" from \"stub-only\".\nconst GENERATED_CLIENT_DIR = path.join(ROOT_DIR, 'node_modules', '.prisma', 'client');\nconst GENERATED_CLIENT_MARKER = path.join(GENERATED_CLIENT_DIR, 'schema.prisma');\n\n//? Default schema location in a scaffolded LuckyStack project. `prisma generate`\n//? auto-discovers `prisma/schema.prisma` from the project root, so no explicit\n//? `--schema` flag is needed when this path exists.\nconst DEFAULT_SCHEMA_PATH = path.join(ROOT_DIR, 'prisma', 'schema.prisma');\n\n/**\n * True when a Prisma schema exists in the consumer project but the generated\n * client output is absent — i.e. the consumer has not run `prisma generate`\n * yet. This is the only condition under which we auto-generate (or surface the\n * \"run prisma:generate\" hint), so an unrelated type-map failure never triggers\n * the Prisma-specific path.\n */\nexport const isPrismaClientMissing = (): boolean =>\n\tfs.existsSync(DEFAULT_SCHEMA_PATH) && !fs.existsSync(GENERATED_CLIENT_MARKER);\n\n/**\n * Runs `prisma generate` once. `prisma generate` only reads the schema —\n * it needs NO database credentials — so this is safe to run on dev boot without\n * any `.env` loading. Resolves to the child's exit code (0 on success). Spawn\n * failures (ENOENT/EACCES) surface through the `tryCatch` tuple, not a throw.\n *\n * Uses the local `node_modules/.bin/prisma` binary directly (shell: false) to\n * avoid shell invocation on Windows. Falls back to `npx prisma` with\n * shell: false when the local binary is absent (e.g. prisma not yet installed).\n */\nexport const runPrismaGenerate = async (): Promise<[Error | null, number | null]> =>\n\ttryCatch(\n\t\t() =>\n\t\t\tnew Promise<number>((resolve, reject) => {\n\t\t\t\t//? Prefer the local binary over `npx` — avoids shell invocation on\n\t\t\t\t//? Windows and is faster (no npx resolution overhead). On Windows the\n\t\t\t\t//? `.cmd` wrapper is what `PATH` resolves to from cmd.exe, but spawn\n\t\t\t\t//? with shell:false needs the real script path, not the .cmd shim.\n\t\t\t\t//? The actual JS CLI lives at `node_modules/prisma/build/index.js`\n\t\t\t\t//? but the cross-platform entry is the `.bin` shim.\n\t\t\t\tconst localBinName = process.platform === 'win32' ? 'prisma.cmd' : 'prisma';\n\t\t\t\tconst localBin = path.join(ROOT_DIR, 'node_modules', '.bin', localBinName);\n\t\t\t\tconst useLocal = fs.existsSync(localBin);\n\n\t\t\t\t//? shell: false in both branches — argv is fully static (no user input).\n\t\t\t\tconst [cmd, args] = useLocal\n\t\t\t\t\t? [localBin, ['generate']]\n\t\t\t\t\t: [process.platform === 'win32' ? 'npx.cmd' : 'npx', ['prisma', 'generate']];\n\n\t\t\t\t//? On Windows a `.cmd`/`.bat` shim can no longer be spawned with\n\t\t\t\t//? shell:false (Node's CVE-2024-27980 mitigation throws EINVAL). Invoke\n\t\t\t\t//? comspec with the resolved path in an OUTER+INNER quote pair (with\n\t\t\t\t//? `/s` cmd strips the outer pair and runs the rest verbatim, keeping any\n\t\t\t\t//? spaced path intact) and `windowsVerbatimArguments` so cmd does not\n\t\t\t\t//? re-quote. Mirrors create-luckystack-app's `spawnResolved`.\n\t\t\t\tconst isWinShim = process.platform === 'win32' && /\\.(cmd|bat)$/i.test(cmd);\n\t\t\t\tconst child = isWinShim\n\t\t\t\t\t? spawn(\n\t\t\t\t\t\t\tprocess.env.ComSpec ?? 'cmd.exe',\n\t\t\t\t\t\t\t['/d', '/s', '/c', `\"\"${cmd}\" ${args.join(' ')}\"`],\n\t\t\t\t\t\t\t{ cwd: ROOT_DIR, stdio: 'inherit', windowsVerbatimArguments: true },\n\t\t\t\t\t )\n\t\t\t\t\t: spawn(cmd, args, {\n\t\t\t\t\t\t\tcwd: ROOT_DIR,\n\t\t\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t\t\t\tshell: false,\n\t\t\t\t\t\t});\n\t\t\t\tchild.on('error', reject);\n\t\t\t\tchild.on('exit', (code) => { resolve(code ?? 0); });\n\t\t\t}),\n\t);\n"],"mappings":";;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,gBAAgB;;;AC4IzB,SAAS,oBAAoB,oBAAsF;AAlFnH,IAAM,gBAA8B;AAAA,EAClC,WAAW;AAAA,EACX,Y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I,sBAAsB,GAAG;AAC3B,gBAAQ,IAAI,oGAA0F,MAAM;AAC5G,cAAM,CAAC,aAAa,QAAQ,IAAI,MAAM,kBAAkB;AACxD,YAAI,eAAe,aAAa,GAAG;AACjC,kBAAQ,IAAI,qCAAqC,cAAc,KAAK,OAAO,WAAW,CAAC,KAAK,eAAe,OAAO,QAAQ,CAAC,GAAG,gEAA2D,KAAK;AAAA,QAChM,OAAO;AACL,kBAAQ,IAAI,wCAAwC,OAAO;AAAA,QAC7D;AAAA,MACF;AAEA,YAAM,CAAC,GAAG,IAAI,MAAMJ,UAAS,MAAM;AAAE,4BAAoB,EAAE,OAAO,KAAK,CAAC;AAAA,MAAG,CAAC;AAC5E,UAAI,KAAK;AAMP,cAAM,OAAO,+BAA+B,KAAK,OAAO,GAAG,CAAC,IACxD,mIACA;AACJ,gBAAQ,IAAI,mDAAmD,OAAO,GAAG,CAAC,GAAG,IAAI,IAAI,KAAK;AAAA,MAC5F,OAAO;AACL,gBAAQ,IAAI,4CAA4C,OAAO;AAAA,MACjE;AAAA,IACF,GAAG;AAAA,EACL,CAAC;AACH;","names":["overrides","rules","path","path","versionMatch","fs","fs","fs","path","ts","ts","fs","path","ts","path","ts","path","ROOT_DIR","getGeneratedSocketTypesPath","getGeneratedSocketTypesPath","normalizeImportPath","path","mergeUnresolvedSymbols","ts","fs","path","ts","path","getGeneratedSocketTypesPath","path","getGeneratedSocketTypesPath","getGeneratedSocketTypesPath","path","getGeneratedSocketTypesPath","fs","getSrcDir","fs","path","ROOT_DIR","path","ROOT_DIR","fs","rules","getSrcDir","fs","path","getServerFunctionDirs","getSrcDir","ROOT_DIR","ts","SKIP_EXPANSION","normalizePath","path","ROOT_DIR","getSrcDir","rules","fs","getServerFunctionDirs","fs","path","fs","path","pathToFileURL","ts","ROOT_DIR","getGeneratedSocketTypesPath","getSrcDir","path","ROOT_DIR","fs","pathToFileURL","getSrcDir","extractSyncPagePath","extractSyncName","getGeneratedSocketTypesPath","fs","path","ROOT_DIR","getServerFunctionDirs","getSrcDir","normalizePath","path","fs","ROOT_DIR","getSrcDir","getServerFunctionDirs","fs","path","ROOT_DIR","tryCatch","tryCatch","path","tryCatch","rules","fs","extractSyncPagePath","extractSyncName"]}