@soda-gql/typegen 0.11.26 → 0.12.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,3 +1,30 @@
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
28
  let node_fs_promises = require("node:fs/promises");
2
29
  let node_path = require("node:path");
3
30
  let __soda_gql_builder = require("@soda-gql/builder");
@@ -5,7 +32,9 @@ let __soda_gql_core = require("@soda-gql/core");
5
32
  let graphql = require("graphql");
6
33
  let neverthrow = require("neverthrow");
7
34
  let node_fs = require("node:fs");
8
- let esbuild = require("esbuild");
35
+ let fast_glob = require("fast-glob");
36
+ fast_glob = __toESM(fast_glob);
37
+ let __swc_core = require("@swc/core");
9
38
 
10
39
  //#region packages/typegen/src/emitter.ts
11
40
  /**
@@ -214,7 +243,7 @@ const generateInputObjectTypeDefinitions = (schema, schemaName, inputNames) => {
214
243
  depthOverrides,
215
244
  formatters
216
245
  });
217
- lines.push(`type Input_${schemaName}_${inputName} = ${typeString};`);
246
+ lines.push(`export type Input_${schemaName}_${inputName} = ${typeString};`);
218
247
  }
219
248
  return lines;
220
249
  };
@@ -234,7 +263,7 @@ const generateTypesCode = (grouped, schemas, injectsModulePath) => {
234
263
  " * @generated",
235
264
  " */",
236
265
  "",
237
- "import type { PrebuiltTypeRegistry } from \"@soda-gql/core\";"
266
+ "import type { AssertExtends, PrebuiltTypeRegistry } from \"@soda-gql/core\";"
238
267
  ];
239
268
  const scalarImports = schemaNames.map((name) => `scalar_${name}`).join(", ");
240
269
  lines.push(`import type { ${scalarImports} } from "${injectsModulePath}";`);
@@ -252,8 +281,16 @@ const generateTypesCode = (grouped, schemas, injectsModulePath) => {
252
281
  lines.push(...inputTypeLines);
253
282
  lines.push("");
254
283
  }
255
- const fragmentEntries = fragments.sort((a, b) => a.key.localeCompare(b.key)).map((f) => ` readonly "${f.key}": { readonly typename: "${f.typename}"; readonly input: ${f.inputType}; readonly output: ${f.outputType} };`);
256
- const operationEntries = operations.sort((a, b) => a.key.localeCompare(b.key)).map((o) => ` readonly "${o.key}": { readonly input: ${o.inputType}; readonly output: ${o.outputType} };`);
284
+ const deduplicatedFragments = new Map();
285
+ for (const f of fragments) {
286
+ deduplicatedFragments.set(f.key, f);
287
+ }
288
+ const fragmentEntries = Array.from(deduplicatedFragments.values()).sort((a, b) => a.key.localeCompare(b.key)).map((f) => ` readonly "${f.key}": { readonly typename: "${f.typename}"; readonly input: ${f.inputType}; readonly output: ${f.outputType} };`);
289
+ const deduplicatedOperations = new Map();
290
+ for (const o of operations) {
291
+ deduplicatedOperations.set(o.key, o);
292
+ }
293
+ const operationEntries = Array.from(deduplicatedOperations.values()).sort((a, b) => a.key.localeCompare(b.key)).map((o) => ` readonly "${o.key}": { readonly input: ${o.inputType}; readonly output: ${o.outputType} };`);
257
294
  lines.push(`export type PrebuiltTypes_${schemaName} = {`);
258
295
  lines.push(" readonly fragments: {");
259
296
  if (fragmentEntries.length > 0) {
@@ -266,12 +303,13 @@ const generateTypesCode = (grouped, schemas, injectsModulePath) => {
266
303
  }
267
304
  lines.push(" };");
268
305
  lines.push("};");
306
+ lines.push(`type _AssertPrebuiltTypes_${schemaName} = AssertExtends<PrebuiltTypes_${schemaName}, PrebuiltTypeRegistry>;`);
269
307
  lines.push("");
270
308
  }
271
309
  return lines.join("\n");
272
310
  };
273
311
  /**
274
- * Emit prebuilt types to the prebuilt/types.ts file.
312
+ * Emit prebuilt types to the types.prebuilt.ts file.
275
313
  *
276
314
  * This function uses a partial failure strategy: if type calculation fails for
277
315
  * individual elements (e.g., due to invalid field selections or missing schema
@@ -340,18 +378,6 @@ const typegenErrors = {
340
378
  code: "TYPEGEN_BUILD_FAILED",
341
379
  message,
342
380
  cause
343
- }),
344
- emitFailed: (path, message, cause) => ({
345
- code: "TYPEGEN_EMIT_FAILED",
346
- message,
347
- path,
348
- cause
349
- }),
350
- bundleFailed: (path, message, cause) => ({
351
- code: "TYPEGEN_BUNDLE_FAILED",
352
- message,
353
- path,
354
- cause
355
381
  })
356
382
  };
357
383
  /**
@@ -368,10 +394,6 @@ const formatTypegenError = (error) => {
368
394
  case "TYPEGEN_SCHEMA_LOAD_FAILED":
369
395
  lines.push(` Schemas: ${error.schemaNames.join(", ")}`);
370
396
  break;
371
- case "TYPEGEN_EMIT_FAILED":
372
- case "TYPEGEN_BUNDLE_FAILED":
373
- lines.push(` Path: ${error.path}`);
374
- break;
375
397
  }
376
398
  if ("cause" in error && error.cause) {
377
399
  lines.push(` Caused by: ${error.cause}`);
@@ -380,192 +402,461 @@ const formatTypegenError = (error) => {
380
402
  };
381
403
 
382
404
  //#endregion
383
- //#region packages/typegen/src/prebuilt-generator.ts
405
+ //#region packages/typegen/src/template-extractor.ts
406
+ const OPERATION_KINDS = new Set([
407
+ "query",
408
+ "mutation",
409
+ "subscription",
410
+ "fragment"
411
+ ]);
412
+ const isOperationKind = (value) => OPERATION_KINDS.has(value);
384
413
  /**
385
- * Generate the prebuilt index module code.
386
- *
387
- * Generates index.prebuilt.ts with builder-level type resolution.
388
- * Types are resolved at the fragment/operation builder level using TKey/TName,
389
- * eliminating the need for ResolvePrebuiltElement at the composer level.
414
+ * Parse TypeScript source with SWC, returning null on failure.
390
415
  */
391
- const generatePrebuiltModule = (schemas, options) => {
392
- const schemaNames = Array.from(schemas.keys());
393
- const injection = options.injection ?? new Map();
394
- const adapterImports = [];
395
- for (const name of schemaNames) {
396
- const config = injection.get(name);
397
- if (config?.hasAdapter) {
398
- adapterImports.push(`adapter_${name}`);
399
- }
400
- }
401
- const internalImports = schemaNames.flatMap((name) => [
402
- `__schema_${name}`,
403
- `__inputTypeMethods_${name}`,
404
- `__directiveMethods_${name}`
405
- ]);
406
- const genericTypes = `
416
+ const safeParseSync = (source, tsx) => {
417
+ try {
418
+ return (0, __swc_core.parseSync)(source, {
419
+ syntax: "typescript",
420
+ tsx,
421
+ decorators: false,
422
+ dynamicImport: true
423
+ });
424
+ } catch {
425
+ return null;
426
+ }
427
+ };
407
428
  /**
408
- * Generic field factory for type-erased field access.
409
- * Returns a callable for nested field builders. Primitive fields can be spread directly.
410
- * Runtime behavior differs but spread works for both: ...f.id() and ...f.user()(...)
411
- */
412
- type GenericFieldFactory = (
413
- ...args: unknown[]
414
- ) => (nest: (tools: GenericFieldsBuilderTools) => AnyFields) => AnyFields;
415
-
429
+ * Collect gql identifiers from import declarations.
430
+ * Finds imports like `import { gql } from "./graphql-system"`.
431
+ */
432
+ const collectGqlIdentifiers = (module$1, filePath, helper) => {
433
+ const identifiers = new Set();
434
+ for (const item of module$1.body) {
435
+ let declaration = null;
436
+ if (item.type === "ImportDeclaration") {
437
+ declaration = item;
438
+ } else if ("declaration" in item && item.declaration && item.declaration.type === "ImportDeclaration") {
439
+ declaration = item.declaration;
440
+ }
441
+ if (!declaration) {
442
+ continue;
443
+ }
444
+ if (!helper.isGraphqlSystemImportSpecifier({
445
+ filePath,
446
+ specifier: declaration.source.value
447
+ })) {
448
+ continue;
449
+ }
450
+ for (const specifier of declaration.specifiers ?? []) {
451
+ if (specifier.type === "ImportSpecifier") {
452
+ const imported = specifier.imported ? specifier.imported.value : specifier.local.value;
453
+ if (imported === "gql" && !specifier.imported) {
454
+ identifiers.add(specifier.local.value);
455
+ }
456
+ }
457
+ }
458
+ }
459
+ return identifiers;
460
+ };
416
461
  /**
417
- * Generic tools for fields builder callbacks.
418
- * Uses type-erased factory to allow any field access while maintaining strict mode compatibility.
419
- */
420
- type GenericFieldsBuilderTools = {
421
- readonly f: Record<string, GenericFieldFactory>;
422
- readonly $: Record<string, unknown>;
462
+ * Check if a call expression is a gql.{schemaName}(...) call.
463
+ * Returns the schema name if it is, null otherwise.
464
+ */
465
+ const getGqlCallSchemaName = (identifiers, call) => {
466
+ const callee = call.callee;
467
+ if (callee.type !== "MemberExpression") {
468
+ return null;
469
+ }
470
+ const member = callee;
471
+ if (member.object.type !== "Identifier" || !identifiers.has(member.object.value)) {
472
+ return null;
473
+ }
474
+ if (member.property.type !== "Identifier") {
475
+ return null;
476
+ }
477
+ const firstArg = call.arguments[0];
478
+ if (!firstArg?.expression || firstArg.expression.type !== "ArrowFunctionExpression") {
479
+ return null;
480
+ }
481
+ return member.property.value;
423
482
  };
424
- `;
425
- const contextTypes = schemaNames.map((name) => `
426
483
  /**
427
- * Resolve fragment types at builder level using TKey.
428
- * If TKey is a known key in PrebuiltTypes, return resolved types.
429
- * Otherwise, return PrebuiltEntryNotFound.
430
- */
431
- type ResolveFragmentAtBuilder_${name}<
432
- TKey extends string | undefined
433
- > = TKey extends keyof PrebuiltTypes_${name}["fragments"]
434
- ? Fragment<
435
- PrebuiltTypes_${name}["fragments"][TKey]["typename"],
436
- PrebuiltTypes_${name}["fragments"][TKey]["input"] extends infer TInput
437
- ? TInput extends void ? void : Partial<TInput & object>
438
- : void,
439
- Partial<AnyFields>,
440
- PrebuiltTypes_${name}["fragments"][TKey]["output"] & object
441
- >
442
- : TKey extends undefined
443
- ? Fragment<"(unknown)", PrebuiltEntryNotFound<"(undefined)", "fragment">, Partial<AnyFields>, PrebuiltEntryNotFound<"(undefined)", "fragment">>
444
- : Fragment<"(unknown)", PrebuiltEntryNotFound<TKey & string, "fragment">, Partial<AnyFields>, PrebuiltEntryNotFound<TKey & string, "fragment">>;
445
-
484
+ * Extract templates from a gql callback's arrow function body.
485
+ * Handles both expression bodies and block bodies with return statements.
486
+ */
487
+ const extractTemplatesFromCallback = (arrow, schemaName) => {
488
+ const templates = [];
489
+ const processExpression = (expr) => {
490
+ if (expr.type === "TaggedTemplateExpression") {
491
+ const tagged = expr;
492
+ extractFromTaggedTemplate(tagged, schemaName, templates);
493
+ return;
494
+ }
495
+ if (expr.type === "CallExpression") {
496
+ const call = expr;
497
+ if (call.callee.type === "TaggedTemplateExpression") {
498
+ extractFromTaggedTemplate(call.callee, schemaName, templates);
499
+ }
500
+ }
501
+ };
502
+ if (arrow.body.type !== "BlockStatement") {
503
+ processExpression(arrow.body);
504
+ return templates;
505
+ }
506
+ for (const stmt of arrow.body.stmts) {
507
+ if (stmt.type === "ReturnStatement" && stmt.argument) {
508
+ processExpression(stmt.argument);
509
+ }
510
+ }
511
+ return templates;
512
+ };
513
+ const extractFromTaggedTemplate = (tagged, schemaName, templates) => {
514
+ let kind;
515
+ let elementName;
516
+ let typeName;
517
+ if (tagged.tag.type === "Identifier") {
518
+ kind = tagged.tag.value;
519
+ } else if (tagged.tag.type === "CallExpression") {
520
+ const tagCall = tagged.tag;
521
+ if (tagCall.callee.type === "Identifier") {
522
+ kind = tagCall.callee.value;
523
+ } else {
524
+ return;
525
+ }
526
+ const firstArg = tagCall.arguments[0]?.expression;
527
+ if (firstArg?.type === "StringLiteral") {
528
+ elementName = firstArg.value;
529
+ }
530
+ const secondArg = tagCall.arguments[1]?.expression;
531
+ if (secondArg?.type === "StringLiteral") {
532
+ typeName = secondArg.value;
533
+ }
534
+ } else {
535
+ return;
536
+ }
537
+ if (!isOperationKind(kind)) {
538
+ return;
539
+ }
540
+ const { quasis, expressions } = tagged.template;
541
+ if (tagged.tag.type === "Identifier" && expressions.length > 0) {
542
+ return;
543
+ }
544
+ if (quasis.length === 0) {
545
+ return;
546
+ }
547
+ let content;
548
+ if (expressions.length === 0) {
549
+ const quasi = quasis[0];
550
+ if (!quasi) return;
551
+ content = quasi.cooked ?? quasi.raw;
552
+ } else {
553
+ const parts = [];
554
+ for (let i = 0; i < quasis.length; i++) {
555
+ const quasi = quasis[i];
556
+ if (!quasi) continue;
557
+ parts.push(quasi.cooked ?? quasi.raw);
558
+ if (i < expressions.length) {
559
+ parts.push(`__FRAG_SPREAD_${i}__`);
560
+ }
561
+ }
562
+ content = parts.join("");
563
+ }
564
+ templates.push({
565
+ schemaName,
566
+ kind,
567
+ content,
568
+ ...elementName !== undefined ? { elementName } : {},
569
+ ...typeName !== undefined ? { typeName } : {}
570
+ });
571
+ };
446
572
  /**
447
- * Resolve operation types at builder level using TName.
448
- */
449
- type ResolveOperationAtBuilder_${name}<
450
- TOperationType extends OperationType,
451
- TName extends string
452
- > = TName extends keyof PrebuiltTypes_${name}["operations"]
453
- ? Operation<
454
- TOperationType,
455
- TName,
456
- string[],
457
- PrebuiltTypes_${name}["operations"][TName]["input"] & AnyConstAssignableInput,
458
- Partial<AnyFields>,
459
- PrebuiltTypes_${name}["operations"][TName]["output"] & object
460
- >
461
- : Operation<
462
- TOperationType,
463
- TName,
464
- string[],
465
- PrebuiltEntryNotFound<TName, "operation">,
466
- Partial<AnyFields>,
467
- PrebuiltEntryNotFound<TName, "operation">
468
- >;
469
-
573
+ * Find the innermost gql call, unwrapping method chains like .attach().
574
+ */
575
+ const findGqlCall = (identifiers, node) => {
576
+ if (!node || node.type !== "CallExpression") {
577
+ return null;
578
+ }
579
+ const call = node;
580
+ if (getGqlCallSchemaName(identifiers, call) !== null) {
581
+ return call;
582
+ }
583
+ const callee = call.callee;
584
+ if (callee.type !== "MemberExpression") {
585
+ return null;
586
+ }
587
+ return findGqlCall(identifiers, callee.object);
588
+ };
470
589
  /**
471
- * Fragment builder that resolves types at builder level using TKey.
472
- */
473
- type PrebuiltFragmentBuilder_${name} = <TKey extends string | undefined = undefined>(
474
- options: {
475
- key?: TKey;
476
- fields: (tools: GenericFieldsBuilderTools) => AnyFields;
477
- variables?: Record<string, unknown>;
478
- metadata?: unknown;
479
- }
480
- ) => ResolveFragmentAtBuilder_${name}<TKey>;
481
-
590
+ * Walk AST to find gql calls and extract templates.
591
+ */
592
+ const walkAndExtract = (node, identifiers) => {
593
+ const templates = [];
594
+ const visit = (n) => {
595
+ if (!n || typeof n !== "object") {
596
+ return;
597
+ }
598
+ if ("type" in n && n.type === "CallExpression") {
599
+ const gqlCall = findGqlCall(identifiers, n);
600
+ if (gqlCall) {
601
+ const schemaName = getGqlCallSchemaName(identifiers, gqlCall);
602
+ if (schemaName) {
603
+ const arrow = gqlCall.arguments[0]?.expression;
604
+ templates.push(...extractTemplatesFromCallback(arrow, schemaName));
605
+ }
606
+ return;
607
+ }
608
+ }
609
+ if (Array.isArray(n)) {
610
+ for (const item of n) {
611
+ visit(item);
612
+ }
613
+ return;
614
+ }
615
+ for (const key of Object.keys(n)) {
616
+ if (key === "span" || key === "type") {
617
+ continue;
618
+ }
619
+ const value = n[key];
620
+ if (value && typeof value === "object") {
621
+ visit(value);
622
+ }
623
+ }
624
+ };
625
+ visit(node);
626
+ return templates;
627
+ };
482
628
  /**
483
- * Operation builder that resolves types at builder level using TName.
484
- */
485
- type PrebuiltOperationBuilder_${name}<TOperationType extends OperationType> = <TName extends string>(
486
- options: {
487
- name: TName;
488
- fields: (tools: GenericFieldsBuilderTools) => AnyFields;
489
- variables?: Record<string, unknown>;
490
- metadata?: unknown;
491
- }
492
- ) => ResolveOperationAtBuilder_${name}<TOperationType, TName>;
629
+ * Extract all tagged templates from a TypeScript source file.
630
+ *
631
+ * @param filePath - Absolute path to the source file (used for import resolution)
632
+ * @param source - TypeScript source code
633
+ * @param helper - GraphQL system identifier for resolving gql imports
634
+ * @returns Extracted templates and any warnings
635
+ */
636
+ const extractTemplatesFromSource = (filePath, source, helper) => {
637
+ const warnings = [];
638
+ const isTsx = filePath.endsWith(".tsx");
639
+ const program = safeParseSync(source, isTsx);
640
+ if (!program || program.type !== "Module") {
641
+ if (source.includes("gql")) {
642
+ warnings.push(`[typegen-extract] Failed to parse ${filePath}`);
643
+ }
644
+ return {
645
+ templates: [],
646
+ warnings
647
+ };
648
+ }
649
+ const gqlIdentifiers = collectGqlIdentifiers(program, filePath, helper);
650
+ if (gqlIdentifiers.size === 0) {
651
+ return {
652
+ templates: [],
653
+ warnings
654
+ };
655
+ }
656
+ return {
657
+ templates: walkAndExtract(program, gqlIdentifiers),
658
+ warnings
659
+ };
660
+ };
493
661
 
662
+ //#endregion
663
+ //#region packages/typegen/src/template-scanner.ts
494
664
  /**
495
- * Prebuilt context with builder-level type resolution for schema "${name}".
496
- */
497
- type PrebuiltContext_${name} = {
498
- readonly fragment: { [K: string]: PrebuiltFragmentBuilder_${name} };
499
- readonly query: { readonly operation: PrebuiltOperationBuilder_${name}<"query"> };
500
- readonly mutation: { readonly operation: PrebuiltOperationBuilder_${name}<"mutation"> };
501
- readonly subscription: { readonly operation: PrebuiltOperationBuilder_${name}<"subscription"> };
502
- readonly $var: unknown;
503
- readonly $dir: StandardDirectives;
504
- readonly $colocate: unknown;
505
- };`).join("\n");
506
- const gqlEntries = schemaNames.map((name) => {
507
- const config = injection.get(name);
508
- const adapterLine = config?.hasAdapter ? `,\n adapter: adapter_${name}` : "";
509
- return ` ${name}: createGqlElementComposer(
510
- __schema_${name} as AnyGraphqlSchema,
511
- {
512
- inputTypeMethods: __inputTypeMethods_${name},
513
- directiveMethods: __directiveMethods_${name}${adapterLine}
514
- }
515
- ) as unknown as GqlComposer_${name}`;
516
- });
517
- const injectsImportSpecifiers = adapterImports.length > 0 ? adapterImports.join(", ") : "";
518
- const injectsImportLine = injectsImportSpecifiers ? `import { ${injectsImportSpecifiers} } from "${options.injectsModulePath}";` : "";
519
- const indexCode = `\
665
+ * Source file scanner for tagged template extraction.
666
+ *
667
+ * Discovers source files from config include/exclude patterns,
668
+ * reads them, and extracts tagged templates using the template extractor.
669
+ *
670
+ * @module
671
+ */
520
672
  /**
521
- * Prebuilt GQL module with builder-level type resolution.
522
- *
523
- * Types are resolved at the fragment/operation builder level using TKey/TName,
524
- * not at the composer level. This enables proper typing for builder arguments
525
- * and eliminates the need for ResolvePrebuiltElement.
526
- *
527
- * @module
528
- * @generated by @soda-gql/typegen
529
- */
530
-
531
- import {
532
- createGqlElementComposer,
533
- type AnyConstAssignableInput,
534
- type AnyFields,
535
- type AnyGraphqlSchema,
536
- type Fragment,
537
- type Operation,
538
- type OperationType,
539
- type PrebuiltEntryNotFound,
540
- type StandardDirectives,
541
- } from "@soda-gql/core";
542
- ${injectsImportLine}
543
- import { ${internalImports.join(", ")} } from "${options.internalModulePath}";
544
- import type { ${schemaNames.map((name) => `PrebuiltTypes_${name}`).join(", ")} } from "./types.prebuilt";
545
- ${genericTypes}
546
- ${contextTypes}
547
-
548
- // Export context types for explicit annotation
549
- ${schemaNames.map((name) => `export type { PrebuiltContext_${name} };`).join("\n")}
550
-
551
- // Composer type - TResult already has resolved types from builders, no ResolvePrebuiltElement needed
552
- ${schemaNames.map((name) => `type GqlComposer_${name} = {
553
- <TResult>(composeElement: (context: PrebuiltContext_${name}) => TResult): TResult;
554
- readonly $schema: AnyGraphqlSchema;
555
- };`).join("\n")}
673
+ * Scan source files for tagged templates.
674
+ *
675
+ * Uses fast-glob to discover files matching include/exclude patterns,
676
+ * then extracts tagged templates from each file.
677
+ */
678
+ const scanSourceFiles = (options) => {
679
+ const { include, exclude, baseDir, helper } = options;
680
+ const warnings = [];
681
+ const ignorePatterns = exclude.map((pattern) => pattern.startsWith("!") ? pattern.slice(1) : pattern);
682
+ const matchedFiles = fast_glob.default.sync(include, {
683
+ cwd: baseDir,
684
+ ignore: ignorePatterns,
685
+ onlyFiles: true,
686
+ absolute: true
687
+ });
688
+ const templates = new Map();
689
+ for (const filePath of matchedFiles) {
690
+ const normalizedPath = (0, node_path.normalize)((0, node_path.resolve)(filePath)).replace(/\\/g, "/");
691
+ try {
692
+ const source = (0, node_fs.readFileSync)(normalizedPath, "utf-8");
693
+ const { templates: extracted, warnings: extractionWarnings } = extractTemplatesFromSource(normalizedPath, source, helper);
694
+ warnings.push(...extractionWarnings);
695
+ if (extracted.length > 0) {
696
+ templates.set(normalizedPath, extracted);
697
+ }
698
+ } catch (error) {
699
+ const message = error instanceof Error ? error.message : String(error);
700
+ warnings.push(`[typegen-scan] Failed to read ${normalizedPath}: ${message}`);
701
+ }
702
+ }
703
+ return {
704
+ templates,
705
+ warnings
706
+ };
707
+ };
556
708
 
709
+ //#endregion
710
+ //#region packages/typegen/src/template-to-selections.ts
711
+ /**
712
+ * Convert extracted templates into field selections for the emitter.
713
+ *
714
+ * @param templates - Templates extracted from source files, keyed by file path
715
+ * @param schemas - Loaded schema objects keyed by schema name
716
+ * @returns Map of canonical IDs to field selection data, plus any warnings
717
+ */
718
+ const convertTemplatesToSelections = (templates, schemas) => {
719
+ const selections = new Map();
720
+ const warnings = [];
721
+ const schemaIndexes = new Map(Object.entries(schemas).map(([name, schema]) => [name, (0, __soda_gql_core.createSchemaIndexFromSchema)(schema)]));
722
+ for (const [filePath, fileTemplates] of templates) {
723
+ for (const template of fileTemplates) {
724
+ const schema = schemas[template.schemaName];
725
+ if (!schema) {
726
+ warnings.push(`[typegen-template] Unknown schema "${template.schemaName}" in ${filePath}`);
727
+ continue;
728
+ }
729
+ const schemaIndex = schemaIndexes.get(template.schemaName);
730
+ if (!schemaIndex) {
731
+ continue;
732
+ }
733
+ try {
734
+ if (template.kind === "fragment") {
735
+ const selection = convertFragmentTemplate(template, schema, filePath);
736
+ if (selection) {
737
+ selections.set(selection.id, selection.data);
738
+ }
739
+ } else {
740
+ const selection = convertOperationTemplate(template, schema, filePath);
741
+ if (selection) {
742
+ selections.set(selection.id, selection.data);
743
+ }
744
+ }
745
+ } catch (error) {
746
+ const message = error instanceof Error ? error.message : String(error);
747
+ warnings.push(`[typegen-template] Failed to process ${template.kind} in ${filePath}: ${message}`);
748
+ }
749
+ }
750
+ }
751
+ return {
752
+ selections,
753
+ warnings
754
+ };
755
+ };
756
+ /**
757
+ * Recursively filter out __FRAG_SPREAD_ placeholder nodes from a selection set.
758
+ * These placeholders are created by template-extractor for interpolated fragment references.
759
+ * buildFieldsFromSelectionSet would throw on them since no interpolationMap is available.
760
+ */
761
+ const filterPlaceholderSpreads = (selectionSet) => ({
762
+ ...selectionSet,
763
+ selections: selectionSet.selections.filter((sel) => !(sel.kind === graphql.Kind.FRAGMENT_SPREAD && sel.name.value.startsWith("__FRAG_SPREAD_"))).map((sel) => {
764
+ if (sel.kind === graphql.Kind.FIELD && sel.selectionSet) {
765
+ return {
766
+ ...sel,
767
+ selectionSet: filterPlaceholderSpreads(sel.selectionSet)
768
+ };
769
+ }
770
+ if (sel.kind === graphql.Kind.INLINE_FRAGMENT && sel.selectionSet) {
771
+ return {
772
+ ...sel,
773
+ selectionSet: filterPlaceholderSpreads(sel.selectionSet)
774
+ };
775
+ }
776
+ return sel;
777
+ })
778
+ });
557
779
  /**
558
- * Prebuilt GQL composers with builder-level type resolution.
559
- *
560
- * These composers have the same runtime behavior as the base composers,
561
- * but their return types are resolved from the prebuilt type registry
562
- * at the builder level instead of using ResolvePrebuiltElement.
563
- */
564
- export const gql: { ${schemaNames.map((name) => `${name}: GqlComposer_${name}`).join("; ")} } = {
565
- ${gqlEntries.join(",\n")}
780
+ * Reconstruct full GraphQL source from an extracted template.
781
+ * For curried syntax (new), prepends the definition header from tag call arguments.
782
+ * For old syntax, returns content as-is.
783
+ */
784
+ const reconstructGraphql = (template) => {
785
+ if (template.elementName) {
786
+ if (template.kind === "fragment" && template.typeName) {
787
+ return `fragment ${template.elementName} on ${template.typeName} ${template.content}`;
788
+ }
789
+ return `${template.kind} ${template.elementName} ${template.content}`;
790
+ }
791
+ return template.content;
566
792
  };
567
- `;
568
- return { indexCode };
793
+ /**
794
+ * Convert a fragment template into FieldSelectionData.
795
+ */
796
+ const convertFragmentTemplate = (template, schema, filePath) => {
797
+ const schemaIndex = (0, __soda_gql_core.createSchemaIndexFromSchema)(schema);
798
+ const graphqlSource = reconstructGraphql(template);
799
+ const variableDefinitions = (0, __soda_gql_core.extractFragmentVariables)(graphqlSource, schemaIndex);
800
+ const { preprocessed } = (0, __soda_gql_core.preprocessFragmentArgs)(graphqlSource);
801
+ const document = (0, graphql.parse)(preprocessed);
802
+ const fragDef = document.definitions.find((d) => d.kind === graphql.Kind.FRAGMENT_DEFINITION);
803
+ if (!fragDef || fragDef.kind !== graphql.Kind.FRAGMENT_DEFINITION) {
804
+ return null;
805
+ }
806
+ const fragmentName = fragDef.name.value;
807
+ const onType = fragDef.typeCondition.name.value;
808
+ const fields = (0, __soda_gql_core.buildFieldsFromSelectionSet)(filterPlaceholderSpreads(fragDef.selectionSet), schema, onType);
809
+ const id = `${filePath}::${fragmentName}`;
810
+ return {
811
+ id,
812
+ data: {
813
+ type: "fragment",
814
+ schemaLabel: schema.label,
815
+ key: fragmentName,
816
+ typename: onType,
817
+ fields,
818
+ variableDefinitions
819
+ }
820
+ };
821
+ };
822
+ /**
823
+ * Convert an operation template into FieldSelectionData.
824
+ */
825
+ const convertOperationTemplate = (template, schema, filePath) => {
826
+ const graphqlSource = reconstructGraphql(template);
827
+ const document = (0, graphql.parse)(graphqlSource);
828
+ const opDef = document.definitions.find((d) => d.kind === graphql.Kind.OPERATION_DEFINITION);
829
+ if (!opDef || opDef.kind !== graphql.Kind.OPERATION_DEFINITION) {
830
+ return null;
831
+ }
832
+ const operationName = opDef.name?.value ?? "Anonymous";
833
+ const operationType = opDef.operation;
834
+ const rootTypeName = getRootTypeName(schema, operationType);
835
+ const fields = (0, __soda_gql_core.buildFieldsFromSelectionSet)(filterPlaceholderSpreads(opDef.selectionSet), schema, rootTypeName);
836
+ const variableDefinitions = opDef.variableDefinitions ?? [];
837
+ const id = `${filePath}::${operationName}`;
838
+ return {
839
+ id,
840
+ data: {
841
+ type: "operation",
842
+ schemaLabel: schema.label,
843
+ operationName,
844
+ operationType,
845
+ fields,
846
+ variableDefinitions: [...variableDefinitions]
847
+ }
848
+ };
849
+ };
850
+ /**
851
+ * Get the root type name for an operation type from the schema.
852
+ */
853
+ const getRootTypeName = (schema, operationType) => {
854
+ switch (operationType) {
855
+ case "query": return schema.operations.query ?? "Query";
856
+ case "mutation": return schema.operations.mutation ?? "Mutation";
857
+ case "subscription": return schema.operations.subscription ?? "Subscription";
858
+ default: return "Query";
859
+ }
569
860
  };
570
861
 
571
862
  //#endregion
@@ -575,11 +866,10 @@ ${gqlEntries.join(",\n")}
575
866
  *
576
867
  * Orchestrates the prebuilt type generation process:
577
868
  * 1. Load schemas from generated CJS bundle
578
- * 2. Generate index.prebuilt.ts
579
- * 3. Build artifact to evaluate elements
580
- * 4. Extract field selections
869
+ * 2. Build artifact to evaluate elements
870
+ * 3. Extract field selections from builder
871
+ * 4. Scan source files for tagged templates and merge selections
581
872
  * 5. Emit types.prebuilt.ts
582
- * 6. Bundle prebuilt module
583
873
  *
584
874
  * @module
585
875
  */
@@ -621,58 +911,14 @@ const toImportSpecifier = (fromPath, targetPath, options) => {
621
911
  return `${withoutExt}${runtimeExt}`;
622
912
  };
623
913
  /**
624
- * Bundle the prebuilt module to CJS format.
625
- */
626
- const bundlePrebuiltModule = async (sourcePath) => {
627
- const sourceExt = (0, node_path.extname)(sourcePath);
628
- const baseName = sourcePath.slice(0, -sourceExt.length);
629
- const cjsPath = `${baseName}.cjs`;
630
- await (0, esbuild.build)({
631
- entryPoints: [sourcePath],
632
- outfile: cjsPath,
633
- format: "cjs",
634
- platform: "node",
635
- bundle: true,
636
- external: ["@soda-gql/core", "@soda-gql/runtime"],
637
- sourcemap: false,
638
- minify: false,
639
- treeShaking: false
640
- });
641
- return { cjsPath };
642
- };
643
- /**
644
- * Write a TypeScript module to disk.
645
- */
646
- const writeModule = async (path, content) => {
647
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
648
- await (0, node_fs_promises.writeFile)(path, content, "utf-8");
649
- };
650
- /**
651
- * Load GraphQL schema documents from schema paths.
652
- * This is needed for generatePrebuiltModule which expects DocumentNode.
653
- */
654
- const loadSchemaDocuments = (schemasConfig) => {
655
- const documents = new Map();
656
- for (const [name, schemaConfig] of Object.entries(schemasConfig)) {
657
- const schemaPaths = Array.isArray(schemaConfig.schema) ? schemaConfig.schema : [schemaConfig.schema];
658
- let combinedSource = "";
659
- for (const schemaPath of schemaPaths) {
660
- combinedSource += `${(0, node_fs.readFileSync)(schemaPath, "utf-8")}\n`;
661
- }
662
- documents.set(name, (0, graphql.parse)(combinedSource));
663
- }
664
- return documents;
665
- };
666
- /**
667
914
  * Run the typegen process.
668
915
  *
669
916
  * This function:
670
917
  * 1. Loads schemas from the generated CJS bundle
671
- * 2. Generates index.prebuilt.ts using generatePrebuiltModule
672
- * 3. Creates a BuilderService and builds the artifact
673
- * 4. Extracts field selections from the artifact
918
+ * 2. Creates a BuilderService and builds the artifact
919
+ * 3. Extracts field selections from the artifact
920
+ * 4. Scans source files for tagged templates and merges selections
674
921
  * 5. Emits types.prebuilt.ts using emitPrebuiltTypes
675
- * 6. Bundles the prebuilt module
676
922
  *
677
923
  * @param options - Typegen options including config
678
924
  * @returns Result containing success data or error
@@ -691,24 +937,8 @@ const runTypegen = async (options) => {
691
937
  return (0, neverthrow.err)(typegenErrors.schemaLoadFailed(schemaNames, schemasResult.error));
692
938
  }
693
939
  const schemas = schemasResult.value;
694
- const schemaDocuments = loadSchemaDocuments(config.schemas);
695
- const prebuiltIndexPath = (0, node_path.join)(outdir, "index.prebuilt.ts");
696
- const internalModulePath = toImportSpecifier(prebuiltIndexPath, (0, node_path.join)(outdir, "_internal.ts"), importSpecifierOptions);
697
- const injectsModulePath = toImportSpecifier(prebuiltIndexPath, (0, node_path.join)(outdir, "_internal-injects.ts"), importSpecifierOptions);
698
- const injection = new Map();
699
- for (const [schemaName, schemaConfig] of Object.entries(config.schemas)) {
700
- injection.set(schemaName, { hasAdapter: !!schemaConfig.inject.adapter });
701
- }
702
- const prebuilt = generatePrebuiltModule(schemaDocuments, {
703
- internalModulePath,
704
- injectsModulePath,
705
- injection
706
- });
707
- try {
708
- await writeModule(prebuiltIndexPath, prebuilt.indexCode);
709
- } catch (error) {
710
- return (0, neverthrow.err)(typegenErrors.emitFailed(prebuiltIndexPath, `Failed to write prebuilt index: ${error instanceof Error ? error.message : String(error)}`, error));
711
- }
940
+ const prebuiltTypesPath = (0, node_path.join)(outdir, "types.prebuilt.ts");
941
+ const injectsModulePath = toImportSpecifier(prebuiltTypesPath, (0, node_path.join)(outdir, "_internal-injects.ts"), importSpecifierOptions);
712
942
  const builderService = (0, __soda_gql_builder.createBuilderService)({ config });
713
943
  const artifactResult = await builderService.buildAsync();
714
944
  if (artifactResult.isErr()) {
@@ -719,7 +949,38 @@ const runTypegen = async (options) => {
719
949
  return (0, neverthrow.err)(typegenErrors.buildFailed("No intermediate elements available after build", undefined));
720
950
  }
721
951
  const fieldSelectionsResult = (0, __soda_gql_builder.extractFieldSelections)(intermediateElements);
722
- const { selections: fieldSelections, warnings: extractWarnings } = fieldSelectionsResult;
952
+ const { selections: builderSelections, warnings: extractWarnings } = fieldSelectionsResult;
953
+ const graphqlHelper = (0, __soda_gql_builder.createGraphqlSystemIdentifyHelper)(config);
954
+ const scanResult = scanSourceFiles({
955
+ include: [...config.include],
956
+ exclude: [...config.exclude],
957
+ baseDir: config.baseDir,
958
+ helper: graphqlHelper
959
+ });
960
+ const templateSelections = convertTemplatesToSelections(scanResult.templates, schemas);
961
+ const extractFilePart = (id) => {
962
+ const filePart = id.split("::")[0] ?? "";
963
+ if (filePart.startsWith("/")) {
964
+ return (0, node_path.relative)(config.baseDir, filePart);
965
+ }
966
+ return filePart;
967
+ };
968
+ const extractElementName = (data) => data.type === "fragment" ? data.key : data.operationName;
969
+ const templateElements = new Set();
970
+ for (const [id, data] of templateSelections.selections) {
971
+ const name = extractElementName(data);
972
+ if (name) templateElements.add(`${extractFilePart(id)}::${name}`);
973
+ }
974
+ const fieldSelections = new Map();
975
+ for (const [id, data] of builderSelections) {
976
+ const name = extractElementName(data);
977
+ if (name && templateElements.has(`${extractFilePart(id)}::${name}`)) continue;
978
+ fieldSelections.set(id, data);
979
+ }
980
+ for (const [id, data] of templateSelections.selections) {
981
+ fieldSelections.set(id, data);
982
+ }
983
+ const scanWarnings = [...scanResult.warnings, ...templateSelections.warnings];
723
984
  const emitResult = await emitPrebuiltTypes({
724
985
  schemas,
725
986
  fieldSelections,
@@ -729,12 +990,7 @@ const runTypegen = async (options) => {
729
990
  if (emitResult.isErr()) {
730
991
  return (0, neverthrow.err)(emitResult.error);
731
992
  }
732
- const { path: prebuiltTypesPath, warnings: emitWarnings } = emitResult.value;
733
- try {
734
- await bundlePrebuiltModule(prebuiltIndexPath);
735
- } catch (error) {
736
- return (0, neverthrow.err)(typegenErrors.bundleFailed(prebuiltIndexPath, `Failed to bundle prebuilt module: ${error instanceof Error ? error.message : String(error)}`, error));
737
- }
993
+ const { warnings: emitWarnings } = emitResult.value;
738
994
  let fragmentCount = 0;
739
995
  let operationCount = 0;
740
996
  for (const selection of fieldSelections.values()) {
@@ -744,9 +1000,12 @@ const runTypegen = async (options) => {
744
1000
  operationCount++;
745
1001
  }
746
1002
  }
747
- const allWarnings = [...extractWarnings, ...emitWarnings];
1003
+ const allWarnings = [
1004
+ ...extractWarnings,
1005
+ ...scanWarnings,
1006
+ ...emitWarnings
1007
+ ];
748
1008
  return (0, neverthrow.ok)({
749
- prebuiltIndexPath,
750
1009
  prebuiltTypesPath,
751
1010
  fragmentCount,
752
1011
  operationCount,
@@ -757,7 +1016,6 @@ const runTypegen = async (options) => {
757
1016
  //#endregion
758
1017
  exports.emitPrebuiltTypes = emitPrebuiltTypes;
759
1018
  exports.formatTypegenError = formatTypegenError;
760
- exports.generatePrebuiltModule = generatePrebuiltModule;
761
1019
  exports.runTypegen = runTypegen;
762
1020
  exports.typegenErrors = typegenErrors;
763
1021
  //# sourceMappingURL=index.cjs.map