-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgenerate-sdk.ts
More file actions
717 lines (624 loc) · 21.2 KB
/
generate-sdk.ts
File metadata and controls
717 lines (624 loc) · 21.2 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
#!/usr/bin/env tsx
/**
* Generate typed SDK methods from the Stricli command tree.
*
* Walks the ENTIRE route tree via introspection, extracts flag definitions
* and JSON schemas, and generates src/sdk.generated.ts with typed parameter
* interfaces and method implementations that call invokeCommand() directly.
*
* Zero manual config — all commands are auto-discovered.
*
* Run: tsx script/generate-sdk.ts
*/
import { writeFile } from "node:fs/promises";
import { routes } from "../src/app.js";
import { extractSchemaFields } from "../src/lib/formatters/output.js";
import {
type Command,
type FlagDef,
isCommand,
isRouteMap,
type RouteMap,
} from "../src/lib/introspect.js";
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
/** Flags that are internal to the CLI framework — never exposed as SDK params */
const INTERNAL_FLAGS = new Set([
"json",
"web",
"fresh",
"compact",
"log-level",
"verbose",
"fields",
]);
/** Flags that trigger streaming mode — included in params but change return type */
const STREAMING_FLAGS = new Set(["refresh", "follow"]);
/** Regex for stripping angle-bracket/ellipsis decorators from placeholder names */
const PLACEHOLDER_CLEAN_RE = /[<>.]/g;
/** Regex to check if a name is a valid unquoted TS identifier */
const VALID_IDENT_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** Discovered command with its route path and metadata. */
type DiscoveredCommand = {
/** Route path segments (e.g., ["org", "list"]) */
path: string[];
/** The Stricli command object */
command: Command;
};
/** Extracted SDK flag info. */
type SdkFlagInfo = {
name: string;
kind: "boolean" | "parsed" | "enum";
tsType: string;
optional: boolean;
default?: unknown;
brief?: string;
values?: string[];
};
// ---------------------------------------------------------------------------
// Route Tree Walking
// ---------------------------------------------------------------------------
/**
* Recursively discover all visible commands in the route tree.
* Skips hidden routes (plural aliases, internal commands).
*/
function discoverCommands(
target: RouteMap | Command,
pathPrefix: string[]
): DiscoveredCommand[] {
if (isCommand(target)) {
return [{ path: pathPrefix, command: target }];
}
if (!isRouteMap(target)) {
return [];
}
const results: DiscoveredCommand[] = [];
for (const entry of target.getAllEntries()) {
if (entry.hidden) {
continue;
}
const childPath = [...pathPrefix, entry.name.original];
results.push(...discoverCommands(entry.target, childPath));
}
return results;
}
// ---------------------------------------------------------------------------
// Flag Extraction
// ---------------------------------------------------------------------------
/** Infer the TypeScript type for a single flag definition. */
function inferFlagType(def: FlagDef): {
tsType: string;
kind: SdkFlagInfo["kind"];
values?: string[];
} {
if (def.kind === "boolean") {
return { tsType: "boolean", kind: "boolean" };
}
if (def.kind === "enum") {
const enumDef = def as FlagDef & { values?: readonly string[] };
if (enumDef.values) {
const values = [...enumDef.values];
const tsType = values.map((v: string) => `"${v}"`).join(" | ");
return { tsType, kind: "enum", values };
}
return { tsType: "string", kind: "enum" };
}
// kind === "parsed" — infer from default value
if (def.default !== undefined && typeof def.default === "number") {
return { tsType: "number", kind: "parsed" };
}
if (def.default !== undefined && typeof def.default === "string") {
const numVal = Number(def.default);
if (!Number.isNaN(numVal) && def.default !== "") {
return { tsType: "number", kind: "parsed" };
}
}
return { tsType: "string", kind: "parsed" };
}
/** Extract SDK-relevant flag info from a Stricli Command's parameters. */
function extractSdkFlags(command: Command): SdkFlagInfo[] {
const flagDefs = command.parameters?.flags;
if (!flagDefs) {
return [];
}
const flags: SdkFlagInfo[] = [];
for (const [name, def] of Object.entries(flagDefs) as [string, FlagDef][]) {
if (INTERNAL_FLAGS.has(name)) {
continue;
}
if (def.hidden) {
continue;
}
const { tsType, kind, values } = inferFlagType(def);
const optional = def.optional === true || def.default !== undefined;
flags.push({
name,
kind,
tsType,
optional,
default: def.default,
brief: def.brief,
values,
});
}
return flags;
}
// ---------------------------------------------------------------------------
// Positional Handling
// ---------------------------------------------------------------------------
/**
* Derive positional parameter info from the command's positional placeholder.
*
* - No positional → null
* - Single or compound placeholder → { name, variadic: false }
* - Variadic (e.g., "<args...>") → { name, variadic: true }
*/
type PositionalInfo =
| null
| { name: string; variadic: false }
| { name: string; variadic: true };
function derivePositional(command: Command): PositionalInfo {
const params = command.parameters?.positional;
if (!params) {
return null;
}
if (params.kind === "array") {
const raw = params.parameter.placeholder ?? "args";
const name = raw.replace(PLACEHOLDER_CLEAN_RE, "");
return { name, variadic: true };
}
if (params.kind === "tuple" && params.parameters.length > 0) {
// For tuple positionals, combine all placeholders into a single string param.
// The command's internal parser handles splitting (e.g., "org/project/trace-id").
const placeholders = params.parameters.map(
(p, i) => p.placeholder ?? `arg${i}`
);
const name = placeholders.join("/").replace(PLACEHOLDER_CLEAN_RE, "");
return { name, variadic: false };
}
return null;
}
// ---------------------------------------------------------------------------
// Return Type Generation from __jsonSchema
// ---------------------------------------------------------------------------
/** Map schema field type strings to TypeScript types. */
function mapSchemaType(schemaType: string): string {
// Handle union types like "string | null"
if (schemaType.includes(" | ")) {
return schemaType
.split(" | ")
.map((t) => mapSchemaType(t.trim()))
.join(" | ");
}
switch (schemaType) {
case "string":
return "string";
case "number":
return "number";
case "boolean":
return "boolean";
case "object":
return "Record<string, unknown>";
case "array":
return "unknown[]";
case "null":
return "null";
default:
return "unknown";
}
}
/** Check if a name needs quoting as a TS property (contains dots, dashes, etc.) */
function needsQuoting(name: string): boolean {
return !VALID_IDENT_RE.test(name);
}
/** Format a field name as a valid TS property key. */
function formatPropertyName(name: string, opt: string): string {
if (needsQuoting(name)) {
return `"${name}"${opt}`;
}
return `${name}${opt}`;
}
/**
* Generate a TypeScript type string from a command's __jsonSchema.
* Returns null if no schema is attached.
*/
function generateReturnType(
command: Command,
typeName: string
): { typeDef: string; typeName: string } | null {
// biome-ignore lint/suspicious/noExplicitAny: __jsonSchema is a non-standard property
const schema = (command as any).__jsonSchema;
if (!schema) {
return null;
}
const fields = extractSchemaFields(schema);
if (fields.length === 0) {
return null;
}
const fieldLines = fields.map((f) => {
const opt = f.optional ? "?" : "";
const desc = f.description ? ` /** ${f.description} */\n` : "";
const prop = formatPropertyName(f.name, opt);
return `${desc} ${prop}: ${mapSchemaType(f.type)};`;
});
const typeDef = `export type ${typeName} = {\n${fieldLines.join("\n")}\n};`;
return { typeDef, typeName };
}
// ---------------------------------------------------------------------------
// Code Generation Helpers
// ---------------------------------------------------------------------------
/** Capitalize a string, converting kebab-case to PascalCase ("auth-token" → "AuthToken"). */
function capitalize(s: string): string {
return s.replace(/(^|-)([a-z])/g, (_, _sep, c: string) => c.toUpperCase());
}
/** Regex for converting kebab-case to camelCase */
const KEBAB_TO_CAMEL_RE = /-([a-z])/g;
/** Regex for converting slash-separated to camelCase */
const SLASH_TO_CAMEL_RE = /\/([a-z])/g;
function camelCase(s: string): string {
return s
.replace(SLASH_TO_CAMEL_RE, (_, c) => c.toUpperCase())
.replace(KEBAB_TO_CAMEL_RE, (_, c) => c.toUpperCase());
}
/** Build a PascalCase type name from path segments (e.g., ["org", "list"] → "OrgList") */
function buildTypeName(path: string[]): string {
return path.map(capitalize).join("");
}
/** Generate the params interface for a command. */
function generateParamsInterface(
path: string[],
positional: PositionalInfo,
flags: SdkFlagInfo[]
): { name: string; code: string } | null {
const lines: string[] = [];
if (positional && !positional.variadic) {
lines.push(" /** Positional argument */");
lines.push(` ${camelCase(positional.name)}?: string;`);
}
for (const flag of flags) {
const opt = flag.optional ? "?" : "";
if (flag.brief) {
lines.push(` /** ${flag.brief} */`);
}
lines.push(` ${camelCase(flag.name)}${opt}: ${flag.tsType};`);
}
if (lines.length === 0) {
return null;
}
const interfaceName = `${buildTypeName(path)}Params`;
const code = `export type ${interfaceName} = {\n${lines.join("\n")}\n};`;
return { name: interfaceName, code };
}
/** Build the flag object expression and positional expression for an invoke call. */
function buildInvokeArgs(
path: string[],
positional: PositionalInfo,
flags: SdkFlagInfo[]
): { flagObj: string; positionalExpr: string; pathStr: string } {
const flagEntries = flags.map((f) => {
const camel = camelCase(f.name);
if (f.name !== camel) {
return `"${f.name}": params?.${camel}`;
}
return `${f.name}: params?.${camel}`;
});
let positionalExpr = "[]";
if (positional) {
if (positional.variadic) {
positionalExpr = "positional";
} else {
const camel = camelCase(positional.name);
positionalExpr = `params?.${camel} ? [params.${camel}] : []`;
}
}
const flagObj =
flagEntries.length > 0 ? `{ ${flagEntries.join(", ")} }` : "{}";
const pathStr = JSON.stringify(path);
return { flagObj, positionalExpr, pathStr };
}
/**
* Generate the method body (invoke call) for a non-streaming command.
* Uses `as Promise<T>` to narrow the invoke union return type, since
* non-streaming calls never pass `meta.streaming` and always return a Promise.
*/
function generateMethodBody(
path: string[],
positional: PositionalInfo,
flags: SdkFlagInfo[],
returnType: string
): string {
const { flagObj, positionalExpr, pathStr } = buildInvokeArgs(
path,
positional,
flags
);
return `invoke<${returnType}>(${pathStr}, ${flagObj}, ${positionalExpr}) as Promise<${returnType}>`;
}
/** Options for generating a streaming method body. */
type StreamingMethodOpts = {
path: string[];
positional: PositionalInfo;
flags: SdkFlagInfo[];
returnType: string;
streamingFlagNames: string[];
indent: string;
};
/**
* Generate the method body for a streaming-capable command.
*
* Detects at runtime whether any streaming flag is present and passes
* `{ streaming: true }` to the invoker when it is.
*/
function generateStreamingMethodBody(opts: StreamingMethodOpts): string {
const { flagObj, positionalExpr, pathStr } = buildInvokeArgs(
opts.path,
opts.positional,
opts.flags
);
// Build the streaming condition: params?.follow !== undefined || params?.refresh !== undefined
const conditions = opts.streamingFlagNames
.map((name) => `params?.${camelCase(name)} !== undefined`)
.join(" || ");
const lines = [
"{",
`${opts.indent} const streaming = ${conditions};`,
`${opts.indent} return invoke<${opts.returnType}>(${pathStr}, ${flagObj}, ${positionalExpr}, { streaming });`,
`${opts.indent} }`,
];
return lines.join("\n");
}
// ---------------------------------------------------------------------------
// Namespace Tree Building
// ---------------------------------------------------------------------------
/**
* A node in the namespace tree. Leaf nodes have a method implementation,
* branch nodes contain child namespaces.
*/
type NamespaceNode = {
methods: Map<string, string>; // method name → generated code
typeDecls: Map<string, string>; // method name → type declaration
children: Map<string, NamespaceNode>;
};
function createNamespaceNode(): NamespaceNode {
return { methods: new Map(), typeDecls: new Map(), children: new Map() };
}
/**
* Insert a command's method and type declaration into the namespace tree.
* Path ["org", "list"] → root.children["org"].methods["list"]
* Path ["dashboard", "widget", "add"] → root.children["dashboard"].children["widget"].methods["add"]
*/
function insertMethod(
tree: NamespaceNode,
path: string[],
methodCode: string,
typeDecl: string
): void {
let node = tree;
const namespaceParts = path.slice(0, -1);
const leafName = path.at(-1);
if (!leafName) {
return;
}
for (const part of namespaceParts) {
let child = node.children.get(part);
if (!child) {
child = createNamespaceNode();
node.children.set(part, child);
}
node = child;
}
node.methods.set(leafName, methodCode);
node.typeDecls.set(leafName, typeDecl);
}
/** Render a namespace node as TypeScript code (recursive). */
function renderNamespaceNode(node: NamespaceNode, indent: string): string {
const parts: string[] = [];
// Render methods
for (const [, code] of node.methods) {
parts.push(code);
}
// Render child namespaces
for (const [name, child] of node.children) {
const childBody = renderNamespaceNode(child, `${indent} `);
const key = needsQuoting(name) ? `"${name}"` : name;
parts.push(`${indent}${key}: {\n${childBody}\n${indent}},`);
}
return parts.join("\n");
}
/** Render a namespace node as a TypeScript type declaration (recursive). */
function renderNamespaceTypeNode(node: NamespaceNode, indent: string): string {
const parts: string[] = [];
// Render type declarations for methods
for (const [, decl] of node.typeDecls) {
parts.push(decl);
}
// Render child namespaces as nested object types
for (const [name, child] of node.children) {
const childBody = renderNamespaceTypeNode(child, `${indent} `);
const key = needsQuoting(name) ? `"${name}"` : name;
parts.push(`${indent}${key}: {\n${childBody}\n${indent}};`);
}
return parts.join("\n");
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
const allCommands = discoverCommands(routes as unknown as RouteMap, []);
console.log(`Discovered ${allCommands.length} commands`);
const paramInterfaces: string[] = [];
const returnTypes: string[] = [];
const root = createNamespaceNode();
for (const { path, command } of allCommands) {
const flags = extractSdkFlags(command);
const positional = derivePositional(command);
// Detect streaming-capable commands
const streamingFlagNames = flags
.filter((f) => STREAMING_FLAGS.has(f.name))
.map((f) => f.name);
const isStreaming = streamingFlagNames.length > 0;
// Generate return type from schema
const schemaTypeName = `${buildTypeName(path)}Result`;
const returnTypeInfo = generateReturnType(command, schemaTypeName);
const returnType = returnTypeInfo ? returnTypeInfo.typeName : "unknown";
if (returnTypeInfo) {
returnTypes.push(returnTypeInfo.typeDef);
}
// Generate params interface
const params = generateParamsInterface(path, positional, flags);
if (params) {
paramInterfaces.push(params.code);
}
// Determine method signature
const hasRequiredFlags = flags.some((f) => !f.optional);
const hasVariadicPositional = positional?.variadic === true;
let paramsArg: string;
let body: string;
const brief = command.brief || path.join(" ");
const rawName = path.at(-1) ?? path[0];
const methodName = needsQuoting(rawName) ? `"${rawName}"` : rawName;
const indent = " ".repeat(path.length - 1);
if (hasVariadicPositional) {
// Variadic: (params: XParams, ...positional: string[]) or (params?: XParams, ...positional: string[])
// Required flags make params required even with variadic positionals
const paramsOpt = hasRequiredFlags ? "" : "?";
paramsArg = params
? `params${paramsOpt}: ${params.name}, ...positional: string[]`
: "...positional: string[]";
body = isStreaming
? generateStreamingMethodBody({
path,
positional,
flags,
returnType,
streamingFlagNames,
indent,
})
: generateMethodBody(path, positional, flags, returnType);
} else if (params) {
const paramsRequired = hasRequiredFlags;
paramsArg = paramsRequired
? `params: ${params.name}`
: `params?: ${params.name}`;
body = isStreaming
? generateStreamingMethodBody({
path,
positional,
flags,
returnType,
streamingFlagNames,
indent,
})
: generateMethodBody(path, positional, flags, returnType);
} else {
body = generateMethodBody(path, positional, flags, returnType);
paramsArg = "";
}
const sig = paramsArg ? `(${paramsArg})` : "()";
let methodCode: string;
let typeDecl: string;
if (isStreaming) {
// Streaming commands use a function body (not arrow expression)
// because they need runtime streaming detection
methodCode = [
`${indent} /** ${brief} */`,
`${indent} ${methodName}: ${sig} => ${body},`,
].join("\n");
// Type declaration: callable interface with overloaded signatures
const streamingFlagTypes = streamingFlagNames.map((name) => {
const flag = flags.find((f) => f.name === name);
return `${camelCase(name)}: ${flag?.tsType ?? "string"}`;
});
const streamingConstraint = streamingFlagTypes.join("; ");
typeDecl = [
`${indent} /** ${brief} */`,
`${indent} ${methodName}: {`,
`${indent} (params: ${params?.name ?? "Record<string, never>"} & { ${streamingConstraint} }): AsyncIterable<unknown>;`,
`${indent} ${sig}: Promise<${returnType}>;`,
`${indent} };`,
].join("\n");
} else {
methodCode = [
`${indent} /** ${brief} */`,
`${indent} ${methodName}: ${sig}: Promise<${returnType}> =>`,
`${indent} ${body},`,
].join("\n");
// Type declaration: method signature without implementation
typeDecl = [
`${indent} /** ${brief} */`,
`${indent} ${methodName}${sig}: Promise<${returnType}>;`,
].join("\n");
}
insertMethod(root, path, methodCode, typeDecl);
}
// Build output
const output = [
"// Auto-generated by script/generate-sdk.ts — DO NOT EDIT",
"// Run `pnpm run generate:sdk` to regenerate.",
"",
'import type { buildInvoker } from "./lib/sdk-invoke.js";',
"",
"// --- Return types (derived from __jsonSchema) ---",
"",
returnTypes.length > 0
? returnTypes.join("\n\n")
: "// No commands have registered schemas yet.",
"",
"// --- Parameter types ---",
"",
paramInterfaces.length > 0
? paramInterfaces.join("\n\n")
: "// No commands have parameters.",
"",
"// --- SDK factory ---",
"",
"/** Invoke function type from sdk-invoke.ts */",
"type Invoke = ReturnType<typeof buildInvoker>;",
"",
"/**",
" * Create the typed SDK method tree.",
" * Called by createSentrySDK() with a bound invoker.",
" * @internal",
" */",
"export function createSDKMethods(invoke: Invoke) {",
" return {",
renderNamespaceNode(root, " "),
" };",
"}",
"",
"/** Return type of createSDKMethods — the typed SDK interface. */",
"export type SentrySDK = ReturnType<typeof createSDKMethods>;",
"",
].join("\n");
const outPath = "./src/sdk.generated.ts";
await writeFile(outPath, output);
console.log(`Generated ${outPath}`);
// Build standalone type declarations (.d.cts) for the npm bundle.
// Contains only type exports — no runtime imports or implementations.
const dtsOutput = [
"// Auto-generated by script/generate-sdk.ts — DO NOT EDIT",
"// Run `pnpm run generate:sdk` to regenerate.",
"",
"// --- Return types (derived from __jsonSchema) ---",
"",
returnTypes.length > 0
? returnTypes.join("\n\n")
: "// No commands have registered schemas yet.",
"",
"// --- Parameter types ---",
"",
paramInterfaces.length > 0
? paramInterfaces.join("\n\n")
: "// No commands have parameters.",
"",
"// --- SDK type ---",
"",
`export type SentrySDK = {\n${renderNamespaceTypeNode(root, " ")}\n};`,
"",
].join("\n");
const dtsPath = "./src/sdk.generated.d.cts";
await writeFile(dtsPath, dtsOutput);
console.log(`Generated ${dtsPath}`);