@voxgig/apidef 8.30.1 → 8.32.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.
@@ -40,6 +40,7 @@ const argsTransform: Transform = async function(
40
40
  ): Promise<TransformResult> {
41
41
  const { apimodel, def } = ctx
42
42
  const kit: KitModel = apimodel.main[KIT]
43
+ const swagger = null != def?.swagger
43
44
 
44
45
  let msg = 'args '
45
46
 
@@ -75,7 +76,7 @@ const argsTransform: Transform = async function(
75
76
  argdefs.push(...routeArgdefs(def, mpoint))
76
77
  }
77
78
 
78
- resolveArgs(ctx, ment, mop, mpoint, argdefs)
79
+ resolveArgs(ctx, ment, mop, mpoint, argdefs, swagger)
79
80
  })
80
81
 
81
82
  })
@@ -98,7 +99,7 @@ function routeArgdefs(def: any, mpoint: ModelPoint): ParameterDef[] {
98
99
  function routeArgNames(def: any, mpoint: ModelPoint): string[] {
99
100
  const route = { ...mpoint, g: {} } as ModelPoint
100
101
  resolveArgs(undefined, { name: '' } as ModelEntity, { name: '', points: [] } as unknown as ModelOp, route,
101
- routeArgdefs(def, mpoint))
102
+ routeArgdefs(def, mpoint), null != def?.swagger)
102
103
  return Object.values(route.g).flat().map((arg: any) => arg.n)
103
104
  }
104
105
 
@@ -130,7 +131,8 @@ const ARG_KIND: Record<string, ModelArg["k"]> = {
130
131
 
131
132
  function resolveArgs(
132
133
  ctx: any,
133
- ment: ModelEntity, mop: ModelOp, mpoint: ModelPoint, argdefs: ParameterDef[]
134
+ ment: ModelEntity, mop: ModelOp, mpoint: ModelPoint, argdefs: ParameterDef[],
135
+ swagger: boolean,
134
136
  ) {
135
137
  const touchedKeys = new Set<string>()
136
138
  const placeholders = [...String(mpoint.o ?? '').matchAll(/\{([^}]+)\}/g)].map((m) => m[1])
@@ -205,6 +207,12 @@ function resolveArgs(
205
207
  marg.t = ['`$ONE`', '`$NULL`', marg.t]
206
208
  }
207
209
 
210
+ const sent = path ? undefined : argSerialization(argdef, kind, swagger)
211
+ if (null != sent) {
212
+ marg.style = sent.style
213
+ marg.explode = sent.explode
214
+ }
215
+
208
216
  const argsKey = (marg.k === 'param' ? 'params' : marg.k) as keyof typeof mpoint.g
209
217
  let kindargs = (mpoint.g[argsKey] = mpoint.g[argsKey] ?? [])
210
218
  kindargs.push(marg)
@@ -245,6 +253,32 @@ function resolveArgs(
245
253
  }
246
254
 
247
255
 
256
+ // The OpenAPI style for each Swagger collection format, where `tsv` has none.
257
+ const SWAGGER_STYLE: Record<string, string> = {
258
+ ssv: 'spaceDelimited', pipes: 'pipeDelimited', tsv: 'tabDelimited',
259
+ }
260
+
261
+
262
+ // How a query, header or cookie argument sends a list or a map: as declared,
263
+ // else as its location does, where only a form explodes. A Swagger array
264
+ // declares a collection format instead, `csv` unless stated. A parameter with
265
+ // `content` is sent as its media type says, so it has neither.
266
+ function argSerialization(argdef: any, kind: string, swagger: boolean):
267
+ { style: string, explode: boolean } | undefined {
268
+ const location = 'header' === kind ? 'simple' : 'form'
269
+ if (swagger && 'array' === argdef.type) {
270
+ const format = 'string' === typeof argdef.collectionFormat ? argdef.collectionFormat : 'csv'
271
+ return 'multi' === format ? { style: 'form', explode: true } :
272
+ { style: SWAGGER_STYLE[format] ?? location, explode: false }
273
+ }
274
+ if (null == argdef.schema && null != argdef.content) {
275
+ return undefined
276
+ }
277
+ const style = 'string' === typeof argdef.style && '' !== argdef.style ? argdef.style : location
278
+ return { style, explode: 'boolean' === typeof argdef.explode ? argdef.explode : 'form' === style }
279
+ }
280
+
281
+
248
282
  // Type facts sit on a Swagger 2 parameter itself, and under `schema` in
249
283
  // OpenAPI 3.
250
284
  function paramSchema(argdef: any): any {
@@ -621,9 +621,10 @@ function unionArray(members: any[]): any {
621
621
  }
622
622
 
623
623
 
624
- // A nullable array says so with `nullable` in OpenAPI 3.0, and a type list in 3.1.
624
+ // The nullable flag adds null once to the declared type.
625
625
  function nullableType(schema: any): any {
626
- return true === schema.nullable && !hasType(schema, 'null') ? [schema.type, 'null'].flat() : schema.type
626
+ return true === schema.nullable && null != schema.type && !hasType(schema, 'null') ?
627
+ [schema.type, 'null'].flat() : schema.type
627
628
  }
628
629
 
629
630
 
@@ -11,7 +11,7 @@ import {
11
11
  itemEnvelopeOf, isFileType, nonNullType,
12
12
  } from '../utility'
13
13
 
14
- import { arrayCarrier, guideMedia, requestFieldSchema, sameType } from './body'
14
+ import { arrayCarrier, guideMedia, requestFieldSchema, sameType, nullableType } from './body'
15
15
 
16
16
  import { KIT } from '../types'
17
17
 
@@ -716,7 +716,7 @@ function modelField(fielddef: SchemaDef): ModelField {
716
716
  const mfield: ModelField = {
717
717
  n: name,
718
718
  h: humanTitle(name),
719
- t: inferFieldType(name, validator(fielddef.type)),
719
+ t: inferFieldType(name, validator(nullableType(fielddef))),
720
720
  r: !!fielddef.required,
721
721
  op: {},
722
722
  }
@@ -996,7 +996,7 @@ function composedFields(schema: any): any[] {
996
996
  const decls: Record<string, any[]> = Object.create(null)
997
997
  for (const part of parts) {
998
998
  each(part.properties, (property: any) => {
999
- (decls[property.key$] = decls[property.key$] ?? []).push(collapseScalarAllOf(property))
999
+ (decls[property.key$] = decls[property.key$] ?? []).push(fieldSchema(property))
1000
1000
  })
1001
1001
  }
1002
1002
 
@@ -1008,6 +1008,20 @@ function composedFields(schema: any): any[] {
1008
1008
  }
1009
1009
 
1010
1010
 
1011
+ function fieldSchema(property: any): any {
1012
+ const collapsed = collapseScalarAllOf(property)
1013
+ if (collapsed === property) {
1014
+ return property
1015
+ }
1016
+ const nullable = [property, ...property.allOf].every((part: any) =>
1017
+ null == part.type || true === part.nullable ||
1018
+ (Array.isArray(part.type) ? part.type : [part.type]).includes('null'))
1019
+ const types = (Array.isArray(collapsed.type) ? collapsed.type : [collapsed.type])
1020
+ .filter((type: any) => nullable || 'null' !== type)
1021
+ return { ...collapsed, nullable, type: 1 === types.length ? types[0] : types }
1022
+ }
1023
+
1024
+
1011
1025
  function mergeDeclarations(decls: any[]): any {
1012
1026
  const merged: any = {}
1013
1027
  for (const decl of decls) {
@@ -8,6 +8,7 @@ import { getelem } from '@voxgig/struct'
8
8
 
9
9
  import {
10
10
  nom,
11
+ nonNullType,
11
12
  } from '../utility'
12
13
 
13
14
 
@@ -331,7 +332,7 @@ function firstTextField(ent: ModelEntity, op?: ModelOp) {
331
332
  // one holding bytes, never does. Fields are sorted by name, so the choice
332
333
  // is alphabetical accident: solar's planet, once its spec declared the
333
334
  // server-assigned `forbidReason`, marked that instead of `kind`.
334
- if ('`$STRING`' === field.t && true !== identity[field.n] && true !== field.ro &&
335
+ if ('`$STRING`' === nonNullType(field.t) && true !== identity[field.n] && true !== field.ro &&
335
336
  'binary' !== field.fo && true !== paramNames[field.n]) {
336
337
  return field
337
338
  }
package/src/types.ts CHANGED
@@ -315,6 +315,7 @@ type GuidePathOp = {
315
315
  transform: {
316
316
  req: any
317
317
  res: any
318
+ page?: Record<string, string>
318
319
  }
319
320
  }
320
321
 
package/src/utility.ts CHANGED
@@ -1046,6 +1046,7 @@ function validator(torig: undefined | string | string[]): any {
1046
1046
  }
1047
1047
  }
1048
1048
 
1049
+
1049
1050
  // The type a field holds when it is not null: the type itself, or the one
1050
1051
  // member of a union beside `$NULL`. Any other union has none.
1051
1052
  function nonNullType(type: any): string | undefined {
@@ -1282,7 +1283,15 @@ const NUMBER_NAME_RE = /^(latitude$|longitude$|lat$|lng$|lon$|price$|amount$|rat
1282
1283
  const STRING_NAME_RE = /^(url$|href$|link$|uri$|email$|name$|title$|description$|slug$|path$|label$|username$|password$|token$|key$)/
1283
1284
  const ID_NAME_RE = /(_id$|^id$)/
1284
1285
 
1285
- function inferFieldType(name: string, specType: string): string {
1286
+ function inferFieldType(name: string, specType: any): any {
1287
+ // A nullable type is inferred by its other member, and keeps its null.
1288
+ const own = nonNullType(specType)
1289
+ if (null != own && own !== specType) {
1290
+ const inferred = inferFieldType(name, own)
1291
+ return inferred === own ? specType :
1292
+ [specType[0], specType[1].map((member: any) => own === member ? inferred : member)]
1293
+ }
1294
+
1286
1295
  // Only override $ANY, or $STRING for boolean-patterned names
1287
1296
  if ('`$ANY`' === specType) {
1288
1297
  if (BOOLEAN_NAME_RE.test(name)) return '`$BOOLEAN`'
@@ -2229,6 +2238,62 @@ function pageRecords(schema: any): any {
2229
2238
  }
2230
2239
 
2231
2240
 
2241
+ // The names that hold each part of a page's metadata, preferred first.
2242
+ const PAGE_ROLES: [string, string[]][] = [
2243
+ ['total', ['total', 'totalcount', 'totalresults', 'totalitems', 'totalhits', 'count']],
2244
+ ['cursor', ['nextcursor', 'cursor', 'nextpagetoken', 'nexttoken', 'endcursor']],
2245
+ ['more', ['hasmore', 'hasnext', 'hasnextpage']],
2246
+ ['next', ['next', 'nexturl', 'nextlink', 'nextpageurl']],
2247
+ ]
2248
+
2249
+
2250
+ function isPageRoleName(name: string): boolean {
2251
+ const norm = name.toLowerCase().replace(/[_-]/g, '')
2252
+ return PAGE_ROLES.some(([, names]) => names.includes(norm))
2253
+ }
2254
+
2255
+
2256
+ // Where a page keeps its total, the cursor or link to the next page, and
2257
+ // whether there is one: beside the records, else in the page's metadata.
2258
+ function pageTransform(props: any, records: string): Record<string, string> | undefined {
2259
+ if (null == props || 'object' !== typeof props) {
2260
+ return undefined
2261
+ }
2262
+ const levels: [string, any][] = [['', props]]
2263
+ for (const k of keysof(props)) {
2264
+ const meta = k !== records && isPageMetaProp(k) ? mergedProperties(props[k]) : undefined
2265
+ if (null != meta) {
2266
+ levels.push([k + '.', meta])
2267
+ }
2268
+ }
2269
+ // A `count` beside data of its own counts that data, as GitHub's traffic does.
2270
+ const ownData = holdsOwnData(Object.fromEntries(
2271
+ Object.entries(props).filter(([k]) => !isPageRoleName(k))))
2272
+ const find = (name: string): string | undefined => {
2273
+ for (const [prefix, level] of levels) {
2274
+ if ('count' === name && '' === prefix && ownData) {
2275
+ continue
2276
+ }
2277
+ const key = keysof(level).find((k: string) => ('' !== prefix || k !== records) &&
2278
+ name === k.toLowerCase().replace(/[_-]/g, '') &&
2279
+ !isObjectSchema(level[k]) && false === propIsList(level[k]))
2280
+ if (null != key) {
2281
+ return '`body.' + prefix + key + '`'
2282
+ }
2283
+ }
2284
+ return undefined
2285
+ }
2286
+ const page: Record<string, string> = {}
2287
+ for (const [role, names] of PAGE_ROLES) {
2288
+ const path = names.map(find).find((found) => null != found)
2289
+ if (null != path) {
2290
+ page[role] = path
2291
+ }
2292
+ }
2293
+ return 0 < keysof(page).length ? page : undefined
2294
+ }
2295
+
2296
+
2232
2297
  function answersPage(schema: any): boolean {
2233
2298
  return null != pageRecords(schema)
2234
2299
  }
@@ -2498,6 +2563,8 @@ export {
2498
2563
  envelopeItemRef,
2499
2564
  composedEnvelopeProp,
2500
2565
  pageRecords,
2566
+ pageTransform,
2567
+ PAGE_ROLES,
2501
2568
  answersPage,
2502
2569
  answersRecordMap,
2503
2570
  propIsList,