@soda-gql/typegen 0.11.25 → 0.12.0
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 +505 -271
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -59
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +8 -59
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +482 -275
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -7
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { dirname, extname, join, relative, resolve } from "node:path";
|
|
3
|
-
import { builderErrors, createBuilderService, extractFieldSelections, loadSchemasFromBundle } from "@soda-gql/builder";
|
|
4
|
-
import { calculateFieldsType, generateInputObjectType, generateInputType, generateInputTypeFromVarDefs, parseInputSpecifier } from "@soda-gql/core";
|
|
1
|
+
import { writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, extname, join, normalize, relative, resolve } from "node:path";
|
|
3
|
+
import { builderErrors, createBuilderService, createGraphqlSystemIdentifyHelper, extractFieldSelections, loadSchemasFromBundle } from "@soda-gql/builder";
|
|
4
|
+
import { buildFieldsFromSelectionSet, calculateFieldsType, createSchemaIndexFromSchema, extractFragmentVariables, generateInputObjectType, generateInputType, generateInputTypeFromVarDefs, parseInputSpecifier, preprocessFragmentArgs } from "@soda-gql/core";
|
|
5
5
|
import { Kind, parse } from "graphql";
|
|
6
6
|
import { err, ok } from "neverthrow";
|
|
7
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
8
|
-
import
|
|
8
|
+
import fg from "fast-glob";
|
|
9
|
+
import { parseSync } from "@swc/core";
|
|
9
10
|
|
|
10
11
|
//#region packages/typegen/src/emitter.ts
|
|
11
12
|
/**
|
|
@@ -214,7 +215,7 @@ const generateInputObjectTypeDefinitions = (schema, schemaName, inputNames) => {
|
|
|
214
215
|
depthOverrides,
|
|
215
216
|
formatters
|
|
216
217
|
});
|
|
217
|
-
lines.push(`type Input_${schemaName}_${inputName} = ${typeString};`);
|
|
218
|
+
lines.push(`export type Input_${schemaName}_${inputName} = ${typeString};`);
|
|
218
219
|
}
|
|
219
220
|
return lines;
|
|
220
221
|
};
|
|
@@ -252,8 +253,16 @@ const generateTypesCode = (grouped, schemas, injectsModulePath) => {
|
|
|
252
253
|
lines.push(...inputTypeLines);
|
|
253
254
|
lines.push("");
|
|
254
255
|
}
|
|
255
|
-
const
|
|
256
|
-
|
|
256
|
+
const deduplicatedFragments = new Map();
|
|
257
|
+
for (const f of fragments) {
|
|
258
|
+
deduplicatedFragments.set(f.key, f);
|
|
259
|
+
}
|
|
260
|
+
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} };`);
|
|
261
|
+
const deduplicatedOperations = new Map();
|
|
262
|
+
for (const o of operations) {
|
|
263
|
+
deduplicatedOperations.set(o.key, o);
|
|
264
|
+
}
|
|
265
|
+
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
266
|
lines.push(`export type PrebuiltTypes_${schemaName} = {`);
|
|
258
267
|
lines.push(" readonly fragments: {");
|
|
259
268
|
if (fragmentEntries.length > 0) {
|
|
@@ -271,7 +280,7 @@ const generateTypesCode = (grouped, schemas, injectsModulePath) => {
|
|
|
271
280
|
return lines.join("\n");
|
|
272
281
|
};
|
|
273
282
|
/**
|
|
274
|
-
* Emit prebuilt types to the
|
|
283
|
+
* Emit prebuilt types to the types.prebuilt.ts file.
|
|
275
284
|
*
|
|
276
285
|
* This function uses a partial failure strategy: if type calculation fails for
|
|
277
286
|
* individual elements (e.g., due to invalid field selections or missing schema
|
|
@@ -340,18 +349,6 @@ const typegenErrors = {
|
|
|
340
349
|
code: "TYPEGEN_BUILD_FAILED",
|
|
341
350
|
message,
|
|
342
351
|
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
352
|
})
|
|
356
353
|
};
|
|
357
354
|
/**
|
|
@@ -368,10 +365,6 @@ const formatTypegenError = (error) => {
|
|
|
368
365
|
case "TYPEGEN_SCHEMA_LOAD_FAILED":
|
|
369
366
|
lines.push(` Schemas: ${error.schemaNames.join(", ")}`);
|
|
370
367
|
break;
|
|
371
|
-
case "TYPEGEN_EMIT_FAILED":
|
|
372
|
-
case "TYPEGEN_BUNDLE_FAILED":
|
|
373
|
-
lines.push(` Path: ${error.path}`);
|
|
374
|
-
break;
|
|
375
368
|
}
|
|
376
369
|
if ("cause" in error && error.cause) {
|
|
377
370
|
lines.push(` Caused by: ${error.cause}`);
|
|
@@ -380,192 +373,438 @@ const formatTypegenError = (error) => {
|
|
|
380
373
|
};
|
|
381
374
|
|
|
382
375
|
//#endregion
|
|
383
|
-
//#region packages/typegen/src/
|
|
376
|
+
//#region packages/typegen/src/template-extractor.ts
|
|
377
|
+
const OPERATION_KINDS = new Set([
|
|
378
|
+
"query",
|
|
379
|
+
"mutation",
|
|
380
|
+
"subscription",
|
|
381
|
+
"fragment"
|
|
382
|
+
]);
|
|
383
|
+
const isOperationKind = (value) => OPERATION_KINDS.has(value);
|
|
384
384
|
/**
|
|
385
|
-
*
|
|
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.
|
|
385
|
+
* Parse TypeScript source with SWC, returning null on failure.
|
|
390
386
|
*/
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
`__inputTypeMethods_${name}`,
|
|
404
|
-
`__directiveMethods_${name}`
|
|
405
|
-
]);
|
|
406
|
-
const genericTypes = `
|
|
387
|
+
const safeParseSync = (source, tsx) => {
|
|
388
|
+
try {
|
|
389
|
+
return parseSync(source, {
|
|
390
|
+
syntax: "typescript",
|
|
391
|
+
tsx,
|
|
392
|
+
decorators: false,
|
|
393
|
+
dynamicImport: true
|
|
394
|
+
});
|
|
395
|
+
} catch {
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
};
|
|
407
399
|
/**
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
400
|
+
* Collect gql identifiers from import declarations.
|
|
401
|
+
* Finds imports like `import { gql } from "./graphql-system"`.
|
|
402
|
+
*/
|
|
403
|
+
const collectGqlIdentifiers = (module, filePath, helper) => {
|
|
404
|
+
const identifiers = new Set();
|
|
405
|
+
for (const item of module.body) {
|
|
406
|
+
let declaration = null;
|
|
407
|
+
if (item.type === "ImportDeclaration") {
|
|
408
|
+
declaration = item;
|
|
409
|
+
} else if ("declaration" in item && item.declaration && item.declaration.type === "ImportDeclaration") {
|
|
410
|
+
declaration = item.declaration;
|
|
411
|
+
}
|
|
412
|
+
if (!declaration) {
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
if (!helper.isGraphqlSystemImportSpecifier({
|
|
416
|
+
filePath,
|
|
417
|
+
specifier: declaration.source.value
|
|
418
|
+
})) {
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
for (const specifier of declaration.specifiers ?? []) {
|
|
422
|
+
if (specifier.type === "ImportSpecifier") {
|
|
423
|
+
const imported = specifier.imported ? specifier.imported.value : specifier.local.value;
|
|
424
|
+
if (imported === "gql" && !specifier.imported) {
|
|
425
|
+
identifiers.add(specifier.local.value);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return identifiers;
|
|
431
|
+
};
|
|
416
432
|
/**
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
433
|
+
* Check if a call expression is a gql.{schemaName}(...) call.
|
|
434
|
+
* Returns the schema name if it is, null otherwise.
|
|
435
|
+
*/
|
|
436
|
+
const getGqlCallSchemaName = (identifiers, call) => {
|
|
437
|
+
const callee = call.callee;
|
|
438
|
+
if (callee.type !== "MemberExpression") {
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
const member = callee;
|
|
442
|
+
if (member.object.type !== "Identifier" || !identifiers.has(member.object.value)) {
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
if (member.property.type !== "Identifier") {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
const firstArg = call.arguments[0];
|
|
449
|
+
if (!firstArg?.expression || firstArg.expression.type !== "ArrowFunctionExpression") {
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
return member.property.value;
|
|
423
453
|
};
|
|
424
|
-
`;
|
|
425
|
-
const contextTypes = schemaNames.map((name) => `
|
|
426
454
|
/**
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
455
|
+
* Extract templates from a gql callback's arrow function body.
|
|
456
|
+
* Handles both expression bodies and block bodies with return statements.
|
|
457
|
+
*/
|
|
458
|
+
const extractTemplatesFromCallback = (arrow, schemaName) => {
|
|
459
|
+
const templates = [];
|
|
460
|
+
const processExpression = (expr) => {
|
|
461
|
+
if (expr.type === "TaggedTemplateExpression") {
|
|
462
|
+
const tagged = expr;
|
|
463
|
+
extractFromTaggedTemplate(tagged, schemaName, templates);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (expr.type === "CallExpression") {
|
|
467
|
+
const call = expr;
|
|
468
|
+
if (call.callee.type === "TaggedTemplateExpression") {
|
|
469
|
+
extractFromTaggedTemplate(call.callee, schemaName, templates);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
if (arrow.body.type !== "BlockStatement") {
|
|
474
|
+
processExpression(arrow.body);
|
|
475
|
+
return templates;
|
|
476
|
+
}
|
|
477
|
+
for (const stmt of arrow.body.stmts) {
|
|
478
|
+
if (stmt.type === "ReturnStatement" && stmt.argument) {
|
|
479
|
+
processExpression(stmt.argument);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return templates;
|
|
483
|
+
};
|
|
484
|
+
const extractFromTaggedTemplate = (tagged, schemaName, templates) => {
|
|
485
|
+
let kind;
|
|
486
|
+
let elementName;
|
|
487
|
+
let typeName;
|
|
488
|
+
if (tagged.tag.type === "Identifier") {
|
|
489
|
+
kind = tagged.tag.value;
|
|
490
|
+
} else if (tagged.tag.type === "CallExpression") {
|
|
491
|
+
const tagCall = tagged.tag;
|
|
492
|
+
if (tagCall.callee.type === "Identifier") {
|
|
493
|
+
kind = tagCall.callee.value;
|
|
494
|
+
} else {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const firstArg = tagCall.arguments[0]?.expression;
|
|
498
|
+
if (firstArg?.type === "StringLiteral") {
|
|
499
|
+
elementName = firstArg.value;
|
|
500
|
+
}
|
|
501
|
+
const secondArg = tagCall.arguments[1]?.expression;
|
|
502
|
+
if (secondArg?.type === "StringLiteral") {
|
|
503
|
+
typeName = secondArg.value;
|
|
504
|
+
}
|
|
505
|
+
} else {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (!isOperationKind(kind)) {
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const { quasis, expressions } = tagged.template;
|
|
512
|
+
if (tagged.tag.type === "Identifier" && expressions.length > 0) {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (quasis.length === 0) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
let content;
|
|
519
|
+
if (expressions.length === 0) {
|
|
520
|
+
const quasi = quasis[0];
|
|
521
|
+
if (!quasi) return;
|
|
522
|
+
content = quasi.cooked ?? quasi.raw;
|
|
523
|
+
} else {
|
|
524
|
+
const parts = [];
|
|
525
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
526
|
+
const quasi = quasis[i];
|
|
527
|
+
if (!quasi) continue;
|
|
528
|
+
parts.push(quasi.cooked ?? quasi.raw);
|
|
529
|
+
if (i < expressions.length) {
|
|
530
|
+
parts.push(`__FRAG_SPREAD_${i}__`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
content = parts.join("");
|
|
534
|
+
}
|
|
535
|
+
templates.push({
|
|
536
|
+
schemaName,
|
|
537
|
+
kind,
|
|
538
|
+
content,
|
|
539
|
+
...elementName !== undefined ? { elementName } : {},
|
|
540
|
+
...typeName !== undefined ? { typeName } : {}
|
|
541
|
+
});
|
|
542
|
+
};
|
|
446
543
|
/**
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
TName,
|
|
464
|
-
string[],
|
|
465
|
-
PrebuiltEntryNotFound<TName, "operation">,
|
|
466
|
-
Partial<AnyFields>,
|
|
467
|
-
PrebuiltEntryNotFound<TName, "operation">
|
|
468
|
-
>;
|
|
469
|
-
|
|
544
|
+
* Find the innermost gql call, unwrapping method chains like .attach().
|
|
545
|
+
*/
|
|
546
|
+
const findGqlCall = (identifiers, node) => {
|
|
547
|
+
if (!node || node.type !== "CallExpression") {
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
const call = node;
|
|
551
|
+
if (getGqlCallSchemaName(identifiers, call) !== null) {
|
|
552
|
+
return call;
|
|
553
|
+
}
|
|
554
|
+
const callee = call.callee;
|
|
555
|
+
if (callee.type !== "MemberExpression") {
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
return findGqlCall(identifiers, callee.object);
|
|
559
|
+
};
|
|
470
560
|
/**
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
561
|
+
* Walk AST to find gql calls and extract templates.
|
|
562
|
+
*/
|
|
563
|
+
const walkAndExtract = (node, identifiers) => {
|
|
564
|
+
const templates = [];
|
|
565
|
+
const visit = (n) => {
|
|
566
|
+
if (!n || typeof n !== "object") {
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if ("type" in n && n.type === "CallExpression") {
|
|
570
|
+
const gqlCall = findGqlCall(identifiers, n);
|
|
571
|
+
if (gqlCall) {
|
|
572
|
+
const schemaName = getGqlCallSchemaName(identifiers, gqlCall);
|
|
573
|
+
if (schemaName) {
|
|
574
|
+
const arrow = gqlCall.arguments[0]?.expression;
|
|
575
|
+
templates.push(...extractTemplatesFromCallback(arrow, schemaName));
|
|
576
|
+
}
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (Array.isArray(n)) {
|
|
581
|
+
for (const item of n) {
|
|
582
|
+
visit(item);
|
|
583
|
+
}
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
for (const key of Object.keys(n)) {
|
|
587
|
+
if (key === "span" || key === "type") {
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const value = n[key];
|
|
591
|
+
if (value && typeof value === "object") {
|
|
592
|
+
visit(value);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
visit(node);
|
|
597
|
+
return templates;
|
|
598
|
+
};
|
|
482
599
|
/**
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
600
|
+
* Extract all tagged templates from a TypeScript source file.
|
|
601
|
+
*
|
|
602
|
+
* @param filePath - Absolute path to the source file (used for import resolution)
|
|
603
|
+
* @param source - TypeScript source code
|
|
604
|
+
* @param helper - GraphQL system identifier for resolving gql imports
|
|
605
|
+
* @returns Extracted templates and any warnings
|
|
606
|
+
*/
|
|
607
|
+
const extractTemplatesFromSource = (filePath, source, helper) => {
|
|
608
|
+
const warnings = [];
|
|
609
|
+
const isTsx = filePath.endsWith(".tsx");
|
|
610
|
+
const program = safeParseSync(source, isTsx);
|
|
611
|
+
if (!program || program.type !== "Module") {
|
|
612
|
+
if (source.includes("gql")) {
|
|
613
|
+
warnings.push(`[typegen-extract] Failed to parse ${filePath}`);
|
|
614
|
+
}
|
|
615
|
+
return {
|
|
616
|
+
templates: [],
|
|
617
|
+
warnings
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
const gqlIdentifiers = collectGqlIdentifiers(program, filePath, helper);
|
|
621
|
+
if (gqlIdentifiers.size === 0) {
|
|
622
|
+
return {
|
|
623
|
+
templates: [],
|
|
624
|
+
warnings
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
return {
|
|
628
|
+
templates: walkAndExtract(program, gqlIdentifiers),
|
|
629
|
+
warnings
|
|
630
|
+
};
|
|
631
|
+
};
|
|
493
632
|
|
|
633
|
+
//#endregion
|
|
634
|
+
//#region packages/typegen/src/template-scanner.ts
|
|
494
635
|
/**
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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 = `\
|
|
636
|
+
* Source file scanner for tagged template extraction.
|
|
637
|
+
*
|
|
638
|
+
* Discovers source files from config include/exclude patterns,
|
|
639
|
+
* reads them, and extracts tagged templates using the template extractor.
|
|
640
|
+
*
|
|
641
|
+
* @module
|
|
642
|
+
*/
|
|
520
643
|
/**
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
}
|
|
644
|
+
* Scan source files for tagged templates.
|
|
645
|
+
*
|
|
646
|
+
* Uses fast-glob to discover files matching include/exclude patterns,
|
|
647
|
+
* then extracts tagged templates from each file.
|
|
648
|
+
*/
|
|
649
|
+
const scanSourceFiles = (options) => {
|
|
650
|
+
const { include, exclude, baseDir, helper } = options;
|
|
651
|
+
const warnings = [];
|
|
652
|
+
const ignorePatterns = exclude.map((pattern) => pattern.startsWith("!") ? pattern.slice(1) : pattern);
|
|
653
|
+
const matchedFiles = fg.sync(include, {
|
|
654
|
+
cwd: baseDir,
|
|
655
|
+
ignore: ignorePatterns,
|
|
656
|
+
onlyFiles: true,
|
|
657
|
+
absolute: true
|
|
658
|
+
});
|
|
659
|
+
const templates = new Map();
|
|
660
|
+
for (const filePath of matchedFiles) {
|
|
661
|
+
const normalizedPath = normalize(resolve(filePath)).replace(/\\/g, "/");
|
|
662
|
+
try {
|
|
663
|
+
const source = readFileSync(normalizedPath, "utf-8");
|
|
664
|
+
const { templates: extracted, warnings: extractionWarnings } = extractTemplatesFromSource(normalizedPath, source, helper);
|
|
665
|
+
warnings.push(...extractionWarnings);
|
|
666
|
+
if (extracted.length > 0) {
|
|
667
|
+
templates.set(normalizedPath, extracted);
|
|
668
|
+
}
|
|
669
|
+
} catch (error) {
|
|
670
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
671
|
+
warnings.push(`[typegen-scan] Failed to read ${normalizedPath}: ${message}`);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return {
|
|
675
|
+
templates,
|
|
676
|
+
warnings
|
|
677
|
+
};
|
|
678
|
+
};
|
|
556
679
|
|
|
680
|
+
//#endregion
|
|
681
|
+
//#region packages/typegen/src/template-to-selections.ts
|
|
682
|
+
/**
|
|
683
|
+
* Convert extracted templates into field selections for the emitter.
|
|
684
|
+
*
|
|
685
|
+
* @param templates - Templates extracted from source files, keyed by file path
|
|
686
|
+
* @param schemas - Loaded schema objects keyed by schema name
|
|
687
|
+
* @returns Map of canonical IDs to field selection data, plus any warnings
|
|
688
|
+
*/
|
|
689
|
+
const convertTemplatesToSelections = (templates, schemas) => {
|
|
690
|
+
const selections = new Map();
|
|
691
|
+
const warnings = [];
|
|
692
|
+
const schemaIndexes = new Map(Object.entries(schemas).map(([name, schema]) => [name, createSchemaIndexFromSchema(schema)]));
|
|
693
|
+
for (const [filePath, fileTemplates] of templates) {
|
|
694
|
+
for (const template of fileTemplates) {
|
|
695
|
+
const schema = schemas[template.schemaName];
|
|
696
|
+
if (!schema) {
|
|
697
|
+
warnings.push(`[typegen-template] Unknown schema "${template.schemaName}" in ${filePath}`);
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
const schemaIndex = schemaIndexes.get(template.schemaName);
|
|
701
|
+
if (!schemaIndex) {
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
try {
|
|
705
|
+
if (template.kind === "fragment") {
|
|
706
|
+
const selection = convertFragmentTemplate(template, schema, filePath);
|
|
707
|
+
if (selection) {
|
|
708
|
+
selections.set(selection.id, selection.data);
|
|
709
|
+
}
|
|
710
|
+
} else {
|
|
711
|
+
const selection = convertOperationTemplate(template, schema, filePath);
|
|
712
|
+
if (selection) {
|
|
713
|
+
selections.set(selection.id, selection.data);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
} catch (error) {
|
|
717
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
718
|
+
warnings.push(`[typegen-template] Failed to process ${template.kind} in ${filePath}: ${message}`);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return {
|
|
723
|
+
selections,
|
|
724
|
+
warnings
|
|
725
|
+
};
|
|
726
|
+
};
|
|
727
|
+
/**
|
|
728
|
+
* Reconstruct full GraphQL source from an extracted template.
|
|
729
|
+
* For curried syntax (new), prepends the definition header from tag call arguments.
|
|
730
|
+
* For old syntax, returns content as-is.
|
|
731
|
+
*/
|
|
732
|
+
const reconstructGraphql = (template) => {
|
|
733
|
+
if (template.elementName) {
|
|
734
|
+
if (template.kind === "fragment" && template.typeName) {
|
|
735
|
+
return `fragment ${template.elementName} on ${template.typeName} ${template.content}`;
|
|
736
|
+
}
|
|
737
|
+
return `${template.kind} ${template.elementName} ${template.content}`;
|
|
738
|
+
}
|
|
739
|
+
return template.content;
|
|
740
|
+
};
|
|
557
741
|
/**
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
742
|
+
* Convert a fragment template into FieldSelectionData.
|
|
743
|
+
*/
|
|
744
|
+
const convertFragmentTemplate = (template, schema, filePath) => {
|
|
745
|
+
const schemaIndex = createSchemaIndexFromSchema(schema);
|
|
746
|
+
const graphqlSource = reconstructGraphql(template);
|
|
747
|
+
const variableDefinitions = extractFragmentVariables(graphqlSource, schemaIndex);
|
|
748
|
+
const { preprocessed } = preprocessFragmentArgs(graphqlSource);
|
|
749
|
+
const document = parse(preprocessed);
|
|
750
|
+
const fragDef = document.definitions.find((d) => d.kind === Kind.FRAGMENT_DEFINITION);
|
|
751
|
+
if (!fragDef || fragDef.kind !== Kind.FRAGMENT_DEFINITION) {
|
|
752
|
+
return null;
|
|
753
|
+
}
|
|
754
|
+
const fragmentName = fragDef.name.value;
|
|
755
|
+
const onType = fragDef.typeCondition.name.value;
|
|
756
|
+
const fields = buildFieldsFromSelectionSet(fragDef.selectionSet, schema, onType);
|
|
757
|
+
const id = `${filePath}::${fragmentName}`;
|
|
758
|
+
return {
|
|
759
|
+
id,
|
|
760
|
+
data: {
|
|
761
|
+
type: "fragment",
|
|
762
|
+
schemaLabel: schema.label,
|
|
763
|
+
key: fragmentName,
|
|
764
|
+
typename: onType,
|
|
765
|
+
fields,
|
|
766
|
+
variableDefinitions
|
|
767
|
+
}
|
|
768
|
+
};
|
|
566
769
|
};
|
|
567
|
-
|
|
568
|
-
|
|
770
|
+
/**
|
|
771
|
+
* Convert an operation template into FieldSelectionData.
|
|
772
|
+
*/
|
|
773
|
+
const convertOperationTemplate = (template, schema, filePath) => {
|
|
774
|
+
const graphqlSource = reconstructGraphql(template);
|
|
775
|
+
const document = parse(graphqlSource);
|
|
776
|
+
const opDef = document.definitions.find((d) => d.kind === Kind.OPERATION_DEFINITION);
|
|
777
|
+
if (!opDef || opDef.kind !== Kind.OPERATION_DEFINITION) {
|
|
778
|
+
return null;
|
|
779
|
+
}
|
|
780
|
+
const operationName = opDef.name?.value ?? "Anonymous";
|
|
781
|
+
const operationType = opDef.operation;
|
|
782
|
+
const rootTypeName = getRootTypeName(schema, operationType);
|
|
783
|
+
const fields = buildFieldsFromSelectionSet(opDef.selectionSet, schema, rootTypeName);
|
|
784
|
+
const variableDefinitions = opDef.variableDefinitions ?? [];
|
|
785
|
+
const id = `${filePath}::${operationName}`;
|
|
786
|
+
return {
|
|
787
|
+
id,
|
|
788
|
+
data: {
|
|
789
|
+
type: "operation",
|
|
790
|
+
schemaLabel: schema.label,
|
|
791
|
+
operationName,
|
|
792
|
+
operationType,
|
|
793
|
+
fields,
|
|
794
|
+
variableDefinitions: [...variableDefinitions]
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
};
|
|
798
|
+
/**
|
|
799
|
+
* Get the root type name for an operation type from the schema.
|
|
800
|
+
*/
|
|
801
|
+
const getRootTypeName = (schema, operationType) => {
|
|
802
|
+
switch (operationType) {
|
|
803
|
+
case "query": return schema.operations.query ?? "Query";
|
|
804
|
+
case "mutation": return schema.operations.mutation ?? "Mutation";
|
|
805
|
+
case "subscription": return schema.operations.subscription ?? "Subscription";
|
|
806
|
+
default: return "Query";
|
|
807
|
+
}
|
|
569
808
|
};
|
|
570
809
|
|
|
571
810
|
//#endregion
|
|
@@ -575,11 +814,10 @@ ${gqlEntries.join(",\n")}
|
|
|
575
814
|
*
|
|
576
815
|
* Orchestrates the prebuilt type generation process:
|
|
577
816
|
* 1. Load schemas from generated CJS bundle
|
|
578
|
-
* 2.
|
|
579
|
-
* 3.
|
|
580
|
-
* 4.
|
|
817
|
+
* 2. Build artifact to evaluate elements
|
|
818
|
+
* 3. Extract field selections from builder
|
|
819
|
+
* 4. Scan source files for tagged templates and merge selections
|
|
581
820
|
* 5. Emit types.prebuilt.ts
|
|
582
|
-
* 6. Bundle prebuilt module
|
|
583
821
|
*
|
|
584
822
|
* @module
|
|
585
823
|
*/
|
|
@@ -621,58 +859,14 @@ const toImportSpecifier = (fromPath, targetPath, options) => {
|
|
|
621
859
|
return `${withoutExt}${runtimeExt}`;
|
|
622
860
|
};
|
|
623
861
|
/**
|
|
624
|
-
* Bundle the prebuilt module to CJS format.
|
|
625
|
-
*/
|
|
626
|
-
const bundlePrebuiltModule = async (sourcePath) => {
|
|
627
|
-
const sourceExt = extname(sourcePath);
|
|
628
|
-
const baseName = sourcePath.slice(0, -sourceExt.length);
|
|
629
|
-
const cjsPath = `${baseName}.cjs`;
|
|
630
|
-
await 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 mkdir(dirname(path), { recursive: true });
|
|
648
|
-
await 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 += `${readFileSync(schemaPath, "utf-8")}\n`;
|
|
661
|
-
}
|
|
662
|
-
documents.set(name, parse(combinedSource));
|
|
663
|
-
}
|
|
664
|
-
return documents;
|
|
665
|
-
};
|
|
666
|
-
/**
|
|
667
862
|
* Run the typegen process.
|
|
668
863
|
*
|
|
669
864
|
* This function:
|
|
670
865
|
* 1. Loads schemas from the generated CJS bundle
|
|
671
|
-
* 2.
|
|
672
|
-
* 3.
|
|
673
|
-
* 4.
|
|
866
|
+
* 2. Creates a BuilderService and builds the artifact
|
|
867
|
+
* 3. Extracts field selections from the artifact
|
|
868
|
+
* 4. Scans source files for tagged templates and merges selections
|
|
674
869
|
* 5. Emits types.prebuilt.ts using emitPrebuiltTypes
|
|
675
|
-
* 6. Bundles the prebuilt module
|
|
676
870
|
*
|
|
677
871
|
* @param options - Typegen options including config
|
|
678
872
|
* @returns Result containing success data or error
|
|
@@ -691,24 +885,8 @@ const runTypegen = async (options) => {
|
|
|
691
885
|
return err(typegenErrors.schemaLoadFailed(schemaNames, schemasResult.error));
|
|
692
886
|
}
|
|
693
887
|
const schemas = schemasResult.value;
|
|
694
|
-
const
|
|
695
|
-
const
|
|
696
|
-
const internalModulePath = toImportSpecifier(prebuiltIndexPath, join(outdir, "_internal.ts"), importSpecifierOptions);
|
|
697
|
-
const injectsModulePath = toImportSpecifier(prebuiltIndexPath, 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 err(typegenErrors.emitFailed(prebuiltIndexPath, `Failed to write prebuilt index: ${error instanceof Error ? error.message : String(error)}`, error));
|
|
711
|
-
}
|
|
888
|
+
const prebuiltTypesPath = join(outdir, "types.prebuilt.ts");
|
|
889
|
+
const injectsModulePath = toImportSpecifier(prebuiltTypesPath, join(outdir, "_internal-injects.ts"), importSpecifierOptions);
|
|
712
890
|
const builderService = createBuilderService({ config });
|
|
713
891
|
const artifactResult = await builderService.buildAsync();
|
|
714
892
|
if (artifactResult.isErr()) {
|
|
@@ -719,7 +897,38 @@ const runTypegen = async (options) => {
|
|
|
719
897
|
return err(typegenErrors.buildFailed("No intermediate elements available after build", undefined));
|
|
720
898
|
}
|
|
721
899
|
const fieldSelectionsResult = extractFieldSelections(intermediateElements);
|
|
722
|
-
const { selections:
|
|
900
|
+
const { selections: builderSelections, warnings: extractWarnings } = fieldSelectionsResult;
|
|
901
|
+
const graphqlHelper = createGraphqlSystemIdentifyHelper(config);
|
|
902
|
+
const scanResult = scanSourceFiles({
|
|
903
|
+
include: [...config.include],
|
|
904
|
+
exclude: [...config.exclude],
|
|
905
|
+
baseDir: config.baseDir,
|
|
906
|
+
helper: graphqlHelper
|
|
907
|
+
});
|
|
908
|
+
const templateSelections = convertTemplatesToSelections(scanResult.templates, schemas);
|
|
909
|
+
const extractFilePart = (id) => {
|
|
910
|
+
const filePart = id.split("::")[0] ?? "";
|
|
911
|
+
if (filePart.startsWith("/")) {
|
|
912
|
+
return relative(config.baseDir, filePart);
|
|
913
|
+
}
|
|
914
|
+
return filePart;
|
|
915
|
+
};
|
|
916
|
+
const extractElementName = (data) => data.type === "fragment" ? data.key : data.operationName;
|
|
917
|
+
const templateElements = new Set();
|
|
918
|
+
for (const [id, data] of templateSelections.selections) {
|
|
919
|
+
const name = extractElementName(data);
|
|
920
|
+
if (name) templateElements.add(`${extractFilePart(id)}::${name}`);
|
|
921
|
+
}
|
|
922
|
+
const fieldSelections = new Map();
|
|
923
|
+
for (const [id, data] of builderSelections) {
|
|
924
|
+
const name = extractElementName(data);
|
|
925
|
+
if (name && templateElements.has(`${extractFilePart(id)}::${name}`)) continue;
|
|
926
|
+
fieldSelections.set(id, data);
|
|
927
|
+
}
|
|
928
|
+
for (const [id, data] of templateSelections.selections) {
|
|
929
|
+
fieldSelections.set(id, data);
|
|
930
|
+
}
|
|
931
|
+
const scanWarnings = [...scanResult.warnings, ...templateSelections.warnings];
|
|
723
932
|
const emitResult = await emitPrebuiltTypes({
|
|
724
933
|
schemas,
|
|
725
934
|
fieldSelections,
|
|
@@ -729,12 +938,7 @@ const runTypegen = async (options) => {
|
|
|
729
938
|
if (emitResult.isErr()) {
|
|
730
939
|
return err(emitResult.error);
|
|
731
940
|
}
|
|
732
|
-
const {
|
|
733
|
-
try {
|
|
734
|
-
await bundlePrebuiltModule(prebuiltIndexPath);
|
|
735
|
-
} catch (error) {
|
|
736
|
-
return err(typegenErrors.bundleFailed(prebuiltIndexPath, `Failed to bundle prebuilt module: ${error instanceof Error ? error.message : String(error)}`, error));
|
|
737
|
-
}
|
|
941
|
+
const { warnings: emitWarnings } = emitResult.value;
|
|
738
942
|
let fragmentCount = 0;
|
|
739
943
|
let operationCount = 0;
|
|
740
944
|
for (const selection of fieldSelections.values()) {
|
|
@@ -744,9 +948,12 @@ const runTypegen = async (options) => {
|
|
|
744
948
|
operationCount++;
|
|
745
949
|
}
|
|
746
950
|
}
|
|
747
|
-
const allWarnings = [
|
|
951
|
+
const allWarnings = [
|
|
952
|
+
...extractWarnings,
|
|
953
|
+
...scanWarnings,
|
|
954
|
+
...emitWarnings
|
|
955
|
+
];
|
|
748
956
|
return ok({
|
|
749
|
-
prebuiltIndexPath,
|
|
750
957
|
prebuiltTypesPath,
|
|
751
958
|
fragmentCount,
|
|
752
959
|
operationCount,
|
|
@@ -755,5 +962,5 @@ const runTypegen = async (options) => {
|
|
|
755
962
|
};
|
|
756
963
|
|
|
757
964
|
//#endregion
|
|
758
|
-
export { emitPrebuiltTypes, formatTypegenError,
|
|
965
|
+
export { emitPrebuiltTypes, formatTypegenError, runTypegen, typegenErrors };
|
|
759
966
|
//# sourceMappingURL=index.mjs.map
|