specshield 3.4.17 → 3.5.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.
@@ -0,0 +1,257 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * A sound, incomplete subschema check: `widens(from, to)` returns true only
5
+ * when every instance `from` accepts is also accepted by `to`. When it can't
6
+ * tell — composition it doesn't model, a keyword it doesn't know — it answers
7
+ * false. So "true" is a proof of compatibility; "false" proves nothing.
8
+ *
9
+ * Deciding inclusion between JSON Schemas in general is hard (Habib et al.,
10
+ * "Finding Data Compatibility Bugs with JSON Subschema Checking", ISSTA 2021);
11
+ * this covers the shapes API changes are made of: properties added or made
12
+ * optional, enums extended, bounds relaxed, types widened, a union gaining a
13
+ * branch, branches reordered.
14
+ *
15
+ * Schemas are compared where they live — $refs followed on demand, each pair
16
+ * of nodes visited once. Recursive schemas are handled coinductively: a pair
17
+ * already being compared is assumed to widen, the standard sound rule for
18
+ * recursive types (it proves inclusion for every instance, finite or not).
19
+ *
20
+ * One assumption, the one every API-compatibility check makes: a closed world.
21
+ * An instance carries only the properties its schema declares — a client
22
+ * doesn't send fields the old spec never mentioned. Without it, declaring any
23
+ * new optional property would count as narrowing (an undeclared field could
24
+ * have held anything). Pass { closedWorld: false } to drop the assumption.
25
+ *
26
+ * A side is { doc, node }: a schema node and the document its $refs resolve in.
27
+ */
28
+
29
+ const S = require('./schema');
30
+
31
+ const ANNOTATION = /^(description|title|example|examples|externalDocs|deprecated|readOnly|writeOnly|xml|discriminator|default|\$schema|\$id|x-.*)$/;
32
+ // Numeric formats as ranges: float/double add nothing to a JSON number, int64
33
+ // covers every integer JSON carries exactly; int32 is the only real bound.
34
+ const NUMERIC_WIDTH = { int32: 1, int64: 2, float: 3, double: 3 };
35
+
36
+ let seq = 0;
37
+ const ids = new WeakMap();
38
+ const effCache = new WeakMap();
39
+
40
+ function id(o) {
41
+ let n = ids.get(o);
42
+ if (!n) { n = ++seq; ids.set(o, n); }
43
+ return n;
44
+ }
45
+
46
+ /** $refs followed and allOf merged, with a stable identity per node. */
47
+ function eff(doc, node) {
48
+ if (node === true || node === false) return node;
49
+ if (!node || typeof node !== 'object') return null;
50
+ let byDoc = effCache.get(node);
51
+ if (!byDoc) { byDoc = new WeakMap(); effCache.set(node, byDoc); }
52
+ if (!byDoc.has(doc)) byDoc.set(doc, S.effective(doc, node));
53
+ return byDoc.get(doc);
54
+ }
55
+
56
+ function widens(from, to, opts = { closedWorld: true }) {
57
+ return check(from.doc, from.node, to.doc, to.node, { closedWorld: opts.closedWorld !== false, memo: new Map() });
58
+ }
59
+
60
+ function check(fd, fn, td, tn, ctx) {
61
+ const f = eff(fd, fn);
62
+ const t = eff(td, tn);
63
+ if (t === true || (isObj(t) && meaningful(t).length === 0)) return true; // {} accepts everything
64
+ if (f === false) return true;
65
+ if (!isObj(f) || !isObj(t)) return false;
66
+ const key = `${id(f)}|${id(t)}`;
67
+ if (ctx.memo.has(key)) return ctx.memo.get(key);
68
+ ctx.memo.set(key, true); // coinductive assumption
69
+ const r = compare(fd, f, td, t, ctx);
70
+ ctx.memo.set(key, r);
71
+ return r;
72
+ }
73
+
74
+ function compare(fd, f, td, t, ctx) {
75
+ const fu = union(f);
76
+ const tu = union(t);
77
+
78
+ // A union on the accepting side: enough that one branch takes all of `from`.
79
+ if (tu && onlyKeys(t, tu.kind) && !fu) {
80
+ if (tu.kind === 'oneOf' && !disjointTypes(td, tu.branches)) return false;
81
+ return tu.branches.some((b) => check(fd, f, td, b, ctx));
82
+ }
83
+ // Unions on both sides: every branch of `from` must land in a branch of `to`.
84
+ if (fu && tu && onlyKeys(f, fu.kind) && onlyKeys(t, tu.kind)) {
85
+ if (tu.kind === 'oneOf' && !disjointTypes(td, tu.branches)) return false;
86
+ return fu.branches.every((fb) => tu.branches.some((tb) => check(fd, fb, td, tb, ctx)));
87
+ }
88
+
89
+ const keys = new Set([...meaningful(f), ...meaningful(t)]);
90
+ for (const k of keys) {
91
+ const a = f[k];
92
+ const b = t[k];
93
+ switch (k) {
94
+ case 'type':
95
+ if (!typeWidens(a, b, f)) return false;
96
+ break;
97
+ case 'nullable':
98
+ if (a === true && b !== true) return false;
99
+ break;
100
+ case 'format':
101
+ if (!formatWidens(a, b, f)) return false;
102
+ break;
103
+ case 'pattern': case 'const': case 'multipleOf': case 'uniqueItems':
104
+ if (b !== undefined && !same(a, b)) return false;
105
+ break;
106
+ case 'enum':
107
+ if (b !== undefined && (!Array.isArray(a) || !a.every((v) => b.some((x) => same(x, v))))) return false;
108
+ break;
109
+ case 'minimum': case 'minLength': case 'minItems': case 'minProperties': case 'exclusiveMinimum':
110
+ if (b !== undefined && !(typeof a === typeof b && a >= b)) return false;
111
+ break;
112
+ case 'maximum': case 'maxLength': case 'maxItems': case 'maxProperties': case 'exclusiveMaximum':
113
+ if (b !== undefined && !(typeof a === typeof b && a <= b)) return false;
114
+ break;
115
+ case 'required':
116
+ if (b !== undefined && !b.every((name) => (a || []).includes(name))) return false;
117
+ break;
118
+ case 'items':
119
+ if (b !== undefined && !(a !== undefined && check(fd, a, td, b, ctx))) return false;
120
+ break;
121
+ case 'properties':
122
+ if (!propertiesWiden(fd, f, td, t, ctx)) return false;
123
+ break;
124
+ case 'additionalProperties':
125
+ if (!additionalWidens(fd, f, td, t, ctx)) return false;
126
+ break;
127
+ case 'oneOf': case 'anyOf':
128
+ // A union next to other keywords: only when the two unions match branch for branch.
129
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.every((x, i) => check(fd, x, td, b[i], ctx))) return false;
130
+ break;
131
+ default:
132
+ // anything else (not, if/then, patternProperties, …): only when identical
133
+ if (!same(a, b)) return false;
134
+ }
135
+ }
136
+ return true;
137
+ }
138
+
139
+ function union(s) {
140
+ if (Array.isArray(s.anyOf)) return { kind: 'anyOf', branches: s.anyOf };
141
+ if (Array.isArray(s.oneOf)) return { kind: 'oneOf', branches: s.oneOf };
142
+ return null;
143
+ }
144
+
145
+ function typeWidens(a, b, f) {
146
+ if (b === undefined) return true;
147
+ const fs = a === undefined ? (f.properties ? ['object'] : null) : [].concat(a);
148
+ if (!fs) return false;
149
+ const ts = [].concat(b);
150
+ return fs.every((x) => ts.includes(x) || (x === 'integer' && ts.includes('number')));
151
+ }
152
+
153
+ function formatWidens(a, b, f) {
154
+ if (b === undefined || a === b) return true;
155
+ const types = [].concat(f.type || []);
156
+ const numeric = types.length > 0 && types.every((x) => x === 'integer' || x === 'number' || x === 'null');
157
+ if (!numeric || !(b in NUMERIC_WIDTH) || (a !== undefined && !(a in NUMERIC_WIDTH))) return false;
158
+ return b !== 'int32' || a === 'int32';
159
+ }
160
+
161
+ /** Every property `from` allows must be allowed by `to`, at least as loosely. */
162
+ function propertiesWiden(fd, f, td, t, ctx) {
163
+ const fp = f.properties || {};
164
+ const tp = t.properties || {};
165
+ for (const [name, a] of Object.entries(fp)) {
166
+ if (tp[name] !== undefined) {
167
+ if (!check(fd, a, td, tp[name], ctx)) return false;
168
+ } else if (t.additionalProperties === false) {
169
+ return false;
170
+ } else if (isObj(t.additionalProperties) && !check(fd, a, td, t.additionalProperties, ctx)) {
171
+ return false;
172
+ }
173
+ }
174
+ // Properties only `to` declares: in a closed world `from`'s instances never
175
+ // carry them; otherwise `from` must not have let arbitrary values through.
176
+ if (ctx.closedWorld) return true;
177
+ for (const [name, b] of Object.entries(tp)) {
178
+ if (fp[name] !== undefined || f.additionalProperties === false) continue;
179
+ if (isObj(f.additionalProperties) ? !check(fd, f.additionalProperties, td, b, ctx) : !acceptsAll(eff(td, b))) return false;
180
+ }
181
+ return true;
182
+ }
183
+
184
+ function additionalWidens(fd, f, td, t, ctx) {
185
+ const a = f.additionalProperties;
186
+ const b = t.additionalProperties;
187
+ if (b === undefined || b === true || (isObj(b) && meaningful(b).length === 0)) return true;
188
+ if (a === false) return true;
189
+ if (b === false) return ctx.closedWorld; // closed world: nothing undeclared is sent
190
+ return isObj(a) && check(fd, a, td, b, ctx);
191
+ }
192
+
193
+ function acceptsAll(s) {
194
+ return s === true || (isObj(s) && meaningful(s).length === 0);
195
+ }
196
+
197
+ /** Branches a oneOf can't both match: distinct JSON types. */
198
+ function disjointTypes(doc, branches) {
199
+ const seen = new Set();
200
+ for (const b of branches) {
201
+ const s = eff(doc, b);
202
+ if (!isObj(s) || s.type === undefined || Array.isArray(s.type)) return false;
203
+ const t = s.type === 'integer' ? 'number' : s.type;
204
+ if (seen.has(t)) return false;
205
+ seen.add(t);
206
+ }
207
+ return true;
208
+ }
209
+
210
+ /**
211
+ * Can an instance of `branch` (which pins a required property to one value)
212
+ * also match another branch of a oneOf? Not when every other branch requires
213
+ * that property with values that leave it out — the usual discriminated union.
214
+ */
215
+ function exclusiveIn(doc, branch, others) {
216
+ const b = eff(doc, branch);
217
+ if (!isObj(b)) return false;
218
+ const req = new Set(b.required || []);
219
+ for (const [prop, raw] of Object.entries(b.properties || {})) {
220
+ const ps = eff(doc, raw);
221
+ if (!req.has(prop) || !isObj(ps)) continue;
222
+ const pinned = ps.const !== undefined ? ps.const : Array.isArray(ps.enum) && ps.enum.length === 1 ? ps.enum[0] : undefined;
223
+ if (pinned === undefined) continue;
224
+ const excluded = others.every((o) => {
225
+ const os = eff(doc, o);
226
+ const op = isObj(os) && os.properties && eff(doc, os.properties[prop]);
227
+ if (!isObj(op) || !(os.required || []).includes(prop)) return false;
228
+ const vals = op.const !== undefined ? [op.const] : op.enum;
229
+ return Array.isArray(vals) && !vals.some((v) => same(v, pinned));
230
+ });
231
+ if (excluded) return true;
232
+ }
233
+ return false;
234
+ }
235
+
236
+ /** Same meaning both ways — "unchanged" for reporting. */
237
+ function equivalent(a, b) {
238
+ return widens(a, b) && widens(b, a);
239
+ }
240
+
241
+ function meaningful(s) {
242
+ return Object.keys(s).filter((k) => !ANNOTATION.test(k));
243
+ }
244
+
245
+ function onlyKeys(s, key) {
246
+ return meaningful(s).every((k) => k === key);
247
+ }
248
+
249
+ function isObj(v) {
250
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
251
+ }
252
+
253
+ function same(a, b) {
254
+ return JSON.stringify(a) === JSON.stringify(b);
255
+ }
256
+
257
+ module.exports = { widens, equivalent, exclusiveIn };