@skmtc/core 0.46.0 → 0.47.1

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 (108) hide show
  1. package/README.md +7 -1
  2. package/esm/context/ParseContext.d.ts +3 -0
  3. package/esm/context/ParseContext.js +17 -7
  4. package/esm/context/generateTypes.d.ts +2 -2
  5. package/esm/helpers/collateExamples.js +35 -17
  6. package/esm/mod.d.ts +1 -0
  7. package/esm/mod.js +1 -0
  8. package/esm/oas/intersection/Intersection.d.ts +122 -0
  9. package/esm/oas/intersection/Intersection.js +266 -0
  10. package/esm/oas/mediaType/jsonMediaType.d.ts +1 -1
  11. package/esm/oas/mediaType/jsonMediaType.js +3 -3
  12. package/esm/oas/requestBody/RequestBody.d.ts +1 -1
  13. package/esm/oas/requestBody/RequestBody.js +1 -1
  14. package/esm/oas/response/Response.d.ts +1 -1
  15. package/esm/oas/response/Response.js +1 -1
  16. package/esm/oas/schema/Schema.d.ts +4 -2
  17. package/esm/oas/schema/siblings.d.ts +10 -2
  18. package/esm/oas/schema/siblings.js +87 -22
  19. package/esm/oas/schemaPath/traverseSchema.d.ts +2 -0
  20. package/esm/oas/schemaPath/traverseSchema.js +40 -0
  21. package/esm/parse/allOfSystem.d.ts +3 -0
  22. package/esm/parse/allOfSystem.js +2 -1
  23. package/esm/parse/keptIntersection.d.ts +53 -0
  24. package/esm/parse/keptIntersection.js +155 -0
  25. package/esm/parse/keptRefs.d.ts +23 -0
  26. package/esm/parse/keptRefs.js +59 -0
  27. package/esm/parse/toCyclicRefs.d.ts +8 -0
  28. package/esm/parse/toCyclicRefs.js +126 -0
  29. package/esm/parse/toDeclaredTypes.d.ts +20 -0
  30. package/esm/parse/toDeclaredTypes.js +43 -0
  31. package/esm/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  32. package/esm/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  33. package/esm/parse/v3-0/_merge-all-of/merge.js +13 -0
  34. package/esm/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  35. package/esm/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  36. package/esm/parse/v3-0/intersection/toIntersection.js +61 -0
  37. package/esm/parse/v3-0/schema/toSchemasV3.js +13 -1
  38. package/esm/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  39. package/esm/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  40. package/esm/parse/v3-1/_merge-all-of/merge.js +13 -0
  41. package/esm/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  42. package/esm/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  43. package/esm/parse/v3-1/intersection/toIntersection.js +61 -0
  44. package/esm/parse/v3-1/schema/toSchemasV3.js +15 -2
  45. package/esm/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  46. package/esm/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  47. package/esm/parse/v3-2/_merge-all-of/merge.js +13 -0
  48. package/esm/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  49. package/esm/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  50. package/esm/parse/v3-2/intersection/toIntersection.js +61 -0
  51. package/esm/parse/v3-2/schema/toSchemasV3.js +15 -2
  52. package/esm/types/Settings.d.ts +9 -0
  53. package/esm/types/Settings.js +2 -1
  54. package/esm/types/TypeSystem.d.ts +17 -2
  55. package/package.json +1 -1
  56. package/script/context/ParseContext.d.ts +3 -0
  57. package/script/context/ParseContext.js +17 -7
  58. package/script/context/generateTypes.d.ts +2 -2
  59. package/script/helpers/collateExamples.js +35 -17
  60. package/script/mod.d.ts +1 -0
  61. package/script/mod.js +1 -0
  62. package/script/oas/intersection/Intersection.d.ts +122 -0
  63. package/script/oas/intersection/Intersection.js +270 -0
  64. package/script/oas/mediaType/jsonMediaType.d.ts +1 -1
  65. package/script/oas/mediaType/jsonMediaType.js +3 -3
  66. package/script/oas/requestBody/RequestBody.d.ts +1 -1
  67. package/script/oas/requestBody/RequestBody.js +1 -1
  68. package/script/oas/response/Response.d.ts +1 -1
  69. package/script/oas/response/Response.js +1 -1
  70. package/script/oas/schema/Schema.d.ts +4 -2
  71. package/script/oas/schema/siblings.d.ts +10 -2
  72. package/script/oas/schema/siblings.js +89 -23
  73. package/script/oas/schemaPath/traverseSchema.d.ts +2 -0
  74. package/script/oas/schemaPath/traverseSchema.js +40 -0
  75. package/script/parse/allOfSystem.d.ts +3 -0
  76. package/script/parse/allOfSystem.js +2 -1
  77. package/script/parse/keptIntersection.d.ts +53 -0
  78. package/script/parse/keptIntersection.js +164 -0
  79. package/script/parse/keptRefs.d.ts +23 -0
  80. package/script/parse/keptRefs.js +63 -0
  81. package/script/parse/toCyclicRefs.d.ts +8 -0
  82. package/script/parse/toCyclicRefs.js +130 -0
  83. package/script/parse/toDeclaredTypes.d.ts +20 -0
  84. package/script/parse/toDeclaredTypes.js +48 -0
  85. package/script/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  86. package/script/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  87. package/script/parse/v3-0/_merge-all-of/merge.js +13 -0
  88. package/script/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  89. package/script/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  90. package/script/parse/v3-0/intersection/toIntersection.js +65 -0
  91. package/script/parse/v3-0/schema/toSchemasV3.js +13 -1
  92. package/script/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  93. package/script/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  94. package/script/parse/v3-1/_merge-all-of/merge.js +13 -0
  95. package/script/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  96. package/script/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  97. package/script/parse/v3-1/intersection/toIntersection.js +65 -0
  98. package/script/parse/v3-1/schema/toSchemasV3.js +15 -2
  99. package/script/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  100. package/script/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  101. package/script/parse/v3-2/_merge-all-of/merge.js +13 -0
  102. package/script/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  103. package/script/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  104. package/script/parse/v3-2/intersection/toIntersection.js +65 -0
  105. package/script/parse/v3-2/schema/toSchemasV3.js +15 -2
  106. package/script/types/Settings.d.ts +9 -0
  107. package/script/types/Settings.js +2 -1
  108. package/script/types/TypeSystem.d.ts +17 -2
@@ -259,7 +259,7 @@ export class OasResponse extends OasBase {
259
259
  * `mediaType`, the schema of the JSON media type that {@link toJsonContent}
260
260
  * picks: `application/json`, else the first JSON-like type such as
261
261
  * `application/json;v=1.0` or `application/vnd.api+json`, else `*\/*`
262
- * when its schema is an object, array, union or `$ref`.
262
+ * when its schema is an object, array, union, intersection or `$ref`.
263
263
  * `undefined` when there is no such media type or it has no schema.
264
264
  */
265
265
  toSchema(mediaType) {
@@ -7,6 +7,7 @@ import type { OasObject } from '../object/Object.js';
7
7
  import type { OasString } from '../string/String.js';
8
8
  import type { OasUnknown } from '../unknown/Unknown.js';
9
9
  import type { OasUnion } from '../union/Union.js';
10
+ import type { OasIntersection } from '../intersection/Intersection.js';
10
11
  /**
11
12
  * Union type representing all possible OpenAPI Schema objects in the SKMTC system.
12
13
  *
@@ -28,7 +29,8 @@ import type { OasUnion } from '../union/Union.js';
28
29
  * - **{@link OasObject}**: Object schemas with properties, required fields, and constraints
29
30
  * - **{@link OasString}**: String schemas with length constraints, patterns, and formats
30
31
  * - **{@link OasUnknown}**: Schemas with unknown or mixed types
31
- * - **{@link OasUnion}**: Union schemas representing oneOf/anyOf/allOf constructs
32
+ * - **{@link OasUnion}**: Union schemas representing oneOf/anyOf constructs
33
+ * - **{@link OasIntersection}**: An allOf that keeps a reference
32
34
  *
33
35
  * @example Type checking and processing
34
36
  * ```typescript
@@ -108,7 +110,7 @@ import type { OasUnion } from '../union/Union.js';
108
110
  * }
109
111
  * ```
110
112
  */
111
- export type OasSchema = OasArray | OasBoolean | OasInteger | OasNumber | OasObject | OasString | OasUnknown | OasUnion;
113
+ export type OasSchema = OasArray | OasBoolean | OasInteger | OasNumber | OasObject | OasString | OasUnknown | OasUnion | OasIntersection;
112
114
  /**
113
115
  * Configuration options for JSON Schema conversion operations.
114
116
  *
@@ -1,5 +1,6 @@
1
1
  import type { OasSchema } from './Schema.js';
2
2
  import type { OasRef } from '../ref/Ref.js';
3
+ import type { OasIntersection } from '../intersection/Intersection.js';
3
4
  /**
4
5
  * The keywords next to a reference in a one-member `allOf`
5
6
  * (`{ allOf: [{ $ref }], minLength: 3, description: '…' }`), the use-site
@@ -68,7 +69,7 @@ export type SiblingKeywords = {
68
69
  };
69
70
  /** A keyword `clone` can apply. `_type` only has to agree. */
70
71
  export type SiblingKeyword = Exclude<keyof SiblingKeywords, '_type'>;
71
- /** The keywords each schema class's `clone` takes: the fields its type has. */
72
+ /** The keywords each schema class's `clone` takes: the fields its type has, and {@link OBJECT_KEYWORDS} for an intersection. */
72
73
  export declare const SIBLINGS_BY_TYPE: Record<OasSchema['type'], SiblingKeyword[]>;
73
74
  /**
74
75
  * The keywords of `over` merged over those of `base`, for a reference copied
@@ -98,6 +99,13 @@ export declare const changesValues: (copy: OasSchema, target: OasSchema, sibling
98
99
  * `OasRef.toSkippedSiblings`.
99
100
  */
100
101
  export declare const toSkippedSiblings: (target: OasSchema, siblings: SiblingKeywords, nullable: boolean | undefined) => string[];
102
+ /**
103
+ * The {@link OBJECT_KEYWORDS} next to a reference that say something the
104
+ * members of an intersection do not: a name none of them requires, a property
105
+ * none of them has the same. References in the members count by their target,
106
+ * without the keywords next to them.
107
+ */
108
+ export declare const toChangedObjectKeywords: (target: OasIntersection, siblings: SiblingKeywords) => SiblingKeyword[];
101
109
  /** The annotations of `target` with those of `siblings` applied: a sibling's value wins, and extension fields merge. */
102
110
  export declare const toSiblingAnnotations: (target: OasSchema, siblings: SiblingKeywords | undefined) => {
103
111
  title: string | undefined;
@@ -113,7 +121,7 @@ export declare const isIntegerValue: (value: unknown) => value is number;
113
121
  export declare const isBooleanValue: (value: unknown) => value is boolean;
114
122
  export declare const isArrayValue: (value: unknown) => value is unknown[];
115
123
  export declare const isObjectValue: (value: unknown) => value is Record<string, unknown>;
116
- /** {@link isStringValue} and the others, keyed by the type they check for. A union or unknown takes any value. */
124
+ /** {@link isStringValue} and the others, keyed by the type they check for. A union, intersection or unknown takes any value. */
117
125
  export declare const VALUE_CHECKS: Record<OasSchema['type'], (value: unknown) => boolean>;
118
126
  /** The formats a number and an integer take. A string takes any format. */
119
127
  export declare const isNumberFormat: (value: unknown) => value is "float" | "double";
@@ -22,7 +22,15 @@ const NUMERIC = [
22
22
  'exclusiveMinimum',
23
23
  'exclusiveMaximum'
24
24
  ];
25
- /** The keywords each schema class's `clone` takes: the fields its type has. */
25
+ /** The keywords of an object. An intersection's `clone` takes them as one more member. */
26
+ const OBJECT_KEYWORDS = [
27
+ 'properties',
28
+ 'required',
29
+ 'additionalProperties',
30
+ 'minProperties',
31
+ 'maxProperties'
32
+ ];
33
+ /** The keywords each schema class's `clone` takes: the fields its type has, and {@link OBJECT_KEYWORDS} for an intersection. */
26
34
  export const SIBLINGS_BY_TYPE = {
27
35
  string: [...DESCRIBING, 'deprecated', 'default', 'enums', 'format', 'minLength', 'maxLength', 'pattern'],
28
36
  number: [...DESCRIBING, ...NUMERIC],
@@ -34,13 +42,10 @@ export const SIBLINGS_BY_TYPE = {
34
42
  'deprecated',
35
43
  'default',
36
44
  'enums',
37
- 'properties',
38
- 'required',
39
- 'additionalProperties',
40
- 'minProperties',
41
- 'maxProperties'
45
+ ...OBJECT_KEYWORDS
42
46
  ],
43
47
  union: [...DESCRIBING, 'default'],
48
+ intersection: [...DESCRIBING, 'deprecated', 'default', ...OBJECT_KEYWORDS],
44
49
  unknown: DESCRIBING
45
50
  };
46
51
  /** Every keyword `clone` can apply, for any type. */
@@ -123,14 +128,21 @@ const BOOLEAN_KEYWORDS = [
123
128
  * a flag the target already has, and a value equal to the target's change
124
129
  * nothing.
125
130
  */
126
- const toChangedKeywords = (copy, target, siblings) => SIBLINGS_BY_TYPE[target.type].filter(keyword => {
127
- if (siblings[keyword] === undefined) {
128
- return false;
129
- }
130
- const applied = Reflect.get(copy, keyword);
131
- const original = Reflect.get(target, keyword);
132
- return BOOLEAN_KEYWORDS.includes(keyword) ? (applied === true) !== (original === true) : !isEqual(applied, original);
133
- });
131
+ const toChangedKeywords = (copy, target, siblings) => {
132
+ // An intersection takes these as a member, so it has no field to compare.
133
+ const objectKeywords = target.type === 'intersection' ? toChangedObjectKeywords(target, siblings) : [];
134
+ return SIBLINGS_BY_TYPE[target.type].filter(keyword => {
135
+ if (siblings[keyword] === undefined) {
136
+ return false;
137
+ }
138
+ if (target.type === 'intersection' && OBJECT_KEYWORDS.includes(keyword)) {
139
+ return objectKeywords.includes(keyword);
140
+ }
141
+ const applied = Reflect.get(copy, keyword);
142
+ const original = Reflect.get(target, keyword);
143
+ return BOOLEAN_KEYWORDS.includes(keyword) ? (applied === true) !== (original === true) : !isEqual(applied, original);
144
+ });
145
+ };
134
146
  /** Whether the keywords next to a reference change `target` at that site. The engine behind `OasRef.resolve`. */
135
147
  export const changesTarget = (copy, target, siblings) => toChangedKeywords(copy, target, siblings).length > 0;
136
148
  /**
@@ -170,23 +182,72 @@ export const toSkippedSiblings = (target, siblings, nullable) => {
170
182
  return false;
171
183
  }
172
184
  };
173
- const type = siblings._type !== undefined && !agrees(siblings._type, target, 0) ? ['type'] : [];
185
+ const type = siblings._type !== undefined && !agrees(siblings._type, target) ? ['type'] : [];
174
186
  const others = SIBLING_KEYWORDS.filter(keyword => isSkipped(keyword, siblings[keyword])).map(toDocumentKeyword);
175
187
  return [...type, ...others];
176
188
  };
177
- /** How deep {@link agrees} follows union members, so a union that contains itself ends. */
178
- const MAX_DEPTH = 10;
189
+ /**
190
+ * The {@link OBJECT_KEYWORDS} next to a reference that say something the
191
+ * members of an intersection do not: a name none of them requires, a property
192
+ * none of them has the same. References in the members count by their target,
193
+ * without the keywords next to them.
194
+ */
195
+ export const toChangedObjectKeywords = (target, siblings) => {
196
+ const objects = target.toTargetParts().filter(part => part.type === 'object');
197
+ const isSame = (keyword) => objects.some(object => isEqual(object[keyword], siblings[keyword]));
198
+ const isUnchanged = (keyword) => {
199
+ switch (keyword) {
200
+ case 'required':
201
+ return (siblings.required ?? []).every(name => objects.some(object => object.required?.includes(name)));
202
+ case 'properties':
203
+ return Object.keys(siblings.properties ?? {}).every(name => objects.some(object => isEqual(object.properties?.[name], siblings.properties?.[name])));
204
+ case 'additionalProperties':
205
+ case 'minProperties':
206
+ case 'maxProperties':
207
+ return isSame(keyword);
208
+ default:
209
+ return true;
210
+ }
211
+ };
212
+ return OBJECT_KEYWORDS.filter(keyword => siblings[keyword] !== undefined && !isUnchanged(keyword));
213
+ };
179
214
  /**
180
215
  * A `type` next to a reference agrees with the target's when it names it, or
181
216
  * `number` for an integer. Next to a union, it agrees when every member,
182
217
  * followed through references, has that type (`type: object` next to a
183
- * `oneOf` of objects): leaving it out then loses nothing.
218
+ * `oneOf` of objects): leaving it out then loses nothing. Next to an
219
+ * intersection, it agrees when one member has that type.
184
220
  */
185
- const agrees = (type, target, depth) => {
221
+ const agrees = (type, target) => {
222
+ const agreed = new Set();
223
+ // A schema that leads back to itself does not agree by that, so a pass reads
224
+ // it as `false` there. It can agree by another member, so a new pass reads
225
+ // the schemas that agreed, until a pass finds no more of them.
226
+ const runPass = () => {
227
+ const before = agreed.size;
228
+ return agreesInPass({ type, target, agreed, visited: new Set() }) || (agreed.size > before && runPass());
229
+ };
230
+ return runPass();
231
+ };
232
+ const agreesInPass = ({ type, target, agreed, visited }) => {
233
+ if (agreed.has(target)) {
234
+ return true;
235
+ }
236
+ if (visited.has(target)) {
237
+ return false;
238
+ }
239
+ visited.add(target);
240
+ const result = toAgreement(type, target, member => agreesInPass({ type, target: member, agreed, visited }));
241
+ if (result) {
242
+ agreed.add(target);
243
+ }
244
+ return result;
245
+ };
246
+ /** {@link agrees} for one schema, with `agreesInside` for its members. */
247
+ const toAgreement = (type, target, agreesInside) => {
186
248
  if (target.type === 'union') {
187
249
  try {
188
- return depth < MAX_DEPTH &&
189
- target.members.every(member => agrees(type, member.isRef() ? member.resolve() : member, depth + 1));
250
+ return target.members.every(member => agreesInside(member.isRef() ? member.resolve() : member));
190
251
  }
191
252
  catch (error) {
192
253
  // A member that is a dangling reference has no known type, so it does not agree.
@@ -196,6 +257,9 @@ const agrees = (type, target, depth) => {
196
257
  throw error;
197
258
  }
198
259
  }
260
+ if (target.type === 'intersection') {
261
+ return target.toParts().some(agreesInside);
262
+ }
199
263
  return type === target.type || (type === 'number' && target.type === 'integer');
200
264
  };
201
265
  /** Whether `format` fits a schema of `type`, as `clone` reads it: any string for a string. */
@@ -227,7 +291,7 @@ export const isBooleanValue = (value) => typeof value === 'boolean';
227
291
  export const isArrayValue = (value) => Array.isArray(value);
228
292
  export const isObjectValue = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
229
293
  const isAnyValue = (_value) => true;
230
- /** {@link isStringValue} and the others, keyed by the type they check for. A union or unknown takes any value. */
294
+ /** {@link isStringValue} and the others, keyed by the type they check for. A union, intersection or unknown takes any value. */
231
295
  export const VALUE_CHECKS = {
232
296
  string: isStringValue,
233
297
  number: isNumberValue,
@@ -236,6 +300,7 @@ export const VALUE_CHECKS = {
236
300
  array: isArrayValue,
237
301
  object: isObjectValue,
238
302
  union: isAnyValue,
303
+ intersection: isAnyValue,
239
304
  unknown: isAnyValue
240
305
  };
241
306
  /** The formats a number and an integer take. A string takes any format. */
@@ -18,6 +18,8 @@ import type { SchemaPath } from '../../types/SchemaPath.js';
18
18
  * element schema.
19
19
  * - **union** → the segment selects a member ({@link selectUnionMember}):
20
20
  * `'$Circle'` by refName, `'{type:circle}'` by discriminator, `'[0]'` by index.
21
+ * - **intersection** → the segment is read as for a member, references followed:
22
+ * the last member that has the whole path.
21
23
  *
22
24
  * A ref is resolved only when the path needs to descend *through* it. Anything
23
25
  * the path cannot navigate throws a descriptive, segment-named error: a missing
@@ -16,6 +16,8 @@ import { toRefParts, toRefPointer } from '../../helpers/refFns.js';
16
16
  * element schema.
17
17
  * - **union** → the segment selects a member ({@link selectUnionMember}):
18
18
  * `'$Circle'` by refName, `'{type:circle}'` by discriminator, `'[0]'` by index.
19
+ * - **intersection** → the segment is read as for a member, references followed:
20
+ * the last member that has the whole path.
19
21
  *
20
22
  * A ref is resolved only when the path needs to descend *through* it. Anything
21
23
  * the path cannot navigate throws a descriptive, segment-named error: a missing
@@ -53,11 +55,49 @@ export const traverseSchema = (value, path) => {
53
55
  case 'union': {
54
56
  return traverseSchema(selectUnionMember(schema, segment), rest);
55
57
  }
58
+ case 'intersection': {
59
+ const members = schema.toParts().filter(part => takesSegment(part, segment));
60
+ if (members.length === 0) {
61
+ throw new Error(`Schema path segment "${segment}" does not match a member of the intersection`);
62
+ }
63
+ return traverseLast(members, path);
64
+ }
56
65
  default: {
57
66
  throw new Error(`Schema path segment "${segment}" cannot traverse a "${schema.type}" schema`);
58
67
  }
59
68
  }
60
69
  };
70
+ /** The schema at `path` in the last of `members` that has the whole path. When none has, the last one's error. */
71
+ const traverseLast = (members, path) => {
72
+ const [last, ...others] = members.toReversed();
73
+ try {
74
+ return traverseSchema(last, path);
75
+ }
76
+ catch (error) {
77
+ for (const member of others) {
78
+ try {
79
+ return traverseSchema(member, path);
80
+ }
81
+ catch {
82
+ // The next member may have the path.
83
+ }
84
+ }
85
+ throw error;
86
+ }
87
+ };
88
+ /** Whether a member of an intersection is one that `segment` can descend into. */
89
+ const takesSegment = (schema, segment) => {
90
+ switch (schema.type) {
91
+ case 'object':
92
+ return schema.properties?.[segment] !== undefined;
93
+ case 'array':
94
+ return segment === 'items';
95
+ case 'union':
96
+ return /^(\$|\[\d+\]$|\{)/.test(segment);
97
+ default:
98
+ return false;
99
+ }
100
+ };
61
101
  /**
62
102
  * Pick one member of a union for an {@link SchemaPath} segment. The segment's
63
103
  * notation chooses the branching strategy:
@@ -1,4 +1,5 @@
1
1
  import type { ParseContextType } from '../context/parseTypes.js';
2
+ import type { KeptRefs } from './keptRefs.js';
2
3
  import type { StackTrail } from '../context/StackTrail.js';
3
4
  /** What the `allOf` merge reads of `client.json#settings.system`, and what it reports back. */
4
5
  type AllOfSystem = {
@@ -9,6 +10,8 @@ type AllOfSystem = {
9
10
  replaced: Set<string>;
10
11
  /** The keywords the merge read as any value: `anyOf` under `system.anyOf: unknown`. */
11
12
  unknown: Set<string>;
13
+ /** The refs that stay refs (`system.intersections`). */
14
+ keptRefs: KeptRefs | undefined;
12
15
  };
13
16
  /**
14
17
  * The `system` settings for one merge: the `allOf` mode, `strict` when the
@@ -9,7 +9,8 @@ export const toAllOfSystem = (context) => ({
9
9
  not: context.system?.not ?? 'strict',
10
10
  anyOf: context.system?.anyOf ?? 'union',
11
11
  replaced: new Set(),
12
- unknown: new Set()
12
+ unknown: new Set(),
13
+ keptRefs: context.keptRefs
13
14
  });
14
15
  /**
15
16
  * One warning for a schema whose `allOf` members contradicted, naming the
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The raw form of an intersection inside a merge: an `allOf` of kept refs
3
+ * (`KeptRefs`) and at most one other schema, which the other members merged
4
+ * into, with only `OWN_KEYWORDS` beside it.
5
+ */
6
+ import type { OpenAPIV3 } from 'openapi-types';
7
+ import type { KeptRefs } from './keptRefs.js';
8
+ type SchemaObject = OpenAPIV3.SchemaObject;
9
+ type ReferenceObject = OpenAPIV3.ReferenceObject;
10
+ type SchemaOrReference = SchemaObject | ReferenceObject;
11
+ type Split = {
12
+ own: SchemaObject;
13
+ rest: SchemaObject;
14
+ };
15
+ /** A schema's keywords that stay beside its `allOf`, and the others. */
16
+ export declare const splitOwnKeywords: (schema: SchemaObject) => Split;
17
+ /** A merge result with the wrapper's own keywords, which win, put back on it. */
18
+ export declare const withOwnKeywords: (merged: SchemaOrReference, own: SchemaObject) => SchemaOrReference;
19
+ type Intersection = {
20
+ own: SchemaObject;
21
+ members: SchemaOrReference[];
22
+ };
23
+ /** The parts of a kept ref, or of a schema in the raw form of an intersection; `undefined` for any other schema. */
24
+ export declare const toIntersectionParts: (schema: SchemaOrReference, keptRefs: KeptRefs) => Intersection | undefined;
25
+ type MergeKeptArgs = {
26
+ first: SchemaOrReference;
27
+ second: SchemaOrReference;
28
+ keptRefs: KeptRefs;
29
+ /** Merges two schemas that hold no kept ref. */
30
+ merge: (first: SchemaOrReference, second: SchemaOrReference) => SchemaOrReference;
31
+ /** Merges a schema's own `allOf`. */
32
+ mergeAllOf: (schema: SchemaObject) => SchemaOrReference;
33
+ readRef: (ref: ReferenceObject) => SchemaObject;
34
+ normalize: (schema: SchemaObject) => SchemaObject;
35
+ };
36
+ /**
37
+ * Merges two schemas where at least one is a kept ref or an intersection: the
38
+ * kept refs stay, and the others merge into one member, at the place of the
39
+ * first of them.
40
+ */
41
+ export declare const mergeKept: ({ first, second, keptRefs, merge, mergeAllOf, readRef, normalize }: MergeKeptArgs) => SchemaOrReference;
42
+ /**
43
+ * The parts of a finished merge, to parse: the keywords that say how the whole
44
+ * value is used move from the one member that is not a ref to the intersection.
45
+ */
46
+ export declare const toSiteIntersection: ({ own, members }: Intersection) => Intersection;
47
+ /**
48
+ * A member with the keywords of one type and no shape (`{ required: ['id'] }`),
49
+ * as that type, and the same for the members of its `oneOf` or `anyOf`: the
50
+ * type was in the kept ref, and a schema with no type loses them.
51
+ */
52
+ export declare const withKeywordType: (member: SchemaOrReference) => SchemaOrReference;
53
+ export {};
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The raw form of an intersection inside a merge: an `allOf` of kept refs
3
+ * (`KeptRefs`) and at most one other schema, which the other members merged
4
+ * into, with only `OWN_KEYWORDS` beside it.
5
+ */
6
+ import { isRef, toRefParts, toRefPointer } from '../helpers/refFns.js';
7
+ import { isEmpty } from '../helpers/isEmpty.js';
8
+ import { hasNullMember } from './anyOfSystem.js';
9
+ import { isPlainObject } from './isPlainObject.js';
10
+ import { isNullOnly } from './v3-0/_merge-all-of/nullable-merge.js';
11
+ /** The keywords of a wrapper that stay beside its `allOf`, out of the merge. `x-*` is one too. */
12
+ const OWN_KEYWORDS = ['title', 'description', 'externalDocs', 'example'];
13
+ /** The keywords that say how the whole value is used. They merge as any keyword, and then are the intersection's own. */
14
+ const SITE_KEYWORDS = ['nullable', 'readOnly', 'writeOnly', 'deprecated', 'default'];
15
+ const isOwnKeyword = (key) => OWN_KEYWORDS.includes(key) || key.startsWith('x-');
16
+ const split = (schema, isOwn) => {
17
+ const entries = Object.entries(schema);
18
+ return {
19
+ own: Object.fromEntries(entries.filter(([key]) => isOwn(key))),
20
+ rest: Object.fromEntries(entries.filter(([key]) => !isOwn(key)))
21
+ };
22
+ };
23
+ /** A schema's keywords that stay beside its `allOf`, and the others. */
24
+ export const splitOwnKeywords = (schema) => split(schema, isOwnKeyword);
25
+ /** A merge result with the wrapper's own keywords, which win, put back on it. */
26
+ export const withOwnKeywords = (merged, own) => {
27
+ if (isEmpty(own)) {
28
+ return merged;
29
+ }
30
+ return isRef(merged) ? { ...own, allOf: [merged] } : { ...merged, ...own };
31
+ };
32
+ /** The parts of a kept ref, or of a schema in the raw form of an intersection; `undefined` for any other schema. */
33
+ export const toIntersectionParts = (schema, keptRefs) => {
34
+ if (isRef(schema)) {
35
+ return keptRefs.has(schema) ? { own: {}, members: [schema] } : undefined;
36
+ }
37
+ if (!Array.isArray(schema.allOf)) {
38
+ return undefined;
39
+ }
40
+ const { allOf, ...keywords } = schema;
41
+ const isKept = (member) => isRef(member) && keptRefs.has(member);
42
+ const others = allOf.filter(member => !isKept(member));
43
+ return Object.keys(keywords).every(isOwnKeyword) &&
44
+ allOf.some(isKept) &&
45
+ others.length <= 1 &&
46
+ others.every(member => !isRef(member) && !Array.isArray(member.allOf))
47
+ ? { own: keywords, members: allOf }
48
+ : undefined;
49
+ };
50
+ /**
51
+ * Merges two schemas where at least one is a kept ref or an intersection: the
52
+ * kept refs stay, and the others merge into one member, at the place of the
53
+ * first of them.
54
+ */
55
+ export const mergeKept = ({ first, second, keptRefs, merge, mergeAllOf, readRef, normalize }) => {
56
+ const toParts = (schema, other) => {
57
+ const parts = toIntersectionParts(schema, keptRefs);
58
+ if (parts !== undefined) {
59
+ return { ...parts, members: parts.members.map(member => (isRef(member) ? member : normalize(member))) };
60
+ }
61
+ if (isRef(schema)) {
62
+ // The other side keeps a ref to the same target: the two are one ref.
63
+ const isKept = toIntersectionParts(other, keptRefs)?.members.some(member => isRef(member) && isSameTarget(member, schema));
64
+ return isKept ? { own: {}, members: [schema] } : toParts(readRef(schema), other);
65
+ }
66
+ if (schema.allOf?.length === 0) {
67
+ throw new Error('Empty allOf');
68
+ }
69
+ return schema.allOf ? toParts(mergeAllOf(schema), other) : { own: {}, members: [schema] };
70
+ };
71
+ const firstParts = toParts(first, second);
72
+ const secondParts = toParts(second, first);
73
+ const members = secondParts.members.reduce((acc, member) => {
74
+ const index = acc.findIndex(other => (isRef(member) ? isRef(other) && isSameTarget(other, member) : !isRef(other)));
75
+ const other = acc[index];
76
+ if (other === undefined) {
77
+ return [...acc, member];
78
+ }
79
+ const joined = isRef(other) && isRef(member)
80
+ ? keptRefs.copy(member, keptRefs.copy(other, { ...other, ...member }))
81
+ : merge(other, member);
82
+ return acc.map((each, at) => (at === index ? joined : each));
83
+ }, firstParts.members.filter(member => !isEmpty(member)));
84
+ return toRawIntersection({ own: { ...firstParts.own, ...secondParts.own }, members });
85
+ };
86
+ const isSameTarget = (first, second) => toRefPointer(toRefParts({ $ref: first.$ref })) === toRefPointer(toRefParts({ $ref: second.$ref }));
87
+ const toRawIntersection = ({ own, members }) => {
88
+ const [only] = members;
89
+ return isEmpty(own) && members.length === 1 && only !== undefined && isRef(only) ? only : { ...own, allOf: members };
90
+ };
91
+ /**
92
+ * The parts of a finished merge, to parse: the keywords that say how the whole
93
+ * value is used move from the one member that is not a ref to the intersection.
94
+ */
95
+ export const toSiteIntersection = ({ own, members }) => {
96
+ const moved = members.map(member => (isRef(member) ? { own: {}, rest: member } : toSiteSplit(member)));
97
+ return {
98
+ own: moved.reduce((acc, { own: site }) => ({ ...acc, ...site }), own),
99
+ members: moved.map(({ rest }) => rest).filter(member => !isEmpty(member))
100
+ };
101
+ };
102
+ const OBJECT_KEYWORDS = ['required', 'minProperties', 'maxProperties', 'additionalProperties'];
103
+ const ARRAY_KEYWORDS = ['minItems', 'maxItems', 'uniqueItems'];
104
+ const STRING_KEYWORDS = ['minLength', 'maxLength', 'pattern'];
105
+ const NUMBER_KEYWORDS = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'];
106
+ /**
107
+ * A member with the keywords of one type and no shape (`{ required: ['id'] }`),
108
+ * as that type, and the same for the members of its `oneOf` or `anyOf`: the
109
+ * type was in the kept ref, and a schema with no type loses them.
110
+ */
111
+ export const withKeywordType = (member) => {
112
+ if (isRef(member) || !isPlainObject(member) || ['type', 'properties', 'items', 'enum'].some(key => key in member)) {
113
+ return member;
114
+ }
115
+ if (Array.isArray(member.oneOf) || Array.isArray(member.anyOf)) {
116
+ return {
117
+ ...member,
118
+ ...(Array.isArray(member.oneOf) ? { oneOf: member.oneOf.map(withKeywordType) } : {}),
119
+ ...(Array.isArray(member.anyOf) ? { anyOf: member.anyOf.map(withKeywordType) } : {})
120
+ };
121
+ }
122
+ const hasKeyword = (keywords) => keywords.some(keyword => keyword in member);
123
+ if (hasKeyword(OBJECT_KEYWORDS)) {
124
+ return { ...member, type: 'object' };
125
+ }
126
+ if (hasKeyword(ARRAY_KEYWORDS)) {
127
+ return { ...member, type: 'array', items: {} };
128
+ }
129
+ if (hasKeyword(STRING_KEYWORDS)) {
130
+ return { ...member, type: 'string' };
131
+ }
132
+ return hasKeyword(NUMBER_KEYWORDS) ? { ...member, type: 'number' } : member;
133
+ };
134
+ /** `schema` with a `null` member of its `oneOf` or `anyOf` written as `nullable`. */
135
+ const withoutNullMember = (schema) => ['oneOf', 'anyOf'].reduce((acc, group) => {
136
+ const members = acc[group];
137
+ if (!Array.isArray(members) || !members.every(isPlainObject) || !hasNullMember(members)) {
138
+ return acc;
139
+ }
140
+ const { [group]: _group, ...rest } = acc;
141
+ const others = members.filter(member => !hasNullMember([member]));
142
+ return { ...rest, ...(others.length > 0 ? { [group]: others } : {}), nullable: true };
143
+ }, schema);
144
+ const toSiteSplit = (written) => {
145
+ const member = withoutNullMember(written);
146
+ if (isNullOnly(member)) {
147
+ return { own: { nullable: true }, rest: {} };
148
+ }
149
+ // `null` goes with the `nullable` that moves: the member is not nullable without it.
150
+ const isSite = (key) => SITE_KEYWORDS.includes(key) || (key === 'example' && member.example === null && member.nullable === true);
151
+ const { own, rest } = split(member, isSite);
152
+ return member.nullable === true && Array.isArray(rest.enum)
153
+ ? { own, rest: { ...rest, enum: rest.enum.filter((value) => value !== null) } }
154
+ : { own, rest };
155
+ };
@@ -0,0 +1,23 @@
1
+ import type { OpenAPIV3 } from 'openapi-types';
2
+ type SchemaObject = OpenAPIV3.SchemaObject;
3
+ type ReferenceObject = OpenAPIV3.ReferenceObject;
4
+ type SchemaOrReference = SchemaObject | ReferenceObject;
5
+ /** The refs that `system.intersections` keeps out of a merge. */
6
+ export type KeptRefs = {
7
+ /** Whether a merge keeps this `$ref` object as a ref. */
8
+ has: (ref: ReferenceObject) => boolean;
9
+ /** Returns `to`, a `$ref` object made from `from`, kept when `from` is. */
10
+ copy: (from: ReferenceObject, to: ReferenceObject) => ReferenceObject;
11
+ /** Whether merging this schema gives an intersection: it is a kept ref or has one in its `allOf`, also through refs that are not kept. */
12
+ holds: (schema: SchemaOrReference) => boolean;
13
+ /** Whether a pair that holds a kept ref allows no value: the two types, read through refs, have none in common. */
14
+ contradict: (first: SchemaOrReference, second: SchemaOrReference) => boolean;
15
+ };
16
+ type ToKeptRefsArgs = {
17
+ documentObject: OpenAPIV3.Document;
18
+ /** `client.json` `system.intersections`. */
19
+ setting: 'merge' | 'cycles' | 'all' | undefined;
20
+ };
21
+ /** The refs a merge of this document keeps, or `undefined` under `merge`. */
22
+ export declare const toKeptRefs: ({ documentObject, setting }: ToKeptRefsArgs) => KeptRefs | undefined;
23
+ export {};
@@ -0,0 +1,59 @@
1
+ import { isRef, toGetRef } from '../helpers/refFns.js';
2
+ import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
3
+ import { isPlainObject } from './isPlainObject.js';
4
+ import { toCyclicRefs } from './toCyclicRefs.js';
5
+ import { haveNoCommonType, toDeclaredTypes } from './toDeclaredTypes.js';
6
+ /** The refs a merge of this document keeps, or `undefined` under `merge`. */
7
+ export const toKeptRefs = ({ documentObject, setting = 'cycles' }) => {
8
+ if (setting === 'merge') {
9
+ return undefined;
10
+ }
11
+ const cyclicRefs = setting === 'cycles' ? toCyclicRefs(documentObject) : new WeakSet();
12
+ const has = (ref) => setting === 'all' || cyclicRefs.has(ref);
13
+ const getRef = toGetRef(documentObject);
14
+ // A ref that names nothing is reported where the merge follows it.
15
+ const peek = (ref) => {
16
+ try {
17
+ return getRef(ref);
18
+ }
19
+ catch (error) {
20
+ if (DanglingRefError.is(error)) {
21
+ return undefined;
22
+ }
23
+ throw error;
24
+ }
25
+ };
26
+ const held = new WeakMap();
27
+ const isHolder = (schema) => {
28
+ if (isRef(schema)) {
29
+ const target = has(schema) ? undefined : peek(schema);
30
+ return has(schema) || (target !== undefined && holds(target));
31
+ }
32
+ return Array.isArray(schema.allOf) && schema.allOf.some(holds);
33
+ };
34
+ const holds = (schema) => {
35
+ // A document in the wild may hold a string where a member belongs.
36
+ if (!isPlainObject(schema)) {
37
+ return false;
38
+ }
39
+ const known = held.get(schema);
40
+ if (known !== undefined) {
41
+ return known;
42
+ }
43
+ const result = isHolder(schema);
44
+ held.set(schema, result);
45
+ return result;
46
+ };
47
+ return {
48
+ has,
49
+ holds,
50
+ copy: (from, to) => {
51
+ if (cyclicRefs.has(from)) {
52
+ cyclicRefs.add(to);
53
+ }
54
+ return to;
55
+ },
56
+ contradict: (first, second) => (holds(first) || holds(second)) &&
57
+ haveNoCommonType(toDeclaredTypes({ schema: first, peek }), toDeclaredTypes({ schema: second, peek }))
58
+ };
59
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The `$ref` objects of a raw document that are in a cycle: the ref's target
3
+ * leads back, through any refs, to a schema that holds the ref. A ref inside a
4
+ * deep ref target is held by that target and by the schema around it.
5
+ *
6
+ * The answer depends on the document only, not on where a parse enters it.
7
+ */
8
+ export declare const toCyclicRefs: (document: unknown) => WeakSet<object>;