@soda-gql/builder 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3894 +1,182 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
1
+ const require_service = require('./service-nHDX5qIj.cjs');
28
2
  let node_fs = require("node:fs");
29
- let node_fs_promises = require("node:fs/promises");
30
3
  let neverthrow = require("neverthrow");
31
- let zod = require("zod");
32
- let node_crypto = require("node:crypto");
33
4
  let node_path = require("node:path");
34
- let node_vm = require("node:vm");
35
- let __soda_gql_common = require("@soda-gql/common");
36
- let __swc_core = require("@swc/core");
37
5
  let __soda_gql_core = require("@soda-gql/core");
38
- __soda_gql_core = __toESM(__soda_gql_core);
39
- let __soda_gql_core_adapter = require("@soda-gql/core/adapter");
40
- __soda_gql_core_adapter = __toESM(__soda_gql_core_adapter);
41
- let __soda_gql_core_runtime = require("@soda-gql/core/runtime");
42
- __soda_gql_core_runtime = __toESM(__soda_gql_core_runtime);
43
- let __soda_gql_runtime = require("@soda-gql/runtime");
44
- __soda_gql_runtime = __toESM(__soda_gql_runtime);
45
6
  let graphql = require("graphql");
46
- let typescript = require("typescript");
47
- typescript = __toESM(typescript);
48
- let fast_glob = require("fast-glob");
49
- fast_glob = __toESM(fast_glob);
50
-
51
- //#region packages/builder/src/schemas/artifact.ts
52
- const BuilderArtifactElementMetadataSchema = zod.z.object({
53
- sourcePath: zod.z.string(),
54
- contentHash: zod.z.string()
55
- });
56
- const BuilderArtifactOperationSchema = zod.z.object({
57
- id: zod.z.string(),
58
- type: zod.z.literal("operation"),
59
- metadata: BuilderArtifactElementMetadataSchema,
60
- prebuild: zod.z.object({
61
- operationType: zod.z.enum([
62
- "query",
63
- "mutation",
64
- "subscription"
65
- ]),
66
- operationName: zod.z.string(),
67
- schemaLabel: zod.z.string(),
68
- document: zod.z.unknown(),
69
- variableNames: zod.z.array(zod.z.string())
70
- })
71
- });
72
- const BuilderArtifactFragmentSchema = zod.z.object({
73
- id: zod.z.string(),
74
- type: zod.z.literal("fragment"),
75
- metadata: BuilderArtifactElementMetadataSchema,
76
- prebuild: zod.z.object({
77
- typename: zod.z.string(),
78
- key: zod.z.string().optional(),
79
- schemaLabel: zod.z.string()
80
- })
81
- });
82
- const BuilderArtifactElementSchema = zod.z.discriminatedUnion("type", [BuilderArtifactOperationSchema, BuilderArtifactFragmentSchema]);
83
- const BuilderArtifactMetaSchema = zod.z.object({
84
- version: zod.z.string(),
85
- createdAt: zod.z.string()
86
- });
87
- const BuilderArtifactSchema = zod.z.object({
88
- meta: BuilderArtifactMetaSchema.optional(),
89
- elements: zod.z.record(zod.z.string(), BuilderArtifactElementSchema),
90
- report: zod.z.object({
91
- durationMs: zod.z.number(),
92
- warnings: zod.z.array(zod.z.string()),
93
- stats: zod.z.object({
94
- hits: zod.z.number(),
95
- misses: zod.z.number(),
96
- skips: zod.z.number()
97
- })
98
- })
99
- });
100
7
 
101
- //#endregion
102
- //#region packages/builder/src/artifact/loader.ts
8
+ //#region packages/builder/src/prebuilt/extractor.ts
103
9
  /**
104
- * Load a pre-built artifact from a JSON file asynchronously.
10
+ * Extract field selections from evaluated intermediate elements.
105
11
  *
106
- * @param path - Absolute path to the artifact JSON file
107
- * @returns Result with the parsed artifact or an error
12
+ * For fragments, calls `spread()` with empty/default variables to get field selections.
13
+ * For operations, calls `documentSource()` to get field selections.
108
14
  *
109
- * @example
110
- * ```ts
111
- * const result = await loadArtifact("/path/to/artifact.json");
112
- * if (result.isOk()) {
113
- * const artifact = result.value;
114
- * // Use artifact...
115
- * }
116
- * ```
15
+ * @param elements - Record of canonical ID to intermediate artifact element
16
+ * @returns Object containing selections map and any warnings encountered
117
17
  */
118
- const loadArtifact = async (path) => {
119
- if (!(0, node_fs.existsSync)(path)) {
120
- return (0, neverthrow.err)({
121
- code: "ARTIFACT_NOT_FOUND",
122
- message: `Artifact file not found: ${path}`,
123
- filePath: path
124
- });
125
- }
126
- let content;
127
- try {
128
- content = await (0, node_fs_promises.readFile)(path, "utf-8");
129
- } catch (error) {
130
- return (0, neverthrow.err)({
131
- code: "ARTIFACT_NOT_FOUND",
132
- message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,
133
- filePath: path
134
- });
18
+ const extractFieldSelections = (elements) => {
19
+ const selections = new Map();
20
+ const warnings = [];
21
+ for (const [id, element] of Object.entries(elements)) {
22
+ const canonicalId = id;
23
+ try {
24
+ if (element.type === "fragment") {
25
+ const variableDefinitions = element.element.variableDefinitions;
26
+ const varRefs = Object.fromEntries(Object.keys(variableDefinitions).map((k) => [k, (0, __soda_gql_core.createVarRefFromVariable)(k)]));
27
+ const fields = element.element.spread(varRefs);
28
+ selections.set(canonicalId, {
29
+ type: "fragment",
30
+ schemaLabel: element.element.schemaLabel,
31
+ key: element.element.key,
32
+ typename: element.element.typename,
33
+ fields,
34
+ variableDefinitions
35
+ });
36
+ } else if (element.type === "operation") {
37
+ const fields = element.element.documentSource();
38
+ const document = element.element.document;
39
+ const operationDef = document.definitions.find((def) => def.kind === graphql.Kind.OPERATION_DEFINITION);
40
+ const variableDefinitions = operationDef?.variableDefinitions ?? [];
41
+ selections.set(canonicalId, {
42
+ type: "operation",
43
+ schemaLabel: element.element.schemaLabel,
44
+ operationName: element.element.operationName,
45
+ operationType: element.element.operationType,
46
+ fields,
47
+ variableDefinitions
48
+ });
49
+ }
50
+ } catch (error) {
51
+ warnings.push(`[prebuilt] Failed to extract field selections for ${canonicalId}: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
135
53
  }
136
- return parseAndValidateArtifact(content, path);
54
+ return {
55
+ selections,
56
+ warnings
57
+ };
137
58
  };
59
+
60
+ //#endregion
61
+ //#region packages/builder/src/schema-loader.ts
62
+ /**
63
+ * Schema loader for CJS bundle evaluation.
64
+ *
65
+ * Loads AnyGraphqlSchema from the generated CJS bundle by accessing
66
+ * the `$schema` property on each gql composer.
67
+ *
68
+ * @module
69
+ */
138
70
  /**
139
- * Load a pre-built artifact from a JSON file synchronously.
71
+ * Load AnyGraphqlSchema from a generated CJS bundle.
72
+ *
73
+ * The generated CJS bundle exports a `gql` object where each property
74
+ * is a GQL element composer with a `$schema` property containing the
75
+ * schema definition. This function executes the bundle in a VM context
76
+ * and extracts those schemas.
140
77
  *
141
- * @param path - Absolute path to the artifact JSON file
142
- * @returns Result with the parsed artifact or an error
78
+ * @param cjsPath - Absolute path to the CJS bundle file
79
+ * @param schemaNames - Names of schemas to load (e.g., ["default", "admin"])
80
+ * @returns Record mapping schema names to AnyGraphqlSchema objects
143
81
  *
144
82
  * @example
145
- * ```ts
146
- * const result = loadArtifactSync("/path/to/artifact.json");
83
+ * ```typescript
84
+ * const result = loadSchemasFromBundle(
85
+ * "/path/to/generated/index.cjs",
86
+ * ["default"]
87
+ * );
88
+ *
147
89
  * if (result.isOk()) {
148
- * const artifact = result.value;
149
- * // Use artifact...
90
+ * const schemas = result.value;
91
+ * console.log(schemas.default); // AnyGraphqlSchema
150
92
  * }
151
93
  * ```
152
94
  */
153
- const loadArtifactSync = (path) => {
154
- if (!(0, node_fs.existsSync)(path)) {
95
+ const loadSchemasFromBundle = (cjsPath, schemaNames) => {
96
+ const resolvedPath = (0, node_path.resolve)(cjsPath);
97
+ if (!(0, node_fs.existsSync)(resolvedPath)) {
155
98
  return (0, neverthrow.err)({
156
- code: "ARTIFACT_NOT_FOUND",
157
- message: `Artifact file not found: ${path}`,
158
- filePath: path
99
+ code: "CONFIG_NOT_FOUND",
100
+ message: `CJS bundle not found: ${resolvedPath}. Run 'soda-gql codegen' first.`,
101
+ path: resolvedPath
159
102
  });
160
103
  }
161
- let content;
104
+ let bundledCode;
162
105
  try {
163
- content = (0, node_fs.readFileSync)(path, "utf-8");
106
+ bundledCode = (0, node_fs.readFileSync)(resolvedPath, "utf-8");
164
107
  } catch (error) {
165
108
  return (0, neverthrow.err)({
166
- code: "ARTIFACT_NOT_FOUND",
167
- message: `Failed to read artifact file: ${error instanceof Error ? error.message : String(error)}`,
168
- filePath: path
109
+ code: "DISCOVERY_IO_ERROR",
110
+ message: `Failed to read CJS bundle: ${error instanceof Error ? error.message : String(error)}`,
111
+ path: resolvedPath,
112
+ cause: error
169
113
  });
170
114
  }
171
- return parseAndValidateArtifact(content, path);
172
- };
173
- /**
174
- * Parse JSON content and validate against BuilderArtifactSchema.
175
- */
176
- function parseAndValidateArtifact(content, filePath) {
177
- let parsed;
115
+ let finalExports;
178
116
  try {
179
- parsed = JSON.parse(content);
117
+ finalExports = require_service.executeSandbox(bundledCode, resolvedPath);
180
118
  } catch (error) {
181
119
  return (0, neverthrow.err)({
182
- code: "ARTIFACT_PARSE_ERROR",
183
- message: `Invalid JSON in artifact file: ${error instanceof Error ? error.message : String(error)}`,
184
- filePath
120
+ code: "RUNTIME_MODULE_LOAD_FAILED",
121
+ message: `Failed to execute CJS bundle: ${error instanceof Error ? error.message : String(error)}`,
122
+ filePath: resolvedPath,
123
+ astPath: "",
124
+ cause: error
185
125
  });
186
126
  }
187
- const validated = BuilderArtifactSchema.safeParse(parsed);
188
- if (!validated.success) {
127
+ const gql = finalExports.gql;
128
+ if (!gql || typeof gql !== "object") {
189
129
  return (0, neverthrow.err)({
190
- code: "ARTIFACT_VALIDATION_ERROR",
191
- message: `Invalid artifact structure: ${validated.error.message}`,
192
- filePath
130
+ code: "CONFIG_INVALID",
131
+ message: "CJS bundle does not export 'gql' object. Ensure codegen was run successfully.",
132
+ path: resolvedPath
193
133
  });
194
134
  }
195
- return (0, neverthrow.ok)(validated.data);
196
- }
197
-
198
- //#endregion
199
- //#region packages/builder/src/errors.ts
200
- /**
201
- * Error constructor helpers for concise error creation.
202
- */
203
- const builderErrors = {
204
- entryNotFound: (entry, message) => ({
205
- code: "ENTRY_NOT_FOUND",
206
- message: message ?? `Entry not found: ${entry}`,
207
- entry
208
- }),
209
- configNotFound: (path, message) => ({
210
- code: "CONFIG_NOT_FOUND",
211
- message: message ?? `Config file not found: ${path}`,
212
- path
213
- }),
214
- configInvalid: (path, message, cause) => ({
215
- code: "CONFIG_INVALID",
216
- message,
217
- path,
218
- cause
219
- }),
220
- discoveryIOError: (path, message, errno, cause) => ({
221
- code: "DISCOVERY_IO_ERROR",
222
- message,
223
- path,
224
- errno,
225
- cause
226
- }),
227
- fingerprintFailed: (filePath, message, cause) => ({
228
- code: "FINGERPRINT_FAILED",
229
- message,
230
- filePath,
231
- cause
232
- }),
233
- unsupportedAnalyzer: (analyzer, message) => ({
234
- code: "UNSUPPORTED_ANALYZER",
235
- message: message ?? `Unsupported analyzer: ${analyzer}`,
236
- analyzer
237
- }),
238
- canonicalPathInvalid: (path, reason) => ({
239
- code: "CANONICAL_PATH_INVALID",
240
- message: `Invalid canonical path: ${path}${reason ? ` (${reason})` : ""}`,
241
- path,
242
- reason
243
- }),
244
- canonicalScopeMismatch: (expected, actual) => ({
245
- code: "CANONICAL_SCOPE_MISMATCH",
246
- message: `Scope mismatch: expected ${expected}, got ${actual}`,
247
- expected,
248
- actual
249
- }),
250
- graphCircularDependency: (chain) => ({
251
- code: "GRAPH_CIRCULAR_DEPENDENCY",
252
- message: `Circular dependency detected: ${chain.join(" → ")}`,
253
- chain
254
- }),
255
- graphMissingImport: (importer, importee) => ({
256
- code: "GRAPH_MISSING_IMPORT",
257
- message: `Missing import: "${importer}" imports "${importee}" but it's not in the graph`,
258
- importer,
259
- importee
260
- }),
261
- docDuplicate: (name, sources) => ({
262
- code: "DOC_DUPLICATE",
263
- message: `Duplicate document name: ${name} found in ${sources.length} files`,
264
- name,
265
- sources
266
- }),
267
- writeFailed: (outPath, message, cause) => ({
268
- code: "WRITE_FAILED",
269
- message,
270
- outPath,
271
- cause
272
- }),
273
- cacheCorrupted: (message, cachePath, cause) => ({
274
- code: "CACHE_CORRUPTED",
275
- message,
276
- cachePath,
277
- cause
278
- }),
279
- runtimeModuleLoadFailed: (filePath, astPath, message, cause) => ({
280
- code: "RUNTIME_MODULE_LOAD_FAILED",
281
- message,
282
- filePath,
283
- astPath,
284
- cause
285
- }),
286
- artifactRegistrationFailed: (elementId, reason) => ({
287
- code: "ARTIFACT_REGISTRATION_FAILED",
288
- message: `Failed to register artifact element ${elementId}: ${reason}`,
289
- elementId,
290
- reason
291
- }),
292
- elementEvaluationFailed: (modulePath, astPath, message, cause) => ({
293
- code: "ELEMENT_EVALUATION_FAILED",
294
- message,
295
- modulePath,
296
- astPath,
297
- cause
298
- }),
299
- internalInvariant: (message, context, cause) => ({
300
- code: "INTERNAL_INVARIANT",
301
- message: `Internal invariant violated: ${message}`,
302
- context,
303
- cause
304
- }),
305
- schemaNotFound: (schemaLabel, canonicalId) => ({
306
- code: "SCHEMA_NOT_FOUND",
307
- message: `Schema not found for label "${schemaLabel}" (element: ${canonicalId})`,
308
- schemaLabel,
309
- canonicalId
310
- })
311
- };
312
- /**
313
- * Convenience helper to create an err Result from BuilderError.
314
- */
315
- const builderErr = (error) => (0, neverthrow.err)(error);
316
- /**
317
- * Type guard for BuilderError.
318
- */
319
- const isBuilderError = (error) => {
320
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && "message" in error && typeof error.message === "string";
321
- };
322
- /**
323
- * Format BuilderError for console output (human-readable).
324
- */
325
- const formatBuilderError = (error) => {
326
- const lines = [];
327
- lines.push(`Error [${error.code}]: ${error.message}`);
328
- switch (error.code) {
329
- case "ENTRY_NOT_FOUND":
330
- lines.push(` Entry: ${error.entry}`);
331
- break;
332
- case "CONFIG_NOT_FOUND":
333
- case "CONFIG_INVALID":
334
- lines.push(` Path: ${error.path}`);
335
- if (error.code === "CONFIG_INVALID" && error.cause) {
336
- lines.push(` Cause: ${error.cause}`);
337
- }
338
- break;
339
- case "DISCOVERY_IO_ERROR":
340
- lines.push(` Path: ${error.path}`);
341
- if (error.errno !== undefined) {
342
- lines.push(` Errno: ${error.errno}`);
343
- }
344
- break;
345
- case "FINGERPRINT_FAILED":
346
- lines.push(` File: ${error.filePath}`);
347
- break;
348
- case "CANONICAL_PATH_INVALID":
349
- lines.push(` Path: ${error.path}`);
350
- if (error.reason) {
351
- lines.push(` Reason: ${error.reason}`);
352
- }
353
- break;
354
- case "CANONICAL_SCOPE_MISMATCH":
355
- lines.push(` Expected: ${error.expected}`);
356
- lines.push(` Actual: ${error.actual}`);
357
- break;
358
- case "GRAPH_CIRCULAR_DEPENDENCY":
359
- lines.push(` Chain: ${error.chain.join(" → ")}`);
360
- break;
361
- case "GRAPH_MISSING_IMPORT":
362
- lines.push(` Importer: ${error.importer}`);
363
- lines.push(` Importee: ${error.importee}`);
364
- break;
365
- case "DOC_DUPLICATE":
366
- lines.push(` Name: ${error.name}`);
367
- lines.push(` Sources:\n ${error.sources.join("\n ")}`);
368
- break;
369
- case "WRITE_FAILED":
370
- lines.push(` Output path: ${error.outPath}`);
371
- break;
372
- case "CACHE_CORRUPTED":
373
- if (error.cachePath) {
374
- lines.push(` Cache path: ${error.cachePath}`);
375
- }
376
- break;
377
- case "RUNTIME_MODULE_LOAD_FAILED":
378
- lines.push(` File: ${error.filePath}`);
379
- lines.push(` AST path: ${error.astPath}`);
380
- break;
381
- case "ARTIFACT_REGISTRATION_FAILED":
382
- lines.push(` Element ID: ${error.elementId}`);
383
- lines.push(` Reason: ${error.reason}`);
384
- break;
385
- case "ELEMENT_EVALUATION_FAILED":
386
- lines.push(` at ${error.modulePath}`);
387
- if (error.astPath) {
388
- lines.push(` in ${error.astPath}`);
389
- }
390
- break;
391
- case "INTERNAL_INVARIANT":
392
- if (error.context) {
393
- lines.push(` Context: ${error.context}`);
394
- }
395
- break;
396
- case "SCHEMA_NOT_FOUND":
397
- lines.push(` Schema label: ${error.schemaLabel}`);
398
- lines.push(` Element: ${error.canonicalId}`);
399
- break;
400
- }
401
- if ("cause" in error && error.cause && !["CONFIG_INVALID"].includes(error.code)) {
402
- lines.push(` Caused by: ${error.cause}`);
403
- }
404
- return lines.join("\n");
405
- };
406
- /**
407
- * Assert unreachable code path (for exhaustiveness checks).
408
- * This is the ONLY acceptable throw in builder code.
409
- */
410
- const assertUnreachable = (value, context) => {
411
- throw new Error(`Unreachable code path${context ? ` in ${context}` : ""}: received ${JSON.stringify(value)}`);
412
- };
413
-
414
- //#endregion
415
- //#region packages/builder/src/errors/formatter.ts
416
- /**
417
- * Hints for each error code to help users understand and fix issues.
418
- */
419
- const errorHints = {
420
- ELEMENT_EVALUATION_FAILED: "Check if all imported fragments are properly exported and included in entry patterns.",
421
- GRAPH_CIRCULAR_DEPENDENCY: "Break the circular import by extracting shared types to a common module.",
422
- GRAPH_MISSING_IMPORT: "Verify the import path exists and the module is included in entry patterns.",
423
- RUNTIME_MODULE_LOAD_FAILED: "Ensure the module can be imported and all dependencies are installed.",
424
- CONFIG_NOT_FOUND: "Create a soda-gql.config.ts file in your project root.",
425
- CONFIG_INVALID: "Check your configuration file for syntax errors or invalid options.",
426
- ENTRY_NOT_FOUND: "Verify the entry pattern matches your file structure.",
427
- INTERNAL_INVARIANT: "This is an internal error. Please report it at https://github.com/soda-gql/soda-gql/issues"
428
- };
429
- /**
430
- * Format a BuilderError into a structured FormattedError object.
431
- */
432
- const formatBuilderErrorStructured = (error) => {
433
- const base = {
434
- code: error.code,
435
- message: error.message,
436
- hint: errorHints[error.code],
437
- cause: "cause" in error ? error.cause : undefined
438
- };
439
- switch (error.code) {
440
- case "ELEMENT_EVALUATION_FAILED": return {
441
- ...base,
442
- location: {
443
- modulePath: error.modulePath,
444
- astPath: error.astPath || undefined
445
- }
446
- };
447
- case "RUNTIME_MODULE_LOAD_FAILED": return {
448
- ...base,
449
- location: {
450
- modulePath: error.filePath,
451
- astPath: error.astPath
452
- }
453
- };
454
- case "GRAPH_MISSING_IMPORT": return {
455
- ...base,
456
- relatedFiles: [error.importer, error.importee]
457
- };
458
- case "GRAPH_CIRCULAR_DEPENDENCY": return {
459
- ...base,
460
- relatedFiles: error.chain
461
- };
462
- case "CONFIG_NOT_FOUND":
463
- case "CONFIG_INVALID": return {
464
- ...base,
465
- location: { modulePath: error.path }
466
- };
467
- case "FINGERPRINT_FAILED": return {
468
- ...base,
469
- location: { modulePath: error.filePath }
470
- };
471
- case "DISCOVERY_IO_ERROR": return {
472
- ...base,
473
- location: { modulePath: error.path }
474
- };
475
- default: return base;
476
- }
477
- };
478
- /**
479
- * Format a BuilderError for CLI/stderr output with human-readable formatting.
480
- * Includes location, hint, and related files when available.
481
- */
482
- const formatBuilderErrorForCLI = (error) => {
483
- const formatted = formatBuilderErrorStructured(error);
484
- const lines = [];
485
- lines.push(`Error [${formatted.code}]: ${formatted.message}`);
486
- if (formatted.location) {
487
- lines.push(` at ${formatted.location.modulePath}`);
488
- if (formatted.location.astPath) {
489
- lines.push(` in ${formatted.location.astPath}`);
490
- }
491
- }
492
- if (formatted.hint) {
493
- lines.push("");
494
- lines.push(` Hint: ${formatted.hint}`);
495
- }
496
- if (formatted.relatedFiles && formatted.relatedFiles.length > 0) {
497
- lines.push("");
498
- lines.push(" Related files:");
499
- for (const file of formatted.relatedFiles) {
500
- lines.push(` - ${file}`);
501
- }
502
- }
503
- return lines.join("\n");
504
- };
505
-
506
- //#endregion
507
- //#region packages/builder/src/scheduler/effects.ts
508
- /**
509
- * File read effect - reads a file from the filesystem.
510
- * Works in both sync and async schedulers.
511
- *
512
- * @example
513
- * const content = yield* new FileReadEffect("/path/to/file").run();
514
- */
515
- var FileReadEffect = class extends __soda_gql_common.Effect {
516
- constructor(path) {
517
- super();
518
- this.path = path;
519
- }
520
- _executeSync() {
521
- return (0, node_fs.readFileSync)(this.path, "utf-8");
522
- }
523
- _executeAsync() {
524
- return (0, node_fs_promises.readFile)(this.path, "utf-8");
525
- }
526
- };
527
- /**
528
- * File stat effect - gets file stats from the filesystem.
529
- * Works in both sync and async schedulers.
530
- *
531
- * @example
532
- * const stats = yield* new FileStatEffect("/path/to/file").run();
533
- */
534
- var FileStatEffect = class extends __soda_gql_common.Effect {
535
- constructor(path) {
536
- super();
537
- this.path = path;
538
- }
539
- _executeSync() {
540
- const stats = (0, node_fs.statSync)(this.path);
541
- return {
542
- mtimeMs: stats.mtimeMs,
543
- size: stats.size,
544
- isFile: stats.isFile()
545
- };
546
- }
547
- async _executeAsync() {
548
- const stats = await (0, node_fs_promises.stat)(this.path);
549
- return {
550
- mtimeMs: stats.mtimeMs,
551
- size: stats.size,
552
- isFile: stats.isFile()
553
- };
554
- }
555
- };
556
- /**
557
- * File read effect that returns null if file doesn't exist.
558
- * Useful for discovery where missing files are expected.
559
- */
560
- var OptionalFileReadEffect = class extends __soda_gql_common.Effect {
561
- constructor(path) {
562
- super();
563
- this.path = path;
564
- }
565
- _executeSync() {
566
- try {
567
- return (0, node_fs.readFileSync)(this.path, "utf-8");
568
- } catch (error) {
569
- if (error.code === "ENOENT") {
570
- return null;
571
- }
572
- throw error;
573
- }
574
- }
575
- async _executeAsync() {
576
- try {
577
- return await (0, node_fs_promises.readFile)(this.path, "utf-8");
578
- } catch (error) {
579
- if (error.code === "ENOENT") {
580
- return null;
581
- }
582
- throw error;
583
- }
584
- }
585
- };
586
- /**
587
- * File stat effect that returns null if file doesn't exist.
588
- * Useful for discovery where missing files are expected.
589
- */
590
- var OptionalFileStatEffect = class extends __soda_gql_common.Effect {
591
- constructor(path) {
592
- super();
593
- this.path = path;
594
- }
595
- _executeSync() {
596
- try {
597
- const stats = (0, node_fs.statSync)(this.path);
598
- return {
599
- mtimeMs: stats.mtimeMs,
600
- size: stats.size,
601
- isFile: stats.isFile()
602
- };
603
- } catch (error) {
604
- if (error.code === "ENOENT") {
605
- return null;
606
- }
607
- throw error;
608
- }
609
- }
610
- async _executeAsync() {
611
- try {
612
- const stats = await (0, node_fs_promises.stat)(this.path);
613
- return {
614
- mtimeMs: stats.mtimeMs,
615
- size: stats.size,
616
- isFile: stats.isFile()
617
- };
618
- } catch (error) {
619
- if (error.code === "ENOENT") {
620
- return null;
621
- }
622
- throw error;
623
- }
624
- }
625
- };
626
- /**
627
- * Element evaluation effect - evaluates a GqlElement using its generator.
628
- * Supports both sync and async schedulers, enabling parallel element evaluation
629
- * when using async scheduler.
630
- *
631
- * Wraps errors with module context for better debugging.
632
- *
633
- * @example
634
- * yield* new ElementEvaluationEffect(element).run();
635
- */
636
- var ElementEvaluationEffect = class extends __soda_gql_common.Effect {
637
- constructor(element) {
638
- super();
639
- this.element = element;
640
- }
641
- /**
642
- * Wrap an error with element context for better debugging.
643
- */
644
- wrapError(error) {
645
- const context = __soda_gql_core.GqlElement.getContext(this.element);
646
- if (context) {
647
- const { filePath, astPath } = (0, __soda_gql_common.parseCanonicalId)(context.canonicalId);
648
- const message = error instanceof Error ? error.message : String(error);
649
- throw builderErrors.elementEvaluationFailed(filePath, astPath, message, error);
650
- }
651
- throw error;
652
- }
653
- _executeSync() {
654
- try {
655
- const generator = __soda_gql_core.GqlElement.createEvaluationGenerator(this.element);
656
- const result = generator.next();
657
- while (!result.done) {
658
- throw new Error("Async operation required during sync element evaluation");
659
- }
660
- } catch (error) {
661
- this.wrapError(error);
135
+ const schemas = {};
136
+ for (const name of schemaNames) {
137
+ const composer = gql[name];
138
+ if (!composer) {
139
+ const availableSchemas = Object.keys(gql).join(", ");
140
+ return (0, neverthrow.err)({
141
+ code: "SCHEMA_NOT_FOUND",
142
+ message: `Schema '${name}' not found in gql exports. Available: ${availableSchemas || "(none)"}`,
143
+ schemaLabel: name,
144
+ canonicalId: `gql.${name}`
145
+ });
662
146
  }
663
- }
664
- async _executeAsync() {
665
- try {
666
- const generator = __soda_gql_core.GqlElement.createEvaluationGenerator(this.element);
667
- let result = generator.next();
668
- while (!result.done) {
669
- await result.value;
670
- result = generator.next();
671
- }
672
- } catch (error) {
673
- this.wrapError(error);
147
+ const schema = composer.$schema;
148
+ if (!schema || typeof schema !== "object") {
149
+ return (0, neverthrow.err)({
150
+ code: "CONFIG_INVALID",
151
+ message: `gql.${name}.$schema is not a valid schema object. Ensure codegen version is up to date.`,
152
+ path: resolvedPath
153
+ });
674
154
  }
155
+ schemas[name] = schema;
675
156
  }
676
- };
677
- /**
678
- * Builder effect constructors.
679
- * Extends the base Effects with file I/O operations and element evaluation.
680
- */
681
- const BuilderEffects = {
682
- ...__soda_gql_common.Effects,
683
- readFile: (path) => new FileReadEffect(path),
684
- stat: (path) => new FileStatEffect(path),
685
- readFileOptional: (path) => new OptionalFileReadEffect(path),
686
- statOptional: (path) => new OptionalFileStatEffect(path),
687
- evaluateElement: (element) => new ElementEvaluationEffect(element)
688
- };
689
-
690
- //#endregion
691
- //#region packages/builder/src/vm/sandbox.ts
692
- /**
693
- * VM sandbox utilities for CJS bundle evaluation.
694
- *
695
- * Provides shared infrastructure for executing CommonJS modules
696
- * in a sandboxed VM context with @soda-gql package mocking.
697
- *
698
- * @module
699
- */
700
- /**
701
- * Create a require function for the sandbox.
702
- * Maps @soda-gql package imports to their actual modules.
703
- */
704
- const createSandboxRequire = () => (path) => {
705
- if (path === "@soda-gql/core") return __soda_gql_core;
706
- if (path === "@soda-gql/core/adapter") return __soda_gql_core_adapter;
707
- if (path === "@soda-gql/core/runtime") return __soda_gql_core_runtime;
708
- if (path === "@soda-gql/runtime") return __soda_gql_runtime;
709
- throw new Error(`Unknown module: ${path}`);
710
- };
711
- /**
712
- * Create a VM sandbox for executing CJS bundles.
713
- *
714
- * Sets up:
715
- * - require() handler for @soda-gql packages
716
- * - module.exports and exports pointing to the same object
717
- * - __dirname, __filename for path resolution
718
- * - global and globalThis pointing to the sandbox itself
719
- *
720
- * @param modulePath - Absolute path to the module being executed
721
- * @param additionalContext - Optional additional context properties
722
- * @returns Configured sandbox object
723
- */
724
- const createSandbox = (modulePath, additionalContext) => {
725
- const moduleExports = {};
726
- const sandbox = {
727
- require: createSandboxRequire(),
728
- module: { exports: moduleExports },
729
- exports: moduleExports,
730
- __dirname: (0, node_path.resolve)(modulePath, ".."),
731
- __filename: modulePath,
732
- global: undefined,
733
- globalThis: undefined,
734
- ...additionalContext
735
- };
736
- sandbox.global = sandbox;
737
- sandbox.globalThis = sandbox;
738
- return sandbox;
739
- };
740
- /**
741
- * Execute CJS code in a sandbox and return the exports.
742
- *
743
- * Note: Reads from sandbox.module.exports because esbuild CJS output
744
- * reassigns module.exports via __toCommonJS(), replacing the original object.
745
- *
746
- * @param code - The CJS code to execute
747
- * @param modulePath - Absolute path to the module (for error messages)
748
- * @param additionalContext - Optional additional context properties
749
- * @returns The module's exports object
750
- */
751
- const executeSandbox = (code, modulePath, additionalContext) => {
752
- const sandbox = createSandbox(modulePath, additionalContext);
753
- const context = (0, node_vm.createContext)(sandbox);
754
- new node_vm.Script(code, { filename: modulePath }).runInContext(context);
755
- return sandbox.module.exports;
756
- };
757
-
758
- //#endregion
759
- //#region packages/builder/src/intermediate-module/codegen.ts
760
- const formatFactory = (expression) => {
761
- const trimmed = expression.trim();
762
- if (!trimmed.includes("\n")) {
763
- return trimmed;
764
- }
765
- const lines = trimmed.split("\n").map((line) => line.trimEnd());
766
- const indented = lines.map((line, index) => index === 0 ? line : ` ${line}`).join("\n");
767
- return `(\n ${indented}\n )`;
768
- };
769
- const buildTree = (definitions) => {
770
- const roots = new Map();
771
- definitions.forEach((definition) => {
772
- const parts = definition.astPath.split(".");
773
- const expressionText = definition.expression.trim();
774
- if (parts.length === 1) {
775
- const rootName = parts[0];
776
- if (rootName) {
777
- roots.set(rootName, {
778
- expression: expressionText,
779
- canonicalId: definition.canonicalId,
780
- children: new Map()
781
- });
782
- }
783
- } else {
784
- const rootName = parts[0];
785
- if (!rootName) return;
786
- let root = roots.get(rootName);
787
- if (!root) {
788
- root = { children: new Map() };
789
- roots.set(rootName, root);
790
- }
791
- let current = root;
792
- for (let i = 1; i < parts.length - 1; i++) {
793
- const part = parts[i];
794
- if (!part) continue;
795
- let child = current.children.get(part);
796
- if (!child) {
797
- child = { children: new Map() };
798
- current.children.set(part, child);
799
- }
800
- current = child;
801
- }
802
- const leafName = parts[parts.length - 1];
803
- if (leafName) {
804
- current.children.set(leafName, {
805
- expression: expressionText,
806
- canonicalId: definition.canonicalId,
807
- children: new Map()
808
- });
809
- }
810
- }
811
- });
812
- return roots;
813
- };
814
- /**
815
- * Check if a string is a valid JavaScript identifier
816
- */
817
- const isValidIdentifier = (name) => {
818
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) && !isReservedWord(name);
819
- };
820
- /**
821
- * Check if a string is a JavaScript reserved word
822
- */
823
- const isReservedWord = (name) => {
824
- const reserved = new Set([
825
- "break",
826
- "case",
827
- "catch",
828
- "class",
829
- "const",
830
- "continue",
831
- "debugger",
832
- "default",
833
- "delete",
834
- "do",
835
- "else",
836
- "export",
837
- "extends",
838
- "finally",
839
- "for",
840
- "function",
841
- "if",
842
- "import",
843
- "in",
844
- "instanceof",
845
- "new",
846
- "return",
847
- "super",
848
- "switch",
849
- "this",
850
- "throw",
851
- "try",
852
- "typeof",
853
- "var",
854
- "void",
855
- "while",
856
- "with",
857
- "yield",
858
- "let",
859
- "static",
860
- "enum",
861
- "await",
862
- "implements",
863
- "interface",
864
- "package",
865
- "private",
866
- "protected",
867
- "public"
868
- ]);
869
- return reserved.has(name);
870
- };
871
- /**
872
- * Format a key for use in an object literal
873
- * Invalid identifiers are quoted, valid ones are not
874
- */
875
- const formatObjectKey = (key) => {
876
- return isValidIdentifier(key) ? key : `"${key}"`;
877
- };
878
- const renderTreeNode = (node, indent) => {
879
- if (node.expression && node.children.size === 0 && node.canonicalId) {
880
- const expr = formatFactory(node.expression);
881
- return `registry.addElement("${node.canonicalId}", () => ${expr})`;
882
- }
883
- const indentStr = " ".repeat(indent);
884
- const entries = Array.from(node.children.entries()).map(([key, child]) => {
885
- const value = renderTreeNode(child, indent + 1);
886
- const formattedKey = formatObjectKey(key);
887
- return `${indentStr} ${formattedKey}: ${value},`;
888
- });
889
- if (entries.length === 0) {
890
- return "{}";
891
- }
892
- return `{\n${entries.join("\n")}\n${indentStr}}`;
893
- };
894
- const buildNestedObject = (definition) => {
895
- const tree = buildTree(definition);
896
- const declarations = [];
897
- const returnEntries = [];
898
- tree.forEach((node, rootName) => {
899
- if (node.children.size > 0) {
900
- const objectLiteral = renderTreeNode(node, 2);
901
- declarations.push(` const ${rootName} = ${objectLiteral};`);
902
- returnEntries.push(rootName);
903
- } else if (node.expression && node.canonicalId) {
904
- const expr = formatFactory(node.expression);
905
- declarations.push(` const ${rootName} = registry.addElement("${node.canonicalId}", () => ${expr});`);
906
- returnEntries.push(rootName);
907
- }
908
- });
909
- const returnStatement = returnEntries.length > 0 ? ` return {\n${returnEntries.map((name) => ` ${name},`).join("\n")}\n };` : " return {};";
910
- if (declarations.length === 0) {
911
- return returnStatement;
912
- }
913
- return `${declarations.join("\n")}\n${returnStatement}`;
914
- };
915
- /**
916
- * Render import statements for the intermediate module using ModuleSummary.
917
- * Only includes imports from modules that have gql exports.
918
- */
919
- const renderImportStatements = ({ filePath, analysis, analyses, graphqlSystemPath }) => {
920
- const importLines = [];
921
- const importedRootNames = new Set();
922
- const namespaceImports = new Set();
923
- const importsByFile = new Map();
924
- analysis.imports.forEach((imp) => {
925
- if (imp.isTypeOnly) {
926
- return;
927
- }
928
- if (!imp.source.startsWith(".")) {
929
- return;
930
- }
931
- const resolvedPath = (0, __soda_gql_common.resolveRelativeImportWithReferences)({
932
- filePath,
933
- specifier: imp.source,
934
- references: analyses
935
- });
936
- if (!resolvedPath) {
937
- return;
938
- }
939
- if (resolvedPath === graphqlSystemPath) {
940
- return;
941
- }
942
- const imports = importsByFile.get(resolvedPath) ?? [];
943
- imports.push(imp);
944
- importsByFile.set(resolvedPath, imports);
945
- });
946
- importsByFile.forEach((imports, filePath$1) => {
947
- const namespaceImport = imports.find((imp) => imp.kind === "namespace");
948
- if (namespaceImport) {
949
- importLines.push(` const ${namespaceImport.local} = yield registry.requestImport("${filePath$1}");`);
950
- namespaceImports.add(namespaceImport.local);
951
- importedRootNames.add(namespaceImport.local);
952
- } else {
953
- const rootNames = new Set();
954
- imports.forEach((imp) => {
955
- if (imp.kind === "named" || imp.kind === "default") {
956
- rootNames.add(imp.local);
957
- importedRootNames.add(imp.local);
958
- }
959
- });
960
- if (rootNames.size > 0) {
961
- const destructured = Array.from(rootNames).sort().join(", ");
962
- importLines.push(` const { ${destructured} } = yield registry.requestImport("${filePath$1}");`);
963
- }
964
- }
965
- });
966
- return {
967
- imports: importLines.length > 0 ? `${importLines.join("\n")}` : "",
968
- importedRootNames,
969
- namespaceImports
970
- };
971
- };
972
- const renderRegistryBlock = ({ filePath, analysis, analyses, graphqlSystemPath }) => {
973
- const { imports } = renderImportStatements({
974
- filePath,
975
- analysis,
976
- analyses,
977
- graphqlSystemPath
978
- });
979
- return [
980
- `registry.setModule("${filePath}", function*() {`,
981
- imports,
982
- "",
983
- buildNestedObject(analysis.definitions),
984
- "});"
985
- ].join("\n");
986
- };
987
-
988
- //#endregion
989
- //#region packages/builder/src/intermediate-module/registry.ts
990
- const createIntermediateRegistry = ({ analyses } = {}) => {
991
- const modules = new Map();
992
- const elements = new Map();
993
- const setModule = (filePath, factory) => {
994
- modules.set(filePath, factory);
995
- };
996
- /**
997
- * Creates an import request to be yielded by module generators.
998
- * Usage: `const { foo } = yield registry.requestImport("/path/to/module");`
999
- */
1000
- const requestImport = (filePath) => ({
1001
- kind: "import",
1002
- filePath
1003
- });
1004
- const addElement = (canonicalId, factory) => {
1005
- const builder = factory();
1006
- __soda_gql_core.GqlElement.setContext(builder, { canonicalId });
1007
- elements.set(canonicalId, builder);
1008
- return builder;
1009
- };
1010
- /**
1011
- * Evaluate a single module and its dependencies using trampoline.
1012
- * Returns the cached result or evaluates and caches if not yet evaluated.
1013
- */
1014
- const evaluateModule = (filePath, evaluated, inProgress) => {
1015
- const cached = evaluated.get(filePath);
1016
- if (cached) {
1017
- return cached;
1018
- }
1019
- const stack = [];
1020
- const factory = modules.get(filePath);
1021
- if (!factory) {
1022
- throw new Error(`Module not found or yet to be registered: ${filePath}`);
1023
- }
1024
- stack.push({
1025
- filePath,
1026
- generator: factory()
1027
- });
1028
- let frame;
1029
- while (frame = stack[stack.length - 1]) {
1030
- inProgress.add(frame.filePath);
1031
- const result$1 = frame.resolvedDependency !== undefined ? frame.generator.next(frame.resolvedDependency) : frame.generator.next();
1032
- frame.resolvedDependency = undefined;
1033
- if (result$1.done) {
1034
- evaluated.set(frame.filePath, result$1.value);
1035
- inProgress.delete(frame.filePath);
1036
- stack.pop();
1037
- const parentFrame = stack[stack.length - 1];
1038
- if (parentFrame) {
1039
- parentFrame.resolvedDependency = result$1.value;
1040
- }
1041
- } else {
1042
- const request = result$1.value;
1043
- if (request.kind === "import") {
1044
- const depPath = request.filePath;
1045
- const depCached = evaluated.get(depPath);
1046
- if (depCached) {
1047
- frame.resolvedDependency = depCached;
1048
- } else {
1049
- if (inProgress.has(depPath)) {
1050
- if (analyses) {
1051
- const currentAnalysis = analyses.get(frame.filePath);
1052
- const targetAnalysis = analyses.get(depPath);
1053
- const currentHasGql = currentAnalysis && currentAnalysis.definitions.length > 0;
1054
- const targetHasGql = targetAnalysis && targetAnalysis.definitions.length > 0;
1055
- if (!currentHasGql || !targetHasGql) {
1056
- frame.resolvedDependency = {};
1057
- continue;
1058
- }
1059
- }
1060
- throw new Error(`Circular dependency detected: ${depPath}`);
1061
- }
1062
- const depFactory = modules.get(depPath);
1063
- if (!depFactory) {
1064
- throw new Error(`Module not found or yet to be registered: ${depPath}`);
1065
- }
1066
- stack.push({
1067
- filePath: depPath,
1068
- generator: depFactory()
1069
- });
1070
- }
1071
- }
1072
- }
1073
- }
1074
- const result = evaluated.get(filePath);
1075
- if (!result) {
1076
- throw new Error(`Module evaluation failed: ${filePath}`);
1077
- }
1078
- return result;
1079
- };
1080
- /**
1081
- * Build artifacts record from evaluated elements.
1082
- */
1083
- const buildArtifacts = () => {
1084
- const artifacts = {};
1085
- for (const [canonicalId, element] of elements.entries()) {
1086
- if (element instanceof __soda_gql_core.Fragment) {
1087
- artifacts[canonicalId] = {
1088
- type: "fragment",
1089
- element
1090
- };
1091
- } else if (element instanceof __soda_gql_core.Operation) {
1092
- artifacts[canonicalId] = {
1093
- type: "operation",
1094
- element
1095
- };
1096
- }
1097
- }
1098
- return artifacts;
1099
- };
1100
- /**
1101
- * Generator that evaluates all elements using the effect system.
1102
- * Uses ParallelEffect to enable parallel evaluation in async mode.
1103
- * In sync mode, ParallelEffect executes effects sequentially.
1104
- */
1105
- function* evaluateElementsGen() {
1106
- const effects = Array.from(elements.values(), (element) => new ElementEvaluationEffect(element));
1107
- if (effects.length > 0) {
1108
- yield* new __soda_gql_common.ParallelEffect(effects).run();
1109
- }
1110
- }
1111
- /**
1112
- * Synchronous evaluation - evaluates all modules and elements synchronously.
1113
- * Throws if any element requires async operations (e.g., async metadata factory).
1114
- */
1115
- const evaluate = () => {
1116
- const evaluated = new Map();
1117
- const inProgress = new Set();
1118
- for (const filePath of modules.keys()) {
1119
- if (!evaluated.has(filePath)) {
1120
- evaluateModule(filePath, evaluated, inProgress);
1121
- }
1122
- }
1123
- const scheduler = (0, __soda_gql_common.createSyncScheduler)();
1124
- const result = scheduler.run(() => evaluateElementsGen());
1125
- if (result.isErr()) {
1126
- throw new Error(`Element evaluation failed: ${result.error.message}`);
1127
- }
1128
- return buildArtifacts();
1129
- };
1130
- /**
1131
- * Asynchronous evaluation - evaluates all modules and elements with async support.
1132
- * Supports async metadata factories and other async operations.
1133
- */
1134
- const evaluateAsync = async () => {
1135
- const evaluated = new Map();
1136
- const inProgress = new Set();
1137
- for (const filePath of modules.keys()) {
1138
- if (!evaluated.has(filePath)) {
1139
- evaluateModule(filePath, evaluated, inProgress);
1140
- }
1141
- }
1142
- const scheduler = (0, __soda_gql_common.createAsyncScheduler)();
1143
- const result = await scheduler.run(() => evaluateElementsGen());
1144
- if (result.isErr()) {
1145
- throw new Error(`Element evaluation failed: ${result.error.message}`);
1146
- }
1147
- return buildArtifacts();
1148
- };
1149
- /**
1150
- * Evaluate all modules synchronously using trampoline.
1151
- * This runs the module dependency resolution without element evaluation.
1152
- * Call this before getElements() when using external scheduler control.
1153
- */
1154
- const evaluateModules = () => {
1155
- const evaluated = new Map();
1156
- const inProgress = new Set();
1157
- for (const filePath of modules.keys()) {
1158
- if (!evaluated.has(filePath)) {
1159
- evaluateModule(filePath, evaluated, inProgress);
1160
- }
1161
- }
1162
- };
1163
- /**
1164
- * Get all registered elements for external effect creation.
1165
- * Call evaluateModules() first to ensure all modules have been evaluated.
1166
- */
1167
- const getElements = () => {
1168
- return Array.from(elements.values());
1169
- };
1170
- const clear = () => {
1171
- modules.clear();
1172
- elements.clear();
1173
- };
1174
- return {
1175
- setModule,
1176
- requestImport,
1177
- addElement,
1178
- evaluate,
1179
- evaluateAsync,
1180
- evaluateModules,
1181
- getElements,
1182
- buildArtifacts,
1183
- clear
1184
- };
1185
- };
1186
-
1187
- //#endregion
1188
- //#region packages/builder/src/intermediate-module/evaluation.ts
1189
- const transpile = ({ filePath, sourceCode }) => {
1190
- try {
1191
- const result = (0, __swc_core.transformSync)(sourceCode, {
1192
- filename: `${filePath}.ts`,
1193
- jsc: {
1194
- parser: {
1195
- syntax: "typescript",
1196
- tsx: false
1197
- },
1198
- target: "es2022"
1199
- },
1200
- module: { type: "es6" },
1201
- sourceMaps: false,
1202
- minify: false
1203
- });
1204
- return (0, neverthrow.ok)(result.code);
1205
- } catch (error) {
1206
- const message = error instanceof Error ? error.message : String(error);
1207
- return (0, neverthrow.err)({
1208
- code: "RUNTIME_MODULE_LOAD_FAILED",
1209
- filePath,
1210
- astPath: "",
1211
- message: `SWC transpilation failed: ${message}`
1212
- });
1213
- }
1214
- };
1215
- /**
1216
- * Resolve graphql system path to the bundled CJS file.
1217
- * Accepts both .ts (for backward compatibility) and .cjs paths.
1218
- * Maps .ts to sibling .cjs file if it exists.
1219
- */
1220
- function resolveGraphqlSystemPath(configPath) {
1221
- const ext = (0, node_path.extname)(configPath);
1222
- if (ext === ".cjs") {
1223
- return (0, node_path.resolve)(process.cwd(), configPath);
1224
- }
1225
- if (ext === ".ts") {
1226
- const basePath = configPath.slice(0, -3);
1227
- const cjsPath = `${basePath}.cjs`;
1228
- const resolvedCjsPath = (0, node_path.resolve)(process.cwd(), cjsPath);
1229
- if ((0, node_fs.existsSync)(resolvedCjsPath)) {
1230
- return resolvedCjsPath;
1231
- }
1232
- return (0, node_path.resolve)(process.cwd(), configPath);
1233
- }
1234
- return (0, node_path.resolve)(process.cwd(), configPath);
1235
- }
1236
- /**
1237
- * Bundle and execute GraphQL system module using rspack + memfs.
1238
- * Creates a self-contained bundle that can run in VM context.
1239
- * This is cached per session to avoid re-bundling.
1240
- */
1241
- let cachedGql = null;
1242
- let cachedModulePath = null;
1243
- /**
1244
- * Clear the cached gql module.
1245
- * Call this between test runs to ensure clean state.
1246
- * @internal - exported for testing purposes only
1247
- */
1248
- const __clearGqlCache = () => {
1249
- cachedGql = null;
1250
- cachedModulePath = null;
1251
- };
1252
- function executeGraphqlSystemModule(modulePath) {
1253
- if (cachedModulePath === modulePath && cachedGql !== null) {
1254
- return { gql: cachedGql };
1255
- }
1256
- const bundledCode = (0, node_fs.readFileSync)(modulePath, "utf-8");
1257
- const sandbox = createSandbox(modulePath);
1258
- new node_vm.Script(bundledCode, { filename: modulePath }).runInNewContext(sandbox);
1259
- const finalExports = sandbox.module.exports;
1260
- const exportedGql = finalExports.gql ?? finalExports.default;
1261
- if (exportedGql === undefined) {
1262
- throw new Error(`No 'gql' export found in GraphQL system module: ${modulePath}`);
1263
- }
1264
- cachedGql = exportedGql;
1265
- cachedModulePath = modulePath;
1266
- return { gql: cachedGql };
1267
- }
1268
- /**
1269
- * Build intermediate modules from dependency graph.
1270
- * Each intermediate module corresponds to one source file.
1271
- */
1272
- const generateIntermediateModules = function* ({ analyses, targetFiles, graphqlSystemPath }) {
1273
- for (const filePath of targetFiles) {
1274
- const analysis = analyses.get(filePath);
1275
- if (!analysis) {
1276
- continue;
1277
- }
1278
- const sourceCode = renderRegistryBlock({
1279
- filePath,
1280
- analysis,
1281
- analyses,
1282
- graphqlSystemPath
1283
- });
1284
- if (process.env.DEBUG_INTERMEDIATE_MODULE) {
1285
- console.log("=== Intermediate module source ===");
1286
- console.log("FilePath:", filePath);
1287
- console.log("Definitions:", analysis.definitions.map((d) => d.astPath));
1288
- console.log("Source code:\n", sourceCode);
1289
- console.log("=================================");
1290
- }
1291
- const transpiledCodeResult = transpile({
1292
- filePath,
1293
- sourceCode
1294
- });
1295
- if (transpiledCodeResult.isErr()) {
1296
- continue;
1297
- }
1298
- const transpiledCode = transpiledCodeResult.value;
1299
- const script = new node_vm.Script(transpiledCode);
1300
- const hash = (0, node_crypto.createHash)("sha1");
1301
- hash.update(transpiledCode);
1302
- const contentHash = hash.digest("hex");
1303
- const canonicalIds = analysis.definitions.map((definition) => definition.canonicalId);
1304
- yield {
1305
- filePath,
1306
- canonicalIds,
1307
- sourceCode,
1308
- transpiledCode,
1309
- contentHash,
1310
- script
1311
- };
1312
- }
1313
- };
1314
- /**
1315
- * Set up VM context and run intermediate module scripts.
1316
- * Returns the registry for evaluation.
1317
- */
1318
- const setupIntermediateModulesContext = ({ intermediateModules, graphqlSystemPath, analyses }) => {
1319
- const registry = createIntermediateRegistry({ analyses });
1320
- const gqlImportPath = resolveGraphqlSystemPath(graphqlSystemPath);
1321
- const { gql } = executeGraphqlSystemModule(gqlImportPath);
1322
- const vmContext = (0, node_vm.createContext)({
1323
- gql,
1324
- registry
1325
- });
1326
- for (const { script, filePath } of intermediateModules.values()) {
1327
- try {
1328
- script.runInContext(vmContext);
1329
- } catch (error) {
1330
- console.error(`Error evaluating intermediate module ${filePath}:`, error);
1331
- throw error;
1332
- }
1333
- }
1334
- return registry;
1335
- };
1336
- /**
1337
- * Synchronous evaluation of intermediate modules.
1338
- * Throws if any element requires async operations (e.g., async metadata factory).
1339
- */
1340
- const evaluateIntermediateModules = (input) => {
1341
- const registry = setupIntermediateModulesContext(input);
1342
- const elements = registry.evaluate();
1343
- registry.clear();
1344
- return elements;
1345
- };
1346
- /**
1347
- * Asynchronous evaluation of intermediate modules.
1348
- * Supports async metadata factories and other async operations.
1349
- */
1350
- const evaluateIntermediateModulesAsync = async (input) => {
1351
- const registry = setupIntermediateModulesContext(input);
1352
- const elements = await registry.evaluateAsync();
1353
- registry.clear();
1354
- return elements;
1355
- };
1356
- /**
1357
- * Generator version of evaluateIntermediateModules for external scheduler control.
1358
- * Yields effects for element evaluation, enabling unified scheduler at the root level.
1359
- *
1360
- * This function:
1361
- * 1. Sets up the VM context and runs intermediate module scripts
1362
- * 2. Runs synchronous module evaluation (trampoline - no I/O)
1363
- * 3. Yields element evaluation effects via ParallelEffect
1364
- * 4. Returns the artifacts record
1365
- */
1366
- function* evaluateIntermediateModulesGen(input) {
1367
- const registry = setupIntermediateModulesContext(input);
1368
- registry.evaluateModules();
1369
- const elements = registry.getElements();
1370
- const effects = elements.map((element) => new ElementEvaluationEffect(element));
1371
- if (effects.length > 0) {
1372
- yield* new __soda_gql_common.ParallelEffect(effects).run();
1373
- }
1374
- const artifacts = registry.buildArtifacts();
1375
- registry.clear();
1376
- return artifacts;
1377
- }
1378
-
1379
- //#endregion
1380
- //#region packages/builder/src/internal/graphql-system.ts
1381
- /**
1382
- * Helper for identifying graphql-system files and import specifiers.
1383
- * Provides robust detection across symlinks, case-insensitive filesystems, and user-defined aliases.
1384
- */
1385
- /**
1386
- * Create a canonical file name getter based on platform.
1387
- * On case-sensitive filesystems, paths are returned as-is.
1388
- * On case-insensitive filesystems, paths are lowercased for comparison.
1389
- */
1390
- const createGetCanonicalFileName = (useCaseSensitiveFileNames) => {
1391
- return useCaseSensitiveFileNames ? (path) => path : (path) => path.toLowerCase();
1392
- };
1393
- /**
1394
- * Detect if the filesystem is case-sensitive.
1395
- * We assume Unix-like systems are case-sensitive, and Windows is not.
1396
- */
1397
- const getUseCaseSensitiveFileNames = () => {
1398
- return process.platform !== "win32";
1399
- };
1400
- /**
1401
- * Create a GraphqlSystemIdentifyHelper from the resolved config.
1402
- * Uses canonical path comparison to handle casing, symlinks, and aliases.
1403
- */
1404
- const createGraphqlSystemIdentifyHelper = (config) => {
1405
- const getCanonicalFileName = createGetCanonicalFileName(getUseCaseSensitiveFileNames());
1406
- const toCanonical = (file) => {
1407
- const resolved = (0, node_path.resolve)(file);
1408
- try {
1409
- return getCanonicalFileName((0, node_fs.realpathSync)(resolved));
1410
- } catch {
1411
- return getCanonicalFileName(resolved);
1412
- }
1413
- };
1414
- const graphqlSystemPath = (0, node_path.resolve)(config.outdir, "index.ts");
1415
- const canonicalGraphqlSystemPath = toCanonical(graphqlSystemPath);
1416
- const canonicalAliases = new Set(config.graphqlSystemAliases.map((alias) => alias));
1417
- return {
1418
- isGraphqlSystemFile: ({ filePath }) => {
1419
- return toCanonical(filePath) === canonicalGraphqlSystemPath;
1420
- },
1421
- isGraphqlSystemImportSpecifier: ({ filePath, specifier }) => {
1422
- if (canonicalAliases.has(specifier)) {
1423
- return true;
1424
- }
1425
- if (!specifier.startsWith(".")) {
1426
- return false;
1427
- }
1428
- const resolved = (0, __soda_gql_common.resolveRelativeImportWithExistenceCheck)({
1429
- filePath,
1430
- specifier
1431
- });
1432
- if (!resolved) {
1433
- return false;
1434
- }
1435
- return toCanonical(resolved) === canonicalGraphqlSystemPath;
1436
- }
1437
- };
1438
- };
1439
-
1440
- //#endregion
1441
- //#region packages/builder/src/prebuilt/extractor.ts
1442
- /**
1443
- * Extract field selections from evaluated intermediate elements.
1444
- *
1445
- * For fragments, calls `spread()` with empty/default variables to get field selections.
1446
- * For operations, calls `documentSource()` to get field selections.
1447
- *
1448
- * @param elements - Record of canonical ID to intermediate artifact element
1449
- * @returns Object containing selections map and any warnings encountered
1450
- */
1451
- const extractFieldSelections = (elements) => {
1452
- const selections = new Map();
1453
- const warnings = [];
1454
- for (const [id, element] of Object.entries(elements)) {
1455
- const canonicalId = id;
1456
- try {
1457
- if (element.type === "fragment") {
1458
- const variableDefinitions = element.element.variableDefinitions;
1459
- const varRefs = Object.fromEntries(Object.keys(variableDefinitions).map((k) => [k, (0, __soda_gql_core.createVarRefFromVariable)(k)]));
1460
- const fields = element.element.spread(varRefs);
1461
- selections.set(canonicalId, {
1462
- type: "fragment",
1463
- schemaLabel: element.element.schemaLabel,
1464
- key: element.element.key,
1465
- typename: element.element.typename,
1466
- fields,
1467
- variableDefinitions
1468
- });
1469
- } else if (element.type === "operation") {
1470
- const fields = element.element.documentSource();
1471
- const document = element.element.document;
1472
- const operationDef = document.definitions.find((def) => def.kind === graphql.Kind.OPERATION_DEFINITION);
1473
- const variableDefinitions = operationDef?.variableDefinitions ?? [];
1474
- selections.set(canonicalId, {
1475
- type: "operation",
1476
- schemaLabel: element.element.schemaLabel,
1477
- operationName: element.element.operationName,
1478
- operationType: element.element.operationType,
1479
- fields,
1480
- variableDefinitions
1481
- });
1482
- }
1483
- } catch (error) {
1484
- warnings.push(`[prebuilt] Failed to extract field selections for ${canonicalId}: ${error instanceof Error ? error.message : String(error)}`);
1485
- }
1486
- }
1487
- return {
1488
- selections,
1489
- warnings
1490
- };
1491
- };
1492
-
1493
- //#endregion
1494
- //#region packages/builder/src/schema-loader.ts
1495
- /**
1496
- * Schema loader for CJS bundle evaluation.
1497
- *
1498
- * Loads AnyGraphqlSchema from the generated CJS bundle by accessing
1499
- * the `$schema` property on each gql composer.
1500
- *
1501
- * @module
1502
- */
1503
- /**
1504
- * Load AnyGraphqlSchema from a generated CJS bundle.
1505
- *
1506
- * The generated CJS bundle exports a `gql` object where each property
1507
- * is a GQL element composer with a `$schema` property containing the
1508
- * schema definition. This function executes the bundle in a VM context
1509
- * and extracts those schemas.
1510
- *
1511
- * @param cjsPath - Absolute path to the CJS bundle file
1512
- * @param schemaNames - Names of schemas to load (e.g., ["default", "admin"])
1513
- * @returns Record mapping schema names to AnyGraphqlSchema objects
1514
- *
1515
- * @example
1516
- * ```typescript
1517
- * const result = loadSchemasFromBundle(
1518
- * "/path/to/generated/index.cjs",
1519
- * ["default"]
1520
- * );
1521
- *
1522
- * if (result.isOk()) {
1523
- * const schemas = result.value;
1524
- * console.log(schemas.default); // AnyGraphqlSchema
1525
- * }
1526
- * ```
1527
- */
1528
- const loadSchemasFromBundle = (cjsPath, schemaNames) => {
1529
- const resolvedPath = (0, node_path.resolve)(cjsPath);
1530
- if (!(0, node_fs.existsSync)(resolvedPath)) {
1531
- return (0, neverthrow.err)({
1532
- code: "CONFIG_NOT_FOUND",
1533
- message: `CJS bundle not found: ${resolvedPath}. Run 'soda-gql codegen' first.`,
1534
- path: resolvedPath
1535
- });
1536
- }
1537
- let bundledCode;
1538
- try {
1539
- bundledCode = (0, node_fs.readFileSync)(resolvedPath, "utf-8");
1540
- } catch (error) {
1541
- return (0, neverthrow.err)({
1542
- code: "DISCOVERY_IO_ERROR",
1543
- message: `Failed to read CJS bundle: ${error instanceof Error ? error.message : String(error)}`,
1544
- path: resolvedPath,
1545
- cause: error
1546
- });
1547
- }
1548
- let finalExports;
1549
- try {
1550
- finalExports = executeSandbox(bundledCode, resolvedPath);
1551
- } catch (error) {
1552
- return (0, neverthrow.err)({
1553
- code: "RUNTIME_MODULE_LOAD_FAILED",
1554
- message: `Failed to execute CJS bundle: ${error instanceof Error ? error.message : String(error)}`,
1555
- filePath: resolvedPath,
1556
- astPath: "",
1557
- cause: error
1558
- });
1559
- }
1560
- const gql = finalExports.gql;
1561
- if (!gql || typeof gql !== "object") {
1562
- return (0, neverthrow.err)({
1563
- code: "CONFIG_INVALID",
1564
- message: "CJS bundle does not export 'gql' object. Ensure codegen was run successfully.",
1565
- path: resolvedPath
1566
- });
1567
- }
1568
- const schemas = {};
1569
- for (const name of schemaNames) {
1570
- const composer = gql[name];
1571
- if (!composer) {
1572
- const availableSchemas = Object.keys(gql).join(", ");
1573
- return (0, neverthrow.err)({
1574
- code: "SCHEMA_NOT_FOUND",
1575
- message: `Schema '${name}' not found in gql exports. Available: ${availableSchemas || "(none)"}`,
1576
- schemaLabel: name,
1577
- canonicalId: `gql.${name}`
1578
- });
1579
- }
1580
- const schema = composer.$schema;
1581
- if (!schema || typeof schema !== "object") {
1582
- return (0, neverthrow.err)({
1583
- code: "CONFIG_INVALID",
1584
- message: `gql.${name}.$schema is not a valid schema object. Ensure codegen version is up to date.`,
1585
- path: resolvedPath
1586
- });
1587
- }
1588
- schemas[name] = schema;
1589
- }
1590
- return (0, neverthrow.ok)(schemas);
1591
- };
1592
-
1593
- //#endregion
1594
- //#region packages/builder/src/artifact/aggregate.ts
1595
- const canonicalToFilePath$1 = (canonicalId) => canonicalId.split("::")[0] ?? canonicalId;
1596
- const computeContentHash = (prebuild) => {
1597
- const hash = (0, node_crypto.createHash)("sha1");
1598
- hash.update(JSON.stringify(prebuild));
1599
- return hash.digest("hex");
1600
- };
1601
- const emitRegistrationError = (definition, message) => ({
1602
- code: "RUNTIME_MODULE_LOAD_FAILED",
1603
- filePath: canonicalToFilePath$1(definition.canonicalId),
1604
- astPath: definition.astPath,
1605
- message
1606
- });
1607
- const aggregate = ({ analyses, elements }) => {
1608
- const registry = new Map();
1609
- for (const analysis of analyses.values()) {
1610
- for (const definition of analysis.definitions) {
1611
- const element = elements[definition.canonicalId];
1612
- if (!element) {
1613
- const availableIds = Object.keys(elements).join(", ");
1614
- const message = `ARTIFACT_NOT_FOUND_IN_RUNTIME_MODULE: ${definition.canonicalId}\nAvailable: ${availableIds}`;
1615
- return (0, neverthrow.err)(emitRegistrationError(definition, message));
1616
- }
1617
- if (registry.has(definition.canonicalId)) {
1618
- return (0, neverthrow.err)(emitRegistrationError(definition, `ARTIFACT_ALREADY_REGISTERED`));
1619
- }
1620
- const metadata = {
1621
- sourcePath: analysis.filePath ?? canonicalToFilePath$1(definition.canonicalId),
1622
- contentHash: ""
1623
- };
1624
- if (element.type === "fragment") {
1625
- const prebuild = {
1626
- typename: element.element.typename,
1627
- key: element.element.key,
1628
- schemaLabel: element.element.schemaLabel
1629
- };
1630
- registry.set(definition.canonicalId, {
1631
- id: definition.canonicalId,
1632
- type: "fragment",
1633
- prebuild,
1634
- metadata: {
1635
- ...metadata,
1636
- contentHash: computeContentHash(prebuild)
1637
- }
1638
- });
1639
- continue;
1640
- }
1641
- if (element.type === "operation") {
1642
- const prebuild = {
1643
- operationType: element.element.operationType,
1644
- operationName: element.element.operationName,
1645
- schemaLabel: element.element.schemaLabel,
1646
- document: element.element.document,
1647
- variableNames: element.element.variableNames,
1648
- metadata: element.element.metadata
1649
- };
1650
- registry.set(definition.canonicalId, {
1651
- id: definition.canonicalId,
1652
- type: "operation",
1653
- prebuild,
1654
- metadata: {
1655
- ...metadata,
1656
- contentHash: computeContentHash(prebuild)
1657
- }
1658
- });
1659
- continue;
1660
- }
1661
- return (0, neverthrow.err)(emitRegistrationError(definition, "UNKNOWN_ARTIFACT_KIND"));
1662
- }
1663
- }
1664
- return (0, neverthrow.ok)(registry);
1665
- };
1666
-
1667
- //#endregion
1668
- //#region packages/builder/src/artifact/issue-handler.ts
1669
- const canonicalToFilePath = (canonicalId) => canonicalId.split("::")[0] ?? canonicalId;
1670
- const checkIssues = ({ elements }) => {
1671
- const operationNames = new Set();
1672
- for (const [canonicalId, { type, element }] of Object.entries(elements)) {
1673
- if (type !== "operation") {
1674
- continue;
1675
- }
1676
- if (operationNames.has(element.operationName)) {
1677
- const sources = [canonicalToFilePath(canonicalId)];
1678
- return (0, neverthrow.err)({
1679
- code: "DOC_DUPLICATE",
1680
- message: `Duplicate document name: ${element.operationName}`,
1681
- name: element.operationName,
1682
- sources
1683
- });
1684
- }
1685
- operationNames.add(element.operationName);
1686
- }
1687
- return (0, neverthrow.ok)([]);
1688
- };
1689
-
1690
- //#endregion
1691
- //#region packages/builder/src/artifact/builder.ts
1692
- const buildArtifact = ({ elements, analyses, stats: cache }) => {
1693
- const issuesResult = checkIssues({ elements });
1694
- if (issuesResult.isErr()) {
1695
- return (0, neverthrow.err)(issuesResult.error);
1696
- }
1697
- const warnings = issuesResult.value;
1698
- const aggregationResult = aggregate({
1699
- analyses,
1700
- elements
1701
- });
1702
- if (aggregationResult.isErr()) {
1703
- return (0, neverthrow.err)(aggregationResult.error);
1704
- }
1705
- return (0, neverthrow.ok)({
1706
- elements: Object.fromEntries(aggregationResult.value.entries()),
1707
- report: {
1708
- durationMs: 0,
1709
- warnings,
1710
- stats: cache
1711
- }
1712
- });
1713
- };
1714
-
1715
- //#endregion
1716
- //#region packages/builder/src/ast/common/scope.ts
1717
- /**
1718
- * Build AST path from scope stack
1719
- */
1720
- const buildAstPath = (stack) => {
1721
- return stack.map((frame) => frame.nameSegment).join(".");
1722
- };
1723
- /**
1724
- * Create an occurrence tracker for disambiguating anonymous/duplicate scopes.
1725
- */
1726
- const createOccurrenceTracker = () => {
1727
- const occurrenceCounters = new Map();
1728
- return { getNextOccurrence(key) {
1729
- const current = occurrenceCounters.get(key) ?? 0;
1730
- occurrenceCounters.set(key, current + 1);
1731
- return current;
1732
- } };
1733
- };
1734
- /**
1735
- * Create a path uniqueness tracker to ensure AST paths are unique.
1736
- */
1737
- const createPathTracker = () => {
1738
- const usedPaths = new Set();
1739
- return { ensureUniquePath(basePath) {
1740
- let path = basePath;
1741
- let suffix = 0;
1742
- while (usedPaths.has(path)) {
1743
- suffix++;
1744
- path = `${basePath}$${suffix}`;
1745
- }
1746
- usedPaths.add(path);
1747
- return path;
1748
- } };
1749
- };
1750
- /**
1751
- * Create an export bindings map from module exports.
1752
- * Maps local variable names to their exported names.
1753
- */
1754
- const createExportBindingsMap = (exports$1) => {
1755
- const exportBindings = new Map();
1756
- exports$1.forEach((exp) => {
1757
- if (exp.kind === "named" && exp.local && !exp.isTypeOnly) {
1758
- exportBindings.set(exp.local, exp.exported);
1759
- }
1760
- });
1761
- return exportBindings;
1762
- };
1763
-
1764
- //#endregion
1765
- //#region packages/builder/src/ast/adapters/swc.ts
1766
- /**
1767
- * SWC adapter for the analyzer core.
1768
- * Implements parser-specific logic using the SWC parser.
1769
- */
1770
- const collectImports$1 = (module$1) => {
1771
- const imports = [];
1772
- const handle = (declaration) => {
1773
- const source = declaration.source.value;
1774
- declaration.specifiers?.forEach((specifier) => {
1775
- if (specifier.type === "ImportSpecifier") {
1776
- imports.push({
1777
- source,
1778
- local: specifier.local.value,
1779
- kind: "named",
1780
- isTypeOnly: Boolean(specifier.isTypeOnly)
1781
- });
1782
- return;
1783
- }
1784
- if (specifier.type === "ImportNamespaceSpecifier") {
1785
- imports.push({
1786
- source,
1787
- local: specifier.local.value,
1788
- kind: "namespace",
1789
- isTypeOnly: false
1790
- });
1791
- return;
1792
- }
1793
- if (specifier.type === "ImportDefaultSpecifier") {
1794
- imports.push({
1795
- source,
1796
- local: specifier.local.value,
1797
- kind: "default",
1798
- isTypeOnly: false
1799
- });
1800
- }
1801
- });
1802
- };
1803
- module$1.body.forEach((item) => {
1804
- if (item.type === "ImportDeclaration") {
1805
- handle(item);
1806
- return;
1807
- }
1808
- if ("declaration" in item && item.declaration && "type" in item.declaration && item.declaration.type === "ImportDeclaration") {
1809
- handle(item.declaration);
1810
- }
1811
- });
1812
- return imports;
1813
- };
1814
- const collectExports$1 = (module$1) => {
1815
- const exports$1 = [];
1816
- const handle = (declaration) => {
1817
- if (declaration.type === "ExportDeclaration") {
1818
- if (declaration.declaration.type === "VariableDeclaration") {
1819
- declaration.declaration.declarations.forEach((decl) => {
1820
- if (decl.id.type === "Identifier") {
1821
- exports$1.push({
1822
- kind: "named",
1823
- exported: decl.id.value,
1824
- local: decl.id.value,
1825
- isTypeOnly: false
1826
- });
1827
- }
1828
- });
1829
- }
1830
- if (declaration.declaration.type === "FunctionDeclaration") {
1831
- const ident = declaration.declaration.identifier;
1832
- if (ident) {
1833
- exports$1.push({
1834
- kind: "named",
1835
- exported: ident.value,
1836
- local: ident.value,
1837
- isTypeOnly: false
1838
- });
1839
- }
1840
- }
1841
- return;
1842
- }
1843
- if (declaration.type === "ExportNamedDeclaration") {
1844
- const source = declaration.source?.value;
1845
- declaration.specifiers?.forEach((specifier) => {
1846
- if (specifier.type !== "ExportSpecifier") {
1847
- return;
1848
- }
1849
- const exported = specifier.exported ? specifier.exported.value : specifier.orig.value;
1850
- const local = specifier.orig.value;
1851
- if (source) {
1852
- exports$1.push({
1853
- kind: "reexport",
1854
- exported,
1855
- local,
1856
- source,
1857
- isTypeOnly: Boolean(specifier.isTypeOnly)
1858
- });
1859
- return;
1860
- }
1861
- exports$1.push({
1862
- kind: "named",
1863
- exported,
1864
- local,
1865
- isTypeOnly: Boolean(specifier.isTypeOnly)
1866
- });
1867
- });
1868
- return;
1869
- }
1870
- if (declaration.type === "ExportAllDeclaration") {
1871
- exports$1.push({
1872
- kind: "reexport",
1873
- exported: "*",
1874
- source: declaration.source.value,
1875
- isTypeOnly: false
1876
- });
1877
- return;
1878
- }
1879
- if (declaration.type === "ExportDefaultDeclaration" || declaration.type === "ExportDefaultExpression") {
1880
- exports$1.push({
1881
- kind: "named",
1882
- exported: "default",
1883
- local: "default",
1884
- isTypeOnly: false
1885
- });
1886
- }
1887
- };
1888
- module$1.body.forEach((item) => {
1889
- if (item.type === "ExportDeclaration" || item.type === "ExportNamedDeclaration" || item.type === "ExportAllDeclaration" || item.type === "ExportDefaultDeclaration" || item.type === "ExportDefaultExpression") {
1890
- handle(item);
1891
- return;
1892
- }
1893
- if ("declaration" in item && item.declaration) {
1894
- const declaration = item.declaration;
1895
- if (declaration.type === "ExportDeclaration" || declaration.type === "ExportNamedDeclaration" || declaration.type === "ExportAllDeclaration" || declaration.type === "ExportDefaultDeclaration" || declaration.type === "ExportDefaultExpression") {
1896
- handle(declaration);
1897
- }
1898
- }
1899
- });
1900
- return exports$1;
1901
- };
1902
- const collectGqlIdentifiers = (module$1, helper) => {
1903
- const identifiers = new Set();
1904
- module$1.body.forEach((item) => {
1905
- const declaration = item.type === "ImportDeclaration" ? item : "declaration" in item && item.declaration && item.declaration.type === "ImportDeclaration" ? item.declaration : null;
1906
- if (!declaration) {
1907
- return;
1908
- }
1909
- if (!helper.isGraphqlSystemImportSpecifier({
1910
- filePath: module$1.__filePath,
1911
- specifier: declaration.source.value
1912
- })) {
1913
- return;
1914
- }
1915
- declaration.specifiers?.forEach((specifier) => {
1916
- if (specifier.type === "ImportSpecifier") {
1917
- const imported = specifier.imported ? specifier.imported.value : specifier.local.value;
1918
- if (imported === "gql") {
1919
- identifiers.add(specifier.local.value);
1920
- }
1921
- }
1922
- });
1923
- });
1924
- return identifiers;
1925
- };
1926
- const isGqlCall = (identifiers, call) => {
1927
- const callee = call.callee;
1928
- if (callee.type !== "MemberExpression") {
1929
- return false;
1930
- }
1931
- if (callee.object.type !== "Identifier") {
1932
- return false;
1933
- }
1934
- if (!identifiers.has(callee.object.value)) {
1935
- return false;
1936
- }
1937
- if (callee.property.type !== "Identifier") {
1938
- return false;
1939
- }
1940
- const firstArg = call.arguments[0];
1941
- if (!firstArg?.expression || firstArg.expression.type !== "ArrowFunctionExpression") {
1942
- return false;
1943
- }
1944
- return true;
1945
- };
1946
- /**
1947
- * Unwrap method chains (like .attach()) to find the underlying gql call.
1948
- * Returns the innermost CallExpression that is a valid gql definition call.
1949
- */
1950
- const unwrapMethodChains$1 = (identifiers, node) => {
1951
- if (!node || node.type !== "CallExpression") {
1952
- return null;
1953
- }
1954
- if (isGqlCall(identifiers, node)) {
1955
- return node;
1956
- }
1957
- const callee = node.callee;
1958
- if (callee.type !== "MemberExpression") {
1959
- return null;
1960
- }
1961
- return unwrapMethodChains$1(identifiers, callee.object);
1962
- };
1963
- const collectAllDefinitions$1 = ({ module: module$1, gqlIdentifiers, imports: _imports, exports: exports$1, source }) => {
1964
- const getPropertyName$1 = (property) => {
1965
- if (!property) {
1966
- return null;
1967
- }
1968
- if (property.type === "Identifier") {
1969
- return property.value;
1970
- }
1971
- if (property.type === "StringLiteral" || property.type === "NumericLiteral") {
1972
- return property.value;
1973
- }
1974
- return null;
1975
- };
1976
- const pending = [];
1977
- const handledCalls = [];
1978
- const exportBindings = createExportBindingsMap(exports$1);
1979
- const tracker = (0, __soda_gql_common.createCanonicalTracker)({
1980
- filePath: module$1.__filePath,
1981
- getExportName: (localName) => exportBindings.get(localName)
1982
- });
1983
- const anonymousCounters = new Map();
1984
- const getAnonymousName = (kind) => {
1985
- const count = anonymousCounters.get(kind) ?? 0;
1986
- anonymousCounters.set(kind, count + 1);
1987
- return `_${kind}_${count}`;
1988
- };
1989
- const withScope = (stack, segment, kind, stableKey, callback) => {
1990
- const handle = tracker.enterScope({
1991
- segment,
1992
- kind,
1993
- stableKey
1994
- });
1995
- try {
1996
- const frame = {
1997
- nameSegment: segment,
1998
- kind
1999
- };
2000
- return callback([...stack, frame]);
2001
- } finally {
2002
- tracker.exitScope(handle);
2003
- }
2004
- };
2005
- const expressionFromCall = (call) => {
2006
- const spanOffset = module$1.__spanOffset;
2007
- let start = call.span.start - spanOffset;
2008
- const end = call.span.end - spanOffset;
2009
- if (start > 0 && source[start] === "q" && source[start - 1] === "g" && source.slice(start, start + 3) === "ql.") {
2010
- start -= 1;
2011
- }
2012
- const raw = source.slice(start, end);
2013
- const marker = raw.indexOf("gql");
2014
- const expression = marker >= 0 ? raw.slice(marker) : raw;
2015
- return expression.replace(/\s*;\s*$/, "");
2016
- };
2017
- const visit = (node, stack) => {
2018
- if (!node || typeof node !== "object") {
2019
- return;
2020
- }
2021
- if (node.type === "CallExpression") {
2022
- const gqlCall = unwrapMethodChains$1(gqlIdentifiers, node);
2023
- if (gqlCall) {
2024
- const needsAnonymousScope = tracker.currentDepth() === 0;
2025
- let anonymousScopeHandle;
2026
- if (needsAnonymousScope) {
2027
- const anonymousName = getAnonymousName("anonymous");
2028
- anonymousScopeHandle = tracker.enterScope({
2029
- segment: anonymousName,
2030
- kind: "expression",
2031
- stableKey: "anonymous"
2032
- });
2033
- }
2034
- try {
2035
- const { astPath } = tracker.registerDefinition();
2036
- const isTopLevel = stack.length === 1;
2037
- let isExported = false;
2038
- let exportBinding;
2039
- if (isTopLevel && stack[0]) {
2040
- const topLevelName = stack[0].nameSegment;
2041
- if (exportBindings.has(topLevelName)) {
2042
- isExported = true;
2043
- exportBinding = exportBindings.get(topLevelName);
2044
- }
2045
- }
2046
- handledCalls.push(node);
2047
- pending.push({
2048
- astPath,
2049
- isTopLevel,
2050
- isExported,
2051
- exportBinding,
2052
- expression: expressionFromCall(gqlCall)
2053
- });
2054
- } finally {
2055
- if (anonymousScopeHandle) {
2056
- tracker.exitScope(anonymousScopeHandle);
2057
- }
2058
- }
2059
- return;
2060
- }
2061
- }
2062
- if (node.type === "VariableDeclaration") {
2063
- node.declarations?.forEach((decl) => {
2064
- if (decl.id?.type === "Identifier") {
2065
- const varName = decl.id.value;
2066
- if (decl.init) {
2067
- withScope(stack, varName, "variable", `var:${varName}`, (newStack) => {
2068
- visit(decl.init, newStack);
2069
- });
2070
- }
2071
- } else if (decl.init) {
2072
- visit(decl.init, stack);
2073
- }
2074
- });
2075
- return;
2076
- }
2077
- if (node.type === "FunctionDeclaration") {
2078
- const funcName = node.identifier?.value ?? getAnonymousName("function");
2079
- if (node.body) {
2080
- withScope(stack, funcName, "function", `func:${funcName}`, (newStack) => {
2081
- visit(node.body, newStack);
2082
- });
2083
- }
2084
- return;
2085
- }
2086
- if (node.type === "ArrowFunctionExpression") {
2087
- const arrowName = getAnonymousName("arrow");
2088
- if (node.body) {
2089
- withScope(stack, arrowName, "function", "arrow", (newStack) => {
2090
- visit(node.body, newStack);
2091
- });
2092
- }
2093
- return;
2094
- }
2095
- if (node.type === "FunctionExpression") {
2096
- const funcName = node.identifier?.value ?? getAnonymousName("function");
2097
- if (node.body) {
2098
- withScope(stack, funcName, "function", `func:${funcName}`, (newStack) => {
2099
- visit(node.body, newStack);
2100
- });
2101
- }
2102
- return;
2103
- }
2104
- if (node.type === "ClassDeclaration") {
2105
- const className = node.identifier?.value ?? getAnonymousName("class");
2106
- withScope(stack, className, "class", `class:${className}`, (classStack) => {
2107
- node.body?.forEach((member) => {
2108
- if (member.type === "ClassMethod" || member.type === "ClassProperty") {
2109
- const memberName = member.key?.value ?? null;
2110
- if (memberName) {
2111
- const memberKind = member.type === "ClassMethod" ? "method" : "property";
2112
- withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {
2113
- if (member.type === "ClassMethod" && member.function?.body) {
2114
- visit(member.function.body, memberStack);
2115
- } else if (member.type === "ClassProperty" && member.value) {
2116
- visit(member.value, memberStack);
2117
- }
2118
- });
2119
- }
2120
- }
2121
- });
2122
- });
2123
- return;
2124
- }
2125
- if (node.type === "KeyValueProperty") {
2126
- const propName = getPropertyName$1(node.key);
2127
- if (propName) {
2128
- withScope(stack, propName, "property", `prop:${propName}`, (newStack) => {
2129
- visit(node.value, newStack);
2130
- });
2131
- }
2132
- return;
2133
- }
2134
- if (Array.isArray(node)) {
2135
- for (const child of node) {
2136
- visit(child, stack);
2137
- }
2138
- } else {
2139
- for (const value of Object.values(node)) {
2140
- if (Array.isArray(value)) {
2141
- for (const child of value) {
2142
- visit(child, stack);
2143
- }
2144
- } else if (value && typeof value === "object") {
2145
- visit(value, stack);
2146
- }
2147
- }
2148
- }
2149
- };
2150
- module$1.body.forEach((statement) => {
2151
- visit(statement, []);
2152
- });
2153
- const definitions = pending.map((item) => ({
2154
- canonicalId: (0, __soda_gql_common.createCanonicalId)(module$1.__filePath, item.astPath),
2155
- astPath: item.astPath,
2156
- isTopLevel: item.isTopLevel,
2157
- isExported: item.isExported,
2158
- exportBinding: item.exportBinding,
2159
- expression: item.expression
2160
- }));
2161
- return {
2162
- definitions,
2163
- handledCalls
2164
- };
2165
- };
2166
- /**
2167
- * SWC adapter implementation.
2168
- * The analyze method parses and collects all data in one pass,
2169
- * ensuring the AST (Module) is released after analysis.
2170
- */
2171
- const swcAdapter = { analyze(input, helper) {
2172
- const program = (0, __swc_core.parseSync)(input.source, {
2173
- syntax: "typescript",
2174
- tsx: input.filePath.endsWith(".tsx"),
2175
- target: "es2022",
2176
- decorators: false,
2177
- dynamicImport: true
2178
- });
2179
- if (program.type !== "Module") {
2180
- return null;
2181
- }
2182
- const spanOffset = program.span.end - input.source.length + 1;
2183
- const swcModule = program;
2184
- swcModule.__filePath = input.filePath;
2185
- swcModule.__spanOffset = spanOffset;
2186
- const gqlIdentifiers = collectGqlIdentifiers(swcModule, helper);
2187
- const imports = collectImports$1(swcModule);
2188
- const exports$1 = collectExports$1(swcModule);
2189
- const { definitions } = collectAllDefinitions$1({
2190
- module: swcModule,
2191
- gqlIdentifiers,
2192
- imports,
2193
- exports: exports$1,
2194
- source: input.source
2195
- });
2196
- return {
2197
- imports,
2198
- exports: exports$1,
2199
- definitions
2200
- };
2201
- } };
2202
-
2203
- //#endregion
2204
- //#region packages/builder/src/ast/adapters/typescript.ts
2205
- /**
2206
- * TypeScript adapter for the analyzer core.
2207
- * Implements parser-specific logic using the TypeScript compiler API.
2208
- */
2209
- const createSourceFile = (filePath, source) => {
2210
- const scriptKind = (0, node_path.extname)(filePath) === ".tsx" ? typescript.default.ScriptKind.TSX : typescript.default.ScriptKind.TS;
2211
- return typescript.default.createSourceFile(filePath, source, typescript.default.ScriptTarget.ES2022, true, scriptKind);
2212
- };
2213
- const collectGqlImports = (sourceFile, helper) => {
2214
- const identifiers = new Set();
2215
- sourceFile.statements.forEach((statement) => {
2216
- if (!typescript.default.isImportDeclaration(statement) || !statement.importClause) {
2217
- return;
2218
- }
2219
- const moduleText = statement.moduleSpecifier.text;
2220
- if (!helper.isGraphqlSystemImportSpecifier({
2221
- filePath: sourceFile.fileName,
2222
- specifier: moduleText
2223
- })) {
2224
- return;
2225
- }
2226
- if (statement.importClause.namedBindings && typescript.default.isNamedImports(statement.importClause.namedBindings)) {
2227
- statement.importClause.namedBindings.elements.forEach((element) => {
2228
- const imported = element.propertyName ? element.propertyName.text : element.name.text;
2229
- if (imported === "gql") {
2230
- identifiers.add(element.name.text);
2231
- }
2232
- });
2233
- }
2234
- });
2235
- return identifiers;
2236
- };
2237
- const collectImports = (sourceFile) => {
2238
- const imports = [];
2239
- sourceFile.statements.forEach((statement) => {
2240
- if (!typescript.default.isImportDeclaration(statement) || !statement.importClause) {
2241
- return;
2242
- }
2243
- const moduleText = statement.moduleSpecifier.text;
2244
- const { importClause } = statement;
2245
- if (importClause.name) {
2246
- imports.push({
2247
- source: moduleText,
2248
- local: importClause.name.text,
2249
- kind: "default",
2250
- isTypeOnly: Boolean(importClause.isTypeOnly)
2251
- });
2252
- }
2253
- const { namedBindings } = importClause;
2254
- if (!namedBindings) {
2255
- return;
2256
- }
2257
- if (typescript.default.isNamespaceImport(namedBindings)) {
2258
- imports.push({
2259
- source: moduleText,
2260
- local: namedBindings.name.text,
2261
- kind: "namespace",
2262
- isTypeOnly: Boolean(importClause.isTypeOnly)
2263
- });
2264
- return;
2265
- }
2266
- namedBindings.elements.forEach((element) => {
2267
- imports.push({
2268
- source: moduleText,
2269
- local: element.name.text,
2270
- kind: "named",
2271
- isTypeOnly: Boolean(importClause.isTypeOnly || element.isTypeOnly)
2272
- });
2273
- });
2274
- });
2275
- return imports;
2276
- };
2277
- const collectExports = (sourceFile) => {
2278
- const exports$1 = [];
2279
- sourceFile.statements.forEach((statement) => {
2280
- if (typescript.default.isExportDeclaration(statement)) {
2281
- const moduleSpecifier = statement.moduleSpecifier ? statement.moduleSpecifier.text : undefined;
2282
- if (statement.exportClause && typescript.default.isNamedExports(statement.exportClause)) {
2283
- statement.exportClause.elements.forEach((element) => {
2284
- if (moduleSpecifier) {
2285
- exports$1.push({
2286
- kind: "reexport",
2287
- exported: element.name.text,
2288
- local: element.propertyName ? element.propertyName.text : undefined,
2289
- source: moduleSpecifier,
2290
- isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly)
2291
- });
2292
- } else {
2293
- exports$1.push({
2294
- kind: "named",
2295
- exported: element.name.text,
2296
- local: element.propertyName ? element.propertyName.text : element.name.text,
2297
- isTypeOnly: Boolean(statement.isTypeOnly || element.isTypeOnly)
2298
- });
2299
- }
2300
- });
2301
- return;
2302
- }
2303
- if (moduleSpecifier) {
2304
- exports$1.push({
2305
- kind: "reexport",
2306
- exported: "*",
2307
- source: moduleSpecifier,
2308
- isTypeOnly: Boolean(statement.isTypeOnly)
2309
- });
2310
- }
2311
- return;
2312
- }
2313
- if (typescript.default.isExportAssignment(statement)) {
2314
- exports$1.push({
2315
- kind: "named",
2316
- exported: "default",
2317
- local: "default",
2318
- isTypeOnly: false
2319
- });
2320
- }
2321
- if (typescript.default.isVariableStatement(statement) && statement.modifiers?.some((modifier) => modifier.kind === typescript.default.SyntaxKind.ExportKeyword)) {
2322
- statement.declarationList.declarations.forEach((declaration) => {
2323
- if (typescript.default.isIdentifier(declaration.name)) {
2324
- exports$1.push({
2325
- kind: "named",
2326
- exported: declaration.name.text,
2327
- local: declaration.name.text,
2328
- isTypeOnly: false
2329
- });
2330
- }
2331
- });
2332
- }
2333
- if (typescript.default.isFunctionDeclaration(statement) && statement.modifiers?.some((modifier) => modifier.kind === typescript.default.SyntaxKind.ExportKeyword) && statement.name) {
2334
- exports$1.push({
2335
- kind: "named",
2336
- exported: statement.name.text,
2337
- local: statement.name.text,
2338
- isTypeOnly: false
2339
- });
2340
- }
2341
- });
2342
- return exports$1;
2343
- };
2344
- const isGqlDefinitionCall = (identifiers, callExpression) => {
2345
- const expression = callExpression.expression;
2346
- if (!typescript.default.isPropertyAccessExpression(expression)) {
2347
- return false;
2348
- }
2349
- if (!typescript.default.isIdentifier(expression.expression) || !identifiers.has(expression.expression.text)) {
2350
- return false;
2351
- }
2352
- const [factory] = callExpression.arguments;
2353
- if (!factory || !typescript.default.isArrowFunction(factory)) {
2354
- return false;
2355
- }
2356
- return true;
2357
- };
2358
- /**
2359
- * Unwrap method chains (like .attach()) to find the underlying gql call.
2360
- * Returns the innermost CallExpression that is a valid gql definition call.
2361
- */
2362
- const unwrapMethodChains = (identifiers, node) => {
2363
- if (!typescript.default.isCallExpression(node)) {
2364
- return null;
2365
- }
2366
- if (isGqlDefinitionCall(identifiers, node)) {
2367
- return node;
2368
- }
2369
- const expression = node.expression;
2370
- if (!typescript.default.isPropertyAccessExpression(expression)) {
2371
- return null;
2372
- }
2373
- return unwrapMethodChains(identifiers, expression.expression);
2374
- };
2375
- /**
2376
- * Get property name from AST node
2377
- */
2378
- const getPropertyName = (name) => {
2379
- if (typescript.default.isIdentifier(name)) {
2380
- return name.text;
2381
- }
2382
- if (typescript.default.isStringLiteral(name) || typescript.default.isNumericLiteral(name)) {
2383
- return name.text;
2384
- }
2385
- return null;
2386
- };
2387
- /**
2388
- * Collect all gql definitions (exported, non-exported, top-level, nested)
2389
- */
2390
- const collectAllDefinitions = ({ sourceFile, identifiers, exports: exports$1 }) => {
2391
- const pending = [];
2392
- const handledCalls = [];
2393
- const exportBindings = createExportBindingsMap(exports$1);
2394
- const tracker = (0, __soda_gql_common.createCanonicalTracker)({
2395
- filePath: sourceFile.fileName,
2396
- getExportName: (localName) => exportBindings.get(localName)
2397
- });
2398
- const anonymousCounters = new Map();
2399
- const getAnonymousName = (kind) => {
2400
- const count = anonymousCounters.get(kind) ?? 0;
2401
- anonymousCounters.set(kind, count + 1);
2402
- return `_${kind}_${count}`;
2403
- };
2404
- const withScope = (stack, segment, kind, stableKey, callback) => {
2405
- const handle = tracker.enterScope({
2406
- segment,
2407
- kind,
2408
- stableKey
2409
- });
2410
- try {
2411
- const frame = {
2412
- nameSegment: segment,
2413
- kind
2414
- };
2415
- return callback([...stack, frame]);
2416
- } finally {
2417
- tracker.exitScope(handle);
2418
- }
2419
- };
2420
- const visit = (node, stack) => {
2421
- if (typescript.default.isCallExpression(node)) {
2422
- const gqlCall = unwrapMethodChains(identifiers, node);
2423
- if (gqlCall) {
2424
- const needsAnonymousScope = tracker.currentDepth() === 0;
2425
- let anonymousScopeHandle;
2426
- if (needsAnonymousScope) {
2427
- const anonymousName = getAnonymousName("anonymous");
2428
- anonymousScopeHandle = tracker.enterScope({
2429
- segment: anonymousName,
2430
- kind: "expression",
2431
- stableKey: "anonymous"
2432
- });
2433
- }
2434
- try {
2435
- const { astPath } = tracker.registerDefinition();
2436
- const isTopLevel = stack.length === 1;
2437
- let isExported = false;
2438
- let exportBinding;
2439
- if (isTopLevel && stack[0]) {
2440
- const topLevelName = stack[0].nameSegment;
2441
- if (exportBindings.has(topLevelName)) {
2442
- isExported = true;
2443
- exportBinding = exportBindings.get(topLevelName);
2444
- }
2445
- }
2446
- handledCalls.push(node);
2447
- pending.push({
2448
- astPath,
2449
- isTopLevel,
2450
- isExported,
2451
- exportBinding,
2452
- expression: gqlCall.getText(sourceFile)
2453
- });
2454
- } finally {
2455
- if (anonymousScopeHandle) {
2456
- tracker.exitScope(anonymousScopeHandle);
2457
- }
2458
- }
2459
- return;
2460
- }
2461
- }
2462
- if (typescript.default.isVariableDeclaration(node) && node.name && typescript.default.isIdentifier(node.name)) {
2463
- const varName = node.name.text;
2464
- if (node.initializer) {
2465
- const next = node.initializer;
2466
- withScope(stack, varName, "variable", `var:${varName}`, (newStack) => {
2467
- visit(next, newStack);
2468
- });
2469
- }
2470
- return;
2471
- }
2472
- if (typescript.default.isFunctionDeclaration(node)) {
2473
- const funcName = node.name?.text ?? getAnonymousName("function");
2474
- if (node.body) {
2475
- const next = node.body;
2476
- withScope(stack, funcName, "function", `func:${funcName}`, (newStack) => {
2477
- typescript.default.forEachChild(next, (child) => visit(child, newStack));
2478
- });
2479
- }
2480
- return;
2481
- }
2482
- if (typescript.default.isArrowFunction(node)) {
2483
- const arrowName = getAnonymousName("arrow");
2484
- withScope(stack, arrowName, "function", "arrow", (newStack) => {
2485
- if (typescript.default.isBlock(node.body)) {
2486
- typescript.default.forEachChild(node.body, (child) => visit(child, newStack));
2487
- } else {
2488
- visit(node.body, newStack);
2489
- }
2490
- });
2491
- return;
2492
- }
2493
- if (typescript.default.isFunctionExpression(node)) {
2494
- const funcName = node.name?.text ?? getAnonymousName("function");
2495
- if (node.body) {
2496
- withScope(stack, funcName, "function", `func:${funcName}`, (newStack) => {
2497
- typescript.default.forEachChild(node.body, (child) => visit(child, newStack));
2498
- });
2499
- }
2500
- return;
2501
- }
2502
- if (typescript.default.isClassDeclaration(node)) {
2503
- const className = node.name?.text ?? getAnonymousName("class");
2504
- withScope(stack, className, "class", `class:${className}`, (classStack) => {
2505
- node.members.forEach((member) => {
2506
- if (typescript.default.isMethodDeclaration(member) || typescript.default.isPropertyDeclaration(member)) {
2507
- const memberName = member.name && typescript.default.isIdentifier(member.name) ? member.name.text : null;
2508
- if (memberName) {
2509
- const memberKind = typescript.default.isMethodDeclaration(member) ? "method" : "property";
2510
- withScope(classStack, memberName, memberKind, `member:${className}.${memberName}`, (memberStack) => {
2511
- if (typescript.default.isMethodDeclaration(member) && member.body) {
2512
- typescript.default.forEachChild(member.body, (child) => visit(child, memberStack));
2513
- } else if (typescript.default.isPropertyDeclaration(member) && member.initializer) {
2514
- visit(member.initializer, memberStack);
2515
- }
2516
- });
2517
- }
2518
- }
2519
- });
2520
- });
2521
- return;
2522
- }
2523
- if (typescript.default.isPropertyAssignment(node)) {
2524
- const propName = getPropertyName(node.name);
2525
- if (propName) {
2526
- withScope(stack, propName, "property", `prop:${propName}`, (newStack) => {
2527
- visit(node.initializer, newStack);
2528
- });
2529
- }
2530
- return;
2531
- }
2532
- typescript.default.forEachChild(node, (child) => visit(child, stack));
2533
- };
2534
- sourceFile.statements.forEach((statement) => {
2535
- visit(statement, []);
2536
- });
2537
- const definitions = pending.map((item) => ({
2538
- canonicalId: (0, __soda_gql_common.createCanonicalId)(sourceFile.fileName, item.astPath),
2539
- astPath: item.astPath,
2540
- isTopLevel: item.isTopLevel,
2541
- isExported: item.isExported,
2542
- exportBinding: item.exportBinding,
2543
- expression: item.expression
2544
- }));
2545
- return {
2546
- definitions,
2547
- handledCalls
2548
- };
2549
- };
2550
- /**
2551
- * TypeScript adapter implementation.
2552
- * The analyze method parses and collects all data in one pass,
2553
- * ensuring the AST (ts.SourceFile) is released after analysis.
2554
- */
2555
- const typescriptAdapter = { analyze(input, helper) {
2556
- const sourceFile = createSourceFile(input.filePath, input.source);
2557
- const gqlIdentifiers = collectGqlImports(sourceFile, helper);
2558
- const imports = collectImports(sourceFile);
2559
- const exports$1 = collectExports(sourceFile);
2560
- const { definitions } = collectAllDefinitions({
2561
- sourceFile,
2562
- identifiers: gqlIdentifiers,
2563
- exports: exports$1
2564
- });
2565
- return {
2566
- imports,
2567
- exports: exports$1,
2568
- definitions
2569
- };
2570
- } };
2571
-
2572
- //#endregion
2573
- //#region packages/builder/src/ast/core.ts
2574
- /**
2575
- * Core analyzer logic that orchestrates the analysis pipeline.
2576
- * Adapters (TypeScript, SWC, etc.) implement the adapter interface to plug into this pipeline.
2577
- */
2578
- /**
2579
- * Core analyzer function that orchestrates the analysis pipeline.
2580
- * Adapters implement the AnalyzerAdapter interface to provide parser-specific logic.
2581
- */
2582
- const analyzeModuleCore = (input, adapter, graphqlHelper) => {
2583
- const hasher = (0, __soda_gql_common.getPortableHasher)();
2584
- const signature = hasher.hash(input.source, "xxhash");
2585
- const result = adapter.analyze(input, graphqlHelper);
2586
- if (!result) {
2587
- return {
2588
- filePath: input.filePath,
2589
- signature,
2590
- definitions: [],
2591
- imports: [],
2592
- exports: []
2593
- };
2594
- }
2595
- return {
2596
- filePath: input.filePath,
2597
- signature,
2598
- definitions: result.definitions,
2599
- imports: result.imports,
2600
- exports: result.exports
2601
- };
2602
- };
2603
-
2604
- //#endregion
2605
- //#region packages/builder/src/ast/index.ts
2606
- const createAstAnalyzer = ({ analyzer, graphqlHelper }) => {
2607
- const analyze = (input) => {
2608
- if (analyzer === "ts") {
2609
- return analyzeModuleCore(input, typescriptAdapter, graphqlHelper);
2610
- }
2611
- if (analyzer === "swc") {
2612
- return analyzeModuleCore(input, swcAdapter, graphqlHelper);
2613
- }
2614
- return assertUnreachable(analyzer, "createAstAnalyzer");
2615
- };
2616
- return {
2617
- type: analyzer,
2618
- analyze
2619
- };
2620
- };
2621
-
2622
- //#endregion
2623
- //#region packages/builder/src/cache/memory-cache.ts
2624
- const sanitizeSegment = (segment) => segment.replace(/[\\/]/g, "_");
2625
- const toNamespaceKey = (segments) => segments.map(sanitizeSegment).join("/");
2626
- const toEntryKey = (key) => {
2627
- const hasher = (0, __soda_gql_common.getPortableHasher)();
2628
- return hasher.hash(key, "xxhash");
2629
- };
2630
- const PERSISTENCE_VERSION = "v1";
2631
- /**
2632
- * Validate persisted data structure.
2633
- * Uses simple validation to detect corruption without strict schema.
2634
- */
2635
- const isValidPersistedData = (data) => {
2636
- if (typeof data !== "object" || data === null) return false;
2637
- const record = data;
2638
- if (typeof record.version !== "string") return false;
2639
- if (typeof record.storage !== "object" || record.storage === null) return false;
2640
- for (const value of Object.values(record.storage)) {
2641
- if (!Array.isArray(value)) return false;
2642
- for (const entry of value) {
2643
- if (!Array.isArray(entry) || entry.length !== 2) return false;
2644
- if (typeof entry[0] !== "string") return false;
2645
- const envelope = entry[1];
2646
- if (typeof envelope !== "object" || envelope === null) return false;
2647
- const env = envelope;
2648
- if (typeof env.key !== "string" || typeof env.version !== "string") return false;
2649
- }
2650
- }
2651
- return true;
2652
- };
2653
- const createMemoryCache = ({ prefix = [], persistence } = {}) => {
2654
- const storage = new Map();
2655
- if (persistence?.enabled) {
2656
- try {
2657
- if ((0, node_fs.existsSync)(persistence.filePath)) {
2658
- const content = (0, node_fs.readFileSync)(persistence.filePath, "utf-8");
2659
- let parsed;
2660
- try {
2661
- parsed = JSON.parse(content);
2662
- } catch {
2663
- console.warn(`[cache] Corrupt cache file (invalid JSON), starting fresh: ${persistence.filePath}`);
2664
- try {
2665
- (0, node_fs.unlinkSync)(persistence.filePath);
2666
- } catch {}
2667
- parsed = null;
2668
- }
2669
- if (parsed) {
2670
- if (!isValidPersistedData(parsed)) {
2671
- console.warn(`[cache] Corrupt cache file (invalid structure), starting fresh: ${persistence.filePath}`);
2672
- try {
2673
- (0, node_fs.unlinkSync)(persistence.filePath);
2674
- } catch {}
2675
- } else if (parsed.version === PERSISTENCE_VERSION) {
2676
- for (const [namespaceKey, entries] of Object.entries(parsed.storage)) {
2677
- const namespaceMap = new Map();
2678
- for (const [hashedKey, envelope] of entries) {
2679
- namespaceMap.set(hashedKey, envelope);
2680
- }
2681
- storage.set(namespaceKey, namespaceMap);
2682
- }
2683
- }
2684
- }
2685
- }
2686
- } catch (error) {
2687
- console.warn(`[cache] Failed to load cache from ${persistence.filePath}:`, error);
2688
- }
2689
- }
2690
- const getOrCreateNamespace = (namespaceKey) => {
2691
- let namespace = storage.get(namespaceKey);
2692
- if (!namespace) {
2693
- namespace = new Map();
2694
- storage.set(namespaceKey, namespace);
2695
- }
2696
- return namespace;
2697
- };
2698
- return {
2699
- createStore: ({ namespace, schema, version = "v1" }) => {
2700
- const namespaceKey = toNamespaceKey([...prefix, ...namespace]);
2701
- const envelopeSchema = zod.z.object({
2702
- key: zod.z.string(),
2703
- version: zod.z.string(),
2704
- value: schema
2705
- });
2706
- const resolveEntryKey = (key) => toEntryKey(key);
2707
- const validateEnvelope = (raw) => {
2708
- const parsed = envelopeSchema.safeParse(raw);
2709
- if (!parsed.success) {
2710
- return null;
2711
- }
2712
- if (parsed.data.version !== version) {
2713
- return null;
2714
- }
2715
- return parsed.data;
2716
- };
2717
- const load = (key) => {
2718
- const namespaceStore = storage.get(namespaceKey);
2719
- if (!namespaceStore) {
2720
- return null;
2721
- }
2722
- const entryKey = resolveEntryKey(key);
2723
- const raw = namespaceStore.get(entryKey);
2724
- if (!raw) {
2725
- return null;
2726
- }
2727
- const envelope = validateEnvelope(raw);
2728
- if (!envelope || envelope.key !== key) {
2729
- namespaceStore.delete(entryKey);
2730
- return null;
2731
- }
2732
- return envelope.value;
2733
- };
2734
- const store = (key, value) => {
2735
- const namespaceStore = getOrCreateNamespace(namespaceKey);
2736
- const entryKey = resolveEntryKey(key);
2737
- const envelope = {
2738
- key,
2739
- version,
2740
- value
2741
- };
2742
- namespaceStore.set(entryKey, envelope);
2743
- };
2744
- const deleteEntry = (key) => {
2745
- const namespaceStore = storage.get(namespaceKey);
2746
- if (!namespaceStore) {
2747
- return;
2748
- }
2749
- const entryKey = resolveEntryKey(key);
2750
- namespaceStore.delete(entryKey);
2751
- };
2752
- function* iterateEntries() {
2753
- const namespaceStore = storage.get(namespaceKey);
2754
- if (!namespaceStore) {
2755
- return;
2756
- }
2757
- for (const raw of namespaceStore.values()) {
2758
- const envelope = validateEnvelope(raw);
2759
- if (!envelope) {
2760
- continue;
2761
- }
2762
- yield [envelope.key, envelope.value];
2763
- }
2764
- }
2765
- const clear = () => {
2766
- const namespaceStore = storage.get(namespaceKey);
2767
- if (namespaceStore) {
2768
- namespaceStore.clear();
2769
- }
2770
- };
2771
- const size = () => {
2772
- let count = 0;
2773
- for (const _ of iterateEntries()) {
2774
- count += 1;
2775
- }
2776
- return count;
2777
- };
2778
- return {
2779
- load,
2780
- store,
2781
- delete: deleteEntry,
2782
- entries: iterateEntries,
2783
- clear,
2784
- size
2785
- };
2786
- },
2787
- clearAll: () => {
2788
- storage.clear();
2789
- },
2790
- save: () => {
2791
- if (!persistence?.enabled) {
2792
- return;
2793
- }
2794
- try {
2795
- const serialized = {};
2796
- for (const [namespaceKey, namespaceMap] of storage.entries()) {
2797
- serialized[namespaceKey] = Array.from(namespaceMap.entries());
2798
- }
2799
- const data = {
2800
- version: PERSISTENCE_VERSION,
2801
- storage: serialized
2802
- };
2803
- const fs = (0, __soda_gql_common.getPortableFS)();
2804
- fs.writeFileSyncAtomic(persistence.filePath, JSON.stringify(data));
2805
- } catch (error) {
2806
- console.warn(`[cache] Failed to save cache to ${persistence.filePath}:`, error);
2807
- }
2808
- }
2809
- };
2810
- };
2811
-
2812
- //#endregion
2813
- //#region packages/builder/src/cache/entity-cache.ts
2814
- /**
2815
- * Abstract base class for entity caches.
2816
- * Provides common caching functionality with signature-based eviction.
2817
- */
2818
- var EntityCache = class {
2819
- cacheStore;
2820
- keyNormalizer;
2821
- constructor(options) {
2822
- this.cacheStore = options.factory.createStore({
2823
- namespace: [...options.namespace],
2824
- schema: options.schema,
2825
- version: options.version
2826
- });
2827
- this.keyNormalizer = options.keyNormalizer ?? __soda_gql_common.normalizePath;
2828
- }
2829
- /**
2830
- * Normalize a key for consistent cache lookups.
2831
- */
2832
- normalizeKey(key) {
2833
- return this.keyNormalizer(key);
2834
- }
2835
- /**
2836
- * Load raw value from cache without signature validation.
2837
- */
2838
- loadRaw(key) {
2839
- return this.cacheStore.load(key);
2840
- }
2841
- /**
2842
- * Store raw value to cache.
2843
- */
2844
- storeRaw(key, value) {
2845
- this.cacheStore.store(key, value);
2846
- }
2847
- /**
2848
- * Delete an entry from the cache.
2849
- */
2850
- delete(key) {
2851
- const normalizedKey = this.normalizeKey(key);
2852
- this.cacheStore.delete(normalizedKey);
2853
- }
2854
- /**
2855
- * Get all cached entries.
2856
- * Subclasses should override this to provide custom iteration.
2857
- */
2858
- *baseEntries() {
2859
- for (const [, value] of this.cacheStore.entries()) {
2860
- yield value;
2861
- }
2862
- }
2863
- /**
2864
- * Clear all entries from the cache.
2865
- */
2866
- clear() {
2867
- this.cacheStore.clear();
2868
- }
2869
- /**
2870
- * Get the number of entries in the cache.
2871
- */
2872
- size() {
2873
- return this.cacheStore.size();
2874
- }
2875
- };
2876
-
2877
- //#endregion
2878
- //#region packages/builder/src/schemas/cache.ts
2879
- const ModuleDefinitionSchema = zod.z.object({
2880
- canonicalId: __soda_gql_common.CanonicalIdSchema,
2881
- astPath: zod.z.string(),
2882
- isTopLevel: zod.z.boolean(),
2883
- isExported: zod.z.boolean(),
2884
- exportBinding: zod.z.string().optional(),
2885
- expression: zod.z.string()
2886
- });
2887
- const ModuleImportSchema = zod.z.object({
2888
- source: zod.z.string(),
2889
- local: zod.z.string(),
2890
- kind: zod.z.enum([
2891
- "named",
2892
- "namespace",
2893
- "default"
2894
- ]),
2895
- isTypeOnly: zod.z.boolean()
2896
- });
2897
- const ModuleExportSchema = zod.z.discriminatedUnion("kind", [zod.z.object({
2898
- kind: zod.z.literal("named"),
2899
- exported: zod.z.string(),
2900
- local: zod.z.string(),
2901
- source: zod.z.undefined().optional(),
2902
- isTypeOnly: zod.z.boolean()
2903
- }), zod.z.object({
2904
- kind: zod.z.literal("reexport"),
2905
- exported: zod.z.string(),
2906
- source: zod.z.string(),
2907
- local: zod.z.string().optional(),
2908
- isTypeOnly: zod.z.boolean()
2909
- })]);
2910
- const ModuleAnalysisSchema = zod.z.object({
2911
- filePath: zod.z.string(),
2912
- signature: zod.z.string(),
2913
- definitions: zod.z.array(ModuleDefinitionSchema).readonly(),
2914
- imports: zod.z.array(ModuleImportSchema).readonly(),
2915
- exports: zod.z.array(ModuleExportSchema).readonly()
2916
- });
2917
-
2918
- //#endregion
2919
- //#region packages/builder/src/schemas/discovery.ts
2920
- const FileFingerprintSchema = zod.z.object({
2921
- hash: zod.z.string(),
2922
- sizeBytes: zod.z.number(),
2923
- mtimeMs: zod.z.number()
2924
- });
2925
- const DiscoveredDependencySchema = zod.z.object({
2926
- specifier: zod.z.string(),
2927
- resolvedPath: zod.z.string().nullable(),
2928
- isExternal: zod.z.boolean()
2929
- });
2930
- const DiscoverySnapshotSchema = zod.z.object({
2931
- filePath: zod.z.string(),
2932
- normalizedFilePath: zod.z.string(),
2933
- signature: zod.z.string(),
2934
- fingerprint: FileFingerprintSchema,
2935
- analyzer: zod.z.string(),
2936
- createdAtMs: zod.z.number(),
2937
- analysis: ModuleAnalysisSchema,
2938
- dependencies: zod.z.array(DiscoveredDependencySchema).readonly()
2939
- });
2940
-
2941
- //#endregion
2942
- //#region packages/builder/src/discovery/cache.ts
2943
- const DISCOVERY_CACHE_VERSION = "discovery-cache/v3";
2944
- var JsonDiscoveryCache = class extends EntityCache {
2945
- constructor(options) {
2946
- const namespace = [
2947
- ...options.namespacePrefix ?? ["discovery"],
2948
- options.analyzer,
2949
- options.evaluatorId
2950
- ];
2951
- super({
2952
- factory: options.factory,
2953
- namespace,
2954
- schema: DiscoverySnapshotSchema,
2955
- version: options.version ?? DISCOVERY_CACHE_VERSION
2956
- });
2957
- }
2958
- load(filePath, expectedSignature) {
2959
- const key = this.normalizeKey(filePath);
2960
- const snapshot = this.loadRaw(key);
2961
- if (!snapshot) {
2962
- return null;
2963
- }
2964
- if (snapshot.signature !== expectedSignature) {
2965
- this.delete(filePath);
2966
- return null;
2967
- }
2968
- return snapshot;
2969
- }
2970
- peek(filePath) {
2971
- const key = this.normalizeKey(filePath);
2972
- return this.loadRaw(key);
2973
- }
2974
- store(snapshot) {
2975
- const key = this.normalizeKey(snapshot.filePath);
2976
- this.storeRaw(key, snapshot);
2977
- }
2978
- entries() {
2979
- return this.baseEntries();
2980
- }
2981
- };
2982
- const createDiscoveryCache = (options) => new JsonDiscoveryCache(options);
2983
-
2984
- //#endregion
2985
- //#region packages/builder/src/discovery/common.ts
2986
- /**
2987
- * Extract all unique dependencies (relative + external) from the analysis.
2988
- * Resolves local specifiers immediately so discovery only traverses once.
2989
- */
2990
- const extractModuleDependencies = (analysis) => {
2991
- const dependencies = new Map();
2992
- const addDependency = (specifier) => {
2993
- if (dependencies.has(specifier)) {
2994
- return;
2995
- }
2996
- const isExternal = (0, __soda_gql_common.isExternalSpecifier)(specifier);
2997
- const resolvedPath = isExternal ? null : (0, __soda_gql_common.resolveRelativeImportWithExistenceCheck)({
2998
- filePath: analysis.filePath,
2999
- specifier
3000
- });
3001
- dependencies.set(specifier, {
3002
- specifier,
3003
- resolvedPath,
3004
- isExternal
3005
- });
3006
- };
3007
- for (const imp of analysis.imports) {
3008
- addDependency(imp.source);
3009
- }
3010
- for (const exp of analysis.exports) {
3011
- if (exp.kind === "reexport") {
3012
- addDependency(exp.source);
3013
- }
3014
- }
3015
- return Array.from(dependencies.values());
3016
- };
3017
- const createSourceHash = (source) => {
3018
- const hasher = (0, __soda_gql_common.getPortableHasher)();
3019
- return hasher.hash(source, "xxhash");
3020
- };
3021
-
3022
- //#endregion
3023
- //#region packages/builder/src/discovery/fingerprint.ts
3024
- /**
3025
- * In-memory fingerprint cache keyed by absolute path
3026
- */
3027
- const fingerprintCache = new Map();
3028
- /**
3029
- * Lazy-loaded xxhash instance
3030
- */
3031
- let xxhashInstance = null;
3032
- /**
3033
- * Lazily load xxhash-wasm instance
3034
- */
3035
- async function getXXHash() {
3036
- if (xxhashInstance === null) {
3037
- const { default: xxhash } = await import("xxhash-wasm");
3038
- xxhashInstance = await xxhash();
3039
- }
3040
- return xxhashInstance;
3041
- }
3042
- /**
3043
- * Compute file fingerprint with memoization.
3044
- * Uses mtime to short-circuit re-hashing unchanged files.
3045
- *
3046
- * @param path - Absolute path to file
3047
- * @returns Result containing FileFingerprint or FingerprintError
3048
- */
3049
- function computeFingerprint(path) {
3050
- try {
3051
- const stats = (0, node_fs.statSync)(path);
3052
- if (!stats.isFile()) {
3053
- return (0, neverthrow.err)({
3054
- code: "NOT_A_FILE",
3055
- path,
3056
- message: `Path is not a file: ${path}`
3057
- });
3058
- }
3059
- const mtimeMs = stats.mtimeMs;
3060
- const cached = fingerprintCache.get(path);
3061
- if (cached && cached.mtimeMs === mtimeMs) {
3062
- return (0, neverthrow.ok)(cached);
3063
- }
3064
- const contents = (0, node_fs.readFileSync)(path);
3065
- const sizeBytes = stats.size;
3066
- const hash = computeHashSync(contents);
3067
- const fingerprint = {
3068
- hash,
3069
- sizeBytes,
3070
- mtimeMs
3071
- };
3072
- fingerprintCache.set(path, fingerprint);
3073
- return (0, neverthrow.ok)(fingerprint);
3074
- } catch (error) {
3075
- if (error.code === "ENOENT") {
3076
- return (0, neverthrow.err)({
3077
- code: "FILE_NOT_FOUND",
3078
- path,
3079
- message: `File not found: ${path}`
3080
- });
3081
- }
3082
- return (0, neverthrow.err)({
3083
- code: "READ_ERROR",
3084
- path,
3085
- message: `Failed to read file: ${error}`
3086
- });
3087
- }
3088
- }
3089
- /**
3090
- * Compute hash synchronously.
3091
- * For first call, uses simple string hash as fallback.
3092
- * Subsequent calls will use xxhash after async initialization.
3093
- */
3094
- function computeHashSync(contents) {
3095
- if (xxhashInstance !== null) {
3096
- const hash = xxhashInstance.h64Raw(new Uint8Array(contents));
3097
- return hash.toString(16);
3098
- }
3099
- void getXXHash();
3100
- return simpleHash(contents);
3101
- }
3102
- /**
3103
- * Simple hash function for initial calls before xxhash loads
3104
- */
3105
- function simpleHash(buffer) {
3106
- let hash = 0;
3107
- for (let i = 0; i < buffer.length; i++) {
3108
- const byte = buffer[i];
3109
- if (byte !== undefined) {
3110
- hash = (hash << 5) - hash + byte;
3111
- hash = hash & hash;
3112
- }
3113
- }
3114
- return hash.toString(16);
3115
- }
3116
- /**
3117
- * Compute fingerprint from pre-read file content and stats.
3118
- * This is used by the generator-based discoverer which already has the content.
3119
- *
3120
- * @param path - Absolute path to file (for caching)
3121
- * @param stats - File stats (mtimeMs, size)
3122
- * @param content - File content as string
3123
- * @returns FileFingerprint
3124
- */
3125
- function computeFingerprintFromContent(path, stats, content) {
3126
- const cached = fingerprintCache.get(path);
3127
- if (cached && cached.mtimeMs === stats.mtimeMs) {
3128
- return cached;
3129
- }
3130
- const buffer = Buffer.from(content, "utf-8");
3131
- const hash = computeHashSync(buffer);
3132
- const fingerprint = {
3133
- hash,
3134
- sizeBytes: stats.size,
3135
- mtimeMs: stats.mtimeMs
3136
- };
3137
- fingerprintCache.set(path, fingerprint);
3138
- return fingerprint;
3139
- }
3140
- /**
3141
- * Invalidate cached fingerprint for a specific path
3142
- *
3143
- * @param path - Absolute path to invalidate
3144
- */
3145
- function invalidateFingerprint(path) {
3146
- fingerprintCache.delete(path);
3147
- }
3148
- /**
3149
- * Clear all cached fingerprints
3150
- */
3151
- function clearFingerprintCache() {
3152
- fingerprintCache.clear();
3153
- }
3154
-
3155
- //#endregion
3156
- //#region packages/builder/src/discovery/discoverer.ts
3157
- /**
3158
- * Generator-based module discovery that yields effects for file I/O.
3159
- * This allows the discovery process to be executed with either sync or async schedulers.
3160
- */
3161
- function* discoverModulesGen({ entryPaths, astAnalyzer, incremental }) {
3162
- const snapshots = new Map();
3163
- const stack = [...entryPaths];
3164
- const changedFiles = incremental?.changedFiles ?? new Set();
3165
- const removedFiles = incremental?.removedFiles ?? new Set();
3166
- const affectedFiles = incremental?.affectedFiles ?? new Set();
3167
- const invalidatedSet = new Set([
3168
- ...changedFiles,
3169
- ...removedFiles,
3170
- ...affectedFiles
3171
- ]);
3172
- let cacheHits = 0;
3173
- let cacheMisses = 0;
3174
- let cacheSkips = 0;
3175
- if (incremental) {
3176
- for (const filePath of removedFiles) {
3177
- incremental.cache.delete(filePath);
3178
- invalidateFingerprint(filePath);
3179
- }
3180
- }
3181
- while (stack.length > 0) {
3182
- const rawFilePath = stack.pop();
3183
- if (!rawFilePath) {
3184
- continue;
3185
- }
3186
- const filePath = (0, __soda_gql_common.normalizePath)(rawFilePath);
3187
- if (snapshots.has(filePath)) {
3188
- continue;
3189
- }
3190
- let shouldReadFile = true;
3191
- if (invalidatedSet.has(filePath)) {
3192
- invalidateFingerprint(filePath);
3193
- cacheSkips++;
3194
- } else if (incremental) {
3195
- const cached = incremental.cache.peek(filePath);
3196
- if (cached) {
3197
- const stats$1 = yield* new OptionalFileStatEffect(filePath).run();
3198
- if (stats$1) {
3199
- const mtimeMs = stats$1.mtimeMs;
3200
- const sizeBytes = stats$1.size;
3201
- if (cached.fingerprint.mtimeMs === mtimeMs && cached.fingerprint.sizeBytes === sizeBytes) {
3202
- snapshots.set(filePath, cached);
3203
- cacheHits++;
3204
- for (const dep of cached.dependencies) {
3205
- if (dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {
3206
- stack.push(dep.resolvedPath);
3207
- }
3208
- }
3209
- shouldReadFile = false;
3210
- }
3211
- }
3212
- }
3213
- }
3214
- if (!shouldReadFile) {
3215
- continue;
3216
- }
3217
- const source = yield* new OptionalFileReadEffect(filePath).run();
3218
- if (source === null) {
3219
- incremental?.cache.delete(filePath);
3220
- invalidateFingerprint(filePath);
3221
- continue;
3222
- }
3223
- const signature = createSourceHash(source);
3224
- const analysis = astAnalyzer.analyze({
3225
- filePath,
3226
- source
3227
- });
3228
- cacheMisses++;
3229
- const dependencies = extractModuleDependencies(analysis);
3230
- for (const dep of dependencies) {
3231
- if (!dep.isExternal && dep.resolvedPath && !snapshots.has(dep.resolvedPath)) {
3232
- stack.push(dep.resolvedPath);
3233
- }
3234
- }
3235
- const stats = yield* new OptionalFileStatEffect(filePath).run();
3236
- const fingerprint = computeFingerprintFromContent(filePath, stats, source);
3237
- const snapshot = {
3238
- filePath,
3239
- normalizedFilePath: (0, __soda_gql_common.normalizePath)(filePath),
3240
- signature,
3241
- fingerprint,
3242
- analyzer: astAnalyzer.type,
3243
- createdAtMs: Date.now(),
3244
- analysis,
3245
- dependencies
3246
- };
3247
- snapshots.set(filePath, snapshot);
3248
- if (incremental) {
3249
- incremental.cache.store(snapshot);
3250
- }
3251
- }
3252
- return {
3253
- snapshots: Array.from(snapshots.values()),
3254
- cacheHits,
3255
- cacheMisses,
3256
- cacheSkips
3257
- };
3258
- }
3259
- /**
3260
- * Discover and analyze all modules starting from entry points.
3261
- * Uses AST parsing instead of RegExp for reliable dependency extraction.
3262
- * Supports caching with fingerprint-based invalidation to skip re-parsing unchanged files.
3263
- *
3264
- * This function uses the synchronous scheduler internally for backward compatibility.
3265
- * For async execution with parallel file I/O, use discoverModulesGen with an async scheduler.
3266
- */
3267
- const discoverModules = (options) => {
3268
- const scheduler = (0, __soda_gql_common.createSyncScheduler)();
3269
- const result = scheduler.run(() => discoverModulesGen(options));
3270
- if (result.isErr()) {
3271
- const error = result.error;
3272
- return (0, neverthrow.err)(builderErrors.discoveryIOError("unknown", error.message));
3273
- }
3274
- return (0, neverthrow.ok)(result.value);
3275
- };
3276
- /**
3277
- * Asynchronous version of discoverModules.
3278
- * Uses async scheduler for parallel file I/O operations.
3279
- *
3280
- * This is useful for large codebases where parallel file operations can improve performance.
3281
- */
3282
- const discoverModulesAsync = async (options) => {
3283
- const scheduler = (0, __soda_gql_common.createAsyncScheduler)();
3284
- const result = await scheduler.run(() => discoverModulesGen(options));
3285
- if (result.isErr()) {
3286
- const error = result.error;
3287
- return (0, neverthrow.err)(builderErrors.discoveryIOError("unknown", error.message));
3288
- }
3289
- return (0, neverthrow.ok)(result.value);
3290
- };
3291
-
3292
- //#endregion
3293
- //#region packages/builder/src/utils/glob.ts
3294
- /**
3295
- * Cross-runtime glob pattern matching abstraction
3296
- * Provides a unified interface for glob operations across Bun and Node.js
3297
- */
3298
- /**
3299
- * Scan files matching a glob pattern from the given directory
3300
- * @param pattern - Glob pattern (e.g., "src/**\/*.ts")
3301
- * @param cwd - Working directory (defaults to process.cwd())
3302
- * @returns Array of matched file paths (relative to cwd)
3303
- */
3304
- const scanGlob = (pattern, cwd = process.cwd()) => {
3305
- if (typeof Bun !== "undefined" && Bun.Glob) {
3306
- const { Glob } = Bun;
3307
- const glob = new Glob(pattern);
3308
- return Array.from(glob.scanSync(cwd));
3309
- }
3310
- return fast_glob.default.sync(pattern, {
3311
- cwd,
3312
- dot: true,
3313
- onlyFiles: true
3314
- });
3315
- };
3316
-
3317
- //#endregion
3318
- //#region packages/builder/src/discovery/entry-paths.ts
3319
- const scanEntries = (pattern) => {
3320
- return scanGlob(pattern, process.cwd());
3321
- };
3322
- /**
3323
- * Resolve entry file paths from glob patterns or direct paths.
3324
- * Used by the discovery system to find entry points for module traversal.
3325
- * All paths are normalized to POSIX format for consistent cache key matching.
3326
- * Uses Node.js normalize() + backslash replacement to match normalizePath from @soda-gql/common.
3327
- */
3328
- const resolveEntryPaths = (entries) => {
3329
- const resolvedPaths = entries.flatMap((entry) => {
3330
- const absolute = (0, node_path.resolve)(entry);
3331
- if ((0, node_fs.existsSync)(absolute)) {
3332
- return [(0, node_path.normalize)(absolute).replace(/\\/g, "/")];
3333
- }
3334
- const matches = scanEntries(entry).map((match) => {
3335
- return (0, node_path.normalize)((0, node_path.resolve)(match)).replace(/\\/g, "/");
3336
- });
3337
- return matches;
3338
- });
3339
- if (resolvedPaths.length === 0) {
3340
- return (0, neverthrow.err)({
3341
- code: "ENTRY_NOT_FOUND",
3342
- message: `No entry files matched ${entries.join(", ")}`,
3343
- entry: entries.join(", ")
3344
- });
3345
- }
3346
- return (0, neverthrow.ok)(resolvedPaths);
3347
- };
3348
-
3349
- //#endregion
3350
- //#region packages/builder/src/tracker/file-tracker.ts
3351
- /**
3352
- * Create a file tracker that maintains in-memory state for change detection.
3353
- *
3354
- * The tracker keeps file metadata (mtime, size) in memory during the process lifetime
3355
- * and detects which files have been added, updated, or removed. State is scoped to
3356
- * the process and does not persist across restarts.
3357
- */
3358
- const createFileTracker = () => {
3359
- let currentScan = { files: new Map() };
3360
- let nextScan = null;
3361
- const scan = (extraPaths) => {
3362
- const allPathsToScan = new Set([...extraPaths, ...currentScan.files.keys()]);
3363
- const files = new Map();
3364
- for (const path of allPathsToScan) {
3365
- try {
3366
- const normalized = (0, __soda_gql_common.normalizePath)(path);
3367
- const stats = (0, node_fs.statSync)(normalized);
3368
- files.set(normalized, {
3369
- mtimeMs: stats.mtimeMs,
3370
- size: stats.size
3371
- });
3372
- } catch {}
3373
- }
3374
- nextScan = { files };
3375
- return (0, neverthrow.ok)(nextScan);
3376
- };
3377
- const detectChanges = () => {
3378
- const previous = currentScan;
3379
- const current = nextScan ?? currentScan;
3380
- const added = new Set();
3381
- const updated = new Set();
3382
- const removed = new Set();
3383
- for (const [path, currentMetadata] of current.files) {
3384
- const previousMetadata = previous.files.get(path);
3385
- if (!previousMetadata) {
3386
- added.add(path);
3387
- } else if (previousMetadata.mtimeMs !== currentMetadata.mtimeMs || previousMetadata.size !== currentMetadata.size) {
3388
- updated.add(path);
3389
- }
3390
- }
3391
- for (const path of previous.files.keys()) {
3392
- if (!current.files.has(path)) {
3393
- removed.add(path);
3394
- }
3395
- }
3396
- return {
3397
- added,
3398
- updated,
3399
- removed
3400
- };
3401
- };
3402
- const update = (scan$1) => {
3403
- currentScan = scan$1;
3404
- nextScan = null;
3405
- };
3406
- return {
3407
- scan,
3408
- detectChanges,
3409
- update
3410
- };
3411
- };
3412
- /**
3413
- * Check if a file diff is empty (no changes detected).
3414
- */
3415
- const isEmptyDiff = (diff) => {
3416
- return diff.added.size === 0 && diff.updated.size === 0 && diff.removed.size === 0;
3417
- };
3418
-
3419
- //#endregion
3420
- //#region packages/builder/src/session/dependency-validation.ts
3421
- const validateModuleDependencies = ({ analyses, graphqlSystemHelper }) => {
3422
- for (const analysis of analyses.values()) {
3423
- for (const { source, isTypeOnly } of analysis.imports) {
3424
- if (isTypeOnly) {
3425
- continue;
3426
- }
3427
- if ((0, __soda_gql_common.isRelativeSpecifier)(source)) {
3428
- if (graphqlSystemHelper.isGraphqlSystemImportSpecifier({
3429
- filePath: analysis.filePath,
3430
- specifier: source
3431
- })) {
3432
- continue;
3433
- }
3434
- const resolvedModule = (0, __soda_gql_common.resolveRelativeImportWithReferences)({
3435
- filePath: analysis.filePath,
3436
- specifier: source,
3437
- references: analyses
3438
- });
3439
- if (!resolvedModule) {
3440
- return (0, neverthrow.err)({
3441
- code: "MISSING_IMPORT",
3442
- chain: [analysis.filePath, source]
3443
- });
3444
- }
3445
- }
3446
- }
3447
- }
3448
- return (0, neverthrow.ok)(null);
3449
- };
3450
-
3451
- //#endregion
3452
- //#region packages/builder/src/session/module-adjacency.ts
3453
- /**
3454
- * Extract module-level adjacency from dependency graph.
3455
- * Returns Map of file path -> set of files that import it.
3456
- * All paths are normalized to POSIX format for consistent cache key matching.
3457
- */
3458
- const extractModuleAdjacency = ({ snapshots }) => {
3459
- const importsByModule = new Map();
3460
- for (const snapshot of snapshots.values()) {
3461
- const { normalizedFilePath, dependencies, analysis } = snapshot;
3462
- const imports = new Set();
3463
- for (const { resolvedPath } of dependencies) {
3464
- if (resolvedPath && resolvedPath !== normalizedFilePath && snapshots.has(resolvedPath)) {
3465
- imports.add(resolvedPath);
3466
- }
3467
- }
3468
- if (dependencies.length === 0 && analysis.imports.length > 0) {
3469
- for (const imp of analysis.imports) {
3470
- if (imp.isTypeOnly) {
3471
- continue;
3472
- }
3473
- const resolved = (0, __soda_gql_common.resolveRelativeImportWithReferences)({
3474
- filePath: normalizedFilePath,
3475
- specifier: imp.source,
3476
- references: snapshots
3477
- });
3478
- if (resolved) {
3479
- imports.add(resolved);
3480
- }
3481
- }
3482
- }
3483
- if (imports.size > 0) {
3484
- importsByModule.set(normalizedFilePath, imports);
3485
- }
3486
- }
3487
- const adjacency = new Map();
3488
- for (const [importer, imports] of importsByModule) {
3489
- for (const imported of imports) {
3490
- if (!adjacency.has(imported)) {
3491
- adjacency.set(imported, new Set());
3492
- }
3493
- adjacency.get(imported)?.add(importer);
3494
- }
3495
- }
3496
- for (const modulePath of snapshots.keys()) {
3497
- if (!adjacency.has(modulePath)) {
3498
- adjacency.set(modulePath, new Set());
3499
- }
3500
- }
3501
- return adjacency;
3502
- };
3503
- /**
3504
- * Collect all modules affected by changes, including transitive dependents.
3505
- * Uses BFS to traverse module adjacency graph.
3506
- * All paths are already normalized from extractModuleAdjacency.
3507
- */
3508
- const collectAffectedFiles = (input) => {
3509
- const { changedFiles, removedFiles, previousModuleAdjacency } = input;
3510
- const affected = new Set([...changedFiles, ...removedFiles]);
3511
- const queue = [...changedFiles];
3512
- const visited = new Set(changedFiles);
3513
- while (queue.length > 0) {
3514
- const current = queue.shift();
3515
- if (!current) break;
3516
- const dependents = previousModuleAdjacency.get(current);
3517
- if (dependents) {
3518
- for (const dependent of dependents) {
3519
- if (!visited.has(dependent)) {
3520
- visited.add(dependent);
3521
- affected.add(dependent);
3522
- queue.push(dependent);
3523
- }
3524
- }
3525
- }
3526
- }
3527
- return affected;
3528
- };
3529
-
3530
- //#endregion
3531
- //#region packages/builder/src/session/builder-session.ts
3532
- /**
3533
- * Singleton state for beforeExit handler registration.
3534
- * Ensures only one handler is registered regardless of how many sessions are created.
3535
- */
3536
- const exitHandlerState = {
3537
- registered: false,
3538
- factories: new Set()
3539
- };
3540
- /**
3541
- * Register a cache factory for save on process exit.
3542
- * Uses singleton pattern to prevent multiple handler registrations.
3543
- */
3544
- const registerExitHandler = (cacheFactory) => {
3545
- exitHandlerState.factories.add(cacheFactory);
3546
- if (!exitHandlerState.registered) {
3547
- exitHandlerState.registered = true;
3548
- process.on("beforeExit", () => {
3549
- for (const factory of exitHandlerState.factories) {
3550
- factory.save();
3551
- }
3552
- });
3553
- }
3554
- };
3555
- /**
3556
- * Unregister a cache factory from the exit handler.
3557
- */
3558
- const unregisterExitHandler = (cacheFactory) => {
3559
- exitHandlerState.factories.delete(cacheFactory);
3560
- };
3561
- /**
3562
- * Reset exit handler state for testing.
3563
- * @internal
3564
- */
3565
- const __resetExitHandlerForTests = () => {
3566
- exitHandlerState.registered = false;
3567
- exitHandlerState.factories.clear();
3568
- };
3569
- /**
3570
- * Create a new builder session.
3571
- *
3572
- * The session maintains in-memory state across builds to enable incremental processing.
3573
- */
3574
- const createBuilderSession = (options) => {
3575
- const config = options.config;
3576
- const evaluatorId = options.evaluatorId ?? "default";
3577
- const entrypoints = new Set(options.entrypointsOverride ?? config.include);
3578
- const state = {
3579
- gen: 0,
3580
- snapshots: new Map(),
3581
- moduleAdjacency: new Map(),
3582
- intermediateModules: new Map(),
3583
- lastArtifact: null,
3584
- lastIntermediateElements: null
3585
- };
3586
- const cacheFactory = createMemoryCache({
3587
- prefix: ["builder"],
3588
- persistence: {
3589
- enabled: true,
3590
- filePath: (0, node_path.join)(process.cwd(), "node_modules", ".cache", "soda-gql", "builder", "cache.json")
3591
- }
3592
- });
3593
- registerExitHandler(cacheFactory);
3594
- const graphqlHelper = createGraphqlSystemIdentifyHelper(config);
3595
- const ensureAstAnalyzer = (0, __soda_gql_common.cachedFn)(() => createAstAnalyzer({
3596
- analyzer: config.analyzer,
3597
- graphqlHelper
3598
- }));
3599
- const ensureDiscoveryCache = (0, __soda_gql_common.cachedFn)(() => createDiscoveryCache({
3600
- factory: cacheFactory,
3601
- analyzer: config.analyzer,
3602
- evaluatorId
3603
- }));
3604
- const ensureFileTracker = (0, __soda_gql_common.cachedFn)(() => createFileTracker());
3605
- /**
3606
- * Prepare build input. Shared between sync and async builds.
3607
- * Returns either a skip result or the input for buildGen.
3608
- */
3609
- const prepareBuildInput = (force) => {
3610
- const entryPathsResult = resolveEntryPaths(Array.from(entrypoints));
3611
- if (entryPathsResult.isErr()) {
3612
- return (0, neverthrow.err)(entryPathsResult.error);
3613
- }
3614
- const entryPaths = entryPathsResult.value;
3615
- const tracker = ensureFileTracker();
3616
- const scanResult = tracker.scan(entryPaths);
3617
- if (scanResult.isErr()) {
3618
- const trackerError = scanResult.error;
3619
- return (0, neverthrow.err)(builderErrors.discoveryIOError(trackerError.type === "scan-failed" ? trackerError.path : "unknown", `Failed to scan files: ${trackerError.message}`));
3620
- }
3621
- const currentScan = scanResult.value;
3622
- const diff = tracker.detectChanges();
3623
- const prepareResult = prepare({
3624
- diff,
3625
- entryPaths,
3626
- lastArtifact: state.lastArtifact,
3627
- force
3628
- });
3629
- if (prepareResult.isErr()) {
3630
- return (0, neverthrow.err)(prepareResult.error);
3631
- }
3632
- if (prepareResult.value.type === "should-skip") {
3633
- return (0, neverthrow.ok)({
3634
- type: "skip",
3635
- artifact: prepareResult.value.data.artifact
3636
- });
3637
- }
3638
- const { changedFiles, removedFiles } = prepareResult.value.data;
3639
- return (0, neverthrow.ok)({
3640
- type: "build",
3641
- input: {
3642
- entryPaths,
3643
- astAnalyzer: ensureAstAnalyzer(),
3644
- discoveryCache: ensureDiscoveryCache(),
3645
- changedFiles,
3646
- removedFiles,
3647
- previousModuleAdjacency: state.moduleAdjacency,
3648
- previousIntermediateModules: state.intermediateModules,
3649
- graphqlSystemPath: (0, node_path.resolve)(config.outdir, "index.ts"),
3650
- graphqlHelper
3651
- },
3652
- currentScan
3653
- });
3654
- };
3655
- /**
3656
- * Finalize build and update session state.
3657
- */
3658
- const finalizeBuild = (genResult, currentScan) => {
3659
- const { snapshots, analyses, currentModuleAdjacency, intermediateModules, elements, stats } = genResult;
3660
- const artifactResult = buildArtifact({
3661
- analyses,
3662
- elements,
3663
- stats
3664
- });
3665
- if (artifactResult.isErr()) {
3666
- return (0, neverthrow.err)(artifactResult.error);
3667
- }
3668
- state.gen++;
3669
- state.snapshots = snapshots;
3670
- state.moduleAdjacency = currentModuleAdjacency;
3671
- state.lastArtifact = artifactResult.value;
3672
- state.intermediateModules = intermediateModules;
3673
- state.lastIntermediateElements = elements;
3674
- ensureFileTracker().update(currentScan);
3675
- return (0, neverthrow.ok)(artifactResult.value);
3676
- };
3677
- /**
3678
- * Synchronous build using SyncScheduler.
3679
- * Throws if any element requires async operations.
3680
- */
3681
- const build = (options$1) => {
3682
- const prepResult = prepareBuildInput(options$1?.force ?? false);
3683
- if (prepResult.isErr()) {
3684
- return (0, neverthrow.err)(prepResult.error);
3685
- }
3686
- if (prepResult.value.type === "skip") {
3687
- return (0, neverthrow.ok)(prepResult.value.artifact);
3688
- }
3689
- const { input, currentScan } = prepResult.value;
3690
- const scheduler = (0, __soda_gql_common.createSyncScheduler)();
3691
- try {
3692
- const result = scheduler.run(() => buildGen(input));
3693
- if (result.isErr()) {
3694
- return (0, neverthrow.err)(convertSchedulerError(result.error));
3695
- }
3696
- return finalizeBuild(result.value, currentScan);
3697
- } catch (error) {
3698
- if (error && typeof error === "object" && "code" in error) {
3699
- return (0, neverthrow.err)(error);
3700
- }
3701
- throw error;
3702
- }
3703
- };
3704
- /**
3705
- * Asynchronous build using AsyncScheduler.
3706
- * Supports async metadata factories and parallel element evaluation.
3707
- */
3708
- const buildAsync = async (options$1) => {
3709
- const prepResult = prepareBuildInput(options$1?.force ?? false);
3710
- if (prepResult.isErr()) {
3711
- return (0, neverthrow.err)(prepResult.error);
3712
- }
3713
- if (prepResult.value.type === "skip") {
3714
- return (0, neverthrow.ok)(prepResult.value.artifact);
3715
- }
3716
- const { input, currentScan } = prepResult.value;
3717
- const scheduler = (0, __soda_gql_common.createAsyncScheduler)();
3718
- try {
3719
- const result = await scheduler.run(() => buildGen(input));
3720
- if (result.isErr()) {
3721
- return (0, neverthrow.err)(convertSchedulerError(result.error));
3722
- }
3723
- return finalizeBuild(result.value, currentScan);
3724
- } catch (error) {
3725
- if (error && typeof error === "object" && "code" in error) {
3726
- return (0, neverthrow.err)(error);
3727
- }
3728
- throw error;
3729
- }
3730
- };
3731
- return {
3732
- build,
3733
- buildAsync,
3734
- getGeneration: () => state.gen,
3735
- getCurrentArtifact: () => state.lastArtifact,
3736
- getIntermediateElements: () => state.lastIntermediateElements,
3737
- dispose: () => {
3738
- cacheFactory.save();
3739
- unregisterExitHandler(cacheFactory);
3740
- }
3741
- };
3742
- };
3743
- const prepare = (input) => {
3744
- const { diff, lastArtifact, force } = input;
3745
- const changedFiles = new Set([...diff.added, ...diff.updated]);
3746
- const removedFiles = diff.removed;
3747
- if (!force && isEmptyDiff(diff) && lastArtifact) {
3748
- return (0, neverthrow.ok)({
3749
- type: "should-skip",
3750
- data: { artifact: lastArtifact }
3751
- });
3752
- }
3753
- return (0, neverthrow.ok)({
3754
- type: "should-build",
3755
- data: {
3756
- changedFiles,
3757
- removedFiles
3758
- }
3759
- });
3760
- };
3761
- /**
3762
- * Unified build generator that yields effects for file I/O and element evaluation.
3763
- * This enables single scheduler control at the root level for both sync and async execution.
3764
- */
3765
- function* buildGen(input) {
3766
- const { entryPaths, astAnalyzer, discoveryCache, changedFiles, removedFiles, previousModuleAdjacency, previousIntermediateModules, graphqlSystemPath, graphqlHelper } = input;
3767
- const affectedFiles = collectAffectedFiles({
3768
- changedFiles,
3769
- removedFiles,
3770
- previousModuleAdjacency
3771
- });
3772
- const discoveryResult = yield* discoverModulesGen({
3773
- entryPaths,
3774
- astAnalyzer,
3775
- incremental: {
3776
- cache: discoveryCache,
3777
- changedFiles,
3778
- removedFiles,
3779
- affectedFiles
3780
- }
3781
- });
3782
- const { cacheHits, cacheMisses, cacheSkips } = discoveryResult;
3783
- const snapshots = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot]));
3784
- const analyses = new Map(discoveryResult.snapshots.map((snapshot) => [snapshot.normalizedFilePath, snapshot.analysis]));
3785
- const dependenciesValidationResult = validateModuleDependencies({
3786
- analyses,
3787
- graphqlSystemHelper: graphqlHelper
3788
- });
3789
- if (dependenciesValidationResult.isErr()) {
3790
- const error = dependenciesValidationResult.error;
3791
- throw builderErrors.graphMissingImport(error.chain[0], error.chain[1]);
3792
- }
3793
- const currentModuleAdjacency = extractModuleAdjacency({ snapshots });
3794
- const stats = {
3795
- hits: cacheHits,
3796
- misses: cacheMisses,
3797
- skips: cacheSkips
3798
- };
3799
- const intermediateModules = new Map(previousIntermediateModules);
3800
- const targetFiles = new Set(affectedFiles);
3801
- for (const filePath of analyses.keys()) {
3802
- if (!previousIntermediateModules.has(filePath)) {
3803
- targetFiles.add(filePath);
3804
- }
3805
- }
3806
- if (targetFiles.size === 0) {
3807
- for (const filePath of analyses.keys()) {
3808
- targetFiles.add(filePath);
3809
- }
3810
- }
3811
- for (const targetFilePath of targetFiles) {
3812
- intermediateModules.delete(targetFilePath);
3813
- }
3814
- for (const intermediateModule of generateIntermediateModules({
3815
- analyses,
3816
- targetFiles,
3817
- graphqlSystemPath
3818
- })) {
3819
- intermediateModules.set(intermediateModule.filePath, intermediateModule);
3820
- }
3821
- const elements = yield* evaluateIntermediateModulesGen({
3822
- intermediateModules,
3823
- graphqlSystemPath,
3824
- analyses
3825
- });
3826
- return {
3827
- snapshots,
3828
- analyses,
3829
- currentModuleAdjacency,
3830
- intermediateModules,
3831
- elements,
3832
- stats
3833
- };
3834
- }
3835
- /**
3836
- * Convert scheduler error to builder error.
3837
- * If the cause is already a BuilderError, return it directly to preserve error codes.
3838
- */
3839
- const convertSchedulerError = (error) => {
3840
- if (error.cause && typeof error.cause === "object" && "code" in error.cause) {
3841
- return error.cause;
3842
- }
3843
- return builderErrors.internalInvariant(error.message, "scheduler", error.cause);
3844
- };
3845
-
3846
- //#endregion
3847
- //#region packages/builder/src/service.ts
3848
- /**
3849
- * Create a builder service instance with session support.
3850
- *
3851
- * The service maintains a long-lived session for incremental builds.
3852
- * File changes are automatically detected using an internal file tracker.
3853
- * First build() call initializes the session, subsequent calls perform
3854
- * incremental builds based on detected file changes.
3855
- *
3856
- * Note: Empty entry arrays will produce ENTRY_NOT_FOUND errors at build time.
3857
- *
3858
- * @param config - Builder configuration including entry patterns, analyzer, mode, and optional debugDir
3859
- * @returns BuilderService instance
3860
- */
3861
- const createBuilderService = ({ config, entrypointsOverride }) => {
3862
- const session = createBuilderSession({
3863
- config,
3864
- entrypointsOverride
3865
- });
3866
- return {
3867
- build: (options) => session.build(options),
3868
- buildAsync: (options) => session.buildAsync(options),
3869
- getGeneration: () => session.getGeneration(),
3870
- getCurrentArtifact: () => session.getCurrentArtifact(),
3871
- getIntermediateElements: () => session.getIntermediateElements(),
3872
- dispose: () => session.dispose()
3873
- };
157
+ return (0, neverthrow.ok)(schemas);
3874
158
  };
3875
159
 
3876
160
  //#endregion
3877
- exports.BuilderArtifactSchema = BuilderArtifactSchema;
3878
- exports.BuilderEffects = BuilderEffects;
3879
- exports.FileReadEffect = FileReadEffect;
3880
- exports.FileStatEffect = FileStatEffect;
3881
- exports.__clearGqlCache = __clearGqlCache;
3882
- exports.builderErrors = builderErrors;
3883
- exports.collectAffectedFiles = collectAffectedFiles;
3884
- exports.createBuilderService = createBuilderService;
3885
- exports.createBuilderSession = createBuilderSession;
3886
- exports.createGraphqlSystemIdentifyHelper = createGraphqlSystemIdentifyHelper;
161
+ exports.BuilderArtifactSchema = require_service.BuilderArtifactSchema;
162
+ exports.BuilderEffects = require_service.BuilderEffects;
163
+ exports.FileReadEffect = require_service.FileReadEffect;
164
+ exports.FileStatEffect = require_service.FileStatEffect;
165
+ exports.__clearGqlCache = require_service.__clearGqlCache;
166
+ exports.builderErrors = require_service.builderErrors;
167
+ exports.collectAffectedFiles = require_service.collectAffectedFiles;
168
+ exports.createBuilderService = require_service.createBuilderService;
169
+ exports.createBuilderSession = require_service.createBuilderSession;
170
+ exports.createDiagnostic = require_service.createDiagnostic;
171
+ exports.createGraphqlSystemIdentifyHelper = require_service.createGraphqlSystemIdentifyHelper;
172
+ exports.createStandardDiagnostic = require_service.createStandardDiagnostic;
173
+ exports.diagnosticMessages = require_service.diagnosticMessages;
3887
174
  exports.extractFieldSelections = extractFieldSelections;
3888
- exports.extractModuleAdjacency = extractModuleAdjacency;
3889
- exports.formatBuilderErrorForCLI = formatBuilderErrorForCLI;
3890
- exports.formatBuilderErrorStructured = formatBuilderErrorStructured;
3891
- exports.loadArtifact = loadArtifact;
3892
- exports.loadArtifactSync = loadArtifactSync;
175
+ exports.extractModuleAdjacency = require_service.extractModuleAdjacency;
176
+ exports.formatBuilderErrorForCLI = require_service.formatBuilderErrorForCLI;
177
+ exports.formatBuilderErrorStructured = require_service.formatBuilderErrorStructured;
178
+ exports.getSeverity = require_service.getSeverity;
179
+ exports.loadArtifact = require_service.loadArtifact;
180
+ exports.loadArtifactSync = require_service.loadArtifactSync;
3893
181
  exports.loadSchemasFromBundle = loadSchemasFromBundle;
3894
182
  //# sourceMappingURL=index.cjs.map