This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
apib-generator.js
489 lines (472 loc) Β· 14.8 KB
/
apib-generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const { pathToRegexp, compile } = require('path-to-regexp')
const capture = require('./capture')
function convertPath(path, queries) {
const keys = []
pathToRegexp(path, keys)
const parameters = {}
for (const key of keys) {
parameters[key.name] = `{${key.name}}`
}
let resultPath = compile(path)(parameters)
.replace(/%7B/g, '{')
.replace(/%7D/g, '}')
if (queries) {
const queryKeys = Object.keys(queries)
if (queryKeys.length) resultPath += `{?${queryKeys.join(',')}}`
}
return resultPath.startsWith('/') ? resultPath : `/${resultPath}`
}
function indent(level) {
return ' '.repeat(level)
}
function generateDocForParameters(parameters, indentLevel = 0) {
let document = `${indent(indentLevel)}+ Parameters\n`
for (const parameterName of Object.keys(parameters)) {
const docs = capture.docs(parameters[parameterName])
const parameterValue = capture.undo(parameters[parameterName])
document += `${indent(indentLevel + 1)}+ ${parameterName}`
if (parameterValue !== null && parameterValue !== undefined) {
document += `: \`${parameterValue}\``
}
let additions = []
let type = docs.possibleValues.length
? capture.typeOf(docs.possibleValues[0])
: capture.typeOf(parameterValue)
if (type === 'string') type = ''
if (type) additions.push(type)
if (docs.required === false) additions.push('optional')
additions = additions.join(', ')
if (additions) document += ` (${additions})`
if (docs.descriptions[0]) document += ` - ${docs.descriptions[0]}`
document += '\n'
let details = ''
details += docs.descriptions
.slice(1)
.map((d) => `${indent(indentLevel + 2)}${d}\n\n`)
.join('')
if (docs.defaultValue !== undefined) {
details += `${indent(indentLevel + 2)}+ Default: \`${
docs.defaultValue
}\`\n\n`
}
if (docs.possibleValues.length) {
details += `${indent(indentLevel + 2)}+ Members\n`
details += docs.possibleValues
.map((v) => `${indent(indentLevel + 3)}+ \`${v}\`\n`)
.join('')
details += '\n'
}
if (details) document += `\n${details}`
}
document += '\n'
return document
}
function generateHeaders(headers, indentLevel = 0) {
let document = `${indent(indentLevel)}+ Headers\n\n`
for (const headerName of Object.keys(headers)) {
// eslint-disable-next-line no-continue
if (headerName.toLowerCase() === 'content-type') continue
const values =
capture.typeOf(headers[headerName]) === 'array'
? headers[headerName]
: [headers[headerName]]
for (const value of values) {
document += `${indent(indentLevel + 2)}${headerName}: ${value}\n`
}
}
document += '\n'
return document
}
function msonEscape(text) {
// eslint-disable-next-line no-param-reassign
if (typeof text !== 'string') text = String(text)
const lines = text.split(/\r\n|\r|\n/)
// eslint-disable-next-line no-param-reassign
text = lines.length > 1 ? `${lines[0]} ...` : lines[0]
const reservedCharacters = [
':',
'(',
')',
'<',
'>',
'{',
'}',
'[',
']',
'_',
'*',
'-',
'+',
'`',
]
const reservedKeywords = [
'Property',
'Properties',
'Item',
'Items',
'Member',
'Members',
'Include',
'One of',
'Sample',
'Trait',
'Traits',
'Parameter',
'Parameters',
'Attribute',
'Attributes',
'Filter',
'Validation',
'Choice',
'Choices',
'Enumeration',
'Enum',
'Object',
'Array',
'Element',
'Elements',
'Description',
]
const textToTest = text.toLowerCase()
const shouldEscape =
reservedCharacters.some((character) =>
textToTest.includes(character.toLowerCase())
) ||
reservedKeywords.some((keyword) => textToTest === keyword.toLowerCase())
if (!shouldEscape) return text
let maxBacktickLength = 0
for (const match of textToTest.match(/`+/gi) || []) {
if (match.length > maxBacktickLength) maxBacktickLength = match.length
}
const surrounder = '`'.repeat(maxBacktickLength + 1)
return `${surrounder}${maxBacktickLength > 0 ? ' ' : ''}${text}${
maxBacktickLength > 0 ? ' ' : ''
}${surrounder}`
}
function objectToMson(
object,
rootName = '',
indentLevel = 0,
extraNewline = true,
ignoreRootType = false
) {
let document = ''
capture.traverse(object, (node) => {
const docs = capture.docs(node.value)
const nodeValue = capture.undo(node.value)
let baseIndent = indentLevel + node.depth
let { parent } = node
while (parent) {
baseIndent += parent.childrenExtraIndent || 0
parent = parent.parent
}
document += indent(baseIndent)
if (node.depth === 0) {
document += `+ ${rootName}`
} else if (node.key) {
document += `+ ${msonEscape(node.key)}`
} else {
document += '+'
if (node.isLeaf) document += ' '
}
if (nodeValue !== null && nodeValue !== undefined) {
const escapedValue = msonEscape(nodeValue)
if (node.isLeaf && escapedValue) {
if ((node.key || node.depth === 0) && rootName) document += ': '
document += escapedValue
}
}
let additions = []
if (docs.possibleValues.length) {
additions.push('enum')
} else {
let ignoreValueType = false
if (node.valueType === 'string') ignoreValueType = true
if (
!node.isLeaf &&
node.valueType === 'object' &&
(node.key || (node.depth === 0 && rootName))
)
ignoreValueType = true
if (node.depth === 0 && ignoreRootType) ignoreValueType = true
if (!ignoreValueType) additions.push(node.valueType)
}
if (docs.required) additions.push('required')
if (docs.fixed) additions.push('fixed')
if (docs.fixedType) additions.push('fixed-type')
if (docs.nullable || nodeValue === null || nodeValue === undefined)
additions.push('nullable')
let sampleEmitted = false
let defaultEmitted = false
if (
docs.sampleValues.length === 1 &&
JSON.stringify(docs.sampleValues[0]) === JSON.stringify(nodeValue)
) {
additions.push('sample')
sampleEmitted = true
} else if (
docs.defaultValue !== undefined &&
JSON.stringify(docs.defaultValue) === JSON.stringify(nodeValue)
) {
additions.push('default')
defaultEmitted = true
}
additions = additions.join(', ')
if (additions) document += ` (${additions})`
if (node.depth > 0 && docs.descriptions[0])
document += ` - ${docs.descriptions[0]}`
document += '\n'
let needChildrenHeader = false
if (node.depth > 0 && docs.descriptions.length > 1) {
document += '\n'
document += docs.descriptions
.slice(1)
.map((d) => `${indent(baseIndent + 1)}${d}\n\n`)
.join('')
needChildrenHeader = true
}
if (docs.possibleValues.length) {
document += objectToMson(
docs.possibleValues,
'Members',
baseIndent + 1,
false,
true
)
needChildrenHeader = true
}
if (docs.defaultValue && !defaultEmitted) {
document += objectToMson(
docs.defaultValue,
'Default',
baseIndent + 1,
false,
true
)
needChildrenHeader = true
}
if (docs.sampleValues.length && !sampleEmitted) {
document += docs.sampleValues
.map((sampleValue) => {
return objectToMson(
sampleValue,
'Sample',
baseIndent + 1,
false,
true
)
})
.join('')
needChildrenHeader = true
}
if (needChildrenHeader && !node.isLeaf) {
document += `${indent(baseIndent + 1)}+ `
if (node.valueType === 'object') {
document += 'Properties'
} else if (docs.possibleValues.length) {
document += 'Sample'
} else {
document += 'Items'
}
document += '\n'
// eslint-disable-next-line no-param-reassign
node.childrenExtraIndent = 1
}
})
if (extraNewline) document += '\n'
return document
}
function generate(group) {
const groupStack = [group]
let document = ''
while (groupStack.length) {
const currentGroup = groupStack.shift()
groupStack.unshift(...currentGroup.children)
let trimLeft = ''
const groupParameters = {}
const groupQueries = {}
const groupRequestHeaders = {}
let parent = currentGroup
// eslint-disable-next-line no-constant-condition
while (true) {
if (parent.docs.basePath) trimLeft = `${parent.docs.basePath}/${trimLeft}`
if (parent.parameters) Object.assign(groupParameters, parent.parameters)
if (parent.queries) Object.assign(groupQueries, parent.queries)
if (parent.requestHeaders)
Object.assign(groupRequestHeaders, parent.requestHeaders)
if (!parent.parent) break
parent = parent.parent
}
// Group header & descriptions
if (currentGroup.depth === 0) {
document += 'FORMAT: 1A9\n'
if (currentGroup.docs.host) {
document += `HOST: ${currentGroup.docs.schemes[0] || 'http'}://${
currentGroup.docs.host
}/${currentGroup.docs.basePath}\n`
}
document += '\n'
if (currentGroup.docs.title) {
document += `# ${currentGroup.docs.title}`
if (currentGroup.docs.version)
document += ` ${currentGroup.docs.version}`
document += '\n\n'
} else if (currentGroup.docs.version) {
document += `# API Documentation ${currentGroup.docs.title}\n\n`
}
} else if (currentGroup.depth === 1 && currentGroup.children.length) {
// is Resource Group
document += `# Group ${currentGroup.docs.title || 'Untitled'}`
if (currentGroup.docs.version) document += ` ${currentGroup.docs.version}`
document += '\n\n'
} else {
document += currentGroup.depth === 1 ? '# ' : '## '
const path = convertPath(currentGroup.docs.basePath, currentGroup.queries)
let { title } = currentGroup.docs
if (!title && (!currentGroup.docs.basePath || currentGroup.docs.version))
title = 'Untitled Resource'
if (title) {
document += title
if (currentGroup.docs.version)
document += ` ${currentGroup.docs.version}`
if (currentGroup.docs.basePath) document += ` [${path}]`
} else {
document += path
}
document += '\n\n'
// Resource parameters
if (
Object.keys(groupParameters).length ||
Object.keys(groupQueries).length
)
document += generateDocForParameters({
...groupParameters,
...groupQueries,
})
}
document += currentGroup.docs.descriptions.reduce(
(p, c) => `${p + c}\n\n`,
''
)
// Group actions
for (const action of currentGroup.actions) {
// Action header & descriptions
document += action.group.depth === 1 ? '## ' : '### '
let url = action.docs.url.replace(
pathToRegexp(trimLeft, undefined, { end: false }),
''
)
const actionAllQueries = Object.assign({}, ...action.queries)
if (
url ||
JSON.stringify(actionAllQueries) !==
JSON.stringify(parent.queries || {})
) {
url = action.docs.url.replace(
pathToRegexp(parent.docs.basePath, undefined, { end: false }),
''
)
url = convertPath(url, actionAllQueries)
}
if (action.docs.title) {
document += `${action.docs.title} [${action.docs.method}`
document += action.docs.url ? ` ${url}]` : ']'
} else {
document += action.docs.method
if (action.docs.url) document += ` ${url}`
}
document += '\n\n'
document += action.docs.descriptions.reduce((p, c) => `${p + c}\n\n`, '')
const hasGroupHeaders = Object.keys(groupRequestHeaders).length
const cycle = Math.max(
action.parameters.length,
action.queries.length,
action.requestHeaders.length,
hasGroupHeaders ? 1 : 0,
action.requestBodies.length,
action.responseHeaders.length,
action.statusCodes.length,
action.responseBodies.length
)
for (let i = 0; i < cycle; i += 1) {
const hasParameters = action.parameters[i] || action.queries[i]
// Action parameters
if (i === 0 && hasParameters) {
document += generateDocForParameters({
...action.parameters[i],
...action.queries[i],
})
}
// Action request
if (
hasGroupHeaders ||
action.requestHeaders[i] ||
action.requestBodies[i] ||
(i > 0 && hasParameters)
) {
document += '+ Request'
const docs = capture.docs(action.requestBodies[i])
if (docs.descriptions[0]) document += ` ${docs.descriptions[0]}`
let contentType = 'application/json'
if (
action.requestHeaders[i] &&
action.requestHeaders[i]['content-type']
) {
;[contentType] = action.requestHeaders[i]['content-type'].split(';')
}
document += ` (${contentType})\n\n`
if (hasGroupHeaders || action.requestHeaders[i]) {
document += generateHeaders(
{
...(groupRequestHeaders || {}),
...action.requestHeaders[i],
},
1
)
}
if (i > 0 && hasParameters) {
document += generateDocForParameters(
{ ...action.parameters[i], ...action.queries[i] },
1
)
}
if (action.requestBodies[i] && contentType === 'application/json') {
document += objectToMson(action.requestBodies[i], 'Attributes', 1)
}
}
// Action response
if (
action.responseHeaders[i] ||
action.statusCodes[i] ||
action.responseBodies[i]
) {
let contentType = 'application/json'
if (
action.responseHeaders[i] &&
action.responseHeaders[i]['content-type']
)
[contentType] = action.responseHeaders[i]['content-type'].split(';')
document += `+ Response ${
action.statusCodes[i] || 200
} (${contentType})\n\n`
if (action.responseHeaders[i]) {
document += generateHeaders(action.responseHeaders[i], 1)
}
if (action.responseBodies[i] && contentType === 'application/json') {
document += objectToMson(action.responseBodies[i], 'Attributes', 1)
}
}
}
}
}
return document
}
module.exports.generate = generate
/* istanbul ignore else */
if (process.env.TEST2DOC_ENV === 'test') {
module.exports.convertPath = convertPath
module.exports.indent = indent
module.exports.generateDocForParameters = generateDocForParameters
module.exports.msonEscape = msonEscape
module.exports.objectToMson = objectToMson
}