-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgenerate-openapi.ts
More file actions
166 lines (143 loc) · 5.91 KB
/
generate-openapi.ts
File metadata and controls
166 lines (143 loc) · 5.91 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
import 'dotenv/config'
import { writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import swagger from '@fastify/swagger'
import Fastify from 'fastify'
const scriptPath = fileURLToPath(import.meta.url)
const scriptDir = dirname(scriptPath)
/**
* Post-process OpenAPI schema to remove fields with default values from required arrays.
* This fixes the issue where z.toJSONSchema() marks optional-with-default fields as required.
*/
function removeDefaultsFromRequired(schema: unknown): unknown {
if (!schema || typeof schema !== 'object') return schema
const obj = schema as Record<string, unknown>
// If this is a schema object with properties and required
if ('properties' in obj && 'required' in obj && Array.isArray(obj.required)) {
const properties = obj.properties as Record<string, unknown> | undefined
const required = obj.required as string[]
if (properties) {
// Remove any property from required if it has a default value
const newRequired = required.filter(key => {
const prop = properties[key]
if (prop && typeof prop === 'object' && 'default' in prop) return false
return true
})
// Recursively process properties
const newProperties: Record<string, unknown> = {}
for (const [key, value] of Object.entries(properties))
newProperties[key] = removeDefaultsFromRequired(value)
return {
...obj,
properties: newProperties,
required: newRequired.length > 0 ? newRequired : undefined,
}
}
}
const processComponents = (components: Record<string, unknown>): Record<string, unknown> => {
const newComponents: Record<string, unknown> = {}
for (const [compKey, compValue] of Object.entries(components))
if (compKey === 'schemas' && typeof compValue === 'object' && compValue !== null) {
const schemas = compValue as Record<string, unknown>
const newSchemas: Record<string, unknown> = {}
for (const [schemaKey, schemaValue] of Object.entries(schemas))
newSchemas[schemaKey] = removeDefaultsFromRequired(schemaValue)
newComponents[compKey] = newSchemas
} else {
newComponents[compKey] = removeDefaultsFromRequired(compValue)
}
return newComponents
}
// Recursively process nested objects
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(obj))
if (key === 'paths' && typeof value === 'object' && value !== null) {
// Process paths object
const paths = value as Record<string, unknown>
const newPaths: Record<string, unknown> = {}
for (const [pathKey, pathValue] of Object.entries(paths))
newPaths[pathKey] = removeDefaultsFromRequired(pathValue)
result[key] = newPaths
} else if (key === 'components' && typeof value === 'object' && value !== null) {
result[key] = processComponents(value as Record<string, unknown>)
} else if (
(key === 'requestBody' || key === 'responses' || key === 'body' || key === 'schema') &&
typeof value === 'object' &&
value !== null
) {
// Process requestBody, responses, body, schema
result[key] = removeDefaultsFromRequired(value)
} else if (Array.isArray(value)) {
result[key] = value.map(item => removeDefaultsFromRequired(item))
} else if (typeof value === 'object' && value !== null) {
result[key] = removeDefaultsFromRequired(value)
} else {
result[key] = value
}
return result
}
async function generateOpenAPI() {
// Stub env for OpenAPI generation when missing (e.g. Vercel Next build)
const stubs: Record<string, string> = {
ANTHROPIC_API_KEY: 'sk-ant-dummy-for-openapi-generation',
OLLAMA_BASE_URL: 'https://ollama.example.com',
OPEN_ROUTER_API_KEY: 'sk-or-v1-dummy-for-openapi-generation',
PGLITE: 'true',
ENCRYPTION_KEY: 'deadbeef'.repeat(8), // 64-char hex (valid, not weak)
JWT_SECRET: 'openapi-gen-jwt-secret-placeholder-32ch',
}
for (const [k, v] of Object.entries(stubs)) if (!process.env[k]) process.env[k] = v
const { default: app } = await import('../src/app.js')
// Create Fastify instance (same as production)
const fastify = Fastify({
logger: false, // Disable logging for generation
pluginTimeout: 30000, // Increase timeout for plugin loading (30 seconds)
})
try {
// Register @fastify/swagger FIRST (before routes)
// Swagger needs to scan routes as they're registered
await fastify.register(swagger, {
openapi: {
info: {
title: 'Basilic API',
version: '1.0.0',
description: 'Basilic API documentation',
},
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
},
apiKeyAuth: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key',
},
},
},
security: [{ bearerAuth: [] }, { apiKeyAuth: [] }],
},
})
// Register app (which autoloads plugins + routes)
// Swagger will automatically scan route schemas as they're registered
await fastify.register(app, { allowTest: false })
// Wait for Fastify to be ready before generating OpenAPI
await fastify.ready()
// Generate OpenAPI JSON
const openApiDocument = fastify.swagger()
// Post-process to remove default-valued fields from required arrays
const processedDocument = removeDefaultsFromRequired(openApiDocument) as typeof openApiDocument
// Write to openapi.json
const outputPath = join(scriptDir, '../openapi/openapi.json')
await writeFile(outputPath, JSON.stringify(processedDocument, null, 2), 'utf-8')
console.log('OpenAPI spec generated:', outputPath)
} catch (error) {
console.error('Failed to generate OpenAPI spec', error)
process.exit(1)
} finally {
await fastify.close()
}
}
generateOpenAPI()