@scalar/openapi-upgrader 0.2.17 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # @scalar/openapi-upgrader
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#10306](https://github.com/scalar/scalar/pull/10306): Preserve Swagger 2.0 `x-nullable` when upgrading schemas, parameters, and headers.
8
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#10211](https://github.com/scalar/scalar/pull/10211): Preserve literal data and tag groups when upgrading to OpenAPI 3.2, migrate XML metadata only in schemas, and remove incompatible legacy XML flags. Make 3.2 upgrades leave the input unchanged, match the complete source version, prevent previously inactive parameter settings from changing serialization, and report path-specific errors for detected compatibility issues that require an author's decision.
14
+
15
+ Tag `kind` values may change: navigation groups are classified from actual operation-tag usage instead of name substrings. Malformed 3.1 versions now report explicit errors, and successful 3.2 upgrades clone the input only once.
16
+
17
+ Expose `UpgradeIncompatibilityError` so Markdown generation can retain OpenAPI 3.1 for descriptions requiring author decisions instead of failing or silently changing semantics. Clone safety and malformed-version errors still propagate.
18
+
19
+ The mock server also retains OpenAPI 3.1 when the strict 3.2 migration reports compatibility diagnostics. Existing inline XML descriptions continue loading without inventing element names.
20
+
21
+ Read only own data properties during migration so inherited parameter lists, XML metadata, and reference targets cannot modify prototype-owned objects.
22
+
23
+ Add `upgrade(input, '3.2', { onIncompatible: 'collect' })` to return a complete document and compatibility diagnostics. Compatible descriptions upgrade to 3.2; incompatible descriptions retain 3.1 without partial transformations. Strict mode remains the default, and malformed-version and clone-safety errors still propagate. The Markdown converter and mock server now use the shared collect mode.
24
+
25
+ ### Patch Changes
26
+
27
+ - [#10278](https://github.com/scalar/scalar/pull/10278): Only migrate XML metadata in schemas when upgrading to OpenAPI 3.2. Preserve example payloads and other data containing xml properties instead of changing them or throwing errors.
28
+ - [#10276](https://github.com/scalar/scalar/pull/10276): Migrate x-tagGroups to OpenAPI 3.2 parent tags and remove the extension, preserving group names, member order, and tag metadata. Resolve group/tag name collisions with unique names and preserve group labels with summary. Warn and preserve the original tags and extension for ambiguous or malformed hierarchies so the API description can still render. Avoid mutating a document prototype during tag migration.
29
+
3
30
  ## 0.2.17
4
31
 
5
32
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade-from-two-to-three.d.ts","sourceRoot":"","sources":["../../src/2.0-to-3.0/upgrade-from-two-to-three.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAa,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AA2LxD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,qBAAqB,EAAE,aAAa,0CA4bzE"}
1
+ {"version":3,"file":"upgrade-from-two-to-three.d.ts","sourceRoot":"","sources":["../../src/2.0-to-3.0/upgrade-from-two-to-three.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAa,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AA2LxD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,qBAAqB,EAAE,aAAa,0CAkczE"}
@@ -185,6 +185,9 @@ export function upgradeFromTwoToThree(originalSpecification) {
185
185
  }
186
186
  // Schemas
187
187
  if (document.definitions) {
188
+ for (const schema of Object.values(document.definitions)) {
189
+ migrateSchemaNullability(schema);
190
+ }
188
191
  document.components = Object.assign({}, document.components, {
189
192
  schemas: document.definitions,
190
193
  });
@@ -285,6 +288,7 @@ export function upgradeFromTwoToThree(originalSpecification) {
285
288
  const produces = document.produces ?? [DEFAULT_MEDIA_TYPE];
286
289
  // Transform schema to content
287
290
  if (responseObj.schema) {
291
+ migrateSchemaNullability(responseObj.schema);
288
292
  if (typeof responseObj.content !== 'object') {
289
293
  responseObj.content = {};
290
294
  }
@@ -400,6 +404,7 @@ export function upgradeFromTwoToThree(originalSpecification) {
400
404
  }, {});
401
405
  }
402
406
  if (responseItem.schema) {
407
+ migrateSchemaNullability(responseItem.schema);
403
408
  const produces = document.produces ?? operationItem.produces ?? [DEFAULT_MEDIA_TYPE];
404
409
  if (typeof responseItem.content !== 'object') {
405
410
  responseItem.content = {};
@@ -516,6 +521,34 @@ export function upgradeFromTwoToThree(originalSpecification) {
516
521
  delete document.produces;
517
522
  return document;
518
523
  }
524
+ /**
525
+ * Swagger tooling uses x-nullable for the nullability keyword introduced in OpenAPI 3.0.
526
+ * Visit only subschemas so example/default values and custom extensions remain user data.
527
+ */
528
+ const migrateSchemaNullability = (schema) => {
529
+ if (!isObjectLike(schema)) {
530
+ return;
531
+ }
532
+ if (typeof schema['x-nullable'] === 'boolean') {
533
+ // False is already the default in OpenAPI 3.0 and needs no keyword in later versions.
534
+ if (schema['x-nullable']) {
535
+ schema.nullable = true;
536
+ }
537
+ delete schema['x-nullable'];
538
+ }
539
+ if (isObjectLike(schema.properties)) {
540
+ for (const property of Object.values(schema.properties)) {
541
+ migrateSchemaNullability(property);
542
+ }
543
+ }
544
+ migrateSchemaNullability(schema.items);
545
+ migrateSchemaNullability(schema.additionalProperties);
546
+ if (Array.isArray(schema.allOf)) {
547
+ for (const member of schema.allOf) {
548
+ migrateSchemaNullability(member);
549
+ }
550
+ }
551
+ };
519
552
  function transformItemsObject(obj) {
520
553
  const schemaProperties = [
521
554
  'type',
@@ -534,14 +567,17 @@ function transformItemsObject(obj) {
534
567
  'uniqueItems',
535
568
  'enum',
536
569
  'multipleOf',
570
+ 'x-nullable',
537
571
  ];
538
- return schemaProperties.reduce((acc, property) => {
572
+ const schema = schemaProperties.reduce((acc, property) => {
539
573
  if (Object.hasOwn(obj, property)) {
540
574
  acc[property] = obj[property];
541
575
  delete obj[property];
542
576
  }
543
577
  return acc;
544
578
  }, {});
579
+ migrateSchemaNullability(schema);
580
+ return schema;
545
581
  }
546
582
  function getParameterLocation(location) {
547
583
  if (location === 'formData') {
@@ -683,6 +719,7 @@ function migrateBodyParameter(bodyParameter, consumes) {
683
719
  delete bodyParameter.name;
684
720
  delete bodyParameter.in;
685
721
  const { schema, ...requestBody } = bodyParameter;
722
+ migrateSchemaNullability(schema);
686
723
  const requestBodyObject = {
687
724
  content: {},
688
725
  ...requestBody,
@@ -0,0 +1,4 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /** Reject only incompatibilities that can be established within this document. */
3
+ export declare const migrateObjects: (document: UnknownObject) => Set<string>;
4
+ //# sourceMappingURL=migrate-objects.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate-objects.d.ts","sourceRoot":"","sources":["../../src/3.1-to-3.2/migrate-objects.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AA2CxD,kFAAkF;AAClF,eAAO,MAAM,cAAc,GAAI,UAAU,aAAa,KAAG,GAAG,CAAC,MAAM,CAmalE,CAAA"}
@@ -0,0 +1,411 @@
1
+ import { escapeJsonPointer } from '@scalar/helpers/json/escape-json-pointer';
2
+ import { parseJsonPointerSegments } from '@scalar/helpers/json/parse-json-pointer-segments';
3
+ import { isObject } from '@scalar/helpers/object/is-object';
4
+ import { UpgradeIncompatibilityError } from '../upgrade-incompatibility-error.js';
5
+ const schemaMaps = ['properties', 'patternProperties', '$defs', 'dependentSchemas'];
6
+ const schemaArrays = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
7
+ const schemaSingles = [
8
+ 'items',
9
+ 'contains',
10
+ 'additionalProperties',
11
+ 'unevaluatedProperties',
12
+ 'unevaluatedItems',
13
+ 'propertyNames',
14
+ 'not',
15
+ 'if',
16
+ 'then',
17
+ 'else',
18
+ 'contentSchema',
19
+ ];
20
+ /** Reject only incompatibilities that can be established within this document. */
21
+ export const migrateObjects = (document) => {
22
+ // A cloned JSON object still inherits Object.prototype. Keep traversal in own
23
+ // data properties, including when the host already has polluted prototypes.
24
+ // Maps also allow literal __proto__ and constructor reference segments safely.
25
+ const properties = new WeakMap();
26
+ const own = (value, key) => {
27
+ const entries = properties.get(value) ??
28
+ new Map(Object.entries(Object.getOwnPropertyDescriptors(value))
29
+ .filter(([, descriptor]) => Object.hasOwn(descriptor, 'value'))
30
+ .map(([name, descriptor]) => [name, descriptor.value]));
31
+ properties.set(value, entries);
32
+ return entries.get(key);
33
+ };
34
+ const operationTags = new Set();
35
+ const errors = [];
36
+ const requiredCache = new WeakMap();
37
+ const cyclicRequired = new WeakSet();
38
+ const requiredWork = { evaluations: 0 };
39
+ const propertySchemas = new WeakSet();
40
+ const xmlRoots = [];
41
+ // Only property schemas and their array items inherit a property name.
42
+ const markPropertySchema = (schema) => {
43
+ if (!isObject(schema) || propertySchemas.has(schema)) {
44
+ return;
45
+ }
46
+ propertySchemas.add(schema);
47
+ markPropertySchema(schema.items);
48
+ if (Array.isArray(schema.prefixItems)) {
49
+ schema.prefixItems.forEach(markPropertySchema);
50
+ }
51
+ };
52
+ const xmlCache = new WeakMap();
53
+ const visited = new WeakMap();
54
+ const fail = (path, message) => {
55
+ errors.push(new Error(`Cannot upgrade to OpenAPI 3.2 at ${path}: ${message}`));
56
+ };
57
+ const resolve = (ref, schemaReference = false) => {
58
+ if (typeof ref !== 'string' || !ref.startsWith('#/')) {
59
+ return undefined;
60
+ }
61
+ try {
62
+ return parseJsonPointerSegments(decodeURIComponent(ref.slice(1))).reduce((value, key) => {
63
+ // A pointer crossing a schema resource boundary cannot be interpreted
64
+ // with the containing document's dialect and base URI.
65
+ if (schemaReference && isObject(value) && (value.$id !== undefined || value.$schema !== undefined)) {
66
+ return undefined;
67
+ }
68
+ if (Array.isArray(value) && !/^(0|[1-9]\d*)$/.test(key)) {
69
+ return undefined;
70
+ }
71
+ // Read only stored values, never inherited properties or accessors.
72
+ if ((!isObject(value) && !Array.isArray(value)) || !Object.hasOwn(value, key)) {
73
+ return undefined;
74
+ }
75
+ return own(value, key);
76
+ }, document);
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ };
82
+ const repeatedVariables = (value, path) => {
83
+ if (typeof value !== 'string') {
84
+ return;
85
+ }
86
+ const names = [...value.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]);
87
+ if (new Set(names).size !== names.length) {
88
+ fail(path, 'Template variables must not be repeated. Rename the repeated variable and define it separately.');
89
+ }
90
+ };
91
+ // Requiredness can be inherited through references or composition. Unknown
92
+ // references and conditional constraints must not be mistaken for optionality.
93
+ const requires = (schema, name, seen = new Set()) => {
94
+ if (schema === false) {
95
+ return true;
96
+ }
97
+ if (schema === true) {
98
+ return false;
99
+ }
100
+ if (!isObject(schema) || schema.$id !== undefined || schema.$schema !== undefined) {
101
+ return undefined;
102
+ }
103
+ if (seen.has(schema)) {
104
+ // Do not cache uncertain results that depend on the active ancestor chain.
105
+ for (const ancestor of seen) {
106
+ cyclicRequired.add(ancestor);
107
+ }
108
+ return undefined;
109
+ }
110
+ const cached = requiredCache.get(schema) ?? new Map();
111
+ if (cached.has(name)) {
112
+ return cached.get(name);
113
+ }
114
+ // Cyclic or unusually large analyses remain uncertain rather than blocking
115
+ // upgrading indefinitely. Completed acyclic subgraphs are memoized below.
116
+ if (++requiredWork.evaluations > 100_000) {
117
+ if (requiredWork.evaluations === 100_001) {
118
+ fail('#', 'Discriminator requiredness analysis was truncated after 100,000 evaluations.');
119
+ }
120
+ return undefined;
121
+ }
122
+ const remember = (result) => {
123
+ if (result !== undefined || !cyclicRequired.has(schema)) {
124
+ cached.set(name, result);
125
+ requiredCache.set(schema, cached);
126
+ }
127
+ return result;
128
+ };
129
+ if (Array.isArray(schema.required) && schema.required.includes(name)) {
130
+ return remember(true);
131
+ }
132
+ const next = new Set([...seen, schema]);
133
+ const constraints = [];
134
+ if (schema.$ref !== undefined) {
135
+ constraints.push(requires(resolve(schema.$ref, true), name, next));
136
+ }
137
+ if (Array.isArray(schema.allOf)) {
138
+ constraints.push(...schema.allOf.map((item) => requires(item, name, next)));
139
+ }
140
+ for (const keyword of ['oneOf', 'anyOf']) {
141
+ if (Array.isArray(schema[keyword])) {
142
+ const alternatives = schema[keyword].map((item) => requires(item, name, next));
143
+ if (alternatives.every((value) => value === true)) {
144
+ constraints.push(true);
145
+ }
146
+ else if (alternatives.every((value) => value === false)) {
147
+ constraints.push(false);
148
+ }
149
+ else {
150
+ constraints.push(undefined);
151
+ }
152
+ }
153
+ }
154
+ if (constraints.includes(true)) {
155
+ return remember(true);
156
+ }
157
+ if (constraints.includes(undefined) ||
158
+ ['if', 'not', '$dynamicRef', 'const', 'enum', 'minProperties', 'dependentRequired', 'dependentSchemas'].some((key) => key in schema)) {
159
+ return remember(undefined);
160
+ }
161
+ return remember(false);
162
+ };
163
+ // An array wrapper name is not a property name: only arrays under
164
+ // properties can pass an inferred name to their inline item schemas.
165
+ const validateXmlNames = (schema, path, { inferredName, propertyName, dialect, ancestors = new Set(), baseChanged = false }) => {
166
+ if (!isObject(schema) || ancestors.has(schema) || (schema.$schema ?? dialect) !== undefined) {
167
+ return;
168
+ }
169
+ const changedBase = baseChanged || schema.$id !== undefined;
170
+ const context = [inferredName, propertyName, changedBase].join(':');
171
+ const completed = xmlCache.get(schema) ?? new Set();
172
+ if (completed.has(context)) {
173
+ return;
174
+ }
175
+ const xml = isObject(schema.xml) ? schema.xml : {};
176
+ const defaultNodeType = schema.$ref !== undefined || schema.$dynamicRef !== undefined || schema.type === 'array' ? 'none' : 'element';
177
+ const wrappedNodeType = xml.wrapped === true ? 'element' : defaultNodeType;
178
+ const nodeType = xml.nodeType ?? (xml.attribute === true ? 'attribute' : wrappedNodeType);
179
+ if ((nodeType === 'element' || nodeType === 'attribute') && !inferredName && xml.name === undefined) {
180
+ fail(path, 'An inline XML element needs an explicit xml.name.');
181
+ }
182
+ const childContext = { dialect, ancestors: new Set([...ancestors, schema]), baseChanged: changedBase };
183
+ if (!changedBase && typeof schema.$ref === 'string') {
184
+ const target = resolve(schema.$ref, true);
185
+ if (isObject(target)) {
186
+ const segments = parseJsonPointerSegments(decodeURIComponent(schema.$ref.slice(1)));
187
+ const componentRoot = segments.length === 3 && segments[0] === 'components' && segments[1] === 'schemas';
188
+ const fromProperty = propertySchemas.has(target);
189
+ validateXmlNames(target, schema.$ref, {
190
+ ...childContext,
191
+ inferredName: componentRoot || fromProperty,
192
+ propertyName: fromProperty,
193
+ });
194
+ }
195
+ }
196
+ // Composition branches are neither properties nor components, so they cannot inherit a name.
197
+ for (const keyword of ['allOf', 'anyOf', 'oneOf']) {
198
+ const branches = schema[keyword];
199
+ if (Array.isArray(branches)) {
200
+ branches.forEach((branch, index) => validateXmlNames(branch, path + '/' + keyword + '/' + index, {
201
+ ...childContext,
202
+ inferredName: false,
203
+ propertyName: false,
204
+ }));
205
+ }
206
+ }
207
+ validateXmlNames(schema.items, path + '/items', { ...childContext, inferredName: propertyName, propertyName });
208
+ if (Array.isArray(schema.prefixItems)) {
209
+ schema.prefixItems.forEach((item, index) => validateXmlNames(item, path + '/prefixItems/' + index, {
210
+ ...childContext,
211
+ inferredName: propertyName,
212
+ propertyName,
213
+ }));
214
+ }
215
+ if (isObject(schema.properties)) {
216
+ for (const [name, property] of Object.entries(schema.properties)) {
217
+ validateXmlNames(property, path + '/properties/' + escapeJsonPointer(name), {
218
+ ...childContext,
219
+ inferredName: true,
220
+ propertyName: true,
221
+ });
222
+ }
223
+ }
224
+ completed.add(context);
225
+ xmlCache.set(schema, completed);
226
+ };
227
+ const visit = (value, kind, path, dialect = document.jsonSchemaDialect, baseChanged = false) => {
228
+ if (!isObject(value)) {
229
+ return;
230
+ }
231
+ const schemaDialect = kind === 'schema' ? (value.$schema ?? dialect) : dialect;
232
+ const schemaBaseChanged = baseChanged || (kind === 'schema' && value.$id !== undefined);
233
+ const visitKey = `${kind}:${String(schemaDialect)}:${schemaBaseChanged}`;
234
+ const seen = visited.get(value) ?? new Set();
235
+ if (seen.has(visitKey)) {
236
+ return;
237
+ }
238
+ seen.add(visitKey);
239
+ visited.set(value, seen);
240
+ const child = (key, type) => visit(own(value, key), type, `${path}/${escapeJsonPointer(key)}`, schemaDialect, schemaBaseChanged);
241
+ const list = (key, type) => {
242
+ const items = own(value, key);
243
+ if (Array.isArray(items)) {
244
+ items.forEach((item, index) => visit(item, type, `${path}/${key}/${index}`, schemaDialect, schemaBaseChanged));
245
+ }
246
+ };
247
+ const map = (key, type) => {
248
+ const items = own(value, key);
249
+ if (isObject(items)) {
250
+ for (const [name, item] of Object.entries(items)) {
251
+ if (key === 'responses' && name.startsWith('x-')) {
252
+ continue;
253
+ }
254
+ if (kind === 'schema' && key === 'properties') {
255
+ markPropertySchema(item);
256
+ }
257
+ visit(item, type, `${path}/${key}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
258
+ }
259
+ }
260
+ };
261
+ if (kind === 'schema') {
262
+ // A pinned older or custom dialect still owns the meaning of its XML keywords.
263
+ if (schemaDialect !== undefined) {
264
+ return;
265
+ }
266
+ const xml = own(value, 'xml');
267
+ if (isObject(xml)) {
268
+ if (xml.wrapped === true && xml.attribute === true) {
269
+ fail(`${path}/xml`, 'wrapped and attribute cannot both be true.');
270
+ }
271
+ if (xml.wrapped === true || xml.attribute === true) {
272
+ xml.nodeType = xml.attribute === true ? 'attribute' : 'element';
273
+ delete xml.wrapped;
274
+ delete xml.attribute;
275
+ }
276
+ }
277
+ if (!schemaBaseChanged && value.$ref !== undefined) {
278
+ visit(resolve(value.$ref, true), 'schema', String(value.$ref), schemaDialect);
279
+ }
280
+ const discriminator = value.discriminator;
281
+ if (isObject(discriminator) &&
282
+ typeof discriminator.propertyName === 'string' &&
283
+ discriminator.defaultMapping === undefined &&
284
+ !schemaBaseChanged &&
285
+ requires(value, discriminator.propertyName) === false) {
286
+ fail(`${path}/discriminator`, 'An optional discriminating property needs an explicit defaultMapping.');
287
+ }
288
+ for (const key of schemaMaps) {
289
+ map(key, 'schema');
290
+ }
291
+ for (const key of schemaArrays) {
292
+ list(key, 'schema');
293
+ }
294
+ for (const key of schemaSingles) {
295
+ child(key, 'schema');
296
+ }
297
+ return;
298
+ }
299
+ // Reference targets outside components can still contain OpenAPI objects.
300
+ if (value.$ref !== undefined) {
301
+ visit(resolve(value.$ref), kind, String(value.$ref), schemaDialect);
302
+ }
303
+ switch (kind) {
304
+ case 'document': {
305
+ const paths = own(value, 'paths');
306
+ if (isObject(paths)) {
307
+ for (const [name, item] of Object.entries(paths)) {
308
+ if (!name.startsWith('/')) {
309
+ continue;
310
+ }
311
+ const location = `${path}/paths/${escapeJsonPointer(name)}`;
312
+ repeatedVariables(name, location);
313
+ visit(item, 'pathItem', location);
314
+ }
315
+ }
316
+ map('webhooks', 'pathItem');
317
+ list('servers', 'server');
318
+ const componentObjects = own(value, 'components');
319
+ if (isObject(componentObjects)) {
320
+ const components = {
321
+ schemas: 'schema',
322
+ parameters: 'parameter',
323
+ headers: 'header',
324
+ requestBodies: 'body',
325
+ responses: 'response',
326
+ callbacks: 'callback',
327
+ pathItems: 'pathItem',
328
+ };
329
+ for (const [key, type] of Object.entries(components)) {
330
+ const entries = own(componentObjects, key);
331
+ if (isObject(entries)) {
332
+ for (const [name, item] of Object.entries(entries)) {
333
+ visit(item, type, `${path}/components/${key}/${escapeJsonPointer(name)}`);
334
+ }
335
+ }
336
+ }
337
+ }
338
+ break;
339
+ }
340
+ case 'pathItem':
341
+ for (const method of ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace']) {
342
+ child(method, 'operation');
343
+ }
344
+ list('parameters', 'parameter');
345
+ list('servers', 'server');
346
+ break;
347
+ case 'operation':
348
+ if (Array.isArray(value.tags)) {
349
+ for (const tag of value.tags) {
350
+ if (typeof tag === 'string') {
351
+ operationTags.add(tag);
352
+ }
353
+ }
354
+ }
355
+ list('parameters', 'parameter');
356
+ list('servers', 'server');
357
+ child('requestBody', 'body');
358
+ map('responses', 'response');
359
+ map('callbacks', 'callback');
360
+ break;
361
+ case 'callback':
362
+ for (const [name, item] of Object.entries(value)) {
363
+ if (!name.startsWith('x-') && name !== '$ref') {
364
+ visit(item, 'pathItem', `${path}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
365
+ }
366
+ }
367
+ break;
368
+ case 'parameter':
369
+ // These settings were ignored in 3.1, but would become active in 3.2.
370
+ if (value.in === 'path' || value.in === 'cookie') {
371
+ delete value.allowReserved;
372
+ }
373
+ child('schema', 'schema');
374
+ map('content', 'media');
375
+ break;
376
+ case 'header':
377
+ child('schema', 'schema');
378
+ map('content', 'media');
379
+ break;
380
+ case 'response':
381
+ map('headers', 'header');
382
+ map('content', 'media');
383
+ break;
384
+ case 'body':
385
+ map('content', 'media');
386
+ break;
387
+ case 'media':
388
+ if (/\/(?:[^;]+\+)?xml(?:\s*;|$)/i.test(path.slice(path.lastIndexOf('/') + 1).replace(/~1/g, '/'))) {
389
+ xmlRoots.push({ schema: value.schema, path: `${path}/schema`, dialect: schemaDialect });
390
+ }
391
+ child('schema', 'schema');
392
+ map('encoding', 'encoding');
393
+ break;
394
+ case 'encoding':
395
+ map('headers', 'header');
396
+ break;
397
+ case 'server':
398
+ repeatedVariables(value.url, `${path}/url`);
399
+ break;
400
+ }
401
+ };
402
+ visit(document, 'document', '#');
403
+ // Resolve naming after traversal, so forward references have their structural context.
404
+ for (const { schema, path, dialect } of xmlRoots) {
405
+ validateXmlNames(schema, path, { inferredName: false, propertyName: false, dialect });
406
+ }
407
+ if (errors.length > 0) {
408
+ throw new UpgradeIncompatibilityError(errors);
409
+ }
410
+ return operationTags;
411
+ };
@@ -0,0 +1,7 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Add native navigation parents only when every group has an unambiguous mapping.
4
+ * Keep the extension to preserve renderer-specific ordering and visibility rules.
5
+ */
6
+ export declare const migrateTagGroups: (document: UnknownObject, operationTags: ReadonlySet<string>) => void;
7
+ //# sourceMappingURL=migrate-tag-groups.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate-tag-groups.d.ts","sourceRoot":"","sources":["../../src/3.1-to-3.2/migrate-tag-groups.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAExD;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,UAAU,aAAa,EAAE,eAAe,WAAW,CAAC,MAAM,CAAC,KAAG,IAiD9F,CAAA"}
@@ -0,0 +1,52 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ /**
3
+ * Add native navigation parents only when every group has an unambiguous mapping.
4
+ * Keep the extension to preserve renderer-specific ordering and visibility rules.
5
+ */
6
+ export const migrateTagGroups = (document, operationTags) => {
7
+ const groups = document['x-tagGroups'];
8
+ if (!Array.isArray(groups) || groups.length === 0) {
9
+ return;
10
+ }
11
+ if (document.tags !== undefined && !Array.isArray(document.tags)) {
12
+ return;
13
+ }
14
+ const tags = document.tags ?? [];
15
+ if (!tags.every((tag) => isObject(tag) && typeof tag.name === 'string')) {
16
+ return;
17
+ }
18
+ const existing = new Map(tags.map((tag) => [tag.name, tag]));
19
+ const parents = new Set();
20
+ const children = new Set();
21
+ for (const group of groups) {
22
+ if (!isObject(group) ||
23
+ typeof group.name !== 'string' ||
24
+ !group.name ||
25
+ !Array.isArray(group.tags) ||
26
+ !group.tags.every((name) => typeof name === 'string') ||
27
+ Object.keys(group).some((key) => key !== 'name' && key !== 'tags') ||
28
+ parents.has(group.name) ||
29
+ existing.has(group.name) ||
30
+ operationTags.has(group.name)) {
31
+ return;
32
+ }
33
+ parents.add(group.name);
34
+ for (const name of group.tags) {
35
+ if (children.has(name) || existing.get(name)?.parent !== undefined) {
36
+ return;
37
+ }
38
+ children.add(name);
39
+ }
40
+ }
41
+ if ([...parents].some((name) => children.has(name)) || existing.size !== tags.length) {
42
+ return;
43
+ }
44
+ const result = [];
45
+ for (const group of groups) {
46
+ result.push({ name: group.name, kind: 'nav' });
47
+ for (const name of group.tags) {
48
+ result.push({ ...(existing.get(name) ?? { name }), parent: group.name });
49
+ }
50
+ }
51
+ document.tags = [...result, ...tags.filter((tag) => !children.has(tag.name))];
52
+ };
@@ -1,8 +1,12 @@
1
1
  import type { UnknownObject } from '@scalar/types/utils';
2
+ /** Apply the final migration to a document already owned by the upgrade pipeline. */
3
+ export declare const migrateThreeOneToThreeTwo: (document: UnknownObject) => UnknownObject;
2
4
  /**
3
- * Upgrade OpenAPI 3.1 to 3.2
5
+ * Upgrade OpenAPI 3.1.x to 3.2 without changing the input.
4
6
  *
5
- * @see https://github.com/OAI/OpenAPI-Specification/compare/main...v3.2-dev
7
+ * Collects incompatibilities requiring an author's decision in an AggregateError
8
+ * with a JSON pointer for each issue. External references and custom schema dialects are not validated.
9
+ * Malformed 3.1 versions, object cycles, and excessive alias expansion throw ordinary Errors.
6
10
  */
7
- export declare function upgradeFromThreeOneToThreeTwo(originalDocument: UnknownObject): UnknownObject;
11
+ export declare const upgradeFromThreeOneToThreeTwo: (originalDocument: UnknownObject) => UnknownObject;
8
12
  //# sourceMappingURL=upgrade-from-three-one-to-three-two.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade-from-three-one-to-three-two.d.ts","sourceRoot":"","sources":["../../src/3.1-to-3.2/upgrade-from-three-one-to-three-two.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAiGxD;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,gBAAgB,EAAE,aAAa,iBAuB5E"}
1
+ {"version":3,"file":"upgrade-from-three-one-to-three-two.d.ts","sourceRoot":"","sources":["../../src/3.1-to-3.2/upgrade-from-three-one-to-three-two.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAsBxD,qFAAqF;AACrF,eAAO,MAAM,yBAAyB,GAAI,UAAU,aAAa,KAAG,aAQnE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,GAAI,kBAAkB,aAAa,KAAG,aAK/E,CAAA"}
@@ -1,107 +1,40 @@
1
- /**
2
- * Recursively migrate XML object properties from 3.1 to 3.2 format
3
- */
4
- function migrateXmlObjects(obj) {
5
- if (obj === null || typeof obj !== 'object') {
6
- return;
7
- }
8
- // Handle arrays
9
- if (Array.isArray(obj)) {
10
- for (const item of obj) {
11
- migrateXmlObjects(item);
12
- }
13
- return;
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ import { cloneDocument } from '../helpers/clone-document.js';
3
+ import { migrateObjects } from './migrate-objects.js';
4
+ import { migrateTagGroups } from './migrate-tag-groups.js';
5
+ /** Reject malformed 3.1 declarations instead of silently leaving a requested upgrade incomplete. */
6
+ const isThreeOneDocument = (document) => {
7
+ if (!isObject(document) || typeof document.openapi !== 'string') {
8
+ return false;
14
9
  }
15
- // Handle xml property migration
16
- if (obj.xml && typeof obj.xml === 'object') {
17
- if (obj.xml.wrapped === true && obj.xml.attribute === true) {
18
- throw new Error('Invalid XML configuration: wrapped and attribute cannot be true at the same time.');
19
- }
20
- // Migrate wrapped: true to nodeType: 'element'
21
- if (obj.xml.wrapped === true) {
22
- delete obj.xml.wrapped;
23
- obj.xml.nodeType = 'element';
24
- }
25
- // Migrate attribute: true to nodeType: 'attribute'
26
- if (obj.xml.attribute === true) {
27
- delete obj.xml.attribute;
28
- obj.xml.nodeType = 'attribute';
29
- }
10
+ if (/^3\.1\.\d+$/.test(document.openapi)) {
11
+ return true;
30
12
  }
31
- // Recursively process all object properties
32
- for (const key in obj) {
33
- if (Object.hasOwn(obj, key)) {
34
- migrateXmlObjects(obj[key]);
35
- }
13
+ if (/^3\.1(?:\D|$)/.test(document.openapi)) {
14
+ throw new Error(`Cannot upgrade to OpenAPI 3.2: invalid OpenAPI version "${document.openapi}". Expected 3.1.x with a numeric patch version.`);
36
15
  }
37
- }
38
- /**
39
- * Migrate x-tagGroups to kind property on tags
40
- */
41
- function migrateTagGroups(document) {
42
- if (document['x-tagGroups'] && Array.isArray(document['x-tagGroups'])) {
43
- const tagGroups = document['x-tagGroups'];
44
- // Ensure tags array exists
45
- if (!document.tags) {
46
- document.tags = [];
47
- }
48
- // Create a map of tag names to their group information
49
- const tagGroupMap = new Map();
50
- for (const group of tagGroups) {
51
- for (const tagName of group.tags) {
52
- tagGroupMap.set(tagName, group.name);
53
- }
54
- }
55
- // Update existing tags with kind property based on group name
56
- if (Array.isArray(document.tags)) {
57
- for (const tag of document.tags) {
58
- if (typeof tag === 'object' && tag !== null && 'name' in tag && typeof tag.name === 'string') {
59
- const groupName = tagGroupMap.get(tag.name);
60
- if (groupName) {
61
- // Map group names to kind values
62
- // This is a simplified mapping - in practice, you might want more sophisticated logic
63
- if (groupName.toLowerCase().includes('nav') || groupName.toLowerCase().includes('navigation')) {
64
- tag.kind = 'nav';
65
- }
66
- else if (groupName.toLowerCase().includes('audience')) {
67
- tag.kind = 'audience';
68
- }
69
- else if (groupName.toLowerCase().includes('badge')) {
70
- tag.kind = 'badge';
71
- }
72
- else {
73
- // Default to nav for unknown group types
74
- tag.kind = 'nav';
75
- }
76
- }
77
- }
78
- }
79
- }
80
- // Remove x-tagGroups
81
- delete document['x-tagGroups'];
16
+ return false;
17
+ };
18
+ /** Apply the final migration to a document already owned by the upgrade pipeline. */
19
+ export const migrateThreeOneToThreeTwo = (document) => {
20
+ if (!isThreeOneDocument(document)) {
21
+ return document;
82
22
  }
83
- }
23
+ const operationTags = migrateObjects(document);
24
+ migrateTagGroups(document, operationTags);
25
+ document.openapi = '3.2.0';
26
+ return document;
27
+ };
84
28
  /**
85
- * Upgrade OpenAPI 3.1 to 3.2
29
+ * Upgrade OpenAPI 3.1.x to 3.2 without changing the input.
86
30
  *
87
- * @see https://github.com/OAI/OpenAPI-Specification/compare/main...v3.2-dev
31
+ * Collects incompatibilities requiring an author's decision in an AggregateError
32
+ * with a JSON pointer for each issue. External references and custom schema dialects are not validated.
33
+ * Malformed 3.1 versions, object cycles, and excessive alias expansion throw ordinary Errors.
88
34
  */
89
- export function upgradeFromThreeOneToThreeTwo(originalDocument) {
90
- const document = originalDocument;
91
- // Version
92
- if (document !== null &&
93
- typeof document === 'object' &&
94
- typeof document.openapi === 'string' &&
95
- document.openapi?.startsWith('3.1')) {
96
- document.openapi = '3.2.0';
35
+ export const upgradeFromThreeOneToThreeTwo = (originalDocument) => {
36
+ if (!isThreeOneDocument(originalDocument)) {
37
+ return originalDocument;
97
38
  }
98
- else {
99
- // Skip if it's something else than 3.1.x
100
- return document;
101
- }
102
- // Migrate x-tagGroups to kind property
103
- migrateTagGroups(document);
104
- // Migrate XML object properties
105
- migrateXmlObjects(document);
106
- return document;
107
- }
39
+ return migrateThreeOneToThreeTwo(cloneDocument(originalDocument));
40
+ };
@@ -0,0 +1,7 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Clone each occurrence independently so YAML aliases cannot couple schema
4
+ * transformations to literal examples. Undefined values are preserved.
5
+ */
6
+ export declare const cloneDocument: (document: UnknownObject) => UnknownObject;
7
+ //# sourceMappingURL=clone-document.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clone-document.d.ts","sourceRoot":"","sources":["../../src/helpers/clone-document.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAOxD;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,UAAU,aAAa,KAAG,aA0CvD,CAAA"}
@@ -0,0 +1,48 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ /** Allow small shared values while capping amplified allocation, not ordinary document size. */
3
+ const ALIAS_EXPANSION_ENTRY_FLOOR = 100_000;
4
+ /** More than ten copies per unique source entry is treated as disproportionate alias expansion. */
5
+ const MAX_ALIAS_EXPANSION_RATIO = 10;
6
+ /**
7
+ * Clone each occurrence independently so YAML aliases cannot couple schema
8
+ * transformations to literal examples. Undefined values are preserved.
9
+ */
10
+ export const cloneDocument = (document) => {
11
+ const ancestors = new WeakSet();
12
+ const expansion = { sourceEntries: 0, copiedEntries: 0, sizes: new Map() };
13
+ const clone = (value) => {
14
+ if (value === null ||
15
+ typeof value === 'string' ||
16
+ typeof value === 'number' ||
17
+ typeof value === 'boolean' ||
18
+ typeof value === 'undefined') {
19
+ return value;
20
+ }
21
+ if (!Array.isArray(value) && !isObject(value)) {
22
+ return structuredClone(value);
23
+ }
24
+ if (ancestors.has(value)) {
25
+ throw new Error('Cannot upgrade to OpenAPI 3.2: cyclic objects cannot be represented in JSON. Use $ref instead.');
26
+ }
27
+ // These are allocation policy limits, not OpenAPI validity constraints: allow
28
+ // 100,000 copied entries unconditionally, then require more than 10x growth
29
+ // before rejecting. Large documents without alias amplification remain valid.
30
+ const size = expansion.sizes.get(value) ?? 1 + (Array.isArray(value) ? value.length : Object.keys(value).length);
31
+ if (!expansion.sizes.has(value)) {
32
+ expansion.sizes.set(value, size);
33
+ expansion.sourceEntries += size;
34
+ }
35
+ expansion.copiedEntries += size;
36
+ if (expansion.copiedEntries > ALIAS_EXPANSION_ENTRY_FLOOR &&
37
+ expansion.copiedEntries > expansion.sourceEntries * MAX_ALIAS_EXPANSION_RATIO) {
38
+ throw new Error('Cannot upgrade to OpenAPI 3.2: excessive YAML alias expansion. Use $ref for shared schemas.');
39
+ }
40
+ ancestors.add(value);
41
+ const result = Array.isArray(value)
42
+ ? value.map(clone)
43
+ : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
44
+ ancestors.delete(value);
45
+ return result;
46
+ };
47
+ return clone(document);
48
+ };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export { upgrade } from './upgrade.js';
1
+ export { type UpgradeOptions, type UpgradeResult, upgrade } from './upgrade.js';
2
+ export { UpgradeIncompatibilityError } from './upgrade-incompatibility-error.js';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,aAAa,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAC5E,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAA"}
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export { upgrade } from './upgrade.js';
2
+ export { UpgradeIncompatibilityError } from './upgrade-incompatibility-error.js';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Compatibility diagnostics that prevent a semantics-preserving OpenAPI 3.2 upgrade.
3
+ * Callers may retain the original version; malformed input and clone safety errors
4
+ * use ordinary Errors and must not be treated as a compatibility fallback.
5
+ */
6
+ export declare class UpgradeIncompatibilityError extends AggregateError {
7
+ errors: Error[];
8
+ constructor(errors: Error[]);
9
+ }
10
+ //# sourceMappingURL=upgrade-incompatibility-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade-incompatibility-error.d.ts","sourceRoot":"","sources":["../src/upgrade-incompatibility-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,2BAA4B,SAAQ,cAAc;IACpD,MAAM,EAAE,KAAK,EAAE,CAAA;gBAEZ,MAAM,EAAE,KAAK,EAAE;CAK5B"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Compatibility diagnostics that prevent a semantics-preserving OpenAPI 3.2 upgrade.
3
+ * Callers may retain the original version; malformed input and clone safety errors
4
+ * use ordinary Errors and must not be treated as a compatibility fallback.
5
+ */
6
+ export class UpgradeIncompatibilityError extends AggregateError {
7
+ errors;
8
+ constructor(errors) {
9
+ super(errors, errors.map((error) => error.message).join('\n'));
10
+ this.errors = errors;
11
+ this.name = 'UpgradeIncompatibilityError';
12
+ }
13
+ }
package/dist/upgrade.d.ts CHANGED
@@ -1,9 +1,29 @@
1
1
  import type { OpenAPIV3, OpenAPIV3_1, OpenAPIV3_2 } from '@scalar/openapi-types';
2
2
  import type { UnknownObject } from '@scalar/types/utils';
3
+ /** Control how compatibility issues in the OpenAPI 3.2 migration are reported. */
4
+ export type UpgradeOptions = {
5
+ /** Defaults to throwing. Collect mode retains OpenAPI 3.1 when migration is incompatible. */
6
+ onIncompatible: 'throw' | 'collect';
7
+ };
8
+ /** A complete document and the compatibility issues that prevented upgrading it to OpenAPI 3.2. */
9
+ export type UpgradeResult = {
10
+ /** OpenAPI 3.2 on success, or the complete OpenAPI 3.1 fallback when diagnostics are present. */
11
+ document: OpenAPIV3_1.Document | OpenAPIV3_2.Document;
12
+ /** All detected compatibility errors, including their JSON pointers; empty on success. */
13
+ diagnostics: Error[];
14
+ };
3
15
  /**
4
- * Upgrade OpenAPI documents from Swagger 2.0 or OpenAPI 3.0 to the specified target version
16
+ * Upgrade a Swagger 2.0 or OpenAPI description to the specified target version.
17
+ * Targeting 3.2 is strict by default. Collect mode returns compatibility diagnostics
18
+ * with a complete 3.1 fallback instead of throwing for migration incompatibilities.
5
19
  */
6
20
  export declare function upgrade(value: UnknownObject, targetVersion: '3.0'): OpenAPIV3.Document;
7
21
  export declare function upgrade(value: UnknownObject, targetVersion: '3.1'): OpenAPIV3_1.Document;
8
- export declare function upgrade(value: UnknownObject, targetVersion: '3.2'): OpenAPIV3_2.Document;
22
+ export declare function upgrade(value: UnknownObject, targetVersion: '3.2', options?: {
23
+ onIncompatible: 'throw';
24
+ }): OpenAPIV3_2.Document;
25
+ export declare function upgrade(value: UnknownObject, targetVersion: '3.2', options: {
26
+ onIncompatible: 'collect';
27
+ }): UpgradeResult;
28
+ export declare function upgrade(value: UnknownObject, targetVersion: '3.2', options: UpgradeOptions): OpenAPIV3_2.Document | UpgradeResult;
9
29
  //# sourceMappingURL=upgrade.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../src/upgrade.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAOxD;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,GAAG,SAAS,CAAC,QAAQ,CAAA;AACvF,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAA;AACzF,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAA"}
1
+ {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../src/upgrade.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AASxD,kFAAkF;AAClF,MAAM,MAAM,cAAc,GAAG;IAC3B,6FAA6F;IAC7F,cAAc,EAAE,OAAO,GAAG,SAAS,CAAA;CACpC,CAAA;AAED,mGAAmG;AACnG,MAAM,MAAM,aAAa,GAAG;IAC1B,iGAAiG;IACjG,QAAQ,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAA;IACrD,0FAA0F;IAC1F,WAAW,EAAE,KAAK,EAAE,CAAA;CACrB,CAAA;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,GAAG,SAAS,CAAC,QAAQ,CAAA;AACvF,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAA;AACzF,wBAAgB,OAAO,CACrB,KAAK,EAAE,aAAa,EACpB,aAAa,EAAE,KAAK,EACpB,OAAO,CAAC,EAAE;IAAE,cAAc,EAAE,OAAO,CAAA;CAAE,GACpC,WAAW,CAAC,QAAQ,CAAA;AACvB,wBAAgB,OAAO,CACrB,KAAK,EAAE,aAAa,EACpB,aAAa,EAAE,KAAK,EACpB,OAAO,EAAE;IAAE,cAAc,EAAE,SAAS,CAAA;CAAE,GACrC,aAAa,CAAA;AAChB,wBAAgB,OAAO,CACrB,KAAK,EAAE,aAAa,EACpB,aAAa,EAAE,KAAK,EACpB,OAAO,EAAE,cAAc,GACtB,WAAW,CAAC,QAAQ,GAAG,aAAa,CAAA"}
package/dist/upgrade.js CHANGED
@@ -1,21 +1,31 @@
1
- import { upgradeFromThreeOneToThreeTwo } from './3.1-to-3.2/index.js';
1
+ import { migrateThreeOneToThreeTwo } from './3.1-to-3.2/upgrade-from-three-one-to-three-two.js';
2
2
  import { upgradeFromTwoToThree } from './2.0-to-3.0/index.js';
3
3
  import { upgradeFromThreeToThreeOne } from './3.0-to-3.1/index.js';
4
- export function upgrade(value, targetVersion) {
5
- // Swagger 2.0 -> OpenAPI 3.0
6
- const openapi30 = upgradeFromTwoToThree(value);
7
- if (targetVersion === '3.0') {
8
- return openapi30;
9
- }
10
- // OpenAPI 3.0 -> OpenAPI 3.1
11
- const openapi31 = upgradeFromThreeToThreeOne(openapi30);
12
- if (targetVersion === '3.1') {
13
- return openapi31;
14
- }
15
- // OpenAPI 3.1 -> OpenAPI 3.2
16
- const openapi32 = upgradeFromThreeOneToThreeTwo(openapi31);
4
+ import { cloneDocument } from './helpers/clone-document.js';
5
+ import { UpgradeIncompatibilityError } from './upgrade-incompatibility-error.js';
6
+ export function upgrade(value, targetVersion, options) {
17
7
  if (targetVersion === '3.2') {
18
- return openapi32;
8
+ // Every step in the 3.2 pipeline owns the same clone, including earlier converters.
9
+ const input = cloneDocument(value);
10
+ const openapi30 = upgradeFromTwoToThree(input);
11
+ const openapi31 = upgradeFromThreeToThreeOne(openapi30);
12
+ try {
13
+ const document = migrateThreeOneToThreeTwo(openapi31);
14
+ return options?.onIncompatible === 'collect' ? { document, diagnostics: [] } : document;
15
+ }
16
+ catch (error) {
17
+ if (options?.onIncompatible !== 'collect' || !(error instanceof UpgradeIncompatibilityError)) {
18
+ throw error;
19
+ }
20
+ // The failed migration may have changed its private copy. Rebuild from the
21
+ // original input so the fallback contains no partial 3.2 transformations.
22
+ return {
23
+ document: upgrade(cloneDocument(value), '3.1'),
24
+ diagnostics: error.errors,
25
+ };
26
+ }
19
27
  }
20
- return openapi32;
28
+ // Preserve the earlier targets without entering the 3.2 migration.
29
+ const openapi30 = upgradeFromTwoToThree(value);
30
+ return targetVersion === '3.0' ? openapi30 : upgradeFromThreeToThreeOne(openapi30);
21
31
  }
package/package.json CHANGED
@@ -20,7 +20,7 @@
20
20
  "openapi 3.0",
21
21
  "openapi 3.1"
22
22
  ],
23
- "version": "0.2.17",
23
+ "version": "0.3.1",
24
24
  "engines": {
25
25
  "node": ">=22"
26
26
  },
@@ -71,11 +71,11 @@
71
71
  },
72
72
  "sideEffects": false,
73
73
  "dependencies": {
74
- "@scalar/helpers": "0.12.0",
75
- "@scalar/openapi-types": "0.9.6"
74
+ "@scalar/helpers": "0.14.0",
75
+ "@scalar/openapi-types": "0.9.7"
76
76
  },
77
77
  "devDependencies": {
78
- "@scalar/types": "0.20.0",
78
+ "@scalar/types": "0.22.0",
79
79
  "vite": "8.1.5"
80
80
  },
81
81
  "scripts": {