@voxgig/apidef 8.25.1 → 8.25.3

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.
@@ -5,7 +5,7 @@ import type { TransformResult, Transform } from '../transform'
5
5
  import { KIT } from '../types'
6
6
 
7
7
  import {
8
- fieldName, guideActive, mergedProperties, requestWrapperOf, sortedKeys,
8
+ fieldName, guideActive, isFileType, mergedProperties, requestWrapperOf, sortedKeys,
9
9
  } from '../utility'
10
10
 
11
11
  import type {
@@ -236,7 +236,7 @@ function swaggerOffers(def: any, pathdef: any, opdef: any): Offer[] {
236
236
  .filter((media) => null != textOf(media))
237
237
  const consumes = 0 < declared.length ? declared : [
238
238
  null != body ? JSON_MEDIA :
239
- form.some((param) => 'file' === param.type) ? MULTIPART_MEDIA : FORM_MEDIA
239
+ form.some(sendsFile) ? MULTIPART_MEDIA : FORM_MEDIA
240
240
  ]
241
241
 
242
242
  return consumes.map((media: string) => ({
@@ -247,6 +247,11 @@ function swaggerOffers(def: any, pathdef: any, opdef: any): Offer[] {
247
247
  }
248
248
 
249
249
 
250
+ function sendsFile(param: any): boolean {
251
+ return isFileType(param.type) || (hasType(param, 'array') && isFileType(param.items?.type))
252
+ }
253
+
254
+
250
255
  // An operation's parameter replaces the path's of the same location and name.
251
256
  function swaggerParams(pathdef: any, opdef: any): any[] {
252
257
  const key = (param: any) => (textOf(param.in) ?? '') + '\u0000' + (textOf(param.name) ?? '')
@@ -333,7 +338,7 @@ function bodyField(name: string, prop: any, encoding: any, arrays: string): Mode
333
338
  field.binary = true
334
339
  }
335
340
  if (list) {
336
- const join = arrayJoin(prop, encoding, arrays)
341
+ const join = field.binary ? undefined : arrayJoin(prop, encoding, arrays)
337
342
  if (null == join) {
338
343
  field.list = true
339
344
  }
@@ -384,7 +389,7 @@ function rawBinary(type: string, schema: any): boolean {
384
389
 
385
390
  function binarySchema(schema: any): boolean {
386
391
  return isMap(schema) && !encodedText(schema) &&
387
- ('binary' === schema.format || 'file' === schema.type || null != schema.contentMediaType)
392
+ ('binary' === schema.format || isFileType(schema.type) || null != schema.contentMediaType)
388
393
  }
389
394
 
390
395
 
@@ -454,11 +459,6 @@ function jsonSchema(offers: Offer[], media?: string): any {
454
459
  }
455
460
 
456
461
 
457
- function jsonRequestSchema(opdef: any): any {
458
- return isMap(opdef) ? jsonSchema(openapiOffers(opdef)) : undefined
459
- }
460
-
461
-
462
462
  // The JSON schema a point's request body is sent with, under the media type
463
463
  // the guide names, else the one the body step prefers.
464
464
  function requestSchema(def: any, method: string, path: string, media?: string): any {
@@ -467,11 +467,11 @@ function requestSchema(def: any, method: string, path: string, media?: string):
467
467
 
468
468
 
469
469
  // The schema of the request body offered under the media type the guide
470
- // names, of any kind, else the preferred JSON one.
470
+ // names, else of the one the body step prefers, of any kind.
471
471
  function selectedRequestSchema(def: any, method: string, path: string, media?: string): any {
472
- const offers = requestOffers(def, method, path) ?? []
473
- const named = null == textOf(media) ? undefined : chooseOffer(rankOffers(offers), media)
474
- return null == named ? jsonSchema(offers) : named.offer.schema
472
+ const ranked = rankOffers(requestOffers(def, method, path) ?? [])
473
+ const named = null == textOf(media) ? undefined : chooseOffer(ranked, media)
474
+ return (named ?? chooseOffer(ranked))?.offer.schema
475
475
  }
476
476
 
477
477
 
@@ -504,14 +504,22 @@ function bodyFields(def: any, mpoint: ModelPoint, media?: string): string[] | fa
504
504
 
505
505
 
506
506
  // A body that may be one of several objects declares the properties of each.
507
- function declaredProperties(schema: any, seen: Set<any> = new Set()): string[] {
507
+ // One the body marks readOnly anywhere is never sent, so it is left out.
508
+ function declaredProperties(schema: any): string[] {
509
+ const declared = propertyDeclarations(schema, new Set())
510
+ const readOnly = new Set(declared.filter(([, prop]) => true === prop?.readOnly).map(([name]) => name))
511
+ return declared.map(([name]) => name).filter((name) => !readOnly.has(name))
512
+ }
513
+
514
+
515
+ function propertyDeclarations(schema: any, seen: Set<any>): [string, any][] {
508
516
  if (!isMap(schema) || seen.has(schema)) {
509
517
  return []
510
518
  }
511
519
  seen.add(schema)
512
- return (isMap(schema.properties) ? Object.keys(schema.properties) : [])
520
+ return (isMap(schema.properties) ? Object.entries(schema.properties) as [string, any][] : [])
513
521
  .concat(['allOf', 'oneOf', 'anyOf'].flatMap((key) =>
514
- listOf(schema[key]).flatMap((member: any) => declaredProperties(member, seen))))
522
+ listOf(schema[key]).flatMap((member: any) => propertyDeclarations(member, seen))))
515
523
  }
516
524
 
517
525
 
@@ -674,7 +682,6 @@ export {
674
682
  guideMedia,
675
683
  requestBody,
676
684
  responseBody,
677
- jsonRequestSchema,
678
685
  requestSchema,
679
686
  arrayRequestSchema,
680
687
  arrayCarrier,
@@ -8,7 +8,7 @@ import {
8
8
  validator, fieldName, inferFieldType, envelopeProp,
9
9
  composedEnvelopeProp, mergedProperties, canonizeCmpName,
10
10
  scanUntaggedUnion, firstSentence, humanTitle, collapseScalarAllOf,
11
- itemEnvelopeOf,
11
+ itemEnvelopeOf, isFileType, nonNullType,
12
12
  } from '../utility'
13
13
 
14
14
  import { arrayCarrier, guideMedia, requestFieldSchema, sameType } from './body'
@@ -621,6 +621,9 @@ function modelField(fielddef: SchemaDef): ModelField {
621
621
  if ('string' === typeof ffmt && '' !== ffmt.trim()) {
622
622
  mfield.fo = ffmt.trim()
623
623
  }
624
+ else if (isFileType(fielddef.type)) {
625
+ mfield.fo = 'binary'
626
+ }
624
627
 
625
628
  // Record an untagged union under this field. The field is already typed
626
629
  // openly ($ANY/$ARRAY/$OBJECT) because there is nothing to narrow it to;
@@ -1043,16 +1046,28 @@ function mergeField(
1043
1046
  existingField.sh = newField.sh
1044
1047
  }
1045
1048
 
1046
- for (const flag of ['ro', 'wo', 'de', 'fo'] as const) {
1049
+ for (const flag of ['ro', 'wo', 'de'] as const) {
1047
1050
  if (null == existingField[flag] && null != newField[flag]) {
1048
- (existingField as any)[flag] = newField[flag]
1051
+ existingField[flag] = newField[flag]
1049
1052
  }
1050
1053
  }
1051
1054
 
1055
+ // A format describes its own type, so another type's format would mislabel the field.
1056
+ if (null == existingField.fo && null != newField.fo &&
1057
+ sameType(ownType(existingField.t), ownType(newField.t))) {
1058
+ existingField.fo = newField.fo
1059
+ }
1060
+
1052
1061
  return existingField
1053
1062
  }
1054
1063
 
1055
1064
 
1065
+ // The type beside a nullable union's `$NULL`, else the type itself.
1066
+ function ownType(type: any): any {
1067
+ return nonNullType(type) ?? type
1068
+ }
1069
+
1070
+
1056
1071
  export {
1057
1072
  fieldTransform,
1058
1073
  inferFieldsFromExamples,
@@ -324,13 +324,13 @@ function firstTextField(ent: ModelEntity, op?: ModelOp) {
324
324
  const fields = Object.keys(ent.fields).sort().map(n => ent.fields[n])
325
325
  for (let fI = 0; fI < fields.length; fI++) {
326
326
  const field = fields[fI]
327
- // NOT A readOnly FIELD. The flow writes this one and then asserts the
328
- // mark comes back, so a field the client may not send fails the step it
329
- // was chosen for. Fields are sorted by name, so which field this lands on
327
+ // NOT A readOnly FIELD, NOR A FILE. The flow writes this one and then
328
+ // asserts the mark comes back, which a field the client may not send, or
329
+ // one holding bytes, never does. Fields are sorted by name, so the choice
330
330
  // is alphabetical accident: solar's planet, once its spec declared the
331
331
  // server-assigned `forbidReason`, marked that instead of `kind`.
332
- if ('`$STRING`' === field.t && 'id' !== field.n &&
333
- true !== field.ro && true !== paramNames[field.n]) {
332
+ if ('`$STRING`' === field.t && 'id' !== field.n && true !== field.ro &&
333
+ 'binary' !== field.fo && true !== paramNames[field.n]) {
334
334
  return field
335
335
  }
336
336
  }
@@ -19,6 +19,8 @@ import type {
19
19
 
20
20
  import { deriveRetShape } from '../guide/graphql01'
21
21
 
22
+ import { paramName } from '../utility'
23
+
22
24
 
23
25
  const REL_STUB = '{ id }'
24
26
 
@@ -92,24 +94,31 @@ function payloadScalarFields(typeName: string, def: any): string[] {
92
94
  }
93
95
 
94
96
 
95
- function buildVars(fielddef: any, def: any): ModelGraphqlVar[] {
97
+ function buildVars(
98
+ fielddef: any,
99
+ def: any,
100
+ optype: string,
101
+ renames?: Record<string, any>,
102
+ ): ModelGraphqlVar[] {
96
103
  const args = fielddef?.args ?? []
97
104
 
98
- // The whole-request-body binding is the SINGLE-entity-input convention
99
- // (issueCreate(input: IssueCreateInput!)). A field taking several input
100
- // objects — items(filter: Filter, orderBy: OrderBy) — must bind each from
101
- // its own argument, or they all receive the same value and at least one
102
- // fails input validation.
105
+ // The whole-request-body binding is the SINGLE-entity-input convention of a
106
+ // mutation (issueCreate(input: IssueCreateInput!)). A query's input object
107
+ // is a filter beside its other arguments, and a field taking several input
108
+ // objects — items(filter: Filter, orderBy: OrderBy) — binds each from its
109
+ // own argument, or they all receive the same value.
103
110
  const inputs = args.filter((a: any) => {
104
111
  const atype = def.types?.[a.type]
105
112
  return null != atype && 'INPUT_OBJECT' === atype.kind
106
113
  })
107
- const soleInput = 1 === inputs.length ? inputs[0].name : undefined
114
+ const soleInput = 'mutation' === optype && 1 === inputs.length ? inputs[0].name : undefined
108
115
 
109
116
  return args.map((arg: any) => {
117
+ // A scalar argument is read from the parameter the args step names for it.
110
118
  const v: any = {
111
119
  name: arg.name,
112
- from: arg.name === soleInput ? '' : arg.name,
120
+ from: arg.name === soleInput ? '' :
121
+ inputs.includes(arg) ? arg.name : paramName(arg.name, renames),
113
122
  gqltype: arg.gqltype,
114
123
  }
115
124
  if (undefined !== arg.deflt) {
@@ -196,7 +205,7 @@ const graphqlTransform: Transform = async function(
196
205
  const fragName = pascal(entname) + 'Fields'
197
206
  const fragSpread = 0 < fragFields.length ? '{ ...' + fragName + ' }' : '{ id }'
198
207
 
199
- const vars = buildVars(fielddef, def)
208
+ const vars = buildVars(fielddef, def, optype, mpoint.r?.param)
200
209
 
201
210
  let selection = fragSpread
202
211
  let respath = 'body.data.' + rootfield
@@ -272,4 +281,5 @@ export {
272
281
  graphqlTransform,
273
282
  selectionFields,
274
283
  renderDoc,
284
+ buildVars,
275
285
  }
@@ -183,7 +183,7 @@ function resolveSummary(def: any): string | undefined {
183
183
  return firstSentence(explicit)
184
184
  }
185
185
 
186
- const desc = 'string' === typeof info.description ? info.description : ''
186
+ const desc = 'string' === typeof info.description ? htmlText(info.description) : ''
187
187
  if ('' === desc.trim() || !hasLetters(desc)) {
188
188
  return undefined
189
189
  }
@@ -208,6 +208,46 @@ function resolveSummary(def: any): string | undefined {
208
208
  }
209
209
 
210
210
 
211
+ const HTML_BLOCK = 'address|article|aside|blockquote|br|dd|div|dl|dt|figcaption|figure|footer|' +
212
+ 'header|hr|li|main|nav|ol|p|pre|section|table|tbody|td|tfoot|th|thead|tr|ul'
213
+ const HTML_INLINE = 'a|abbr|b|big|cite|code|em|font|i|img|kbd|mark|q|s|samp|small|span|' +
214
+ 'strong|sub|sup|tt|u|var'
215
+ const HTML_COMMENT_RE = /<!--[\s\S]*?(-->|$)/g
216
+ const HTML_HEADING_RE = /<h([1-6])([ \t\n\r\f][^<>]*)?>([\s\S]*?)<\/h[1-6][ \t\n\r\f]*>/gi
217
+ const HTML_BLOCK_RE =
218
+ new RegExp('<\\/?(' + HTML_BLOCK + '|h[1-6])([ \\t\\n\\r\\f][^<>]*)?\\/?>', 'gi')
219
+ const HTML_INLINE_RE =
220
+ new RegExp('<\\/?(' + HTML_INLINE + ')([ \\t\\n\\r\\f][^<>]*)?\\/?>', 'gi')
221
+ const HTML_ENTITY_RE = /&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|amp|lt|gt|quot|apos|nbsp);/gi
222
+ const HTML_ENTITIES: Record<string, string> = {
223
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0',
224
+ }
225
+
226
+
227
+ // HTML as the text the summary reads: a heading on a line of its own as a
228
+ // markdown heading, a block element as a paragraph break, other markup gone.
229
+ // Only HTML tag names count, so a generic such as List<String> is kept.
230
+ function htmlText(text: string): string {
231
+ return text
232
+ .replace(HTML_COMMENT_RE, '')
233
+ .replace(HTML_HEADING_RE, (_m, level, _attrs, inner) =>
234
+ '\n\n' + '#'.repeat(Number(level)) + ' ' +
235
+ inner.replace(HTML_BLOCK_RE, ' ').replace(HTML_INLINE_RE, '').replace(/\s+/g, ' ').trim() +
236
+ '\n\n')
237
+ .replace(HTML_BLOCK_RE, '\n\n')
238
+ .replace(HTML_INLINE_RE, '')
239
+ .replace(HTML_ENTITY_RE, (entity, name) => {
240
+ const key = name.toLowerCase()
241
+ if ('#' !== key[0]) {
242
+ return HTML_ENTITIES[key]
243
+ }
244
+ const code = 'x' === key[1] ? parseInt(key.slice(2), 16) : parseInt(key.slice(1), 10)
245
+ return 0 < code && code <= 0x10ffff && (code < 0xd800 || 0xdfff < code) ?
246
+ String.fromCodePoint(code) : entity
247
+ })
248
+ }
249
+
250
+
211
251
  // A server variable that opens the URL stands for its origin, or for its
212
252
  // scheme when `://` follows, so its value carries the scheme.
213
253
  const LEADING_VARIABLE_RE = /^\{([^{}]+)\}($|[/?#]|:\/\/)/
package/src/utility.ts CHANGED
@@ -959,6 +959,7 @@ function renderJSONIC(
959
959
 
960
960
  const VALID_CANON: Record<string, string> = Object.assign(Object.create(null), {
961
961
  'string': '`$STRING`',
962
+ 'file': '`$STRING`',
962
963
  'number': '`$NUMBER`',
963
964
  'integer': '`$INTEGER`',
964
965
  'boolean': '`$BOOLEAN`',
@@ -970,12 +971,23 @@ const VALID_CANON: Record<string, string> = Object.assign(Object.create(null), {
970
971
 
971
972
  const CANON_ONE = '`$ONE`'
972
973
 
974
+ const CANON_NULL = '`$NULL`'
975
+
976
+
977
+ function declaredType(type: string): string {
978
+ return type.toLowerCase().trim()
979
+ }
980
+
981
+
982
+ // Swagger 2's file, a binary string in OpenAPI 3.
983
+ function isFileType(type: unknown): boolean {
984
+ return 'string' === typeof type && 'file' === declaredType(type)
985
+ }
986
+
973
987
 
974
988
  function validator(torig: undefined | string | string[]): any {
975
989
  if ('string' === typeof torig) {
976
- const tstr = torig.toLowerCase().trim()
977
- const canon = VALID_CANON[tstr] ?? 'Any'
978
- return canon
990
+ return VALID_CANON[declaredType(torig)] ?? '`$ANY`'
979
991
  }
980
992
  else if (Array.isArray(torig)) {
981
993
  return [CANON_ONE, torig.map((t: string) => validator(t))]
@@ -985,6 +997,19 @@ function validator(torig: undefined | string | string[]): any {
985
997
  }
986
998
  }
987
999
 
1000
+ // The type a field holds when it is not null: the type itself, or the one
1001
+ // member of a union beside `$NULL`. Any other union has none.
1002
+ function nonNullType(type: any): string | undefined {
1003
+ if ('string' === typeof type) {
1004
+ return type
1005
+ }
1006
+ if (!Array.isArray(type) || CANON_ONE !== type[0] || !Array.isArray(type[1])) {
1007
+ return undefined
1008
+ }
1009
+ const members = type[1].filter((member: any) => CANON_NULL !== member)
1010
+ return 1 === members.length && 'string' === typeof members[0] ? members[0] : undefined
1011
+ }
1012
+
988
1013
  const FILE_EXT_RE =
989
1014
  /\.(php|json|txt|png|jpg|jpeg|gif|svg|xml|html|csv|yml|yaml|md)$/i
990
1015
 
@@ -2146,7 +2171,9 @@ function firstSentence(text: string): string {
2146
2171
  let out = m ? m[1] : collapsed
2147
2172
  const MAX = 240
2148
2173
  if (out.length > MAX) {
2149
- out = out.slice(0, MAX - 1).trimEnd() + '\u2026'
2174
+ const cut = out.slice(0, MAX - 1)
2175
+ const space = cut.lastIndexOf(' ')
2176
+ out = (0 < space ? cut.slice(0, space) : cut).trimEnd() + '\u2026'
2150
2177
  }
2151
2178
  return out
2152
2179
  }
@@ -2168,6 +2195,8 @@ export {
2168
2195
  makeWarner,
2169
2196
  formatJSONIC,
2170
2197
  validator,
2198
+ isFileType,
2199
+ nonNullType,
2171
2200
  VALID_CANON,
2172
2201
  CANON_ONE,
2173
2202
  canonize,