-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgenerate.ts
More file actions
873 lines (783 loc) · 27.6 KB
/
generate.ts
File metadata and controls
873 lines (783 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
/**
* Main generate function - orchestrates the entire codegen pipeline
*
* This is the primary entry point for programmatic usage.
* The CLI is a thin wrapper around this function.
*/
import * as fs from 'node:fs';
import path from 'node:path';
import { buildClientSchema, printSchema } from 'graphql';
import { PgpmPackage } from '@pgpmjs/core';
import { pgCache } from 'pg-cache';
import { createEphemeralDb, type EphemeralDbResult } from 'pgsql-client';
import { deployPgpm } from 'pgsql-seed';
import type { CliConfig, DbConfig, GraphQLSDKConfigTarget, PgpmConfig, SchemaConfig } from '../types/config';
import { getConfigOptions } from '../types/config';
import type { Operation, Table, TypeRegistry } from '../types/schema';
import { generate as generateReactQueryFiles } from './codegen';
import { generateRootBarrel, generateMultiTargetBarrel } from './codegen/barrel';
import { generateCli as generateCliFiles, generateMultiTargetCli } from './codegen/cli';
import type { MultiTargetCliTarget } from './codegen/cli';
import {
generateReadme as generateCliReadme,
generateAgentsDocs as generateCliAgentsDocs,
getCliMcpTools,
generateSkills as generateCliSkills,
generateMultiTargetReadme,
generateMultiTargetAgentsDocs,
getMultiTargetCliMcpTools,
generateMultiTargetSkills,
} from './codegen/cli/docs-generator';
import type { MultiTargetDocsInput } from './codegen/cli/docs-generator';
import { resolveDocsConfig } from './codegen/docs-utils';
import type { McpTool } from './codegen/docs-utils';
import {
generateHooksReadme,
generateHooksAgentsDocs,
getHooksMcpTools,
generateHooksSkills,
} from './codegen/hooks-docs-generator';
import { generateOrm as generateOrmFiles } from './codegen/orm';
import {
generateOrmReadme,
generateOrmAgentsDocs,
getOrmMcpTools,
generateOrmSkills,
} from './codegen/orm/docs-generator';
import { generateSharedTypes } from './codegen/shared';
import {
generateTargetReadme,
generateCombinedMcpConfig,
generateRootRootReadme,
} from './codegen/target-docs-generator';
import type { RootRootReadmeTarget } from './codegen/target-docs-generator';
import { createSchemaSource, validateSourceOptions } from './introspect';
import { writeGeneratedFiles } from './output';
import { runCodegenPipeline, validateTablesFound } from './pipeline';
import { findWorkspaceRoot } from './workspace';
export interface GenerateOptions extends GraphQLSDKConfigTarget {
authorization?: string;
verbose?: boolean;
dryRun?: boolean;
skipCustomOperations?: boolean;
}
export interface GenerateResult {
success: boolean;
message: string;
output?: string;
tables?: string[];
filesWritten?: string[];
errors?: string[];
pipelineData?: {
tables: Table[];
customOperations: {
queries: Operation[];
mutations: Operation[];
typeRegistry?: TypeRegistry;
};
};
}
/**
* Main generate function - takes a single config and generates code
*
* This is the primary entry point for programmatic usage.
* For multiple configs, call this function in a loop.
*/
export interface GenerateInternalOptions {
skipCli?: boolean;
/**
* Internal-only name for the target when generating skills.
* Used by generateMulti() so skill names are stable and composable.
*/
targetName?: string;
}
function resolveSkillsOutputDir(
config: GraphQLSDKConfigTarget,
outputRoot: string,
): string {
const workspaceRoot =
findWorkspaceRoot(path.resolve(outputRoot)) ??
findWorkspaceRoot(process.cwd()) ??
process.cwd();
if (config.skillsPath) {
return path.isAbsolute(config.skillsPath)
? config.skillsPath
: path.resolve(workspaceRoot, config.skillsPath);
}
return path.resolve(workspaceRoot, '.agents/skills');
}
export async function generate(
options: GenerateOptions = {},
internalOptions?: GenerateInternalOptions,
): Promise<GenerateResult> {
// Apply defaults to get resolved config
const config = getConfigOptions(options);
const outputRoot = config.output;
// Determine which generators to run
// ORM is always required when React Query is enabled (hooks delegate to ORM)
// This handles minimist setting orm=false when --orm flag is absent
const runReactQuery = config.reactQuery ?? false;
const runCli = internalOptions?.skipCli ? false : !!config.cli;
const runOrm =
runReactQuery || !!config.cli || (options.orm !== undefined ? !!options.orm : false);
// Auto-enable nodeHttpAdapter when CLI is enabled, unless explicitly set to false
const useNodeHttpAdapter =
options.nodeHttpAdapter === true ||
(runCli && options.nodeHttpAdapter !== false);
const schemaEnabled = !!options.schema?.enabled;
if (!schemaEnabled && !runReactQuery && !runOrm && !runCli) {
return {
success: false,
message:
'No generators enabled. Use reactQuery: true, orm: true, or cli: true in your config.',
output: outputRoot,
};
}
// Validate source
const sourceValidation = validateSourceOptions({
endpoint: config.endpoint || undefined,
schemaFile: config.schemaFile || undefined,
db: config.db,
});
if (!sourceValidation.valid) {
return {
success: false,
message: sourceValidation.error!,
output: outputRoot,
};
}
const source = createSchemaSource({
endpoint: config.endpoint || undefined,
schemaFile: config.schemaFile || undefined,
db: config.db,
authorization: options.authorization || config.headers?.Authorization,
headers: config.headers,
});
if (schemaEnabled && !runReactQuery && !runOrm && !runCli) {
try {
console.log(`Fetching schema from ${source.describe()}...`);
const { introspection } = await source.fetch();
const schema = buildClientSchema(introspection as any);
const sdl = printSchema(schema);
if (!sdl.trim()) {
return {
success: false,
message: 'Schema introspection returned empty SDL.',
output: outputRoot,
};
}
const outDir = path.resolve(options.schema?.output || outputRoot || '.');
await fs.promises.mkdir(outDir, { recursive: true });
const filename = options.schema?.filename || 'schema.graphql';
const filePath = path.join(outDir, filename);
await fs.promises.writeFile(filePath, sdl, 'utf-8');
return {
success: true,
message: `Schema exported to ${filePath}`,
output: outDir,
filesWritten: [filePath],
};
} catch (err) {
return {
success: false,
message: `Failed to export schema: ${err instanceof Error ? err.message : 'Unknown error'}`,
output: outputRoot,
};
}
}
// Run pipeline
let pipelineResult: Awaited<ReturnType<typeof runCodegenPipeline>>;
try {
console.log(`Fetching schema from ${source.describe()}...`);
pipelineResult = await runCodegenPipeline({
source,
config,
verbose: options.verbose,
skipCustomOperations: options.skipCustomOperations,
});
} catch (err) {
return {
success: false,
message: `Failed to fetch schema: ${err instanceof Error ? err.message : 'Unknown error'}`,
output: outputRoot,
};
}
const { tables, customOperations } = pipelineResult;
// Validate tables
const tablesValidation = validateTablesFound(tables);
if (!tablesValidation.valid) {
return {
success: false,
message: tablesValidation.error!,
output: outputRoot,
};
}
const allFilesWritten: string[] = [];
const bothEnabled = runReactQuery && runOrm;
const filesToWrite: Array<{ path: string; content: string }> = [];
// Generate shared types when both are enabled
if (bothEnabled) {
console.log('Generating shared types...');
const sharedResult = generateSharedTypes({
tables,
customOperations: {
queries: customOperations.queries,
mutations: customOperations.mutations,
typeRegistry: customOperations.typeRegistry,
},
config,
});
filesToWrite.push(...sharedResult.files);
}
// Generate React Query hooks
if (runReactQuery) {
console.log('Generating React Query hooks...');
const { files } = generateReactQueryFiles({
tables,
customOperations: {
queries: customOperations.queries,
mutations: customOperations.mutations,
typeRegistry: customOperations.typeRegistry,
},
config,
sharedTypesPath: bothEnabled ? '..' : undefined,
});
filesToWrite.push(
...files.map((file) => ({
...file,
path: path.posix.join('hooks', file.path),
})),
);
}
// Generate ORM client
if (runOrm) {
console.log('Generating ORM client...');
const { files } = generateOrmFiles({
tables,
customOperations: {
queries: customOperations.queries,
mutations: customOperations.mutations,
typeRegistry: customOperations.typeRegistry,
},
config: { ...config, nodeHttpAdapter: useNodeHttpAdapter },
sharedTypesPath: bothEnabled ? '..' : undefined,
});
filesToWrite.push(
...files.map((file) => ({
...file,
path: path.posix.join('orm', file.path),
})),
);
// Generate NodeHttpAdapter in ORM output when enabled
if (useNodeHttpAdapter) {
const { generateNodeFetchFile } = await import('./codegen/cli/utils-generator');
const nodeFetchFile = generateNodeFetchFile();
filesToWrite.push({
path: path.posix.join('orm', nodeFetchFile.fileName),
content: nodeFetchFile.content,
});
}
}
// Generate CLI commands
if (runCli) {
console.log('Generating CLI commands...');
const { files } = generateCliFiles({
tables,
customOperations: {
queries: customOperations.queries,
mutations: customOperations.mutations,
},
config: { ...config, nodeHttpAdapter: useNodeHttpAdapter },
typeRegistry: customOperations.typeRegistry,
});
filesToWrite.push(
...files.map((file) => ({
path: path.posix.join('cli', file.fileName),
content: file.content,
})),
);
}
// Generate barrel file at output root
const barrelContent = generateRootBarrel({
hasTypes: bothEnabled,
hasHooks: runReactQuery,
hasOrm: runOrm,
hasCli: runCli,
});
filesToWrite.push({ path: 'index.ts', content: barrelContent });
// Generate docs for each enabled generator
const docsConfig = resolveDocsConfig(config.docs);
const allCustomOps: Operation[] = [
...(customOperations.queries ?? []),
...(customOperations.mutations ?? []),
];
const allMcpTools: McpTool[] = [];
const targetName = internalOptions?.targetName ?? 'default';
const skillsToWrite: Array<{ path: string; content: string }> = [];
if (runOrm) {
if (docsConfig.readme) {
const readme = generateOrmReadme(tables, allCustomOps, customOperations.typeRegistry);
filesToWrite.push({ path: path.posix.join('orm', readme.fileName), content: readme.content });
}
if (docsConfig.agents) {
const agents = generateOrmAgentsDocs(tables, allCustomOps);
filesToWrite.push({ path: path.posix.join('orm', agents.fileName), content: agents.content });
}
if (docsConfig.mcp) {
allMcpTools.push(...getOrmMcpTools(tables, allCustomOps));
}
if (docsConfig.skills) {
for (const skill of generateOrmSkills(tables, allCustomOps, targetName, customOperations.typeRegistry)) {
skillsToWrite.push({ path: skill.fileName, content: skill.content });
}
}
}
if (runReactQuery) {
if (docsConfig.readme) {
const readme = generateHooksReadme(tables, allCustomOps, customOperations.typeRegistry);
filesToWrite.push({ path: path.posix.join('hooks', readme.fileName), content: readme.content });
}
if (docsConfig.agents) {
const agents = generateHooksAgentsDocs(tables, allCustomOps);
filesToWrite.push({ path: path.posix.join('hooks', agents.fileName), content: agents.content });
}
if (docsConfig.mcp) {
allMcpTools.push(...getHooksMcpTools(tables, allCustomOps));
}
if (docsConfig.skills) {
for (const skill of generateHooksSkills(tables, allCustomOps, targetName, customOperations.typeRegistry)) {
skillsToWrite.push({ path: skill.fileName, content: skill.content });
}
}
}
if (runCli) {
const toolName =
typeof config.cli === 'object' && config.cli?.toolName
? config.cli.toolName
: 'app';
if (docsConfig.readme) {
const readme = generateCliReadme(tables, allCustomOps, toolName, customOperations.typeRegistry);
filesToWrite.push({ path: path.posix.join('cli', readme.fileName), content: readme.content });
}
if (docsConfig.agents) {
const agents = generateCliAgentsDocs(tables, allCustomOps, toolName, customOperations.typeRegistry);
filesToWrite.push({ path: path.posix.join('cli', agents.fileName), content: agents.content });
}
if (docsConfig.mcp) {
allMcpTools.push(...getCliMcpTools(tables, allCustomOps, toolName, customOperations.typeRegistry));
}
if (docsConfig.skills) {
for (const skill of generateCliSkills(tables, allCustomOps, toolName, targetName, customOperations.typeRegistry)) {
skillsToWrite.push({ path: skill.fileName, content: skill.content });
}
}
}
// Generate combined mcp.json at output root
if (docsConfig.mcp && allMcpTools.length > 0) {
const mcpName =
typeof config.cli === 'object' && config.cli?.toolName
? config.cli.toolName
: 'graphql-sdk';
const mcpFile = generateCombinedMcpConfig(allMcpTools, mcpName);
filesToWrite.push({ path: mcpFile.fileName, content: mcpFile.content });
}
// Generate per-target README at output root
if (docsConfig.readme) {
const targetReadme = generateTargetReadme({
hasOrm: runOrm,
hasHooks: runReactQuery,
hasCli: runCli,
tableCount: tables.length,
customQueryCount: customOperations.queries.length,
customMutationCount: customOperations.mutations.length,
config,
});
filesToWrite.push({ path: targetReadme.fileName, content: targetReadme.content });
}
if (!options.dryRun) {
const writeResult = await writeGeneratedFiles(filesToWrite, outputRoot, [], {
pruneStaleFiles: true,
});
if (!writeResult.success) {
return {
success: false,
message: `Failed to write generated files: ${writeResult.errors?.join(', ')}`,
output: outputRoot,
errors: writeResult.errors,
};
}
allFilesWritten.push(...(writeResult.filesWritten ?? []));
if (skillsToWrite.length > 0) {
const skillsOutputDir = resolveSkillsOutputDir(config, outputRoot);
const skillsWriteResult = await writeGeneratedFiles(skillsToWrite, skillsOutputDir, [], {
pruneStaleFiles: false,
});
if (!skillsWriteResult.success) {
return {
success: false,
message: `Failed to write generated skill files: ${skillsWriteResult.errors?.join(', ')}`,
output: skillsOutputDir,
errors: skillsWriteResult.errors,
};
}
allFilesWritten.push(...(skillsWriteResult.filesWritten ?? []));
}
}
const generators = [
runReactQuery && 'React Query',
runOrm && 'ORM',
runCli && 'CLI',
]
.filter(Boolean)
.join(' and ');
return {
success: true,
message: options.dryRun
? `Dry run complete. Would generate ${generators} for ${tables.length} tables.`
: `Generated ${generators} for ${tables.length} tables. Files written to ${outputRoot}`,
output: outputRoot,
tables: tables.map((t) => t.name),
filesWritten: allFilesWritten,
pipelineData: {
tables,
customOperations: {
queries: customOperations.queries,
mutations: customOperations.mutations,
typeRegistry: customOperations.typeRegistry,
},
},
};
}
export function expandApiNamesToMultiTarget(
config: GraphQLSDKConfigTarget,
): Record<string, GraphQLSDKConfigTarget> | null {
const apiNames = config.db?.apiNames;
if (!apiNames || apiNames.length <= 1) return null;
const targets: Record<string, GraphQLSDKConfigTarget> = {};
for (const apiName of apiNames) {
targets[apiName] = {
...config,
db: {
...config.db,
apiNames: [apiName],
},
output: config.output
? `${config.output}/${apiName}`
: `./generated/graphql/${apiName}`,
};
}
return targets;
}
export function expandSchemaDirToMultiTarget(
config: GraphQLSDKConfigTarget,
): Record<string, GraphQLSDKConfigTarget> | null {
const schemaDir = config.schemaDir;
if (!schemaDir) return null;
const resolvedDir = path.resolve(schemaDir);
if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {
return null;
}
const graphqlFiles = fs.readdirSync(resolvedDir)
.filter((f) => f.endsWith('.graphql'))
.sort();
if (graphqlFiles.length === 0) return null;
const targets: Record<string, GraphQLSDKConfigTarget> = {};
for (const file of graphqlFiles) {
const name = path.basename(file, '.graphql');
targets[name] = {
...config,
schemaDir: undefined,
schemaFile: path.join(resolvedDir, file),
output: config.output
? `${config.output}/${name}`
: `./generated/graphql/${name}`,
};
}
return targets;
}
export interface GenerateMultiOptions {
configs: Record<string, GraphQLSDKConfigTarget>;
cliOverrides?: Partial<GraphQLSDKConfigTarget>;
verbose?: boolean;
dryRun?: boolean;
schema?: SchemaConfig;
unifiedCli?: CliConfig | boolean;
}
export interface GenerateMultiResult {
results: Array<{ name: string; result: GenerateResult }>;
hasError: boolean;
}
interface SharedPgpmSource {
key: string;
ephemeralDb: EphemeralDbResult;
deployed: boolean;
}
function getPgpmSourceKey(pgpm: PgpmConfig): string | null {
if (pgpm.modulePath) return `module:${path.resolve(pgpm.modulePath)}`;
if (pgpm.workspacePath && pgpm.moduleName)
return `workspace:${path.resolve(pgpm.workspacePath)}:${pgpm.moduleName}`;
return null;
}
function getModulePathFromPgpm(
pgpm: PgpmConfig,
): string {
if (pgpm.modulePath) return pgpm.modulePath;
if (pgpm.workspacePath && pgpm.moduleName) {
const workspace = new PgpmPackage(pgpm.workspacePath);
const moduleProject = workspace.getModuleProject(pgpm.moduleName);
const modulePath = moduleProject.getModulePath();
if (!modulePath) {
throw new Error(`Module "${pgpm.moduleName}" not found in workspace`);
}
return modulePath;
}
throw new Error('Invalid PGPM config: requires modulePath or workspacePath+moduleName');
}
async function prepareSharedPgpmSources(
configs: Record<string, GraphQLSDKConfigTarget>,
cliOverrides?: Partial<GraphQLSDKConfigTarget>,
): Promise<Map<string, SharedPgpmSource>> {
const sharedSources = new Map<string, SharedPgpmSource>();
const pgpmTargetCount = new Map<string, number>();
for (const name of Object.keys(configs)) {
const merged = { ...configs[name], ...(cliOverrides ?? {}) };
const pgpm = merged.db?.pgpm;
if (!pgpm) continue;
const key = getPgpmSourceKey(pgpm);
if (!key) continue;
pgpmTargetCount.set(key, (pgpmTargetCount.get(key) ?? 0) + 1);
}
for (const [key, count] of pgpmTargetCount) {
if (count < 2) continue;
let pgpmConfig: PgpmConfig | undefined;
for (const name of Object.keys(configs)) {
const merged = { ...configs[name], ...(cliOverrides ?? {}) };
const pgpm = merged.db?.pgpm;
if (pgpm && getPgpmSourceKey(pgpm) === key) {
pgpmConfig = pgpm;
break;
}
}
if (!pgpmConfig) continue;
const ephemeralDb = createEphemeralDb({
prefix: 'codegen_pgpm_shared_',
verbose: false,
});
const modulePath = getModulePathFromPgpm(pgpmConfig);
await deployPgpm(ephemeralDb.config, modulePath, false);
sharedSources.set(key, {
key,
ephemeralDb,
deployed: true,
});
console.log(
`[multi-target] Shared PGPM source deployed once for ${count} targets: ${key}`,
);
}
return sharedSources;
}
function applySharedPgpmDb(
config: GraphQLSDKConfigTarget,
sharedSources: Map<string, SharedPgpmSource>,
): GraphQLSDKConfigTarget {
const pgpm = config.db?.pgpm;
if (!pgpm) return config;
const key = getPgpmSourceKey(pgpm);
if (!key) return config;
const shared = sharedSources.get(key);
if (!shared) return config;
const sharedDbConfig: DbConfig = {
...config.db,
pgpm: undefined,
config: shared.ephemeralDb.config,
keepDb: true,
};
return {
...config,
db: sharedDbConfig,
};
}
export async function generateMulti(
options: GenerateMultiOptions,
): Promise<GenerateMultiResult> {
const { configs, cliOverrides, verbose, dryRun, schema, unifiedCli } = options;
const names = Object.keys(configs);
const results: Array<{ name: string; result: GenerateResult }> = [];
let hasError = false;
const schemaEnabled = !!schema?.enabled;
const targetInfos: RootRootReadmeTarget[] = [];
const useUnifiedCli = !schemaEnabled && !!unifiedCli && names.length > 1;
const cliTargets: MultiTargetCliTarget[] = [];
const sharedSources = await prepareSharedPgpmSources(configs, cliOverrides);
try {
for (const name of names) {
const baseConfig: GraphQLSDKConfigTarget = {
...configs[name],
...(cliOverrides ?? {}),
};
const targetConfig = applySharedPgpmDb(baseConfig, sharedSources);
const result = await generate(
{
...targetConfig,
verbose,
dryRun,
schema: schemaEnabled
? { ...schema, filename: schema?.filename ?? `${name}.graphql` }
: targetConfig.schema,
},
useUnifiedCli ? { skipCli: true, targetName: name } : { targetName: name },
);
results.push({ name, result });
if (!result.success) {
hasError = true;
} else {
const resolvedConfig = getConfigOptions(targetConfig);
const gens: string[] = [];
if (resolvedConfig.reactQuery) gens.push('React Query');
if (resolvedConfig.orm || resolvedConfig.reactQuery || !!resolvedConfig.cli) gens.push('ORM');
if (resolvedConfig.cli) gens.push('CLI');
targetInfos.push({
name,
output: resolvedConfig.output,
endpoint: resolvedConfig.endpoint || undefined,
generators: gens,
});
if (useUnifiedCli && result.pipelineData) {
const isAuthTarget = name === 'auth';
cliTargets.push({
name,
endpoint: resolvedConfig.endpoint || '',
ormImportPath: `../${resolvedConfig.output.replace(/^\.\//, '')}/orm`,
tables: result.pipelineData.tables,
customOperations: result.pipelineData.customOperations,
isAuthTarget,
typeRegistry: result.pipelineData.customOperations.typeRegistry,
});
}
}
}
if (useUnifiedCli && cliTargets.length > 0 && !dryRun) {
const cliConfig = typeof unifiedCli === 'object' ? unifiedCli : {};
const toolName = cliConfig.toolName ?? 'app';
// Auto-enable nodeHttpAdapter for unified CLI unless explicitly disabled
// Check first target config for explicit nodeHttpAdapter setting
const firstTargetConfig = configs[names[0]];
const multiNodeHttpAdapter =
firstTargetConfig?.nodeHttpAdapter === true ||
(firstTargetConfig?.nodeHttpAdapter !== false);
const { files } = generateMultiTargetCli({
toolName,
builtinNames: cliConfig.builtinNames,
targets: cliTargets,
nodeHttpAdapter: multiNodeHttpAdapter,
entryPoint: cliConfig.entryPoint,
});
const cliFilesToWrite = files.map((file) => ({
path: path.posix.join('cli', file.fileName),
content: file.content,
}));
const firstTargetDocsConfig = names.length > 0 && configs[names[0]]?.docs;
const docsConfig = resolveDocsConfig(firstTargetDocsConfig);
const { resolveBuiltinNames } = await import('./codegen/cli');
const builtinNames = resolveBuiltinNames(
cliTargets.map((t) => t.name),
cliConfig.builtinNames,
);
// Merge all target type registries into a combined registry for docs generation
const combinedRegistry = new Map<string, import('../types/schema').ResolvedType>();
for (const t of cliTargets) {
if (t.typeRegistry) {
for (const [key, value] of t.typeRegistry) {
combinedRegistry.set(key, value);
}
}
}
const docsInput: MultiTargetDocsInput = {
toolName,
builtinNames,
registry: combinedRegistry.size > 0 ? combinedRegistry : undefined,
targets: cliTargets.map((t) => ({
name: t.name,
endpoint: t.endpoint,
tables: t.tables,
customOperations: [
...(t.customOperations?.queries ?? []),
...(t.customOperations?.mutations ?? []),
],
isAuthTarget: t.isAuthTarget,
})),
};
const allMcpTools: McpTool[] = [];
if (docsConfig.readme) {
const readme = generateMultiTargetReadme(docsInput);
cliFilesToWrite.push({ path: path.posix.join('cli', readme.fileName), content: readme.content });
}
if (docsConfig.agents) {
const agents = generateMultiTargetAgentsDocs(docsInput);
cliFilesToWrite.push({ path: path.posix.join('cli', agents.fileName), content: agents.content });
}
if (docsConfig.mcp) {
allMcpTools.push(...getMultiTargetCliMcpTools(docsInput));
}
if (docsConfig.mcp && allMcpTools.length > 0) {
const mcpFile = generateCombinedMcpConfig(allMcpTools, toolName);
cliFilesToWrite.push({ path: path.posix.join('cli', mcpFile.fileName), content: mcpFile.content });
}
const { writeGeneratedFiles: writeFiles } = await import('./output');
await writeFiles(cliFilesToWrite, '.', [], { pruneStaleFiles: false });
if (docsConfig.skills) {
const cliSkillsToWrite = generateMultiTargetSkills(docsInput).map((skill) => ({
path: skill.fileName,
content: skill.content,
}));
const firstTargetResolved = getConfigOptions({
...(firstTargetConfig ?? {}),
...(cliOverrides ?? {}),
});
const skillsOutputDir = resolveSkillsOutputDir(
firstTargetResolved,
firstTargetResolved.output,
);
await writeFiles(cliSkillsToWrite, skillsOutputDir, [], { pruneStaleFiles: false });
}
}
// Generate root-root README and barrel if multi-target
if (names.length > 1 && targetInfos.length > 0 && !dryRun) {
const { writeGeneratedFiles: writeFiles } = await import('./output');
const rootReadme = generateRootRootReadme(targetInfos);
await writeFiles(
[{ path: rootReadme.fileName, content: rootReadme.content }],
'.',
[],
{ pruneStaleFiles: false },
);
// Write a root barrel (index.ts) that re-exports each target as a
// namespace so the package has a single entry-point. Derive the
// common output root from the first target's output path.
const successfulNames = results
.filter((r) => r.result.success)
.map((r) => r.name);
if (successfulNames.length > 0) {
const firstOutput = getConfigOptions(configs[successfulNames[0]]).output;
const outputRoot = path.dirname(firstOutput);
const barrelContent = generateMultiTargetBarrel(successfulNames);
await writeFiles(
[{ path: 'index.ts', content: barrelContent }],
outputRoot,
[],
{ pruneStaleFiles: false },
);
}
}
} finally {
for (const shared of sharedSources.values()) {
const keepDb = Object.values(configs).some((c) => c.db?.keepDb);
// Release pg-cache pool for this ephemeral database before dropping
// deployPgpm() caches connections that must be closed first
pgCache.delete(shared.ephemeralDb.config.database);
await pgCache.waitForDisposals();
shared.ephemeralDb.teardown({ keepDb });
}
}
return { results, hasError };
}