@voxgig/apidef 8.16.0 → 8.17.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/parse.ts CHANGED
@@ -103,35 +103,108 @@ async function parseOpenAPI(source: any, _meta?: any) {
103
103
  )
104
104
  }
105
105
 
106
+ if (SURROGATE_RE.test(source)) {
107
+ parsed = wellFormed(parsed, new Map())
108
+ }
109
+
106
110
  if (null == parsed.components) {
107
111
  parsed.components = {}
108
112
  }
109
113
 
110
- // Normalize path keys: jsonic's YAML parser leaves the surrounding double
111
- // quotes IN the key for explicit-key form (`? "..."`). gitlab uses this for
112
- // long paths and as a result every downstream split('/') sees a literal
113
- // quote character at the head/tail of the path, breaking URL substitution.
114
- if (parsed.paths && 'object' === typeof parsed.paths) {
115
- const cleaned: Record<string, any> = {}
116
- for (const [k, v] of Object.entries(parsed.paths)) {
117
- const stripped = k.replace(/^"+|"+$/g, '')
118
- cleaned[stripped] = v
119
- }
120
- parsed.paths = cleaned
114
+ if (isRecord(parsed.paths)) {
115
+ parsed.paths = renameKeys(parsed.paths, normalizePathKeys(Object.keys(parsed.paths)))
121
116
  }
122
117
 
123
- // See docs/design/derived-names.md
124
- normalizeColonPathParams(parsed, _meta)
125
-
126
118
  // Single-pass: add x-ref properties and resolve $ref pointers together.
127
119
  addXRefsAndResolve(parsed, parsed)
128
120
 
121
+ // After resolution, so a pointer into `paths` names the key as written and a
122
+ // parameter declared by `$ref` counts. See docs/design/derived-names.md
123
+ normalizeColonPathParams(parsed, _meta)
124
+
129
125
  const def = decycle(parsed)
130
126
 
131
127
  return def
132
128
  }
133
129
 
134
130
 
131
+ // A surrogate escape, or a raw lone surrogate unit.
132
+ const SURROGATE_RE =
133
+ /\\(?:u\{?|U)0*[dD][89a-fA-F][0-9a-fA-F]{2}|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
134
+
135
+ const LONE_SURROGATE_RE =
136
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
137
+
138
+
139
+ function wellFormedString(s: string): string {
140
+ return s.replace(LONE_SURROGATE_RE, '�')
141
+ }
142
+
143
+
144
+ // The Go parser reads a lone surrogate as U+FFFD, and so does every UTF-8
145
+ // writer. Keys it makes equal merge as the parser merges a repeated key.
146
+ function wellFormed(node: any, done: Map<any, any>): any {
147
+ if ('string' === typeof node) return wellFormedString(node)
148
+ if (null == node || 'object' !== typeof node) return node
149
+ if (done.has(node)) return done.get(node)
150
+
151
+ if (Array.isArray(node)) {
152
+ done.set(node, node)
153
+ for (let i = 0; i < node.length; i++) node[i] = wellFormed(node[i], done)
154
+ return node
155
+ }
156
+
157
+ const out = Object.create(Object.getPrototypeOf(node))
158
+ done.set(node, out)
159
+ for (const key of Object.keys(node)) {
160
+ const wkey = wellFormedString(key)
161
+ const val = wellFormed(node[key], done)
162
+ const prev = Object.prototype.hasOwnProperty.call(out, wkey) ? out[wkey] : undefined
163
+ out[wkey] = null == prev ? val : Jsonic.util.deep(prev, val)
164
+ }
165
+ return out
166
+ }
167
+
168
+
169
+ function renameKeys(obj: any, keys: string[]): any {
170
+ const out = Object.create(Object.getPrototypeOf(obj))
171
+ Object.keys(obj).forEach((key, i) => { out[keys[i]] = obj[key] })
172
+ return out
173
+ }
174
+
175
+
176
+ // @tabnas/yaml keeps the quotes of an explicit key (`? "/a"`, `? '/a'`) in the
177
+ // key. A rename that would collide with another key is not made.
178
+ function normalizePathKeys(keys: string[]): string[] {
179
+ return keepDistinct(keys, keys.map(unquotePathKey))
180
+ }
181
+
182
+
183
+ function unquotePathKey(key: string): string {
184
+ if (key.length < 2 || key[0] !== key[key.length - 1]) return key
185
+ if ("'" === key[0]) return key.slice(1, -1).replace(/''/g, "'")
186
+ if ('"' !== key[0]) return key
187
+ try {
188
+ const decoded = JSON.parse(key)
189
+ if ('string' === typeof decoded) return wellFormedString(decoded)
190
+ }
191
+ catch (_e: any) {
192
+ // Not a JSON string: an escape only YAML knows, so strip the quotes alone.
193
+ }
194
+ return key.slice(1, -1)
195
+ }
196
+
197
+
198
+ function keepDistinct(keys: string[], next: string[]): string[] {
199
+ const count = new Map<string, number>()
200
+ keys.forEach((key, i) => {
201
+ count.set(key, (count.get(key) ?? 0) + 1)
202
+ if (next[i] !== key) count.set(next[i], (count.get(next[i]) ?? 0) + 1)
203
+ })
204
+ return keys.map((key, i) => next[i] !== key && 1 < (count.get(next[i]) ?? 0) ? key : next[i])
205
+ }
206
+
207
+
135
208
  // Edges decycle cut, so the guide can still count through them; a clone has none.
136
209
  const DECYCLED = new WeakMap<object, Map<string, object>>()
137
210
 
@@ -262,61 +335,57 @@ function resolveRefSite(
262
335
  }
263
336
 
264
337
 
265
- function resolvePointer(root: any, ref: string): any {
266
- const seen = new Set<string>()
267
- const siblings: any[] = []
268
- let current: any = undefined
269
- let pointer = ref
338
+ const INDEX_RE = /^(0|[1-9]\d*)$/
270
339
 
271
- for (; ;) {
272
- if (!pointer.startsWith('#/')) return undefined
273
- if (seen.has(pointer)) return undefined
274
- seen.add(pointer)
275
340
 
276
- const parts = pointer
277
- .substring(2)
278
- .split('/')
279
- .map(p => p.replace(/~1/g, '/').replace(/~0/g, '~'))
341
+ function isRecord(node: any): boolean {
342
+ return null != node && 'object' === typeof node && !Array.isArray(node)
343
+ }
280
344
 
281
- current = root
282
- for (const part of parts) {
283
- if (current == null || typeof current !== 'object') return undefined
284
- current = current[part]
285
- }
286
345
 
287
- // Landed on another alias: follow it. Anything else is the target.
288
- if (current != null &&
289
- 'object' === typeof current &&
290
- !Array.isArray(current) &&
291
- 'string' === typeof current.$ref) {
292
- const sib: any = {}
293
- let hasSib = false
294
- for (const k of Object.keys(current)) {
295
- if ('$ref' === k) continue
296
- sib[k] = current[k]
297
- hasSib = true
298
- }
299
- if (hasSib) siblings.push(sib)
300
- pointer = current.$ref
301
- continue
302
- }
346
+ function isAlias(node: any): boolean {
347
+ return isRecord(node) && 'string' === typeof node.$ref
348
+ }
303
349
 
304
- if (0 === siblings.length) {
305
- // No siblings anywhere on the chain: return the target itself, so
306
- // multiple references keep sharing one object (see the note on
307
- // addXRefsAndResolve — a fresh copy per site would defeat that).
308
- return current
309
- }
310
350
 
311
- // Siblings present: a merged view is necessarily a new object. Apply
312
- // deepest-first so the outermost alias's keywords win.
313
- const merged: any = (null != current && 'object' === typeof current &&
314
- !Array.isArray(current)) ? { ...current } : {}
315
- for (let i = siblings.length - 1; 0 <= i; i--) {
316
- Object.assign(merged, siblings[i])
317
- }
318
- return merged
351
+ // An own key of an object, or an RFC 6901 index of an array.
352
+ function pointerChild(node: any, part: string): any {
353
+ if (Array.isArray(node)) {
354
+ return INDEX_RE.test(part) && Number(part) < node.length ? node[Number(part)] : undefined
319
355
  }
356
+ return isRecord(node) && Object.prototype.hasOwnProperty.call(node, part) ?
357
+ node[part] : undefined
358
+ }
359
+
360
+
361
+ // The object a pointer names, following every alias met on the way, so the
362
+ // answer does not depend on which aliases the walk has already replaced. A
363
+ // pointer that names no object, or needs itself, names nothing.
364
+ function resolvePointer(root: any, ref: string, active: Set<string> = new Set()): any {
365
+ if (!ref.startsWith('#/') || active.has(ref)) return undefined
366
+ active.add(ref)
367
+
368
+ let node: any = root
369
+ for (const raw of ref.substring(2).split('/')) {
370
+ node = pointerChild(followAlias(root, node, active),
371
+ raw.replace(/~1/g, '/').replace(/~0/g, '~'))
372
+ if (undefined === node) break
373
+ }
374
+ node = followAlias(root, node, active)
375
+
376
+ active.delete(ref)
377
+ return isRecord(node) ? node : undefined
378
+ }
379
+
380
+
381
+ // An alias's own keywords win over its target's. Without them the target
382
+ // itself is the answer, so references keep sharing one object.
383
+ function followAlias(root: any, node: any, active: Set<string>): any {
384
+ if (!isAlias(node)) return node
385
+ const target = resolvePointer(root, node.$ref, active)
386
+ if (undefined === target) return undefined
387
+ const sib = refSiblings(node)
388
+ return 0 === Object.keys(sib).length ? target : { ...target, ...sib }
320
389
  }
321
390
 
322
391
 
@@ -342,6 +411,8 @@ function validateSource(kind: string, source: any, meta: { file: string }) {
342
411
  export {
343
412
  parse,
344
413
  decycledChild,
414
+ normalizePathKeys,
415
+ colonPathKeys,
345
416
  }
346
417
 
347
418
 
@@ -353,19 +424,31 @@ const METHODS = [
353
424
  // Rewrite `/a/:b/c` to `/a/{b}/c`, for a `:b` the path or one of its
354
425
  // operations declares `in: path`. See docs/design/derived-names.md
355
426
  function normalizeColonPathParams(parsed: any, meta?: any) {
356
- if (null == parsed.paths || 'object' !== typeof parsed.paths) return
427
+ if (!isRecord(parsed.paths)) return
357
428
 
358
- const renamed: string[] = []
359
- const out: Record<string, any> = {}
429
+ const paths = Object.keys(parsed.paths)
430
+ const next = colonPathKeys(parsed.paths)
431
+ parsed.paths = renameKeys(parsed.paths, next)
360
432
 
361
- for (const [path, item] of Object.entries<any>(parsed.paths)) {
362
- if (!path.includes('/:')) {
363
- out[path] = item
364
- continue
365
- }
433
+ const renamed = paths.filter((path, i) => next[i] !== path)
434
+ if (0 < renamed.length && null != meta?.log?.info) {
435
+ meta.log.info({
436
+ point: 'path-colon-params',
437
+ count: renamed.length,
438
+ note: 'rewrote ' + renamed.length + ' colon-style path parameter(s) to' +
439
+ ' OpenAPI brace form, e.g. ' + renamed[0]
440
+ })
441
+ }
442
+ }
366
443
 
367
- // Every `in: path` name this path knows about: the path-level parameters
368
- // plus each operation's own.
444
+
445
+ // Every `in: path` name counts: the path item's parameters and each operation's.
446
+ function colonPathKeys(paths: Record<string, any>): string[] {
447
+ const keys = Object.keys(paths)
448
+ return keepDistinct(keys, keys.map((path) => {
449
+ if (!path.includes('/:')) return path
450
+
451
+ const item = paths[path]
369
452
  const declared = new Set<string>()
370
453
  const collect = (params: any) => {
371
454
  if (!Array.isArray(params)) return
@@ -382,22 +465,8 @@ function normalizeColonPathParams(parsed: any, meta?: any) {
382
465
  }
383
466
  }
384
467
 
385
- const next = path.split('/').map((seg) =>
468
+ return path.split('/').map((seg) =>
386
469
  seg.startsWith(':') && declared.has(seg.slice(1)) ? '{' + seg.slice(1) + '}' : seg
387
470
  ).join('/')
388
-
389
- if (next !== path) renamed.push(path)
390
- out[next] = item
391
- }
392
-
393
- parsed.paths = out
394
-
395
- if (0 < renamed.length && null != meta?.log?.info) {
396
- meta.log.info({
397
- point: 'path-colon-params',
398
- count: renamed.length,
399
- note: 'rewrote ' + renamed.length + ' colon-style path parameter(s) to' +
400
- ' OpenAPI brace form, e.g. ' + renamed[0]
401
- })
402
- }
471
+ }))
403
472
  }
@@ -34,10 +34,6 @@ const entityTransform: Transform = async function(
34
34
 
35
35
  let msg = ''
36
36
 
37
- if (true !== ctx.def?.graphql) {
38
- mergeCollectionPaths(guide, ctx.log)
39
- }
40
-
41
37
  each(guide.entity, (guideEntity: GuideEntity, entname: string) => {
42
38
  if (!guideActive(guideEntity)) {
43
39
  ctx.log.debug({ point: 'guide-entity', note: entname, active: false })
@@ -86,8 +82,11 @@ function filterEntityAncestors(entities: Record<string, any>) {
86
82
  // Move "/X" paths onto the entity that owns "/X/{id}" or "/X/{id}/sub".
87
83
  // Only acts when the path "/X" sits on a different entity than the
88
84
  // per-instance paths — leaves correctly-classified APIs alone.
89
- function mergeCollectionPaths(guide: any, log?: any) {
85
+ // Returns the entities the moves emptied, which are removed.
86
+ // Guide stage only: on the unified guide it would override guide.aontu.
87
+ function mergeCollectionPaths(guide: any, log?: any): string[] {
90
88
  const entities = guide.entity as Record<string, any>
89
+ const emptied: string[] = []
91
90
 
92
91
  const rootOwners: Record<string, { ename: string, depth: number }> = {}
93
92
 
@@ -169,7 +168,19 @@ function mergeCollectionPaths(guide: any, log?: any) {
169
168
  to: owner.ename,
170
169
  })
171
170
  }
171
+
172
+ if (0 < pathsToMove.length && 0 === Object.keys(entity.path).length) {
173
+ emptied.push(ename)
174
+ }
172
175
  }
176
+
177
+ // With no path left it names nothing guide.aontu could switch back on.
178
+ for (const ename of emptied) {
179
+ delete entities[ename]
180
+ log?.debug?.({ point: 'merge-collection-drop', entity: ename })
181
+ }
182
+
183
+ return emptied
173
184
  }
174
185
 
175
186
 
package/src/utility.ts CHANGED
@@ -66,6 +66,32 @@ function writeFileSyncWarn(warn: Warner, fs: any, path: string, text: string) {
66
66
  }
67
67
 
68
68
 
69
+ // Before `.aon` was retired apidef wrote each of its files under that
70
+ // extension, so the `.aon` twin of a file it writes as `.aontu` is its own.
71
+ function removeLegacyAon(fs: any, log: any, file: string): boolean {
72
+ const legacy = file.replace(/\.aontu$/, '.aon')
73
+ if (legacy === file || !fs.existsSync(legacy)) {
74
+ return false
75
+ }
76
+
77
+ try {
78
+ fs.unlinkSync(legacy)
79
+ log?.info?.({
80
+ point: 'legacy-aon', file: legacy,
81
+ note: 'removed ' + relativizePath(legacy) + ', now written as .aontu',
82
+ })
83
+ return true
84
+ }
85
+ catch (err: any) {
86
+ log?.warn?.({
87
+ point: 'legacy-aon-failed', file: legacy, err,
88
+ note: 'could not remove ' + relativizePath(legacy) + ': ' + err?.message,
89
+ })
90
+ return false
91
+ }
92
+ }
93
+
94
+
69
95
 
70
96
  function getdlog(
71
97
  tagin?: string,
@@ -159,6 +185,7 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
159
185
  'premises': 'premise',
160
186
  'promises': 'promise',
161
187
  'psyches': 'psyche',
188
+ 'purchases': 'purchase',
162
189
  'purses': 'purse',
163
190
  'releases': 'release',
164
191
  'roses': 'rose',
@@ -177,6 +204,15 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
177
204
  })
178
205
 
179
206
 
207
+ // The stems whose -ves plural comes from -fe (knives) or -f (wolves). The
208
+ // -fe stems match the whole word, since olives is not the plural of olife.
209
+ const FE_PLURAL_STEMS = ['kni', 'li', 'wi']
210
+ const F_PLURAL_STEMS = [
211
+ 'cal', 'dwar', 'el', 'hal', 'hoo', 'lea', 'loa', 'scar', 'shea', 'thie',
212
+ 'whar', 'wol',
213
+ ]
214
+
215
+
180
216
  // Sorted longest-first so the most specific IRREGULARS suffix wins.
181
217
  // Without this, 'women' would be shadowed by 'men' (3 < 5) under
182
218
  // insertion-order iteration. Both happen to round-trip correctly
@@ -274,16 +310,21 @@ function depluralize(word: string): string {
274
310
  }
275
311
  }
276
312
 
277
- // -ves -> -f or -fe (wolves -> wolf, knives -> knife)
313
+ // -ves -> -f or -fe only for the words that take it (wolves -> wolf,
314
+ // knives -> knife); every other -ves plural drops the -s alone
315
+ // (objectives -> objective).
278
316
  if (lower.endsWith('ves')) {
279
317
  const stem = word.slice(0, -3)
318
+ const lstem = stem.toLowerCase()
280
319
  const dropped = word.slice(-3)
281
320
  const isUpper = dropped === dropped.toUpperCase()
282
- // Check if it should be -fe (like knife, wife, life)
283
- if (['kni', 'wi', 'li'].includes(stem.toLowerCase())) {
321
+ if (FE_PLURAL_STEMS.includes(lstem)) {
284
322
  return stem + (isUpper ? 'FE' : 'fe')
285
323
  }
286
- return stem + (isUpper ? 'F' : 'f')
324
+ if (F_PLURAL_STEMS.some((fstem) => lstem.endsWith(fstem))) {
325
+ return stem + (isUpper ? 'F' : 'f')
326
+ }
327
+ return word.slice(0, -1)
287
328
  }
288
329
 
289
330
  // -oes -> -o (potatoes -> potato)
@@ -1224,12 +1265,13 @@ function requestBodySchema(requestBody: any): any {
1224
1265
  }
1225
1266
 
1226
1267
 
1268
+ // Sorted, not definition order, which the Go parser does not keep.
1227
1269
  function schemaProps(schema: any): string[] {
1228
1270
  const props = schema?.properties
1229
1271
  if (null == props || 'object' !== typeof props) {
1230
1272
  return []
1231
1273
  }
1232
- return Object.keys(props)
1274
+ return sortedKeys(props)
1233
1275
  }
1234
1276
 
1235
1277
 
@@ -1802,6 +1844,7 @@ export {
1802
1844
  debugpathOn,
1803
1845
  findPathsWithPrefix,
1804
1846
  writeFileSyncWarn,
1847
+ removeLegacyAon,
1805
1848
  warnOnError,
1806
1849
  relativizePath,
1807
1850
  getModelPath,