@soda-gql/builder 0.0.1
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/LICENSE +21 -0
- package/dist/index.cjs +2935 -0
- package/dist/index.d.cts +820 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +820 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2870 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["canonicalToFilePath","metadata: BuilderArtifactElementMetadata","lines: string[]","buildAstPath","createOccurrenceTracker","createPathTracker","starts: number[]","toLocation","collectImports","imports: ModuleImport[]","collectExports","exports: ModuleExport[]","collectAllDefinitions","getPropertyName","pending: PendingDefinition[]","handledCalls: CallExpression[]","createCanonicalTracker","frame: ScopeFrame","exportBinding: string | undefined","createCanonicalId","collectDiagnostics","swcAdapter: AnalyzerAdapter<Module, CallExpression>","imports: ModuleImport[]","exports: ModuleExport[]","pending: PendingDefinition[]","handledCalls: ts.CallExpression[]","createCanonicalTracker","frame: ScopeFrame","exportBinding: string | undefined","createCanonicalId","typescriptAdapter: AnalyzerAdapter<ts.SourceFile, ts.CallExpression>","xxhashInstance: XXHashAPI | null","fingerprint: FileFingerprint","source: string","snapshot: DiscoverySnapshot","declarations: string[]","returnEntries: string[]","importLines: string[]","filePath","cached: ArtifactModule | undefined","artifacts: Record<string, IntermediateArtifactElement>","cachedGql: unknown","cachedModulePath: string | null","moduleExports: Record<string, unknown>","currentScan: FileScan","nextScan: FileScan | null","scan","entrypoints: ReadonlySet<string>","state: SessionState","options","stats: ModuleLoadStats"],"sources":["../src/schemas/artifact.ts","../src/artifact/aggregate.ts","../src/artifact/issue-handler.ts","../src/artifact/builder.ts","../src/errors.ts","../src/ast/common/scope.ts","../src/ast/adapters/swc.ts","../src/ast/adapters/typescript.ts","../src/ast/core.ts","../src/ast/index.ts","../src/cache/json-cache.ts","../src/cache/json-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/intermediate-module/codegen.ts","../src/intermediate-module/registry.ts","../src/intermediate-module/evaluation.ts","../src/internal/graphql-system.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 { BuilderArtifactModel, BuilderArtifactOperation, BuilderArtifactSlice } from \"../artifact/types\";\n\nconst BuilderArtifactElementMetadataSchema = z.object({\n sourcePath: z.string(),\n sourceHash: z.string(),\n contentHash: z.string(),\n});\n\nconst BuilderArtifactOperationSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"operation\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n operationType: z.enum([\"query\", \"mutation\", \"subscription\"]),\n operationName: z.string(),\n document: z.unknown(), // DocumentNode object\n variableNames: z.array(z.string()),\n projectionPathGraph: z.unknown(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactOperationSchema<\n _ extends z.infer<typeof BuilderArtifactOperationSchema> = BuilderArtifactOperation,\n>(): never;\n\nconst BuilderArtifactSliceSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"slice\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n operationType: z.enum([\"query\", \"mutation\", \"subscription\"]),\n }),\n});\n\ndeclare function __validate_BuilderArtifactSliceSchema<\n _ extends z.infer<typeof BuilderArtifactSliceSchema> = BuilderArtifactSlice,\n>(): never;\n\nconst BuilderArtifactModelSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"model\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n typename: z.string(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactModelSchema<\n _ extends z.infer<typeof BuilderArtifactModelSchema> = BuilderArtifactModel,\n>(): never;\n\nconst BuilderArtifactElementSchema = z.discriminatedUnion(\"type\", [\n BuilderArtifactOperationSchema,\n BuilderArtifactSliceSchema,\n BuilderArtifactModelSchema,\n]);\n\nexport const BuilderArtifactSchema = z.object({\n elements: z.record(z.string<CanonicalId>(), BuilderArtifactElementSchema),\n report: z.object({\n durationMs: z.number(),\n warnings: z.array(z.string()),\n stats: z.object({\n hits: z.number(),\n misses: z.number(),\n skips: z.number(),\n }),\n }),\n});\n\nexport type BuilderArtifact = z.infer<typeof BuilderArtifactSchema>;\nexport type BuilderArtifactElement = z.infer<typeof BuilderArtifactElementSchema>;\n","import { createHash } from \"node:crypto\";\n\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis, ModuleDefinition } from \"../ast\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\nimport type { BuilderError } from \"../types\";\nimport type { BuilderArtifactElement, BuilderArtifactElementMetadata } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nconst computeContentHash = (prebuild: unknown): string => {\n const hash = createHash(\"sha1\");\n hash.update(JSON.stringify(prebuild));\n return hash.digest(\"hex\");\n};\n\nconst emitRegistrationError = (definition: ModuleDefinition, message: string): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: canonicalToFilePath(definition.canonicalId),\n astPath: definition.astPath,\n message,\n});\n\ntype AggregateInput = {\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n};\n\nexport const aggregate = ({ analyses, elements }: AggregateInput): Result<Map<string, BuilderArtifactElement>, BuilderError> => {\n const registry = new Map<string, BuilderArtifactElement>();\n\n for (const analysis of analyses.values()) {\n for (const definition of analysis.definitions) {\n const element = elements[definition.canonicalId];\n if (!element) {\n const availableIds = Object.keys(elements).join(\", \");\n const message = `ARTIFACT_NOT_FOUND_IN_RUNTIME_MODULE: ${definition.canonicalId}\\nAvailable: ${availableIds}`;\n return err(emitRegistrationError(definition, message));\n }\n\n if (registry.has(definition.canonicalId)) {\n return err(emitRegistrationError(definition, `ARTIFACT_ALREADY_REGISTERED`));\n }\n\n const metadata: BuilderArtifactElementMetadata = {\n sourcePath: analysis.filePath ?? canonicalToFilePath(definition.canonicalId),\n sourceHash: analysis.signature,\n contentHash: \"\", // Will be computed after prebuild creation\n };\n\n if (element.type === \"model\") {\n const prebuild = { typename: element.element.typename };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"model\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n if (element.type === \"slice\") {\n const prebuild = { operationType: element.element.operationType };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"slice\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n if (element.type === \"operation\") {\n const prebuild = {\n operationType: element.element.operationType,\n operationName: element.element.operationName,\n document: element.element.document,\n variableNames: element.element.variableNames,\n projectionPathGraph: element.element.projectionPathGraph,\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 if (element.type === \"inlineOperation\") {\n const prebuild = {\n operationType: element.element.operationType,\n operationName: element.element.operationName,\n document: element.element.document,\n variableNames: element.element.variableNames,\n };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"inlineOperation\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n return err(emitRegistrationError(definition, \"UNKNOWN_ARTIFACT_KIND\"));\n }\n }\n\n return ok(registry);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../types\";\nimport type { IntermediateElements } from \"./types\";\n\nconst canonicalToFilePath = (canonicalId: string): string => canonicalId.split(\"::\")[0] ?? canonicalId;\n\nexport const checkIssues = ({ elements }: { elements: IntermediateElements }): Result<string[], BuilderError> => {\n const operationNames = new Set<string>();\n\n for (const [canonicalId, { type, element }] of Object.entries(elements)) {\n if (type !== \"operation\") {\n continue;\n }\n\n if (operationNames.has(element.operationName)) {\n const sources = [canonicalToFilePath(canonicalId)];\n return err({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${element.operationName}`,\n name: element.operationName,\n sources,\n });\n }\n\n operationNames.add(element.operationName);\n }\n\n return ok([]);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { ModuleLoadStats } from \"../discovery\";\nimport type { BuilderError } from \"../types\";\nimport { aggregate } from \"./aggregate\";\nimport { checkIssues } from \"./issue-handler\";\nimport type { BuilderArtifact, IntermediateElements } from \"./types\";\n\ntype BuildArtifactInput = {\n readonly elements: IntermediateElements;\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly stats: ModuleLoadStats;\n};\n\nexport const buildArtifact = ({\n elements,\n analyses,\n stats: cache,\n}: BuildArtifactInput): Result<BuilderArtifact, BuilderError> => {\n const issuesResult = checkIssues({ elements });\n if (issuesResult.isErr()) {\n return err(issuesResult.error);\n }\n\n const warnings = issuesResult.value;\n\n const aggregationResult = aggregate({ analyses, elements });\n if (aggregationResult.isErr()) {\n return err(aggregationResult.error);\n }\n\n return ok({\n elements: Object.fromEntries(aggregationResult.value.entries()),\n report: {\n durationMs: 0,\n warnings,\n stats: cache,\n },\n } satisfies BuilderArtifact);\n};\n","import { err, type Result } from \"neverthrow\";\n\n/**\n * Comprehensive error code taxonomy for Builder operations.\n */\nexport type BuilderErrorCode =\n // Input/Configuration errors\n | \"ENTRY_NOT_FOUND\"\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n // Discovery errors\n | \"DISCOVERY_IO_ERROR\"\n | \"FINGERPRINT_FAILED\"\n | \"UNSUPPORTED_ANALYZER\"\n // Canonical ID errors\n | \"CANONICAL_PATH_INVALID\"\n | \"CANONICAL_SCOPE_MISMATCH\"\n // Graph/Analysis errors\n | \"GRAPH_CIRCULAR_DEPENDENCY\"\n | \"GRAPH_MISSING_IMPORT\"\n | \"DOC_DUPLICATE\"\n // Emission/IO errors\n | \"WRITE_FAILED\"\n | \"CACHE_CORRUPTED\"\n // Runtime evaluation errors\n | \"RUNTIME_MODULE_LOAD_FAILED\"\n | \"ARTIFACT_REGISTRATION_FAILED\"\n // Internal invariant violations\n | \"INTERNAL_INVARIANT\";\n\n/**\n * Structured error type for all Builder operations.\n */\nexport type BuilderError =\n // Input/Configuration\n | {\n readonly code: \"ENTRY_NOT_FOUND\";\n readonly message: string;\n readonly entry: string;\n }\n | {\n readonly code: \"CONFIG_NOT_FOUND\";\n readonly message: string;\n readonly path: string;\n }\n | {\n readonly code: \"CONFIG_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly cause?: unknown;\n }\n // Discovery\n | {\n readonly code: \"DISCOVERY_IO_ERROR\";\n readonly message: string;\n readonly path: string;\n readonly errno?: string | number;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"FINGERPRINT_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"UNSUPPORTED_ANALYZER\";\n readonly message: string;\n readonly analyzer: string;\n }\n // Canonical ID\n | {\n readonly code: \"CANONICAL_PATH_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly reason?: string;\n }\n | {\n readonly code: \"CANONICAL_SCOPE_MISMATCH\";\n readonly message: string;\n readonly expected: string;\n readonly actual: string;\n }\n // Graph/Analysis\n | {\n readonly code: \"GRAPH_CIRCULAR_DEPENDENCY\";\n readonly message: string;\n readonly chain: readonly string[];\n }\n | {\n readonly code: \"GRAPH_MISSING_IMPORT\";\n readonly message: string;\n readonly importer: string;\n readonly importee: string;\n }\n | {\n readonly code: \"DOC_DUPLICATE\";\n readonly message: string;\n readonly name: string;\n readonly sources: readonly string[];\n }\n // Emission/IO\n | {\n readonly code: \"WRITE_FAILED\";\n readonly message: string;\n readonly outPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"CACHE_CORRUPTED\";\n readonly message: string;\n readonly cachePath?: string;\n readonly cause?: unknown;\n }\n // Runtime evaluation\n | {\n readonly code: \"RUNTIME_MODULE_LOAD_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"ARTIFACT_REGISTRATION_FAILED\";\n readonly message: string;\n readonly elementId: string;\n readonly reason: string;\n }\n // Internal invariant\n | {\n readonly code: \"INTERNAL_INVARIANT\";\n readonly message: string;\n readonly context?: string;\n readonly cause?: unknown;\n };\n\n/**\n * Helper type for Builder operation results.\n */\nexport type BuilderResult<T> = Result<T, BuilderError>;\n\n/**\n * Error constructor helpers for concise error creation.\n */\nexport const builderErrors = {\n entryNotFound: (entry: string, message?: string): BuilderError => ({\n code: \"ENTRY_NOT_FOUND\",\n message: message ?? `Entry not found: ${entry}`,\n entry,\n }),\n\n configNotFound: (path: string, message?: string): BuilderError => ({\n code: \"CONFIG_NOT_FOUND\",\n message: message ?? `Config file not found: ${path}`,\n path,\n }),\n\n configInvalid: (path: string, message: string, cause?: unknown): BuilderError => ({\n code: \"CONFIG_INVALID\",\n message,\n path,\n cause,\n }),\n\n discoveryIOError: (path: string, message: string, errno?: string | number, cause?: unknown): BuilderError => ({\n code: \"DISCOVERY_IO_ERROR\",\n message,\n path,\n errno,\n cause,\n }),\n\n fingerprintFailed: (filePath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"FINGERPRINT_FAILED\",\n message,\n filePath,\n cause,\n }),\n\n unsupportedAnalyzer: (analyzer: string, message?: string): BuilderError => ({\n code: \"UNSUPPORTED_ANALYZER\",\n message: message ?? `Unsupported analyzer: ${analyzer}`,\n analyzer,\n }),\n\n canonicalPathInvalid: (path: string, reason?: string): BuilderError => ({\n code: \"CANONICAL_PATH_INVALID\",\n message: `Invalid canonical path: ${path}${reason ? ` (${reason})` : \"\"}`,\n path,\n reason,\n }),\n\n canonicalScopeMismatch: (expected: string, actual: string): BuilderError => ({\n code: \"CANONICAL_SCOPE_MISMATCH\",\n message: `Scope mismatch: expected ${expected}, got ${actual}`,\n expected,\n actual,\n }),\n\n graphCircularDependency: (chain: readonly string[]): BuilderError => ({\n code: \"GRAPH_CIRCULAR_DEPENDENCY\",\n message: `Circular dependency detected: ${chain.join(\" → \")}`,\n chain,\n }),\n\n graphMissingImport: (importer: string, importee: string): BuilderError => ({\n code: \"GRAPH_MISSING_IMPORT\",\n message: `Missing import: \"${importer}\" imports \"${importee}\" but it's not in the graph`,\n importer,\n importee,\n }),\n\n docDuplicate: (name: string, sources: readonly string[]): BuilderError => ({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${name} found in ${sources.length} files`,\n name,\n sources,\n }),\n\n writeFailed: (outPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"WRITE_FAILED\",\n message,\n outPath,\n cause,\n }),\n\n cacheCorrupted: (message: string, cachePath?: string, cause?: unknown): BuilderError => ({\n code: \"CACHE_CORRUPTED\",\n message,\n cachePath,\n cause,\n }),\n\n runtimeModuleLoadFailed: (filePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n message,\n filePath,\n astPath,\n cause,\n }),\n\n artifactRegistrationFailed: (elementId: string, reason: string): BuilderError => ({\n code: \"ARTIFACT_REGISTRATION_FAILED\",\n message: `Failed to register artifact element ${elementId}: ${reason}`,\n elementId,\n reason,\n }),\n\n internalInvariant: (message: string, context?: string, cause?: unknown): BuilderError => ({\n code: \"INTERNAL_INVARIANT\",\n message: `Internal invariant violated: ${message}`,\n context,\n cause,\n }),\n} as const;\n\n/**\n * Convenience helper to create an err Result from BuilderError.\n */\nexport const builderErr = <T = never>(error: BuilderError): BuilderResult<T> => err(error);\n\n/**\n * Type guard for BuilderError.\n */\nexport const isBuilderError = (error: unknown): error is BuilderError => {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\"\n );\n};\n\n/**\n * Format BuilderError for console output (human-readable).\n */\nexport const formatBuilderError = (error: BuilderError): string => {\n const lines: string[] = [];\n\n lines.push(`Error [${error.code}]: ${error.message}`);\n\n // Add context-specific details\n switch (error.code) {\n case \"ENTRY_NOT_FOUND\":\n lines.push(` Entry: ${error.entry}`);\n break;\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.code === \"CONFIG_INVALID\" && error.cause) {\n lines.push(` Cause: ${error.cause}`);\n }\n break;\n case \"DISCOVERY_IO_ERROR\":\n lines.push(` Path: ${error.path}`);\n if (error.errno !== undefined) {\n lines.push(` Errno: ${error.errno}`);\n }\n break;\n case \"FINGERPRINT_FAILED\":\n lines.push(` File: ${error.filePath}`);\n break;\n case \"CANONICAL_PATH_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.reason) {\n lines.push(` Reason: ${error.reason}`);\n }\n break;\n case \"CANONICAL_SCOPE_MISMATCH\":\n lines.push(` Expected: ${error.expected}`);\n lines.push(` Actual: ${error.actual}`);\n break;\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n lines.push(` Chain: ${error.chain.join(\" → \")}`);\n break;\n case \"GRAPH_MISSING_IMPORT\":\n lines.push(` Importer: ${error.importer}`);\n lines.push(` Importee: ${error.importee}`);\n break;\n case \"DOC_DUPLICATE\":\n lines.push(` Name: ${error.name}`);\n lines.push(` Sources:\\n ${error.sources.join(\"\\n \")}`);\n break;\n case \"WRITE_FAILED\":\n lines.push(` Output path: ${error.outPath}`);\n break;\n case \"CACHE_CORRUPTED\":\n if (error.cachePath) {\n lines.push(` Cache path: ${error.cachePath}`);\n }\n break;\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n lines.push(` File: ${error.filePath}`);\n lines.push(` AST path: ${error.astPath}`);\n break;\n case \"ARTIFACT_REGISTRATION_FAILED\":\n lines.push(` Element ID: ${error.elementId}`);\n lines.push(` Reason: ${error.reason}`);\n break;\n case \"INTERNAL_INVARIANT\":\n if (error.context) {\n lines.push(` Context: ${error.context}`);\n }\n break;\n }\n\n // Add cause if present and not already shown\n if (\"cause\" in error && error.cause && ![\"CONFIG_INVALID\"].includes(error.code)) {\n lines.push(` Caused by: ${error.cause}`);\n }\n\n return lines.join(\"\\n\");\n};\n\n/**\n * Assert unreachable code path (for exhaustiveness checks).\n * This is the ONLY acceptable throw in builder code.\n */\nexport const assertUnreachable = (value: never, context?: string): never => {\n throw new Error(`Unreachable code path${context ? ` in ${context}` : \"\"}: received ${JSON.stringify(value)}`);\n};\n","/**\n * Shared utilities for AST traversal and scope tracking.\n * Used by both TypeScript and SWC adapters.\n */\n\n/**\n * Scope frame for tracking AST path segments\n */\nexport type ScopeFrame = {\n /** Name segment (e.g., \"MyComponent\", \"useQuery\", \"arrow#1\") */\n readonly nameSegment: string;\n /** Kind of scope */\n readonly kind: \"function\" | \"class\" | \"variable\" | \"property\" | \"method\" | \"expression\";\n};\n\n/**\n * Build AST path from scope stack\n */\nexport const buildAstPath = (stack: readonly ScopeFrame[]): string => {\n return stack.map((frame) => frame.nameSegment).join(\".\");\n};\n\n/**\n * Create an occurrence tracker for disambiguating anonymous/duplicate scopes.\n */\nexport const createOccurrenceTracker = (): {\n getNextOccurrence: (key: string) => number;\n} => {\n const occurrenceCounters = new Map<string, number>();\n\n return {\n getNextOccurrence(key: string): number {\n const current = occurrenceCounters.get(key) ?? 0;\n occurrenceCounters.set(key, current + 1);\n return current;\n },\n };\n};\n\n/**\n * Create a path uniqueness tracker to ensure AST paths are unique.\n */\nexport const createPathTracker = (): {\n ensureUniquePath: (basePath: string) => string;\n} => {\n const usedPaths = new Set<string>();\n\n return {\n ensureUniquePath(basePath: string): string {\n let path = basePath;\n let suffix = 0;\n while (usedPaths.has(path)) {\n suffix++;\n path = `${basePath}$${suffix}`;\n }\n usedPaths.add(path);\n return path;\n },\n };\n};\n\n/**\n * Create an export bindings map from module exports.\n * Maps local variable names to their exported names.\n */\nexport const createExportBindingsMap = <T extends { kind: string; local?: string; exported: string; isTypeOnly?: boolean }>(\n exports: readonly T[],\n): Map<string, string> => {\n const exportBindings = new Map<string, string>();\n exports.forEach((exp) => {\n if (exp.kind === \"named\" && exp.local && !exp.isTypeOnly) {\n exportBindings.set(exp.local, exp.exported);\n }\n });\n return exportBindings;\n};\n","/**\n * SWC adapter for the analyzer core.\n * Implements parser-specific logic using the SWC parser.\n */\n\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport { parseSync } from \"@swc/core\";\nimport type { CallExpression, ImportDeclaration, Module, Span } from \"@swc/types\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter } from \"../core\";\n\n/**\n * Extended SWC Module with filePath attached (similar to ts.SourceFile.fileName)\n */\ntype SwcModule = Module & { __filePath: string };\n\nimport type {\n AnalyzeModuleInput,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n SourceLocation,\n SourcePosition,\n} from \"../types\";\n\nconst getLineStarts = (source: string): readonly number[] => {\n const starts: number[] = [0];\n for (let index = 0; index < source.length; index += 1) {\n if (source[index] === \"\\n\") {\n starts.push(index + 1);\n }\n }\n return starts;\n};\n\nconst toPositionResolver = (source: string) => {\n const lineStarts = getLineStarts(source);\n return (offset: number): SourcePosition => {\n let low = 0;\n let high = lineStarts.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const start = lineStarts[mid];\n const next = mid + 1 < lineStarts.length ? lineStarts[mid + 1] : source.length + 1;\n if (start == null || next == null) {\n break;\n }\n if (offset < start) {\n high = mid - 1;\n } else if (offset >= next) {\n low = mid + 1;\n } else {\n return { line: mid + 1, column: offset - start + 1 } satisfies SourcePosition;\n }\n }\n return {\n line: lineStarts.length,\n // biome-ignore lint/style/noNonNullAssertion: lineStarts is guaranteed to have at least one item\n column: offset - lineStarts[lineStarts.length - 1]! + 1,\n } satisfies SourcePosition;\n };\n};\n\nconst toLocation = (resolvePosition: (offset: number) => SourcePosition, span: Span): SourceLocation => ({\n start: resolvePosition(span.start),\n end: resolvePosition(span.end),\n});\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 const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n imports.push({\n source,\n imported,\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 imported: \"*\",\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 imported: \"default\",\n local: specifier.local.value,\n kind: \"default\",\n isTypeOnly: false,\n });\n }\n });\n };\n\n module.body.forEach((item) => {\n if (item.type === \"ImportDeclaration\") {\n handle(item);\n return;\n }\n // Handle module declarations with import declarations\n if (\n \"declaration\" in item &&\n item.declaration &&\n \"type\" in item.declaration &&\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any).type === \"ImportDeclaration\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n handle(item.declaration as any as ImportDeclaration);\n }\n });\n\n return imports;\n};\n\nconst collectExports = (module: Module): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const handle = (declaration: any) => {\n if (declaration.type === \"ExportDeclaration\") {\n if (declaration.declaration.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n declaration.declaration.declarations.forEach((decl: any) => {\n if (decl.id.type === \"Identifier\") {\n exports.push({\n kind: \"named\",\n exported: decl.id.value,\n local: decl.id.value,\n isTypeOnly: false,\n });\n }\n });\n }\n if (declaration.declaration.type === \"FunctionDeclaration\") {\n const ident = declaration.declaration.identifier;\n if (ident) {\n exports.push({\n kind: \"named\",\n exported: ident.value,\n local: ident.value,\n isTypeOnly: false,\n });\n }\n }\n return;\n }\n\n if (declaration.type === \"ExportNamedDeclaration\") {\n const source = declaration.source?.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type !== \"ExportSpecifier\") {\n return;\n }\n const exported = specifier.exported ? specifier.exported.value : specifier.orig.value;\n const local = specifier.orig.value;\n if (source) {\n exports.push({\n kind: \"reexport\",\n exported,\n local,\n source,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n exports.push({\n kind: \"named\",\n exported,\n local,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n });\n return;\n }\n\n if (declaration.type === \"ExportAllDeclaration\") {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: declaration.source.value,\n isTypeOnly: false,\n });\n return;\n }\n\n if (declaration.type === \"ExportDefaultDeclaration\" || declaration.type === \"ExportDefaultExpression\") {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n };\n\n module.body.forEach((item) => {\n if (\n item.type === \"ExportDeclaration\" ||\n item.type === \"ExportNamedDeclaration\" ||\n item.type === \"ExportAllDeclaration\" ||\n item.type === \"ExportDefaultDeclaration\" ||\n item.type === \"ExportDefaultExpression\"\n ) {\n handle(item);\n return;\n }\n\n if (\"declaration\" in item && item.declaration) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n const declaration = item.declaration as any;\n if (\n declaration.type === \"ExportDeclaration\" ||\n declaration.type === \"ExportNamedDeclaration\" ||\n declaration.type === \"ExportAllDeclaration\" ||\n declaration.type === \"ExportDefaultDeclaration\" ||\n declaration.type === \"ExportDefaultExpression\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Complex SWC AST type\n handle(declaration as any);\n }\n }\n });\n\n return exports;\n};\n\nconst collectGqlIdentifiers = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\n : // biome-ignore lint/suspicious/noExplicitAny: SWC AST type checking\n \"declaration\" in item && item.declaration && (item.declaration as any).type === \"ImportDeclaration\"\n ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n if (!declaration) {\n return;\n }\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n if (imported === \"gql\") {\n identifiers.add(specifier.local.value);\n }\n }\n });\n });\n return identifiers;\n};\n\nconst isGqlCall = (identifiers: ReadonlySet<string>, call: CallExpression): boolean => {\n const callee = call.callee;\n if (callee.type !== \"MemberExpression\") {\n return false;\n }\n\n if (callee.object.type !== \"Identifier\") {\n return false;\n }\n\n if (!identifiers.has(callee.object.value)) {\n return false;\n }\n\n if (callee.property.type !== \"Identifier\") {\n return false;\n }\n\n const firstArg = call.arguments[0];\n if (!firstArg?.expression || firstArg.expression.type !== \"ArrowFunctionExpression\") {\n return false;\n }\n\n return true;\n};\n\nconst collectAllDefinitions = ({\n module,\n gqlIdentifiers,\n imports: _imports,\n exports,\n resolvePosition,\n source,\n}: {\n module: SwcModule;\n gqlIdentifiers: ReadonlySet<string>;\n imports: readonly ModuleImport[];\n exports: readonly ModuleExport[];\n resolvePosition: (offset: number) => SourcePosition;\n source: string;\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly CallExpression[];\n} => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const getPropertyName = (property: any): string | null => {\n if (!property) {\n return null;\n }\n if (property.type === \"Identifier\") {\n return property.value;\n }\n if (property.type === \"StringLiteral\" || property.type === \"NumericLiteral\") {\n return property.value;\n }\n return null;\n };\n\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly loc: SourceLocation;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: module.__filePath,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const expressionFromCall = (call: CallExpression): string => {\n let start = call.span.start;\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, call.span.end);\n const marker = raw.indexOf(\"gql\");\n if (marker >= 0) {\n return raw.slice(marker);\n }\n return raw;\n };\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any, stack: ScopeFrame[]) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n // Check if this is a gql definition call\n if (node.type === \"CallExpression\" && isGqlCall(gqlIdentifiers, node)) {\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 loc: toLocation(resolvePosition, node.span),\n expression: expressionFromCall(node),\n });\n\n // Don't visit children of gql calls\n return;\n }\n\n // Variable declaration\n if (node.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.declarations?.forEach((decl: any) => {\n if (decl.id?.type === \"Identifier\") {\n const varName = decl.id.value;\n\n if (decl.init) {\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(decl.init, newStack);\n });\n }\n }\n });\n return;\n }\n\n // Function declaration\n if (node.type === \"FunctionDeclaration\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Arrow function\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowName = getAnonymousName(\"arrow\");\n\n if (node.body) {\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Function expression\n if (node.type === \"FunctionExpression\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Class declaration\n if (node.type === \"ClassDeclaration\") {\n const className = node.identifier?.value ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"MethodProperty\" || member.type === \"ClassProperty\") {\n const memberName = member.key?.value ?? null;\n if (memberName) {\n const memberKind = member.type === \"MethodProperty\" ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (member.type === \"MethodProperty\" && member.body) {\n visit(member.body, memberStack);\n } else if (member.type === \"ClassProperty\" && member.value) {\n visit(member.value, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (node.type === \"KeyValueProperty\") {\n const propName = getPropertyName(node.key);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.value, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n if (Array.isArray(node)) {\n for (const child of node) {\n visit(child, stack);\n }\n } else {\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child, stack);\n }\n } else if (value && typeof value === \"object\") {\n visit(value, stack);\n }\n }\n }\n };\n\n // Start traversal from top-level statements\n module.body.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(module.__filePath, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n loc: item.loc,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * Collect diagnostics (now empty since we support all definition types)\n */\nconst collectDiagnostics = (): ModuleDiagnostic[] => {\n // No longer emit NON_TOP_LEVEL_DEFINITION diagnostics\n // All gql definitions are now supported\n return [];\n};\n\n/**\n * SWC adapter implementation\n */\nexport const swcAdapter: AnalyzerAdapter<Module, CallExpression> = {\n parse(input: AnalyzeModuleInput): Module | null {\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 // Attach filePath to module (similar to ts.SourceFile.fileName)\n const swcModule = program as SwcModule;\n swcModule.__filePath = input.filePath;\n return swcModule;\n },\n\n collectGqlIdentifiers(file: Module, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> {\n return collectGqlIdentifiers(file as SwcModule, helper);\n },\n\n collectImports(file: Module): readonly ModuleImport[] {\n return collectImports(file);\n },\n\n collectExports(file: Module): readonly ModuleExport[] {\n return collectExports(file);\n },\n\n collectDefinitions(\n file: Module,\n context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly source: string;\n },\n ): {\n readonly definitions: readonly ModuleDefinition[];\n readonly handles: readonly CallExpression[];\n } {\n const resolvePosition = toPositionResolver(context.source);\n const { definitions, handledCalls } = collectAllDefinitions({\n module: file as SwcModule,\n gqlIdentifiers: context.gqlIdentifiers,\n imports: context.imports,\n exports: context.exports,\n resolvePosition,\n source: context.source,\n });\n return { definitions, handles: handledCalls };\n },\n\n collectDiagnostics(\n _file: Module,\n _context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly handledCalls: readonly CallExpression[];\n readonly source: string;\n },\n ): readonly ModuleDiagnostic[] {\n return collectDiagnostics();\n },\n};\n","/**\n * TypeScript adapter for the analyzer core.\n * Implements parser-specific logic using the TypeScript compiler API.\n */\n\nimport { extname } from \"node:path\";\nimport { createCanonicalId, createCanonicalTracker } from \"@soda-gql/common\";\nimport ts from \"typescript\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter } from \"../core\";\nimport type {\n AnalyzeModuleInput,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n SourceLocation,\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 toLocation = (sourceFile: ts.SourceFile, node: ts.Node): SourceLocation => {\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n\n return {\n start: { line: start.line + 1, column: start.character + 1 },\n end: { line: end.line + 1, column: end.character + 1 },\n } satisfies SourceLocation;\n};\n\nconst collectGqlImports = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: sourceFile.fileName, specifier: moduleText })) {\n return;\n }\n\n if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {\n statement.importClause.namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n if (imported === \"gql\") {\n identifiers.add(element.name.text);\n }\n });\n }\n });\n\n return identifiers;\n};\n\nconst collectImports = (sourceFile: ts.SourceFile): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n const { importClause } = statement;\n\n if (importClause.name) {\n imports.push({\n source: moduleText,\n imported: \"default\",\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 imported: \"*\",\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 imported: element.propertyName ? element.propertyName.text : element.name.text,\n local: element.name.text,\n kind: \"named\",\n isTypeOnly: Boolean(importClause.isTypeOnly || element.isTypeOnly),\n });\n });\n });\n\n return imports;\n};\n\nconst collectExports = (sourceFile: ts.SourceFile): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (ts.isExportDeclaration(statement)) {\n const moduleSpecifier = statement.moduleSpecifier ? (statement.moduleSpecifier as ts.StringLiteral).text : undefined;\n\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n statement.exportClause.elements.forEach((element) => {\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : undefined,\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n } else {\n exports.push({\n kind: \"named\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : element.name.text,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n }\n });\n return;\n }\n\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly),\n });\n }\n\n return;\n }\n\n if (ts.isExportAssignment(statement)) {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n\n if (\n ts.isVariableStatement(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n statement.declarationList.declarations.forEach((declaration) => {\n if (ts.isIdentifier(declaration.name)) {\n exports.push({\n kind: \"named\",\n exported: declaration.name.text,\n local: declaration.name.text,\n isTypeOnly: false,\n });\n }\n });\n }\n\n if (\n ts.isFunctionDeclaration(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) &&\n statement.name\n ) {\n exports.push({\n kind: \"named\",\n exported: statement.name.text,\n local: statement.name.text,\n isTypeOnly: false,\n });\n }\n });\n\n return exports;\n};\n\nconst isGqlDefinitionCall = (identifiers: ReadonlySet<string>, callExpression: ts.CallExpression): boolean => {\n const expression = callExpression.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return false;\n }\n\n if (!ts.isIdentifier(expression.expression) || !identifiers.has(expression.expression.text)) {\n return false;\n }\n\n const [factory] = callExpression.arguments;\n if (!factory || !ts.isArrowFunction(factory)) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Get property name from AST node\n */\nconst getPropertyName = (name: ts.PropertyName): string | null => {\n if (ts.isIdentifier(name)) {\n return name.text;\n }\n if (ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return null;\n};\n\n/**\n * Collect all gql definitions (exported, non-exported, top-level, nested)\n */\nconst collectAllDefinitions = ({\n sourceFile,\n identifiers,\n exports,\n}: {\n sourceFile: ts.SourceFile;\n identifiers: ReadonlySet<string>;\n exports: readonly ModuleExport[];\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly ts.CallExpression[];\n} => {\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly loc: SourceLocation;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: ts.CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: sourceFile.fileName,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `${kind}#${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const visit = (node: ts.Node, stack: ScopeFrame[]) => {\n // Check if this is a gql definition call\n if (ts.isCallExpression(node) && isGqlDefinitionCall(identifiers, node)) {\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 loc: toLocation(sourceFile, node),\n expression: node.getText(sourceFile),\n });\n\n // Don't visit children of gql calls\n return;\n }\n\n // Variable declaration\n if (ts.isVariableDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const varName = node.name.text;\n\n if (node.initializer) {\n const next = node.initializer;\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(next, newStack);\n });\n }\n return;\n }\n\n // Function declaration\n if (ts.isFunctionDeclaration(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n const next = node.body;\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(next, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Arrow function\n if (ts.isArrowFunction(node)) {\n const arrowName = getAnonymousName(\"arrow\");\n\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n if (ts.isBlock(node.body)) {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n } else {\n visit(node.body, newStack);\n }\n });\n return;\n }\n\n // Function expression\n if (ts.isFunctionExpression(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Class declaration\n if (ts.isClassDeclaration(node)) {\n const className = node.name?.text ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n node.members.forEach((member) => {\n if (ts.isMethodDeclaration(member) || ts.isPropertyDeclaration(member)) {\n const memberName = member.name && ts.isIdentifier(member.name) ? member.name.text : null;\n if (memberName) {\n const memberKind = ts.isMethodDeclaration(member) ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (ts.isMethodDeclaration(member) && member.body) {\n ts.forEachChild(member.body, (child) => visit(child, memberStack));\n } else if (ts.isPropertyDeclaration(member) && member.initializer) {\n visit(member.initializer, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (ts.isPropertyAssignment(node)) {\n const propName = getPropertyName(node.name);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.initializer, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n ts.forEachChild(node, (child) => visit(child, stack));\n };\n\n // Start traversal from top-level statements\n sourceFile.statements.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(sourceFile.fileName, item.astPath),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n loc: item.loc,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n/**\n * Collect diagnostics (now empty since we support all definition types)\n */\nconst collectDiagnostics = (\n _sourceFile: ts.SourceFile,\n _identifiers: ReadonlySet<string>,\n _handledCalls: readonly ts.CallExpression[],\n): ModuleDiagnostic[] => {\n // No longer emit NON_TOP_LEVEL_DEFINITION diagnostics\n // All gql definitions are now supported\n return [];\n};\n\n/**\n * TypeScript adapter implementation\n */\nexport const typescriptAdapter: AnalyzerAdapter<ts.SourceFile, ts.CallExpression> = {\n parse(input: AnalyzeModuleInput): ts.SourceFile | null {\n return createSourceFile(input.filePath, input.source);\n },\n\n collectGqlIdentifiers(file: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> {\n return collectGqlImports(file, helper);\n },\n\n collectImports(file: ts.SourceFile): readonly ModuleImport[] {\n return collectImports(file);\n },\n\n collectExports(file: ts.SourceFile): readonly ModuleExport[] {\n return collectExports(file);\n },\n\n collectDefinitions(\n file: ts.SourceFile,\n context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly source: string;\n },\n ): {\n readonly definitions: readonly ModuleDefinition[];\n readonly handles: readonly ts.CallExpression[];\n } {\n const { definitions, handledCalls } = collectAllDefinitions({\n sourceFile: file,\n identifiers: context.gqlIdentifiers,\n exports: context.exports,\n });\n return { definitions, handles: handledCalls };\n },\n\n collectDiagnostics(\n file: ts.SourceFile,\n context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly handledCalls: readonly ts.CallExpression[];\n readonly source: string;\n },\n ): readonly ModuleDiagnostic[] {\n return collectDiagnostics(file, context.gqlIdentifiers, context.handledCalls);\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 * Adapter interface that each parser implementation (TS, SWC) must provide.\n * TFile: The parsed AST root type (e.g., ts.SourceFile, swc.Module)\n * THandle: A handle type for tracking analyzed call expressions (e.g., ts.CallExpression)\n */\nexport interface AnalyzerAdapter<TFile, THandle> {\n /**\n * Parse source code into an AST.\n */\n parse(input: AnalyzeModuleInput): TFile | null;\n\n /**\n * Collect identifiers imported from /graphql-system that represent gql APIs.\n * Uses GraphqlSystemIdentifyHelper to properly identify graphql-system imports.\n */\n collectGqlIdentifiers(file: TFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string>;\n\n /**\n * Collect all module imports.\n */\n collectImports(file: TFile): readonly ModuleImport[];\n\n /**\n * Collect all module exports.\n */\n collectExports(file: TFile): readonly ModuleExport[];\n\n /**\n * Collect all GraphQL definitions (exported, non-exported, top-level, nested).\n * Returns both the definitions and handles for tracking which calls were processed.\n */\n collectDefinitions(\n file: TFile,\n context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly source: string;\n },\n ): {\n readonly definitions: readonly ModuleDefinition[];\n readonly handles: readonly THandle[];\n };\n\n /**\n * Collect diagnostics for any gql calls that weren't at the top level.\n */\n collectDiagnostics(\n file: TFile,\n context: {\n readonly gqlIdentifiers: ReadonlySet<string>;\n readonly handledCalls: readonly THandle[];\n readonly source: string;\n },\n ): readonly ModuleDiagnostic[];\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 = <TFile, THandle>(\n input: AnalyzeModuleInput,\n adapter: AnalyzerAdapter<TFile, THandle>,\n graphqlHelper: GraphqlSystemIdentifyHelper,\n): ModuleAnalysis => {\n // Parse source\n const hasher = getPortableHasher();\n const signature = hasher.hash(input.source, \"xxhash\");\n\n const file = adapter.parse(input);\n if (!file) {\n return {\n filePath: input.filePath,\n signature,\n definitions: [],\n diagnostics: [],\n imports: [],\n exports: [],\n };\n }\n\n // Collect identifiers, imports, and exports\n const gqlIdentifiers = adapter.collectGqlIdentifiers(file, graphqlHelper);\n const imports = adapter.collectImports(file);\n const exports = adapter.collectExports(file);\n\n // Collect definitions\n const { definitions, handles } = adapter.collectDefinitions(file, {\n gqlIdentifiers,\n imports,\n exports,\n source: input.source,\n });\n\n // Collect diagnostics\n const diagnostics = adapter.collectDiagnostics(file, {\n gqlIdentifiers,\n handledCalls: handles,\n source: input.source,\n });\n\n return {\n filePath: input.filePath,\n signature,\n definitions,\n diagnostics,\n imports,\n exports,\n };\n};\n","import { assertUnreachable } from \"../errors\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { BuilderAnalyzer } from \"../types\";\nimport { swcAdapter } from \"./adapters/swc\";\nimport { typescriptAdapter } from \"./adapters/typescript\";\nimport { analyzeModuleCore } from \"./core\";\nimport type { AnalyzeModuleInput, ModuleAnalysis } from \"./types\";\n\nexport type {\n AnalyzeModuleInput,\n ModuleAnalysis,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n SourceLocation,\n SourcePosition,\n} from \"./types\";\n\nexport const createAstAnalyzer = ({\n analyzer,\n graphqlHelper,\n}: {\n readonly analyzer: BuilderAnalyzer;\n readonly graphqlHelper: GraphqlSystemIdentifyHelper;\n}) => {\n const analyze = (input: AnalyzeModuleInput): ModuleAnalysis => {\n if (analyzer === \"ts\") {\n return analyzeModuleCore(input, typescriptAdapter, graphqlHelper);\n }\n if (analyzer === \"swc\") {\n return analyzeModuleCore(input, swcAdapter, graphqlHelper);\n }\n return assertUnreachable(analyzer, \"createAstAnalyzer\");\n };\n\n return {\n type: analyzer,\n analyze,\n };\n};\n\n// Deprecated: Use createAstAnalyzer instead\nexport const getAstAnalyzer = (analyzer: BuilderAnalyzer) => {\n throw new Error(\"getAstAnalyzer is deprecated. Use createAstAnalyzer with graphqlHelper parameter instead.\");\n};\n","import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\ntype CacheNamespace = readonly string[];\n\nexport type JsonCacheFactoryOptions = {\n readonly rootDir: string;\n readonly prefix?: CacheNamespace;\n};\n\nexport type JsonCacheStoreOptions<_K extends string, V> = {\n readonly namespace: CacheNamespace;\n readonly schema: z.ZodType<V>;\n readonly version?: string;\n};\n\nexport type JsonCacheStore<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 JsonCacheFactory = {\n createStore<K extends string, V>(options: JsonCacheStoreOptions<K, V>): JsonCacheStore<K, V>;\n clearAll(): void;\n};\n\nconst JSON_EXT = \".json\";\n\nconst sanitizeSegment = (segment: string): string => segment.replace(/[\\\\/]/g, \"_\");\n\nconst ensureDirectory = (directory: string): void => {\n if (!existsSync(directory)) {\n mkdirSync(directory, { recursive: true });\n }\n};\n\nconst toNamespacePath = (root: string, segments: CacheNamespace): string => join(root, ...segments.map(sanitizeSegment));\n\nconst toEntryFilename = (key: string): string => {\n const hasher = getPortableHasher();\n return `${hasher.hash(key, \"xxhash\")}${JSON_EXT}`;\n};\n\nexport const createJsonCache = ({ rootDir, prefix = [] }: JsonCacheFactoryOptions): JsonCacheFactory => {\n const basePath = toNamespacePath(rootDir, prefix);\n ensureDirectory(basePath);\n\n const enumerateFiles = (directory: string): string[] => {\n if (!existsSync(directory)) {\n return [];\n }\n\n return readdirSync(directory, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith(JSON_EXT))\n .map((entry) => join(directory, entry.name));\n };\n\n return {\n createStore: <K extends string, V>({\n namespace,\n schema,\n version = \"v1\",\n }: JsonCacheStoreOptions<K, V>): JsonCacheStore<K, V> => {\n const storeRoot = toNamespacePath(basePath, namespace);\n ensureDirectory(storeRoot);\n\n const envelopeSchema = z.object({\n key: z.string(),\n version: z.string(),\n value: schema,\n });\n\n const resolveEntryPath = (key: string) => join(storeRoot, toEntryFilename(key));\n\n const readEnvelope = (filePath: string) => {\n try {\n const raw = readFileSync(filePath, \"utf8\");\n const parsed = envelopeSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n unlinkSync(filePath);\n return null;\n }\n\n if (parsed.data.version !== version) {\n unlinkSync(filePath);\n return null;\n }\n\n return parsed.data;\n } catch {\n unlinkSync(filePath);\n return null;\n }\n };\n\n const load = (key: K): V | null => {\n const filePath = resolveEntryPath(key);\n if (!existsSync(filePath)) {\n return null;\n }\n\n const envelope = readEnvelope(filePath);\n if (!envelope || envelope.key !== key) {\n return null;\n }\n\n return envelope.value as V;\n };\n\n const store = (key: K, value: V): void => {\n const filePath = resolveEntryPath(key);\n ensureDirectory(storeRoot);\n\n const envelope = {\n key,\n version,\n value,\n };\n\n writeFileSync(filePath, JSON.stringify(envelope));\n };\n\n const deleteEntry = (key: K): void => {\n const filePath = resolveEntryPath(key);\n if (existsSync(filePath)) {\n unlinkSync(filePath);\n }\n };\n\n function* iterateEntries(): IterableIterator<[K, V]> {\n for (const filePath of enumerateFiles(storeRoot)) {\n const envelope = readEnvelope(filePath);\n if (!envelope) {\n continue;\n }\n\n yield [envelope.key as K, envelope.value as V];\n }\n }\n\n const clear = (): void => {\n for (const filePath of enumerateFiles(storeRoot)) {\n unlinkSync(filePath);\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 if (existsSync(basePath)) {\n rmSync(basePath, { recursive: true, force: true });\n }\n ensureDirectory(basePath);\n },\n };\n};\n","import { normalizePath } from \"@soda-gql/common\";\nimport type { ZodSchema } from \"zod\";\nimport type { JsonCacheFactory, JsonCacheStore } from \"./json-cache\";\n\nexport type JsonEntityCacheOptions<V> = {\n readonly factory: JsonCacheFactory;\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 JSON-based entity caches.\n * Provides common caching functionality with signature-based eviction.\n */\nexport abstract class JsonEntityCache<K extends string, V> {\n protected readonly cacheStore: JsonCacheStore<K, V>;\n private readonly keyNormalizer: (key: string) => string;\n\n constructor(options: JsonEntityCacheOptions<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 SourcePositionSchema = z.object({\n line: z.number(),\n column: z.number(),\n});\n\nexport const SourceLocationSchema = z.object({\n start: SourcePositionSchema,\n end: SourcePositionSchema,\n});\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 loc: SourceLocationSchema,\n expression: z.string(),\n});\n\nexport const ModuleDiagnosticSchema = z.object({\n code: z.literal(\"NON_TOP_LEVEL_DEFINITION\"),\n message: z.string(),\n loc: SourceLocationSchema,\n});\n\nexport const ModuleImportSchema = z.object({\n source: z.string(),\n imported: z.string(),\n local: z.string(),\n kind: z.enum([\"named\", \"namespace\", \"default\"]),\n isTypeOnly: z.boolean(),\n});\n\nexport const ModuleExportSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"named\"),\n exported: z.string(),\n local: z.string(),\n source: z.undefined().optional(),\n isTypeOnly: z.boolean(),\n }),\n z.object({\n kind: z.literal(\"reexport\"),\n exported: z.string(),\n source: z.string(),\n local: z.string().optional(),\n isTypeOnly: z.boolean(),\n }),\n]);\n\nexport const ModuleAnalysisSchema = z.object({\n filePath: z.string(),\n signature: z.string(),\n definitions: z.array(ModuleDefinitionSchema).readonly(),\n diagnostics: z.array(ModuleDiagnosticSchema).readonly(),\n imports: z.array(ModuleImportSchema).readonly(),\n exports: z.array(ModuleExportSchema).readonly(),\n});\n\nexport type ModuleAnalysis = z.infer<typeof ModuleAnalysisSchema>;\n","import { z } from \"zod\";\nimport { ModuleAnalysisSchema } from \"./cache\";\n\nconst FileFingerprintSchema = z.object({\n hash: z.string(),\n sizeBytes: z.number(),\n mtimeMs: z.number(),\n});\n\nexport const DiscoveredDependencySchema = z.object({\n specifier: z.string(),\n resolvedPath: z.string().nullable(),\n isExternal: z.boolean(),\n});\n\nexport const DiscoverySnapshotSchema = z.object({\n filePath: z.string(),\n normalizedFilePath: z.string(),\n signature: z.string(),\n fingerprint: FileFingerprintSchema,\n analyzer: z.string(),\n createdAtMs: z.number(),\n analysis: ModuleAnalysisSchema,\n dependencies: z.array(DiscoveredDependencySchema).readonly(),\n});\n","import type { JsonCacheFactory } from \"../cache/json-cache\";\nimport { JsonEntityCache } from \"../cache/json-entity-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: JsonCacheFactory;\n readonly analyzer: string;\n readonly evaluatorId: string;\n readonly namespacePrefix?: readonly string[];\n readonly version?: string;\n};\n\nexport class JsonDiscoveryCache extends JsonEntityCache<string, DiscoverySnapshot> implements DiscoveryCache {\n constructor(options: DiscoveryCacheOptions) {\n const namespace = [...(options.namespacePrefix ?? [\"discovery\"]), options.analyzer, options.evaluatorId];\n\n super({\n factory: options.factory,\n namespace,\n schema: DiscoverySnapshotSchema,\n version: options.version ?? DISCOVERY_CACHE_VERSION,\n });\n }\n\n load(filePath: string, expectedSignature: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n const snapshot = this.loadRaw(key);\n if (!snapshot) {\n return null;\n }\n\n if (snapshot.signature !== expectedSignature) {\n this.delete(filePath);\n return null;\n }\n\n return snapshot;\n }\n\n peek(filePath: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n return this.loadRaw(key);\n }\n\n store(snapshot: DiscoverySnapshot): void {\n const key = this.normalizeKey(snapshot.filePath);\n this.storeRaw(key, snapshot);\n }\n\n entries(): IterableIterator<DiscoverySnapshot> {\n return this.baseEntries();\n }\n}\n\nexport const createDiscoveryCache = (options: DiscoveryCacheOptions): DiscoveryCache => new JsonDiscoveryCache(options);\n","import { getPortableHasher, isExternalSpecifier, resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport type { DiscoveredDependency } from \"./types\";\n\n/**\n * Extract all unique dependencies (relative + external) from the analysis.\n * Resolves local specifiers immediately so discovery only traverses once.\n */\nexport const extractModuleDependencies = (analysis: ModuleAnalysis): readonly DiscoveredDependency[] => {\n const dependencies = new Map<string, DiscoveredDependency>();\n\n const addDependency = (specifier: string): void => {\n if (dependencies.has(specifier)) {\n return;\n }\n\n const isExternal = isExternalSpecifier(specifier);\n const resolvedPath = isExternal ? null : resolveRelativeImportWithExistenceCheck({ filePath: analysis.filePath, specifier });\n\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal,\n });\n };\n\n for (const imp of analysis.imports) {\n addDependency(imp.source);\n }\n\n for (const exp of analysis.exports) {\n if (exp.kind === \"reexport\") {\n addDependency(exp.source);\n }\n }\n\n return Array.from(dependencies.values());\n};\n\nexport const createSourceHash = (source: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(source, \"xxhash\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { XXHashAPI } from \"xxhash-wasm\";\n\n/**\n * File fingerprint containing hash, size, and modification time\n */\nexport type FileFingerprint = {\n /** xxHash hash of file contents */\n hash: string;\n /** File size in bytes */\n sizeBytes: number;\n /** Last modification time in milliseconds since epoch */\n mtimeMs: number;\n};\n\n/**\n * Fingerprint computation error types\n */\nexport type FingerprintError =\n | { code: \"FILE_NOT_FOUND\"; path: string; message: string }\n | { code: \"NOT_A_FILE\"; path: string; message: string }\n | { code: \"READ_ERROR\"; path: string; message: string };\n\n/**\n * In-memory fingerprint cache keyed by absolute path\n */\nconst fingerprintCache = new Map<string, FileFingerprint>();\n\n/**\n * Lazy-loaded xxhash instance\n */\nlet xxhashInstance: XXHashAPI | null = null;\n\n/**\n * Lazily load xxhash-wasm instance\n */\nasync function getXXHash(): Promise<XXHashAPI> {\n if (xxhashInstance === null) {\n const { default: xxhash } = await import(\"xxhash-wasm\");\n xxhashInstance = await xxhash();\n }\n return xxhashInstance;\n}\n\n/**\n * Compute file fingerprint with memoization.\n * Uses mtime to short-circuit re-hashing unchanged files.\n *\n * @param path - Absolute path to file\n * @returns Result containing FileFingerprint or FingerprintError\n */\nexport function computeFingerprint(path: string): Result<FileFingerprint, FingerprintError> {\n try {\n const stats = statSync(path);\n\n if (!stats.isFile()) {\n return err({\n code: \"NOT_A_FILE\",\n path,\n message: `Path is not a file: ${path}`,\n });\n }\n\n const mtimeMs = stats.mtimeMs;\n const cached = fingerprintCache.get(path);\n\n // Short-circuit if mtime unchanged\n if (cached && cached.mtimeMs === mtimeMs) {\n return ok(cached);\n }\n\n // Read and hash file contents\n const contents = readFileSync(path);\n const sizeBytes = stats.size;\n\n // Compute hash synchronously (xxhash-wasm will be loaded async first time)\n const hash = computeHashSync(contents);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes,\n mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return ok(fingerprint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return err({\n code: \"FILE_NOT_FOUND\",\n path,\n message: `File not found: ${path}`,\n });\n }\n\n return err({\n code: \"READ_ERROR\",\n path,\n message: `Failed to read file: ${error}`,\n });\n }\n}\n\n/**\n * Compute hash synchronously.\n * For first call, uses simple string hash as fallback.\n * Subsequent calls will use xxhash after async initialization.\n */\nfunction computeHashSync(contents: Buffer): string {\n // If xxhash is already loaded, use it\n if (xxhashInstance !== null) {\n const hash = xxhashInstance.h64Raw(new Uint8Array(contents));\n return hash.toString(16);\n }\n\n // First call: trigger async loading for next time\n void getXXHash();\n\n // Fallback: simple hash for first call only\n return simpleHash(contents);\n}\n\n/**\n * Simple hash function for initial calls before xxhash loads\n */\nfunction simpleHash(buffer: Buffer): string {\n let hash = 0;\n for (let i = 0; i < buffer.length; i++) {\n const byte = buffer[i];\n if (byte !== undefined) {\n hash = (hash << 5) - hash + byte;\n hash = hash & hash; // Convert to 32bit integer\n }\n }\n return hash.toString(16);\n}\n\n/**\n * 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 { readFileSync, statSync } from \"node:fs\";\nimport { normalizePath } from \"@soda-gql/common\";\nimport { err, ok } from \"neverthrow\";\nimport type { createAstAnalyzer } from \"../ast\";\nimport { type BuilderResult, builderErrors } from \"../errors\";\nimport { createSourceHash, extractModuleDependencies } from \"./common\";\nimport { computeFingerprint, invalidateFingerprint } from \"./fingerprint\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\nexport type DiscoverModulesOptions = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n /** Set of file paths explicitly invalidated (from BuilderChangeSet) */\n readonly incremental?: {\n readonly cache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly affectedFiles: Set<string>;\n };\n};\n\nexport type DiscoverModulesResult = {\n readonly snapshots: readonly DiscoverySnapshot[];\n readonly cacheHits: number;\n readonly cacheMisses: number;\n readonly cacheSkips: number;\n};\n\n/**\n * 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 */\nexport const discoverModules = ({\n entryPaths,\n astAnalyzer,\n incremental,\n}: DiscoverModulesOptions): BuilderResult<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 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 try {\n // Fast path: check fingerprint without reading file content\n const stats = statSync(filePath);\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 continue;\n }\n } catch {\n // File may have been deleted or inaccessible, fall through to re-read\n }\n }\n }\n\n // Read source and compute signature\n let source: string;\n try {\n source = readFileSync(filePath, \"utf8\");\n } catch (error) {\n // Handle deleted files gracefully - they may be in cache but removed from disk\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n // Delete from cache and invalidate fingerprint\n incremental?.cache.delete(filePath);\n invalidateFingerprint(filePath);\n continue;\n }\n // Return other IO errors\n return err(builderErrors.discoveryIOError(filePath, error instanceof Error ? error.message : String(error)));\n }\n const signature = createSourceHash(source);\n\n // Parse module\n const analysis = astAnalyzer.analyze({ filePath, source });\n cacheMisses++;\n\n // Build dependency records (relative + external) in a single pass\n const dependencies = extractModuleDependencies(analysis);\n\n // Enqueue all resolved relative dependencies for traversal\n for (const dep of dependencies) {\n if (!dep.isExternal && dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n\n // Compute fingerprint\n const fingerprintResult = computeFingerprint(filePath);\n if (fingerprintResult.isErr()) {\n return err(builderErrors.discoveryIOError(filePath, `Failed to compute fingerprint: ${fingerprintResult.error.message}`));\n }\n const fingerprint = fingerprintResult.value;\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 ok({\n snapshots: Array.from(snapshots.values()),\n cacheHits,\n cacheMisses,\n cacheSkips,\n });\n};\n","/**\n * Cross-runtime glob pattern matching abstraction\n * Provides a unified interface for glob operations across Bun and Node.js\n */\n\nimport fg from \"fast-glob\";\n\n/**\n * Scan files matching a glob pattern from the given directory\n * @param pattern - Glob pattern (e.g., \"src/**\\/*.ts\")\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns Array of matched file paths (relative to cwd)\n */\nexport const scanGlob = (pattern: string, cwd: string = process.cwd()): readonly string[] => {\n // Runtime detection: prefer Bun's native Glob when available for better performance\n if (typeof Bun !== \"undefined\" && Bun.Glob) {\n const { Glob } = Bun;\n const glob = new Glob(pattern);\n return Array.from(glob.scanSync(cwd));\n }\n\n // Node.js fallback: use fast-glob for cross-platform compatibility\n return fg.sync(pattern, { cwd, dot: true, onlyFiles: true });\n};\n","import { existsSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { err, ok } from \"neverthrow\";\n\nimport type { BuilderError } from \"../types\";\nimport { scanGlob } from \"../utils/glob\";\n\nconst scanEntries = (pattern: string): readonly string[] => {\n return scanGlob(pattern, process.cwd());\n};\n\n/**\n * Resolve entry file paths from glob patterns or direct paths.\n * Used by the discovery system to find entry points for module traversal.\n * All paths are normalized to POSIX format for consistent cache key matching.\n * Uses Node.js normalize() + backslash replacement to match normalizePath from @soda-gql/common.\n */\nexport const resolveEntryPaths = (entries: readonly string[]) => {\n const resolvedPaths = entries.flatMap((entry) => {\n const absolute = resolve(entry);\n if (existsSync(absolute)) {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return [normalize(absolute).replace(/\\\\/g, \"/\")];\n }\n\n const matches = scanEntries(entry).map((match) => {\n // Normalize to POSIX format to match discovery cache keys (normalize() + replace backslashes)\n return normalize(resolve(match)).replace(/\\\\/g, \"/\");\n });\n return matches;\n });\n\n if (resolvedPaths.length === 0) {\n return err<readonly string[], BuilderError>({\n code: \"ENTRY_NOT_FOUND\",\n message: `No entry files matched ${entries.join(\", \")}`,\n entry: entries.join(\", \"),\n });\n }\n\n return ok<readonly string[], BuilderError>(resolvedPaths);\n};\n","import { 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}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\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 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 = registry.importModule(\"path\");\n importLines.push(` const ${namespaceImport.local} = registry.importModule(\"${filePath}\");`);\n namespaceImports.add(namespaceImport.local);\n importedRootNames.add(namespaceImport.local);\n } else {\n // Named imports: const { a, b } = registry.importModule(\"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} } = registry.importModule(\"${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}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n}): string => {\n const { imports } = renderImportStatements({ filePath, analysis, analyses });\n\n return [`registry.setModule(\"${filePath}\", () => {`, imports, \"\", buildNestedObject(analysis.definitions), \"});\"].join(\"\\n\");\n};\n","import {\n type AnyComposedOperation,\n type AnyInlineOperation,\n type AnyModel,\n type AnySlice,\n ComposedOperation,\n GqlElement,\n InlineOperation,\n Model,\n Slice,\n} from \"@soda-gql/core\";\nimport type { IntermediateArtifactElement } from \"./types\";\n\nexport type IntermediateRegistry = ReturnType<typeof createIntermediateRegistry>;\n\ntype AcceptableArtifact = AnyModel | AnySlice | AnyComposedOperation | AnyInlineOperation;\ntype ArtifactModule = ArtifactRecord;\ntype ArtifactRecord = {\n readonly [key: string]: AcceptableArtifact | ArtifactRecord;\n};\n\nexport const createIntermediateRegistry = () => {\n const modules = new Map<string, () => ArtifactModule>();\n const elements = new Map<string, AcceptableArtifact>();\n\n const setModule = (filePath: string, factory: () => ArtifactModule) => {\n let cached: ArtifactModule | undefined;\n modules.set(filePath, () => (cached ??= factory()));\n };\n\n const importModule = (filePath: string) => {\n const factory = modules.get(filePath);\n if (!factory) {\n throw new Error(`Module not found or yet to be registered: ${filePath}`);\n }\n return factory();\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 const evaluate = (): Record<string, IntermediateArtifactElement> => {\n // First, register all modules by calling their factories\n for (const mod of modules.values()) {\n mod();\n }\n\n // Then, evaluate all builders after registration\n for (const element of elements.values()) {\n GqlElement.evaluate(element);\n }\n\n // Build a single record with discriminated union entries\n const artifacts: Record<string, IntermediateArtifactElement> = {};\n for (const [canonicalId, element] of elements.entries()) {\n if (element instanceof Model) {\n artifacts[canonicalId] = { type: \"model\", element };\n } else if (element instanceof Slice) {\n artifacts[canonicalId] = { type: \"slice\", element };\n } else if (element instanceof ComposedOperation) {\n artifacts[canonicalId] = { type: \"operation\", element };\n } else if (element instanceof InlineOperation) {\n artifacts[canonicalId] = { type: \"inlineOperation\", element };\n }\n }\n\n return artifacts;\n };\n\n const clear = () => {\n modules.clear();\n elements.clear();\n };\n\n return {\n setModule,\n importModule,\n addElement,\n evaluate,\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 * as sandboxCore from \"@soda-gql/core\";\nimport * as sandboxRuntime from \"@soda-gql/runtime\";\nimport { transformSync } from \"@swc/core\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { BuilderError } from \"../errors\";\nimport { renderRegistryBlock } from \"./codegen\";\nimport { createIntermediateRegistry } from \"./registry\";\nimport type { IntermediateModule } from \"./types\";\n\nexport type BuildIntermediateModulesInput = {\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly targetFiles: Set<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\nfunction executeGraphqlSystemModule(modulePath: string): { gql: unknown } {\n // Use cached module if same path\n if (cachedModulePath === modulePath && cachedGql !== null) {\n return { gql: cachedGql };\n }\n\n // Bundle the GraphQL system module\n const bundledCode = readFileSync(modulePath, \"utf-8\");\n\n // Create a shared CommonJS module exports object\n const moduleExports: Record<string, unknown> = {};\n\n // Create sandbox with proper CommonJS emulation\n const sandbox = {\n // Provide @soda-gql packages through require()\n require: (path: string) => {\n if (path === \"@soda-gql/core\") {\n return sandboxCore;\n }\n if (path === \"@soda-gql/runtime\") {\n return sandboxRuntime;\n }\n throw new Error(`Unknown module: ${path}`);\n },\n // Both module.exports and exports point to the same object\n module: { exports: moduleExports },\n exports: moduleExports,\n __dirname: resolve(modulePath, \"..\"),\n __filename: modulePath,\n global: undefined as unknown,\n globalThis: undefined as unknown,\n };\n // Wire global and globalThis to the sandbox itself\n sandbox.global = sandbox;\n sandbox.globalThis = sandbox;\n\n new Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);\n\n // Read exported gql (handle both direct export and default export)\n const exportedGql = moduleExports.gql ?? moduleExports.default;\n\n if (exportedGql === undefined) {\n throw new Error(`No 'gql' export found in GraphQL system module: ${modulePath}`);\n }\n\n // Cache the result\n cachedGql = exportedGql;\n cachedModulePath = modulePath;\n\n return { gql: cachedGql };\n}\n\n/**\n * Build intermediate modules from dependency graph.\n * Each intermediate module corresponds to one source file.\n */\nexport const generateIntermediateModules = function* ({\n analyses,\n targetFiles,\n}: 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 });\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 const evaluateIntermediateModules = ({\n intermediateModules,\n graphqlSystemPath,\n}: {\n intermediateModules: Map<string, IntermediateModule>;\n graphqlSystemPath: string;\n}) => {\n // Determine import paths from config\n const registry = createIntermediateRegistry();\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 const elements = registry.evaluate();\n registry.clear();\n\n return elements;\n};\n","/**\n * Helper for identifying graphql-system files and import specifiers.\n * Provides robust detection across symlinks, case-insensitive filesystems, and user-defined aliases.\n */\n\nimport { resolve } from \"node:path\";\nimport { resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\n\nexport type GraphqlSystemIdentifyHelper = {\n readonly isGraphqlSystemFile: (input: { filePath: string }) => boolean;\n readonly isGraphqlSystemImportSpecifier: (input: { filePath: string; specifier: string }) => boolean;\n};\n\n/**\n * Create a canonical file name getter based on platform.\n * On case-sensitive filesystems, paths are returned as-is.\n * On case-insensitive filesystems, paths are lowercased for comparison.\n */\nconst createGetCanonicalFileName = (useCaseSensitiveFileNames: boolean): ((path: string) => string) => {\n return useCaseSensitiveFileNames ? (path: string) => path : (path: string) => path.toLowerCase();\n};\n\n/**\n * Detect if the filesystem is case-sensitive.\n * We assume Unix-like systems are case-sensitive, and Windows is not.\n */\nconst getUseCaseSensitiveFileNames = (): boolean => {\n return process.platform !== \"win32\";\n};\n\n/**\n * Create a GraphqlSystemIdentifyHelper from the resolved config.\n * Uses canonical path comparison to handle casing, symlinks, and aliases.\n */\nexport const createGraphqlSystemIdentifyHelper = (config: ResolvedSodaGqlConfig): GraphqlSystemIdentifyHelper => {\n const getCanonicalFileName = createGetCanonicalFileName(getUseCaseSensitiveFileNames());\n\n const toCanonical = (file: string): string => {\n const resolved = resolve(file);\n return getCanonicalFileName(resolved);\n };\n\n // Derive graphql system path from outdir (assume index.ts as default entry)\n const graphqlSystemPath = resolve(config.outdir, \"index.ts\");\n const canonicalGraphqlSystemPath = toCanonical(graphqlSystemPath);\n\n // Build canonical alias map\n const canonicalAliases = new Set(config.graphqlSystemAliases.map((alias) => alias));\n\n return {\n isGraphqlSystemFile: ({ filePath }: { filePath: string }) => {\n return toCanonical(filePath) === canonicalGraphqlSystemPath;\n },\n isGraphqlSystemImportSpecifier: ({ filePath, specifier }: { filePath: string; specifier: string }) => {\n // Check against aliases first if configured\n if (canonicalAliases.has(specifier)) {\n return true;\n }\n\n // Only try to resolve relative imports (starting with . or ..)\n // External specifiers without an alias configured should not match\n if (!specifier.startsWith(\".\")) {\n return false;\n }\n\n // Try to resolve as relative import\n const resolved = resolveRelativeImportWithExistenceCheck({ filePath, specifier });\n if (!resolved) {\n return false;\n }\n\n return toCanonical(resolved) === canonicalGraphqlSystemPath;\n },\n };\n};\n","import { 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\";\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}: {\n analyses: Map<string, ModuleAnalysis>;\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 const resolvedModule = resolveRelativeImportWithReferences({\n filePath: analysis.filePath,\n specifier: source,\n references: analyses,\n });\n if (!resolvedModule) {\n // Import points to a module that doesn't exist in the analysis\n return err({\n code: \"MISSING_IMPORT\" as const,\n chain: [analysis.filePath, source] as const,\n });\n }\n }\n }\n }\n\n return ok(null);\n};\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { DiscoverySnapshot } from \"../discovery\";\n\n/**\n * Extract module-level adjacency from dependency graph.\n * Returns Map of file path -> set of files that import it.\n * All paths are normalized to POSIX format for consistent cache key matching.\n */\nexport const extractModuleAdjacency = ({\n snapshots,\n}: {\n snapshots: Map<string, DiscoverySnapshot>;\n}): Map<string, Set<string>> => {\n const importsByModule = new Map<string, Set<string>>();\n\n for (const snapshot of snapshots.values()) {\n const { normalizedFilePath, dependencies, analysis } = snapshot;\n const imports = new Set<string>();\n\n // Extract module paths from canonical IDs in dependencies\n for (const { resolvedPath } of dependencies) {\n if (resolvedPath && resolvedPath !== normalizedFilePath && snapshots.has(resolvedPath)) {\n imports.add(resolvedPath);\n }\n }\n\n // Phase 3: Handle runtime imports for modules with no tracked dependencies\n if (dependencies.length === 0 && analysis.imports.length > 0) {\n for (const imp of analysis.imports) {\n if (imp.isTypeOnly) {\n continue;\n }\n\n const resolved = resolveRelativeImportWithReferences({\n filePath: normalizedFilePath,\n specifier: imp.source,\n references: snapshots,\n });\n if (resolved) {\n imports.add(resolved);\n }\n }\n }\n\n if (imports.size > 0) {\n importsByModule.set(normalizedFilePath, imports);\n }\n }\n\n // Phase 4: Invert to adjacency map (imported -> [importers])\n const adjacency = new Map<string, Set<string>>();\n\n for (const [importer, imports] of importsByModule) {\n for (const imported of imports) {\n if (!adjacency.has(imported)) {\n adjacency.set(imported, new Set());\n }\n adjacency.get(imported)?.add(importer);\n }\n }\n\n // Include all modules, even isolated ones with no importers\n for (const modulePath of snapshots.keys()) {\n if (!adjacency.has(modulePath)) {\n adjacency.set(modulePath, new Set());\n }\n }\n\n return adjacency;\n};\n\n/**\n * Collect all modules affected by changes, including transitive dependents.\n * Uses BFS to traverse module adjacency graph.\n * All paths are already normalized from extractModuleAdjacency.\n */\nexport const collectAffectedFiles = (input: {\n changedFiles: Set<string>;\n removedFiles: Set<string>;\n previousModuleAdjacency: Map<string, Set<string>>;\n}): Set<string> => {\n const { changedFiles, removedFiles, previousModuleAdjacency } = input;\n const affected = new Set<string>([...changedFiles, ...removedFiles]);\n const queue = [...changedFiles];\n const visited = new Set<string>(changedFiles);\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break;\n\n const dependents = previousModuleAdjacency.get(current);\n\n if (dependents) {\n for (const dependent of dependents) {\n if (!visited.has(dependent)) {\n visited.add(dependent);\n affected.add(dependent);\n queue.push(dependent);\n }\n }\n }\n }\n\n return affected;\n};\n","import { join, resolve } from \"node:path\";\nimport { cachedFn } 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 { createJsonCache } from \"../cache/json-cache\";\nimport {\n createDiscoveryCache,\n type DiscoveryCache,\n type DiscoverySnapshot,\n discoverModules,\n type ModuleLoadStats,\n resolveEntryPaths,\n} from \"../discovery\";\nimport { builderErrors } from \"../errors\";\nimport { evaluateIntermediateModules, generateIntermediateModules, type IntermediateModule } from \"../intermediate-module\";\nimport { createGraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport { createFileTracker, type FileDiff, isEmptyDiff } from \"../tracker\";\nimport type { BuilderError } from \"../types\";\nimport { validateModuleDependencies } from \"./dependency-validation\";\nimport { collectAffectedFiles, extractModuleAdjacency } from \"./module-adjacency\";\n\n/**\n * Session state maintained across incremental builds.\n */\ntype SessionState = {\n /** Generation number */\n gen: number;\n /** Discovery snapshots keyed by normalized file path */\n snapshots: Map<string, DiscoverySnapshot>;\n /** Module-level adjacency: file -> files that import it */\n moduleAdjacency: Map<string, Set<string>>;\n /** Written intermediate modules: filePath -> intermediate module */\n intermediateModules: Map<string, IntermediateModule>;\n /** Last successful artifact */\n lastArtifact: BuilderArtifact | null;\n};\n\n/**\n * Builder session interface for incremental builds.\n */\nexport interface BuilderSession {\n /**\n * Perform build fully or incrementally.\n * The session automatically detects file changes using the file tracker.\n */\n build(options?: { force?: boolean }): 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\n/**\n * Create a new builder session.\n *\n * The session maintains in-memory state across builds to enable incremental processing.\n */\nexport const createBuilderSession = (options: {\n readonly evaluatorId?: string;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n readonly config: ResolvedSodaGqlConfig;\n}): BuilderSession => {\n const config = options.config;\n const evaluatorId = options.evaluatorId ?? \"default\";\n const entrypoints: ReadonlySet<string> = new Set(options.entrypointsOverride ?? config.include);\n\n // Session state stored in closure\n const state: SessionState = {\n gen: 0,\n snapshots: new Map(),\n moduleAdjacency: new Map(),\n intermediateModules: new Map(),\n lastArtifact: null,\n };\n\n // Reusable infrastructure\n const cacheFactory = createJsonCache({\n rootDir: join(process.cwd(), \".cache\", \"soda-gql\", \"builder\"),\n prefix: [\"builder\"],\n });\n\n const graphqlHelper = createGraphqlSystemIdentifyHelper(config);\n const ensureAstAnalyzer = cachedFn(() =>\n createAstAnalyzer({\n analyzer: config.analyzer,\n graphqlHelper,\n }),\n );\n const ensureDiscoveryCache = cachedFn(() =>\n createDiscoveryCache({\n factory: cacheFactory,\n analyzer: config.analyzer,\n evaluatorId,\n }),\n );\n const ensureFileTracker = cachedFn(() => createFileTracker());\n\n const build = (options?: { force?: boolean }): Result<BuilderArtifact, BuilderError> => {\n const force = options?.force ?? false;\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 // 5. 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(prepareResult.value.data.artifact);\n }\n\n const { changedFiles, removedFiles } = prepareResult.value.data;\n\n // 6. Run discovery\n const discoveryCache = ensureDiscoveryCache();\n const astAnalyzer = ensureAstAnalyzer();\n const discoveryResult = discover({\n discoveryCache,\n astAnalyzer,\n removedFiles,\n changedFiles,\n entryPaths,\n previousModuleAdjacency: state.moduleAdjacency,\n });\n if (discoveryResult.isErr()) {\n return err(discoveryResult.error);\n }\n\n const { snapshots, analyses, currentModuleAdjacency, affectedFiles, stats } = discoveryResult.value;\n\n // 7. Build artifact\n const buildResult = buildDiscovered({\n analyses,\n affectedFiles,\n stats,\n previousIntermediateModules: state.intermediateModules,\n graphqlSystemPath: resolve(config.outdir, \"index.ts\"),\n });\n if (buildResult.isErr()) {\n return err(buildResult.error);\n }\n\n const { intermediateModules, artifact } = buildResult.value;\n\n // 8. Update session state\n state.gen++;\n state.snapshots = snapshots;\n state.moduleAdjacency = currentModuleAdjacency;\n state.lastArtifact = artifact;\n state.intermediateModules = intermediateModules;\n\n // 9. Persist tracker state (soft failure - don't block on cache write)\n tracker.update(currentScan);\n\n return ok(artifact);\n };\n\n return {\n build,\n getGeneration: () => state.gen,\n getCurrentArtifact: () => state.lastArtifact,\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\nconst discover = ({\n discoveryCache,\n astAnalyzer,\n removedFiles,\n changedFiles,\n entryPaths,\n previousModuleAdjacency,\n}: {\n discoveryCache: DiscoveryCache;\n astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n removedFiles: Set<string>;\n changedFiles: Set<string>;\n entryPaths: readonly string[];\n previousModuleAdjacency: Map<string, Set<string>>;\n}) => {\n // Collect all affected modules (changed + dependents from removed + transitive)\n const affectedFiles = collectAffectedFiles({\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n });\n\n // Run discovery with invalidations\n const discoveryResult = discoverModules({\n entryPaths,\n astAnalyzer,\n incremental: {\n cache: discoveryCache,\n changedFiles,\n removedFiles,\n affectedFiles,\n },\n });\n if (discoveryResult.isErr()) {\n return err(discoveryResult.error);\n }\n\n const { cacheHits, cacheMisses, cacheSkips } = discoveryResult.value;\n\n const snapshots = new Map(discoveryResult.value.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot]));\n const analyses = new Map(discoveryResult.value.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot.analysis]));\n\n const dependenciesValidationResult = validateModuleDependencies({ analyses });\n if (dependenciesValidationResult.isErr()) {\n const error = dependenciesValidationResult.error;\n return err(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 return ok({ snapshots, analyses, currentModuleAdjacency, affectedFiles, stats });\n};\n\nconst buildDiscovered = ({\n analyses,\n affectedFiles,\n stats,\n previousIntermediateModules,\n graphqlSystemPath,\n}: {\n analyses: Map<string, ModuleAnalysis>;\n affectedFiles: Set<string>;\n stats: ModuleLoadStats;\n previousIntermediateModules: ReadonlyMap<string, IntermediateModule>;\n graphqlSystemPath: string;\n}) => {\n // Create next intermediate modules map (copy current state)\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 })) {\n intermediateModules.set(intermediateModule.filePath, intermediateModule);\n }\n\n const elements = evaluateIntermediateModules({ intermediateModules, graphqlSystemPath });\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 return ok({ intermediateModules, artifact: artifactResult.value });\n};\n","import type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport type { Result } from \"neverthrow\";\nimport type { BuilderArtifact } from \"./artifact/types\";\nimport { createBuilderSession } from \"./session\";\nimport type { BuilderError } from \"./types\";\n\n/**\n * Configuration for BuilderService.\n * Mirrors BuilderInput shape.\n */\nexport type BuilderServiceConfig = {\n readonly config: ResolvedSodaGqlConfig;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n};\n\n/**\n * Builder service interface providing artifact generation.\n */\nexport interface BuilderService {\n /**\n * Generate artifacts from configured entry points.\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 * @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 * 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/**\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 getGeneration: () => session.getGeneration(),\n getCurrentArtifact: () => session.getCurrentArtifact(),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,uCAAuC,EAAE,OAAO;CACpD,YAAY,EAAE,QAAQ;CACtB,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,UAAU,EAAE,SAAS;EACrB,eAAe,EAAE,MAAM,EAAE,QAAQ,CAAC;EAClC,qBAAqB,EAAE,SAAS;EACjC,CAAC;CACH,CAAC;AAMF,MAAM,6BAA6B,EAAE,OAAO;CAC1C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,QAAQ;CACxB,UAAU;CACV,UAAU,EAAE,OAAO,EACjB,eAAe,EAAE,KAAK;EAAC;EAAS;EAAY;EAAe,CAAC,EAC7D,CAAC;CACH,CAAC;AAMF,MAAM,6BAA6B,EAAE,OAAO;CAC1C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,QAAQ;CACxB,UAAU;CACV,UAAU,EAAE,OAAO,EACjB,UAAU,EAAE,QAAQ,EACrB,CAAC;CACH,CAAC;AAMF,MAAM,+BAA+B,EAAE,mBAAmB,QAAQ;CAChE;CACA;CACA;CACD,CAAC;AAEF,MAAa,wBAAwB,EAAE,OAAO;CAC5C,UAAU,EAAE,OAAO,EAAE,QAAqB,EAAE,6BAA6B;CACzE,QAAQ,EAAE,OAAO;EACf,YAAY,EAAE,QAAQ;EACtB,UAAU,EA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,MAAa,wBAAwB,EAAE,QAAQ,0BAAgE;CAC7G,MAAM,UAAU,qBAAqB;EAAE;EAAQ;EAAqB,CAAC;AAErE,QAAO;EACL,QAAQ,YAAY,QAAQ,MAAM,QAAQ;EAC1C,qBAAqB,QAAQ,eAAe;EAC5C,0BAA0B,QAAQ,oBAAoB;EACvD"}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@soda-gql/builder",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"private": false,
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"author": {
|
|
11
|
+
"name": "Shota Hatada",
|
|
12
|
+
"email": "shota.hatada@whatasoda.me",
|
|
13
|
+
"url": "https://github.com/whatasoda"
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"development": "./src/index.ts",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js",
|
|
23
|
+
"require": "./dist/index.cjs",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@soda-gql/common": "0.0.1",
|
|
30
|
+
"@soda-gql/core": "0.0.1",
|
|
31
|
+
"@swc/core": "^1.6.3",
|
|
32
|
+
"@swc/types": "^0.1.6",
|
|
33
|
+
"fast-glob": "^3.3.3",
|
|
34
|
+
"neverthrow": "^8.1.1",
|
|
35
|
+
"typescript": "^5.0.0",
|
|
36
|
+
"xxhash-wasm": "^1.1.0",
|
|
37
|
+
"zod": "^4.1.11"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {},
|
|
40
|
+
"peerDependencies": {}
|
|
41
|
+
}
|