@voxgig/apidef 8.23.0 → 8.25.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 (42) 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 +251 -86
  8. package/dist/guide/heuristic01.js.map +1 -1
  9. package/dist/model.d.ts +1 -0
  10. package/dist/transform/args.d.ts +4 -1
  11. package/dist/transform/args.js +42 -13
  12. package/dist/transform/args.js.map +1 -1
  13. package/dist/transform/body.d.ts +21 -2
  14. package/dist/transform/body.js +228 -15
  15. package/dist/transform/body.js.map +1 -1
  16. package/dist/transform/field.d.ts +3 -1
  17. package/dist/transform/field.js +154 -91
  18. package/dist/transform/field.js.map +1 -1
  19. package/dist/transform/operation.js +77 -24
  20. package/dist/transform/operation.js.map +1 -1
  21. package/dist/transform/select.js +10 -4
  22. package/dist/transform/select.js.map +1 -1
  23. package/dist/transform/top.d.ts +2 -1
  24. package/dist/transform/top.js +50 -3
  25. package/dist/transform/top.js.map +1 -1
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/dist/utility.d.ts +10 -1
  28. package/dist/utility.js +145 -13
  29. package/dist/utility.js.map +1 -1
  30. package/model/apidef.aontu +1 -0
  31. package/package.json +1 -1
  32. package/src/builder/entity/entity.ts +17 -15
  33. package/src/guide/guide.ts +5 -3
  34. package/src/guide/heuristic01.ts +316 -94
  35. package/src/model.ts +2 -0
  36. package/src/transform/args.ts +50 -14
  37. package/src/transform/body.ts +280 -16
  38. package/src/transform/field.ts +184 -91
  39. package/src/transform/operation.ts +97 -26
  40. package/src/transform/select.ts +13 -4
  41. package/src/transform/top.ts +59 -3
  42. package/src/utility.ts +177 -13
@@ -96,10 +96,19 @@ const topTransform = async function(
96
96
  // Institute of Chicago lists `api.artic.edu/api/v1` (no
97
97
  // https://). Go's net/http barfs on that with "unsupported
98
98
  // protocol scheme". Default to https when the URL has no scheme
99
- // and the value isn't a relative path.
99
+ // and is neither a relative path nor opened by a server variable.
100
100
  for (const server of (kit.info.servers as any[])) {
101
101
  if (!server || 'string' !== typeof server.url) continue
102
- server.url = withScheme(server.url)
102
+ const given = server.url
103
+ const braced = singleBraces(given)
104
+ server.url = withScheme(braced.url)
105
+ if (0 < braced.names.length) {
106
+ declareVariables(server, braced.names)
107
+ ctx.warn?.({
108
+ note: 'server URL `' + given + '` writes its variables in Postman\'s double' +
109
+ ' braces: taken as `' + server.url + '`',
110
+ })
111
+ }
103
112
  }
104
113
 
105
114
  // No server named: the `server` option, else a `base` variable the caller fills.
@@ -199,15 +208,61 @@ function resolveSummary(def: any): string | undefined {
199
208
  }
200
209
 
201
210
 
211
+ // A server variable that opens the URL stands for its origin, or for its
212
+ // scheme when `://` follows, so its value carries the scheme.
213
+ const LEADING_VARIABLE_RE = /^\{([^{}]+)\}($|[/?#]|:\/\/)/
214
+ const ORIGIN_DESCRIPTION =
215
+ 'The origin of the API, with its scheme, such as https://api.example.com.'
216
+
217
+
202
218
  function withScheme(url: string): string {
203
219
  const u = url.trim()
204
220
  if ('' === u || /^[a-z][a-z0-9+.-]*:\/\//i.test(u)) return url
205
221
  if (u.startsWith('//')) return 'https:' + u
206
- if (u.startsWith('/')) return url
222
+ if (u.startsWith('/') || LEADING_VARIABLE_RE.test(u)) return url
207
223
  return 'https://' + u
208
224
  }
209
225
 
210
226
 
227
+ function originVariable(url: string): string | undefined {
228
+ const lead = LEADING_VARIABLE_RE.exec(url.trim())
229
+ return null == lead || '://' === lead[2] ? undefined : lead[1]
230
+ }
231
+
232
+
233
+ // OpenAPI reads only the inner pair of Postman's `{{name}}` as the variable.
234
+ // Any other run of braces, or a name the SDKs cannot substitute, is kept.
235
+ const BRACE_RUN_RE = /\{+[A-Za-z0-9_]+\}+/g
236
+ const POSTMAN_VARIABLE_RE = /^\{\{([A-Za-z0-9_]+)\}\}$/
237
+
238
+
239
+ function singleBraces(url: string): { url: string, names: string[] } {
240
+ const names: string[] = []
241
+ const out = url.replace(BRACE_RUN_RE, (run: string) => {
242
+ const name = POSTMAN_VARIABLE_RE.exec(run)?.[1]
243
+ if (null == name) return run
244
+ if (!names.includes(name)) names.push(name)
245
+ return '{' + name + '}'
246
+ })
247
+ return { url: out, names }
248
+ }
249
+
250
+
251
+ // An empty default leaves the value to the SDK's caller.
252
+ function declareVariables(server: any, names: string[]) {
253
+ const declared = null == server.variables ? {} : server.variables
254
+ if (!isObject(declared)) return
255
+ const origin = originVariable(server.url)
256
+ const missing = names.filter((name) =>
257
+ !Object.prototype.hasOwnProperty.call(declared, name))
258
+ server.variables = {
259
+ ...declared,
260
+ ...Object.fromEntries(missing.map((name) => [name, origin === name ?
261
+ { default: '', description: ORIGIN_DESCRIPTION } : { default: '' }])),
262
+ }
263
+ }
264
+
265
+
211
266
  function resolveWebsite(def: any, servers: any[]): string | undefined {
212
267
  const info = def?.info ?? {}
213
268
 
@@ -506,6 +561,7 @@ function stringifyInfoScalars(node: any): any {
506
561
 
507
562
  export {
508
563
  topTransform,
564
+ stringifyInfoScalars,
509
565
  resolveSecurity,
510
566
  resolveSummary,
511
567
  ensureDescription,
package/src/utility.ts CHANGED
@@ -137,6 +137,7 @@ function formatJsonSrc(jsonsrc: string) {
137
137
 
138
138
 
139
139
  const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
140
+ 'aircraft': 'aircraft',
140
141
  'analytics': 'analytics',
141
142
  'analyses': 'analysis',
142
143
  'appendices': 'appendix',
@@ -153,12 +154,14 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
153
154
  'crises': 'crisis',
154
155
  'criteria': 'criterion',
155
156
  // 'data': 'datum',
157
+ 'deer': 'deer',
156
158
  'diagnoses': 'diagnosis',
157
159
  'doses': 'dose',
158
160
  'douches': 'douche',
159
161
  'enterprises': 'enterprise',
160
162
  'exercises': 'exercise',
161
163
  'feet': 'foot',
164
+ 'fish': 'fish',
162
165
  'franchises': 'franchise',
163
166
  'furnaces': 'furnace',
164
167
  'geese': 'goose',
@@ -172,6 +175,7 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
172
175
  'matrices': 'matrix',
173
176
  'men': 'man',
174
177
  'mice': 'mouse',
178
+ 'moose': 'moose',
175
179
  'moustaches': 'moustache',
176
180
  'movies': 'movie',
177
181
  'mustaches': 'mustache',
@@ -181,6 +185,7 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
181
185
  'nurses': 'nurse',
182
186
  'oases': 'oasis',
183
187
  'oboes': 'oboe',
188
+ 'oxen': 'ox',
184
189
  'pastiches': 'pastiche',
185
190
  'pauses': 'pause',
186
191
  'phases': 'phase',
@@ -191,11 +196,13 @@ const IRREGULARS: Record<string, string> = Object.assign(Object.create(null), {
191
196
  'psyches': 'psyche',
192
197
  'purchases': 'purchase',
193
198
  'purses': 'purse',
199
+ 'quizzes': 'quiz',
194
200
  'releases': 'release',
195
201
  'roses': 'rose',
196
202
  'people': 'person',
197
203
  'phenomena': 'phenomenon',
198
204
  'series': 'series',
205
+ 'sheep': 'sheep',
199
206
  'shoes': 'shoe',
200
207
  'sources': 'source',
201
208
  'species': 'species',
@@ -223,6 +230,9 @@ const F_PLURAL_STEMS = [
223
230
  // today, but the sort makes any future entry safe by construction.
224
231
  const IRREGULAR_KEYS = Object.keys(IRREGULARS).sort((a, b) => b.length - a.length)
225
232
 
233
+ // Nouns in -o whose plural takes -es; the rest take -s (photos).
234
+ const OES_NOUNS = ['echo', 'embargo', 'hero', 'potato', 'tomato', 'torpedo', 'veto']
235
+
226
236
 
227
237
  function matchCase(source: string, target: string): string {
228
238
  if (source === source.toLowerCase()) return target.toLowerCase()
@@ -368,6 +378,38 @@ function depluralize(word: string): string {
368
378
  }
369
379
 
370
380
 
381
+ // The plural of a snake name's last word that depluralize reads back as the
382
+ // name, so the two cannot disagree.
383
+ function pluralize(word: string): string {
384
+ if (null == word || '' === word) {
385
+ return word
386
+ }
387
+
388
+ const cut = word.lastIndexOf('_') + 1
389
+ const last = word.slice(cut)
390
+ const lower = last.toLowerCase()
391
+
392
+ const plurals = [
393
+ ...pluralsOf(CUSTOM_PLURALS, lower),
394
+ ...pluralsOf(IRREGULARS, lower),
395
+ ...(/[^aeiou]y$/.test(lower) ? [lower.slice(0, -1) + 'ies'] : []),
396
+ ...(/fe?$/.test(lower) ? [lower.replace(/fe?$/, 'ves')] : []),
397
+ ...(/(s|x|z|ch|sh)$/.test(lower) || OES_NOUNS.includes(lower) ? [lower + 'es'] : []),
398
+ lower + 's',
399
+ ].map((plural) => word.slice(0, cut) + matchCase(last, plural))
400
+
401
+ return plurals.find((plural) => depluralize(plural) === word) ??
402
+ plurals[plurals.length - 1]
403
+ }
404
+
405
+
406
+ function pluralsOf(plurals: Record<string, string>, singular: string): string[] {
407
+ return Object.keys(plurals)
408
+ .filter((plural) => plurals[plural].toLowerCase() === singular)
409
+ .sort()
410
+ }
411
+
412
+
371
413
  function find(obj: any, qkey: string): any[] {
372
414
  const vals: any[] = []
373
415
  const seen = new WeakSet<object>()
@@ -1012,6 +1054,13 @@ function canonizeField(s: string) {
1012
1054
  }
1013
1055
 
1014
1056
 
1057
+ // Field names are WIRE identifiers: the entity-name canonizer would rename
1058
+ // modelType to model_type and items to item, keys the server never sends.
1059
+ function fieldName(prop: string): string {
1060
+ return canonizeField(normalizeFieldName(prop))
1061
+ }
1062
+
1063
+
1015
1064
  function stripSchemaNamespace(name: string): string {
1016
1065
  if (null == name || !name.includes('.')) return name
1017
1066
  const segs = name.split('.')
@@ -1613,30 +1662,112 @@ export type {
1613
1662
  }
1614
1663
 
1615
1664
 
1616
- // A response property only "wraps" the entity when it is itself a structured
1617
- // value that could contain the entity: an object, an array, a $ref, or a
1618
- // composed (allOf/oneOf/anyOf) schema. A scalar property (string, integer,
1619
- // number, boolean) that merely shares the entity's name is a field of the
1620
- // entity, not a wrapper, so the response must not be unwrapped down to it.
1665
+ // What an allOf member holds when it only describes. The siblings of a $ref
1666
+ // are ignored in OpenAPI 3.0, so a property describes one in an allOf.
1667
+ const ANNOTATION_KEYS = new Set(['description', 'title', 'example', 'nullable', 'deprecated'])
1668
+
1669
+ const SCALAR_TYPES = new Set(['string', 'integer', 'number', 'boolean'])
1670
+
1671
+
1672
+ // An allOf of one scalar and annotations is that scalar, under the
1673
+ // annotations and then the property's own keys. Any other allOf is kept.
1674
+ function collapseScalarAllOf(property: any): any {
1675
+ const members = property?.allOf
1676
+ if (!Array.isArray(members)) {
1677
+ return property
1678
+ }
1679
+
1680
+ const valued = members.filter((member: any) => !isAnnotation(member))
1681
+ if (1 !== valued.length || !isScalarSchema(valued[0])) {
1682
+ return property
1683
+ }
1684
+
1685
+ const { allOf: _members, ...own } = property
1686
+ return Object.assign({}, valued[0], ...members.filter(isAnnotation), own)
1687
+ }
1688
+
1689
+
1690
+ function isAnnotation(member: any): boolean {
1691
+ return null != member && 'object' === typeof member && !Array.isArray(member) &&
1692
+ Object.keys(member).every((key: string) => ANNOTATION_KEYS.has(key))
1693
+ }
1694
+
1695
+
1696
+ function isScalarSchema(schema: any): boolean {
1697
+ if (null == schema || 'object' !== typeof schema || Array.isArray(schema) ||
1698
+ null != schema.allOf || null != schema.oneOf || null != schema.anyOf) {
1699
+ return false
1700
+ }
1701
+ const types = (Array.isArray(schema.type) ? schema.type : [schema.type])
1702
+ .filter((type: any) => 'null' !== type)
1703
+ return 1 === types.length && SCALAR_TYPES.has(types[0])
1704
+ }
1705
+
1706
+
1707
+ // A response property only "wraps" the entity when it is a structured value
1708
+ // that could contain it: an object, an array, a $ref, or a composition that
1709
+ // could hold one. A scalar that shares the entity's name is a field, however
1710
+ // it is composed, so the response is not unwrapped down to it.
1621
1711
  function isEntityWrapperProp(propSchema: any): boolean {
1622
- if (null == propSchema || 'object' !== typeof propSchema) {
1712
+ const prop = collapseScalarAllOf(propSchema)
1713
+ if (null == prop || 'object' !== typeof prop) {
1623
1714
  return false
1624
1715
  }
1625
- if (null != propSchema.$ref) {
1716
+ if (null != prop.$ref) {
1626
1717
  return true
1627
1718
  }
1628
- if (null != propSchema.properties ||
1629
- null != propSchema.items ||
1630
- null != propSchema.allOf ||
1631
- null != propSchema.oneOf ||
1632
- null != propSchema.anyOf) {
1719
+ if (null != prop.properties ||
1720
+ null != prop.items ||
1721
+ null != prop.allOf ||
1722
+ holdsStructuredBranch(prop.oneOf) ||
1723
+ holdsStructuredBranch(prop.anyOf)) {
1633
1724
  return true
1634
1725
  }
1635
- const t = propSchema.type
1726
+ const t = prop.type
1636
1727
  return 'object' === t || 'array' === t
1637
1728
  }
1638
1729
 
1639
1730
 
1731
+ // A null branch only makes a union of scalars nullable.
1732
+ function holdsStructuredBranch(branches: any): boolean {
1733
+ return null != branches && !(Array.isArray(branches) && 0 < branches.length &&
1734
+ branches.every((branch: any) => isScalarSchema(branch) || 'null' === branch?.type))
1735
+ }
1736
+
1737
+
1738
+ // The key each item of a list response wraps the record under, where the item
1739
+ // holds nothing else, as each item of a Maxio list holds one record under the
1740
+ // name of its type.
1741
+ function itemEnvelopeKey(schema: any, names: string[]): string | null {
1742
+ if ('array' !== schema?.type) {
1743
+ return null
1744
+ }
1745
+ const keys = keysof(mergedProperties(schema.items))
1746
+ const key = keys[0]
1747
+ if (1 !== keys.length || !names.includes(key) || !/^[^.`$]+$/.test(key)) {
1748
+ return null
1749
+ }
1750
+ const prop = collapseScalarAllOf(mergedProperties(schema.items)?.[key])
1751
+ return isEntityWrapperProp(prop) && 'array' !== prop?.type && null == prop?.items ?
1752
+ key : null
1753
+ }
1754
+
1755
+
1756
+ // The response transform that answers each item's record under its key.
1757
+ function itemEnvelopeTransform(key: string): any[] {
1758
+ return ['`$EACH`', 'body', { '`$MERGE`': '`.' + key + '`' }]
1759
+ }
1760
+
1761
+
1762
+ // The key of an itemEnvelopeTransform, else null.
1763
+ function itemEnvelopeOf(res: any): string | null {
1764
+ const merge = Array.isArray(res) && 3 === res.length &&
1765
+ '`$EACH`' === res[0] && 'body' === res[1] ? res[2]?.['`$MERGE`'] : null
1766
+ const m = 'string' === typeof merge ? merge.match(/^`\.([^.`$]+)`$/) : null
1767
+ return null == m ? null : m[1]
1768
+ }
1769
+
1770
+
1640
1771
  function envelopeProp(resprops: any, opname: string): string | null {
1641
1772
  const keys = keysof(resprops)
1642
1773
  if (0 === keys.length) {
@@ -1973,6 +2104,30 @@ function closedBodyTransform(schema: any): Record<string, string> | null {
1973
2104
  return out
1974
2105
  }
1975
2106
 
2107
+
2108
+ // The key a request transform sends the whole record under, else null.
2109
+ function requestWrapperOf(req: any): string | null {
2110
+ if (null == req || 'object' !== typeof req || Array.isArray(req)) {
2111
+ return null
2112
+ }
2113
+ const keys = Object.keys(req)
2114
+ return 1 === keys.length && '`reqdata`' === req[keys[0]] ? keys[0] : null
2115
+ }
2116
+
2117
+ // A body wraps the record under the entity's name only when that is all it
2118
+ // holds, and it is structured; otherwise the name is one field of the record,
2119
+ // such as the container in SaladCloud's container group create. A CLOSED body
2120
+ // names every property the server accepts, so the body is those properties,
2121
+ // not the whole payload, which also carries the op's path parameters.
2122
+ function bodyRequestTransform(schema: any, names: string[]): any {
2123
+ if (null == schema) return undefined
2124
+ const props = schema.properties
2125
+ const wrapped = names.find((name: string) => null != name && '' !== name &&
2126
+ isEntityWrapperProp(props?.[name]) && keysof(props).every((k: string) => k === name))
2127
+ return null != wrapped ? { [wrapped]: '`reqdata`' } : (closedBodyTransform(schema) ?? undefined)
2128
+ }
2129
+
2130
+
1976
2131
  function firstSentence(text: string): string {
1977
2132
  const collapsed = text.replace(/\s+/g, ' ').trim()
1978
2133
  const m = collapsed.match(/^(.+?[.!?])(\s|$)/)
@@ -1986,11 +2141,13 @@ function firstSentence(text: string): string {
1986
2141
 
1987
2142
 
1988
2143
  export {
2144
+ bodyRequestTransform,
1989
2145
  nom,
1990
2146
  getdlog,
1991
2147
  loadFile,
1992
2148
  formatJsonSrc,
1993
2149
  depluralize,
2150
+ pluralize,
1994
2151
  setCustomPlurals,
1995
2152
  clearCustomPlurals,
1996
2153
  find,
@@ -2003,6 +2160,7 @@ export {
2003
2160
  CANON_ONE,
2004
2161
  canonize,
2005
2162
  canonizeField,
2163
+ fieldName,
2006
2164
  canonizeCmpName,
2007
2165
  stripSchemaNamespace,
2008
2166
  sanitizeSlug,
@@ -2029,12 +2187,18 @@ export {
2029
2187
  getModelPath,
2030
2188
  sortedKeys,
2031
2189
  sortedEntries,
2190
+ collapseScalarAllOf,
2032
2191
  isEntityWrapperProp,
2192
+ itemEnvelopeKey,
2193
+ itemEnvelopeTransform,
2194
+ itemEnvelopeOf,
2033
2195
  envelopeProp,
2034
2196
  envelopeItemRef,
2035
2197
  composedEnvelopeProp,
2198
+ propIsList,
2036
2199
  mergedProperties,
2037
2200
  closedBodyTransform,
2201
+ requestWrapperOf,
2038
2202
  untaggedUnionBranches,
2039
2203
  scanUntaggedUnion,
2040
2204
  firstSentence,