@kawapress/plugin-openapi 0.0.0-stage → 0.0.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README-zh-CN.md +75 -0
  3. package/README.md +74 -2
  4. package/bin/kawapress-openapi.mjs +10 -0
  5. package/package.json +67 -3
  6. package/src/cli.ts +35 -0
  7. package/src/commands.ts +28 -0
  8. package/src/components/KawaOpenApiBody.vue +20 -0
  9. package/src/components/KawaOpenApiBodyView.vue +41 -0
  10. package/src/components/KawaOpenApiCard.vue +33 -0
  11. package/src/components/KawaOpenApiEndpoint.vue +186 -0
  12. package/src/components/KawaOpenApiFieldList.vue +35 -0
  13. package/src/components/KawaOpenApiJourney.vue +100 -0
  14. package/src/components/KawaOpenApiMap.vue +50 -0
  15. package/src/components/KawaOpenApiParameters.vue +24 -0
  16. package/src/components/KawaOpenApiPayload.vue +77 -0
  17. package/src/components/KawaOpenApiRef.vue +21 -0
  18. package/src/components/KawaOpenApiResponses.vue +37 -0
  19. package/src/components/KawaOpenApiSamples.vue +39 -0
  20. package/src/components/KawaOpenApiTabs.vue +68 -0
  21. package/src/components/openapi.css +550 -0
  22. package/src/components/validate.ts +138 -0
  23. package/src/data/body.ts +115 -0
  24. package/src/data/components.ts +687 -0
  25. package/src/data/fields.ts +129 -0
  26. package/src/data/payload.ts +214 -0
  27. package/src/data/rules.ts +67 -0
  28. package/src/data/samples.ts +187 -0
  29. package/src/data/text.ts +85 -0
  30. package/src/data/typescript.ts +105 -0
  31. package/src/env.d.ts +8 -0
  32. package/src/index.ts +123 -0
  33. package/src/options.ts +53 -0
  34. package/src/pages.ts +120 -0
  35. package/src/read/arazzo.ts +168 -0
  36. package/src/read/document.ts +91 -0
  37. package/src/read/example.ts +143 -0
  38. package/src/read/model.ts +341 -0
  39. package/src/read/schema.ts +212 -0
  40. package/src/render/labels.ts +283 -0
  41. package/src/render/pages.ts +237 -0
  42. package/src/render/routes.ts +48 -0
  43. package/src/runtime-plugin.ts +12 -0
  44. package/src/service.ts +128 -0
  45. package/src/snapshot/history.ts +188 -0
  46. package/src/snapshot/snapshot.ts +91 -0
  47. package/src/tag.ts +114 -0
  48. package/src/types.ts +207 -0
  49. package/src/vite.ts +169 -0
@@ -0,0 +1,143 @@
1
+ import type { SchemaNode } from '../types'
2
+
3
+ /** Named schemas by name. */
4
+ export type SchemaTable = ReadonlyMap<string, SchemaNode>
5
+
6
+ /** Which side of the exchange a value is for: requests leave out `readOnly` fields, responses `writeOnly` ones. */
7
+ export type Direction = 'request' | 'response'
8
+
9
+ const MAX_DEPTH = 8
10
+
11
+ /** The schema behind a named reference; the node itself otherwise. */
12
+ export function resolveNode(node: SchemaNode, schemas: SchemaTable): SchemaNode {
13
+ let current = node
14
+ const seen = new Set<string>()
15
+ while (current.kind === 'ref' && current.ref && !seen.has(current.ref)) {
16
+ seen.add(current.ref)
17
+ const target = schemas.get(current.ref)
18
+ if (!target) {
19
+ break
20
+ }
21
+ current = target
22
+ }
23
+ return current
24
+ }
25
+
26
+ /** Whether a property is shown on this side of the exchange. */
27
+ export function visibleOn(schema: SchemaNode, schemas: SchemaTable, direction: Direction): boolean {
28
+ const target = resolveNode(schema, schemas)
29
+ return direction === 'request' ? !(schema.readOnly || target.readOnly) : !(schema.writeOnly || target.writeOnly)
30
+ }
31
+
32
+ /**
33
+ * A plausible example value for a schema: the schema's own example, its
34
+ * default, the first enum value, or a value made up from the type and format.
35
+ * A model that contains itself stops at the second level.
36
+ */
37
+ export function exampleOf(
38
+ node: SchemaNode,
39
+ schemas: SchemaTable,
40
+ direction: Direction,
41
+ name = '',
42
+ trail: readonly string[] = [],
43
+ ): unknown {
44
+ if (node.hasExample) {
45
+ return node.example
46
+ }
47
+ if (node.kind === 'ref' && node.ref) {
48
+ if (trail.includes(node.ref) || trail.length > MAX_DEPTH) {
49
+ return node.ref ? {} : null
50
+ }
51
+ return exampleOf(resolveNode(node, schemas), schemas, direction, name, [...trail, node.ref])
52
+ }
53
+ if (node.default !== undefined) {
54
+ return node.default
55
+ }
56
+ if (node.enum && node.enum.length > 0) {
57
+ return node.enum[0]
58
+ }
59
+ if (node.variants && node.variants.length > 0) {
60
+ return exampleOf(node.variants[0], schemas, direction, name, trail)
61
+ }
62
+ switch (node.kind) {
63
+ case 'object': {
64
+ const value: Record<string, unknown> = {}
65
+ if (trail.length > MAX_DEPTH) {
66
+ return value
67
+ }
68
+ for (const property of node.properties ?? []) {
69
+ if (visibleOn(property.schema, schemas, direction)) {
70
+ value[property.name] = exampleOf(property.schema, schemas, direction, property.name, trail)
71
+ }
72
+ }
73
+ if (!node.properties?.length && node.additionalProperties && node.additionalProperties !== true) {
74
+ value.key = exampleOf(node.additionalProperties, schemas, direction, 'key', trail)
75
+ }
76
+ return value
77
+ }
78
+ case 'array':
79
+ return node.items ? [exampleOf(node.items, schemas, direction, singular(name), trail)] : []
80
+ case 'string':
81
+ return stringExample(node, name)
82
+ case 'integer':
83
+ case 'number':
84
+ return numberExample(node)
85
+ case 'boolean':
86
+ return true
87
+ case 'null':
88
+ return null
89
+ default:
90
+ return node.properties ? exampleOf({ ...node, kind: 'object' }, schemas, direction, name, trail) : null
91
+ }
92
+ }
93
+
94
+ function numberExample(node: SchemaNode): number {
95
+ const { minimum, exclusiveMinimum, maximum, exclusiveMaximum } = node.constraints
96
+ if (minimum !== undefined) {
97
+ return minimum
98
+ }
99
+ if (exclusiveMinimum !== undefined) {
100
+ return node.kind === 'integer' ? exclusiveMinimum + 1 : exclusiveMinimum + 0.5
101
+ }
102
+ const upper = maximum ?? exclusiveMaximum
103
+ if (upper !== undefined && upper < 1) {
104
+ return upper - 1
105
+ }
106
+ return node.kind === 'integer' ? 1 : 1.5
107
+ }
108
+
109
+ const FORMAT_EXAMPLES: Record<string, string> = {
110
+ 'date-time': '2026-01-15T09:30:00Z',
111
+ 'date': '2026-01-15',
112
+ 'time': '09:30:00',
113
+ 'duration': 'PT15M',
114
+ 'email': 'user@example.com',
115
+ 'idn-email': 'user@example.com',
116
+ 'hostname': 'api.example.com',
117
+ 'ipv4': '192.0.2.1',
118
+ 'ipv6': '2001:db8::1',
119
+ 'uri': 'https://example.com/resource',
120
+ 'url': 'https://example.com/resource',
121
+ 'uri-reference': '/resource',
122
+ 'uuid': '3fa85f64-5717-4562-b3fc-2c963f66afa6',
123
+ 'byte': 'U3dhZ2dlciByb2Nrcw==',
124
+ 'binary': '<binary>',
125
+ 'password': '********',
126
+ }
127
+
128
+ function stringExample(node: SchemaNode, name: string): string {
129
+ if (node.format && FORMAT_EXAMPLES[node.format]) {
130
+ return FORMAT_EXAMPLES[node.format]
131
+ }
132
+ const base = name ? name.replace(/[^\w-]+/g, '_') : 'string'
133
+ const { minLength = 0, maxLength } = node.constraints
134
+ let text = base.length >= minLength ? base : base.padEnd(minLength, 'x')
135
+ if (maxLength !== undefined && text.length > maxLength) {
136
+ text = text.slice(0, Math.max(maxLength, 1))
137
+ }
138
+ return text
139
+ }
140
+
141
+ function singular(name: string): string {
142
+ return name.endsWith('ies') ? `${name.slice(0, -3)}y` : name.endsWith('s') ? name.slice(0, -1) : name
143
+ }
@@ -0,0 +1,341 @@
1
+ import type {
2
+ HttpMethod,
3
+ OpenApiAction,
4
+ OpenApiBody,
5
+ OpenApiModel,
6
+ OpenApiOperation,
7
+ OpenApiParameter,
8
+ OpenApiResource,
9
+ OpenApiResponse,
10
+ OpenApiSecurityScheme,
11
+ SchemaNode,
12
+ } from '../types'
13
+ import type { Json } from './document'
14
+ import type { Direction, SchemaTable } from './example'
15
+ import { asString, isObject, RefResolver } from './document'
16
+ import { exampleOf } from './example'
17
+ import { emptyNode, normalizeSchema } from './schema'
18
+
19
+ export const HTTP_METHODS: readonly HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
20
+ /** Slugs the plugin's own pages use under the mount route. */
21
+ export const RESERVED_SLUGS = new Set(['models', 'journeys', 'changes'])
22
+ export const WEBHOOK_RESOURCE = 'webhooks'
23
+ /** Resource name of every webhook. */
24
+ export const WEBHOOK_TITLE = 'Webhooks'
25
+
26
+ /** Reads an OpenAPI 3.0 / 3.1 document into the plugin's model; workflows are added separately. */
27
+ export function readOpenApi(document: Json, file: string): OpenApiModel {
28
+ const version = asString(document.openapi)
29
+ if (!/^3\.[01]\./.test(version)) {
30
+ const found = version || (document.swagger ? `Swagger ${String(document.swagger)}` : 'no "openapi" field')
31
+ throw new Error(`${file}: only OpenAPI 3.0 and 3.1 are supported, found ${found}.`)
32
+ }
33
+ const refs = new RefResolver(document, file)
34
+ const info = isObject(document.info) ? document.info : {}
35
+ const components = isObject(document.components) ? document.components : {}
36
+
37
+ const schemas = Object.entries(isObject(components.schemas) ? components.schemas : {})
38
+ .map(([name, raw]) => ({ name, schema: normalizeSchema(raw, refs, `components.schemas.${name}`) }))
39
+ .sort((a, b) => a.name.localeCompare(b.name))
40
+ const table: SchemaTable = new Map(schemas.map(entry => [entry.name, entry.schema]))
41
+
42
+ const tagOrder = (Array.isArray(document.tags) ? document.tags : []).filter(isObject)
43
+ const resources = new Map<string, OpenApiResource>()
44
+ for (const tag of tagOrder) {
45
+ const name = asString(tag.name)
46
+ if (name) {
47
+ resources.set(name, { name, slug: resourceSlug(tag, name), description: asString(tag.description) })
48
+ }
49
+ }
50
+
51
+ const globalSecurity = securityNames(document.security) ?? []
52
+ const operations: OpenApiOperation[] = []
53
+ const reader = new OperationReader(refs, table, file)
54
+
55
+ for (const [path, rawItem] of Object.entries(isObject(document.paths) ? document.paths : {})) {
56
+ const item = refs.deref<Json>(rawItem, `paths.${path}`)
57
+ for (const method of HTTP_METHODS) {
58
+ if (isObject(item[method])) {
59
+ operations.push(reader.read(item, method, path, false, globalSecurity))
60
+ }
61
+ }
62
+ }
63
+ for (const [event, rawItem] of Object.entries(isObject(document.webhooks) ? document.webhooks : {})) {
64
+ const item = refs.deref<Json>(rawItem, `webhooks.${event}`)
65
+ for (const method of HTTP_METHODS) {
66
+ if (isObject(item[method])) {
67
+ operations.push(reader.read(item, method, event, true, []))
68
+ }
69
+ }
70
+ }
71
+
72
+ for (const operation of operations) {
73
+ if (!resources.has(operation.resource)) {
74
+ resources.set(operation.resource, {
75
+ name: operation.resource,
76
+ slug: operation.webhook ? WEBHOOK_RESOURCE : slugify(operation.resource) || slugify(firstSegment(operation.path)) || 'default',
77
+ description: '',
78
+ })
79
+ }
80
+ }
81
+ const usedResources = [...resources.values()].filter(resource => operations.some(operation => operation.resource === resource.name))
82
+ checkSlugs(usedResources, operations, file)
83
+
84
+ const order = new Map(usedResources.map((resource, index) => [resource.name, index]))
85
+ const sorted = operations
86
+ .map((operation, index) => ({ operation, index }))
87
+ .sort((a, b) => (order.get(a.operation.resource)! - order.get(b.operation.resource)!) || (a.index - b.index))
88
+ .map(({ operation }) => operation)
89
+
90
+ return {
91
+ openapi: version,
92
+ info: {
93
+ title: asString(info.title) || 'API',
94
+ version: info.version === undefined ? '' : String(info.version),
95
+ summary: asString(info.summary),
96
+ description: asString(info.description),
97
+ },
98
+ servers: (Array.isArray(document.servers) ? document.servers : [])
99
+ .filter(isObject)
100
+ .map(server => ({ url: expandServer(server), description: asString(server.description) })),
101
+ securitySchemes: Object.entries(isObject(components.securitySchemes) ? components.securitySchemes : {})
102
+ .map(([name, raw]) => readSecurityScheme(name, refs.deref<Json>(raw, `components.securitySchemes.${name}`))),
103
+ resources: usedResources,
104
+ operations: sorted,
105
+ schemas,
106
+ workflows: [],
107
+ sourceFiles: [file],
108
+ }
109
+ }
110
+
111
+ class OperationReader {
112
+ constructor(private refs: RefResolver, private schemas: SchemaTable, private file: string) {}
113
+
114
+ read(item: Json, method: HttpMethod, path: string, webhook: boolean, globalSecurity: string[]): OpenApiOperation {
115
+ const raw = item[method] as Json
116
+ const where = `${webhook ? 'webhooks' : 'paths'}.${path}.${method}`
117
+ const id = asString(raw.operationId) || derivedId(method, path)
118
+ const tags = Array.isArray(raw.tags) ? raw.tags.map(String) : []
119
+ const resource = webhook ? WEBHOOK_TITLE : (tags[0] ?? (firstSegment(path) || 'default'))
120
+
121
+ const parameters = new Map<string, OpenApiParameter>()
122
+ for (const source of [item.parameters, raw.parameters]) {
123
+ for (const [index, entry] of (Array.isArray(source) ? source : []).entries()) {
124
+ const parameter = this.parameter(entry, `${where}.parameters[${index}]`)
125
+ parameters.set(`${parameter.in}:${parameter.name}`, parameter)
126
+ }
127
+ }
128
+
129
+ const requestBody = raw.requestBody === undefined
130
+ ? undefined
131
+ : this.body(this.refs.deref<Json>(raw.requestBody, `${where}.requestBody`), `${where}.requestBody`, 'request')
132
+
133
+ const responses: OpenApiResponse[] = Object.entries(isObject(raw.responses) ? raw.responses : {})
134
+ .map(([status, value]) => {
135
+ const response = this.refs.deref<Json>(value, `${where}.responses.${status}`)
136
+ const body = this.body(response, `${where}.responses.${status}`, 'response')
137
+ return { status: String(status), description: asString(response.description), ...(body ? { body } : {}) }
138
+ })
139
+ .sort((a, b) => statusRank(a.status) - statusRank(b.status))
140
+
141
+ return {
142
+ id,
143
+ slug: slugify(id) || derivedId(method, path),
144
+ resource,
145
+ method,
146
+ path,
147
+ webhook,
148
+ action: webhook ? 'other' : actionOf(method, path),
149
+ summary: asString(raw.summary),
150
+ description: asString(raw.description),
151
+ deprecated: raw.deprecated === true,
152
+ ...(raw['x-since'] !== undefined ? { since: String(raw['x-since']) } : {}),
153
+ security: securityNames(raw.security) ?? globalSecurity,
154
+ parameters: [...parameters.values()],
155
+ ...(requestBody ? { requestBody } : {}),
156
+ responses,
157
+ }
158
+ }
159
+
160
+ private parameter(entry: unknown, where: string): OpenApiParameter {
161
+ const raw = this.refs.deref<Json>(entry, where)
162
+ const location = asString(raw.in)
163
+ if (!['path', 'query', 'header', 'cookie'].includes(location)) {
164
+ throw new Error(`${this.file}: ${where} has no valid "in" (path, query, header or cookie).`)
165
+ }
166
+ let schema: SchemaNode = emptyNode('string')
167
+ if (raw.schema !== undefined) {
168
+ schema = normalizeSchema(raw.schema, this.refs, `${where}.schema`)
169
+ }
170
+ else if (isObject(raw.content)) {
171
+ const first = Object.values(raw.content)[0]
172
+ schema = isObject(first) ? normalizeSchema(first.schema, this.refs, `${where}.content`) : schema
173
+ }
174
+ const example = raw.example ?? firstExample(raw.examples, this.refs, where) ?? (schema.hasExample ? schema.example : undefined)
175
+ return {
176
+ name: asString(raw.name),
177
+ in: location as OpenApiParameter['in'],
178
+ required: location === 'path' || raw.required === true,
179
+ deprecated: raw.deprecated === true,
180
+ description: asString(raw.description) || schema.description,
181
+ schema,
182
+ ...(example !== undefined ? { example } : {}),
183
+ ...(raw['x-since'] !== undefined ? { since: String(raw['x-since']) } : {}),
184
+ }
185
+ }
186
+
187
+ private body(raw: Json, where: string, direction: Direction): OpenApiBody | undefined {
188
+ const content = isObject(raw.content) ? raw.content : undefined
189
+ if (!content) {
190
+ return undefined
191
+ }
192
+ const entries = Object.entries(content)
193
+ const [contentType, rawMedia] = entries.find(([type]) => /json/i.test(type)) ?? entries[0] ?? []
194
+ if (!contentType || !isObject(rawMedia)) {
195
+ return undefined
196
+ }
197
+ const media = this.refs.deref<Json>(rawMedia, `${where}.content`)
198
+ const schema = media.schema === undefined ? emptyNode('any') : normalizeSchema(media.schema, this.refs, `${where}.schema`)
199
+ const given = 'example' in media ? media.example : firstExample(media.examples, this.refs, where)
200
+ const fromSchema = given === undefined && schema.kind === 'ref' && schema.ref ? this.schemas.get(schema.ref) : undefined
201
+ const example = given !== undefined
202
+ ? given
203
+ : schema.hasExample ? schema.example : fromSchema?.hasExample ? fromSchema.example : exampleOf(schema, this.schemas, direction)
204
+ return {
205
+ contentType,
206
+ required: raw.required === true,
207
+ description: asString(raw.description),
208
+ schema,
209
+ example,
210
+ exampleGenerated: given === undefined && !schema.hasExample && !fromSchema?.hasExample,
211
+ }
212
+ }
213
+ }
214
+
215
+ function firstExample(examples: unknown, refs: RefResolver, where: string): unknown {
216
+ if (!isObject(examples)) {
217
+ return undefined
218
+ }
219
+ const first = Object.values(examples)[0]
220
+ if (first === undefined) {
221
+ return undefined
222
+ }
223
+ const example = refs.deref<Json>(first, `${where}.examples`)
224
+ return isObject(example) && 'value' in example ? example.value : undefined
225
+ }
226
+
227
+ function readSecurityScheme(name: string, raw: Json): OpenApiSecurityScheme {
228
+ const type = asString(raw.type) as OpenApiSecurityScheme['type']
229
+ return {
230
+ name,
231
+ type,
232
+ ...(type === 'http' && raw.scheme ? { scheme: asString(raw.scheme).toLowerCase() } : {}),
233
+ ...(type === 'apiKey' ? { paramName: asString(raw.name), in: asString(raw.in) as OpenApiSecurityScheme['in'] } : {}),
234
+ description: asString(raw.description),
235
+ }
236
+ }
237
+
238
+ function securityNames(value: unknown): string[] | undefined {
239
+ if (!Array.isArray(value)) {
240
+ return undefined
241
+ }
242
+ return [...new Set(value.filter(isObject).flatMap(requirement => Object.keys(requirement)))]
243
+ }
244
+
245
+ /** `{scheme}://api.{region}.example` with each variable's default filled in. */
246
+ function expandServer(server: Json): string {
247
+ const variables = isObject(server.variables) ? server.variables : {}
248
+ return asString(server.url).replaceAll(/\{([^}]+)\}/g, (match, name: string) => {
249
+ const variable = variables[name]
250
+ return isObject(variable) && variable.default !== undefined ? String(variable.default) : match
251
+ })
252
+ }
253
+
254
+ export function actionOf(method: HttpMethod, path: string): OpenApiAction {
255
+ const segments = path.split('/').filter(Boolean)
256
+ const last = segments.at(-1) ?? ''
257
+ const item = last.startsWith('{')
258
+ // `/orders` and `/orders/{id}/items` are collections; `/orders/{id}/cancel` is an action on an item.
259
+ const collection = !item && (!segments.some(segment => segment.startsWith('{')) || /s$/i.test(last))
260
+ if (collection && method === 'get') {
261
+ return 'list'
262
+ }
263
+ if (collection && method === 'post') {
264
+ return 'create'
265
+ }
266
+ if (item && method === 'get') {
267
+ return 'read'
268
+ }
269
+ if (item && (method === 'put' || method === 'patch')) {
270
+ return 'update'
271
+ }
272
+ if (item && method === 'delete') {
273
+ return 'delete'
274
+ }
275
+ return 'other'
276
+ }
277
+
278
+ /** 2xx first, then 3xx, 4xx, 5xx, ranges after their codes, `default` last. */
279
+ function statusRank(status: string): number {
280
+ if (status === 'default') {
281
+ return 10_000
282
+ }
283
+ const match = /^(\d)(\d\d|XX)$/i.exec(status)
284
+ if (!match) {
285
+ return 9_000
286
+ }
287
+ return Number(match[1]) * 1000 + (match[2].toUpperCase() === 'XX' ? 999 : Number(match[2]))
288
+ }
289
+
290
+ function derivedId(method: string, path: string): string {
291
+ return slugify(`${method} ${path.replaceAll(/[{}]/g, '')}`)
292
+ }
293
+
294
+ function firstSegment(path: string): string {
295
+ return path.split('/').find(segment => segment && !segment.startsWith('{')) ?? ''
296
+ }
297
+
298
+ function resourceSlug(tag: Json, name: string): string {
299
+ return asString(tag['x-slug']) || slugify(name)
300
+ }
301
+
302
+ /** `createOrder` / `Create order` / `order.paid` → `create-order` / `create-order` / `order-paid`. */
303
+ export function slugify(text: string): string {
304
+ return text
305
+ .replaceAll(/([a-z0-9])([A-Z])/g, '$1-$2')
306
+ .replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
307
+ .toLowerCase()
308
+ .replaceAll(/[^a-z0-9]+/g, '-')
309
+ .replaceAll(/^-+|-+$/g, '')
310
+ }
311
+
312
+ function checkSlugs(resources: OpenApiResource[], operations: OpenApiOperation[], file: string): void {
313
+ const resourceBySlug = new Map<string, string>()
314
+ for (const resource of resources) {
315
+ if (RESERVED_SLUGS.has(resource.slug)) {
316
+ throw new Error(`${file}: the tag "${resource.name}" would use the page path "${resource.slug}/", which the plugin uses itself. Rename the tag or give it an "x-slug".`)
317
+ }
318
+ const other = resourceBySlug.get(resource.slug)
319
+ if (other) {
320
+ throw new Error(`${file}: the tags "${other}" and "${resource.name}" both become the page path "${resource.slug}/". Give one of them an "x-slug".`)
321
+ }
322
+ resourceBySlug.set(resource.slug, resource.name)
323
+ }
324
+ const ids = new Map<string, OpenApiOperation>()
325
+ for (const operation of operations) {
326
+ const key = `${operation.resource}/${operation.slug}`
327
+ const other = ids.get(key)
328
+ if (other) {
329
+ throw new Error(`${file}: ${other.method.toUpperCase()} ${other.path} and ${operation.method.toUpperCase()} ${operation.path} both become the page "${key}". Give them distinct operationIds.`)
330
+ }
331
+ ids.set(key, operation)
332
+ }
333
+ const byId = new Map<string, OpenApiOperation>()
334
+ for (const operation of operations) {
335
+ const other = byId.get(operation.id)
336
+ if (other) {
337
+ throw new Error(`${file}: the operationId "${operation.id}" is used by both ${other.method.toUpperCase()} ${other.path} and ${operation.method.toUpperCase()} ${operation.path}.`)
338
+ }
339
+ byId.set(operation.id, operation)
340
+ }
341
+ }
@@ -0,0 +1,212 @@
1
+ import type { SchemaConstraints, SchemaKind, SchemaNode, SchemaProperty } from '../types'
2
+ import type { Json, RefResolver } from './document'
3
+ import { asString, isObject, schemaRefName } from './document'
4
+
5
+ const KINDS = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'])
6
+ const CONSTRAINT_KEYS = [
7
+ 'minimum',
8
+ 'maximum',
9
+ 'multipleOf',
10
+ 'minLength',
11
+ 'maxLength',
12
+ 'pattern',
13
+ 'minItems',
14
+ 'maxItems',
15
+ 'uniqueItems',
16
+ ] as const
17
+
18
+ /**
19
+ * Turns a raw schema into a `SchemaNode`. References to `components.schemas`
20
+ * stay named leaves; `allOf` is merged into one object; `oneOf` / `anyOf`
21
+ * become variants; 3.0 `nullable` and 3.1 `type: [T, 'null']` both become
22
+ * `nullable`.
23
+ */
24
+ export function normalizeSchema(raw: unknown, refs: RefResolver, where: string, depth = 0): SchemaNode {
25
+ if (depth > 64) {
26
+ throw new Error(`${refs.file}: ${where} nests schemas too deeply.`)
27
+ }
28
+ if (isObject(raw) && typeof raw.$ref === 'string') {
29
+ const name = schemaRefName(raw.$ref)
30
+ if (name) {
31
+ refs.target(raw.$ref, where)
32
+ // 3.1 allows siblings next to $ref; the description is the useful one.
33
+ return { ...emptyNode('ref'), ref: name, description: asString(raw.description) }
34
+ }
35
+ return normalizeSchema(refs.deref(raw, where), refs, where, depth + 1)
36
+ }
37
+ if (raw === true || raw === undefined || (isObject(raw) && Object.keys(raw).length === 0)) {
38
+ return emptyNode('any')
39
+ }
40
+ if (!isObject(raw)) {
41
+ return emptyNode(raw === false ? 'null' : 'any')
42
+ }
43
+
44
+ const schema = Array.isArray(raw.allOf) ? mergeAllOf(raw, refs, where) : raw
45
+ const node = emptyNode(kindOf(schema))
46
+ node.description = asString(schema.description)
47
+ if (typeof schema.title === 'string') {
48
+ node.title = schema.title
49
+ }
50
+ if (typeof schema.format === 'string') {
51
+ node.format = schema.format
52
+ }
53
+ node.nullable = schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes('null'))
54
+ node.deprecated = schema.deprecated === true
55
+ node.readOnly = schema.readOnly === true
56
+ node.writeOnly = schema.writeOnly === true
57
+ if (Array.isArray(schema.enum)) {
58
+ node.enum = schema.enum.filter(value => value !== null || !node.nullable)
59
+ }
60
+ else if ('const' in schema) {
61
+ node.enum = [schema.const]
62
+ }
63
+ if ('default' in schema) {
64
+ node.default = schema.default
65
+ }
66
+ if ('example' in schema) {
67
+ node.example = schema.example
68
+ node.hasExample = true
69
+ }
70
+ else if (Array.isArray(schema.examples) && schema.examples.length > 0) {
71
+ node.example = schema.examples[0]
72
+ node.hasExample = true
73
+ }
74
+ if (typeof schema['x-since'] === 'string' || typeof schema['x-since'] === 'number') {
75
+ node.since = String(schema['x-since'])
76
+ }
77
+ node.constraints = constraintsOf(schema)
78
+
79
+ const variants = schema.oneOf ?? schema.anyOf
80
+ if (Array.isArray(variants)) {
81
+ const members = variants.filter(member => !(isObject(member) && member.type === 'null'))
82
+ if (members.length < variants.length) {
83
+ node.nullable = true
84
+ }
85
+ if (members.length === 1 && node.kind === 'union') {
86
+ return { ...normalizeSchema(members[0], refs, where, depth + 1), description: node.description || describe(members[0]), nullable: node.nullable }
87
+ }
88
+ node.variants = members.map((member, index) => normalizeSchema(member, refs, `${where} (variant ${index + 1})`, depth + 1))
89
+ }
90
+
91
+ if (isObject(schema.properties)) {
92
+ const required = new Set(Array.isArray(schema.required) ? schema.required.map(String) : [])
93
+ node.properties = Object.entries(schema.properties).map(([name, value]): SchemaProperty => ({
94
+ name,
95
+ required: required.has(name),
96
+ schema: normalizeSchema(value, refs, `${where}.${name}`, depth + 1),
97
+ }))
98
+ }
99
+ if (schema.additionalProperties === true || (isObject(schema.additionalProperties) && Object.keys(schema.additionalProperties).length === 0)) {
100
+ node.additionalProperties = true
101
+ }
102
+ else if (isObject(schema.additionalProperties)) {
103
+ node.additionalProperties = normalizeSchema(schema.additionalProperties, refs, `${where}.*`, depth + 1)
104
+ }
105
+ if (schema.items !== undefined && !Array.isArray(schema.items)) {
106
+ node.items = normalizeSchema(schema.items, refs, `${where}[]`, depth + 1)
107
+ }
108
+ return node
109
+ }
110
+
111
+ export function emptyNode(kind: SchemaKind): SchemaNode {
112
+ return {
113
+ kind,
114
+ description: '',
115
+ nullable: false,
116
+ deprecated: false,
117
+ readOnly: false,
118
+ writeOnly: false,
119
+ hasExample: false,
120
+ constraints: {},
121
+ }
122
+ }
123
+
124
+ function describe(raw: unknown): string {
125
+ return isObject(raw) ? asString(raw.description) : ''
126
+ }
127
+
128
+ function kindOf(schema: Json): SchemaKind {
129
+ const types = (Array.isArray(schema.type) ? schema.type : [schema.type]).filter(type => type !== 'null' && typeof type === 'string')
130
+ if (types.length > 1) {
131
+ return 'union'
132
+ }
133
+ if (types.length === 1 && KINDS.has(types[0] as string)) {
134
+ return types[0] as SchemaKind
135
+ }
136
+ if (Array.isArray(schema.type) && schema.type.includes('null')) {
137
+ return 'null'
138
+ }
139
+ if (Array.isArray(schema.oneOf) || Array.isArray(schema.anyOf)) {
140
+ return 'union'
141
+ }
142
+ if (isObject(schema.properties) || schema.additionalProperties !== undefined) {
143
+ return 'object'
144
+ }
145
+ if (schema.items !== undefined) {
146
+ return 'array'
147
+ }
148
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
149
+ const first = schema.enum.find(value => value !== null)
150
+ return typeof first === 'number' ? (Number.isInteger(first) ? 'integer' : 'number') : typeof first === 'boolean' ? 'boolean' : 'string'
151
+ }
152
+ return 'any'
153
+ }
154
+
155
+ function constraintsOf(schema: Json): SchemaConstraints {
156
+ const constraints: SchemaConstraints = {}
157
+ for (const key of CONSTRAINT_KEYS) {
158
+ const value = schema[key]
159
+ if (value !== undefined) {
160
+ (constraints as Record<string, unknown>)[key] = value
161
+ }
162
+ }
163
+ // 3.0 writes exclusive bounds as booleans next to minimum / maximum.
164
+ if (typeof schema.exclusiveMinimum === 'number') {
165
+ constraints.exclusiveMinimum = schema.exclusiveMinimum
166
+ }
167
+ else if (schema.exclusiveMinimum === true && typeof schema.minimum === 'number') {
168
+ constraints.exclusiveMinimum = schema.minimum
169
+ delete constraints.minimum
170
+ }
171
+ if (typeof schema.exclusiveMaximum === 'number') {
172
+ constraints.exclusiveMaximum = schema.exclusiveMaximum
173
+ }
174
+ else if (schema.exclusiveMaximum === true && typeof schema.maximum === 'number') {
175
+ constraints.exclusiveMaximum = schema.maximum
176
+ delete constraints.maximum
177
+ }
178
+ return constraints
179
+ }
180
+
181
+ /** One object out of `allOf`: properties and `required` merged, the outer schema's own keys winning. */
182
+ function mergeAllOf(schema: Json, refs: RefResolver, where: string): Json {
183
+ const merged: Json = {}
184
+ const properties: Json = {}
185
+ const required = new Set<string>()
186
+ const parts = [...(schema.allOf as unknown[]).map(part => refs.deref<Json>(part, where)), { ...schema, allOf: undefined }]
187
+ for (const part of parts) {
188
+ if (!isObject(part)) {
189
+ continue
190
+ }
191
+ const flat = Array.isArray(part.allOf) ? mergeAllOf(part, refs, where) : part
192
+ for (const [key, value] of Object.entries(flat)) {
193
+ if (key === 'properties' && isObject(value)) {
194
+ Object.assign(properties, value)
195
+ }
196
+ else if (key === 'required' && Array.isArray(value)) {
197
+ value.forEach(name => required.add(String(name)))
198
+ }
199
+ else if (key !== 'allOf' && value !== undefined && (key !== 'description' || value)) {
200
+ merged[key] = value
201
+ }
202
+ }
203
+ }
204
+ if (Object.keys(properties).length > 0) {
205
+ merged.properties = properties
206
+ merged.type ??= 'object'
207
+ }
208
+ if (required.size > 0) {
209
+ merged.required = [...required]
210
+ }
211
+ return merged
212
+ }