@skmtc/core 0.40.0 → 0.41.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 (77) 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 +9 -0
  4. package/esm/context/ParseContext.js +90 -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 +6 -2
  11. package/esm/helpers/refFns.js +24 -7
  12. package/esm/mod.d.ts +1 -0
  13. package/esm/mod.js +1 -0
  14. package/esm/oas/operation/Operation.d.ts +4 -1
  15. package/esm/oas/operation/Operation.js +6 -5
  16. package/esm/oas/operation/toEffectiveParameters.d.ts +8 -0
  17. package/esm/oas/operation/toEffectiveParameters.js +32 -3
  18. package/esm/oas/ref/DanglingRefError.d.ts +22 -0
  19. package/esm/oas/ref/DanglingRefError.js +33 -0
  20. package/esm/oas/ref/Ref.d.ts +5 -0
  21. package/esm/oas/ref/Ref.js +28 -2
  22. package/esm/oas/schema/siblings.js +12 -2
  23. package/esm/oas/union/Union.d.ts +2 -1
  24. package/esm/oas/union/Union.js +23 -12
  25. package/esm/oas/webhook/Webhook.js +2 -4
  26. package/esm/parse/securityRequirements.d.ts +6 -0
  27. package/esm/parse/securityRequirements.js +8 -0
  28. package/esm/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  29. package/esm/parse/v3-0/parameter/toParameterV3.js +4 -3
  30. package/esm/parse/v3-0/ref/toRefV31.js +5 -2
  31. package/esm/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  32. package/esm/parse/v3-1/parameter/toParameterV3.js +4 -3
  33. package/esm/parse/v3-1/ref/toRefV31.js +5 -2
  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/types/Settings.d.ts +10 -0
  38. package/esm/types/Settings.js +2 -1
  39. package/package.json +5 -1
  40. package/script/context/GenerateContext.d.ts +1 -1
  41. package/script/context/GenerateContext.js +4 -3
  42. package/script/context/ParseContext.d.ts +9 -0
  43. package/script/context/ParseContext.js +90 -2
  44. package/script/context/generateTypes.d.ts +16 -2
  45. package/script/context/generateTypes.js +2 -0
  46. package/script/context/tryParseAt.d.ts +4 -1
  47. package/script/context/tryParseAt.js +10 -3
  48. package/script/helpers/collateExamples.js +15 -5
  49. package/script/helpers/refFns.d.ts +6 -2
  50. package/script/helpers/refFns.js +24 -7
  51. package/script/mod.d.ts +1 -0
  52. package/script/mod.js +1 -0
  53. package/script/oas/operation/Operation.d.ts +4 -1
  54. package/script/oas/operation/Operation.js +5 -4
  55. package/script/oas/operation/toEffectiveParameters.d.ts +8 -0
  56. package/script/oas/operation/toEffectiveParameters.js +34 -4
  57. package/script/oas/ref/DanglingRefError.d.ts +22 -0
  58. package/script/oas/ref/DanglingRefError.js +37 -0
  59. package/script/oas/ref/Ref.d.ts +5 -0
  60. package/script/oas/ref/Ref.js +28 -2
  61. package/script/oas/schema/siblings.js +12 -2
  62. package/script/oas/union/Union.d.ts +2 -1
  63. package/script/oas/union/Union.js +23 -12
  64. package/script/oas/webhook/Webhook.js +1 -3
  65. package/script/parse/securityRequirements.d.ts +6 -0
  66. package/script/parse/securityRequirements.js +8 -0
  67. package/script/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  68. package/script/parse/v3-0/parameter/toParameterV3.js +4 -3
  69. package/script/parse/v3-0/ref/toRefV31.js +5 -2
  70. package/script/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  71. package/script/parse/v3-1/parameter/toParameterV3.js +4 -3
  72. package/script/parse/v3-1/ref/toRefV31.js +5 -2
  73. package/script/parse/v3-2/mediaType/toMediaTypeItemV3.js +4 -3
  74. package/script/parse/v3-2/parameter/toParameterV3.js +4 -3
  75. package/script/parse/v3-2/ref/toRefV31.js +5 -2
  76. package/script/types/Settings.d.ts +10 -0
  77. package/script/types/Settings.js +2 -1
@@ -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 = {
@@ -157,6 +159,13 @@ export declare class ParseContext {
157
159
  * would use type names or qualified field paths.
158
160
  */
159
161
  registerRef(consumer: StackTrail, refKey: string): void;
162
+ /**
163
+ * Register an OAS `$ref` at its consumer site, as {@link registerRef}
164
+ * does, under the key {@link toRefKey} gives its `$ref`, and keep the ref
165
+ * with that site, so that once the document is parsed `#checkRefs` can
166
+ * resolve it there.
167
+ */
168
+ registerOasRef<T extends OasRefData['refType']>(consumer: StackTrail, ref: OasRef<T>): void;
160
169
  /**
161
170
  * Register an error against a ref key — typically called when the
162
171
  * 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_logDanglingRef;
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,16 @@ 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
+ }
364
393
  /**
365
394
  * Register an error against a ref key — typically called when the
366
395
  * target of a `$ref` (or type reference) fails to parse. `undefined`
@@ -512,7 +541,7 @@ export class ParseContext {
512
541
  });
513
542
  }
514
543
  }
515
- _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
544
+ _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
545
  if (this.protocol.type !== 'oas') {
517
546
  return;
518
547
  }
@@ -625,4 +654,63 @@ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMa
625
654
  frames.length >= rootFrames.length &&
626
655
  rootFrames.every((frame, index) => frames[index] === frame);
627
656
  return startsWithRoot ? new StackTrail(frames.slice(rootFrames.length)) : stackTrail;
657
+ }, _ParseContext_checkRefs = function _ParseContext_checkRefs() {
658
+ __classPrivateFieldGet(this, _ParseContext_oasRefs, "f").forEach(({ consumer, ref }) => {
659
+ if (__classPrivateFieldGet(this, _ParseContext_refErrors, "f").has(toRefKey(ref.$ref))) {
660
+ return;
661
+ }
662
+ try {
663
+ ref.resolveOnce();
664
+ }
665
+ catch (error) {
666
+ if (DanglingRefError.is(error)) {
667
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDanglingRef).call(this, { consumer, ref, error });
668
+ }
669
+ else {
670
+ this.logIssueNoKey({
671
+ level: 'warning',
672
+ message: `${error instanceof Error ? error.message : String(error)}. It is kept, and resolving it throws.`,
673
+ parent: { $ref: ref.$ref },
674
+ stackTrail: consumer,
675
+ type: 'REF_TYPE_MISMATCH'
676
+ });
677
+ }
678
+ }
679
+ });
680
+ }, _ParseContext_logDanglingRef = function _ParseContext_logDanglingRef({ consumer, ref, error }) {
681
+ const exampleOrLink = ref.refType === 'example' || ref.refType === 'link';
682
+ if (exampleOrLink || this.system.danglingRefs === 'keep') {
683
+ this.logIssueNoKey({
684
+ level: 'warning',
685
+ message: exampleOrLink
686
+ ? `${error.message}. It is kept, as a ref to an example or a link is in both system.danglingRefs modes, and resolving it throws DanglingRefError.`
687
+ : `${error.message}. It is kept (system.danglingRefs is keep), and resolving it throws DanglingRefError.`,
688
+ parent: { $ref: ref.$ref },
689
+ stackTrail: consumer,
690
+ type: 'DANGLING_REF'
691
+ });
692
+ return;
693
+ }
694
+ // An error inside a component removes that component, and what uses it
695
+ // (`removeErroredItems`).
696
+ this.logIssueNoKey({
697
+ level: 'error',
698
+ message: `${error.message}, so what holds it is removed (system.danglingRefs is strict).`,
699
+ cause: error,
700
+ parent: { $ref: ref.$ref },
701
+ stackTrail: consumer,
702
+ type: 'DANGLING_REF'
703
+ });
704
+ // What holds the ref outside the components (an operation, a webhook, a
705
+ // path-level parameter) is removed here. Its own location has the
706
+ // DANGLING_REF already; an operation that a path-level parameter applies
707
+ // to gets an INVALID_DEPENDENCY_REF.
708
+ const documentTrail = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, consumer);
709
+ if (documentTrail.toStackRef() !== undefined) {
710
+ return;
711
+ }
712
+ const location = consumer.toString();
713
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeConsumer).call(this, consumer, documentTrail)
714
+ .filter(removed => removed !== location)
715
+ .forEach(removed => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDependencyIssue).call(this, { location: removed, refKey: ref.$ref, rootCause: { error, location } }));
628
716
  };
@@ -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. An `error` under `system.danglingRefs:
190
+ * strict` (the default): what holds the ref is removed, and each item that
191
+ * uses it gets an `INVALID_DEPENDENCY_REF`. A `warning` under `keep`: the
192
+ * ref stays, and resolving it throws `DanglingRefError`. A ref to an example
193
+ * or a link is a `warning` in both modes. A ref that core resolves while it
194
+ * parses (an `allOf` member that it merges) is an `error` in both modes, at
195
+ * the item that holds it.
196
+ *
197
+ * `REF_TYPE_MISMATCH` (`warning`) — 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. The
200
+ * ref stays, and resolving it throws.
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 (an
65
+ * `allOf` member it merges, say), so the ref cannot be kept, whatever
66
+ * `system.danglingRefs` is
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 (an
29
+ * `allOf` member it merges, say), so the ref cannot be kept, whatever
30
+ * `system.danglingRefs` is
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 whatever system.danglingRefs is.`
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
  *
@@ -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
  *
@@ -180,5 +197,5 @@ export const toGetRef = (oasDocument) => ({ $ref }) => {
180
197
  if (item) {
181
198
  return item;
182
199
  }
183
- throw new Error(`Invalid reference: ${$ref}`);
200
+ throw new DanglingRefError($ref);
184
201
  };
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';
@@ -151,7 +151,10 @@ export declare class OasOperation extends OasBase {
151
151
  *
152
152
  * As OpenAPI defines them: the path item's parameters apply to each of its
153
153
  * operations, and an operation's own parameter with the same name and
154
- * location replaces the path item's. The path item's come first.
154
+ * location replaces the path item's. The path item's come first. A
155
+ * reference that names nothing (kept under `system.danglingRefs: keep`) is
156
+ * left out: it has no name or location, and the parser logged a
157
+ * `DANGLING_REF` warning for it.
155
158
  *
156
159
  * @param filter - only include parameters from specified locations
157
160
  * @returns
@@ -3,7 +3,7 @@ import { traverseSchema } from '../schemaPath/traverseSchema.js';
3
3
  import { OasObject } from '../object/Object.js';
4
4
  import { toPrimaryResponseCode } from '../response/toPrimaryResponseCode.js';
5
5
  import { OasBase } from '../../types/OasBase.js';
6
- import { toEffectiveParameters } from './toEffectiveParameters.js';
6
+ import { toEffectiveParameters, toResolvedParameters } from './toEffectiveParameters.js';
7
7
  export class OasOperation extends OasBase {
8
8
  /**
9
9
  * Creates a new OasOperation instance from operation field data.
@@ -223,15 +223,16 @@ export class OasOperation extends OasBase {
223
223
  *
224
224
  * As OpenAPI defines them: the path item's parameters apply to each of its
225
225
  * operations, and an operation's own parameter with the same name and
226
- * location replaces the path item's. The path item's come first.
226
+ * location replaces the path item's. The path item's come first. A
227
+ * reference that names nothing (kept under `system.danglingRefs: keep`) is
228
+ * left out: it has no name or location, and the parser logged a
229
+ * `DANGLING_REF` warning for it.
227
230
  *
228
231
  * @param filter - only include parameters from specified locations
229
232
  * @returns
230
233
  */
231
234
  toParams(filter) {
232
- return toEffectiveParameters({ own: this.parameters, shared: this.pathItem?.parameters })
233
- .map(param => param.resolve())
234
- .filter(param => (filter?.length ? filter.includes(param.location) : true));
235
+ return toResolvedParameters(toEffectiveParameters({ own: this.parameters, shared: this.pathItem?.parameters })).filter(param => (filter?.length ? filter.includes(param.location) : true));
235
236
  }
236
237
  /**
237
238
  * Creates an OAS object representation of operation parameters.
@@ -11,6 +11,14 @@ type ToEffectiveParametersArgs = {
11
11
  * The parameters that apply to an operation or webhook, as OpenAPI defines
12
12
  * them: the path item's first, then its own. An own parameter with the same
13
13
  * name and location replaces the path item's. References stay references.
14
+ * A reference that names nothing (kept under `system.danglingRefs: keep`)
15
+ * has no name or location, so it replaces nothing and nothing replaces it.
14
16
  */
15
17
  export declare const toEffectiveParameters: ({ own, shared }: ToEffectiveParametersArgs) => Parameter[];
18
+ /**
19
+ * Resolves each parameter. A reference that names nothing is left out: it
20
+ * has no name or location to render, and the parser logged a `DANGLING_REF`
21
+ * warning for it.
22
+ */
23
+ export declare const toResolvedParameters: (parameters: Parameter[]) => OasParameter[];
16
24
  export {};
@@ -1,13 +1,42 @@
1
+ import { DanglingRefError } from '../ref/DanglingRefError.js';
1
2
  /**
2
3
  * The parameters that apply to an operation or webhook, as OpenAPI defines
3
4
  * them: the path item's first, then its own. An own parameter with the same
4
5
  * name and location replaces the path item's. References stay references.
6
+ * A reference that names nothing (kept under `system.danglingRefs: keep`)
7
+ * has no name or location, so it replaces nothing and nothing replaces it.
5
8
  */
6
9
  export const toEffectiveParameters = ({ own = [], shared = [] }) => {
7
10
  const ownKeys = new Set(own.map(toParameterKey));
8
- return [...shared.filter(parameter => !ownKeys.has(toParameterKey(parameter))), ...own];
11
+ return [
12
+ ...shared.filter(parameter => {
13
+ const key = toParameterKey(parameter);
14
+ return key === undefined || !ownKeys.has(key);
15
+ }),
16
+ ...own
17
+ ];
9
18
  };
19
+ /**
20
+ * Resolves each parameter. A reference that names nothing is left out: it
21
+ * has no name or location to render, and the parser logged a `DANGLING_REF`
22
+ * warning for it.
23
+ */
24
+ export const toResolvedParameters = (parameters) => parameters.flatMap(parameter => {
25
+ const resolved = toResolvedParameter(parameter);
26
+ return resolved === undefined ? [] : [resolved];
27
+ });
10
28
  const toParameterKey = (parameter) => {
11
- const { name, location } = parameter.resolve();
12
- return `${location}:${name}`;
29
+ const resolved = toResolvedParameter(parameter);
30
+ return resolved === undefined ? undefined : `${resolved.location}:${resolved.name}`;
31
+ };
32
+ const toResolvedParameter = (parameter) => {
33
+ try {
34
+ return parameter.resolve();
35
+ }
36
+ catch (error) {
37
+ if (DanglingRefError.is(error)) {
38
+ return undefined;
39
+ }
40
+ throw error;
41
+ }
13
42
  };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Thrown when a reference that names nothing in the document is resolved.
3
+ *
4
+ * Under `client.json` `system.danglingRefs: strict` (the default) the parser
5
+ * removes what holds such a reference, so a generator never meets one. Under
6
+ * `keep` the reference 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
+ * Under `client.json` `system.danglingRefs: strict` (the default) the parser
5
+ * removes what holds such a reference, so a generator never meets one. Under
6
+ * `keep` the reference 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 under `client.json` `system.danglingRefs: keep`),
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;