@voxgig/apidef 8.3.0 → 8.5.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.
@@ -32,7 +32,7 @@ import type {
32
32
  const fieldTransform: Transform = async function(
33
33
  ctx: any,
34
34
  ): Promise<TransformResult> {
35
- const { apimodel, def } = ctx
35
+ const { apimodel, def, guide, model } = ctx
36
36
  const kit: KitModel = apimodel.main[KIT]
37
37
 
38
38
  let msg = 'field '
@@ -72,9 +72,101 @@ const fieldTransform: Transform = async function(
72
72
  // Downstream (test generators, fixture builders) gate id-specific code on
73
73
  // this presence so that public read-only APIs without ids don't get
74
74
  // bogus id assertions.
75
+ // COMPOSITE FIRST, because a compound key need not come with an `id`.
76
+ //
77
+ // An entity addressed by `{owner}/{repo}` whose response carries only
78
+ // `owner` and `name` has no field literally named `id`, and its adjacent
79
+ // placeholders are left unrenamed so `addressedById` is false too.
80
+ // Neither branch below then ran, so the entity got NO id descriptor and
81
+ // even an explicit `guide.entity.<name>.id.parts` was silently ignored —
82
+ // while the Go port, which initialises a descriptor unconditionally,
83
+ // emitted the composite. The ports disagreed on exactly the shape this
84
+ // feature exists for.
85
+ const gent = guide?.entity?.[ment.name]
86
+ const composite = compositeId(ment, gent, def)
87
+
75
88
  const idField = fields.find((f: ModelField) => 'id' === f.name)
76
- if (idField) {
77
- ment.id = { name: 'id', field: 'id' }
89
+
90
+ // A COMPOSITE ID IS A STRING, whatever the API's own `id` field is —
91
+ // AND THE API'S OWN id IS KEPT.
92
+ //
93
+ // github's repo declares `id` as an integer, its global database id,
94
+ // while the composite identity is `owner/repo`. Two facts have to
95
+ // survive: `id` must hold a string, because that is what the joined
96
+ // value is and what every generated type has to store; and the spec's
97
+ // numeric property must not be silently reinterpreted, because a
98
+ // consumer that wants the database id is entitled to it with its own
99
+ // type and format intact.
100
+ //
101
+ // So the API's field MOVES to `<api>_id` rather than being rewritten in
102
+ // place, carrying its type, format and per-op overrides with it, and the
103
+ // entity's `alias.field` map records where it went. Retyping in place
104
+ // (the first attempt) claimed the server's numeric id was a string;
105
+ // leaving it alone made `id.field` name a declaration the runtime value
106
+ // cannot satisfy. Moving it is the only option that lies about neither.
107
+ if (null != composite.parts && null != idField && !scalarStringField(idField)) {
108
+ const idf: any = idField
109
+ const apiname = String((model as any)?.name || 'api')
110
+ const keep = apiname + '_id'
111
+
112
+ if (!fields.some((f: ModelField) => f.name === keep)) {
113
+ // A DEEP COPY, because the move is followed by deletions on the
114
+ // original. A spread shares the `op` object, so clearing the stale
115
+ // per-op `type` off `id` cleared it off the preserved field too —
116
+ // the preservation preserved nothing for exactly the key it was
117
+ // added to keep.
118
+ fields.push(JSON.parse(JSON.stringify({ ...idf, name: keep })) as any)
119
+
120
+ const alias = ((ment as any).alias = (ment as any).alias || {})
121
+ alias.field = alias.field || {}
122
+ alias.field[keep] = 'id'
123
+ }
124
+
125
+ idf.type = '`$STRING`'
126
+ // The facts that described the moved type go with it: `format: int64`
127
+ // beside a string, or a per-op `type` override still saying integer,
128
+ // is a model contradicting itself — and the op override is what a
129
+ // generator reads for that op.
130
+ delete idf.format
131
+ for (const opname of Object.keys(idf.op || {})) {
132
+ delete idf.op[opname].type
133
+ }
134
+
135
+ fields.sort((a: ModelField, b: ModelField) =>
136
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
137
+ }
138
+
139
+ if (null != composite.parts && null == idField) {
140
+ // The FIELD as well as the descriptor, for the reason the branch below
141
+ // documents: a model that declares the descriptor without the field
142
+ // makes the generated type disagree with the generated test.
143
+ fields.push({
144
+ name: 'id',
145
+ type: '`$STRING`',
146
+ req: false,
147
+ } as any)
148
+ fields.sort((a: ModelField, b: ModelField) =>
149
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
150
+ }
151
+
152
+ const singleKey = (composite as any).single
153
+ delete (composite as any).single
154
+
155
+ if (null == idField && null != singleKey && null == composite.parts) {
156
+ // The guide disabled composite; the terminal parameter is the key, and
157
+ // the entity needs the field to carry it for the same reason the
158
+ // composite branch above does.
159
+ fields.push({
160
+ name: 'id',
161
+ type: '`$STRING`',
162
+ req: false,
163
+ } as any)
164
+ fields.sort((a: ModelField, b: ModelField) =>
165
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
166
+ }
167
+
168
+ if (idField || null != composite.parts || null != singleKey) {
169
+ ment.id = { name: 'id', field: 'id', ...composite }
78
170
  }
79
171
  else if (addressedById(ment)) {
80
172
  // The FIELD as well as the descriptor. An entity addressed by id has an
@@ -111,7 +203,7 @@ const fieldTransform: Transform = async function(
111
203
  // with neither a field nor an id param — the read-only public APIs the
112
204
  // rule above was written for — still get no descriptor, so they still
113
205
  // get no id assertions.
114
- ment.id = { name: 'id', field: 'id' }
206
+ ment.id = { name: 'id', field: 'id', ...composite }
115
207
  }
116
208
 
117
209
  msg += ment.name + ' '
@@ -122,6 +214,569 @@ const fieldTransform: Transform = async function(
122
214
 
123
215
 
124
216
 
217
+ // The separator that joins a composite id into one string.
218
+ //
219
+ // A forward slash cannot occur inside a single path segment — a raw `/`
220
+ // would end the segment, and a value that legitimately contains one arrives
221
+ // percent-encoded as `%2F` — so joining on it can never be ambiguous, and
222
+ // splitting on it can never over-split. That is what makes the composite id
223
+ // safe to carry as a single opaque string, which is the property the SDK and
224
+ // Seneca entities are built on.
225
+ const ID_SEP = '/'
226
+
227
+ // Subfields that conventionally carry the identifying value of a nested
228
+ // object, in preference order. github's repo `owner` is a user object whose
229
+ // identifier is `login`; other specs use `name`, `slug` or `key`. `id` is
230
+ // last: it is the most common name and the least likely to be the value a
231
+ // PATH parameter takes (a path that wanted an id would say so).
232
+ const NESTED_ID_KEYS = ['login', 'slug', 'name', 'key', 'id']
233
+
234
+
235
+ // The ops that address ONE record, most authoritative first. Only a
236
+ // tie-break: identityParams compares candidates from all of them.
237
+ const ID_OPS = ['load', 'update', 'patch', 'remove']
238
+
239
+
240
+ // The parameters that TOGETHER name one record: the trailing run of
241
+ // ADJACENT variable segments on the addressing route.
242
+ //
243
+ // ADJACENCY IS THE WHOLE TEST, and it is what separates a compound key from
244
+ // ordinary parent/child nesting:
245
+ //
246
+ // /repos/{owner}/{repo} -> owner, repo COMPOSITE
247
+ // /api/planet/{planet_id}/moon/{moon_id} -> moon_id single
248
+ // /repos/{owner}/{repo}/pulls/{pull_number} -> pull_number single
249
+ //
250
+ // A literal segment between two variables names a SUB-COLLECTION, so the
251
+ // earlier variable scopes the later one — `planet_id` says which planet's
252
+ // moons, and `moon_id` alone identifies the moon. Two variables with nothing
253
+ // between them address no sub-collection: neither value names anything on
254
+ // its own, and only the pair identifies a repository.
255
+ //
256
+ // Taking every variable on the path instead was tried first and is wrong on
257
+ // most real specs — it made `moon` (planet_id + moon_id), petstore's `order`,
258
+ // `pet` and `user`, and taxonomy's `domain` and `kingdom` all falsely
259
+ // composite, which the apidef-validate goldens caught immediately. Nested
260
+ // resources are the common shape; compound keys are the exception, and
261
+ // adjacency is the thing that actually distinguishes them.
262
+ //
263
+ // Read from the op that names a single record, never from `list`: a
264
+ // collection route's path params are the entity's parents. A point ending in
265
+ // a literal is a verb ON the record (`.../{number}/merge`) and carries the
266
+ // same variables, so it is a fallback rather than a different answer.
267
+ // Walk back from a point's end, collecting variables until a literal stops
268
+ // the run. That literal is the sub-collection boundary; anything before it
269
+ // scopes this record rather than naming it.
270
+ function trailingVars(point: any): string[] {
271
+ const segs = ((point?.segments || []) as any[]).filter((s: any) => null != s)
272
+ const run: string[] = []
273
+
274
+ for (let i = segs.length - 1; 0 <= i; i--) {
275
+ if (null == segs[i].var) {
276
+ break
277
+ }
278
+ run.unshift(String(segs[i].var))
279
+ }
280
+
281
+ return run
282
+ }
283
+
284
+
285
+ function identityParams(ment: ModelEntity): string[] {
286
+ // EVERY ID-BEARING OP AT ONCE, not the first one that offers a candidate.
287
+ //
288
+ // These four ops all address a single record, so all four describe the
289
+ // same identity — but they do not all carry the same routes. gitlab's
290
+ // `project` has `/api/v4/projects/{id}` under `remove` alone, while its
291
+ // `load` carries only sub-resources like
292
+ // `/api/v4/projects/{id}/uploads/{secret}/{filename}`. Returning on the
293
+ // first op with any candidate therefore made a PROJECT identified by
294
+ // `secret/filename`. The op order is now only a tie-break.
295
+ const cands: any[] = []
296
+
297
+ for (let o = 0; o < ID_OPS.length; o++) {
298
+ const mop = (ment as any).op?.[ID_OPS[o]]
299
+ if (null == mop) {
300
+ continue
301
+ }
302
+
303
+ // Action points are verbs dispatched by `$action`, not addresses.
304
+ for (const pt of (mop.points || [])) {
305
+ if (null != pt?.select?.['$action']) {
306
+ continue
307
+ }
308
+ const run = trailingVars(pt)
309
+ if (0 === run.length) {
310
+ continue
311
+ }
312
+ cands.push({
313
+ run,
314
+ // Segments BEFORE the run: how much parent scope the route needs.
315
+ scope: ((pt.segments || []).length - run.length),
316
+ // DOES THE RUN END IN THE RECORD'S OWN KEY? Then it is the
317
+ // record's address and nothing further is needed.
318
+ //
319
+ // This transform RENAMES that parameter to `id`, so a run ending in
320
+ // it is this port's own statement of what identifies the record —
321
+ // and the composite inference must not contradict it.
322
+ // `/gists/{gist_id}` becomes `/gists/{id}` and is a gist;
323
+ // `/gists/{gist_id}/{sha}` is a REVISION of one, and won on key
324
+ // length alone, so a gist came out keyed `gist_id/sha` while the
325
+ // generated SDK's own load match takes the single parameter. The
326
+ // same contradiction gave cloudsmith's repo and vulnerability
327
+ // compound keys their SDKs never address them by.
328
+ //
329
+ // Deliberately narrow: exactly `id` or an unrenamed `<entity>_id`,
330
+ // never any `*_id`. `actor_type/actor_id` IS a compound key, and a
331
+ // looser test breaks it.
332
+ own: 'id' === run[run.length - 1] ||
333
+ (ment as any).name + '_id' === run[run.length - 1],
334
+ order: o,
335
+ })
336
+ }
337
+ }
338
+
339
+ // WHICH ROUTE IS THE RECORD'S OWN ADDRESS.
340
+ //
341
+ // An entity gathers every route that reads it, and in a large
342
+ // specification most of those are sub-resources. Three earlier rules were
343
+ // measured against the validation corpus, and each is wrong:
344
+ //
345
+ // The FIRST route listed gave github's `repo` the single part
346
+ // `subject_digest`, from
347
+ // `/repos/{owner}/{repo}/attestations/{subject_digest}` — no compound
348
+ // key at all, for the entity this feature exists for. Invisible on a
349
+ // small spec, where the first item route IS the record's own.
350
+ //
351
+ // The SHORTEST route ending in a variable took cloudsmith's
352
+ // `/vulnerabilities/{owner}/` — a LIST of an owner's vulnerabilities —
353
+ // and cut a four-part key down to `owner`, dropping three more
354
+ // composites. Ending in a variable does not make a route an address.
355
+ //
356
+ // The LONGEST trailing run took
357
+ // `/orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}` and made a TEAM
358
+ // identified by `owner/repo`. A deep sub-resource can carry more
359
+ // adjacent variables than the record's own route does.
360
+ //
361
+ // What separates them is PARENT SCOPE: the record's own route is the
362
+ // least-qualified one that names it, and among equally-qualified routes
363
+ // the one carrying the fullest key. `/repos/{owner}/{repo}` is qualified
364
+ // by one segment and the attestations route by four; `/teams/{team_id}`
365
+ // by one and the org-team-repo route by five; cloudsmith's vulnerability
366
+ // routes are all qualified by one, so the fullest of them wins.
367
+ const best = cands.reduce((b: any, c: any) => {
368
+ if (null == b) {
369
+ return c
370
+ }
371
+ if (c.scope !== b.scope) {
372
+ return c.scope < b.scope ? c : b
373
+ }
374
+ if (c.own !== b.own) {
375
+ return c.own ? c : b
376
+ }
377
+ if (c.run.length !== b.run.length) {
378
+ return b.run.length < c.run.length ? c : b
379
+ }
380
+ return c.order < b.order ? c : b
381
+ }, null)
382
+
383
+ return null == best ? [] : best.run
384
+ }
385
+
386
+ // THE PROPERTY MAPS A RESPONSE COULD BE DESCRIBING, best first.
387
+ //
388
+ // BOTH SPEC DIALECTS. An OpenAPI 3 response carries its schema under
389
+ // `content['application/json']`; a SWAGGER 2 response carries it directly as
390
+ // `schema`. Reading only the first resolved nothing for every Swagger 2 spec
391
+ // in the validation corpus.
392
+ //
393
+ // JSON ONLY, where there is a choice. An operation may declare several media
394
+ // types with different schemas, and field extraction uses the JSON one — so
395
+ // picking whichever came first in source order could infer a path from an XML
396
+ // or binary schema that the actual JSON record does not have.
397
+ //
398
+ // `allOf` IS EXPANDED, because a response that composes its entity that way
399
+ // has neither `properties` nor `items` of its own. field extraction expands
400
+ // it; not doing so here meant the fields were present while the id could not
401
+ // be reconstructed.
402
+ //
403
+ // ONLY THE ENVELOPE IS DESCENDED, via the same `envelopeProp` rule field
404
+ // extraction uses. Descending every object-valued property instead treats an
405
+ // ordinary nested object as a whole record: for `{ slug, metadata: { tenant } }`
406
+ // addressed by `{tenant}/{slug}`, `tenant` resolved to `tenant` rather than
407
+ // `metadata.tenant` — a confidently wrong path, which is worse than no
408
+ // mapping at all.
409
+ //
410
+ // ACTION POINTS ARE SKIPPED, as `identityParams` skips them: an action's
411
+ // response is a verb's result, not a representation of the entity, so a field
412
+ // that happens to appear there says nothing about what a returned record
413
+ // carries.
414
+ function responseCandidates(ment: ModelEntity, def: any): any[] {
415
+ const out: any[] = []
416
+ const seen = new Set<any>()
417
+
418
+ // Every property map this schema describes, expanding allOf.
419
+ const propsOf = (schema: any): any[] => {
420
+ const node = resolveRef(schema, def)
421
+ if (null == node || seen.has(node)) {
422
+ return []
423
+ }
424
+ seen.add(node)
425
+
426
+ if (Array.isArray(node.allOf)) {
427
+ return node.allOf.flatMap((member: any) => propsOf(member))
428
+ }
429
+
430
+ if (null != node.properties) {
431
+ return [node.properties]
432
+ }
433
+
434
+ // A bare array response: the record is the item.
435
+ const items = resolveRef(node.items, def)
436
+ if (null != items) {
437
+ return propsOf(items)
438
+ }
439
+
440
+ return []
441
+ }
442
+
443
+ const add = (schema: any, opname: string) => {
444
+ for (const props of propsOf(schema)) {
445
+ out.push(props)
446
+
447
+ // One level in, but ONLY through the envelope property.
448
+ const envelope = envelopeProp(props, opname)
449
+ if (null == envelope) {
450
+ continue
451
+ }
452
+ const inner = resolveRef(props[envelope], def)
453
+ if (null == inner) {
454
+ continue
455
+ }
456
+ for (const innerProps of propsOf(inner)) {
457
+ out.push(innerProps)
458
+ }
459
+ }
460
+ }
461
+
462
+ for (const opname of ['load', 'list', 'update', 'create']) {
463
+ const mop = (ment as any).op?.[opname]
464
+
465
+ for (const mpoint of (mop?.points || [])) {
466
+ // An action point's response is not the entity.
467
+ if (null != mpoint?.select?.['$action']) {
468
+ continue
469
+ }
470
+
471
+ const path = (def?.paths || {})[mpoint?.orig]
472
+ const method = String(mpoint?.method || '').toLowerCase()
473
+ const responses = path?.[method]?.responses || {}
474
+
475
+ for (const code of Object.keys(responses)) {
476
+ if (!/^2/.test(code)) {
477
+ continue
478
+ }
479
+ const resdef = responses[code] || {}
480
+
481
+ const content = resdef.content || {}
482
+ const ctypes = Object.keys(content)
483
+ // Prefer JSON; fall back to whatever single type is offered.
484
+ const json = ctypes.find((c: string) => c.includes('json'))
485
+ if (null != json) {
486
+ add(content[json]?.schema, opname)
487
+ }
488
+ else {
489
+ for (const ctype of ctypes) {
490
+ add(content[ctype]?.schema, opname)
491
+ }
492
+ }
493
+
494
+ // Swagger 2 puts it here.
495
+ add(resdef.schema, opname)
496
+ }
497
+ }
498
+ }
499
+
500
+ return out
501
+ }
502
+
503
+
504
+ // A `$ref` followed one hop, or the schema itself. apidef resolves most refs
505
+ // before this stage; this covers the ones that survive on a nested property.
506
+ function resolveRef(schema: any, def: any): any {
507
+ if (null == schema) {
508
+ return null
509
+ }
510
+ const ref = schema.$ref
511
+ if ('string' !== typeof ref || !ref.startsWith('#/')) {
512
+ return schema
513
+ }
514
+
515
+ let node: any = def
516
+ for (const seg of ref.slice(2).split('/')) {
517
+ node = node?.[seg]
518
+ if (null == node) {
519
+ return null
520
+ }
521
+ }
522
+ return node
523
+ }
524
+
525
+
526
+ // The conventional identifying subfield of a property map, or null.
527
+ function conventionalIdKey(props: any): string | null {
528
+ for (const key of NESTED_ID_KEYS) {
529
+ const p = props[key]
530
+ if (null == p) {
531
+ continue
532
+ }
533
+ const t = String(p.type || '')
534
+ if ('object' !== t && 'array' !== t) {
535
+ return key
536
+ }
537
+ }
538
+
539
+ return null
540
+ }
541
+
542
+
543
+ // Every name a part might be carried under: the model's name for it, plus the
544
+ // original wire names of any path parameter that was renamed to it.
545
+ function partAliases(ment: ModelEntity, part: string): string[] {
546
+ const names = new Set<string>([part])
547
+
548
+ each((ment as any).op, (mop: any) => {
549
+ each(mop?.points, (mpoint: any) => {
550
+ const rename = mpoint?.rename?.param || {}
551
+ for (const orig of Object.keys(rename)) {
552
+ if (String(rename[orig]) === part) {
553
+ names.add(orig)
554
+ }
555
+ }
556
+ for (const arg of (mpoint?.args?.params || [])) {
557
+ if (null != arg && arg.name === part && null != arg.orig) {
558
+ names.add(String(arg.orig))
559
+ }
560
+ }
561
+ })
562
+ })
563
+
564
+ return [...names]
565
+ }
566
+
567
+
568
+ // Where one part is carried in a given property map, or null.
569
+ //
570
+ // The four rules, in order, each a fact the spec states: a scalar property of
571
+ // that name; the part naming this entity, resolved to `name`; a scalar
572
+ // `<part>_name` / `_login` / `_slug`; or an object property's conventional
573
+ // identifying subfield.
574
+ function resolvePart(
575
+ ment: ModelEntity,
576
+ part: string,
577
+ aliases: string[],
578
+ props: any,
579
+ def: any,
580
+ ): string | null {
581
+ if (null == props) {
582
+ return null
583
+ }
584
+
585
+ const prop = (name: string) => resolveRef(props[name], def)
586
+ const scalar = (p: any) =>
587
+ null != p && 'object' !== String(p.type) && 'array' !== String(p.type) &&
588
+ null == p.properties && null == p.items
589
+
590
+ for (const name of aliases) {
591
+ if (scalar(prop(name))) {
592
+ return name
593
+ }
594
+ }
595
+
596
+ if (part === ment.name && scalar(prop('name'))) {
597
+ return 'name'
598
+ }
599
+
600
+ for (const name of aliases) {
601
+ for (const suffix of ['_name', '_login', '_slug']) {
602
+ if (scalar(prop(name + suffix))) {
603
+ return name + suffix
604
+ }
605
+ }
606
+ }
607
+
608
+ for (const name of aliases) {
609
+ const nested = prop(name)
610
+ if (null != nested?.properties) {
611
+ const sub = conventionalIdKey(nested.properties)
612
+ if (null != sub) {
613
+ return name + '.' + sub
614
+ }
615
+ }
616
+ }
617
+
618
+ return null
619
+ }
620
+
621
+
622
+ // WHERE EACH COMPOSITE PART'S VALUE LIVES IN A RESPONSE.
623
+ //
624
+ // The parts are PATH PARAMETER names; a response names its fields whatever it
625
+ // likes. Resolving one to the other is what lets an SDK put an id on a record
626
+ // the API returned, rather than only address a record whose id it was given.
627
+ //
628
+ // The rules, in order, and each of them is a fact about the spec rather than
629
+ // a guess:
630
+ //
631
+ // 1. a scalar field of exactly that name -> itself
632
+ // 2. the part names this entity, and there is a `name` -> `name`
633
+ // (`/repos/{owner}/{repo}` on entity `repo`, whose response calls the
634
+ // repository `name`)
635
+ // 3. a scalar `<part>_name` / `<part>_login` / `<part>_slug`
636
+ // 4. an OBJECT field of that name -> `<part>.<conventional key>`
637
+ // (`owner` is a user object; the value is `owner.login`)
638
+ //
639
+ // A part none of these resolve is left OUT. Downstream then knows the id
640
+ // cannot be rebuilt for that entity and can say so, which is better than a
641
+ // confidently wrong id on a real record. guide.aon can state it instead.
642
+ function identityFrom(
643
+ ment: ModelEntity,
644
+ parts: string[],
645
+ def: any,
646
+ ): Record<string, string> {
647
+ // THE RESPONSE SCHEMA IS THE AUTHORITY, not `ment.fields`.
648
+ //
649
+ // `ment.fields` is merged across load, create, update and list, so a part
650
+ // that exists only in a REQUEST BODY appears there too. Resolving against
651
+ // it recorded such a part in `from` as though a returned record carried it,
652
+ // and a consumer then rebuilt an id from a property the response never
653
+ // sends — worse than leaving the part unresolved, which at least says so.
654
+ //
655
+ // Candidate property maps, in order: the response's own properties, then
656
+ // one level into an envelope. A response that wraps the record
657
+ // (`{ item: {...} }`, `{ data: [ {...} ] }`) states the record's fields one
658
+ // level in, and searching only the wrapper found nothing.
659
+ const candidates = responseCandidates(ment, def)
660
+ const out: Record<string, string> = {}
661
+
662
+ for (const part of parts) {
663
+ // THE WIRE NAME AS WELL AS THE MODEL NAME. `identityParams` reads the
664
+ // RENAMED parameter off the path segments, while a response keeps its own
665
+ // casing — so a `tenantKey` renamed to `tenant_key` was looked up under a
666
+ // name the response does not use, and the mapping was dropped for every
667
+ // camel-cased or depluralized parameter.
668
+ const aliases = partAliases(ment, part)
669
+
670
+ let found: string | null = null
671
+
672
+ for (const props of candidates) {
673
+ found = resolvePart(ment, part, aliases, props, def)
674
+ if (null != found) {
675
+ break
676
+ }
677
+ }
678
+
679
+ if (null != found) {
680
+ out[part] = found
681
+ }
682
+ }
683
+
684
+ return out
685
+ }
686
+
687
+
688
+ // Is this model field declared as a string? A composite id is the parts
689
+ // joined, so the field that holds it has to be one.
690
+ function scalarStringField(f: any): boolean {
691
+ return String(f?.type || '').toUpperCase().includes('STRING')
692
+ }
693
+
694
+
695
+ // WHICH PARAMETER IS THE RECORD'S OWN KEY, among several that looked
696
+ // adjacent. The same shape apidef's id handling recognises everywhere else:
697
+ //
698
+ // 1. one named exactly `id`
699
+ // 2. `<entity>_id` — the entity's own id, however the path spells it
700
+ // 3. any `*_id` — an id by name
701
+ // 4. failing all that, the terminal parameter
702
+ //
703
+ // Position is the LAST resort, not the first.
704
+ function singleKeyOf(ment: ModelEntity, parts: string[]): string | undefined {
705
+ if (0 === parts.length) {
706
+ return undefined
707
+ }
708
+
709
+ return parts.find((p: string) => 'id' === p)
710
+ ?? parts.find((p: string) => p === ment.name + '_id')
711
+ ?? parts.find((p: string) => p.endsWith('_id'))
712
+ ?? parts[parts.length - 1]
713
+ }
714
+
715
+
716
+ // The composite half of the id descriptor, or `{}` for the ordinary case.
717
+ //
718
+ // Emitted ONLY for a genuinely composite id (two or more addressing
719
+ // parameters). A single-parameter entity already round-trips through one
720
+ // `id` and gains nothing from carrying a one-element `parts`, so its
721
+ // descriptor is left exactly as it was — no existing model output moves.
722
+ function compositeId(
723
+ ment: ModelEntity,
724
+ gent?: any,
725
+ def?: any,
726
+ ): { parts?: string[], sep?: string, from?: Record<string, string> } {
727
+ const gid = gent?.id
728
+ const sep = null != gid?.sep && '' !== String(gid.sep) ? String(gid.sep) : ID_SEP
729
+
730
+ // `composite: false` turns the inference off. A boolean rather than an
731
+ // empty `parts`, because aontu resolves an empty list to nothing and the
732
+ // key would arrive absent — indistinguishable from never having been set.
733
+ if (null != gid && false === gid.composite) {
734
+ // DISABLING COMPOSITE MUST NOT DISABLE THE ID. The correction says these
735
+ // adjacent parameters are not a compound key; it does not say the record
736
+ // has no key. Returning a bare `{}` left an entity whose response has no
737
+ // literal `id` with no descriptor at all — the false positive removed and
738
+ // nothing identifying the real key.
739
+ //
740
+ // WHICH of the adjacent parameters is that key is decided by the same
741
+ // id-finding rules apidef uses elsewhere, not by position. Taking the
742
+ // terminal one picked `archive_format` for
743
+ // `/artifacts/{artifact_id}/{archive_format}` — the modifier, precisely
744
+ // the false positive the correction exists to undo.
745
+ return { single: singleKeyOf(ment, identityParams(ment)) } as any
746
+ }
747
+
748
+ // `from` STATED IN guide.aon WINS PER PART, so a spec can correct one
749
+ // mapping without restating the others — which matters because the
750
+ // heuristic gets most of them right and the odd one wrong.
751
+ const withFrom = (parts: string[], usesep: string) => {
752
+ const derived = identityFrom(ment, parts, def)
753
+ const stated = null != gid?.from && 'object' === typeof gid.from ? gid.from : {}
754
+ const from: Record<string, string> = {}
755
+
756
+ for (const part of parts) {
757
+ const say = (stated as any)[part]
758
+ const use = null != say && '' !== String(say) ? String(say) : derived[part]
759
+ if (null != use) {
760
+ from[part] = use
761
+ }
762
+ }
763
+
764
+ return 0 === Object.keys(from).length ?
765
+ { parts, sep: usesep } : { parts, sep: usesep, from }
766
+ }
767
+
768
+ if (null != gid && null != gid.parts) {
769
+ const given = (gid.parts as any[])
770
+ .filter((p: any) => null != p && '' !== String(p))
771
+ .map((p: any) => String(p))
772
+ return 1 < given.length ? withFrom(given, sep) : {}
773
+ }
774
+
775
+ const parts = identityParams(ment)
776
+ return 1 < parts.length ? withFrom(parts, sep) : {}
777
+ }
778
+
779
+
125
780
  // True when any of the entity's own operation points declares an `id`
126
781
  // parameter — i.e. the API addresses this entity by id, whether or not its
127
782
  // response schema declares an id field.