@voxgig/apidef 8.23.0 → 8.24.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.
Files changed (39) hide show
  1. package/dist/builder/entity/entity.d.ts +2 -1
  2. package/dist/builder/entity/entity.js +14 -11
  3. package/dist/builder/entity/entity.js.map +1 -1
  4. package/dist/guide/guide.js +5 -2
  5. package/dist/guide/guide.js.map +1 -1
  6. package/dist/guide/heuristic01.d.ts +2 -1
  7. package/dist/guide/heuristic01.js +232 -85
  8. package/dist/guide/heuristic01.js.map +1 -1
  9. package/dist/transform/args.d.ts +4 -1
  10. package/dist/transform/args.js +42 -13
  11. package/dist/transform/args.js.map +1 -1
  12. package/dist/transform/body.d.ts +19 -2
  13. package/dist/transform/body.js +189 -15
  14. package/dist/transform/body.js.map +1 -1
  15. package/dist/transform/field.d.ts +3 -1
  16. package/dist/transform/field.js +159 -87
  17. package/dist/transform/field.js.map +1 -1
  18. package/dist/transform/operation.js +77 -24
  19. package/dist/transform/operation.js.map +1 -1
  20. package/dist/transform/select.js +10 -4
  21. package/dist/transform/select.js.map +1 -1
  22. package/dist/transform/top.d.ts +2 -1
  23. package/dist/transform/top.js +50 -3
  24. package/dist/transform/top.js.map +1 -1
  25. package/dist/tsconfig.tsbuildinfo +1 -1
  26. package/dist/utility.d.ts +9 -1
  27. package/dist/utility.js +139 -13
  28. package/dist/utility.js.map +1 -1
  29. package/package.json +1 -1
  30. package/src/builder/entity/entity.ts +17 -15
  31. package/src/guide/guide.ts +5 -3
  32. package/src/guide/heuristic01.ts +292 -93
  33. package/src/transform/args.ts +50 -14
  34. package/src/transform/body.ts +231 -15
  35. package/src/transform/field.ts +190 -88
  36. package/src/transform/operation.ts +97 -26
  37. package/src/transform/select.ts +13 -4
  38. package/src/transform/top.ts +59 -3
  39. package/src/utility.ts +169 -13
@@ -71,11 +71,7 @@ const argsTransform: Transform = async function(
71
71
  }
72
72
  }
73
73
  else {
74
- const pathdef: PathDef = def.paths[mpoint.o]
75
- argdefs.push(...((pathdef as any)?.parameters ?? []))
76
-
77
- const opdef: MethodDef = (pathdef as any)?.[mpoint.m.toLowerCase()]
78
- argdefs.push(...(opdef?.parameters ?? []))
74
+ argdefs.push(...routeArgdefs(def, mpoint))
79
75
  }
80
76
 
81
77
  resolveArgs(ctx, ment, mop, mpoint, argdefs)
@@ -90,6 +86,22 @@ const argsTransform: Transform = async function(
90
86
  }
91
87
 
92
88
 
89
+ function routeArgdefs(def: any, mpoint: ModelPoint): ParameterDef[] {
90
+ const pathdef: PathDef = def.paths?.[mpoint.o]
91
+ const opdef: MethodDef = (pathdef as any)?.[mpoint.m.toLowerCase()]
92
+ return [...((pathdef as any)?.parameters ?? []), ...(opdef?.parameters ?? [])]
93
+ }
94
+
95
+
96
+ // The names a caller gives a REST route's arguments, as this step names them.
97
+ function routeArgNames(def: any, mpoint: ModelPoint): string[] {
98
+ const route = { ...mpoint, g: {} } as ModelPoint
99
+ resolveArgs(undefined, { name: '' } as ModelEntity, { name: '', points: [] } as unknown as ModelOp, route,
100
+ routeArgdefs(def, mpoint))
101
+ return Object.values(route.g).flat().map((arg: any) => arg.n)
102
+ }
103
+
104
+
93
105
  // Locate the normalised root-field descriptor a GraphQL point came from.
94
106
  function graphqlFieldDef(def: any, mpoint: ModelPoint): any {
95
107
  const field = mpoint.gq?.field ?? mpoint.o
@@ -123,6 +135,11 @@ function resolveArgs(
123
135
  const placeholders = [...String(mpoint.o ?? '').matchAll(/\{([^}]+)\}/g)].map((m) => m[1])
124
136
 
125
137
  each(argdefs, (argdef: ParameterDef) => {
138
+ // A Swagger body parameter is the request body, which the body step reads.
139
+ if ('body' === (argdef as any).in) {
140
+ return
141
+ }
142
+
126
143
  const specName = normalizeFieldName(argdef.name)
127
144
  const orig = depluralize(snakify(specName))
128
145
 
@@ -158,23 +175,27 @@ function resolveArgs(
158
175
  param: argdef.name,
159
176
  })
160
177
  }
161
- // Rename map can be keyed by either the spec original (camelCase) or by
162
- // the snakified form depending on which path went through heuristic01.
163
- // Try both before falling through to `orig`.
178
+ // A path argument is named by the lookup that names its segment, so the
179
+ // two agree under a raw rename key, and one that fills a placeholder is
180
+ // required, as OpenAPI requires; a GraphQL argument keeps its own flag.
181
+ // Any other rename map is keyed by the spec original or the snakified form.
182
+ const path = 'param' === kind
183
+ const fills = path && placeholders.some((p) => p === argdef.name || canonizeParam(p) === orig)
164
184
  const renameMap = mpoint.r[kind]
165
- const name = placed ? paramName(argdef.name, mpoint.r.param) :
185
+ const name = path ? paramName(argdef.name, mpoint.r.param) :
166
186
  (renameMap?.[specName] ?? renameMap?.[orig] ?? orig)
187
+ const schema = paramSchema(argdef)
167
188
  // The name the definition gives, which the SDK sends on the wire. The
168
189
  // model name beside it is only what a caller writes.
169
190
  const marg: ModelArg = {
170
191
  n: name,
171
192
  or: String(argdef.name),
172
- t: inferFieldType(name, validator(argdef.schema?.type)),
193
+ t: inferFieldType(name, validator(schema?.type)),
173
194
  k: kind,
174
- r: placed || !!argdef.required
195
+ r: fills || !!argdef.required
175
196
  }
176
197
 
177
- const example = resolveArgExample(argdef)
198
+ const example = resolveArgExample(argdef, schema)
178
199
  if (undefined !== example) {
179
200
  marg.ex = example
180
201
  }
@@ -223,7 +244,21 @@ function resolveArgs(
223
244
  }
224
245
 
225
246
 
226
- function resolveArgExample(argdef: any): any {
247
+ // Type facts sit on a Swagger 2 parameter itself, and under `schema` in
248
+ // OpenAPI 3. A formData parameter converts to a body field, not a parameter.
249
+ function paramSchema(argdef: any): any {
250
+ if (null != argdef?.schema) {
251
+ return argdef.schema
252
+ }
253
+ if ('formData' === argdef?.in) {
254
+ return undefined
255
+ }
256
+ // Swagger 2's file type is a binary string in OpenAPI 3.
257
+ return 'file' === argdef?.type ? { ...argdef, type: 'string', format: 'binary' } : argdef
258
+ }
259
+
260
+
261
+ function resolveArgExample(argdef: any, schema: any): any {
227
262
  if (undefined !== argdef?.example) return argdef.example
228
263
 
229
264
  const examples = argdef?.examples
@@ -235,7 +270,6 @@ function resolveArgExample(argdef: any): any {
235
270
  }
236
271
  }
237
272
 
238
- const schema = argdef?.schema
239
273
  if (schema) {
240
274
  if (undefined !== schema.example) return schema.example
241
275
  if (undefined !== schema.default) return schema.default
@@ -247,4 +281,6 @@ function resolveArgExample(argdef: any): any {
247
281
 
248
282
  export {
249
283
  argsTransform,
284
+ resolveArgExample,
285
+ routeArgNames,
250
286
  }
@@ -37,6 +37,12 @@ type Offer = {
37
37
  swagger?: boolean
38
38
  }
39
39
 
40
+ type Ranked = {
41
+ offer: Offer
42
+ declared: string
43
+ body: ModelBody
44
+ }
45
+
40
46
 
41
47
  const bodyTransform: Transform = async function(
42
48
  ctx: any,
@@ -98,14 +104,12 @@ function requestBody(
98
104
  path: string,
99
105
  media?: string,
100
106
  ): ModelBody | undefined {
101
- const pathdef = def?.paths?.[path]
102
- const opdef = pathdef?.[String(method).toLowerCase()]
103
- if (!isMap(opdef)) {
107
+ const offers = requestOffers(def, method, path)
108
+ if (null == offers) {
104
109
  return undefined
105
110
  }
106
111
 
107
- const body = chooseBody(null != def.swagger ?
108
- swaggerOffers(def, pathdef, opdef) : openapiOffers(opdef), media)
112
+ const body = chooseBody(offers, media)
109
113
 
110
114
  if (null == body || ('json' === body.kind && JSON_MEDIA === essence(body.media) &&
111
115
  (body.alternatives ?? []).every((other) => 'json' === other.kind))) {
@@ -133,20 +137,23 @@ function responseBody(
133
137
  }
134
138
 
135
139
 
140
+ function requestOffers(def: any, method: string, path: string): Offer[] | undefined {
141
+ const pathdef = def?.paths?.[path]
142
+ const opdef = pathdef?.[String(method).toLowerCase()]
143
+ if (!isMap(opdef)) {
144
+ return undefined
145
+ }
146
+ return null != def.swagger ? swaggerOffers(def, pathdef, opdef) : openapiOffers(opdef)
147
+ }
148
+
149
+
136
150
  function chooseBody(offers: Offer[], media?: string): ModelBody | undefined {
137
- const ranked = offers
138
- .sort((a, b) => compare(a.media, b.media))
139
- .map((offer) => ({ declared: offer.media.trim().toLowerCase(), body: describeBody(offer) }))
140
- .sort((a, b) => byPreference(a.body, b.body))
151
+ const ranked = rankOffers(offers)
141
152
  const bodies = ranked.map((entry) => entry.body).filter((body, i, all) =>
142
153
  i === all.findIndex((other) => other.media === body.media))
143
154
 
144
- // A named media type is matched as declared first, so a range keeps its schema.
145
- const named = textOf(media)?.toLowerCase()
146
- const chosen = null == named ? bodies[0] :
147
- ranked.find((entry) => entry.declared === named)?.body ??
148
- bodies.find((body) => body.media.toLowerCase() === named) ??
149
- describeBody({ media: textOf(media) as string })
155
+ const chosen = chooseOffer(ranked, media)?.body ??
156
+ (null == textOf(media) ? undefined : describeBody({ media: textOf(media) as string }))
150
157
 
151
158
  if (null == chosen) {
152
159
  return undefined
@@ -157,6 +164,23 @@ function chooseBody(offers: Offer[], media?: string): ModelBody | undefined {
157
164
  }
158
165
 
159
166
 
167
+ function rankOffers(offers: Offer[]): Ranked[] {
168
+ return offers
169
+ .sort((a, b) => compare(a.media, b.media))
170
+ .map((offer) => ({ offer, declared: offer.media.trim().toLowerCase(), body: describeBody(offer) }))
171
+ .sort((a, b) => byPreference(a.body, b.body))
172
+ }
173
+
174
+
175
+ // A named media type is matched as declared first, so a range keeps its schema.
176
+ function chooseOffer(ranked: Ranked[], media?: string): Ranked | undefined {
177
+ const named = textOf(media)?.toLowerCase()
178
+ return null == named ? ranked[0] :
179
+ ranked.find((entry) => entry.declared === named) ??
180
+ ranked.find((entry) => entry.body.media.toLowerCase() === named)
181
+ }
182
+
183
+
160
184
  function openapiOffers(opdef: any): Offer[] {
161
185
  const content = opdef.requestBody?.content
162
186
  if (!isMap(content)) {
@@ -195,9 +219,11 @@ function swaggerOffers(def: any, pathdef: any, opdef: any): Offer[] {
195
219
  }
196
220
 
197
221
  const bodySchema = null == body ? undefined : (body.schema ?? {})
222
+ const required = form.filter((param) => true === param.required).map((param) => param.name)
198
223
  const formSchema = 0 === form.length ? undefined : {
199
224
  type: 'object',
200
225
  properties: Object.fromEntries(form.map((param) => [param.name, formProperty(param)])),
226
+ ...(0 < required.length ? { required } : {}),
201
227
  }
202
228
 
203
229
  const declared = listOf(Array.isArray(opdef.consumes) ? opdef.consumes : def.consumes)
@@ -415,8 +441,198 @@ function compare(a: string, b: string): number {
415
441
  }
416
442
 
417
443
 
444
+ // The schema the body step sends a request body with, when that body is JSON.
445
+ function jsonSchema(offers: Offer[], media?: string): any {
446
+ const chosen = chooseOffer(rankOffers(offers), media)
447
+ return 'json' === chosen?.body.kind ? chosen.offer.schema : undefined
448
+ }
449
+
450
+
451
+ function jsonRequestSchema(opdef: any): any {
452
+ return isMap(opdef) ? jsonSchema(openapiOffers(opdef)) : undefined
453
+ }
454
+
455
+
456
+ // The JSON schema a point's request body is sent with, under the media type
457
+ // the guide names, else the one the body step prefers.
458
+ function requestSchema(def: any, method: string, path: string, media?: string): any {
459
+ return jsonSchema(requestOffers(def, method, path) ?? [], media)
460
+ }
461
+
462
+
463
+ // The schema of the request body offered under the media type the guide
464
+ // names, of any kind, else the preferred JSON one.
465
+ function selectedRequestSchema(def: any, method: string, path: string, media?: string): any {
466
+ const offers = requestOffers(def, method, path) ?? []
467
+ const named = null == textOf(media) ? undefined : chooseOffer(rankOffers(offers), media)
468
+ return null == named ? jsonSchema(offers) : named.offer.schema
469
+ }
470
+
471
+
472
+ function arrayRequestSchema(def: any, method: string, path: string, media?: string): any {
473
+ return arrayShape(requestSchema(def, method, path, media))
474
+ }
475
+
476
+
477
+ // An array, or an allOf whose parts make one, or a oneOf or anyOf of one, or
478
+ // of arrays alone, beside any null: each fact from the first part that states
479
+ // it, outermost first, the items from the array's own part first, and null
480
+ // only where the composition admits it.
481
+ function arrayShape(schema: any): any {
482
+ const parts: any[] = []
483
+ const visit = (node: any) => {
484
+ if (isMap(node) && !parts.includes(node)) {
485
+ parts.push(node)
486
+ ; (Array.isArray(node.allOf) ? node.allOf : []).forEach(visit)
487
+ for (const one of [node.oneOf, node.anyOf]) {
488
+ const members = Array.isArray(one) ? one.filter((member: any) => !nullOnly(member)) : []
489
+ if (1 === members.length) visit(members[0])
490
+ else if (1 < members.length && members.every(arrayOnly)) parts.push(unionArray(members))
491
+ }
492
+ }
493
+ }
494
+ visit(schema)
495
+ const found = parts.find(isArray)
496
+ const list = null == found || null != found.type ? found : { ...found, type: 'array' }
497
+ if (null == list) {
498
+ return list
499
+ }
500
+ const items = list.items ?? parts.find((part) => null != part.items)?.items
501
+ const description = parts.find((part) => null != part.description)?.description
502
+ const types = [list.type].flat().filter((type: any) => 'null' !== type)
503
+ return {
504
+ ...list,
505
+ type: 1 === types.length ? types[0] : types,
506
+ ...(null == items ? {} : { items }),
507
+ ...(null == description ? {} : { description }),
508
+ nullable: admitsNull(schema),
509
+ }
510
+ }
511
+
512
+
513
+ // Null must pass the schema's own type, const and enum, every allOf part,
514
+ // exactly one oneOf member, and some anyOf member.
515
+ function admitsNull(schema: any): boolean {
516
+ if (!isMap(schema)) return false
517
+ const own = (null == schema.type || hasType(schema, 'null') || true === schema.nullable) &&
518
+ (!('const' in schema) || null === schema.const) &&
519
+ (!Array.isArray(schema.enum) || schema.enum.includes(null))
520
+ return own && listOf(schema.allOf).every(admitsNull) &&
521
+ (!Array.isArray(schema.oneOf) || 1 === schema.oneOf.filter(admitsNull).length) &&
522
+ (!Array.isArray(schema.anyOf) || schema.anyOf.some(admitsNull))
523
+ }
524
+
525
+
526
+ // Only null passes: by its type, a const or enum of null alone, an allOf part
527
+ // that passes only null, or a oneOf or anyOf every member of which does.
528
+ function nullOnly(schema: any): boolean {
529
+ if (!isMap(schema)) return false
530
+ if ('const' in schema) return null === schema.const
531
+ if (Array.isArray(schema.enum)) return 0 < schema.enum.length && schema.enum.every((v: any) => null === v)
532
+ if (listOf(schema.allOf).some(nullOnly)) return true
533
+ if ([schema.oneOf, schema.anyOf].some((one) => Array.isArray(one) && 0 < one.length && one.every(nullOnly))) {
534
+ return true
535
+ }
536
+ return null != schema.type && [schema.type].flat().every((type) => 'null' === type)
537
+ }
538
+
539
+
540
+ // Only arrays pass: by a const, or an enum, of arrays alone.
541
+ function arrayValued(schema: any): boolean {
542
+ return Array.isArray(schema.const) ||
543
+ (Array.isArray(schema.enum) && 0 < schema.enum.length && schema.enum.every(Array.isArray))
544
+ }
545
+
546
+
547
+ function isArray(schema: any): boolean {
548
+ return isMap(schema) && (hasType(schema, 'array') || (null == schema.type && arrayValued(schema)))
549
+ }
550
+
551
+
552
+ // Only arrays pass, beside any null: a union member that admits a string too is
553
+ // no array.
554
+ function arrayOnly(schema: any): boolean {
555
+ if (!isMap(schema)) return false
556
+ if (arrayValued(schema)) return true
557
+ const types = null == schema.type ? [] : [schema.type].flat()
558
+ return types.includes('array') && types.every((type: any) => 'array' === type || 'null' === type)
559
+ }
560
+
561
+
562
+ // The items are kept only where every member's items name one component.
563
+ function unionArray(members: any[]): any {
564
+ const ref = members[0].items?.['x-ref']
565
+ const one = null != ref && members.every((member) => ref === member.items?.['x-ref'])
566
+ return { type: 'array', ...(one ? { items: members[0].items } : {}) }
567
+ }
568
+
569
+
570
+ // A nullable array says so with `nullable` in OpenAPI 3.0, and a type list in 3.1.
571
+ function nullableType(schema: any): any {
572
+ return true === schema.nullable && !hasType(schema, 'null') ? [schema.type, 'null'].flat() : schema.type
573
+ }
574
+
575
+
576
+ const REQDATA_FIELD_RE = /^`reqdata\.([A-Za-z_][A-Za-z0-9_]*)`$/
577
+
578
+ // The field of the request data a point's JSON array body is sent from, when
579
+ // its request transform unwraps one.
580
+ function arrayCarrier(
581
+ def: any,
582
+ mpoint: ModelPoint,
583
+ media?: string,
584
+ ): { name: string, required: boolean, type: string | string[], description?: string } | undefined {
585
+ const req: any = mpoint.t?.req
586
+ const name = 'string' === typeof req ? req.match(REQDATA_FIELD_RE)?.[1] : undefined
587
+ const schema = null == name ? undefined : arrayRequestSchema(def, mpoint.m, mpoint.o, media)
588
+ if (null == name || null == schema) {
589
+ return undefined
590
+ }
591
+ const decl = requestDecl(def, mpoint.m, mpoint.o)
592
+ return {
593
+ name,
594
+ required: true === decl?.required,
595
+ type: nullableType(schema),
596
+ description: textOf(decl?.description) ?? textOf(schema.description),
597
+ }
598
+ }
599
+
600
+
601
+ // OpenAPI's request body, or the Swagger parameter that is one.
602
+ function requestDecl(def: any, method: string, path: string): any {
603
+ const pathdef = def?.paths?.[path]
604
+ const opdef = pathdef?.[String(method).toLowerCase()]
605
+ if (!isMap(opdef)) {
606
+ return undefined
607
+ }
608
+ return null != def.swagger ?
609
+ swaggerParams(pathdef, opdef).find((param) => 'body' === param.in) : opdef.requestBody
610
+ }
611
+
612
+
613
+ // Types compare by value, and a type list as the set it is, in one order.
614
+ function sameType(a: any, b: any): boolean {
615
+ return JSON.stringify(typeSet(a)) === JSON.stringify(typeSet(b))
616
+ }
617
+
618
+
619
+ function typeSet(type: any): any {
620
+ return !Array.isArray(type) ? type :
621
+ type.every((member: any) => 'string' === typeof member) ? [...type].sort() : type.map(typeSet)
622
+ }
623
+
624
+
418
625
  export {
419
626
  bodyTransform,
627
+ guideMedia,
420
628
  requestBody,
421
629
  responseBody,
630
+ jsonRequestSchema,
631
+ requestSchema,
632
+ arrayRequestSchema,
633
+ arrayCarrier,
634
+ requestDecl,
635
+ nullableType,
636
+ sameType,
637
+ selectedRequestSchema,
422
638
  }