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
12 changes: 9 additions & 3 deletions src/generateDiff.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { compare } from 'fast-json-patch';

import { formatDiffOutput } from './helpers/DiffHelpers';
import {
formatDiffOutput,
removeCircularReferences,
} from './helpers/DiffHelpers';
import { DiffOutput } from './types';

/**
Expand All @@ -15,6 +18,9 @@ export default function generateDiff(
firstDocument: any,
secondDocument: any
): DiffOutput[] {
const diffOutput = compare(firstDocument, secondDocument);
return formatDiffOutput(diffOutput, firstDocument);
// resolved `$ref`s make recursive schemas circular, which `compare` can't clone
const first = removeCircularReferences(firstDocument);
const second = removeCircularReferences(secondDocument);
const diffOutput = compare(first, second);
return formatDiffOutput(diffOutput, first);
}
44 changes: 44 additions & 0 deletions src/helpers/DiffHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,47 @@ export function incompatibleDocuments(
}
return false;
}

/**
* Copies a document, replacing each reference back to an ancestor (as in a
* recursive schema once `$ref`s are resolved) with a marker naming that
* ancestor's JSON pointer. Shared, non-recursive references are copied as is.
* Naming the ancestor keeps a recursive reference that is redirected elsewhere
* visible in the diff.
* @param value The document, or a part of it
* @param {String} path The JSON pointer of `value`
* @param ancestors The objects being copied above `value`, with their pointers
* @returns A copy of `value` without circular references
*
* @private
*/
export function removeCircularReferences(
value: any,
path = '',
ancestors = new Map<any, string>()
): any {
if (typeof value !== 'object' || value === null) {
return value;
}
const ancestorPath = ancestors.get(value);
if (ancestorPath !== undefined) {
return `[Circular ${ancestorPath || '/'}]`;
}
ancestors.set(value, path);
const copy = Array.isArray(value)
? value.map((item, index) =>
removeCircularReferences(item, `${path}/${index}`, ancestors)
)
: Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
removeCircularReferences(
item,
`${path}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`,
ancestors
),
])
);
ancestors.delete(value);
return copy;
}
26 changes: 26 additions & 0 deletions test/generateDiff.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,30 @@ describe('Diff', () => {
)
).toStrictEqual(diffOutput);
});

test('Check diff output with circular references through parser', async () => {
const specDocument = readFileSync(
resolve('./test/spec/asyncapi-v3-circular.yml'),
'utf-8'
);
const first = await parser.parse(specDocument);
const second = await parser.parse(
specDocument.replace('type: string', 'type: number')
);
expect(
generateDiff(first.document?.json(), first.document?.json())
).toStrictEqual([]);
expect(
generateDiff(first.document?.json(), second.document?.json())
).toEqual(
expect.arrayContaining([
{
action: 'edit',
path: '/channels/entities/messages/entityCreated/payload/properties/filters/items/anyOf/1/type',
before: 'string',
after: 'number',
},
])
);
});
});
36 changes: 36 additions & 0 deletions test/helpers/DiffHelpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Operation } from 'fast-json-patch';
import {
formatAction,
getBeforeValue,
removeCircularReferences,
setIndex,
formatDiffOutput,
getDocumentMajorVersion,
Expand Down Expand Up @@ -92,3 +93,38 @@ describe('between different asyncapi version', () => {
expect(incompatibleDocuments({asyncapi: '3.0.0'}, {asyncapi: '3.0.0'})).toBeFalsy();
});
});

describe('removeCircularReferences', () => {
test('replaces references back to an ancestor and keeps shared ones', () => {
const shared = { type: 'string' };
const node: any = { a: shared, b: shared };
node.items = [node];
expect(removeCircularReferences(node)).toStrictEqual({
a: { type: 'string' },
b: { type: 'string' },
items: ['[Circular /]'],
});
});

test('names the ancestor, so redirecting a recursive reference is a change', () => {
const a: any = {};
const b: any = {};
a.child = b;
b.child = a;
const toA = removeCircularReferences(a);
b.child = b;
expect(toA).toStrictEqual({ child: { child: '[Circular /]' } });
expect(removeCircularReferences(a)).toStrictEqual({
child: { child: '[Circular /child]' },
});
});

test('escapes keys in the JSON pointer', () => {
const node: any = {};
node['a/b~c'] = { back: node, self: null };
node['a/b~c'].self = node['a/b~c'];
expect(removeCircularReferences(node)).toStrictEqual({
'a/b~c': { back: '[Circular /]', self: '[Circular /a~1b~0c]' },
});
});
});
24 changes: 24 additions & 0 deletions test/spec/asyncapi-v3-circular.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
asyncapi: 3.0.0
info:
title: Circular
version: 1.0.0
channels:
entities:
address: entities
messages:
entityCreated:
payload:
$ref: '#/components/schemas/entity'
components:
schemas:
filters:
type: array
items:
anyOf:
- $ref: '#/components/schemas/filters'
- type: string
entity:
type: object
properties:
filters:
$ref: '#/components/schemas/filters'
Loading