@kawapress/plugin-openapi 0.1.0 → 0.2.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.
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ export type {
17
17
  OpenApiModel,
18
18
  OpenApiOperation,
19
19
  OpenApiParameter,
20
+ OpenApiPerLocale,
20
21
  OpenApiPluginOptions,
21
22
  OpenApiResource,
22
23
  OpenApiResponse,
@@ -92,7 +93,7 @@ export function openapiPlugin(options: OpenApiPluginOptions): OpenApiPlugin {
92
93
  })
93
94
  api.configResolved((config) => {
94
95
  site = config
95
- resolved = resolveOpenApiOptions(options, config.root)
96
+ resolved = resolveOpenApiOptions(options, config.root, Object.keys(config.locales ?? DEFAULT_LOCALES))
96
97
  })
97
98
  api.markdown((compiler) => {
98
99
  markdown = compiler
@@ -109,7 +110,7 @@ export function openapiPlugin(options: OpenApiPluginOptions): OpenApiPlugin {
109
110
  options: getResolved,
110
111
  base: () => site?.base ?? '/',
111
112
  markdown: () => markdown,
112
- languageOf: prefix => locales[prefix ? prefix.slice(1) : 'root']?.lang,
113
+ languageOf: locale => locales[locale]?.lang,
113
114
  component: kind => fileURLToPath(new URL(`./components/${COMPONENT_FILES[kind] ?? 'KawaOpenApiRef'}.vue`, import.meta.url)),
114
115
  }),
115
116
  ]
package/src/options.ts CHANGED
@@ -1,16 +1,24 @@
1
- import type { OpenApiPluginOptions, OpenApiSampleLanguage } from './types'
1
+ import type { OpenApiPerLocale, OpenApiPluginOptions, OpenApiSampleLanguage } from './types'
2
2
  import { isAbsolute, resolve } from 'node:path'
3
3
 
4
4
  export const DEFAULT_ROUTE = 'openapi/'
5
5
  export const DEFAULT_SNAPSHOT_DIR = 'openapi-snapshots'
6
6
  export const DEFAULT_SAMPLES: readonly OpenApiSampleLanguage[] = ['curl', 'javascript', 'python']
7
+ /** The locale whose source the others fall back to. */
8
+ export const ROOT_LOCALE = 'root'
7
9
 
8
- export interface ResolvedOpenApiOptions {
9
- root: string
10
+ /** The files one locale reads its API from. */
11
+ export interface OpenApiSource {
10
12
  /** Absolute path of the OpenAPI document. */
11
13
  spec: string
12
14
  /** Absolute paths of the Arazzo files. */
13
15
  workflows: string[]
16
+ }
17
+
18
+ export interface ResolvedOpenApiOptions {
19
+ root: string
20
+ /** Sources by locale key; `root` is always there and serves locales without their own. */
21
+ sources: Readonly<Record<string, OpenApiSource>>
14
22
  /** `/openapi/`. */
15
23
  route: string
16
24
  snapshotDir: string
@@ -18,12 +26,26 @@ export interface ResolvedOpenApiOptions {
18
26
  samples: readonly OpenApiSampleLanguage[]
19
27
  }
20
28
 
21
- export function resolveOpenApiOptions(options: OpenApiPluginOptions, root: string): ResolvedOpenApiOptions {
29
+ /** Resolves paths against the site root; per-locale entries must name one of `localeKeys` when given. */
30
+ export function resolveOpenApiOptions(options: OpenApiPluginOptions, root: string, localeKeys?: readonly string[]): ResolvedOpenApiOptions {
22
31
  if (!options.spec) {
23
32
  throw new Error('KawaPress OpenAPI: the option "spec" is required, for example spec: \'./openapi.yaml\'.')
24
33
  }
25
34
  const at = (path: string): string => (isAbsolute(path) ? path : resolve(root, path))
26
- const workflows = options.workflows === undefined ? [] : Array.isArray(options.workflows) ? options.workflows : [options.workflows]
35
+ const specs = perLocale(options.spec, 'spec', localeKeys)
36
+ if (!specs[ROOT_LOCALE]) {
37
+ throw new Error(`KawaPress OpenAPI: the option "spec" needs a "${ROOT_LOCALE}" entry; locales without their own spec use it.`)
38
+ }
39
+ const workflows = perLocale(options.workflows ?? [], 'workflows', localeKeys)
40
+ const sources: Record<string, OpenApiSource> = {}
41
+ for (const key of new Set([ROOT_LOCALE, ...Object.keys(specs), ...Object.keys(workflows)])) {
42
+ const files = workflows[key] ?? workflows[ROOT_LOCALE] ?? []
43
+ sources[key] = {
44
+ spec: at(specs[key] ?? specs[ROOT_LOCALE]),
45
+ workflows: (Array.isArray(files) ? files : [files]).map(at),
46
+ }
47
+ }
48
+
27
49
  const samples = options.samples ?? DEFAULT_SAMPLES
28
50
  const unknown = samples.filter(language => !DEFAULT_SAMPLES.includes(language))
29
51
  if (unknown.length > 0) {
@@ -32,8 +54,7 @@ export function resolveOpenApiOptions(options: OpenApiPluginOptions, root: strin
32
54
  const server = options.tryIt === false ? undefined : options.tryIt?.server?.replace(/\/+$/, '')
33
55
  return {
34
56
  root,
35
- spec: at(options.spec),
36
- workflows: workflows.map(at),
57
+ sources,
37
58
  route: normalizeRoute(options.route ?? DEFAULT_ROUTE),
38
59
  snapshotDir: at(options.snapshotDir ?? DEFAULT_SNAPSHOT_DIR),
39
60
  tryIt: options.tryIt === false ? false : server ? { server } : {},
@@ -41,6 +62,28 @@ export function resolveOpenApiOptions(options: OpenApiPluginOptions, root: strin
41
62
  }
42
63
  }
43
64
 
65
+ /** The source of a locale: its own, or the `root` one. */
66
+ export function sourceOf(options: ResolvedOpenApiOptions, key: string): OpenApiSource {
67
+ return options.sources[key] ?? options.sources[ROOT_LOCALE]!
68
+ }
69
+
70
+ /** Every distinct source, `root` first. */
71
+ export function allSources(options: ResolvedOpenApiOptions): OpenApiSource[] {
72
+ return [...new Set([sourceOf(options, ROOT_LOCALE), ...Object.values(options.sources)])]
73
+ }
74
+
75
+ /** A per-locale option as a record by locale key; a single value is the `root` entry. */
76
+ function perLocale<T extends string | string[]>(value: OpenApiPerLocale<T>, option: string, localeKeys: readonly string[] | undefined): Record<string, T> {
77
+ if (typeof value === 'string' || Array.isArray(value)) {
78
+ return { [ROOT_LOCALE]: value as T }
79
+ }
80
+ const unknown = localeKeys ? Object.keys(value).filter(key => !localeKeys.includes(key)) : []
81
+ if (unknown.length > 0) {
82
+ throw new Error(`KawaPress OpenAPI: the option "${option}" has entries for ${unknown.join(', ')}, but the site's locales are ${localeKeys!.join(', ')}.`)
83
+ }
84
+ return value
85
+ }
86
+
44
87
  /** `openapi` / `/openapi` / `/openapi/` all become `/openapi/`. */
45
88
  export function normalizeRoute(route: string): string {
46
89
  const segments = route.split('/').filter(Boolean)
@@ -49,5 +92,10 @@ export function normalizeRoute(route: string): string {
49
92
 
50
93
  /** URL prefix of a locale key: `root` has none, `en` is `/en`. */
51
94
  export function localePrefix(key: string): string {
52
- return key === 'root' ? '' : `/${key}`
95
+ return key === ROOT_LOCALE ? '' : `/${key}`
96
+ }
97
+
98
+ /** Locale key of a URL prefix: the inverse of `localePrefix()`. */
99
+ export function localeKeyOf(prefix: string): string {
100
+ return prefix ? prefix.slice(1) : ROOT_LOCALE
53
101
  }
package/src/pages.ts CHANGED
@@ -3,9 +3,9 @@ import type { ResolvedOpenApiOptions } from './options'
3
3
  import type { PageContext } from './render/pages'
4
4
  import type { LoadedApi, OpenApiService } from './service'
5
5
  import { join } from 'node:path'
6
- import { localePrefix } from './options'
6
+ import { localePrefix, ROOT_LOCALE, sourceOf } from './options'
7
7
  import { labelsForLanguage } from './render/labels'
8
- import { renderChangesPage, renderJourneyPage, renderModelPage, renderOperationPage, renderOverviewPage, renderResourcePage } from './render/pages'
8
+ import { renderChangesPage, renderJourneyPage, renderJourneysPage, renderModelPage, renderModelsPage, renderOperationPage, renderOverviewPage, renderResourcePage } from './render/pages'
9
9
  import { createOpenApiLinks, modelSlug } from './render/routes'
10
10
  import { SNAPSHOT_PATTERN } from './service'
11
11
  import { diffSnapshots, sortSnapshots } from './snapshot/history'
@@ -22,8 +22,13 @@ export interface OpenApiPagesDeps {
22
22
  warn: (message: string) => void
23
23
  }
24
24
 
25
- /** The page of the changes group; its parameter lets the group produce no page at all. */
25
+ /**
26
+ * Fixed pages registered under a parameter, so their group can produce no
27
+ * page at all when there is nothing to show.
28
+ */
26
29
  const CHANGES_PAGE = 'changes'
30
+ const JOURNEYS_PAGE = 'journeys'
31
+ const MODELS_PAGE = 'models'
27
32
 
28
33
  /**
29
34
  * Registers the pages of every locale: resource map, resources, operations,
@@ -43,12 +48,18 @@ export function registerOpenApiPages(api: GeneratorPluginAPI, deps: OpenApiPages
43
48
 
44
49
  const prepare = async (context: PluginPagesContext): Promise<{ loaded: LoadedApi, page: PageContext }> => {
45
50
  const options = deps.options()
46
- await Promise.all([options.spec, ...options.workflows].map(file => context.read(file)))
51
+ const source = sourceOf(options, key)
52
+ await Promise.all([source.spec, ...source.workflows].map(file => context.read(file)))
47
53
  await context.glob(join(options.snapshotDir, SNAPSHOT_PATTERN))
48
- const loaded = await deps.service.get()
54
+ const loaded = await deps.service.get(key)
49
55
  if (!reported.has(loaded)) {
50
56
  reported.add(loaded)
51
- report(loaded, deps.warn)
57
+ if (source === sourceOf(options, ROOT_LOCALE)) {
58
+ report(loaded, deps.warn)
59
+ }
60
+ else {
61
+ reportDrift(key, loaded, await deps.service.get(ROOT_LOCALE), deps.warn)
62
+ }
52
63
  }
53
64
  return { loaded, page: { labels, links: createOpenApiLinks(loaded.model, prefix, deps.route) } }
54
65
  }
@@ -70,6 +81,14 @@ export function registerOpenApiPages(api: GeneratorPluginAPI, deps: OpenApiPages
70
81
  ...renderOperationPage(operation, page),
71
82
  }))
72
83
  })
84
+ register(`${base}[models]/`, async (context) => {
85
+ const { loaded, page } = await prepare(context)
86
+ return loaded.model.schemas.length ? [{ models: MODELS_PAGE, ...renderModelsPage(loaded.model, page) }] : []
87
+ })
88
+ register(`${base}[journeys]/`, async (context) => {
89
+ const { loaded, page } = await prepare(context)
90
+ return loaded.model.workflows.length ? [{ journeys: JOURNEYS_PAGE, ...renderJourneysPage(loaded.model, page) }] : []
91
+ })
73
92
  register(`${base}models/[model]`, async (context) => {
74
93
  const { loaded, page } = await prepare(context)
75
94
  return loaded.model.schemas.map(entry => ({ model: modelSlug(entry.name), ...renderModelPage(entry, loaded.model, page) }))
@@ -118,3 +137,12 @@ function report(loaded: LoadedApi, warn: (message: string) => void): void {
118
137
  warn(`the spec differs from its own snapshot ${latest.version} in ${changes.length} places; bump info.version or run \`kawapress-openapi snapshot --force\`.`)
119
138
  }
120
139
  }
140
+
141
+ /** A locale's own spec should translate the root one; say where their shapes differ. */
142
+ function reportDrift(key: string, loaded: LoadedApi, root: LoadedApi, warn: (message: string) => void): void {
143
+ const changes = diffSnapshots(createSnapshot(root.model), createSnapshot(loaded.model))
144
+ if (changes.length > 0) {
145
+ const shown = changes.slice(0, 3).map(change => [change.operation, change.subject].filter(Boolean).join(' ')).join('; ')
146
+ warn(`the spec of the locale "${key}" differs in shape from the root one in ${changes.length} places (${shown}${changes.length > 3 ? '; …' : ''}); per-locale specs should only translate the prose.`)
147
+ }
148
+ }
@@ -74,6 +74,7 @@ export function readArazzo(document: Json, file: string, model: OpenApiModel): O
74
74
  name,
75
75
  type: isObject(schema) ? asString(schema.type) || 'any' : 'any',
76
76
  description: isObject(schema) ? asString(schema.description) : '',
77
+ ...(isObject(schema) && (schema.default !== undefined || schema.example !== undefined) ? { example: schema.default ?? schema.example } : {}),
77
78
  })),
78
79
  steps,
79
80
  }
@@ -3,6 +3,53 @@ import type { OpenApiAction, OpenApiParameter } from '../types'
3
3
 
4
4
  /** Fixed texts of the pages and components, in the language of a locale. */
5
5
  export interface OpenApiLabels {
6
+ /** The interactive journey. `{n}`, `{total}`, `{names}`, `{steps}`, `{name}`, `{title}` are filled in by the page. */
7
+ journey: {
8
+ sendStep: string
9
+ runAll: string
10
+ reset: string
11
+ progress: string
12
+ allDone: string
13
+ values: string
14
+ input: string
15
+ waiting: string
16
+ fromResponse: string
17
+ calls: string
18
+ client: string
19
+ server: string
20
+ noCalls: string
21
+ request: string
22
+ response: string
23
+ notSent: string
24
+ sendThis: string
25
+ sendAgain: string
26
+ tryAhead: string
27
+ receive: string
28
+ show: string
29
+ hide: string
30
+ openEarly: string
31
+ waitEarlier: string
32
+ missing: string
33
+ stepRef: string
34
+ /** Joins names in a list. */
35
+ separator: string
36
+ invalid: string
37
+ noExample: string
38
+ inputsChanged: string
39
+ missingValue: string
40
+ noBody: string
41
+ noResponse: string
42
+ finished: string
43
+ summary: string
44
+ code: string
45
+ copy: string
46
+ copied: string
47
+ copyFailed: string
48
+ fromStep: string
49
+ fromInput: string
50
+ waitWebhook: string
51
+ step: string
52
+ }
6
53
  overview: string
7
54
  resources: string
8
55
  journeys: string
@@ -52,11 +99,6 @@ export interface OpenApiLabels {
52
99
  getLabel: string
53
100
  fromStep: (step: number, output: string) => string
54
101
  fromInput: (name: string) => string
55
- runJourney: string
56
- runAgain: string
57
- pending: string
58
- running: string
59
- done: string
60
102
  inputs: string
61
103
  source: string
62
104
  steps: string
@@ -86,6 +128,51 @@ export interface ValidationMessages {
86
128
  }
87
129
 
88
130
  const zh: OpenApiLabels = {
131
+ journey: {
132
+ sendStep: '发送第 {n} 步',
133
+ runAll: '一口气跑完',
134
+ reset: '重来',
135
+ progress: '已完成 {n} / {total}',
136
+ allDone: '全部完成',
137
+ values: '你手里的值',
138
+ input: '输入',
139
+ waiting: '等第 {n} 步返回',
140
+ fromResponse: '第 {n} 步的响应 · {pointer}',
141
+ calls: '调用记录',
142
+ client: '你的服务',
143
+ server: 'API',
144
+ noCalls: '还没有发出请求',
145
+ request: '请求',
146
+ response: '响应',
147
+ notSent: '还没发送',
148
+ sendThis: '发送这一步',
149
+ sendAgain: '再发一次',
150
+ tryAhead: '跳过去试试',
151
+ receive: '模拟收到',
152
+ show: '看这一步的请求和响应',
153
+ hide: '收起',
154
+ openEarly: '提前展开',
155
+ waitEarlier: '等前面的步骤完成,也可以',
156
+ missing: '缺少 {names},要等{steps}发送后才有。这就是这几步必须按顺序走的原因。',
157
+ stepRef: '第 {n} 步',
158
+ separator: '、',
159
+ invalid: '请求没有通过 schema 校验:',
160
+ noExample: '规格里没有写这个错误的示例。',
161
+ inputsChanged: '输入改了。点「一口气跑完」用新输入重放。',
162
+ missingValue: '还没有',
163
+ noBody: '没有请求体',
164
+ noResponse: '没有响应体',
165
+ finished: '跑通了',
166
+ summary: '{calls} 次调用,在步骤之间传递了 {values} 个值。',
167
+ code: '整个流程的代码',
168
+ copy: '复制代码',
169
+ copied: '已复制',
170
+ copyFailed: '复制失败',
171
+ fromStep: '{name} 来自第 {n} 步',
172
+ fromInput: '{name} 来自输入',
173
+ waitWebhook: '等待 Webhook:{name}',
174
+ step: '第 {n} 步:{title}',
175
+ },
89
176
  overview: 'API 总览',
90
177
  resources: '资源',
91
178
  journeys: '旅程',
@@ -135,11 +222,6 @@ const zh: OpenApiLabels = {
135
222
  getLabel: '得到',
136
223
  fromStep: (step, output) => `← 第 ${step} 步的 ${output}`,
137
224
  fromInput: name => `← 输入 ${name}`,
138
- runJourney: '在 Mock 中跑通',
139
- runAgain: '再跑一次',
140
- pending: '未运行',
141
- running: '运行中…',
142
- done: '完成',
143
225
  inputs: '输入',
144
226
  source: '来源',
145
227
  steps: '步骤',
@@ -180,6 +262,51 @@ const zh: OpenApiLabels = {
180
262
  }
181
263
 
182
264
  const en: OpenApiLabels = {
265
+ journey: {
266
+ sendStep: 'Send step {n}',
267
+ runAll: 'Run all steps',
268
+ reset: 'Start over',
269
+ progress: '{n} of {total} done',
270
+ allDone: 'All done',
271
+ values: 'Values in hand',
272
+ input: 'input',
273
+ waiting: 'From step {n}',
274
+ fromResponse: 'Step {n} response · {pointer}',
275
+ calls: 'Calls',
276
+ client: 'Your app',
277
+ server: 'API',
278
+ noCalls: 'No requests yet',
279
+ request: 'Request',
280
+ response: 'Response',
281
+ notSent: 'not sent yet',
282
+ sendThis: 'Send this step',
283
+ sendAgain: 'Send again',
284
+ tryAhead: 'Try it now',
285
+ receive: 'Simulate delivery',
286
+ show: 'Show request and response',
287
+ hide: 'Hide',
288
+ openEarly: 'open it now',
289
+ waitEarlier: 'Waits for the earlier steps, or',
290
+ missing: 'Missing {names}, which only exists after {steps}. That is why these steps run in this order.',
291
+ stepRef: 'step {n}',
292
+ separator: ', ',
293
+ invalid: 'The request does not match the schema:',
294
+ noExample: 'The spec has no example of this error.',
295
+ inputsChanged: 'Inputs changed. Run all steps to replay with them.',
296
+ missingValue: 'not yet',
297
+ noBody: 'No request body',
298
+ noResponse: 'No response body',
299
+ finished: 'It works',
300
+ summary: '{calls} calls, {values} values passed between steps.',
301
+ code: 'The whole flow as code',
302
+ copy: 'Copy',
303
+ copied: 'Copied',
304
+ copyFailed: 'Copy failed',
305
+ fromStep: '{name} from step {n}',
306
+ fromInput: '{name} from the inputs',
307
+ waitWebhook: 'Wait for the webhook: {name}',
308
+ step: 'Step {n}: {title}',
309
+ },
183
310
  overview: 'API overview',
184
311
  resources: 'Resources',
185
312
  journeys: 'Journeys',
@@ -229,11 +356,6 @@ const en: OpenApiLabels = {
229
356
  getLabel: 'Get',
230
357
  fromStep: (step, output) => `← ${output} from step ${step}`,
231
358
  fromInput: name => `← input ${name}`,
232
- runJourney: 'Run with mocks',
233
- runAgain: 'Run again',
234
- pending: 'Not run',
235
- running: 'Running…',
236
- done: 'Done',
237
359
  inputs: 'Inputs',
238
360
  source: 'Source',
239
361
  steps: 'Steps',
@@ -43,14 +43,10 @@ export function renderOverviewPage(api: LoadedApi, { labels, links }: PageContex
43
43
  sections.push(facts.join(' · '))
44
44
  sections.push(`## ${labels.resources}`, tag('map'))
45
45
  if (model.workflows.length) {
46
- sections.push(`## ${labels.journeys}`, model.workflows.map(workflow => (
47
- `- [${workflow.summary || workflow.id}](${links.journey(workflow.id)})${workflow.description ? ` — ${inline(firstLine(workflow.description))}` : ''}`
48
- )).join('\n'))
46
+ sections.push(`## ${labels.journeys}`, journeyList(model, links))
49
47
  }
50
48
  if (model.schemas.length) {
51
- sections.push(`## ${labels.models}`, model.schemas.map(entry => (
52
- `- [\`${entry.name}\`](${links.model(entry.name)})${entry.schema.description ? ` — ${inline(firstLine(entry.schema.description))}` : ''}`
53
- )).join('\n'))
49
+ sections.push(`## ${labels.models}`, modelList(model, links))
54
50
  }
55
51
  if (api.snapshots.length > 1) {
56
52
  sections.push(`[${labels.changes}](${links.changes})`)
@@ -64,6 +60,34 @@ export function renderOverviewPage(api: LoadedApi, { labels, links }: PageContex
64
60
  }
65
61
  }
66
62
 
63
+ /** Index of the journeys folder, which also names that folder in the sidebar. */
64
+ export function renderJourneysPage(model: OpenApiModel, { labels, links }: PageContext): PluginPageContent {
65
+ return {
66
+ markdown: `# ${labels.journeys}\n\n${journeyList(model, links)}\n`,
67
+ frontmatter: { title: labels.journeys },
68
+ }
69
+ }
70
+
71
+ /** Index of the models folder, which also names that folder in the sidebar. */
72
+ export function renderModelsPage(model: OpenApiModel, { labels, links }: PageContext): PluginPageContent {
73
+ return {
74
+ markdown: `# ${labels.models}\n\n${modelList(model, links)}\n`,
75
+ frontmatter: { title: labels.models },
76
+ }
77
+ }
78
+
79
+ function journeyList(model: OpenApiModel, links: OpenApiLinks): string {
80
+ return model.workflows.map(workflow => (
81
+ `- [${workflow.summary || workflow.id}](${links.journey(workflow.id)})${workflow.description ? ` — ${inline(firstLine(workflow.description))}` : ''}`
82
+ )).join('\n')
83
+ }
84
+
85
+ function modelList(model: OpenApiModel, links: OpenApiLinks): string {
86
+ return model.schemas.map(entry => (
87
+ `- [\`${entry.name}\`](${links.model(entry.name)})${entry.schema.description ? ` — ${inline(firstLine(entry.schema.description))}` : ''}`
88
+ )).join('\n')
89
+ }
90
+
67
91
  /** One resource: its description, then a line per operation. */
68
92
  export function renderResourcePage(resource: OpenApiResource, model: OpenApiModel, { labels, links }: PageContext): PluginPageContent {
69
93
  const sections = [`# ${resource.name}`]
package/src/service.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ResolvedOpenApiOptions } from './options'
1
+ import type { OpenApiSource, ResolvedOpenApiOptions } from './options'
2
2
  import type { OpenApiSnapshot } from './snapshot/snapshot'
3
3
  import type { OpenApiModel } from './types'
4
4
  import { existsSync, statSync } from 'node:fs'
@@ -6,6 +6,7 @@ import { readFile } from 'node:fs/promises'
6
6
  import { join } from 'node:path'
7
7
  import { glob } from 'tinyglobby'
8
8
  import { normalizePath } from 'vite'
9
+ import { allSources, ROOT_LOCALE, sourceOf } from './options'
9
10
  import { readArazzo } from './read/arazzo'
10
11
  import { parseDocument } from './read/document'
11
12
  import { readOpenApi } from './read/model'
@@ -25,51 +26,78 @@ export interface LoadedApi {
25
26
  export const SNAPSHOT_PATTERN = '*.json'
26
27
 
27
28
  /**
28
- * Reads and caches the API: one parse per change of the spec, the workflow
29
- * files or the snapshots, shared by every page group and component.
29
+ * Reads and caches the API of each locale's source: one parse per change of
30
+ * its spec, its workflow files or the snapshots, shared by every page group
31
+ * and component of the locales that read that source.
30
32
  */
31
33
  export class OpenApiService {
32
- private cached: { key: string, api: LoadedApi } | undefined
33
- private pending: { key: string, promise: Promise<LoadedApi> } | undefined
34
+ private caches = new Map<string, SourceCache>()
34
35
 
35
36
  constructor(private options: () => ResolvedOpenApiOptions) {}
36
37
 
37
- /** The latest successful result, without reading anything. */
38
- peek(): LoadedApi | undefined {
39
- return this.cached?.api
38
+ /** The latest successful result of a locale, without reading anything. */
39
+ peek(locale: string = ROOT_LOCALE): LoadedApi | undefined {
40
+ return this.cacheOf(locale).cached?.api
40
41
  }
41
42
 
42
- /** Files whose change means the data is stale. */
43
+ /** Files whose change means the data of some locale is stale. */
43
44
  watchedFiles(): Set<string> {
44
- const options = this.options()
45
- return new Set([options.spec, ...options.workflows, ...(this.cached?.api.snapshotFiles ?? [])].map(file => normalizePath(file)))
45
+ const files = allSources(this.options()).flatMap(source => [
46
+ source.spec,
47
+ ...source.workflows,
48
+ ...(this.caches.get(sourceKey(source))?.cached?.api.snapshotFiles ?? []),
49
+ ])
50
+ return new Set(files.map(file => normalizePath(file)))
46
51
  }
47
52
 
48
- async get(): Promise<LoadedApi> {
53
+ async get(locale: string = ROOT_LOCALE): Promise<LoadedApi> {
49
54
  const options = this.options()
55
+ const source = sourceOf(options, locale)
50
56
  const snapshotFiles = existsSync(options.snapshotDir)
51
57
  ? (await glob(SNAPSHOT_PATTERN, { cwd: options.snapshotDir, absolute: true })).sort()
52
58
  : []
53
- const files = [options.spec, ...options.workflows, ...snapshotFiles]
59
+ const files = [source.spec, ...source.workflows, ...snapshotFiles]
54
60
  const key = files.map(file => `${file}:${stamp(file)}`).join('|')
55
- if (this.cached?.key === key) {
56
- return this.cached.api
61
+ const cache = this.cacheOf(locale)
62
+ if (cache.cached?.key === key) {
63
+ return cache.cached.api
57
64
  }
58
- if (this.pending?.key !== key) {
59
- const promise = load(options, snapshotFiles).then((api) => {
60
- this.cached = { key, api }
65
+ if (cache.pending?.key !== key) {
66
+ const promise = load(source, snapshotFiles).then((api) => {
67
+ cache.cached = { key, api }
61
68
  return api
62
69
  }).finally(() => {
63
- if (this.pending?.promise === promise) {
64
- this.pending = undefined
70
+ if (cache.pending?.promise === promise) {
71
+ cache.pending = undefined
65
72
  }
66
73
  })
67
- this.pending = { key, promise }
74
+ cache.pending = { key, promise }
75
+ }
76
+ return cache.pending!.promise
77
+ }
78
+
79
+ /** Locales that read the same spec and workflow files share one cache. */
80
+ private cacheOf(locale: string): SourceCache {
81
+ const key = sourceKey(sourceOf(this.options(), locale))
82
+ let cache = this.caches.get(key)
83
+ if (!cache) {
84
+ cache = {}
85
+ this.caches.set(key, cache)
68
86
  }
69
- return this.pending!.promise
87
+ return cache
70
88
  }
71
89
  }
72
90
 
91
+ /** Identity of a source: a locale may share the spec of `root` but read its own workflows. */
92
+ function sourceKey(source: OpenApiSource): string {
93
+ return [source.spec, ...source.workflows].join('\0')
94
+ }
95
+
96
+ interface SourceCache {
97
+ cached?: { key: string, api: LoadedApi }
98
+ pending?: { key: string, promise: Promise<LoadedApi> }
99
+ }
100
+
73
101
  function stamp(file: string): string {
74
102
  try {
75
103
  const stats = statSync(file)
@@ -80,9 +108,9 @@ function stamp(file: string): string {
80
108
  }
81
109
  }
82
110
 
83
- async function load(options: ResolvedOpenApiOptions, snapshotFiles: string[]): Promise<LoadedApi> {
84
- const model = readOpenApi(parseDocument(await readText(options.spec, 'spec'), options.spec), options.spec)
85
- for (const file of options.workflows) {
111
+ async function load(source: OpenApiSource, snapshotFiles: string[]): Promise<LoadedApi> {
112
+ const model = readOpenApi(parseDocument(await readText(source.spec, 'spec'), source.spec), source.spec)
113
+ for (const file of source.workflows) {
86
114
  model.workflows.push(...readArazzo(parseDocument(await readText(file, 'workflows'), file), file, model))
87
115
  model.sourceFiles.push(file)
88
116
  }
package/src/types.ts CHANGED
@@ -1,11 +1,22 @@
1
1
  /** Languages of the code samples. */
2
2
  export type OpenApiSampleLanguage = 'curl' | 'javascript' | 'python'
3
3
 
4
+ /**
5
+ * One value for every locale, or one per locale key such as
6
+ * `{ root: './api.zh.yaml', en: './api.yaml' }`. Locales without their own
7
+ * entry use the `root` one.
8
+ */
9
+ export type OpenApiPerLocale<T> = T | Record<string, T>
10
+
4
11
  export interface OpenApiPluginOptions {
5
- /** OpenAPI 3.0 or 3.1 document, JSON or YAML, relative to the site root. */
6
- spec: string
12
+ /**
13
+ * OpenAPI 3.0 or 3.1 document, JSON or YAML, relative to the site root.
14
+ * Per locale, the documents are translations of one API: the same
15
+ * operations, schemas and fields, in different prose.
16
+ */
17
+ spec: OpenApiPerLocale<string>
7
18
  /** Arazzo 1.x workflow files, relative to the site root. */
8
- workflows?: string | string[]
19
+ workflows?: OpenApiPerLocale<string | string[]>
9
20
  /** Where the pages are mounted, `openapi/` by default. Every locale gets its own copy under its prefix. */
10
21
  route?: string
11
22
  /** Only generate pages for these locale keys; all by default. */
@@ -186,7 +197,7 @@ export interface OpenApiWorkflow {
186
197
  description: string
187
198
  /** Absolute path of the Arazzo file. */
188
199
  file: string
189
- inputs: { name: string, type: string, description: string }[]
200
+ inputs: { name: string, type: string, description: string, example?: unknown }[]
190
201
  steps: WorkflowStep[]
191
202
  }
192
203
 
package/src/vite.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  createSchemaTable,
20
20
  } from './data/components'
21
21
  import { escapeHtml } from './data/text'
22
+ import { localeKeyOf, sourceOf } from './options'
22
23
  import { labelsForLanguage } from './render/labels'
23
24
  import { createOpenApiLinks, withBaseLinks } from './render/routes'
24
25
  import { COMPONENT_MODULE } from './tag'
@@ -29,8 +30,8 @@ export interface OpenApiVitePluginOptions {
29
30
  /** Site base, for links in the HTML. */
30
31
  base: () => string
31
32
  markdown: () => MarkdownExit | undefined
32
- /** The `lang` of the locale whose pages have the given URL prefix. */
33
- languageOf: (prefix: string) => string | undefined
33
+ /** The `lang` of a locale key. */
34
+ languageOf: (locale: string) => string | undefined
34
35
  /** Absolute path of the module that default-exports the component of a kind. */
35
36
  component: (kind: string) => string
36
37
  }
@@ -68,14 +69,15 @@ export function createOpenApiVitePlugin(config: OpenApiVitePluginOptions): Plugi
68
69
  for (const file of service.watchedFiles()) {
69
70
  this.addWatchFile(file)
70
71
  }
71
- const api = await service.get()
72
+ const locale = localeKeyOf(prefix)
73
+ const api = await service.get(locale)
72
74
  const options = config.options()
73
75
  const pageLinks = createOpenApiLinks(api.model, prefix, options.route)
74
76
  const markdown = config.markdown()
75
77
  const context: DataContext = {
76
78
  api,
77
79
  schemas: createSchemaTable(api),
78
- labels: labelsForLanguage(config.languageOf(prefix)),
80
+ labels: labelsForLanguage(config.languageOf(locale)),
79
81
  pageLinks,
80
82
  links: withBaseLinks(pageLinks, path => withBase(path, config.base())),
81
83
  highlight: async (code, lang) => (await markdown?.options.highlight?.(code, lang, '', {})) || `<pre><code>${escapeHtml(code)}</code></pre>`,
@@ -85,7 +87,7 @@ export function createOpenApiVitePlugin(config: OpenApiVitePluginOptions): Plugi
85
87
  const operationOf = (attribute: string) => {
86
88
  const name = query.get(attribute) ?? ''
87
89
  const operation = api.model.operations.find(item => item.id === name)
88
- return operation ?? fail(`there is no operation "${name}" in ${options.spec}. Known operations: ${api.model.operations.slice(0, 8).map(item => item.id).join(', ')}${api.model.operations.length > 8 ? ', …' : ''}.`)
90
+ return operation ?? fail(`there is no operation "${name}" in ${sourceOf(options, locale).spec}. Known operations: ${api.model.operations.slice(0, 8).map(item => item.id).join(', ')}${api.model.operations.length > 8 ? ', …' : ''}.`)
89
91
  }
90
92
 
91
93
  let data: unknown