@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.
@@ -0,0 +1,401 @@
1
+ /**
2
+ * The browser side of a journey: evaluates step templates against the values
3
+ * collected so far, renders JSON with marked values, and writes the whole flow
4
+ * as code. Pure functions, no Vue, so the server and the tests can use them.
5
+ */
6
+
7
+ /** The key under which a payload template keeps a runtime expression. */
8
+ export const EXPRESSION_KEY = '$kawa'
9
+
10
+ export type JourneyExpression
11
+ = | { kind: 'literal', value: unknown }
12
+ | { kind: 'input', name: string }
13
+ | { kind: 'output', step: string, output: string }
14
+
15
+ /** What a template position holds once evaluated. */
16
+ export interface Slot {
17
+ /** `input:<name>` or `<step>.<output>`. */
18
+ key: string
19
+ /** Display name: the input or output name. */
20
+ name: string
21
+ value: unknown
22
+ missing: boolean
23
+ }
24
+
25
+ export interface Token {
26
+ text: string
27
+ /** `key`, `string`, `number`, `literal`, `punct`, or a slot class. */
28
+ kind: string
29
+ slot?: string
30
+ /** Colour index of an output slot or an outlined response value. */
31
+ mark?: number
32
+ }
33
+
34
+ export type Line = Token[]
35
+
36
+ export interface Values {
37
+ inputs: Record<string, unknown>
38
+ /** `<step>.<output>` → value. */
39
+ outputs: Record<string, unknown>
40
+ }
41
+
42
+ export function slotKey(expression: JourneyExpression): string {
43
+ return expression.kind === 'input' ? `input:${expression.name}` : expression.kind === 'output' ? `${expression.step}.${expression.output}` : ''
44
+ }
45
+
46
+ export function isExpression(value: unknown): value is { [EXPRESSION_KEY]: JourneyExpression } {
47
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
48
+ && Object.keys(value).length === 1 && typeof (value as Record<string, unknown>)[EXPRESSION_KEY] === 'object'
49
+ }
50
+
51
+ export function resolve(expression: JourneyExpression, values: Values): Slot {
52
+ if (expression.kind === 'literal') {
53
+ return { key: '', name: '', value: expression.value, missing: false }
54
+ }
55
+ const key = slotKey(expression)
56
+ const value = expression.kind === 'input' ? values.inputs[expression.name] : values.outputs[key]
57
+ return { key, name: expression.kind === 'input' ? expression.name : expression.output, value, missing: value === undefined }
58
+ }
59
+
60
+ /** The template with every expression replaced by its value; missing values stay `undefined`. */
61
+ export function evaluate(template: unknown, values: Values, missing: Set<string> = new Set()): unknown {
62
+ if (isExpression(template)) {
63
+ const slot = resolve(template[EXPRESSION_KEY], values)
64
+ if (slot.missing) {
65
+ missing.add(slot.key)
66
+ }
67
+ return slot.value
68
+ }
69
+ if (Array.isArray(template)) {
70
+ return template.map(item => evaluate(item, values, missing))
71
+ }
72
+ if (typeof template === 'object' && template !== null) {
73
+ return Object.fromEntries(Object.entries(template).map(([key, item]) => [key, evaluate(item, values, missing)]))
74
+ }
75
+ return template
76
+ }
77
+
78
+ export function readPointer(root: unknown, pointer: string): unknown {
79
+ let current = root
80
+ for (const raw of pointer.replace(/^\//, '').split('/').filter((_, index, all) => all.length > 1 || all[0] !== '')) {
81
+ const key = raw.replaceAll('~1', '/').replaceAll('~0', '~')
82
+ if (Array.isArray(current)) {
83
+ current = current[Number(key)]
84
+ }
85
+ else if (typeof current === 'object' && current !== null) {
86
+ current = (current as Record<string, unknown>)[key]
87
+ }
88
+ else {
89
+ return undefined
90
+ }
91
+ }
92
+ return current
93
+ }
94
+
95
+ /** The example response with the request's top-level fields copied over the fields of the same name. */
96
+ export function mockResponse(example: unknown, request: unknown): unknown {
97
+ const copy = example === undefined ? undefined : JSON.parse(JSON.stringify(example)) as unknown
98
+ if (isRecord(copy) && isRecord(request)) {
99
+ for (const [key, value] of Object.entries(request)) {
100
+ if (key in copy && value !== undefined && typeof value !== 'object') {
101
+ copy[key] = value
102
+ }
103
+ }
104
+ }
105
+ return copy
106
+ }
107
+
108
+ /* ------------------------------------------------------------------ render */
109
+
110
+ interface RenderOptions {
111
+ values: Values
112
+ /** Slot key → colour index. */
113
+ marks: Record<string, number>
114
+ /** JSON pointer → colour index, for response values to outline. */
115
+ outlines?: Record<string, number>
116
+ }
117
+
118
+ /** A request template as lines of tokens; expressions become slot tokens. */
119
+ export function templateLines(template: unknown, options: RenderOptions): Line[] {
120
+ const lines: Line[] = [[]]
121
+ write(template, '', 0, lines, options, true)
122
+ return lines
123
+ }
124
+
125
+ /** A response value as lines of tokens; outlined pointers are marked. */
126
+ export function valueLines(value: unknown, options: RenderOptions): Line[] {
127
+ const lines: Line[] = [[]]
128
+ write(value, '', 0, lines, options, false)
129
+ return lines
130
+ }
131
+
132
+ function write(value: unknown, pointer: string, depth: number, lines: Line[], options: RenderOptions, template: boolean): void {
133
+ const line = lines.at(-1)!
134
+ if (template && isExpression(value)) {
135
+ const slot = resolve(value[EXPRESSION_KEY], options.values)
136
+ if (!slot.key) {
137
+ write(slot.value, pointer, depth, lines, options, false)
138
+ return
139
+ }
140
+ line.push({
141
+ text: slot.missing ? slot.name : JSON.stringify(slot.value),
142
+ kind: slot.missing ? 'missing' : slot.key.startsWith('input:') ? 'input' : 'output',
143
+ slot: slot.key,
144
+ ...(options.marks[slot.key] !== undefined ? { mark: options.marks[slot.key] } : {}),
145
+ })
146
+ return
147
+ }
148
+ const outline = options.outlines?.[pointer]
149
+ const push = (token: Token): void => {
150
+ line.push(outline === undefined ? token : { ...token, mark: outline, kind: `${token.kind} outlined` })
151
+ }
152
+ if (Array.isArray(value) || isRecord(value)) {
153
+ const entries: [string | undefined, unknown][] = Array.isArray(value) ? value.map(item => [undefined, item]) : Object.entries(value)
154
+ const [open, close] = Array.isArray(value) ? ['[', ']'] : ['{', '}']
155
+ if (!entries.length) {
156
+ push({ text: `${open}${close}`, kind: 'punct' })
157
+ return
158
+ }
159
+ push({ text: open, kind: 'punct' })
160
+ entries.forEach(([key, item], index) => {
161
+ const next: Line = [{ text: ' '.repeat(depth + 1), kind: 'punct' }]
162
+ lines.push(next)
163
+ const childPointer = `${pointer}/${key === undefined ? index : key.replaceAll('~', '~0').replaceAll('/', '~1')}`
164
+ const childOutline = options.outlines?.[childPointer]
165
+ if (key !== undefined) {
166
+ next.push(childOutline === undefined ? { text: JSON.stringify(key), kind: 'key' } : { text: JSON.stringify(key), kind: 'key outlined', mark: childOutline })
167
+ next.push({ text: ': ', kind: 'punct' })
168
+ }
169
+ write(item, childPointer, depth + 1, lines, options, template)
170
+ if (index < entries.length - 1) {
171
+ lines.at(-1)!.push({ text: ',', kind: 'punct' })
172
+ }
173
+ })
174
+ lines.push([{ text: `${' '.repeat(depth)}${close}`, kind: 'punct' }])
175
+ return
176
+ }
177
+ push({ text: JSON.stringify(value) ?? 'undefined', kind: typeof value === 'string' ? 'string' : typeof value === 'number' ? 'number' : 'literal' })
178
+ }
179
+
180
+ /* -------------------------------------------------------------------- code */
181
+
182
+ export interface CodeStep {
183
+ id: string
184
+ method: string
185
+ path: string
186
+ webhook: boolean
187
+ auth: boolean
188
+ parameters: { name: string, in: string, value: JourneyExpression }[]
189
+ body?: unknown
190
+ outputs: { key: string, name: string, pointer: string }[]
191
+ }
192
+
193
+ export interface CodeInput {
194
+ name: string
195
+ value: unknown
196
+ }
197
+
198
+ /** Variable names for the slots: the input or output name, made unique. */
199
+ export function variableNames(inputs: CodeInput[], steps: CodeStep[]): Record<string, string> {
200
+ const names: Record<string, string> = {}
201
+ const used = new Set<string>(['TOKEN', 'API'])
202
+ const claim = (key: string, wanted: string, fallback: string): void => {
203
+ let name = identifier(wanted)
204
+ if (used.has(name)) {
205
+ name = identifier(fallback)
206
+ }
207
+ while (used.has(name)) {
208
+ name = `${name}_`
209
+ }
210
+ used.add(name)
211
+ names[key] = name
212
+ }
213
+ for (const input of inputs) {
214
+ claim(`input:${input.name}`, input.name, `input_${input.name}`)
215
+ }
216
+ for (const step of steps) {
217
+ for (const output of step.outputs) {
218
+ claim(output.key, output.name, `${step.id}_${output.name}`)
219
+ }
220
+ }
221
+ return names
222
+ }
223
+
224
+ function identifier(name: string): string {
225
+ const cleaned = name.replaceAll(/\W/g, '_')
226
+ return /^\d/.test(cleaned) ? `_${cleaned}` : cleaned
227
+ }
228
+
229
+ /** The whole flow as a shell script with curl and jq. */
230
+ export function curlScript(base: string, inputs: CodeInput[], steps: CodeStep[], comment: (step: CodeStep, index: number) => string): string {
231
+ const names = variableNames(inputs, steps)
232
+ const lines = [`API=${shellQuote(base)}`, 'TOKEN=...']
233
+ for (const input of inputs) {
234
+ lines.push(`${names[`input:${input.name}`]}=${shellQuote(typeof input.value === 'string' ? input.value : JSON.stringify(input.value ?? ''))}`)
235
+ }
236
+ steps.forEach((step, index) => {
237
+ lines.push('', `# ${comment(step, index)}`)
238
+ if (step.webhook) {
239
+ return
240
+ }
241
+ const ref = (expression: JourneyExpression): string => expression.kind === 'literal' ? String(expression.value) : `$${names[slotKey(expression)]}`
242
+ const url = `$API${fillPath(step, ref)}${queryOf(step, ref)}`
243
+ const parts = [`curl -s -X ${step.method} "${url}"`]
244
+ if (step.auth) {
245
+ parts.push('-H "Authorization: Bearer $TOKEN"')
246
+ }
247
+ for (const parameter of step.parameters.filter(item => item.in === 'header')) {
248
+ parts.push(`-H "${parameter.name}: ${ref(parameter.value)}"`)
249
+ }
250
+ if (step.body !== undefined) {
251
+ parts.push('-H "Content-Type: application/json"', `-d '${shellJson(step.body, names)}'`)
252
+ }
253
+ const call = parts.join(' \\\n ')
254
+ if (step.outputs.length === 1) {
255
+ lines.push(`${names[step.outputs[0].key]}=$(${call} | jq -r '${jqPath(step.outputs[0].pointer)}')`)
256
+ }
257
+ else if (step.outputs.length > 1) {
258
+ const response = `${identifier(step.id)}_response`
259
+ lines.push(`${response}=$(${call})`)
260
+ for (const output of step.outputs) {
261
+ lines.push(`${names[output.key]}=$(echo "$${response}" | jq -r '${jqPath(output.pointer)}')`)
262
+ }
263
+ }
264
+ else {
265
+ lines.push(call)
266
+ }
267
+ })
268
+ return lines.join('\n')
269
+ }
270
+
271
+ /** The whole flow as JavaScript with fetch. */
272
+ export function javascriptScript(base: string, inputs: CodeInput[], steps: CodeStep[], comment: (step: CodeStep, index: number) => string): string {
273
+ const names = variableNames(inputs, steps)
274
+ const lines = [
275
+ `const API = ${JSON.stringify(base)}`,
276
+ 'const TOKEN = process.env.TOKEN',
277
+ '',
278
+ 'async function call(method, path, body, headers = {}) {',
279
+ ' const response = await fetch(API + path, {',
280
+ ' method,',
281
+ // eslint-disable-next-line no-template-curly-in-string
282
+ ' headers: { Authorization: `Bearer ${TOKEN}`, \'Content-Type\': \'application/json\', ...headers },',
283
+ ' body: body === undefined ? undefined : JSON.stringify(body),',
284
+ ' })',
285
+ // eslint-disable-next-line no-template-curly-in-string
286
+ ' if (!response.ok) throw new Error(`${method} ${path}: ${response.status}`)',
287
+ ' return response.status === 204 ? undefined : response.json()',
288
+ '}',
289
+ '',
290
+ ]
291
+ for (const input of inputs) {
292
+ lines.push(`const ${names[`input:${input.name}`]} = ${JSON.stringify(input.value ?? '')}`)
293
+ }
294
+ steps.forEach((step, index) => {
295
+ lines.push('', `// ${comment(step, index)}`)
296
+ if (step.webhook) {
297
+ return
298
+ }
299
+ const ref = (expression: JourneyExpression): string => expression.kind === 'literal' ? String(expression.value) : `\${${names[slotKey(expression)]}}`
300
+ const path = `\`${fillPath(step, ref)}${queryOf(step, ref)}\``
301
+ const headers = step.parameters.filter(item => item.in === 'header')
302
+ const args = [JSON.stringify(step.method), path]
303
+ if (step.body !== undefined || headers.length) {
304
+ args.push(step.body === undefined ? 'undefined' : jsLiteral(step.body, names, 0))
305
+ }
306
+ if (headers.length) {
307
+ args.push(`{ ${headers.map(item => `${JSON.stringify(item.name)}: \`${ref(item.value)}\``).join(', ')} }`)
308
+ }
309
+ const call = `await call(${args.join(', ')})`
310
+ if (step.outputs.length) {
311
+ const response = `${identifier(step.id)}`
312
+ lines.push(`const ${response} = ${call}`)
313
+ for (const output of step.outputs) {
314
+ lines.push(`const ${names[output.key]} = ${response}${jsPath(output.pointer)}`)
315
+ }
316
+ }
317
+ else {
318
+ lines.push(call)
319
+ }
320
+ })
321
+ return lines.join('\n')
322
+ }
323
+
324
+ function fillPath(step: CodeStep, ref: (expression: JourneyExpression) => string): string {
325
+ return step.path.replaceAll(/\{([^}]+)\}/g, (whole, name: string) => {
326
+ const parameter = step.parameters.find(item => item.in === 'path' && item.name === name)
327
+ return parameter ? ref(parameter.value) : whole
328
+ })
329
+ }
330
+
331
+ function queryOf(step: CodeStep, ref: (expression: JourneyExpression) => string): string {
332
+ const query = step.parameters.filter(item => item.in === 'query')
333
+ return query.length ? `?${query.map(item => `${encodeURIComponent(item.name)}=${ref(item.value)}`).join('&')}` : ''
334
+ }
335
+
336
+ function shellQuote(text: string): string {
337
+ return `'${text.replaceAll('\'', '\'\\\'\'')}'`
338
+ }
339
+
340
+ /** JSON for a single-quoted shell argument, splicing variables in. */
341
+ function shellJson(template: unknown, names: Record<string, string>): string {
342
+ const spliced: string[] = []
343
+ const marked = JSON.stringify(replaceExpressions(template, (expression) => {
344
+ if (expression.kind === 'literal') {
345
+ return expression.value
346
+ }
347
+ spliced.push(names[slotKey(expression)])
348
+ return `\u0000${spliced.length - 1}\u0000`
349
+ }))
350
+ return marked
351
+ .replaceAll('\'', '\'\\\'\'')
352
+ .replaceAll(/"\\u0000(\d+)\\u0000"/g, (_, index: string) => `"'"$${spliced[Number(index)]}"'"`)
353
+ }
354
+
355
+ function jsLiteral(template: unknown, names: Record<string, string>, depth: number): string {
356
+ if (isExpression(template)) {
357
+ const expression = template[EXPRESSION_KEY]
358
+ return expression.kind === 'literal' ? JSON.stringify(expression.value) : names[slotKey(expression)]
359
+ }
360
+ const pad = ' '.repeat(depth + 1)
361
+ if (Array.isArray(template)) {
362
+ return template.length ? `[\n${template.map(item => `${pad}${jsLiteral(item, names, depth + 1)},`).join('\n')}\n${' '.repeat(depth)}]` : '[]'
363
+ }
364
+ if (isRecord(template)) {
365
+ const entries = Object.entries(template)
366
+ return entries.length
367
+ ? `{\n${entries.map(([key, item]) => `${pad}${/^[a-z_$][\w$]*$/i.test(key) ? key : JSON.stringify(key)}: ${jsLiteral(item, names, depth + 1)},`).join('\n')}\n${' '.repeat(depth)}}`
368
+ : '{}'
369
+ }
370
+ return JSON.stringify(template)
371
+ }
372
+
373
+ function replaceExpressions(template: unknown, replace: (expression: JourneyExpression) => unknown): unknown {
374
+ if (isExpression(template)) {
375
+ return replace(template[EXPRESSION_KEY])
376
+ }
377
+ if (Array.isArray(template)) {
378
+ return template.map(item => replaceExpressions(item, replace))
379
+ }
380
+ if (isRecord(template)) {
381
+ return Object.fromEntries(Object.entries(template).map(([key, item]) => [key, replaceExpressions(item, replace)]))
382
+ }
383
+ return template
384
+ }
385
+
386
+ function segments(pointer: string): string[] {
387
+ return pointer.replace(/^\//, '').split('/').filter(Boolean).map(raw => raw.replaceAll('~1', '/').replaceAll('~0', '~'))
388
+ }
389
+
390
+ function jqPath(pointer: string): string {
391
+ const parts = segments(pointer)
392
+ return parts.length ? parts.map(part => /^\d+$/.test(part) ? `[${part}]` : /^[a-z_]\w*$/i.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`).join('').replace(/^\[/, '.[') : '.'
393
+ }
394
+
395
+ function jsPath(pointer: string): string {
396
+ return segments(pointer).map(part => /^\d+$/.test(part) ? `[${part}]` : /^[a-z_$][\w$]*$/i.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`).join('')
397
+ }
398
+
399
+ function isRecord(value: unknown): value is Record<string, unknown> {
400
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
401
+ }