@kawapress/plugin-openapi 0.0.0-stage → 0.1.0

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,687 @@
1
+ import type { ValidationMessagesData } from '../components/validate'
2
+ import type { ResolvedOpenApiOptions } from '../options'
3
+ import type { SchemaTable } from '../read/example'
4
+ import type { OpenApiLabels } from '../render/labels'
5
+ import type { OpenApiLinks } from '../render/routes'
6
+ import type { LoadedApi } from '../service'
7
+ import type { OpenApiAction, OpenApiOperation, OpenApiParameter, OpenApiResponse, OpenApiWorkflow, WorkflowValue } from '../types'
8
+ import type { BodyContext, BodyData, FieldRow } from './body'
9
+ import type { PayloadData } from './payload'
10
+ import type { RequestExample } from './samples'
11
+ import { EXPRESSION_KEY, isExpression, outputValue, referencesOf } from '../read/arazzo'
12
+ import { isObject } from '../read/document'
13
+ import { exampleOf, resolveNode } from '../read/example'
14
+ import { emptyNode } from '../read/schema'
15
+ import { operationKey } from '../snapshot/snapshot'
16
+ import { buildBodyData, fieldRows } from './body'
17
+ import { typeLabel } from './fields'
18
+ import { buildPayload, payloadMarkdown } from './payload'
19
+ import { ruleOf } from './rules'
20
+ import { codeSamples, requestExample } from './samples'
21
+ import { constraintTexts, firstLine, plainLine, renderProse } from './text'
22
+ import { pascalCase } from './typescript'
23
+
24
+ /** Everything a data builder needs for one locale and page. */
25
+ export interface DataContext {
26
+ api: LoadedApi
27
+ schemas: SchemaTable
28
+ labels: OpenApiLabels
29
+ /** Links with the site base, for HTML. */
30
+ links: OpenApiLinks
31
+ /** Links without the base, for Markdown output. */
32
+ pageLinks: OpenApiLinks
33
+ highlight: (code: string, lang: string) => Promise<string>
34
+ options: Pick<ResolvedOpenApiOptions, 'samples' | 'tryIt'>
35
+ }
36
+
37
+ export function createSchemaTable(api: LoadedApi): SchemaTable {
38
+ return new Map(api.model.schemas.map(entry => [entry.name, entry.schema]))
39
+ }
40
+
41
+ function bodyContext(context: DataContext): BodyContext {
42
+ return {
43
+ schemas: context.schemas,
44
+ labels: context.labels,
45
+ modelHref: name => context.links.model(name),
46
+ highlight: context.highlight,
47
+ }
48
+ }
49
+
50
+ function sinceFor(context: DataContext, operation: OpenApiOperation, subject: string): (path: string) => string | undefined {
51
+ const key = operationKey(operation)
52
+ return path => context.api.subjectSince.get(`${key}|${subject} ${path}`)
53
+ }
54
+
55
+ /* ---------------------------------------------------------------- endpoint */
56
+
57
+ export interface EndpointData {
58
+ method: string
59
+ path: string
60
+ webhook: boolean
61
+ deprecated: boolean
62
+ since?: string
63
+ security: string[]
64
+ curl?: string
65
+ tryIt?: {
66
+ server?: string
67
+ request: RequestExample
68
+ rule?: unknown
69
+ response?: { status: string, body?: unknown }
70
+ messages: ValidationMessagesData
71
+ }
72
+ text: {
73
+ deprecated: string
74
+ since?: string
75
+ auth: string
76
+ copyCurl: string
77
+ copied: string
78
+ copyFailed: string
79
+ tryIt: string
80
+ send: string
81
+ sending: string
82
+ mock: string
83
+ server: string
84
+ token: string
85
+ mockNote: string
86
+ serverNote?: string
87
+ notSent: string
88
+ invalidJson: string
89
+ validationFailed: string
90
+ requestBody: string
91
+ parameters: string
92
+ }
93
+ markdown: string
94
+ }
95
+
96
+ export function buildEndpointData(operation: OpenApiOperation, context: DataContext): EndpointData {
97
+ const { labels, api, schemas } = context
98
+ const request = requestExample(operation, api.model, schemas)
99
+ const success = operation.responses.find(response => response.status.startsWith('2'))
100
+ const tryIt = context.options.tryIt
101
+ const curl = operation.webhook ? undefined : codeSamples(request, ['curl'])[0].code
102
+ const security = operation.security.map((name) => {
103
+ const scheme = api.model.securitySchemes.find(item => item.name === name)
104
+ return scheme?.type === 'http' && scheme.scheme ? `${name} (${scheme.scheme})` : name
105
+ })
106
+ const method = operation.webhook ? 'HOOK' : operation.method.toUpperCase()
107
+ return {
108
+ method,
109
+ path: operation.path,
110
+ webhook: operation.webhook,
111
+ deprecated: operation.deprecated,
112
+ ...(operation.since ? { since: operation.since } : {}),
113
+ security,
114
+ ...(curl ? { curl } : {}),
115
+ ...(tryIt && !operation.webhook
116
+ ? {
117
+ tryIt: {
118
+ ...(tryIt.server ? { server: tryIt.server } : {}),
119
+ request,
120
+ ...(operation.requestBody ? { rule: ruleOf(operation.requestBody.schema, schemas, 'request') } : {}),
121
+ ...(success ? { response: { status: success.status, ...(success.body ? { body: success.body.example } : {}) } } : {}),
122
+ messages: labels.validation,
123
+ },
124
+ }
125
+ : {}),
126
+ text: {
127
+ deprecated: labels.deprecatedOperation,
128
+ ...(operation.since ? { since: labels.since(operation.since) } : {}),
129
+ auth: labels.auth,
130
+ copyCurl: labels.copyCurl,
131
+ copied: labels.copied,
132
+ copyFailed: labels.copyFailed,
133
+ tryIt: labels.tryIt,
134
+ send: labels.send,
135
+ sending: labels.sending,
136
+ mock: labels.mock,
137
+ server: labels.server,
138
+ token: labels.token,
139
+ mockNote: labels.mockNote,
140
+ ...(tryIt && tryIt.server ? { serverNote: labels.serverNote(tryIt.server) } : {}),
141
+ notSent: labels.notSent,
142
+ invalidJson: labels.invalidJson,
143
+ validationFailed: labels.validationFailed,
144
+ requestBody: labels.requestBody,
145
+ parameters: labels.parameters,
146
+ },
147
+ markdown: [
148
+ `\`${method} ${operation.path}\``,
149
+ operation.deprecated ? `> ${labels.deprecatedOperation}` : '',
150
+ operation.since ? labels.since(operation.since) : '',
151
+ security.length ? `${labels.auth}: ${security.join(', ')}` : '',
152
+ ].filter(Boolean).join('\n\n'),
153
+ }
154
+ }
155
+
156
+ /* -------------------------------------------------------------- parameters */
157
+
158
+ export interface ParametersData {
159
+ groups: { title: string, rows: FieldRow[] }[]
160
+ text: { required: string, deprecated: string, defaultValue: string, since: string }
161
+ markdown: string
162
+ }
163
+
164
+ export function buildParametersData(operation: OpenApiOperation, context: DataContext): ParametersData {
165
+ const { labels, schemas } = context
166
+ const order: OpenApiParameter['in'][] = ['path', 'query', 'header', 'cookie']
167
+ const since = sinceFor(context, operation, 'param')
168
+ const groups = order
169
+ .map(location => ({
170
+ title: labels.parameterGroups[location],
171
+ rows: operation.parameters.filter(parameter => parameter.in === location).map((parameter): FieldRow => {
172
+ const target = resolveNode(parameter.schema, schemas)
173
+ const ref = parameter.schema.kind === 'ref' ? parameter.schema.ref : undefined
174
+ const typeHref = ref ? context.links.model(ref) : undefined
175
+ const inferred = parameter.since ?? target.since ?? since(`${location} ${parameter.name}`)
176
+ const constraints = constraintTexts(parameter.schema, schemas, labels)
177
+ if (target.default !== undefined) {
178
+ constraints.push(`${labels.defaultValue} ${JSON.stringify(target.default)}`)
179
+ }
180
+ return {
181
+ path: parameter.name,
182
+ depth: 0,
183
+ type: typeLabel(parameter.schema, schemas),
184
+ ...(typeHref ? { typeHref } : {}),
185
+ required: parameter.required,
186
+ constraints,
187
+ descriptionHtml: renderProse(parameter.description),
188
+ deprecated: parameter.deprecated,
189
+ ...(inferred ? { since: inferred } : {}),
190
+ }
191
+ }),
192
+ }))
193
+ .filter(group => group.rows.length > 0)
194
+ const markdown = groups.map(group => [
195
+ `**${group.title}**`,
196
+ group.rows.map((row) => {
197
+ const notes = [row.required ? labels.required : '', ...row.constraints, row.deprecated ? labels.deprecated : ''].filter(Boolean)
198
+ const parameter = operation.parameters.find(item => item.name === row.path)
199
+ return `- \`${row.path}\` \`${row.type}\`${notes.length ? ` (${notes.join(', ')})` : ''}${parameter?.description ? ` — ${firstLine(parameter.description)}` : ''}`
200
+ }).join('\n'),
201
+ ].join('\n\n')).join('\n\n')
202
+ return { groups, text: { required: labels.required, deprecated: labels.deprecated, defaultValue: labels.defaultValue, since: labels.since('{n}') }, markdown }
203
+ }
204
+
205
+ /* -------------------------------------------------------------------- body */
206
+
207
+ export interface BodyViewData {
208
+ body: BodyData
209
+ text: BodyText
210
+ }
211
+
212
+ export interface BodyText {
213
+ views: { payload: string, table: string, typescript: string }
214
+ generated: string
215
+ required: string
216
+ deprecated: string
217
+ defaultValue: string
218
+ since: string
219
+ columns: { field: string, type: string, constraints: string, description: string }
220
+ }
221
+
222
+ export function bodyText(labels: OpenApiLabels): BodyText {
223
+ return {
224
+ views: labels.views,
225
+ generated: labels.generated,
226
+ required: labels.required,
227
+ deprecated: labels.deprecated,
228
+ defaultValue: labels.defaultValue,
229
+ since: labels.since('{n}'),
230
+ columns: labels.columns,
231
+ }
232
+ }
233
+
234
+ export async function buildRequestData(operation: OpenApiOperation, context: DataContext): Promise<BodyViewData | undefined> {
235
+ const body = operation.requestBody
236
+ if (!body) {
237
+ return undefined
238
+ }
239
+ return {
240
+ body: await buildBodyData({
241
+ schema: body.schema,
242
+ example: body.example,
243
+ generated: body.exampleGenerated,
244
+ contentType: body.contentType,
245
+ description: body.description,
246
+ direction: 'request',
247
+ typeName: `${pascalCase(operation.id)}Request`,
248
+ sinceOf: sinceFor(context, operation, 'request'),
249
+ }, bodyContext(context)),
250
+ text: bodyText(context.labels),
251
+ }
252
+ }
253
+
254
+ /* --------------------------------------------------------------- responses */
255
+
256
+ export interface ResponsesData {
257
+ responses: { status: string, descriptionHtml: string, body?: BodyData }[]
258
+ /** Index of the response open at first: the first 2xx. */
259
+ initial: number
260
+ text: BodyText & { noBody: string }
261
+ markdown: string
262
+ }
263
+
264
+ export async function buildResponsesData(operation: OpenApiOperation, context: DataContext): Promise<ResponsesData> {
265
+ const responses = await Promise.all(operation.responses.map(async (response: OpenApiResponse) => ({
266
+ status: response.status,
267
+ descriptionHtml: renderProse(response.description),
268
+ ...(response.body
269
+ ? {
270
+ body: await buildBodyData({
271
+ schema: response.body.schema,
272
+ example: response.body.example,
273
+ generated: response.body.exampleGenerated,
274
+ contentType: response.body.contentType,
275
+ description: '',
276
+ direction: 'response',
277
+ typeName: `${pascalCase(operation.id)}Response${response.status.replaceAll(/\W/g, '')}`,
278
+ sinceOf: sinceFor(context, operation, `response ${response.status}`),
279
+ }, bodyContext(context)),
280
+ }
281
+ : {}),
282
+ })))
283
+ const initial = Math.max(0, operation.responses.findIndex(response => response.status.startsWith('2')))
284
+ return {
285
+ responses,
286
+ initial,
287
+ text: { ...bodyText(context.labels), noBody: context.labels.noBody },
288
+ markdown: responses.map(response => [
289
+ `### ${response.status}`,
290
+ operation.responses.find(item => item.status === response.status)?.description ?? '',
291
+ response.body?.markdown ?? context.labels.noBody,
292
+ ].filter(Boolean).join('\n\n')).join('\n\n'),
293
+ }
294
+ }
295
+
296
+ /* ----------------------------------------------------------------- samples */
297
+
298
+ export interface SamplesData {
299
+ samples: { label: string, html: string, code: string }[]
300
+ markdown: string
301
+ }
302
+
303
+ export async function buildSamplesData(operation: OpenApiOperation, context: DataContext): Promise<SamplesData> {
304
+ const request = requestExample(operation, context.api.model, context.schemas)
305
+ const samples = await Promise.all(codeSamples(request, context.options.samples).map(async sample => ({
306
+ label: sample.label,
307
+ code: sample.code,
308
+ html: await context.highlight(sample.code, sample.lang),
309
+ lang: sample.lang,
310
+ })))
311
+ return {
312
+ samples: samples.map(({ label, html, code }) => ({ label, html, code })),
313
+ markdown: samples.map(sample => `**${sample.label}**\n\n\`\`\`${sample.lang}\n${sample.code}\n\`\`\``).join('\n\n'),
314
+ }
315
+ }
316
+
317
+ /* ------------------------------------------------------------------ schema */
318
+
319
+ export async function buildSchemaData(name: string, context: DataContext): Promise<BodyViewData | undefined> {
320
+ const entry = context.api.model.schemas.find(item => item.name === name)
321
+ if (!entry) {
322
+ return undefined
323
+ }
324
+ const schema = { ...emptyNode('ref'), ref: name }
325
+ const example = entry.schema.hasExample ? entry.schema.example : exampleOf(schema, context.schemas, 'response')
326
+ return {
327
+ body: await buildBodyData({
328
+ schema,
329
+ example,
330
+ generated: !entry.schema.hasExample,
331
+ contentType: 'application/json',
332
+ description: '',
333
+ direction: 'response',
334
+ typeName: name,
335
+ }, bodyContext(context)),
336
+ text: bodyText(context.labels),
337
+ }
338
+ }
339
+
340
+ /* --------------------------------------------------------------------- map */
341
+
342
+ export interface MapCell {
343
+ method: string
344
+ path: string
345
+ title: string
346
+ href: string
347
+ deprecated: boolean
348
+ since?: string
349
+ }
350
+
351
+ export interface MapData {
352
+ columns: { action: OpenApiAction, title: string }[]
353
+ rows: { name: string, href: string, summary: string, cells: Record<OpenApiAction, MapCell[]> }[]
354
+ text: { resource: string, deprecated: string, since: string }
355
+ markdown: string
356
+ }
357
+
358
+ const ACTIONS: OpenApiAction[] = ['list', 'create', 'read', 'update', 'delete', 'other']
359
+
360
+ export function buildMapData(context: DataContext): MapData {
361
+ const { model } = context.api
362
+ const { labels } = context
363
+ const latest = context.api.snapshots.length ? [...context.api.snapshots].map(snapshot => snapshot.version).sort().at(-1) : undefined
364
+ const rows = model.resources.map((resource) => {
365
+ const cells = Object.fromEntries(ACTIONS.map(action => [action, [] as MapCell[]])) as Record<OpenApiAction, MapCell[]>
366
+ for (const operation of model.operations.filter(item => item.resource === resource.name)) {
367
+ cells[operation.action].push({
368
+ method: operation.webhook ? 'HOOK' : operation.method.toUpperCase(),
369
+ path: operation.path,
370
+ title: operation.summary || operation.id,
371
+ href: context.links.operation(operation.id) ?? '',
372
+ deprecated: operation.deprecated,
373
+ ...(operation.since && operation.since === latest ? { since: operation.since } : {}),
374
+ })
375
+ }
376
+ return { name: resource.name, href: context.links.resource(resource.name) ?? '', summary: plainLine(resource.description), cells }
377
+ })
378
+ // The CRUD columns always show: an empty cell says the API cannot do that.
379
+ const used = ACTIONS.filter(action => action !== 'other' || rows.some(row => row.cells.other.length > 0))
380
+ const markdown = [
381
+ `| ${labels.resources} | ${used.map(action => labels.actions[action]).join(' | ')} |`,
382
+ `| --- | ${used.map(() => '---').join(' | ')} |`,
383
+ ...rows.map(row => `| [${row.name}](${context.pageLinks.resource(row.name)}) | ${used.map(action => row.cells[action].map(cell => `\`${cell.method} ${cell.path}\``).join('<br>') || '—').join(' | ')} |`),
384
+ ].join('\n')
385
+ return {
386
+ columns: used.map(action => ({ action, title: labels.actions[action] })),
387
+ rows,
388
+ text: { resource: labels.resources, deprecated: labels.deprecated, since: labels.since('{n}') },
389
+ markdown,
390
+ }
391
+ }
392
+
393
+ /* ----------------------------------------------------------------- journey */
394
+
395
+ export interface JourneyStepData {
396
+ index: number
397
+ id: string
398
+ descriptionHtml: string
399
+ method: string
400
+ path: string
401
+ title: string
402
+ href: string
403
+ webhook: boolean
404
+ parameters: { name: string, in: string, value: string, mark?: number }[]
405
+ request?: PayloadData
406
+ status: string
407
+ response?: PayloadData
408
+ flows: { mark: number, text: string }[]
409
+ }
410
+
411
+ export interface JourneyData {
412
+ id: string
413
+ steps: JourneyStepData[]
414
+ text: {
415
+ send: string
416
+ get: string
417
+ receive: string
418
+ respond: string
419
+ run: string
420
+ runAgain: string
421
+ pending: string
422
+ running: string
423
+ done: string
424
+ parameters: string
425
+ }
426
+ markdown: string
427
+ }
428
+
429
+ /** Colour index of `$inputs` values. */
430
+ export const INPUT_MARK = -1
431
+ const MARK_COLOURS = 5
432
+
433
+ export function buildJourneyData(workflow: OpenApiWorkflow, context: DataContext): JourneyData {
434
+ const { model } = context.api
435
+ const { labels, schemas } = context
436
+ const operations = new Map(model.operations.map(operation => [operation.id, operation]))
437
+ const stepIndex = new Map(workflow.steps.map((step, index) => [step.id, index]))
438
+ const marks = new Map<string, number>()
439
+ for (const step of workflow.steps) {
440
+ for (const reference of referencesOf(step)) {
441
+ const key = `${reference.step}.${reference.output}`
442
+ if (!marks.has(key)) {
443
+ marks.set(key, marks.size % MARK_COLOURS)
444
+ }
445
+ }
446
+ }
447
+ const responses = new Map<string, unknown>()
448
+ const responseOf = (stepId: string): unknown => responses.get(stepId)
449
+
450
+ const resolve = (value: WorkflowValue): { value: unknown, mark?: number } => {
451
+ if (value.kind === 'literal') {
452
+ return { value: value.value }
453
+ }
454
+ if (value.kind === 'input') {
455
+ return { value: `$inputs.${value.name}`, mark: INPUT_MARK }
456
+ }
457
+ const producer = workflow.steps[stepIndex.get(value.step)!]
458
+ const found = producer ? outputValue(producer, value.output, responseOf(producer.id)) : undefined
459
+ return { value: found ?? `$steps.${value.step}.outputs.${value.output}`, mark: marks.get(`${value.step}.${value.output}`) }
460
+ }
461
+
462
+ const steps = workflow.steps.map((step, index): JourneyStepData => {
463
+ const operation = operations.get(step.operation)!
464
+ const response = operation.responses.find(item => item.status === step.status)
465
+ ?? operation.responses.find(item => item.status.startsWith('2'))
466
+ ?? operation.responses[0]
467
+ const responseBody = response?.body?.example
468
+ responses.set(step.id, responseBody)
469
+
470
+ const parameters = step.parameters.map((parameter) => {
471
+ const resolved = resolve(parameter.value)
472
+ return {
473
+ name: parameter.name,
474
+ in: parameter.in ?? operation.parameters.find(item => item.name === parameter.name)?.in ?? 'query',
475
+ value: typeof resolved.value === 'string' ? resolved.value : JSON.stringify(resolved.value),
476
+ ...(resolved.mark !== undefined ? { mark: resolved.mark } : {}),
477
+ }
478
+ })
479
+
480
+ let request: PayloadData | undefined
481
+ if (step.payload !== undefined || operation.requestBody) {
482
+ const requestMarks = new Map<string, number>()
483
+ const payload = step.payload === undefined
484
+ ? operation.requestBody?.example
485
+ : substitute(step.payload, '', requestMarks, resolve)
486
+ request = buildPayload(payload, operation.requestBody?.schema, { schemas, direction: 'request', labels, modelHref: () => undefined, marks: requestMarks, bare: true })
487
+ }
488
+
489
+ const responseMarks = new Map<string, number>()
490
+ for (const output of step.outputs) {
491
+ const mark = marks.get(`${step.id}.${output.name}`)
492
+ if (mark !== undefined && output.pointer !== undefined) {
493
+ responseMarks.set(output.pointer, mark)
494
+ }
495
+ }
496
+ const flows = referencesOf(step)
497
+ .filter((reference, position, all) => all.findIndex(item => item.step === reference.step && item.output === reference.output) === position)
498
+ .map(reference => ({ mark: marks.get(`${reference.step}.${reference.output}`)!, text: labels.fromStep(stepIndex.get(reference.step)! + 1, reference.output) }))
499
+ const inputs = inputsOf(step)
500
+ flows.push(...inputs.map(name => ({ mark: INPUT_MARK, text: labels.fromInput(name) })))
501
+
502
+ return {
503
+ index,
504
+ id: step.id,
505
+ descriptionHtml: renderProse(step.description),
506
+ method: operation.webhook ? 'HOOK' : operation.method.toUpperCase(),
507
+ path: operation.path,
508
+ title: operation.summary || operation.id,
509
+ href: context.links.operation(operation.id) ?? '',
510
+ webhook: operation.webhook,
511
+ parameters,
512
+ ...(request ? { request } : {}),
513
+ status: response?.status ?? '',
514
+ ...(responseBody !== undefined ? { response: buildPayload(responseBody, response?.body?.schema, { schemas, direction: 'response', labels, modelHref: () => undefined, marks: responseMarks, bare: true }) } : {}),
515
+ flows,
516
+ }
517
+ })
518
+
519
+ const markdown = steps.map(step => [
520
+ `### ${step.index + 1}. ${step.title}`,
521
+ `\`${step.method} ${step.path}\` — [${labels.viewOperation}](${context.pageLinks.operation(workflow.steps[step.index].operation)})`,
522
+ step.flows.map(flow => `- ${flow.text}`).join('\n'),
523
+ step.parameters.length ? `${labels.parameters}: ${step.parameters.map(parameter => `\`${parameter.name}=${parameter.value}\``).join(', ')}` : '',
524
+ step.request ? `${step.webhook ? labels.receive : labels.sendLabel}:\n\n${payloadMarkdown(step.request)}` : '',
525
+ step.response ? `${step.webhook ? labels.respond : labels.getLabel} (${step.status}):\n\n${payloadMarkdown(step.response)}` : '',
526
+ ].filter(Boolean).join('\n\n')).join('\n\n')
527
+
528
+ return {
529
+ id: workflow.id,
530
+ steps,
531
+ text: {
532
+ send: labels.sendLabel,
533
+ get: labels.getLabel,
534
+ receive: labels.receive,
535
+ respond: labels.respond,
536
+ run: labels.runJourney,
537
+ runAgain: labels.runAgain,
538
+ pending: labels.pending,
539
+ running: labels.running,
540
+ done: labels.done,
541
+ parameters: labels.parameters,
542
+ },
543
+ markdown,
544
+ }
545
+ }
546
+
547
+ /** Names of the workflow inputs a step reads, in order. */
548
+ function inputsOf(step: OpenApiWorkflow['steps'][number]): string[] {
549
+ const names = new Set<string>()
550
+ const visit = (value: unknown): void => {
551
+ if (isExpression(value)) {
552
+ const expression = value[EXPRESSION_KEY]
553
+ if (expression.kind === 'input') {
554
+ names.add(expression.name)
555
+ }
556
+ }
557
+ else if (Array.isArray(value)) {
558
+ value.forEach(visit)
559
+ }
560
+ else if (isObject(value)) {
561
+ Object.values(value).forEach(visit)
562
+ }
563
+ }
564
+ step.parameters.forEach(parameter => visit({ [EXPRESSION_KEY]: parameter.value }))
565
+ visit(step.payload)
566
+ return [...names]
567
+ }
568
+
569
+ /** Replaces the expression placeholders of a step payload with example values, noting where each one went. */
570
+ function substitute(
571
+ value: unknown,
572
+ pointer: string,
573
+ marks: Map<string, number>,
574
+ resolve: (value: WorkflowValue) => { value: unknown, mark?: number },
575
+ ): unknown {
576
+ if (isExpression(value)) {
577
+ const resolved = resolve(value[EXPRESSION_KEY])
578
+ if (resolved.mark !== undefined) {
579
+ marks.set(pointer, resolved.mark)
580
+ }
581
+ return resolved.value
582
+ }
583
+ if (Array.isArray(value)) {
584
+ return value.map((item, index) => substitute(item, `${pointer}/${index}`, marks, resolve))
585
+ }
586
+ if (isObject(value)) {
587
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, substitute(item, `${pointer}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`, marks, resolve)]))
588
+ }
589
+ return value
590
+ }
591
+
592
+ /* -------------------------------------------------------------------- card */
593
+
594
+ export interface CardData {
595
+ method: string
596
+ path: string
597
+ title: string
598
+ summaryHtml: string
599
+ href: string
600
+ fields: { name: string, type: string, note: string }[]
601
+ response?: { status: string, type: string, href?: string }
602
+ text: { details: string }
603
+ markdown: string
604
+ }
605
+
606
+ export function buildCardData(operation: OpenApiOperation, context: DataContext, only?: string[]): CardData {
607
+ const { labels, schemas } = context
608
+ const body = operation.requestBody
609
+ const rows = body ? fieldRows(body.schema, 'request', { schemas, labels, modelHref: () => undefined }).filter(row => row.depth === 0) : []
610
+ const fields = (only?.length ? rows.filter(row => only.includes(row.path)) : rows.filter(row => row.required))
611
+ .map(row => ({ name: row.path, type: row.type, note: [row.required ? labels.required : '', ...row.constraints.slice(0, 1), row.since ? labels.since(row.since) : ''].filter(Boolean).join(' · ') }))
612
+ const success = operation.responses.find(response => response.status.startsWith('2'))
613
+ const ref = success?.body?.schema.kind === 'ref' ? success.body.schema.ref : undefined
614
+ const method = operation.webhook ? 'HOOK' : operation.method.toUpperCase()
615
+ const title = operation.summary || operation.id
616
+ return {
617
+ method,
618
+ path: operation.path,
619
+ title,
620
+ summaryHtml: renderProse(firstLine(operation.description)),
621
+ href: context.links.operation(operation.id) ?? '',
622
+ fields,
623
+ ...(success ? { response: { status: success.status, type: success.body ? typeLabel(success.body.schema, schemas) : '', ...(ref && context.links.model(ref) ? { href: context.links.model(ref)! } : {}) } } : {}),
624
+ text: { details: labels.details },
625
+ markdown: [
626
+ `**[\`${method} ${operation.path}\` ${title}](${context.pageLinks.operation(operation.id)})**`,
627
+ firstLine(operation.description),
628
+ fields.map(field => `- \`${field.name}\` \`${field.type}\`${field.note ? ` (${field.note})` : ''}`).join('\n'),
629
+ ].filter(Boolean).join('\n\n'),
630
+ }
631
+ }
632
+
633
+ /* --------------------------------------------------------------------- ref */
634
+
635
+ export interface RefData {
636
+ method?: string
637
+ label: string
638
+ title: string
639
+ summary: string
640
+ href: string
641
+ markdown: string
642
+ }
643
+
644
+ export type RefTarget = { op: string } | { schema: string } | { journey: string }
645
+
646
+ export function buildRefData(target: RefTarget, context: DataContext): RefData | undefined {
647
+ const { model } = context.api
648
+ if ('op' in target) {
649
+ const operation = model.operations.find(item => item.id === target.op)
650
+ if (!operation) {
651
+ return undefined
652
+ }
653
+ const method = operation.webhook ? 'HOOK' : operation.method.toUpperCase()
654
+ return {
655
+ method,
656
+ label: operation.path,
657
+ title: operation.summary || operation.id,
658
+ summary: plainLine(operation.description),
659
+ href: context.links.operation(operation.id)!,
660
+ markdown: `[\`${method} ${operation.path}\`](${context.pageLinks.operation(operation.id)})`,
661
+ }
662
+ }
663
+ if ('schema' in target) {
664
+ const entry = model.schemas.find(item => item.name === target.schema)
665
+ if (!entry) {
666
+ return undefined
667
+ }
668
+ return {
669
+ label: entry.name,
670
+ title: entry.schema.title ?? entry.name,
671
+ summary: plainLine(entry.schema.description),
672
+ href: context.links.model(entry.name)!,
673
+ markdown: `[\`${entry.name}\`](${context.pageLinks.model(entry.name)})`,
674
+ }
675
+ }
676
+ const workflow = model.workflows.find(item => item.id === target.journey)
677
+ if (!workflow) {
678
+ return undefined
679
+ }
680
+ return {
681
+ label: workflow.summary || workflow.id,
682
+ title: workflow.summary || workflow.id,
683
+ summary: plainLine(workflow.description),
684
+ href: context.links.journey(workflow.id)!,
685
+ markdown: `[${workflow.summary || workflow.id}](${context.pageLinks.journey(workflow.id)})`,
686
+ }
687
+ }