generated from etclabscore/pristine-typescript
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
287 lines (253 loc) · 8.58 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { JSONSchema, JSONSchemaObject, PatternProperties } from "@json-schema-tools/meta-schema";
/**
* Signature of the mutation method passed to traverse.
*
* @param schema The schema or subschema node being traversed
* @param isCycle false if the schema passed is not the root of a detected cycle. Useful for special handling of cycled schemas.
* @param path json-path string in dot-notation as per [draft-goessner-dispatch-jsonpath-00](https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html#name-overview-of-jsonpath-expres)
* @param parent if the schema is the root, this will be the same as `schema`. Otherwise, it will be a reference to JSONSchema that is the parent.
*/
export type MutationFunction = (
schema: JSONSchema,
isCycle: boolean,
path: string,
parent: JSONSchema,
) => JSONSchema;
/**
* The options you can use when traversing.
*/
export interface TraverseOptions {
/**
* Set this to true if you don't want to call the mutator function on the root schema.
*/
skipFirstMutation?: boolean;
/**
* Set this to true if you want to merge the returned value of the mutation function into
* the original schema.
*/
mergeNotMutate?: boolean;
/**
* true if you want the original schema that was provided to be directly modified by the provided mutation/merge function
* To preserve cyclical refs this is necessary.
*/
mutable?: boolean;
/**
* true if you want to traverse in a breadth-first manner. This will cause the mutation function to be called first with
* the root schema, moving down the subschemas until the terminal subschemas.
*/
bfs?: boolean;
}
export const defaultOptions: TraverseOptions = {
skipFirstMutation: false,
mutable: false,
bfs: false,
};
const jsonPathStringify = (s: string[]) => {
return s.map((i) => {
if (i === "") {
return '$';
} else {
return `.${i}`;
}
}).join("");
};
const isCycle = (s: JSONSchema, recursiveStack: JSONSchema[]): JSONSchema | false => {
const foundInRecursiveStack = recursiveStack.find((recSchema) => recSchema === s);
if (foundInRecursiveStack) {
return foundInRecursiveStack;
}
return false;
};
const last = (i: JSONSchema[], skip: number = 1): JSONSchema => {
return i[i.length - skip];
};
/**
* Traverse all subschema of a schema, calling the mutator function with each.
* The mutator is called on leaf nodes first.
*
* @param schema the schema to traverse
* @param mutation the function to pass each node in the subschema tree.
* @param traverseOptions a set of options for traversal.
* @param depth For internal use. Tracks the current recursive depth in the tree. This is used to implement
* some of the options.
*
*/
export default function traverse(
schema: JSONSchema,
mutation: MutationFunction,
traverseOptions = defaultOptions,
depth = 0,
recursiveStack: JSONSchema[] = [],
mutableStack: JSONSchema[] = [],
pathStack: string[] = [],
prePostMap: Array<[JSONSchema, JSONSchema]> = [],
cycleSet: JSONSchema[] = [],
): JSONSchema {
const opts = { ...defaultOptions, ...traverseOptions }; // would be nice to make an 'entry' func when we get around to optimizations
// booleans are a bit messed. Since all other schemas are objects (non-primitive type
// which gets a new address in mem) for each new JS refer to one of 2 memory addrs, and
// thus adding it to the recursive stack will prevent it from being explored if the
// boolean is seen in a further nested schema.
if (depth === 0) {
pathStack = [""];
}
if (typeof schema === "boolean" || schema instanceof Boolean) {
if (opts.skipFirstMutation === true && depth === 0) {
return schema;
} else {
return mutation(
schema,
false,
jsonPathStringify(pathStack),
last(mutableStack) || schema
);
}
}
let mutableSchema: JSONSchemaObject = schema;
if (opts.mutable === false) {
mutableSchema = { ...schema };
}
mutableStack.push(mutableSchema);
if (opts.bfs === true) {
if (opts.skipFirstMutation === false || depth !== 0) {
mutableSchema = mutation(
mutableSchema,
false,
jsonPathStringify(pathStack),
last(mutableStack, 2)
) as JSONSchemaObject;
}
}
recursiveStack.push(schema);
prePostMap.push([schema, mutableSchema]);
const rec = (s: JSONSchema, path: string[]): JSONSchema => {
const foundCycle = isCycle(s, recursiveStack);
if (foundCycle) {
cycleSet.push(foundCycle);
// if the cycle is a ref to the root schema && skipFirstMutation is try we need to call mutate.
// If we don't, it will never happen.
if (opts.skipFirstMutation === true && foundCycle === recursiveStack[0]) {
return mutation(
s,
true,
jsonPathStringify(path),
last(mutableStack), // should we be popping here?
);
}
const [, cycledMutableSchema] = prePostMap.find(
([orig]) => foundCycle === orig,
) as [JSONSchema, JSONSchema];
return cycledMutableSchema;
}
// else
return traverse(
s,
mutation,
traverseOptions,
depth + 1,
recursiveStack,
mutableStack,
path,
prePostMap,
cycleSet,
);
};
if (schema.anyOf) {
mutableSchema.anyOf = schema.anyOf.map((x, i) => {
const result = rec(x, [...pathStack, `anyOf[${i}]`]);
return result;
});
} else if (schema.allOf) {
mutableSchema.allOf = schema.allOf.map((x, i) => {
const result = rec(x, [...pathStack, `allOf[${i}]`]);
return result;
});
} else if (schema.oneOf) {
mutableSchema.oneOf = schema.oneOf.map((x, i) => {
const result = rec(x, [...pathStack, `oneOf[${i}]`]);
return result;
});
} else {
if (schema.items) {
if (schema.items instanceof Array) {
mutableSchema.items = schema.items.map((x, i) => {
const result = rec(x, [...pathStack, `items[${i}]`]);
return result;
});
} else {
const foundCycle = isCycle(schema.items, recursiveStack);
if (foundCycle) {
cycleSet.push(foundCycle);
if (opts.skipFirstMutation === true && foundCycle === recursiveStack[0]) {
mutableSchema.items = mutation(
schema.items,
true,
jsonPathStringify(pathStack),
last(mutableStack)
);
} else {
const [, cycledMutableSchema] = prePostMap.find(
([orig]) => foundCycle === orig,
) as [JSONSchema, JSONSchema];
mutableSchema.items = cycledMutableSchema;
}
} else {
mutableSchema.items = traverse(
schema.items,
mutation,
traverseOptions,
depth + 1,
recursiveStack,
mutableStack,
[...pathStack, "items"],
prePostMap,
cycleSet,
);
}
}
}
if (schema.additionalItems !== undefined) {
mutableSchema.additionalItems = rec(
schema.additionalItems,
[...pathStack, "additionalItems"]
);
}
if (schema.properties !== undefined) {
const sProps: { [key: string]: JSONSchema } = schema.properties;
const mutableProps: { [key: string]: JSONSchema } = {};
Object.keys(schema.properties).forEach((schemaPropKey: string) => {
mutableProps[schemaPropKey] = rec(sProps[schemaPropKey], [...pathStack, "properties", schemaPropKey.toString()]);
});
mutableSchema.properties = mutableProps;
}
if (schema.patternProperties !== undefined) {
const sProps = schema.patternProperties;
const mutableProps: PatternProperties = {};
Object.keys(schema.patternProperties).forEach((regex: string) => {
mutableProps[regex] = rec(sProps[regex], [...pathStack, "patternProperties", regex.toString()]);
});
mutableSchema.patternProperties = mutableProps;
}
if (schema.additionalProperties !== undefined && !!schema.additionalProperties === true) {
mutableSchema.additionalProperties = rec(schema.additionalProperties, [...pathStack, "additionalProperties"]);
}
}
if (opts.skipFirstMutation === true && depth === 0) {
return mutableSchema;
}
if (opts.bfs === true) {
mutableStack.pop();
return mutableSchema;
} else {
const isCycle = cycleSet.indexOf(schema) !== -1
//console.log(recursiveStack, depth, mutableSchema);
const mutated = mutation(
mutableSchema,
isCycle,
jsonPathStringify(pathStack),
last(mutableStack, 2) || schema
);
mutableStack.pop();
return mutated;
}
}