@skmtc/core 0.40.0 → 0.42.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 (79) hide show
  1. package/esm/context/GenerateContext.d.ts +1 -1
  2. package/esm/context/GenerateContext.js +4 -3
  3. package/esm/context/ParseContext.d.ts +26 -0
  4. package/esm/context/ParseContext.js +112 -2
  5. package/esm/context/generateTypes.d.ts +16 -2
  6. package/esm/context/generateTypes.js +2 -0
  7. package/esm/context/tryParseAt.d.ts +4 -1
  8. package/esm/context/tryParseAt.js +10 -3
  9. package/esm/helpers/collateExamples.js +15 -5
  10. package/esm/helpers/refFns.d.ts +9 -3
  11. package/esm/helpers/refFns.js +29 -9
  12. package/esm/mod.d.ts +1 -0
  13. package/esm/mod.js +1 -0
  14. package/esm/oas/ref/DanglingRefError.d.ts +22 -0
  15. package/esm/oas/ref/DanglingRefError.js +33 -0
  16. package/esm/oas/ref/Ref.d.ts +5 -0
  17. package/esm/oas/ref/Ref.js +28 -2
  18. package/esm/oas/schema/siblings.js +12 -2
  19. package/esm/oas/union/Union.d.ts +2 -1
  20. package/esm/oas/union/Union.js +23 -12
  21. package/esm/parse/securityRequirements.d.ts +6 -0
  22. package/esm/parse/securityRequirements.js +8 -0
  23. package/esm/parse/v3-0/_merge-all-of/merge-union.js +9 -1
  24. package/esm/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  25. package/esm/parse/v3-0/parameter/toParameterV3.js +4 -3
  26. package/esm/parse/v3-0/ref/toRefV31.js +5 -2
  27. package/esm/parse/v3-0/schema/toSchemasV3.js +6 -3
  28. package/esm/parse/v3-1/_merge-all-of/merge-union.js +16 -4
  29. package/esm/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  30. package/esm/parse/v3-1/parameter/toParameterV3.js +4 -3
  31. package/esm/parse/v3-1/ref/toRefV31.js +5 -2
  32. package/esm/parse/v3-1/schema/toSchemasV3.js +6 -3
  33. package/esm/parse/v3-2/_merge-all-of/merge-union.js +16 -4
  34. package/esm/parse/v3-2/mediaType/toMediaTypeItemV3.js +4 -3
  35. package/esm/parse/v3-2/parameter/toParameterV3.js +4 -3
  36. package/esm/parse/v3-2/ref/toRefV31.js +5 -2
  37. package/esm/parse/v3-2/schema/toSchemasV3.js +6 -3
  38. package/esm/types/Settings.d.ts +21 -0
  39. package/esm/types/Settings.js +19 -1
  40. package/package.json +5 -1
  41. package/script/context/GenerateContext.d.ts +1 -1
  42. package/script/context/GenerateContext.js +4 -3
  43. package/script/context/ParseContext.d.ts +26 -0
  44. package/script/context/ParseContext.js +112 -2
  45. package/script/context/generateTypes.d.ts +16 -2
  46. package/script/context/generateTypes.js +2 -0
  47. package/script/context/tryParseAt.d.ts +4 -1
  48. package/script/context/tryParseAt.js +10 -3
  49. package/script/helpers/collateExamples.js +15 -5
  50. package/script/helpers/refFns.d.ts +9 -3
  51. package/script/helpers/refFns.js +29 -9
  52. package/script/mod.d.ts +1 -0
  53. package/script/mod.js +1 -0
  54. package/script/oas/ref/DanglingRefError.d.ts +22 -0
  55. package/script/oas/ref/DanglingRefError.js +37 -0
  56. package/script/oas/ref/Ref.d.ts +5 -0
  57. package/script/oas/ref/Ref.js +28 -2
  58. package/script/oas/schema/siblings.js +12 -2
  59. package/script/oas/union/Union.d.ts +2 -1
  60. package/script/oas/union/Union.js +23 -12
  61. package/script/parse/securityRequirements.d.ts +6 -0
  62. package/script/parse/securityRequirements.js +8 -0
  63. package/script/parse/v3-0/_merge-all-of/merge-union.js +9 -1
  64. package/script/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  65. package/script/parse/v3-0/parameter/toParameterV3.js +4 -3
  66. package/script/parse/v3-0/ref/toRefV31.js +5 -2
  67. package/script/parse/v3-0/schema/toSchemasV3.js +6 -3
  68. package/script/parse/v3-1/_merge-all-of/merge-union.js +16 -4
  69. package/script/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  70. package/script/parse/v3-1/parameter/toParameterV3.js +4 -3
  71. package/script/parse/v3-1/ref/toRefV31.js +5 -2
  72. package/script/parse/v3-1/schema/toSchemasV3.js +6 -3
  73. package/script/parse/v3-2/_merge-all-of/merge-union.js +16 -4
  74. package/script/parse/v3-2/mediaType/toMediaTypeItemV3.js +4 -3
  75. package/script/parse/v3-2/parameter/toParameterV3.js +4 -3
  76. package/script/parse/v3-2/ref/toRefV31.js +5 -2
  77. package/script/parse/v3-2/schema/toSchemasV3.js +6 -3
  78. package/script/types/Settings.d.ts +21 -0
  79. package/script/types/Settings.js +20 -2
@@ -328,7 +328,7 @@ export declare class GenerateContext implements GenerateContextType {
328
328
  * Perform one lookup of schema by `refName`.
329
329
  * @param refName
330
330
  * @returns Matching schema or ref
331
- * @throws if schema is not found
331
+ * @throws {DanglingRefError} when no schema has that name
332
332
  */
333
333
  resolveSchemaRefOnce(refName: RefName): OasSchema | OasRef<'schema'>;
334
334
  /**
@@ -12,6 +12,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  var _GenerateContext_instances, _GenerateContext_files, _GenerateContext_failedItems, _GenerateContext_foldedPaths, _GenerateContext_previews, _GenerateContext_captureChannel, _GenerateContext_enrichmentAudit, _GenerateContext_currentSubjectTrail, _GenerateContext_reportSkippedEnrichment, _GenerateContext_logError, _GenerateContext_failItem, _GenerateContext_schemaRefNames, _GenerateContext_subjectDefaults, _GenerateContext_runOasOperationGenerator, _GenerateContext_runWebhookGenerator, _GenerateContext_runGqlOperationGenerator, _GenerateContext_runModelGenerator, _GenerateContext_addPreview, _GenerateContext_toContentSettingsExportPath, _GenerateContext_ejectedBySuffixedPath_get, _GenerateContext_ejectedBySuffixedPathCache, _GenerateContext_findContainer, _GenerateContext_toContainer;
13
13
  import { normalizeWorkspacePath } from '../helpers/normalizeWorkspacePath.js';
14
14
  import { applyGeneratedSuffix, DEFAULT_GENERATED_SUFFIX } from '../helpers/applyGeneratedSuffix.js';
15
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
15
16
  import { isMethod } from '../types/Method.js';
16
17
  import { OasOperationDriver } from '../dsl/operation/oas/OasOperationDriver.js';
17
18
  import { WebhookDriver } from '../dsl/webhook/WebhookDriver.js';
@@ -830,14 +831,14 @@ export class GenerateContext {
830
831
  * Perform one lookup of schema by `refName`.
831
832
  * @param refName
832
833
  * @returns Matching schema or ref
833
- * @throws if schema is not found
834
+ * @throws {DanglingRefError} when no schema has that name
834
835
  */
835
836
  resolveSchemaRefOnce(refName) {
836
837
  switch (this.document.type) {
837
838
  case 'oas': {
838
839
  const component = this.document.value.components?.schemas?.[refName];
839
840
  if (!component) {
840
- throw new Error(`Schema not found: ${refName}`);
841
+ throw new DanglingRefError(refName);
841
842
  }
842
843
  const target = component.resolveOnce();
843
844
  // One step, with what the component adds next to its reference
@@ -850,7 +851,7 @@ export class GenerateContext {
850
851
  case 'gql': {
851
852
  const schema = this.document.value.registry.schemas[refName];
852
853
  if (!schema) {
853
- throw new Error(`Schema not found: ${refName}`);
854
+ throw new DanglingRefError(refName);
854
855
  }
855
856
  // GqlRegistry stores OasSchema | OasRef entries: one step, as for OAS.
856
857
  return schema.resolveOnce();
@@ -28,6 +28,8 @@ import { StackTrail } from './StackTrail.js';
28
28
  import type { SkmtcDocumentInput, SkmtcParsedDocument } from '../types/SkmtcDocument.js';
29
29
  import type { GqlParseOptions, LogAtArgs, LogIssueArgs, LogIssueAtArgs, LogIssueNoKeyArgs, LogSkippedValuesArgs } from './parseTypes.js';
30
30
  import type { ParseIssue } from './ParseIssue.js';
31
+ import type { OasRef } from '../oas/ref/Ref.js';
32
+ import type { OasRefData } from '../oas/ref/ref-types.js';
31
33
  export type { ParseIssue, GqlIssueType } from './ParseIssue.js';
32
34
  export type { GqlParseOptions, LogAtArgs, LogIssueArgs, LogIssueAtArgs, LogIssueNoKeyArgs, LogSkippedValuesArgs, ParseContextType, ParseErrorInput, ParseIssueInput, ParseWarningInput } from './parseTypes.js';
33
35
  type OasProtocolState = {
@@ -50,6 +52,11 @@ type GqlProtocolState = {
50
52
  options: GqlParseOptions;
51
53
  };
52
54
  type ProtocolState = OasProtocolState | GqlProtocolState;
55
+ type ToDanglingAllOfMemberArgs = {
56
+ $ref: string;
57
+ /** The schema that holds the `allOf`. */
58
+ stackTrail: StackTrail;
59
+ };
53
60
  type ConstructorArgs = {
54
61
  input: SkmtcDocumentInput;
55
62
  logger: Logger;
@@ -157,6 +164,25 @@ export declare class ParseContext {
157
164
  * would use type names or qualified field paths.
158
165
  */
159
166
  registerRef(consumer: StackTrail, refKey: string): void;
167
+ /**
168
+ * Register an OAS `$ref` at its consumer site, as {@link registerRef}
169
+ * does, under the key {@link toRefKey} gives its `$ref`, and keep the ref
170
+ * with that site, so that once the document is parsed `#checkRefs` can
171
+ * resolve it there.
172
+ */
173
+ registerOasRef<T extends OasRefData['refType']>(consumer: StackTrail, ref: OasRef<T>): void;
174
+ /**
175
+ * What a merge reads in place of a `$ref` that names nothing: an `allOf`
176
+ * member, or in a `oneOf` or `anyOf`, a member's own `allOf` member or a
177
+ * member merged with the keywords beside the union. When
178
+ * `system.danglingRefs` lists `allOfMember`, it is `{}`, which
179
+ * adds nothing to the merge (`A & unknown` is `A`), and a `DANGLING_REF`
180
+ * warning at `stackTrail`: the model has no properties from that member.
181
+ * Otherwise it throws `DanglingRefError`, and what holds the `allOf` is
182
+ * removed. It is separate from `schema`: here core decides, at parse, and
183
+ * the generator never sees the member.
184
+ */
185
+ toDanglingAllOfMember({ $ref, stackTrail }: ToDanglingAllOfMemberArgs): OpenAPIV3.SchemaObject;
160
186
  /**
161
187
  * Register an error against a ref key — typically called when the
162
188
  * target of a `$ref` (or type reference) fails to parse. `undefined`
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail;
12
+ var _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_oasRefs, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail, _ParseContext_checkRefs, _ParseContext_removeHolder;
13
13
  /**
14
14
  * Unified parse context for both OAS and GraphQL inputs.
15
15
  *
@@ -41,6 +41,20 @@ import { StackTrail } from './StackTrail.js';
41
41
  import { isPlainObject } from '../parse/isPlainObject.js';
42
42
  import { toApplyingBrokenParameter, toNameAndIn } from '../parse/pathParameters.js';
43
43
  import { toSerializedError } from '../types/SerializedError.js';
44
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
45
+ import { toRefName } from '../helpers/refFns.js';
46
+ /**
47
+ * The key a `$ref`'s consumers and errors are kept under. A
48
+ * `#/components/<bucket>/…` ref is keyed by the name it resolves (`toRefName`
49
+ * unescapes it), which is the key `StackTrail.toStackRef()` gives that
50
+ * component's own errors: `#/components/schemas/Foo%20Bar` is kept under
51
+ * `#/components/schemas/Foo Bar`. Any other `$ref` is its own key.
52
+ */
53
+ const toRefKey = ($ref) => {
54
+ // The last segment is not empty, so `toRefName` does not throw.
55
+ const bucket = /^#\/components\/([^/]+)\/.*[^/]$/.exec($ref)?.[1];
56
+ return bucket === undefined ? $ref : `#/components/${bucket}/${toRefName($ref)}`;
57
+ };
44
58
  /** The stored form of an issue: an error's `cause` as a `SerializedError`. */
45
59
  const toParseIssue = (issue) => {
46
60
  if (issue.level !== 'error') {
@@ -113,6 +127,10 @@ export class ParseContext {
113
127
  // use type names. The maps don't care about the encoding.
114
128
  _ParseContext_refConsumers.set(this, new Map());
115
129
  _ParseContext_refErrors.set(this, new Map()
130
+ /** Each OAS ref and the place it is written, which `#checkRefs` resolves once the document is parsed. */
131
+ );
132
+ /** Each OAS ref and the place it is written, which `#checkRefs` resolves once the document is parsed. */
133
+ _ParseContext_oasRefs.set(this, []
116
134
  /**
117
135
  * Frames of the trail `parse()` was called with (`[traceId, spanId,
118
136
  * 'parse']` through `toArtifacts`). Every trail built during the walk
@@ -262,6 +280,7 @@ export class ParseContext {
262
280
  throw new Error(`Unhandled OAS dialect: ${JSON.stringify(_exhaustive)}`);
263
281
  }
264
282
  }
283
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_checkRefs).call(this);
265
284
  this.removeErroredItems();
266
285
  return { type: 'oas', value: oasState.oasDocument };
267
286
  }
@@ -361,6 +380,41 @@ export class ParseContext {
361
380
  __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").set(refKey, [consumer]);
362
381
  }
363
382
  }
383
+ /**
384
+ * Register an OAS `$ref` at its consumer site, as {@link registerRef}
385
+ * does, under the key {@link toRefKey} gives its `$ref`, and keep the ref
386
+ * with that site, so that once the document is parsed `#checkRefs` can
387
+ * resolve it there.
388
+ */
389
+ registerOasRef(consumer, ref) {
390
+ this.registerRef(consumer, toRefKey(ref.$ref));
391
+ __classPrivateFieldGet(this, _ParseContext_oasRefs, "f").push({ consumer, ref });
392
+ }
393
+ /**
394
+ * What a merge reads in place of a `$ref` that names nothing: an `allOf`
395
+ * member, or in a `oneOf` or `anyOf`, a member's own `allOf` member or a
396
+ * member merged with the keywords beside the union. When
397
+ * `system.danglingRefs` lists `allOfMember`, it is `{}`, which
398
+ * adds nothing to the merge (`A & unknown` is `A`), and a `DANGLING_REF`
399
+ * warning at `stackTrail`: the model has no properties from that member.
400
+ * Otherwise it throws `DanglingRefError`, and what holds the `allOf` is
401
+ * removed. It is separate from `schema`: here core decides, at parse, and
402
+ * the generator never sees the member.
403
+ */
404
+ toDanglingAllOfMember({ $ref, stackTrail }) {
405
+ const error = new DanglingRefError($ref);
406
+ if (!this.system.danglingRefs?.includes('allOfMember')) {
407
+ throw error;
408
+ }
409
+ this.logIssueNoKey({
410
+ level: 'warning',
411
+ message: `${error.message}. It is left out of the allOf merge (system.danglingRefs lists 'allOfMember').`,
412
+ parent: { $ref },
413
+ stackTrail,
414
+ type: 'DANGLING_REF'
415
+ });
416
+ return {};
417
+ }
364
418
  /**
365
419
  * Register an error against a ref key — typically called when the
366
420
  * target of a `$ref` (or type reference) fails to parse. `undefined`
@@ -512,7 +566,7 @@ export class ParseContext {
512
566
  });
513
567
  }
514
568
  }
515
- _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
569
+ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_oasRefs = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
516
570
  if (this.protocol.type !== 'oas') {
517
571
  return;
518
572
  }
@@ -625,4 +679,60 @@ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMa
625
679
  frames.length >= rootFrames.length &&
626
680
  rootFrames.every((frame, index) => frames[index] === frame);
627
681
  return startsWithRoot ? new StackTrail(frames.slice(rootFrames.length)) : stackTrail;
682
+ }, _ParseContext_checkRefs = function _ParseContext_checkRefs() {
683
+ __classPrivateFieldGet(this, _ParseContext_oasRefs, "f").forEach(({ consumer, ref }) => {
684
+ if (__classPrivateFieldGet(this, _ParseContext_refErrors, "f").has(toRefKey(ref.$ref))) {
685
+ return;
686
+ }
687
+ try {
688
+ ref.resolveOnce();
689
+ }
690
+ catch (error) {
691
+ if (!DanglingRefError.is(error)) {
692
+ const message = error instanceof Error ? error.message : String(error);
693
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeHolder).call(this, {
694
+ consumer,
695
+ ref,
696
+ error,
697
+ type: 'REF_TYPE_MISMATCH',
698
+ message: `${message}, so what holds it is removed.`
699
+ });
700
+ }
701
+ else if (this.system.danglingRefs?.includes(ref.refType)) {
702
+ this.logIssueNoKey({
703
+ level: 'warning',
704
+ message: `${error.message}. It is kept (system.danglingRefs lists '${ref.refType}'), and resolving it throws DanglingRefError.`,
705
+ parent: { $ref: ref.$ref },
706
+ stackTrail: consumer,
707
+ type: 'DANGLING_REF'
708
+ });
709
+ }
710
+ else {
711
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeHolder).call(this, {
712
+ consumer,
713
+ ref,
714
+ error,
715
+ type: 'DANGLING_REF',
716
+ message: `${error.message}, so what holds it is removed. To keep it, list '${ref.refType}' in system.danglingRefs.`
717
+ });
718
+ }
719
+ }
720
+ });
721
+ }, _ParseContext_removeHolder = function _ParseContext_removeHolder({ consumer, ref, error, type, message }) {
722
+ this.logIssueNoKey({
723
+ level: 'error',
724
+ message,
725
+ cause: error,
726
+ parent: { $ref: ref.$ref },
727
+ stackTrail: consumer,
728
+ type
729
+ });
730
+ const documentTrail = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, consumer);
731
+ if (documentTrail.toStackRef() !== undefined) {
732
+ return;
733
+ }
734
+ const location = consumer.toString();
735
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeConsumer).call(this, consumer, documentTrail)
736
+ .filter(removed => removed !== location)
737
+ .forEach(removed => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDependencyIssue).call(this, { location: removed, refKey: ref.$ref, rootCause: { error, location } }));
628
738
  };
@@ -185,11 +185,25 @@ export type AnyOasDocument = OpenAPIV2.Document | OpenAPIV3.Document | OpenAPIV3
185
185
  * of two or more members as any value. The schema keeps its other keywords.
186
186
  * One for each schema.
187
187
  *
188
+ * `DANGLING_REF` — a `$ref` names nothing in the document. One for each
189
+ * place the `$ref` is written. A `warning` when `system.danglingRefs` lists
190
+ * the `$ref`'s kind: the ref stays, and resolving it throws
191
+ * `DanglingRefError`; with `allOfMember` listed, a `$ref` that core merges
192
+ * (in an `allOf`, or in a `oneOf` or `anyOf` member) is left out of the
193
+ * merge. Otherwise (the default lists none)
194
+ * an `error`: what holds the ref is removed, and each item that uses it gets
195
+ * an `INVALID_DEPENDENCY_REF`.
196
+ *
197
+ * `REF_TYPE_MISMATCH` (`error`) — a `$ref` names a component of the wrong
198
+ * kind, such as a request body that is a `$ref` to
199
+ * `#/components/schemas/Pet`. One for each place the `$ref` is written. What
200
+ * holds the ref is removed; `system.danglingRefs` does not apply.
201
+ *
188
202
  * `RUN_FAILED` (`error`) — the run itself failed outside the per-item
189
203
  * catches. Its `location` names the entry and phase, for example
190
204
  * `toArtifacts:render`.
191
205
  */
192
- export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISSING_STRING_TYPE' | 'MISSING_ARRAY_TYPE' | 'MISSING_BOOLEAN_TYPE' | 'MISSING_RESPONSES' | 'MISSING_INFO' | 'EMPTY_PARAMETER' | 'INVALID_EXAMPLE' | 'INVALID_ENUM' | 'INVALID_DEFAULT' | 'INVALID_NULLABLE' | 'UNEXPECTED_FORMAT' | 'INVALID_RESPONSE' | 'INVALID_REQUEST_BODY' | 'INVALID_HEADER' | 'INVALID_FORMAT' | 'INVALID_OPERATION' | 'INVALID_SCHEMA' | 'INVALID_PARAMETER' | 'INVALID_SECURITY_SCHEME' | 'INVALID_DEPENDENCY_REF' | 'EXAMPLE_AND_EXAMPLES_DEFINED' | 'INVALID_TAG_PARENT' | 'INVALID_TAG' | 'INVALID_EXTERNAL_DOCS' | 'UNSUPPORTED_OPERATION_METHOD' | 'WILDCARD_MEDIA_TYPE' | 'NO_JSON_MEDIA_TYPE' | 'ALLOF_CONTRADICTION' | 'ANYOF_AS_UNKNOWN' | 'RUN_FAILED';
206
+ export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISSING_STRING_TYPE' | 'MISSING_ARRAY_TYPE' | 'MISSING_BOOLEAN_TYPE' | 'MISSING_RESPONSES' | 'MISSING_INFO' | 'EMPTY_PARAMETER' | 'INVALID_EXAMPLE' | 'INVALID_ENUM' | 'INVALID_DEFAULT' | 'INVALID_NULLABLE' | 'UNEXPECTED_FORMAT' | 'INVALID_RESPONSE' | 'INVALID_REQUEST_BODY' | 'INVALID_HEADER' | 'INVALID_FORMAT' | 'INVALID_OPERATION' | 'INVALID_SCHEMA' | 'INVALID_PARAMETER' | 'INVALID_SECURITY_SCHEME' | 'INVALID_DEPENDENCY_REF' | 'EXAMPLE_AND_EXAMPLES_DEFINED' | 'INVALID_TAG_PARENT' | 'INVALID_TAG' | 'INVALID_EXTERNAL_DOCS' | 'UNSUPPORTED_OPERATION_METHOD' | 'WILDCARD_MEDIA_TYPE' | 'NO_JSON_MEDIA_TYPE' | 'ALLOF_CONTRADICTION' | 'ANYOF_AS_UNKNOWN' | 'DANGLING_REF' | 'REF_TYPE_MISMATCH' | 'RUN_FAILED';
193
207
  /**
194
208
  * Valibot schema for {@link OasIssueType}. Annotation deliberately omitted
195
209
  * so the precise literal-union output type flows through to consumers
@@ -197,7 +211,7 @@ export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISS
197
211
  * this list and {@link OasIssueType} is caught by `assertSchemaMatchesType`
198
212
  * below.
199
213
  */
200
- export declare const oasIssueType: v.UnionSchema<[v.LiteralSchema<"UNEXPECTED_PROPERTY", undefined>, v.LiteralSchema<"MISSING_OBJECT_TYPE", undefined>, v.LiteralSchema<"MISSING_STRING_TYPE", undefined>, v.LiteralSchema<"MISSING_ARRAY_TYPE", undefined>, v.LiteralSchema<"MISSING_BOOLEAN_TYPE", undefined>, v.LiteralSchema<"MISSING_RESPONSES", undefined>, v.LiteralSchema<"MISSING_INFO", undefined>, v.LiteralSchema<"EMPTY_PARAMETER", undefined>, v.LiteralSchema<"INVALID_EXAMPLE", undefined>, v.LiteralSchema<"INVALID_ENUM", undefined>, v.LiteralSchema<"INVALID_DEFAULT", undefined>, v.LiteralSchema<"INVALID_NULLABLE", undefined>, v.LiteralSchema<"UNEXPECTED_FORMAT", undefined>, v.LiteralSchema<"INVALID_RESPONSE", undefined>, v.LiteralSchema<"INVALID_REQUEST_BODY", undefined>, v.LiteralSchema<"INVALID_HEADER", undefined>, v.LiteralSchema<"INVALID_FORMAT", undefined>, v.LiteralSchema<"INVALID_OPERATION", undefined>, v.LiteralSchema<"INVALID_SCHEMA", undefined>, v.LiteralSchema<"INVALID_PARAMETER", undefined>, v.LiteralSchema<"INVALID_SECURITY_SCHEME", undefined>, v.LiteralSchema<"INVALID_DEPENDENCY_REF", undefined>, v.LiteralSchema<"EXAMPLE_AND_EXAMPLES_DEFINED", undefined>, v.LiteralSchema<"INVALID_TAG_PARENT", undefined>, v.LiteralSchema<"INVALID_TAG", undefined>, v.LiteralSchema<"INVALID_EXTERNAL_DOCS", undefined>, v.LiteralSchema<"UNSUPPORTED_OPERATION_METHOD", undefined>, v.LiteralSchema<"WILDCARD_MEDIA_TYPE", undefined>, v.LiteralSchema<"NO_JSON_MEDIA_TYPE", undefined>, v.LiteralSchema<"ALLOF_CONTRADICTION", undefined>, v.LiteralSchema<"ANYOF_AS_UNKNOWN", undefined>, v.LiteralSchema<"RUN_FAILED", undefined>], undefined>;
214
+ export declare const oasIssueType: v.UnionSchema<[v.LiteralSchema<"UNEXPECTED_PROPERTY", undefined>, v.LiteralSchema<"MISSING_OBJECT_TYPE", undefined>, v.LiteralSchema<"MISSING_STRING_TYPE", undefined>, v.LiteralSchema<"MISSING_ARRAY_TYPE", undefined>, v.LiteralSchema<"MISSING_BOOLEAN_TYPE", undefined>, v.LiteralSchema<"MISSING_RESPONSES", undefined>, v.LiteralSchema<"MISSING_INFO", undefined>, v.LiteralSchema<"EMPTY_PARAMETER", undefined>, v.LiteralSchema<"INVALID_EXAMPLE", undefined>, v.LiteralSchema<"INVALID_ENUM", undefined>, v.LiteralSchema<"INVALID_DEFAULT", undefined>, v.LiteralSchema<"INVALID_NULLABLE", undefined>, v.LiteralSchema<"UNEXPECTED_FORMAT", undefined>, v.LiteralSchema<"INVALID_RESPONSE", undefined>, v.LiteralSchema<"INVALID_REQUEST_BODY", undefined>, v.LiteralSchema<"INVALID_HEADER", undefined>, v.LiteralSchema<"INVALID_FORMAT", undefined>, v.LiteralSchema<"INVALID_OPERATION", undefined>, v.LiteralSchema<"INVALID_SCHEMA", undefined>, v.LiteralSchema<"INVALID_PARAMETER", undefined>, v.LiteralSchema<"INVALID_SECURITY_SCHEME", undefined>, v.LiteralSchema<"INVALID_DEPENDENCY_REF", undefined>, v.LiteralSchema<"EXAMPLE_AND_EXAMPLES_DEFINED", undefined>, v.LiteralSchema<"INVALID_TAG_PARENT", undefined>, v.LiteralSchema<"INVALID_TAG", undefined>, v.LiteralSchema<"INVALID_EXTERNAL_DOCS", undefined>, v.LiteralSchema<"UNSUPPORTED_OPERATION_METHOD", undefined>, v.LiteralSchema<"WILDCARD_MEDIA_TYPE", undefined>, v.LiteralSchema<"NO_JSON_MEDIA_TYPE", undefined>, v.LiteralSchema<"ALLOF_CONTRADICTION", undefined>, v.LiteralSchema<"ANYOF_AS_UNKNOWN", undefined>, v.LiteralSchema<"DANGLING_REF", undefined>, v.LiteralSchema<"REF_TYPE_MISMATCH", undefined>, v.LiteralSchema<"RUN_FAILED", undefined>], undefined>;
201
215
  export type GenerateResult = {
202
216
  files: Map<string, FileBase>;
203
217
  previews: Record<string, Preview>;
@@ -38,6 +38,8 @@ export const oasIssueType = v.union([
38
38
  v.literal('NO_JSON_MEDIA_TYPE'),
39
39
  v.literal('ALLOF_CONTRADICTION'),
40
40
  v.literal('ANYOF_AS_UNKNOWN'),
41
+ v.literal('DANGLING_REF'),
42
+ v.literal('REF_TYPE_MISMATCH'),
41
43
  v.literal('RUN_FAILED')
42
44
  ]);
43
45
  // Compile-time drift detector: this binding fails to type-check if
@@ -60,7 +60,10 @@ export type TryParseAtArgs<T> = {
60
60
  * Run `fn(childStack)` inside `stackTrail.trace(key, ...)`. On throw:
61
61
  *
62
62
  * - logs a `level: 'error'` issue at the child location with the
63
- * given `type` and the thrown value as `cause`
63
+ * given `type` and the thrown value as `cause`. A `DanglingRefError`
64
+ * is logged as `DANGLING_REF`: core resolved a ref while it parsed (one
65
+ * it merges, in an `allOf` or a `oneOf` or `anyOf` member, when
66
+ * `system.danglingRefs` does not list `allOfMember`)
64
67
  * - registers a ref error if `refKey` is provided
65
68
  * - returns `undefined`
66
69
  *
@@ -19,11 +19,15 @@
19
19
  * logging into one call so both surfaces share the failure-handling
20
20
  * shape verbatim.
21
21
  */
22
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
22
23
  /**
23
24
  * Run `fn(childStack)` inside `stackTrail.trace(key, ...)`. On throw:
24
25
  *
25
26
  * - logs a `level: 'error'` issue at the child location with the
26
- * given `type` and the thrown value as `cause`
27
+ * given `type` and the thrown value as `cause`. A `DanglingRefError`
28
+ * is logged as `DANGLING_REF`: core resolved a ref while it parsed (one
29
+ * it merges, in an `allOf` or a `oneOf` or `anyOf` member, when
30
+ * `system.danglingRefs` does not list `allOfMember`)
27
31
  * - registers a ref error if `refKey` is provided
28
32
  * - returns `undefined`
29
33
  *
@@ -35,6 +39,7 @@ export const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn
35
39
  }
36
40
  catch (error) {
37
41
  const normalized = error instanceof Error ? error : new Error(String(error));
42
+ const dangling = DanglingRefError.is(error);
38
43
  stackTrail.trace(key, childStack => {
39
44
  if (refKey !== undefined) {
40
45
  context.registerRefError(error, refKey, childStack.toString());
@@ -43,9 +48,11 @@ export const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn
43
48
  level: 'error',
44
49
  stackTrail: childStack,
45
50
  parent,
46
- message: normalized.message,
51
+ message: dangling
52
+ ? `${normalized.message}. Core resolves it while it parses, so what holds it is removed.`
53
+ : normalized.message,
47
54
  cause: normalized,
48
- type
55
+ type: dangling ? 'DANGLING_REF' : type
49
56
  });
50
57
  });
51
58
  return undefined;
@@ -1,5 +1,6 @@
1
1
  import "../_dnt.polyfills.js";
2
2
  import { isEmpty } from './isEmpty.js';
3
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
3
4
  /**
4
5
  * Recursively collates and builds example values from OpenAPI schemas.
5
6
  *
@@ -165,11 +166,20 @@ export const collateExamples = ({ objectSchema, depth, seen }) => {
165
166
  if (seen?.has(objectSchema.$ref)) {
166
167
  return undefined;
167
168
  }
168
- return collateExamples({
169
- objectSchema: objectSchema.resolve(),
170
- depth: depth + 1,
171
- seen: new Set(seen ?? []).add(objectSchema.$ref)
172
- });
169
+ try {
170
+ return collateExamples({
171
+ objectSchema: objectSchema.resolve(),
172
+ depth: depth + 1,
173
+ seen: new Set(seen ?? []).add(objectSchema.$ref)
174
+ });
175
+ }
176
+ catch (error) {
177
+ // A dangling reference names no schema, so it has no example either.
178
+ if (DanglingRefError.is(error)) {
179
+ return undefined;
180
+ }
181
+ throw error;
182
+ }
173
183
  }
174
184
  case 'object': {
175
185
  if (objectSchema.example) {
@@ -9,6 +9,10 @@ import type { ReferenceObject } from '../parse/v3-0/_merge-all-of/types.js';
9
9
  * and extracts the final component as a branded RefName type. It's used throughout
10
10
  * the SKMTC system to convert string references into type-safe reference names.
11
11
  *
12
+ * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
13
+ * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
14
+ * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
15
+ *
12
16
  * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
13
17
  * @returns The extracted reference name as a branded RefName type
14
18
  *
@@ -117,7 +121,7 @@ export declare const isRef: (value: unknown) => value is Ref;
117
121
  * @param oasDocument - The OpenAPI document containing the schemas to resolve against
118
122
  * @returns A function that resolves reference objects to schema objects
119
123
  *
120
- * @throws {Error} When a reference cannot be resolved or points to a non-existent schema
124
+ * @throws {DanglingRefError} When a reference names no schema in the document
121
125
  *
122
126
  * @example Basic usage
123
127
  * ```typescript
@@ -148,7 +152,7 @@ export declare const isRef: (value: unknown) => value is Ref;
148
152
  * const schema = resolver({ $ref: '#/components/schemas/NonExistent' });
149
153
  * } catch (error) {
150
154
  * console.error('Reference resolution failed:', error.message);
151
- * // Error: Invalid reference: #/components/schemas/NonExistent
155
+ * // Ref "#/components/schemas/NonExistent" names nothing in the document
152
156
  * }
153
157
  * ```
154
158
  *
@@ -167,5 +171,7 @@ export declare const isRef: (value: unknown) => value is Ref;
167
171
  * }
168
172
  * ```
169
173
  */
170
- export declare const toGetRef: (oasDocument: OpenAPIV3.Document) => ({ $ref }: ReferenceObject) => OpenAPIV3.SchemaObject;
174
+ export declare const toGetRef: (oasDocument: OpenAPIV3.Document, onDangling?: OnDangling) => ({ $ref }: ReferenceObject) => OpenAPIV3.SchemaObject;
175
+ /** What a resolver reads in place of a `$ref` that names nothing; it may throw. */
176
+ type OnDangling = ($ref: string) => OpenAPIV3.SchemaObject;
171
177
  export {};
@@ -1,4 +1,5 @@
1
1
  import "../_dnt.polyfills.js";
2
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
2
3
  /**
3
4
  * Extracts a reference name from an OpenAPI $ref string.
4
5
  *
@@ -6,6 +7,10 @@ import "../_dnt.polyfills.js";
6
7
  * and extracts the final component as a branded RefName type. It's used throughout
7
8
  * the SKMTC system to convert string references into type-safe reference names.
8
9
  *
10
+ * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
11
+ * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
12
+ * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
13
+ *
9
14
  * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
10
15
  * @returns The extracted reference name as a branded RefName type
11
16
  *
@@ -41,12 +46,24 @@ import "../_dnt.polyfills.js";
41
46
  * ```
42
47
  */
43
48
  export const toRefName = ($ref) => {
44
- // TODO: Add validation here to ensure reference exists
45
- const refName = $ref.split('/').slice(-1)[0];
46
- if (!refName) {
49
+ const segment = $ref.split('/').slice(-1)[0];
50
+ if (!segment) {
47
51
  throw new Error('Invalid reference');
48
52
  }
49
- return refName;
53
+ return toUnescapedSegment(segment);
54
+ };
55
+ /** A JSON pointer segment of a URI fragment, unescaped: percent escapes first, then `~1` and `~0`. */
56
+ const toUnescapedSegment = (segment) => {
57
+ return toPercentDecoded(segment).replaceAll('~1', '/').replaceAll('~0', '~');
58
+ };
59
+ const toPercentDecoded = (segment) => {
60
+ try {
61
+ return decodeURIComponent(segment);
62
+ }
63
+ catch {
64
+ // A `%` that starts no valid escape is read as written.
65
+ return segment;
66
+ }
50
67
  };
51
68
  /**
52
69
  * Type guard function to check if a value is an OpenAPI reference object.
@@ -121,7 +138,7 @@ export const isRef = (value) => {
121
138
  * @param oasDocument - The OpenAPI document containing the schemas to resolve against
122
139
  * @returns A function that resolves reference objects to schema objects
123
140
  *
124
- * @throws {Error} When a reference cannot be resolved or points to a non-existent schema
141
+ * @throws {DanglingRefError} When a reference names no schema in the document
125
142
  *
126
143
  * @example Basic usage
127
144
  * ```typescript
@@ -152,7 +169,7 @@ export const isRef = (value) => {
152
169
  * const schema = resolver({ $ref: '#/components/schemas/NonExistent' });
153
170
  * } catch (error) {
154
171
  * console.error('Reference resolution failed:', error.message);
155
- * // Error: Invalid reference: #/components/schemas/NonExistent
172
+ * // Ref "#/components/schemas/NonExistent" names nothing in the document
156
173
  * }
157
174
  * ```
158
175
  *
@@ -171,14 +188,17 @@ export const isRef = (value) => {
171
188
  * }
172
189
  * ```
173
190
  */
174
- export const toGetRef = (oasDocument) => ({ $ref }) => {
191
+ export const toGetRef = (oasDocument, onDangling) => ({ $ref }) => {
175
192
  const refName = toRefName($ref);
176
193
  const item = oasDocument.components?.schemas?.[refName];
177
194
  if (isRef(item)) {
178
- return toGetRef(oasDocument)(item);
195
+ return toGetRef(oasDocument, onDangling)(item);
179
196
  }
180
197
  if (item) {
181
198
  return item;
182
199
  }
183
- throw new Error(`Invalid reference: ${$ref}`);
200
+ if (onDangling) {
201
+ return onDangling($ref);
202
+ }
203
+ throw new DanglingRefError($ref);
184
204
  };
package/esm/mod.d.ts CHANGED
@@ -163,6 +163,7 @@ export * from './oas/parameter/Parameter.js';
163
163
  export * from './oas/parameter/parameter-types.js';
164
164
  export * from './oas/pathItem/PathItem.js';
165
165
  export * from './oas/ref/Ref.js';
166
+ export * from './oas/ref/DanglingRefError.js';
166
167
  export * from './oas/ref/ref-types.js';
167
168
  export * from './parse/v3-0/ref/toRefV31.js';
168
169
  export * from './oas/requestBody/RequestBody.js';
package/esm/mod.js CHANGED
@@ -163,6 +163,7 @@ export * from './oas/parameter/Parameter.js';
163
163
  export * from './oas/parameter/parameter-types.js';
164
164
  export * from './oas/pathItem/PathItem.js';
165
165
  export * from './oas/ref/Ref.js';
166
+ export * from './oas/ref/DanglingRefError.js';
166
167
  export * from './oas/ref/ref-types.js';
167
168
  export * from './parse/v3-0/ref/toRefV31.js';
168
169
  export * from './oas/requestBody/RequestBody.js';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Thrown when a reference that names nothing in the document is resolved.
3
+ *
4
+ * By default the parser removes what holds such a reference, so a generator
5
+ * never meets one. When `client.json` `system.danglingRefs` lists the
6
+ * reference's kind, it stays, and a generator that resolves it can catch
7
+ * this error and render something else in its place. Test for it with
8
+ * {@link DanglingRefError.is}, not `instanceof`.
9
+ */
10
+ import "../../_dnt.polyfills.js";
11
+ export declare class DanglingRefError extends Error {
12
+ /** The `$ref`, or the component name, that names nothing. */
13
+ ref: string;
14
+ constructor(ref: string);
15
+ /**
16
+ * True when `error` is a `DanglingRefError`. It reads the error's name,
17
+ * not its class, so it is also true for one thrown by another copy of
18
+ * `@skmtc/core`, such as the copy a generator bundle resolves, where
19
+ * `instanceof` is false.
20
+ */
21
+ static is(error: unknown): error is DanglingRefError;
22
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Thrown when a reference that names nothing in the document is resolved.
3
+ *
4
+ * By default the parser removes what holds such a reference, so a generator
5
+ * never meets one. When `client.json` `system.danglingRefs` lists the
6
+ * reference's kind, it stays, and a generator that resolves it can catch
7
+ * this error and render something else in its place. Test for it with
8
+ * {@link DanglingRefError.is}, not `instanceof`.
9
+ */
10
+ import "../../_dnt.polyfills.js";
11
+ export class DanglingRefError extends Error {
12
+ constructor(ref) {
13
+ super(`Ref "${ref}" names nothing in the document`);
14
+ /** The `$ref`, or the component name, that names nothing. */
15
+ Object.defineProperty(this, "ref", {
16
+ enumerable: true,
17
+ configurable: true,
18
+ writable: true,
19
+ value: void 0
20
+ });
21
+ this.name = 'DanglingRefError';
22
+ this.ref = ref;
23
+ }
24
+ /**
25
+ * True when `error` is a `DanglingRefError`. It reads the error's name,
26
+ * not its class, so it is also true for one thrown by another copy of
27
+ * `@skmtc/core`, such as the copy a generator bundle resolves, where
28
+ * `instanceof` is false.
29
+ */
30
+ static is(error) {
31
+ return error instanceof Error && error.name === 'DanglingRefError';
32
+ }
33
+ }
@@ -232,6 +232,11 @@ export declare class OasRef<T extends OasRefData['refType']> extends OasBase {
232
232
  * reads from `document.registry.schemas`.
233
233
  *
234
234
  * @returns Either the resolved component or another reference in the chain
235
+ * @throws {DanglingRefError} when the reference names nothing in the
236
+ * document (kept when `client.json` `system.danglingRefs` lists its kind),
237
+ * including a `$ref` with no name, such as `#/components/schemas/`
238
+ * @throws Error when it names a component of another kind, such as a
239
+ * `requestBody` ref to `#/components/schemas/…`
235
240
  */
236
241
  resolveOnce(): OasRef<T> | ResolvedRef<T>;
237
242
  toRefName(): RefName;