@contractkit/plugin-typescript 0.16.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.
Files changed (60) hide show
  1. package/.turbo/turbo-build$colon$ci.log +35 -0
  2. package/.turbo/turbo-build.log +15 -0
  3. package/.turbo/turbo-test$colon$ci.log +81 -0
  4. package/.turbo/turbo-test.log +19 -0
  5. package/CHANGELOG.md +151 -0
  6. package/README.md +153 -0
  7. package/coverage/base.css +224 -0
  8. package/coverage/block-navigation.js +87 -0
  9. package/coverage/clover.xml +1882 -0
  10. package/coverage/coverage-final.json +9 -0
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +131 -0
  13. package/coverage/prettify.css +1 -0
  14. package/coverage/prettify.js +2 -0
  15. package/coverage/sort-arrow-sprite.png +0 -0
  16. package/coverage/sorter.js +210 -0
  17. package/coverage/src/codegen-contract.ts.html +3331 -0
  18. package/coverage/src/codegen-operation.ts.html +2530 -0
  19. package/coverage/src/codegen-plain-types.ts.html +901 -0
  20. package/coverage/src/codegen-sdk.ts.html +2797 -0
  21. package/coverage/src/index.html +206 -0
  22. package/coverage/src/index.ts.html +1360 -0
  23. package/coverage/src/path-utils.ts.html +649 -0
  24. package/coverage/src/ts-render.ts.html +592 -0
  25. package/coverage/tests/helpers.ts.html +826 -0
  26. package/coverage/tests/index.html +116 -0
  27. package/dist/codegen-contract.d.ts +56 -0
  28. package/dist/codegen-contract.d.ts.map +1 -0
  29. package/dist/codegen-operation.d.ts +25 -0
  30. package/dist/codegen-operation.d.ts.map +1 -0
  31. package/dist/codegen-plain-types.d.ts +10 -0
  32. package/dist/codegen-plain-types.d.ts.map +1 -0
  33. package/dist/codegen-sdk.d.ts +38 -0
  34. package/dist/codegen-sdk.d.ts.map +1 -0
  35. package/dist/index.d.ts +77 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +3162 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/path-utils.d.ts +15 -0
  40. package/dist/path-utils.d.ts.map +1 -0
  41. package/dist/ts-render.d.ts +20 -0
  42. package/dist/ts-render.d.ts.map +1 -0
  43. package/eslint.config.js +6 -0
  44. package/package.json +43 -0
  45. package/src/codegen-contract.ts +1082 -0
  46. package/src/codegen-operation.ts +815 -0
  47. package/src/codegen-plain-types.ts +272 -0
  48. package/src/codegen-sdk.ts +904 -0
  49. package/src/index.ts +425 -0
  50. package/src/path-utils.ts +188 -0
  51. package/src/ts-render.ts +169 -0
  52. package/tests/codegen-contract.test.ts +1004 -0
  53. package/tests/codegen-operation.test.ts +939 -0
  54. package/tests/codegen-plain-types.test.ts +636 -0
  55. package/tests/codegen-sdk.test.ts +1500 -0
  56. package/tests/codegen-server.test.ts +192 -0
  57. package/tests/helpers.ts +247 -0
  58. package/tests/pipeline.test.ts +372 -0
  59. package/tsconfig.json +9 -0
  60. package/vitest.config.ts +14 -0
@@ -0,0 +1,904 @@
1
+ import type { OpRootNode, OpRouteNode, OpOperationNode, OpRequestBodyNode, ContractTypeNode, ParamSource } from '@contractkit/core';
2
+ import { resolveModifiers, isJsonMime, classifyContentType } from '@contractkit/core';
3
+ import { renderInputTsType, renderOutputTsType, quoteKey, headerNameToProperty, JSON_VALUE_TYPE_DECL } from './ts-render.js';
4
+ import { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';
5
+ import { bodyTypesStructurallyEqual } from './codegen-operation.js';
6
+ import { basename, dirname, relative } from 'path';
7
+
8
+ // ─── Body strategy ────────────────────────────────────────────────────────
9
+
10
+ type BodyStrategy =
11
+ | { kind: 'none' }
12
+ | { kind: 'single'; body: OpRequestBodyNode }
13
+ | { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }
14
+ | { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }
15
+ | { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };
16
+
17
+ /** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */
18
+ function jsonOrFormSerialize(varName: string, contentType: string): string {
19
+ if (contentType === 'application/x-www-form-urlencoded') {
20
+ return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;
21
+ }
22
+ if (contentType === 'multipart/form-data') {
23
+ return `(${varName} as FormData)`;
24
+ }
25
+ // application/json + any `+json` structured suffix — JSON.stringify with bigint support.
26
+ return `JSON.stringify(${varName}, bigIntReplacer)`;
27
+ }
28
+
29
+ /**
30
+ * Build a runtime expression that picks the right serialization based on a contentType variable.
31
+ * Used by the SDK when the caller passes (or defaults to) a content-type at call time.
32
+ */
33
+ function renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {
34
+ // Build a chained ternary, last MIME is the fallback
35
+ const arms = bodies.slice(0, -1);
36
+ const last = bodies[bodies.length - 1]!;
37
+ let expr = jsonOrFormSerialize(varName, last.contentType);
38
+ for (let i = arms.length - 1; i >= 0; i--) {
39
+ const arm = arms[i]!;
40
+ expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;
41
+ }
42
+ return expr;
43
+ }
44
+
45
+ function classifyBodyStrategy(op: OpOperationNode): BodyStrategy {
46
+ const bodies = op.request?.bodies ?? [];
47
+ if (bodies.length === 0) return { kind: 'none' };
48
+ if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };
49
+ if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {
50
+ return { kind: 'multi-equal', bodies };
51
+ }
52
+ if (bodies.some(b => b.contentType === 'multipart/form-data')) {
53
+ return { kind: 'multi-formdata-detect', bodies };
54
+ }
55
+ return { kind: 'multi-required-arg', bodies };
56
+ }
57
+
58
+ // ─── Public entry point ────────────────────────────────────────────────────
59
+
60
+ export interface SdkCodegenOptions {
61
+ typeImportPathTemplate?: string;
62
+ outPath?: string;
63
+ /** Map from model name → absolute output file path (for cross-module type imports) */
64
+ modelOutPaths?: Map<string, string>;
65
+ /** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */
66
+ sdkOptionsPath?: string;
67
+ /** Set of model names that have Input variants (models with visibility modifiers) */
68
+ modelsWithInput?: Set<string>;
69
+ /** Set of model names that have Output variants (models with format(output=...)) */
70
+ modelsWithOutput?: Set<string>;
71
+ /**
72
+ * Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —
73
+ * internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`
74
+ * to include them (e.g. for an internal-use SDK).
75
+ */
76
+ includeInternal?: boolean;
77
+ }
78
+
79
+ /**
80
+ * Returns true if the root contains at least one operation eligible for SDK emission.
81
+ * With `includeInternal: false` (default) that means at least one non-internal op; with
82
+ * `includeInternal: true` any op qualifies.
83
+ */
84
+ export function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {
85
+ for (const route of root.routes) {
86
+ for (const op of route.operations) {
87
+ if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;
88
+ }
89
+ }
90
+ return false;
91
+ }
92
+
93
+ export function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {
94
+ const lines: string[] = [];
95
+ const includeInternal = options.includeInternal ?? false;
96
+
97
+ const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);
98
+ const clientClassName = deriveClientClassName(root.file);
99
+
100
+ // Type-only imports
101
+ if (types.length > 0) {
102
+ lines.push(...generateTypeImports(types, root.file, options));
103
+ }
104
+
105
+ // SdkOptions import (from shared file) or inline fallback
106
+ if (options.sdkOptionsPath && options.outPath) {
107
+ let rel = relative(dirname(options.outPath), options.sdkOptionsPath);
108
+ rel = rel.replace(/\.ts$/, '.js');
109
+ if (!rel.startsWith('.')) rel = './' + rel;
110
+ const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';
111
+ lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);
112
+ const valueImports: string[] = [];
113
+ if (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');
114
+ if (sdkNeedsBigIntReviver(root, includeInternal)) valueImports.push('parseJson');
115
+ if (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');
116
+ if (valueImports.length > 0) {
117
+ lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);
118
+ }
119
+ } else {
120
+ lines.push('');
121
+ lines.push('export class SdkError extends Error {');
122
+ lines.push(' constructor(');
123
+ lines.push(' public readonly status: number,');
124
+ lines.push(' public readonly statusText: string,');
125
+ lines.push(' public readonly body: unknown,');
126
+ lines.push(' ) {');
127
+ lines.push(' super(`${status} ${statusText}`);');
128
+ lines.push(" this.name = 'SdkError';");
129
+ lines.push(' }');
130
+ lines.push('}');
131
+ lines.push('');
132
+ lines.push('export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;');
133
+ lines.push('');
134
+ lines.push('export interface SdkOptions {');
135
+ lines.push(' baseUrl: string;');
136
+ lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');
137
+ lines.push(' fetch?: SdkFetch;');
138
+ lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');
139
+ lines.push(' requestIdFactory?: () => string;');
140
+ lines.push('}');
141
+ lines.push('');
142
+ lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');
143
+ lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');
144
+ lines.push(' return async (url: string, init: RequestInit): Promise<Response> => {');
145
+ lines.push(" const baseHeaders = typeof options.headers === 'function'");
146
+ lines.push(' ? await options.headers()');
147
+ lines.push(' : options.headers ?? {};');
148
+ lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');
149
+ lines.push(' ...init,');
150
+ lines.push(" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },");
151
+ lines.push(' });');
152
+ lines.push(' if (!res.ok) {');
153
+ lines.push(' const text = await res.text();');
154
+ lines.push(' let body: unknown;');
155
+ lines.push(' try { body = JSON.parse(text); } catch { body = text; }');
156
+ lines.push(' throw new SdkError(res.status, res.statusText, body);');
157
+ lines.push(' }');
158
+ lines.push(' return res;');
159
+ lines.push(' };');
160
+ lines.push('}');
161
+ lines.push('');
162
+ lines.push('export function buildQueryString(query: object | undefined): string {');
163
+ lines.push(' const searchParams = new URLSearchParams();');
164
+ lines.push(' if (query) {');
165
+ lines.push(' for (const [k, v] of Object.entries(query)) {');
166
+ lines.push(' if (v === undefined || v === null) continue;');
167
+ lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');
168
+ lines.push(' else searchParams.set(k, String(v));');
169
+ lines.push(' }');
170
+ lines.push(' }');
171
+ lines.push(' const qs = searchParams.toString();');
172
+ lines.push(" return qs ? `?${qs}` : '';");
173
+ lines.push('}');
174
+ lines.push('');
175
+ lines.push('export async function parseJson<T>(res: Response): Promise<T> {');
176
+ lines.push(' return JSON.parse(await res.text(), bigIntReviver) as T;');
177
+ lines.push('}');
178
+ }
179
+
180
+ if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {
181
+ lines.push(JSON_VALUE_TYPE_DECL);
182
+ }
183
+
184
+ lines.push('');
185
+
186
+ // Client class
187
+ lines.push('/**');
188
+ const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;
189
+ lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);
190
+ lines.push(' */');
191
+ lines.push(`export class ${clientClassName} {`);
192
+ lines.push(' constructor(private fetch: SdkFetch) {}');
193
+
194
+ for (const route of root.routes) {
195
+ for (const op of route.operations) {
196
+ const mods = resolveModifiers(route, op);
197
+ if (!includeInternal && mods.includes('internal')) continue;
198
+ lines.push('');
199
+ if (mods.includes('deprecated')) lines.push(' /** @deprecated */');
200
+ lines.push(...generateMethod(route, op, root.file, options));
201
+ }
202
+ }
203
+
204
+ lines.push('}');
205
+ lines.push('');
206
+
207
+ return lines.join('\n');
208
+ }
209
+
210
+ // ─── Method generation ────────────────────────────────────────────────────
211
+
212
+ function generateMethod(route: OpRouteNode, op: OpOperationNode, file: string, options: SdkCodegenOptions): string[] {
213
+ const lines: string[] = [];
214
+ const methodName = deriveMethodName(op, route);
215
+ const httpMethod = op.method.toUpperCase();
216
+ const { modelsWithInput, modelsWithOutput } = options;
217
+
218
+ // Build method parameters (request-side — use Input variants)
219
+ const params = buildMethodParams(route, op, modelsWithInput);
220
+ const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');
221
+
222
+ // Determine return type — response side uses Output variants (post-transform wire shape).
223
+ // For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.
224
+ const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];
225
+ const isVoid = !primaryResponse?.bodyType;
226
+ const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';
227
+ const dataType = isVoid
228
+ ? 'void'
229
+ : respCategory === 'text'
230
+ ? 'string'
231
+ : respCategory === 'binary'
232
+ ? 'Blob'
233
+ : renderOutputTsType(primaryResponse!.bodyType!, modelsWithOutput);
234
+ const respHeaders = primaryResponse?.headers ?? [];
235
+ const hasRespHeaders = respHeaders.length > 0;
236
+ const headersShape = hasRespHeaders
237
+ ? `{ ${respHeaders.map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`).join('; ')} }`
238
+ : '';
239
+ const returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;
240
+
241
+ // JSDoc
242
+ const desc = op.description ?? route.description;
243
+ if (op.name || desc) {
244
+ const tags: string[] = [];
245
+ if (op.name) tags.push(`@name ${op.name}`);
246
+ if (desc) tags.push(`@description ${desc}`);
247
+ if (tags.length === 1) {
248
+ lines.push(` /** ${tags[0]} */`);
249
+ } else {
250
+ lines.push(` /**`);
251
+ for (const tag of tags) lines.push(` * ${tag}`);
252
+ lines.push(` */`);
253
+ }
254
+ }
255
+
256
+ lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);
257
+
258
+ // Build URL with path params
259
+ const urlExpr = buildUrlExpression(route.path, route.params);
260
+
261
+ // Query string
262
+ const hasQuery = !!op.query;
263
+ let fetchUrl = urlExpr;
264
+ if (hasQuery) {
265
+ lines.push(` const qs = buildQueryString(query);`);
266
+ fetchUrl = urlExpr;
267
+ }
268
+
269
+ // Build fetch options
270
+ const strategy = classifyBodyStrategy(op);
271
+ const hasBody = strategy.kind !== 'none';
272
+ const hasOpHeaders = !!op.headers;
273
+
274
+ // Pre-emit serialization preludes for multi-MIME strategies
275
+ if (strategy.kind === 'multi-equal') {
276
+ const defaultCt = strategy.bodies[0]!.contentType;
277
+ lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);
278
+ lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);
279
+ } else if (strategy.kind === 'multi-formdata-detect') {
280
+ lines.push(` const __isFormData = body instanceof FormData;`);
281
+ const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;
282
+ lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);
283
+ lines.push(
284
+ ` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,
285
+ );
286
+ } else if (strategy.kind === 'multi-required-arg') {
287
+ lines.push(` const __contentType = options.contentType;`);
288
+ lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);
289
+ }
290
+
291
+ const fetchArgs: string[] = [];
292
+
293
+ if (hasQuery) {
294
+ fetchArgs.push(`url: \`${fetchUrl}\${qs}\``);
295
+ } else {
296
+ fetchArgs.push(`url: \`${fetchUrl}\``);
297
+ }
298
+
299
+ fetchArgs.push(`method: '${httpMethod}'`);
300
+
301
+ if (strategy.kind === 'single') {
302
+ const body = strategy.body;
303
+ const cat = classifyContentType(body.contentType);
304
+ if (cat === 'multipart') {
305
+ // FormData supplies its own Content-Type with boundary; don't override it.
306
+ fetchArgs.push('body: body');
307
+ } else if (cat === 'urlencoded') {
308
+ fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
309
+ fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');
310
+ } else if (cat === 'text' || cat === 'binary') {
311
+ // text/* and binary mimes pass the body through to fetch as-is — no schema serialization.
312
+ fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
313
+ fetchArgs.push('body: body');
314
+ } else {
315
+ fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
316
+ fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');
317
+ }
318
+ } else if (hasBody) {
319
+ // multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude
320
+ fetchArgs.push(`headers: { 'Content-Type': __contentType }`);
321
+ fetchArgs.push('body: __serialized');
322
+ }
323
+
324
+ if (hasOpHeaders) {
325
+ const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));
326
+ if (lastHeaderIdx !== -1) {
327
+ const existing = fetchArgs[lastHeaderIdx]!;
328
+ const inner = existing.slice('headers: '.length).replace(/^\{\s*|\s*\}$/g, '');
329
+ fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;
330
+ } else {
331
+ fetchArgs.push('headers: customHeaders');
332
+ }
333
+ }
334
+
335
+ const resultPrefix = isVoid && !hasRespHeaders ? '' : 'const result = ';
336
+ if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {
337
+ // Simple case — inline
338
+ lines.push(` ${resultPrefix}await this.fetch(\`${fetchUrl}\`, { method: '${httpMethod}' });`);
339
+ } else {
340
+ lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);
341
+ for (let i = 1; i < fetchArgs.length; i++) {
342
+ lines.push(` ${fetchArgs[i]},`);
343
+ }
344
+ lines.push(` });`);
345
+ }
346
+
347
+ const readBodyExpr =
348
+ respCategory === 'text' ? `await result.text()` : respCategory === 'binary' ? `await result.blob()` : `await parseJson<${dataType}>(result)`;
349
+
350
+ if (hasRespHeaders) {
351
+ const headerEntries = respHeaders
352
+ .map(h => `${quoteKey(headerNameToProperty(h.name))}: result.headers.get('${h.name}') ?? undefined`)
353
+ .join(', ');
354
+ if (isVoid) {
355
+ lines.push(` return { headers: { ${headerEntries} } };`);
356
+ } else {
357
+ lines.push(` const data = ${readBodyExpr};`);
358
+ lines.push(` return { data, headers: { ${headerEntries} } };`);
359
+ }
360
+ } else if (!isVoid) {
361
+ lines.push(` return ${readBodyExpr};`);
362
+ }
363
+
364
+ lines.push(' }');
365
+
366
+ return lines;
367
+ }
368
+
369
+ // ─── URL building ─────────────────────────────────────────────────────────
370
+
371
+ function buildUrlExpression(path: string, _?: ParamSource): string {
372
+ // Replace {paramName} with ${encodeURIComponent(paramName)}
373
+ return path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_match, name) => {
374
+ return `\${encodeURIComponent(${name})}`;
375
+ });
376
+ }
377
+
378
+ // ─── Method parameters ────────────────────────────────────────────────────
379
+
380
+ interface MethodParam {
381
+ name: string;
382
+ type: string;
383
+ optional: boolean;
384
+ }
385
+
386
+ function buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {
387
+ const params: MethodParam[] = [];
388
+
389
+ // Path params — always first, always required (request-side — use Input variants)
390
+ if (route.params) {
391
+ if (route.params.kind === 'params') {
392
+ for (const p of route.params.nodes) {
393
+ params.push({ name: p.name, type: renderInputTsType(p.type, modelsWithInput), optional: false });
394
+ }
395
+ } else if (route.params.kind === 'ref') {
396
+ const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;
397
+ params.push({ name: 'params', type: typeName, optional: false });
398
+ } else {
399
+ params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });
400
+ }
401
+ }
402
+
403
+ // Body (request-side — use Input variants)
404
+ const strategy = classifyBodyStrategy(op);
405
+ if (strategy.kind === 'single') {
406
+ const body = strategy.body;
407
+ const cat = classifyContentType(body.contentType);
408
+ if (cat === 'multipart') {
409
+ params.push({ name: 'body', type: 'FormData', optional: false });
410
+ } else if (cat === 'text') {
411
+ params.push({ name: 'body', type: 'string', optional: false });
412
+ } else if (cat === 'binary') {
413
+ params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });
414
+ } else {
415
+ params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });
416
+ }
417
+ } else if (strategy.kind === 'multi-equal') {
418
+ const bodies = strategy.bodies;
419
+ const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);
420
+ params.push({ name: 'body', type: bodyType, optional: false });
421
+ const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');
422
+ params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });
423
+ } else if (strategy.kind === 'multi-formdata-detect') {
424
+ const types = strategy.bodies
425
+ .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))
426
+ .join(' | ');
427
+ params.push({ name: 'body', type: types, optional: false });
428
+ } else if (strategy.kind === 'multi-required-arg') {
429
+ const types = strategy.bodies
430
+ .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))
431
+ .join(' | ');
432
+ params.push({ name: 'body', type: types, optional: false });
433
+ const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');
434
+ params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });
435
+ }
436
+
437
+ // Query (request-side — use Input variants)
438
+ if (op.query) {
439
+ if (op.query.kind === 'params') {
440
+ const fields = op.query.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');
441
+ params.push({ name: 'query', type: `{ ${fields} }`, optional: true });
442
+ } else if (op.query.kind === 'ref') {
443
+ const typeName = modelsWithInput?.has(op.query.name) ? `${op.query.name}Input` : op.query.name;
444
+ params.push({ name: 'query', type: typeName, optional: true });
445
+ } else {
446
+ params.push({ name: 'query', type: renderInputTsType(op.query.node, modelsWithInput), optional: true });
447
+ }
448
+ }
449
+
450
+ // Headers (request-side — use Input variants)
451
+ if (op.headers) {
452
+ if (op.headers.kind === 'params') {
453
+ const fields = op.headers.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');
454
+ params.push({ name: 'customHeaders', type: `{ ${fields} }`, optional: true });
455
+ } else if (op.headers.kind === 'ref') {
456
+ const typeName = modelsWithInput?.has(op.headers.name) ? `${op.headers.name}Input` : op.headers.name;
457
+ params.push({ name: 'customHeaders', type: typeName, optional: true });
458
+ } else {
459
+ params.push({ name: 'customHeaders', type: renderInputTsType(op.headers.node, modelsWithInput), optional: true });
460
+ }
461
+ }
462
+
463
+ return params;
464
+ }
465
+
466
+ // ─── Method name inference ────────────────────────────────────────────────
467
+
468
+ function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {
469
+ if (op.sdk) return op.sdk;
470
+ if (op.name) return nameToMethodName(op.name);
471
+ return inferMethodName(op.method, route.path);
472
+ }
473
+
474
+ function nameToMethodName(name: string): string {
475
+ const parts = name.split(/[\s\-_]+/).filter(Boolean);
476
+ return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');
477
+ }
478
+
479
+ function inferMethodName(method: string, path: string): string {
480
+ // Build a name from the path segments + method
481
+ // e.g. GET /users/:id → getUsersById
482
+ // e.g. POST /users → postUsers
483
+ // e.g. DELETE /users/:id → deleteUsersById
484
+ const segments = path.split('/').filter(s => s.length > 0);
485
+ const parts: string[] = [method.toLowerCase()];
486
+
487
+ for (const seg of segments) {
488
+ if (seg.startsWith('{')) {
489
+ // {id} → ById, {accountId} → ByAccountId
490
+ const paramName = seg.slice(1, -1);
491
+ parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));
492
+ } else {
493
+ // Regular segment — camelCase it
494
+ const segParts = seg.split(/[.-]/).filter(Boolean);
495
+ for (const sp of segParts) {
496
+ parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));
497
+ }
498
+ }
499
+ }
500
+
501
+ return parts[0]! + parts.slice(1).join('');
502
+ }
503
+
504
+ // ─── Naming conventions ────────────────────────────────────────────────────
505
+
506
+ function deriveBaseName(file: string): string {
507
+ const base =
508
+ file
509
+ .split('/')
510
+ .pop()
511
+ ?.replace(/\.(op|ck)$/, '') ?? 'Resource';
512
+ return base
513
+ .split('.')
514
+ .map(s => s.charAt(0).toUpperCase() + s.slice(1))
515
+ .join('');
516
+ }
517
+
518
+ export function deriveClientClassName(file: string): string {
519
+ return `${deriveBaseName(file)}Client`;
520
+ }
521
+
522
+ export function deriveClientPropertyName(file: string): string {
523
+ const base = deriveBaseName(file);
524
+ return base.charAt(0).toLowerCase() + base.slice(1);
525
+ }
526
+
527
+ // ─── Type collection ──────────────────────────────────────────────────────
528
+
529
+ function collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {
530
+ const types = new Set<string>();
531
+ for (const route of root.routes) {
532
+ const publicOps = route.operations.filter(op => includeInternal || !resolveModifiers(route, op).includes('internal'));
533
+ if (publicOps.length === 0) continue;
534
+ // Only collect path-param types if there are public ops on this route
535
+ collectParamSourceRefs(route.params, types);
536
+ collectParamSourceInputRefs(route.params, types, modelsWithInput);
537
+ for (const op of publicOps) {
538
+ if (op.request) {
539
+ for (const body of op.request.bodies) {
540
+ collectTypeNodeRefs(body.bodyType, types);
541
+ collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);
542
+ }
543
+ }
544
+ for (const resp of op.responses) {
545
+ if (resp.bodyType) {
546
+ collectTypeNodeRefs(resp.bodyType, types);
547
+ collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);
548
+ }
549
+ if (resp.headers) {
550
+ for (const h of resp.headers) {
551
+ collectTypeNodeRefs(h.type, types);
552
+ collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);
553
+ }
554
+ }
555
+ }
556
+ collectParamSourceRefs(op.query, types);
557
+ collectParamSourceInputRefs(op.query, types, modelsWithInput);
558
+ collectParamSourceRefs(op.headers, types);
559
+ collectParamSourceInputRefs(op.headers, types, modelsWithInput);
560
+ }
561
+ }
562
+ return [...types].sort();
563
+ }
564
+
565
+ /** Collect Output variant refs for response-side ContractTypeNode types. */
566
+ function collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {
567
+ if (!modelsWithOutput) return;
568
+ switch (type.kind) {
569
+ case 'ref':
570
+ if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);
571
+ break;
572
+ case 'array':
573
+ collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);
574
+ break;
575
+ case 'intersection':
576
+ case 'union':
577
+ case 'discriminatedUnion':
578
+ type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));
579
+ break;
580
+ case 'inlineObject':
581
+ type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));
582
+ break;
583
+ case 'lazy':
584
+ collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);
585
+ break;
586
+ }
587
+ }
588
+
589
+ /** Collect Input variant refs for request-side ParamSource types. */
590
+ function collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {
591
+ if (!source || !modelsWithInput) return;
592
+ if (source.kind === 'ref') {
593
+ if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);
594
+ } else if (source.kind === 'params') {
595
+ for (const param of source.nodes) {
596
+ collectInputTypeNodeRefs(param.type, out, modelsWithInput);
597
+ }
598
+ } else {
599
+ collectInputTypeNodeRefs(source.node, out, modelsWithInput);
600
+ }
601
+ }
602
+
603
+ /** Collect Input variant refs for request-side ContractTypeNode types. */
604
+ function collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {
605
+ if (!modelsWithInput) return;
606
+ switch (type.kind) {
607
+ case 'ref':
608
+ if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);
609
+ break;
610
+ case 'array':
611
+ collectInputTypeNodeRefs(type.item, out, modelsWithInput);
612
+ break;
613
+ case 'intersection':
614
+ case 'union':
615
+ case 'discriminatedUnion':
616
+ type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));
617
+ break;
618
+ case 'inlineObject':
619
+ type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));
620
+ break;
621
+ case 'lazy':
622
+ collectInputTypeNodeRefs(type.inner, out, modelsWithInput);
623
+ break;
624
+ }
625
+ }
626
+
627
+ function collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {
628
+ if (!source) return;
629
+ if (source.kind === 'ref') {
630
+ if (/^[A-Z]/.test(source.name)) out.add(source.name);
631
+ } else if (source.kind === 'params') {
632
+ for (const param of source.nodes) {
633
+ collectTypeNodeRefs(param.type, out);
634
+ }
635
+ } else {
636
+ collectTypeNodeRefs(source.node, out);
637
+ }
638
+ }
639
+
640
+ /** True if any emitted operation has query params (drives the `buildQueryString` import). */
641
+ function sdkNeedsQueryString(root: OpRootNode, includeInternal = false): boolean {
642
+ for (const route of root.routes) {
643
+ for (const op of route.operations) {
644
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
645
+ if (op.query) return true;
646
+ }
647
+ }
648
+ return false;
649
+ }
650
+
651
+ /** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */
652
+ function sdkNeedsBigIntReplacer(root: OpRootNode, includeInternal = false): boolean {
653
+ for (const route of root.routes) {
654
+ for (const op of route.operations) {
655
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
656
+ if (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;
657
+ }
658
+ }
659
+ return false;
660
+ }
661
+
662
+ /** True if any public operation parses a JSON response body (uses bigIntReviver). */
663
+ function sdkNeedsBigIntReviver(root: OpRootNode, includeInternal = false): boolean {
664
+ for (const route of root.routes) {
665
+ for (const op of route.operations) {
666
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
667
+ if (
668
+ op.responses.some(r => {
669
+ if (!r.bodyType) return false;
670
+ // Only JSON-shaped responses use parseJson — text/binary read raw.
671
+ return !r.contentType || classifyContentType(r.contentType) === 'json';
672
+ })
673
+ ) {
674
+ return true;
675
+ }
676
+ }
677
+ }
678
+ return false;
679
+ }
680
+
681
+ function sdkNeedsJson(root: OpRootNode, includeInternal = false): boolean {
682
+ for (const route of root.routes) {
683
+ for (const op of route.operations) {
684
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
685
+ const check = (src: ParamSource | undefined) => {
686
+ if (!src || src.kind === 'ref') return false;
687
+ if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));
688
+ return typeNeedsScalar(src.node, 'json');
689
+ };
690
+ if (
691
+ !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||
692
+ op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, 'json')) ||
693
+ check(op.query) ||
694
+ check(op.headers) ||
695
+ check(route.params)
696
+ )
697
+ return true;
698
+ }
699
+ }
700
+ return false;
701
+ }
702
+
703
+ function collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {
704
+ switch (type.kind) {
705
+ case 'ref':
706
+ if (/^[A-Z]/.test(type.name)) out.add(type.name);
707
+ break;
708
+ case 'array':
709
+ collectTypeNodeRefs(type.item, out);
710
+ break;
711
+ case 'tuple':
712
+ type.items.forEach(t => collectTypeNodeRefs(t, out));
713
+ break;
714
+ case 'record':
715
+ collectTypeNodeRefs(type.key, out);
716
+ collectTypeNodeRefs(type.value, out);
717
+ break;
718
+ case 'union':
719
+ type.members.forEach(t => collectTypeNodeRefs(t, out));
720
+ break;
721
+ case 'discriminatedUnion':
722
+ type.members.forEach(t => collectTypeNodeRefs(t, out));
723
+ break;
724
+ case 'intersection':
725
+ type.members.forEach(t => collectTypeNodeRefs(t, out));
726
+ break;
727
+ case 'lazy':
728
+ collectTypeNodeRefs(type.inner, out);
729
+ break;
730
+ case 'inlineObject':
731
+ type.fields.forEach(f => collectTypeNodeRefs(f.type, out));
732
+ break;
733
+ }
734
+ }
735
+
736
+ // ─── Type import resolution ───────────────────────────────────────────────
737
+
738
+ function generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions): string[] {
739
+ const lines: string[] = [];
740
+ const { modelOutPaths, outPath } = options;
741
+
742
+ if (modelOutPaths && outPath) {
743
+ const byFile = new Map<string, string[]>();
744
+ const unresolved: string[] = [];
745
+
746
+ for (const type of types) {
747
+ const typeOutPath = modelOutPaths.get(type);
748
+ if (typeOutPath) {
749
+ const group = byFile.get(typeOutPath) ?? [];
750
+ group.push(type);
751
+ byFile.set(typeOutPath, group);
752
+ } else {
753
+ unresolved.push(type);
754
+ }
755
+ }
756
+
757
+ const fromDir = dirname(outPath);
758
+ for (const [typeOutPath, names] of byFile) {
759
+ let rel = relative(fromDir, typeOutPath);
760
+ rel = rel.replace(/\.ts$/, '.js');
761
+ if (!rel.startsWith('.')) rel = './' + rel;
762
+ lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);
763
+ }
764
+
765
+ for (const type of unresolved) {
766
+ const moduleName = pascalToDotCase(type);
767
+ lines.push(`import type { ${type} } from './${moduleName}.js';`);
768
+ }
769
+ } else {
770
+ const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);
771
+ lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);
772
+ }
773
+
774
+ return lines;
775
+ }
776
+
777
+ function deriveTypeImportPath(file: string, template?: string): string {
778
+ const base =
779
+ file
780
+ .split('/')
781
+ .pop()
782
+ ?.replace(/\.(op|ck)$/, '') ?? 'resource';
783
+ const module = base.split('.')[0] ?? base;
784
+ if (template) {
785
+ return template.replace(/\{module\}/g, module).replace(/\{base\}/g, base);
786
+ }
787
+ return `#modules/${module}/types/index.js`;
788
+ }
789
+
790
+ // ─── Shared SDK files ──────────────────────────────────────────────────────
791
+
792
+ /** Generate the shared SdkOptions interface file. */
793
+ export function generateSdkOptions(): string {
794
+ return [
795
+ 'export class SdkError extends Error {',
796
+ ' constructor(',
797
+ ' public readonly status: number,',
798
+ ' public readonly statusText: string,',
799
+ ' public readonly body: unknown,',
800
+ ' ) {',
801
+ ' super(`${status} ${statusText}`);',
802
+ " this.name = 'SdkError';",
803
+ ' }',
804
+ '}',
805
+ '',
806
+ 'export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;',
807
+ '',
808
+ 'export interface SdkOptions {',
809
+ ' baseUrl: string;',
810
+ ' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',
811
+ ' fetch?: SdkFetch;',
812
+ ' /** Called once per request to produce a unique X-Request-ID header value */',
813
+ ' requestIdFactory?: () => string;',
814
+ '}',
815
+ '',
816
+ 'export const bigIntReplacer = (_: string, value: any): any => {',
817
+ " if (typeof value === 'bigint') {",
818
+ " return value.toString() + 'n';",
819
+ ' }',
820
+ ' return value;',
821
+ '};',
822
+ '',
823
+ 'export const bigIntReviver = (_: string, value: any): any => {',
824
+ " if (typeof value === 'string' && /^-?\\d+n$/.test(value)) {",
825
+ ' return BigInt(value.slice(0, -1));',
826
+ ' }',
827
+ ' return value;',
828
+ '};',
829
+ '',
830
+ JSON_VALUE_TYPE_DECL,
831
+ '',
832
+ 'export function createSdkFetch(options: SdkOptions): SdkFetch {',
833
+ ' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',
834
+ ' return async (url: string, init: RequestInit): Promise<Response> => {',
835
+ " const baseHeaders = typeof options.headers === 'function'",
836
+ ' ? await options.headers()',
837
+ ' : options.headers ?? {};',
838
+ ' const res = await fetch(`${options.baseUrl}${url}`, {',
839
+ ' ...init,',
840
+ " headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },",
841
+ ' });',
842
+ ' if (!res.ok) {',
843
+ ' const text = await res.text();',
844
+ ' let body: unknown;',
845
+ ' try { body = JSON.parse(text); } catch { body = text; }',
846
+ ' throw new SdkError(res.status, res.statusText, body);',
847
+ ' }',
848
+ ' return res;',
849
+ ' };',
850
+ '}',
851
+ '',
852
+ 'export function buildQueryString(query: object | undefined): string {',
853
+ ' const searchParams = new URLSearchParams();',
854
+ ' if (query) {',
855
+ ' for (const [k, v] of Object.entries(query)) {',
856
+ ' if (v === undefined || v === null) continue;',
857
+ ' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',
858
+ ' else searchParams.set(k, String(v));',
859
+ ' }',
860
+ ' }',
861
+ ' const qs = searchParams.toString();',
862
+ " return qs ? `?${qs}` : '';",
863
+ '}',
864
+ '',
865
+ 'export async function parseJson<T>(res: Response): Promise<T> {',
866
+ ' return JSON.parse(await res.text(), bigIntReviver) as T;',
867
+ '}',
868
+ '',
869
+ ].join('\n');
870
+ }
871
+
872
+ export interface SdkClientInfo {
873
+ className: string;
874
+ propertyName: string;
875
+ importPath: string;
876
+ }
877
+
878
+ /** Generate the sdk.ts aggregator that wraps all clients into a single Sdk class. */
879
+ export function generateSdkAggregator(clients: SdkClientInfo[], sdkOptionsImportPath = './sdk-options.js', sdkClassName = 'Sdk'): string {
880
+ const lines: string[] = [];
881
+
882
+ lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);
883
+ lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);
884
+ for (const c of clients) {
885
+ lines.push(`import { ${c.className} } from '${c.importPath}';`);
886
+ }
887
+ lines.push('');
888
+
889
+ lines.push(`export class ${sdkClassName} {`);
890
+ for (const c of clients) {
891
+ lines.push(` readonly ${c.propertyName}: ${c.className};`);
892
+ }
893
+ lines.push('');
894
+ lines.push(' constructor(options: SdkOptions) {');
895
+ lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');
896
+ for (const c of clients) {
897
+ lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);
898
+ }
899
+ lines.push(' }');
900
+ lines.push('}');
901
+ lines.push('');
902
+
903
+ return lines.join('\n');
904
+ }