@pikku/openapi-parser 0.12.3 → 0.12.5

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/CHANGELOG.md CHANGED
@@ -1 +1,13 @@
1
1
  # @pikku/openapi-parser
2
+
3
+ ## 0.12.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 8552e18: Don't generate `output: z.void()` for operations without response schemas — omit the field instead
8
+
9
+ ## 0.12.4
10
+
11
+ ### Patch Changes
12
+
13
+ - e3142ad: Use JSON.stringify for safe interpolation of OpenAPI spec values in generated code to prevent code injection via malicious specs.
package/dist/codegen.js CHANGED
@@ -148,9 +148,6 @@ function generateFunctionFile(named, parsed, vars, ctx, spec, flags) {
148
148
  if (parsed.responseSchema) {
149
149
  funcConfig.push(` output: ${outputName},`);
150
150
  }
151
- else {
152
- funcConfig.push(' output: z.void(),');
153
- }
154
151
  if (errorClasses.length > 0) {
155
152
  funcConfig.push(` errors: [${errorClasses.join(', ')}],`);
156
153
  }
@@ -159,7 +156,7 @@ function generateFunctionFile(named, parsed, vars, ctx, spec, flags) {
159
156
  }
160
157
  const funcParams = hasInput ? `{ ${camelName} }, data` : `{ ${camelName} }`;
161
158
  const returnCast = parsed.responseSchema ? ' as any' : '';
162
- funcConfig.push(` func: async (${funcParams}) => {`, ` return ${camelName}.call('${method}', '${parsed.path}'${hasInput ? ', data' : ''})${returnCast}`, ' },');
159
+ funcConfig.push(` func: async (${funcParams}) => {`, ` return ${camelName}.call(${JSON.stringify(method)}, ${JSON.stringify(parsed.path)}${hasInput ? ', data' : ''})${returnCast}`, ' },');
163
160
  lines.push(`export const ${named.functionName} = pikkuSessionlessFunc({`);
164
161
  lines.push(funcConfig.join('\n'));
165
162
  lines.push('})');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/openapi-parser",
3
- "version": "0.12.3",
3
+ "version": "0.12.5",
4
4
  "description": "OpenAPI spec parser and code generator for Pikku",
5
5
  "author": "yasser.fadl@gmail.com",
6
6
  "license": "MIT",
package/src/codegen.ts ADDED
@@ -0,0 +1,648 @@
1
+ /**
2
+ * Generates addon files from a parsed OpenAPI spec.
3
+ * Returns Record<string, string> compatible with getAddonFiles output.
4
+ */
5
+ import type {
6
+ ParsedSpec,
7
+ ParsedOperation,
8
+ ErrorResponse,
9
+ } from './parse-openapi.js'
10
+ import {
11
+ schemaToZod,
12
+ schemaVarName,
13
+ sanitizeTypeName,
14
+ createContext,
15
+ type ZodCodegenContext,
16
+ } from './zod-codegen.js'
17
+ import {
18
+ generateOperationNames,
19
+ detectCommonPrefix,
20
+ type NamedOperation,
21
+ } from './naming.js'
22
+
23
+ interface AddonVars {
24
+ name: string
25
+ camelName: string
26
+ pascalName: string
27
+ screamingName: string
28
+ displayName: string
29
+ description: string
30
+ }
31
+
32
+ interface CodegenFlags {
33
+ oauth: boolean
34
+ secret: boolean
35
+ mcp?: boolean
36
+ }
37
+
38
+ function safeKey(key: string): string {
39
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key)
40
+ }
41
+
42
+ const GENERIC_SUMMARIES = new Set([
43
+ 'index',
44
+ 'show',
45
+ 'create',
46
+ 'update',
47
+ 'destroy',
48
+ 'delete',
49
+ 'list',
50
+ ])
51
+
52
+ /** Map from HTTP status code to pikku error class name */
53
+ const STATUS_TO_ERROR: Record<number, string> = {
54
+ 400: 'BadRequestError',
55
+ 401: 'UnauthorizedError',
56
+ 403: 'ForbiddenError',
57
+ 404: 'NotFoundError',
58
+ 405: 'MethodNotAllowedError',
59
+ 409: 'ConflictError',
60
+ 422: 'UnprocessableContentError',
61
+ 429: 'TooManyRequestsError',
62
+ 500: 'InternalServerError',
63
+ }
64
+
65
+ function capitalize(str: string): string {
66
+ return str.charAt(0).toUpperCase() + str.slice(1)
67
+ }
68
+
69
+ function humanDescription(parsed: ParsedOperation): string | undefined {
70
+ const description = parsed.description?.trim()
71
+ if (description && !GENERIC_SUMMARIES.has(description.toLowerCase())) {
72
+ return capitalize(description)
73
+ }
74
+ return undefined
75
+ }
76
+
77
+ function getErrorClassesForResponses(
78
+ errorResponses: ErrorResponse[]
79
+ ): string[] {
80
+ const classes: string[] = []
81
+ for (const err of errorResponses) {
82
+ const cls = STATUS_TO_ERROR[err.statusCode]
83
+ if (cls && !classes.includes(cls)) {
84
+ classes.push(cls)
85
+ }
86
+ }
87
+ return classes
88
+ }
89
+
90
+ export function generateAddonFromOpenAPI(
91
+ spec: ParsedSpec,
92
+ vars: AddonVars,
93
+ flags: CodegenFlags
94
+ ): Record<string, string> {
95
+ const files: Record<string, string> = {}
96
+ const { name } = vars
97
+
98
+ // Build context for Zod codegen with component schema refs
99
+ const schemaRefs = new Map<string, string>()
100
+ for (const schemaName of Object.keys(spec.componentSchemas)) {
101
+ schemaRefs.set(schemaName, schemaVarName(schemaName))
102
+ }
103
+ const ctx = createContext(schemaRefs)
104
+
105
+ // Generate operation names
106
+ const paths = spec.operations.map((op) => op.path)
107
+ const commonPrefix = detectCommonPrefix(paths)
108
+ const namedOps = generateOperationNames(
109
+ spec.operations.map((op) => ({
110
+ method: op.method,
111
+ path: op.path,
112
+ operationId: op.operationId,
113
+ })),
114
+ commonPrefix
115
+ )
116
+
117
+ // Pair named operations with their parsed data
118
+ const opPairs: Array<{ named: NamedOperation; parsed: ParsedOperation }> =
119
+ namedOps.map((named, i) => ({ named, parsed: spec.operations[i] }))
120
+
121
+ // Generate types file with shared schemas (only if there are any)
122
+ if (Object.keys(spec.componentSchemas).length > 0) {
123
+ files[`src/${name}.types.ts`] = generateTypesFile(spec, ctx)
124
+ }
125
+
126
+ // Generate function files
127
+ const functionExports: string[] = []
128
+ for (const { named, parsed } of opPairs) {
129
+ const funcCtx = createContext(schemaRefs)
130
+ const funcCode = generateFunctionFile(
131
+ named,
132
+ parsed,
133
+ vars,
134
+ funcCtx,
135
+ spec,
136
+ flags
137
+ )
138
+ files[`src/functions/${named.functionName}.function.ts`] = funcCode
139
+ functionExports.push(named.functionName)
140
+ }
141
+
142
+ // Generate index.ts with all exports
143
+ files['src/index.ts'] = generateIndexFile(functionExports)
144
+
145
+ // Generate typed API service class with route map
146
+ files[`src/${name}-api.service.ts`] = generateServiceFile(
147
+ spec,
148
+ opPairs,
149
+ vars,
150
+ flags
151
+ )
152
+
153
+ // Generate variable file for BASE_URL
154
+ files[`src/${name}.variable.ts`] = generateVariableFile(spec, vars)
155
+
156
+ return files
157
+ }
158
+
159
+ function generateTypesFile(spec: ParsedSpec, ctx: ZodCodegenContext): string {
160
+ const lines: string[] = []
161
+ lines.push("import { z } from 'zod'")
162
+ lines.push('')
163
+ lines.push(`// Shared schemas from ${spec.info.title} v${spec.info.version}`)
164
+ lines.push('')
165
+
166
+ for (const [name, schema] of Object.entries(spec.componentSchemas)) {
167
+ const varName = schemaVarName(name)
168
+ const zodCode = schemaToZod(schema, ctx)
169
+ lines.push(`export const ${varName} = ${zodCode}`)
170
+ lines.push(
171
+ `export type ${sanitizeTypeName(name)} = z.infer<typeof ${varName}>`
172
+ )
173
+ lines.push('')
174
+ }
175
+
176
+ return lines.join('\n')
177
+ }
178
+
179
+ function generateFunctionFile(
180
+ named: NamedOperation,
181
+ parsed: ParsedOperation,
182
+ vars: AddonVars,
183
+ ctx: ZodCodegenContext,
184
+ spec: ParsedSpec,
185
+ flags: CodegenFlags
186
+ ): string {
187
+ const lines: string[] = []
188
+ const { camelName } = vars
189
+
190
+ // Tag description as file header
191
+ if (parsed.tags.length > 0) {
192
+ const tag = parsed.tags[0]
193
+ const tagDesc = spec.tagDescriptions[tag]
194
+ if (tagDesc) {
195
+ lines.push(`// ${tag} — ${tagDesc}`)
196
+ lines.push('')
197
+ }
198
+ }
199
+
200
+ const hasInput =
201
+ parsed.pathParams.length > 0 ||
202
+ parsed.queryParams.length > 0 ||
203
+ parsed.headerParams.length > 0 ||
204
+ parsed.requestBody
205
+
206
+ const pascalName =
207
+ named.functionName.charAt(0).toUpperCase() + named.functionName.slice(1)
208
+ const inputName = `${pascalName}Input`
209
+ const outputName = `${pascalName}Output`
210
+
211
+ // Determine error imports needed
212
+ const errorClasses = getErrorClassesForResponses(parsed.errorResponses)
213
+
214
+ lines.push("import { z } from 'zod'")
215
+ lines.push("import { pikkuSessionlessFunc } from '#pikku'")
216
+
217
+ if (errorClasses.length > 0) {
218
+ lines.push(
219
+ `import { ${errorClasses.join(', ')} } from '@pikku/core/errors'`
220
+ )
221
+ }
222
+
223
+ lines.push('')
224
+
225
+ // Build Input schema (exported for pikku schema discovery)
226
+ if (hasInput) {
227
+ const inputCode = buildInputSchema(parsed, ctx)
228
+ lines.push(`export const ${inputName} = ${inputCode}`)
229
+ lines.push('')
230
+ }
231
+
232
+ // Build Output schema (exported for pikku schema discovery)
233
+ if (parsed.responseSchema) {
234
+ const outputCode = buildOutputSchema(parsed.responseSchema, ctx)
235
+ lines.push(`export const ${outputName} = ${outputCode}`)
236
+ lines.push('')
237
+ }
238
+
239
+ const description = humanDescription(parsed)
240
+ const method = parsed.method.toUpperCase()
241
+
242
+ const funcConfig: string[] = []
243
+ if (description) {
244
+ funcConfig.push(` description: ${JSON.stringify(description)},`)
245
+ }
246
+ if (hasInput) funcConfig.push(` input: ${inputName},`)
247
+ if (parsed.responseSchema) {
248
+ funcConfig.push(` output: ${outputName},`)
249
+ }
250
+
251
+ if (errorClasses.length > 0) {
252
+ funcConfig.push(` errors: [${errorClasses.join(', ')}],`)
253
+ }
254
+
255
+ if (flags.mcp) {
256
+ funcConfig.push(' mcp: true,')
257
+ }
258
+
259
+ const funcParams = hasInput ? `{ ${camelName} }, data` : `{ ${camelName} }`
260
+
261
+ const returnCast = parsed.responseSchema ? ' as any' : ''
262
+ funcConfig.push(
263
+ ` func: async (${funcParams}) => {`,
264
+ ` return ${camelName}.call(${JSON.stringify(method)}, ${JSON.stringify(parsed.path)}${hasInput ? ', data' : ''})${returnCast}`,
265
+ ' },'
266
+ )
267
+
268
+ lines.push(`export const ${named.functionName} = pikkuSessionlessFunc({`)
269
+ lines.push(funcConfig.join('\n'))
270
+ lines.push('})')
271
+ lines.push('')
272
+
273
+ return lines.join('\n')
274
+ }
275
+
276
+ function buildInputSchema(
277
+ parsed: ParsedOperation,
278
+ ctx: ZodCodegenContext
279
+ ): string {
280
+ const props: string[] = []
281
+
282
+ for (const param of parsed.pathParams) {
283
+ props.push(formatParamProp(param, ctx))
284
+ }
285
+
286
+ for (const param of parsed.queryParams) {
287
+ props.push(formatParamProp(param, ctx))
288
+ }
289
+
290
+ for (const param of parsed.headerParams) {
291
+ props.push(formatParamProp(param, ctx))
292
+ }
293
+
294
+ if (parsed.requestBody) {
295
+ if (parsed.requestBody.properties) {
296
+ const requiredSet = new Set(parsed.requestBody.required ?? [])
297
+ for (const [key, propSchema] of Object.entries(
298
+ parsed.requestBody.properties
299
+ )) {
300
+ // Skip readOnly properties from input
301
+ if (propSchema.readOnly) continue
302
+ const isOptional = !requiredSet.has(key)
303
+ const zodCode = schemaToZod(propSchema, ctx, { optional: isOptional })
304
+ const withDesc = propSchema.description
305
+ ? `${zodCode}.describe(${JSON.stringify(propSchema.description)})`
306
+ : zodCode
307
+ props.push(` ${safeKey(key)}: ${withDesc},`)
308
+ }
309
+ } else {
310
+ const bodyZod = schemaToZod(parsed.requestBody, ctx)
311
+ props.push(` body: ${bodyZod},`)
312
+ }
313
+ }
314
+
315
+ return `z.object({\n${props.join('\n')}\n})`
316
+ }
317
+
318
+ function formatParamProp(
319
+ param: {
320
+ name: string
321
+ required: boolean
322
+ schema: any
323
+ description?: string
324
+ example?: unknown
325
+ },
326
+ ctx: ZodCodegenContext
327
+ ): string {
328
+ const zodCode = schemaToZod(param.schema, ctx, { optional: !param.required })
329
+
330
+ let descParts: string[] = []
331
+ if (param.description) descParts.push(param.description)
332
+ if (param.example !== undefined)
333
+ descParts.push(`Example: ${JSON.stringify(param.example)}`)
334
+
335
+ const desc =
336
+ descParts.length > 0
337
+ ? `${zodCode}.describe(${JSON.stringify(descParts.join('. '))})`
338
+ : zodCode
339
+
340
+ return ` ${safeKey(param.name)}: ${desc},`
341
+ }
342
+
343
+ function buildOutputSchema(schema: any, ctx: ZodCodegenContext): string {
344
+ // For output schemas, filter out writeOnly properties
345
+ if (schema.properties) {
346
+ const filteredProps: Record<string, any> = {}
347
+ for (const [key, propSchema] of Object.entries(schema.properties) as [
348
+ string,
349
+ any,
350
+ ][]) {
351
+ if (!propSchema.writeOnly) {
352
+ filteredProps[key] = propSchema
353
+ }
354
+ }
355
+ const filteredSchema = { ...schema, properties: filteredProps }
356
+ return schemaToZod(filteredSchema, ctx)
357
+ }
358
+ return schemaToZod(schema, ctx)
359
+ }
360
+
361
+ function generateIndexFile(functionExports: string[]): string {
362
+ const lines: string[] = []
363
+ for (const name of functionExports) {
364
+ lines.push(`export { ${name} } from './functions/${name}.function.js'`)
365
+ }
366
+ lines.push('')
367
+ return lines.join('\n')
368
+ }
369
+
370
+ interface RouteInfo {
371
+ path: string[]
372
+ query: string[]
373
+ headers: string[]
374
+ errors?: Record<number, string>
375
+ }
376
+
377
+ function generateServiceFile(
378
+ spec: ParsedSpec,
379
+ opPairs: Array<{ named: NamedOperation; parsed: ParsedOperation }>,
380
+ vars: AddonVars,
381
+ flags: CodegenFlags
382
+ ): string {
383
+ const { name, pascalName, screamingName, displayName } = vars
384
+ const lines: string[] = []
385
+
386
+ // Always import all error classes used in the switch statement
387
+ const allErrorClasses = new Set<string>(Object.values(STATUS_TO_ERROR))
388
+
389
+ if (flags.oauth) {
390
+ lines.push("import { OAuth2Client } from '@pikku/core/oauth2'")
391
+ lines.push(
392
+ "import type { TypedSecretService } from '#pikku/secrets/pikku-secrets.gen.js'"
393
+ )
394
+ } else if (flags.secret) {
395
+ lines.push(
396
+ `import type { ${pascalName}Secrets } from './${name}.secret.js'`
397
+ )
398
+ }
399
+
400
+ if (allErrorClasses.size > 0) {
401
+ lines.push(
402
+ `import { ${[...allErrorClasses].sort().join(', ')} } from '@pikku/core/errors'`
403
+ )
404
+ }
405
+
406
+ lines.push(
407
+ `import type { TypedVariablesService } from '#pikku/variables/pikku-variables.gen.js'`
408
+ )
409
+ lines.push('')
410
+
411
+ if (flags.oauth) {
412
+ // Use OAuth2 details from spec if available
413
+ const oauthScheme = Object.values(spec.securitySchemes).find(
414
+ (s) => s.type === 'oauth2'
415
+ )
416
+ const authUrl =
417
+ oauthScheme?.flows?.authorizationUrl ??
418
+ 'https://example.com/oauth2/authorize'
419
+ const tokenUrl =
420
+ oauthScheme?.flows?.tokenUrl ?? 'https://example.com/oauth2/token'
421
+ const scopes = oauthScheme?.flows?.scopes
422
+ ? Object.keys(oauthScheme.flows.scopes)
423
+ : ['read', 'write']
424
+
425
+ lines.push(`export const ${screamingName}_OAUTH2_CONFIG = {`)
426
+ lines.push(` tokenSecretId: '${screamingName}_TOKENS',`)
427
+ lines.push(` authorizationUrl: ${JSON.stringify(authUrl)},`)
428
+ lines.push(` tokenUrl: ${JSON.stringify(tokenUrl)},`)
429
+ lines.push(` scopes: ${JSON.stringify(scopes)},`)
430
+ lines.push('}')
431
+ lines.push('')
432
+ }
433
+
434
+ // Generate route map from parsed operations
435
+ const routes: Record<string, RouteInfo> = {}
436
+ for (const { parsed } of opPairs) {
437
+ const key = `${parsed.method.toUpperCase()} ${parsed.path}`
438
+ const route: RouteInfo = {
439
+ path: parsed.pathParams.map((p) => p.name),
440
+ query: parsed.queryParams.map((p) => p.name),
441
+ headers: parsed.headerParams.map((p) => p.name),
442
+ }
443
+ if (parsed.errorResponses.length > 0) {
444
+ route.errors = {}
445
+ for (const err of parsed.errorResponses) {
446
+ route.errors[err.statusCode] = err.description
447
+ }
448
+ }
449
+ routes[key] = route
450
+ }
451
+
452
+ lines.push(
453
+ `const ROUTES: Record<string, { path: string[], query: string[], headers: string[], errors?: Record<number, string> }> = ${JSON.stringify(routes, null, 2)}`
454
+ )
455
+ lines.push('')
456
+
457
+ // Class declaration
458
+ lines.push(`export class ${pascalName}Service {`)
459
+ lines.push(' private baseUrl: string')
460
+
461
+ if (flags.oauth) {
462
+ lines.push(' private oauth: OAuth2Client')
463
+ lines.push('')
464
+ lines.push(
465
+ ` constructor(secrets: TypedSecretService, variables: TypedVariablesService) {`
466
+ )
467
+ lines.push(
468
+ ` this.baseUrl = variables.get('${screamingName}_BASE_URL') as string`
469
+ )
470
+ lines.push(' this.oauth = new OAuth2Client(')
471
+ lines.push(` ${screamingName}_OAUTH2_CONFIG,`)
472
+ lines.push(` '${screamingName}_APP_CREDENTIALS',`)
473
+ lines.push(' secrets')
474
+ lines.push(' )')
475
+ lines.push(' }')
476
+ } else if (flags.secret) {
477
+ lines.push('')
478
+ lines.push(
479
+ ` constructor(private creds: ${pascalName}Secrets, variables: TypedVariablesService) {`
480
+ )
481
+ lines.push(
482
+ ` this.baseUrl = variables.get('${screamingName}_BASE_URL') as string`
483
+ )
484
+ lines.push(' }')
485
+ } else {
486
+ lines.push('')
487
+ lines.push(` constructor(variables: TypedVariablesService) {`)
488
+ lines.push(
489
+ ` this.baseUrl = variables.get('${screamingName}_BASE_URL') as string`
490
+ )
491
+ lines.push(' }')
492
+ }
493
+
494
+ lines.push('')
495
+
496
+ // call() method — splits data into path/query/headers/body using route map
497
+ lines.push(' async call<T>(')
498
+ lines.push(" method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',")
499
+ lines.push(' path: string,')
500
+ lines.push(' data?: Record<string, unknown>')
501
+ lines.push(' ): Promise<T> {')
502
+ lines.push(' const route = ROUTES[`${method} ${path}`]')
503
+ lines.push(' let endpoint = path')
504
+ lines.push(' let body: Record<string, unknown> | undefined')
505
+ lines.push(' const query: Record<string, string> = {}')
506
+ lines.push(' const headers: Record<string, string> = {')
507
+ lines.push(" 'Content-Type': 'application/json',")
508
+ lines.push(' }')
509
+ lines.push('')
510
+ lines.push(' if (data && route) {')
511
+ lines.push(' // Interpolate path params')
512
+ lines.push(' for (const param of route.path) {')
513
+ lines.push(' if (data[param] !== undefined) {')
514
+ lines.push(
515
+ ' endpoint = endpoint.replace(`{${param}}`, String(data[param]))'
516
+ )
517
+ lines.push(' }')
518
+ lines.push(' }')
519
+ lines.push(' // Extract query params')
520
+ lines.push(' for (const param of route.query) {')
521
+ lines.push(' if (data[param] !== undefined) {')
522
+ lines.push(' query[param] = String(data[param])')
523
+ lines.push(' }')
524
+ lines.push(' }')
525
+ lines.push(' // Extract header params')
526
+ lines.push(' for (const param of route.headers) {')
527
+ lines.push(' if (data[param] !== undefined) {')
528
+ lines.push(' headers[param] = String(data[param])')
529
+ lines.push(' }')
530
+ lines.push(' }')
531
+ lines.push(' // Everything else goes into body')
532
+ lines.push(
533
+ ' const pathQueryHeaders = new Set([...route.path, ...route.query, ...route.headers])'
534
+ )
535
+ lines.push(' const remaining = Object.fromEntries(')
536
+ lines.push(
537
+ ' Object.entries(data).filter(([k]) => !pathQueryHeaders.has(k))'
538
+ )
539
+ lines.push(' )')
540
+ lines.push(' if (Object.keys(remaining).length > 0) {')
541
+ lines.push(' body = remaining')
542
+ lines.push(' }')
543
+ lines.push(' }')
544
+ lines.push('')
545
+ lines.push(' const url = new URL(`${this.baseUrl}${endpoint}`)')
546
+ lines.push(' for (const [key, value] of Object.entries(query)) {')
547
+ lines.push(' url.searchParams.set(key, value)')
548
+ lines.push(' }')
549
+ lines.push('')
550
+
551
+ if (flags.oauth) {
552
+ lines.push(
553
+ ' const response = await this.oauth.request(url.toString(), {'
554
+ )
555
+ lines.push(' method,')
556
+ lines.push(' headers,')
557
+ lines.push(' body: body ? JSON.stringify(body) : undefined,')
558
+ lines.push(' })')
559
+ } else if (flags.secret) {
560
+ // Use apiKey details from spec if available
561
+ const apiKeyScheme = Object.values(spec.securitySchemes).find(
562
+ (s) => s.type === 'apiKey'
563
+ )
564
+ if (apiKeyScheme?.name && apiKeyScheme?.in === 'header') {
565
+ lines.push(
566
+ ` headers[${JSON.stringify(apiKeyScheme.name)}] = this.creds.apiKey`
567
+ )
568
+ } else {
569
+ lines.push(' headers.Authorization = `Bearer ${this.creds.apiKey}`')
570
+ }
571
+ lines.push('')
572
+ lines.push(' const response = await fetch(url.toString(), {')
573
+ lines.push(' method,')
574
+ lines.push(' headers,')
575
+ lines.push(' body: body ? JSON.stringify(body) : undefined,')
576
+ lines.push(' })')
577
+ } else {
578
+ lines.push(' const response = await fetch(url.toString(), {')
579
+ lines.push(' method,')
580
+ lines.push(' headers,')
581
+ lines.push(' body: body ? JSON.stringify(body) : undefined,')
582
+ lines.push(' })')
583
+ }
584
+
585
+ lines.push('')
586
+ lines.push(' if (!response.ok) {')
587
+ lines.push(' const errorText = await response.text()')
588
+ lines.push(
589
+ ' const errorMessage = route?.errors?.[response.status] ?? errorText'
590
+ )
591
+ lines.push(' switch (response.status) {')
592
+ lines.push(' case 400: throw new BadRequestError(errorMessage)')
593
+ lines.push(' case 401: throw new UnauthorizedError(errorMessage)')
594
+ lines.push(' case 403: throw new ForbiddenError(errorMessage)')
595
+ lines.push(' case 404: throw new NotFoundError(errorMessage)')
596
+ lines.push(' case 405: throw new MethodNotAllowedError(errorMessage)')
597
+ lines.push(' case 409: throw new ConflictError(errorMessage)')
598
+ lines.push(
599
+ ' case 422: throw new UnprocessableContentError(errorMessage)'
600
+ )
601
+ lines.push(' case 429: throw new TooManyRequestsError(errorMessage)')
602
+ lines.push(' case 500: throw new InternalServerError(errorMessage)')
603
+ lines.push(
604
+ ` default: throw new Error(\`${displayName} API error (\${response.status}): \${errorText}\`)`
605
+ )
606
+ lines.push(' }')
607
+ lines.push(' }')
608
+ lines.push('')
609
+ lines.push(' const text = await response.text()')
610
+ lines.push(' if (!text) return {} as T')
611
+ lines.push(' return JSON.parse(text) as T')
612
+ lines.push(' }')
613
+
614
+ lines.push('}')
615
+ lines.push('')
616
+
617
+ return lines.join('\n')
618
+ }
619
+
620
+ function generateVariableFile(spec: ParsedSpec, vars: AddonVars): string {
621
+ const { camelName, screamingName, displayName } = vars
622
+ const serverUrls = spec.serverUrls.length > 0 ? spec.serverUrls : []
623
+ const defaultUrl = serverUrls[0]
624
+
625
+ const lines: string[] = []
626
+ lines.push("import { z } from 'zod'")
627
+ lines.push("import { wireVariable } from '@pikku/core/variable'")
628
+ lines.push('')
629
+
630
+ const schemaVarName = `${camelName}BaseUrlSchema`
631
+
632
+ const urlsLiteral = serverUrls.map((u) => JSON.stringify(u)).join(', ')
633
+ lines.push(
634
+ `export const ${schemaVarName} = z.enum([${urlsLiteral}]).default(${JSON.stringify(defaultUrl)})`
635
+ )
636
+
637
+ lines.push('')
638
+ lines.push(`wireVariable({`)
639
+ lines.push(` name: '${screamingName}_BASE_URL',`)
640
+ lines.push(` displayName: '${displayName} Base URL',`)
641
+ lines.push(` description: 'The base URL for the ${displayName} API.',`)
642
+ lines.push(` variableId: '${screamingName}_BASE_URL',`)
643
+ lines.push(` schema: ${schemaVarName},`)
644
+ lines.push(`})`)
645
+ lines.push('')
646
+
647
+ return lines.join('\n')
648
+ }