@skmtc/core 0.45.0 → 0.47.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 (187) hide show
  1. package/esm/anchors/attribute.js +3 -2
  2. package/esm/context/CoreContext.d.ts +1 -1
  3. package/esm/context/CoreContext.js +1 -1
  4. package/esm/context/GenerateContext.d.ts +13 -10
  5. package/esm/context/GenerateContext.js +36 -25
  6. package/esm/context/ParseContext.d.ts +3 -0
  7. package/esm/context/ParseContext.js +151 -39
  8. package/esm/context/generateTypes.d.ts +7 -6
  9. package/esm/dsl/GeneratorKeys.d.ts +21 -15
  10. package/esm/dsl/GeneratorKeys.js +16 -11
  11. package/esm/dsl/Inserted.d.ts +1 -1
  12. package/esm/dsl/Inserted.js +1 -1
  13. package/esm/dsl/model/ModelDriver.d.ts +6 -5
  14. package/esm/dsl/model/ModelDriver.js +22 -20
  15. package/esm/dsl/model/toModelEntry.d.ts +18 -18
  16. package/esm/dsl/model/toModelEntry.js +9 -9
  17. package/esm/dsl/model/toModelProjectionBase.d.ts +17 -16
  18. package/esm/dsl/model/toModelProjectionBase.js +12 -8
  19. package/esm/dsl/model/types.d.ts +26 -17
  20. package/esm/dsl/operation/gql/toGqlOperationProjectionBase.d.ts +2 -2
  21. package/esm/dsl/operation/gql/toGqlOperationProjectionBase.js +2 -2
  22. package/esm/dsl/operation/oas/toOasOperationProjectionBase.d.ts +2 -2
  23. package/esm/dsl/operation/oas/toOasOperationProjectionBase.js +2 -2
  24. package/esm/dsl/webhook/toWebhookProjectionBase.d.ts +2 -2
  25. package/esm/dsl/webhook/toWebhookProjectionBase.js +2 -2
  26. package/esm/helpers/collateExamples.js +35 -17
  27. package/esm/helpers/refFns.d.ts +108 -43
  28. package/esm/helpers/refFns.js +166 -57
  29. package/esm/mod.d.ts +1 -0
  30. package/esm/mod.js +1 -0
  31. package/esm/oas/document/Document.d.ts +6 -0
  32. package/esm/oas/document/Document.js +44 -2
  33. package/esm/oas/intersection/Intersection.d.ts +122 -0
  34. package/esm/oas/intersection/Intersection.js +266 -0
  35. package/esm/oas/mediaType/jsonMediaType.d.ts +1 -1
  36. package/esm/oas/mediaType/jsonMediaType.js +3 -3
  37. package/esm/oas/ref/DanglingRefError.d.ts +5 -2
  38. package/esm/oas/ref/DanglingRefError.js +4 -3
  39. package/esm/oas/ref/Ref.d.ts +23 -12
  40. package/esm/oas/ref/Ref.js +68 -72
  41. package/esm/oas/requestBody/RequestBody.d.ts +1 -1
  42. package/esm/oas/requestBody/RequestBody.js +1 -1
  43. package/esm/oas/response/Response.d.ts +1 -1
  44. package/esm/oas/response/Response.js +1 -1
  45. package/esm/oas/schema/Schema.d.ts +4 -2
  46. package/esm/oas/schema/siblings.d.ts +10 -2
  47. package/esm/oas/schema/siblings.js +87 -22
  48. package/esm/oas/schemaPath/traverseSchema.d.ts +2 -0
  49. package/esm/oas/schemaPath/traverseSchema.js +51 -5
  50. package/esm/parse/allOfSystem.d.ts +3 -0
  51. package/esm/parse/allOfSystem.js +2 -1
  52. package/esm/parse/keptIntersection.d.ts +53 -0
  53. package/esm/parse/keptIntersection.js +155 -0
  54. package/esm/parse/keptRefs.d.ts +23 -0
  55. package/esm/parse/keptRefs.js +59 -0
  56. package/esm/parse/toCyclicRefs.d.ts +8 -0
  57. package/esm/parse/toCyclicRefs.js +126 -0
  58. package/esm/parse/toDeclaredTypes.d.ts +20 -0
  59. package/esm/parse/toDeclaredTypes.js +43 -0
  60. package/esm/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  61. package/esm/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  62. package/esm/parse/v3-0/_merge-all-of/merge.js +13 -0
  63. package/esm/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  64. package/esm/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  65. package/esm/parse/v3-0/intersection/toIntersection.js +61 -0
  66. package/esm/parse/v3-0/ref/toRefTargetV3.d.ts +23 -0
  67. package/esm/parse/v3-0/ref/toRefTargetV3.js +70 -0
  68. package/esm/parse/v3-0/schema/toSchemasV3.js +13 -1
  69. package/esm/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  70. package/esm/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  71. package/esm/parse/v3-1/_merge-all-of/merge.js +13 -0
  72. package/esm/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  73. package/esm/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  74. package/esm/parse/v3-1/intersection/toIntersection.js +61 -0
  75. package/esm/parse/v3-1/ref/toRefTargetV3.d.ts +23 -0
  76. package/esm/parse/v3-1/ref/toRefTargetV3.js +70 -0
  77. package/esm/parse/v3-1/schema/toSchemasV3.js +15 -2
  78. package/esm/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  79. package/esm/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  80. package/esm/parse/v3-2/_merge-all-of/merge.js +13 -0
  81. package/esm/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  82. package/esm/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  83. package/esm/parse/v3-2/intersection/toIntersection.js +61 -0
  84. package/esm/parse/v3-2/ref/toRefTargetV3.d.ts +23 -0
  85. package/esm/parse/v3-2/ref/toRefTargetV3.js +70 -0
  86. package/esm/parse/v3-2/schema/toSchemasV3.js +15 -2
  87. package/esm/types/GeneratorType.d.ts +1 -1
  88. package/esm/types/ProjectionOptions.d.ts +1 -1
  89. package/esm/types/ProjectionOptions.js +1 -1
  90. package/esm/types/RefName.d.ts +3 -3
  91. package/esm/types/Settings.d.ts +9 -0
  92. package/esm/types/Settings.js +2 -1
  93. package/esm/types/TypeSystem.d.ts +20 -5
  94. package/package.json +1 -1
  95. package/script/anchors/attribute.js +3 -2
  96. package/script/context/CoreContext.d.ts +1 -1
  97. package/script/context/CoreContext.js +1 -1
  98. package/script/context/GenerateContext.d.ts +13 -10
  99. package/script/context/GenerateContext.js +36 -25
  100. package/script/context/ParseContext.d.ts +3 -0
  101. package/script/context/ParseContext.js +150 -38
  102. package/script/context/generateTypes.d.ts +7 -6
  103. package/script/dsl/GeneratorKeys.d.ts +21 -15
  104. package/script/dsl/GeneratorKeys.js +16 -11
  105. package/script/dsl/Inserted.d.ts +1 -1
  106. package/script/dsl/Inserted.js +1 -1
  107. package/script/dsl/model/ModelDriver.d.ts +6 -5
  108. package/script/dsl/model/ModelDriver.js +22 -20
  109. package/script/dsl/model/toModelEntry.d.ts +18 -18
  110. package/script/dsl/model/toModelEntry.js +9 -9
  111. package/script/dsl/model/toModelProjectionBase.d.ts +17 -16
  112. package/script/dsl/model/toModelProjectionBase.js +12 -8
  113. package/script/dsl/model/types.d.ts +26 -17
  114. package/script/dsl/operation/gql/toGqlOperationProjectionBase.d.ts +2 -2
  115. package/script/dsl/operation/gql/toGqlOperationProjectionBase.js +2 -2
  116. package/script/dsl/operation/oas/toOasOperationProjectionBase.d.ts +2 -2
  117. package/script/dsl/operation/oas/toOasOperationProjectionBase.js +2 -2
  118. package/script/dsl/webhook/toWebhookProjectionBase.d.ts +2 -2
  119. package/script/dsl/webhook/toWebhookProjectionBase.js +2 -2
  120. package/script/helpers/collateExamples.js +35 -17
  121. package/script/helpers/refFns.d.ts +108 -43
  122. package/script/helpers/refFns.js +180 -59
  123. package/script/mod.d.ts +1 -0
  124. package/script/mod.js +1 -0
  125. package/script/oas/document/Document.d.ts +6 -0
  126. package/script/oas/document/Document.js +44 -2
  127. package/script/oas/intersection/Intersection.d.ts +122 -0
  128. package/script/oas/intersection/Intersection.js +270 -0
  129. package/script/oas/mediaType/jsonMediaType.d.ts +1 -1
  130. package/script/oas/mediaType/jsonMediaType.js +3 -3
  131. package/script/oas/ref/DanglingRefError.d.ts +5 -2
  132. package/script/oas/ref/DanglingRefError.js +4 -3
  133. package/script/oas/ref/Ref.d.ts +23 -12
  134. package/script/oas/ref/Ref.js +67 -71
  135. package/script/oas/requestBody/RequestBody.d.ts +1 -1
  136. package/script/oas/requestBody/RequestBody.js +1 -1
  137. package/script/oas/response/Response.d.ts +1 -1
  138. package/script/oas/response/Response.js +1 -1
  139. package/script/oas/schema/Schema.d.ts +4 -2
  140. package/script/oas/schema/siblings.d.ts +10 -2
  141. package/script/oas/schema/siblings.js +89 -23
  142. package/script/oas/schemaPath/traverseSchema.d.ts +2 -0
  143. package/script/oas/schemaPath/traverseSchema.js +50 -4
  144. package/script/parse/allOfSystem.d.ts +3 -0
  145. package/script/parse/allOfSystem.js +2 -1
  146. package/script/parse/keptIntersection.d.ts +53 -0
  147. package/script/parse/keptIntersection.js +164 -0
  148. package/script/parse/keptRefs.d.ts +23 -0
  149. package/script/parse/keptRefs.js +63 -0
  150. package/script/parse/toCyclicRefs.d.ts +8 -0
  151. package/script/parse/toCyclicRefs.js +130 -0
  152. package/script/parse/toDeclaredTypes.d.ts +20 -0
  153. package/script/parse/toDeclaredTypes.js +48 -0
  154. package/script/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  155. package/script/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  156. package/script/parse/v3-0/_merge-all-of/merge.js +13 -0
  157. package/script/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  158. package/script/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  159. package/script/parse/v3-0/intersection/toIntersection.js +65 -0
  160. package/script/parse/v3-0/ref/toRefTargetV3.d.ts +23 -0
  161. package/script/parse/v3-0/ref/toRefTargetV3.js +74 -0
  162. package/script/parse/v3-0/schema/toSchemasV3.js +13 -1
  163. package/script/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  164. package/script/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  165. package/script/parse/v3-1/_merge-all-of/merge.js +13 -0
  166. package/script/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  167. package/script/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  168. package/script/parse/v3-1/intersection/toIntersection.js +65 -0
  169. package/script/parse/v3-1/ref/toRefTargetV3.d.ts +23 -0
  170. package/script/parse/v3-1/ref/toRefTargetV3.js +74 -0
  171. package/script/parse/v3-1/schema/toSchemasV3.js +15 -2
  172. package/script/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  173. package/script/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  174. package/script/parse/v3-2/_merge-all-of/merge.js +13 -0
  175. package/script/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  176. package/script/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  177. package/script/parse/v3-2/intersection/toIntersection.js +65 -0
  178. package/script/parse/v3-2/ref/toRefTargetV3.d.ts +23 -0
  179. package/script/parse/v3-2/ref/toRefTargetV3.js +74 -0
  180. package/script/parse/v3-2/schema/toSchemasV3.js +15 -2
  181. package/script/types/GeneratorType.d.ts +1 -1
  182. package/script/types/ProjectionOptions.d.ts +1 -1
  183. package/script/types/ProjectionOptions.js +1 -1
  184. package/script/types/RefName.d.ts +3 -3
  185. package/script/types/Settings.d.ts +9 -0
  186. package/script/types/Settings.js +2 -1
  187. package/script/types/TypeSystem.d.ts +20 -5
@@ -11,7 +11,7 @@ import type { GeneratedValue } from '../GeneratedValue.js';
11
11
  import type { Inserted } from '../Inserted.js';
12
12
  import type { ModelProjection, NormalizedModelProjection } from '../model/types.js';
13
13
  import type { OasOperationProjection } from '../operation/oas/types.js';
14
- import type { RefName } from '../../types/RefName.js';
14
+ import type { RefParts } from '../../helpers/refFns.js';
15
15
  import type { OasSchema } from '../../oas/schema/Schema.js';
16
16
  import type { OasRef } from '../../oas/ref/Ref.js';
17
17
  import type { OasVoid } from '../../oas/void/Void.js';
@@ -98,7 +98,7 @@ export declare const toWebhookProjectionBase: <EnrichmentType = undefined, IdTyp
98
98
  * webhook's payload type). `{ options }` is required when the peer
99
99
  * declares options and refused when it does not.
100
100
  */
101
- insertModel<V extends GeneratedValue, PeerEnrichmentType_1 = undefined, PeerProjectionOptions_1 = undefined>(projection: ModelProjection<V, PeerEnrichmentType_1, PeerProjectionOptions_1>, refName: RefName, ...rest: ProjectionOptionsRest<PeerInsertOptions<PeerProjectionOptions_1>, PeerProjectionOptions_1>): Inserted<V, PeerEnrichmentType_1>;
101
+ insertModel<V extends GeneratedValue, PeerEnrichmentType_1 = undefined, PeerProjectionOptions_1 = undefined>(projection: ModelProjection<V, PeerEnrichmentType_1, PeerProjectionOptions_1>, ref: RefParts, ...rest: ProjectionOptionsRest<PeerInsertOptions<PeerProjectionOptions_1>, PeerProjectionOptions_1>): Inserted<V, PeerEnrichmentType_1>;
102
102
  /**
103
103
  * Insert a related model with reference normalization. Useful for inline
104
104
  * payload schemas where the schema may be either a `$ref` or a concrete
@@ -70,8 +70,8 @@ export const toWebhookProjectionBase = (base, config) => {
70
70
  * webhook's payload type). `{ options }` is required when the peer
71
71
  * declares options and refused when it does not.
72
72
  */
73
- insertModel(projection, refName, ...rest) {
74
- return this.context.insertModel(projection, refName, {
73
+ insertModel(projection, ref, ...rest) {
74
+ return this.context.insertModel(projection, ref, {
75
75
  ...toPeerInsertOptions(rest),
76
76
  destinationPath: this.settings.exportPath
77
77
  });
@@ -1,5 +1,6 @@
1
1
  import "../_dnt.polyfills.js";
2
2
  import { isEmpty } from './isEmpty.js';
3
+ import { isObjectValue } from '../oas/schema/siblings.js';
3
4
  import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
4
5
  /**
5
6
  * Recursively collates and builds example values from OpenAPI schemas.
@@ -163,23 +164,7 @@ export const collateExamples = ({ objectSchema, depth, seen }) => {
163
164
  // legitimately deep one fail identically, and a caller that only wanted a
164
165
  // sample body gets an exception instead. Cutting the cycle here is what
165
166
  // makes the depth limit mean what it says.
166
- if (seen?.has(objectSchema.$ref)) {
167
- return undefined;
168
- }
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
- }
167
+ return collateRef({ ref: objectSchema, depth: depth + 1, seen });
183
168
  }
184
169
  case 'object': {
185
170
  if (objectSchema.example) {
@@ -235,9 +220,42 @@ export const collateExamples = ({ objectSchema, depth, seen }) => {
235
220
  }
236
221
  return undefined;
237
222
  }
223
+ case 'intersection': {
224
+ if (objectSchema.example) {
225
+ return objectSchema.example;
226
+ }
227
+ // A value matches every member, so the examples of objects are one object.
228
+ // Its members are as deep as the intersection: they are one value.
229
+ const examples = objectSchema.members
230
+ .map(member => member.isRef()
231
+ ? collateRef({ ref: member, depth, seen })
232
+ : collateExamples({ objectSchema: member, depth, seen }))
233
+ .filter(example => Boolean(example));
234
+ return examples.every(isObjectValue) ? toMergedExample(examples) : examples[0];
235
+ }
238
236
  default: {
239
237
  const _exhaustive = objectSchema;
240
238
  throw new Error(`Unhandled schema type: ${_exhaustive.type}`);
241
239
  }
242
240
  }
243
241
  };
242
+ /** The example of what a reference resolves to. A reference on the path to itself, or one that names nothing, has none. */
243
+ const collateRef = ({ ref, depth, seen }) => {
244
+ if (seen?.has(ref.$ref)) {
245
+ return undefined;
246
+ }
247
+ try {
248
+ return collateExamples({
249
+ objectSchema: ref.resolve(),
250
+ depth,
251
+ seen: new Set(seen ?? []).add(ref.$ref)
252
+ });
253
+ }
254
+ catch (error) {
255
+ if (DanglingRefError.is(error)) {
256
+ return undefined;
257
+ }
258
+ throw error;
259
+ }
260
+ };
261
+ const toMergedExample = (examples) => examples.length === 0 ? undefined : Object.assign({}, ...examples);
@@ -3,52 +3,117 @@ import type { RefName } from '../types/RefName.js';
3
3
  import type { OpenAPIV3 } from 'openapi-types';
4
4
  import type { ReferenceObject } from '../parse/v3-0/_merge-all-of/types.js';
5
5
  import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
6
+ import type { OasRefData } from '../oas/ref/ref-types.js';
7
+ /** The kind of component a `$ref` points at: `schema`, `parameter`, `response`, and so on. */
8
+ type RefType = OasRefData['refType'];
6
9
  /**
7
- * Extracts a reference name from an OpenAPI $ref string.
8
- *
9
- * This function parses JSON Pointer references (like '#/components/schemas/User')
10
- * and extracts the final component as a branded RefName type. It's used throughout
11
- * the SKMTC system to convert string references into type-safe reference names.
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
- *
17
- * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
18
- * @returns The extracted reference name as a branded RefName type
19
- *
20
- * @throws {Error} When the reference string is invalid or empty
21
- *
22
- * @example Basic usage
23
- * ```typescript
24
- * import { toRefName } from '@skmtc/core/helpers';
25
- *
26
- * const refName = toRefName('#/components/schemas/User');
27
- * console.log(refName); // 'User' (typed as RefName)
28
- *
29
- * const responseRef = toRefName('#/components/responses/ErrorResponse');
30
- * console.log(responseRef); // 'ErrorResponse' (typed as RefName)
31
- * ```
10
+ * Where a `$ref` points, in two parts: `refPath`, the JSON pointer before its
11
+ * last segment, and `refName`, that last segment unescaped.
12
+ * `#/components/schemas/Pet` is `refPath` `#/components/schemas` and `refName`
13
+ * `Pet`. `#/components/schemas/__sharedInput/$defs/schema0` is `refPath`
14
+ * `#/components/schemas/__sharedInput/$defs` and `refName` `schema0`.
15
+ *
16
+ * `refPath` has one spelling, whatever the `$ref` has: no percent escapes, and
17
+ * `~` and `/` in a segment as `~0` and `~1` (RFC 6901). Two refs to one place
18
+ * have equal parts.
19
+ *
20
+ * The model API takes a model's ref in this shape (`insertModel(Peer, ref)`,
21
+ * `toIdentifierName({ ref, … })`), so the two parts travel together. An
22
+ * `OasRef` has both fields and fits it as it is.
23
+ */
24
+ export type RefParts = {
25
+ /** The last segment of the pointer, unescaped. Empty for a `$ref` that ends in `/`. */
26
+ refName: RefName;
27
+ /**
28
+ * The pointer before the last segment, starting with `#`, with no percent
29
+ * escapes. A remote `$ref` ({@link isRemoteRefPath}) has the file before the `#`.
30
+ */
31
+ refPath: string;
32
+ };
33
+ type ToRefPartsArgs = {
34
+ $ref: string;
35
+ };
36
+ /**
37
+ * Splits a `$ref` into {@link RefParts}.
32
38
  *
33
- * @example Error cases
34
- * ```typescript
35
- * // These will throw errors:
36
- * toRefName('invalid/ref/'); // Error: 'Invalid reference'
37
- * toRefName('#/components/schemas/'); // Error: 'Invalid reference'
38
- * ```
39
+ * A `$ref` is a URI whose fragment holds a JSON pointer (RFC 6901), so the
40
+ * name is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and
41
+ * `~`. `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
39
42
  *
40
- * @example Integration with OAS processing
41
- * ```typescript
42
- * class SchemaProcessor {
43
- * processReference(ref: string) {
44
- * const refName = toRefName(ref);
45
- * const schema = this.document.components.schemas[refName];
46
- * return this.processSchema(schema, refName);
47
- * }
48
- * }
49
- * ```
43
+ * A remote `$ref`, one that does not start with `#`, points outside the
44
+ * document, so its `refPath` does not start with `#` and it names nothing
45
+ * here: `other.yml#/components/schemas/A` is `refPath`
46
+ * `other.yml#/components/schemas` and `refName` `A`. This never throws: a
47
+ * `$ref` that names nothing is found out when it is resolved.
48
+ */
49
+ export declare const toRefParts: ({ $ref }: ToRefPartsArgs) => RefParts;
50
+ /** The `components` bucket that holds components of each kind: `schemas`, `parameters`, and so on. */
51
+ export declare const toComponentsBucket: (refType: RefType) => string;
52
+ /**
53
+ * Whether a `refPath` is that of a remote `$ref`: one that points outside the
54
+ * document (`other.yml#/components/schemas/A`, `./pet.yaml`, a bare id). Core
55
+ * does not fetch, so a remote `$ref` names nothing. The document is bundled
56
+ * into one before core reads it.
57
+ */
58
+ export declare const isRemoteRefPath: (refPath: string) => boolean;
59
+ /** The segments of a `refPath` in the document, each unescaped. `#` has none. */
60
+ export declare const toRefPathSegments: (refPath: string) => string[];
61
+ type IsDefaultRefPathArgs = {
62
+ refPath: string;
63
+ refType: RefType;
64
+ };
65
+ /**
66
+ * The `components` bucket a `refPath` is, such as `schemas` for
67
+ * `#/components/schemas`, or `undefined` for any other path. A ref whose path
68
+ * is a bucket names a component, of the bucket's kind whatever kind the ref
69
+ * is written for; any other ref points into a document's content, as one into
70
+ * an extension of `components` (`#/components/x-shared/Foo`) does. A bucket
71
+ * core does not read (`pathItems`) is still a bucket.
72
+ */
73
+ export declare const toRefPathBucket: (refPath: string) => string | undefined;
74
+ /** Whether `refPath` is where components of `refType` live, as `toRefParts` spells it. */
75
+ export declare const isDefaultRefPath: ({ refPath, refType }: IsDefaultRefPathArgs) => boolean;
76
+ /**
77
+ * The whole pointer of a ref, with no percent escapes. Two `$ref`s that point
78
+ * at the same place give the same pointer, so it keys a ref that does not
79
+ * point at a component. A remote `$ref` is given as written.
80
+ */
81
+ export declare const toRefPointer: ({ refName, refPath }: RefParts) => string;
82
+ /**
83
+ * The ref of the schema component named `refName`: `refPath`
84
+ * `#/components/schemas`. For code that holds a component's name but no
85
+ * `OasRef`, such as the engine's sweep over `components.schemas`.
86
+ */
87
+ export declare const toSchemaComponentRef: (refName: RefName) => RefParts;
88
+ /**
89
+ * The key a model is known by in the engine: its generator key, its
90
+ * enrichments (`[id][key][variant]`) and its manifest entry. A component
91
+ * (`refPath` `#/components/schemas`) is keyed by its `refName`, as it always
92
+ * was. Any other target is keyed by its whole pointer ({@link toRefPointer}),
93
+ * so two targets that share a `refName` stay apart.
94
+ */
95
+ export declare const toModelKey: ({ refName, refPath }: RefParts) => string;
96
+ /**
97
+ * A name for a model that differs between targets with one `refName`
98
+ * (`…/properties/disk` under two schemas). A component is named by its
99
+ * `refName`, through `toComponentName`. Any other target is named by its whole
100
+ * pointer, its segments joined by `_`: `Order_items`, `Pet_properties_tag`.
101
+ * A segment that is not alphanumeric gets a hash, so `@type` and `type` differ.
102
+ */
103
+ export declare const toModelName: ({ refName, refPath }: RefParts, toComponentName?: (refName: string) => string) => string;
104
+ /** Whether a model key ({@link toModelKey}) is a whole pointer, and not a component's `refName`. */
105
+ export declare const isPointerKey: (key: string) => boolean;
106
+ /**
107
+ * Reverses {@link toModelKey}, for a key read back out of a generator key.
108
+ * A pointer starts with `#/`; any other key is a component's `refName`. A key
109
+ * has no percent escapes, so a `%` in it is read as written.
110
+ */
111
+ export declare const fromModelKey: (key: string) => RefParts;
112
+ /**
113
+ * The value at a ref's pointer in a raw document, or `undefined` when the
114
+ * pointer leads nowhere, or out of the document. It walks objects by key and arrays by index.
50
115
  */
51
- export declare const toRefName: ($ref: string) => RefName;
116
+ export declare const toRawRefTarget: (document: unknown, { refName, refPath }: RefParts) => unknown;
52
117
  /**
53
118
  * Type representing an object with a $ref property.
54
119
  */
@@ -75,7 +140,7 @@ type Ref = {
75
140
  * if (isRef(schemaOrRef)) {
76
141
  * // TypeScript now knows schemaOrRef has a $ref property
77
142
  * console.log(schemaOrRef.$ref); // Safe to access
78
- * const refName = toRefName(schemaOrRef.$ref);
143
+ * const { refName, refPath } = toRefParts({ $ref: schemaOrRef.$ref });
79
144
  * } else {
80
145
  * // Handle as actual schema object
81
146
  * console.log('Direct schema object');
@@ -1,61 +1,157 @@
1
1
  import "../_dnt.polyfills.js";
2
2
  import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
3
+ import { toJsonPointer, unescapeSegment } from '../types/JsonPointer.js';
4
+ import { componentsKeys } from '../oas/components/Components.js';
5
+ import { isPlainObject } from '../parse/isPlainObject.js';
6
+ import { camelCase, capitalize } from './strings.js';
3
7
  /**
4
- * Extracts a reference name from an OpenAPI $ref string.
8
+ * Splits a `$ref` into {@link RefParts}.
5
9
  *
6
- * This function parses JSON Pointer references (like '#/components/schemas/User')
7
- * and extracts the final component as a branded RefName type. It's used throughout
8
- * the SKMTC system to convert string references into type-safe reference names.
10
+ * A `$ref` is a URI whose fragment holds a JSON pointer (RFC 6901), so the
11
+ * name is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and
12
+ * `~`. `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
9
13
  *
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
- *
14
- * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
15
- * @returns The extracted reference name as a branded RefName type
16
- *
17
- * @throws {Error} When the reference string is invalid or empty
18
- *
19
- * @example Basic usage
20
- * ```typescript
21
- * import { toRefName } from '@skmtc/core/helpers';
22
- *
23
- * const refName = toRefName('#/components/schemas/User');
24
- * console.log(refName); // 'User' (typed as RefName)
25
- *
26
- * const responseRef = toRefName('#/components/responses/ErrorResponse');
27
- * console.log(responseRef); // 'ErrorResponse' (typed as RefName)
28
- * ```
29
- *
30
- * @example Error cases
31
- * ```typescript
32
- * // These will throw errors:
33
- * toRefName('invalid/ref/'); // Error: 'Invalid reference'
34
- * toRefName('#/components/schemas/'); // Error: 'Invalid reference'
35
- * ```
36
- *
37
- * @example Integration with OAS processing
38
- * ```typescript
39
- * class SchemaProcessor {
40
- * processReference(ref: string) {
41
- * const refName = toRefName(ref);
42
- * const schema = this.document.components.schemas[refName];
43
- * return this.processSchema(schema, refName);
44
- * }
45
- * }
46
- * ```
14
+ * A remote `$ref`, one that does not start with `#`, points outside the
15
+ * document, so its `refPath` does not start with `#` and it names nothing
16
+ * here: `other.yml#/components/schemas/A` is `refPath`
17
+ * `other.yml#/components/schemas` and `refName` `A`. This never throws: a
18
+ * `$ref` that names nothing is found out when it is resolved.
19
+ */
20
+ export const toRefParts = ({ $ref }) => {
21
+ if (!$ref.startsWith('#')) {
22
+ const cut = $ref.lastIndexOf('/');
23
+ const refName = $ref.slice(cut + 1);
24
+ return { refName, refPath: cut === -1 ? '.' : $ref.slice(0, cut) };
25
+ }
26
+ const pointer = $ref.slice(1);
27
+ const segments = (pointer.startsWith('/') ? pointer.slice(1) : pointer)
28
+ .split('/')
29
+ .map(segment => unescapeSegment(toPercentDecoded(segment)));
30
+ return toPartsOf(segments);
31
+ };
32
+ /** The parts of a pointer's segments, each unescaped. */
33
+ const toPartsOf = (segments) => ({
34
+ refName: (segments.at(-1) ?? ''),
35
+ refPath: segments.length > 1 ? toJsonPointer(segments.slice(0, -1)) : '#'
36
+ });
37
+ /** The `components` bucket that holds components of each kind: `schemas`, `parameters`, and so on. */
38
+ export const toComponentsBucket = (refType) => {
39
+ switch (refType) {
40
+ case 'schema':
41
+ return 'schemas';
42
+ case 'requestBody':
43
+ return 'requestBodies';
44
+ case 'parameter':
45
+ return 'parameters';
46
+ case 'response':
47
+ return 'responses';
48
+ case 'example':
49
+ return 'examples';
50
+ case 'header':
51
+ return 'headers';
52
+ case 'securityScheme':
53
+ return 'securitySchemes';
54
+ case 'link':
55
+ return 'links';
56
+ default: {
57
+ const _exhaustive = refType;
58
+ throw new Error(`Unhandled ref type: ${_exhaustive}`);
59
+ }
60
+ }
61
+ };
62
+ /**
63
+ * Whether a `refPath` is that of a remote `$ref`: one that points outside the
64
+ * document (`other.yml#/components/schemas/A`, `./pet.yaml`, a bare id). Core
65
+ * does not fetch, so a remote `$ref` names nothing. The document is bundled
66
+ * into one before core reads it.
67
+ */
68
+ export const isRemoteRefPath = (refPath) => !refPath.startsWith('#');
69
+ /** The segments of a `refPath` in the document, each unescaped. `#` has none. */
70
+ export const toRefPathSegments = (refPath) => {
71
+ const body = refPath.startsWith('#/') ? refPath.slice(2) : refPath.slice(1);
72
+ return body === '' ? [] : body.split('/').map(unescapeSegment);
73
+ };
74
+ /**
75
+ * The `components` bucket a `refPath` is, such as `schemas` for
76
+ * `#/components/schemas`, or `undefined` for any other path. A ref whose path
77
+ * is a bucket names a component, of the bucket's kind whatever kind the ref
78
+ * is written for; any other ref points into a document's content, as one into
79
+ * an extension of `components` (`#/components/x-shared/Foo`) does. A bucket
80
+ * core does not read (`pathItems`) is still a bucket.
47
81
  */
48
- export const toRefName = ($ref) => {
49
- const segment = $ref.split('/').slice(-1)[0];
50
- if (!segment) {
51
- throw new Error('Invalid reference');
82
+ export const toRefPathBucket = (refPath) => {
83
+ if (isRemoteRefPath(refPath)) {
84
+ return undefined;
52
85
  }
53
- return toUnescapedSegment(segment);
86
+ const [first, bucket, ...rest] = toRefPathSegments(refPath);
87
+ return first === 'components' && rest.length === 0 && isBucket(bucket) ? bucket : undefined;
54
88
  };
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', '~');
89
+ /** The `components` buckets OpenAPI defines that core does not read. */
90
+ const unreadBuckets = ['callbacks', 'pathItems', 'mediaTypes'];
91
+ const isBucket = (key) => componentsKeys.includes(key) || unreadBuckets.includes(key);
92
+ /** Whether `refPath` is where components of `refType` live, as `toRefParts` spells it. */
93
+ export const isDefaultRefPath = ({ refPath, refType }) => toRefPathBucket(refPath) === toComponentsBucket(refType);
94
+ /**
95
+ * The whole pointer of a ref, with no percent escapes. Two `$ref`s that point
96
+ * at the same place give the same pointer, so it keys a ref that does not
97
+ * point at a component. A remote `$ref` is given as written.
98
+ */
99
+ export const toRefPointer = ({ refName, refPath }) => isRemoteRefPath(refPath) ? `${refPath}/${refName}` : toJsonPointer([...toRefPathSegments(refPath), refName]);
100
+ /**
101
+ * The ref of the schema component named `refName`: `refPath`
102
+ * `#/components/schemas`. For code that holds a component's name but no
103
+ * `OasRef`, such as the engine's sweep over `components.schemas`.
104
+ */
105
+ export const toSchemaComponentRef = (refName) => ({
106
+ refName,
107
+ refPath: `#/components/${toComponentsBucket('schema')}`
108
+ });
109
+ /**
110
+ * The key a model is known by in the engine: its generator key, its
111
+ * enrichments (`[id][key][variant]`) and its manifest entry. A component
112
+ * (`refPath` `#/components/schemas`) is keyed by its `refName`, as it always
113
+ * was. Any other target is keyed by its whole pointer ({@link toRefPointer}),
114
+ * so two targets that share a `refName` stay apart.
115
+ */
116
+ export const toModelKey = ({ refName, refPath }) => isDefaultRefPath({ refPath, refType: 'schema' }) ? refName : toRefPointer({ refName, refPath });
117
+ /**
118
+ * A name for a model that differs between targets with one `refName`
119
+ * (`…/properties/disk` under two schemas). A component is named by its
120
+ * `refName`, through `toComponentName`. Any other target is named by its whole
121
+ * pointer, its segments joined by `_`: `Order_items`, `Pet_properties_tag`.
122
+ * A segment that is not alphanumeric gets a hash, so `@type` and `type` differ.
123
+ */
124
+ export const toModelName = ({ refName, refPath }, toComponentName = name => name) => {
125
+ if (isDefaultRefPath({ refPath, refType: 'schema' })) {
126
+ return toComponentName(refName);
127
+ }
128
+ const segments = [...(isRemoteRefPath(refPath) ? [refPath] : toRefPathSegments(refPath)), refName];
129
+ const [first, second, ...rest] = segments;
130
+ const named = first === 'components' && second === 'schemas' ? rest : segments;
131
+ return capitalize(named.map(segment => (/^[a-zA-Z0-9]+$/.test(segment) ? segment : `${camelCase(segment)}${toShortHash(segment)}`)).join('_'));
58
132
  };
133
+ /** A 32-bit FNV-1a hash, in base 36. */
134
+ const toShortHash = (value) => [...value]
135
+ .reduce((hash, char) => Math.imul(hash ^ (char.codePointAt(0) ?? 0), 0x01000193) >>> 0, 0x811c9dc5)
136
+ .toString(36);
137
+ /** Whether a model key ({@link toModelKey}) is a whole pointer, and not a component's `refName`. */
138
+ export const isPointerKey = (key) => key.startsWith('#/');
139
+ /**
140
+ * Reverses {@link toModelKey}, for a key read back out of a generator key.
141
+ * A pointer starts with `#/`; any other key is a component's `refName`. A key
142
+ * has no percent escapes, so a `%` in it is read as written.
143
+ */
144
+ export const fromModelKey = (key) => isPointerKey(key) ? toPartsOf(key.slice(2).split('/').map(unescapeSegment)) : toSchemaComponentRef(key);
145
+ /**
146
+ * The value at a ref's pointer in a raw document, or `undefined` when the
147
+ * pointer leads nowhere, or out of the document. It walks objects by key and arrays by index.
148
+ */
149
+ export const toRawRefTarget = (document, { refName, refPath }) => isRemoteRefPath(refPath) ? undefined : [...toRefPathSegments(refPath), refName].reduce((value, segment) => {
150
+ if (Array.isArray(value)) {
151
+ return /^\d+$/.test(segment) ? value[Number(segment)] : undefined;
152
+ }
153
+ return isPlainObject(value) && Object.hasOwn(value, segment) ? value[segment] : undefined;
154
+ }, document);
59
155
  const toPercentDecoded = (segment) => {
60
156
  try {
61
157
  return decodeURIComponent(segment);
@@ -84,7 +180,7 @@ const toPercentDecoded = (segment) => {
84
180
  * if (isRef(schemaOrRef)) {
85
181
  * // TypeScript now knows schemaOrRef has a $ref property
86
182
  * console.log(schemaOrRef.$ref); // Safe to access
87
- * const refName = toRefName(schemaOrRef.$ref);
183
+ * const { refName, refPath } = toRefParts({ $ref: schemaOrRef.$ref });
88
184
  * } else {
89
185
  * // Handle as actual schema object
90
186
  * console.log('Direct schema object');
@@ -191,20 +287,27 @@ export const isRef = (value) => {
191
287
  */
192
288
  export const toGetRef = (oasDocument, onDangling) => ({ $ref }) => toTargetSchema({ oasDocument, onDangling, $ref, followed: [] });
193
289
  /**
194
- * The schema at the end of the chain of `$ref`s. A `$ref` that names nothing,
195
- * or a chain that comes back to a component it has passed (`A` is a `$ref`
196
- * to `B`, and `B` to `A`), gives `onDangling` a `DanglingRefError`, or throws it.
290
+ * The schema at the end of the chain of `$ref`s, each followed by its whole
291
+ * pointer: a component (`#/components/schemas/Pet`) or any other place in
292
+ * the document (`#/components/schemas/Pet/properties/tag`). A `$ref` that
293
+ * names nothing, one to a component that is not a schema, or a chain that
294
+ * comes back to a place it has passed (`A` is a `$ref` to `B`, and `B` to
295
+ * `A`), gives `onDangling` a `DanglingRefError`, or throws it.
197
296
  */
198
297
  const toTargetSchema = ({ oasDocument, onDangling, $ref, followed }) => {
199
- const item = oasDocument.components?.schemas?.[toRefName($ref)];
200
- if (!item) {
201
- return toDangling(onDangling, new DanglingRefError($ref));
298
+ const parts = toRefParts({ $ref });
299
+ const bucket = toRefPathBucket(parts.refPath);
300
+ const namesSchema = parts.refName !== '' && (bucket === undefined || bucket === toComponentsBucket('schema'));
301
+ const item = namesSchema ? toRawRefTarget(oasDocument, parts) : undefined;
302
+ if (!isRawSchema(item)) {
303
+ return toDangling(onDangling, new DanglingRefError($ref, { remote: isRemoteRefPath(parts.refPath) }));
202
304
  }
203
305
  if (!isRef(item)) {
204
306
  return item;
205
307
  }
206
308
  const passed = [...followed, $ref];
207
- const loopStart = passed.findIndex(each => toRefName(each) === toRefName(item.$ref));
309
+ const toPointer = (each) => toRefPointer(toRefParts({ $ref: each }));
310
+ const loopStart = passed.findIndex(each => toPointer(each) === toPointer(item.$ref));
208
311
  if (loopStart === -1) {
209
312
  return toTargetSchema({ oasDocument, onDangling, $ref: item.$ref, followed: passed });
210
313
  }
@@ -213,6 +316,12 @@ const toTargetSchema = ({ oasDocument, onDangling, $ref, followed }) => {
213
316
  const loop = [...passed.slice(loopStart + 1), item.$ref];
214
317
  return toDangling(onDangling, new DanglingRefError(passed[0] ?? $ref, { loop }));
215
318
  };
319
+ /**
320
+ * Whether a value found at a pointer can be read as a schema: an object. Its
321
+ * keywords are read as the merge reads any member; nothing more is checked
322
+ * here, as for a component.
323
+ */
324
+ const isRawSchema = (value) => isPlainObject(value);
216
325
  const toDangling = (onDangling, error) => {
217
326
  if (onDangling) {
218
327
  return onDangling(error);
package/esm/mod.d.ts CHANGED
@@ -181,6 +181,7 @@ export * from './parse/v3-0/string/toString.js';
181
181
  export * from './oas/tag/Tag.js';
182
182
  export * from './oas/tag/tag-types.js';
183
183
  export * from './oas/union/Union.js';
184
+ export * from './oas/intersection/Intersection.js';
184
185
  export * from './parse/v3-0/union/toUnion.js';
185
186
  export * from './oas/unknown/Unknown.js';
186
187
  export * from './oas/unknown/unknown-types.js';
package/esm/mod.js CHANGED
@@ -181,6 +181,7 @@ export * from './parse/v3-0/string/toString.js';
181
181
  export * from './oas/tag/Tag.js';
182
182
  export * from './oas/tag/tag-types.js';
183
183
  export * from './oas/union/Union.js';
184
+ export * from './oas/intersection/Intersection.js';
184
185
  export * from './parse/v3-0/union/toUnion.js';
185
186
  export * from './oas/unknown/Unknown.js';
186
187
  export * from './oas/unknown/unknown-types.js';
@@ -173,6 +173,12 @@ export declare class OasDocument {
173
173
  * ```
174
174
  */
175
175
  constructor(fields?: DocumentFields);
176
+ /** The parsed target of a ref that does not point at a component, by its whole pointer. */
177
+ toRefTarget(pointer: string): ComponentsEntry | undefined;
178
+ /** Keeps the parsed target of a ref that does not point at a component, under its whole pointer. */
179
+ setRefTarget(pointer: string, target: ComponentsEntry): void;
180
+ /** Removes a ref target, as {@link removeItem} removes a component, and returns it. */
181
+ removeRefTarget(pointer: string): ComponentsEntry | undefined;
176
182
  /**
177
183
  * Removes an item from the document based on a stack trail path.
178
184
  *
@@ -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 _OasDocument_fields;
12
+ var _OasDocument_fields, _OasDocument_refTargets;
13
13
  import "../../_dnt.polyfills.js";
14
14
  /**
15
15
  * Represents a complete OpenAPI v3 document in the SKMTC OAS processing system.
@@ -139,8 +139,50 @@ export class OasDocument {
139
139
  });
140
140
  /** @internal Private fields storage */
141
141
  _OasDocument_fields.set(this, void 0);
142
+ /**
143
+ * The targets of refs that do not point at a component, such as
144
+ * `#/components/schemas/Pet/properties/tag` or
145
+ * `#/paths/~1pets/get/responses/200/content/application~1json/schema`.
146
+ * Each is parsed once, at its own position, and kept under its whole
147
+ * pointer (`toRefPointer`). The model sweep does not visit them: a
148
+ * generator reaches one through a ref.
149
+ */
150
+ _OasDocument_refTargets.set(this, new Map()
151
+ /**
152
+ * Creates a new OasDocument instance.
153
+ *
154
+ * The document is typically created with undefined fields and populated
155
+ * later during the parsing process. This allows for lazy initialization
156
+ * and proper error handling during document processing.
157
+ *
158
+ * @param fields - Optional document fields (usually set later during parsing)
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * // Usually created without fields during parsing
163
+ * const document = new OasDocument();
164
+ *
165
+ * // Fields are set later by the parser
166
+ * document.fields = parsedDocumentFields;
167
+ * ```
168
+ */
169
+ );
142
170
  __classPrivateFieldSet(this, _OasDocument_fields, fields, "f");
143
171
  }
172
+ /** The parsed target of a ref that does not point at a component, by its whole pointer. */
173
+ toRefTarget(pointer) {
174
+ return __classPrivateFieldGet(this, _OasDocument_refTargets, "f").get(pointer);
175
+ }
176
+ /** Keeps the parsed target of a ref that does not point at a component, under its whole pointer. */
177
+ setRefTarget(pointer, target) {
178
+ __classPrivateFieldGet(this, _OasDocument_refTargets, "f").set(pointer, target);
179
+ }
180
+ /** Removes a ref target, as {@link removeItem} removes a component, and returns it. */
181
+ removeRefTarget(pointer) {
182
+ const target = __classPrivateFieldGet(this, _OasDocument_refTargets, "f").get(pointer);
183
+ __classPrivateFieldGet(this, _OasDocument_refTargets, "f").delete(pointer);
184
+ return target;
185
+ }
144
186
  /**
145
187
  * Removes an item from the document based on a stack trail path.
146
188
  *
@@ -332,4 +374,4 @@ export class OasDocument {
332
374
  };
333
375
  }
334
376
  }
335
- _OasDocument_fields = new WeakMap();
377
+ _OasDocument_fields = new WeakMap(), _OasDocument_refTargets = new WeakMap();