@voxgig/apidef 8.32.3 → 8.33.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.
@@ -23,7 +23,8 @@ import type {
23
23
  } from '../model'
24
24
 
25
25
  import {
26
- cmpRefName, depluralize, foldName, guideActive, guidePath, paramName, READ_METHODS,
26
+ canonize, cmpRefName, depluralize, foldName, guideActive, guideParts, guidePath, isParam,
27
+ paramName, paramOf, READ_METHODS,
27
28
  } from '../utility'
28
29
 
29
30
  import { byCodePoint } from '../refcount'
@@ -168,14 +169,16 @@ function mergeCollectionPaths(
168
169
  }
169
170
 
170
171
  // An owner that reads nothing, holds only routes beneath the collection,
171
- // and extends the name a share's own record gives, takes that name.
172
+ // and extends the name a share's own record gives, or is extended by it,
173
+ // takes that name.
172
174
  const absorbed: Record<string, string> = {}
173
175
  for (const pathStr of Object.keys(owned).sort(byCodePoint)) {
174
176
  const owner = owned[pathStr]
175
177
  if (null == owner || null != absorbed[owner.ename] ||
176
178
  Object.values(absorbed).includes(owner.ename)) continue
177
179
  const ename = shares[pathStr].slice().sort(byCodePoint).find((share: string) =>
178
- owner.ename.startsWith(share + '_') && namedByRecord(share, pathStr) &&
180
+ (owner.ename.startsWith(share + '_') || share.endsWith('_' + owner.ename)) &&
181
+ namedByRecord(share, pathStr) &&
179
182
  !apart(share, pathStr, owner) &&
180
183
  onlyBeneath(entities[owner.ename], collectionRoot(pathStr) as string) &&
181
184
  !Object.values(entities[owner.ename].path).some((pd: any) =>
@@ -281,6 +284,161 @@ function mergeFoldedEntities(guide: any, log?: any): string[] {
281
284
  }
282
285
 
283
286
 
287
+ const WRITE_OPS = ['create', 'update', 'patch', 'remove']
288
+
289
+
290
+ // Entities are minimised: an entity whose one route writes to a literal
291
+ // straight beneath another entity's route is a command on that entity. The
292
+ // route joins it with the literal, spelled as written, as its action, and
293
+ // takes the parameter names that entity's route gives. Guide stage only.
294
+ function mergeCommandEntities(guide: any, log?: any): string[] {
295
+ const entities = guide.entity as Record<string, any>
296
+ const live = (ename: string) => null != entities[ename] && false !== entities[ename].active
297
+
298
+ const commandPath = (ename: string): string | null => {
299
+ const paths = live(ename) ? Object.keys(entities[ename].path ?? {}) : []
300
+ const ops = 1 === paths.length ? Object.keys(entities[ename].path[paths[0]]?.op ?? {}) : []
301
+ return 0 < ops.length && ops.every((opname) => WRITE_OPS.includes(opname)) ? paths[0] : null
302
+ }
303
+
304
+ const routeOf = (ename: string, key: string): string | undefined =>
305
+ Object.keys(entities[ename]?.path ?? {}).sort(byCodePoint)
306
+ .find((pathStr: string) => guidePath(pathStr) === key)
307
+
308
+ const holding = (key: string) => Object.keys(entities).sort(byCodePoint)
309
+ .filter((ename: string) => live(ename) && null != routeOf(ename, key))
310
+
311
+ const reads = (ename: string, key: string) =>
312
+ Object.keys(entities[ename].path[routeOf(ename, key) as string]?.op ?? {})
313
+ .some((opname: string) => !WRITE_OPS.includes(opname))
314
+
315
+ // Shallowest first, so a command beneath another joins where that one went.
316
+ const depth = (ename: string) => guidePath(commandPath(ename) as string).split('/').length
317
+ const order = Object.keys(entities).filter((ename: string) => null != commandPath(ename))
318
+ .sort((a: string, b: string) => depth(a) - depth(b) || byCodePoint(a, b))
319
+
320
+ const merged: string[] = []
321
+ for (const ename of order) {
322
+ const pathStr = commandPath(ename)
323
+ if (null == pathStr) continue
324
+ const key = guidePath(pathStr)
325
+ const at = key.lastIndexOf('/')
326
+ const last = key.slice(at + 1)
327
+ const action = snakify(last).replace(/[^a-zA-Z0-9_]/g, '')
328
+ if (at <= 0 || /[{}]/.test(last) || '' === action) continue
329
+
330
+ const parent = key.slice(0, at)
331
+ const owners = holding(parent).filter((other: string) => other !== ename)
332
+ const owner = owners.find((other: string) => reads(other, parent)) ?? owners[0]
333
+ if (null == owner || holding(key).some((other: string) =>
334
+ other !== ename && other !== owner && null == commandPath(other))) continue
335
+
336
+ const names = entities[owner].path[routeOf(owner, parent) as string]?.rename?.param ?? {}
337
+ const shared = new Set(guideParts(parent).map(paramOf).filter(Boolean))
338
+ movePath(entities[ename], entities[owner], pathStr)
339
+ const moved = entities[owner].path[pathStr]
340
+ moved.rename = {
341
+ ...(moved.rename ?? {}),
342
+ param: Object.fromEntries([
343
+ ...Object.entries(moved.rename?.param ?? {}).filter(([param]) => !shared.has(param)),
344
+ ...Object.entries(names).map(([param, rename]: [string, any]) => [param, { ...rename }]),
345
+ ]),
346
+ }
347
+ if (0 === Object.keys(moved.action ?? {}).length) {
348
+ moved.action = { [action]: { why_action: ['ent', owner, 'command', ename] } }
349
+ }
350
+ delete entities[ename]
351
+ merged.push(ename)
352
+ log?.info?.({
353
+ point: 'entity-command-merge', from: ename, to: owner, path: pathStr,
354
+ note: `entity ${ename} merged into ${owner}: its one route writes to ` +
355
+ `${last} beneath ${parent}, a command on ${owner} rather than an entity.`
356
+ })
357
+ }
358
+ return merged
359
+ }
360
+
361
+
362
+ // Points of one operation that share a selector reach only the first, so
363
+ // each path beyond the plainest takes the literals that set it apart as its
364
+ // action. The plainest is the one whose last literal names the entity, then
365
+ // the one with fewest literals. Variants of one path in its query string or fragment stay as they
366
+ // are. Guide stage only.
367
+ function separateSharedPoints(guide: any, def: any, log?: any): string[] {
368
+ const separated: string[] = []
369
+ const literals = (key: string) => guideParts(key).filter((part: string) => !isParam(part))
370
+ const actionOf = (lits: string[]) => lits
371
+ .map((lit: string) => snakify(lit.replace(/\.?\{[^}]*\}/g, '')).replace(/[^a-zA-Z0-9_]/g, ''))
372
+ .filter((word: string) => '' !== word).join('_')
373
+
374
+ for (const ename of Object.keys(guide.entity ?? {}).sort(byCodePoint)) {
375
+ const entity = guide.entity[ename]
376
+ if (false === entity.active) continue
377
+ const groups: Record<string, string[]> = {}
378
+ const reserved: Record<string, Set<string>> = {}
379
+ for (const pathStr of Object.keys(entity.path ?? {}).sort(byCodePoint)) {
380
+ const gpath = entity.path[pathStr]
381
+ const actions = Object.keys(gpath.action ?? {})
382
+ const renames = gpath.rename?.param ?? {}
383
+ const params = guideParts(pathStr).filter(isParam).map(paramOf)
384
+ .map((param: string) => canonize(renames[param]?.target ?? param))
385
+ for (const opname of Object.keys(gpath.op ?? {}).sort(byCodePoint)) {
386
+ const method = String(gpath.op[opname]?.method ?? '').toLowerCase()
387
+ const exist = [...params, ...requiredArgs(def, pathStr, method)].sort(byCodePoint)
388
+ const key = opname + '\t' + exist.join(',')
389
+ if (0 < actions.length) {
390
+ actions.forEach((action: string) => (reserved[key] = reserved[key] ?? new Set()).add(action))
391
+ }
392
+ else {
393
+ (groups[key] = groups[key] ?? []).push(pathStr)
394
+ }
395
+ }
396
+ }
397
+
398
+ for (const key of Object.keys(groups).sort(byCodePoint)) {
399
+ const paths = groups[key].filter((pathStr: string) =>
400
+ 0 === Object.keys(entity.path[pathStr]?.action ?? {}).length)
401
+ const names = (key: string) => depluralize(snakify(literals(key).pop() ?? '')) === ename ? 0 : 1
402
+ const keys = [...new Set(paths.map(guidePath))].sort((a: string, b: string) =>
403
+ names(a) - names(b) || literals(a).length - literals(b).length ||
404
+ a.length - b.length || byCodePoint(a, b))
405
+ if (keys.length < 2) continue
406
+ const plain = keys[0]
407
+ const plainLits = new Set(literals(plain))
408
+ const taken = new Set<string>(reserved[key] ?? [])
409
+ for (const other of keys.slice(1)) {
410
+ let action = actionOf(literals(other).filter((lit: string) => !plainLits.has(lit)))
411
+ if ('' === action || taken.has(action)) action = actionOf(literals(other))
412
+ if ('' === action || taken.has(action)) continue
413
+ taken.add(action)
414
+ for (const pathStr of paths.filter((p: string) => guidePath(p) === other)) {
415
+ entity.path[pathStr].action = {
416
+ [action]: { why_action: ['ent', ename, 'shared-selector', plain] }
417
+ }
418
+ separated.push(pathStr)
419
+ }
420
+ }
421
+ log?.info?.({
422
+ point: 'shared-selector-actions', entity: ename, plain, paths,
423
+ note: `points of ${ename} shared a selector; each path beyond ${plain} ` +
424
+ 'takes the literals that set it apart as its action.'
425
+ })
426
+ }
427
+ }
428
+ return separated
429
+ }
430
+
431
+
432
+ // The names of the query, header and cookie arguments an operation requires.
433
+ function requiredArgs(def: any, pathStr: string, method: string): string[] {
434
+ const pathItem = def?.paths?.[pathStr] ?? {}
435
+ return [...(pathItem.parameters ?? []), ...(pathItem[method]?.parameters ?? [])]
436
+ .filter((param: any) => true === param?.required && 'path' !== param?.in &&
437
+ 'body' !== param?.in && 'formData' !== param?.in && 'string' === typeof param?.name)
438
+ .map((param: any) => canonize(param.name))
439
+ }
440
+
441
+
284
442
  function opsMeet(entity: any, target: any): boolean {
285
443
  return Object.keys(entity?.path ?? {}).some((pathStr: string) =>
286
444
  Object.keys(entity.path[pathStr]?.op ?? {}).some((opname: string) =>
@@ -493,4 +651,6 @@ export {
493
651
  entityTransform,
494
652
  mergeCollectionPaths,
495
653
  mergeFoldedEntities,
654
+ mergeCommandEntities,
655
+ separateSharedPoints,
496
656
  }
@@ -8,7 +8,8 @@ import {
8
8
  validator, fieldName, inferFieldType, envelopeProp,
9
9
  composedEnvelopeProp, mergedProperties, canonizeCmpName,
10
10
  scanUntaggedUnion, firstSentence, humanTitle, collapseScalarAllOf,
11
- itemEnvelopeOf, isFileType, nonNullType,
11
+ itemEnvelopeOf, isFileType, nonNullType, jsonContent, responseSchema, rangeResponse,
12
+ cmpNamespace, stripNamespace,
12
13
  } from '../utility'
13
14
 
14
15
  import { arrayCarrier, guideMedia, requestFieldSchema, sameType, nullableType } from './body'
@@ -362,16 +363,29 @@ function answeredProps(
362
363
 
363
364
 
364
365
 
365
- function namesEntity(schema: any, ment: ModelEntity): boolean {
366
+ function namesEntity(schema: any, ment: ModelEntity, def: any): boolean {
366
367
  const xref = schema?.['x-ref']
367
368
 
368
369
  if ('string' !== typeof xref) {
369
370
  return false
370
371
  }
371
372
 
372
- const cmp = xref.slice(xref.lastIndexOf('/') + 1)
373
+ const cmp = canonizeCmpName(xref.slice(xref.lastIndexOf('/') + 1))
373
374
 
374
- return canonizeCmpName(cmp) === ment.name
375
+ return cmp === ment.name || stripNamespace(cmp, namespaceOf(def)) === ment.name
376
+ }
377
+
378
+
379
+ const NAMESPACES = new WeakMap<object, string | null>()
380
+
381
+ function namespaceOf(def: any): string | null {
382
+ if (null == def || 'object' !== typeof def) {
383
+ return null
384
+ }
385
+ if (!NAMESPACES.has(def)) {
386
+ NAMESPACES.set(def, cmpNamespace(def))
387
+ }
388
+ return NAMESPACES.get(def) ?? null
375
389
  }
376
390
 
377
391
  // A `$ref` followed one hop, or the schema itself. apidef resolves most refs
@@ -879,11 +893,9 @@ function findFieldDefs(
879
893
  let fieldSets
880
894
 
881
895
  if (responses) {
882
- fieldSets = getx(responses, '200 content "application/json" schema') ??
883
- getx(responses, '200 schema')
896
+ fieldSets = responseSchema(responses['200'] ?? rangeResponse(responses))
884
897
  if (null == fieldSets && answersOnlyAccepted(responses)) {
885
- fieldSets = getx(responses, '202 content "application/json" schema') ??
886
- getx(responses, '202 schema')
898
+ fieldSets = responseSchema(responses['202'])
887
899
  }
888
900
  if ('list' == mop.name) {
889
901
  const unwrapped = transformRecords(fieldSets, mpoint.t?.res) ?? unwrapArrayWrapper(fieldSets)
@@ -897,14 +909,12 @@ function findFieldDefs(
897
909
  fieldSets = mergedProperties(fieldSets)?.[envelope]?.items
898
910
  }
899
911
  else {
900
- const fromCreated = getx(responses, '201 content "application/json" schema items') ??
901
- getx(responses, '201 schema items')
912
+ const fromCreated = responseSchema(responses['201'])?.items
902
913
  if (fromCreated) fieldSets = fromCreated
903
914
  }
904
915
  }
905
916
  else if ('put' === method && null == fieldSets) {
906
- fieldSets = getx(responses, '201 content "application/json" schema') ??
907
- getx(responses, '201 schema')
917
+ fieldSets = responseSchema(responses['201'])
908
918
  }
909
919
 
910
920
  if ('list' != mop.name) {
@@ -922,7 +932,7 @@ function findFieldDefs(
922
932
  }
923
933
  }
924
934
 
925
- if (isAction && !namesEntity(fieldSets, ment)) {
935
+ if (isAction && !namesEntity(fieldSets, ment, def)) {
926
936
  return fielddefs
927
937
  }
928
938
 
@@ -1091,15 +1101,17 @@ function findExampleObject(opdef: any, envelope?: string | null): any {
1091
1101
  const responses = opdef.responses
1092
1102
  if (null == responses) return null
1093
1103
 
1094
- const resdef = responses['200'] ?? responses['201'] ?? responses['202']
1104
+ const resdef = responses['200'] ?? responses['201'] ?? responses['202'] ??
1105
+ rangeResponse(responses)
1095
1106
  if (null == resdef) return null
1096
1107
 
1097
1108
  // OpenAPI 3.x: content.application/json.example
1098
- let example = getx(resdef, 'content "application/json" example')
1109
+ const media = jsonContent(resdef.content)
1110
+ let example = media?.example
1099
1111
  if (null != example && 'object' === typeof example) return unwrapExample(example, envelope)
1100
1112
 
1101
1113
  // OpenAPI 3.x: content.application/json.examples (named examples — take first)
1102
- const examples = getx(resdef, 'content "application/json" examples')
1114
+ const examples = media?.examples
1103
1115
  if (null != examples && 'object' === typeof examples) {
1104
1116
  for (const val of Object.values(examples)) {
1105
1117
  const ex = (val as any)?.value
@@ -1108,7 +1120,7 @@ function findExampleObject(opdef: any, envelope?: string | null): any {
1108
1120
  }
1109
1121
 
1110
1122
  // OpenAPI 3.x: content.application/json.schema.example
1111
- example = getx(resdef, 'content "application/json" schema example')
1123
+ example = media?.schema?.example
1112
1124
  if (null != example && 'object' === typeof example) return unwrapExample(example, envelope)
1113
1125
 
1114
1126
  // Swagger 2.0: response.example / response.examples.application/json
@@ -43,9 +43,9 @@ import type {
43
43
  // verb is declared as `action: <verb>: {}` beside a CRUD op on the same path.
44
44
  const RESOLVED_OPS = ['load', 'list', 'create', 'update', 'remove', 'patch']
45
45
 
46
- // Emitted by the heuristic for HEAD and OPTIONS methods; no SDK operation
46
+ // Emitted by the heuristic for HEAD, OPTIONS and TRACE methods; no SDK operation
47
47
  // exists for them yet, so they are skipped without a warning.
48
- const IGNORED_OPS = ['head', 'options', 'OPTIONS']
48
+ const IGNORED_OPS = ['head', 'options', 'OPTIONS', 'TRACE']
49
49
 
50
50
 
51
51
  const operationTransform: Transform = async function(
@@ -211,8 +211,8 @@ function resolveActionCreate(ctx: any, opm: ModelOpMap, on: OpEntity) {
211
211
  const verbs = [...new Set(paths.flatMap((p) => Object.keys(p.action ?? {})))].sort()
212
212
  ctx.warn?.({
213
213
  note: `Create on entity=${on.gent.name} has no route of its own, only the action ` +
214
- `${verbs.join(', ')}, so a plain create sends it. Set the route's op in the ` +
215
- `guide if it should not.`,
214
+ `${verbs.join(', ')}, so a create must name it with $action. Set the route's ` +
215
+ `op in the guide if it is not a create.`,
216
216
  entity: on.gent.name,
217
217
  op: 'create',
218
218
  })
package/src/types.ts CHANGED
@@ -226,7 +226,7 @@ import type {
226
226
  BasicMethodDesc,
227
227
  } from './desc'
228
228
 
229
- type MethodName = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'QUERY' | ''
229
+ type MethodName = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'QUERY' | 'TRACE' | ''
230
230
 
231
231
 
232
232