@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
@@ -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>;
@@ -74,6 +74,8 @@ exports.oasIssueType = v.union([
74
74
  v.literal('NO_JSON_MEDIA_TYPE'),
75
75
  v.literal('ALLOF_CONTRADICTION'),
76
76
  v.literal('ANYOF_AS_UNKNOWN'),
77
+ v.literal('DANGLING_REF'),
78
+ v.literal('REF_TYPE_MISMATCH'),
77
79
  v.literal('RUN_FAILED')
78
80
  ]);
79
81
  // 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
  *
@@ -22,11 +22,15 @@
22
22
  */
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.tryParseAt = void 0;
25
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
25
26
  /**
26
27
  * Run `fn(childStack)` inside `stackTrail.trace(key, ...)`. On throw:
27
28
  *
28
29
  * - logs a `level: 'error'` issue at the child location with the
29
- * given `type` and the thrown value as `cause`
30
+ * given `type` and the thrown value as `cause`. A `DanglingRefError`
31
+ * is logged as `DANGLING_REF`: core resolved a ref while it parsed (an
32
+ * `allOf` member it merges, say), so the ref cannot be kept, whatever
33
+ * `system.danglingRefs` is
30
34
  * - registers a ref error if `refKey` is provided
31
35
  * - returns `undefined`
32
36
  *
@@ -38,6 +42,7 @@ const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn }) => {
38
42
  }
39
43
  catch (error) {
40
44
  const normalized = error instanceof Error ? error : new Error(String(error));
45
+ const dangling = DanglingRefError_js_1.DanglingRefError.is(error);
41
46
  stackTrail.trace(key, childStack => {
42
47
  if (refKey !== undefined) {
43
48
  context.registerRefError(error, refKey, childStack.toString());
@@ -46,9 +51,11 @@ const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn }) => {
46
51
  level: 'error',
47
52
  stackTrail: childStack,
48
53
  parent,
49
- message: normalized.message,
54
+ message: dangling
55
+ ? `${normalized.message}. Core resolves it while it parses, so what holds it is removed whatever system.danglingRefs is.`
56
+ : normalized.message,
50
57
  cause: normalized,
51
- type
58
+ type: dangling ? 'DANGLING_REF' : type
52
59
  });
53
60
  });
54
61
  return undefined;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collateExamples = void 0;
4
4
  require("../_dnt.polyfills.js");
5
5
  const isEmpty_js_1 = require("./isEmpty.js");
6
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
6
7
  /**
7
8
  * Recursively collates and builds example values from OpenAPI schemas.
8
9
  *
@@ -168,11 +169,20 @@ const collateExamples = ({ objectSchema, depth, seen }) => {
168
169
  if (seen?.has(objectSchema.$ref)) {
169
170
  return undefined;
170
171
  }
171
- return (0, exports.collateExamples)({
172
- objectSchema: objectSchema.resolve(),
173
- depth: depth + 1,
174
- seen: new Set(seen ?? []).add(objectSchema.$ref)
175
- });
172
+ try {
173
+ return (0, exports.collateExamples)({
174
+ objectSchema: objectSchema.resolve(),
175
+ depth: depth + 1,
176
+ seen: new Set(seen ?? []).add(objectSchema.$ref)
177
+ });
178
+ }
179
+ catch (error) {
180
+ // A dangling reference names no schema, so it has no example either.
181
+ if (DanglingRefError_js_1.DanglingRefError.is(error)) {
182
+ return undefined;
183
+ }
184
+ throw error;
185
+ }
176
186
  }
177
187
  case 'object': {
178
188
  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
  *
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toGetRef = exports.isRef = exports.toRefName = void 0;
4
4
  require("../_dnt.polyfills.js");
5
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
5
6
  /**
6
7
  * Extracts a reference name from an OpenAPI $ref string.
7
8
  *
@@ -9,6 +10,10 @@ require("../_dnt.polyfills.js");
9
10
  * and extracts the final component as a branded RefName type. It's used throughout
10
11
  * the SKMTC system to convert string references into type-safe reference names.
11
12
  *
13
+ * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
14
+ * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
15
+ * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
16
+ *
12
17
  * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
13
18
  * @returns The extracted reference name as a branded RefName type
14
19
  *
@@ -44,14 +49,26 @@ require("../_dnt.polyfills.js");
44
49
  * ```
45
50
  */
46
51
  const toRefName = ($ref) => {
47
- // TODO: Add validation here to ensure reference exists
48
- const refName = $ref.split('/').slice(-1)[0];
49
- if (!refName) {
52
+ const segment = $ref.split('/').slice(-1)[0];
53
+ if (!segment) {
50
54
  throw new Error('Invalid reference');
51
55
  }
52
- return refName;
56
+ return toUnescapedSegment(segment);
53
57
  };
54
58
  exports.toRefName = toRefName;
59
+ /** A JSON pointer segment of a URI fragment, unescaped: percent escapes first, then `~1` and `~0`. */
60
+ const toUnescapedSegment = (segment) => {
61
+ return toPercentDecoded(segment).replaceAll('~1', '/').replaceAll('~0', '~');
62
+ };
63
+ const toPercentDecoded = (segment) => {
64
+ try {
65
+ return decodeURIComponent(segment);
66
+ }
67
+ catch {
68
+ // A `%` that starts no valid escape is read as written.
69
+ return segment;
70
+ }
71
+ };
55
72
  /**
56
73
  * Type guard function to check if a value is an OpenAPI reference object.
57
74
  *
@@ -126,7 +143,7 @@ exports.isRef = isRef;
126
143
  * @param oasDocument - The OpenAPI document containing the schemas to resolve against
127
144
  * @returns A function that resolves reference objects to schema objects
128
145
  *
129
- * @throws {Error} When a reference cannot be resolved or points to a non-existent schema
146
+ * @throws {DanglingRefError} When a reference names no schema in the document
130
147
  *
131
148
  * @example Basic usage
132
149
  * ```typescript
@@ -157,7 +174,7 @@ exports.isRef = isRef;
157
174
  * const schema = resolver({ $ref: '#/components/schemas/NonExistent' });
158
175
  * } catch (error) {
159
176
  * console.error('Reference resolution failed:', error.message);
160
- * // Error: Invalid reference: #/components/schemas/NonExistent
177
+ * // Ref "#/components/schemas/NonExistent" names nothing in the document
161
178
  * }
162
179
  * ```
163
180
  *
@@ -185,6 +202,6 @@ const toGetRef = (oasDocument) => ({ $ref }) => {
185
202
  if (item) {
186
203
  return item;
187
204
  }
188
- throw new Error(`Invalid reference: ${$ref}`);
205
+ throw new DanglingRefError_js_1.DanglingRefError($ref);
189
206
  };
190
207
  exports.toGetRef = toGetRef;
package/script/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/script/mod.js CHANGED
@@ -179,6 +179,7 @@ __exportStar(require("./oas/parameter/Parameter.js"), exports);
179
179
  __exportStar(require("./oas/parameter/parameter-types.js"), exports);
180
180
  __exportStar(require("./oas/pathItem/PathItem.js"), exports);
181
181
  __exportStar(require("./oas/ref/Ref.js"), exports);
182
+ __exportStar(require("./oas/ref/DanglingRefError.js"), exports);
182
183
  __exportStar(require("./oas/ref/ref-types.js"), exports);
183
184
  __exportStar(require("./parse/v3-0/ref/toRefV31.js"), exports);
184
185
  __exportStar(require("./oas/requestBody/RequestBody.js"), exports);
@@ -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
@@ -226,15 +226,16 @@ class OasOperation extends OasBase_js_1.OasBase {
226
226
  *
227
227
  * As OpenAPI defines them: the path item's parameters apply to each of its
228
228
  * operations, and an operation's own parameter with the same name and
229
- * location replaces the path item's. The path item's come first.
229
+ * location replaces the path item's. The path item's come first. A
230
+ * reference that names nothing (kept under `system.danglingRefs: keep`) is
231
+ * left out: it has no name or location, and the parser logged a
232
+ * `DANGLING_REF` warning for it.
230
233
  *
231
234
  * @param filter - only include parameters from specified locations
232
235
  * @returns
233
236
  */
234
237
  toParams(filter) {
235
- return (0, toEffectiveParameters_js_1.toEffectiveParameters)({ own: this.parameters, shared: this.pathItem?.parameters })
236
- .map(param => param.resolve())
237
- .filter(param => (filter?.length ? filter.includes(param.location) : true));
238
+ return (0, toEffectiveParameters_js_1.toResolvedParameters)((0, toEffectiveParameters_js_1.toEffectiveParameters)({ own: this.parameters, shared: this.pathItem?.parameters })).filter(param => (filter?.length ? filter.includes(param.location) : true));
238
239
  }
239
240
  /**
240
241
  * 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,17 +1,47 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toEffectiveParameters = void 0;
3
+ exports.toResolvedParameters = exports.toEffectiveParameters = void 0;
4
+ const DanglingRefError_js_1 = require("../ref/DanglingRefError.js");
4
5
  /**
5
6
  * The parameters that apply to an operation or webhook, as OpenAPI defines
6
7
  * them: the path item's first, then its own. An own parameter with the same
7
8
  * name and location replaces the path item's. References stay references.
9
+ * A reference that names nothing (kept under `system.danglingRefs: keep`)
10
+ * has no name or location, so it replaces nothing and nothing replaces it.
8
11
  */
9
12
  const toEffectiveParameters = ({ own = [], shared = [] }) => {
10
13
  const ownKeys = new Set(own.map(toParameterKey));
11
- return [...shared.filter(parameter => !ownKeys.has(toParameterKey(parameter))), ...own];
14
+ return [
15
+ ...shared.filter(parameter => {
16
+ const key = toParameterKey(parameter);
17
+ return key === undefined || !ownKeys.has(key);
18
+ }),
19
+ ...own
20
+ ];
12
21
  };
13
22
  exports.toEffectiveParameters = toEffectiveParameters;
23
+ /**
24
+ * Resolves each parameter. A reference that names nothing is left out: it
25
+ * has no name or location to render, and the parser logged a `DANGLING_REF`
26
+ * warning for it.
27
+ */
28
+ const toResolvedParameters = (parameters) => parameters.flatMap(parameter => {
29
+ const resolved = toResolvedParameter(parameter);
30
+ return resolved === undefined ? [] : [resolved];
31
+ });
32
+ exports.toResolvedParameters = toResolvedParameters;
14
33
  const toParameterKey = (parameter) => {
15
- const { name, location } = parameter.resolve();
16
- return `${location}:${name}`;
34
+ const resolved = toResolvedParameter(parameter);
35
+ return resolved === undefined ? undefined : `${resolved.location}:${resolved.name}`;
36
+ };
37
+ const toResolvedParameter = (parameter) => {
38
+ try {
39
+ return parameter.resolve();
40
+ }
41
+ catch (error) {
42
+ if (DanglingRefError_js_1.DanglingRefError.is(error)) {
43
+ return undefined;
44
+ }
45
+ throw error;
46
+ }
17
47
  };
@@ -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,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DanglingRefError = void 0;
4
+ /**
5
+ * Thrown when a reference that names nothing in the document is resolved.
6
+ *
7
+ * Under `client.json` `system.danglingRefs: strict` (the default) the parser
8
+ * removes what holds such a reference, so a generator never meets one. Under
9
+ * `keep` the reference stays, and a generator that resolves it can catch
10
+ * this error and render something else in its place. Test for it with
11
+ * {@link DanglingRefError.is}, not `instanceof`.
12
+ */
13
+ require("../../_dnt.polyfills.js");
14
+ class DanglingRefError extends Error {
15
+ constructor(ref) {
16
+ super(`Ref "${ref}" names nothing in the document`);
17
+ /** The `$ref`, or the component name, that names nothing. */
18
+ Object.defineProperty(this, "ref", {
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: true,
22
+ value: void 0
23
+ });
24
+ this.name = 'DanglingRefError';
25
+ this.ref = ref;
26
+ }
27
+ /**
28
+ * True when `error` is a `DanglingRefError`. It reads the error's name,
29
+ * not its class, so it is also true for one thrown by another copy of
30
+ * `@skmtc/core`, such as the copy a generator bundle resolves, where
31
+ * `instanceof` is false.
32
+ */
33
+ static is(error) {
34
+ return error instanceof Error && error.name === 'DanglingRefError';
35
+ }
36
+ }
37
+ exports.DanglingRefError = DanglingRefError;
@@ -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;
@@ -17,6 +17,7 @@ require("../../_dnt.polyfills.js");
17
17
  const traverseSchema_js_1 = require("../schemaPath/traverseSchema.js");
18
18
  const refFns_js_1 = require("../../helpers/refFns.js");
19
19
  const OasBase_js_1 = require("../../types/OasBase.js");
20
+ const DanglingRefError_js_1 = require("./DanglingRefError.js");
20
21
  const siblings_js_1 = require("../schema/siblings.js");
21
22
  const MAX_LOOKUPS = 10;
22
23
  /**
@@ -46,6 +47,18 @@ function refTypeToPluralPath(refType) {
46
47
  }
47
48
  }
48
49
  }
50
+ /**
51
+ * The name `resolveOnce` looks up. `toRefName` throws for a `$ref` whose last
52
+ * segment is empty (`#/components/schemas/`): that `$ref` names nothing.
53
+ */
54
+ const toLookupName = ($ref) => {
55
+ try {
56
+ return (0, refFns_js_1.toRefName)($ref);
57
+ }
58
+ catch {
59
+ throw new DanglingRefError_js_1.DanglingRefError($ref);
60
+ }
61
+ };
49
62
  /**
50
63
  * Represents an OpenAPI reference ($ref) in the SKMTC OAS processing system.
51
64
  *
@@ -448,14 +461,19 @@ class OasRef extends OasBase_js_1.OasBase {
448
461
  * reads from `document.registry.schemas`.
449
462
  *
450
463
  * @returns Either the resolved component or another reference in the chain
464
+ * @throws {DanglingRefError} when the reference names nothing in the
465
+ * document (kept under `client.json` `system.danglingRefs: keep`),
466
+ * including a `$ref` with no name, such as `#/components/schemas/`
467
+ * @throws Error when it names a component of another kind, such as a
468
+ * `requestBody` ref to `#/components/schemas/…`
451
469
  */
452
470
  resolveOnce() {
453
- const refName = (0, refFns_js_1.toRefName)(this.$ref);
471
+ const refName = toLookupName(this.$ref);
454
472
  const resolved = __classPrivateFieldGet(this, _OasRef_document, "f").type === 'oas'
455
473
  ? __classPrivateFieldGet(this, _OasRef_instances, "m", _OasRef_resolveOasOnce).call(this, __classPrivateFieldGet(this, _OasRef_document, "f").value, refName)
456
474
  : __classPrivateFieldGet(this, _OasRef_instances, "m", _OasRef_resolveGqlOnce).call(this, __classPrivateFieldGet(this, _OasRef_document, "f").value, refName);
457
475
  if (!resolved) {
458
- throw new Error(`Ref "${this.$ref}" not found`);
476
+ throw new DanglingRefError_js_1.DanglingRefError(this.$ref);
459
477
  }
460
478
  if (resolved.isRef()) {
461
479
  if (resolved.refType !== this.refType) {
@@ -648,6 +666,14 @@ _OasRef_document = new WeakMap(), _OasRef_resolution = new WeakMap(), _OasRef_in
648
666
  // OasSchema to ResolvedRef<T> for a generic T, as in resolveOnce().
649
667
  return (0, siblings_js_1.changesTarget)(copy, component, this) ? copy : target;
650
668
  }, _OasRef_resolveOasOnce = function _OasRef_resolveOasOnce(document, refName) {
669
+ // A `#/components/<bucket>/<name>` ref names its bucket. A request body
670
+ // that is a `$ref` to `#/components/schemas/Pet` names a schema, so it is
671
+ // never looked up in the request bodies.
672
+ const bucket = /^#\/components\/([^/]+)\//.exec(this.$ref)?.[1];
673
+ const expected = refTypeToPluralPath(this.refType);
674
+ if (bucket !== undefined && bucket !== expected) {
675
+ throw new Error(`Ref type mismatch for "${this.$ref}". Expected a ref into "components/${expected}" but it names one in "components/${bucket}"`);
676
+ }
651
677
  const c = document.components;
652
678
  const refType = this.refType;
653
679
  switch (refType) {
@@ -39,6 +39,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.toSiblingEnums = exports.toSiblingValue = exports.isIntegerFormat = exports.isNumberFormat = exports.VALUE_CHECKS = exports.isObjectValue = exports.isArrayValue = exports.isBooleanValue = exports.isIntegerValue = exports.isNumberValue = exports.isStringValue = exports.toSiblingAnnotations = exports.toSkippedSiblings = exports.changesValues = exports.changesTarget = exports.hasSiblingKeywords = exports.mergeSiblingKeywords = exports.SIBLINGS_BY_TYPE = void 0;
40
40
  const v = __importStar(require("valibot"));
41
41
  const isEqual_js_1 = __importDefault(require("lodash-es/isEqual.js"));
42
+ const DanglingRefError_js_1 = require("../ref/DanglingRefError.js");
42
43
  const number_types_js_1 = require("../number/number-types.js");
43
44
  const integer_types_js_1 = require("../integer/integer-types.js");
44
45
  /**
@@ -227,8 +228,17 @@ const MAX_DEPTH = 10;
227
228
  */
228
229
  const agrees = (type, target, depth) => {
229
230
  if (target.type === 'union') {
230
- return depth < MAX_DEPTH &&
231
- target.members.every(member => agrees(type, member.isRef() ? member.resolve() : member, depth + 1));
231
+ try {
232
+ return depth < MAX_DEPTH &&
233
+ target.members.every(member => agrees(type, member.isRef() ? member.resolve() : member, depth + 1));
234
+ }
235
+ catch (error) {
236
+ // A member that is a dangling reference has no known type, so it does not agree.
237
+ if (DanglingRefError_js_1.DanglingRefError.is(error)) {
238
+ return false;
239
+ }
240
+ throw error;
241
+ }
232
242
  }
233
243
  return type === target.type || (type === 'number' && target.type === 'integer');
234
244
  };
@@ -216,7 +216,8 @@ export declare class OasUnion extends OasBase {
216
216
  * an object that is not nullable, that requires the discriminator's
217
217
  * property, and that allows only string literals for it. No value may
218
218
  * belong to two members. A member that is a union, or anything other than
219
- * an object, makes it `false`.
219
+ * an object, makes it `false`, as does a reference on the way that names
220
+ * nothing in the document (kept under `system.danglingRefs: keep`).
220
221
  *
221
222
  * It reads the schemas only. A generator may refuse more: one that leaves
222
223
  * out `readOnly` properties cannot discriminate on one.
@@ -4,6 +4,7 @@ exports.OasUnion = void 0;
4
4
  const traverseSchema_js_1 = require("../schemaPath/traverseSchema.js");
5
5
  const siblings_js_1 = require("../schema/siblings.js");
6
6
  const OasBase_js_1 = require("../../types/OasBase.js");
7
+ const DanglingRefError_js_1 = require("../ref/DanglingRefError.js");
7
8
  /**
8
9
  * Represents a union type schema in the OpenAPI Specification.
9
10
  *
@@ -286,7 +287,8 @@ class OasUnion extends OasBase_js_1.OasBase {
286
287
  * an object that is not nullable, that requires the discriminator's
287
288
  * property, and that allows only string literals for it. No value may
288
289
  * belong to two members. A member that is a union, or anything other than
289
- * an object, makes it `false`.
290
+ * an object, makes it `false`, as does a reference on the way that names
291
+ * nothing in the document (kept under `system.danglingRefs: keep`).
290
292
  *
291
293
  * It reads the schemas only. A generator may refuse more: one that leaves
292
294
  * out `readOnly` properties cannot discriminate on one.
@@ -297,17 +299,26 @@ class OasUnion extends OasBase_js_1.OasBase {
297
299
  return false;
298
300
  }
299
301
  const seen = new Set();
300
- return this.members.every(member => {
301
- const values = toDiscriminatorValues(member, key);
302
- return (values !== undefined &&
303
- values.every(value => {
304
- if (seen.has(value)) {
305
- return false;
306
- }
307
- seen.add(value);
308
- return true;
309
- }));
310
- });
302
+ try {
303
+ return this.members.every(member => {
304
+ const values = toDiscriminatorValues(member, key);
305
+ return (values !== undefined &&
306
+ values.every(value => {
307
+ if (seen.has(value)) {
308
+ return false;
309
+ }
310
+ seen.add(value);
311
+ return true;
312
+ }));
313
+ });
314
+ }
315
+ catch (error) {
316
+ // A dangling reference: the schema it stands for is not known.
317
+ if (DanglingRefError_js_1.DanglingRefError.is(error)) {
318
+ return false;
319
+ }
320
+ throw error;
321
+ }
311
322
  }
312
323
  toJsonSchema(options) {
313
324
  return {
@@ -176,9 +176,7 @@ class OasWebhook extends OasBase_js_1.OasBase {
176
176
  * parameters carry the same shape, only their direction is inbound.
177
177
  */
178
178
  toParams(filter) {
179
- return (0, toEffectiveParameters_js_1.toEffectiveParameters)({ own: this.parameters, shared: this.pathItem?.parameters })
180
- .map(param => param.resolve())
181
- .filter(param => (filter?.length ? filter.includes(param.location) : true));
179
+ return (0, toEffectiveParameters_js_1.toResolvedParameters)((0, toEffectiveParameters_js_1.toEffectiveParameters)({ own: this.parameters, shared: this.pathItem?.parameters })).filter(param => (filter?.length ? filter.includes(param.location) : true));
182
180
  }
183
181
  /**
184
182
  * The status code of the primary acknowledgement response — the lowest 2xx
@@ -58,6 +58,12 @@ export type ToOperationsWithValidSecurityArgs<Item extends SecuredItem> = {
58
58
  * failed to parse or is not defined, or that has no `security` and
59
59
  * inherits an unusable root. Each dropped item logs one `INVALID_OPERATION`
60
60
  * error on its own trail. `security: []` inherits nothing and is kept.
61
+ *
62
+ * A kept item depends on each scheme its security names (its own, else the
63
+ * root's), as it would on a `$ref` to it, so it is registered as a consumer
64
+ * of the scheme. When the parser removes the scheme later (one that is a
65
+ * `$ref` that names nothing), the item goes with it, and so is never kept
66
+ * without its auth.
61
67
  */
62
68
  export declare const toOperationsWithValidSecurity: <Item extends SecuredItem>({ items, check }: ToOperationsWithValidSecurityArgs<Item>) => Item[];
63
69
  export {};