@soda-gql/builder 0.13.0 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +4 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/plugin-support.cjs +1 -1
- package/dist/plugin-support.d.cts +1 -1
- package/dist/plugin-support.d.cts.map +1 -1
- package/dist/plugin-support.d.mts +1 -1
- package/dist/plugin-support.mjs +1 -1
- package/dist/{service-DepGc5-B.cjs → service-BAtxGC5_.cjs} +27 -9
- package/dist/service-BAtxGC5_.cjs.map +1 -0
- package/dist/{service-iCPQhpXW.mjs → service-Dp3ZaxVG.mjs} +27 -9
- package/dist/service-Dp3ZaxVG.mjs.map +1 -0
- package/dist/{service-vzMbq7Pe.d.cts → service-IP_32qPC.d.mts} +7 -5
- package/dist/{service-vzMbq7Pe.d.cts.map → service-IP_32qPC.d.mts.map} +1 -1
- package/dist/{service-Do9da7Cm.d.mts → service-LY6CaxEG.d.cts} +7 -5
- package/dist/{service-Do9da7Cm.d.mts.map → service-LY6CaxEG.d.cts.map} +1 -1
- package/package.json +5 -5
- package/dist/service-DepGc5-B.cjs.map +0 -1
- package/dist/service-iCPQhpXW.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"service-iCPQhpXW.mjs","names":["content: string","parsed: unknown","diagnosticMessages: Record<DiagnosticCode, (ctx?: MessageContext) => string>","lines: string[]","errorHints: Partial<Record<BuilderErrorCode, string>>","base: FormattedError","lines: string[]","path: string","element: AcceptableArtifact","moduleExports: Record<string, unknown>","sandbox: CjsSandbox","declarations: string[]","returnEntries: string[]","importLines: string[]","filePath","stack: EvaluationFrame[]","frame: EvaluationFrame | undefined","result","artifacts: Record<string, IntermediateArtifactElement>","_transformSync: TransformSync | undefined","cachedGql: unknown","cachedModulePath: string | null","bundledCode: string","metadata: BuilderArtifactElementMetadata","collectImports","imports: ModuleImport[]","collectExports","exports: ModuleExport[]","exports","module","unwrapMethodChains","collectAllDefinitions","getPropertyName","pending: PendingDefinition[]","handledCalls: CallExpression[]","frame: ScopeFrame","anonymousScopeHandle: ScopeHandle | undefined","exportBinding: string | undefined","getLocation","collectImportDiagnostics","diagnostics: ModuleDiagnostic[]","containsGqlIdentifier","getArgumentType","collectCallDiagnostics","checkCallExpression","object","collectClassPropertyDiagnostics","_parseSync: ParseSync | undefined","swcAdapter: AnalyzerAdapter","imports: ModuleImport[]","exports: ModuleExport[]","exports","pending: PendingDefinition[]","handledCalls: ts.CallExpression[]","frame: ScopeFrame","anonymousScopeHandle: ScopeHandle | undefined","exportBinding: string | undefined","diagnostics: ModuleDiagnostic[]","baseExpr","typescriptAdapter: AnalyzerAdapter","inputWithBaseDir: AnalyzeModuleInput","parsed: unknown","envelope: Envelope<V>","serialized: Record<string, Array<[string, Envelope<unknown>]>>","data: PersistedData","xxhashInstance: XXHashAPI | null","fingerprint: FileFingerprint","stats","analysis: ModuleAnalysis","snapshot: DiscoverySnapshot","POSIX_REGEX_SOURCE","utils","scan","constants","utils","parse","START_ANCHOR","opts","DOTS_SLASH","DOT_LITERAL","NO_DOT","QMARK","QMARK_NO_DOT","STAR","value","ONE_CHAR","rest","SLASH_LITERAL","PLUS_LITERAL","NO_DOT_SLASH","NO_DOTS_SLASH","NO_DOTS","source","utils","picomatch","state","err","picomatch","directPaths: string[]","globPatterns: string[]","currentScan: FileScan","nextScan: FileScan | null","scan","entrypoints: ReadonlySet<string>","state: SessionState","options","stats: ModuleLoadStats"],"sources":["../src/schemas/artifact.ts","../src/artifact/loader.ts","../src/ast/common/detection.ts","../src/errors.ts","../src/errors/formatter.ts","../src/scheduler/effects.ts","../src/vm/sandbox.ts","../src/intermediate-module/codegen.ts","../src/intermediate-module/registry.ts","../src/intermediate-module/evaluation.ts","../src/internal/graphql-system.ts","../src/artifact/canonical-id-utils.ts","../src/artifact/aggregate.ts","../src/artifact/issue-handler.ts","../src/artifact/builder.ts","../src/ast/common/scope.ts","../src/ast/adapters/swc.ts","../src/ast/adapters/typescript.ts","../src/ast/core.ts","../src/ast/index.ts","../src/cache/memory-cache.ts","../src/cache/entity-cache.ts","../src/schemas/cache.ts","../src/schemas/discovery.ts","../src/discovery/cache.ts","../src/discovery/common.ts","../src/discovery/fingerprint.ts","../src/discovery/discoverer.ts","../../../node_modules/picomatch/lib/constants.js","../../../node_modules/picomatch/lib/utils.js","../../../node_modules/picomatch/lib/scan.js","../../../node_modules/picomatch/lib/parse.js","../../../node_modules/picomatch/lib/picomatch.js","../../../node_modules/picomatch/index.js","../src/utils/glob.ts","../src/discovery/entry-paths.ts","../src/tracker/file-tracker.ts","../src/session/dependency-validation.ts","../src/session/module-adjacency.ts","../src/session/builder-session.ts","../src/service.ts"],"sourcesContent":["import type { CanonicalId } from \"@soda-gql/common\";\nimport { z } from \"zod\";\nimport type { BuilderArtifactFragment, BuilderArtifactOperation } from \"../artifact/types\";\n\nconst BuilderArtifactElementMetadataSchema = z.object({\n sourcePath: z.string(),\n contentHash: z.string(),\n});\n\nconst BuilderArtifactOperationSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"operation\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n operationType: z.enum([\"query\", \"mutation\", \"subscription\"]),\n operationName: z.string(),\n schemaLabel: z.string(),\n document: z.unknown(), // DocumentNode object\n variableNames: z.array(z.string()),\n metadata: z.unknown().optional(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactOperationSchema<\n _ extends z.infer<typeof BuilderArtifactOperationSchema> = BuilderArtifactOperation,\n>(): never;\n\nconst BuilderArtifactFragmentSchema = z.object({\n id: z.string<CanonicalId>(),\n type: z.literal(\"fragment\"),\n metadata: BuilderArtifactElementMetadataSchema,\n prebuild: z.object({\n typename: z.string(),\n key: z.string().optional(),\n schemaLabel: z.string(),\n }),\n});\n\ndeclare function __validate_BuilderArtifactFragmentSchema<\n _ extends z.infer<typeof BuilderArtifactFragmentSchema> = BuilderArtifactFragment,\n>(): never;\n\nconst BuilderArtifactElementSchema = z.discriminatedUnion(\"type\", [\n BuilderArtifactOperationSchema,\n BuilderArtifactFragmentSchema,\n]);\n\nconst BuilderArtifactMetaSchema = z.object({\n version: z.string(),\n createdAt: z.string(),\n});\n\nexport const BuilderArtifactSchema = z.object({\n meta: BuilderArtifactMetaSchema.optional(),\n elements: z.record(z.string<CanonicalId>(), BuilderArtifactElementSchema),\n report: z.object({\n durationMs: z.number(),\n warnings: z.array(z.string()),\n stats: z.object({\n hits: z.number(),\n misses: z.number(),\n skips: z.number(),\n }),\n }),\n});\n\nexport type BuilderArtifact = z.infer<typeof BuilderArtifactSchema>;\nexport type BuilderArtifactElement = z.infer<typeof BuilderArtifactElementSchema>;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { BuilderArtifactSchema } from \"../schemas/artifact\";\nimport type { BuilderArtifact } from \"./types\";\n\n/**\n * Error codes for artifact loading failures.\n */\nexport type ArtifactLoadErrorCode = \"ARTIFACT_NOT_FOUND\" | \"ARTIFACT_PARSE_ERROR\" | \"ARTIFACT_VALIDATION_ERROR\";\n\n/**\n * Error type for artifact loading operations.\n */\nexport type ArtifactLoadError = {\n readonly code: ArtifactLoadErrorCode;\n readonly message: string;\n readonly filePath?: string;\n};\n\n/**\n * Load a pre-built artifact from a JSON file asynchronously.\n *\n * @param path - Absolute path to the artifact JSON file\n * @returns Result with the parsed artifact or an error\n *\n * @example\n * ```ts\n * const result = await loadArtifact(\"/path/to/artifact.json\");\n * if (result.isOk()) {\n * const artifact = result.value;\n * // Use artifact...\n * }\n * ```\n */\nexport const loadArtifact = async (path: string): Promise<Result<BuilderArtifact, ArtifactLoadError>> => {\n if (!existsSync(path)) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Artifact file not found: ${path}`,\n filePath: path,\n });\n }\n\n let content: string;\n try {\n content = await readFile(path, \"utf-8\");\n } catch (error) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath: path,\n });\n }\n\n return parseAndValidateArtifact(content, path);\n};\n\n/**\n * Load a pre-built artifact from a JSON file synchronously.\n *\n * @param path - Absolute path to the artifact JSON file\n * @returns Result with the parsed artifact or an error\n *\n * @example\n * ```ts\n * const result = loadArtifactSync(\"/path/to/artifact.json\");\n * if (result.isOk()) {\n * const artifact = result.value;\n * // Use artifact...\n * }\n * ```\n */\nexport const loadArtifactSync = (path: string): Result<BuilderArtifact, ArtifactLoadError> => {\n if (!existsSync(path)) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Artifact file not found: ${path}`,\n filePath: path,\n });\n }\n\n let content: string;\n try {\n content = readFileSync(path, \"utf-8\");\n } catch (error) {\n return err({\n code: \"ARTIFACT_NOT_FOUND\",\n message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath: path,\n });\n }\n\n return parseAndValidateArtifact(content, path);\n};\n\n/**\n * Parse JSON content and validate against BuilderArtifactSchema.\n */\nfunction parseAndValidateArtifact(content: string, filePath: string): Result<BuilderArtifact, ArtifactLoadError> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n return err({\n code: \"ARTIFACT_PARSE_ERROR\",\n message: `Invalid JSON in artifact file: ${error instanceof Error ? error.message : String(error)}`,\n filePath,\n });\n }\n\n const validated = BuilderArtifactSchema.safeParse(parsed);\n if (!validated.success) {\n return err({\n code: \"ARTIFACT_VALIDATION_ERROR\",\n message: `Invalid artifact structure: ${validated.error.message}`,\n filePath,\n });\n }\n\n // Cast to BuilderArtifact since Zod schema validates the structure\n // but TypeScript can't infer the exact runtime types (e.g., RuntimeOperationInput)\n return ok(validated.data as BuilderArtifact);\n}\n","/**\n * Shared detection utilities for identifying invalid gql patterns.\n * Used by both TypeScript and SWC adapters, and exported for formatter consumption.\n */\n\nimport type { DiagnosticCode, DiagnosticLocation, DiagnosticSeverity, ModuleDiagnostic } from \"../types\";\n\n// ============================================================================\n// Diagnostic Factory\n// ============================================================================\n\n/**\n * Configuration for creating a diagnostic\n */\nexport type DiagnosticConfig = {\n readonly code: DiagnosticCode;\n readonly message: string;\n readonly location: DiagnosticLocation;\n readonly context?: Readonly<Record<string, string>>;\n};\n\n/**\n * Create a diagnostic with appropriate severity\n */\nexport const createDiagnostic = (config: DiagnosticConfig): ModuleDiagnostic => ({\n code: config.code,\n severity: getSeverity(config.code),\n message: config.message,\n location: config.location,\n context: config.context,\n});\n\n// ============================================================================\n// Severity Classification\n// ============================================================================\n\n/**\n * Get severity for a diagnostic code.\n * - \"error\": Code will definitely not work\n * - \"warning\": Code might work but is unsupported/unreliable\n */\nexport const getSeverity = (code: DiagnosticCode): DiagnosticSeverity => {\n switch (code) {\n // Errors: code will definitely not work\n case \"MISSING_ARGUMENT\":\n case \"INVALID_ARGUMENT_TYPE\":\n case \"NON_MEMBER_CALLEE\":\n case \"OPTIONAL_CHAINING\":\n case \"SPREAD_ARGUMENT\":\n return \"error\";\n\n // Warnings: code might work but is unsupported\n case \"RENAMED_IMPORT\":\n case \"STAR_IMPORT\":\n case \"DEFAULT_IMPORT\":\n case \"COMPUTED_PROPERTY\":\n case \"DYNAMIC_CALLEE\":\n case \"CLASS_PROPERTY\":\n case \"EXTRA_ARGUMENTS\":\n return \"warning\";\n }\n};\n\n// ============================================================================\n// Message Templates\n// ============================================================================\n\ntype MessageContext = Readonly<Record<string, string>>;\n\n/**\n * Diagnostic message templates for each code\n */\nexport const diagnosticMessages: Record<DiagnosticCode, (ctx?: MessageContext) => string> = {\n // Import-level\n RENAMED_IMPORT: (ctx) => `Import alias \"${ctx?.importedAs ?? \"?\"}\" not recognized - use \"import { gql } from ...\"`,\n STAR_IMPORT: (ctx) => `Namespace import \"${ctx?.namespaceAlias ?? \"?\"}\" not fully supported - use named import`,\n DEFAULT_IMPORT: () => `Default import not supported - use \"import { gql } from ...\"`,\n\n // Call-level\n MISSING_ARGUMENT: () => `gql definition requires a factory function argument`,\n INVALID_ARGUMENT_TYPE: (ctx) => `Expected arrow function, got ${ctx?.actualType ?? \"unknown\"}`,\n NON_MEMBER_CALLEE: () => `Cannot call gql directly - use gql.schemaName(...)`,\n COMPUTED_PROPERTY: () => `Computed property access not supported - use gql.schemaName(...)`,\n DYNAMIC_CALLEE: () => `Dynamic callee expression not supported`,\n OPTIONAL_CHAINING: () => `Optional chaining on gql not supported - use gql.schemaName(...) directly`,\n EXTRA_ARGUMENTS: (ctx) =>\n `gql definition only accepts one argument, ${ctx?.extraCount ?? \"extra\"} additional argument(s) ignored`,\n SPREAD_ARGUMENT: () => `Spread arguments not supported - use arrow function directly`,\n\n // Scope-level\n CLASS_PROPERTY: () => `Class property definitions may have inconsistent scope tracking`,\n};\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a diagnostic with a standard message\n */\nexport const createStandardDiagnostic = (\n code: DiagnosticCode,\n location: DiagnosticLocation,\n context?: MessageContext,\n): ModuleDiagnostic => {\n return createDiagnostic({\n code,\n message: diagnosticMessages[code](context),\n location,\n context,\n });\n};\n","import { err, type Result } from \"neverthrow\";\n\n/**\n * Comprehensive error code taxonomy for Builder operations.\n */\nexport type BuilderErrorCode =\n // Input/Configuration errors\n | \"ENTRY_NOT_FOUND\"\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n // Discovery errors\n | \"DISCOVERY_IO_ERROR\"\n | \"FINGERPRINT_FAILED\"\n | \"UNSUPPORTED_ANALYZER\"\n // Canonical ID errors\n | \"CANONICAL_PATH_INVALID\"\n | \"CANONICAL_SCOPE_MISMATCH\"\n // Graph/Analysis errors\n | \"GRAPH_CIRCULAR_DEPENDENCY\"\n | \"GRAPH_MISSING_IMPORT\"\n | \"DOC_DUPLICATE\"\n // Emission/IO errors\n | \"WRITE_FAILED\"\n | \"CACHE_CORRUPTED\"\n // Runtime evaluation errors\n | \"RUNTIME_MODULE_LOAD_FAILED\"\n | \"ARTIFACT_REGISTRATION_FAILED\"\n | \"ELEMENT_EVALUATION_FAILED\"\n // Internal invariant violations\n | \"INTERNAL_INVARIANT\"\n // Schema validation errors\n | \"SCHEMA_NOT_FOUND\";\n\n/**\n * Structured error type for all Builder operations.\n */\nexport type BuilderError =\n // Input/Configuration\n | {\n readonly code: \"ENTRY_NOT_FOUND\";\n readonly message: string;\n readonly entry: string;\n }\n | {\n readonly code: \"CONFIG_NOT_FOUND\";\n readonly message: string;\n readonly path: string;\n }\n | {\n readonly code: \"CONFIG_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly cause?: unknown;\n }\n // Discovery\n | {\n readonly code: \"DISCOVERY_IO_ERROR\";\n readonly message: string;\n readonly path: string;\n readonly errno?: string | number;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"FINGERPRINT_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"UNSUPPORTED_ANALYZER\";\n readonly message: string;\n readonly analyzer: string;\n }\n // Canonical ID\n | {\n readonly code: \"CANONICAL_PATH_INVALID\";\n readonly message: string;\n readonly path: string;\n readonly reason?: string;\n }\n | {\n readonly code: \"CANONICAL_SCOPE_MISMATCH\";\n readonly message: string;\n readonly expected: string;\n readonly actual: string;\n }\n // Graph/Analysis\n | {\n readonly code: \"GRAPH_CIRCULAR_DEPENDENCY\";\n readonly message: string;\n readonly chain: readonly string[];\n }\n | {\n readonly code: \"GRAPH_MISSING_IMPORT\";\n readonly message: string;\n readonly importer: string;\n readonly importee: string;\n }\n | {\n readonly code: \"DOC_DUPLICATE\";\n readonly message: string;\n readonly name: string;\n readonly sources: readonly string[];\n }\n // Emission/IO\n | {\n readonly code: \"WRITE_FAILED\";\n readonly message: string;\n readonly outPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"CACHE_CORRUPTED\";\n readonly message: string;\n readonly cachePath?: string;\n readonly cause?: unknown;\n }\n // Runtime evaluation\n | {\n readonly code: \"RUNTIME_MODULE_LOAD_FAILED\";\n readonly message: string;\n readonly filePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n | {\n readonly code: \"ARTIFACT_REGISTRATION_FAILED\";\n readonly message: string;\n readonly elementId: string;\n readonly reason: string;\n }\n | {\n readonly code: \"ELEMENT_EVALUATION_FAILED\";\n readonly message: string;\n readonly modulePath: string;\n readonly astPath: string;\n readonly cause?: unknown;\n }\n // Internal invariant\n | {\n readonly code: \"INTERNAL_INVARIANT\";\n readonly message: string;\n readonly context?: string;\n readonly cause?: unknown;\n }\n // Schema validation\n | {\n readonly code: \"SCHEMA_NOT_FOUND\";\n readonly message: string;\n readonly schemaLabel: string;\n readonly canonicalId: string;\n };\n\n/**\n * Helper type for Builder operation results.\n */\nexport type BuilderResult<T> = Result<T, BuilderError>;\n\n/**\n * Error constructor helpers for concise error creation.\n */\nexport const builderErrors = {\n entryNotFound: (entry: string, message?: string): BuilderError => ({\n code: \"ENTRY_NOT_FOUND\",\n message: message ?? `Entry not found: ${entry}`,\n entry,\n }),\n\n configNotFound: (path: string, message?: string): BuilderError => ({\n code: \"CONFIG_NOT_FOUND\",\n message: message ?? `Config file not found: ${path}`,\n path,\n }),\n\n configInvalid: (path: string, message: string, cause?: unknown): BuilderError => ({\n code: \"CONFIG_INVALID\",\n message,\n path,\n cause,\n }),\n\n discoveryIOError: (path: string, message: string, errno?: string | number, cause?: unknown): BuilderError => ({\n code: \"DISCOVERY_IO_ERROR\",\n message,\n path,\n errno,\n cause,\n }),\n\n fingerprintFailed: (filePath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"FINGERPRINT_FAILED\",\n message,\n filePath,\n cause,\n }),\n\n unsupportedAnalyzer: (analyzer: string, message?: string): BuilderError => ({\n code: \"UNSUPPORTED_ANALYZER\",\n message: message ?? `Unsupported analyzer: ${analyzer}`,\n analyzer,\n }),\n\n canonicalPathInvalid: (path: string, reason?: string): BuilderError => ({\n code: \"CANONICAL_PATH_INVALID\",\n message: `Invalid canonical path: ${path}${reason ? ` (${reason})` : \"\"}`,\n path,\n reason,\n }),\n\n canonicalScopeMismatch: (expected: string, actual: string): BuilderError => ({\n code: \"CANONICAL_SCOPE_MISMATCH\",\n message: `Scope mismatch: expected ${expected}, got ${actual}`,\n expected,\n actual,\n }),\n\n graphCircularDependency: (chain: readonly string[]): BuilderError => ({\n code: \"GRAPH_CIRCULAR_DEPENDENCY\",\n message: `Circular dependency detected: ${chain.join(\" → \")}`,\n chain,\n }),\n\n graphMissingImport: (importer: string, importee: string): BuilderError => ({\n code: \"GRAPH_MISSING_IMPORT\",\n message: `Missing import: \"${importer}\" imports \"${importee}\" but it's not in the graph`,\n importer,\n importee,\n }),\n\n docDuplicate: (name: string, sources: readonly string[]): BuilderError => ({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${name} found in ${sources.length} files`,\n name,\n sources,\n }),\n\n writeFailed: (outPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"WRITE_FAILED\",\n message,\n outPath,\n cause,\n }),\n\n cacheCorrupted: (message: string, cachePath?: string, cause?: unknown): BuilderError => ({\n code: \"CACHE_CORRUPTED\",\n message,\n cachePath,\n cause,\n }),\n\n runtimeModuleLoadFailed: (filePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n message,\n filePath,\n astPath,\n cause,\n }),\n\n artifactRegistrationFailed: (elementId: string, reason: string): BuilderError => ({\n code: \"ARTIFACT_REGISTRATION_FAILED\",\n message: `Failed to register artifact element ${elementId}: ${reason}`,\n elementId,\n reason,\n }),\n\n elementEvaluationFailed: (modulePath: string, astPath: string, message: string, cause?: unknown): BuilderError => ({\n code: \"ELEMENT_EVALUATION_FAILED\",\n message,\n modulePath,\n astPath,\n cause,\n }),\n\n internalInvariant: (message: string, context?: string, cause?: unknown): BuilderError => ({\n code: \"INTERNAL_INVARIANT\",\n message: `Internal invariant violated: ${message}`,\n context,\n cause,\n }),\n\n schemaNotFound: (schemaLabel: string, canonicalId: string): BuilderError => ({\n code: \"SCHEMA_NOT_FOUND\",\n message: `Schema not found for label \"${schemaLabel}\" (element: ${canonicalId})`,\n schemaLabel,\n canonicalId,\n }),\n} as const;\n\n/**\n * Convenience helper to create an err Result from BuilderError.\n */\nexport const builderErr = <T = never>(error: BuilderError): BuilderResult<T> => err(error);\n\n/**\n * Type guard for BuilderError.\n */\nexport const isBuilderError = (error: unknown): error is BuilderError => {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\"\n );\n};\n\n/**\n * Format BuilderError for console output (human-readable).\n */\nexport const formatBuilderError = (error: BuilderError): string => {\n const lines: string[] = [];\n\n lines.push(`Error [${error.code}]: ${error.message}`);\n\n // Add context-specific details\n switch (error.code) {\n case \"ENTRY_NOT_FOUND\":\n lines.push(` Entry: ${error.entry}`);\n break;\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.code === \"CONFIG_INVALID\" && error.cause) {\n lines.push(` Cause: ${error.cause}`);\n }\n break;\n case \"DISCOVERY_IO_ERROR\":\n lines.push(` Path: ${error.path}`);\n if (error.errno !== undefined) {\n lines.push(` Errno: ${error.errno}`);\n }\n break;\n case \"FINGERPRINT_FAILED\":\n lines.push(` File: ${error.filePath}`);\n break;\n case \"CANONICAL_PATH_INVALID\":\n lines.push(` Path: ${error.path}`);\n if (error.reason) {\n lines.push(` Reason: ${error.reason}`);\n }\n break;\n case \"CANONICAL_SCOPE_MISMATCH\":\n lines.push(` Expected: ${error.expected}`);\n lines.push(` Actual: ${error.actual}`);\n break;\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n lines.push(` Chain: ${error.chain.join(\" → \")}`);\n break;\n case \"GRAPH_MISSING_IMPORT\":\n lines.push(` Importer: ${error.importer}`);\n lines.push(` Importee: ${error.importee}`);\n break;\n case \"DOC_DUPLICATE\":\n lines.push(` Name: ${error.name}`);\n lines.push(` Sources:\\n ${error.sources.join(\"\\n \")}`);\n break;\n case \"WRITE_FAILED\":\n lines.push(` Output path: ${error.outPath}`);\n break;\n case \"CACHE_CORRUPTED\":\n if (error.cachePath) {\n lines.push(` Cache path: ${error.cachePath}`);\n }\n break;\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n lines.push(` File: ${error.filePath}`);\n lines.push(` AST path: ${error.astPath}`);\n break;\n case \"ARTIFACT_REGISTRATION_FAILED\":\n lines.push(` Element ID: ${error.elementId}`);\n lines.push(` Reason: ${error.reason}`);\n break;\n case \"ELEMENT_EVALUATION_FAILED\":\n lines.push(` at ${error.modulePath}`);\n if (error.astPath) {\n lines.push(` in ${error.astPath}`);\n }\n break;\n case \"INTERNAL_INVARIANT\":\n if (error.context) {\n lines.push(` Context: ${error.context}`);\n }\n break;\n case \"SCHEMA_NOT_FOUND\":\n lines.push(` Schema label: ${error.schemaLabel}`);\n lines.push(` Element: ${error.canonicalId}`);\n break;\n }\n\n // Add cause if present and not already shown\n if (\"cause\" in error && error.cause && ![\"CONFIG_INVALID\"].includes(error.code)) {\n lines.push(` Caused by: ${error.cause}`);\n }\n\n return lines.join(\"\\n\");\n};\n\n/**\n * Assert unreachable code path (for exhaustiveness checks).\n * This is the ONLY acceptable throw in builder code.\n */\nexport const assertUnreachable = (value: never, context?: string): never => {\n throw new Error(`Unreachable code path${context ? ` in ${context}` : \"\"}: received ${JSON.stringify(value)}`);\n};\n","import type { BuilderError, BuilderErrorCode } from \"../errors\";\n\n/**\n * Hints for each error code to help users understand and fix issues.\n */\nconst errorHints: Partial<Record<BuilderErrorCode, string>> = {\n ELEMENT_EVALUATION_FAILED: \"Check if all imported fragments are properly exported and included in entry patterns.\",\n GRAPH_CIRCULAR_DEPENDENCY: \"Break the circular import by extracting shared types to a common module.\",\n GRAPH_MISSING_IMPORT: \"Verify the import path exists and the module is included in entry patterns.\",\n RUNTIME_MODULE_LOAD_FAILED: \"Ensure the module can be imported and all dependencies are installed.\",\n CONFIG_NOT_FOUND: \"Create a soda-gql.config.ts file in your project root.\",\n CONFIG_INVALID: \"Check your configuration file for syntax errors or invalid options.\",\n ENTRY_NOT_FOUND: \"Verify the entry pattern matches your file structure.\",\n INTERNAL_INVARIANT: \"This is an internal error. Please report it at https://github.com/soda-gql/soda-gql/issues\",\n};\n\n/**\n * Formatted error with structured information for display.\n */\nexport type FormattedError = {\n readonly code: BuilderErrorCode;\n readonly message: string;\n readonly location?: {\n readonly modulePath: string;\n readonly astPath?: string;\n };\n readonly hint?: string;\n readonly relatedFiles?: readonly string[];\n readonly cause?: unknown;\n};\n\n/**\n * Format a BuilderError into a structured FormattedError object.\n */\nexport const formatBuilderErrorStructured = (error: BuilderError): FormattedError => {\n const base: FormattedError = {\n code: error.code,\n message: error.message,\n hint: errorHints[error.code],\n cause: \"cause\" in error ? error.cause : undefined,\n };\n\n switch (error.code) {\n case \"ELEMENT_EVALUATION_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.modulePath,\n astPath: error.astPath || undefined,\n },\n };\n\n case \"RUNTIME_MODULE_LOAD_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.filePath,\n astPath: error.astPath,\n },\n };\n\n case \"GRAPH_MISSING_IMPORT\":\n return {\n ...base,\n relatedFiles: [error.importer, error.importee],\n };\n\n case \"GRAPH_CIRCULAR_DEPENDENCY\":\n return {\n ...base,\n relatedFiles: error.chain,\n };\n\n case \"CONFIG_NOT_FOUND\":\n case \"CONFIG_INVALID\":\n return {\n ...base,\n location: {\n modulePath: error.path,\n },\n };\n\n case \"FINGERPRINT_FAILED\":\n return {\n ...base,\n location: {\n modulePath: error.filePath,\n },\n };\n\n case \"DISCOVERY_IO_ERROR\":\n return {\n ...base,\n location: {\n modulePath: error.path,\n },\n };\n\n default:\n return base;\n }\n};\n\n/**\n * Format a BuilderError for CLI/stderr output with human-readable formatting.\n * Includes location, hint, and related files when available.\n */\nexport const formatBuilderErrorForCLI = (error: BuilderError): string => {\n const formatted = formatBuilderErrorStructured(error);\n const lines: string[] = [];\n\n // Header with error code and message\n lines.push(`Error [${formatted.code}]: ${formatted.message}`);\n\n // Location information\n if (formatted.location) {\n lines.push(` at ${formatted.location.modulePath}`);\n if (formatted.location.astPath) {\n lines.push(` in ${formatted.location.astPath}`);\n }\n }\n\n // Hint for fixing the issue\n if (formatted.hint) {\n lines.push(\"\");\n lines.push(` Hint: ${formatted.hint}`);\n }\n\n // Related files (for dependency errors)\n if (formatted.relatedFiles && formatted.relatedFiles.length > 0) {\n lines.push(\"\");\n lines.push(\" Related files:\");\n for (const file of formatted.relatedFiles) {\n lines.push(` - ${file}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { Effect, Effects, parseCanonicalId } from \"@soda-gql/common\";\nimport { type AnyFragment, type AnyGqlDefine, type AnyOperation, GqlElement } from \"@soda-gql/core\";\nimport { builderErrors } from \"../errors\";\n\ntype AcceptableArtifact = AnyFragment | AnyOperation | AnyGqlDefine;\n\n/**\n * File stats result type.\n */\nexport type FileStats = {\n readonly mtimeMs: number;\n readonly size: number;\n readonly isFile: boolean;\n};\n\n/**\n * File read effect - reads a file from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const content = yield* new FileReadEffect(\"/path/to/file\").run();\n */\nexport class FileReadEffect extends Effect<string> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string {\n return readFileSync(this.path, \"utf-8\");\n }\n\n protected _executeAsync(): Promise<string> {\n return readFile(this.path, \"utf-8\");\n }\n}\n\n/**\n * File stat effect - gets file stats from the filesystem.\n * Works in both sync and async schedulers.\n *\n * @example\n * const stats = yield* new FileStatEffect(\"/path/to/file\").run();\n */\nexport class FileStatEffect extends Effect<FileStats> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n\n protected async _executeAsync(): Promise<FileStats> {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n }\n}\n\n/**\n * File read effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileReadEffect extends Effect<string | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): string | null {\n try {\n return readFileSync(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<string | null> {\n try {\n return await readFile(this.path, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * File stat effect that returns null if file doesn't exist.\n * Useful for discovery where missing files are expected.\n */\nexport class OptionalFileStatEffect extends Effect<FileStats | null> {\n constructor(readonly path: string) {\n super();\n }\n\n protected _executeSync(): FileStats | null {\n try {\n const stats = statSync(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n protected async _executeAsync(): Promise<FileStats | null> {\n try {\n const stats = await stat(this.path);\n return {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n isFile: stats.isFile(),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n}\n\n/**\n * Element evaluation effect - evaluates a GqlElement using its generator.\n * Supports both sync and async schedulers, enabling parallel element evaluation\n * when using async scheduler.\n *\n * Wraps errors with module context for better debugging.\n *\n * @example\n * yield* new ElementEvaluationEffect(element).run();\n */\nexport class ElementEvaluationEffect extends Effect<void> {\n constructor(readonly element: AcceptableArtifact) {\n super();\n }\n\n /**\n * Wrap an error with element context for better debugging.\n */\n private wrapError(error: unknown): never {\n const context = GqlElement.getContext(this.element);\n if (context) {\n const { filePath, astPath } = parseCanonicalId(context.canonicalId);\n const message = error instanceof Error ? error.message : String(error);\n throw builderErrors.elementEvaluationFailed(filePath, astPath, message, error);\n }\n throw error;\n }\n\n protected _executeSync(): void {\n try {\n // Run generator synchronously - throws if async operation is required\n const generator = GqlElement.createEvaluationGenerator(this.element);\n const result = generator.next();\n while (!result.done) {\n // If generator yields, it means async operation is needed\n throw new Error(\"Async operation required during sync element evaluation\");\n }\n } catch (error) {\n this.wrapError(error);\n }\n }\n\n protected async _executeAsync(): Promise<void> {\n try {\n const generator = GqlElement.createEvaluationGenerator(this.element);\n let result = generator.next();\n while (!result.done) {\n // Yield value is a Promise<void>\n await result.value;\n result = generator.next();\n }\n } catch (error) {\n this.wrapError(error);\n }\n }\n}\n\n/**\n * Builder effect constructors.\n * Extends the base Effects with file I/O operations and element evaluation.\n */\nexport const BuilderEffects = {\n ...Effects,\n\n /**\n * Create a file read effect.\n * @param path - The file path to read\n */\n readFile: (path: string): FileReadEffect => new FileReadEffect(path),\n\n /**\n * Create a file stat effect.\n * @param path - The file path to stat\n */\n stat: (path: string): FileStatEffect => new FileStatEffect(path),\n\n /**\n * Create an optional file read effect that returns null if file doesn't exist.\n * @param path - The file path to read\n */\n readFileOptional: (path: string): OptionalFileReadEffect => new OptionalFileReadEffect(path),\n\n /**\n * Create an optional file stat effect that returns null if file doesn't exist.\n * @param path - The file path to stat\n */\n statOptional: (path: string): OptionalFileStatEffect => new OptionalFileStatEffect(path),\n\n /**\n * Create an element evaluation effect.\n * @param element - The GqlElement to evaluate\n */\n evaluateElement: (element: AcceptableArtifact): ElementEvaluationEffect => new ElementEvaluationEffect(element),\n} as const;\n","/**\n * VM sandbox utilities for CJS bundle evaluation.\n *\n * Provides shared infrastructure for executing CommonJS modules\n * in a sandboxed VM context with @soda-gql package mocking.\n *\n * @module\n */\n\nimport { resolve } from \"node:path\";\nimport { createContext, Script } from \"node:vm\";\nimport * as sandboxCore from \"@soda-gql/core\";\nimport * as sandboxCoreAdapter from \"@soda-gql/core/adapter\";\nimport * as sandboxCoreRuntime from \"@soda-gql/core/runtime\";\n\n/**\n * Sandbox type with CommonJS module exports.\n */\nexport type CjsSandbox = {\n require: (path: string) => unknown;\n module: { exports: Record<string, unknown> };\n exports: Record<string, unknown>;\n __dirname: string;\n __filename: string;\n global: unknown;\n globalThis: unknown;\n [key: string]: unknown;\n};\n\n/**\n * Create a require function for the sandbox.\n * Maps @soda-gql package imports to their actual modules.\n */\nconst createSandboxRequire =\n () =>\n (path: string): unknown => {\n if (path === \"@soda-gql/core\") return sandboxCore;\n if (path === \"@soda-gql/core/adapter\") return sandboxCoreAdapter;\n if (path === \"@soda-gql/core/runtime\") return sandboxCoreRuntime;\n throw new Error(`Unknown module: ${path}`);\n };\n\n/**\n * Create a VM sandbox for executing CJS bundles.\n *\n * Sets up:\n * - require() handler for @soda-gql packages\n * - module.exports and exports pointing to the same object\n * - __dirname, __filename for path resolution\n * - global and globalThis pointing to the sandbox itself\n *\n * @param modulePath - Absolute path to the module being executed\n * @param additionalContext - Optional additional context properties\n * @returns Configured sandbox object\n */\nexport const createSandbox = (modulePath: string, additionalContext?: Record<string, unknown>): CjsSandbox => {\n const moduleExports: Record<string, unknown> = {};\n\n const sandbox: CjsSandbox = {\n require: createSandboxRequire(),\n module: { exports: moduleExports },\n exports: moduleExports,\n __dirname: resolve(modulePath, \"..\"),\n __filename: modulePath,\n global: undefined as unknown,\n globalThis: undefined as unknown,\n ...additionalContext,\n };\n\n // Wire global and globalThis to the sandbox itself\n sandbox.global = sandbox;\n sandbox.globalThis = sandbox;\n\n return sandbox;\n};\n\n/**\n * Execute CJS code in a sandbox and return the exports.\n *\n * Note: Reads from sandbox.module.exports because esbuild CJS output\n * reassigns module.exports via __toCommonJS(), replacing the original object.\n *\n * @param code - The CJS code to execute\n * @param modulePath - Absolute path to the module (for error messages)\n * @param additionalContext - Optional additional context properties\n * @returns The module's exports object\n */\nexport const executeSandbox = (\n code: string,\n modulePath: string,\n additionalContext?: Record<string, unknown>,\n): Record<string, unknown> => {\n const sandbox = createSandbox(modulePath, additionalContext);\n const context = createContext(sandbox);\n new Script(code, { filename: modulePath }).runInContext(context);\n\n // Read from module.exports due to esbuild's CommonJS transform\n return sandbox.module.exports;\n};\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { ModuleAnalysis, ModuleDefinition, ModuleImport } from \"../ast\";\n\nconst formatFactory = (expression: string): string => {\n const trimmed = expression.trim();\n if (!trimmed.includes(\"\\n\")) {\n return trimmed;\n }\n\n const lines = trimmed.split(\"\\n\").map((line) => line.trimEnd());\n const indented = lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join(\"\\n\");\n\n return `(\\n ${indented}\\n )`;\n};\n\ntype TreeNode = {\n expression?: string; // Leaf node with actual expression\n canonicalId?: string; // Canonical ID for this node\n children: Map<string, TreeNode>; // Branch node with children\n};\n\nconst buildTree = (definitions: readonly ModuleDefinition[]): Map<string, TreeNode> => {\n const roots = new Map<string, TreeNode>();\n\n definitions.forEach((definition) => {\n const parts = definition.astPath.split(\".\");\n const expressionText = definition.expression.trim();\n\n if (parts.length === 1) {\n // Top-level export\n const rootName = parts[0];\n if (rootName) {\n roots.set(rootName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n } else {\n // Nested export\n const rootName = parts[0];\n if (!rootName) return;\n\n let root = roots.get(rootName);\n if (!root) {\n root = { children: new Map() };\n roots.set(rootName, root);\n }\n\n let current = root;\n for (let i = 1; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n\n let child = current.children.get(part);\n if (!child) {\n child = { children: new Map() };\n current.children.set(part, child);\n }\n current = child;\n }\n\n const leafName = parts[parts.length - 1];\n if (leafName) {\n current.children.set(leafName, {\n expression: expressionText,\n canonicalId: definition.canonicalId,\n children: new Map(),\n });\n }\n }\n });\n\n return roots;\n};\n\n/**\n * Check if a string is a valid JavaScript identifier\n */\nconst isValidIdentifier = (name: string): boolean => {\n // JavaScript identifier regex: starts with letter, _, or $, followed by letters, digits, _, or $\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) && !isReservedWord(name);\n};\n\n/**\n * Check if a string is a JavaScript reserved word\n */\nconst isReservedWord = (name: string): boolean => {\n const reserved = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"export\",\n \"extends\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n \"let\",\n \"static\",\n \"enum\",\n \"await\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n ]);\n return reserved.has(name);\n};\n\n/**\n * Format a key for use in an object literal\n * Invalid identifiers are quoted, valid ones are not\n */\nconst formatObjectKey = (key: string): string => {\n return isValidIdentifier(key) ? key : `\"${key}\"`;\n};\n\nconst renderTreeNode = (node: TreeNode, indent: number): string => {\n if (node.expression && node.children.size === 0 && node.canonicalId) {\n // Leaf node - use addBuilder\n const expr = formatFactory(node.expression);\n return `registry.addElement(\"${node.canonicalId}\", () => ${expr})`;\n }\n\n // Branch node - render nested object\n const indentStr = \" \".repeat(indent);\n const entries = Array.from(node.children.entries()).map(([key, child]) => {\n const value = renderTreeNode(child, indent + 1);\n const formattedKey = formatObjectKey(key);\n return `${indentStr} ${formattedKey}: ${value},`;\n });\n\n if (entries.length === 0) {\n return \"{}\";\n }\n\n return `{\\n${entries.join(\"\\n\")}\\n${indentStr}}`;\n};\n\nconst buildNestedObject = (definition: readonly ModuleDefinition[]): string => {\n const tree = buildTree(definition);\n const declarations: string[] = [];\n const returnEntries: string[] = [];\n\n tree.forEach((node, rootName) => {\n if (node.children.size > 0) {\n // Has children - create a const declaration\n const objectLiteral = renderTreeNode(node, 2);\n declarations.push(` const ${rootName} = ${objectLiteral};`);\n returnEntries.push(rootName);\n } else if (node.expression && node.canonicalId) {\n // Single export - use addElement\n const expr = formatFactory(node.expression);\n declarations.push(` const ${rootName} = registry.addElement(\"${node.canonicalId}\", () => ${expr});`);\n returnEntries.push(rootName);\n }\n });\n\n const returnStatement =\n returnEntries.length > 0\n ? ` return {\\n${returnEntries.map((name) => ` ${name},`).join(\"\\n\")}\\n };`\n : \" return {};\";\n\n if (declarations.length === 0) {\n return returnStatement;\n }\n\n return `${declarations.join(\"\\n\")}\\n${returnStatement}`;\n};\n\n/**\n * Render import statements for the intermediate module using ModuleSummary.\n * Only includes imports from modules that have gql exports.\n */\nconst renderImportStatements = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): { imports: string; importedRootNames: Set<string>; namespaceImports: Set<string> } => {\n const importLines: string[] = [];\n const importedRootNames = new Set<string>();\n const namespaceImports = new Set<string>();\n\n // Group imports by resolved file path\n const importsByFile = new Map<string, ModuleImport[]>();\n\n analysis.imports.forEach((imp) => {\n if (imp.isTypeOnly) {\n return;\n }\n\n // Skip non-relative imports (external packages)\n if (!imp.source.startsWith(\".\")) {\n return;\n }\n\n const resolvedPath = resolveRelativeImportWithReferences({ filePath, specifier: imp.source, references: analyses });\n if (!resolvedPath) {\n return;\n }\n\n // Skip graphql-system imports - gql is provided via VM context\n if (resolvedPath === graphqlSystemPath) {\n return;\n }\n\n const imports = importsByFile.get(resolvedPath) ?? [];\n imports.push(imp);\n importsByFile.set(resolvedPath, imports);\n });\n\n // Render registry.importModule() for each file\n importsByFile.forEach((imports, filePath) => {\n // Check if this is a namespace import\n const namespaceImport = imports.find((imp) => imp.kind === \"namespace\");\n\n if (namespaceImport) {\n // Namespace import: const foo = yield registry.requestImport(\"path\");\n importLines.push(` const ${namespaceImport.local} = yield registry.requestImport(\"${filePath}\");`);\n namespaceImports.add(namespaceImport.local);\n importedRootNames.add(namespaceImport.local);\n } else {\n // Named imports: const { a, b } = yield registry.requestImport(\"path\");\n const rootNames = new Set<string>();\n\n imports.forEach((imp) => {\n if (imp.kind === \"named\" || imp.kind === \"default\") {\n rootNames.add(imp.local);\n importedRootNames.add(imp.local);\n }\n });\n\n if (rootNames.size > 0) {\n const destructured = Array.from(rootNames).sort().join(\", \");\n importLines.push(` const { ${destructured} } = yield registry.requestImport(\"${filePath}\");`);\n }\n }\n });\n\n return {\n imports: importLines.length > 0 ? `${importLines.join(\"\\n\")}` : \"\",\n importedRootNames,\n namespaceImports,\n };\n};\n\nexport const renderRegistryBlock = ({\n filePath,\n analysis,\n analyses,\n graphqlSystemPath,\n}: {\n filePath: string;\n analysis: ModuleAnalysis;\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemPath: string;\n}): string => {\n const { imports } = renderImportStatements({ filePath, analysis, analyses, graphqlSystemPath });\n\n return [`registry.setModule(\"${filePath}\", function*() {`, imports, \"\", buildNestedObject(analysis.definitions), \"});\"].join(\n \"\\n\",\n );\n};\n","import { createAsyncScheduler, createSyncScheduler, type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport {\n type AnyFragment,\n type AnyGqlDefine,\n type AnyOperation,\n Fragment,\n GqlDefine,\n GqlElement,\n Operation,\n} from \"@soda-gql/core\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport { builderErrors } from \"../errors\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport type { EvaluationRequest, IntermediateArtifactElement } from \"./types\";\n\nexport type IntermediateRegistry = ReturnType<typeof createIntermediateRegistry>;\n\ntype AcceptableArtifact = AnyFragment | AnyOperation | AnyGqlDefine;\ntype ArtifactModule = ArtifactRecord;\ntype ArtifactRecord = {\n readonly [key: string]: AcceptableArtifact | ArtifactRecord;\n};\n\n/**\n * Generator factory type for module evaluation.\n * The generator yields EvaluationRequest when it needs to import a dependency,\n * receives the resolved module as the yield result, and returns the final ArtifactModule.\n */\ntype GeneratorFactory = () => Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n\n/**\n * Internal frame type for the evaluation stack.\n */\ntype EvaluationFrame = {\n readonly filePath: string;\n readonly generator: Generator<EvaluationRequest, ArtifactModule, ArtifactModule>;\n resolvedDependency?: ArtifactModule;\n};\n\nexport const createIntermediateRegistry = ({ analyses }: { analyses?: Map<string, ModuleAnalysis> } = {}) => {\n const modules = new Map<string, GeneratorFactory>();\n const elements = new Map<string, AcceptableArtifact>();\n\n const setModule = (filePath: string, factory: GeneratorFactory) => {\n modules.set(filePath, factory);\n };\n\n /**\n * Creates an import request to be yielded by module generators.\n * Usage: `const { foo } = yield registry.requestImport(\"/path/to/module\");`\n */\n const requestImport = (filePath: string): EvaluationRequest => ({\n kind: \"import\",\n filePath,\n });\n\n const addElement = <TArtifact extends AcceptableArtifact>(canonicalId: string, factory: () => TArtifact) => {\n const builder = factory();\n GqlElement.setContext(builder, { canonicalId });\n // Don't evaluate yet - defer until all builders are registered\n elements.set(canonicalId, builder);\n return builder;\n };\n\n /**\n * Evaluate a single module and its dependencies using trampoline.\n * Returns the cached result or evaluates and caches if not yet evaluated.\n */\n const evaluateModule = (filePath: string, evaluated: Map<string, ArtifactModule>, inProgress: Set<string>): ArtifactModule => {\n // Already evaluated - return cached\n const cached = evaluated.get(filePath);\n if (cached) {\n return cached;\n }\n\n const stack: EvaluationFrame[] = [];\n\n // Start with the requested module\n const factory = modules.get(filePath);\n if (!factory) {\n throw builderErrors.runtimeModuleLoadFailed(filePath, \"\", `Module not found or yet to be registered: ${filePath}`);\n }\n stack.push({ filePath, generator: factory() });\n\n // Trampoline loop - process generators without deep recursion\n let frame: EvaluationFrame | undefined;\n while ((frame = stack[stack.length - 1])) {\n // Mark as in progress (for circular dependency detection)\n inProgress.add(frame.filePath);\n\n // Advance the generator\n const result =\n frame.resolvedDependency !== undefined ? frame.generator.next(frame.resolvedDependency) : frame.generator.next();\n\n // Clear the resolved dependency after use\n frame.resolvedDependency = undefined;\n\n if (result.done) {\n // Generator completed - cache result and pop frame\n evaluated.set(frame.filePath, result.value);\n inProgress.delete(frame.filePath);\n stack.pop();\n\n // If there's a parent frame waiting for this result, provide it\n const parentFrame = stack[stack.length - 1];\n if (parentFrame) {\n parentFrame.resolvedDependency = result.value;\n }\n } else {\n // Generator yielded - it needs a dependency\n const request = result.value;\n\n if (request.kind === \"import\") {\n const depPath = request.filePath;\n\n // Check if already evaluated (cached)\n const depCached = evaluated.get(depPath);\n if (depCached) {\n // Provide cached result without pushing new frame\n frame.resolvedDependency = depCached;\n } else {\n // Check for circular dependency\n if (inProgress.has(depPath)) {\n // If analyses is available, check if both modules have gql definitions\n // Only throw if both import source and target have gql definitions\n if (analyses) {\n const currentAnalysis = analyses.get(frame.filePath);\n const targetAnalysis = analyses.get(depPath);\n const currentHasGql = currentAnalysis && currentAnalysis.definitions.length > 0;\n const targetHasGql = targetAnalysis && targetAnalysis.definitions.length > 0;\n\n if (!currentHasGql || !targetHasGql) {\n // One or both modules have no gql definitions - allow circular import\n frame.resolvedDependency = {};\n continue;\n }\n }\n throw builderErrors.internalInvariant(`Circular dependency detected: ${depPath}`, filePath);\n }\n\n // Need to evaluate dependency first\n const depFactory = modules.get(depPath);\n if (!depFactory) {\n throw builderErrors.runtimeModuleLoadFailed(depPath, \"\", `Module not found or yet to be registered: ${depPath}`);\n }\n\n // Push new frame for dependency\n stack.push({\n filePath: depPath,\n generator: depFactory(),\n });\n }\n }\n }\n }\n\n const result = evaluated.get(filePath);\n if (!result) {\n throw builderErrors.runtimeModuleLoadFailed(filePath, \"\", `Module evaluation failed: ${filePath}`);\n }\n return result;\n };\n\n /**\n * Build artifacts record from evaluated elements.\n */\n const buildArtifacts = (): Record<string, IntermediateArtifactElement> => {\n const artifacts: Record<string, IntermediateArtifactElement> = {};\n for (const [canonicalId, element] of elements.entries()) {\n if (element instanceof Fragment) {\n artifacts[canonicalId] = { type: \"fragment\", element };\n } else if (element instanceof Operation) {\n artifacts[canonicalId] = { type: \"operation\", element };\n } else if (element instanceof GqlDefine) {\n artifacts[canonicalId] = { type: \"define\", element };\n }\n }\n return artifacts;\n };\n\n /**\n * Generator that evaluates all elements using the effect system.\n * Uses ParallelEffect to enable parallel evaluation in async mode.\n * In sync mode, ParallelEffect executes effects sequentially.\n */\n function* evaluateElementsGen(): EffectGenerator<void> {\n const effects = Array.from(elements.values(), (element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n }\n\n /**\n * Synchronous evaluation - evaluates all modules and elements synchronously.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n const evaluate = (): Record<string, IntermediateArtifactElement> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (each evaluation handles its own dependencies)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using sync scheduler\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw builderErrors.internalInvariant(`Element evaluation failed: ${result.error.message}`, \"registry.evaluate\");\n }\n\n return buildArtifacts();\n };\n\n /**\n * Asynchronous evaluation - evaluates all modules and elements with async support.\n * Supports async metadata factories and other async operations.\n */\n const evaluateAsync = async (): Promise<Record<string, IntermediateArtifactElement>> => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n // Evaluate all modules (module evaluation is synchronous - no I/O operations)\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n\n // Then, evaluate all elements using async scheduler\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => evaluateElementsGen());\n\n if (result.isErr()) {\n throw builderErrors.internalInvariant(`Element evaluation failed: ${result.error.message}`, \"registry.evaluateAsync\");\n }\n\n return buildArtifacts();\n };\n\n /**\n * Evaluate all modules synchronously using trampoline.\n * This runs the module dependency resolution without element evaluation.\n * Call this before getElements() when using external scheduler control.\n */\n const evaluateModules = (): void => {\n const evaluated = new Map<string, ArtifactModule>();\n const inProgress = new Set<string>();\n\n for (const filePath of modules.keys()) {\n if (!evaluated.has(filePath)) {\n evaluateModule(filePath, evaluated, inProgress);\n }\n }\n };\n\n /**\n * Get all registered elements for external effect creation.\n * Call evaluateModules() first to ensure all modules have been evaluated.\n */\n const getElements = (): AcceptableArtifact[] => {\n return Array.from(elements.values());\n };\n\n const clear = () => {\n modules.clear();\n elements.clear();\n };\n\n return {\n setModule,\n requestImport,\n addElement,\n evaluate,\n evaluateAsync,\n evaluateModules,\n getElements,\n buildArtifacts,\n clear,\n };\n};\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { extname, resolve } from \"node:path\";\nimport { createContext, Script } from \"node:vm\";\nimport { type EffectGenerator, ParallelEffect } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport { type BuilderError, builderErrors, isBuilderError } from \"../errors\";\nimport { ElementEvaluationEffect } from \"../scheduler\";\nimport { createSandbox } from \"../vm/sandbox\";\nimport { renderRegistryBlock } from \"./codegen\";\nimport { createIntermediateRegistry } from \"./registry\";\nimport type { IntermediateArtifactElement, IntermediateModule } from \"./types\";\n\nexport type BuildIntermediateModulesInput = {\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly targetFiles: Set<string>;\n readonly graphqlSystemPath: string;\n};\n\ntype TransformSync = typeof import(\"@swc/core\").transformSync;\nlet _transformSync: TransformSync | undefined;\nconst getTransformSync = (): TransformSync => {\n if (!_transformSync) {\n if (typeof import.meta.url !== \"string\") {\n throw new Error(\"@swc/core cannot be resolved: import.meta.url is unavailable in CJS bundle context\");\n }\n const localRequire = createRequire(import.meta.url);\n _transformSync = localRequire(\"@swc/core\").transformSync;\n }\n return _transformSync!;\n};\n\nconst transpile = ({ filePath, sourceCode }: { filePath: string; sourceCode: string }): Result<string, BuilderError> => {\n try {\n const result = getTransformSync()(sourceCode, {\n filename: `${filePath}.ts`,\n jsc: {\n parser: {\n syntax: \"typescript\",\n tsx: false,\n },\n target: \"es2022\",\n },\n module: {\n type: \"es6\",\n },\n sourceMaps: false,\n minify: false,\n });\n\n return ok(result.code);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return err({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath: filePath,\n astPath: \"\",\n message: `SWC transpilation failed: ${message}`,\n });\n }\n};\n\n/**\n * Resolve graphql system path to the bundled CJS file.\n * Accepts both .ts (for backward compatibility) and .cjs paths.\n * Maps .ts to sibling .cjs file if it exists.\n */\nfunction resolveGraphqlSystemPath(configPath: string): string {\n const ext = extname(configPath);\n\n // If already pointing to .cjs, use as-is\n if (ext === \".cjs\") {\n return resolve(process.cwd(), configPath);\n }\n\n // If pointing to .ts, try to resolve to sibling .cjs\n if (ext === \".ts\") {\n const basePath = configPath.slice(0, -3); // Remove .ts\n const cjsPath = `${basePath}.cjs`;\n const resolvedCjsPath = resolve(process.cwd(), cjsPath);\n\n // Check if .cjs exists, otherwise fall back to .ts (for error messages)\n if (existsSync(resolvedCjsPath)) {\n return resolvedCjsPath;\n }\n\n // Fall back to .ts path (will fail later with clearer error)\n return resolve(process.cwd(), configPath);\n }\n\n // For other extensions or no extension, use as-is\n return resolve(process.cwd(), configPath);\n}\n\n/**\n * Bundle and execute GraphQL system module using rspack + memfs.\n * Creates a self-contained bundle that can run in VM context.\n * This is cached per session to avoid re-bundling.\n */\nlet cachedGql: unknown = null;\nlet cachedModulePath: string | null = null;\n\n/**\n * Clear the cached gql module.\n * Call this between test runs to ensure clean state.\n * @internal - exported for testing purposes only\n */\nexport const __clearGqlCache = (): void => {\n cachedGql = null;\n cachedModulePath = null;\n};\n\nfunction executeGraphqlSystemModule(modulePath: string): { gql: unknown } {\n // Use cached module if same path\n if (cachedModulePath === modulePath && cachedGql !== null) {\n return { gql: cachedGql };\n }\n\n let bundledCode: string;\n try {\n bundledCode = readFileSync(modulePath, \"utf-8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw builderErrors.runtimeModuleLoadFailed(modulePath, \"\", `Failed to read GraphQL system module: ${message}`, error);\n }\n\n try {\n // Create sandbox and execute\n const sandbox = createSandbox(modulePath);\n new Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);\n\n // Read exported gql (handle both direct export and default export)\n const finalExports = sandbox.module.exports;\n const exportedGql = finalExports.gql ?? finalExports.default;\n\n if (exportedGql === undefined) {\n throw builderErrors.runtimeModuleLoadFailed(\n modulePath,\n \"\",\n `No 'gql' export found in GraphQL system module: ${modulePath}`,\n );\n }\n\n // Cache the result\n cachedGql = exportedGql;\n cachedModulePath = modulePath;\n\n return { gql: cachedGql };\n } catch (error) {\n if (isBuilderError(error)) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw builderErrors.runtimeModuleLoadFailed(modulePath, \"\", `GraphQL system module execution failed: ${message}`, error);\n }\n}\n\n/**\n * Build intermediate modules from dependency graph.\n * Each intermediate module corresponds to one source file.\n */\nexport const generateIntermediateModules = function* ({\n analyses,\n targetFiles,\n graphqlSystemPath,\n}: BuildIntermediateModulesInput): Generator<IntermediateModule, void, undefined> {\n for (const filePath of targetFiles) {\n const analysis = analyses.get(filePath);\n if (!analysis) {\n continue;\n }\n\n // Generate source code for this intermediate module\n const sourceCode = renderRegistryBlock({ filePath, analysis, analyses, graphqlSystemPath });\n\n // Debug: log the generated source code\n if (process.env.DEBUG_INTERMEDIATE_MODULE) {\n console.log(\"=== Intermediate module source ===\");\n console.log(\"FilePath:\", filePath);\n console.log(\n \"Definitions:\",\n analysis.definitions.map((d) => d.astPath),\n );\n console.log(\"Source code:\\n\", sourceCode);\n console.log(\"=================================\");\n }\n\n // Transpile TypeScript to JavaScript using SWC\n const transpiledCodeResult = transpile({ filePath, sourceCode });\n if (transpiledCodeResult.isErr()) {\n throw transpiledCodeResult.error;\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 // Memory optimization: transpiledCode is only needed to create the Script object.\n // After script creation, we can release it to reduce memory footprint.\n // sourceCode is only needed for debugging (DEBUG_INTERMEDIATE_MODULE env var).\n const shouldKeepSource = !!process.env.DEBUG_INTERMEDIATE_MODULE;\n yield {\n filePath,\n canonicalIds,\n sourceCode: shouldKeepSource ? sourceCode : \"\",\n transpiledCode: \"\", // Released after Script creation\n contentHash,\n script,\n };\n }\n};\n\nexport type EvaluateIntermediateModulesInput = {\n intermediateModules: Map<string, IntermediateModule>;\n graphqlSystemPath: string;\n analyses: Map<string, ModuleAnalysis>;\n};\n\n/**\n * Set up VM context and run intermediate module scripts.\n * Returns the registry for evaluation.\n */\nconst setupIntermediateModulesContext = ({\n intermediateModules,\n graphqlSystemPath,\n analyses,\n}: EvaluateIntermediateModulesInput) => {\n const registry = createIntermediateRegistry({ analyses });\n const gqlImportPath = resolveGraphqlSystemPath(graphqlSystemPath);\n\n const { gql } = executeGraphqlSystemModule(gqlImportPath);\n\n const vmContext = createContext({ gql, registry });\n\n for (const { script, filePath } of intermediateModules.values()) {\n try {\n script.runInContext(vmContext);\n } catch (error) {\n if (isBuilderError(error)) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw builderErrors.runtimeModuleLoadFailed(filePath, \"\", `Error evaluating intermediate module: ${message}`, error);\n }\n }\n\n return registry;\n};\n\n/**\n * Synchronous evaluation of intermediate modules.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\nexport const evaluateIntermediateModules = (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = registry.evaluate();\n registry.clear();\n return elements;\n};\n\n/**\n * Asynchronous evaluation of intermediate modules.\n * Supports async metadata factories and other async operations.\n */\nexport const evaluateIntermediateModulesAsync = async (input: EvaluateIntermediateModulesInput) => {\n const registry = setupIntermediateModulesContext(input);\n const elements = await registry.evaluateAsync();\n registry.clear();\n return elements;\n};\n\n/**\n * Generator version of evaluateIntermediateModules for external scheduler control.\n * Yields effects for element evaluation, enabling unified scheduler at the root level.\n *\n * This function:\n * 1. Sets up the VM context and runs intermediate module scripts\n * 2. Runs synchronous module evaluation (trampoline - no I/O)\n * 3. Yields element evaluation effects via ParallelEffect\n * 4. Returns the artifacts record\n */\nexport function* evaluateIntermediateModulesGen(\n input: EvaluateIntermediateModulesInput,\n): EffectGenerator<Record<string, IntermediateArtifactElement>> {\n const registry = setupIntermediateModulesContext(input);\n\n // Run synchronous module evaluation (trampoline pattern, no I/O)\n registry.evaluateModules();\n\n // Yield element evaluation effects\n const elements = registry.getElements();\n const effects = elements.map((element) => new ElementEvaluationEffect(element));\n if (effects.length > 0) {\n yield* new ParallelEffect(effects).run();\n }\n\n const artifacts = registry.buildArtifacts();\n registry.clear();\n return artifacts;\n}\n","/**\n * Helper for identifying graphql-system files, inject modules, and import specifiers.\n * Provides robust detection across symlinks, case-insensitive filesystems, and user-defined aliases.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { resolveRelativeImportWithExistenceCheck } from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\n\nexport type GraphqlSystemIdentifyHelper = {\n readonly isGraphqlSystemFile: (input: { filePath: string }) => boolean;\n readonly isGraphqlSystemImportSpecifier: (input: { filePath: string; specifier: string }) => boolean;\n /**\n * Check if a file is an internal module that should be stubbed at runtime.\n * This includes graphql-system and inject modules (scalars, adapter).\n */\n readonly isInternalModuleFile: (input: { filePath: string }) => boolean;\n};\n\n/**\n * Create a canonical file name getter based on platform.\n * On case-sensitive filesystems, paths are returned as-is.\n * On case-insensitive filesystems, paths are lowercased for comparison.\n */\nconst createGetCanonicalFileName = (useCaseSensitiveFileNames: boolean): ((path: string) => string) => {\n return useCaseSensitiveFileNames ? (path: string) => path : (path: string) => path.toLowerCase();\n};\n\n/**\n * Detect if the filesystem is case-sensitive.\n * We assume Unix-like systems are case-sensitive, and Windows is not.\n */\nconst getUseCaseSensitiveFileNames = (): boolean => {\n return process.platform !== \"win32\";\n};\n\n/**\n * Create a GraphqlSystemIdentifyHelper from the resolved config.\n * Uses canonical path comparison to handle casing, symlinks, and aliases.\n */\nexport const createGraphqlSystemIdentifyHelper = (config: ResolvedSodaGqlConfig): GraphqlSystemIdentifyHelper => {\n const getCanonicalFileName = createGetCanonicalFileName(getUseCaseSensitiveFileNames());\n\n const toCanonical = (file: string): string => {\n const resolved = resolve(file);\n // Use realpathSync to resolve symlinks for accurate comparison\n try {\n return getCanonicalFileName(realpathSync(resolved));\n } catch {\n // If realpath fails (file doesn't exist yet), fall back to resolved path\n return getCanonicalFileName(resolved);\n }\n };\n\n // Derive graphql system path from outdir (assume index.ts as default entry)\n const graphqlSystemPath = resolve(config.outdir, \"index.ts\");\n const canonicalGraphqlSystemPath = toCanonical(graphqlSystemPath);\n\n // Build canonical alias map\n const canonicalAliases = new Set(config.graphqlSystemAliases.map((alias) => alias));\n\n // Collect inject module paths (scalars, adapter) from all schemas.\n // Paths are resolved via realpath to handle symlinks accurately.\n const canonicalInjectPaths = new Set<string>();\n for (const schemaConfig of Object.values(config.schemas)) {\n canonicalInjectPaths.add(toCanonical(schemaConfig.inject.scalars));\n if (schemaConfig.inject.adapter) {\n canonicalInjectPaths.add(toCanonical(schemaConfig.inject.adapter));\n }\n }\n\n return {\n isGraphqlSystemFile: ({ filePath }: { filePath: string }) => {\n return toCanonical(filePath) === canonicalGraphqlSystemPath;\n },\n isGraphqlSystemImportSpecifier: ({ filePath, specifier }: { filePath: string; specifier: string }) => {\n // Check against aliases first if configured\n if (canonicalAliases.has(specifier)) {\n return true;\n }\n\n // Only try to resolve relative imports (starting with . or ..)\n // External specifiers without an alias configured should not match\n if (!specifier.startsWith(\".\")) {\n return false;\n }\n\n // Try to resolve as relative import\n const resolved = resolveRelativeImportWithExistenceCheck({ filePath, specifier });\n if (!resolved) {\n return false;\n }\n\n return toCanonical(resolved) === canonicalGraphqlSystemPath;\n },\n isInternalModuleFile: ({ filePath }: { filePath: string }) => {\n const canonical = toCanonical(filePath);\n return canonical === canonicalGraphqlSystemPath || canonicalInjectPaths.has(canonical);\n },\n };\n};\n","import { parseCanonicalId, validateCanonicalId } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../errors\";\nimport { builderErrors } from \"../errors\";\n\n/**\n * Parsed canonical ID components.\n */\nexport type ParsedCanonicalId = {\n readonly filePath: string;\n readonly astPath: string;\n};\n\n/**\n * Parse a canonical ID with validation.\n * Returns a Result with parsed components or a BuilderError.\n *\n * @param canonicalId - The canonical ID to parse\n * @returns Result with {filePath, astPath} or BuilderError\n */\nexport const parseCanonicalIdSafe = (canonicalId: string): Result<ParsedCanonicalId, BuilderError> => {\n const validation = validateCanonicalId(canonicalId);\n\n if (!validation.isValid) {\n return err(builderErrors.canonicalPathInvalid(canonicalId, validation.reason));\n }\n\n return ok(parseCanonicalId(canonicalId));\n};\n\n/**\n * Extract file path from canonical ID with validation.\n * Returns a Result with the file path or a BuilderError.\n *\n * @param canonicalId - The canonical ID to extract from\n * @returns Result with filePath or BuilderError\n */\nexport const extractFilePathSafe = (canonicalId: string): Result<string, BuilderError> => {\n return parseCanonicalIdSafe(canonicalId).map(({ filePath }) => filePath);\n};\n","import { createHash } from \"node:crypto\";\n\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\nimport type { BuilderError } from \"../types\";\nimport { parseCanonicalIdSafe } from \"./canonical-id-utils\";\nimport type { BuilderArtifactElement, BuilderArtifactElementMetadata } from \"./types\";\n\nconst computeContentHash = (prebuild: unknown): string => {\n const hash = createHash(\"sha1\");\n hash.update(JSON.stringify(prebuild));\n return hash.digest(\"hex\");\n};\n\nconst emitRegistrationError = (filePath: string, astPath: string, message: string): BuilderError => ({\n code: \"RUNTIME_MODULE_LOAD_FAILED\",\n filePath,\n astPath,\n message,\n});\n\ntype AggregateInput = {\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n};\n\nexport const aggregate = ({ analyses, elements }: AggregateInput): Result<Map<string, BuilderArtifactElement>, BuilderError> => {\n const registry = new Map<string, BuilderArtifactElement>();\n\n for (const analysis of analyses.values()) {\n for (const definition of analysis.definitions) {\n // Validate canonical ID format early\n const parsedResult = parseCanonicalIdSafe(definition.canonicalId);\n if (parsedResult.isErr()) {\n return err(parsedResult.error);\n }\n const { filePath, astPath } = parsedResult.value;\n\n const element = elements[definition.canonicalId];\n if (!element) {\n const availableIds = Object.keys(elements).join(\", \");\n const message = `ARTIFACT_NOT_FOUND_IN_RUNTIME_MODULE: ${definition.canonicalId}\\nAvailable: ${availableIds}`;\n return err(emitRegistrationError(filePath, astPath, message));\n }\n\n // Skip define elements - they exist only for builder evaluation, not final output\n if (element.type === \"define\") {\n continue;\n }\n\n if (registry.has(definition.canonicalId)) {\n return err(emitRegistrationError(filePath, astPath, `ARTIFACT_ALREADY_REGISTERED`));\n }\n\n // Use file path from canonical ID (which is relative when baseDir is set)\n const metadata: BuilderArtifactElementMetadata = {\n sourcePath: filePath,\n contentHash: \"\", // Will be computed after prebuild creation\n };\n\n if (element.type === \"fragment\") {\n const prebuild = {\n typename: element.element.typename,\n key: element.element.key,\n schemaLabel: element.element.schemaLabel,\n };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"fragment\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n if (element.type === \"operation\") {\n const prebuild = {\n operationType: element.element.operationType,\n operationName: element.element.operationName,\n schemaLabel: element.element.schemaLabel,\n document: element.element.document,\n variableNames: element.element.variableNames,\n metadata: element.element.metadata,\n };\n registry.set(definition.canonicalId, {\n id: definition.canonicalId,\n type: \"operation\",\n prebuild,\n metadata: { ...metadata, contentHash: computeContentHash(prebuild) },\n });\n continue;\n }\n\n return err(emitRegistrationError(filePath, astPath, \"UNKNOWN_ARTIFACT_KIND\"));\n }\n }\n\n return ok(registry);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"../types\";\nimport { extractFilePathSafe } from \"./canonical-id-utils\";\nimport type { IntermediateElements } from \"./types\";\n\nexport const checkIssues = ({ elements }: { elements: IntermediateElements }): Result<string[], BuilderError> => {\n const operationNames = new Set<string>();\n\n for (const [canonicalId, { type, element }] of Object.entries(elements)) {\n if (type !== \"operation\") {\n continue;\n }\n\n if (operationNames.has(element.operationName)) {\n // Validate canonical ID before using\n const filePathResult = extractFilePathSafe(canonicalId);\n if (filePathResult.isErr()) {\n return err(filePathResult.error);\n }\n\n const sources = [filePathResult.value];\n return err({\n code: \"DOC_DUPLICATE\",\n message: `Duplicate document name: ${element.operationName}`,\n name: element.operationName,\n sources,\n });\n }\n\n operationNames.add(element.operationName);\n }\n\n return ok([]);\n};\n","import { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { ModuleLoadStats } from \"../discovery\";\nimport type { BuilderError } from \"../types\";\nimport { aggregate } from \"./aggregate\";\nimport { checkIssues } from \"./issue-handler\";\nimport type { BuilderArtifact, IntermediateElements } from \"./types\";\n\ntype BuildArtifactInput = {\n readonly elements: IntermediateElements;\n readonly analyses: ReadonlyMap<string, ModuleAnalysis>;\n readonly stats: ModuleLoadStats;\n};\n\nexport const buildArtifact = ({\n elements,\n analyses,\n stats: cache,\n}: BuildArtifactInput): Result<BuilderArtifact, BuilderError> => {\n const issuesResult = checkIssues({ elements });\n if (issuesResult.isErr()) {\n return err(issuesResult.error);\n }\n\n const warnings = issuesResult.value;\n\n const aggregationResult = aggregate({ analyses, elements });\n if (aggregationResult.isErr()) {\n return err(aggregationResult.error);\n }\n\n return ok({\n elements: Object.fromEntries(aggregationResult.value.entries()),\n report: {\n durationMs: 0,\n warnings,\n stats: cache,\n },\n } satisfies BuilderArtifact);\n};\n","/**\n * Shared utilities for AST traversal and scope tracking.\n * Used by both TypeScript and SWC adapters.\n */\n\n/**\n * Scope frame for tracking AST path segments\n */\nexport type ScopeFrame = {\n /** Name segment (e.g., \"MyComponent\", \"useQuery\", \"_arrow_1\") */\n readonly nameSegment: string;\n /** Kind of scope */\n readonly kind: \"function\" | \"class\" | \"variable\" | \"property\" | \"method\" | \"expression\";\n};\n\n/**\n * Build AST path from scope stack\n */\nexport const buildAstPath = (stack: readonly ScopeFrame[]): string => {\n return stack.map((frame) => frame.nameSegment).join(\".\");\n};\n\n/**\n * Create an occurrence tracker for disambiguating anonymous/duplicate scopes.\n */\nexport const createOccurrenceTracker = (): {\n getNextOccurrence: (key: string) => number;\n} => {\n const occurrenceCounters = new Map<string, number>();\n\n return {\n getNextOccurrence(key: string): number {\n const current = occurrenceCounters.get(key) ?? 0;\n occurrenceCounters.set(key, current + 1);\n return current;\n },\n };\n};\n\n/**\n * Create a path uniqueness tracker to ensure AST paths are unique.\n */\nexport const createPathTracker = (): {\n ensureUniquePath: (basePath: string) => string;\n} => {\n const usedPaths = new Set<string>();\n\n return {\n ensureUniquePath(basePath: string): string {\n let path = basePath;\n let suffix = 0;\n while (usedPaths.has(path)) {\n suffix++;\n path = `${basePath}$${suffix}`;\n }\n usedPaths.add(path);\n return path;\n },\n };\n};\n\n/**\n * Create an export bindings map from module exports.\n * Maps local variable names to their exported names.\n */\nexport const createExportBindingsMap = <T extends { kind: string; local?: string; exported: string; isTypeOnly?: boolean }>(\n exports: readonly T[],\n): Map<string, string> => {\n const exportBindings = new Map<string, string>();\n exports.forEach((exp) => {\n if (exp.kind === \"named\" && exp.local && !exp.isTypeOnly) {\n exportBindings.set(exp.local, exp.exported);\n }\n });\n return exportBindings;\n};\n","/**\n * SWC adapter for the analyzer core.\n * Implements parser-specific logic using the SWC parser.\n */\n\nimport { createRequire } from \"node:module\";\nimport {\n createCanonicalId,\n createCanonicalTracker,\n createSwcSpanConverter,\n type ScopeHandle,\n type SwcSpanConverter,\n} from \"@soda-gql/common\";\nimport type { CallExpression, ImportDeclaration, Module } from \"@swc/types\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\n\n/**\n * Extended SWC Module with filePath attached (similar to ts.SourceFile.fileName)\n */\ntype SwcModule = Module & {\n __filePath: string;\n /** Offset to subtract from spans to normalize to 0-based source indices */\n __spanOffset: number;\n /** Converter for UTF-8 byte offsets to UTF-16 char indices */\n __spanConverter: SwcSpanConverter;\n};\n\nimport { createStandardDiagnostic } from \"../common/detection\";\nimport type {\n AnalyzeModuleInput,\n DiagnosticLocation,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n} from \"../types\";\n\nconst collectImports = (module: Module): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n const handle = (declaration: ImportDeclaration) => {\n const source = declaration.source.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"named\",\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"namespace\",\n isTypeOnly: false,\n });\n return;\n }\n if (specifier.type === \"ImportDefaultSpecifier\") {\n imports.push({\n source,\n local: specifier.local.value,\n kind: \"default\",\n isTypeOnly: false,\n });\n }\n });\n };\n\n module.body.forEach((item) => {\n if (item.type === \"ImportDeclaration\") {\n handle(item);\n return;\n }\n // Handle module declarations with import declarations\n if (\n \"declaration\" in item &&\n item.declaration &&\n \"type\" in item.declaration &&\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any).type === \"ImportDeclaration\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n handle(item.declaration as any as ImportDeclaration);\n }\n });\n\n return imports;\n};\n\nconst collectExports = (module: Module): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const handle = (declaration: any) => {\n if (declaration.type === \"ExportDeclaration\") {\n if (declaration.declaration.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n declaration.declaration.declarations.forEach((decl: any) => {\n if (decl.id.type === \"Identifier\") {\n exports.push({\n kind: \"named\",\n exported: decl.id.value,\n local: decl.id.value,\n isTypeOnly: false,\n });\n }\n });\n }\n if (declaration.declaration.type === \"FunctionDeclaration\") {\n const ident = declaration.declaration.identifier;\n if (ident) {\n exports.push({\n kind: \"named\",\n exported: ident.value,\n local: ident.value,\n isTypeOnly: false,\n });\n }\n }\n return;\n }\n\n if (declaration.type === \"ExportNamedDeclaration\") {\n const source = declaration.source?.value;\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type !== \"ExportSpecifier\") {\n return;\n }\n const exported = specifier.exported ? specifier.exported.value : specifier.orig.value;\n const local = specifier.orig.value;\n if (source) {\n exports.push({\n kind: \"reexport\",\n exported,\n local,\n source,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n return;\n }\n exports.push({\n kind: \"named\",\n exported,\n local,\n isTypeOnly: Boolean(specifier.isTypeOnly),\n });\n });\n return;\n }\n\n if (declaration.type === \"ExportAllDeclaration\") {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: declaration.source.value,\n isTypeOnly: false,\n });\n return;\n }\n\n if (declaration.type === \"ExportDefaultDeclaration\" || declaration.type === \"ExportDefaultExpression\") {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n };\n\n module.body.forEach((item) => {\n if (\n item.type === \"ExportDeclaration\" ||\n item.type === \"ExportNamedDeclaration\" ||\n item.type === \"ExportAllDeclaration\" ||\n item.type === \"ExportDefaultDeclaration\" ||\n item.type === \"ExportDefaultExpression\"\n ) {\n handle(item);\n return;\n }\n\n if (\"declaration\" in item && item.declaration) {\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n const declaration = item.declaration as any;\n if (\n declaration.type === \"ExportDeclaration\" ||\n declaration.type === \"ExportNamedDeclaration\" ||\n declaration.type === \"ExportAllDeclaration\" ||\n declaration.type === \"ExportDefaultDeclaration\" ||\n declaration.type === \"ExportDefaultExpression\"\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Complex SWC AST type\n handle(declaration as any);\n }\n }\n });\n\n return exports;\n};\n\nconst collectGqlIdentifiers = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\n : // biome-ignore lint/suspicious/noExplicitAny: SWC AST type checking\n \"declaration\" in item && item.declaration && (item.declaration as any).type === \"ImportDeclaration\"\n ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n if (!declaration) {\n return;\n }\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n // Only add non-renamed imports (imported exists when renamed: \"gql as g\")\n if (imported === \"gql\" && !specifier.imported) {\n identifiers.add(specifier.local.value);\n }\n }\n });\n });\n return identifiers;\n};\n\nconst isGqlCall = (identifiers: ReadonlySet<string>, call: CallExpression): boolean => {\n const callee = call.callee;\n if (callee.type !== \"MemberExpression\") {\n return false;\n }\n\n if (callee.object.type !== \"Identifier\") {\n return false;\n }\n\n if (!identifiers.has(callee.object.value)) {\n return false;\n }\n\n if (callee.property.type !== \"Identifier\") {\n return false;\n }\n\n const firstArg = call.arguments[0];\n if (!firstArg?.expression || firstArg.expression.type !== \"ArrowFunctionExpression\") {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: any): CallExpression | null => {\n if (!node || node.type !== \"CallExpression\") {\n return null;\n }\n\n // Check if this is directly a gql call\n if (isGqlCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\") {\n return null;\n }\n\n // Recursively check the object of the member expression\n // e.g., for `gql.default(...).attach(...)`, callee.object is `gql.default(...)`\n return unwrapMethodChains(identifiers, callee.object);\n};\n\nconst collectAllDefinitions = ({\n module,\n gqlIdentifiers,\n imports: _imports,\n exports,\n source,\n baseDir,\n}: {\n module: SwcModule;\n gqlIdentifiers: ReadonlySet<string>;\n imports: readonly ModuleImport[];\n exports: readonly ModuleExport[];\n source: string;\n baseDir?: string;\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly CallExpression[];\n} => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const getPropertyName = (property: any): string | null => {\n if (!property) {\n return null;\n }\n if (property.type === \"Identifier\") {\n return property.value;\n }\n if (property.type === \"StringLiteral\" || property.type === \"NumericLiteral\") {\n return property.value;\n }\n return null;\n };\n\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: module.__filePath,\n baseDir,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n // Use underscore separator instead of # to ensure valid JavaScript identifiers\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `_${kind}_${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n const expressionFromCall = (call: CallExpression): string => {\n // Normalize span by subtracting the module's span offset, then convert byte→char\n const spanOffset = module.__spanOffset;\n const converter = module.__spanConverter;\n let start = converter.byteOffsetToCharIndex(call.span.start - spanOffset);\n const end = converter.byteOffsetToCharIndex(call.span.end - spanOffset);\n\n // Adjust when span starts one character after the leading \"g\"\n if (start > 0 && source[start] === \"q\" && source[start - 1] === \"g\" && source.slice(start, start + 3) === \"ql.\") {\n start -= 1;\n }\n\n const raw = source.slice(start, end);\n const marker = raw.indexOf(\"gql\");\n const expression = marker >= 0 ? raw.slice(marker) : raw;\n\n // Strip trailing semicolons and whitespace that SWC may include in the span\n // TypeScript's node.getText() doesn't include these, so we normalize to match\n return expression.replace(/\\s*;\\s*$/, \"\");\n };\n\n // Check if we're inside a class property (class property scope tracking is unreliable)\n const isInClassProperty = (stack: ScopeFrame[]): boolean =>\n stack.some((frame, i) => frame.kind === \"property\" && stack[i - 1]?.kind === \"class\");\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any, stack: ScopeFrame[]) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (node.type === \"CallExpression\") {\n const gqlCall = unwrapMethodChains(gqlIdentifiers, node);\n // Skip definition collection for gql calls inside class properties\n // (CLASS_PROPERTY diagnostic is still emitted by collectClassPropertyDiagnostics)\n if (gqlCall && !isInClassProperty(stack)) {\n // If scopeStack is empty (unbound gql call), enter an anonymous scope\n const needsAnonymousScope = tracker.currentDepth() === 0;\n let anonymousScopeHandle: ScopeHandle | undefined;\n\n if (needsAnonymousScope) {\n const anonymousName = getAnonymousName(\"anonymous\");\n anonymousScopeHandle = tracker.enterScope({\n segment: anonymousName,\n kind: \"expression\",\n stableKey: \"anonymous\",\n });\n }\n\n try {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: expressionFromCall(gqlCall),\n });\n } finally {\n // Exit anonymous scope if we entered one\n if (anonymousScopeHandle) {\n tracker.exitScope(anonymousScopeHandle);\n }\n }\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (node.type === \"VariableDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.declarations?.forEach((decl: any) => {\n if (decl.id?.type === \"Identifier\") {\n const varName = decl.id.value;\n\n if (decl.init) {\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(decl.init, newStack);\n });\n }\n } else if (decl.init) {\n // Handle destructuring patterns (ObjectPattern, ArrayPattern)\n // Visit the initializer without entering a scope (anonymous gql calls will handle their own scope)\n visit(decl.init, stack);\n }\n });\n return;\n }\n\n // Function declaration\n if (node.type === \"FunctionDeclaration\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Arrow function\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowName = getAnonymousName(\"arrow\");\n\n if (node.body) {\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Function expression\n if (node.type === \"FunctionExpression\") {\n const funcName = node.identifier?.value ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n visit(node.body, newStack);\n });\n }\n return;\n }\n\n // Class declaration\n if (node.type === \"ClassDeclaration\") {\n const className = node.identifier?.value ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"ClassMethod\" || member.type === \"ClassProperty\") {\n const memberName = member.key?.value ?? null;\n if (memberName) {\n const memberKind = member.type === \"ClassMethod\" ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (member.type === \"ClassMethod\" && member.function?.body) {\n visit(member.function.body, memberStack);\n } else if (member.type === \"ClassProperty\" && member.value) {\n visit(member.value, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (node.type === \"KeyValueProperty\") {\n const propName = getPropertyName(node.key);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.value, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n if (Array.isArray(node)) {\n for (const child of node) {\n visit(child, stack);\n }\n } else {\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child, stack);\n }\n } else if (value && typeof value === \"object\") {\n visit(value, stack);\n }\n }\n }\n };\n\n // Start traversal from top-level statements\n module.body.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(module.__filePath, item.astPath, { baseDir }),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n// ============================================================================\n// Diagnostic Collection\n// ============================================================================\n\n/**\n * Get location from an SWC node span\n */\nconst getLocation = (module: SwcModule, span: { start: number; end: number }): DiagnosticLocation => {\n const converter = module.__spanConverter;\n const start = converter.byteOffsetToCharIndex(span.start - module.__spanOffset);\n const end = converter.byteOffsetToCharIndex(span.end - module.__spanOffset);\n return { start, end };\n};\n\n/**\n * Collect diagnostics for invalid import patterns from graphql-system\n */\nconst collectImportDiagnostics = (module: SwcModule, helper: GraphqlSystemIdentifyHelper): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n module.body.forEach((item) => {\n const declaration =\n item.type === \"ImportDeclaration\"\n ? item\n : \"declaration\" in item &&\n item.declaration &&\n \"type\" in item.declaration &&\n // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any).type === \"ImportDeclaration\"\n ? // biome-ignore lint/suspicious/noExplicitAny: SWC type cast\n (item.declaration as any as ImportDeclaration)\n : null;\n\n if (!declaration) {\n return;\n }\n\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: module.__filePath, specifier: declaration.source.value })) {\n return;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC types are not fully compatible\n declaration.specifiers?.forEach((specifier: any) => {\n // Check for default import\n if (specifier.type === \"ImportDefaultSpecifier\") {\n diagnostics.push(createStandardDiagnostic(\"DEFAULT_IMPORT\", getLocation(module, specifier.span), undefined));\n return;\n }\n\n // Check for namespace import: import * as gqlSystem from \"...\"\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n diagnostics.push(\n createStandardDiagnostic(\"STAR_IMPORT\", getLocation(module, specifier.span), {\n namespaceAlias: specifier.local.value,\n }),\n );\n return;\n }\n\n // Check for renamed gql import: import { gql as g } from \"...\"\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier.imported ? specifier.imported.value : specifier.local.value;\n // Only report if gql is renamed (imported exists and is \"gql\")\n if (imported === \"gql\" && specifier.imported) {\n diagnostics.push(\n createStandardDiagnostic(\"RENAMED_IMPORT\", getLocation(module, specifier.span), {\n importedAs: specifier.local.value,\n }),\n );\n }\n }\n });\n });\n\n return diagnostics;\n};\n\n/**\n * Check if a node contains a reference to any gql identifier\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst containsGqlIdentifier = (node: any, identifiers: ReadonlySet<string>): boolean => {\n if (!node || typeof node !== \"object\") {\n return false;\n }\n if (node.type === \"Identifier\" && identifiers.has(node.value)) {\n return true;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n if (containsGqlIdentifier(child, identifiers)) {\n return true;\n }\n }\n } else if (value && typeof value === \"object\") {\n if (containsGqlIdentifier(value, identifiers)) {\n return true;\n }\n }\n }\n return false;\n};\n\n/**\n * Get the type name of an argument for error messages\n */\n// biome-ignore lint/suspicious/noExplicitAny: SWC AST type\nconst getArgumentType = (node: any): string => {\n if (!node) return \"undefined\";\n switch (node.type) {\n case \"StringLiteral\":\n return \"string\";\n case \"NumericLiteral\":\n return \"number\";\n case \"ObjectExpression\":\n return \"object\";\n case \"ArrayExpression\":\n return \"array\";\n case \"FunctionExpression\":\n return \"function\";\n case \"NullLiteral\":\n return \"null\";\n case \"BooleanLiteral\":\n return \"boolean\";\n default:\n return \"unknown\";\n }\n};\n\n/**\n * Collect diagnostics for invalid gql call patterns\n */\nconst collectCallDiagnostics = (module: SwcModule, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n if (node.type === \"CallExpression\") {\n const diagnostic = checkCallExpression(module, node, gqlIdentifiers);\n if (diagnostic) {\n diagnostics.push(diagnostic);\n }\n }\n\n // Recursively visit children\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child);\n }\n } else if (value && typeof value === \"object\") {\n visit(value);\n }\n }\n };\n\n module.body.forEach(visit);\n return diagnostics;\n};\n\n/**\n * Check a call expression for invalid gql patterns\n */\nconst checkCallExpression = (\n module: SwcModule,\n call: CallExpression,\n gqlIdentifiers: ReadonlySet<string>,\n): ModuleDiagnostic | null => {\n const callee = call.callee;\n\n // Check for direct gql() call (non-member): gql(...)\n if (callee.type === \"Identifier\" && gqlIdentifiers.has(callee.value)) {\n return createStandardDiagnostic(\"NON_MEMBER_CALLEE\", getLocation(module, call.span), undefined);\n }\n\n // Check for optional chaining: gql?.default(...)\n // SWC wraps optional chaining in OptionalChainingExpression\n if (callee.type === \"OptionalChainingExpression\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const base = (callee as any).base;\n if (base?.type === \"MemberExpression\") {\n const object = base.object;\n if (object?.type === \"Identifier\" && gqlIdentifiers.has(object.value)) {\n return createStandardDiagnostic(\"OPTIONAL_CHAINING\", getLocation(module, call.span), undefined);\n }\n }\n return null;\n }\n\n // Must be member expression for valid gql call\n if (callee.type !== \"MemberExpression\") {\n return null;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const object = (callee as any).object;\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const property = (callee as any).property;\n\n // Check for computed access: gql[\"default\"](...) or gql[variable](...)\n // SWC represents computed property access with property.type === \"Computed\"\n if (property?.type === \"Computed\" && object?.type === \"Identifier\" && gqlIdentifiers.has(object.value)) {\n return createStandardDiagnostic(\"COMPUTED_PROPERTY\", getLocation(module, call.span), undefined);\n }\n\n // Check for dynamic callee: (x || gql).default(...)\n if (object?.type !== \"Identifier\") {\n if (containsGqlIdentifier(object, gqlIdentifiers)) {\n return createStandardDiagnostic(\"DYNAMIC_CALLEE\", getLocation(module, call.span), undefined);\n }\n return null;\n }\n\n // Not a gql identifier - skip\n if (!gqlIdentifiers.has(object.value)) {\n return null;\n }\n\n // Check arguments for gql.schema(...) calls\n if (!call.arguments || call.arguments.length === 0) {\n return createStandardDiagnostic(\"MISSING_ARGUMENT\", getLocation(module, call.span), undefined);\n }\n\n const firstArg = call.arguments[0];\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const firstArgAny = firstArg as any;\n\n // Check for spread argument: gql.default(...args)\n if (firstArgAny?.spread) {\n return createStandardDiagnostic(\"SPREAD_ARGUMENT\", getLocation(module, call.span), undefined);\n }\n\n const expression = firstArgAny?.expression;\n if (expression && expression.type !== \"ArrowFunctionExpression\") {\n const actualType = getArgumentType(expression);\n return createStandardDiagnostic(\"INVALID_ARGUMENT_TYPE\", getLocation(module, call.span), { actualType });\n }\n\n // Check for extra arguments: gql.default(() => ..., extra)\n if (call.arguments.length > 1) {\n const extraCount = call.arguments.length - 1;\n return createStandardDiagnostic(\"EXTRA_ARGUMENTS\", getLocation(module, call.span), {\n extraCount: String(extraCount),\n });\n }\n\n return null;\n};\n\n/**\n * Collect diagnostics for gql calls in class properties\n */\nconst collectClassPropertyDiagnostics = (module: SwcModule, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const containsGqlCall = (node: any): boolean => {\n if (!node || typeof node !== \"object\") {\n return false;\n }\n if (node.type === \"CallExpression\" && isGqlCall(gqlIdentifiers, node)) {\n return true;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n if (containsGqlCall(child)) {\n return true;\n }\n }\n } else if (value && typeof value === \"object\") {\n if (containsGqlCall(value)) {\n return true;\n }\n }\n }\n return false;\n };\n\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") {\n return;\n }\n\n if (node.type === \"ClassDeclaration\") {\n // biome-ignore lint/suspicious/noExplicitAny: SWC AST type\n node.body?.forEach((member: any) => {\n if (member.type === \"ClassProperty\" && member.value) {\n if (containsGqlCall(member.value)) {\n diagnostics.push(createStandardDiagnostic(\"CLASS_PROPERTY\", getLocation(module, member.span), undefined));\n }\n }\n });\n }\n\n // Recursively visit children\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child);\n }\n } else if (value && typeof value === \"object\") {\n visit(value);\n }\n }\n };\n\n module.body.forEach(visit);\n return diagnostics;\n};\n\n/**\n * SWC adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (Module) is released after analysis.\n */\ntype ParseSync = typeof import(\"@swc/core\").parseSync;\nlet _parseSync: ParseSync | undefined;\nconst getParseSync = (): ParseSync => {\n if (!_parseSync) {\n if (typeof import.meta.url !== \"string\") {\n throw new Error(\"@swc/core cannot be resolved: import.meta.url is unavailable in CJS bundle context\");\n }\n const localRequire = createRequire(import.meta.url);\n _parseSync = localRequire(\"@swc/core\").parseSync;\n }\n return _parseSync!;\n};\n\nexport const swcAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const program = getParseSync()(input.source, {\n syntax: \"typescript\",\n tsx: input.filePath.endsWith(\".tsx\"),\n target: \"es2022\",\n decorators: false,\n dynamicImport: true,\n });\n\n if (program.type !== \"Module\") {\n return null;\n }\n\n // SWC's BytePos counter accumulates across parseSync calls within the same process.\n // Use UTF-8 byte length (not source.length which is UTF-16 code units) for correct offset.\n const converter = createSwcSpanConverter(input.source);\n const spanOffset = program.span.end - converter.byteLength + 1;\n\n // Attach filePath to module (similar to ts.SourceFile.fileName)\n const swcModule = program as SwcModule;\n swcModule.__filePath = input.filePath;\n swcModule.__spanOffset = spanOffset;\n swcModule.__spanConverter = converter;\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlIdentifiers(swcModule, helper);\n const imports = collectImports(swcModule);\n const exports = collectExports(swcModule);\n\n const { definitions } = collectAllDefinitions({\n module: swcModule,\n gqlIdentifiers,\n imports,\n exports,\n source: input.source,\n baseDir: input.baseDir,\n });\n\n // Collect diagnostics\n const diagnostics = [\n ...collectImportDiagnostics(swcModule, helper),\n ...collectCallDiagnostics(swcModule, gqlIdentifiers),\n ...collectClassPropertyDiagnostics(swcModule, gqlIdentifiers),\n ];\n\n // Return results - swcModule goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n diagnostics,\n };\n },\n};\n","/**\n * TypeScript adapter for the analyzer core.\n * Implements parser-specific logic using the TypeScript compiler API.\n */\n\nimport { extname } from \"node:path\";\nimport { createCanonicalId, createCanonicalTracker, type ScopeHandle } from \"@soda-gql/common\";\nimport ts from \"typescript\";\nimport type { GraphqlSystemIdentifyHelper } from \"../../internal/graphql-system\";\nimport { createStandardDiagnostic } from \"../common/detection\";\nimport { createExportBindingsMap, type ScopeFrame } from \"../common/scope\";\nimport type { AnalyzerAdapter, AnalyzerResult } from \"../core\";\nimport type {\n AnalyzeModuleInput,\n DiagnosticLocation,\n ModuleDefinition,\n ModuleDiagnostic,\n ModuleExport,\n ModuleImport,\n} from \"../types\";\n\nconst createSourceFile = (filePath: string, source: string): ts.SourceFile => {\n const scriptKind = extname(filePath) === \".tsx\" ? ts.ScriptKind.TSX : ts.ScriptKind.TS;\n return ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2022, true, scriptKind);\n};\n\nconst collectGqlImports = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ReadonlySet<string> => {\n const identifiers = new Set<string>();\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: sourceFile.fileName, specifier: moduleText })) {\n return;\n }\n\n if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {\n statement.importClause.namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n // Only add non-renamed imports (propertyName exists when renamed: \"gql as g\")\n if (imported === \"gql\" && !element.propertyName) {\n identifiers.add(element.name.text);\n }\n });\n }\n });\n\n return identifiers;\n};\n\nconst collectImports = (sourceFile: ts.SourceFile): ModuleImport[] => {\n const imports: ModuleImport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n const { importClause } = statement;\n\n if (importClause.name) {\n imports.push({\n source: moduleText,\n local: importClause.name.text,\n kind: \"default\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) {\n return;\n }\n\n if (ts.isNamespaceImport(namedBindings)) {\n imports.push({\n source: moduleText,\n local: namedBindings.name.text,\n kind: \"namespace\",\n isTypeOnly: Boolean(importClause.isTypeOnly),\n });\n return;\n }\n\n namedBindings.elements.forEach((element) => {\n imports.push({\n source: moduleText,\n local: element.name.text,\n kind: \"named\",\n isTypeOnly: Boolean(importClause.isTypeOnly || element.isTypeOnly),\n });\n });\n });\n\n return imports;\n};\n\nconst collectExports = (sourceFile: ts.SourceFile): ModuleExport[] => {\n const exports: ModuleExport[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (ts.isExportDeclaration(statement)) {\n const moduleSpecifier = statement.moduleSpecifier ? (statement.moduleSpecifier as ts.StringLiteral).text : undefined;\n\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n statement.exportClause.elements.forEach((element) => {\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : undefined,\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n } else {\n exports.push({\n kind: \"named\",\n exported: element.name.text,\n local: element.propertyName ? element.propertyName.text : element.name.text,\n isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly),\n });\n }\n });\n return;\n }\n\n if (moduleSpecifier) {\n exports.push({\n kind: \"reexport\",\n exported: \"*\",\n source: moduleSpecifier,\n isTypeOnly: Boolean(statement.isTypeOnly),\n });\n }\n\n return;\n }\n\n if (ts.isExportAssignment(statement)) {\n exports.push({\n kind: \"named\",\n exported: \"default\",\n local: \"default\",\n isTypeOnly: false,\n });\n }\n\n if (\n ts.isVariableStatement(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n statement.declarationList.declarations.forEach((declaration) => {\n if (ts.isIdentifier(declaration.name)) {\n exports.push({\n kind: \"named\",\n exported: declaration.name.text,\n local: declaration.name.text,\n isTypeOnly: false,\n });\n }\n });\n }\n\n if (\n ts.isFunctionDeclaration(statement) &&\n statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) &&\n statement.name\n ) {\n exports.push({\n kind: \"named\",\n exported: statement.name.text,\n local: statement.name.text,\n isTypeOnly: false,\n });\n }\n });\n\n return exports;\n};\n\n/**\n * Unwrap NonNullExpression nodes to get the underlying expression.\n * Handles cases like `gql!` or `gql!!` by recursively unwrapping.\n */\nconst unwrapNonNullExpression = (node: ts.Expression): ts.Expression => {\n if (ts.isNonNullExpression(node)) {\n return unwrapNonNullExpression(node.expression);\n }\n return node;\n};\n\nconst isGqlDefinitionCall = (identifiers: ReadonlySet<string>, callExpression: ts.CallExpression): boolean => {\n const expression = callExpression.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return false;\n }\n\n // Unwrap NonNullExpression: gql!.default(...) -> gql.default(...)\n const baseExpr = unwrapNonNullExpression(expression.expression);\n\n if (!ts.isIdentifier(baseExpr) || !identifiers.has(baseExpr.text)) {\n return false;\n }\n\n const [factory] = callExpression.arguments;\n if (!factory || !(ts.isArrowFunction(factory) || ts.isFunctionExpression(factory))) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Unwrap method chains (like .attach()) to find the underlying gql call.\n * Returns the innermost CallExpression that is a valid gql definition call.\n */\nconst unwrapMethodChains = (identifiers: ReadonlySet<string>, node: ts.Node): ts.CallExpression | null => {\n if (!ts.isCallExpression(node)) {\n return null;\n }\n\n // Check if this is directly a gql definition call\n if (isGqlDefinitionCall(identifiers, node)) {\n return node;\n }\n\n // Check if this is a method call on another expression (e.g., .attach())\n const expression = node.expression;\n if (!ts.isPropertyAccessExpression(expression)) {\n return null;\n }\n\n // Recursively check the object of the property access\n // e.g., for `gql.default(...).attach(...)`, expression.expression is `gql.default(...)`\n return unwrapMethodChains(identifiers, expression.expression);\n};\n\n/**\n * Get property name from AST node\n */\nconst getPropertyName = (name: ts.PropertyName): string | null => {\n if (ts.isIdentifier(name)) {\n return name.text;\n }\n if (ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return null;\n};\n\n/**\n * Collect all gql definitions (exported, non-exported, top-level, nested)\n */\nconst collectAllDefinitions = ({\n sourceFile,\n identifiers,\n exports,\n baseDir,\n}: {\n sourceFile: ts.SourceFile;\n identifiers: ReadonlySet<string>;\n exports: readonly ModuleExport[];\n baseDir?: string;\n}): {\n readonly definitions: ModuleDefinition[];\n readonly handledCalls: readonly ts.CallExpression[];\n} => {\n type PendingDefinition = {\n readonly astPath: string;\n readonly isTopLevel: boolean;\n readonly isExported: boolean;\n readonly exportBinding?: string;\n readonly expression: string;\n };\n\n const pending: PendingDefinition[] = [];\n const handledCalls: ts.CallExpression[] = [];\n\n // Build export bindings map (which variables are exported and with what name)\n const exportBindings = createExportBindingsMap(exports);\n\n // Create canonical tracker\n const tracker = createCanonicalTracker({\n filePath: sourceFile.fileName,\n baseDir,\n getExportName: (localName) => exportBindings.get(localName),\n });\n\n // Anonymous scope counters (for naming only, not occurrence tracking)\n // Use underscore separator instead of # to ensure valid JavaScript identifiers\n const anonymousCounters = new Map<string, number>();\n const getAnonymousName = (kind: string): string => {\n const count = anonymousCounters.get(kind) ?? 0;\n anonymousCounters.set(kind, count + 1);\n return `_${kind}_${count}`;\n };\n\n // Helper to synchronize tracker with immutable stack pattern\n const withScope = <T>(\n stack: ScopeFrame[],\n segment: string,\n kind: ScopeFrame[\"kind\"],\n stableKey: string,\n callback: (newStack: ScopeFrame[]) => T,\n ): T => {\n const handle = tracker.enterScope({ segment, kind, stableKey });\n try {\n const frame: ScopeFrame = { nameSegment: segment, kind };\n return callback([...stack, frame]);\n } finally {\n tracker.exitScope(handle);\n }\n };\n\n // Check if we're inside a class property (class property scope tracking is unreliable)\n const isInClassProperty = (stack: ScopeFrame[]): boolean =>\n stack.some((frame, i) => frame.kind === \"property\" && stack[i - 1]?.kind === \"class\");\n\n const visit = (node: ts.Node, stack: ScopeFrame[]) => {\n // Check if this is a gql definition call (possibly wrapped in method chains like .attach())\n if (ts.isCallExpression(node)) {\n const gqlCall = unwrapMethodChains(identifiers, node);\n // Skip definition collection for gql calls inside class properties\n // (CLASS_PROPERTY diagnostic is still emitted by collectClassPropertyDiagnostics)\n if (gqlCall && !isInClassProperty(stack)) {\n // If scopeStack is empty (unbound gql call), enter an anonymous scope\n const needsAnonymousScope = tracker.currentDepth() === 0;\n let anonymousScopeHandle: ScopeHandle | undefined;\n\n if (needsAnonymousScope) {\n const anonymousName = getAnonymousName(\"anonymous\");\n anonymousScopeHandle = tracker.enterScope({\n segment: anonymousName,\n kind: \"expression\",\n stableKey: \"anonymous\",\n });\n }\n\n try {\n // Use tracker to get astPath\n const { astPath } = tracker.registerDefinition();\n const isTopLevel = stack.length === 1;\n\n // Determine if exported\n let isExported = false;\n let exportBinding: string | undefined;\n\n if (isTopLevel && stack[0]) {\n const topLevelName = stack[0].nameSegment;\n if (exportBindings.has(topLevelName)) {\n isExported = true;\n exportBinding = exportBindings.get(topLevelName);\n }\n }\n\n handledCalls.push(node);\n pending.push({\n astPath,\n isTopLevel,\n isExported,\n exportBinding,\n // Use the unwrapped gql call expression (without .attach() chain)\n expression: gqlCall.getText(sourceFile),\n });\n } finally {\n // Exit anonymous scope if we entered one\n if (anonymousScopeHandle) {\n tracker.exitScope(anonymousScopeHandle);\n }\n }\n\n // Don't visit children of gql calls\n return;\n }\n }\n\n // Variable declaration\n if (ts.isVariableDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const varName = node.name.text;\n\n if (node.initializer) {\n const next = node.initializer;\n withScope(stack, varName, \"variable\", `var:${varName}`, (newStack) => {\n visit(next, newStack);\n });\n }\n return;\n }\n\n // Function declaration\n if (ts.isFunctionDeclaration(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n const next = node.body;\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(next, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Arrow function\n if (ts.isArrowFunction(node)) {\n const arrowName = getAnonymousName(\"arrow\");\n\n withScope(stack, arrowName, \"function\", \"arrow\", (newStack) => {\n if (ts.isBlock(node.body)) {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n } else {\n visit(node.body, newStack);\n }\n });\n return;\n }\n\n // Function expression\n if (ts.isFunctionExpression(node)) {\n const funcName = node.name?.text ?? getAnonymousName(\"function\");\n\n if (node.body) {\n withScope(stack, funcName, \"function\", `func:${funcName}`, (newStack) => {\n ts.forEachChild(node.body, (child) => visit(child, newStack));\n });\n }\n return;\n }\n\n // Class declaration\n if (ts.isClassDeclaration(node)) {\n const className = node.name?.text ?? getAnonymousName(\"class\");\n\n withScope(stack, className, \"class\", `class:${className}`, (classStack) => {\n node.members.forEach((member) => {\n if (ts.isMethodDeclaration(member) || ts.isPropertyDeclaration(member)) {\n const memberName = member.name && ts.isIdentifier(member.name) ? member.name.text : null;\n if (memberName) {\n const memberKind = ts.isMethodDeclaration(member) ? \"method\" : \"property\";\n withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {\n if (ts.isMethodDeclaration(member) && member.body) {\n ts.forEachChild(member.body, (child) => visit(child, memberStack));\n } else if (ts.isPropertyDeclaration(member) && member.initializer) {\n visit(member.initializer, memberStack);\n }\n });\n }\n }\n });\n });\n return;\n }\n\n // Object literal property\n if (ts.isPropertyAssignment(node)) {\n const propName = getPropertyName(node.name);\n if (propName) {\n withScope(stack, propName, \"property\", `prop:${propName}`, (newStack) => {\n visit(node.initializer, newStack);\n });\n }\n return;\n }\n\n // Recursively visit children\n ts.forEachChild(node, (child) => visit(child, stack));\n };\n\n // Start traversal from top-level statements\n sourceFile.statements.forEach((statement) => {\n visit(statement, []);\n });\n\n const definitions = pending.map(\n (item) =>\n ({\n canonicalId: createCanonicalId(sourceFile.fileName, item.astPath, { baseDir }),\n astPath: item.astPath,\n isTopLevel: item.isTopLevel,\n isExported: item.isExported,\n exportBinding: item.exportBinding,\n expression: item.expression,\n }) satisfies ModuleDefinition,\n );\n\n return { definitions, handledCalls };\n};\n\n// ============================================================================\n// Diagnostic Collection\n// ============================================================================\n\n/**\n * Get location from a TypeScript node\n */\nconst getLocation = (sourceFile: ts.SourceFile, node: ts.Node): DiagnosticLocation => {\n const start = node.getStart(sourceFile);\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(start);\n return {\n start,\n end: node.getEnd(),\n line: line + 1, // 1-indexed\n column: character + 1,\n };\n};\n\n/**\n * Collect diagnostics for invalid import patterns from graphql-system\n */\nconst collectImportDiagnostics = (sourceFile: ts.SourceFile, helper: GraphqlSystemIdentifyHelper): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n sourceFile.statements.forEach((statement) => {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) {\n return;\n }\n\n const moduleText = (statement.moduleSpecifier as ts.StringLiteral).text;\n if (!helper.isGraphqlSystemImportSpecifier({ filePath: sourceFile.fileName, specifier: moduleText })) {\n return;\n }\n\n const { importClause } = statement;\n\n // Check for default import: import gql from \"...\"\n if (importClause.name) {\n diagnostics.push(createStandardDiagnostic(\"DEFAULT_IMPORT\", getLocation(sourceFile, importClause.name), undefined));\n }\n\n const { namedBindings } = importClause;\n if (!namedBindings) {\n return;\n }\n\n // Check for namespace import: import * as gqlSystem from \"...\"\n if (ts.isNamespaceImport(namedBindings)) {\n diagnostics.push(\n createStandardDiagnostic(\"STAR_IMPORT\", getLocation(sourceFile, namedBindings), {\n namespaceAlias: namedBindings.name.text,\n }),\n );\n return;\n }\n\n // Check for renamed gql import: import { gql as g } from \"...\"\n namedBindings.elements.forEach((element) => {\n const imported = element.propertyName ? element.propertyName.text : element.name.text;\n // Only report if gql is renamed (propertyName exists and is \"gql\")\n if (imported === \"gql\" && element.propertyName) {\n diagnostics.push(\n createStandardDiagnostic(\"RENAMED_IMPORT\", getLocation(sourceFile, element), {\n importedAs: element.name.text,\n }),\n );\n }\n });\n });\n\n return diagnostics;\n};\n\n/**\n * Check if a node contains a reference to any gql identifier\n */\nconst containsGqlIdentifier = (node: ts.Node, identifiers: ReadonlySet<string>): boolean => {\n if (ts.isIdentifier(node) && identifiers.has(node.text)) {\n return true;\n }\n let found = false;\n ts.forEachChild(node, (child) => {\n if (containsGqlIdentifier(child, identifiers)) {\n found = true;\n }\n });\n return found;\n};\n\n/**\n * Get the type name of an argument for error messages\n */\nconst getArgumentType = (node: ts.Node): string => {\n if (ts.isStringLiteral(node)) return \"string\";\n if (ts.isNumericLiteral(node)) return \"number\";\n if (ts.isObjectLiteralExpression(node)) return \"object\";\n if (ts.isArrayLiteralExpression(node)) return \"array\";\n if (ts.isFunctionExpression(node)) return \"function\";\n if (node.kind === ts.SyntaxKind.NullKeyword) return \"null\";\n if (node.kind === ts.SyntaxKind.UndefinedKeyword) return \"undefined\";\n if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) return \"boolean\";\n return \"unknown\";\n};\n\n/**\n * Collect diagnostics for invalid gql call patterns\n */\nconst collectCallDiagnostics = (sourceFile: ts.SourceFile, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n const visit = (node: ts.Node) => {\n if (ts.isCallExpression(node)) {\n const diagnostic = checkCallExpression(sourceFile, node, gqlIdentifiers);\n if (diagnostic) {\n diagnostics.push(diagnostic);\n }\n }\n ts.forEachChild(node, visit);\n };\n\n sourceFile.statements.forEach(visit);\n return diagnostics;\n};\n\n/**\n * Check a call expression for invalid gql patterns\n */\nconst checkCallExpression = (\n sourceFile: ts.SourceFile,\n call: ts.CallExpression,\n gqlIdentifiers: ReadonlySet<string>,\n): ModuleDiagnostic | null => {\n const { expression } = call;\n\n // Check for direct gql() call (non-member): gql(...)\n if (ts.isIdentifier(expression) && gqlIdentifiers.has(expression.text)) {\n return createStandardDiagnostic(\"NON_MEMBER_CALLEE\", getLocation(sourceFile, call), undefined);\n }\n\n // Check for element access: gql[\"default\"](...) or gql\n if (ts.isElementAccessExpression(expression)) {\n const baseExpr = unwrapNonNullExpression(expression.expression);\n if (ts.isIdentifier(baseExpr) && gqlIdentifiers.has(baseExpr.text)) {\n return createStandardDiagnostic(\"COMPUTED_PROPERTY\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Must be property access for valid gql call\n if (!ts.isPropertyAccessExpression(expression)) {\n return null;\n }\n\n // Unwrap NonNullExpression: gql!.default(...) -> gql.default(...)\n const baseExpr = unwrapNonNullExpression(expression.expression);\n\n // Check for optional chaining: gql?.default(...)\n if (expression.questionDotToken) {\n if (ts.isIdentifier(baseExpr) && gqlIdentifiers.has(baseExpr.text)) {\n return createStandardDiagnostic(\"OPTIONAL_CHAINING\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Check for dynamic callee: (x || gql).default(...)\n if (!ts.isIdentifier(baseExpr)) {\n if (containsGqlIdentifier(expression.expression, gqlIdentifiers)) {\n return createStandardDiagnostic(\"DYNAMIC_CALLEE\", getLocation(sourceFile, call), undefined);\n }\n return null;\n }\n\n // Not a gql identifier - skip\n if (!gqlIdentifiers.has(baseExpr.text)) {\n return null;\n }\n\n // Check arguments for gql.schema(...) calls\n if (call.arguments.length === 0) {\n return createStandardDiagnostic(\"MISSING_ARGUMENT\", getLocation(sourceFile, call), undefined);\n }\n\n const firstArg = call.arguments[0];\n\n // Check for spread argument: gql.default(...args)\n if (firstArg && ts.isSpreadElement(firstArg)) {\n return createStandardDiagnostic(\"SPREAD_ARGUMENT\", getLocation(sourceFile, call), undefined);\n }\n\n if (firstArg && !ts.isArrowFunction(firstArg)) {\n const actualType = getArgumentType(firstArg);\n return createStandardDiagnostic(\"INVALID_ARGUMENT_TYPE\", getLocation(sourceFile, call), { actualType });\n }\n\n // Check for extra arguments: gql.default(() => ..., extra)\n if (call.arguments.length > 1) {\n const extraCount = call.arguments.length - 1;\n return createStandardDiagnostic(\"EXTRA_ARGUMENTS\", getLocation(sourceFile, call), {\n extraCount: String(extraCount),\n });\n }\n\n return null;\n};\n\n/**\n * Collect diagnostics for gql calls in class properties\n */\nconst collectClassPropertyDiagnostics = (sourceFile: ts.SourceFile, gqlIdentifiers: ReadonlySet<string>): ModuleDiagnostic[] => {\n const diagnostics: ModuleDiagnostic[] = [];\n\n const containsGqlCall = (node: ts.Node): boolean => {\n if (ts.isCallExpression(node) && isGqlDefinitionCall(gqlIdentifiers, node)) {\n return true;\n }\n let found = false;\n ts.forEachChild(node, (child) => {\n if (containsGqlCall(child)) {\n found = true;\n }\n });\n return found;\n };\n\n const visit = (node: ts.Node) => {\n if (ts.isClassDeclaration(node)) {\n node.members.forEach((member) => {\n if (ts.isPropertyDeclaration(member) && member.initializer) {\n if (containsGqlCall(member.initializer)) {\n diagnostics.push(createStandardDiagnostic(\"CLASS_PROPERTY\", getLocation(sourceFile, member), undefined));\n }\n }\n });\n }\n ts.forEachChild(node, visit);\n };\n\n sourceFile.statements.forEach(visit);\n return diagnostics;\n};\n\n/**\n * TypeScript adapter implementation.\n * The analyze method parses and collects all data in one pass,\n * ensuring the AST (ts.SourceFile) is released after analysis.\n */\nexport const typescriptAdapter: AnalyzerAdapter = {\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null {\n // Parse source - AST is local to this function\n const sourceFile = createSourceFile(input.filePath, input.source);\n\n // Collect all data in one pass\n const gqlIdentifiers = collectGqlImports(sourceFile, helper);\n const imports = collectImports(sourceFile);\n const exports = collectExports(sourceFile);\n\n const { definitions } = collectAllDefinitions({\n sourceFile,\n identifiers: gqlIdentifiers,\n exports,\n baseDir: input.baseDir,\n });\n\n // Collect diagnostics\n const diagnostics = [\n ...collectImportDiagnostics(sourceFile, helper),\n ...collectCallDiagnostics(sourceFile, gqlIdentifiers),\n ...collectClassPropertyDiagnostics(sourceFile, gqlIdentifiers),\n ];\n\n // Return results - sourceFile goes out of scope and becomes eligible for GC\n return {\n imports,\n exports,\n definitions,\n diagnostics,\n };\n },\n};\n","/**\n * Core analyzer logic that orchestrates the analysis pipeline.\n * Adapters (TypeScript, SWC, etc.) implement the adapter interface to plug into this pipeline.\n */\n\nimport { getPortableHasher } from \"@soda-gql/common\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleDiagnostic, ModuleExport, ModuleImport } from \"./types\";\n\n/**\n * Result of analyzing a module, containing all collected data.\n */\nexport type AnalyzerResult = {\n readonly imports: readonly ModuleImport[];\n readonly exports: readonly ModuleExport[];\n readonly definitions: readonly ModuleDefinition[];\n readonly diagnostics: readonly ModuleDiagnostic[];\n};\n\n/**\n * Adapter interface that each parser implementation (TS, SWC) must provide.\n * The analyze method parses and collects all data in one pass, allowing the AST\n * to be released immediately after analysis completes.\n */\nexport interface AnalyzerAdapter {\n /**\n * Parse source code into an AST, collect all required data, and return results.\n * The AST is kept within this function's scope and released after analysis.\n * This design enables early garbage collection of AST objects.\n */\n analyze(input: AnalyzeModuleInput, helper: GraphqlSystemIdentifyHelper): AnalyzerResult | null;\n}\n\n/**\n * Core analyzer function that orchestrates the analysis pipeline.\n * Adapters implement the AnalyzerAdapter interface to provide parser-specific logic.\n */\nexport const analyzeModuleCore = (\n input: AnalyzeModuleInput,\n adapter: AnalyzerAdapter,\n graphqlHelper: GraphqlSystemIdentifyHelper,\n): ModuleAnalysis => {\n const hasher = getPortableHasher();\n const signature = hasher.hash(input.source, \"xxhash\");\n\n // Delegate all analysis to the adapter - AST is created and released within analyze()\n const result = adapter.analyze(input, graphqlHelper);\n\n if (!result) {\n return {\n filePath: input.filePath,\n signature,\n definitions: [],\n imports: [],\n exports: [],\n diagnostics: [],\n };\n }\n\n return {\n filePath: input.filePath,\n signature,\n definitions: result.definitions,\n imports: result.imports,\n exports: result.exports,\n diagnostics: result.diagnostics,\n };\n};\n","import { assertUnreachable } from \"../errors\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport type { BuilderAnalyzer } from \"../types\";\nimport { swcAdapter } from \"./adapters/swc\";\nimport { typescriptAdapter } from \"./adapters/typescript\";\nimport { analyzeModuleCore } from \"./core\";\nimport type { AnalyzeModuleInput, ModuleAnalysis } from \"./types\";\n\nexport type { AnalyzeModuleInput, ModuleAnalysis, ModuleDefinition, ModuleExport, ModuleImport } from \"./types\";\n\nexport const createAstAnalyzer = ({\n analyzer,\n graphqlHelper,\n baseDir,\n}: {\n readonly analyzer: BuilderAnalyzer;\n readonly graphqlHelper: GraphqlSystemIdentifyHelper;\n /**\n * Base directory for relative path computation in canonical IDs.\n * When provided, all canonical IDs generated during analysis will use\n * relative paths from baseDir, enabling portable artifacts.\n */\n readonly baseDir?: string;\n}) => {\n const analyze = (input: Omit<AnalyzeModuleInput, \"baseDir\">): ModuleAnalysis => {\n const inputWithBaseDir: AnalyzeModuleInput = { ...input, baseDir };\n if (analyzer === \"ts\") {\n return analyzeModuleCore(inputWithBaseDir, typescriptAdapter, graphqlHelper);\n }\n if (analyzer === \"swc\") {\n return analyzeModuleCore(inputWithBaseDir, swcAdapter, graphqlHelper);\n }\n return assertUnreachable(analyzer, \"createAstAnalyzer\");\n };\n\n return {\n type: analyzer,\n analyze,\n };\n};\n","import { existsSync, readFileSync, unlinkSync } from \"node:fs\";\nimport { getPortableFS, getPortableHasher } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\ntype CacheNamespace = readonly string[];\n\nexport type CacheFactoryOptions = {\n readonly prefix?: CacheNamespace;\n readonly persistence?: {\n readonly enabled: boolean;\n readonly filePath: string;\n };\n};\n\nexport type CacheStoreOptions<_K extends string, V> = {\n readonly namespace: CacheNamespace;\n readonly schema: z.ZodType<V>;\n readonly version?: string;\n};\n\nexport type CacheStore<K extends string, V> = {\n load(key: K): V | null;\n store(key: K, value: V): void;\n delete(key: K): void;\n entries(): IterableIterator<[K, V]>;\n clear(): void;\n size(): number;\n};\n\nexport type CacheFactory = {\n createStore<K extends string, V>(options: CacheStoreOptions<K, V>): CacheStore<K, V>;\n clearAll(): void;\n save(): void;\n};\n\nconst sanitizeSegment = (segment: string): string => segment.replace(/[\\\\/]/g, \"_\");\n\nconst toNamespaceKey = (segments: CacheNamespace): string => segments.map(sanitizeSegment).join(\"/\");\n\nconst toEntryKey = (key: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(key, \"xxhash\");\n};\n\ntype Envelope<V> = {\n key: string;\n version: string;\n value: V;\n};\n\ntype PersistedData = {\n version: string;\n storage: Record<string, Array<[string, Envelope<unknown>]>>;\n};\n\nconst PERSISTENCE_VERSION = \"v1\";\n\n/**\n * Validate persisted data structure.\n * Uses simple validation to detect corruption without strict schema.\n */\nconst isValidPersistedData = (data: unknown): data is PersistedData => {\n if (typeof data !== \"object\" || data === null) return false;\n const record = data as Record<string, unknown>;\n\n if (typeof record.version !== \"string\") return false;\n if (typeof record.storage !== \"object\" || record.storage === null) return false;\n\n // Validate each namespace has array of entries\n for (const value of Object.values(record.storage as Record<string, unknown>)) {\n if (!Array.isArray(value)) return false;\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2) return false;\n if (typeof entry[0] !== \"string\") return false;\n // Validate envelope has required fields\n const envelope = entry[1];\n if (typeof envelope !== \"object\" || envelope === null) return false;\n const env = envelope as Record<string, unknown>;\n if (typeof env.key !== \"string\" || typeof env.version !== \"string\") return false;\n }\n }\n\n return true;\n};\n\nexport const createMemoryCache = ({ prefix = [], persistence }: CacheFactoryOptions = {}): CacheFactory => {\n // Global in-memory storage: Map<namespaceKey, Map<hashedKey, Envelope>>\n const storage = new Map<string, Map<string, Envelope<unknown>>>();\n\n // Load from disk if persistence is enabled (synchronous on startup)\n if (persistence?.enabled) {\n try {\n if (existsSync(persistence.filePath)) {\n const content = readFileSync(persistence.filePath, \"utf-8\");\n\n // Parse and validate JSON structure\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n // Invalid JSON - delete corrupt file and start fresh\n console.warn(`[cache] Corrupt cache file (invalid JSON), starting fresh: ${persistence.filePath}`);\n try {\n unlinkSync(persistence.filePath);\n } catch {\n // Ignore deletion errors\n }\n parsed = null;\n }\n\n if (parsed) {\n // Validate structure to detect corruption\n if (!isValidPersistedData(parsed)) {\n console.warn(`[cache] Corrupt cache file (invalid structure), starting fresh: ${persistence.filePath}`);\n try {\n unlinkSync(persistence.filePath);\n } catch {\n // Ignore deletion errors\n }\n } else if (parsed.version === PERSISTENCE_VERSION) {\n // Restore Map structure from validated data\n for (const [namespaceKey, entries] of Object.entries(parsed.storage)) {\n const namespaceMap = new Map<string, Envelope<unknown>>();\n for (const [hashedKey, envelope] of entries) {\n namespaceMap.set(hashedKey, envelope);\n }\n storage.set(namespaceKey, namespaceMap);\n }\n }\n // Version mismatch - start fresh without warning (expected on version upgrade)\n }\n }\n } catch (error) {\n // Unexpected error during load - start fresh\n console.warn(`[cache] Failed to load cache from ${persistence.filePath}:`, error);\n }\n }\n\n const getOrCreateNamespace = (namespaceKey: string): Map<string, Envelope<unknown>> => {\n let namespace = storage.get(namespaceKey);\n if (!namespace) {\n namespace = new Map();\n storage.set(namespaceKey, namespace);\n }\n return namespace;\n };\n\n return {\n createStore: <K extends string, V>({ namespace, schema, version = \"v1\" }: CacheStoreOptions<K, V>): CacheStore<K, V> => {\n const namespaceKey = toNamespaceKey([...prefix, ...namespace]);\n const envelopeSchema = z.object({\n key: z.string(),\n version: z.string(),\n value: schema,\n });\n\n const resolveEntryKey = (key: string) => toEntryKey(key);\n\n const validateEnvelope = (raw: Envelope<unknown>): Envelope<V> | null => {\n const parsed = envelopeSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n if (parsed.data.version !== version) {\n return null;\n }\n\n return parsed.data as Envelope<V>;\n };\n\n const load = (key: K): V | null => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return null;\n }\n\n const entryKey = resolveEntryKey(key);\n const raw = namespaceStore.get(entryKey);\n if (!raw) {\n return null;\n }\n\n const envelope = validateEnvelope(raw);\n if (!envelope || envelope.key !== key) {\n namespaceStore.delete(entryKey);\n return null;\n }\n\n return envelope.value;\n };\n\n const store = (key: K, value: V): void => {\n const namespaceStore = getOrCreateNamespace(namespaceKey);\n const entryKey = resolveEntryKey(key);\n\n const envelope: Envelope<V> = {\n key,\n version,\n value,\n };\n\n namespaceStore.set(entryKey, envelope as Envelope<unknown>);\n };\n\n const deleteEntry = (key: K): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n const entryKey = resolveEntryKey(key);\n namespaceStore.delete(entryKey);\n };\n\n function* iterateEntries(): IterableIterator<[K, V]> {\n const namespaceStore = storage.get(namespaceKey);\n if (!namespaceStore) {\n return;\n }\n\n for (const raw of namespaceStore.values()) {\n const envelope = validateEnvelope(raw);\n if (!envelope) {\n continue;\n }\n\n yield [envelope.key as K, envelope.value];\n }\n }\n\n const clear = (): void => {\n const namespaceStore = storage.get(namespaceKey);\n if (namespaceStore) {\n namespaceStore.clear();\n }\n };\n\n const size = (): number => {\n let count = 0;\n for (const _ of iterateEntries()) {\n count += 1;\n }\n return count;\n };\n\n return {\n load,\n store,\n delete: deleteEntry,\n entries: iterateEntries,\n clear,\n size,\n };\n },\n\n clearAll: (): void => {\n storage.clear();\n },\n\n save: (): void => {\n if (!persistence?.enabled) {\n return;\n }\n\n try {\n // Convert Map structure to plain object for JSON serialization\n const serialized: Record<string, Array<[string, Envelope<unknown>]>> = {};\n for (const [namespaceKey, namespaceMap] of storage.entries()) {\n serialized[namespaceKey] = Array.from(namespaceMap.entries());\n }\n\n const data: PersistedData = {\n version: PERSISTENCE_VERSION,\n storage: serialized,\n };\n\n // Use atomic write to prevent corruption on crash\n // mkdirSync with recursive is idempotent - no TOCTOU race\n const fs = getPortableFS();\n fs.writeFileSyncAtomic(persistence.filePath, JSON.stringify(data));\n } catch (error) {\n console.warn(`[cache] Failed to save cache to ${persistence.filePath}:`, error);\n }\n },\n };\n};\n","import { normalizePath } from \"@soda-gql/common\";\nimport type { ZodSchema } from \"zod\";\nimport type { CacheFactory, CacheStore } from \"./memory-cache\";\n\nexport type EntityCacheOptions<V> = {\n readonly factory: CacheFactory;\n readonly namespace: readonly string[];\n readonly schema: ZodSchema<V>;\n readonly version: string;\n readonly keyNormalizer?: (key: string) => string;\n};\n\n/**\n * Abstract base class for entity caches.\n * Provides common caching functionality with signature-based eviction.\n */\nexport abstract class EntityCache<K extends string, V> {\n protected readonly cacheStore: CacheStore<K, V>;\n private readonly keyNormalizer: (key: string) => string;\n\n constructor(options: EntityCacheOptions<V>) {\n this.cacheStore = options.factory.createStore({\n namespace: [...options.namespace],\n schema: options.schema,\n version: options.version,\n });\n this.keyNormalizer = options.keyNormalizer ?? normalizePath;\n }\n\n /**\n * Normalize a key for consistent cache lookups.\n */\n protected normalizeKey(key: string): K {\n return this.keyNormalizer(key) as K;\n }\n\n /**\n * Load raw value from cache without signature validation.\n */\n protected loadRaw(key: K): V | null {\n return this.cacheStore.load(key);\n }\n\n /**\n * Store raw value to cache.\n */\n protected storeRaw(key: K, value: V): void {\n this.cacheStore.store(key, value);\n }\n\n /**\n * Delete an entry from the cache.\n */\n delete(key: string): void {\n const normalizedKey = this.normalizeKey(key);\n this.cacheStore.delete(normalizedKey);\n }\n\n /**\n * Get all cached entries.\n * Subclasses should override this to provide custom iteration.\n */\n protected *baseEntries(): IterableIterator<V> {\n for (const [, value] of this.cacheStore.entries()) {\n yield value;\n }\n }\n\n /**\n * Clear all entries from the cache.\n */\n clear(): void {\n this.cacheStore.clear();\n }\n\n /**\n * Get the number of entries in the cache.\n */\n size(): number {\n return this.cacheStore.size();\n }\n}\n","import { CanonicalIdSchema } from \"@soda-gql/common\";\nimport { z } from \"zod\";\n\nexport const ModuleDefinitionSchema = z.object({\n canonicalId: CanonicalIdSchema,\n astPath: z.string(),\n isTopLevel: z.boolean(),\n isExported: z.boolean(),\n exportBinding: z.string().optional(),\n expression: z.string(),\n});\n\nexport const ModuleImportSchema = z.object({\n source: z.string(),\n local: z.string(),\n kind: z.enum([\"named\", \"namespace\", \"default\"]),\n isTypeOnly: z.boolean(),\n});\n\nexport const ModuleExportSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"named\"),\n exported: z.string(),\n local: z.string(),\n source: z.undefined().optional(),\n isTypeOnly: z.boolean(),\n }),\n z.object({\n kind: z.literal(\"reexport\"),\n exported: z.string(),\n source: z.string(),\n local: z.string().optional(),\n isTypeOnly: z.boolean(),\n }),\n]);\n\nconst DiagnosticCodeSchema = z.enum([\n \"RENAMED_IMPORT\",\n \"STAR_IMPORT\",\n \"DEFAULT_IMPORT\",\n \"MISSING_ARGUMENT\",\n \"INVALID_ARGUMENT_TYPE\",\n \"NON_MEMBER_CALLEE\",\n \"COMPUTED_PROPERTY\",\n \"DYNAMIC_CALLEE\",\n \"OPTIONAL_CHAINING\",\n \"EXTRA_ARGUMENTS\",\n \"SPREAD_ARGUMENT\",\n \"CLASS_PROPERTY\",\n]);\n\nconst DiagnosticLocationSchema = z.object({\n start: z.number(),\n end: z.number(),\n line: z.number().optional(),\n column: z.number().optional(),\n});\n\nconst ModuleDiagnosticSchema = z.object({\n code: DiagnosticCodeSchema,\n severity: z.enum([\"error\", \"warning\"]),\n message: z.string(),\n location: DiagnosticLocationSchema,\n context: z.record(z.string(), z.string()).readonly().optional(),\n});\n\nexport const ModuleAnalysisSchema = z.object({\n filePath: z.string(),\n signature: z.string(),\n definitions: z.array(ModuleDefinitionSchema).readonly(),\n imports: z.array(ModuleImportSchema).readonly(),\n exports: z.array(ModuleExportSchema).readonly(),\n diagnostics: z.array(ModuleDiagnosticSchema).readonly(),\n});\n\nexport type ModuleAnalysis = z.infer<typeof ModuleAnalysisSchema>;\n","import { z } from \"zod\";\nimport { ModuleAnalysisSchema } from \"./cache\";\n\nconst FileFingerprintSchema = z.object({\n hash: z.string(),\n sizeBytes: z.number(),\n mtimeMs: z.number(),\n});\n\nexport const DiscoveredDependencySchema = z.object({\n specifier: z.string(),\n resolvedPath: z.string().nullable(),\n isExternal: z.boolean(),\n});\n\nexport const DiscoverySnapshotSchema = z.object({\n filePath: z.string(),\n normalizedFilePath: z.string(),\n signature: z.string(),\n fingerprint: FileFingerprintSchema,\n analyzer: z.string(),\n createdAtMs: z.number(),\n analysis: ModuleAnalysisSchema,\n dependencies: z.array(DiscoveredDependencySchema).readonly(),\n});\n","import { EntityCache } from \"../cache/entity-cache\";\nimport type { CacheFactory } from \"../cache/memory-cache\";\nimport { DiscoverySnapshotSchema } from \"../schemas/discovery\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\n// Bumped to v3 for DiscoverySnapshot schema change (added fingerprint and metadata fields)\nconst DISCOVERY_CACHE_VERSION = \"discovery-cache/v3\";\n\nexport type DiscoveryCacheOptions = {\n readonly factory: CacheFactory;\n readonly analyzer: string;\n readonly evaluatorId: string;\n readonly namespacePrefix?: readonly string[];\n readonly version?: string;\n};\n\nexport class JsonDiscoveryCache extends EntityCache<string, DiscoverySnapshot> implements DiscoveryCache {\n constructor(options: DiscoveryCacheOptions) {\n const namespace = [...(options.namespacePrefix ?? [\"discovery\"]), options.analyzer, options.evaluatorId];\n\n super({\n factory: options.factory,\n namespace,\n schema: DiscoverySnapshotSchema,\n version: options.version ?? DISCOVERY_CACHE_VERSION,\n });\n }\n\n load(filePath: string, expectedSignature: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n const snapshot = this.loadRaw(key);\n if (!snapshot) {\n return null;\n }\n\n if (snapshot.signature !== expectedSignature) {\n this.delete(filePath);\n return null;\n }\n\n return snapshot;\n }\n\n peek(filePath: string): DiscoverySnapshot | null {\n const key = this.normalizeKey(filePath);\n return this.loadRaw(key);\n }\n\n store(snapshot: DiscoverySnapshot): void {\n const key = this.normalizeKey(snapshot.filePath);\n this.storeRaw(key, snapshot);\n }\n\n entries(): IterableIterator<DiscoverySnapshot> {\n return this.baseEntries();\n }\n}\n\nexport const createDiscoveryCache = (options: DiscoveryCacheOptions): DiscoveryCache => new JsonDiscoveryCache(options);\n","import {\n type AliasResolver,\n getPortableHasher,\n isExternalSpecifier,\n resolveRelativeImportWithExistenceCheck,\n} from \"@soda-gql/common\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport type { DiscoveredDependency } from \"./types\";\n\n/**\n * Options for extracting module dependencies.\n */\nexport type ExtractModuleDependenciesOptions = {\n readonly analysis: ModuleAnalysis;\n /** Optional alias resolver for tsconfig paths */\n readonly aliasResolver?: AliasResolver;\n};\n\n/**\n * Extract all unique dependencies (relative + external) from the analysis.\n * Resolves local specifiers immediately so discovery only traverses once.\n *\n * Resolution order:\n * 1. Relative imports → resolveRelativeImportWithExistenceCheck\n * 2. Alias imports (if aliasResolver provided) → aliasResolver.resolve\n * 3. Otherwise → mark as external\n */\nexport const extractModuleDependencies = ({\n analysis,\n aliasResolver,\n}: ExtractModuleDependenciesOptions): readonly DiscoveredDependency[] => {\n const dependencies = new Map<string, DiscoveredDependency>();\n\n const addDependency = (specifier: string): void => {\n if (dependencies.has(specifier)) {\n return;\n }\n\n // Try relative import first\n if (!isExternalSpecifier(specifier)) {\n const resolvedPath = resolveRelativeImportWithExistenceCheck({\n filePath: analysis.filePath,\n specifier,\n });\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal: false,\n });\n return;\n }\n\n // Try alias resolution if available\n if (aliasResolver) {\n const resolvedPath = aliasResolver.resolve(specifier);\n if (resolvedPath) {\n dependencies.set(specifier, {\n specifier,\n resolvedPath,\n isExternal: false,\n });\n return;\n }\n }\n\n // External package\n dependencies.set(specifier, {\n specifier,\n resolvedPath: null,\n isExternal: true,\n });\n };\n\n for (const imp of analysis.imports) {\n addDependency(imp.source);\n }\n\n for (const exp of analysis.exports) {\n if (exp.kind === \"reexport\") {\n addDependency(exp.source);\n }\n }\n\n return Array.from(dependencies.values());\n};\n\nexport const createSourceHash = (source: string): string => {\n const hasher = getPortableHasher();\n return hasher.hash(source, \"xxhash\");\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { XXHashAPI } from \"xxhash-wasm\";\n\n/**\n * File fingerprint containing hash, size, and modification time\n */\nexport type FileFingerprint = {\n /** xxHash hash of file contents */\n hash: string;\n /** File size in bytes */\n sizeBytes: number;\n /** Last modification time in milliseconds since epoch */\n mtimeMs: number;\n};\n\n/**\n * Fingerprint computation error types\n */\nexport type FingerprintError =\n | { code: \"FILE_NOT_FOUND\"; path: string; message: string }\n | { code: \"NOT_A_FILE\"; path: string; message: string }\n | { code: \"READ_ERROR\"; path: string; message: string };\n\n/**\n * In-memory fingerprint cache keyed by absolute path\n */\nconst fingerprintCache = new Map<string, FileFingerprint>();\n\n/**\n * Lazy-loaded xxhash instance\n */\nlet xxhashInstance: XXHashAPI | null = null;\n\n/**\n * Lazily load xxhash-wasm instance\n */\nasync function getXXHash(): Promise<XXHashAPI> {\n if (xxhashInstance === null) {\n const { default: xxhash } = await import(\"xxhash-wasm\");\n xxhashInstance = await xxhash();\n }\n return xxhashInstance;\n}\n\n/**\n * Compute file fingerprint with memoization.\n * Uses mtime to short-circuit re-hashing unchanged files.\n *\n * @param path - Absolute path to file\n * @returns Result containing FileFingerprint or FingerprintError\n */\nexport function computeFingerprint(path: string): Result<FileFingerprint, FingerprintError> {\n try {\n const stats = statSync(path);\n\n if (!stats.isFile()) {\n return err({\n code: \"NOT_A_FILE\",\n path,\n message: `Path is not a file: ${path}`,\n });\n }\n\n const mtimeMs = stats.mtimeMs;\n const cached = fingerprintCache.get(path);\n\n // Short-circuit if mtime unchanged\n if (cached && cached.mtimeMs === mtimeMs) {\n return ok(cached);\n }\n\n // Read and hash file contents\n const contents = readFileSync(path);\n const sizeBytes = stats.size;\n\n // Compute hash synchronously (xxhash-wasm will be loaded async first time)\n const hash = computeHashSync(contents);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes,\n mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return ok(fingerprint);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return err({\n code: \"FILE_NOT_FOUND\",\n path,\n message: `File not found: ${path}`,\n });\n }\n\n return err({\n code: \"READ_ERROR\",\n path,\n message: `Failed to read file: ${error}`,\n });\n }\n}\n\n/**\n * Compute hash synchronously.\n * For first call, uses simple string hash as fallback.\n * Subsequent calls will use xxhash after async initialization.\n */\nfunction computeHashSync(contents: Buffer): string {\n // If xxhash is already loaded, use it\n if (xxhashInstance !== null) {\n const hash = xxhashInstance.h64Raw(new Uint8Array(contents));\n return hash.toString(16);\n }\n\n // First call: trigger async loading for next time\n void getXXHash();\n\n // Fallback: simple hash for first call only\n return simpleHash(contents);\n}\n\n/**\n * Simple hash function for initial calls before xxhash loads\n */\nfunction simpleHash(buffer: Buffer): string {\n let hash = 0;\n for (let i = 0; i < buffer.length; i++) {\n const byte = buffer[i];\n if (byte !== undefined) {\n hash = (hash << 5) - hash + byte;\n hash = hash & hash; // Convert to 32bit integer\n }\n }\n return hash.toString(16);\n}\n\n/**\n * Compute fingerprint from pre-read file content and stats.\n * This is used by the generator-based discoverer which already has the content.\n *\n * @param path - Absolute path to file (for caching)\n * @param stats - File stats (mtimeMs, size)\n * @param content - File content as string\n * @returns FileFingerprint\n */\nexport function computeFingerprintFromContent(\n path: string,\n stats: { readonly mtimeMs: number; readonly size: number },\n content: string,\n): FileFingerprint {\n // Check cache first by mtime\n const cached = fingerprintCache.get(path);\n if (cached && cached.mtimeMs === stats.mtimeMs) {\n return cached;\n }\n\n // Convert string to buffer for hashing\n const buffer = Buffer.from(content, \"utf-8\");\n const hash = computeHashSync(buffer);\n\n const fingerprint: FileFingerprint = {\n hash,\n sizeBytes: stats.size,\n mtimeMs: stats.mtimeMs,\n };\n\n fingerprintCache.set(path, fingerprint);\n return fingerprint;\n}\n\n/**\n * Invalidate cached fingerprint for a specific path\n *\n * @param path - Absolute path to invalidate\n */\nexport function invalidateFingerprint(path: string): void {\n fingerprintCache.delete(path);\n}\n\n/**\n * Clear all cached fingerprints\n */\nexport function clearFingerprintCache(): void {\n fingerprintCache.clear();\n}\n","import { extname } from \"node:path\";\nimport {\n type AliasResolver,\n createAsyncScheduler,\n createSyncScheduler,\n type EffectGenerator,\n normalizePath,\n} from \"@soda-gql/common\";\nimport { err, ok } from \"neverthrow\";\nimport type { createAstAnalyzer } from \"../ast\";\nimport type { ModuleAnalysis } from \"../ast/types\";\nimport { type BuilderResult, builderErrors } from \"../errors\";\nimport { type FileStats, OptionalFileReadEffect, OptionalFileStatEffect } from \"../scheduler\";\nimport { createSourceHash, extractModuleDependencies } from \"./common\";\nimport { computeFingerprintFromContent, invalidateFingerprint } from \"./fingerprint\";\nimport type { DiscoveryCache, DiscoverySnapshot } from \"./types\";\n\n/**\n * JavaScript file extensions that should be treated as empty modules.\n * These files are included in the dependency graph but not parsed for definitions.\n */\nconst JS_FILE_EXTENSIONS = [\".js\", \".mjs\", \".cjs\", \".jsx\"] as const;\n\n/**\n * Check if a file path is a JavaScript file (not TypeScript).\n * Used to skip AST analysis for JS files that are resolved as fallbacks.\n */\nconst isJsFile = (filePath: string): boolean => {\n const ext = extname(filePath).toLowerCase();\n return (JS_FILE_EXTENSIONS as readonly string[]).includes(ext);\n};\n\nexport type DiscoverModulesOptions = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n /** Optional alias resolver for tsconfig paths */\n readonly aliasResolver?: AliasResolver;\n /** Set of file paths explicitly invalidated (from BuilderChangeSet) */\n readonly incremental?: {\n readonly cache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly affectedFiles: Set<string>;\n };\n};\n\nexport type DiscoverModulesResult = {\n readonly snapshots: readonly DiscoverySnapshot[];\n readonly cacheHits: number;\n readonly cacheMisses: number;\n readonly cacheSkips: number;\n};\n\n/**\n * Generator-based module discovery that yields effects for file I/O.\n * This allows the discovery process to be executed with either sync or async schedulers.\n */\nexport function* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n aliasResolver,\n incremental,\n}: DiscoverModulesOptions): EffectGenerator<DiscoverModulesResult> {\n const snapshots = new Map<string, DiscoverySnapshot>();\n const stack = [...entryPaths];\n const changedFiles = incremental?.changedFiles ?? new Set<string>();\n const removedFiles = incremental?.removedFiles ?? new Set<string>();\n const affectedFiles = incremental?.affectedFiles ?? new Set<string>();\n const invalidatedSet = new Set<string>([...changedFiles, ...removedFiles, ...affectedFiles]);\n let cacheHits = 0;\n let cacheMisses = 0;\n let cacheSkips = 0;\n\n if (incremental) {\n for (const filePath of removedFiles) {\n incremental.cache.delete(filePath);\n invalidateFingerprint(filePath);\n }\n }\n\n while (stack.length > 0) {\n const rawFilePath = stack.pop();\n if (!rawFilePath) {\n continue;\n }\n\n // Normalize path for consistent cache key matching\n const filePath = normalizePath(rawFilePath);\n\n if (snapshots.has(filePath)) {\n continue;\n }\n\n // Check if explicitly invalidated\n let shouldReadFile = true;\n if (invalidatedSet.has(filePath)) {\n invalidateFingerprint(filePath);\n cacheSkips++;\n // Fall through to re-read and re-parse\n } else if (incremental) {\n // Try fingerprint-based cache check (avoid reading file)\n const cached = incremental.cache.peek(filePath);\n\n if (cached) {\n // Fast path: check fingerprint without reading file content\n const stats = yield* new OptionalFileStatEffect(filePath).run();\n\n if (stats) {\n const mtimeMs = stats.mtimeMs;\n const sizeBytes = stats.size;\n\n // If fingerprint matches, reuse cached snapshot\n if (cached.fingerprint.mtimeMs === mtimeMs && cached.fingerprint.sizeBytes === sizeBytes) {\n snapshots.set(filePath, cached);\n cacheHits++;\n // Enqueue dependencies from cache\n for (const dep of cached.dependencies) {\n if (dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n shouldReadFile = false;\n }\n }\n // If stats is null (file deleted), fall through to read attempt\n }\n }\n\n if (!shouldReadFile) {\n continue;\n }\n\n // Read source and compute signature\n const source = yield* new OptionalFileReadEffect(filePath).run();\n\n if (source === null) {\n // Handle deleted files gracefully - they may be in cache but removed from disk\n incremental?.cache.delete(filePath);\n invalidateFingerprint(filePath);\n continue;\n }\n\n const signature = createSourceHash(source);\n\n // Parse module (skip AST analysis for JS files - treat as empty)\n let analysis: ModuleAnalysis;\n if (isJsFile(filePath)) {\n // JS files are included in the dependency graph but treated as empty modules.\n // This happens when a .js import specifier resolves to an actual .js file\n // because no corresponding .ts file exists.\n analysis = {\n filePath,\n signature,\n definitions: [],\n imports: [],\n exports: [],\n diagnostics: [],\n };\n } else {\n analysis = astAnalyzer.analyze({ filePath, source });\n }\n cacheMisses++;\n\n // Build dependency records (relative + external) in a single pass\n const dependencies = extractModuleDependencies({ analysis, aliasResolver });\n\n // Enqueue all resolved relative dependencies for traversal\n for (const dep of dependencies) {\n if (!dep.isExternal && dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {\n stack.push(dep.resolvedPath);\n }\n }\n\n // Get stats for fingerprint (we may already have them from cache check)\n const stats = (yield* new OptionalFileStatEffect(filePath).run()) as FileStats;\n\n // Compute fingerprint from content (avoids re-reading the file)\n const fingerprint = computeFingerprintFromContent(filePath, stats, source);\n\n // Create snapshot\n const snapshot: DiscoverySnapshot = {\n filePath,\n normalizedFilePath: normalizePath(filePath),\n signature,\n fingerprint,\n analyzer: astAnalyzer.type,\n createdAtMs: Date.now(),\n analysis,\n dependencies,\n };\n\n snapshots.set(filePath, snapshot);\n\n // Store in cache\n if (incremental) {\n incremental.cache.store(snapshot);\n }\n }\n\n return {\n snapshots: Array.from(snapshots.values()),\n cacheHits,\n cacheMisses,\n cacheSkips,\n };\n}\n\n/**\n * Discover and analyze all modules starting from entry points.\n * Uses AST parsing instead of RegExp for reliable dependency extraction.\n * Supports caching with fingerprint-based invalidation to skip re-parsing unchanged files.\n *\n * This function uses the synchronous scheduler internally for backward compatibility.\n * For async execution with parallel file I/O, use discoverModulesGen with an async scheduler.\n */\nexport const discoverModules = (options: DiscoverModulesOptions): BuilderResult<DiscoverModulesResult> => {\n const scheduler = createSyncScheduler();\n const result = scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n\n/**\n * Asynchronous version of discoverModules.\n * Uses async scheduler for parallel file I/O operations.\n *\n * This is useful for large codebases where parallel file operations can improve performance.\n */\nexport const discoverModulesAsync = async (options: DiscoverModulesOptions): Promise<BuilderResult<DiscoverModulesResult>> => {\n const scheduler = createAsyncScheduler();\n const result = await scheduler.run(() => discoverModulesGen(options));\n\n if (result.isErr()) {\n const error = result.error;\n // Convert scheduler error to builder error\n return err(builderErrors.discoveryIOError(\"unknown\", error.message));\n }\n\n return ok(result.value);\n};\n","'use strict';\n\nconst WIN_SLASH = '\\\\\\\\/';\nconst WIN_NO_SLASH = `[^${WIN_SLASH}]`;\n\n/**\n * Posix glob regex\n */\n\nconst DOT_LITERAL = '\\\\.';\nconst PLUS_LITERAL = '\\\\+';\nconst QMARK_LITERAL = '\\\\?';\nconst SLASH_LITERAL = '\\\\/';\nconst ONE_CHAR = '(?=.)';\nconst QMARK = '[^/]';\nconst END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;\nconst START_ANCHOR = `(?:^|${SLASH_LITERAL})`;\nconst DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;\nconst NO_DOT = `(?!${DOT_LITERAL})`;\nconst NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;\nconst NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;\nconst NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;\nconst QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;\nconst STAR = `${QMARK}*?`;\nconst SEP = '/';\n\nconst POSIX_CHARS = {\n DOT_LITERAL,\n PLUS_LITERAL,\n QMARK_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n QMARK,\n END_ANCHOR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR,\n SEP\n};\n\n/**\n * Windows glob regex\n */\n\nconst WINDOWS_CHARS = {\n ...POSIX_CHARS,\n\n SLASH_LITERAL: `[${WIN_SLASH}]`,\n QMARK: WIN_NO_SLASH,\n STAR: `${WIN_NO_SLASH}*?`,\n DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,\n NO_DOT: `(?!${DOT_LITERAL})`,\n NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,\n NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n QMARK_NO_DOT: `[^.${WIN_SLASH}]`,\n START_ANCHOR: `(?:^|[${WIN_SLASH}])`,\n END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,\n SEP: '\\\\'\n};\n\n/**\n * POSIX Bracket Regex\n */\n\nconst POSIX_REGEX_SOURCE = {\n alnum: 'a-zA-Z0-9',\n alpha: 'a-zA-Z',\n ascii: '\\\\x00-\\\\x7F',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1F\\\\x7F',\n digit: '0-9',\n graph: '\\\\x21-\\\\x7E',\n lower: 'a-z',\n print: '\\\\x20-\\\\x7E ',\n punct: '\\\\-!\"#$%&\\'()\\\\*+,./:;<=>?@[\\\\]^_`{|}~',\n space: ' \\\\t\\\\r\\\\n\\\\v\\\\f',\n upper: 'A-Z',\n word: 'A-Za-z0-9_',\n xdigit: 'A-Fa-f0-9'\n};\n\nmodule.exports = {\n MAX_LENGTH: 1024 * 64,\n POSIX_REGEX_SOURCE,\n\n // regular expressions\n REGEX_BACKSLASH: /\\\\(?![*+?^${}(|)[\\]])/g,\n REGEX_NON_SPECIAL_CHARS: /^[^@![\\].,$*+?^{}()|\\\\/]+/,\n REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\\]]/,\n REGEX_SPECIAL_CHARS_BACKREF: /(\\\\?)((\\W)(\\3*))/g,\n REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\\]])/g,\n REGEX_REMOVE_BACKSLASH: /(?:\\[.*?[^\\\\]\\]|\\\\(?=.))/g,\n\n // Replace globs with equivalent patterns to reduce parsing time.\n REPLACEMENTS: {\n __proto__: null,\n '***': '*',\n '**/**': '**',\n '**/**/**': '**'\n },\n\n // Digits\n CHAR_0: 48, /* 0 */\n CHAR_9: 57, /* 9 */\n\n // Alphabet chars.\n CHAR_UPPERCASE_A: 65, /* A */\n CHAR_LOWERCASE_A: 97, /* a */\n CHAR_UPPERCASE_Z: 90, /* Z */\n CHAR_LOWERCASE_Z: 122, /* z */\n\n CHAR_LEFT_PARENTHESES: 40, /* ( */\n CHAR_RIGHT_PARENTHESES: 41, /* ) */\n\n CHAR_ASTERISK: 42, /* * */\n\n // Non-alphabetic chars.\n CHAR_AMPERSAND: 38, /* & */\n CHAR_AT: 64, /* @ */\n CHAR_BACKWARD_SLASH: 92, /* \\ */\n CHAR_CARRIAGE_RETURN: 13, /* \\r */\n CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */\n CHAR_COLON: 58, /* : */\n CHAR_COMMA: 44, /* , */\n CHAR_DOT: 46, /* . */\n CHAR_DOUBLE_QUOTE: 34, /* \" */\n CHAR_EQUAL: 61, /* = */\n CHAR_EXCLAMATION_MARK: 33, /* ! */\n CHAR_FORM_FEED: 12, /* \\f */\n CHAR_FORWARD_SLASH: 47, /* / */\n CHAR_GRAVE_ACCENT: 96, /* ` */\n CHAR_HASH: 35, /* # */\n CHAR_HYPHEN_MINUS: 45, /* - */\n CHAR_LEFT_ANGLE_BRACKET: 60, /* < */\n CHAR_LEFT_CURLY_BRACE: 123, /* { */\n CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */\n CHAR_LINE_FEED: 10, /* \\n */\n CHAR_NO_BREAK_SPACE: 160, /* \\u00A0 */\n CHAR_PERCENT: 37, /* % */\n CHAR_PLUS: 43, /* + */\n CHAR_QUESTION_MARK: 63, /* ? */\n CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */\n CHAR_RIGHT_CURLY_BRACE: 125, /* } */\n CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */\n CHAR_SEMICOLON: 59, /* ; */\n CHAR_SINGLE_QUOTE: 39, /* ' */\n CHAR_SPACE: 32, /* */\n CHAR_TAB: 9, /* \\t */\n CHAR_UNDERSCORE: 95, /* _ */\n CHAR_VERTICAL_LINE: 124, /* | */\n CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \\uFEFF */\n\n /**\n * Create EXTGLOB_CHARS\n */\n\n extglobChars(chars) {\n return {\n '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },\n '?': { type: 'qmark', open: '(?:', close: ')?' },\n '+': { type: 'plus', open: '(?:', close: ')+' },\n '*': { type: 'star', open: '(?:', close: ')*' },\n '@': { type: 'at', open: '(?:', close: ')' }\n };\n },\n\n /**\n * Create GLOB_CHARS\n */\n\n globChars(win32) {\n return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;\n }\n};\n","/*global navigator*/\n'use strict';\n\nconst {\n REGEX_BACKSLASH,\n REGEX_REMOVE_BACKSLASH,\n REGEX_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_GLOBAL\n} = require('./constants');\n\nexports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);\nexports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);\nexports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);\nexports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\\\$1');\nexports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');\n\nexports.isWindows = () => {\n if (typeof navigator !== 'undefined' && navigator.platform) {\n const platform = navigator.platform.toLowerCase();\n return platform === 'win32' || platform === 'windows';\n }\n\n if (typeof process !== 'undefined' && process.platform) {\n return process.platform === 'win32';\n }\n\n return false;\n};\n\nexports.removeBackslashes = str => {\n return str.replace(REGEX_REMOVE_BACKSLASH, match => {\n return match === '\\\\' ? '' : match;\n });\n};\n\nexports.escapeLast = (input, char, lastIdx) => {\n const idx = input.lastIndexOf(char, lastIdx);\n if (idx === -1) return input;\n if (input[idx - 1] === '\\\\') return exports.escapeLast(input, char, idx - 1);\n return `${input.slice(0, idx)}\\\\${input.slice(idx)}`;\n};\n\nexports.removePrefix = (input, state = {}) => {\n let output = input;\n if (output.startsWith('./')) {\n output = output.slice(2);\n state.prefix = './';\n }\n return output;\n};\n\nexports.wrapOutput = (input, state = {}, options = {}) => {\n const prepend = options.contains ? '' : '^';\n const append = options.contains ? '' : '$';\n\n let output = `${prepend}(?:${input})${append}`;\n if (state.negated === true) {\n output = `(?:^(?!${output}).*$)`;\n }\n return output;\n};\n\nexports.basename = (path, { windows } = {}) => {\n const segs = path.split(windows ? /[\\\\/]/ : '/');\n const last = segs[segs.length - 1];\n\n if (last === '') {\n return segs[segs.length - 2];\n }\n\n return last;\n};\n","'use strict';\n\nconst utils = require('./utils');\nconst {\n CHAR_ASTERISK, /* * */\n CHAR_AT, /* @ */\n CHAR_BACKWARD_SLASH, /* \\ */\n CHAR_COMMA, /* , */\n CHAR_DOT, /* . */\n CHAR_EXCLAMATION_MARK, /* ! */\n CHAR_FORWARD_SLASH, /* / */\n CHAR_LEFT_CURLY_BRACE, /* { */\n CHAR_LEFT_PARENTHESES, /* ( */\n CHAR_LEFT_SQUARE_BRACKET, /* [ */\n CHAR_PLUS, /* + */\n CHAR_QUESTION_MARK, /* ? */\n CHAR_RIGHT_CURLY_BRACE, /* } */\n CHAR_RIGHT_PARENTHESES, /* ) */\n CHAR_RIGHT_SQUARE_BRACKET /* ] */\n} = require('./constants');\n\nconst isPathSeparator = code => {\n return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;\n};\n\nconst depth = token => {\n if (token.isPrefix !== true) {\n token.depth = token.isGlobstar ? Infinity : 1;\n }\n};\n\n/**\n * Quickly scans a glob pattern and returns an object with a handful of\n * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),\n * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not\n * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).\n *\n * ```js\n * const pm = require('picomatch');\n * console.log(pm.scan('foo/bar/*.js'));\n * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object} Returns an object with tokens and regex source string.\n * @api public\n */\n\nconst scan = (input, options) => {\n const opts = options || {};\n\n const length = input.length - 1;\n const scanToEnd = opts.parts === true || opts.scanToEnd === true;\n const slashes = [];\n const tokens = [];\n const parts = [];\n\n let str = input;\n let index = -1;\n let start = 0;\n let lastIndex = 0;\n let isBrace = false;\n let isBracket = false;\n let isGlob = false;\n let isExtglob = false;\n let isGlobstar = false;\n let braceEscaped = false;\n let backslashes = false;\n let negated = false;\n let negatedExtglob = false;\n let finished = false;\n let braces = 0;\n let prev;\n let code;\n let token = { value: '', depth: 0, isGlob: false };\n\n const eos = () => index >= length;\n const peek = () => str.charCodeAt(index + 1);\n const advance = () => {\n prev = code;\n return str.charCodeAt(++index);\n };\n\n while (index < length) {\n code = advance();\n let next;\n\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braceEscaped = true;\n }\n continue;\n }\n\n if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n continue;\n }\n\n if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (braceEscaped !== true && code === CHAR_COMMA) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_RIGHT_CURLY_BRACE) {\n braces--;\n\n if (braces === 0) {\n braceEscaped = false;\n isBrace = token.isBrace = true;\n finished = true;\n break;\n }\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_FORWARD_SLASH) {\n slashes.push(index);\n tokens.push(token);\n token = { value: '', depth: 0, isGlob: false };\n\n if (finished === true) continue;\n if (prev === CHAR_DOT && index === (start + 1)) {\n start += 2;\n continue;\n }\n\n lastIndex = index + 1;\n continue;\n }\n\n if (opts.noext !== true) {\n const isExtglobChar = code === CHAR_PLUS\n || code === CHAR_AT\n || code === CHAR_ASTERISK\n || code === CHAR_QUESTION_MARK\n || code === CHAR_EXCLAMATION_MARK;\n\n if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n isExtglob = token.isExtglob = true;\n finished = true;\n if (code === CHAR_EXCLAMATION_MARK && index === start) {\n negatedExtglob = true;\n }\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n }\n\n if (code === CHAR_ASTERISK) {\n if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_QUESTION_MARK) {\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_LEFT_SQUARE_BRACKET) {\n while (eos() !== true && (next = advance())) {\n if (next === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (next === CHAR_RIGHT_SQUARE_BRACKET) {\n isBracket = token.isBracket = true;\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {\n negated = token.negated = true;\n start++;\n continue;\n }\n\n if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_LEFT_PARENTHESES) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n\n if (isGlob === true) {\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n }\n\n if (opts.noext === true) {\n isExtglob = false;\n isGlob = false;\n }\n\n let base = str;\n let prefix = '';\n let glob = '';\n\n if (start > 0) {\n prefix = str.slice(0, start);\n str = str.slice(start);\n lastIndex -= start;\n }\n\n if (base && isGlob === true && lastIndex > 0) {\n base = str.slice(0, lastIndex);\n glob = str.slice(lastIndex);\n } else if (isGlob === true) {\n base = '';\n glob = str;\n } else {\n base = str;\n }\n\n if (base && base !== '' && base !== '/' && base !== str) {\n if (isPathSeparator(base.charCodeAt(base.length - 1))) {\n base = base.slice(0, -1);\n }\n }\n\n if (opts.unescape === true) {\n if (glob) glob = utils.removeBackslashes(glob);\n\n if (base && backslashes === true) {\n base = utils.removeBackslashes(base);\n }\n }\n\n const state = {\n prefix,\n input,\n start,\n base,\n glob,\n isBrace,\n isBracket,\n isGlob,\n isExtglob,\n isGlobstar,\n negated,\n negatedExtglob\n };\n\n if (opts.tokens === true) {\n state.maxDepth = 0;\n if (!isPathSeparator(code)) {\n tokens.push(token);\n }\n state.tokens = tokens;\n }\n\n if (opts.parts === true || opts.tokens === true) {\n let prevIndex;\n\n for (let idx = 0; idx < slashes.length; idx++) {\n const n = prevIndex ? prevIndex + 1 : start;\n const i = slashes[idx];\n const value = input.slice(n, i);\n if (opts.tokens) {\n if (idx === 0 && start !== 0) {\n tokens[idx].isPrefix = true;\n tokens[idx].value = prefix;\n } else {\n tokens[idx].value = value;\n }\n depth(tokens[idx]);\n state.maxDepth += tokens[idx].depth;\n }\n if (idx !== 0 || value !== '') {\n parts.push(value);\n }\n prevIndex = i;\n }\n\n if (prevIndex && prevIndex + 1 < input.length) {\n const value = input.slice(prevIndex + 1);\n parts.push(value);\n\n if (opts.tokens) {\n tokens[tokens.length - 1].value = value;\n depth(tokens[tokens.length - 1]);\n state.maxDepth += tokens[tokens.length - 1].depth;\n }\n }\n\n state.slashes = slashes;\n state.parts = parts;\n }\n\n return state;\n};\n\nmodule.exports = scan;\n","'use strict';\n\nconst constants = require('./constants');\nconst utils = require('./utils');\n\n/**\n * Constants\n */\n\nconst {\n MAX_LENGTH,\n POSIX_REGEX_SOURCE,\n REGEX_NON_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_BACKREF,\n REPLACEMENTS\n} = constants;\n\n/**\n * Helpers\n */\n\nconst expandRange = (args, options) => {\n if (typeof options.expandRange === 'function') {\n return options.expandRange(...args, options);\n }\n\n args.sort();\n const value = `[${args.join('-')}]`;\n\n try {\n /* eslint-disable-next-line no-new */\n new RegExp(value);\n } catch (ex) {\n return args.map(v => utils.escapeRegex(v)).join('..');\n }\n\n return value;\n};\n\n/**\n * Create the message for a syntax error\n */\n\nconst syntaxError = (type, char) => {\n return `Missing ${type}: \"${char}\" - use \"\\\\\\\\${char}\" to match literal characters`;\n};\n\n/**\n * Parse the given input string.\n * @param {String} input\n * @param {Object} options\n * @return {Object}\n */\n\nconst parse = (input, options) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n input = REPLACEMENTS[input] || input;\n\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n\n let len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n const bos = { type: 'bos', value: '', output: opts.prepend || '' };\n const tokens = [bos];\n\n const capture = opts.capture ? '' : '?:';\n\n // create constants based on platform, for windows or posix\n const PLATFORM_CHARS = constants.globChars(opts.windows);\n const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);\n\n const {\n DOT_LITERAL,\n PLUS_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR\n } = PLATFORM_CHARS;\n\n const globstar = opts => {\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const nodot = opts.dot ? '' : NO_DOT;\n const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;\n let star = opts.bash === true ? globstar(opts) : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n // minimatch options support\n if (typeof opts.noext === 'boolean') {\n opts.noextglob = opts.noext;\n }\n\n const state = {\n input,\n index: -1,\n start: 0,\n dot: opts.dot === true,\n consumed: '',\n output: '',\n prefix: '',\n backtrack: false,\n negated: false,\n brackets: 0,\n braces: 0,\n parens: 0,\n quotes: 0,\n globstar: false,\n tokens\n };\n\n input = utils.removePrefix(input, state);\n len = input.length;\n\n const extglobs = [];\n const braces = [];\n const stack = [];\n let prev = bos;\n let value;\n\n /**\n * Tokenizing helpers\n */\n\n const eos = () => state.index === len - 1;\n const peek = state.peek = (n = 1) => input[state.index + n];\n const advance = state.advance = () => input[++state.index] || '';\n const remaining = () => input.slice(state.index + 1);\n const consume = (value = '', num = 0) => {\n state.consumed += value;\n state.index += num;\n };\n\n const append = token => {\n state.output += token.output != null ? token.output : token.value;\n consume(token.value);\n };\n\n const negate = () => {\n let count = 1;\n\n while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {\n advance();\n state.start++;\n count++;\n }\n\n if (count % 2 === 0) {\n return false;\n }\n\n state.negated = true;\n state.start++;\n return true;\n };\n\n const increment = type => {\n state[type]++;\n stack.push(type);\n };\n\n const decrement = type => {\n state[type]--;\n stack.pop();\n };\n\n /**\n * Push tokens onto the tokens array. This helper speeds up\n * tokenizing by 1) helping us avoid backtracking as much as possible,\n * and 2) helping us avoid creating extra tokens when consecutive\n * characters are plain text. This improves performance and simplifies\n * lookbehinds.\n */\n\n const push = tok => {\n if (prev.type === 'globstar') {\n const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');\n const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));\n\n if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {\n state.output = state.output.slice(0, -prev.output.length);\n prev.type = 'star';\n prev.value = '*';\n prev.output = star;\n state.output += prev.output;\n }\n }\n\n if (extglobs.length && tok.type !== 'paren') {\n extglobs[extglobs.length - 1].inner += tok.value;\n }\n\n if (tok.value || tok.output) append(tok);\n if (prev && prev.type === 'text' && tok.type === 'text') {\n prev.output = (prev.output || prev.value) + tok.value;\n prev.value += tok.value;\n return;\n }\n\n tok.prev = prev;\n tokens.push(tok);\n prev = tok;\n };\n\n const extglobOpen = (type, value) => {\n const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };\n\n token.prev = prev;\n token.parens = state.parens;\n token.output = state.output;\n const output = (opts.capture ? '(' : '') + token.open;\n\n increment('parens');\n push({ type, value, output: state.output ? '' : ONE_CHAR });\n push({ type: 'paren', extglob: true, value: advance(), output });\n extglobs.push(token);\n };\n\n const extglobClose = token => {\n let output = token.close + (opts.capture ? ')' : '');\n let rest;\n\n if (token.type === 'negate') {\n let extglobStar = star;\n\n if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {\n extglobStar = globstar(opts);\n }\n\n if (extglobStar !== star || eos() || /^\\)+$/.test(remaining())) {\n output = token.close = `)$))${extglobStar}`;\n }\n\n if (token.inner.includes('*') && (rest = remaining()) && /^\\.[^\\\\/.]+$/.test(rest)) {\n // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.\n // In this case, we need to parse the string and use it in the output of the original pattern.\n // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.\n //\n // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.\n const expression = parse(rest, { ...options, fastpaths: false }).output;\n\n output = token.close = `)${expression})${extglobStar})`;\n }\n\n if (token.prev.type === 'bos') {\n state.negatedExtglob = true;\n }\n }\n\n push({ type: 'paren', extglob: true, value, output });\n decrement('parens');\n };\n\n /**\n * Fast paths\n */\n\n if (opts.fastpaths !== false && !/(^[*!]|[/()[\\]{}\"])/.test(input)) {\n let backslashes = false;\n\n let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {\n if (first === '\\\\') {\n backslashes = true;\n return m;\n }\n\n if (first === '?') {\n if (esc) {\n return esc + first + (rest ? QMARK.repeat(rest.length) : '');\n }\n if (index === 0) {\n return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');\n }\n return QMARK.repeat(chars.length);\n }\n\n if (first === '.') {\n return DOT_LITERAL.repeat(chars.length);\n }\n\n if (first === '*') {\n if (esc) {\n return esc + first + (rest ? star : '');\n }\n return star;\n }\n return esc ? m : `\\\\${m}`;\n });\n\n if (backslashes === true) {\n if (opts.unescape === true) {\n output = output.replace(/\\\\/g, '');\n } else {\n output = output.replace(/\\\\+/g, m => {\n return m.length % 2 === 0 ? '\\\\\\\\' : (m ? '\\\\' : '');\n });\n }\n }\n\n if (output === input && opts.contains === true) {\n state.output = input;\n return state;\n }\n\n state.output = utils.wrapOutput(output, state, options);\n return state;\n }\n\n /**\n * Tokenize input until we reach end-of-string\n */\n\n while (!eos()) {\n value = advance();\n\n if (value === '\\u0000') {\n continue;\n }\n\n /**\n * Escaped characters\n */\n\n if (value === '\\\\') {\n const next = peek();\n\n if (next === '/' && opts.bash !== true) {\n continue;\n }\n\n if (next === '.' || next === ';') {\n continue;\n }\n\n if (!next) {\n value += '\\\\';\n push({ type: 'text', value });\n continue;\n }\n\n // collapse slashes to reduce potential for exploits\n const match = /^\\\\+/.exec(remaining());\n let slashes = 0;\n\n if (match && match[0].length > 2) {\n slashes = match[0].length;\n state.index += slashes;\n if (slashes % 2 !== 0) {\n value += '\\\\';\n }\n }\n\n if (opts.unescape === true) {\n value = advance();\n } else {\n value += advance();\n }\n\n if (state.brackets === 0) {\n push({ type: 'text', value });\n continue;\n }\n }\n\n /**\n * If we're inside a regex character class, continue\n * until we reach the closing bracket.\n */\n\n if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {\n if (opts.posix !== false && value === ':') {\n const inner = prev.value.slice(1);\n if (inner.includes('[')) {\n prev.posix = true;\n\n if (inner.includes(':')) {\n const idx = prev.value.lastIndexOf('[');\n const pre = prev.value.slice(0, idx);\n const rest = prev.value.slice(idx + 2);\n const posix = POSIX_REGEX_SOURCE[rest];\n if (posix) {\n prev.value = pre + posix;\n state.backtrack = true;\n advance();\n\n if (!bos.output && tokens.indexOf(prev) === 1) {\n bos.output = ONE_CHAR;\n }\n continue;\n }\n }\n }\n }\n\n if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {\n value = `\\\\${value}`;\n }\n\n if (value === ']' && (prev.value === '[' || prev.value === '[^')) {\n value = `\\\\${value}`;\n }\n\n if (opts.posix === true && value === '!' && prev.value === '[') {\n value = '^';\n }\n\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * If we're inside a quoted string, continue\n * until we reach the closing double quote.\n */\n\n if (state.quotes === 1 && value !== '\"') {\n value = utils.escapeRegex(value);\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * Double quotes\n */\n\n if (value === '\"') {\n state.quotes = state.quotes === 1 ? 0 : 1;\n if (opts.keepQuotes === true) {\n push({ type: 'text', value });\n }\n continue;\n }\n\n /**\n * Parentheses\n */\n\n if (value === '(') {\n increment('parens');\n push({ type: 'paren', value });\n continue;\n }\n\n if (value === ')') {\n if (state.parens === 0 && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '('));\n }\n\n const extglob = extglobs[extglobs.length - 1];\n if (extglob && state.parens === extglob.parens + 1) {\n extglobClose(extglobs.pop());\n continue;\n }\n\n push({ type: 'paren', value, output: state.parens ? ')' : '\\\\)' });\n decrement('parens');\n continue;\n }\n\n /**\n * Square brackets\n */\n\n if (value === '[') {\n if (opts.nobracket === true || !remaining().includes(']')) {\n if (opts.nobracket !== true && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('closing', ']'));\n }\n\n value = `\\\\${value}`;\n } else {\n increment('brackets');\n }\n\n push({ type: 'bracket', value });\n continue;\n }\n\n if (value === ']') {\n if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n if (state.brackets === 0) {\n if (opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '['));\n }\n\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n decrement('brackets');\n\n const prevValue = prev.value.slice(1);\n if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {\n value = `/${value}`;\n }\n\n prev.value += value;\n append({ value });\n\n // when literal brackets are explicitly disabled\n // assume we should match with a regex character class\n if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {\n continue;\n }\n\n const escaped = utils.escapeRegex(prev.value);\n state.output = state.output.slice(0, -prev.value.length);\n\n // when literal brackets are explicitly enabled\n // assume we should escape the brackets to match literal characters\n if (opts.literalBrackets === true) {\n state.output += escaped;\n prev.value = escaped;\n continue;\n }\n\n // when the user specifies nothing, try to match both\n prev.value = `(${capture}${escaped}|${prev.value})`;\n state.output += prev.value;\n continue;\n }\n\n /**\n * Braces\n */\n\n if (value === '{' && opts.nobrace !== true) {\n increment('braces');\n\n const open = {\n type: 'brace',\n value,\n output: '(',\n outputIndex: state.output.length,\n tokensIndex: state.tokens.length\n };\n\n braces.push(open);\n push(open);\n continue;\n }\n\n if (value === '}') {\n const brace = braces[braces.length - 1];\n\n if (opts.nobrace === true || !brace) {\n push({ type: 'text', value, output: value });\n continue;\n }\n\n let output = ')';\n\n if (brace.dots === true) {\n const arr = tokens.slice();\n const range = [];\n\n for (let i = arr.length - 1; i >= 0; i--) {\n tokens.pop();\n if (arr[i].type === 'brace') {\n break;\n }\n if (arr[i].type !== 'dots') {\n range.unshift(arr[i].value);\n }\n }\n\n output = expandRange(range, opts);\n state.backtrack = true;\n }\n\n if (brace.comma !== true && brace.dots !== true) {\n const out = state.output.slice(0, brace.outputIndex);\n const toks = state.tokens.slice(brace.tokensIndex);\n brace.value = brace.output = '\\\\{';\n value = output = '\\\\}';\n state.output = out;\n for (const t of toks) {\n state.output += (t.output || t.value);\n }\n }\n\n push({ type: 'brace', value, output });\n decrement('braces');\n braces.pop();\n continue;\n }\n\n /**\n * Pipes\n */\n\n if (value === '|') {\n if (extglobs.length > 0) {\n extglobs[extglobs.length - 1].conditions++;\n }\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Commas\n */\n\n if (value === ',') {\n let output = value;\n\n const brace = braces[braces.length - 1];\n if (brace && stack[stack.length - 1] === 'braces') {\n brace.comma = true;\n output = '|';\n }\n\n push({ type: 'comma', value, output });\n continue;\n }\n\n /**\n * Slashes\n */\n\n if (value === '/') {\n // if the beginning of the glob is \"./\", advance the start\n // to the current index, and don't add the \"./\" characters\n // to the state. This greatly simplifies lookbehinds when\n // checking for BOS characters like \"!\" and \".\" (not \"./\")\n if (prev.type === 'dot' && state.index === state.start + 1) {\n state.start = state.index + 1;\n state.consumed = '';\n state.output = '';\n tokens.pop();\n prev = bos; // reset \"prev\" to the first token\n continue;\n }\n\n push({ type: 'slash', value, output: SLASH_LITERAL });\n continue;\n }\n\n /**\n * Dots\n */\n\n if (value === '.') {\n if (state.braces > 0 && prev.type === 'dot') {\n if (prev.value === '.') prev.output = DOT_LITERAL;\n const brace = braces[braces.length - 1];\n prev.type = 'dots';\n prev.output += value;\n prev.value += value;\n brace.dots = true;\n continue;\n }\n\n if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {\n push({ type: 'text', value, output: DOT_LITERAL });\n continue;\n }\n\n push({ type: 'dot', value, output: DOT_LITERAL });\n continue;\n }\n\n /**\n * Question marks\n */\n\n if (value === '?') {\n const isGroup = prev && prev.value === '(';\n if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('qmark', value);\n continue;\n }\n\n if (prev && prev.type === 'paren') {\n const next = peek();\n let output = value;\n\n if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\\w+>)/.test(remaining()))) {\n output = `\\\\${value}`;\n }\n\n push({ type: 'text', value, output });\n continue;\n }\n\n if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {\n push({ type: 'qmark', value, output: QMARK_NO_DOT });\n continue;\n }\n\n push({ type: 'qmark', value, output: QMARK });\n continue;\n }\n\n /**\n * Exclamation\n */\n\n if (value === '!') {\n if (opts.noextglob !== true && peek() === '(') {\n if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {\n extglobOpen('negate', value);\n continue;\n }\n }\n\n if (opts.nonegate !== true && state.index === 0) {\n negate();\n continue;\n }\n }\n\n /**\n * Plus\n */\n\n if (value === '+') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('plus', value);\n continue;\n }\n\n if ((prev && prev.value === '(') || opts.regex === false) {\n push({ type: 'plus', value, output: PLUS_LITERAL });\n continue;\n }\n\n if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {\n push({ type: 'plus', value });\n continue;\n }\n\n push({ type: 'plus', value: PLUS_LITERAL });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value === '@') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n push({ type: 'at', extglob: true, value, output: '' });\n continue;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value !== '*') {\n if (value === '$' || value === '^') {\n value = `\\\\${value}`;\n }\n\n const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());\n if (match) {\n value += match[0];\n state.index += match[0].length;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Stars\n */\n\n if (prev && (prev.type === 'globstar' || prev.star === true)) {\n prev.type = 'star';\n prev.star = true;\n prev.value += value;\n prev.output = star;\n state.backtrack = true;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n let rest = remaining();\n if (opts.noextglob !== true && /^\\([^?]/.test(rest)) {\n extglobOpen('star', value);\n continue;\n }\n\n if (prev.type === 'star') {\n if (opts.noglobstar === true) {\n consume(value);\n continue;\n }\n\n const prior = prev.prev;\n const before = prior.prev;\n const isStart = prior.type === 'slash' || prior.type === 'bos';\n const afterStar = before && (before.type === 'star' || before.type === 'globstar');\n\n if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');\n const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');\n if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n // strip consecutive `/**/`\n while (rest.slice(0, 3) === '/**') {\n const after = input[state.index + 4];\n if (after && after !== '/') {\n break;\n }\n rest = rest.slice(3);\n consume('/**', 3);\n }\n\n if (prior.type === 'bos' && eos()) {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = globstar(opts);\n state.output = prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');\n prev.value += value;\n state.globstar = true;\n state.output += prior.output + prev.output;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {\n const end = rest[1] !== void 0 ? '|$' : '';\n\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;\n prev.value += value;\n\n state.output += prior.output + prev.output;\n state.globstar = true;\n\n consume(value + advance());\n\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n if (prior.type === 'bos' && rest[0] === '/') {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;\n state.output = prev.output;\n state.globstar = true;\n consume(value + advance());\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n // remove single star from output\n state.output = state.output.slice(0, -prev.output.length);\n\n // reset previous token to globstar\n prev.type = 'globstar';\n prev.output = globstar(opts);\n prev.value += value;\n\n // reset output with globstar\n state.output += prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n const token = { type: 'star', value, output: star };\n\n if (opts.bash === true) {\n token.output = '.*?';\n if (prev.type === 'bos' || prev.type === 'slash') {\n token.output = nodot + token.output;\n }\n push(token);\n continue;\n }\n\n if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {\n token.output = value;\n push(token);\n continue;\n }\n\n if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {\n if (prev.type === 'dot') {\n state.output += NO_DOT_SLASH;\n prev.output += NO_DOT_SLASH;\n\n } else if (opts.dot === true) {\n state.output += NO_DOTS_SLASH;\n prev.output += NO_DOTS_SLASH;\n\n } else {\n state.output += nodot;\n prev.output += nodot;\n }\n\n if (peek() !== '*') {\n state.output += ONE_CHAR;\n prev.output += ONE_CHAR;\n }\n }\n\n push(token);\n }\n\n while (state.brackets > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));\n state.output = utils.escapeLast(state.output, '[');\n decrement('brackets');\n }\n\n while (state.parens > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));\n state.output = utils.escapeLast(state.output, '(');\n decrement('parens');\n }\n\n while (state.braces > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));\n state.output = utils.escapeLast(state.output, '{');\n decrement('braces');\n }\n\n if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {\n push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });\n }\n\n // rebuild the output if we had to backtrack at any point\n if (state.backtrack === true) {\n state.output = '';\n\n for (const token of state.tokens) {\n state.output += token.output != null ? token.output : token.value;\n\n if (token.suffix) {\n state.output += token.suffix;\n }\n }\n }\n\n return state;\n};\n\n/**\n * Fast paths for creating regular expressions for common glob patterns.\n * This can significantly speed up processing and has very little downside\n * impact when none of the fast paths match.\n */\n\nparse.fastpaths = (input, options) => {\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n const len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n input = REPLACEMENTS[input] || input;\n\n // create constants based on platform, for windows or posix\n const {\n DOT_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOTS_SLASH,\n STAR,\n START_ANCHOR\n } = constants.globChars(opts.windows);\n\n const nodot = opts.dot ? NO_DOTS : NO_DOT;\n const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;\n const capture = opts.capture ? '' : '?:';\n const state = { negated: false, prefix: '' };\n let star = opts.bash === true ? '.*?' : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n const globstar = opts => {\n if (opts.noglobstar === true) return star;\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const create = str => {\n switch (str) {\n case '*':\n return `${nodot}${ONE_CHAR}${star}`;\n\n case '.*':\n return `${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*.*':\n return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*/*':\n return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;\n\n case '**':\n return nodot + globstar(opts);\n\n case '**/*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;\n\n case '**/*.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '**/.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n default: {\n const match = /^(.*?)\\.(\\w+)$/.exec(str);\n if (!match) return;\n\n const source = create(match[1]);\n if (!source) return;\n\n return source + DOT_LITERAL + match[2];\n }\n }\n };\n\n const output = utils.removePrefix(input, state);\n let source = create(output);\n\n if (source && opts.strictSlashes !== true) {\n source += `${SLASH_LITERAL}?`;\n }\n\n return source;\n};\n\nmodule.exports = parse;\n","'use strict';\n\nconst scan = require('./scan');\nconst parse = require('./parse');\nconst utils = require('./utils');\nconst constants = require('./constants');\nconst isObject = val => val && typeof val === 'object' && !Array.isArray(val);\n\n/**\n * Creates a matcher function from one or more glob patterns. The\n * returned function takes a string to match as its first argument,\n * and returns true if the string is a match. The returned matcher\n * function also takes a boolean as the second argument that, when true,\n * returns an object with additional information.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch(glob[, options]);\n *\n * const isMatch = picomatch('*.!(*a)');\n * console.log(isMatch('a.a')); //=> false\n * console.log(isMatch('a.b')); //=> true\n * ```\n * @name picomatch\n * @param {String|Array} `globs` One or more glob patterns.\n * @param {Object=} `options`\n * @return {Function=} Returns a matcher function.\n * @api public\n */\n\nconst picomatch = (glob, options, returnState = false) => {\n if (Array.isArray(glob)) {\n const fns = glob.map(input => picomatch(input, options, returnState));\n const arrayMatcher = str => {\n for (const isMatch of fns) {\n const state = isMatch(str);\n if (state) return state;\n }\n return false;\n };\n return arrayMatcher;\n }\n\n const isState = isObject(glob) && glob.tokens && glob.input;\n\n if (glob === '' || (typeof glob !== 'string' && !isState)) {\n throw new TypeError('Expected pattern to be a non-empty string');\n }\n\n const opts = options || {};\n const posix = opts.windows;\n const regex = isState\n ? picomatch.compileRe(glob, options)\n : picomatch.makeRe(glob, options, false, true);\n\n const state = regex.state;\n delete regex.state;\n\n let isIgnored = () => false;\n if (opts.ignore) {\n const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };\n isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);\n }\n\n const matcher = (input, returnObject = false) => {\n const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });\n const result = { glob, state, regex, posix, input, output, match, isMatch };\n\n if (typeof opts.onResult === 'function') {\n opts.onResult(result);\n }\n\n if (isMatch === false) {\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (isIgnored(input)) {\n if (typeof opts.onIgnore === 'function') {\n opts.onIgnore(result);\n }\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (typeof opts.onMatch === 'function') {\n opts.onMatch(result);\n }\n return returnObject ? result : true;\n };\n\n if (returnState) {\n matcher.state = state;\n }\n\n return matcher;\n};\n\n/**\n * Test `input` with the given `regex`. This is used by the main\n * `picomatch()` function to test the input string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.test(input, regex[, options]);\n *\n * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\\/([^/]*?))$/));\n * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp} `regex`\n * @return {Object} Returns an object with matching info.\n * @api public\n */\n\npicomatch.test = (input, regex, options, { glob, posix } = {}) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected input to be a string');\n }\n\n if (input === '') {\n return { isMatch: false, output: '' };\n }\n\n const opts = options || {};\n const format = opts.format || (posix ? utils.toPosixSlashes : null);\n let match = input === glob;\n let output = (match && format) ? format(input) : input;\n\n if (match === false) {\n output = format ? format(input) : input;\n match = output === glob;\n }\n\n if (match === false || opts.capture === true) {\n if (opts.matchBase === true || opts.basename === true) {\n match = picomatch.matchBase(input, regex, options, posix);\n } else {\n match = regex.exec(output);\n }\n }\n\n return { isMatch: Boolean(match), match, output };\n};\n\n/**\n * Match the basename of a filepath.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.matchBase(input, glob[, options]);\n * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).\n * @return {Boolean}\n * @api public\n */\n\npicomatch.matchBase = (input, glob, options) => {\n const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);\n return regex.test(utils.basename(input));\n};\n\n/**\n * Returns true if **any** of the given glob `patterns` match the specified `string`.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.isMatch(string, patterns[, options]);\n *\n * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true\n * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false\n * ```\n * @param {String|Array} str The string to test.\n * @param {String|Array} patterns One or more glob patterns to use for matching.\n * @param {Object} [options] See available [options](#options).\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\npicomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);\n\n/**\n * Parse a glob pattern to create the source string for a regular\n * expression.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const result = picomatch.parse(pattern[, options]);\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {Object} Returns an object with useful properties and output to be used as a regex source string.\n * @api public\n */\n\npicomatch.parse = (pattern, options) => {\n if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));\n return parse(pattern, { ...options, fastpaths: false });\n};\n\n/**\n * Scan a glob pattern to separate the pattern into segments.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.scan(input[, options]);\n *\n * const result = picomatch.scan('!./foo/*.js');\n * console.log(result);\n * { prefix: '!./',\n * input: '!./foo/*.js',\n * start: 3,\n * base: 'foo',\n * glob: '*.js',\n * isBrace: false,\n * isBracket: false,\n * isGlob: true,\n * isExtglob: false,\n * isGlobstar: false,\n * negated: true }\n * ```\n * @param {String} `input` Glob pattern to scan.\n * @param {Object} `options`\n * @return {Object} Returns an object with\n * @api public\n */\n\npicomatch.scan = (input, options) => scan(input, options);\n\n/**\n * Compile a regular expression from the `state` object returned by the\n * [parse()](#parse) method.\n *\n * @param {Object} `state`\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.\n * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.\n * @return {RegExp}\n * @api public\n */\n\npicomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {\n if (returnOutput === true) {\n return state.output;\n }\n\n const opts = options || {};\n const prepend = opts.contains ? '' : '^';\n const append = opts.contains ? '' : '$';\n\n let source = `${prepend}(?:${state.output})${append}`;\n if (state && state.negated === true) {\n source = `^(?!${source}).*$`;\n }\n\n const regex = picomatch.toRegex(source, options);\n if (returnState === true) {\n regex.state = state;\n }\n\n return regex;\n};\n\n/**\n * Create a regular expression from a parsed glob pattern.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const state = picomatch.parse('*.js');\n * // picomatch.compileRe(state[, options]);\n *\n * console.log(picomatch.compileRe(state));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `state` The object returned from the `.parse` method.\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.\n * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.\n * @return {RegExp} Returns a regex created from the given pattern.\n * @api public\n */\n\npicomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {\n if (!input || typeof input !== 'string') {\n throw new TypeError('Expected a non-empty string');\n }\n\n let parsed = { negated: false, fastpaths: true };\n\n if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {\n parsed.output = parse.fastpaths(input, options);\n }\n\n if (!parsed.output) {\n parsed = parse(input, options);\n }\n\n return picomatch.compileRe(parsed, options, returnOutput, returnState);\n};\n\n/**\n * Create a regular expression from the given regex source string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.toRegex(source[, options]);\n *\n * const { output } = picomatch.parse('*.js');\n * console.log(picomatch.toRegex(output));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `source` Regular expression source string.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\npicomatch.toRegex = (source, options) => {\n try {\n const opts = options || {};\n return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));\n } catch (err) {\n if (options && options.debug === true) throw err;\n return /$^/;\n }\n};\n\n/**\n * Picomatch constants.\n * @return {Object}\n */\n\npicomatch.constants = constants;\n\n/**\n * Expose \"picomatch\"\n */\n\nmodule.exports = picomatch;\n","'use strict';\n\nconst pico = require('./lib/picomatch');\nconst utils = require('./lib/utils');\n\nfunction picomatch(glob, options, returnState = false) {\n // default to os.platform()\n if (options && (options.windows === null || options.windows === undefined)) {\n // don't mutate the original options object\n options = { ...options, windows: utils.isWindows() };\n }\n\n return pico(glob, options, returnState);\n}\n\nObject.assign(picomatch, pico);\nmodule.exports = picomatch;\n","/**\n * Glob pattern matching using fast-glob\n */\n\nimport fg from \"fast-glob\";\n\n/**\n * Scan files matching glob patterns from the given directory.\n * Supports negation patterns (e.g., \"!**\\/excluded.ts\").\n *\n * @param patterns - Glob pattern(s). Can be a single pattern or array of patterns.\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns Array of matched file paths (relative to cwd)\n */\nexport const scanGlob = (patterns: string | readonly string[], cwd: string = process.cwd()): readonly string[] => {\n const patternArray = Array.isArray(patterns) ? patterns : [patterns];\n return fg.sync(patternArray as string[], { cwd, dot: true, onlyFiles: true });\n};\n","import { existsSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { err, ok } from \"neverthrow\";\n\nimport picomatch from \"picomatch\";\n\nimport type { BuilderError } from \"../types\";\nimport { scanGlob } from \"../utils/glob\";\n\n/**\n * Resolve entry file paths from glob patterns or direct paths.\n * Used by the discovery system to find entry points for module traversal.\n * All paths are normalized to POSIX format for consistent cache key matching.\n * Uses Node.js normalize() + backslash replacement to match normalizePath from @soda-gql/common.\n *\n * @param entries - Include patterns (glob or direct paths). Supports negation patterns (e.g., \"!./path/to/exclude.ts\")\n * @param exclude - Exclude patterns from config.exclude. Converted to negation globs for filtering.\n */\nexport const resolveEntryPaths = (entries: readonly string[], exclude: readonly string[] = []) => {\n // Separate direct file paths from glob patterns\n const directPaths: string[] = [];\n const globPatterns: string[] = [];\n\n for (const entry of entries) {\n // Negation patterns are always glob patterns\n if (entry.startsWith(\"!\")) {\n globPatterns.push(entry);\n continue;\n }\n\n const absolute = resolve(entry);\n if (existsSync(absolute)) {\n // Normalize to POSIX format to match discovery cache keys\n directPaths.push(normalize(absolute).replace(/\\\\/g, \"/\"));\n } else {\n // Treat as glob pattern\n globPatterns.push(entry);\n }\n }\n\n // Filter direct paths against exclude patterns (both literal and glob)\n if (exclude.length > 0 && directPaths.length > 0) {\n const excludePatterns = exclude.map((p) => {\n const raw = p.startsWith(\"!\") ? p.slice(1) : p;\n return normalize(resolve(raw)).replace(/\\\\/g, \"/\");\n });\n const isExcluded = picomatch(excludePatterns);\n const filtered = directPaths.filter((p) => !isExcluded(p));\n directPaths.length = 0;\n directPaths.push(...filtered);\n }\n\n // Append exclude patterns as negation globs\n for (const pattern of exclude) {\n globPatterns.push(pattern.startsWith(\"!\") ? pattern : `!${pattern}`);\n }\n\n // Scan all glob patterns together (important for negation patterns to work)\n const globMatches =\n globPatterns.length > 0\n ? scanGlob(globPatterns, process.cwd()).map((match) => {\n // Normalize to POSIX format to match discovery cache keys\n return normalize(resolve(match)).replace(/\\\\/g, \"/\");\n })\n : [];\n\n const resolvedPaths = [...directPaths, ...globMatches];\n\n if (resolvedPaths.length === 0) {\n return err<readonly string[], BuilderError>({\n code: \"ENTRY_NOT_FOUND\",\n message: `No entry files matched ${entries.join(\", \")}`,\n entry: entries.join(\", \"),\n });\n }\n\n return ok<readonly string[], BuilderError>(resolvedPaths);\n};\n","import { statSync } from \"node:fs\";\nimport { normalizePath } from \"@soda-gql/common\";\nimport { ok, type Result } from \"neverthrow\";\n\n/**\n * File metadata tracked for change detection.\n */\nexport type FileMetadata = {\n /** Modification time in milliseconds */\n mtimeMs: number;\n /** File size in bytes */\n size: number;\n};\n\n/**\n * Result of scanning current file system state.\n */\nexport type FileScan = {\n /** Map of normalized file paths to current metadata */\n files: Map<string, FileMetadata>;\n};\n\n/**\n * Detected file changes between two states.\n */\nexport type FileDiff = {\n /** Files present in current but not in previous */\n added: Set<string>;\n /** Files present in both but with changed metadata */\n updated: Set<string>;\n /** Files present in previous but not in current */\n removed: Set<string>;\n};\n\n/**\n * Errors that can occur during file tracking operations.\n */\nexport type TrackerError = { type: \"scan-failed\"; path: string; message: string };\n\n/**\n * File tracker interface for detecting file changes across builds.\n */\nexport interface FileTracker {\n /**\n * Scan current file system state for the given paths.\n * Gracefully skips files that don't exist or cannot be read.\n */\n scan(extraPaths: readonly string[]): Result<FileScan, TrackerError>;\n\n /**\n * Detect changes between previous and current file states.\n */\n detectChanges(): FileDiff;\n\n /**\n * Update the in-memory tracker state.\n * State persists only for the lifetime of this process.\n */\n update(scan: FileScan): void;\n}\n\n/**\n * Create a file tracker that maintains in-memory state for change detection.\n *\n * The tracker keeps file metadata (mtime, size) in memory during the process lifetime\n * and detects which files have been added, updated, or removed. State is scoped to\n * the process and does not persist across restarts.\n */\nexport const createFileTracker = (): FileTracker => {\n // In-memory state that persists for the lifetime of this tracker instance\n let currentScan: FileScan = {\n files: new Map(),\n };\n let nextScan: FileScan | null = null;\n\n const scan = (extraPaths: readonly string[]): Result<FileScan, TrackerError> => {\n const allPathsToScan = new Set([...extraPaths, ...currentScan.files.keys()]);\n const files = new Map<string, FileMetadata>();\n\n for (const path of allPathsToScan) {\n try {\n const normalized = normalizePath(path);\n const stats = statSync(normalized);\n\n files.set(normalized, {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {}\n }\n\n nextScan = { files };\n return ok(nextScan);\n };\n\n const detectChanges = (): FileDiff => {\n const previous = currentScan;\n const current = nextScan ?? currentScan;\n const added = new Set<string>();\n const updated = new Set<string>();\n const removed = new Set<string>();\n\n // Check for added and updated files\n for (const [path, currentMetadata] of current.files) {\n const previousMetadata = previous.files.get(path);\n\n if (!previousMetadata) {\n added.add(path);\n } else if (previousMetadata.mtimeMs !== currentMetadata.mtimeMs || previousMetadata.size !== currentMetadata.size) {\n updated.add(path);\n }\n }\n\n // Check for removed files\n for (const path of previous.files.keys()) {\n if (!current.files.has(path)) {\n removed.add(path);\n }\n }\n\n return { added, updated, removed };\n };\n\n const update = (scan: FileScan): void => {\n // Update in-memory state - promote nextScan to currentScan\n currentScan = scan;\n nextScan = null;\n };\n\n return {\n scan,\n detectChanges,\n update,\n };\n};\n\n/**\n * Check if a file diff is empty (no changes detected).\n */\nexport const isEmptyDiff = (diff: FileDiff): boolean => {\n return diff.added.size === 0 && diff.updated.size === 0 && diff.removed.size === 0;\n};\n","import { isRelativeSpecifier, resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { ModuleAnalysis } from \"../ast\";\nimport type { GraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\n\nexport type DependencyGraphError = {\n readonly code: \"MISSING_IMPORT\";\n readonly chain: readonly [importingFile: string, importSpecifier: string];\n};\n\nexport const validateModuleDependencies = ({\n analyses,\n graphqlSystemHelper,\n}: {\n analyses: Map<string, ModuleAnalysis>;\n graphqlSystemHelper: GraphqlSystemIdentifyHelper;\n}): Result<null, DependencyGraphError> => {\n for (const analysis of analyses.values()) {\n for (const { source, isTypeOnly } of analysis.imports) {\n if (isTypeOnly) {\n continue;\n }\n\n // Only check relative imports (project modules)\n if (isRelativeSpecifier(source)) {\n // Skip graphql-system imports - they are not part of the analyzed modules\n if (graphqlSystemHelper.isGraphqlSystemImportSpecifier({ filePath: analysis.filePath, specifier: source })) {\n continue;\n }\n\n const resolvedModule = resolveRelativeImportWithReferences({\n filePath: analysis.filePath,\n specifier: source,\n references: analyses,\n });\n if (!resolvedModule) {\n // Import points to a module that doesn't exist in the analysis\n return err({\n code: \"MISSING_IMPORT\" as const,\n chain: [analysis.filePath, source] as const,\n });\n }\n }\n }\n }\n\n return ok(null);\n};\n","import { resolveRelativeImportWithReferences } from \"@soda-gql/common\";\nimport type { DiscoverySnapshot } from \"../discovery\";\n\n/**\n * Extract module-level adjacency from dependency graph.\n * Returns Map of file path -> set of files that import it.\n * All paths are normalized to POSIX format for consistent cache key matching.\n */\nexport const extractModuleAdjacency = ({\n snapshots,\n}: {\n snapshots: Map<string, DiscoverySnapshot>;\n}): Map<string, Set<string>> => {\n const importsByModule = new Map<string, Set<string>>();\n\n for (const snapshot of snapshots.values()) {\n const { normalizedFilePath, dependencies, analysis } = snapshot;\n const imports = new Set<string>();\n\n // Extract module paths from canonical IDs in dependencies\n for (const { resolvedPath } of dependencies) {\n if (resolvedPath && resolvedPath !== normalizedFilePath && snapshots.has(resolvedPath)) {\n imports.add(resolvedPath);\n }\n }\n\n // Phase 3: Handle runtime imports for modules with no tracked dependencies\n if (dependencies.length === 0 && analysis.imports.length > 0) {\n for (const imp of analysis.imports) {\n if (imp.isTypeOnly) {\n continue;\n }\n\n const resolved = resolveRelativeImportWithReferences({\n filePath: normalizedFilePath,\n specifier: imp.source,\n references: snapshots,\n });\n if (resolved) {\n imports.add(resolved);\n }\n }\n }\n\n if (imports.size > 0) {\n importsByModule.set(normalizedFilePath, imports);\n }\n }\n\n // Phase 4: Invert to adjacency map (imported -> [importers])\n const adjacency = new Map<string, Set<string>>();\n\n for (const [importer, imports] of importsByModule) {\n for (const imported of imports) {\n if (!adjacency.has(imported)) {\n adjacency.set(imported, new Set());\n }\n adjacency.get(imported)?.add(importer);\n }\n }\n\n // Include all modules, even isolated ones with no importers\n for (const modulePath of snapshots.keys()) {\n if (!adjacency.has(modulePath)) {\n adjacency.set(modulePath, new Set());\n }\n }\n\n return adjacency;\n};\n\n/**\n * Collect all modules affected by changes, including transitive dependents.\n * Uses BFS to traverse module adjacency graph.\n * All paths are already normalized from extractModuleAdjacency.\n */\nexport const collectAffectedFiles = (input: {\n changedFiles: Set<string>;\n removedFiles: Set<string>;\n previousModuleAdjacency: Map<string, Set<string>>;\n}): Set<string> => {\n const { changedFiles, removedFiles, previousModuleAdjacency } = input;\n const affected = new Set<string>([...changedFiles, ...removedFiles]);\n const queue = [...changedFiles];\n const visited = new Set<string>(changedFiles);\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break;\n\n const dependents = previousModuleAdjacency.get(current);\n\n if (dependents) {\n for (const dependent of dependents) {\n if (!visited.has(dependent)) {\n visited.add(dependent);\n affected.add(dependent);\n queue.push(dependent);\n }\n }\n }\n }\n\n return affected;\n};\n","import { join, resolve } from \"node:path\";\nimport {\n type AliasResolver,\n cachedFn,\n createAliasResolver,\n createAsyncScheduler,\n createSyncScheduler,\n type EffectGenerator,\n type SchedulerError,\n} from \"@soda-gql/common\";\nimport type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport { type BuilderArtifact, buildArtifact } from \"../artifact\";\nimport { createAstAnalyzer, type ModuleAnalysis } from \"../ast\";\nimport { type CacheFactory, createMemoryCache } from \"../cache/memory-cache\";\nimport {\n createDiscoveryCache,\n type DiscoveryCache,\n type DiscoverySnapshot,\n discoverModulesGen,\n type ModuleLoadStats,\n resolveEntryPaths,\n} from \"../discovery\";\nimport { builderErrors, isBuilderError } from \"../errors\";\nimport {\n evaluateIntermediateModulesGen,\n generateIntermediateModules,\n type IntermediateArtifactElement,\n type IntermediateModule,\n} from \"../intermediate-module\";\nimport { createGraphqlSystemIdentifyHelper } from \"../internal/graphql-system\";\nimport { createFileTracker, type FileDiff, type FileScan, isEmptyDiff } from \"../tracker\";\nimport type { BuilderError } from \"../types\";\nimport { validateModuleDependencies } from \"./dependency-validation\";\nimport { collectAffectedFiles, extractModuleAdjacency } from \"./module-adjacency\";\n\n/**\n * Session state maintained across incremental builds.\n */\ntype SessionState = {\n /** Generation number */\n gen: number;\n /** Discovery snapshots keyed by normalized file path */\n snapshots: Map<string, DiscoverySnapshot>;\n /** Module-level adjacency: file -> files that import it */\n moduleAdjacency: Map<string, Set<string>>;\n /** Written intermediate modules: filePath -> intermediate module */\n intermediateModules: Map<string, IntermediateModule>;\n /** Last successful artifact */\n lastArtifact: BuilderArtifact | null;\n /** Last successful intermediate elements (for prebuilt type generation) */\n lastIntermediateElements: Record<string, IntermediateArtifactElement> | null;\n};\n\n/**\n * Input for the unified build generator.\n */\ntype BuildGenInput = {\n readonly entryPaths: readonly string[];\n readonly astAnalyzer: ReturnType<typeof createAstAnalyzer>;\n readonly aliasResolver?: AliasResolver;\n readonly discoveryCache: DiscoveryCache;\n readonly changedFiles: Set<string>;\n readonly removedFiles: Set<string>;\n readonly previousModuleAdjacency: Map<string, Set<string>>;\n readonly previousIntermediateModules: ReadonlyMap<string, IntermediateModule>;\n readonly graphqlSystemPath: string;\n readonly graphqlHelper: ReturnType<typeof createGraphqlSystemIdentifyHelper>;\n /** Optional phase callbacks for profiling */\n readonly onPhase?: BuildPhaseCallbacks;\n};\n\n/**\n * Result from the unified build generator.\n */\ntype BuildGenResult = {\n readonly snapshots: Map<string, DiscoverySnapshot>;\n readonly analyses: Map<string, ModuleAnalysis>;\n readonly currentModuleAdjacency: Map<string, Set<string>>;\n readonly intermediateModules: Map<string, IntermediateModule>;\n readonly elements: Record<string, IntermediateArtifactElement>;\n readonly stats: ModuleLoadStats;\n};\n\n/**\n * Optional callbacks for profiling build phases.\n * Called at phase boundaries when provided.\n */\nexport interface BuildPhaseCallbacks {\n /** Called after discovery phase completes */\n afterDiscovery?: () => void;\n /** Called after intermediate module generation completes */\n afterIntermediateGen?: () => void;\n /** Called after evaluation phase completes */\n afterEvaluation?: () => void;\n}\n\n/**\n * Options for build methods.\n */\nexport interface BuildOptions {\n /** Force full rebuild ignoring cache */\n force?: boolean;\n /** Optional callbacks for profiling (called at phase boundaries) */\n onPhase?: BuildPhaseCallbacks;\n}\n\n/**\n * Builder session interface for incremental builds.\n */\nexport interface BuilderSession {\n /**\n * Perform build fully or incrementally (synchronous).\n * The session automatically detects file changes using the file tracker.\n * Throws if any element requires async operations (e.g., async metadata factory).\n */\n build(options?: BuildOptions): Result<BuilderArtifact, BuilderError>;\n /**\n * Perform build fully or incrementally (asynchronous).\n * The session automatically detects file changes using the file tracker.\n * Supports async metadata factories and parallel element evaluation.\n */\n buildAsync(options?: BuildOptions): Promise<Result<BuilderArtifact, BuilderError>>;\n /**\n * Get the current generation number.\n */\n getGeneration(): number;\n /**\n * Get the current artifact.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n /**\n * Get the intermediate elements from the most recent build.\n * Returns null if no build has been performed yet.\n * Used by typegen to extract field selections for prebuilt type generation.\n */\n getIntermediateElements(): Record<string, IntermediateArtifactElement> | null;\n /**\n * Dispose the session and save cache to disk.\n */\n dispose(): void;\n}\n\n/**\n * Singleton state for beforeExit handler registration.\n * Ensures only one handler is registered regardless of how many sessions are created.\n */\nconst exitHandlerState = {\n registered: false,\n factories: new Set<CacheFactory>(),\n};\n\n/**\n * Register a cache factory for save on process exit.\n * Uses singleton pattern to prevent multiple handler registrations.\n */\nconst registerExitHandler = (cacheFactory: CacheFactory): void => {\n exitHandlerState.factories.add(cacheFactory);\n\n if (!exitHandlerState.registered) {\n exitHandlerState.registered = true;\n process.on(\"beforeExit\", () => {\n // Save all registered cache factories sequentially\n for (const factory of exitHandlerState.factories) {\n factory.save();\n }\n });\n }\n};\n\n/**\n * Unregister a cache factory from the exit handler.\n */\nconst unregisterExitHandler = (cacheFactory: CacheFactory): void => {\n exitHandlerState.factories.delete(cacheFactory);\n};\n\n/**\n * Reset exit handler state for testing.\n * @internal\n */\nexport const __resetExitHandlerForTests = (): void => {\n exitHandlerState.registered = false;\n exitHandlerState.factories.clear();\n};\n\n/**\n * Create a new builder session.\n *\n * The session maintains in-memory state across builds to enable incremental processing.\n */\nexport const createBuilderSession = (options: {\n readonly evaluatorId?: string;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n readonly config: ResolvedSodaGqlConfig;\n}): BuilderSession => {\n const config = options.config;\n const evaluatorId = options.evaluatorId ?? \"default\";\n const entrypoints: ReadonlySet<string> = new Set(options.entrypointsOverride ?? config.include);\n\n // Session state stored in closure\n const state: SessionState = {\n gen: 0,\n snapshots: new Map(),\n moduleAdjacency: new Map(),\n intermediateModules: new Map(),\n lastArtifact: null,\n lastIntermediateElements: null,\n };\n\n // Reusable infrastructure\n const cacheFactory = createMemoryCache({\n prefix: [\"builder\"],\n persistence: {\n enabled: true,\n filePath: join(process.cwd(), \"node_modules\", \".cache\", \"soda-gql\", \"builder\", \"cache.json\"),\n },\n });\n\n // Register for auto-save on process exit using singleton handler\n registerExitHandler(cacheFactory);\n\n const graphqlHelper = createGraphqlSystemIdentifyHelper(config);\n const ensureAstAnalyzer = cachedFn(() =>\n createAstAnalyzer({\n analyzer: config.analyzer,\n graphqlHelper,\n baseDir: config.baseDir,\n }),\n );\n const ensureDiscoveryCache = cachedFn(() =>\n createDiscoveryCache({\n factory: cacheFactory,\n analyzer: config.analyzer,\n evaluatorId,\n }),\n );\n const ensureFileTracker = cachedFn(() => createFileTracker());\n\n /**\n * Prepare build input. Shared between sync and async builds.\n * Returns either a skip result or the input for buildGen.\n */\n const prepareBuildInput = (\n force: boolean,\n ): Result<\n { type: \"skip\"; artifact: BuilderArtifact } | { type: \"build\"; input: BuildGenInput; currentScan: FileScan },\n BuilderError\n > => {\n // 1. Resolve entry paths (apply config.exclude as negation globs)\n const entryPathsResult = resolveEntryPaths(Array.from(entrypoints), config.exclude);\n if (entryPathsResult.isErr()) {\n return err(entryPathsResult.error);\n }\n const entryPaths = entryPathsResult.value;\n\n // 2. Load tracker and detect changes\n const tracker = ensureFileTracker();\n const scanResult = tracker.scan(entryPaths);\n if (scanResult.isErr()) {\n const trackerError = scanResult.error;\n return err(\n builderErrors.discoveryIOError(\n trackerError.type === \"scan-failed\" ? trackerError.path : \"unknown\",\n `Failed to scan files: ${trackerError.message}`,\n ),\n );\n }\n\n // 3. Scan current files (entry paths + previously tracked files)\n const currentScan = scanResult.value;\n const diff = tracker.detectChanges();\n\n // 4. Prepare for build\n const prepareResult = prepare({\n diff,\n entryPaths,\n lastArtifact: state.lastArtifact,\n force,\n });\n if (prepareResult.isErr()) {\n return err(prepareResult.error);\n }\n\n if (prepareResult.value.type === \"should-skip\") {\n return ok({ type: \"skip\", artifact: prepareResult.value.data.artifact });\n }\n\n const { changedFiles, removedFiles } = prepareResult.value.data;\n\n return ok({\n type: \"build\",\n input: {\n entryPaths,\n astAnalyzer: ensureAstAnalyzer(),\n aliasResolver: config.tsconfigPaths ? createAliasResolver(config.tsconfigPaths) : undefined,\n discoveryCache: ensureDiscoveryCache(),\n changedFiles,\n removedFiles,\n previousModuleAdjacency: state.moduleAdjacency,\n previousIntermediateModules: state.intermediateModules,\n graphqlSystemPath: resolve(config.outdir, \"index.ts\"),\n graphqlHelper,\n },\n currentScan,\n });\n };\n\n /**\n * Finalize build and update session state.\n */\n const finalizeBuild = (genResult: BuildGenResult, currentScan: FileScan): Result<BuilderArtifact, BuilderError> => {\n const { snapshots, analyses, currentModuleAdjacency, intermediateModules, elements, stats } = genResult;\n\n // Build artifact from all intermediate modules\n const artifactResult = buildArtifact({\n analyses,\n elements,\n stats,\n });\n\n if (artifactResult.isErr()) {\n return err(artifactResult.error);\n }\n\n // Update session state\n state.gen++;\n state.snapshots = snapshots;\n state.moduleAdjacency = currentModuleAdjacency;\n state.lastArtifact = artifactResult.value;\n state.intermediateModules = intermediateModules;\n state.lastIntermediateElements = elements;\n\n // Persist tracker state (soft failure - don't block on cache write)\n ensureFileTracker().update(currentScan);\n\n return ok(artifactResult.value);\n };\n\n /**\n * Synchronous build using SyncScheduler.\n * Throws if any element requires async operations.\n */\n const build = (options?: BuildOptions): Result<BuilderArtifact, BuilderError> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createSyncScheduler();\n\n try {\n const result = scheduler.run(() => buildGen({ ...input, onPhase: options?.onPhase }));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (isBuilderError(error)) {\n return err(error);\n }\n throw error;\n }\n };\n\n /**\n * Asynchronous build using AsyncScheduler.\n * Supports async metadata factories and parallel element evaluation.\n */\n const buildAsync = async (options?: BuildOptions): Promise<Result<BuilderArtifact, BuilderError>> => {\n const prepResult = prepareBuildInput(options?.force ?? false);\n if (prepResult.isErr()) {\n return err(prepResult.error);\n }\n\n if (prepResult.value.type === \"skip\") {\n return ok(prepResult.value.artifact);\n }\n\n const { input, currentScan } = prepResult.value;\n const scheduler = createAsyncScheduler();\n\n try {\n const result = await scheduler.run(() => buildGen({ ...input, onPhase: options?.onPhase }));\n\n if (result.isErr()) {\n return err(convertSchedulerError(result.error));\n }\n\n return finalizeBuild(result.value, currentScan);\n } catch (error) {\n // Handle thrown BuilderError from buildGen\n if (isBuilderError(error)) {\n return err(error);\n }\n throw error;\n }\n };\n\n return {\n build,\n buildAsync,\n getGeneration: () => state.gen,\n getCurrentArtifact: () => state.lastArtifact,\n getIntermediateElements: () => state.lastIntermediateElements,\n dispose: () => {\n cacheFactory.save();\n // Unregister from exit handler to prevent duplicate saves\n unregisterExitHandler(cacheFactory);\n },\n };\n};\n\nconst prepare = (input: {\n diff: FileDiff;\n entryPaths: readonly string[];\n lastArtifact: BuilderArtifact | null;\n force: boolean;\n}) => {\n const { diff, lastArtifact, force } = input;\n\n // Convert diff to sets for discovery\n const changedFiles = new Set<string>([...diff.added, ...diff.updated]);\n const removedFiles = diff.removed;\n\n // Skip build only if:\n // 1. Not forced\n // 2. No changes detected\n // 3. Previous artifact exists\n if (!force && isEmptyDiff(diff) && lastArtifact) {\n return ok({ type: \"should-skip\" as const, data: { artifact: lastArtifact } });\n }\n\n return ok({ type: \"should-build\" as const, data: { changedFiles, removedFiles } });\n};\n\n/**\n * Unified build generator that yields effects for file I/O and element evaluation.\n * This enables single scheduler control at the root level for both sync and async execution.\n */\nfunction* buildGen(input: BuildGenInput): EffectGenerator<BuildGenResult> {\n const {\n entryPaths,\n astAnalyzer,\n aliasResolver,\n discoveryCache,\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n previousIntermediateModules,\n graphqlSystemPath,\n graphqlHelper,\n onPhase,\n } = input;\n\n // Phase 1: Collect affected files\n const affectedFiles = collectAffectedFiles({\n changedFiles,\n removedFiles,\n previousModuleAdjacency,\n });\n\n // Phase 2: Discovery (yields file I/O effects)\n const discoveryResult = yield* discoverModulesGen({\n entryPaths,\n astAnalyzer,\n aliasResolver,\n incremental: {\n cache: discoveryCache,\n changedFiles,\n removedFiles,\n affectedFiles,\n },\n });\n\n // Notify phase callback after discovery\n onPhase?.afterDiscovery?.();\n\n const { cacheHits, cacheMisses, cacheSkips } = discoveryResult;\n\n const snapshots = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot]));\n const analyses = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot.analysis]));\n\n // Phase 3: Validate module dependencies (pure computation)\n const dependenciesValidationResult = validateModuleDependencies({ analyses, graphqlSystemHelper: graphqlHelper });\n if (dependenciesValidationResult.isErr()) {\n const error = dependenciesValidationResult.error;\n throw builderErrors.graphMissingImport(error.chain[0], error.chain[1]);\n }\n\n const currentModuleAdjacency = extractModuleAdjacency({ snapshots });\n\n const stats: ModuleLoadStats = {\n hits: cacheHits,\n misses: cacheMisses,\n skips: cacheSkips,\n };\n\n // Phase 4: Generate intermediate modules (pure computation)\n const intermediateModules = new Map(previousIntermediateModules);\n\n // Build target set: include affected files + any newly discovered files that haven't been built yet\n const targetFiles = new Set(affectedFiles);\n for (const filePath of analyses.keys()) {\n if (!previousIntermediateModules.has(filePath)) {\n targetFiles.add(filePath);\n }\n }\n // If no targets identified (e.g., first build with no changes), build everything\n if (targetFiles.size === 0) {\n for (const filePath of analyses.keys()) {\n targetFiles.add(filePath);\n }\n }\n\n // Remove deleted intermediate modules from next map immediately\n for (const targetFilePath of targetFiles) {\n intermediateModules.delete(targetFilePath);\n }\n\n // Build and write affected intermediate modules\n for (const intermediateModule of generateIntermediateModules({ analyses, targetFiles, graphqlSystemPath })) {\n intermediateModules.set(intermediateModule.filePath, intermediateModule);\n }\n\n // Notify phase callback after intermediate module generation\n onPhase?.afterIntermediateGen?.();\n\n // Phase 5: Evaluate intermediate modules (yields element evaluation effects)\n const elements = yield* evaluateIntermediateModulesGen({ intermediateModules, graphqlSystemPath, analyses });\n\n // Notify phase callback after evaluation\n onPhase?.afterEvaluation?.();\n\n return {\n snapshots,\n analyses,\n currentModuleAdjacency,\n intermediateModules,\n elements,\n stats,\n };\n}\n\n/**\n * Convert scheduler error to builder error.\n * If the cause is already a BuilderError, return it directly to preserve error codes.\n */\nconst convertSchedulerError = (error: SchedulerError): BuilderError => {\n // If the cause is a BuilderError, return it directly\n if (isBuilderError(error.cause)) {\n return error.cause;\n }\n return builderErrors.internalInvariant(error.message, \"scheduler\", error.cause);\n};\n","import type { ResolvedSodaGqlConfig } from \"@soda-gql/config\";\nimport type { Result } from \"neverthrow\";\nimport type { BuilderArtifact } from \"./artifact/types\";\nimport type { IntermediateArtifactElement } from \"./intermediate-module\";\nimport { createBuilderSession } from \"./session\";\nimport type { BuilderError } from \"./types\";\n\n/**\n * Configuration for BuilderService.\n * Mirrors BuilderInput shape.\n */\nexport type BuilderServiceConfig = {\n readonly config: ResolvedSodaGqlConfig;\n readonly entrypointsOverride?: readonly string[] | ReadonlySet<string>;\n};\n\n/**\n * Builder service interface providing artifact generation.\n */\nexport interface BuilderService {\n /**\n * Generate artifacts from configured entry points (synchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Throws if any element requires async operations (e.g., async metadata factory).\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Result containing BuilderArtifact on success or BuilderError on failure.\n */\n build(options?: { force?: boolean }): Result<BuilderArtifact, BuilderError>;\n\n /**\n * Generate artifacts from configured entry points (asynchronous).\n *\n * The service automatically detects file changes using an internal file tracker.\n * On first call, performs full build. Subsequent calls perform incremental builds\n * based on detected file changes (added/updated/removed).\n *\n * Supports async metadata factories and parallel element evaluation.\n *\n * @param options - Optional build options\n * @param options.force - If true, bypass change detection and force full rebuild\n * @returns Promise of Result containing BuilderArtifact on success or BuilderError on failure.\n */\n buildAsync(options?: { force?: boolean }): Promise<Result<BuilderArtifact, BuilderError>>;\n\n /**\n * Get the current generation number of the artifact.\n * Increments on each successful build.\n * Returns 0 if no artifact has been built yet.\n */\n getGeneration(): number;\n\n /**\n * Get the most recent artifact without triggering a new build.\n * Returns null if no artifact has been built yet.\n */\n getCurrentArtifact(): BuilderArtifact | null;\n\n /**\n * Get the intermediate elements from the most recent build.\n * Returns null if no build has been performed yet.\n * Used by typegen to extract field selections for prebuilt type generation.\n */\n getIntermediateElements(): Record<string, IntermediateArtifactElement> | null;\n\n /**\n * Dispose the service and save cache to disk.\n * Should be called when the service is no longer needed.\n */\n dispose(): void;\n}\n\n/**\n * Create a builder service instance with session support.\n *\n * The service maintains a long-lived session for incremental builds.\n * File changes are automatically detected using an internal file tracker.\n * First build() call initializes the session, subsequent calls perform\n * incremental builds based on detected file changes.\n *\n * Note: Empty entry arrays will produce ENTRY_NOT_FOUND errors at build time.\n *\n * @param config - Builder configuration including entry patterns, analyzer, mode, and optional debugDir\n * @returns BuilderService instance\n */\nexport const createBuilderService = ({ config, entrypointsOverride }: BuilderServiceConfig): BuilderService => {\n const session = createBuilderSession({ config, entrypointsOverride });\n\n return {\n build: (options) => session.build(options),\n buildAsync: (options) => session.buildAsync(options),\n getGeneration: () => session.getGeneration(),\n getCurrentArtifact: () => session.getCurrentArtifact(),\n getIntermediateElements: () => session.getIntermediateElements(),\n dispose: () => session.dispose(),\n };\n};\n"],"x_google_ignoreList":[28,29,30,31,32,33],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,uCAAuC,EAAE,OAAO;CACpD,YAAY,EAAE,QAAQ;CACtB,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,iCAAiC,EAAE,OAAO;CAC9C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,YAAY;CAC5B,UAAU;CACV,UAAU,EAAE,OAAO;EACjB,eAAe,EAAE,KAAK;GAAC;GAAS;GAAY;GAAe,CAAC;EAC5D,eAAe,EAAE,QAAQ;EACzB,aAAa,EAAE,QAAQ;EACvB,UAAU,EAAE,SAAS;EACrB,eAAe,EAAE,MAAM,EAAE,QAAQ,CAAC;EAClC,UAAU,EAAE,SAAS,CAAC,UAAU;EACjC,CAAC;CACH,CAAC;AAMF,MAAM,gCAAgC,EAAE,OAAO;CAC7C,IAAI,EAAE,QAAqB;CAC3B,MAAM,EAAE,QAAQ,WAAW;CAC3B,UAAU;CACV,UAAU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