@soda-gql/builder 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Effect","path: string","element: AcceptableArtifact","GqlElement","Effects","declarations: string[]","returnEntries: string[]","importLines: string[]","filePath","stack: EvaluationFrame[]","frame: EvaluationFrame | undefined","result","artifacts: Record<string, IntermediateArtifactElement>","Fragment","Operation","ParallelEffect","cachedGql: unknown","cachedModulePath: string | null","moduleExports: Record<string, unknown>","sandboxCore","sandboxRuntime","Script","ParallelEffect","z","canonicalToFilePath","metadata: BuilderArtifactElementMetadata","lines: string[]","collectImports","imports: ModuleImport[]","collectExports","exports: ModuleExport[]","exports","module","unwrapMethodChains","collectAllDefinitions","getPropertyName","pending: PendingDefinition[]","handledCalls: CallExpression[]","frame: ScopeFrame","exportBinding: string | undefined","swcAdapter: AnalyzerAdapter","ts","imports: ModuleImport[]","exports: ModuleExport[]","exports","pending: PendingDefinition[]","handledCalls: ts.CallExpression[]","frame: ScopeFrame","exportBinding: string | undefined","typescriptAdapter: AnalyzerAdapter","data: PersistedData","z","envelope: Envelope<V>","serialized: Record<string, Array<[string, Envelope<unknown>]>>","normalizePath","z","CanonicalIdSchema","z","xxhashInstance: XXHashAPI | null","fingerprint: FileFingerprint","stats","snapshot: DiscoverySnapshot","fg","currentScan: FileScan","nextScan: FileScan | null","scan","entrypoints: ReadonlySet<string>","state: SessionState","options","stats: ModuleLoadStats"],"sources":["../src/scheduler/effects.ts","../src/intermediate-module/codegen.ts","../src/intermediate-module/registry.ts","../src/intermediate-module/evaluation.ts","../src/internal/graphql-system.ts","../src/schemas/artifact.ts","../src/artifact/aggregate.ts","../src/artifact/issue-handler.ts","../src/artifact/builder.ts","../src/errors.ts","../src/ast/common/scope.ts","../src/ast/adapters/swc.ts","../src/ast/adapters/typescript.ts","../src/ast/core.ts","../src/ast/index.ts","../src/cache/memory-cache.ts","../src/cache/entity-cache.ts","../src/schemas/cache.ts","../src/schemas/discovery.ts","../src/discovery/cache.ts","../src/discovery/common.ts","../src/discovery/fingerprint.ts","../src/discovery/discoverer.ts","../src/utils/glob.ts","../src/discovery/entry-paths.ts","../src/tracker/file-tracker.ts","../src/session/dependency-validation.ts","../src/session/module-adjacency.ts","../src/session/builder-session.ts","../src/service.ts"],"sourcesContent":["import { readFileSync, statSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { Effect, Effects } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyOperation, GqlElement } from \"@soda-gql/core\";\n\ntype AcceptableArtifact = AnyFragment | AnyOperation;\n\n/**\n * File stats result type.\n */\nexport type FileStats = {\n readonly mtimeMs: number;\n readonly size: number;\n readonly isFile: boolean;\n};\n\n/**\n * File read effect - reads a file from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const content = yield* new FileReadEffect(\"/path/to/file\").run();\n */\nexport class FileReadEffect extends Effect<string> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string {\n return readFileSync(this.path, \"utf-8\");\n }\n\n protected _executeAsync(): Promise<string> {\n return readFile(this.path, \"utf-8\");\n }\n}\n\n/**\n * File stat effect - gets file stats from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const stats = yield* new FileStatEffect(\"/path/to/file\").run();\n */\nexport class FileStatEffect extends Effect<FileStats> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n\n protected async _executeAsync(): Promise<FileStats> {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n}\n\n/**\n * File read effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileReadEffect extends Effect<string | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string | null {\n try {\n return readFileSync(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<string | null> {\n try {\n return await readFile(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * File stat effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileStatEffect extends Effect<FileStats | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats | null {\n try {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<FileStats | null> {\n try {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * Element evaluation effect - evaluates a GqlElement using its generator.\n * Supports both sync and async schedulers, enabling parallel element evaluation\n * when using async scheduler.\n *\n * @example\n * yield* new ElementEvaluationEffect(element).run();\n */\nexport class ElementEvaluationEffect extends Effect<void> {\n constructor(readonly element: AcceptableArtifact) {\n super();\n }\n\n protected _executeSync(): void {\n // Run generator synchronously - throws if async operation is required\n const generator = GqlElement.createEvaluationGenerator(this.element);\n const result = generator.next();\n while (!result.done) {\n // If generator yields, it means async operation is needed\n throw new Error(\"Async operation required during sync element evaluation\");\n }\n }\n\n protected async _executeAsync(): Promise<void> {\n const generator = GqlElement.createEvaluationGenerator(this.element);\n let result = generator.next();\n while (!result.done) {\n // Yield value is a Promise<void>\n await result.value;\n result = generator.next();\n }\n }\n}\n\n/**\n * Builder effect constructors.\n * Extends the base Effects with file I/O operations and element evaluation.\n */\nexport const BuilderEffects = {\n ...Effects,\n\n /**\n * Create a file read effect.\n * @param path - The file path to read\n */\n readFile: (path: string): FileReadEffect => new FileReadEffect(path),\n\n /**\n * Create a file stat effect.\n * @param path - The file path to stat\n */\n stat: (path: string): FileStatEffect => new FileStatEffect(path),\n\n /**\n * Create an optional file read effect that returns null if file doesn't exist.\n * @param path - The file path to read\n */\n readFileOptional: (path: string): OptionalFileReadEffect => new OptionalFileReadEffect(path),\n\n /**\n * Create an optional file stat effect that returns null if file doesn't exist.\n * @param path - The file path to stat\n */\n statOptional: (path: string): OptionalFileStatEffect => new OptionalFileStatEffect(path),\n\n /**\n * Create an element evaluation effect.\n * @param element - The GqlElement to evaluate\n */\n evaluateElement: (element: AcceptableArtifact): ElementEvaluationEffect => new ElementEvaluationEffect(element),\n} as const;\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { ModuleAnalysis, ModuleDefinition, ModuleImport } from \"../ast\";\n\nconst formatFactory = (expression: string): string => {\n const trimmed = expression.trim();\n if (!trimmed.includes(\"\\n\")) {\n return trimmed;\n }\n\n const lines = trimmed.split(\"\\n\").map((line) => line.trimEnd());\n const indented = lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join(\"\\n\");\n\n return `(\\n ${indented}\\n )`;\n};\n\ntype TreeNode = {\n expression?: string; // Leaf node with actual expression\n canonicalId?: string; // Canonical ID for this node\n children: Map<string, TreeNode>; // Branch node with children\n};\n\nconst buildTree = (definitions: readonly ModuleDefinition[]): Map<string, TreeNode> => {\n const roots = new Map<string, TreeNode>();\n\n definitions.forEach((definition) => {\n const parts = definition.astPath.split(\".\");\n const expressionText = definition.expression.trim();\n\n if (parts.length === 1) {\n // Top-level export\n const rootName = parts[0];\n if (rootName) {\n roots.set(rootName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n } else {\n // Nested export\n const rootName = parts[0];\n if (!rootName) return;\n\n let root = roots.get(rootName);\n if (!root) {\n root = { children: new Map() };\n roots.set(rootName, root);\n }\n\n let current = root;\n for (let i = 1; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n\n let child = current.children.get(part);\n if (!child) {\n child = { children: new Map() };\n current.children.set(part, child);\n }\n current = child;\n }\n\n const leafName = parts[parts.length - 1];\n if (leafName) {\n current.children.set(leafName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n }\n });\n\n return roots;\n};\n\n/**\n * Check if a string is a valid JavaScript identifier\n */\nconst isValidIdentifier = (name: string): boolean => {\n // JavaScript identifier regex: starts with letter, _, or $, followed by letters, digits, _, or $\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) && !isReservedWord(name);\n};\n\n/**\n * Check if a string is a JavaScript reserved word\n */\nconst isReservedWord = (name: string): boolean => {\n const reserved = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"export\",\n \"extends\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n \"let\",\n \"static\",\n \"enum\",\n \"await\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n ]);\n return reserved.has(name);\n};\n\n/**\n * Format a key for use in an object literal\n * Invalid identifiers are quoted, valid ones are not\n */\nconst formatObjectKey = (key: string): string => {\n return isValidIdentifier(key) ? key : `\"${key}\"`;\n};\n\nconst renderTreeNode = (node: TreeNode, indent: number): string => {\n if (node.expression && node.children.size === 0 && node.canonicalId) {\n // Leaf node - use addBuilder\n const expr = formatFactory(node.expression);\n return `registry.addElement(\"${node.canonicalId}\", () => ${expr})`;\n }\n\n // Branch node - render nested object\n const indentStr = \" \".repeat(indent);\n const entries = Array.from(node.children.entries()).map(([key, child]) => {\n const value = renderTreeNode(child, indent + 1);\n const formattedKey = formatObjectKey(key);\n return `${indentStr} ${formattedKey}: ${value},`;\n });\n\n if (entries.length === 0) {\n return \"{}\";\n }\n\n return `{\\n${entries.join(\"\\n\")}\\n${indentStr}}`;\n};\n\nconst buildNestedObject = (definition: readonly ModuleDefinition[]): string => {\n const tree = buildTree(definition);\n const declarations: string[] = [];\n const returnEntries: string[] = [];\n\n tree.forEach((node, rootName) => {\n if (node.children.size > 0) {\n // Has children - create a const declaration\n const objectLiteral = renderTreeNode(node, 2);\n declarations.push(` const ${rootName} = ${objectLiteral};`);\n returnEntries.push(rootName);\n } else if (node.expression && node.canonicalId) {\n // Single export - use addElement\n const expr = formatFactory(node.expression);\n declarations.push(` const ${rootName} = registry.addElement(\"${node.canonicalId}\", () => ${expr});`);\n returnEntries.push(rootName);\n }\n });\n\n const returnStatement =\n returnEntries.length > 0\n ? ` return {\\n${returnEntries.map((name) => ` ${name},`).join(\"\\n\")}\\n };`\n : \" return {};\";\n\n if (declarations.length === 0) {\n return returnStatement;\n }\n\n return `${declarations.join(\"\\n\")}\\n${returnStatement}`;\n};\n\n/**\n * Render import statements for the intermediate module using ModuleSummary.\n * Only includes imports from modules that have gql exports.\n */\nconst renderImportStatements = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): { imports: string; importedRootNames: Set<string>; namespaceImports: Set<string> } => {\n const importLines: string[] = [];\n const importedRootNames = new Set<string>();\n const namespaceImports = new Set<string>();\n\n // Group imports by resolved file path\n const importsByFile = new Map<string, ModuleImport[]>();\n\n analysis.imports.forEach((imp) => {\n if (imp.isTypeOnly) {\n return;\n }\n\n // Skip non-relative imports (external packages)\n if (!imp.source.startsWith(\".\")) {\n return;\n }\n\n const resolvedPath = resolveRelativeImportWithReferences({ filePath, specifier: imp.source, references: analyses });\n if (!resolvedPath) {\n return;\n }\n\n // Skip graphql-system imports - gql is provided via VM context\n if (resolvedPath === graphqlSystemPath) {\n return;\n }\n\n const imports = importsByFile.get(resolvedPath) ?? [];\n imports.push(imp);\n importsByFile.set(resolvedPath, imports);\n });\n\n // Render registry.importModule() for each file\n importsByFile.forEach((imports, filePath) => {\n // Check if this is a namespace import\n const namespaceImport = imports.find((imp) => imp.kind === \"namespace\");\n\n if (namespaceImport) {\n // Namespace import: const foo = yield registry.requestImport(\"path\");\n importLines.push(` const ${namespaceImport.local} = yield registry.requestImport(\"${filePath}\");`);\n namespaceImports.add(namespaceImport.local);\n importedRootNames.add(namespaceImport.local);\n } else {\n // Named imports: const { a, b } = yield registry.requestImport(\"path\");\n const rootNames = new Set<string>();\n\n imports.forEach((imp) => {\n if (imp.kind === \"named\" || imp.kind === \"default\") {\n rootNames.add(imp.local);\n importedRootNames.add(imp.local);\n }\n });\n\n if (rootNames.size > 0) {\n const destructured = Array.from(rootNames).sort().join(\", \");\n importLines.push(` const { ${destructured} } = yield registry.requestImport(\"${filePath}\");`);\n }\n }\n });\n\n return {\n imports: importLines.length > 0 ? `${importLines.join(\"\\n\")}` : \"\",\n importedRootNames,\n namespaceImports,\n };\n};\n\nexport const renderRegistryBlock = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): string => {\n const { imports } = renderImportStatements({ filePath, analysis, analyses, graphqlSystemPath });\n\n return [`registry.setModule(\"${filePath}\", function*() {`, imports, \"\", buildNestedObject(analysis.definitions), \"});\"].join(\n \"\\n\",\n );\n};\n","import { createAsyncScheduler, createSyncScheduler, type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyOperation, Fragment, GqlElement, Operation } from \"@soda-gql/core\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport type { EvaluationRequest, IntermediateArtifactElement } from \"./types\";\n\nexport type IntermediateRegistry = ReturnType<typeof createIntermediateRegistry>;\n\ntype AcceptableArtifact = AnyFragment | AnyOperation;\ntype ArtifactModule = ArtifactRecord;\ntype ArtifactRecord = {\n readonly [key: string]: AcceptableArtifact | ArtifactRecord;\n};\n\n/**\n * Generator factory type for module evaluation.\n * The generator yields EvaluationRequest when it needs to import a dependency,\n * receives the resolved module as the yield result, and returns the final ArtifactModule.\n */\ntype GeneratorFactory = () => Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n\n/**\n * Internal frame type for the evaluation stack.\n */\ntype EvaluationFrame = {\n readonly filePath: string;\n readonly generator: Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n resolvedDependency?: ArtifactModule;\n};\n\nexport const createIntermediateRegistry = ({ analyses }: { analyses?: Map<string, ModuleAnalysis> } = {}) => {\n const modules = new Map<string, GeneratorFactory>();\n const elements = new Map<string, AcceptableArtifact>();\n\n const setModule = (filePath: string, factory: GeneratorFactory) => {\n modules.set(filePath, factory);\n };\n\n /**\n * Creates an import request to be yielded by module generators.\n * Usage: `const { foo } = yield registry.requestImport(\"/path/to/module\");`\n */\n const requestImport = (filePath: string): EvaluationRequest => ({\n kind: \"import\",\n filePath,\n });\n\n const addElement = <TArtifact extends AcceptableArtifact>(canonicalId: string, factory: () => TArtifact) => {\n const builder = factory();\n GqlElement.setContext(builder, { canonicalId });\n // Don't evaluate yet - defer until all builders are registered\n elements.set(canonicalId, builder);\n return builder;\n };\n\n /**\n * Evaluate a single module and its dependencies using trampoline.\n * Returns the cached result or evaluates and caches if not yet evaluated.\n */\n const evaluateModule = (filePath: string, evaluated: Map<string, ArtifactModule>, inProgress: Set<string>): ArtifactModule => {\n // Already evaluated - return cached\n const cached = evaluated.get(filePath);\n if (cached) {\n return cached;\n }\n\n const stack: EvaluationFrame[] = [];\n\n // Start with the requested module\n const factory = modules.get(filePath);\n if (!factory) {\n throw new Error(`Module not found or yet to be registered: ${filePath}`);\n }\n stack.push({ filePath, generator: factory() });\n\n // Trampoline loop - process generators without deep recursion\n let frame: EvaluationFrame | undefined;\n while ((frame = stack[stack.length - 1])) {\n // Mark as in progress (for circular dependency detection)\n inProgress.add(frame.filePath);\n\n // Advance the generator\n const result =\n frame.resolvedDependency !== undefined ? frame.generator.next(frame.resolvedDependency) : frame.generator.next();\n\n // Clear the resolved dependency after use\n frame.resolvedDependency = undefined;\n\n if (result.done) {\n // Generator completed - cache result and pop frame\n evaluated.set(frame.filePath, result.value);\n inProgress.delete(frame.filePath);\n stack.pop();\n\n // If there's a parent frame waiting for this result, provide it\n const parentFrame = stack[stack.length - 1];\n if (parentFrame) {\n parentFrame.resolvedDependency = result.value;\n }\n } else {\n // Generator yielded - it needs a dependency\n const request = result.value;\n\n if (request.kind === \"import\") {\n const depPath = request.filePath;\n\n // Check if already evaluated (cached)\n const depCached = evaluated.get(depPath);\n if (depCached) {\n // Provide cached result without pushing new frame\n frame.resolvedDependency = depCached;\n } else {\n // Check for circular dependency\n if (inProgress.has(depPath)) {\n // If analyses is available, check if both modules have gql definitions\n // Only throw if both import source and target have gql definitions\n if (analyses) {\n const currentAnalysis = analyses.get(frame.filePath);\n const targetAnalysis = analyses.get(depPath);\n const currentHasGql = currentAnalysis && currentAnalysis.definitions.length > 0;\n const targetHasGql = targetAnalysis && targetAnalysis.definitions.length > 0;\n\n if (!currentHasGql || !targetHasGql) {\n // One or both modules have no gql definitions - allow circular import\n frame.resolvedDependency = {};\n continue;\n }\n }\n throw new Error(`Circular dependency detected: ${depPath}`);\n }\n\n // Need to evaluate dependency first\n const depFactory = modules.get(depPath);\n if (!depFactory) {\n throw new Error(`Module not found or yet to be registered: ${depPath}`);\n }\n\n // Push new frame for dependency\n stack.push({\n filePath: depPath,\n generator: depFactory(),\n });\n }\n }\n }\n }\n\n const result = evaluated.get(filePath);\n if (!result) {\n throw new Error(`Module evaluation failed: ${filePath}`);\n }\n return result;\n };\n\n /**\n * Build artifacts record from evaluated elements.\n */\n const buildArtifacts = (): Record<string, IntermediateArtifactElement> => {\n const artifacts: Record<string, IntermediateArtifactElement> = {};\n for (const [canonicalId, element] of elements.entries()) {\n if (element instanceof Fragment) {\n artifacts[canonicalId] = { type: \"fragment\", element };\n } else if (element instanceof Operation) {\n artifacts[canonicalId] = { type: \"operation\", element };\n }\n }\n return artifacts;\n };\n\n /**\n * Generator that evaluates all elements using the effect system.\n * Uses ParallelEffect to enable parallel evaluation in async mode.\n * In sync mode, ParallelEffect executes effects sequentially.\n */\n function* evaluateElementsGen(): EffectGenerator<void> {\n const effects = Array.from(elements.values(), (element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n }\n\n /**\n * Synchronous evaluation - evaluates all modules and elements synchronously.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n const evaluate = (): Record<string, IntermediateArtifactElement> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (each evaluation handles its own dependencies)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using sync scheduler\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw new Error(`Element evaluation failed: ${result.error.message}`);\n }\n\n return buildArtifacts();\n };\n\n /**\n * Asynchronous evaluation - evaluates all modules and elements with async support.\n * Supports async metadata factories and other async operations.\n */\n const evaluateAsync = async (): Promise<Record<string, IntermediateArtifactElement>> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (module evaluation is synchronous - no I/O operations)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using async scheduler\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw new Error(`Element evaluation failed: ${result.error.message}`);\n }\n\n return buildArtifacts();\n };\n\n /**\n * Evaluate all modules synchronously using trampoline.\n * This runs the module dependency resolution without element evaluation.\n * Call this before getElements() when using external scheduler control.\n */\n const evaluateModules = (): void => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n };\n\n /**\n * Get all registered elements for external effect creation.\n * Call evaluateModules() first to ensure all modules have been evaluated.\n */\n const getElements = (): AcceptableArtifact[] => {\n return Array.from(elements.values());\n };\n\n const clear = () => {\n modules.clear();\n elements.clear();\n };\n\n return {\n setModule,\n requestImport,\n addElement,\n evaluate,\n evaluateAsync,\n evaluateModules,\n getElements,\n buildArtifacts,\n clear,\n };\n};\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { extname, resolve } from \"node:path\";\nimport { createContext, Script } from \"node:vm\";\nimport { type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport * as sandboxCore from \"@soda-gql/core\";\nimport * as sandboxRuntime from \"@soda-gql/runtime\";\nimport { transformSync } from \"@swc/core\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { BuilderError } from \"../errors\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport { renderRegistryBlock } from \"./codegen\";\nimport { createIntermediateRegistry } from \"./registry\";\nimport type { IntermediateArtifactElement, IntermediateModule } from \"./types\";\n\nexport type BuildIntermediateModulesInput = {\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly targetFiles: Set<string>;\n readonly graphqlSystemPath: string;\n};\n\nconst transpile = ({ filePath, sourceCode }: { filePath: string; sourceCode: string }): Result<string, BuilderError> => {\n try {\n const result = transformSync(sourceCode, {\n filename: `${filePath}.ts`,\n jsc: {\n parser: {\n syntax: \"typescript\",\n tsx: false,\n },\n target: \"es2022\",\n },\n module: {\n type: \"es6\",\n },\n sourceMaps: false,\n minify: false,\n });\n\n return ok(result.code);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return err({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: filePath,\n astPath: \"\",\n message: `SWC transpilation failed: ${message}`,\n });\n }\n};\n\n/**\n * Resolve graphql system path to the bundled CJS file.\n * Accepts both .ts (for backward compatibility) and .cjs paths.\n * Maps .ts to sibling .cjs file if it exists.\n */\nfunction resolveGraphqlSystemPath(configPath: string): string {\n const ext = extname(configPath);\n\n // If already pointing to .cjs, use as-is\n if (ext === \".cjs\") {\n return resolve(process.cwd(), configPath);\n }\n\n // If pointing to .ts, try to resolve to sibling .cjs\n if (ext === \".ts\") {\n const basePath = configPath.slice(0, -3); // Remove .ts\n const cjsPath = `${basePath}.cjs`;\n const resolvedCjsPath = resolve(process.cwd(), cjsPath);\n\n // Check if .cjs exists, otherwise fall back to .ts (for error messages)\n if (existsSync(resolvedCjsPath)) {\n return resolvedCjsPath;\n }\n\n // Fall back to .ts path (will fail later with clearer error)\n return resolve(process.cwd(), configPath);\n }\n\n // For other extensions or no extension, use as-is\n return resolve(process.cwd(), configPath);\n}\n\n/**\n * Bundle and execute GraphQL system module using rspack + memfs.\n * Creates a self-contained bundle that can run in VM context.\n * This is cached per session to avoid re-bundling.\n */\nlet cachedGql: unknown = null;\nlet cachedModulePath: string | null = null;\n\n/**\n * Clear the cached gql module.\n * Call this between test runs to ensure clean state.\n * @internal - exported for testing purposes only\n */\nexport const __clearGqlCache = (): void => {\n cachedGql = null;\n cachedModulePath = null;\n};\n\nfunction executeGraphqlSystemModule(modulePath: string): { gql: unknown } {\n // Use cached module if same path\n if (cachedModulePath === modulePath && cachedGql !== null) {\n return { gql: cachedGql };\n }\n\n // Bundle the GraphQL system module\n const bundledCode = readFileSync(modulePath, \"utf-8\");\n\n // Create a shared CommonJS module exports object\n const moduleExports: Record<string, unknown> = {};\n\n // Create sandbox with proper CommonJS emulation\n const sandbox = {\n // Provide @soda-gql packages through require()\n require: (path: string) => {\n if (path === \"@soda-gql/core\") {\n return sandboxCore;\n }\n if (path === \"@soda-gql/runtime\") {\n return sandboxRuntime;\n }\n throw new Error(`Unknown module: ${path}`);\n },\n // Both module.exports and exports point to the same object\n module: { exports: moduleExports },\n exports: moduleExports,\n __dirname: resolve(modulePath, \"..\"),\n __filename: modulePath,\n global: undefined as unknown,\n globalThis: undefined as unknown,\n };\n // Wire global and globalThis to the sandbox itself\n sandbox.global = sandbox;\n sandbox.globalThis = sandbox;\n\n new Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);\n\n // Read exported gql (handle both direct export and default export)\n const exportedGql = moduleExports.gql ?? moduleExports.default;\n\n if (exportedGql === undefined) {\n throw new Error(`No 'gql' export found in GraphQL system module: ${modulePath}`);\n }\n\n // Cache the result\n cachedGql = exportedGql;\n cachedModulePath = modulePath;\n\n return { gql: cachedGql };\n}\n\n/**\n * Build intermediate modules from dependency graph.\n * Each intermediate module corresponds to one source file.\n */\nexport const generateIntermediateModules = function* ({\n analyses,\n targetFiles,\n graphqlSystemPath,\n}: BuildIntermediateModulesInput): Generator<IntermediateModule, void, undefined> {\n for (const filePath of targetFiles) {\n const analysis = analyses.get(filePath);\n if (!analysis) {\n continue;\n }\n\n // Generate source code for this intermediate module\n const sourceCode = renderRegistryBlock({ filePath, analysis, analyses, graphqlSystemPath });\n\n // Debug: log the generated source code\n if (process.env.DEBUG_INTERMEDIATE_MODULE) {\n console.log(\"=== Intermediate module source ===\");\n console.log(\"FilePath:\", filePath);\n console.log(\n \"Definitions:\",\n analysis.definitions.map((d) => d.astPath),\n );\n console.log(\"Source code:\\n\", sourceCode);\n console.log(\"=================================\");\n }\n\n // Transpile TypeScript to JavaScript using SWC\n const transpiledCodeResult = transpile({ filePath, sourceCode });\n if (transpiledCodeResult.isErr()) {\n // error\n continue;\n }\n const transpiledCode = transpiledCodeResult.value;\n\n const script = new Script(transpiledCode);\n\n const hash = createHash(\"sha1\");\n hash.update(transpiledCode);\n const contentHash = hash.digest(\"hex\");\n const canonicalIds = analysis.definitions.map((definition) => definition.canonicalId);\n\n yield {\n filePath,\n canonicalIds,\n sourceCode,\n transpiledCode,\n contentHash,\n script,\n };\n }\n};\n\nexport type EvaluateIntermediateModulesInput = {\n intermediateModules: Map<string, IntermediateModule>;\n graphqlSystemPath: string;\n analyses: Map<string, ModuleAnalysis>;\n};\n\n/**\n * Set up VM context and run intermediate module scripts.\n * Returns the registry for evaluation.\n */\nconst setupIntermediateModulesContext = ({\n intermediateModules,\n graphqlSystemPath,\n analyses,\n}: EvaluateIntermediateModulesInput) => {\n const registry = createIntermediateRegistry({ analyses });\n const gqlImportPath = resolveGraphqlSystemPath(graphqlSystemPath);\n\n const { gql } = executeGraphqlSystemModule(gqlImportPath);\n\n const vmContext = createContext({ gql, registry });\n\n for (const { script, filePath } of intermediateModules.values()) {\n try {\n script.runInContext(vmContext);\n } catch (error) {\n console.error(`Error evaluating intermediate module ${filePath}:`, error);\n throw error;\n }\n }\n\n return registry;\n};\n\n/**\n * Synchronous evaluation of intermediate modules.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\nexport const evaluateIntermediateModules = (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = registry.evaluate();\n registry.clear();\n return elements;\n};\n\n/**\n * Asynchronous evaluation of intermediate modules.\n * Supports async metadata factories and other async operations.\n */\nexport const evaluateIntermediateModulesAsync = async (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = await registry.evaluateAsync();\n registry.clear();\n return elements;\n};\n\n/**\n * Generator version of evaluateIntermediateModules for external scheduler control.\n * Yields effects for element evaluation, enabling unified scheduler at the root level.\n *\n * This function:\n * 1. Sets up the VM context and runs intermediate module scripts\n * 2. Runs synchronous module evaluation (trampoline - no I/O)\n * 3. Yields element evaluation effects via ParallelEffect\n * 4. Returns the artifacts record\n */\nexport function* evaluateIntermediateModulesGen(\n input: EvaluateIntermediateModulesInput,\n): EffectGenerator<Record<string, IntermediateArtifactElement>> {\n const registry = setupIntermediateModulesContext(input);\n\n // Run synchronous module evaluation (trampoline pattern, no I/O)\n registry.evaluateModules();\n\n // Yield element evaluation effects\n const elements = registry.getElements();\n const effects = elements.map((element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n\n const artifacts = registry.buildArtifacts();\n registry.clear();\n return artifacts;\n}\n","/**\n * Helper for identifying graphql-system files and import specifiers.\n * Provides robust detection across symlinks, case-insensitive filesystems, and user-defined aliases.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\n\nexport type GraphqlSystemIdentifyHelper = {\n readonly isGraphqlSystemFile: (input: { filePath: string }) => boolean;\n readonly isGraphqlSystemImportSpecifier: (input: { filePath: string; specifier: string }) => boolean;\n};\n\n/**\n * Create a canonical file name getter based on platform.\n * On case-sensitive filesystems, paths are returned as-is.\n * On case-insensitive filesystems, paths are lowercased for comparison.\n */\nconst createGetCanonicalFileName = (useCaseSensitiveFileNames: boolean): ((path: string) => string) => {\n return useCaseSensitiveFileNames ? (path: string) => path : (path: string) => path.toLowerCase();\n};\n\n/**\n * Detect if the filesystem is case-sensitive.\n * We assume Unix-like systems are case-sensitive, and Windows is not.\n */\nconst getUseCaseSensitiveFileNames = (): boolean => {\n return process.platform !== \"win32\";\n};\n\n/**\n * Create a GraphqlSystemIdentifyHelper from the resolved config.\n * Uses canonical path comparison to handle casing, symlinks, and aliases.\n */\nexport const createGraphqlSystemIdentifyHelper = (config: ResolvedSodaGqlConfig): GraphqlSystemIdentifyHelper => {\n const getCanonicalFileName = createGetCanonicalFileName(getUseCaseSensitiveFileNames());\n\n const toCanonical = (file: string): string => {\n const resolved = resolve(file);\n // Use realpathSync to resolve symlinks for accurate comparison\n try {\n return getCanonicalFileName(realpathSync(resolved));\n } catch {\n // If realpath fails (file doesn't exist yet), fall back to resolved path\n return getCanonicalFileName(resolved);\n }\n };\n\n // Derive graphql system path from outdir (assume index.ts as default entry)\n const graphqlSystemPath = resolve(config.outdir, \"index.ts\");\n const canonicalGraphqlSystemPath = toCanonical(graphqlSystemPath);\n\n // Build canonical alias map\n const canonicalAliases = new Set(config.graphqlSystemAliases.map((alias) => alias));\n\n return {\n isGraphqlSystemFile: ({ filePath }: { filePath: string }) => {\n return toCanonical(filePath) === canonicalGraphqlSystemPath;\n },\n isGraphqlSystemImportSpecifier: ({ filePath, specifier }: { filePath: string; specifier: string }) => {\n // Check against aliases first if configured\n if (canonicalAliases.has(specifier)) {\n return true;\n }\n\n // Only try to resolve relative imports (starting with . or ..)\n // External specifiers without an alias configured should not match\n if (!specifier.startsWith(\".\")) {\n return false;\n }\n\n // Try to resolve as relative import\n const resolved = resolveRelativeImportWithExistenceCheck({ filePath, specifier });\n if (!resolved) {\n return false;\n }\n\n return toCanonical(resolved) === canonicalGraphqlSystemPath;\n },\n };\n};\n","import type { CanonicalId } from \"@soda-gql/common\";\nimport { z } from \"zod\";\nimport type { BuilderArtifactFragment, BuilderArtifactOperation } from \"../artifact/types\";\n\nconst BuilderArtifactElementMetadataSchema = z.object({\n sourcePath: z.string(),\n contentHash: z.string(),\n});\n\nconst BuilderArtifactOperationSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"operation\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n operationType: z.enum([\"query\", \"mutation\", \"subscription\"]),\n operationName: z.string(),\n document: z.unknown(), // DocumentNode object\n variableNames: z.array(z.string()),\n }),\n});\n\ndeclare function __validate_BuilderArtifactOperationSchema<\n _ extends z.infer<typeof BuilderArtifactOperationSchema> = BuilderArtifactOperation,\n>(): never;\n\nconst BuilderArtifactFragmentSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"fragment\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n typename: z.string(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactFragmentSchema<\n _ extends z.infer<typeof BuilderArtifactFragmentSchema> = BuilderArtifactFragment,\n>(): never;\n\nconst BuilderArtifactElementSchema = z.discriminatedUnion(\"type\", [\n BuilderArtifactOperationSchema,\n BuilderArtifactFragmentSchema,\n]);\n\nexport const BuilderArtifactSchema = z.object({\n elements: z.record(z.string<CanonicalId>(), BuilderArtifactElementSchema),\n report: z.object({\n durationMs: z.number(),\n warnings: z.array(z.string()),\n stats: z.object({\n hits: z.number(),\n misses: z.number(),\n skips: z.number(),\n }),\n }),\n});\n\nexport type BuilderArtifact = z.infer<typeof BuilderArtifactSchema>;\nexport type BuilderArtifactElement = z.infer<typeof BuilderArtifactElementSchema>;\n","import { createHash } from \"node:crypto\";\n\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis, ModuleDefinition } from \"../ast\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\nimport type { BuilderError } from \"../types\";\nimport type { BuilderArtifactElement, BuilderArtifactElementMetadata } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nconst computeContentHash = (prebuild: unknown): string => {\n const hash = createHash(\"sha1\");\n hash.update(JSON.stringify(prebuild));\n return hash.digest(\"hex\");\n};\n\nconst emitRegistrationError = (definition: ModuleDefinition, message: string): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: canonicalToFilePath(definition.canonicalId),\n astPath: definition.astPath,\n message,\n});\n\ntype AggregateInput = {\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n};\n\nexport const aggregate = ({ analyses, elements }: AggregateInput): Result<Map<string, BuilderArtifactElement>, BuilderError> => {\n const registry = new Map<string, BuilderArtifactElement>();\n\n for (const analysis of analyses.values()) {\n for (const definition of analysis.definitions) {\n const element = elements[definition.canonicalId];\n if (!element) {\n const availableIds = Object.keys(elements).join(\", \");\n const message = `ARTIFACT_NOT_FOUND_IN_RUNTIME_MODULE: ${definition.canonicalId}\\nAvailable: ${availableIds}`;\n return err(emitRegistrationError(definition, message));\n }\n\n if (registry.has(definition.canonicalId)) {\n return err(emitRegistrationError(definition, `ARTIFACT_ALREADY_REGISTERED`));\n }\n\n const metadata: BuilderArtifactElementMetadata = {\n sourcePath: analysis.filePath ?? canonicalToFilePath(definition.canonicalId),\n contentHash: \"\", // Will be computed after prebuild creation\n };\n\n if (element.type === \"fragment\") {\n const prebuild = { typename: element.element.typename };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"fragment\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n if (element.type === \"operation\") {\n const prebuild = {\n operationType: element.element.operationType,\n operationName: element.element.operationName,\n document: element.element.document,\n variableNames: element.element.variableNames,\n metadata: element.element.metadata,\n };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"operation\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n return err(emitRegistrationError(definition, \"UNKNOWN_ARTIFACT_KIND\"));\n }\n }\n\n return ok(registry);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../types\";\nimport type { IntermediateElements } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nexport const checkIssues = ({ elements }: { elements: IntermediateElements }): Result<string[], BuilderError> => {\n const operationNames = new Set<string>();\n\n for (const [canonicalId, { type, element }] of Object.entries(elements)) {\n if (type !== \"operation\") {\n continue;\n }\n\n if (operationNames.has(element.operationName)) {\n const sources = [canonicalToFilePath(canonicalId)];\n return err({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${element.operationName}`,\n name: element.operationName,\n sources,\n });\n }\n\n operationNames.add(element.operationName);\n }\n\n return ok([]);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { ModuleLoadStats } from \"../discovery\";\nimport type { BuilderError } from \"../types\";\nimport { aggregate } from \"./aggregate\";\nimport { checkIssues } from \"./issue-handler\";\nimport type { BuilderArtifact, IntermediateElements } from \"./types\";\n\ntype BuildArtifactInput = {\n readonly elements: IntermediateElements;\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly stats: ModuleLoadStats;\n};\n\nexport const buildArtifact = ({\n elements,\n analyses,\n stats: cache,\n}: BuildArtifactInput): Result<BuilderArtifact, BuilderError> => {\n const issuesResult = checkIssues({ elements });\n if (issuesResult.isErr()) {\n return err(issuesResult.error);\n }\n\n const warnings = issuesResult.value;\n\n const aggregationResult = aggregate({ analyses, elements });\n if (aggregationResult.isErr()) {\n return err(aggregationResult.error);\n }\n\n return ok({\n elements: Object.fromEntries(aggregationResult.value.entries()),\n report: {\n durationMs: 0,\n warnings,\n stats: cache,\n },\n } satisfies BuilderArtifact);\n};\n","import { err, type Result } from \"neverthrow\";\n\n/**\n * Comprehensive error code taxonomy for Builder operations.\n */\nexport type BuilderErrorCode =\n // Input/Configuration errors\n | \"ENTRY_NOT_FOUND\"\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n // Discovery errors\n | \"DISCOVERY_IO_ERROR\"\n | \"FINGERPRINT_FAILED\"\n | \"UNSUPPORTED_ANALYZER\"\n // Canonical ID errors\n | \"CANONICAL_PATH_INVALID\"\n | \"CANONICAL_SCOPE_MISMATCH\"\n // Graph/Analysis errors\n | \"GRAPH_CIRCULAR_DEPENDENCY\"\n | \"GRAPH_MISSING_IMPORT\"\n | \"DOC_DUPLICATE\"\n // Emission/IO errors\n | \"WRITE_FAILED\"\n | \"CACHE_CORRUPTED\"\n // Runtime evaluation errors\n | \"RUNTIME_MODULE_LOAD_FAILED\"\n | \"ARTIFACT_REGISTRATION_FAILED\"\n // Internal invariant violations\n | \"INTERNAL_INVARIANT\";\n\n/**\n * Structured error type for all Builder operations.\n */\nexport type BuilderError =\n // Input/Configuration\n | {\n readonly code: \"ENTRY_NOT_FOUND\";\n readonly message: string;\n readonly entry: string;\n }\n | {\n readonly code: \"CONFIG_NOT_FOUND\";\n readonly message: string;\n readonly path: string;\n }\n | {\n readonly code: \"CONFIG_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly cause?: unknown;\n }\n // Discovery\n | {\n readonly code: \"DISCOVERY_IO_ERROR\";\n readonly message: string;\n readonly path: string;\n readonly errno?: string | number;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"FINGERPRINT_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"UNSUPPORTED_ANALYZER\";\n readonly message: string;\n readonly analyzer: string;\n }\n // Canonical ID\n | {\n readonly code: \"CANONICAL_PATH_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly reason?: string;\n }\n | {\n readonly code: \"CANONICAL_SCOPE_MISMATCH\";\n readonly message: string;\n readonly expected: string;\n readonly actual: string;\n }\n // Graph/Analysis\n | {\n readonly code: \"GRAPH_CIRCULAR_DEPENDENCY\";\n readonly message: string;\n readonly chain: readonly string[];\n }\n | {\n readonly code: \"GRAPH_MISSING_IMPORT\";\n readonly message: string;\n readonly importer: string;\n readonly importee: string;\n }\n | {\n readonly code: \"DOC_DUPLICATE\";\n readonly message: string;\n readonly name: string;\n readonly sources: readonly string[];\n }\n // Emission/IO\n | {\n readonly code: \"WRITE_FAILED\";\n readonly message: string;\n readonly outPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"CACHE_CORRUPTED\";\n readonly message: string;\n readonly cachePath?: string;\n readonly cause?: unknown;\n }\n // Runtime evaluation\n | {\n readonly code: \"RUNTIME_MODULE_LOAD_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"ARTIFACT_REGISTRATION_FAILED\";\n readonly message: string;\n readonly elementId: string;\n readonly reason: string;\n }\n // Internal invariant\n | {\n readonly code: \"INTERNAL_INVARIANT\";\n readonly message: string;\n readonly context?: string;\n readonly cause?: unknown;\n };\n\n/**\n * Helper type for Builder operation results.\n */\nexport type BuilderResult<T> = Result<T, BuilderError>;\n\n/**\n * Error constructor helpers for concise error creation.\n */\nexport const builderErrors = {\n entryNotFound: (entry: string, message?: string): BuilderError => ({\n code: \"ENTRY_NOT_FOUND\",\n message: message ?? `Entry not found: ${entry}`,\n entry,\n }),\n\n configNotFound: (path: string, message?: string): BuilderError => ({\n code: \"CONFIG_NOT_FOUND\",\n message: message ?? `Config file not found: ${path}`,\n path,\n }),\n\n configInvalid: (path: string, message: string, cause?: unknown): BuilderError => ({\n code: \"CONFIG_INVALID\",\n message,\n path,\n cause,\n }),\n\n discoveryIOError: (path: string, message: string, errno?: string | number, cause?: unknown): BuilderError => ({\n code: \"DISCOVERY_IO_ERROR\",\n message,\n path,\n errno,\n cause,\n }),\n\n fingerprintFailed: (filePath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"FINGERPRINT_FAILED\",\n message,\n filePath,\n cause,\n }),\n\n unsupportedAnalyzer: (analyzer: string, message?: string): BuilderError => ({\n code: \"UNSUPPORTED_ANALYZER\",\n message: message ?? `Unsupported analyzer: ${analyzer}`,\n analyzer,\n }),\n\n canonicalPathInvalid: (path: string, reason?: string): BuilderError => ({\n code: \"CANONICAL_PATH_INVALID\",\n message: `Invalid canonical path: ${path}${reason ? ` (${reason})` : \"\"}`,\n path,\n reason,\n }),\n\n canonicalScopeMismatch: (expected: string, actual: string): BuilderError => ({\n code: \"CANONICAL_SCOPE_MISMATCH\",\n message: `Scope mismatch: expected ${expected}, got ${actual}`,\n expected,\n actual,\n }),\n\n graphCircularDependency: (chain: readonly string[]): BuilderError => ({\n code: \"GRAPH_CIRCULAR_DEPENDENCY\",\n message: `Circular dependency detected: ${chain.join(\" → \")}`,\n chain,\n }),\n\n graphMissingImport: (importer: string, importee: string): BuilderError => ({\n code: \"GRAPH_MISSING_IMPORT\",\n message: `Missing import: \"${importer}\" imports \"${importee}\" but it's not in the graph`,\n importer,\n importee,\n }),\n\n docDuplicate: (name: string, sources: readonly string[]): BuilderError => ({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${name} found in ${sources.length} files`,\n name,\n sources,\n }),\n\n writeFailed: (outPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"WRITE_FAILED\",\n message,\n outPath,\n cause,\n }),\n\n cacheCorrupted: (message: string, cachePath?: string, cause?: unknown): BuilderError => ({\n code: \"CACHE_CORRUPTED\",\n message,\n cachePath,\n cause,\n }),\n\n runtimeModuleLoadFailed: (filePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n message,\n filePath,\n astPath,\n cause,\n }),\n\n artifactRegistrationFailed: (elementId: string, reason: string): BuilderError => ({\n code: \"ARTIFACT_REGISTRATION_FAILED\",\n message: `Failed to register artifact element ${elementId}: ${reason}`,\n elementId,\n reason,\n }),\n\n internalInvariant: (message: string, context?: string, cause?: unknown): BuilderError => ({\n code: \"INTERNAL_INVARIANT\",\n message: `Internal invariant violated: ${message}`,\n context,\n cause,\n }),\n} as const;\n\n/**\n * Convenience helper to create an err Result from BuilderError.\n */\nexport const builderErr = <T = never>(error: BuilderError): BuilderResult<T> => err(error);\n\n/**\n * Type guard for BuilderError.\n */\nexport const isBuilderError = (error: unknown): error is BuilderError => {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\"\n );\n};\n\n/**\n * Format BuilderError for console output (human-readable).\n */\nexport const formatBuilderError = (error: BuilderError): string => {\n const lines: string[] = [];\n\n lines.push(`Error [${error.code}]: ${error.message}`);\n\n // Add context-specific details\n switch (error.code) {\n case \"ENTRY_NOT_FOUND\":\n lines.push(` Entry: ${error.entry}`);\n break;\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.code === \"CONFIG_INVALID\" && error.cause) {\n lines.push(` Cause: ${error.cause}`);\n }\n break;\n case \"DISCOVERY_IO_ERROR\":\n lines.push(` Path: ${error.path}`);\n if (error.errno !== undefined) {\n lines.push(` Errno: ${error.errno}`);\n }\n break;\n case \"FINGERPRINT_FAILED\":\n lines.push(` File: ${error.filePath}`);\n break;\n case \"CANONICAL_PATH_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.reason) {\n lines.push(` Reason: ${error.reason}`);\n }\n break;\n case \"CANONICAL_SCOPE_MISMATCH\":\n lines.push(` Expected: ${error.expected}`);\n lines.push(` Actual: ${error.actual}`);\n break;\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n lines.push(` Chain: ${error.chain.join(\" → \")}`);\n break;\n case \"GRAPH_MISSING_IMPORT\":\n lines.push(` Importer: ${error.importer}`);\n lines.push(` Importee: ${error.importee}`);\n break;\n case \"DOC_DUPLICATE\":\n lines.push(` Name: ${error.name}`);\n lines.push(` Sources:\\n ${error.sources.join(\"\\n \")}`);\n break;\n case \"WRITE_FAILED\":\n lines.push(` Output path: ${error.outPath}`);\n break;\n case \"CACHE_CORRUPTED\":\n if (error.cachePath) {\n lines.push(` Cache path: ${error.cachePath}`);\n }\n break;\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n lines.push(` File: ${error.filePath}`);\n lines.push(` AST path: ${error.astPath}`);\n break;\n case \"ARTIFACT_REGISTRATION_FAILED\":\n lines.push(` Element ID: ${error.elementId}`);\n lines.push(` Reason: ${error.reason}`);\n break;\n case \"INTERNAL_INVARIANT\":\n if (error.context) {\n lines.push(` Context: ${error.context}`);\n }\n break;\n }\n\n // Add cause if present and not already shown\n if (\"cause\" in error && error.cause && ![\"CONFIG_INVALID\"].includes(error.code)) {\n lines.push(` Caused by: ${error.cause}`);\n }\n\n return lines.join(\"\\n\");\n};\n\n/**\n * Assert unreachable code path (for exhaustiveness checks).\n * This is the ONLY acceptable throw in builder code.\n */\nexport const assertUnreachable = (value: never, context?: string): never => {\n throw new Error(`Unreachable code path${context ? ` in ${context}` : \"\"}: received ${JSON.stringify(value)}`);\n};\n","/**\n * Shared utilities for AST traversal and scope tracking.\n * Used by both TypeScript and SWC adapters.\n */\n\n/**\n * Scope frame for tracking AST path segments\n */\nexport type ScopeFrame = {\n /** Name segment (e.g., \"MyComponent\", \"useQuery\", \"arrow#1\") */\n readonly nameSegment: string;\n /** Kind of scope */\n readonly kind: \"function\" | \"class\" | \"variable\" | \"property\" | \"method\" | \"expression\";\n};\n\n/**\n * Build AST path from scope stack\n */\nexport const buildAstPath = (stack: readonly ScopeFrame[]): string => {\n return stack.map((frame) => frame.nameSegment).join(\".\");\n};\n\n/**\n * Create an occurrence tracker for disambiguating anonymous/duplicate scopes.\n */\nexport const createOccurrenceTracker = (): {\n getNextOccurrence: (key: string) => number;\n} => {\n const occurrenceCounters = new Map<string, number>();\n\n return {\n getNextOccurrence(key: string): number {\n const current = occurrenceCounters.get(key) ?? 0;\n occurrenceCounters.set(key, current + 1);\n return current;\n },\n };\n};\n\n/**\n * Create a path uniqueness tracker to ensure AST paths are unique.\n */\nexport const createPathTracker = (): {\n ensureUniquePath: (basePath: string) => string;\n} => {\n const usedPaths = new Set<string>();\n\n return {\n ensureUniquePath(basePath: string): string {\n let path = basePath;\n let suffix = 0;\n while (usedPaths.has(path)) {\n suffix++;\n path = `${basePath}$${suffix}`;\n }\n usedPaths.add(path);\n return path;\n },\n };\n};\n\n/**\n * Create an export bindings map from module exports.\n * Maps local variable names to their exported names.\n */\nexport const createExportBindingsMap = <T extends { kind: string; local?: string; exported: string; isTypeOnly?: boolean }>(\n exports: readonly T[],\n): Map<string, string> => {\n const exportBindings = new Map<string, string>();\n exports.forEach((exp) => {\n if (exp.kind === \"named\" && exp.local && !exp.isTypeOnly) {\n exportBindings.set(exp.local, exp.exported);\n }\n });\n return exportBindings;\n};\n","/**\n * SWC adapter for the analyzer core.\n * Implements parser-specific logic using the SWC parser.\n */\n\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport { parseSync } from \"@swc/core\";\nimport type { CallExpression, ImportDeclaration, Module } from \"@swc/types\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\n\n/**\n * Extended SWC Module with filePath attached (similar to ts.SourceFile.fileName)\n */\ntype SwcModule = Module & {\n __filePath: string;\n /** Offset to subtract from spans to normalize to 0-based source indices */\n __spanOffset: number;\n};\n\nimport type { AnalyzeModuleInput, ModuleDefinition, ModuleExport, ModuleImport } from \"../types\";\n\nconst collectImports = (module: Module): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n const handle = (declaration: ImportDeclaration) => {\n const source = declaration.source.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"named\",\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"namespace\",\n isTypeOnly: false,\n });\n return;\n }\n if (specifier.type === \"ImportDefaultSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"default\",\n isTypeOnly: false,\n });\n }\n });\n };\n\n module.body.forEach((item) => {\n if (item.type === \"ImportDeclaration\") {\n handle(item);\n return;\n }\n // Handle module declarations with import declarations\n if (\n \"declaration\" in item &&\n item.declaration &&\n \"type\" in item.declaration &&\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any).type === \"ImportDeclaration\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n handle(item.declaration as any as ImportDeclaration);\n }\n });\n\n return imports;\n};\n\nconst collectExports = (module: Module): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const handle = (declaration: any) => {\n if (declaration.type === \"ExportDeclaration\") {\n if (declaration.declaration.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n declaration.declaration.declarations.forEach((decl: any) => {\n if (decl.id.type === \"Identifier\") {\n exports.push({\n kind: \"named\",\n exported: decl.id.value,\n local: decl.id.value,\n isTypeOnly: false,\n });\n }\n });\n }\n if (declaration.declaration.type === \"FunctionDeclaration\") {\n const ident = declaration.declaration.identifier;\n if (ident) {\n exports.push({\n kind: \"named\",\n exported: ident.value,\n local: ident.value,\n isTypeOnly: false,\n });\n }\n }\n return;\n }\n\n if (declaration.type === \"ExportNamedDeclaration\") {\n const source = declaration.source?.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type !== \"ExportSpecifier\") {\n return;\n }\n const exported = specifier.exported ? specifier.exported.value : specifier.orig.value;\n const local = specifier.orig.value;\n if (source) {\n exports.push({\n kind: \"reexport\",\n exported,\n local,\n source,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n exports.push({\n kind: \"named\",\n exported,\n local,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n });\n return;\n }\n\n if (declaration.type === \"ExportAllDeclaration\") {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: declaration.source.value,\n isTypeOnly: false,\n });\n return;\n }\n\n if (declaration.type === \"ExportDefaultDeclaration\" || declaration.type === \"ExportDefaultExpression\") {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n };\n\n module.body.forEach((item) => {\n if (\n item.type === \"ExportDeclaration\" ||\n item.type === \"ExportNamedDeclaration\" ||\n item.type === \"ExportAllDeclaration\" ||\n item.type === \"ExportDefaultDeclaration\" ||\n item.type === \"ExportDefaultExpression\"\n ) {\n handle(item);\n return;\n }\n\n if (\"declaration\" in item && item.declaration) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n const declaration = item.declaration as any;\n if (\n declaration.type === \"ExportDeclaration\" ||\n declaration.type === \"ExportNamedDeclaration\" ||\n declaration.type === \"ExportAllDeclaration\" ||\n declaration.type === \"ExportDefaultDeclaration\" ||\n declaration.type === \"ExportDefaultExpression\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Complex SWC AST type\n handle(declaration as any);\n }\n }\n });\n\n return exports;\n};\n\nconst collectGqlIdentifiers = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\n : // biome-ignore lint/suspicious/noExplicitAny: SWC AST type checking\n \"declaration\" in item && item.declaration && (item.declaration as any).type === \"ImportDeclaration\"\n ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n if (!declaration) {\n return;\n }\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n if (imported === \"gql\") {\n identifiers.add(specifier.local.value);\n }\n }\n });\n });\n return identifiers;\n};\n\nconst isGqlCall = (identifiers: ReadonlySet<string>, call: CallExpression): boolean => {\n const callee = call.callee;\n if (callee.type !== \"MemberExpression\") {\n return false;\n }\n\n if (callee.object.type !== \"Identifier\") {\n return false;\n }\n\n if (!identifiers.has(callee.object.value)) {\n return false;\n }\n\n if (callee.property.type !== \"Identifier\") {\n return false;\n }\n\n const firstArg = call.arguments[0];\n if (!firstArg?.expression || firstArg.expression.type !== \"ArrowFunctionExpression\") {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: any): CallExpression | null => {\n if (!node || node.type !== \"CallExpression\") {\n return null;\n }\n\n // Check if this is directly a gql call\n if (isGqlCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\") {\n return null;\n }\n\n // Recursively check the object of the member expression\n // e.g., for `gql.default(...).attach(...)`, callee.object is `gql.default(...)`\n return unwrapMethodChains(identifiers, callee.object);\n};\n\nconst collectAllDefinitions = ({\n module,\n gqlIdentifiers,\n imports: _imports,\n exports,\n source,\n}: {\n module: SwcModule;\n gqlIdentifiers: ReadonlySet<string>;\n imports: readonly ModuleImport[];\n exports: readonly ModuleExport[];\n source: string;\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly CallExpression[];\n} => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const getPropertyName = (property: any): string | null => {\n if (!property) {\n return null;\n }\n if (property.type === \"Identifier\") {\n return property.value;\n }\n if (property.type === \"StringLiteral\" || property.type === \"NumericLiteral\") {\n return property.value;\n }\n return null;\n };\n\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: module.__filePath,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const expressionFromCall = (call: CallExpression): string => {\n // Normalize span by subtracting the module's span offset\n const spanOffset = module.__spanOffset;\n let start = call.span.start - spanOffset;\n const end = call.span.end - spanOffset;\n\n // Adjust when span starts one character after the leading \"g\"\n if (start > 0 && source[start] === \"q\" && source[start - 1] === \"g\" && source.slice(start, start + 3) === \"ql.\") {\n start -= 1;\n }\n\n const raw = source.slice(start, end);\n const marker = raw.indexOf(\"gql\");\n const expression = marker >= 0 ? raw.slice(marker) : raw;\n\n // Strip trailing semicolons and whitespace that SWC may include in the span\n // TypeScript's node.getText() doesn't include these, so we normalize to match\n return expression.replace(/\\s*;\\s*$/, \"\");\n };\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any, stack: ScopeFrame[]) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (node.type === \"CallExpression\") {\n const gqlCall = unwrapMethodChains(gqlIdentifiers, node);\n if (gqlCall) {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: expressionFromCall(gqlCall),\n });\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (node.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.declarations?.forEach((decl: any) => {\n if (decl.id?.type === \"Identifier\") {\n const varName = decl.id.value;\n\n if (decl.init) {\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(decl.init, newStack);\n });\n }\n }\n });\n return;\n }\n\n // Function declaration\n if (node.type === \"FunctionDeclaration\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Arrow function\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowName = getAnonymousName(\"arrow\");\n\n if (node.body) {\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Function expression\n if (node.type === \"FunctionExpression\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Class declaration\n if (node.type === \"ClassDeclaration\") {\n const className = node.identifier?.value ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"ClassMethod\" || member.type === \"ClassProperty\") {\n const memberName = member.key?.value ?? null;\n if (memberName) {\n const memberKind = member.type === \"ClassMethod\" ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (member.type === \"ClassMethod\" && member.function?.body) {\n visit(member.function.body, memberStack);\n } else if (member.type === \"ClassProperty\" && member.value) {\n visit(member.value, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (node.type === \"KeyValueProperty\") {\n const propName = getPropertyName(node.key);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.value, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n if (Array.isArray(node)) {\n for (const child of node) {\n visit(child, stack);\n }\n } else {\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child, stack);\n }\n } else if (value && typeof value === \"object\") {\n visit(value, stack);\n }\n }\n }\n };\n\n // Start traversal from top-level statements\n module.body.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(module.__filePath, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * SWC adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (Module) is released after analysis.\n */\nexport const swcAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const program = parseSync(input.source, {\n syntax: \"typescript\",\n tsx: input.filePath.endsWith(\".tsx\"),\n target: \"es2022\",\n decorators: false,\n dynamicImport: true,\n });\n\n if (program.type !== \"Module\") {\n return null;\n }\n\n // SWC's BytePos counter accumulates across parseSync calls within the same process.\n // To convert span positions to 0-indexed source positions, we compute the accumulated\n // offset from previous parses: (program.span.end - source.length) gives us the total\n // bytes from previously parsed files, and we add 1 because spans are 1-indexed.\n const spanOffset = program.span.end - input.source.length + 1;\n\n // Attach filePath to module (similar to ts.SourceFile.fileName)\n const swcModule = program as SwcModule;\n swcModule.__filePath = input.filePath;\n swcModule.__spanOffset = spanOffset;\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlIdentifiers(swcModule, helper);\n const imports = collectImports(swcModule);\n const exports = collectExports(swcModule);\n\n const { definitions } = collectAllDefinitions({\n module: swcModule,\n gqlIdentifiers,\n imports,\n exports,\n source: input.source,\n });\n\n // Return results - swcModule goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n };\n },\n};\n","/**\n * TypeScript adapter for the analyzer core.\n * Implements parser-specific logic using the TypeScript compiler API.\n */\n\nimport { extname } from \"node:path\";\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport ts from \"typescript\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\nimport type { AnalyzeModuleInput, ModuleDefinition, ModuleExport, ModuleImport } from \"../types\";\n\nconst createSourceFile = (filePath: string, source: string): ts.SourceFile => {\n const scriptKind = extname(filePath) === \".tsx\" ? ts.ScriptKind.TSX : ts.ScriptKind.TS;\n return ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2022, true, scriptKind);\n};\n\nconst collectGqlImports = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: sourceFile.fileName, specifier: moduleText })) {\n return;\n }\n\n if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {\n statement.importClause.namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n if (imported === \"gql\") {\n identifiers.add(element.name.text);\n }\n });\n }\n });\n\n return identifiers;\n};\n\nconst collectImports = (sourceFile: ts.SourceFile): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n const { importClause } = statement;\n\n if (importClause.name) {\n imports.push({\n source: moduleText,\n local: importClause.name.text,\n kind: \"default\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) {\n return;\n }\n\n if (ts.isNamespaceImport(namedBindings)) {\n imports.push({\n source: moduleText,\n local: namedBindings.name.text,\n kind: \"namespace\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n return;\n }\n\n namedBindings.elements.forEach((element) => {\n imports.push({\n source: moduleText,\n local: element.name.text,\n kind: \"named\",\n isTypeOnly: Boolean(importClause.isTypeOnly || element.isTypeOnly),\n });\n });\n });\n\n return imports;\n};\n\nconst collectExports = (sourceFile: ts.SourceFile): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (ts.isExportDeclaration(statement)) {\n const moduleSpecifier = statement.moduleSpecifier ? (statement.moduleSpecifier as ts.StringLiteral).text : undefined;\n\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n statement.exportClause.elements.forEach((element) => {\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : undefined,\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n } else {\n exports.push({\n kind: \"named\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : element.name.text,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n }\n });\n return;\n }\n\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly),\n });\n }\n\n return;\n }\n\n if (ts.isExportAssignment(statement)) {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n\n if (\n ts.isVariableStatement(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n statement.declarationList.declarations.forEach((declaration) => {\n if (ts.isIdentifier(declaration.name)) {\n exports.push({\n kind: \"named\",\n exported: declaration.name.text,\n local: declaration.name.text,\n isTypeOnly: false,\n });\n }\n });\n }\n\n if (\n ts.isFunctionDeclaration(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) &&\n statement.name\n ) {\n exports.push({\n kind: \"named\",\n exported: statement.name.text,\n local: statement.name.text,\n isTypeOnly: false,\n });\n }\n });\n\n return exports;\n};\n\nconst isGqlDefinitionCall = (identifiers: ReadonlySet<string>, callExpression: ts.CallExpression): boolean => {\n const expression = callExpression.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return false;\n }\n\n if (!ts.isIdentifier(expression.expression) || !identifiers.has(expression.expression.text)) {\n return false;\n }\n\n const [factory] = callExpression.arguments;\n if (!factory || !ts.isArrowFunction(factory)) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: ts.Node): ts.CallExpression | null => {\n if (!ts.isCallExpression(node)) {\n return null;\n }\n\n // Check if this is directly a gql definition call\n if (isGqlDefinitionCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const expression = node.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return null;\n }\n\n // Recursively check the object of the property access\n // e.g., for `gql.default(...).attach(...)`, expression.expression is `gql.default(...)`\n return unwrapMethodChains(identifiers, expression.expression);\n};\n\n/**\n * Get property name from AST node\n */\nconst getPropertyName = (name: ts.PropertyName): string | null => {\n if (ts.isIdentifier(name)) {\n return name.text;\n }\n if (ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return null;\n};\n\n/**\n * Collect all gql definitions (exported, non-exported, top-level, nested)\n */\nconst collectAllDefinitions = ({\n sourceFile,\n identifiers,\n exports,\n}: {\n sourceFile: ts.SourceFile;\n identifiers: ReadonlySet<string>;\n exports: readonly ModuleExport[];\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly ts.CallExpression[];\n} => {\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: ts.CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: sourceFile.fileName,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const visit = (node: ts.Node, stack: ScopeFrame[]) => {\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (ts.isCallExpression(node)) {\n const gqlCall = unwrapMethodChains(identifiers, node);\n if (gqlCall) {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: gqlCall.getText(sourceFile),\n });\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (ts.isVariableDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const varName = node.name.text;\n\n if (node.initializer) {\n const next = node.initializer;\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(next, newStack);\n });\n }\n return;\n }\n\n // Function declaration\n if (ts.isFunctionDeclaration(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n const next = node.body;\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(next, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Arrow function\n if (ts.isArrowFunction(node)) {\n const arrowName = getAnonymousName(\"arrow\");\n\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n if (ts.isBlock(node.body)) {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n } else {\n visit(node.body, newStack);\n }\n });\n return;\n }\n\n // Function expression\n if (ts.isFunctionExpression(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Class declaration\n if (ts.isClassDeclaration(node)) {\n const className = node.name?.text ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n node.members.forEach((member) => {\n if (ts.isMethodDeclaration(member) || ts.isPropertyDeclaration(member)) {\n const memberName = member.name && ts.isIdentifier(member.name) ? member.name.text : null;\n if (memberName) {\n const memberKind = ts.isMethodDeclaration(member) ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (ts.isMethodDeclaration(member) && member.body) {\n ts.forEachChild(member.body, (child) => visit(child, memberStack));\n } else if (ts.isPropertyDeclaration(member) && member.initializer) {\n visit(member.initializer, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (ts.isPropertyAssignment(node)) {\n const propName = getPropertyName(node.name);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.initializer, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n ts.forEachChild(node, (child) => visit(child, stack));\n };\n\n // Start traversal from top-level statements\n sourceFile.statements.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(sourceFile.fileName, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * TypeScript adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (ts.SourceFile) is released after analysis.\n */\nexport const typescriptAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const sourceFile = createSourceFile(input.filePath, input.source);\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlImports(sourceFile, helper);\n const imports = collectImports(sourceFile);\n const exports = collectExports(sourceFile);\n\n const { definitions } = collectAllDefinitions({\n sourceFile,\n identifiers: gqlIdentifiers,\n exports,\n });\n\n // Return results - sourceFile goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n };\n },\n};\n","/**\n * Core analyzer logic that orchestrates the analysis pipeline.\n * Adapters (TypeScript, SWC, etc.) implement the adapter interface to plug into this pipeline.\n */\n\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleExport, ModuleImport } from \"./types\";\n\n/**\n * Result of analyzing a module, containing all collected data.\n */\nexport type AnalyzerResult = {\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly definitions: readonly ModuleDefinition[];\n};\n\n/**\n * Adapter interface that each parser implementation (TS, SWC) must provide.\n * The analyze method parses and collects all data in one pass, allowing the AST\n * to be released immediately after analysis completes.\n */\nexport interface AnalyzerAdapter {\n /**\n * Parse source code into an AST, collect all required data, and return results.\n * The AST is kept within this function's scope and released after analysis.\n * This design enables early garbage collection of AST objects.\n */\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null;\n}\n\n/**\n * Core analyzer function that orchestrates the analysis pipeline.\n * Adapters implement the AnalyzerAdapter interface to provide parser-specific logic.\n */\nexport const analyzeModuleCore = (\n input: AnalyzeModuleInput,\n adapter: AnalyzerAdapter,\n graphqlHelper: GraphqlSystemIdentifyHelper,\n): ModuleAnalysis => {\n const hasher = getPortableHasher();\n const signature = hasher.hash(input.source, \"xxhash\");\n\n // Delegate all analysis to the adapter - AST is created and released within analyze()\n const result = adapter.analyze(input, graphqlHelper);\n\n if (!result) {\n return {\n filePath: input.filePath,\n signature,\n definitions: [],\n imports: [],\n exports: [],\n };\n }\n\n return {\n filePath: input.filePath,\n signature,\n definitions: result.definitions,\n imports: result.imports,\n exports: result.exports,\n };\n};\n","import { assertUnreachable } from \"../errors\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { BuilderAnalyzer } from \"../types\";\nimport { swcAdapter } from \"./adapters/swc\";\nimport { typescriptAdapter } from \"./adapters/typescript\";\nimport { analyzeModuleCore } from \"./core\";\nimport type { AnalyzeModuleInput, ModuleAnalysis } from \"./types\";\n\nexport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleExport, ModuleImport } from \"./types\";\n\nexport const createAstAnalyzer = ({\n analyzer,\n graphqlHelper,\n}: {\n readonly analyzer: BuilderAnalyzer;\n readonly graphqlHelper: GraphqlSystemIdentifyHelper;\n}) => {\n const analyze = (input: AnalyzeModuleInput): ModuleAnalysis => {\n if (analyzer === \"ts\") {\n return analyzeModuleCore(input, typescriptAdapter, graphqlHelper);\n }\n if (analyzer === \"swc\") {\n return analyzeModuleCore(input, swcAdapter, graphqlHelper);\n }\n return assertUnreachable(analyzer, \"createAstAnalyzer\");\n };\n\n return {\n type: analyzer,\n analyze,\n };\n};\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\ntype CacheNamespace = readonly string[];\n\nexport type CacheFactoryOptions = {\n readonly prefix?: CacheNamespace;\n readonly persistence?: {\n readonly enabled: boolean;\n readonly filePath: string;\n };\n};\n\nexport type CacheStoreOptions<_K extends string, V> = {\n readonly namespace: CacheNamespace;\n readonly schema: z.ZodType<V>;\n readonly version?: string;\n};\n\nexport type CacheStore<K extends string, V> = {\n load(key: K): V | null;\n store(key: K, value: V): void;\n delete(key: K): void;\n entries(): IterableIterator<[K, V]>;\n clear(): void;\n size(): number;\n};\n\nexport type CacheFactory = {\n createStore<K extends string, V>(options: CacheStoreOptions<K, V>): CacheStore<K, V>;\n clearAll(): void;\n save(): void;\n};\n\nconst sanitizeSegment = (segment: string): string => segment.replace(/[\\\\/]/g, \"_\");\n\nconst toNamespaceKey = (segments: CacheNamespace): string => segments.map(sanitizeSegment).join(\"/\");\n\nconst toEntryKey = (key: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(key, \"xxhash\");\n};\n\ntype Envelope<V> = {\n key: string;\n version: string;\n value: V;\n};\n\ntype PersistedData = {\n version: string;\n storage: Record<string, Array<[string, Envelope<unknown>]>>;\n};\n\nconst PERSISTENCE_VERSION = \"v1\";\n\nexport const createMemoryCache = ({ prefix = [], persistence }: CacheFactoryOptions = {}): CacheFactory => {\n // Global in-memory storage: Map<namespaceKey, Map<hashedKey, Envelope>>\n const storage = new Map<string, Map<string, Envelope<unknown>>>();\n\n // Load from disk if persistence is enabled (synchronous on startup)\n if (persistence?.enabled) {\n try {\n if (existsSync(persistence.filePath)) {\n const content = readFileSync(persistence.filePath, \"utf-8\");\n const data: PersistedData = JSON.parse(content);\n\n if (data.version === PERSISTENCE_VERSION && data.storage) {\n // Restore Map structure from persisted data\n for (const [namespaceKey, entries] of Object.entries(data.storage)) {\n const namespaceMap = new Map<string, Envelope<unknown>>();\n for (const [hashedKey, envelope] of entries) {\n namespaceMap.set(hashedKey, envelope);\n }\n storage.set(namespaceKey, namespaceMap);\n }\n }\n }\n } catch (error) {\n // Silently continue with empty cache on load failure\n console.warn(`[cache] Failed to load cache from ${persistence.filePath}:`, error);\n }\n }\n\n const getOrCreateNamespace = (namespaceKey: string): Map<string, Envelope<unknown>> => {\n let namespace = storage.get(namespaceKey);\n if (!namespace) {\n namespace = new Map();\n storage.set(namespaceKey, namespace);\n }\n return namespace;\n };\n\n return {\n createStore: <K extends string, V>({ namespace, schema, version = \"v1\" }: CacheStoreOptions<K, V>): CacheStore<K, V> => {\n const namespaceKey = toNamespaceKey([...prefix, ...namespace]);\n const envelopeSchema = z.object({\n key: z.string(),\n version: z.string(),\n value: schema,\n });\n\n const resolveEntryKey = (key: string) => toEntryKey(key);\n\n const validateEnvelope = (raw: Envelope<unknown>): Envelope<V> | null => {\n const parsed = envelopeSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n if (parsed.data.version !== version) {\n return null;\n }\n\n return parsed.data as Envelope<V>;\n };\n\n const load = (key: K): V | null => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return null;\n }\n\n const entryKey = resolveEntryKey(key);\n const raw = namespaceStore.get(entryKey);\n if (!raw) {\n return null;\n }\n\n const envelope = validateEnvelope(raw);\n if (!envelope || envelope.key !== key) {\n namespaceStore.delete(entryKey);\n return null;\n }\n\n return envelope.value;\n };\n\n const store = (key: K, value: V): void => {\n const namespaceStore = getOrCreateNamespace(namespaceKey);\n const entryKey = resolveEntryKey(key);\n\n const envelope: Envelope<V> = {\n key,\n version,\n value,\n };\n\n namespaceStore.set(entryKey, envelope as Envelope<unknown>);\n };\n\n const deleteEntry = (key: K): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n const entryKey = resolveEntryKey(key);\n namespaceStore.delete(entryKey);\n };\n\n function* iterateEntries(): IterableIterator<[K, V]> {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n for (const raw of namespaceStore.values()) {\n const envelope = validateEnvelope(raw);\n if (!envelope) {\n continue;\n }\n\n yield [envelope.key as K, envelope.value];\n }\n }\n\n const clear = (): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (namespaceStore) {\n namespaceStore.clear();\n }\n };\n\n const size = (): number => {\n let count = 0;\n for (const _ of iterateEntries()) {\n count += 1;\n }\n return count;\n };\n\n return {\n load,\n store,\n delete: deleteEntry,\n entries: iterateEntries,\n clear,\n size,\n };\n },\n\n clearAll: (): void => {\n storage.clear();\n },\n\n save: (): void => {\n if (!persistence?.enabled) {\n return;\n }\n\n try {\n // Convert Map structure to plain object for JSON serialization\n const serialized: Record<string, Array<[string, Envelope<unknown>]>> = {};\n for (const [namespaceKey, namespaceMap] of storage.entries()) {\n serialized[namespaceKey] = Array.from(namespaceMap.entries());\n }\n\n const data: PersistedData = {\n version: PERSISTENCE_VERSION,\n storage: serialized,\n };\n\n // Ensure directory exists\n const dir = dirname(persistence.filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Write to file synchronously\n writeFileSync(persistence.filePath, JSON.stringify(data), \"utf-8\");\n } catch (error) {\n console.warn(`[cache] Failed to save cache to ${persistence.filePath}:`, error);\n }\n },\n };\n};\n","import { normalizePath } from \"@soda-gql/common\";\nimport type { ZodSchema } from \"zod\";\nimport type { CacheFactory, CacheStore } from \"./memory-cache\";\n\nexport type EntityCacheOptions<V> = {\n readonly factory: CacheFactory;\n readonly namespace: readonly string[];\n readonly schema: ZodSchema<V>;\n readonly version: string;\n readonly keyNormalizer?: (key: string) => string;\n};\n\n/**\n * Abstract base class for entity caches.\n * Provides common caching functionality with signature-based eviction.\n */\nexport abstract class EntityCache<K extends string, V> {\n protected readonly cacheStore: CacheStore<K, V>;\n private readonly keyNormalizer: (key: string) => string;\n\n constructor(options: EntityCacheOptions<V>) {\n this.cacheStore = options.factory.createStore({\n namespace: [...options.namespace],\n schema: options.schema,\n version: options.version,\n });\n this.keyNormalizer = options.keyNormalizer ?? normalizePath;\n }\n\n /**\n * Normalize a key for consistent cache lookups.\n */\n protected normalizeKey(key: string): K {\n return this.keyNormalizer(key) as K;\n }\n\n /**\n * Load raw value from cache without signature validation.\n */\n protected loadRaw(key: K): V | null {\n return this.cacheStore.load(key);\n }\n\n /**\n * Store raw value to cache.\n */\n protected storeRaw(key: K, value: V): void {\n this.cacheStore.store(key, value);\n }\n\n /**\n * Delete an entry from the cache.\n */\n delete(key: string): void {\n const normalizedKey = this.normalizeKey(key);\n this.cacheStore.delete(normalizedKey);\n }\n\n /**\n * Get all cached entries.\n * Subclasses should override this to provide custom iteration.\n */\n protected *baseEntries(): IterableIterator<V> {\n for (const [, value] of this.cacheStore.entries()) {\n yield value;\n }\n }\n\n /**\n * Clear all entries from the cache.\n */\n clear(): void {\n this.cacheStore.clear();\n }\n\n /**\n * Get the number of entries in the cache.\n */\n size(): number {\n return this.cacheStore.size();\n }\n}\n","import { CanonicalIdSchema } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\nexport const ModuleDefinitionSchema = z.object({\n canonicalId: CanonicalIdSchema,\n astPath: z.string(),\n isTopLevel: z.boolean(),\n isExported: z.boolean(),\n exportBinding: z.string().optional(),\n expression: z.string(),\n});\n\nexport const ModuleImportSchema = z.object({\n source: z.string(),\n local: z.string(),\n kind: z.enum([\"named\", \"namespace\", \"default\"]),\n isTypeOnly: z.boolean(),\n});\n\nexport const ModuleExportSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"named\"),\n exported: z.string(),\n local: z.string(),\n source: z.undefined().optional(),\n isTypeOnly: z.boolean(),\n }),\n z.object({\n kind: z.literal(\"reexport\"),\n exported: z.string(),\n source: z.string(),\n local: z.string().optional(),\n isTypeOnly: z.boolean(),\n }),\n]);\n\nexport const ModuleAnalysisSchema = z.object({\n filePath: z.string(),\n signature: z.string(),\n definitions: z.array(ModuleDefinitionSchema).readonly(),\n imports: z.array(ModuleImportSchema).readonly(),\n exports: z.array(ModuleExportSchema).readonly(),\n});\n\nexport type ModuleAnalysis = z.infer<typeof ModuleAnalysisSchema>;\n","import { z } from \"zod\";\nimport { ModuleAnalysisSchema } from \"./cache\";\n\nconst FileFingerprintSchema = z.object({\n hash: z.string(),\n sizeBytes: z.number(),\n mtimeMs: z.number(),\n});\n\nexport const DiscoveredDependencySchema = z.object({\n specifier: z.string(),\n resolvedPath: z.string().nullable(),\n isExternal: z.boolean(),\n});\n\nexport const DiscoverySnapshotSchema = z.object({\n filePath: z.string(),\n normalizedFilePath: z.string(),\n signature: z.string(),\n fingerprint: FileFingerprintSchema,\n analyzer: z.string(),\n createdAtMs: z.number(),\n analysis: ModuleAnalysisSchema,\n dependencies: z.array(DiscoveredDependencySchema).readonly(),\n});\n","import { EntityCache } from \"../cache/entity-cache\";\nimport type { CacheFactory } from \"../cache/memory-cache\";\nimport { DiscoverySnapshotSchema } from \"../schemas/discovery\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\n// Bumped to v3 for DiscoverySnapshot schema change (added fingerprint and metadata fields)\nconst DISCOVERY_CACHE_VERSION = \"discovery-cache/v3\";\n\nexport type DiscoveryCacheOptions = {\n readonly factory: CacheFactory;\n readonly analyzer: string;\n readonly evaluatorId: string;\n readonly namespacePrefix?: readonly string[];\n readonly version?: string;\n};\n\nexport class JsonDiscoveryCache extends EntityCache<string, DiscoverySnapshot> implements DiscoveryCache {\n constructor(options: DiscoveryCacheOptions) {\n const namespace = [...(options.namespacePrefix ?? [\"discovery\"]), options.analyzer, options.evaluatorId];\n\n super({\n factory: options.factory,\n namespace,\n schema: DiscoverySnapshotSchema,\n version: options.version ?? DISCOVERY_CACHE_VERSION,\n });\n }\n\n load(filePath: string, expectedSignature: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n const snapshot = this.loadRaw(key);\n if (!snapshot) {\n return null;\n }\n\n if (snapshot.signature !== expectedSignature) {\n this.delete(filePath);\n return null;\n }\n\n return snapshot;\n }\n\n peek(filePath: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n return this.loadRaw(key);\n }\n\n store(snapshot: DiscoverySnapshot): void {\n const key = this.normalizeKey(snapshot.filePath);\n this.storeRaw(key, snapshot);\n }\n\n entries(): IterableIterator<DiscoverySnapshot> {\n return this.baseEntries();\n }\n}\n\nexport const createDiscoveryCache = (options: DiscoveryCacheOptions): DiscoveryCache => new JsonDiscoveryCache(options);\n","import { getPortableHasher, isExternalSpecifier, resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport type { DiscoveredDependency } from \"./types\";\n\n/**\n * Extract all unique dependencies (relative + external) from the analysis.\n * Resolves local specifiers immediately so discovery only traverses once.\n */\nexport const extractModuleDependencies = (analysis: ModuleAnalysis): readonly DiscoveredDependency[] => {\n const dependencies = new Map<string, DiscoveredDependency>();\n\n const addDependency = (specifier: string): void => {\n if (dependencies.has(specifier)) {\n return;\n }\n\n const isExternal = isExternalSpecifier(specifier);\n const resolvedPath = isExternal ? null : resolveRelativeImportWithExistenceCheck({ filePath: analysis.filePath, specifier });\n\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal,\n });\n };\n\n for (const imp of analysis.imports) {\n addDependency(imp.source);\n }\n\n for (const exp of analysis.exports) {\n if (exp.kind === \"reexport\") {\n addDependency(exp.source);\n }\n }\n\n return Array.from(dependencies.values());\n};\n\nexport const createSourceHash = (source: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(source, \"xxhash\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { XXHashAPI } from \"xxhash-wasm\";\n\n/**\n * File fingerprint containing hash, size, and modification time\n */\nexport type FileFingerprint = {\n /** xxHash hash of file contents */\n hash: string;\n /** File size in bytes */\n sizeBytes: number;\n /** Last modification time in milliseconds since epoch */\n mtimeMs: number;\n};\n\n/**\n * Fingerprint computation error types\n */\nexport type FingerprintError =\n | { code: \"FILE_NOT_FOUND\"; path: string; message: string }\n | { code: \"NOT_A_FILE\"; path: string; message: string }\n | { code: \"READ_ERROR\"; path: string; message: string };\n\n/**\n * In-memory fingerprint cache keyed by absolute path\n */\nconst fingerprintCache = new Map<string, FileFingerprint>();\n\n/**\n * Lazy-loaded xxhash instance\n */\nlet xxhashInstance: XXHashAPI | null = null;\n\n/**\n * Lazily load xxhash-wasm instance\n */\nasync function getXXHash(): Promise<XXHashAPI> {\n if (xxhashInstance === null) {\n const { default: xxhash } = await import(\"xxhash-wasm\");\n xxhashInstance = await xxhash();\n }\n return xxhashInstance;\n}\n\n/**\n * Compute file fingerprint with memoization.\n * Uses mtime to short-circuit re-hashing unchanged files.\n *\n * @param path - Absolute path to file\n * @returns Result containing FileFingerprint or FingerprintError\n */\nexport function computeFingerprint(path: string): Result<FileFingerprint, FingerprintError> {\n try {\n const stats = statSync(path);\n\n if (!stats.isFile()) {\n return err({\n code: \"NOT_A_FILE\",\n path,\n message: `Path is not a file: ${path}`,\n });\n }\n\n const mtimeMs = stats.mtimeMs;\n const cached = fingerprintCache.get(path);\n\n // Short-circuit if mtime unchanged\n if (cached && cached.mtimeMs === mtimeMs) {\n return ok(cached);\n }\n\n // Read and hash file contents\n const contents = readFileSync(path);\n const sizeBytes = stats.size;\n\n // Compute hash synchronously (xxhash-wasm will be loaded async first time)\n const hash = computeHashSync(contents);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes,\n mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return ok(fingerprint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return err({\n code: \"FILE_NOT_FOUND\",\n path,\n message: `File not found: ${path}`,\n });\n }\n\n return err({\n code: \"READ_ERROR\",\n path,\n message: `Failed to read file: ${error}`,\n });\n }\n}\n\n/**\n * Compute hash synchronously.\n * For first call, uses simple string hash as fallback.\n * Subsequent calls will use xxhash after async initialization.\n */\nfunction computeHashSync(contents: Buffer): string {\n // If xxhash is already loaded, use it\n if (xxhashInstance !== null) {\n const hash = xxhashInstance.h64Raw(new Uint8Array(contents));\n return hash.toString(16);\n }\n\n // First call: trigger async loading for next time\n void getXXHash();\n\n // Fallback: simple hash for first call only\n return simpleHash(contents);\n}\n\n/**\n * Simple hash function for initial calls before xxhash loads\n */\nfunction simpleHash(buffer: Buffer): string {\n let hash = 0;\n for (let i = 0; i < buffer.length; i++) {\n const byte = buffer[i];\n if (byte !== undefined) {\n hash = (hash << 5) - hash + byte;\n hash = hash & hash; // Convert to 32bit integer\n }\n }\n return hash.toString(16);\n}\n\n/**\n * Compute fingerprint from pre-read file content and stats.\n * This is used by the generator-based discoverer which already has the content.\n *\n * @param path - Absolute path to file (for caching)\n * @param stats - File stats (mtimeMs, size)\n * @param content - File content as string\n * @returns FileFingerprint\n */\nexport function computeFingerprintFromContent(\n path: string,\n stats: { readonly mtimeMs: number; readonly size: number },\n content: string,\n): FileFingerprint {\n // Check cache first by mtime\n const cached = fingerprintCache.get(path);\n if (cached && cached.mtimeMs === stats.mtimeMs) {\n return cached;\n }\n\n // Convert string to buffer for hashing\n const buffer = Buffer.from(content, \"utf-8\");\n const hash = computeHashSync(buffer);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes: stats.size,\n mtimeMs: stats.mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return fingerprint;\n}\n\n/**\n * Invalidate cached fingerprint for a specific path\n *\n * @param path - Absolute path to invalidate\n */\nexport function invalidateFingerprint(path: string): void {\n fingerprintCache.delete(path);\n}\n\n/**\n * Clear all cached fingerprints\n */\nexport function clearFingerprintCache(): void {\n fingerprintCache.clear();\n}\n","import { createAsyncScheduler, createSyncScheduler, type EffectGenerator, normalizePath } from \"@soda-gql/common\";\nimport { err, ok } from \"neverthrow\";\nimport type { createAstAnalyzer } from \"../ast\";\nimport { type BuilderResult, builderErrors } from \"../errors\";\nimport { type FileStats, OptionalFileReadEffect, OptionalFileStatEffect } from \"../scheduler\";\nimport { createSourceHash, extractModuleDependencies } from \"./common\";\nimport { computeFingerprintFromContent, invalidateFingerprint } from \"./fingerprint\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\nexport type DiscoverModulesOptions = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n /** Set of file paths explicitly invalidated (from BuilderChangeSet) */\n readonly incremental?: {\n readonly cache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly affectedFiles: Set<string>;\n };\n};\n\nexport type DiscoverModulesResult = {\n readonly snapshots: readonly DiscoverySnapshot[];\n readonly cacheHits: number;\n readonly cacheMisses: number;\n readonly cacheSkips: number;\n};\n\n/**\n * Generator-based module discovery that yields effects for file I/O.\n * This allows the discovery process to be executed with either sync or async schedulers.\n */\nexport function* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n incremental,\n}: DiscoverModulesOptions): EffectGenerator<DiscoverModulesResult> {\n const snapshots = new Map<string, DiscoverySnapshot>();\n const stack = [...entryPaths];\n const changedFiles = incremental?.changedFiles ?? new Set<string>();\n const removedFiles = incremental?.removedFiles ?? new Set<string>();\n const affectedFiles = incremental?.affectedFiles ?? new Set<string>();\n const invalidatedSet = new Set<string>([...changedFiles, ...removedFiles, ...affectedFiles]);\n let cacheHits = 0;\n let cacheMisses = 0;\n let cacheSkips = 0;\n\n if (incremental) {\n for (const filePath of removedFiles) {\n incremental.cache.delete(filePath);\n invalidateFingerprint(filePath);\n }\n }\n\n while (stack.length > 0) {\n const rawFilePath = stack.pop();\n if (!rawFilePath) {\n continue;\n }\n\n // Normalize path for consistent cache key matching\n const filePath = normalizePath(rawFilePath);\n\n if (snapshots.has(filePath)) {\n continue;\n }\n\n // Check if explicitly invalidated\n let shouldReadFile = true;\n if (invalidatedSet.has(filePath)) {\n invalidateFingerprint(filePath);\n cacheSkips++;\n // Fall through to re-read and re-parse\n } else if (incremental) {\n // Try fingerprint-based cache check (avoid reading file)\n const cached = incremental.cache.peek(filePath);\n\n if (cached) {\n // Fast path: check fingerprint without reading file content\n const stats = yield* new OptionalFileStatEffect(filePath).run();\n\n if (stats) {\n const mtimeMs = stats.mtimeMs;\n const sizeBytes = stats.size;\n\n // If fingerprint matches, reuse cached snapshot\n if (cached.fingerprint.mtimeMs === mtimeMs && cached.fingerprint.sizeBytes === sizeBytes) {\n snapshots.set(filePath, cached);\n cacheHits++;\n // Enqueue dependencies from cache\n for (const dep of cached.dependencies) {\n if (dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n shouldReadFile = false;\n }\n }\n // If stats is null (file deleted), fall through to read attempt\n }\n }\n\n if (!shouldReadFile) {\n continue;\n }\n\n // Read source and compute signature\n const source = yield* new OptionalFileReadEffect(filePath).run();\n\n if (source === null) {\n // Handle deleted files gracefully - they may be in cache but removed from disk\n incremental?.cache.delete(filePath);\n invalidateFingerprint(filePath);\n continue;\n }\n\n const signature = createSourceHash(source);\n\n // Parse module\n const analysis = astAnalyzer.analyze({ filePath, source });\n cacheMisses++;\n\n // Build dependency records (relative + external) in a single pass\n const dependencies = extractModuleDependencies(analysis);\n\n // Enqueue all resolved relative dependencies for traversal\n for (const dep of dependencies) {\n if (!dep.isExternal && dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n\n // Get stats for fingerprint (we may already have them from cache check)\n const stats = (yield* new OptionalFileStatEffect(filePath).run()) as FileStats;\n\n // Compute fingerprint from content (avoids re-reading the file)\n const fingerprint = computeFingerprintFromContent(filePath, stats, source);\n\n // Create snapshot\n const snapshot: DiscoverySnapshot = {\n filePath,\n normalizedFilePath: normalizePath(filePath),\n signature,\n fingerprint,\n analyzer: astAnalyzer.type,\n createdAtMs: Date.now(),\n analysis,\n dependencies,\n };\n\n snapshots.set(filePath, snapshot);\n\n // Store in cache\n if (incremental) {\n incremental.cache.store(snapshot);\n }\n }\n\n return {\n snapshots: Array.from(snapshots.values()),\n cacheHits,\n cacheMisses,\n cacheSkips,\n };\n}\n\n/**\n * Discover and analyze all modules starting from entry points.\n * Uses AST parsing instead of RegExp for reliable dependency extraction.\n * Supports caching with fingerprint-based invalidation to skip re-parsing unchanged files.\n *\n * This function uses the synchronous scheduler internally for backward compatibility.\n * For async execution with parallel file I/O, use discoverModulesGen with an async scheduler.\n */\nexport const discoverModules = (options: DiscoverModulesOptions): BuilderResult<DiscoverModulesResult> => {\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n\n/**\n * Asynchronous version of discoverModules.\n * Uses async scheduler for parallel file I/O operations.\n *\n * This is useful for large codebases where parallel file operations can improve performance.\n */\nexport const discoverModulesAsync = async (options: DiscoverModulesOptions): Promise<BuilderResult<DiscoverModulesResult>> => {\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n","/**\n * Cross-runtime glob pattern matching abstraction\n * Provides a unified interface for glob operations across Bun and Node.js\n */\n\nimport fg from \"fast-glob\";\n\n/**\n * Scan files matching a glob pattern from the given directory\n * @param pattern - Glob pattern (e.g., \"src/**\\/*.ts\")\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns Array of matched file paths (relative to cwd)\n */\nexport const scanGlob = (pattern: string, cwd: string = process.cwd()): readonly string[] => {\n // Runtime detection: prefer Bun's native Glob when available for better performance\n if (typeof Bun !== \"undefined\" && Bun.Glob) {\n const { Glob } = Bun;\n const glob = new Glob(pattern);\n return Array.from(glob.scanSync(cwd));\n }\n\n // Node.js fallback: use fast-glob for cross-platform compatibility\n return fg.sync(pattern, { cwd, dot: true, onlyFiles: true });\n};\n","import { existsSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { err, ok } from \"neverthrow\";\n\nimport type { BuilderError } from \"../types\";\nimport { scanGlob } from \"../utils/glob\";\n\nconst scanEntries = (pattern: string): readonly string[] => {\n return scanGlob(pattern, process.cwd());\n};\n\n/**\n * Resolve entry file paths from glob patterns or direct paths.\n * Used by the discovery system to find entry points for module traversal.\n * All paths are normalized to POSIX format for consistent cache key matching.\n * Uses Node.js normalize() + backslash replacement to match normalizePath from @soda-gql/common.\n */\nexport const resolveEntryPaths = (entries: readonly string[]) => {\n const resolvedPaths = entries.flatMap((entry) => {\n const absolute = resolve(entry);\n if (existsSync(absolute)) {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return [normalize(absolute).replace(/\\\\/g, \"/\")];\n }\n\n const matches = scanEntries(entry).map((match) => {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return normalize(resolve(match)).replace(/\\\\/g, \"/\");\n });\n return matches;\n });\n\n if (resolvedPaths.length === 0) {\n return err<readonly string[], BuilderError>({\n code: \"ENTRY_NOT_FOUND\",\n message: `No entry files matched ${entries.join(\", \")}`,\n entry: entries.join(\", \"),\n });\n }\n\n return ok<readonly string[], BuilderError>(resolvedPaths);\n};\n","import { statSync } from \"node:fs\";\nimport { normalizePath } from \"@soda-gql/common\";\nimport { ok, type Result } from \"neverthrow\";\n\n/**\n * File metadata tracked for change detection.\n */\nexport type FileMetadata = {\n /** Modification time in milliseconds */\n mtimeMs: number;\n /** File size in bytes */\n size: number;\n};\n\n/**\n * Result of scanning current file system state.\n */\nexport type FileScan = {\n /** Map of normalized file paths to current metadata */\n files: Map<string, FileMetadata>;\n};\n\n/**\n * Detected file changes between two states.\n */\nexport type FileDiff = {\n /** Files present in current but not in previous */\n added: Set<string>;\n /** Files present in both but with changed metadata */\n updated: Set<string>;\n /** Files present in previous but not in current */\n removed: Set<string>;\n};\n\n/**\n * Errors that can occur during file tracking operations.\n */\nexport type TrackerError = { type: \"scan-failed\"; path: string; message: string };\n\n/**\n * File tracker interface for detecting file changes across builds.\n */\nexport interface FileTracker {\n /**\n * Scan current file system state for the given paths.\n * Gracefully skips files that don't exist or cannot be read.\n */\n scan(extraPaths: readonly string[]): Result<FileScan, TrackerError>;\n\n /**\n * Detect changes between previous and current file states.\n */\n detectChanges(): FileDiff;\n\n /**\n * Update the in-memory tracker state.\n * State persists only for the lifetime of this process.\n */\n update(scan: FileScan): void;\n}\n\n/**\n * Create a file tracker that maintains in-memory state for change detection.\n *\n * The tracker keeps file metadata (mtime, size) in memory during the process lifetime\n * and detects which files have been added, updated, or removed. State is scoped to\n * the process and does not persist across restarts.\n */\nexport const createFileTracker = (): FileTracker => {\n // In-memory state that persists for the lifetime of this tracker instance\n let currentScan: FileScan = {\n files: new Map(),\n };\n let nextScan: FileScan | null = null;\n\n const scan = (extraPaths: readonly string[]): Result<FileScan, TrackerError> => {\n const allPathsToScan = new Set([...extraPaths, ...currentScan.files.keys()]);\n const files = new Map<string, FileMetadata>();\n\n for (const path of allPathsToScan) {\n try {\n const normalized = normalizePath(path);\n const stats = statSync(normalized);\n\n files.set(normalized, {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {}\n }\n\n nextScan = { files };\n return ok(nextScan);\n };\n\n const detectChanges = (): FileDiff => {\n const previous = currentScan;\n const current = nextScan ?? currentScan;\n const added = new Set<string>();\n const updated = new Set<string>();\n const removed = new Set<string>();\n\n // Check for added and updated files\n for (const [path, currentMetadata] of current.files) {\n const previousMetadata = previous.files.get(path);\n\n if (!previousMetadata) {\n added.add(path);\n } else if (previousMetadata.mtimeMs !== currentMetadata.mtimeMs || previousMetadata.size !== currentMetadata.size) {\n updated.add(path);\n }\n }\n\n // Check for removed files\n for (const path of previous.files.keys()) {\n if (!current.files.has(path)) {\n removed.add(path);\n }\n }\n\n return { added, updated, removed };\n };\n\n const update = (scan: FileScan): void => {\n // Update in-memory state - promote nextScan to currentScan\n currentScan = scan;\n nextScan = null;\n };\n\n return {\n scan,\n detectChanges,\n update,\n };\n};\n\n/**\n * Check if a file diff is empty (no changes detected).\n */\nexport const isEmptyDiff = (diff: FileDiff): boolean => {\n return diff.added.size === 0 && diff.updated.size === 0 && diff.removed.size === 0;\n};\n","import { isRelativeSpecifier, resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\n\nexport type DependencyGraphError = {\n readonly code: \"MISSING_IMPORT\";\n readonly chain: readonly [importingFile: string, importSpecifier: string];\n};\n\nexport const validateModuleDependencies = ({\n analyses,\n graphqlSystemHelper,\n}: {\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemHelper: GraphqlSystemIdentifyHelper;\n}): Result<null, DependencyGraphError> => {\n for (const analysis of analyses.values()) {\n for (const { source, isTypeOnly } of analysis.imports) {\n if (isTypeOnly) {\n continue;\n }\n\n // Only check relative imports (project modules)\n if (isRelativeSpecifier(source)) {\n // Skip graphql-system imports - they are not part of the analyzed modules\n if (graphqlSystemHelper.isGraphqlSystemImportSpecifier({ filePath: analysis.filePath, specifier: source })) {\n continue;\n }\n\n const resolvedModule = resolveRelativeImportWithReferences({\n filePath: analysis.filePath,\n specifier: source,\n references: analyses,\n });\n if (!resolvedModule) {\n // Import points to a module that doesn't exist in the analysis\n return err({\n code: \"MISSING_IMPORT\" as const,\n chain: [analysis.filePath, source] as const,\n });\n }\n }\n }\n }\n\n return ok(null);\n};\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { DiscoverySnapshot } from \"../discovery\";\n\n/**\n * Extract module-level adjacency from dependency graph.\n * Returns Map of file path -> set of files that import it.\n * All paths are normalized to POSIX format for consistent cache key matching.\n */\nexport const extractModuleAdjacency = ({\n snapshots,\n}: {\n snapshots: Map<string, DiscoverySnapshot>;\n}): Map<string, Set<string>> => {\n const importsByModule = new Map<string, Set<string>>();\n\n for (const snapshot of snapshots.values()) {\n const { normalizedFilePath, dependencies, analysis } = snapshot;\n const imports = new Set<string>();\n\n // Extract module paths from canonical IDs in dependencies\n for (const { resolvedPath } of dependencies) {\n if (resolvedPath && resolvedPath !== normalizedFilePath && snapshots.has(resolvedPath)) {\n imports.add(resolvedPath);\n }\n }\n\n // Phase 3: Handle runtime imports for modules with no tracked dependencies\n if (dependencies.length === 0 && analysis.imports.length > 0) {\n for (const imp of analysis.imports) {\n if (imp.isTypeOnly) {\n continue;\n }\n\n const resolved = resolveRelativeImportWithReferences({\n filePath: normalizedFilePath,\n specifier: imp.source,\n references: snapshots,\n });\n if (resolved) {\n imports.add(resolved);\n }\n }\n }\n\n if (imports.size > 0) {\n importsByModule.set(normalizedFilePath, imports);\n }\n }\n\n // Phase 4: Invert to adjacency map (imported -> [importers])\n const adjacency = new Map<string, Set<string>>();\n\n for (const [importer, imports] of importsByModule) {\n for (const imported of imports) {\n if (!adjacency.has(imported)) {\n adjacency.set(imported, new Set());\n }\n adjacency.get(imported)?.add(importer);\n }\n }\n\n // Include all modules, even isolated ones with no importers\n for (const modulePath of snapshots.keys()) {\n if (!adjacency.has(modulePath)) {\n adjacency.set(modulePath, new Set());\n }\n }\n\n return adjacency;\n};\n\n/**\n * Collect all modules affected by changes, including transitive dependents.\n * Uses BFS to traverse module adjacency graph.\n * All paths are already normalized from extractModuleAdjacency.\n */\nexport const collectAffectedFiles = (input: {\n changedFiles: Set<string>;\n removedFiles: Set<string>;\n previousModuleAdjacency: Map<string, Set<string>>;\n}): Set<string> => {\n const { changedFiles, removedFiles, previousModuleAdjacency } = input;\n const affected = new Set<string>([...changedFiles, ...removedFiles]);\n const queue = [...changedFiles];\n const visited = new Set<string>(changedFiles);\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break;\n\n const dependents = previousModuleAdjacency.get(current);\n\n if (dependents) {\n for (const dependent of dependents) {\n if (!visited.has(dependent)) {\n visited.add(dependent);\n affected.add(dependent);\n queue.push(dependent);\n }\n }\n }\n }\n\n return affected;\n};\n","import { join, resolve } from \"node:path\";\nimport { cachedFn, createAsyncScheduler, createSyncScheduler, type EffectGenerator, type SchedulerError } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { type BuilderArtifact, buildArtifact } from \"../artifact\";\nimport { createAstAnalyzer, type ModuleAnalysis } from \"../ast\";\nimport { createMemoryCache } from \"../cache/memory-cache\";\nimport {\n createDiscoveryCache,\n type DiscoveryCache,\n type DiscoverySnapshot,\n discoverModulesGen,\n type ModuleLoadStats,\n resolveEntryPaths,\n} from \"../discovery\";\nimport { builderErrors } from \"../errors\";\nimport {\n evaluateIntermediateModulesGen,\n generateIntermediateModules,\n type IntermediateArtifactElement,\n type IntermediateModule,\n} from \"../intermediate-module\";\nimport { createGraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport { createFileTracker, type FileDiff, type FileScan, isEmptyDiff } from \"../tracker\";\nimport type { BuilderError } from \"../types\";\nimport { validateModuleDependencies } from \"./dependency-validation\";\nimport { collectAffectedFiles, extractModuleAdjacency } from \"./module-adjacency\";\n\n/**\n * Session state maintained across incremental builds.\n */\ntype SessionState = {\n /** Generation number */\n gen: number;\n /** Discovery snapshots keyed by normalized file path */\n snapshots: Map<string, DiscoverySnapshot>;\n /** Module-level adjacency: file -> files that import it */\n moduleAdjacency: Map<string, Set<string>>;\n /** Written intermediate modules: filePath -> intermediate module */\n intermediateModules: Map<string, IntermediateModule>;\n /** Last successful artifact */\n lastArtifact: BuilderArtifact | null;\n};\n\n/**\n * Input for the unified build generator.\n */\ntype BuildGenInput = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n readonly discoveryCache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly previousModuleAdjacency: Map<string, Set<string>>;\n readonly previousIntermediateModules: ReadonlyMap<string, IntermediateModule>;\n readonly graphqlSystemPath: string;\n readonly graphqlHelper: ReturnType<typeof createGraphqlSystemIdentifyHelper>;\n};\n\n/**\n * Result from the unified build generator.\n */\ntype BuildGenResult = {\n readonly snapshots: Map<string, DiscoverySnapshot>;\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly currentModuleAdjacency: Map<string, Set<string>>;\n readonly intermediateModules: Map<string, IntermediateModule>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n readonly stats: ModuleLoadStats;\n};\n\n/**\n * Builder session interface for incremental builds.\n */\nexport interface BuilderSession {\n /**\n * Perform build fully or incrementally (synchronous).\n * The session automatically detects file changes using the file tracker.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n build(options?: { force?: boolean }): Result<BuilderArtifact, BuilderError>;\n /**\n * Perform build fully or incrementally (asynchronous).\n * The session automatically detects file changes using the file tracker.\n * Supports async metadata factories and parallel element evaluation.\n */\n buildAsync(options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>>;\n /**\n * Get the current generation number.\n */\n getGeneration(): number;\n /**\n * Get the current artifact.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n /**\n * Dispose the session and save cache to disk.\n */\n dispose(): void;\n}\n\n/**\n * Create a new builder session.\n *\n * The session maintains in-memory state across builds to enable incremental processing.\n */\nexport const createBuilderSession = (options: {\n readonly evaluatorId?: string;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n readonly config: ResolvedSodaGqlConfig;\n}): BuilderSession => {\n const config = options.config;\n const evaluatorId = options.evaluatorId ?? \"default\";\n const entrypoints: ReadonlySet<string> = new Set(options.entrypointsOverride ?? config.include);\n\n // Session state stored in closure\n const state: SessionState = {\n gen: 0,\n snapshots: new Map(),\n moduleAdjacency: new Map(),\n intermediateModules: new Map(),\n lastArtifact: null,\n };\n\n // Reusable infrastructure\n const cacheFactory = createMemoryCache({\n prefix: [\"builder\"],\n persistence: {\n enabled: true,\n filePath: join(process.cwd(), \".cache\", \"soda-gql\", \"builder\", \"cache.json\"),\n },\n });\n\n // Auto-save cache on process exit\n process.on(\"beforeExit\", () => {\n cacheFactory.save();\n });\n\n const graphqlHelper = createGraphqlSystemIdentifyHelper(config);\n const ensureAstAnalyzer = cachedFn(() =>\n createAstAnalyzer({\n analyzer: config.analyzer,\n graphqlHelper,\n }),\n );\n const ensureDiscoveryCache = cachedFn(() =>\n createDiscoveryCache({\n factory: cacheFactory,\n analyzer: config.analyzer,\n evaluatorId,\n }),\n );\n const ensureFileTracker = cachedFn(() => createFileTracker());\n\n /**\n * Prepare build input. Shared between sync and async builds.\n * Returns either a skip result or the input for buildGen.\n */\n const prepareBuildInput = (\n force: boolean,\n ): Result<\n { type: \"skip\"; artifact: BuilderArtifact } | { type: \"build\"; input: BuildGenInput; currentScan: FileScan },\n BuilderError\n > => {\n // 1. Resolve entry paths\n const entryPathsResult = resolveEntryPaths(Array.from(entrypoints));\n if (entryPathsResult.isErr()) {\n return err(entryPathsResult.error);\n }\n const entryPaths = entryPathsResult.value;\n\n // 2. Load tracker and detect changes\n const tracker = ensureFileTracker();\n const scanResult = tracker.scan(entryPaths);\n if (scanResult.isErr()) {\n const trackerError = scanResult.error;\n return err(\n builderErrors.discoveryIOError(\n trackerError.type === \"scan-failed\" ? trackerError.path : \"unknown\",\n `Failed to scan files: ${trackerError.message}`,\n ),\n );\n }\n\n // 3. Scan current files (entry paths + previously tracked files)\n const currentScan = scanResult.value;\n const diff = tracker.detectChanges();\n\n // 4. Prepare for build\n const prepareResult = prepare({\n diff,\n entryPaths,\n lastArtifact: state.lastArtifact,\n force,\n });\n if (prepareResult.isErr()) {\n return err(prepareResult.error);\n }\n\n if (prepareResult.value.type === \"should-skip\") {\n return ok({ type: \"skip\", artifact: prepareResult.value.data.artifact });\n }\n\n const { changedFiles, removedFiles } = prepareResult.value.data;\n\n return ok({\n type: \"build\",\n input: {\n entryPaths,\n astAnalyzer: ensureAstAnalyzer(),\n discoveryCache: ensureDiscoveryCache(),\n changedFiles,\n removedFiles,\n previousModuleAdjacency: state.moduleAdjacency,\n previousIntermediateModules: state.intermediateModules,\n graphqlSystemPath: resolve(config.outdir, \"index.ts\"),\n graphqlHelper,\n },\n currentScan,\n });\n };\n\n /**\n * Finalize build and update session state.\n */\n const finalizeBuild = (genResult: BuildGenResult, currentScan: FileScan): Result<BuilderArtifact, BuilderError> => {\n const { snapshots, analyses, currentModuleAdjacency, intermediateModules, elements, stats } = genResult;\n\n // Build artifact from all intermediate modules\n const artifactResult = buildArtifact({\n analyses,\n elements,\n stats,\n });\n\n if (artifactResult.isErr()) {\n return err(artifactResult.error);\n }\n\n // Update session state\n state.gen++;\n state.snapshots = snapshots;\n state.moduleAdjacency = currentModuleAdjacency;\n state.lastArtifact = artifactResult.value;\n state.intermediateModules = intermediateModules;\n\n // Persist tracker state (soft failure - don't block on cache write)\n ensureFileTracker().update(currentScan);\n\n return ok(artifactResult.value);\n };\n\n /**\n * Synchronous build using SyncScheduler.\n * Throws if any element requires async operations.\n */\n const build = (options?: { force?: boolean }): Result<BuilderArtifact, BuilderError> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createSyncScheduler();\n\n try {\n const result = scheduler.run(() => buildGen(input));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (error && typeof error === \"object\" && \"code\" in error) {\n return err(error as BuilderError);\n }\n throw error;\n }\n };\n\n /**\n * Asynchronous build using AsyncScheduler.\n * Supports async metadata factories and parallel element evaluation.\n */\n const buildAsync = async (options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createAsyncScheduler();\n\n try {\n const result = await scheduler.run(() => buildGen(input));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (error && typeof error === \"object\" && \"code\" in error) {\n return err(error as BuilderError);\n }\n throw error;\n }\n };\n\n return {\n build,\n buildAsync,\n getGeneration: () => state.gen,\n getCurrentArtifact: () => state.lastArtifact,\n dispose: () => {\n cacheFactory.save();\n },\n };\n};\n\nconst prepare = (input: {\n diff: FileDiff;\n entryPaths: readonly string[];\n lastArtifact: BuilderArtifact | null;\n force: boolean;\n}) => {\n const { diff, lastArtifact, force } = input;\n\n // Convert diff to sets for discovery\n const changedFiles = new Set<string>([...diff.added, ...diff.updated]);\n const removedFiles = diff.removed;\n\n // Skip build only if:\n // 1. Not forced\n // 2. No changes detected\n // 3. Previous artifact exists\n if (!force && isEmptyDiff(diff) && lastArtifact) {\n return ok({ type: \"should-skip\" as const, data: { artifact: lastArtifact } });\n }\n\n return ok({ type: \"should-build\" as const, data: { changedFiles, removedFiles } });\n};\n\n/**\n * Unified build generator that yields effects for file I/O and element evaluation.\n * This enables single scheduler control at the root level for both sync and async execution.\n */\nfunction* buildGen(input: BuildGenInput): EffectGenerator<BuildGenResult> {\n const {\n entryPaths,\n astAnalyzer,\n discoveryCache,\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n previousIntermediateModules,\n graphqlSystemPath,\n graphqlHelper,\n } = input;\n\n // Phase 1: Collect affected files\n const affectedFiles = collectAffectedFiles({\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n });\n\n // Phase 2: Discovery (yields file I/O effects)\n const discoveryResult = yield* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n incremental: {\n cache: discoveryCache,\n changedFiles,\n removedFiles,\n affectedFiles,\n },\n });\n\n const { cacheHits, cacheMisses, cacheSkips } = discoveryResult;\n\n const snapshots = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot]));\n const analyses = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot.analysis]));\n\n // Phase 3: Validate module dependencies (pure computation)\n const dependenciesValidationResult = validateModuleDependencies({ analyses, graphqlSystemHelper: graphqlHelper });\n if (dependenciesValidationResult.isErr()) {\n const error = dependenciesValidationResult.error;\n throw builderErrors.graphMissingImport(error.chain[0], error.chain[1]);\n }\n\n const currentModuleAdjacency = extractModuleAdjacency({ snapshots });\n\n const stats: ModuleLoadStats = {\n hits: cacheHits,\n misses: cacheMisses,\n skips: cacheSkips,\n };\n\n // Phase 4: Generate intermediate modules (pure computation)\n const intermediateModules = new Map(previousIntermediateModules);\n\n // Build target set: include affected files + any newly discovered files that haven't been built yet\n const targetFiles = new Set(affectedFiles);\n for (const filePath of analyses.keys()) {\n if (!previousIntermediateModules.has(filePath)) {\n targetFiles.add(filePath);\n }\n }\n // If no targets identified (e.g., first build with no changes), build everything\n if (targetFiles.size === 0) {\n for (const filePath of analyses.keys()) {\n targetFiles.add(filePath);\n }\n }\n\n // Remove deleted intermediate modules from next map immediately\n for (const targetFilePath of targetFiles) {\n intermediateModules.delete(targetFilePath);\n }\n\n // Build and write affected intermediate modules\n for (const intermediateModule of generateIntermediateModules({ analyses, targetFiles, graphqlSystemPath })) {\n intermediateModules.set(intermediateModule.filePath, intermediateModule);\n }\n\n // Phase 5: Evaluate intermediate modules (yields element evaluation effects)\n const elements = yield* evaluateIntermediateModulesGen({ intermediateModules, graphqlSystemPath, analyses });\n\n return {\n snapshots,\n analyses,\n currentModuleAdjacency,\n intermediateModules,\n elements,\n stats,\n };\n}\n\n/**\n * Convert scheduler error to builder error.\n * If the cause is already a BuilderError, return it directly to preserve error codes.\n */\nconst convertSchedulerError = (error: SchedulerError): BuilderError => {\n // If the cause is a BuilderError, return it directly\n if (error.cause && typeof error.cause === \"object\" && \"code\" in error.cause) {\n return error.cause as BuilderError;\n }\n return builderErrors.internalInvariant(error.message, \"scheduler\", error.cause);\n};\n","import type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport type { Result } from \"neverthrow\";\nimport type { BuilderArtifact } from \"./artifact/types\";\nimport { createBuilderSession } from \"./session\";\nimport type { BuilderError } from \"./types\";\n\n/**\n * Configuration for BuilderService.\n * Mirrors BuilderInput shape.\n */\nexport type BuilderServiceConfig = {\n readonly config: ResolvedSodaGqlConfig;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n};\n\n/**\n * Builder service interface providing artifact generation.\n */\nexport interface BuilderService {\n /**\n * Generate artifacts from configured entry points (synchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Throws if any element requires async operations (e.g., async metadata factory).\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Result containing BuilderArtifact on success or BuilderError on failure.\n */\n build(options?: { force?: boolean }): Result<BuilderArtifact, BuilderError>;\n\n /**\n * Generate artifacts from configured entry points (asynchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Supports async metadata factories and parallel element evaluation.\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Promise of Result containing BuilderArtifact on success or BuilderError on failure.\n */\n buildAsync(options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>>;\n\n /**\n * Get the current generation number of the artifact.\n * Increments on each successful build.\n * Returns 0 if no artifact has been built yet.\n */\n getGeneration(): number;\n\n /**\n * Get the most recent artifact without triggering a new build.\n * Returns null if no artifact has been built yet.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n\n /**\n * Dispose the service and save cache to disk.\n * Should be called when the service is no longer needed.\n */\n dispose(): void;\n}\n\n/**\n * Create a builder service instance with session support.\n *\n * The service maintains a long-lived session for incremental builds.\n * File changes are automatically detected using an internal file tracker.\n * First build() call initializes the session, subsequent calls perform\n * incremental builds based on detected file changes.\n *\n * Note: Empty entry arrays will produce ENTRY_NOT_FOUND errors at build time.\n *\n * @param config - Builder configuration including entry patterns, analyzer, mode, and optional debugDir\n * @returns BuilderService instance\n */\nexport const createBuilderService = ({ config, entrypointsOverride }: BuilderServiceConfig): BuilderService => {\n const session = createBuilderSession({ config, entrypointsOverride });\n\n return {\n build: (options) => session.build(options),\n buildAsync: (options) => session.buildAsync(options),\n getGeneration: () => session.getGeneration(),\n getCurrentArtifact: () => session.getCurrentArtifact(),\n dispose: () => session.dispose(),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,iBAAb,cAAoCA,yBAA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AO,MAAM,UAAU,YAAY,UAAU,MAAM,OAAO;AAC3E,SAAO,MAAM;;AAEf,QAAO,cAAc,kBAAkB,MAAM,SAAS,aAAa,MAAM,MAAM;;;;;;;;;;;;;;;;;;ACzXjF,MAAa,wBAAwB,EAAE,QAAQ,0BAAgE;CAC7G,MAAM,UAAU,qBAAqB;EAAE;EAAQ;EAAqB,CAAC;AAErE,QAAO;EACL,QAAQ,YAAY,QAAQ,MAAM,QAAQ;EAC1C,aAAa,YAAY,QAAQ,WAAW,QAAQ;EACpD,qBAAqB,QAAQ,eAAe;EAC5C,0BAA0B,QAAQ,oBAAoB;EACtD,eAAe,QAAQ,SAAS;EACjC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Effect","path: string","element: AcceptableArtifact","GqlElement","Effects","declarations: string[]","returnEntries: string[]","importLines: string[]","filePath","stack: EvaluationFrame[]","frame: EvaluationFrame | undefined","result","artifacts: Record<string, IntermediateArtifactElement>","Fragment","Operation","ParallelEffect","cachedGql: unknown","cachedModulePath: string | null","moduleExports: Record<string, unknown>","sandboxCore","sandboxRuntime","Script","ParallelEffect","z","canonicalToFilePath","metadata: BuilderArtifactElementMetadata","lines: string[]","collectImports","imports: ModuleImport[]","collectExports","exports: ModuleExport[]","exports","module","unwrapMethodChains","collectAllDefinitions","getPropertyName","pending: PendingDefinition[]","handledCalls: CallExpression[]","frame: ScopeFrame","exportBinding: string | undefined","swcAdapter: AnalyzerAdapter","ts","imports: ModuleImport[]","exports: ModuleExport[]","exports","pending: PendingDefinition[]","handledCalls: ts.CallExpression[]","frame: ScopeFrame","exportBinding: string | undefined","typescriptAdapter: AnalyzerAdapter","data: PersistedData","z","envelope: Envelope<V>","serialized: Record<string, Array<[string, Envelope<unknown>]>>","normalizePath","z","CanonicalIdSchema","z","xxhashInstance: XXHashAPI | null","fingerprint: FileFingerprint","stats","snapshot: DiscoverySnapshot","fg","currentScan: FileScan","nextScan: FileScan | null","scan","entrypoints: ReadonlySet<string>","state: SessionState","options","stats: ModuleLoadStats"],"sources":["../src/scheduler/effects.ts","../src/intermediate-module/codegen.ts","../src/intermediate-module/registry.ts","../src/intermediate-module/evaluation.ts","../src/internal/graphql-system.ts","../src/schemas/artifact.ts","../src/artifact/aggregate.ts","../src/artifact/issue-handler.ts","../src/artifact/builder.ts","../src/errors.ts","../src/ast/common/scope.ts","../src/ast/adapters/swc.ts","../src/ast/adapters/typescript.ts","../src/ast/core.ts","../src/ast/index.ts","../src/cache/memory-cache.ts","../src/cache/entity-cache.ts","../src/schemas/cache.ts","../src/schemas/discovery.ts","../src/discovery/cache.ts","../src/discovery/common.ts","../src/discovery/fingerprint.ts","../src/discovery/discoverer.ts","../src/utils/glob.ts","../src/discovery/entry-paths.ts","../src/tracker/file-tracker.ts","../src/session/dependency-validation.ts","../src/session/module-adjacency.ts","../src/session/builder-session.ts","../src/service.ts"],"sourcesContent":["import { readFileSync, statSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { Effect, Effects } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyOperation, GqlElement } from \"@soda-gql/core\";\n\ntype AcceptableArtifact = AnyFragment | AnyOperation;\n\n/**\n * File stats result type.\n */\nexport type FileStats = {\n readonly mtimeMs: number;\n readonly size: number;\n readonly isFile: boolean;\n};\n\n/**\n * File read effect - reads a file from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const content = yield* new FileReadEffect(\"/path/to/file\").run();\n */\nexport class FileReadEffect extends Effect<string> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string {\n return readFileSync(this.path, \"utf-8\");\n }\n\n protected _executeAsync(): Promise<string> {\n return readFile(this.path, \"utf-8\");\n }\n}\n\n/**\n * File stat effect - gets file stats from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const stats = yield* new FileStatEffect(\"/path/to/file\").run();\n */\nexport class FileStatEffect extends Effect<FileStats> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n\n protected async _executeAsync(): Promise<FileStats> {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n}\n\n/**\n * File read effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileReadEffect extends Effect<string | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string | null {\n try {\n return readFileSync(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<string | null> {\n try {\n return await readFile(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * File stat effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileStatEffect extends Effect<FileStats | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats | null {\n try {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<FileStats | null> {\n try {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * Element evaluation effect - evaluates a GqlElement using its generator.\n * Supports both sync and async schedulers, enabling parallel element evaluation\n * when using async scheduler.\n *\n * @example\n * yield* new ElementEvaluationEffect(element).run();\n */\nexport class ElementEvaluationEffect extends Effect<void> {\n constructor(readonly element: AcceptableArtifact) {\n super();\n }\n\n protected _executeSync(): void {\n // Run generator synchronously - throws if async operation is required\n const generator = GqlElement.createEvaluationGenerator(this.element);\n const result = generator.next();\n while (!result.done) {\n // If generator yields, it means async operation is needed\n throw new Error(\"Async operation required during sync element evaluation\");\n }\n }\n\n protected async _executeAsync(): Promise<void> {\n const generator = GqlElement.createEvaluationGenerator(this.element);\n let result = generator.next();\n while (!result.done) {\n // Yield value is a Promise<void>\n await result.value;\n result = generator.next();\n }\n }\n}\n\n/**\n * Builder effect constructors.\n * Extends the base Effects with file I/O operations and element evaluation.\n */\nexport const BuilderEffects = {\n ...Effects,\n\n /**\n * Create a file read effect.\n * @param path - The file path to read\n */\n readFile: (path: string): FileReadEffect => new FileReadEffect(path),\n\n /**\n * Create a file stat effect.\n * @param path - The file path to stat\n */\n stat: (path: string): FileStatEffect => new FileStatEffect(path),\n\n /**\n * Create an optional file read effect that returns null if file doesn't exist.\n * @param path - The file path to read\n */\n readFileOptional: (path: string): OptionalFileReadEffect => new OptionalFileReadEffect(path),\n\n /**\n * Create an optional file stat effect that returns null if file doesn't exist.\n * @param path - The file path to stat\n */\n statOptional: (path: string): OptionalFileStatEffect => new OptionalFileStatEffect(path),\n\n /**\n * Create an element evaluation effect.\n * @param element - The GqlElement to evaluate\n */\n evaluateElement: (element: AcceptableArtifact): ElementEvaluationEffect => new ElementEvaluationEffect(element),\n} as const;\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { ModuleAnalysis, ModuleDefinition, ModuleImport } from \"../ast\";\n\nconst formatFactory = (expression: string): string => {\n const trimmed = expression.trim();\n if (!trimmed.includes(\"\\n\")) {\n return trimmed;\n }\n\n const lines = trimmed.split(\"\\n\").map((line) => line.trimEnd());\n const indented = lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join(\"\\n\");\n\n return `(\\n ${indented}\\n )`;\n};\n\ntype TreeNode = {\n expression?: string; // Leaf node with actual expression\n canonicalId?: string; // Canonical ID for this node\n children: Map<string, TreeNode>; // Branch node with children\n};\n\nconst buildTree = (definitions: readonly ModuleDefinition[]): Map<string, TreeNode> => {\n const roots = new Map<string, TreeNode>();\n\n definitions.forEach((definition) => {\n const parts = definition.astPath.split(\".\");\n const expressionText = definition.expression.trim();\n\n if (parts.length === 1) {\n // Top-level export\n const rootName = parts[0];\n if (rootName) {\n roots.set(rootName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n } else {\n // Nested export\n const rootName = parts[0];\n if (!rootName) return;\n\n let root = roots.get(rootName);\n if (!root) {\n root = { children: new Map() };\n roots.set(rootName, root);\n }\n\n let current = root;\n for (let i = 1; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n\n let child = current.children.get(part);\n if (!child) {\n child = { children: new Map() };\n current.children.set(part, child);\n }\n current = child;\n }\n\n const leafName = parts[parts.length - 1];\n if (leafName) {\n current.children.set(leafName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n }\n });\n\n return roots;\n};\n\n/**\n * Check if a string is a valid JavaScript identifier\n */\nconst isValidIdentifier = (name: string): boolean => {\n // JavaScript identifier regex: starts with letter, _, or $, followed by letters, digits, _, or $\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) && !isReservedWord(name);\n};\n\n/**\n * Check if a string is a JavaScript reserved word\n */\nconst isReservedWord = (name: string): boolean => {\n const reserved = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"export\",\n \"extends\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n \"let\",\n \"static\",\n \"enum\",\n \"await\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n ]);\n return reserved.has(name);\n};\n\n/**\n * Format a key for use in an object literal\n * Invalid identifiers are quoted, valid ones are not\n */\nconst formatObjectKey = (key: string): string => {\n return isValidIdentifier(key) ? key : `\"${key}\"`;\n};\n\nconst renderTreeNode = (node: TreeNode, indent: number): string => {\n if (node.expression && node.children.size === 0 && node.canonicalId) {\n // Leaf node - use addBuilder\n const expr = formatFactory(node.expression);\n return `registry.addElement(\"${node.canonicalId}\", () => ${expr})`;\n }\n\n // Branch node - render nested object\n const indentStr = \" \".repeat(indent);\n const entries = Array.from(node.children.entries()).map(([key, child]) => {\n const value = renderTreeNode(child, indent + 1);\n const formattedKey = formatObjectKey(key);\n return `${indentStr} ${formattedKey}: ${value},`;\n });\n\n if (entries.length === 0) {\n return \"{}\";\n }\n\n return `{\\n${entries.join(\"\\n\")}\\n${indentStr}}`;\n};\n\nconst buildNestedObject = (definition: readonly ModuleDefinition[]): string => {\n const tree = buildTree(definition);\n const declarations: string[] = [];\n const returnEntries: string[] = [];\n\n tree.forEach((node, rootName) => {\n if (node.children.size > 0) {\n // Has children - create a const declaration\n const objectLiteral = renderTreeNode(node, 2);\n declarations.push(` const ${rootName} = ${objectLiteral};`);\n returnEntries.push(rootName);\n } else if (node.expression && node.canonicalId) {\n // Single export - use addElement\n const expr = formatFactory(node.expression);\n declarations.push(` const ${rootName} = registry.addElement(\"${node.canonicalId}\", () => ${expr});`);\n returnEntries.push(rootName);\n }\n });\n\n const returnStatement =\n returnEntries.length > 0\n ? ` return {\\n${returnEntries.map((name) => ` ${name},`).join(\"\\n\")}\\n };`\n : \" return {};\";\n\n if (declarations.length === 0) {\n return returnStatement;\n }\n\n return `${declarations.join(\"\\n\")}\\n${returnStatement}`;\n};\n\n/**\n * Render import statements for the intermediate module using ModuleSummary.\n * Only includes imports from modules that have gql exports.\n */\nconst renderImportStatements = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): { imports: string; importedRootNames: Set<string>; namespaceImports: Set<string> } => {\n const importLines: string[] = [];\n const importedRootNames = new Set<string>();\n const namespaceImports = new Set<string>();\n\n // Group imports by resolved file path\n const importsByFile = new Map<string, ModuleImport[]>();\n\n analysis.imports.forEach((imp) => {\n if (imp.isTypeOnly) {\n return;\n }\n\n // Skip non-relative imports (external packages)\n if (!imp.source.startsWith(\".\")) {\n return;\n }\n\n const resolvedPath = resolveRelativeImportWithReferences({ filePath, specifier: imp.source, references: analyses });\n if (!resolvedPath) {\n return;\n }\n\n // Skip graphql-system imports - gql is provided via VM context\n if (resolvedPath === graphqlSystemPath) {\n return;\n }\n\n const imports = importsByFile.get(resolvedPath) ?? [];\n imports.push(imp);\n importsByFile.set(resolvedPath, imports);\n });\n\n // Render registry.importModule() for each file\n importsByFile.forEach((imports, filePath) => {\n // Check if this is a namespace import\n const namespaceImport = imports.find((imp) => imp.kind === \"namespace\");\n\n if (namespaceImport) {\n // Namespace import: const foo = yield registry.requestImport(\"path\");\n importLines.push(` const ${namespaceImport.local} = yield registry.requestImport(\"${filePath}\");`);\n namespaceImports.add(namespaceImport.local);\n importedRootNames.add(namespaceImport.local);\n } else {\n // Named imports: const { a, b } = yield registry.requestImport(\"path\");\n const rootNames = new Set<string>();\n\n imports.forEach((imp) => {\n if (imp.kind === \"named\" || imp.kind === \"default\") {\n rootNames.add(imp.local);\n importedRootNames.add(imp.local);\n }\n });\n\n if (rootNames.size > 0) {\n const destructured = Array.from(rootNames).sort().join(\", \");\n importLines.push(` const { ${destructured} } = yield registry.requestImport(\"${filePath}\");`);\n }\n }\n });\n\n return {\n imports: importLines.length > 0 ? `${importLines.join(\"\\n\")}` : \"\",\n importedRootNames,\n namespaceImports,\n };\n};\n\nexport const renderRegistryBlock = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): string => {\n const { imports } = renderImportStatements({ filePath, analysis, analyses, graphqlSystemPath });\n\n return [`registry.setModule(\"${filePath}\", function*() {`, imports, \"\", buildNestedObject(analysis.definitions), \"});\"].join(\n \"\\n\",\n );\n};\n","import { createAsyncScheduler, createSyncScheduler, type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyOperation, Fragment, GqlElement, Operation } from \"@soda-gql/core\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport type { EvaluationRequest, IntermediateArtifactElement } from \"./types\";\n\nexport type IntermediateRegistry = ReturnType<typeof createIntermediateRegistry>;\n\ntype AcceptableArtifact = AnyFragment | AnyOperation;\ntype ArtifactModule = ArtifactRecord;\ntype ArtifactRecord = {\n readonly [key: string]: AcceptableArtifact | ArtifactRecord;\n};\n\n/**\n * Generator factory type for module evaluation.\n * The generator yields EvaluationRequest when it needs to import a dependency,\n * receives the resolved module as the yield result, and returns the final ArtifactModule.\n */\ntype GeneratorFactory = () => Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n\n/**\n * Internal frame type for the evaluation stack.\n */\ntype EvaluationFrame = {\n readonly filePath: string;\n readonly generator: Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n resolvedDependency?: ArtifactModule;\n};\n\nexport const createIntermediateRegistry = ({ analyses }: { analyses?: Map<string, ModuleAnalysis> } = {}) => {\n const modules = new Map<string, GeneratorFactory>();\n const elements = new Map<string, AcceptableArtifact>();\n\n const setModule = (filePath: string, factory: GeneratorFactory) => {\n modules.set(filePath, factory);\n };\n\n /**\n * Creates an import request to be yielded by module generators.\n * Usage: `const { foo } = yield registry.requestImport(\"/path/to/module\");`\n */\n const requestImport = (filePath: string): EvaluationRequest => ({\n kind: \"import\",\n filePath,\n });\n\n const addElement = <TArtifact extends AcceptableArtifact>(canonicalId: string, factory: () => TArtifact) => {\n const builder = factory();\n GqlElement.setContext(builder, { canonicalId });\n // Don't evaluate yet - defer until all builders are registered\n elements.set(canonicalId, builder);\n return builder;\n };\n\n /**\n * Evaluate a single module and its dependencies using trampoline.\n * Returns the cached result or evaluates and caches if not yet evaluated.\n */\n const evaluateModule = (filePath: string, evaluated: Map<string, ArtifactModule>, inProgress: Set<string>): ArtifactModule => {\n // Already evaluated - return cached\n const cached = evaluated.get(filePath);\n if (cached) {\n return cached;\n }\n\n const stack: EvaluationFrame[] = [];\n\n // Start with the requested module\n const factory = modules.get(filePath);\n if (!factory) {\n throw new Error(`Module not found or yet to be registered: ${filePath}`);\n }\n stack.push({ filePath, generator: factory() });\n\n // Trampoline loop - process generators without deep recursion\n let frame: EvaluationFrame | undefined;\n while ((frame = stack[stack.length - 1])) {\n // Mark as in progress (for circular dependency detection)\n inProgress.add(frame.filePath);\n\n // Advance the generator\n const result =\n frame.resolvedDependency !== undefined ? frame.generator.next(frame.resolvedDependency) : frame.generator.next();\n\n // Clear the resolved dependency after use\n frame.resolvedDependency = undefined;\n\n if (result.done) {\n // Generator completed - cache result and pop frame\n evaluated.set(frame.filePath, result.value);\n inProgress.delete(frame.filePath);\n stack.pop();\n\n // If there's a parent frame waiting for this result, provide it\n const parentFrame = stack[stack.length - 1];\n if (parentFrame) {\n parentFrame.resolvedDependency = result.value;\n }\n } else {\n // Generator yielded - it needs a dependency\n const request = result.value;\n\n if (request.kind === \"import\") {\n const depPath = request.filePath;\n\n // Check if already evaluated (cached)\n const depCached = evaluated.get(depPath);\n if (depCached) {\n // Provide cached result without pushing new frame\n frame.resolvedDependency = depCached;\n } else {\n // Check for circular dependency\n if (inProgress.has(depPath)) {\n // If analyses is available, check if both modules have gql definitions\n // Only throw if both import source and target have gql definitions\n if (analyses) {\n const currentAnalysis = analyses.get(frame.filePath);\n const targetAnalysis = analyses.get(depPath);\n const currentHasGql = currentAnalysis && currentAnalysis.definitions.length > 0;\n const targetHasGql = targetAnalysis && targetAnalysis.definitions.length > 0;\n\n if (!currentHasGql || !targetHasGql) {\n // One or both modules have no gql definitions - allow circular import\n frame.resolvedDependency = {};\n continue;\n }\n }\n throw new Error(`Circular dependency detected: ${depPath}`);\n }\n\n // Need to evaluate dependency first\n const depFactory = modules.get(depPath);\n if (!depFactory) {\n throw new Error(`Module not found or yet to be registered: ${depPath}`);\n }\n\n // Push new frame for dependency\n stack.push({\n filePath: depPath,\n generator: depFactory(),\n });\n }\n }\n }\n }\n\n const result = evaluated.get(filePath);\n if (!result) {\n throw new Error(`Module evaluation failed: ${filePath}`);\n }\n return result;\n };\n\n /**\n * Build artifacts record from evaluated elements.\n */\n const buildArtifacts = (): Record<string, IntermediateArtifactElement> => {\n const artifacts: Record<string, IntermediateArtifactElement> = {};\n for (const [canonicalId, element] of elements.entries()) {\n if (element instanceof Fragment) {\n artifacts[canonicalId] = { type: \"fragment\", element };\n } else if (element instanceof Operation) {\n artifacts[canonicalId] = { type: \"operation\", element };\n }\n }\n return artifacts;\n };\n\n /**\n * Generator that evaluates all elements using the effect system.\n * Uses ParallelEffect to enable parallel evaluation in async mode.\n * In sync mode, ParallelEffect executes effects sequentially.\n */\n function* evaluateElementsGen(): EffectGenerator<void> {\n const effects = Array.from(elements.values(), (element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n }\n\n /**\n * Synchronous evaluation - evaluates all modules and elements synchronously.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n const evaluate = (): Record<string, IntermediateArtifactElement> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (each evaluation handles its own dependencies)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using sync scheduler\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw new Error(`Element evaluation failed: ${result.error.message}`);\n }\n\n return buildArtifacts();\n };\n\n /**\n * Asynchronous evaluation - evaluates all modules and elements with async support.\n * Supports async metadata factories and other async operations.\n */\n const evaluateAsync = async (): Promise<Record<string, IntermediateArtifactElement>> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (module evaluation is synchronous - no I/O operations)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using async scheduler\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw new Error(`Element evaluation failed: ${result.error.message}`);\n }\n\n return buildArtifacts();\n };\n\n /**\n * Evaluate all modules synchronously using trampoline.\n * This runs the module dependency resolution without element evaluation.\n * Call this before getElements() when using external scheduler control.\n */\n const evaluateModules = (): void => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n };\n\n /**\n * Get all registered elements for external effect creation.\n * Call evaluateModules() first to ensure all modules have been evaluated.\n */\n const getElements = (): AcceptableArtifact[] => {\n return Array.from(elements.values());\n };\n\n const clear = () => {\n modules.clear();\n elements.clear();\n };\n\n return {\n setModule,\n requestImport,\n addElement,\n evaluate,\n evaluateAsync,\n evaluateModules,\n getElements,\n buildArtifacts,\n clear,\n };\n};\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { extname, resolve } from \"node:path\";\nimport { createContext, Script } from \"node:vm\";\nimport { type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport * as sandboxCore from \"@soda-gql/core\";\nimport * as sandboxRuntime from \"@soda-gql/runtime\";\nimport { transformSync } from \"@swc/core\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { BuilderError } from \"../errors\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport { renderRegistryBlock } from \"./codegen\";\nimport { createIntermediateRegistry } from \"./registry\";\nimport type { IntermediateArtifactElement, IntermediateModule } from \"./types\";\n\nexport type BuildIntermediateModulesInput = {\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly targetFiles: Set<string>;\n readonly graphqlSystemPath: string;\n};\n\nconst transpile = ({ filePath, sourceCode }: { filePath: string; sourceCode: string }): Result<string, BuilderError> => {\n try {\n const result = transformSync(sourceCode, {\n filename: `${filePath}.ts`,\n jsc: {\n parser: {\n syntax: \"typescript\",\n tsx: false,\n },\n target: \"es2022\",\n },\n module: {\n type: \"es6\",\n },\n sourceMaps: false,\n minify: false,\n });\n\n return ok(result.code);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return err({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: filePath,\n astPath: \"\",\n message: `SWC transpilation failed: ${message}`,\n });\n }\n};\n\n/**\n * Resolve graphql system path to the bundled CJS file.\n * Accepts both .ts (for backward compatibility) and .cjs paths.\n * Maps .ts to sibling .cjs file if it exists.\n */\nfunction resolveGraphqlSystemPath(configPath: string): string {\n const ext = extname(configPath);\n\n // If already pointing to .cjs, use as-is\n if (ext === \".cjs\") {\n return resolve(process.cwd(), configPath);\n }\n\n // If pointing to .ts, try to resolve to sibling .cjs\n if (ext === \".ts\") {\n const basePath = configPath.slice(0, -3); // Remove .ts\n const cjsPath = `${basePath}.cjs`;\n const resolvedCjsPath = resolve(process.cwd(), cjsPath);\n\n // Check if .cjs exists, otherwise fall back to .ts (for error messages)\n if (existsSync(resolvedCjsPath)) {\n return resolvedCjsPath;\n }\n\n // Fall back to .ts path (will fail later with clearer error)\n return resolve(process.cwd(), configPath);\n }\n\n // For other extensions or no extension, use as-is\n return resolve(process.cwd(), configPath);\n}\n\n/**\n * Bundle and execute GraphQL system module using rspack + memfs.\n * Creates a self-contained bundle that can run in VM context.\n * This is cached per session to avoid re-bundling.\n */\nlet cachedGql: unknown = null;\nlet cachedModulePath: string | null = null;\n\n/**\n * Clear the cached gql module.\n * Call this between test runs to ensure clean state.\n * @internal - exported for testing purposes only\n */\nexport const __clearGqlCache = (): void => {\n cachedGql = null;\n cachedModulePath = null;\n};\n\nfunction executeGraphqlSystemModule(modulePath: string): { gql: unknown } {\n // Use cached module if same path\n if (cachedModulePath === modulePath && cachedGql !== null) {\n return { gql: cachedGql };\n }\n\n // Bundle the GraphQL system module\n const bundledCode = readFileSync(modulePath, \"utf-8\");\n\n // Create a shared CommonJS module exports object\n const moduleExports: Record<string, unknown> = {};\n\n // Create sandbox with proper CommonJS emulation\n const sandbox = {\n // Provide @soda-gql packages through require()\n require: (path: string) => {\n if (path === \"@soda-gql/core\") {\n return sandboxCore;\n }\n if (path === \"@soda-gql/runtime\") {\n return sandboxRuntime;\n }\n throw new Error(`Unknown module: ${path}`);\n },\n // Both module.exports and exports point to the same object\n module: { exports: moduleExports },\n exports: moduleExports,\n __dirname: resolve(modulePath, \"..\"),\n __filename: modulePath,\n global: undefined as unknown,\n globalThis: undefined as unknown,\n };\n // Wire global and globalThis to the sandbox itself\n sandbox.global = sandbox;\n sandbox.globalThis = sandbox;\n\n new Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);\n\n // Read exported gql (handle both direct export and default export)\n // Note: We read from sandbox.module.exports because esbuild CJS output\n // reassigns module.exports = __toCommonJS(...), replacing the original object\n const finalExports = sandbox.module.exports as Record<string, unknown>;\n const exportedGql = finalExports.gql ?? finalExports.default;\n\n if (exportedGql === undefined) {\n throw new Error(`No 'gql' export found in GraphQL system module: ${modulePath}`);\n }\n\n // Cache the result\n cachedGql = exportedGql;\n cachedModulePath = modulePath;\n\n return { gql: cachedGql };\n}\n\n/**\n * Build intermediate modules from dependency graph.\n * Each intermediate module corresponds to one source file.\n */\nexport const generateIntermediateModules = function* ({\n analyses,\n targetFiles,\n graphqlSystemPath,\n}: BuildIntermediateModulesInput): Generator<IntermediateModule, void, undefined> {\n for (const filePath of targetFiles) {\n const analysis = analyses.get(filePath);\n if (!analysis) {\n continue;\n }\n\n // Generate source code for this intermediate module\n const sourceCode = renderRegistryBlock({ filePath, analysis, analyses, graphqlSystemPath });\n\n // Debug: log the generated source code\n if (process.env.DEBUG_INTERMEDIATE_MODULE) {\n console.log(\"=== Intermediate module source ===\");\n console.log(\"FilePath:\", filePath);\n console.log(\n \"Definitions:\",\n analysis.definitions.map((d) => d.astPath),\n );\n console.log(\"Source code:\\n\", sourceCode);\n console.log(\"=================================\");\n }\n\n // Transpile TypeScript to JavaScript using SWC\n const transpiledCodeResult = transpile({ filePath, sourceCode });\n if (transpiledCodeResult.isErr()) {\n // error\n continue;\n }\n const transpiledCode = transpiledCodeResult.value;\n\n const script = new Script(transpiledCode);\n\n const hash = createHash(\"sha1\");\n hash.update(transpiledCode);\n const contentHash = hash.digest(\"hex\");\n const canonicalIds = analysis.definitions.map((definition) => definition.canonicalId);\n\n yield {\n filePath,\n canonicalIds,\n sourceCode,\n transpiledCode,\n contentHash,\n script,\n };\n }\n};\n\nexport type EvaluateIntermediateModulesInput = {\n intermediateModules: Map<string, IntermediateModule>;\n graphqlSystemPath: string;\n analyses: Map<string, ModuleAnalysis>;\n};\n\n/**\n * Set up VM context and run intermediate module scripts.\n * Returns the registry for evaluation.\n */\nconst setupIntermediateModulesContext = ({\n intermediateModules,\n graphqlSystemPath,\n analyses,\n}: EvaluateIntermediateModulesInput) => {\n const registry = createIntermediateRegistry({ analyses });\n const gqlImportPath = resolveGraphqlSystemPath(graphqlSystemPath);\n\n const { gql } = executeGraphqlSystemModule(gqlImportPath);\n\n const vmContext = createContext({ gql, registry });\n\n for (const { script, filePath } of intermediateModules.values()) {\n try {\n script.runInContext(vmContext);\n } catch (error) {\n console.error(`Error evaluating intermediate module ${filePath}:`, error);\n throw error;\n }\n }\n\n return registry;\n};\n\n/**\n * Synchronous evaluation of intermediate modules.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\nexport const evaluateIntermediateModules = (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = registry.evaluate();\n registry.clear();\n return elements;\n};\n\n/**\n * Asynchronous evaluation of intermediate modules.\n * Supports async metadata factories and other async operations.\n */\nexport const evaluateIntermediateModulesAsync = async (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = await registry.evaluateAsync();\n registry.clear();\n return elements;\n};\n\n/**\n * Generator version of evaluateIntermediateModules for external scheduler control.\n * Yields effects for element evaluation, enabling unified scheduler at the root level.\n *\n * This function:\n * 1. Sets up the VM context and runs intermediate module scripts\n * 2. Runs synchronous module evaluation (trampoline - no I/O)\n * 3. Yields element evaluation effects via ParallelEffect\n * 4. Returns the artifacts record\n */\nexport function* evaluateIntermediateModulesGen(\n input: EvaluateIntermediateModulesInput,\n): EffectGenerator<Record<string, IntermediateArtifactElement>> {\n const registry = setupIntermediateModulesContext(input);\n\n // Run synchronous module evaluation (trampoline pattern, no I/O)\n registry.evaluateModules();\n\n // Yield element evaluation effects\n const elements = registry.getElements();\n const effects = elements.map((element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n\n const artifacts = registry.buildArtifacts();\n registry.clear();\n return artifacts;\n}\n","/**\n * Helper for identifying graphql-system files and import specifiers.\n * Provides robust detection across symlinks, case-insensitive filesystems, and user-defined aliases.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\n\nexport type GraphqlSystemIdentifyHelper = {\n readonly isGraphqlSystemFile: (input: { filePath: string }) => boolean;\n readonly isGraphqlSystemImportSpecifier: (input: { filePath: string; specifier: string }) => boolean;\n};\n\n/**\n * Create a canonical file name getter based on platform.\n * On case-sensitive filesystems, paths are returned as-is.\n * On case-insensitive filesystems, paths are lowercased for comparison.\n */\nconst createGetCanonicalFileName = (useCaseSensitiveFileNames: boolean): ((path: string) => string) => {\n return useCaseSensitiveFileNames ? (path: string) => path : (path: string) => path.toLowerCase();\n};\n\n/**\n * Detect if the filesystem is case-sensitive.\n * We assume Unix-like systems are case-sensitive, and Windows is not.\n */\nconst getUseCaseSensitiveFileNames = (): boolean => {\n return process.platform !== \"win32\";\n};\n\n/**\n * Create a GraphqlSystemIdentifyHelper from the resolved config.\n * Uses canonical path comparison to handle casing, symlinks, and aliases.\n */\nexport const createGraphqlSystemIdentifyHelper = (config: ResolvedSodaGqlConfig): GraphqlSystemIdentifyHelper => {\n const getCanonicalFileName = createGetCanonicalFileName(getUseCaseSensitiveFileNames());\n\n const toCanonical = (file: string): string => {\n const resolved = resolve(file);\n // Use realpathSync to resolve symlinks for accurate comparison\n try {\n return getCanonicalFileName(realpathSync(resolved));\n } catch {\n // If realpath fails (file doesn't exist yet), fall back to resolved path\n return getCanonicalFileName(resolved);\n }\n };\n\n // Derive graphql system path from outdir (assume index.ts as default entry)\n const graphqlSystemPath = resolve(config.outdir, \"index.ts\");\n const canonicalGraphqlSystemPath = toCanonical(graphqlSystemPath);\n\n // Build canonical alias map\n const canonicalAliases = new Set(config.graphqlSystemAliases.map((alias) => alias));\n\n return {\n isGraphqlSystemFile: ({ filePath }: { filePath: string }) => {\n return toCanonical(filePath) === canonicalGraphqlSystemPath;\n },\n isGraphqlSystemImportSpecifier: ({ filePath, specifier }: { filePath: string; specifier: string }) => {\n // Check against aliases first if configured\n if (canonicalAliases.has(specifier)) {\n return true;\n }\n\n // Only try to resolve relative imports (starting with . or ..)\n // External specifiers without an alias configured should not match\n if (!specifier.startsWith(\".\")) {\n return false;\n }\n\n // Try to resolve as relative import\n const resolved = resolveRelativeImportWithExistenceCheck({ filePath, specifier });\n if (!resolved) {\n return false;\n }\n\n return toCanonical(resolved) === canonicalGraphqlSystemPath;\n },\n };\n};\n","import type { CanonicalId } from \"@soda-gql/common\";\nimport { z } from \"zod\";\nimport type { BuilderArtifactFragment, BuilderArtifactOperation } from \"../artifact/types\";\n\nconst BuilderArtifactElementMetadataSchema = z.object({\n sourcePath: z.string(),\n contentHash: z.string(),\n});\n\nconst BuilderArtifactOperationSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"operation\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n operationType: z.enum([\"query\", \"mutation\", \"subscription\"]),\n operationName: z.string(),\n document: z.unknown(), // DocumentNode object\n variableNames: z.array(z.string()),\n }),\n});\n\ndeclare function __validate_BuilderArtifactOperationSchema<\n _ extends z.infer<typeof BuilderArtifactOperationSchema> = BuilderArtifactOperation,\n>(): never;\n\nconst BuilderArtifactFragmentSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"fragment\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n typename: z.string(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactFragmentSchema<\n _ extends z.infer<typeof BuilderArtifactFragmentSchema> = BuilderArtifactFragment,\n>(): never;\n\nconst BuilderArtifactElementSchema = z.discriminatedUnion(\"type\", [\n BuilderArtifactOperationSchema,\n BuilderArtifactFragmentSchema,\n]);\n\nexport const BuilderArtifactSchema = z.object({\n elements: z.record(z.string<CanonicalId>(), BuilderArtifactElementSchema),\n report: z.object({\n durationMs: z.number(),\n warnings: z.array(z.string()),\n stats: z.object({\n hits: z.number(),\n misses: z.number(),\n skips: z.number(),\n }),\n }),\n});\n\nexport type BuilderArtifact = z.infer<typeof BuilderArtifactSchema>;\nexport type BuilderArtifactElement = z.infer<typeof BuilderArtifactElementSchema>;\n","import { createHash } from \"node:crypto\";\n\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis, ModuleDefinition } from \"../ast\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\nimport type { BuilderError } from \"../types\";\nimport type { BuilderArtifactElement, BuilderArtifactElementMetadata } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nconst computeContentHash = (prebuild: unknown): string => {\n const hash = createHash(\"sha1\");\n hash.update(JSON.stringify(prebuild));\n return hash.digest(\"hex\");\n};\n\nconst emitRegistrationError = (definition: ModuleDefinition, message: string): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: canonicalToFilePath(definition.canonicalId),\n astPath: definition.astPath,\n message,\n});\n\ntype AggregateInput = {\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n};\n\nexport const aggregate = ({ analyses, elements }: AggregateInput): Result<Map<string, BuilderArtifactElement>, BuilderError> => {\n const registry = new Map<string, BuilderArtifactElement>();\n\n for (const analysis of analyses.values()) {\n for (const definition of analysis.definitions) {\n const element = elements[definition.canonicalId];\n if (!element) {\n const availableIds = Object.keys(elements).join(\", \");\n const message = `ARTIFACT_NOT_FOUND_IN_RUNTIME_MODULE: ${definition.canonicalId}\\nAvailable: ${availableIds}`;\n return err(emitRegistrationError(definition, message));\n }\n\n if (registry.has(definition.canonicalId)) {\n return err(emitRegistrationError(definition, `ARTIFACT_ALREADY_REGISTERED`));\n }\n\n const metadata: BuilderArtifactElementMetadata = {\n sourcePath: analysis.filePath ?? canonicalToFilePath(definition.canonicalId),\n contentHash: \"\", // Will be computed after prebuild creation\n };\n\n if (element.type === \"fragment\") {\n const prebuild = { typename: element.element.typename };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"fragment\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n if (element.type === \"operation\") {\n const prebuild = {\n operationType: element.element.operationType,\n operationName: element.element.operationName,\n document: element.element.document,\n variableNames: element.element.variableNames,\n metadata: element.element.metadata,\n };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"operation\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n return err(emitRegistrationError(definition, \"UNKNOWN_ARTIFACT_KIND\"));\n }\n }\n\n return ok(registry);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../types\";\nimport type { IntermediateElements } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nexport const checkIssues = ({ elements }: { elements: IntermediateElements }): Result<string[], BuilderError> => {\n const operationNames = new Set<string>();\n\n for (const [canonicalId, { type, element }] of Object.entries(elements)) {\n if (type !== \"operation\") {\n continue;\n }\n\n if (operationNames.has(element.operationName)) {\n const sources = [canonicalToFilePath(canonicalId)];\n return err({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${element.operationName}`,\n name: element.operationName,\n sources,\n });\n }\n\n operationNames.add(element.operationName);\n }\n\n return ok([]);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { ModuleLoadStats } from \"../discovery\";\nimport type { BuilderError } from \"../types\";\nimport { aggregate } from \"./aggregate\";\nimport { checkIssues } from \"./issue-handler\";\nimport type { BuilderArtifact, IntermediateElements } from \"./types\";\n\ntype BuildArtifactInput = {\n readonly elements: IntermediateElements;\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly stats: ModuleLoadStats;\n};\n\nexport const buildArtifact = ({\n elements,\n analyses,\n stats: cache,\n}: BuildArtifactInput): Result<BuilderArtifact, BuilderError> => {\n const issuesResult = checkIssues({ elements });\n if (issuesResult.isErr()) {\n return err(issuesResult.error);\n }\n\n const warnings = issuesResult.value;\n\n const aggregationResult = aggregate({ analyses, elements });\n if (aggregationResult.isErr()) {\n return err(aggregationResult.error);\n }\n\n return ok({\n elements: Object.fromEntries(aggregationResult.value.entries()),\n report: {\n durationMs: 0,\n warnings,\n stats: cache,\n },\n } satisfies BuilderArtifact);\n};\n","import { err, type Result } from \"neverthrow\";\n\n/**\n * Comprehensive error code taxonomy for Builder operations.\n */\nexport type BuilderErrorCode =\n // Input/Configuration errors\n | \"ENTRY_NOT_FOUND\"\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n // Discovery errors\n | \"DISCOVERY_IO_ERROR\"\n | \"FINGERPRINT_FAILED\"\n | \"UNSUPPORTED_ANALYZER\"\n // Canonical ID errors\n | \"CANONICAL_PATH_INVALID\"\n | \"CANONICAL_SCOPE_MISMATCH\"\n // Graph/Analysis errors\n | \"GRAPH_CIRCULAR_DEPENDENCY\"\n | \"GRAPH_MISSING_IMPORT\"\n | \"DOC_DUPLICATE\"\n // Emission/IO errors\n | \"WRITE_FAILED\"\n | \"CACHE_CORRUPTED\"\n // Runtime evaluation errors\n | \"RUNTIME_MODULE_LOAD_FAILED\"\n | \"ARTIFACT_REGISTRATION_FAILED\"\n // Internal invariant violations\n | \"INTERNAL_INVARIANT\";\n\n/**\n * Structured error type for all Builder operations.\n */\nexport type BuilderError =\n // Input/Configuration\n | {\n readonly code: \"ENTRY_NOT_FOUND\";\n readonly message: string;\n readonly entry: string;\n }\n | {\n readonly code: \"CONFIG_NOT_FOUND\";\n readonly message: string;\n readonly path: string;\n }\n | {\n readonly code: \"CONFIG_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly cause?: unknown;\n }\n // Discovery\n | {\n readonly code: \"DISCOVERY_IO_ERROR\";\n readonly message: string;\n readonly path: string;\n readonly errno?: string | number;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"FINGERPRINT_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"UNSUPPORTED_ANALYZER\";\n readonly message: string;\n readonly analyzer: string;\n }\n // Canonical ID\n | {\n readonly code: \"CANONICAL_PATH_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly reason?: string;\n }\n | {\n readonly code: \"CANONICAL_SCOPE_MISMATCH\";\n readonly message: string;\n readonly expected: string;\n readonly actual: string;\n }\n // Graph/Analysis\n | {\n readonly code: \"GRAPH_CIRCULAR_DEPENDENCY\";\n readonly message: string;\n readonly chain: readonly string[];\n }\n | {\n readonly code: \"GRAPH_MISSING_IMPORT\";\n readonly message: string;\n readonly importer: string;\n readonly importee: string;\n }\n | {\n readonly code: \"DOC_DUPLICATE\";\n readonly message: string;\n readonly name: string;\n readonly sources: readonly string[];\n }\n // Emission/IO\n | {\n readonly code: \"WRITE_FAILED\";\n readonly message: string;\n readonly outPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"CACHE_CORRUPTED\";\n readonly message: string;\n readonly cachePath?: string;\n readonly cause?: unknown;\n }\n // Runtime evaluation\n | {\n readonly code: \"RUNTIME_MODULE_LOAD_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"ARTIFACT_REGISTRATION_FAILED\";\n readonly message: string;\n readonly elementId: string;\n readonly reason: string;\n }\n // Internal invariant\n | {\n readonly code: \"INTERNAL_INVARIANT\";\n readonly message: string;\n readonly context?: string;\n readonly cause?: unknown;\n };\n\n/**\n * Helper type for Builder operation results.\n */\nexport type BuilderResult<T> = Result<T, BuilderError>;\n\n/**\n * Error constructor helpers for concise error creation.\n */\nexport const builderErrors = {\n entryNotFound: (entry: string, message?: string): BuilderError => ({\n code: \"ENTRY_NOT_FOUND\",\n message: message ?? `Entry not found: ${entry}`,\n entry,\n }),\n\n configNotFound: (path: string, message?: string): BuilderError => ({\n code: \"CONFIG_NOT_FOUND\",\n message: message ?? `Config file not found: ${path}`,\n path,\n }),\n\n configInvalid: (path: string, message: string, cause?: unknown): BuilderError => ({\n code: \"CONFIG_INVALID\",\n message,\n path,\n cause,\n }),\n\n discoveryIOError: (path: string, message: string, errno?: string | number, cause?: unknown): BuilderError => ({\n code: \"DISCOVERY_IO_ERROR\",\n message,\n path,\n errno,\n cause,\n }),\n\n fingerprintFailed: (filePath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"FINGERPRINT_FAILED\",\n message,\n filePath,\n cause,\n }),\n\n unsupportedAnalyzer: (analyzer: string, message?: string): BuilderError => ({\n code: \"UNSUPPORTED_ANALYZER\",\n message: message ?? `Unsupported analyzer: ${analyzer}`,\n analyzer,\n }),\n\n canonicalPathInvalid: (path: string, reason?: string): BuilderError => ({\n code: \"CANONICAL_PATH_INVALID\",\n message: `Invalid canonical path: ${path}${reason ? ` (${reason})` : \"\"}`,\n path,\n reason,\n }),\n\n canonicalScopeMismatch: (expected: string, actual: string): BuilderError => ({\n code: \"CANONICAL_SCOPE_MISMATCH\",\n message: `Scope mismatch: expected ${expected}, got ${actual}`,\n expected,\n actual,\n }),\n\n graphCircularDependency: (chain: readonly string[]): BuilderError => ({\n code: \"GRAPH_CIRCULAR_DEPENDENCY\",\n message: `Circular dependency detected: ${chain.join(\" → \")}`,\n chain,\n }),\n\n graphMissingImport: (importer: string, importee: string): BuilderError => ({\n code: \"GRAPH_MISSING_IMPORT\",\n message: `Missing import: \"${importer}\" imports \"${importee}\" but it's not in the graph`,\n importer,\n importee,\n }),\n\n docDuplicate: (name: string, sources: readonly string[]): BuilderError => ({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${name} found in ${sources.length} files`,\n name,\n sources,\n }),\n\n writeFailed: (outPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"WRITE_FAILED\",\n message,\n outPath,\n cause,\n }),\n\n cacheCorrupted: (message: string, cachePath?: string, cause?: unknown): BuilderError => ({\n code: \"CACHE_CORRUPTED\",\n message,\n cachePath,\n cause,\n }),\n\n runtimeModuleLoadFailed: (filePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n message,\n filePath,\n astPath,\n cause,\n }),\n\n artifactRegistrationFailed: (elementId: string, reason: string): BuilderError => ({\n code: \"ARTIFACT_REGISTRATION_FAILED\",\n message: `Failed to register artifact element ${elementId}: ${reason}`,\n elementId,\n reason,\n }),\n\n internalInvariant: (message: string, context?: string, cause?: unknown): BuilderError => ({\n code: \"INTERNAL_INVARIANT\",\n message: `Internal invariant violated: ${message}`,\n context,\n cause,\n }),\n} as const;\n\n/**\n * Convenience helper to create an err Result from BuilderError.\n */\nexport const builderErr = <T = never>(error: BuilderError): BuilderResult<T> => err(error);\n\n/**\n * Type guard for BuilderError.\n */\nexport const isBuilderError = (error: unknown): error is BuilderError => {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\"\n );\n};\n\n/**\n * Format BuilderError for console output (human-readable).\n */\nexport const formatBuilderError = (error: BuilderError): string => {\n const lines: string[] = [];\n\n lines.push(`Error [${error.code}]: ${error.message}`);\n\n // Add context-specific details\n switch (error.code) {\n case \"ENTRY_NOT_FOUND\":\n lines.push(` Entry: ${error.entry}`);\n break;\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.code === \"CONFIG_INVALID\" && error.cause) {\n lines.push(` Cause: ${error.cause}`);\n }\n break;\n case \"DISCOVERY_IO_ERROR\":\n lines.push(` Path: ${error.path}`);\n if (error.errno !== undefined) {\n lines.push(` Errno: ${error.errno}`);\n }\n break;\n case \"FINGERPRINT_FAILED\":\n lines.push(` File: ${error.filePath}`);\n break;\n case \"CANONICAL_PATH_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.reason) {\n lines.push(` Reason: ${error.reason}`);\n }\n break;\n case \"CANONICAL_SCOPE_MISMATCH\":\n lines.push(` Expected: ${error.expected}`);\n lines.push(` Actual: ${error.actual}`);\n break;\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n lines.push(` Chain: ${error.chain.join(\" → \")}`);\n break;\n case \"GRAPH_MISSING_IMPORT\":\n lines.push(` Importer: ${error.importer}`);\n lines.push(` Importee: ${error.importee}`);\n break;\n case \"DOC_DUPLICATE\":\n lines.push(` Name: ${error.name}`);\n lines.push(` Sources:\\n ${error.sources.join(\"\\n \")}`);\n break;\n case \"WRITE_FAILED\":\n lines.push(` Output path: ${error.outPath}`);\n break;\n case \"CACHE_CORRUPTED\":\n if (error.cachePath) {\n lines.push(` Cache path: ${error.cachePath}`);\n }\n break;\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n lines.push(` File: ${error.filePath}`);\n lines.push(` AST path: ${error.astPath}`);\n break;\n case \"ARTIFACT_REGISTRATION_FAILED\":\n lines.push(` Element ID: ${error.elementId}`);\n lines.push(` Reason: ${error.reason}`);\n break;\n case \"INTERNAL_INVARIANT\":\n if (error.context) {\n lines.push(` Context: ${error.context}`);\n }\n break;\n }\n\n // Add cause if present and not already shown\n if (\"cause\" in error && error.cause && ![\"CONFIG_INVALID\"].includes(error.code)) {\n lines.push(` Caused by: ${error.cause}`);\n }\n\n return lines.join(\"\\n\");\n};\n\n/**\n * Assert unreachable code path (for exhaustiveness checks).\n * This is the ONLY acceptable throw in builder code.\n */\nexport const assertUnreachable = (value: never, context?: string): never => {\n throw new Error(`Unreachable code path${context ? ` in ${context}` : \"\"}: received ${JSON.stringify(value)}`);\n};\n","/**\n * Shared utilities for AST traversal and scope tracking.\n * Used by both TypeScript and SWC adapters.\n */\n\n/**\n * Scope frame for tracking AST path segments\n */\nexport type ScopeFrame = {\n /** Name segment (e.g., \"MyComponent\", \"useQuery\", \"arrow#1\") */\n readonly nameSegment: string;\n /** Kind of scope */\n readonly kind: \"function\" | \"class\" | \"variable\" | \"property\" | \"method\" | \"expression\";\n};\n\n/**\n * Build AST path from scope stack\n */\nexport const buildAstPath = (stack: readonly ScopeFrame[]): string => {\n return stack.map((frame) => frame.nameSegment).join(\".\");\n};\n\n/**\n * Create an occurrence tracker for disambiguating anonymous/duplicate scopes.\n */\nexport const createOccurrenceTracker = (): {\n getNextOccurrence: (key: string) => number;\n} => {\n const occurrenceCounters = new Map<string, number>();\n\n return {\n getNextOccurrence(key: string): number {\n const current = occurrenceCounters.get(key) ?? 0;\n occurrenceCounters.set(key, current + 1);\n return current;\n },\n };\n};\n\n/**\n * Create a path uniqueness tracker to ensure AST paths are unique.\n */\nexport const createPathTracker = (): {\n ensureUniquePath: (basePath: string) => string;\n} => {\n const usedPaths = new Set<string>();\n\n return {\n ensureUniquePath(basePath: string): string {\n let path = basePath;\n let suffix = 0;\n while (usedPaths.has(path)) {\n suffix++;\n path = `${basePath}$${suffix}`;\n }\n usedPaths.add(path);\n return path;\n },\n };\n};\n\n/**\n * Create an export bindings map from module exports.\n * Maps local variable names to their exported names.\n */\nexport const createExportBindingsMap = <T extends { kind: string; local?: string; exported: string; isTypeOnly?: boolean }>(\n exports: readonly T[],\n): Map<string, string> => {\n const exportBindings = new Map<string, string>();\n exports.forEach((exp) => {\n if (exp.kind === \"named\" && exp.local && !exp.isTypeOnly) {\n exportBindings.set(exp.local, exp.exported);\n }\n });\n return exportBindings;\n};\n","/**\n * SWC adapter for the analyzer core.\n * Implements parser-specific logic using the SWC parser.\n */\n\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport { parseSync } from \"@swc/core\";\nimport type { CallExpression, ImportDeclaration, Module } from \"@swc/types\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\n\n/**\n * Extended SWC Module with filePath attached (similar to ts.SourceFile.fileName)\n */\ntype SwcModule = Module & {\n __filePath: string;\n /** Offset to subtract from spans to normalize to 0-based source indices */\n __spanOffset: number;\n};\n\nimport type { AnalyzeModuleInput, ModuleDefinition, ModuleExport, ModuleImport } from \"../types\";\n\nconst collectImports = (module: Module): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n const handle = (declaration: ImportDeclaration) => {\n const source = declaration.source.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"named\",\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"namespace\",\n isTypeOnly: false,\n });\n return;\n }\n if (specifier.type === \"ImportDefaultSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"default\",\n isTypeOnly: false,\n });\n }\n });\n };\n\n module.body.forEach((item) => {\n if (item.type === \"ImportDeclaration\") {\n handle(item);\n return;\n }\n // Handle module declarations with import declarations\n if (\n \"declaration\" in item &&\n item.declaration &&\n \"type\" in item.declaration &&\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any).type === \"ImportDeclaration\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n handle(item.declaration as any as ImportDeclaration);\n }\n });\n\n return imports;\n};\n\nconst collectExports = (module: Module): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const handle = (declaration: any) => {\n if (declaration.type === \"ExportDeclaration\") {\n if (declaration.declaration.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n declaration.declaration.declarations.forEach((decl: any) => {\n if (decl.id.type === \"Identifier\") {\n exports.push({\n kind: \"named\",\n exported: decl.id.value,\n local: decl.id.value,\n isTypeOnly: false,\n });\n }\n });\n }\n if (declaration.declaration.type === \"FunctionDeclaration\") {\n const ident = declaration.declaration.identifier;\n if (ident) {\n exports.push({\n kind: \"named\",\n exported: ident.value,\n local: ident.value,\n isTypeOnly: false,\n });\n }\n }\n return;\n }\n\n if (declaration.type === \"ExportNamedDeclaration\") {\n const source = declaration.source?.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type !== \"ExportSpecifier\") {\n return;\n }\n const exported = specifier.exported ? specifier.exported.value : specifier.orig.value;\n const local = specifier.orig.value;\n if (source) {\n exports.push({\n kind: \"reexport\",\n exported,\n local,\n source,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n exports.push({\n kind: \"named\",\n exported,\n local,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n });\n return;\n }\n\n if (declaration.type === \"ExportAllDeclaration\") {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: declaration.source.value,\n isTypeOnly: false,\n });\n return;\n }\n\n if (declaration.type === \"ExportDefaultDeclaration\" || declaration.type === \"ExportDefaultExpression\") {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n };\n\n module.body.forEach((item) => {\n if (\n item.type === \"ExportDeclaration\" ||\n item.type === \"ExportNamedDeclaration\" ||\n item.type === \"ExportAllDeclaration\" ||\n item.type === \"ExportDefaultDeclaration\" ||\n item.type === \"ExportDefaultExpression\"\n ) {\n handle(item);\n return;\n }\n\n if (\"declaration\" in item && item.declaration) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n const declaration = item.declaration as any;\n if (\n declaration.type === \"ExportDeclaration\" ||\n declaration.type === \"ExportNamedDeclaration\" ||\n declaration.type === \"ExportAllDeclaration\" ||\n declaration.type === \"ExportDefaultDeclaration\" ||\n declaration.type === \"ExportDefaultExpression\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Complex SWC AST type\n handle(declaration as any);\n }\n }\n });\n\n return exports;\n};\n\nconst collectGqlIdentifiers = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\n : // biome-ignore lint/suspicious/noExplicitAny: SWC AST type checking\n \"declaration\" in item && item.declaration && (item.declaration as any).type === \"ImportDeclaration\"\n ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n if (!declaration) {\n return;\n }\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n if (imported === \"gql\") {\n identifiers.add(specifier.local.value);\n }\n }\n });\n });\n return identifiers;\n};\n\nconst isGqlCall = (identifiers: ReadonlySet<string>, call: CallExpression): boolean => {\n const callee = call.callee;\n if (callee.type !== \"MemberExpression\") {\n return false;\n }\n\n if (callee.object.type !== \"Identifier\") {\n return false;\n }\n\n if (!identifiers.has(callee.object.value)) {\n return false;\n }\n\n if (callee.property.type !== \"Identifier\") {\n return false;\n }\n\n const firstArg = call.arguments[0];\n if (!firstArg?.expression || firstArg.expression.type !== \"ArrowFunctionExpression\") {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: any): CallExpression | null => {\n if (!node || node.type !== \"CallExpression\") {\n return null;\n }\n\n // Check if this is directly a gql call\n if (isGqlCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\") {\n return null;\n }\n\n // Recursively check the object of the member expression\n // e.g., for `gql.default(...).attach(...)`, callee.object is `gql.default(...)`\n return unwrapMethodChains(identifiers, callee.object);\n};\n\nconst collectAllDefinitions = ({\n module,\n gqlIdentifiers,\n imports: _imports,\n exports,\n source,\n}: {\n module: SwcModule;\n gqlIdentifiers: ReadonlySet<string>;\n imports: readonly ModuleImport[];\n exports: readonly ModuleExport[];\n source: string;\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly CallExpression[];\n} => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const getPropertyName = (property: any): string | null => {\n if (!property) {\n return null;\n }\n if (property.type === \"Identifier\") {\n return property.value;\n }\n if (property.type === \"StringLiteral\" || property.type === \"NumericLiteral\") {\n return property.value;\n }\n return null;\n };\n\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: module.__filePath,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const expressionFromCall = (call: CallExpression): string => {\n // Normalize span by subtracting the module's span offset\n const spanOffset = module.__spanOffset;\n let start = call.span.start - spanOffset;\n const end = call.span.end - spanOffset;\n\n // Adjust when span starts one character after the leading \"g\"\n if (start > 0 && source[start] === \"q\" && source[start - 1] === \"g\" && source.slice(start, start + 3) === \"ql.\") {\n start -= 1;\n }\n\n const raw = source.slice(start, end);\n const marker = raw.indexOf(\"gql\");\n const expression = marker >= 0 ? raw.slice(marker) : raw;\n\n // Strip trailing semicolons and whitespace that SWC may include in the span\n // TypeScript's node.getText() doesn't include these, so we normalize to match\n return expression.replace(/\\s*;\\s*$/, \"\");\n };\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any, stack: ScopeFrame[]) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (node.type === \"CallExpression\") {\n const gqlCall = unwrapMethodChains(gqlIdentifiers, node);\n if (gqlCall) {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: expressionFromCall(gqlCall),\n });\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (node.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.declarations?.forEach((decl: any) => {\n if (decl.id?.type === \"Identifier\") {\n const varName = decl.id.value;\n\n if (decl.init) {\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(decl.init, newStack);\n });\n }\n }\n });\n return;\n }\n\n // Function declaration\n if (node.type === \"FunctionDeclaration\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Arrow function\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowName = getAnonymousName(\"arrow\");\n\n if (node.body) {\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Function expression\n if (node.type === \"FunctionExpression\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Class declaration\n if (node.type === \"ClassDeclaration\") {\n const className = node.identifier?.value ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"ClassMethod\" || member.type === \"ClassProperty\") {\n const memberName = member.key?.value ?? null;\n if (memberName) {\n const memberKind = member.type === \"ClassMethod\" ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (member.type === \"ClassMethod\" && member.function?.body) {\n visit(member.function.body, memberStack);\n } else if (member.type === \"ClassProperty\" && member.value) {\n visit(member.value, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (node.type === \"KeyValueProperty\") {\n const propName = getPropertyName(node.key);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.value, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n if (Array.isArray(node)) {\n for (const child of node) {\n visit(child, stack);\n }\n } else {\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child, stack);\n }\n } else if (value && typeof value === \"object\") {\n visit(value, stack);\n }\n }\n }\n };\n\n // Start traversal from top-level statements\n module.body.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(module.__filePath, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * SWC adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (Module) is released after analysis.\n */\nexport const swcAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const program = parseSync(input.source, {\n syntax: \"typescript\",\n tsx: input.filePath.endsWith(\".tsx\"),\n target: \"es2022\",\n decorators: false,\n dynamicImport: true,\n });\n\n if (program.type !== \"Module\") {\n return null;\n }\n\n // SWC's BytePos counter accumulates across parseSync calls within the same process.\n // To convert span positions to 0-indexed source positions, we compute the accumulated\n // offset from previous parses: (program.span.end - source.length) gives us the total\n // bytes from previously parsed files, and we add 1 because spans are 1-indexed.\n const spanOffset = program.span.end - input.source.length + 1;\n\n // Attach filePath to module (similar to ts.SourceFile.fileName)\n const swcModule = program as SwcModule;\n swcModule.__filePath = input.filePath;\n swcModule.__spanOffset = spanOffset;\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlIdentifiers(swcModule, helper);\n const imports = collectImports(swcModule);\n const exports = collectExports(swcModule);\n\n const { definitions } = collectAllDefinitions({\n module: swcModule,\n gqlIdentifiers,\n imports,\n exports,\n source: input.source,\n });\n\n // Return results - swcModule goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n };\n },\n};\n","/**\n * TypeScript adapter for the analyzer core.\n * Implements parser-specific logic using the TypeScript compiler API.\n */\n\nimport { extname } from \"node:path\";\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport ts from \"typescript\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\nimport type { AnalyzeModuleInput, ModuleDefinition, ModuleExport, ModuleImport } from \"../types\";\n\nconst createSourceFile = (filePath: string, source: string): ts.SourceFile => {\n const scriptKind = extname(filePath) === \".tsx\" ? ts.ScriptKind.TSX : ts.ScriptKind.TS;\n return ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2022, true, scriptKind);\n};\n\nconst collectGqlImports = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: sourceFile.fileName, specifier: moduleText })) {\n return;\n }\n\n if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {\n statement.importClause.namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n if (imported === \"gql\") {\n identifiers.add(element.name.text);\n }\n });\n }\n });\n\n return identifiers;\n};\n\nconst collectImports = (sourceFile: ts.SourceFile): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n const { importClause } = statement;\n\n if (importClause.name) {\n imports.push({\n source: moduleText,\n local: importClause.name.text,\n kind: \"default\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) {\n return;\n }\n\n if (ts.isNamespaceImport(namedBindings)) {\n imports.push({\n source: moduleText,\n local: namedBindings.name.text,\n kind: \"namespace\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n return;\n }\n\n namedBindings.elements.forEach((element) => {\n imports.push({\n source: moduleText,\n local: element.name.text,\n kind: \"named\",\n isTypeOnly: Boolean(importClause.isTypeOnly || element.isTypeOnly),\n });\n });\n });\n\n return imports;\n};\n\nconst collectExports = (sourceFile: ts.SourceFile): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (ts.isExportDeclaration(statement)) {\n const moduleSpecifier = statement.moduleSpecifier ? (statement.moduleSpecifier as ts.StringLiteral).text : undefined;\n\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n statement.exportClause.elements.forEach((element) => {\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : undefined,\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n } else {\n exports.push({\n kind: \"named\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : element.name.text,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n }\n });\n return;\n }\n\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly),\n });\n }\n\n return;\n }\n\n if (ts.isExportAssignment(statement)) {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n\n if (\n ts.isVariableStatement(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n statement.declarationList.declarations.forEach((declaration) => {\n if (ts.isIdentifier(declaration.name)) {\n exports.push({\n kind: \"named\",\n exported: declaration.name.text,\n local: declaration.name.text,\n isTypeOnly: false,\n });\n }\n });\n }\n\n if (\n ts.isFunctionDeclaration(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) &&\n statement.name\n ) {\n exports.push({\n kind: \"named\",\n exported: statement.name.text,\n local: statement.name.text,\n isTypeOnly: false,\n });\n }\n });\n\n return exports;\n};\n\nconst isGqlDefinitionCall = (identifiers: ReadonlySet<string>, callExpression: ts.CallExpression): boolean => {\n const expression = callExpression.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return false;\n }\n\n if (!ts.isIdentifier(expression.expression) || !identifiers.has(expression.expression.text)) {\n return false;\n }\n\n const [factory] = callExpression.arguments;\n if (!factory || !ts.isArrowFunction(factory)) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: ts.Node): ts.CallExpression | null => {\n if (!ts.isCallExpression(node)) {\n return null;\n }\n\n // Check if this is directly a gql definition call\n if (isGqlDefinitionCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const expression = node.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return null;\n }\n\n // Recursively check the object of the property access\n // e.g., for `gql.default(...).attach(...)`, expression.expression is `gql.default(...)`\n return unwrapMethodChains(identifiers, expression.expression);\n};\n\n/**\n * Get property name from AST node\n */\nconst getPropertyName = (name: ts.PropertyName): string | null => {\n if (ts.isIdentifier(name)) {\n return name.text;\n }\n if (ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return null;\n};\n\n/**\n * Collect all gql definitions (exported, non-exported, top-level, nested)\n */\nconst collectAllDefinitions = ({\n sourceFile,\n identifiers,\n exports,\n}: {\n sourceFile: ts.SourceFile;\n identifiers: ReadonlySet<string>;\n exports: readonly ModuleExport[];\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly ts.CallExpression[];\n} => {\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: ts.CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: sourceFile.fileName,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const visit = (node: ts.Node, stack: ScopeFrame[]) => {\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (ts.isCallExpression(node)) {\n const gqlCall = unwrapMethodChains(identifiers, node);\n if (gqlCall) {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: gqlCall.getText(sourceFile),\n });\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (ts.isVariableDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const varName = node.name.text;\n\n if (node.initializer) {\n const next = node.initializer;\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(next, newStack);\n });\n }\n return;\n }\n\n // Function declaration\n if (ts.isFunctionDeclaration(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n const next = node.body;\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(next, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Arrow function\n if (ts.isArrowFunction(node)) {\n const arrowName = getAnonymousName(\"arrow\");\n\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n if (ts.isBlock(node.body)) {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n } else {\n visit(node.body, newStack);\n }\n });\n return;\n }\n\n // Function expression\n if (ts.isFunctionExpression(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Class declaration\n if (ts.isClassDeclaration(node)) {\n const className = node.name?.text ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n node.members.forEach((member) => {\n if (ts.isMethodDeclaration(member) || ts.isPropertyDeclaration(member)) {\n const memberName = member.name && ts.isIdentifier(member.name) ? member.name.text : null;\n if (memberName) {\n const memberKind = ts.isMethodDeclaration(member) ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (ts.isMethodDeclaration(member) && member.body) {\n ts.forEachChild(member.body, (child) => visit(child, memberStack));\n } else if (ts.isPropertyDeclaration(member) && member.initializer) {\n visit(member.initializer, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (ts.isPropertyAssignment(node)) {\n const propName = getPropertyName(node.name);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.initializer, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n ts.forEachChild(node, (child) => visit(child, stack));\n };\n\n // Start traversal from top-level statements\n sourceFile.statements.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(sourceFile.fileName, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * TypeScript adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (ts.SourceFile) is released after analysis.\n */\nexport const typescriptAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const sourceFile = createSourceFile(input.filePath, input.source);\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlImports(sourceFile, helper);\n const imports = collectImports(sourceFile);\n const exports = collectExports(sourceFile);\n\n const { definitions } = collectAllDefinitions({\n sourceFile,\n identifiers: gqlIdentifiers,\n exports,\n });\n\n // Return results - sourceFile goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n };\n },\n};\n","/**\n * Core analyzer logic that orchestrates the analysis pipeline.\n * Adapters (TypeScript, SWC, etc.) implement the adapter interface to plug into this pipeline.\n */\n\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleExport, ModuleImport } from \"./types\";\n\n/**\n * Result of analyzing a module, containing all collected data.\n */\nexport type AnalyzerResult = {\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly definitions: readonly ModuleDefinition[];\n};\n\n/**\n * Adapter interface that each parser implementation (TS, SWC) must provide.\n * The analyze method parses and collects all data in one pass, allowing the AST\n * to be released immediately after analysis completes.\n */\nexport interface AnalyzerAdapter {\n /**\n * Parse source code into an AST, collect all required data, and return results.\n * The AST is kept within this function's scope and released after analysis.\n * This design enables early garbage collection of AST objects.\n */\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null;\n}\n\n/**\n * Core analyzer function that orchestrates the analysis pipeline.\n * Adapters implement the AnalyzerAdapter interface to provide parser-specific logic.\n */\nexport const analyzeModuleCore = (\n input: AnalyzeModuleInput,\n adapter: AnalyzerAdapter,\n graphqlHelper: GraphqlSystemIdentifyHelper,\n): ModuleAnalysis => {\n const hasher = getPortableHasher();\n const signature = hasher.hash(input.source, \"xxhash\");\n\n // Delegate all analysis to the adapter - AST is created and released within analyze()\n const result = adapter.analyze(input, graphqlHelper);\n\n if (!result) {\n return {\n filePath: input.filePath,\n signature,\n definitions: [],\n imports: [],\n exports: [],\n };\n }\n\n return {\n filePath: input.filePath,\n signature,\n definitions: result.definitions,\n imports: result.imports,\n exports: result.exports,\n };\n};\n","import { assertUnreachable } from \"../errors\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { BuilderAnalyzer } from \"../types\";\nimport { swcAdapter } from \"./adapters/swc\";\nimport { typescriptAdapter } from \"./adapters/typescript\";\nimport { analyzeModuleCore } from \"./core\";\nimport type { AnalyzeModuleInput, ModuleAnalysis } from \"./types\";\n\nexport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleExport, ModuleImport } from \"./types\";\n\nexport const createAstAnalyzer = ({\n analyzer,\n graphqlHelper,\n}: {\n readonly analyzer: BuilderAnalyzer;\n readonly graphqlHelper: GraphqlSystemIdentifyHelper;\n}) => {\n const analyze = (input: AnalyzeModuleInput): ModuleAnalysis => {\n if (analyzer === \"ts\") {\n return analyzeModuleCore(input, typescriptAdapter, graphqlHelper);\n }\n if (analyzer === \"swc\") {\n return analyzeModuleCore(input, swcAdapter, graphqlHelper);\n }\n return assertUnreachable(analyzer, \"createAstAnalyzer\");\n };\n\n return {\n type: analyzer,\n analyze,\n };\n};\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\ntype CacheNamespace = readonly string[];\n\nexport type CacheFactoryOptions = {\n readonly prefix?: CacheNamespace;\n readonly persistence?: {\n readonly enabled: boolean;\n readonly filePath: string;\n };\n};\n\nexport type CacheStoreOptions<_K extends string, V> = {\n readonly namespace: CacheNamespace;\n readonly schema: z.ZodType<V>;\n readonly version?: string;\n};\n\nexport type CacheStore<K extends string, V> = {\n load(key: K): V | null;\n store(key: K, value: V): void;\n delete(key: K): void;\n entries(): IterableIterator<[K, V]>;\n clear(): void;\n size(): number;\n};\n\nexport type CacheFactory = {\n createStore<K extends string, V>(options: CacheStoreOptions<K, V>): CacheStore<K, V>;\n clearAll(): void;\n save(): void;\n};\n\nconst sanitizeSegment = (segment: string): string => segment.replace(/[\\\\/]/g, \"_\");\n\nconst toNamespaceKey = (segments: CacheNamespace): string => segments.map(sanitizeSegment).join(\"/\");\n\nconst toEntryKey = (key: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(key, \"xxhash\");\n};\n\ntype Envelope<V> = {\n key: string;\n version: string;\n value: V;\n};\n\ntype PersistedData = {\n version: string;\n storage: Record<string, Array<[string, Envelope<unknown>]>>;\n};\n\nconst PERSISTENCE_VERSION = \"v1\";\n\nexport const createMemoryCache = ({ prefix = [], persistence }: CacheFactoryOptions = {}): CacheFactory => {\n // Global in-memory storage: Map<namespaceKey, Map<hashedKey, Envelope>>\n const storage = new Map<string, Map<string, Envelope<unknown>>>();\n\n // Load from disk if persistence is enabled (synchronous on startup)\n if (persistence?.enabled) {\n try {\n if (existsSync(persistence.filePath)) {\n const content = readFileSync(persistence.filePath, \"utf-8\");\n const data: PersistedData = JSON.parse(content);\n\n if (data.version === PERSISTENCE_VERSION && data.storage) {\n // Restore Map structure from persisted data\n for (const [namespaceKey, entries] of Object.entries(data.storage)) {\n const namespaceMap = new Map<string, Envelope<unknown>>();\n for (const [hashedKey, envelope] of entries) {\n namespaceMap.set(hashedKey, envelope);\n }\n storage.set(namespaceKey, namespaceMap);\n }\n }\n }\n } catch (error) {\n // Silently continue with empty cache on load failure\n console.warn(`[cache] Failed to load cache from ${persistence.filePath}:`, error);\n }\n }\n\n const getOrCreateNamespace = (namespaceKey: string): Map<string, Envelope<unknown>> => {\n let namespace = storage.get(namespaceKey);\n if (!namespace) {\n namespace = new Map();\n storage.set(namespaceKey, namespace);\n }\n return namespace;\n };\n\n return {\n createStore: <K extends string, V>({ namespace, schema, version = \"v1\" }: CacheStoreOptions<K, V>): CacheStore<K, V> => {\n const namespaceKey = toNamespaceKey([...prefix, ...namespace]);\n const envelopeSchema = z.object({\n key: z.string(),\n version: z.string(),\n value: schema,\n });\n\n const resolveEntryKey = (key: string) => toEntryKey(key);\n\n const validateEnvelope = (raw: Envelope<unknown>): Envelope<V> | null => {\n const parsed = envelopeSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n if (parsed.data.version !== version) {\n return null;\n }\n\n return parsed.data as Envelope<V>;\n };\n\n const load = (key: K): V | null => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return null;\n }\n\n const entryKey = resolveEntryKey(key);\n const raw = namespaceStore.get(entryKey);\n if (!raw) {\n return null;\n }\n\n const envelope = validateEnvelope(raw);\n if (!envelope || envelope.key !== key) {\n namespaceStore.delete(entryKey);\n return null;\n }\n\n return envelope.value;\n };\n\n const store = (key: K, value: V): void => {\n const namespaceStore = getOrCreateNamespace(namespaceKey);\n const entryKey = resolveEntryKey(key);\n\n const envelope: Envelope<V> = {\n key,\n version,\n value,\n };\n\n namespaceStore.set(entryKey, envelope as Envelope<unknown>);\n };\n\n const deleteEntry = (key: K): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n const entryKey = resolveEntryKey(key);\n namespaceStore.delete(entryKey);\n };\n\n function* iterateEntries(): IterableIterator<[K, V]> {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n for (const raw of namespaceStore.values()) {\n const envelope = validateEnvelope(raw);\n if (!envelope) {\n continue;\n }\n\n yield [envelope.key as K, envelope.value];\n }\n }\n\n const clear = (): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (namespaceStore) {\n namespaceStore.clear();\n }\n };\n\n const size = (): number => {\n let count = 0;\n for (const _ of iterateEntries()) {\n count += 1;\n }\n return count;\n };\n\n return {\n load,\n store,\n delete: deleteEntry,\n entries: iterateEntries,\n clear,\n size,\n };\n },\n\n clearAll: (): void => {\n storage.clear();\n },\n\n save: (): void => {\n if (!persistence?.enabled) {\n return;\n }\n\n try {\n // Convert Map structure to plain object for JSON serialization\n const serialized: Record<string, Array<[string, Envelope<unknown>]>> = {};\n for (const [namespaceKey, namespaceMap] of storage.entries()) {\n serialized[namespaceKey] = Array.from(namespaceMap.entries());\n }\n\n const data: PersistedData = {\n version: PERSISTENCE_VERSION,\n storage: serialized,\n };\n\n // Ensure directory exists\n const dir = dirname(persistence.filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Write to file synchronously\n writeFileSync(persistence.filePath, JSON.stringify(data), \"utf-8\");\n } catch (error) {\n console.warn(`[cache] Failed to save cache to ${persistence.filePath}:`, error);\n }\n },\n };\n};\n","import { normalizePath } from \"@soda-gql/common\";\nimport type { ZodSchema } from \"zod\";\nimport type { CacheFactory, CacheStore } from \"./memory-cache\";\n\nexport type EntityCacheOptions<V> = {\n readonly factory: CacheFactory;\n readonly namespace: readonly string[];\n readonly schema: ZodSchema<V>;\n readonly version: string;\n readonly keyNormalizer?: (key: string) => string;\n};\n\n/**\n * Abstract base class for entity caches.\n * Provides common caching functionality with signature-based eviction.\n */\nexport abstract class EntityCache<K extends string, V> {\n protected readonly cacheStore: CacheStore<K, V>;\n private readonly keyNormalizer: (key: string) => string;\n\n constructor(options: EntityCacheOptions<V>) {\n this.cacheStore = options.factory.createStore({\n namespace: [...options.namespace],\n schema: options.schema,\n version: options.version,\n });\n this.keyNormalizer = options.keyNormalizer ?? normalizePath;\n }\n\n /**\n * Normalize a key for consistent cache lookups.\n */\n protected normalizeKey(key: string): K {\n return this.keyNormalizer(key) as K;\n }\n\n /**\n * Load raw value from cache without signature validation.\n */\n protected loadRaw(key: K): V | null {\n return this.cacheStore.load(key);\n }\n\n /**\n * Store raw value to cache.\n */\n protected storeRaw(key: K, value: V): void {\n this.cacheStore.store(key, value);\n }\n\n /**\n * Delete an entry from the cache.\n */\n delete(key: string): void {\n const normalizedKey = this.normalizeKey(key);\n this.cacheStore.delete(normalizedKey);\n }\n\n /**\n * Get all cached entries.\n * Subclasses should override this to provide custom iteration.\n */\n protected *baseEntries(): IterableIterator<V> {\n for (const [, value] of this.cacheStore.entries()) {\n yield value;\n }\n }\n\n /**\n * Clear all entries from the cache.\n */\n clear(): void {\n this.cacheStore.clear();\n }\n\n /**\n * Get the number of entries in the cache.\n */\n size(): number {\n return this.cacheStore.size();\n }\n}\n","import { CanonicalIdSchema } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\nexport const ModuleDefinitionSchema = z.object({\n canonicalId: CanonicalIdSchema,\n astPath: z.string(),\n isTopLevel: z.boolean(),\n isExported: z.boolean(),\n exportBinding: z.string().optional(),\n expression: z.string(),\n});\n\nexport const ModuleImportSchema = z.object({\n source: z.string(),\n local: z.string(),\n kind: z.enum([\"named\", \"namespace\", \"default\"]),\n isTypeOnly: z.boolean(),\n});\n\nexport const ModuleExportSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"named\"),\n exported: z.string(),\n local: z.string(),\n source: z.undefined().optional(),\n isTypeOnly: z.boolean(),\n }),\n z.object({\n kind: z.literal(\"reexport\"),\n exported: z.string(),\n source: z.string(),\n local: z.string().optional(),\n isTypeOnly: z.boolean(),\n }),\n]);\n\nexport const ModuleAnalysisSchema = z.object({\n filePath: z.string(),\n signature: z.string(),\n definitions: z.array(ModuleDefinitionSchema).readonly(),\n imports: z.array(ModuleImportSchema).readonly(),\n exports: z.array(ModuleExportSchema).readonly(),\n});\n\nexport type ModuleAnalysis = z.infer<typeof ModuleAnalysisSchema>;\n","import { z } from \"zod\";\nimport { ModuleAnalysisSchema } from \"./cache\";\n\nconst FileFingerprintSchema = z.object({\n hash: z.string(),\n sizeBytes: z.number(),\n mtimeMs: z.number(),\n});\n\nexport const DiscoveredDependencySchema = z.object({\n specifier: z.string(),\n resolvedPath: z.string().nullable(),\n isExternal: z.boolean(),\n});\n\nexport const DiscoverySnapshotSchema = z.object({\n filePath: z.string(),\n normalizedFilePath: z.string(),\n signature: z.string(),\n fingerprint: FileFingerprintSchema,\n analyzer: z.string(),\n createdAtMs: z.number(),\n analysis: ModuleAnalysisSchema,\n dependencies: z.array(DiscoveredDependencySchema).readonly(),\n});\n","import { EntityCache } from \"../cache/entity-cache\";\nimport type { CacheFactory } from \"../cache/memory-cache\";\nimport { DiscoverySnapshotSchema } from \"../schemas/discovery\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\n// Bumped to v3 for DiscoverySnapshot schema change (added fingerprint and metadata fields)\nconst DISCOVERY_CACHE_VERSION = \"discovery-cache/v3\";\n\nexport type DiscoveryCacheOptions = {\n readonly factory: CacheFactory;\n readonly analyzer: string;\n readonly evaluatorId: string;\n readonly namespacePrefix?: readonly string[];\n readonly version?: string;\n};\n\nexport class JsonDiscoveryCache extends EntityCache<string, DiscoverySnapshot> implements DiscoveryCache {\n constructor(options: DiscoveryCacheOptions) {\n const namespace = [...(options.namespacePrefix ?? [\"discovery\"]), options.analyzer, options.evaluatorId];\n\n super({\n factory: options.factory,\n namespace,\n schema: DiscoverySnapshotSchema,\n version: options.version ?? DISCOVERY_CACHE_VERSION,\n });\n }\n\n load(filePath: string, expectedSignature: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n const snapshot = this.loadRaw(key);\n if (!snapshot) {\n return null;\n }\n\n if (snapshot.signature !== expectedSignature) {\n this.delete(filePath);\n return null;\n }\n\n return snapshot;\n }\n\n peek(filePath: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n return this.loadRaw(key);\n }\n\n store(snapshot: DiscoverySnapshot): void {\n const key = this.normalizeKey(snapshot.filePath);\n this.storeRaw(key, snapshot);\n }\n\n entries(): IterableIterator<DiscoverySnapshot> {\n return this.baseEntries();\n }\n}\n\nexport const createDiscoveryCache = (options: DiscoveryCacheOptions): DiscoveryCache => new JsonDiscoveryCache(options);\n","import { getPortableHasher, isExternalSpecifier, resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport type { DiscoveredDependency } from \"./types\";\n\n/**\n * Extract all unique dependencies (relative + external) from the analysis.\n * Resolves local specifiers immediately so discovery only traverses once.\n */\nexport const extractModuleDependencies = (analysis: ModuleAnalysis): readonly DiscoveredDependency[] => {\n const dependencies = new Map<string, DiscoveredDependency>();\n\n const addDependency = (specifier: string): void => {\n if (dependencies.has(specifier)) {\n return;\n }\n\n const isExternal = isExternalSpecifier(specifier);\n const resolvedPath = isExternal ? null : resolveRelativeImportWithExistenceCheck({ filePath: analysis.filePath, specifier });\n\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal,\n });\n };\n\n for (const imp of analysis.imports) {\n addDependency(imp.source);\n }\n\n for (const exp of analysis.exports) {\n if (exp.kind === \"reexport\") {\n addDependency(exp.source);\n }\n }\n\n return Array.from(dependencies.values());\n};\n\nexport const createSourceHash = (source: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(source, \"xxhash\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { XXHashAPI } from \"xxhash-wasm\";\n\n/**\n * File fingerprint containing hash, size, and modification time\n */\nexport type FileFingerprint = {\n /** xxHash hash of file contents */\n hash: string;\n /** File size in bytes */\n sizeBytes: number;\n /** Last modification time in milliseconds since epoch */\n mtimeMs: number;\n};\n\n/**\n * Fingerprint computation error types\n */\nexport type FingerprintError =\n | { code: \"FILE_NOT_FOUND\"; path: string; message: string }\n | { code: \"NOT_A_FILE\"; path: string; message: string }\n | { code: \"READ_ERROR\"; path: string; message: string };\n\n/**\n * In-memory fingerprint cache keyed by absolute path\n */\nconst fingerprintCache = new Map<string, FileFingerprint>();\n\n/**\n * Lazy-loaded xxhash instance\n */\nlet xxhashInstance: XXHashAPI | null = null;\n\n/**\n * Lazily load xxhash-wasm instance\n */\nasync function getXXHash(): Promise<XXHashAPI> {\n if (xxhashInstance === null) {\n const { default: xxhash } = await import(\"xxhash-wasm\");\n xxhashInstance = await xxhash();\n }\n return xxhashInstance;\n}\n\n/**\n * Compute file fingerprint with memoization.\n * Uses mtime to short-circuit re-hashing unchanged files.\n *\n * @param path - Absolute path to file\n * @returns Result containing FileFingerprint or FingerprintError\n */\nexport function computeFingerprint(path: string): Result<FileFingerprint, FingerprintError> {\n try {\n const stats = statSync(path);\n\n if (!stats.isFile()) {\n return err({\n code: \"NOT_A_FILE\",\n path,\n message: `Path is not a file: ${path}`,\n });\n }\n\n const mtimeMs = stats.mtimeMs;\n const cached = fingerprintCache.get(path);\n\n // Short-circuit if mtime unchanged\n if (cached && cached.mtimeMs === mtimeMs) {\n return ok(cached);\n }\n\n // Read and hash file contents\n const contents = readFileSync(path);\n const sizeBytes = stats.size;\n\n // Compute hash synchronously (xxhash-wasm will be loaded async first time)\n const hash = computeHashSync(contents);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes,\n mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return ok(fingerprint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return err({\n code: \"FILE_NOT_FOUND\",\n path,\n message: `File not found: ${path}`,\n });\n }\n\n return err({\n code: \"READ_ERROR\",\n path,\n message: `Failed to read file: ${error}`,\n });\n }\n}\n\n/**\n * Compute hash synchronously.\n * For first call, uses simple string hash as fallback.\n * Subsequent calls will use xxhash after async initialization.\n */\nfunction computeHashSync(contents: Buffer): string {\n // If xxhash is already loaded, use it\n if (xxhashInstance !== null) {\n const hash = xxhashInstance.h64Raw(new Uint8Array(contents));\n return hash.toString(16);\n }\n\n // First call: trigger async loading for next time\n void getXXHash();\n\n // Fallback: simple hash for first call only\n return simpleHash(contents);\n}\n\n/**\n * Simple hash function for initial calls before xxhash loads\n */\nfunction simpleHash(buffer: Buffer): string {\n let hash = 0;\n for (let i = 0; i < buffer.length; i++) {\n const byte = buffer[i];\n if (byte !== undefined) {\n hash = (hash << 5) - hash + byte;\n hash = hash & hash; // Convert to 32bit integer\n }\n }\n return hash.toString(16);\n}\n\n/**\n * Compute fingerprint from pre-read file content and stats.\n * This is used by the generator-based discoverer which already has the content.\n *\n * @param path - Absolute path to file (for caching)\n * @param stats - File stats (mtimeMs, size)\n * @param content - File content as string\n * @returns FileFingerprint\n */\nexport function computeFingerprintFromContent(\n path: string,\n stats: { readonly mtimeMs: number; readonly size: number },\n content: string,\n): FileFingerprint {\n // Check cache first by mtime\n const cached = fingerprintCache.get(path);\n if (cached && cached.mtimeMs === stats.mtimeMs) {\n return cached;\n }\n\n // Convert string to buffer for hashing\n const buffer = Buffer.from(content, \"utf-8\");\n const hash = computeHashSync(buffer);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes: stats.size,\n mtimeMs: stats.mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return fingerprint;\n}\n\n/**\n * Invalidate cached fingerprint for a specific path\n *\n * @param path - Absolute path to invalidate\n */\nexport function invalidateFingerprint(path: string): void {\n fingerprintCache.delete(path);\n}\n\n/**\n * Clear all cached fingerprints\n */\nexport function clearFingerprintCache(): void {\n fingerprintCache.clear();\n}\n","import { createAsyncScheduler, createSyncScheduler, type EffectGenerator, normalizePath } from \"@soda-gql/common\";\nimport { err, ok } from \"neverthrow\";\nimport type { createAstAnalyzer } from \"../ast\";\nimport { type BuilderResult, builderErrors } from \"../errors\";\nimport { type FileStats, OptionalFileReadEffect, OptionalFileStatEffect } from \"../scheduler\";\nimport { createSourceHash, extractModuleDependencies } from \"./common\";\nimport { computeFingerprintFromContent, invalidateFingerprint } from \"./fingerprint\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\nexport type DiscoverModulesOptions = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n /** Set of file paths explicitly invalidated (from BuilderChangeSet) */\n readonly incremental?: {\n readonly cache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly affectedFiles: Set<string>;\n };\n};\n\nexport type DiscoverModulesResult = {\n readonly snapshots: readonly DiscoverySnapshot[];\n readonly cacheHits: number;\n readonly cacheMisses: number;\n readonly cacheSkips: number;\n};\n\n/**\n * Generator-based module discovery that yields effects for file I/O.\n * This allows the discovery process to be executed with either sync or async schedulers.\n */\nexport function* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n incremental,\n}: DiscoverModulesOptions): EffectGenerator<DiscoverModulesResult> {\n const snapshots = new Map<string, DiscoverySnapshot>();\n const stack = [...entryPaths];\n const changedFiles = incremental?.changedFiles ?? new Set<string>();\n const removedFiles = incremental?.removedFiles ?? new Set<string>();\n const affectedFiles = incremental?.affectedFiles ?? new Set<string>();\n const invalidatedSet = new Set<string>([...changedFiles, ...removedFiles, ...affectedFiles]);\n let cacheHits = 0;\n let cacheMisses = 0;\n let cacheSkips = 0;\n\n if (incremental) {\n for (const filePath of removedFiles) {\n incremental.cache.delete(filePath);\n invalidateFingerprint(filePath);\n }\n }\n\n while (stack.length > 0) {\n const rawFilePath = stack.pop();\n if (!rawFilePath) {\n continue;\n }\n\n // Normalize path for consistent cache key matching\n const filePath = normalizePath(rawFilePath);\n\n if (snapshots.has(filePath)) {\n continue;\n }\n\n // Check if explicitly invalidated\n let shouldReadFile = true;\n if (invalidatedSet.has(filePath)) {\n invalidateFingerprint(filePath);\n cacheSkips++;\n // Fall through to re-read and re-parse\n } else if (incremental) {\n // Try fingerprint-based cache check (avoid reading file)\n const cached = incremental.cache.peek(filePath);\n\n if (cached) {\n // Fast path: check fingerprint without reading file content\n const stats = yield* new OptionalFileStatEffect(filePath).run();\n\n if (stats) {\n const mtimeMs = stats.mtimeMs;\n const sizeBytes = stats.size;\n\n // If fingerprint matches, reuse cached snapshot\n if (cached.fingerprint.mtimeMs === mtimeMs && cached.fingerprint.sizeBytes === sizeBytes) {\n snapshots.set(filePath, cached);\n cacheHits++;\n // Enqueue dependencies from cache\n for (const dep of cached.dependencies) {\n if (dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n shouldReadFile = false;\n }\n }\n // If stats is null (file deleted), fall through to read attempt\n }\n }\n\n if (!shouldReadFile) {\n continue;\n }\n\n // Read source and compute signature\n const source = yield* new OptionalFileReadEffect(filePath).run();\n\n if (source === null) {\n // Handle deleted files gracefully - they may be in cache but removed from disk\n incremental?.cache.delete(filePath);\n invalidateFingerprint(filePath);\n continue;\n }\n\n const signature = createSourceHash(source);\n\n // Parse module\n const analysis = astAnalyzer.analyze({ filePath, source });\n cacheMisses++;\n\n // Build dependency records (relative + external) in a single pass\n const dependencies = extractModuleDependencies(analysis);\n\n // Enqueue all resolved relative dependencies for traversal\n for (const dep of dependencies) {\n if (!dep.isExternal && dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n\n // Get stats for fingerprint (we may already have them from cache check)\n const stats = (yield* new OptionalFileStatEffect(filePath).run()) as FileStats;\n\n // Compute fingerprint from content (avoids re-reading the file)\n const fingerprint = computeFingerprintFromContent(filePath, stats, source);\n\n // Create snapshot\n const snapshot: DiscoverySnapshot = {\n filePath,\n normalizedFilePath: normalizePath(filePath),\n signature,\n fingerprint,\n analyzer: astAnalyzer.type,\n createdAtMs: Date.now(),\n analysis,\n dependencies,\n };\n\n snapshots.set(filePath, snapshot);\n\n // Store in cache\n if (incremental) {\n incremental.cache.store(snapshot);\n }\n }\n\n return {\n snapshots: Array.from(snapshots.values()),\n cacheHits,\n cacheMisses,\n cacheSkips,\n };\n}\n\n/**\n * Discover and analyze all modules starting from entry points.\n * Uses AST parsing instead of RegExp for reliable dependency extraction.\n * Supports caching with fingerprint-based invalidation to skip re-parsing unchanged files.\n *\n * This function uses the synchronous scheduler internally for backward compatibility.\n * For async execution with parallel file I/O, use discoverModulesGen with an async scheduler.\n */\nexport const discoverModules = (options: DiscoverModulesOptions): BuilderResult<DiscoverModulesResult> => {\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n\n/**\n * Asynchronous version of discoverModules.\n * Uses async scheduler for parallel file I/O operations.\n *\n * This is useful for large codebases where parallel file operations can improve performance.\n */\nexport const discoverModulesAsync = async (options: DiscoverModulesOptions): Promise<BuilderResult<DiscoverModulesResult>> => {\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n","/**\n * Cross-runtime glob pattern matching abstraction\n * Provides a unified interface for glob operations across Bun and Node.js\n */\n\nimport fg from \"fast-glob\";\n\n/**\n * Scan files matching a glob pattern from the given directory\n * @param pattern - Glob pattern (e.g., \"src/**\\/*.ts\")\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns Array of matched file paths (relative to cwd)\n */\nexport const scanGlob = (pattern: string, cwd: string = process.cwd()): readonly string[] => {\n // Runtime detection: prefer Bun's native Glob when available for better performance\n if (typeof Bun !== \"undefined\" && Bun.Glob) {\n const { Glob } = Bun;\n const glob = new Glob(pattern);\n return Array.from(glob.scanSync(cwd));\n }\n\n // Node.js fallback: use fast-glob for cross-platform compatibility\n return fg.sync(pattern, { cwd, dot: true, onlyFiles: true });\n};\n","import { existsSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { err, ok } from \"neverthrow\";\n\nimport type { BuilderError } from \"../types\";\nimport { scanGlob } from \"../utils/glob\";\n\nconst scanEntries = (pattern: string): readonly string[] => {\n return scanGlob(pattern, process.cwd());\n};\n\n/**\n * Resolve entry file paths from glob patterns or direct paths.\n * Used by the discovery system to find entry points for module traversal.\n * All paths are normalized to POSIX format for consistent cache key matching.\n * Uses Node.js normalize() + backslash replacement to match normalizePath from @soda-gql/common.\n */\nexport const resolveEntryPaths = (entries: readonly string[]) => {\n const resolvedPaths = entries.flatMap((entry) => {\n const absolute = resolve(entry);\n if (existsSync(absolute)) {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return [normalize(absolute).replace(/\\\\/g, \"/\")];\n }\n\n const matches = scanEntries(entry).map((match) => {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return normalize(resolve(match)).replace(/\\\\/g, \"/\");\n });\n return matches;\n });\n\n if (resolvedPaths.length === 0) {\n return err<readonly string[], BuilderError>({\n code: \"ENTRY_NOT_FOUND\",\n message: `No entry files matched ${entries.join(\", \")}`,\n entry: entries.join(\", \"),\n });\n }\n\n return ok<readonly string[], BuilderError>(resolvedPaths);\n};\n","import { statSync } from \"node:fs\";\nimport { normalizePath } from \"@soda-gql/common\";\nimport { ok, type Result } from \"neverthrow\";\n\n/**\n * File metadata tracked for change detection.\n */\nexport type FileMetadata = {\n /** Modification time in milliseconds */\n mtimeMs: number;\n /** File size in bytes */\n size: number;\n};\n\n/**\n * Result of scanning current file system state.\n */\nexport type FileScan = {\n /** Map of normalized file paths to current metadata */\n files: Map<string, FileMetadata>;\n};\n\n/**\n * Detected file changes between two states.\n */\nexport type FileDiff = {\n /** Files present in current but not in previous */\n added: Set<string>;\n /** Files present in both but with changed metadata */\n updated: Set<string>;\n /** Files present in previous but not in current */\n removed: Set<string>;\n};\n\n/**\n * Errors that can occur during file tracking operations.\n */\nexport type TrackerError = { type: \"scan-failed\"; path: string; message: string };\n\n/**\n * File tracker interface for detecting file changes across builds.\n */\nexport interface FileTracker {\n /**\n * Scan current file system state for the given paths.\n * Gracefully skips files that don't exist or cannot be read.\n */\n scan(extraPaths: readonly string[]): Result<FileScan, TrackerError>;\n\n /**\n * Detect changes between previous and current file states.\n */\n detectChanges(): FileDiff;\n\n /**\n * Update the in-memory tracker state.\n * State persists only for the lifetime of this process.\n */\n update(scan: FileScan): void;\n}\n\n/**\n * Create a file tracker that maintains in-memory state for change detection.\n *\n * The tracker keeps file metadata (mtime, size) in memory during the process lifetime\n * and detects which files have been added, updated, or removed. State is scoped to\n * the process and does not persist across restarts.\n */\nexport const createFileTracker = (): FileTracker => {\n // In-memory state that persists for the lifetime of this tracker instance\n let currentScan: FileScan = {\n files: new Map(),\n };\n let nextScan: FileScan | null = null;\n\n const scan = (extraPaths: readonly string[]): Result<FileScan, TrackerError> => {\n const allPathsToScan = new Set([...extraPaths, ...currentScan.files.keys()]);\n const files = new Map<string, FileMetadata>();\n\n for (const path of allPathsToScan) {\n try {\n const normalized = normalizePath(path);\n const stats = statSync(normalized);\n\n files.set(normalized, {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {}\n }\n\n nextScan = { files };\n return ok(nextScan);\n };\n\n const detectChanges = (): FileDiff => {\n const previous = currentScan;\n const current = nextScan ?? currentScan;\n const added = new Set<string>();\n const updated = new Set<string>();\n const removed = new Set<string>();\n\n // Check for added and updated files\n for (const [path, currentMetadata] of current.files) {\n const previousMetadata = previous.files.get(path);\n\n if (!previousMetadata) {\n added.add(path);\n } else if (previousMetadata.mtimeMs !== currentMetadata.mtimeMs || previousMetadata.size !== currentMetadata.size) {\n updated.add(path);\n }\n }\n\n // Check for removed files\n for (const path of previous.files.keys()) {\n if (!current.files.has(path)) {\n removed.add(path);\n }\n }\n\n return { added, updated, removed };\n };\n\n const update = (scan: FileScan): void => {\n // Update in-memory state - promote nextScan to currentScan\n currentScan = scan;\n nextScan = null;\n };\n\n return {\n scan,\n detectChanges,\n update,\n };\n};\n\n/**\n * Check if a file diff is empty (no changes detected).\n */\nexport const isEmptyDiff = (diff: FileDiff): boolean => {\n return diff.added.size === 0 && diff.updated.size === 0 && diff.removed.size === 0;\n};\n","import { isRelativeSpecifier, resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\n\nexport type DependencyGraphError = {\n readonly code: \"MISSING_IMPORT\";\n readonly chain: readonly [importingFile: string, importSpecifier: string];\n};\n\nexport const validateModuleDependencies = ({\n analyses,\n graphqlSystemHelper,\n}: {\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemHelper: GraphqlSystemIdentifyHelper;\n}): Result<null, DependencyGraphError> => {\n for (const analysis of analyses.values()) {\n for (const { source, isTypeOnly } of analysis.imports) {\n if (isTypeOnly) {\n continue;\n }\n\n // Only check relative imports (project modules)\n if (isRelativeSpecifier(source)) {\n // Skip graphql-system imports - they are not part of the analyzed modules\n if (graphqlSystemHelper.isGraphqlSystemImportSpecifier({ filePath: analysis.filePath, specifier: source })) {\n continue;\n }\n\n const resolvedModule = resolveRelativeImportWithReferences({\n filePath: analysis.filePath,\n specifier: source,\n references: analyses,\n });\n if (!resolvedModule) {\n // Import points to a module that doesn't exist in the analysis\n return err({\n code: \"MISSING_IMPORT\" as const,\n chain: [analysis.filePath, source] as const,\n });\n }\n }\n }\n }\n\n return ok(null);\n};\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { DiscoverySnapshot } from \"../discovery\";\n\n/**\n * Extract module-level adjacency from dependency graph.\n * Returns Map of file path -> set of files that import it.\n * All paths are normalized to POSIX format for consistent cache key matching.\n */\nexport const extractModuleAdjacency = ({\n snapshots,\n}: {\n snapshots: Map<string, DiscoverySnapshot>;\n}): Map<string, Set<string>> => {\n const importsByModule = new Map<string, Set<string>>();\n\n for (const snapshot of snapshots.values()) {\n const { normalizedFilePath, dependencies, analysis } = snapshot;\n const imports = new Set<string>();\n\n // Extract module paths from canonical IDs in dependencies\n for (const { resolvedPath } of dependencies) {\n if (resolvedPath && resolvedPath !== normalizedFilePath && snapshots.has(resolvedPath)) {\n imports.add(resolvedPath);\n }\n }\n\n // Phase 3: Handle runtime imports for modules with no tracked dependencies\n if (dependencies.length === 0 && analysis.imports.length > 0) {\n for (const imp of analysis.imports) {\n if (imp.isTypeOnly) {\n continue;\n }\n\n const resolved = resolveRelativeImportWithReferences({\n filePath: normalizedFilePath,\n specifier: imp.source,\n references: snapshots,\n });\n if (resolved) {\n imports.add(resolved);\n }\n }\n }\n\n if (imports.size > 0) {\n importsByModule.set(normalizedFilePath, imports);\n }\n }\n\n // Phase 4: Invert to adjacency map (imported -> [importers])\n const adjacency = new Map<string, Set<string>>();\n\n for (const [importer, imports] of importsByModule) {\n for (const imported of imports) {\n if (!adjacency.has(imported)) {\n adjacency.set(imported, new Set());\n }\n adjacency.get(imported)?.add(importer);\n }\n }\n\n // Include all modules, even isolated ones with no importers\n for (const modulePath of snapshots.keys()) {\n if (!adjacency.has(modulePath)) {\n adjacency.set(modulePath, new Set());\n }\n }\n\n return adjacency;\n};\n\n/**\n * Collect all modules affected by changes, including transitive dependents.\n * Uses BFS to traverse module adjacency graph.\n * All paths are already normalized from extractModuleAdjacency.\n */\nexport const collectAffectedFiles = (input: {\n changedFiles: Set<string>;\n removedFiles: Set<string>;\n previousModuleAdjacency: Map<string, Set<string>>;\n}): Set<string> => {\n const { changedFiles, removedFiles, previousModuleAdjacency } = input;\n const affected = new Set<string>([...changedFiles, ...removedFiles]);\n const queue = [...changedFiles];\n const visited = new Set<string>(changedFiles);\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break;\n\n const dependents = previousModuleAdjacency.get(current);\n\n if (dependents) {\n for (const dependent of dependents) {\n if (!visited.has(dependent)) {\n visited.add(dependent);\n affected.add(dependent);\n queue.push(dependent);\n }\n }\n }\n }\n\n return affected;\n};\n","import { join, resolve } from \"node:path\";\nimport { cachedFn, createAsyncScheduler, createSyncScheduler, type EffectGenerator, type SchedulerError } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { type BuilderArtifact, buildArtifact } from \"../artifact\";\nimport { createAstAnalyzer, type ModuleAnalysis } from \"../ast\";\nimport { createMemoryCache } from \"../cache/memory-cache\";\nimport {\n createDiscoveryCache,\n type DiscoveryCache,\n type DiscoverySnapshot,\n discoverModulesGen,\n type ModuleLoadStats,\n resolveEntryPaths,\n} from \"../discovery\";\nimport { builderErrors } from \"../errors\";\nimport {\n evaluateIntermediateModulesGen,\n generateIntermediateModules,\n type IntermediateArtifactElement,\n type IntermediateModule,\n} from \"../intermediate-module\";\nimport { createGraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport { createFileTracker, type FileDiff, type FileScan, isEmptyDiff } from \"../tracker\";\nimport type { BuilderError } from \"../types\";\nimport { validateModuleDependencies } from \"./dependency-validation\";\nimport { collectAffectedFiles, extractModuleAdjacency } from \"./module-adjacency\";\n\n/**\n * Session state maintained across incremental builds.\n */\ntype SessionState = {\n /** Generation number */\n gen: number;\n /** Discovery snapshots keyed by normalized file path */\n snapshots: Map<string, DiscoverySnapshot>;\n /** Module-level adjacency: file -> files that import it */\n moduleAdjacency: Map<string, Set<string>>;\n /** Written intermediate modules: filePath -> intermediate module */\n intermediateModules: Map<string, IntermediateModule>;\n /** Last successful artifact */\n lastArtifact: BuilderArtifact | null;\n};\n\n/**\n * Input for the unified build generator.\n */\ntype BuildGenInput = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n readonly discoveryCache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly previousModuleAdjacency: Map<string, Set<string>>;\n readonly previousIntermediateModules: ReadonlyMap<string, IntermediateModule>;\n readonly graphqlSystemPath: string;\n readonly graphqlHelper: ReturnType<typeof createGraphqlSystemIdentifyHelper>;\n};\n\n/**\n * Result from the unified build generator.\n */\ntype BuildGenResult = {\n readonly snapshots: Map<string, DiscoverySnapshot>;\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly currentModuleAdjacency: Map<string, Set<string>>;\n readonly intermediateModules: Map<string, IntermediateModule>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n readonly stats: ModuleLoadStats;\n};\n\n/**\n * Builder session interface for incremental builds.\n */\nexport interface BuilderSession {\n /**\n * Perform build fully or incrementally (synchronous).\n * The session automatically detects file changes using the file tracker.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n build(options?: { force?: boolean }): Result<BuilderArtifact, BuilderError>;\n /**\n * Perform build fully or incrementally (asynchronous).\n * The session automatically detects file changes using the file tracker.\n * Supports async metadata factories and parallel element evaluation.\n */\n buildAsync(options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>>;\n /**\n * Get the current generation number.\n */\n getGeneration(): number;\n /**\n * Get the current artifact.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n /**\n * Dispose the session and save cache to disk.\n */\n dispose(): void;\n}\n\n/**\n * Create a new builder session.\n *\n * The session maintains in-memory state across builds to enable incremental processing.\n */\nexport const createBuilderSession = (options: {\n readonly evaluatorId?: string;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n readonly config: ResolvedSodaGqlConfig;\n}): BuilderSession => {\n const config = options.config;\n const evaluatorId = options.evaluatorId ?? \"default\";\n const entrypoints: ReadonlySet<string> = new Set(options.entrypointsOverride ?? config.include);\n\n // Session state stored in closure\n const state: SessionState = {\n gen: 0,\n snapshots: new Map(),\n moduleAdjacency: new Map(),\n intermediateModules: new Map(),\n lastArtifact: null,\n };\n\n // Reusable infrastructure\n const cacheFactory = createMemoryCache({\n prefix: [\"builder\"],\n persistence: {\n enabled: true,\n filePath: join(process.cwd(), \".cache\", \"soda-gql\", \"builder\", \"cache.json\"),\n },\n });\n\n // Auto-save cache on process exit\n process.on(\"beforeExit\", () => {\n cacheFactory.save();\n });\n\n const graphqlHelper = createGraphqlSystemIdentifyHelper(config);\n const ensureAstAnalyzer = cachedFn(() =>\n createAstAnalyzer({\n analyzer: config.analyzer,\n graphqlHelper,\n }),\n );\n const ensureDiscoveryCache = cachedFn(() =>\n createDiscoveryCache({\n factory: cacheFactory,\n analyzer: config.analyzer,\n evaluatorId,\n }),\n );\n const ensureFileTracker = cachedFn(() => createFileTracker());\n\n /**\n * Prepare build input. Shared between sync and async builds.\n * Returns either a skip result or the input for buildGen.\n */\n const prepareBuildInput = (\n force: boolean,\n ): Result<\n { type: \"skip\"; artifact: BuilderArtifact } | { type: \"build\"; input: BuildGenInput; currentScan: FileScan },\n BuilderError\n > => {\n // 1. Resolve entry paths\n const entryPathsResult = resolveEntryPaths(Array.from(entrypoints));\n if (entryPathsResult.isErr()) {\n return err(entryPathsResult.error);\n }\n const entryPaths = entryPathsResult.value;\n\n // 2. Load tracker and detect changes\n const tracker = ensureFileTracker();\n const scanResult = tracker.scan(entryPaths);\n if (scanResult.isErr()) {\n const trackerError = scanResult.error;\n return err(\n builderErrors.discoveryIOError(\n trackerError.type === \"scan-failed\" ? trackerError.path : \"unknown\",\n `Failed to scan files: ${trackerError.message}`,\n ),\n );\n }\n\n // 3. Scan current files (entry paths + previously tracked files)\n const currentScan = scanResult.value;\n const diff = tracker.detectChanges();\n\n // 4. Prepare for build\n const prepareResult = prepare({\n diff,\n entryPaths,\n lastArtifact: state.lastArtifact,\n force,\n });\n if (prepareResult.isErr()) {\n return err(prepareResult.error);\n }\n\n if (prepareResult.value.type === \"should-skip\") {\n return ok({ type: \"skip\", artifact: prepareResult.value.data.artifact });\n }\n\n const { changedFiles, removedFiles } = prepareResult.value.data;\n\n return ok({\n type: \"build\",\n input: {\n entryPaths,\n astAnalyzer: ensureAstAnalyzer(),\n discoveryCache: ensureDiscoveryCache(),\n changedFiles,\n removedFiles,\n previousModuleAdjacency: state.moduleAdjacency,\n previousIntermediateModules: state.intermediateModules,\n graphqlSystemPath: resolve(config.outdir, \"index.ts\"),\n graphqlHelper,\n },\n currentScan,\n });\n };\n\n /**\n * Finalize build and update session state.\n */\n const finalizeBuild = (genResult: BuildGenResult, currentScan: FileScan): Result<BuilderArtifact, BuilderError> => {\n const { snapshots, analyses, currentModuleAdjacency, intermediateModules, elements, stats } = genResult;\n\n // Build artifact from all intermediate modules\n const artifactResult = buildArtifact({\n analyses,\n elements,\n stats,\n });\n\n if (artifactResult.isErr()) {\n return err(artifactResult.error);\n }\n\n // Update session state\n state.gen++;\n state.snapshots = snapshots;\n state.moduleAdjacency = currentModuleAdjacency;\n state.lastArtifact = artifactResult.value;\n state.intermediateModules = intermediateModules;\n\n // Persist tracker state (soft failure - don't block on cache write)\n ensureFileTracker().update(currentScan);\n\n return ok(artifactResult.value);\n };\n\n /**\n * Synchronous build using SyncScheduler.\n * Throws if any element requires async operations.\n */\n const build = (options?: { force?: boolean }): Result<BuilderArtifact, BuilderError> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createSyncScheduler();\n\n try {\n const result = scheduler.run(() => buildGen(input));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (error && typeof error === \"object\" && \"code\" in error) {\n return err(error as BuilderError);\n }\n throw error;\n }\n };\n\n /**\n * Asynchronous build using AsyncScheduler.\n * Supports async metadata factories and parallel element evaluation.\n */\n const buildAsync = async (options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createAsyncScheduler();\n\n try {\n const result = await scheduler.run(() => buildGen(input));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (error && typeof error === \"object\" && \"code\" in error) {\n return err(error as BuilderError);\n }\n throw error;\n }\n };\n\n return {\n build,\n buildAsync,\n getGeneration: () => state.gen,\n getCurrentArtifact: () => state.lastArtifact,\n dispose: () => {\n cacheFactory.save();\n },\n };\n};\n\nconst prepare = (input: {\n diff: FileDiff;\n entryPaths: readonly string[];\n lastArtifact: BuilderArtifact | null;\n force: boolean;\n}) => {\n const { diff, lastArtifact, force } = input;\n\n // Convert diff to sets for discovery\n const changedFiles = new Set<string>([...diff.added, ...diff.updated]);\n const removedFiles = diff.removed;\n\n // Skip build only if:\n // 1. Not forced\n // 2. No changes detected\n // 3. Previous artifact exists\n if (!force && isEmptyDiff(diff) && lastArtifact) {\n return ok({ type: \"should-skip\" as const, data: { artifact: lastArtifact } });\n }\n\n return ok({ type: \"should-build\" as const, data: { changedFiles, removedFiles } });\n};\n\n/**\n * Unified build generator that yields effects for file I/O and element evaluation.\n * This enables single scheduler control at the root level for both sync and async execution.\n */\nfunction* buildGen(input: BuildGenInput): EffectGenerator<BuildGenResult> {\n const {\n entryPaths,\n astAnalyzer,\n discoveryCache,\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n previousIntermediateModules,\n graphqlSystemPath,\n graphqlHelper,\n } = input;\n\n // Phase 1: Collect affected files\n const affectedFiles = collectAffectedFiles({\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n });\n\n // Phase 2: Discovery (yields file I/O effects)\n const discoveryResult = yield* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n incremental: {\n cache: discoveryCache,\n changedFiles,\n removedFiles,\n affectedFiles,\n },\n });\n\n const { cacheHits, cacheMisses, cacheSkips } = discoveryResult;\n\n const snapshots = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot]));\n const analyses = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot.analysis]));\n\n // Phase 3: Validate module dependencies (pure computation)\n const dependenciesValidationResult = validateModuleDependencies({ analyses, graphqlSystemHelper: graphqlHelper });\n if (dependenciesValidationResult.isErr()) {\n const error = dependenciesValidationResult.error;\n throw builderErrors.graphMissingImport(error.chain[0], error.chain[1]);\n }\n\n const currentModuleAdjacency = extractModuleAdjacency({ snapshots });\n\n const stats: ModuleLoadStats = {\n hits: cacheHits,\n misses: cacheMisses,\n skips: cacheSkips,\n };\n\n // Phase 4: Generate intermediate modules (pure computation)\n const intermediateModules = new Map(previousIntermediateModules);\n\n // Build target set: include affected files + any newly discovered files that haven't been built yet\n const targetFiles = new Set(affectedFiles);\n for (const filePath of analyses.keys()) {\n if (!previousIntermediateModules.has(filePath)) {\n targetFiles.add(filePath);\n }\n }\n // If no targets identified (e.g., first build with no changes), build everything\n if (targetFiles.size === 0) {\n for (const filePath of analyses.keys()) {\n targetFiles.add(filePath);\n }\n }\n\n // Remove deleted intermediate modules from next map immediately\n for (const targetFilePath of targetFiles) {\n intermediateModules.delete(targetFilePath);\n }\n\n // Build and write affected intermediate modules\n for (const intermediateModule of generateIntermediateModules({ analyses, targetFiles, graphqlSystemPath })) {\n intermediateModules.set(intermediateModule.filePath, intermediateModule);\n }\n\n // Phase 5: Evaluate intermediate modules (yields element evaluation effects)\n const elements = yield* evaluateIntermediateModulesGen({ intermediateModules, graphqlSystemPath, analyses });\n\n return {\n snapshots,\n analyses,\n currentModuleAdjacency,\n intermediateModules,\n elements,\n stats,\n };\n}\n\n/**\n * Convert scheduler error to builder error.\n * If the cause is already a BuilderError, return it directly to preserve error codes.\n */\nconst convertSchedulerError = (error: SchedulerError): BuilderError => {\n // If the cause is a BuilderError, return it directly\n if (error.cause && typeof error.cause === \"object\" && \"code\" in error.cause) {\n return error.cause as BuilderError;\n }\n return builderErrors.internalInvariant(error.message, \"scheduler\", error.cause);\n};\n","import type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport type { Result } from \"neverthrow\";\nimport type { BuilderArtifact } from \"./artifact/types\";\nimport { createBuilderSession } from \"./session\";\nimport type { BuilderError } from \"./types\";\n\n/**\n * Configuration for BuilderService.\n * Mirrors BuilderInput shape.\n */\nexport type BuilderServiceConfig = {\n readonly config: ResolvedSodaGqlConfig;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n};\n\n/**\n * Builder service interface providing artifact generation.\n */\nexport interface BuilderService {\n /**\n * Generate artifacts from configured entry points (synchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Throws if any element requires async operations (e.g., async metadata factory).\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Result containing BuilderArtifact on success or BuilderError on failure.\n */\n build(options?: { force?: boolean }): Result<BuilderArtifact, BuilderError>;\n\n /**\n * Generate artifacts from configured entry points (asynchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Supports async metadata factories and parallel element evaluation.\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Promise of Result containing BuilderArtifact on success or BuilderError on failure.\n */\n buildAsync(options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>>;\n\n /**\n * Get the current generation number of the artifact.\n * Increments on each successful build.\n * Returns 0 if no artifact has been built yet.\n */\n getGeneration(): number;\n\n /**\n * Get the most recent artifact without triggering a new build.\n * Returns null if no artifact has been built yet.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n\n /**\n * Dispose the service and save cache to disk.\n * Should be called when the service is no longer needed.\n */\n dispose(): void;\n}\n\n/**\n * Create a builder service instance with session support.\n *\n * The service maintains a long-lived session for incremental builds.\n * File changes are automatically detected using an internal file tracker.\n * First build() call initializes the session, subsequent calls perform\n * incremental builds based on detected file changes.\n *\n * Note: Empty entry arrays will produce ENTRY_NOT_FOUND errors at build time.\n *\n * @param config - Builder configuration including entry patterns, analyzer, mode, and optional debugDir\n * @returns BuilderService instance\n */\nexport const createBuilderService = ({ config, entrypointsOverride }: BuilderServiceConfig): BuilderService => {\n const session = createBuilderSession({ config, entrypointsOverride });\n\n return {\n build: (options) => session.build(options),\n buildAsync: (options) => session.buildAsync(options),\n getGeneration: () => session.getGeneration(),\n getCurrentArtifact: () => session.getCurrentArtifact(),\n dispose: () => session.dispose(),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,iBAAb,cAAoCA,yBAAe;CACjD,YAAY,AAASC,MAAc;AACjC,SAAO;EADY;;CAIrB,AAAU,eAAuB;AAC/B,mCAAoB,KAAK,MAAM,QAAQ;;CAGzC,AAAU,gBAAiC;AACzC,wCAAgB,KAAK,MAAM,QAAQ;;;;;;;;;;AAWvC,IAAa,iBAAb,cAAoCD,yBAAkB;CACpD,YAAY,AAASC,MAAc;AACjC,SAAO;EADY;;CAIrB,AAAU,eAA0B;EAClC,MAAM,8BAAiB,KAAK,KAAK;AACjC,SAAO;GACL,SAAS,MAAM;GACf,MAAM,MAAM;GACZ,QAAQ,MAAM,QAAQ;GACvB;;CAGH,MAAgB,gBAAoC;EAClD,MAAM,QAAQ,iCAAW,KAAK,KAAK;AACnC,SAAO;GACL,SAAS,MAAM;GACf,MAAM,MAAM;GACZ,QAAQ,MAAM,QAAQ;GACvB;;;;;;;AAQL,IAAa,yBAAb,cAA4CD,yBAAsB;CAChE,YAAY,AAASC,MAAc;AACjC,SAAO;EADY;;CAIrB,AAAU,eAA8B;AACtC,MAAI;AACF,oCAAoB,KAAK,MAAM,QAAQ;WAChC,OAAO;AACd,OAAK,MAAgC,SAAS,UAAU;AACtD,WAAO;;AAET,SAAM;;;CAIV,MAAgB,gBAAwC;AACtD,MAAI;AACF,UAAO,qCAAe,KAAK,MAAM,QAAQ;WAClC,OAAO;AACd,OAAK,MAAgC,SAAS,UAAU;AACtD,WAAO;;AAET,SAAM;;;;;;;;AASZ,IAAa,yBAAb,cAA4CD,yBAAyB;CACnE,YAAY,AAASC,MAAc;AACjC,SAAO;EADY;;CAIrB,AAAU,eAAiC;AACzC,MAAI;GACF,MAAM,8BAAiB,KAAK,KAAK;AACjC,UAA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