@soda-gql/codegen 0.11.12 → 0.11.14

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.
@@ -1,771 +0,0 @@
1
- let graphql = require("graphql");
2
-
3
- //#region packages/codegen/src/generator.ts
4
- const builtinScalarTypes = new Map([
5
- ["ID", {
6
- input: "string",
7
- output: "string"
8
- }],
9
- ["String", {
10
- input: "string",
11
- output: "string"
12
- }],
13
- ["Int", {
14
- input: "number",
15
- output: "number"
16
- }],
17
- ["Float", {
18
- input: "number",
19
- output: "number"
20
- }],
21
- ["Boolean", {
22
- input: "boolean",
23
- output: "boolean"
24
- }]
25
- ]);
26
- const ensureRecord = (collection, key, factory) => {
27
- const existing = collection.get(key);
28
- if (existing) {
29
- return existing;
30
- }
31
- const created = factory(key);
32
- collection.set(key, created);
33
- return created;
34
- };
35
- const addObjectFields = (target, fields) => {
36
- if (!fields) {
37
- return;
38
- }
39
- for (const field of fields) {
40
- target.set(field.name.value, field);
41
- }
42
- };
43
- const addInputFields = (target, fields) => {
44
- if (!fields) {
45
- return;
46
- }
47
- for (const field of fields) {
48
- target.set(field.name.value, field);
49
- }
50
- };
51
- const addEnumValues = (target, values) => {
52
- if (!values) {
53
- return;
54
- }
55
- for (const value of values) {
56
- target.set(value.name.value, value);
57
- }
58
- };
59
- const addUnionMembers = (target, members) => {
60
- if (!members) {
61
- return;
62
- }
63
- for (const member of members) {
64
- target.set(member.name.value, member);
65
- }
66
- };
67
- const mergeDirectives = (existing, incoming, precedence) => {
68
- const current = existing ?? [];
69
- const next = incoming ? Array.from(incoming) : [];
70
- return precedence === "definition" ? [...next, ...current] : [...current, ...next];
71
- };
72
- const updateOperationTypes = (operationTypes, definition) => {
73
- for (const operation of definition.operationTypes ?? []) {
74
- const typeName = operation.type.name.value;
75
- switch (operation.operation) {
76
- case "query":
77
- operationTypes.query = typeName;
78
- break;
79
- case "mutation":
80
- operationTypes.mutation = typeName;
81
- break;
82
- case "subscription":
83
- operationTypes.subscription = typeName;
84
- break;
85
- default: break;
86
- }
87
- }
88
- };
89
- const addDirectiveArgs = (target, args) => {
90
- if (!args) {
91
- return;
92
- }
93
- for (const arg of args) {
94
- target.set(arg.name.value, arg);
95
- }
96
- };
97
- const createSchemaIndex = (document) => {
98
- const objects = new Map();
99
- const inputs = new Map();
100
- const enums = new Map();
101
- const unions = new Map();
102
- const scalars = new Map();
103
- const directives = new Map();
104
- const operationTypes = {};
105
- for (const definition of document.definitions) {
106
- switch (definition.kind) {
107
- case graphql.Kind.OBJECT_TYPE_DEFINITION:
108
- case graphql.Kind.OBJECT_TYPE_EXTENSION: {
109
- const precedence = definition.kind === graphql.Kind.OBJECT_TYPE_DEFINITION ? "definition" : "extension";
110
- const record = ensureRecord(objects, definition.name.value, (name) => ({
111
- name,
112
- fields: new Map(),
113
- directives: []
114
- }));
115
- addObjectFields(record.fields, definition.fields);
116
- record.directives = mergeDirectives(record.directives, definition.directives, precedence);
117
- break;
118
- }
119
- case graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION:
120
- case graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION: {
121
- const precedence = definition.kind === graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION ? "definition" : "extension";
122
- const record = ensureRecord(inputs, definition.name.value, (name) => ({
123
- name,
124
- fields: new Map(),
125
- directives: []
126
- }));
127
- addInputFields(record.fields, definition.fields);
128
- record.directives = mergeDirectives(record.directives, definition.directives, precedence);
129
- break;
130
- }
131
- case graphql.Kind.ENUM_TYPE_DEFINITION:
132
- case graphql.Kind.ENUM_TYPE_EXTENSION: {
133
- const precedence = definition.kind === graphql.Kind.ENUM_TYPE_DEFINITION ? "definition" : "extension";
134
- const record = ensureRecord(enums, definition.name.value, (name) => ({
135
- name,
136
- values: new Map(),
137
- directives: []
138
- }));
139
- addEnumValues(record.values, definition.values);
140
- record.directives = mergeDirectives(record.directives, definition.directives, precedence);
141
- break;
142
- }
143
- case graphql.Kind.UNION_TYPE_DEFINITION:
144
- case graphql.Kind.UNION_TYPE_EXTENSION: {
145
- const precedence = definition.kind === graphql.Kind.UNION_TYPE_DEFINITION ? "definition" : "extension";
146
- const record = ensureRecord(unions, definition.name.value, (name) => ({
147
- name,
148
- members: new Map(),
149
- directives: []
150
- }));
151
- addUnionMembers(record.members, definition.types);
152
- record.directives = mergeDirectives(record.directives, definition.directives, precedence);
153
- break;
154
- }
155
- case graphql.Kind.SCALAR_TYPE_DEFINITION:
156
- case graphql.Kind.SCALAR_TYPE_EXTENSION: {
157
- const precedence = definition.kind === graphql.Kind.SCALAR_TYPE_DEFINITION ? "definition" : "extension";
158
- const record = ensureRecord(scalars, definition.name.value, (name) => ({
159
- name,
160
- directives: []
161
- }));
162
- record.directives = mergeDirectives(record.directives, definition.directives, precedence);
163
- break;
164
- }
165
- case graphql.Kind.DIRECTIVE_DEFINITION: {
166
- const name = definition.name.value;
167
- if (name === "skip" || name === "include" || name === "deprecated" || name === "specifiedBy") {
168
- break;
169
- }
170
- const args = new Map();
171
- addDirectiveArgs(args, definition.arguments);
172
- directives.set(name, {
173
- name,
174
- locations: definition.locations.map((loc) => loc.value),
175
- args,
176
- isRepeatable: definition.repeatable
177
- });
178
- break;
179
- }
180
- case graphql.Kind.SCHEMA_DEFINITION:
181
- case graphql.Kind.SCHEMA_EXTENSION:
182
- updateOperationTypes(operationTypes, definition);
183
- break;
184
- default: break;
185
- }
186
- }
187
- if (!operationTypes.query && objects.has("Query")) {
188
- operationTypes.query = "Query";
189
- }
190
- if (!operationTypes.mutation && objects.has("Mutation")) {
191
- operationTypes.mutation = "Mutation";
192
- }
193
- if (!operationTypes.subscription && objects.has("Subscription")) {
194
- operationTypes.subscription = "Subscription";
195
- }
196
- return {
197
- objects,
198
- inputs,
199
- enums,
200
- unions,
201
- scalars,
202
- directives,
203
- operationTypes
204
- };
205
- };
206
- const collectTypeLevels = (type, nonNull = false, levels = []) => {
207
- if (type.kind === graphql.Kind.NON_NULL_TYPE) {
208
- return collectTypeLevels(type.type, true, levels);
209
- }
210
- if (type.kind === graphql.Kind.LIST_TYPE) {
211
- levels.push({
212
- kind: "list",
213
- nonNull
214
- });
215
- return collectTypeLevels(type.type, false, levels);
216
- }
217
- levels.push({
218
- kind: "named",
219
- nonNull
220
- });
221
- return {
222
- name: type.name.value,
223
- levels
224
- };
225
- };
226
- const buildTypeModifier = (levels) => {
227
- let modifier = "?";
228
- for (const level of levels.slice().reverse()) {
229
- if (level.kind === "named") {
230
- modifier = level.nonNull ? "!" : "?";
231
- continue;
232
- }
233
- const listSuffix = level.nonNull ? "[]!" : "[]?";
234
- modifier = `${modifier}${listSuffix}`;
235
- }
236
- return modifier;
237
- };
238
- const parseTypeReference = (type) => {
239
- const { name, levels } = collectTypeLevels(type);
240
- return {
241
- name,
242
- modifier: buildTypeModifier(levels)
243
- };
244
- };
245
- const isScalarName = (schema, name) => builtinScalarTypes.has(name) || schema.scalars.has(name);
246
- const isEnumName = (schema, name) => schema.enums.has(name);
247
- const _isInputName = (schema, name) => schema.inputs.has(name);
248
- const isUnionName = (schema, name) => schema.unions.has(name);
249
- const isObjectName = (schema, name) => schema.objects.has(name);
250
- const renderConstValue = (value) => {
251
- switch (value.kind) {
252
- case graphql.Kind.NULL: return "null";
253
- case graphql.Kind.INT:
254
- case graphql.Kind.FLOAT: return value.value;
255
- case graphql.Kind.STRING:
256
- case graphql.Kind.ENUM: return JSON.stringify(value.value);
257
- case graphql.Kind.BOOLEAN: return value.value ? "true" : "false";
258
- case graphql.Kind.LIST: return `[${value.values.map((item) => renderConstValue(item)).join(", ")}]`;
259
- case graphql.Kind.OBJECT: {
260
- if (value.fields.length === 0) {
261
- return "{}";
262
- }
263
- const entries = value.fields.map((field) => `${field.name.value}: ${renderConstValue(field.value)}`);
264
- return `{ ${entries.join(", ")} }`;
265
- }
266
- }
267
- };
268
- const renderInputRef = (schema, definition) => {
269
- const { name, modifier } = parseTypeReference(definition.type);
270
- const defaultValue = definition.defaultValue;
271
- let kind;
272
- if (isScalarName(schema, name)) {
273
- kind = "scalar";
274
- } else if (isEnumName(schema, name)) {
275
- kind = "enum";
276
- } else {
277
- kind = "input";
278
- }
279
- if (defaultValue) {
280
- return `{ kind: "${kind}", name: "${name}", modifier: "${modifier}", defaultValue: { default: ${renderConstValue(defaultValue)} } }`;
281
- }
282
- return `{ kind: "${kind}", name: "${name}", modifier: "${modifier}" }`;
283
- };
284
- const renderArgumentMap = (schema, args) => {
285
- const entries = [...args ?? []].sort((left, right) => left.name.value.localeCompare(right.name.value)).map((arg) => `${arg.name.value}: ${renderInputRef(schema, arg)}`);
286
- return renderPropertyLines({
287
- entries,
288
- indentSize: 8
289
- });
290
- };
291
- const renderOutputRef = (schema, type, args) => {
292
- const { name, modifier } = parseTypeReference(type);
293
- const argumentMap = renderArgumentMap(schema, args);
294
- let kind;
295
- if (isScalarName(schema, name)) {
296
- kind = "scalar";
297
- } else if (isEnumName(schema, name)) {
298
- kind = "enum";
299
- } else if (isUnionName(schema, name)) {
300
- kind = "union";
301
- } else if (isObjectName(schema, name)) {
302
- kind = "object";
303
- } else {
304
- kind = "scalar";
305
- }
306
- return `{ kind: "${kind}", name: "${name}", modifier: "${modifier}", arguments: ${argumentMap} }`;
307
- };
308
- const renderPropertyLines = ({ entries, indentSize }) => {
309
- if (entries.length === 0) {
310
- return "{}";
311
- }
312
- const indent = " ".repeat(indentSize);
313
- const lastIndent = " ".repeat(indentSize - 2);
314
- return [
315
- "{",
316
- `${indent}${entries.join(`,\n${indent}`)},`,
317
- `${lastIndent}}`
318
- ].join(`\n`);
319
- };
320
- const renderObjectFields = (schema, fields) => {
321
- const entries = Array.from(fields.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((field) => `${field.name.value}: ${renderOutputRef(schema, field.type, field.arguments)}`);
322
- return renderPropertyLines({
323
- entries,
324
- indentSize: 6
325
- });
326
- };
327
- const renderInputFields = (schema, fields) => {
328
- const entries = Array.from(fields.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((field) => `${field.name.value}: ${renderInputRef(schema, field)}`);
329
- return renderPropertyLines({
330
- entries,
331
- indentSize: 6
332
- });
333
- };
334
- const renderScalarVar = (schemaName, record) => {
335
- const typeInfo = builtinScalarTypes.get(record.name) ?? {
336
- input: "string",
337
- output: "string"
338
- };
339
- return `const scalar_${schemaName}_${record.name} = { name: "${record.name}", $type: {} as { input: ${typeInfo.input}; output: ${typeInfo.output}; inputProfile: { kind: "scalar"; name: "${record.name}"; value: ${typeInfo.input} }; outputProfile: { kind: "scalar"; name: "${record.name}"; value: ${typeInfo.output} } } } as const;`;
340
- };
341
- const renderEnumVar = (schemaName, record) => {
342
- const valueNames = Array.from(record.values.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((value) => value.name.value);
343
- const valuesObj = valueNames.length === 0 ? "{}" : `{ ${valueNames.map((v) => `${v}: true`).join(", ")} }`;
344
- const valueUnion = valueNames.length === 0 ? "never" : valueNames.map((v) => `"${v}"`).join(" | ");
345
- return `const enum_${schemaName}_${record.name} = defineEnum<"${record.name}", ${valueUnion}>("${record.name}", ${valuesObj});`;
346
- };
347
- const renderInputVar = (schemaName, schema, record) => {
348
- const fields = renderInputFields(schema, record.fields);
349
- return `const input_${schemaName}_${record.name} = { name: "${record.name}", fields: ${fields} } as const;`;
350
- };
351
- const renderObjectVar = (schemaName, schema, record) => {
352
- const fields = renderObjectFields(schema, record.fields);
353
- return `const object_${schemaName}_${record.name} = { name: "${record.name}", fields: ${fields} } as const;`;
354
- };
355
- const renderUnionVar = (schemaName, record) => {
356
- const memberNames = Array.from(record.members.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((member) => member.name.value);
357
- const typesObj = memberNames.length === 0 ? "{}" : `{ ${memberNames.map((m) => `${m}: true`).join(", ")} }`;
358
- return `const union_${schemaName}_${record.name} = { name: "${record.name}", types: ${typesObj} } as const;`;
359
- };
360
- const collectObjectTypeNames = (schema) => Array.from(schema.objects.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
361
- const renderFragmentBuildersType = (objectTypeNames, schemaName, adapterTypeName) => {
362
- if (objectTypeNames.length === 0) {
363
- return `type FragmentBuilders_${schemaName} = Record<string, never>;`;
364
- }
365
- const adapterPart = adapterTypeName ? `, ExtractMetadataAdapter<${adapterTypeName}>` : "";
366
- const entries = objectTypeNames.map((name) => ` readonly ${name}: FragmentBuilderFor<Schema_${schemaName}, "${name}"${adapterPart}>`);
367
- return `type FragmentBuilders_${schemaName} = {\n${entries.join(";\n")};\n};`;
368
- };
369
- const collectInputTypeNames = (schema) => Array.from(schema.inputs.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
370
- const collectEnumTypeNames = (schema) => Array.from(schema.enums.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
371
- const collectUnionTypeNames = (schema) => Array.from(schema.unions.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
372
- const collectScalarNames = (schema) => Array.from(schema.scalars.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
373
- const collectDirectiveNames = (schema) => Array.from(schema.directives.keys()).sort((left, right) => left.localeCompare(right));
374
- const renderInputTypeMethod = (factoryVar, kind, typeName) => `${typeName}: ${factoryVar}("${kind}", "${typeName}")`;
375
- const renderInputTypeMethods = (schema, factoryVar) => {
376
- const scalarMethods = Array.from(builtinScalarTypes.keys()).concat(collectScalarNames(schema).filter((name) => !builtinScalarTypes.has(name))).map((name) => renderInputTypeMethod(factoryVar, "scalar", name));
377
- const enumMethods = collectEnumTypeNames(schema).map((name) => renderInputTypeMethod(factoryVar, "enum", name));
378
- const inputMethods = collectInputTypeNames(schema).map((name) => renderInputTypeMethod(factoryVar, "input", name));
379
- const allMethods = [
380
- ...scalarMethods,
381
- ...enumMethods,
382
- ...inputMethods
383
- ].sort((left, right) => {
384
- const leftName = left.split(":")[0] ?? "";
385
- const rightName = right.split(":")[0] ?? "";
386
- return leftName.localeCompare(rightName);
387
- });
388
- return renderPropertyLines({
389
- entries: allMethods,
390
- indentSize: 2
391
- });
392
- };
393
- /**
394
- * Renders argument specifiers for a directive.
395
- * Returns null if the directive has no arguments.
396
- */
397
- const renderDirectiveArgsSpec = (schema, args) => {
398
- if (args.size === 0) return null;
399
- const entries = Array.from(args.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((arg) => `${arg.name.value}: ${renderInputRef(schema, arg)}`);
400
- return renderPropertyLines({
401
- entries,
402
- indentSize: 4
403
- });
404
- };
405
- const renderDirectiveMethod = (schema, record) => {
406
- const locationsJson = JSON.stringify(record.locations);
407
- const argsSpec = renderDirectiveArgsSpec(schema, record.args);
408
- if (argsSpec === null) {
409
- return `${record.name}: createDirectiveMethod("${record.name}", ${locationsJson} as const)`;
410
- }
411
- return `${record.name}: createTypedDirectiveMethod("${record.name}", ${locationsJson} as const, ${argsSpec})`;
412
- };
413
- const renderDirectiveMethods = (schema) => {
414
- const directiveNames = collectDirectiveNames(schema);
415
- if (directiveNames.length === 0) {
416
- return "{}";
417
- }
418
- const methods = directiveNames.map((name) => {
419
- const record = schema.directives.get(name);
420
- return record ? renderDirectiveMethod(schema, record) : null;
421
- }).filter((method) => method !== null);
422
- return renderPropertyLines({
423
- entries: methods,
424
- indentSize: 2
425
- });
426
- };
427
- /**
428
- * Generates the _internal-injects.ts module code.
429
- * This file contains only adapter imports (scalar, adapter) to keep it lightweight.
430
- * The heavy schema types remain in _internal.ts.
431
- */
432
- const generateInjectsCode = (injection) => {
433
- const imports = [];
434
- const exports$1 = [];
435
- const typeExports = [];
436
- const importsByPath = new Map();
437
- for (const [schemaName, config] of injection) {
438
- const scalarAlias = `scalar_${schemaName}`;
439
- const scalarSpecifiers = importsByPath.get(config.scalarImportPath) ?? [];
440
- if (!importsByPath.has(config.scalarImportPath)) {
441
- importsByPath.set(config.scalarImportPath, scalarSpecifiers);
442
- }
443
- scalarSpecifiers.push(`scalar as ${scalarAlias}`);
444
- exports$1.push(`export { ${scalarAlias} };`);
445
- typeExports.push(`export type Scalar_${schemaName} = typeof ${scalarAlias};`);
446
- if (config.adapterImportPath) {
447
- const adapterAlias = `adapter_${schemaName}`;
448
- const adapterSpecifiers = importsByPath.get(config.adapterImportPath) ?? [];
449
- if (!importsByPath.has(config.adapterImportPath)) {
450
- importsByPath.set(config.adapterImportPath, adapterSpecifiers);
451
- }
452
- adapterSpecifiers.push(`adapter as ${adapterAlias}`);
453
- exports$1.push(`export { ${adapterAlias} };`);
454
- typeExports.push(`export type Adapter_${schemaName} = typeof ${adapterAlias} & { _?: never };`);
455
- }
456
- }
457
- for (const [path, specifiers] of importsByPath) {
458
- if (specifiers.length === 1) {
459
- imports.push(`import { ${specifiers[0]} } from "${path}";`);
460
- } else {
461
- imports.push(`import {\n ${specifiers.join(",\n ")},\n} from "${path}";`);
462
- }
463
- }
464
- return `\
465
- /**
466
- * Adapter injections for schema.
467
- * Separated to allow lightweight imports for prebuilt module.
468
- * @generated by @soda-gql/codegen
469
- */
470
-
471
- ${imports.join("\n")}
472
-
473
- // Value exports
474
- ${exports$1.join("\n")}
475
-
476
- // Type exports
477
- ${typeExports.join("\n")}
478
- `;
479
- };
480
- const multiRuntimeTemplate = ($$) => {
481
- const imports = [];
482
- const scalarAliases = new Map();
483
- const adapterAliases = new Map();
484
- if ($$.injection.mode === "inject") {
485
- const injectsImports = [];
486
- for (const [schemaName, injection] of $$.injection.perSchema) {
487
- const scalarAlias = `scalar_${schemaName}`;
488
- scalarAliases.set(schemaName, scalarAlias);
489
- injectsImports.push(scalarAlias);
490
- if (injection.adapterImportPath) {
491
- const adapterAlias = `adapter_${schemaName}`;
492
- adapterAliases.set(schemaName, adapterAlias);
493
- injectsImports.push(adapterAlias);
494
- }
495
- }
496
- imports.push(`import { ${injectsImports.join(", ")} } from "${$$.injection.injectsModulePath}";`);
497
- }
498
- {
499
- const { importPaths } = $$.splitting;
500
- for (const [name, config] of Object.entries($$.schemas)) {
501
- if (config.enumNames.length > 0) {
502
- const enumImports = config.enumNames.map((n) => `enum_${name}_${n}`).join(", ");
503
- imports.push(`import { ${enumImports} } from "${importPaths.enums}";`);
504
- }
505
- if (config.inputNames.length > 0) {
506
- const inputImports = config.inputNames.map((n) => `input_${name}_${n}`).join(", ");
507
- imports.push(`import { ${inputImports} } from "${importPaths.inputs}";`);
508
- }
509
- if (config.objectNames.length > 0) {
510
- const objectImports = config.objectNames.map((n) => `object_${name}_${n}`).join(", ");
511
- imports.push(`import { ${objectImports} } from "${importPaths.objects}";`);
512
- }
513
- if (config.unionNames.length > 0) {
514
- const unionImports = config.unionNames.map((n) => `union_${name}_${n}`).join(", ");
515
- imports.push(`import { ${unionImports} } from "${importPaths.unions}";`);
516
- }
517
- }
518
- }
519
- const extraImports = imports.length > 0 ? `${imports.join("\n")}\n` : "";
520
- const schemaBlocks = [];
521
- const gqlEntries = [];
522
- for (const [name, config] of Object.entries($$.schemas)) {
523
- const schemaVar = `${name}Schema`;
524
- const adapterVar = adapterAliases.get(name);
525
- const typeExports = [`export type Schema_${name} = typeof ${schemaVar} & { _?: never };`];
526
- if (adapterVar) {
527
- typeExports.push(`export type Adapter_${name} = typeof ${adapterVar} & { _?: never };`);
528
- }
529
- typeExports.push(config.fragmentBuildersTypeBlock);
530
- const inputTypeMethodsVar = `inputTypeMethods_${name}`;
531
- const factoryVar = `createMethod_${name}`;
532
- const customDirectivesVar = `customDirectives_${name}`;
533
- const defaultDepthBlock = config.defaultInputDepth !== undefined && config.defaultInputDepth !== 3 ? `\n __defaultInputDepth: ${config.defaultInputDepth},` : "";
534
- const depthOverridesBlock = config.inputDepthOverrides && Object.keys(config.inputDepthOverrides).length > 0 ? `\n __inputDepthOverrides: ${JSON.stringify(config.inputDepthOverrides)},` : "";
535
- const isSplitMode = true;
536
- const scalarVarsBlock = config.scalarVars.join("\n");
537
- const enumVarsBlock = isSplitMode ? "// (enums imported)" : config.enumVars.length > 0 ? config.enumVars.join("\n") : "// (no enums)";
538
- const inputVarsBlock = isSplitMode ? "// (inputs imported)" : config.inputVars.length > 0 ? config.inputVars.join("\n") : "// (no inputs)";
539
- const objectVarsBlock = isSplitMode ? "// (objects imported)" : config.objectVars.length > 0 ? config.objectVars.join("\n") : "// (no objects)";
540
- const unionVarsBlock = isSplitMode ? "// (unions imported)" : config.unionVars.length > 0 ? config.unionVars.join("\n") : "// (no unions)";
541
- const scalarAssembly = $$.injection.mode === "inject" ? scalarAliases.get(name) ?? "{}" : config.scalarNames.length > 0 ? `{ ${config.scalarNames.map((n) => `${n}: scalar_${name}_${n}`).join(", ")} }` : "{}";
542
- const enumAssembly = config.enumNames.length > 0 ? `{ ${config.enumNames.map((n) => `${n}: enum_${name}_${n}`).join(", ")} }` : "{}";
543
- const inputAssembly = config.inputNames.length > 0 ? `{ ${config.inputNames.map((n) => `${n}: input_${name}_${n}`).join(", ")} }` : "{}";
544
- const objectAssembly = config.objectNames.length > 0 ? `{ ${config.objectNames.map((n) => `${n}: object_${name}_${n}`).join(", ")} }` : "{}";
545
- const unionAssembly = config.unionNames.length > 0 ? `{ ${config.unionNames.map((n) => `${n}: union_${name}_${n}`).join(", ")} }` : "{}";
546
- const scalarVarsSection = $$.injection.mode === "inject" ? "// (scalars imported)" : scalarVarsBlock;
547
- const scalarAssemblyLine = $$.injection.mode === "inject" ? `// scalar_${name} is imported directly` : `const scalar_${name} = ${scalarAssembly} as const;`;
548
- const scalarRef = $$.injection.mode === "inject" ? scalarAliases.get(name) ?? `scalar_${name}` : `scalar_${name}`;
549
- schemaBlocks.push(`
550
- // Individual scalar definitions
551
- ${scalarVarsSection}
552
-
553
- // Individual enum definitions
554
- ${enumVarsBlock}
555
-
556
- // Individual input definitions
557
- ${inputVarsBlock}
558
-
559
- // Individual object definitions
560
- ${objectVarsBlock}
561
-
562
- // Individual union definitions
563
- ${unionVarsBlock}
564
-
565
- // Category assembly
566
- ${scalarAssemblyLine}
567
- const enum_${name} = ${enumAssembly} as const;
568
- const input_${name} = ${inputAssembly} as const;
569
- const object_${name} = ${objectAssembly} as const;
570
- const union_${name} = ${unionAssembly} as const;
571
-
572
- // Schema assembly
573
- const ${schemaVar} = {
574
- label: "${name}" as const,
575
- operations: { query: "${config.queryType}", mutation: "${config.mutationType}", subscription: "${config.subscriptionType}" } as const,
576
- scalar: ${scalarRef},
577
- enum: enum_${name},
578
- input: input_${name},
579
- object: object_${name},
580
- union: union_${name},${defaultDepthBlock}${depthOverridesBlock}
581
- } as const;
582
-
583
- const ${factoryVar} = createVarMethodFactory<typeof ${schemaVar}>();
584
- const ${inputTypeMethodsVar} = ${config.inputTypeMethodsBlock};
585
- const ${customDirectivesVar} = { ...createStandardDirectives(), ...${config.directiveMethodsBlock} };
586
-
587
- ${typeExports.join("\n")}`);
588
- const gqlVarName = `gql_${name}`;
589
- if (adapterVar) {
590
- const typeParams = `<Schema_${name}, FragmentBuilders_${name}, typeof ${customDirectivesVar}, Adapter_${name}>`;
591
- schemaBlocks.push(`const ${gqlVarName} = createGqlElementComposer${typeParams}(${schemaVar}, { adapter: ${adapterVar}, inputTypeMethods: ${inputTypeMethodsVar}, directiveMethods: ${customDirectivesVar} });`);
592
- } else {
593
- const typeParams = `<Schema_${name}, FragmentBuilders_${name}, typeof ${customDirectivesVar}>`;
594
- schemaBlocks.push(`const ${gqlVarName} = createGqlElementComposer${typeParams}(${schemaVar}, { inputTypeMethods: ${inputTypeMethodsVar}, directiveMethods: ${customDirectivesVar} });`);
595
- }
596
- schemaBlocks.push(`export type Context_${name} = Parameters<typeof ${gqlVarName}>[0] extends (ctx: infer C) => unknown ? C : never;`);
597
- const prebuiltExports = [
598
- `export { ${schemaVar} as __schema_${name} }`,
599
- `export { ${inputTypeMethodsVar} as __inputTypeMethods_${name} }`,
600
- `export { ${customDirectivesVar} as __directiveMethods_${name} }`
601
- ];
602
- if (adapterVar) {
603
- prebuiltExports.push(`export { ${adapterVar} as __adapter_${name} }`);
604
- }
605
- schemaBlocks.push(`${prebuiltExports.join(";\n")};`);
606
- gqlEntries.push(` ${name}: ${gqlVarName}`);
607
- }
608
- const needsDefineEnum = false;
609
- return `\
610
- import {${needsDefineEnum ? "\n defineEnum," : ""}
611
- type ExtractMetadataAdapter,
612
- type FragmentBuilderFor,
613
- createDirectiveMethod,
614
- createTypedDirectiveMethod,
615
- createGqlElementComposer,
616
- createStandardDirectives,
617
- createVarMethodFactory,
618
- } from "@soda-gql/core";
619
- ${extraImports}
620
- ${schemaBlocks.join("\n")}
621
-
622
- export const gql = {
623
- ${gqlEntries.join(",\n")}
624
- };
625
- `;
626
- };
627
- const generateMultiSchemaModule = (schemas, options) => {
628
- const schemaConfigs = {};
629
- const allStats = {
630
- objects: 0,
631
- enums: 0,
632
- inputs: 0,
633
- unions: 0
634
- };
635
- for (const [name, document] of schemas.entries()) {
636
- const schema = createSchemaIndex(document);
637
- const objectTypeNames = collectObjectTypeNames(schema);
638
- const enumTypeNames = collectEnumTypeNames(schema);
639
- const inputTypeNames = collectInputTypeNames(schema);
640
- const unionTypeNames = collectUnionTypeNames(schema);
641
- const customScalarNames = collectScalarNames(schema).filter((n) => !builtinScalarTypes.has(n));
642
- const scalarVars = [];
643
- const enumVars = [];
644
- const inputVars = [];
645
- const objectVars = [];
646
- const unionVars = [];
647
- for (const scalarName of builtinScalarTypes.keys()) {
648
- const record = schema.scalars.get(scalarName) ?? {
649
- name: scalarName,
650
- directives: []
651
- };
652
- scalarVars.push(renderScalarVar(name, record));
653
- }
654
- for (const scalarName of customScalarNames) {
655
- const record = schema.scalars.get(scalarName);
656
- if (record) {
657
- scalarVars.push(renderScalarVar(name, record));
658
- }
659
- }
660
- for (const enumName of enumTypeNames) {
661
- const record = schema.enums.get(enumName);
662
- if (record) {
663
- enumVars.push(renderEnumVar(name, record));
664
- }
665
- }
666
- for (const inputName of inputTypeNames) {
667
- const record = schema.inputs.get(inputName);
668
- if (record) {
669
- inputVars.push(renderInputVar(name, schema, record));
670
- }
671
- }
672
- for (const objectName of objectTypeNames) {
673
- const record = schema.objects.get(objectName);
674
- if (record) {
675
- objectVars.push(renderObjectVar(name, schema, record));
676
- }
677
- }
678
- for (const unionName of unionTypeNames) {
679
- const record = schema.unions.get(unionName);
680
- if (record) {
681
- unionVars.push(renderUnionVar(name, record));
682
- }
683
- }
684
- const allScalarNames = [...builtinScalarTypes.keys(), ...customScalarNames];
685
- const factoryVar = `createMethod_${name}`;
686
- const inputTypeMethodsBlock = renderInputTypeMethods(schema, factoryVar);
687
- const directiveMethodsBlock = renderDirectiveMethods(schema);
688
- const adapterTypeName = options?.injection?.get(name)?.adapterImportPath ? `Adapter_${name}` : undefined;
689
- const fragmentBuildersTypeBlock = renderFragmentBuildersType(objectTypeNames, name, adapterTypeName);
690
- const queryType = schema.operationTypes.query ?? "Query";
691
- const mutationType = schema.operationTypes.mutation ?? "Mutation";
692
- const subscriptionType = schema.operationTypes.subscription ?? "Subscription";
693
- schemaConfigs[name] = {
694
- queryType,
695
- mutationType,
696
- subscriptionType,
697
- scalarVars,
698
- enumVars,
699
- inputVars,
700
- objectVars,
701
- unionVars,
702
- scalarNames: allScalarNames,
703
- enumNames: enumTypeNames,
704
- inputNames: inputTypeNames,
705
- objectNames: objectTypeNames,
706
- unionNames: unionTypeNames,
707
- inputTypeMethodsBlock,
708
- directiveMethodsBlock,
709
- fragmentBuildersTypeBlock,
710
- defaultInputDepth: options?.defaultInputDepth?.get(name),
711
- inputDepthOverrides: options?.inputDepthOverrides?.get(name)
712
- };
713
- allStats.objects += objectVars.length;
714
- allStats.enums += enumVars.length;
715
- allStats.inputs += inputVars.length;
716
- allStats.unions += unionVars.length;
717
- }
718
- const injection = options?.injection ? {
719
- mode: "inject",
720
- perSchema: options.injection,
721
- injectsModulePath: "./_internal-injects"
722
- } : { mode: "inline" };
723
- const splitting = { importPaths: {
724
- enums: "./_defs/enums",
725
- inputs: "./_defs/inputs",
726
- objects: "./_defs/objects",
727
- unions: "./_defs/unions"
728
- } };
729
- const code = multiRuntimeTemplate({
730
- schemas: schemaConfigs,
731
- injection,
732
- splitting
733
- });
734
- const injectsCode = options?.injection ? generateInjectsCode(options.injection) : undefined;
735
- const categoryVarsResult = Object.fromEntries(Object.entries(schemaConfigs).map(([schemaName, config]) => {
736
- const toDefVar = (code$1, prefix) => {
737
- const match = code$1.match(new RegExp(`const (${prefix}_${schemaName}_(\\w+))`));
738
- return {
739
- name: match?.[1] ?? "",
740
- code: code$1
741
- };
742
- };
743
- return [schemaName, {
744
- enums: config.enumVars.map((c) => toDefVar(c, "enum")),
745
- inputs: config.inputVars.map((c) => toDefVar(c, "input")),
746
- objects: config.objectVars.map((c) => toDefVar(c, "object")),
747
- unions: config.unionVars.map((c) => toDefVar(c, "union"))
748
- }];
749
- }));
750
- return {
751
- code,
752
- injectsCode,
753
- categoryVars: categoryVarsResult,
754
- stats: allStats
755
- };
756
- };
757
-
758
- //#endregion
759
- Object.defineProperty(exports, 'createSchemaIndex', {
760
- enumerable: true,
761
- get: function () {
762
- return createSchemaIndex;
763
- }
764
- });
765
- Object.defineProperty(exports, 'generateMultiSchemaModule', {
766
- enumerable: true,
767
- get: function () {
768
- return generateMultiSchemaModule;
769
- }
770
- });
771
- //# sourceMappingURL=generator-DvfP6gTY.cjs.map