Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/differs.core/src/classifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ export const CLASSIFICATION_SETS = {
* ```
*/
export function classify(change: RawChange): ChangeSeverity {
if (change.enumConstraintEquivalent) return 'non-breaking';

const { type } = change;

// Check each category in order of specificity
Expand Down
12 changes: 4 additions & 8 deletions packages/differs.core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,7 @@ export { CHANGE_TYPE_SEVERITY } from '@contractual/types';
* JSON Schema type values
*/
export type JSONSchemaType =
| 'string'
| 'number'
| 'integer'
| 'boolean'
| 'object'
| 'array'
| 'null';
'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null';

/**
* Normalized type representation (always an array for comparison)
Expand Down Expand Up @@ -311,6 +305,8 @@ export function deepEqual(a: unknown, b: unknown): boolean {

if (a === null || b === null) return a === b;

if (Array.isArray(a) !== Array.isArray(b)) return false;

if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return false;
return a.every((val, idx) => deepEqual(val, b[idx]));
Expand All @@ -322,7 +318,7 @@ export function deepEqual(a: unknown, b: unknown): boolean {
const aKeys = Object.keys(aObj);
const bKeys = Object.keys(bObj);
if (aKeys.length !== bKeys.length) return false;
return aKeys.every((key) => deepEqual(aObj[key], bObj[key]));
return aKeys.every((key) => Object.hasOwn(bObj, key) && deepEqual(aObj[key], bObj[key]));
}

return false;
Expand Down
21 changes: 18 additions & 3 deletions packages/differs.core/src/walker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,6 @@ function compareEnum(
oldValue: undefined,
newValue: newEnum,
});
return changes;
}

// Enum removed
Expand All @@ -401,7 +400,6 @@ function compareEnum(
oldValue: oldEnum,
newValue: undefined,
});
return changes;
}

// Both have enums - compare values
Expand Down Expand Up @@ -459,7 +457,24 @@ function compareEnum(
}
}

return changes;
// Prove equivalence where both schemas are available, rather than pairing
// unrelated raw changes later by their potentially shared display paths.
const constToEnum =
oldEnum === undefined &&
oldSchema.const !== undefined &&
newSchema.const === undefined &&
newEnum?.length === 1 &&
deepEqual(oldSchema.const, newEnum[0]);
const enumToConst =
newEnum === undefined &&
newSchema.const !== undefined &&
oldSchema.const === undefined &&
oldEnum?.length === 1 &&
deepEqual(oldEnum[0], newSchema.const);

return constToEnum || enumToConst
? changes.map((change) => ({ ...change, enumConstraintEquivalent: true }))
: changes;
}

/**
Expand Down
256 changes: 256 additions & 0 deletions packages/differs.openapi/src/differ.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, expect, test } from 'vitest';
import { assembleResult, deepEqual, walk } from '@contractual/differs.core';
import { diffOpenApiObjects } from './differ.js';
import { diffStructural } from './structural.js';

Expand Down Expand Up @@ -183,3 +184,258 @@ describe('OpenAPI enum compatibility direction', () => {
});
});
});

describe('OpenAPI enum constraint interactions', () => {
test.each(['request', 'response'] as const)(
'%s const removal is retained when an enum is added',
(direction) => {
const oldSpec = openApiSpec(direction, false, { const: 'a' });
const newSpec = openApiSpec(direction, false, { enum: ['a', 'b'] });
const rawChanges = diffStructural(oldSpec, newSpec);
expect(rawChanges).toEqual([
expect.objectContaining({ type: 'enum-added', newValue: ['a', 'b'] }),
expect.objectContaining({
type: 'enum-removed',
oldValue: 'a',
path: expect.stringMatching(/\/const$/),
}),
]);
const result = diffOpenApiObjects(oldSpec, newSpec);
expect(result.changes).toContainEqual(
expect.objectContaining({
category: direction === 'response' ? 'enum-removed' : 'enum-added',
severity: 'breaking',
})
);
expect(result.suggestedBump).toBe('major');
}
);

test('enum removal does not hide a simultaneous const replacement', () => {
const result = diffOpenApiObjects(
openApiSpec('response', false, { enum: ['a', 'b'], const: 'a' }),
openApiSpec('response', false, { const: 'c' })
);
expect(result.changes).toEqual([
expect.objectContaining({ category: 'enum-removed', severity: 'breaking' }),
expect.objectContaining({
category: 'enum-value-removed',
oldValue: 'a',
newValue: 'c',
severity: 'breaking',
}),
]);
expect(result.suggestedBump).toBe('major');
});

test.each(['request', 'response'] as const)(
'%s enum changes inside overlapping oneOf branches require a major bump',
(direction) => {
const before = {
oneOf: [
{ type: 'string', enum: ['a', 'b'] },
{ type: 'string', enum: ['b'] },
],
};
const after = {
oneOf: [
{ type: 'string', enum: ['a'] },
{ type: 'string', enum: ['b'] },
],
};
for (const [oldSchema, newSchema] of [
[before, after],
[after, before],
]) {
const result = diffOpenApiObjects(
openApiSpec(direction, false, oldSchema),
openApiSpec(direction, false, newSchema)
);
expect(result.changes).toEqual([
expect.objectContaining({
severity: 'breaking',
path: expect.stringContaining('/oneOf/0/enum'),
}),
]);
expect(result.suggestedBump).toBe('major');
}
}
);
});

test('enum removal retains a simultaneous const addition for input compatibility', () => {
const changes = walk({ type: 'string', enum: ['a', 'b'] }, { type: 'string', const: 'a' });

expect(changes).toEqual([
{ path: '/enum', type: 'enum-removed', oldValue: ['a', 'b'], newValue: undefined },
{ path: '/const', type: 'enum-added', oldValue: undefined, newValue: 'a' },
]);
expect(assembleResult(changes, { type: 'string', const: 'a' }).suggestedBump).toBe('major');
});

describe('equivalent singleton enum and const substitutions', () => {
test.each(['request', 'response'] as const)(
'%s substitutions preserve the value set',
(direction) => {
for (const value of ['a', null, { nested: ['a'] }]) {
const schemaType =
value === null ? 'null' : typeof value === 'object' ? 'object' : 'string';
const schemas = [
{ type: schemaType, enum: [value] },
{ type: schemaType, const: value },
];
for (const [oldSchema, newSchema] of [schemas, [...schemas].reverse()]) {
const oldSpec = openApiSpec(direction, false, oldSchema);
const newSpec = openApiSpec(direction, false, newSchema);
expect(diffStructural(oldSpec, newSpec)).toHaveLength(2);
const result = diffOpenApiObjects(oldSpec, newSpec);
expect(result.changes).toHaveLength(2);
expect(result.changes.every((change) => change.severity === 'non-breaking')).toBe(true);
expect(result.suggestedBump).toBe('minor');
expect(assembleResult(walk(oldSchema, newSchema), newSchema).suggestedBump).toBe('minor');
}
}
}
);

test('equivalent substitutions remain compatible inside oneOf', () => {
const before = { oneOf: [{ const: 'a' }, { const: 'b' }] };
const after = { oneOf: [{ enum: ['a'] }, { const: 'b' }] };
for (const direction of ['request', 'response'] as const) {
const result = diffOpenApiObjects(
openApiSpec(direction, false, before),
openApiSpec(direction, false, after)
);
expect(result.changes).toHaveLength(2);
expect(result.changes.every((change) => change.severity === 'non-breaking')).toBe(true);
expect(result.suggestedBump).toBe('minor');
}
});

test('different singleton values still require a major bump', () => {
for (const [oldSchema, newSchema] of [
[{ const: 'a' }, { enum: ['b'] }],
[{ enum: ['a'] }, { const: 'b' }],
]) {
for (const direction of ['request', 'response'] as const) {
expect(
diffOpenApiObjects(
openApiSpec(direction, false, oldSchema),
openApiSpec(direction, false, newSchema)
).suggestedBump
).toBe('major');
}
expect(assembleResult(walk(oldSchema, newSchema), newSchema).suggestedBump).toBe('major');
}
});
});

test('parameter names cannot imitate oneOf schema paths', () => {
function spec(values: string[]) {
return {
openapi: '3.1.0',
info: { title: 'Parameters', version: '1.0.0' },
paths: {
'/example': {
get: {
parameters: [
{ in: 'query', name: 'x/oneOf/0/x~y', schema: { type: 'string', enum: values } },
],
responses: { 200: { description: 'OK' } },
},
},
},
};
}
const result = diffOpenApiObjects(spec(['a']), spec(['a', 'b']));
expect(result.changes).toEqual([
expect.objectContaining({
category: 'enum-value-added',
severity: 'non-breaking',
path: '/paths/~1example/get/parameters/x~1oneOf~10~1x~0y/schema/enum',
}),
]);
expect(result.suggestedBump).toBe('minor');
});

test('same-name parameters do not share equivalence evidence', () => {
function spec(querySchema: Record<string, unknown>, headerSchema: Record<string, unknown>) {
return {
openapi: '3.1.0',
info: { title: 'Parameters', version: '1.0.0' },
paths: {
'/example': {
get: {
parameters: [
{ in: 'query', name: 'x', schema: querySchema },
{ in: 'header', name: 'x', schema: headerSchema },
],
responses: { 200: { description: 'OK' } },
},
},
},
};
}
const result = diffOpenApiObjects(spec({ enum: ['a'] }, {}), spec({}, { const: 'a' }));
expect(result.changes).toContainEqual(
expect.objectContaining({ category: 'enum-added', severity: 'breaking' })
);
expect(result.suggestedBump).toBe('major');
});

test('object const equivalence ignores key order', () => {
const before = { const: { a: 1, b: 2 } };
const after = { enum: [{ b: 2, a: 1 }] };
expect(assembleResult(walk(before, after), after).suggestedBump).toBe('minor');
});

test('coexisting enum and const constraints are not treated as substitutions', () => {
const before = { enum: ['a'], const: 'b' };
const after = { enum: ['a'] };
for (const change of walk(before, after)) expect(change.enumConstraintEquivalent).toBeUndefined();
expect(
diffOpenApiObjects(
openApiSpec('response', false, before),
openApiSpec('response', false, after)
).suggestedBump
).toBe('major');
});

test('arrays and objects with numeric keys are different enum values', () => {
const before = { const: ['a'] };
const after = { enum: [{ 0: 'a' }] };
const changes = walk(before, after);
expect(changes.every((change) => change.enumConstraintEquivalent === undefined)).toBe(true);
expect(assembleResult(changes, after).suggestedBump).toBe('major');
});

test('JSON object equality requires matching own keys, including __proto__', () => {
const ownPrototypeKey = JSON.parse('{"__proto__":{}}');
const differentKey = JSON.parse('{"different":"value"}');
for (const [left, right] of [
[ownPrototypeKey, differentKey],
[differentKey, ownPrototypeKey],
]) {
expect(deepEqual(left, right)).toBe(false);
for (const [before, after] of [
[{ const: left }, { enum: [right] }],
[{ enum: [left] }, { const: right }],
]) {
const changes = walk(before, after);
expect(changes.every((change) => change.enumConstraintEquivalent === undefined)).toBe(true);
expect(assembleResult(changes, after).suggestedBump).toBe('major');
}
}

const sameLeft = JSON.parse('{"__proto__":{},"nested":{"a":1,"b":[2]}}');
const sameRight = JSON.parse('{"nested":{"b":[2],"a":1},"__proto__":{}}');
for (const [left, right] of [
[sameLeft, sameRight],
[sameRight, sameLeft],
]) {
expect(deepEqual(left, right)).toBe(true);
expect(
assembleResult(walk({ const: left }, { enum: [right] }), { enum: [right] }).suggestedBump
).toBe('minor');
}
});
9 changes: 9 additions & 0 deletions packages/differs.openapi/src/differ.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ export function diffOpenApiObjects(
}

function classifyOpenApiChange(change: RawChange, newSpec: unknown): ChangeSeverity {
if (change.enumConstraintEquivalent) return 'non-breaking';

// oneOf accepts exactly one matching branch. Either narrowing or widening
// a branch can invalidate old inputs or introduce outputs old clients reject.
// Without proving branch disjointness, treat enum changes conservatively.
if (change.type.startsWith('enum-') && /\/oneOf\/\d+\//.test(change.path)) {
return 'breaking';
}

if (change.schemaDirection === 'output') {
// Responses must remain valid against the schema known to existing clients.
// A const replacement is disjoint, rather than a narrowing: the walker
Expand Down
Loading
Loading