@corpdk/codegen-cli 2026.10.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CorpDK
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ import { Types } from '@graphql-codegen/plugin-helpers';
2
+
3
+ interface Config {
4
+ /** Name of the env var that holds the HTTP endpoint. Default: DS_HTTP_URL */
5
+ httpUrlEnvVar?: string;
6
+ /** Name of the env var that holds the WebSocket endpoint. Default: DS_WS_URL */
7
+ wsUrlEnvVar?: string;
8
+ }
9
+ declare const preset: Types.OutputPreset<Config>;
10
+
11
+ export { type Config, preset };
package/dist/index.js ADDED
@@ -0,0 +1,670 @@
1
+ // src/index.ts
2
+ import { buildASTSchema } from "graphql";
3
+
4
+ // src/schema-utils.ts
5
+ import {
6
+ isScalarType,
7
+ isEnumType,
8
+ isObjectType,
9
+ isNonNullType,
10
+ isListType,
11
+ getNamedType
12
+ } from "graphql";
13
+ function toKebabCase(name) {
14
+ return name.replaceAll(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
15
+ }
16
+ function toPascalCase(name) {
17
+ return name.charAt(0).toUpperCase() + name.slice(1);
18
+ }
19
+ function getGraphqlTypeString(type) {
20
+ if (isNonNullType(type)) return `${getGraphqlTypeString(type.ofType)}!`;
21
+ if (isListType(type)) return `[${getGraphqlTypeString(type.ofType)}]`;
22
+ return type.name;
23
+ }
24
+ function getParseType(type) {
25
+ const named = getNamedType(type);
26
+ if (named.name === "Boolean") return "boolean";
27
+ return "string";
28
+ }
29
+ function buildSelectionSet(type, depth = 0) {
30
+ if (depth > 6) return null;
31
+ const named = getNamedType(type);
32
+ if (isScalarType(named) || isEnumType(named)) {
33
+ return null;
34
+ }
35
+ if (isObjectType(named)) {
36
+ const fields = named.getFields();
37
+ const parts = [];
38
+ for (const [fieldName, field] of Object.entries(fields)) {
39
+ const namedFieldType = getNamedType(field.type);
40
+ if (isScalarType(namedFieldType) || isEnumType(namedFieldType)) {
41
+ parts.push(fieldName);
42
+ } else {
43
+ const nested = buildSelectionSet(field.type, depth + 1);
44
+ if (nested) parts.push(`${fieldName} ${nested}`);
45
+ }
46
+ }
47
+ if (parts.length === 0) return null;
48
+ return `{ ${parts.join(" ")} }`;
49
+ }
50
+ return null;
51
+ }
52
+ function buildDocument(opType, fieldName, args, returnType) {
53
+ const opName = toPascalCase(fieldName);
54
+ const selection = buildSelectionSet(returnType);
55
+ const varDecls = args.map((a) => `$${a.name}: ${a.graphqlType}`);
56
+ const varStr = varDecls.length > 0 ? `(${varDecls.join(", ")})` : "";
57
+ const fieldArgs = args.map((a) => `${a.name}: $${a.name}`);
58
+ const fieldArgStr = fieldArgs.length > 0 ? `(${fieldArgs.join(", ")})` : "";
59
+ const fieldPart = selection ? `${fieldName}${fieldArgStr} ${selection}` : `${fieldName}${fieldArgStr}`;
60
+ return `${opType} ${opName}${varStr} { ${fieldPart} }`;
61
+ }
62
+ function extractOperations(schema) {
63
+ const ops = [];
64
+ const roots = [
65
+ ["query", schema.getQueryType()],
66
+ ["mutation", schema.getMutationType()],
67
+ ["subscription", schema.getSubscriptionType()]
68
+ ];
69
+ for (const [opType, rootType] of roots) {
70
+ if (!rootType) continue;
71
+ const fields = rootType.getFields();
72
+ for (const [fieldName, field] of Object.entries(fields)) {
73
+ const args = field.args.map((arg) => ({
74
+ name: arg.name,
75
+ graphqlType: getGraphqlTypeString(arg.type),
76
+ parseType: getParseType(arg.type),
77
+ description: arg.description ?? "",
78
+ required: isNonNullType(arg.type)
79
+ }));
80
+ ops.push({
81
+ operationType: opType,
82
+ fieldName,
83
+ commandName: toKebabCase(fieldName),
84
+ description: field.description ?? "",
85
+ args,
86
+ document: buildDocument(
87
+ opType,
88
+ fieldName,
89
+ args,
90
+ field.type
91
+ )
92
+ });
93
+ }
94
+ }
95
+ return ops;
96
+ }
97
+
98
+ // src/gen-cli.ts
99
+ function serializeOperations(ops) {
100
+ const entries = ops.map((op) => {
101
+ const argEntries = op.args.map(
102
+ (a) => ` ${JSON.stringify(a.name)}: { parseType: "${a.parseType}", graphqlType: ${JSON.stringify(a.graphqlType)}, description: ${JSON.stringify(a.description)}, required: ${a.required} }`
103
+ );
104
+ return ` ${JSON.stringify(op.commandName)}: {
105
+ operationType: "${op.operationType}",
106
+ description: ${JSON.stringify(op.description)},
107
+ document: \`${op.document}\`,
108
+ args: {
109
+ ` + (argEntries.length > 0 ? argEntries.join(",\n") + "\n" : "") + ` },
110
+ }`;
111
+ });
112
+ return `const OPERATIONS = {
113
+ ${entries.join(",\n")}
114
+ };`;
115
+ }
116
+ var RUNTIME_LINES = [
117
+ "// ---------------------------------------------------------------------------",
118
+ "// Runtime helpers",
119
+ "// ---------------------------------------------------------------------------",
120
+ "",
121
+ "function printHelp(name) {",
122
+ ' const queries = Object.entries(OPERATIONS).filter(([,o]) => o.operationType === "query");',
123
+ ' const mutations = Object.entries(OPERATIONS).filter(([,o]) => o.operationType === "mutation");',
124
+ ' const subs = Object.entries(OPERATIONS).filter(([,o]) => o.operationType === "subscription");',
125
+ "",
126
+ " function fmtArgs(args) {",
127
+ " return Object.entries(args).map(([n, a]) =>",
128
+ ' a.required ? "--" + n + " <" + a.graphqlType + ">" : "[--" + n + " <" + a.graphqlType + ">]"',
129
+ ' ).join(" ");',
130
+ " }",
131
+ "",
132
+ String.raw` let h = "Usage: " + name + " <command> [options]\n\n";`,
133
+ "",
134
+ " if (queries.length) {",
135
+ String.raw` h += "Queries:\n";`,
136
+ " for (const [cmd, op] of queries) {",
137
+ " const a = fmtArgs(op.args);",
138
+ String.raw` h += " " + cmd + (a ? " " + a : "") + "\n";`,
139
+ String.raw` h += " " + op.description + "\n";`,
140
+ " }",
141
+ String.raw` h += "\n";`,
142
+ " }",
143
+ "",
144
+ " if (mutations.length) {",
145
+ String.raw` h += "Mutations:\n";`,
146
+ " for (const [cmd, op] of mutations) {",
147
+ " const a = fmtArgs(op.args);",
148
+ String.raw` h += " " + cmd + (a ? " " + a : "") + "\n";`,
149
+ String.raw` h += " " + op.description + "\n";`,
150
+ " }",
151
+ String.raw` h += "\n";`,
152
+ " }",
153
+ "",
154
+ " if (subs.length) {",
155
+ String.raw` h += "Subscriptions (streams NDJSON until Ctrl-C or --count/--timeout):\n";`,
156
+ " for (const [cmd, op] of subs) {",
157
+ String.raw` h += " " + cmd + " [--count N] [--timeout Ms]\n";`,
158
+ String.raw` h += " " + op.description + "\n";`,
159
+ " }",
160
+ String.raw` h += "\n";`,
161
+ " }",
162
+ "",
163
+ String.raw` h += "Input (mutations/queries with variables):\n";`,
164
+ String.raw` h += " --input <file.json> Read variables from JSON file\n";`,
165
+ String.raw` h += " (stdin) Pipe JSON when stdin is not a TTY\n";`,
166
+ String.raw` h += " Merge order: --input file < piped stdin < explicit flags\n\n";`,
167
+ "",
168
+ String.raw` h += "Output: newline-delimited JSON on stdout. Errors on stderr (exit 1).\n\n";`,
169
+ "",
170
+ String.raw` h += "Environment:\n";`,
171
+ String.raw` h += " DS_HTTP_URL " + DS_HTTP_URL + "\n";`,
172
+ String.raw` h += " DS_WS_URL " + DS_WS_URL + "\n";`,
173
+ "",
174
+ " process.stdout.write(h);",
175
+ "}",
176
+ "",
177
+ "function coerceArg(value, graphqlType) {",
178
+ String.raw` const base = graphqlType.replace(/[!\[\]]/g, "");`,
179
+ ' if (base === "Int") return parseInt(value, 10);',
180
+ ' if (base === "Float") return parseFloat(value);',
181
+ " return value;",
182
+ "}",
183
+ "",
184
+ "async function executeHttp(document, variables) {",
185
+ " const body = JSON.stringify({ query: document, variables });",
186
+ " let res;",
187
+ " try {",
188
+ " res = await fetch(DS_HTTP_URL, {",
189
+ ' method: "POST",',
190
+ ' headers: { "Content-Type": "application/json", "Accept": "application/json" },',
191
+ " body,",
192
+ " });",
193
+ " } catch (err) {",
194
+ String.raw` process.stderr.write("Connection failed: " + err.message + "\n");`,
195
+ " process.exit(1);",
196
+ " }",
197
+ " const json = await res.json();",
198
+ " if (json.errors) {",
199
+ String.raw` process.stderr.write(JSON.stringify(json.errors, null, 2) + "\n");`,
200
+ " process.exit(1);",
201
+ " }",
202
+ " return json;",
203
+ "}",
204
+ "",
205
+ "function executeSubscription(document, variables, opts) {",
206
+ " const { count, timeout } = opts;",
207
+ " return new Promise((resolve, reject) => {",
208
+ " let ws;",
209
+ " try {",
210
+ ' ws = new WebSocket(DS_WS_URL, "graphql-transport-ws");',
211
+ " } catch (err) {",
212
+ ' reject(new Error("WebSocket connection failed: " + err.message));',
213
+ " return;",
214
+ " }",
215
+ " let received = 0;",
216
+ " let done = false;",
217
+ "",
218
+ " function finish() {",
219
+ " if (done) return;",
220
+ " done = true;",
221
+ " try { ws.close(); } catch (_) {}",
222
+ " resolve(undefined);",
223
+ " }",
224
+ "",
225
+ " ws.onopen = () => {",
226
+ ' ws.send(JSON.stringify({ type: "connection_init", payload: {} }));',
227
+ " };",
228
+ "",
229
+ " ws.onmessage = (event) => {",
230
+ " let msg;",
231
+ " try { msg = JSON.parse(event.data); } catch { return; }",
232
+ ' if (msg.type === "connection_ack") {',
233
+ ' ws.send(JSON.stringify({ id: "1", type: "subscribe",',
234
+ " payload: { query: document, variables } }));",
235
+ ' } else if (msg.type === "next") {',
236
+ String.raw` process.stdout.write(JSON.stringify(msg.payload) + "\n");`,
237
+ " received++;",
238
+ " if (count !== undefined && received >= count) finish();",
239
+ ' } else if (msg.type === "error") {',
240
+ String.raw` process.stderr.write(JSON.stringify(msg.payload) + "\n");`,
241
+ " finish();",
242
+ ' } else if (msg.type === "complete") {',
243
+ " finish();",
244
+ " }",
245
+ " };",
246
+ "",
247
+ " ws.onerror = (err) => {",
248
+ ' if (!done) reject(new Error("WebSocket error: " + err.message));',
249
+ " };",
250
+ " ws.onclose = () => { if (!done) finish(); };",
251
+ "",
252
+ " if (timeout !== undefined) setTimeout(finish, timeout);",
253
+ "",
254
+ ' process.on("SIGINT", finish);',
255
+ ' process.on("SIGTERM", finish);',
256
+ " });",
257
+ "}",
258
+ "",
259
+ "async function readInputVars(inputFile) {",
260
+ " let vars = {};",
261
+ " if (inputFile) {",
262
+ " try {",
263
+ ' vars = JSON.parse(readFileSync(inputFile, "utf8"));',
264
+ " } catch (err) {",
265
+ String.raw` process.stderr.write("Failed to read --input file: " + err.message + "\n");`,
266
+ " process.exit(1);",
267
+ " }",
268
+ " }",
269
+ " if (!process.stdin.isTTY) {",
270
+ " const chunks = [];",
271
+ " for await (const chunk of process.stdin) chunks.push(chunk);",
272
+ " const raw = Buffer.concat(chunks).toString().trim();",
273
+ " if (raw) {",
274
+ " try { Object.assign(vars, JSON.parse(raw)); }",
275
+ String.raw` catch (err) { process.stderr.write("Invalid JSON on stdin: " + err.message + "\n"); process.exit(1); }`,
276
+ " }",
277
+ " }",
278
+ " return vars;",
279
+ "}",
280
+ "",
281
+ "async function main() {",
282
+ " const argv = process.argv.slice(2);",
283
+ " const cmd = argv[0];",
284
+ ' const BIN = basename(process.argv[1], ".js");',
285
+ "",
286
+ ' if (!cmd || cmd === "--help" || cmd === "-h") {',
287
+ " printHelp(BIN);",
288
+ " process.exit(0);",
289
+ " }",
290
+ "",
291
+ " const op = OPERATIONS[cmd];",
292
+ " if (!op) {",
293
+ String.raw` process.stderr.write('Error: unknown command "' + cmd + '"\n\n');`,
294
+ " printHelp(BIN);",
295
+ " process.exit(1);",
296
+ " }",
297
+ "",
298
+ " // Build parseArgs option map from operation args",
299
+ ' const optionMap = { help: { type: "boolean", short: "h" }, input: { type: "string" } };',
300
+ ' if (op.operationType === "subscription") {',
301
+ ' optionMap["count"] = { type: "string" };',
302
+ ' optionMap["timeout"] = { type: "string" };',
303
+ " }",
304
+ " for (const [n, a] of Object.entries(op.args)) {",
305
+ " optionMap[n] = { type: a.parseType };",
306
+ " }",
307
+ "",
308
+ " let values;",
309
+ " try {",
310
+ " ({ values } = parseArgs({ args: argv.slice(1), options: optionMap, allowPositionals: false }));",
311
+ " } catch (err) {",
312
+ String.raw` process.stderr.write("Error: " + err.message + "\n");`,
313
+ " process.exit(1);",
314
+ " }",
315
+ "",
316
+ ' if (values["help"]) {',
317
+ ' let h = "Usage: " + BIN + " " + cmd;',
318
+ " for (const [n, a] of Object.entries(op.args)) {",
319
+ ' h += a.required ? " --" + n + " <" + a.graphqlType + ">" : " [--" + n + " <" + a.graphqlType + ">]";',
320
+ " }",
321
+ String.raw` h += "\n\n" + op.description + "\n";`,
322
+ " process.stdout.write(h);",
323
+ " process.exit(0);",
324
+ " }",
325
+ "",
326
+ ' const baseVars = await readInputVars(values["input"]);',
327
+ " const variables = Object.assign({}, baseVars);",
328
+ "",
329
+ " for (const [n, a] of Object.entries(op.args)) {",
330
+ " if (values[n] !== undefined) {",
331
+ " variables[n] = coerceArg(values[n], a.graphqlType);",
332
+ " }",
333
+ " if (a.required && variables[n] === undefined) {",
334
+ String.raw` process.stderr.write("Error: --" + n + " is required\n");`,
335
+ " process.exit(1);",
336
+ " }",
337
+ " }",
338
+ "",
339
+ ' if (op.operationType === "subscription") {',
340
+ " await executeSubscription(op.document, variables, {",
341
+ ' count: values["count"] !== undefined ? parseInt(values["count"], 10) : undefined,',
342
+ ' timeout: values["timeout"] !== undefined ? parseInt(values["timeout"], 10) : undefined,',
343
+ " });",
344
+ " } else {",
345
+ " const result = await executeHttp(op.document, variables);",
346
+ String.raw` process.stdout.write(JSON.stringify(result) + "\n");`,
347
+ " }",
348
+ "}"
349
+ ];
350
+ function generateCli(ops, config) {
351
+ const httpEnvVar = config.httpUrlEnvVar ?? "DS_HTTP_URL";
352
+ const wsEnvVar = config.wsUrlEnvVar ?? "DS_WS_URL";
353
+ const header = [
354
+ "#!/usr/bin/env node",
355
+ "// @generated \u2014 do not edit manually",
356
+ "// Regenerate by running: pnpm codegen (in your DS package)",
357
+ "// Requires Node 18+ (fetch) and Node 22+ (WebSocket)",
358
+ "",
359
+ 'import { parseArgs } from "node:util";',
360
+ 'import { readFileSync } from "node:fs";',
361
+ 'import { basename } from "node:path";',
362
+ "",
363
+ `const DS_HTTP_URL = process.env.${httpEnvVar} ?? "http://localhost:4000/graphql";`,
364
+ `const DS_WS_URL = process.env.${wsEnvVar} ?? "ws://localhost:4000/graphql";`,
365
+ ""
366
+ ].join("\n");
367
+ const footer = [
368
+ "",
369
+ "main().catch((err) => {",
370
+ String.raw` process.stderr.write(err.message + "\n");`,
371
+ " process.exit(1);",
372
+ "});"
373
+ ].join("\n");
374
+ return header + serializeOperations(ops) + "\n\n" + RUNTIME_LINES.join("\n") + footer;
375
+ }
376
+
377
+ // src/gen-man.ts
378
+ function groffEscape(s) {
379
+ return s.replaceAll("\\", String.raw`\\`).replaceAll('"', String.raw`\(dq`).replaceAll("-", String.raw`\-`);
380
+ }
381
+ function fmtSynopsis(ops) {
382
+ return ops.map((op) => {
383
+ const args = op.args.map(
384
+ (a) => a.required ? String.raw`\fB\-\-${a.name}\fP \fI${a.graphqlType}\fP` : String.raw`[\fB\-\-${a.name}\fP \fI${a.graphqlType}\fP]`
385
+ ).join(" ");
386
+ return `.TP
387
+ .B ${groffEscape(op.commandName)}${args ? "\n" + args : ""}`;
388
+ }).join("\n");
389
+ }
390
+ function fmtCommandSection(ops, heading) {
391
+ if (ops.length === 0) return "";
392
+ const items = ops.map((op) => {
393
+ const argLines = op.args.map((a) => {
394
+ const required = a.required ? " (required)" : " (optional)";
395
+ const flag = String.raw`\fB\-\-${a.name}\fP \fI${a.graphqlType}\fP`;
396
+ const desc = groffEscape(a.description || "No description.");
397
+ return `.RS
398
+ ${flag}${required}
399
+ .br
400
+ ${desc}
401
+ .RE`;
402
+ }).join("\n");
403
+ return `.TP
404
+ .B ${groffEscape(op.commandName)}
405
+ ${groffEscape(op.description || "No description.")}
406
+ ` + (argLines ? argLines + "\n" : "");
407
+ }).join("\n");
408
+ return `.SH ${heading}
409
+ ${items}`;
410
+ }
411
+ function generateMan(ops) {
412
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
413
+ const queries = ops.filter((o) => o.operationType === "query");
414
+ const mutations = ops.filter((o) => o.operationType === "mutation");
415
+ const subs = ops.filter((o) => o.operationType === "subscription");
416
+ return [
417
+ String.raw`.TH DS\-CLI 1 "${today}" "ds-cli 0.1.0" "User Commands"`,
418
+ "",
419
+ ".SH NAME",
420
+ String.raw`ds\-cli \- Auto\-generated CLI for the GraphQL data service`,
421
+ "",
422
+ ".SH SYNOPSIS",
423
+ String.raw`.B ds\-cli`,
424
+ ".I command",
425
+ "[options]",
426
+ "",
427
+ ".SH DESCRIPTION",
428
+ "Interact with the GraphQL data service from the command line.",
429
+ String.raw`All commands output newline\-delimited JSON on stdout.`,
430
+ "Errors are written to stderr and the process exits with code 1.",
431
+ ".PP",
432
+ String.raw`Variables can be supplied as command\-line flags, via`,
433
+ String.raw`.B \-\-input`,
434
+ "file, or piped as JSON on stdin.",
435
+ "Explicit flags override file and stdin values.",
436
+ "",
437
+ ".SH SYNOPSIS (commands)",
438
+ fmtSynopsis(ops),
439
+ "",
440
+ fmtCommandSection(queries, "QUERIES"),
441
+ "",
442
+ fmtCommandSection(mutations, "MUTATIONS"),
443
+ "",
444
+ fmtCommandSection(subs, "SUBSCRIPTIONS"),
445
+ "",
446
+ ".SH INPUT",
447
+ ".TP",
448
+ String.raw`.B \-\-input <file.json>`,
449
+ "Read variables from a JSON file.",
450
+ ".TP",
451
+ ".B (stdin)",
452
+ "When stdin is not a TTY, read variables JSON from the pipe.",
453
+ ".PP",
454
+ String.raw`Merge order: \-\-input file < piped stdin < explicit flags.`,
455
+ "",
456
+ ".SH SUBSCRIPTION OPTIONS",
457
+ ".TP",
458
+ String.raw`.B \-\-count N`,
459
+ "Exit after receiving N events.",
460
+ ".TP",
461
+ String.raw`.B \-\-timeout Ms`,
462
+ "Exit after Ms milliseconds regardless of received events.",
463
+ "",
464
+ ".SH ENVIRONMENT",
465
+ ".TP",
466
+ ".B DS_HTTP_URL",
467
+ "GraphQL HTTP endpoint. Default: http://localhost:4000/graphql",
468
+ ".TP",
469
+ ".B DS_WS_URL",
470
+ "GraphQL WebSocket endpoint. Default: ws://localhost:4000/graphql",
471
+ "",
472
+ ".SH EXIT STATUS",
473
+ ".TP",
474
+ ".B 0",
475
+ "Success.",
476
+ ".TP",
477
+ ".B 1",
478
+ "GraphQL error, connection failure, or invalid arguments.",
479
+ "",
480
+ ".SH NOTES",
481
+ "Requires Node.js 18+ (fetch) and Node.js 22+ (WebSocket).",
482
+ String.raw`This file is auto\-generated. Run`,
483
+ ".B pnpm codegen",
484
+ "in your DS package to regenerate."
485
+ ].filter((line) => line !== void 0).join("\n");
486
+ }
487
+
488
+ // src/gen-info.ts
489
+ function texEscape(s) {
490
+ return s.replaceAll("@", "@@").replaceAll("{", "@{").replaceAll("}", "@}");
491
+ }
492
+ function fmtArgsTable(args) {
493
+ if (args.length === 0) return "No arguments.\n";
494
+ const rows = args.map((a) => {
495
+ const req = a.required ? "(required)" : "(optional)";
496
+ return `@item @code{--${texEscape(a.name)}} @var{${texEscape(a.graphqlType)}} ${req}
497
+ ${texEscape(a.description || "No description.")}`;
498
+ });
499
+ return `@table @asis
500
+ ${rows.join("\n")}
501
+ @end table
502
+ `;
503
+ }
504
+ function fmtCommandsSection(ops, title, extraNote) {
505
+ if (ops.length === 0) return "";
506
+ const items = ops.map((op) => {
507
+ const usage = [
508
+ op.commandName,
509
+ ...op.args.map(
510
+ (a) => a.required ? `--${a.name} <${a.graphqlType}>` : `[--${a.name} <${a.graphqlType}>]`
511
+ )
512
+ ].join(" ");
513
+ return `@subsection ${texEscape(op.commandName)}
514
+ @example
515
+ ${texEscape(usage)}
516
+ @end example
517
+
518
+ ${texEscape(op.description || "No description.")}
519
+
520
+ ` + fmtArgsTable(op.args);
521
+ }).join("\n");
522
+ return `@section ${texEscape(title)}
523
+ ` + (extraNote ? `${texEscape(extraNote)}
524
+
525
+ ` : "") + items;
526
+ }
527
+ function generateInfo(ops) {
528
+ const queries = ops.filter((o) => o.operationType === "query");
529
+ const mutations = ops.filter((o) => o.operationType === "mutation");
530
+ const subs = ops.filter((o) => o.operationType === "subscription");
531
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
532
+ return [
533
+ String.raw`\input texinfo`,
534
+ "@c @generated \u2014 do not edit manually",
535
+ `@c Generated: ${today}`,
536
+ "@c Compile with: makeinfo ds-cli.texi",
537
+ "",
538
+ "@settitle ds-cli",
539
+ "@documentencoding UTF-8",
540
+ "",
541
+ "@copying",
542
+ "This manual documents ds-cli, the auto-generated GraphQL CLI.",
543
+ "",
544
+ "Copyright @copyright{} the project authors.",
545
+ "@end copying",
546
+ "",
547
+ "@titlepage",
548
+ "@title ds-cli",
549
+ "@subtitle Auto-generated CLI for the GraphQL data service",
550
+ "@page",
551
+ "@insertcopying",
552
+ "@end titlepage",
553
+ "",
554
+ "@ifnottex",
555
+ "@node Top",
556
+ "@top ds-cli",
557
+ "@insertcopying",
558
+ "@end ifnottex",
559
+ "",
560
+ "@menu",
561
+ "* Overview:: What ds-cli does",
562
+ "* Commands:: All available commands",
563
+ "* Input:: Supplying variables",
564
+ "* Environment:: Configuration via environment variables",
565
+ "* Requirements:: Node.js version requirements",
566
+ "@end menu",
567
+ "",
568
+ "@node Overview",
569
+ "@chapter Overview",
570
+ "",
571
+ "ds-cli is an auto-generated command-line interface for the GraphQL data service.",
572
+ "It is regenerated from the GraphQL schema whenever you run @code{pnpm codegen}",
573
+ "in your DS package.",
574
+ "",
575
+ "All commands write newline-delimited JSON to stdout.",
576
+ "Errors are written to stderr and the process exits with code 1.",
577
+ "",
578
+ "@node Commands",
579
+ "@chapter Commands",
580
+ "",
581
+ fmtCommandsSection(queries, "Queries"),
582
+ "",
583
+ fmtCommandsSection(mutations, "Mutations"),
584
+ "",
585
+ fmtCommandsSection(
586
+ subs,
587
+ "Subscriptions",
588
+ "Subscriptions stream newline-delimited JSON until Ctrl-C, --count, or --timeout."
589
+ ),
590
+ "",
591
+ "@node Input",
592
+ "@chapter Input",
593
+ "",
594
+ "Variables can be supplied three ways (merged in this order, later overrides earlier):",
595
+ "",
596
+ "@enumerate",
597
+ "@item",
598
+ "@code{--input <file.json>} \u2014 read from a JSON file.",
599
+ "@item",
600
+ "Piped stdin \u2014 when stdin is not a TTY, read JSON from the pipe.",
601
+ "@item",
602
+ "Explicit flags \u2014 @code{--name value} on the command line.",
603
+ "@end enumerate",
604
+ "",
605
+ "For subscriptions, two extra options are available:",
606
+ "@table @code",
607
+ "@item --count N",
608
+ "Exit after receiving N events.",
609
+ "@item --timeout Ms",
610
+ "Exit after Ms milliseconds.",
611
+ "@end table",
612
+ "",
613
+ "@node Environment",
614
+ "@chapter Environment",
615
+ "",
616
+ "@table @env",
617
+ "@item DS_HTTP_URL",
618
+ "GraphQL HTTP endpoint. Default: @code{http://localhost:4000/graphql}",
619
+ "@item DS_WS_URL",
620
+ "GraphQL WebSocket endpoint. Default: @code{ws://localhost:4000/graphql}",
621
+ "@end table",
622
+ "",
623
+ "@node Requirements",
624
+ "@chapter Requirements",
625
+ "",
626
+ "Requires Node.js 18 or later (for @code{fetch}).",
627
+ "WebSocket subscriptions require Node.js 22 or later.",
628
+ "",
629
+ "@bye"
630
+ ].join("\n");
631
+ }
632
+
633
+ // src/index.ts
634
+ var preset = {
635
+ buildGeneratesSection: (options) => {
636
+ const { presetConfig, baseOutputDir, schemaAst, schema } = options;
637
+ const config = presetConfig ?? {};
638
+ const graphqlSchema = schemaAst ?? buildASTSchema(schema);
639
+ const ops = extractOperations(graphqlSchema);
640
+ return [
641
+ {
642
+ filename: `${baseOutputDir}index.js`,
643
+ plugins: [{ cli: {} }],
644
+ config: {},
645
+ pluginMap: { cli: { plugin: () => generateCli(ops, config) } },
646
+ schema,
647
+ documents: []
648
+ },
649
+ {
650
+ filename: `${baseOutputDir}man/ds-cli.1`,
651
+ plugins: [{ man: {} }],
652
+ config: {},
653
+ pluginMap: { man: { plugin: () => generateMan(ops) } },
654
+ schema,
655
+ documents: []
656
+ },
657
+ {
658
+ filename: `${baseOutputDir}info/ds-cli.texi`,
659
+ plugins: [{ info: {} }],
660
+ config: {},
661
+ pluginMap: { info: { plugin: () => generateInfo(ops) } },
662
+ schema,
663
+ documents: []
664
+ }
665
+ ];
666
+ }
667
+ };
668
+ export {
669
+ preset
670
+ };
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@corpdk/codegen-cli",
3
+ "version": "2026.10.0-alpha.1",
4
+ "type": "module",
5
+ "publishConfig": {
6
+ "registry": "https://registry.npmjs.org/",
7
+ "access": "public"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "main": "./dist/index.js",
13
+ "exports": {
14
+ ".": "./dist/index.js"
15
+ },
16
+ "devDependencies": {
17
+ "@graphql-codegen/plugin-helpers": "^6.2.0",
18
+ "graphql": "^16.13.2",
19
+ "tsup": "^8.5.1",
20
+ "typescript": "^6.0.2"
21
+ },
22
+ "peerDependencies": {
23
+ "graphql": "^16.0.0"
24
+ },
25
+ "license": "MIT",
26
+ "scripts": {
27
+ "build": "tsup src/index.ts --format esm --dts",
28
+ "clean": "rm -rf dist node_modules .turbo *.tsbuildinfo"
29
+ }
30
+ }