@soda-gql/builder 0.11.11 → 0.11.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/plugin-support.cjs +1 -1
- package/dist/plugin-support.d.cts +1 -1
- package/dist/plugin-support.d.mts +1 -1
- package/dist/plugin-support.mjs +1 -1
- package/dist/{service-BCL5TzS7.cjs → service-ByiDYWPX.cjs} +9 -1
- package/dist/service-ByiDYWPX.cjs.map +1 -0
- package/dist/{service-FWWXRFCK.d.mts → service-Do9da7Cm.d.mts} +5 -2
- package/dist/service-Do9da7Cm.d.mts.map +1 -0
- package/dist/{service-sD5URKvq.mjs → service-Xz1_XYDb.mjs} +10 -2
- package/dist/service-Xz1_XYDb.mjs.map +1 -0
- package/dist/{service-BkxH32kl.d.cts → service-vzMbq7Pe.d.cts} +5 -2
- package/dist/service-vzMbq7Pe.d.cts.map +1 -0
- package/package.json +4 -4
- package/dist/service-BCL5TzS7.cjs.map +0 -1
- package/dist/service-BkxH32kl.d.cts.map +0 -1
- package/dist/service-FWWXRFCK.d.mts.map +0 -1
- package/dist/service-sD5URKvq.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-Xz1_XYDb.mjs","names":["content: string","parsed: unknown","diagnosticMessages: Record<DiagnosticCode, (ctx?: MessageContext) => string>","lines: string[]","errorHints: Partial<Record<BuilderErrorCode, string>>","base: FormattedError","lines: string[]","path: string","element: AcceptableArtifact","moduleExports: Record<string, unknown>","sandbox: CjsSandbox","declarations: string[]","returnEntries: string[]","importLines: string[]","filePath","stack: EvaluationFrame[]","frame: EvaluationFrame | undefined","result","artifacts: Record<string, IntermediateArtifactElement>","cachedGql: unknown","cachedModulePath: string | null","metadata: BuilderArtifactElementMetadata","collectImports","imports: ModuleImport[]","collectExports","exports: ModuleExport[]","unwrapMethodChains","collectAllDefinitions","getPropertyName","pending: PendingDefinition[]","handledCalls: CallExpression[]","frame: ScopeFrame","anonymousScopeHandle: ScopeHandle | undefined","exportBinding: string | undefined","getLocation","collectImportDiagnostics","diagnostics: ModuleDiagnostic[]","containsGqlIdentifier","getArgumentType","collectCallDiagnostics","checkCallExpression","object","collectClassPropertyDiagnostics","swcAdapter: AnalyzerAdapter","imports: ModuleImport[]","exports: ModuleExport[]","pending: PendingDefinition[]","handledCalls: ts.CallExpression[]","frame: ScopeFrame","anonymousScopeHandle: ScopeHandle | undefined","exportBinding: string | undefined","diagnostics: ModuleDiagnostic[]","baseExpr","typescriptAdapter: AnalyzerAdapter","inputWithBaseDir: AnalyzeModuleInput","parsed: unknown","envelope: Envelope<V>","serialized: Record<string, Array<[string, Envelope<unknown>]>>","data: PersistedData","xxhashInstance: XXHashAPI | null","fingerprint: FileFingerprint","stats","analysis: ModuleAnalysis","snapshot: DiscoverySnapshot","directPaths: string[]","globPatterns: string[]","currentScan: FileScan","nextScan: FileScan | null","scan","entrypoints: ReadonlySet<string>","state: SessionState","options","stats: ModuleLoadStats"],"sources":["../src/schemas/artifact.ts","../src/artifact/loader.ts","../src/ast/common/detection.ts","../src/errors.ts","../src/errors/formatter.ts","../src/scheduler/effects.ts","../src/vm/sandbox.ts","../src/intermediate-module/codegen.ts","../src/intermediate-module/registry.ts","../src/intermediate-module/evaluation.ts","../src/internal/graphql-system.ts","../src/artifact/canonical-id-utils.ts","../src/artifact/aggregate.ts","../src/artifact/issue-handler.ts","../src/artifact/builder.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 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 schemaLabel: 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 key: z.string().optional(),\n schemaLabel: 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\nconst BuilderArtifactMetaSchema = z.object({\n version: z.string(),\n createdAt: z.string(),\n});\n\nexport const BuilderArtifactSchema = z.object({\n meta: BuilderArtifactMetaSchema.optional(),\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 { existsSync, readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { BuilderArtifactSchema } from \"../schemas/artifact\";\nimport type { BuilderArtifact } from \"./types\";\n\n/**\n * Error codes for artifact loading failures.\n */\nexport type ArtifactLoadErrorCode = \"ARTIFACT_NOT_FOUND\" | \"ARTIFACT_PARSE_ERROR\" | \"ARTIFACT_VALIDATION_ERROR\";\n\n/**\n * Error type for artifact loading operations.\n */\nexport type ArtifactLoadError = {\n readonly code: ArtifactLoadErrorCode;\n readonly message: string;\n readonly filePath?: string;\n};\n\n/**\n * Load a pre-built artifact from a JSON file asynchronously.\n *\n * @param path - Absolute path to the artifact JSON file\n * @returns Result with the parsed artifact or an error\n *\n * @example\n * ```ts\n * const result = await loadArtifact(\"/path/to/artifact.json\");\n * if (result.isOk()) {\n * const artifact = result.value;\n * // Use artifact...\n * }\n * ```\n */\nexport const loadArtifact = async (path: string): Promise<Result<BuilderArtifact, ArtifactLoadError>> => {\n if (!existsSync(path)) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Artifact file not found: ${path}`,\n filePath: path,\n });\n }\n\n let content: string;\n try {\n content = await readFile(path, \"utf-8\");\n } catch (error) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath: path,\n });\n }\n\n return parseAndValidateArtifact(content, path);\n};\n\n/**\n * Load a pre-built artifact from a JSON file synchronously.\n *\n * @param path - Absolute path to the artifact JSON file\n * @returns Result with the parsed artifact or an error\n *\n * @example\n * ```ts\n * const result = loadArtifactSync(\"/path/to/artifact.json\");\n * if (result.isOk()) {\n * const artifact = result.value;\n * // Use artifact...\n * }\n * ```\n */\nexport const loadArtifactSync = (path: string): Result<BuilderArtifact, ArtifactLoadError> => {\n if (!existsSync(path)) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Artifact file not found: ${path}`,\n filePath: path,\n });\n }\n\n let content: string;\n try {\n content = readFileSync(path, \"utf-8\");\n } catch (error) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath: path,\n });\n }\n\n return parseAndValidateArtifact(content, path);\n};\n\n/**\n * Parse JSON content and validate against BuilderArtifactSchema.\n */\nfunction parseAndValidateArtifact(content: string, filePath: string): Result<BuilderArtifact, ArtifactLoadError> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n return err({\n code: \"ARTIFACT_PARSE_ERROR\",\n message: `Invalid JSON in artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath,\n });\n }\n\n const validated = BuilderArtifactSchema.safeParse(parsed);\n if (!validated.success) {\n return err({\n code: \"ARTIFACT_VALIDATION_ERROR\",\n message: `Invalid artifact structure: ${validated.error.message}`,\n filePath,\n });\n }\n\n // Cast to BuilderArtifact since Zod schema validates the structure\n // but TypeScript can't infer the exact runtime types (e.g., RuntimeOperationInput)\n return ok(validated.data as BuilderArtifact);\n}\n","/**\n * Shared detection utilities for identifying invalid gql patterns.\n * Used by both TypeScript and SWC adapters, and exported for formatter consumption.\n */\n\nimport type { DiagnosticCode, DiagnosticLocation, DiagnosticSeverity, ModuleDiagnostic } from \"../types\";\n\n// ============================================================================\n// Diagnostic Factory\n// ============================================================================\n\n/**\n * Configuration for creating a diagnostic\n */\nexport type DiagnosticConfig = {\n readonly code: DiagnosticCode;\n readonly message: string;\n readonly location: DiagnosticLocation;\n readonly context?: Readonly<Record<string, string>>;\n};\n\n/**\n * Create a diagnostic with appropriate severity\n */\nexport const createDiagnostic = (config: DiagnosticConfig): ModuleDiagnostic => ({\n code: config.code,\n severity: getSeverity(config.code),\n message: config.message,\n location: config.location,\n context: config.context,\n});\n\n// ============================================================================\n// Severity Classification\n// ============================================================================\n\n/**\n * Get severity for a diagnostic code.\n * - \"error\": Code will definitely not work\n * - \"warning\": Code might work but is unsupported/unreliable\n */\nexport const getSeverity = (code: DiagnosticCode): DiagnosticSeverity => {\n switch (code) {\n // Errors: code will definitely not work\n case \"MISSING_ARGUMENT\":\n case \"INVALID_ARGUMENT_TYPE\":\n case \"NON_MEMBER_CALLEE\":\n case \"OPTIONAL_CHAINING\":\n case \"SPREAD_ARGUMENT\":\n return \"error\";\n\n // Warnings: code might work but is unsupported\n case \"RENAMED_IMPORT\":\n case \"STAR_IMPORT\":\n case \"DEFAULT_IMPORT\":\n case \"COMPUTED_PROPERTY\":\n case \"DYNAMIC_CALLEE\":\n case \"CLASS_PROPERTY\":\n case \"EXTRA_ARGUMENTS\":\n return \"warning\";\n }\n};\n\n// ============================================================================\n// Message Templates\n// ============================================================================\n\ntype MessageContext = Readonly<Record<string, string>>;\n\n/**\n * Diagnostic message templates for each code\n */\nexport const diagnosticMessages: Record<DiagnosticCode, (ctx?: MessageContext) => string> = {\n // Import-level\n RENAMED_IMPORT: (ctx) => `Import alias \"${ctx?.importedAs ?? \"?\"}\" not recognized - use \"import { gql } from ...\"`,\n STAR_IMPORT: (ctx) => `Namespace import \"${ctx?.namespaceAlias ?? \"?\"}\" not fully supported - use named import`,\n DEFAULT_IMPORT: () => `Default import not supported - use \"import { gql } from ...\"`,\n\n // Call-level\n MISSING_ARGUMENT: () => `gql definition requires a factory function argument`,\n INVALID_ARGUMENT_TYPE: (ctx) => `Expected arrow function, got ${ctx?.actualType ?? \"unknown\"}`,\n NON_MEMBER_CALLEE: () => `Cannot call gql directly - use gql.schemaName(...)`,\n COMPUTED_PROPERTY: () => `Computed property access not supported - use gql.schemaName(...)`,\n DYNAMIC_CALLEE: () => `Dynamic callee expression not supported`,\n OPTIONAL_CHAINING: () => `Optional chaining on gql not supported - use gql.schemaName(...) directly`,\n EXTRA_ARGUMENTS: (ctx) =>\n `gql definition only accepts one argument, ${ctx?.extraCount ?? \"extra\"} additional argument(s) ignored`,\n SPREAD_ARGUMENT: () => `Spread arguments not supported - use arrow function directly`,\n\n // Scope-level\n CLASS_PROPERTY: () => `Class property definitions may have inconsistent scope tracking`,\n};\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a diagnostic with a standard message\n */\nexport const createStandardDiagnostic = (\n code: DiagnosticCode,\n location: DiagnosticLocation,\n context?: MessageContext,\n): ModuleDiagnostic => {\n return createDiagnostic({\n code,\n message: diagnosticMessages[code](context),\n location,\n context,\n });\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 | \"ELEMENT_EVALUATION_FAILED\"\n // Internal invariant violations\n | \"INTERNAL_INVARIANT\"\n // Schema validation errors\n | \"SCHEMA_NOT_FOUND\";\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 | {\n readonly code: \"ELEMENT_EVALUATION_FAILED\";\n readonly message: string;\n readonly modulePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n // Internal invariant\n | {\n readonly code: \"INTERNAL_INVARIANT\";\n readonly message: string;\n readonly context?: string;\n readonly cause?: unknown;\n }\n // Schema validation\n | {\n readonly code: \"SCHEMA_NOT_FOUND\";\n readonly message: string;\n readonly schemaLabel: string;\n readonly canonicalId: string;\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 elementEvaluationFailed: (modulePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"ELEMENT_EVALUATION_FAILED\",\n message,\n modulePath,\n astPath,\n cause,\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\n schemaNotFound: (schemaLabel: string, canonicalId: string): BuilderError => ({\n code: \"SCHEMA_NOT_FOUND\",\n message: `Schema not found for label \"${schemaLabel}\" (element: ${canonicalId})`,\n schemaLabel,\n canonicalId,\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 \"ELEMENT_EVALUATION_FAILED\":\n lines.push(` at ${error.modulePath}`);\n if (error.astPath) {\n lines.push(` in ${error.astPath}`);\n }\n break;\n case \"INTERNAL_INVARIANT\":\n if (error.context) {\n lines.push(` Context: ${error.context}`);\n }\n break;\n case \"SCHEMA_NOT_FOUND\":\n lines.push(` Schema label: ${error.schemaLabel}`);\n lines.push(` Element: ${error.canonicalId}`);\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","import type { BuilderError, BuilderErrorCode } from \"../errors\";\n\n/**\n * Hints for each error code to help users understand and fix issues.\n */\nconst errorHints: Partial<Record<BuilderErrorCode, string>> = {\n ELEMENT_EVALUATION_FAILED: \"Check if all imported fragments are properly exported and included in entry patterns.\",\n GRAPH_CIRCULAR_DEPENDENCY: \"Break the circular import by extracting shared types to a common module.\",\n GRAPH_MISSING_IMPORT: \"Verify the import path exists and the module is included in entry patterns.\",\n RUNTIME_MODULE_LOAD_FAILED: \"Ensure the module can be imported and all dependencies are installed.\",\n CONFIG_NOT_FOUND: \"Create a soda-gql.config.ts file in your project root.\",\n CONFIG_INVALID: \"Check your configuration file for syntax errors or invalid options.\",\n ENTRY_NOT_FOUND: \"Verify the entry pattern matches your file structure.\",\n INTERNAL_INVARIANT: \"This is an internal error. Please report it at https://github.com/soda-gql/soda-gql/issues\",\n};\n\n/**\n * Formatted error with structured information for display.\n */\nexport type FormattedError = {\n readonly code: BuilderErrorCode;\n readonly message: string;\n readonly location?: {\n readonly modulePath: string;\n readonly astPath?: string;\n };\n readonly hint?: string;\n readonly relatedFiles?: readonly string[];\n readonly cause?: unknown;\n};\n\n/**\n * Format a BuilderError into a structured FormattedError object.\n */\nexport const formatBuilderErrorStructured = (error: BuilderError): FormattedError => {\n const base: FormattedError = {\n code: error.code,\n message: error.message,\n hint: errorHints[error.code],\n cause: \"cause\" in error ? error.cause : undefined,\n };\n\n switch (error.code) {\n case \"ELEMENT_EVALUATION_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.modulePath,\n astPath: error.astPath || undefined,\n },\n };\n\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.filePath,\n astPath: error.astPath,\n },\n };\n\n case \"GRAPH_MISSING_IMPORT\":\n return {\n ...base,\n relatedFiles: [error.importer, error.importee],\n };\n\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n return {\n ...base,\n relatedFiles: error.chain,\n };\n\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n return {\n ...base,\n location: {\n modulePath: error.path,\n },\n };\n\n case \"FINGERPRINT_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.filePath,\n },\n };\n\n case \"DISCOVERY_IO_ERROR\":\n return {\n ...base,\n location: {\n modulePath: error.path,\n },\n };\n\n default:\n return base;\n }\n};\n\n/**\n * Format a BuilderError for CLI/stderr output with human-readable formatting.\n * Includes location, hint, and related files when available.\n */\nexport const formatBuilderErrorForCLI = (error: BuilderError): string => {\n const formatted = formatBuilderErrorStructured(error);\n const lines: string[] = [];\n\n // Header with error code and message\n lines.push(`Error [${formatted.code}]: ${formatted.message}`);\n\n // Location information\n if (formatted.location) {\n lines.push(` at ${formatted.location.modulePath}`);\n if (formatted.location.astPath) {\n lines.push(` in ${formatted.location.astPath}`);\n }\n }\n\n // Hint for fixing the issue\n if (formatted.hint) {\n lines.push(\"\");\n lines.push(` Hint: ${formatted.hint}`);\n }\n\n // Related files (for dependency errors)\n if (formatted.relatedFiles && formatted.relatedFiles.length > 0) {\n lines.push(\"\");\n lines.push(\" Related files:\");\n for (const file of formatted.relatedFiles) {\n lines.push(` - ${file}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { Effect, Effects, parseCanonicalId } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyGqlDefine, type AnyOperation, GqlElement } from \"@soda-gql/core\";\nimport { builderErrors } from \"../errors\";\n\ntype AcceptableArtifact = AnyFragment | AnyOperation | AnyGqlDefine;\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 * Wraps errors with module context for better debugging.\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 /**\n * Wrap an error with element context for better debugging.\n */\n private wrapError(error: unknown): never {\n const context = GqlElement.getContext(this.element);\n if (context) {\n const { filePath, astPath } = parseCanonicalId(context.canonicalId);\n const message = error instanceof Error ? error.message : String(error);\n throw builderErrors.elementEvaluationFailed(filePath, astPath, message, error);\n }\n throw error;\n }\n\n protected _executeSync(): void {\n try {\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 } catch (error) {\n this.wrapError(error);\n }\n }\n\n protected async _executeAsync(): Promise<void> {\n try {\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 } catch (error) {\n this.wrapError(error);\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","/**\n * VM sandbox utilities for CJS bundle evaluation.\n *\n * Provides shared infrastructure for executing CommonJS modules\n * in a sandboxed VM context with @soda-gql package mocking.\n *\n * @module\n */\n\nimport { resolve } from \"node:path\";\nimport { createContext, Script } from \"node:vm\";\nimport * as sandboxCore from \"@soda-gql/core\";\nimport * as sandboxCoreAdapter from \"@soda-gql/core/adapter\";\nimport * as sandboxCoreRuntime from \"@soda-gql/core/runtime\";\nimport * as sandboxRuntime from \"@soda-gql/runtime\";\n\n/**\n * Sandbox type with CommonJS module exports.\n */\nexport type CjsSandbox = {\n require: (path: string) => unknown;\n module: { exports: Record<string, unknown> };\n exports: Record<string, unknown>;\n __dirname: string;\n __filename: string;\n global: unknown;\n globalThis: unknown;\n [key: string]: unknown;\n};\n\n/**\n * Create a require function for the sandbox.\n * Maps @soda-gql package imports to their actual modules.\n */\nconst createSandboxRequire =\n () =>\n (path: string): unknown => {\n if (path === \"@soda-gql/core\") return sandboxCore;\n if (path === \"@soda-gql/core/adapter\") return sandboxCoreAdapter;\n if (path === \"@soda-gql/core/runtime\") return sandboxCoreRuntime;\n if (path === \"@soda-gql/runtime\") return sandboxRuntime;\n throw new Error(`Unknown module: ${path}`);\n };\n\n/**\n * Create a VM sandbox for executing CJS bundles.\n *\n * Sets up:\n * - require() handler for @soda-gql packages\n * - module.exports and exports pointing to the same object\n * - __dirname, __filename for path resolution\n * - global and globalThis pointing to the sandbox itself\n *\n * @param modulePath - Absolute path to the module being executed\n * @param additionalContext - Optional additional context properties\n * @returns Configured sandbox object\n */\nexport const createSandbox = (modulePath: string, additionalContext?: Record<string, unknown>): CjsSandbox => {\n const moduleExports: Record<string, unknown> = {};\n\n const sandbox: CjsSandbox = {\n require: createSandboxRequire(),\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 ...additionalContext,\n };\n\n // Wire global and globalThis to the sandbox itself\n sandbox.global = sandbox;\n sandbox.globalThis = sandbox;\n\n return sandbox;\n};\n\n/**\n * Execute CJS code in a sandbox and return the exports.\n *\n * Note: Reads from sandbox.module.exports because esbuild CJS output\n * reassigns module.exports via __toCommonJS(), replacing the original object.\n *\n * @param code - The CJS code to execute\n * @param modulePath - Absolute path to the module (for error messages)\n * @param additionalContext - Optional additional context properties\n * @returns The module's exports object\n */\nexport const executeSandbox = (\n code: string,\n modulePath: string,\n additionalContext?: Record<string, unknown>,\n): Record<string, unknown> => {\n const sandbox = createSandbox(modulePath, additionalContext);\n const context = createContext(sandbox);\n new Script(code, { filename: modulePath }).runInContext(context);\n\n // Read from module.exports due to esbuild's CommonJS transform\n return sandbox.module.exports;\n};\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 {\n type AnyFragment,\n type AnyGqlDefine,\n type AnyOperation,\n Fragment,\n GqlDefine,\n GqlElement,\n Operation,\n} 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 | AnyGqlDefine;\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 } else if (element instanceof GqlDefine) {\n artifacts[canonicalId] = { type: \"define\", 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 { 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 { createSandbox } from \"../vm/sandbox\";\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 sandbox and execute\n const sandbox = createSandbox(modulePath);\n new Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);\n\n // Read exported gql (handle both direct export and default export)\n const finalExports = sandbox.module.exports;\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, inject modules, 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 * Check if a file is an internal module that should be stubbed at runtime.\n * This includes graphql-system and inject modules (scalars, adapter).\n */\n readonly isInternalModuleFile: (input: { filePath: 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 // Collect inject module paths (scalars, adapter) from all schemas.\n // Paths are resolved via realpath to handle symlinks accurately.\n const canonicalInjectPaths = new Set<string>();\n for (const schemaConfig of Object.values(config.schemas)) {\n canonicalInjectPaths.add(toCanonical(schemaConfig.inject.scalars));\n if (schemaConfig.inject.adapter) {\n canonicalInjectPaths.add(toCanonical(schemaConfig.inject.adapter));\n }\n }\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 isInternalModuleFile: ({ filePath }: { filePath: string }) => {\n const canonical = toCanonical(filePath);\n return canonical === canonicalGraphqlSystemPath || canonicalInjectPaths.has(canonical);\n },\n };\n};\n","import { parseCanonicalId, validateCanonicalId } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../errors\";\nimport { builderErrors } from \"../errors\";\n\n/**\n * Parsed canonical ID components.\n */\nexport type ParsedCanonicalId = {\n readonly filePath: string;\n readonly astPath: string;\n};\n\n/**\n * Parse a canonical ID with validation.\n * Returns a Result with parsed components or a BuilderError.\n *\n * @param canonicalId - The canonical ID to parse\n * @returns Result with {filePath, astPath} or BuilderError\n */\nexport const parseCanonicalIdSafe = (canonicalId: string): Result<ParsedCanonicalId, BuilderError> => {\n const validation = validateCanonicalId(canonicalId);\n\n if (!validation.isValid) {\n return err(builderErrors.canonicalPathInvalid(canonicalId, validation.reason));\n }\n\n return ok(parseCanonicalId(canonicalId));\n};\n\n/**\n * Extract file path from canonical ID with validation.\n * Returns a Result with the file path or a BuilderError.\n *\n * @param canonicalId - The canonical ID to extract from\n * @returns Result with filePath or BuilderError\n */\nexport const extractFilePathSafe = (canonicalId: string): Result<string, BuilderError> => {\n return parseCanonicalIdSafe(canonicalId).map(({ filePath }) => filePath);\n};\n","import { createHash } from \"node:crypto\";\n\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\nimport type { BuilderError } from \"../types\";\nimport { parseCanonicalIdSafe } from \"./canonical-id-utils\";\nimport type { BuilderArtifactElement, BuilderArtifactElementMetadata } from \"./types\";\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 = (filePath: string, astPath: string, message: string): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath,\n 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 // Validate canonical ID format early\n const parsedResult = parseCanonicalIdSafe(definition.canonicalId);\n if (parsedResult.isErr()) {\n return err(parsedResult.error);\n }\n const { filePath, astPath } = parsedResult.value;\n\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(filePath, astPath, message));\n }\n\n // Skip define elements - they exist only for builder evaluation, not final output\n if (element.type === \"define\") {\n continue;\n }\n\n if (registry.has(definition.canonicalId)) {\n return err(emitRegistrationError(filePath, astPath, `ARTIFACT_ALREADY_REGISTERED`));\n }\n\n // Use file path from canonical ID (which is relative when baseDir is set)\n const metadata: BuilderArtifactElementMetadata = {\n sourcePath: filePath,\n contentHash: \"\", // Will be computed after prebuild creation\n };\n\n if (element.type === \"fragment\") {\n const prebuild = {\n typename: element.element.typename,\n key: element.element.key,\n schemaLabel: element.element.schemaLabel,\n };\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 schemaLabel: element.element.schemaLabel,\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(filePath, astPath, \"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 { extractFilePathSafe } from \"./canonical-id-utils\";\nimport type { IntermediateElements } from \"./types\";\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 // Validate canonical ID before using\n const filePathResult = extractFilePathSafe(canonicalId);\n if (filePathResult.isErr()) {\n return err(filePathResult.error);\n }\n\n const sources = [filePathResult.value];\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","/**\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, type ScopeHandle } 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 { createStandardDiagnostic } from \"../common/detection\";\nimport type {\n AnalyzeModuleInput,\n DiagnosticLocation,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n} 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 // Only add non-renamed imports (imported exists when renamed: \"gql as g\")\n if (imported === \"gql\" && !specifier.imported) {\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 baseDir,\n}: {\n module: SwcModule;\n gqlIdentifiers: ReadonlySet<string>;\n imports: readonly ModuleImport[];\n exports: readonly ModuleExport[];\n source: string;\n baseDir?: 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 baseDir,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n // Use underscore separator instead of # to ensure valid JavaScript identifiers\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 // Check if we're inside a class property (class property scope tracking is unreliable)\n const isInClassProperty = (stack: ScopeFrame[]): boolean =>\n stack.some((frame, i) => frame.kind === \"property\" && stack[i - 1]?.kind === \"class\");\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 // Skip definition collection for gql calls inside class properties\n // (CLASS_PROPERTY diagnostic is still emitted by collectClassPropertyDiagnostics)\n if (gqlCall && !isInClassProperty(stack)) {\n // If scopeStack is empty (unbound gql call), enter an anonymous scope\n const needsAnonymousScope = tracker.currentDepth() === 0;\n let anonymousScopeHandle: ScopeHandle | undefined;\n\n if (needsAnonymousScope) {\n const anonymousName = getAnonymousName(\"anonymous\");\n anonymousScopeHandle = tracker.enterScope({\n segment: anonymousName,\n kind: \"expression\",\n stableKey: \"anonymous\",\n });\n }\n\n try {\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 } finally {\n // Exit anonymous scope if we entered one\n if (anonymousScopeHandle) {\n tracker.exitScope(anonymousScopeHandle);\n }\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 } else if (decl.init) {\n // Handle destructuring patterns (ObjectPattern, ArrayPattern)\n // Visit the initializer without entering a scope (anonymous gql calls will handle their own scope)\n visit(decl.init, stack);\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, { baseDir }),\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// Diagnostic Collection\n// ============================================================================\n\n/**\n * Get location from an SWC node span\n */\nconst getLocation = (module: SwcModule, span: { start: number; end: number }): DiagnosticLocation => {\n const start = span.start - module.__spanOffset;\n const end = span.end - module.__spanOffset;\n return { start, end };\n};\n\n/**\n * Collect diagnostics for invalid import patterns from graphql-system\n */\nconst collectImportDiagnostics = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\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 ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n\n if (!declaration) {\n return;\n }\n\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n // Check for default import\n if (specifier.type === \"ImportDefaultSpecifier\") {\n diagnostics.push(createStandardDiagnostic(\"DEFAULT_IMPORT\", getLocation(module, specifier.span), undefined));\n return;\n }\n\n // Check for namespace import: import * as gqlSystem from \"...\"\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n diagnostics.push(\n createStandardDiagnostic(\"STAR_IMPORT\", getLocation(module, specifier.span), {\n namespaceAlias: specifier.local.value,\n }),\n );\n return;\n }\n\n // Check for renamed gql import: import { gql as g } from \"...\"\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n // Only report if gql is renamed (imported exists and is \"gql\")\n if (imported === \"gql\" && specifier.imported) {\n diagnostics.push(\n createStandardDiagnostic(\"RENAMED_IMPORT\", getLocation(module, specifier.span), {\n importedAs: specifier.local.value,\n }),\n );\n }\n }\n });\n });\n\n return diagnostics;\n};\n\n/**\n * Check if a node contains a reference to any gql identifier\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst containsGqlIdentifier = (node: any, identifiers: ReadonlySet<string>): boolean => {\n if (!node || typeof node !== \"object\") {\n return false;\n }\n if (node.type === \"Identifier\" && identifiers.has(node.value)) {\n return true;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n if (containsGqlIdentifier(child, identifiers)) {\n return true;\n }\n }\n } else if (value && typeof value === \"object\") {\n if (containsGqlIdentifier(value, identifiers)) {\n return true;\n }\n }\n }\n return false;\n};\n\n/**\n * Get the type name of an argument for error messages\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst getArgumentType = (node: any): string => {\n if (!node) return \"undefined\";\n switch (node.type) {\n case \"StringLiteral\":\n return \"string\";\n case \"NumericLiteral\":\n return \"number\";\n case \"ObjectExpression\":\n return \"object\";\n case \"ArrayExpression\":\n return \"array\";\n case \"FunctionExpression\":\n return \"function\";\n case \"NullLiteral\":\n return \"null\";\n case \"BooleanLiteral\":\n return \"boolean\";\n default:\n return \"unknown\";\n }\n};\n\n/**\n * Collect diagnostics for invalid gql call patterns\n */\nconst collectCallDiagnostics = (module: SwcModule, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n if (node.type === \"CallExpression\") {\n const diagnostic = checkCallExpression(module, node, gqlIdentifiers);\n if (diagnostic) {\n diagnostics.push(diagnostic);\n }\n }\n\n // Recursively visit children\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child);\n }\n } else if (value && typeof value === \"object\") {\n visit(value);\n }\n }\n };\n\n module.body.forEach(visit);\n return diagnostics;\n};\n\n/**\n * Check a call expression for invalid gql patterns\n */\nconst checkCallExpression = (\n module: SwcModule,\n call: CallExpression,\n gqlIdentifiers: ReadonlySet<string>,\n): ModuleDiagnostic | null => {\n const callee = call.callee;\n\n // Check for direct gql() call (non-member): gql(...)\n if (callee.type === \"Identifier\" && gqlIdentifiers.has(callee.value)) {\n return createStandardDiagnostic(\"NON_MEMBER_CALLEE\", getLocation(module, call.span), undefined);\n }\n\n // Check for optional chaining: gql?.default(...)\n // SWC wraps optional chaining in OptionalChainingExpression\n if (callee.type === \"OptionalChainingExpression\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const base = (callee as any).base;\n if (base?.type === \"MemberExpression\") {\n const object = base.object;\n if (object?.type === \"Identifier\" && gqlIdentifiers.has(object.value)) {\n return createStandardDiagnostic(\"OPTIONAL_CHAINING\", getLocation(module, call.span), undefined);\n }\n }\n return null;\n }\n\n // Must be member expression for valid gql call\n if (callee.type !== \"MemberExpression\") {\n return null;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const object = (callee as any).object;\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const property = (callee as any).property;\n\n // Check for computed access: gql[\"default\"](...) or gql[variable](...)\n // SWC represents computed property access with property.type === \"Computed\"\n if (property?.type === \"Computed\" && object?.type === \"Identifier\" && gqlIdentifiers.has(object.value)) {\n return createStandardDiagnostic(\"COMPUTED_PROPERTY\", getLocation(module, call.span), undefined);\n }\n\n // Check for dynamic callee: (x || gql).default(...)\n if (object?.type !== \"Identifier\") {\n if (containsGqlIdentifier(object, gqlIdentifiers)) {\n return createStandardDiagnostic(\"DYNAMIC_CALLEE\", getLocation(module, call.span), undefined);\n }\n return null;\n }\n\n // Not a gql identifier - skip\n if (!gqlIdentifiers.has(object.value)) {\n return null;\n }\n\n // Check arguments for gql.schema(...) calls\n if (!call.arguments || call.arguments.length === 0) {\n return createStandardDiagnostic(\"MISSING_ARGUMENT\", getLocation(module, call.span), undefined);\n }\n\n const firstArg = call.arguments[0];\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const firstArgAny = firstArg as any;\n\n // Check for spread argument: gql.default(...args)\n if (firstArgAny?.spread) {\n return createStandardDiagnostic(\"SPREAD_ARGUMENT\", getLocation(module, call.span), undefined);\n }\n\n const expression = firstArgAny?.expression;\n if (expression && expression.type !== \"ArrowFunctionExpression\") {\n const actualType = getArgumentType(expression);\n return createStandardDiagnostic(\"INVALID_ARGUMENT_TYPE\", getLocation(module, call.span), { actualType });\n }\n\n // Check for extra arguments: gql.default(() => ..., extra)\n if (call.arguments.length > 1) {\n const extraCount = call.arguments.length - 1;\n return createStandardDiagnostic(\"EXTRA_ARGUMENTS\", getLocation(module, call.span), {\n extraCount: String(extraCount),\n });\n }\n\n return null;\n};\n\n/**\n * Collect diagnostics for gql calls in class properties\n */\nconst collectClassPropertyDiagnostics = (module: SwcModule, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const containsGqlCall = (node: any): boolean => {\n if (!node || typeof node !== \"object\") {\n return false;\n }\n if (node.type === \"CallExpression\" && isGqlCall(gqlIdentifiers, node)) {\n return true;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n if (containsGqlCall(child)) {\n return true;\n }\n }\n } else if (value && typeof value === \"object\") {\n if (containsGqlCall(value)) {\n return true;\n }\n }\n }\n return false;\n };\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n if (node.type === \"ClassDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"ClassProperty\" && member.value) {\n if (containsGqlCall(member.value)) {\n diagnostics.push(createStandardDiagnostic(\"CLASS_PROPERTY\", getLocation(module, member.span), undefined));\n }\n }\n });\n }\n\n // Recursively visit children\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child);\n }\n } else if (value && typeof value === \"object\") {\n visit(value);\n }\n }\n };\n\n module.body.forEach(visit);\n return diagnostics;\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 baseDir: input.baseDir,\n });\n\n // Collect diagnostics\n const diagnostics = [\n ...collectImportDiagnostics(swcModule, helper),\n ...collectCallDiagnostics(swcModule, gqlIdentifiers),\n ...collectClassPropertyDiagnostics(swcModule, gqlIdentifiers),\n ];\n\n // Return results - swcModule goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n diagnostics,\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, type ScopeHandle } from \"@soda-gql/common\";\nimport ts from \"typescript\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createStandardDiagnostic } from \"../common/detection\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\nimport type {\n AnalyzeModuleInput,\n DiagnosticLocation,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n} 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 // Only add non-renamed imports (propertyName exists when renamed: \"gql as g\")\n if (imported === \"gql\" && !element.propertyName) {\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\n/**\n * Unwrap NonNullExpression nodes to get the underlying expression.\n * Handles cases like `gql!` or `gql!!` by recursively unwrapping.\n */\nconst unwrapNonNullExpression = (node: ts.Expression): ts.Expression => {\n if (ts.isNonNullExpression(node)) {\n return unwrapNonNullExpression(node.expression);\n }\n return node;\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 // Unwrap NonNullExpression: gql!.default(...) -> gql.default(...)\n const baseExpr = unwrapNonNullExpression(expression.expression);\n\n if (!ts.isIdentifier(baseExpr) || !identifiers.has(baseExpr.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 baseDir,\n}: {\n sourceFile: ts.SourceFile;\n identifiers: ReadonlySet<string>;\n exports: readonly ModuleExport[];\n baseDir?: string;\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 baseDir,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n // Use underscore separator instead of # to ensure valid JavaScript identifiers\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 // Check if we're inside a class property (class property scope tracking is unreliable)\n const isInClassProperty = (stack: ScopeFrame[]): boolean =>\n stack.some((frame, i) => frame.kind === \"property\" && stack[i - 1]?.kind === \"class\");\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 // Skip definition collection for gql calls inside class properties\n // (CLASS_PROPERTY diagnostic is still emitted by collectClassPropertyDiagnostics)\n if (gqlCall && !isInClassProperty(stack)) {\n // If scopeStack is empty (unbound gql call), enter an anonymous scope\n const needsAnonymousScope = tracker.currentDepth() === 0;\n let anonymousScopeHandle: ScopeHandle | undefined;\n\n if (needsAnonymousScope) {\n const anonymousName = getAnonymousName(\"anonymous\");\n anonymousScopeHandle = tracker.enterScope({\n segment: anonymousName,\n kind: \"expression\",\n stableKey: \"anonymous\",\n });\n }\n\n try {\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 } finally {\n // Exit anonymous scope if we entered one\n if (anonymousScopeHandle) {\n tracker.exitScope(anonymousScopeHandle);\n }\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, { baseDir }),\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// Diagnostic Collection\n// ============================================================================\n\n/**\n * Get location from a TypeScript node\n */\nconst getLocation = (sourceFile: ts.SourceFile, node: ts.Node): DiagnosticLocation => {\n const start = node.getStart(sourceFile);\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(start);\n return {\n start,\n end: node.getEnd(),\n line: line + 1, // 1-indexed\n column: character + 1,\n };\n};\n\n/**\n * Collect diagnostics for invalid import patterns from graphql-system\n */\nconst collectImportDiagnostics = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\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 const { importClause } = statement;\n\n // Check for default import: import gql from \"...\"\n if (importClause.name) {\n diagnostics.push(createStandardDiagnostic(\"DEFAULT_IMPORT\", getLocation(sourceFile, importClause.name), undefined));\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) {\n return;\n }\n\n // Check for namespace import: import * as gqlSystem from \"...\"\n if (ts.isNamespaceImport(namedBindings)) {\n diagnostics.push(\n createStandardDiagnostic(\"STAR_IMPORT\", getLocation(sourceFile, namedBindings), {\n namespaceAlias: namedBindings.name.text,\n }),\n );\n return;\n }\n\n // Check for renamed gql import: import { gql as g } from \"...\"\n namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n // Only report if gql is renamed (propertyName exists and is \"gql\")\n if (imported === \"gql\" && element.propertyName) {\n diagnostics.push(\n createStandardDiagnostic(\"RENAMED_IMPORT\", getLocation(sourceFile, element), {\n importedAs: element.name.text,\n }),\n );\n }\n });\n });\n\n return diagnostics;\n};\n\n/**\n * Check if a node contains a reference to any gql identifier\n */\nconst containsGqlIdentifier = (node: ts.Node, identifiers: ReadonlySet<string>): boolean => {\n if (ts.isIdentifier(node) && identifiers.has(node.text)) {\n return true;\n }\n let found = false;\n ts.forEachChild(node, (child) => {\n if (containsGqlIdentifier(child, identifiers)) {\n found = true;\n }\n });\n return found;\n};\n\n/**\n * Get the type name of an argument for error messages\n */\nconst getArgumentType = (node: ts.Node): string => {\n if (ts.isStringLiteral(node)) return \"string\";\n if (ts.isNumericLiteral(node)) return \"number\";\n if (ts.isObjectLiteralExpression(node)) return \"object\";\n if (ts.isArrayLiteralExpression(node)) return \"array\";\n if (ts.isFunctionExpression(node)) return \"function\";\n if (node.kind === ts.SyntaxKind.NullKeyword) return \"null\";\n if (node.kind === ts.SyntaxKind.UndefinedKeyword) return \"undefined\";\n if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) return \"boolean\";\n return \"unknown\";\n};\n\n/**\n * Collect diagnostics for invalid gql call patterns\n */\nconst collectCallDiagnostics = (sourceFile: ts.SourceFile, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n const visit = (node: ts.Node) => {\n if (ts.isCallExpression(node)) {\n const diagnostic = checkCallExpression(sourceFile, node, gqlIdentifiers);\n if (diagnostic) {\n diagnostics.push(diagnostic);\n }\n }\n ts.forEachChild(node, visit);\n };\n\n sourceFile.statements.forEach(visit);\n return diagnostics;\n};\n\n/**\n * Check a call expression for invalid gql patterns\n */\nconst checkCallExpression = (\n sourceFile: ts.SourceFile,\n call: ts.CallExpression,\n gqlIdentifiers: ReadonlySet<string>,\n): ModuleDiagnostic | null => {\n const { expression } = call;\n\n // Check for direct gql() call (non-member): gql(...)\n if (ts.isIdentifier(expression) && gqlIdentifiers.has(expression.text)) {\n return createStandardDiagnostic(\"NON_MEMBER_CALLEE\", getLocation(sourceFile, call), undefined);\n }\n\n // Check for element access: gql[\"default\"](...) or gql\n if (ts.isElementAccessExpression(expression)) {\n const baseExpr = unwrapNonNullExpression(expression.expression);\n if (ts.isIdentifier(baseExpr) && gqlIdentifiers.has(baseExpr.text)) {\n return createStandardDiagnostic(\"COMPUTED_PROPERTY\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Must be property access for valid gql call\n if (!ts.isPropertyAccessExpression(expression)) {\n return null;\n }\n\n // Unwrap NonNullExpression: gql!.default(...) -> gql.default(...)\n const baseExpr = unwrapNonNullExpression(expression.expression);\n\n // Check for optional chaining: gql?.default(...)\n if (expression.questionDotToken) {\n if (ts.isIdentifier(baseExpr) && gqlIdentifiers.has(baseExpr.text)) {\n return createStandardDiagnostic(\"OPTIONAL_CHAINING\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Check for dynamic callee: (x || gql).default(...)\n if (!ts.isIdentifier(baseExpr)) {\n if (containsGqlIdentifier(expression.expression, gqlIdentifiers)) {\n return createStandardDiagnostic(\"DYNAMIC_CALLEE\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Not a gql identifier - skip\n if (!gqlIdentifiers.has(baseExpr.text)) {\n return null;\n }\n\n // Check arguments for gql.schema(...) calls\n if (call.arguments.length === 0) {\n return createStandardDiagnostic(\"MISSING_ARGUMENT\", getLocation(sourceFile, call), undefined);\n }\n\n const firstArg = call.arguments[0];\n\n // Check for spread argument: gql.default(...args)\n if (firstArg && ts.isSpreadElement(firstArg)) {\n return createStandardDiagnostic(\"SPREAD_ARGUMENT\", getLocation(sourceFile, call), undefined);\n }\n\n if (firstArg && !ts.isArrowFunction(firstArg)) {\n const actualType = getArgumentType(firstArg);\n return createStandardDiagnostic(\"INVALID_ARGUMENT_TYPE\", getLocation(sourceFile, call), { actualType });\n }\n\n // Check for extra arguments: gql.default(() => ..., extra)\n if (call.arguments.length > 1) {\n const extraCount = call.arguments.length - 1;\n return createStandardDiagnostic(\"EXTRA_ARGUMENTS\", getLocation(sourceFile, call), {\n extraCount: String(extraCount),\n });\n }\n\n return null;\n};\n\n/**\n * Collect diagnostics for gql calls in class properties\n */\nconst collectClassPropertyDiagnostics = (sourceFile: ts.SourceFile, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n const containsGqlCall = (node: ts.Node): boolean => {\n if (ts.isCallExpression(node) && isGqlDefinitionCall(gqlIdentifiers, node)) {\n return true;\n }\n let found = false;\n ts.forEachChild(node, (child) => {\n if (containsGqlCall(child)) {\n found = true;\n }\n });\n return found;\n };\n\n const visit = (node: ts.Node) => {\n if (ts.isClassDeclaration(node)) {\n node.members.forEach((member) => {\n if (ts.isPropertyDeclaration(member) && member.initializer) {\n if (containsGqlCall(member.initializer)) {\n diagnostics.push(createStandardDiagnostic(\"CLASS_PROPERTY\", getLocation(sourceFile, member), undefined));\n }\n }\n });\n }\n ts.forEachChild(node, visit);\n };\n\n sourceFile.statements.forEach(visit);\n return diagnostics;\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 baseDir: input.baseDir,\n });\n\n // Collect diagnostics\n const diagnostics = [\n ...collectImportDiagnostics(sourceFile, helper),\n ...collectCallDiagnostics(sourceFile, gqlIdentifiers),\n ...collectClassPropertyDiagnostics(sourceFile, gqlIdentifiers),\n ];\n\n // Return results - sourceFile goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n diagnostics,\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, ModuleDiagnostic, 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 readonly diagnostics: readonly ModuleDiagnostic[];\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 diagnostics: [],\n };\n }\n\n return {\n filePath: input.filePath,\n signature,\n definitions: result.definitions,\n imports: result.imports,\n exports: result.exports,\n diagnostics: result.diagnostics,\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 baseDir,\n}: {\n readonly analyzer: BuilderAnalyzer;\n readonly graphqlHelper: GraphqlSystemIdentifyHelper;\n /**\n * Base directory for relative path computation in canonical IDs.\n * When provided, all canonical IDs generated during analysis will use\n * relative paths from baseDir, enabling portable artifacts.\n */\n readonly baseDir?: string;\n}) => {\n const analyze = (input: Omit<AnalyzeModuleInput, \"baseDir\">): ModuleAnalysis => {\n const inputWithBaseDir: AnalyzeModuleInput = { ...input, baseDir };\n if (analyzer === \"ts\") {\n return analyzeModuleCore(inputWithBaseDir, typescriptAdapter, graphqlHelper);\n }\n if (analyzer === \"swc\") {\n return analyzeModuleCore(inputWithBaseDir, swcAdapter, graphqlHelper);\n }\n return assertUnreachable(analyzer, \"createAstAnalyzer\");\n };\n\n return {\n type: analyzer,\n analyze,\n };\n};\n","import { existsSync, readFileSync, unlinkSync } from \"node:fs\";\nimport { getPortableFS, 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\n/**\n * Validate persisted data structure.\n * Uses simple validation to detect corruption without strict schema.\n */\nconst isValidPersistedData = (data: unknown): data is PersistedData => {\n if (typeof data !== \"object\" || data === null) return false;\n const record = data as Record<string, unknown>;\n\n if (typeof record.version !== \"string\") return false;\n if (typeof record.storage !== \"object\" || record.storage === null) return false;\n\n // Validate each namespace has array of entries\n for (const value of Object.values(record.storage as Record<string, unknown>)) {\n if (!Array.isArray(value)) return false;\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2) return false;\n if (typeof entry[0] !== \"string\") return false;\n // Validate envelope has required fields\n const envelope = entry[1];\n if (typeof envelope !== \"object\" || envelope === null) return false;\n const env = envelope as Record<string, unknown>;\n if (typeof env.key !== \"string\" || typeof env.version !== \"string\") return false;\n }\n }\n\n return true;\n};\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\n // Parse and validate JSON structure\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n // Invalid JSON - delete corrupt file and start fresh\n console.warn(`[cache] Corrupt cache file (invalid JSON), starting fresh: ${persistence.filePath}`);\n try {\n unlinkSync(persistence.filePath);\n } catch {\n // Ignore deletion errors\n }\n parsed = null;\n }\n\n if (parsed) {\n // Validate structure to detect corruption\n if (!isValidPersistedData(parsed)) {\n console.warn(`[cache] Corrupt cache file (invalid structure), starting fresh: ${persistence.filePath}`);\n try {\n unlinkSync(persistence.filePath);\n } catch {\n // Ignore deletion errors\n }\n } else if (parsed.version === PERSISTENCE_VERSION) {\n // Restore Map structure from validated data\n for (const [namespaceKey, entries] of Object.entries(parsed.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 // Version mismatch - start fresh without warning (expected on version upgrade)\n }\n }\n } catch (error) {\n // Unexpected error during load - start fresh\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 // Use atomic write to prevent corruption on crash\n // mkdirSync with recursive is idempotent - no TOCTOU race\n const fs = getPortableFS();\n fs.writeFileSyncAtomic(persistence.filePath, JSON.stringify(data));\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\nconst DiagnosticCodeSchema = z.enum([\n \"RENAMED_IMPORT\",\n \"STAR_IMPORT\",\n \"DEFAULT_IMPORT\",\n \"MISSING_ARGUMENT\",\n \"INVALID_ARGUMENT_TYPE\",\n \"NON_MEMBER_CALLEE\",\n \"COMPUTED_PROPERTY\",\n \"DYNAMIC_CALLEE\",\n \"OPTIONAL_CHAINING\",\n \"EXTRA_ARGUMENTS\",\n \"SPREAD_ARGUMENT\",\n \"CLASS_PROPERTY\",\n]);\n\nconst DiagnosticLocationSchema = z.object({\n start: z.number(),\n end: z.number(),\n line: z.number().optional(),\n column: z.number().optional(),\n});\n\nconst ModuleDiagnosticSchema = z.object({\n code: DiagnosticCodeSchema,\n severity: z.enum([\"error\", \"warning\"]),\n message: z.string(),\n location: DiagnosticLocationSchema,\n context: z.record(z.string(), z.string()).readonly().optional(),\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 diagnostics: z.array(ModuleDiagnosticSchema).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 {\n type AliasResolver,\n getPortableHasher,\n isExternalSpecifier,\n resolveRelativeImportWithExistenceCheck,\n} from \"@soda-gql/common\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport type { DiscoveredDependency } from \"./types\";\n\n/**\n * Options for extracting module dependencies.\n */\nexport type ExtractModuleDependenciesOptions = {\n readonly analysis: ModuleAnalysis;\n /** Optional alias resolver for tsconfig paths */\n readonly aliasResolver?: AliasResolver;\n};\n\n/**\n * Extract all unique dependencies (relative + external) from the analysis.\n * Resolves local specifiers immediately so discovery only traverses once.\n *\n * Resolution order:\n * 1. Relative imports → resolveRelativeImportWithExistenceCheck\n * 2. Alias imports (if aliasResolver provided) → aliasResolver.resolve\n * 3. Otherwise → mark as external\n */\nexport const extractModuleDependencies = ({\n analysis,\n aliasResolver,\n}: ExtractModuleDependenciesOptions): 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 // Try relative import first\n if (!isExternalSpecifier(specifier)) {\n const resolvedPath = resolveRelativeImportWithExistenceCheck({\n filePath: analysis.filePath,\n specifier,\n });\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal: false,\n });\n return;\n }\n\n // Try alias resolution if available\n if (aliasResolver) {\n const resolvedPath = aliasResolver.resolve(specifier);\n if (resolvedPath) {\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal: false,\n });\n return;\n }\n }\n\n // External package\n dependencies.set(specifier, {\n specifier,\n resolvedPath: null,\n isExternal: true,\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 { extname } from \"node:path\";\nimport {\n type AliasResolver,\n createAsyncScheduler,\n createSyncScheduler,\n type EffectGenerator,\n normalizePath,\n} from \"@soda-gql/common\";\nimport { err, ok } from \"neverthrow\";\nimport type { createAstAnalyzer } from \"../ast\";\nimport type { ModuleAnalysis } from \"../ast/types\";\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\n/**\n * JavaScript file extensions that should be treated as empty modules.\n * These files are included in the dependency graph but not parsed for definitions.\n */\nconst JS_FILE_EXTENSIONS = [\".js\", \".mjs\", \".cjs\", \".jsx\"] as const;\n\n/**\n * Check if a file path is a JavaScript file (not TypeScript).\n * Used to skip AST analysis for JS files that are resolved as fallbacks.\n */\nconst isJsFile = (filePath: string): boolean => {\n const ext = extname(filePath).toLowerCase();\n return (JS_FILE_EXTENSIONS as readonly string[]).includes(ext);\n};\n\nexport type DiscoverModulesOptions = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n /** Optional alias resolver for tsconfig paths */\n readonly aliasResolver?: AliasResolver;\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 aliasResolver,\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 (skip AST analysis for JS files - treat as empty)\n let analysis: ModuleAnalysis;\n if (isJsFile(filePath)) {\n // JS files are included in the dependency graph but treated as empty modules.\n // This happens when a .js import specifier resolves to an actual .js file\n // because no corresponding .ts file exists.\n analysis = {\n filePath,\n signature,\n definitions: [],\n imports: [],\n exports: [],\n diagnostics: [],\n };\n } else {\n analysis = astAnalyzer.analyze({ filePath, source });\n }\n cacheMisses++;\n\n // Build dependency records (relative + external) in a single pass\n const dependencies = extractModuleDependencies({ analysis, aliasResolver });\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 * Glob pattern matching using fast-glob\n */\n\nimport fg from \"fast-glob\";\n\n/**\n * Scan files matching glob patterns from the given directory.\n * Supports negation patterns (e.g., \"!**\\/excluded.ts\").\n *\n * @param patterns - Glob pattern(s). Can be a single pattern or array of patterns.\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns Array of matched file paths (relative to cwd)\n */\nexport const scanGlob = (patterns: string | readonly string[], cwd: string = process.cwd()): readonly string[] => {\n const patternArray = Array.isArray(patterns) ? patterns : [patterns];\n return fg.sync(patternArray as string[], { 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\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 *\n * @param entries - Include patterns (glob or direct paths). Supports negation patterns (e.g., \"!./path/to/exclude.ts\")\n */\nexport const resolveEntryPaths = (entries: readonly string[]) => {\n // Separate direct file paths from glob patterns\n const directPaths: string[] = [];\n const globPatterns: string[] = [];\n\n for (const entry of entries) {\n // Negation patterns are always glob patterns\n if (entry.startsWith(\"!\")) {\n globPatterns.push(entry);\n continue;\n }\n\n const absolute = resolve(entry);\n if (existsSync(absolute)) {\n // Normalize to POSIX format to match discovery cache keys\n directPaths.push(normalize(absolute).replace(/\\\\/g, \"/\"));\n } else {\n // Treat as glob pattern\n globPatterns.push(entry);\n }\n }\n\n // Scan all glob patterns together (important for negation patterns to work)\n const globMatches =\n globPatterns.length > 0\n ? scanGlob(globPatterns, process.cwd()).map((match) => {\n // Normalize to POSIX format to match discovery cache keys\n return normalize(resolve(match)).replace(/\\\\/g, \"/\");\n })\n : [];\n\n const resolvedPaths = [...directPaths, ...globMatches];\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 {\n type AliasResolver,\n cachedFn,\n createAliasResolver,\n createAsyncScheduler,\n createSyncScheduler,\n type EffectGenerator,\n type SchedulerError,\n} 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 { type CacheFactory, 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 /** Last successful intermediate elements (for prebuilt type generation) */\n lastIntermediateElements: Record<string, IntermediateArtifactElement> | 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 aliasResolver?: AliasResolver;\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 * Get the intermediate elements from the most recent build.\n * Returns null if no build has been performed yet.\n * Used by typegen to extract field selections for prebuilt type generation.\n */\n getIntermediateElements(): Record<string, IntermediateArtifactElement> | null;\n /**\n * Dispose the session and save cache to disk.\n */\n dispose(): void;\n}\n\n/**\n * Singleton state for beforeExit handler registration.\n * Ensures only one handler is registered regardless of how many sessions are created.\n */\nconst exitHandlerState = {\n registered: false,\n factories: new Set<CacheFactory>(),\n};\n\n/**\n * Register a cache factory for save on process exit.\n * Uses singleton pattern to prevent multiple handler registrations.\n */\nconst registerExitHandler = (cacheFactory: CacheFactory): void => {\n exitHandlerState.factories.add(cacheFactory);\n\n if (!exitHandlerState.registered) {\n exitHandlerState.registered = true;\n process.on(\"beforeExit\", () => {\n // Save all registered cache factories sequentially\n for (const factory of exitHandlerState.factories) {\n factory.save();\n }\n });\n }\n};\n\n/**\n * Unregister a cache factory from the exit handler.\n */\nconst unregisterExitHandler = (cacheFactory: CacheFactory): void => {\n exitHandlerState.factories.delete(cacheFactory);\n};\n\n/**\n * Reset exit handler state for testing.\n * @internal\n */\nexport const __resetExitHandlerForTests = (): void => {\n exitHandlerState.registered = false;\n exitHandlerState.factories.clear();\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 lastIntermediateElements: null,\n };\n\n // Reusable infrastructure\n const cacheFactory = createMemoryCache({\n prefix: [\"builder\"],\n persistence: {\n enabled: true,\n filePath: join(process.cwd(), \"node_modules\", \".cache\", \"soda-gql\", \"builder\", \"cache.json\"),\n },\n });\n\n // Register for auto-save on process exit using singleton handler\n registerExitHandler(cacheFactory);\n\n const graphqlHelper = createGraphqlSystemIdentifyHelper(config);\n const ensureAstAnalyzer = cachedFn(() =>\n createAstAnalyzer({\n analyzer: config.analyzer,\n graphqlHelper,\n baseDir: config.baseDir,\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 aliasResolver: config.tsconfigPaths ? createAliasResolver(config.tsconfigPaths) : undefined,\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 state.lastIntermediateElements = elements;\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 getIntermediateElements: () => state.lastIntermediateElements,\n dispose: () => {\n cacheFactory.save();\n // Unregister from exit handler to prevent duplicate saves\n unregisterExitHandler(cacheFactory);\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 aliasResolver,\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 aliasResolver,\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 type { IntermediateArtifactElement } from \"./intermediate-module\";\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 * Get the intermediate elements from the most recent build.\n * Returns null if no build has been performed yet.\n * Used by typegen to extract field selections for prebuilt type generation.\n */\n getIntermediateElements(): Record<string, IntermediateArtifactElement> | 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 getIntermediateElements: () => session.getIntermediateElements(),\n dispose: () => session.dispose(),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,uCAAuC,EAAE,OAAO;CACpD,YAAY,EAAE,QAAQ;CACtB,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,iCAAiC,EAAE,OAAO;CAC9C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,YAAY;CAC5B,UAAU;CACV,UAAU,EAAE,OAAO;EACjB,eAAe,EAAE,KAAK;GAAC;GAAS;GAAY;GAAe,CAAC;EAC5D,eAAe,EAAE,QAAQ;EACzB,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE,SAAS;EACrB,eAAe,EAAE,MAAM,EAAE,QAAQ,CAAC;EACnC,CAAC;CACH,CAAC;AAMF,MAAM,gCAAgC,EAAE,OAAO;CAC7C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,WAAW;CAC3B,UAAU;CACV,UAAU,EAAE,OAAO;EACjB,UAAU,EAAE,QAAQ;EACpB,KAAK,EAAE,QAAQ,CAAC,UAAU;EAC1B,aAAa,EAAE,QAAQ;EACxB,CAAC;CACH,CAAC;AAMF,MAAM,+BAA+B,EAAE,mBAAmB,QAAQ,CAChE,gCACA,8BACD,CAAC;AAEF,MAAM,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