specshield 3.4.14 → 3.4.16

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,231 @@
1
+ 'use strict';
2
+
3
+ const L = require('../locate');
4
+ const { validateBody } = require('../../conformance/responseValidator');
5
+
6
+ /**
7
+ * Version transforms: Stripe-style "old clients get the old shape". The new
8
+ * code speaks the target spec; a thin layer rewrites JSON at the edge —
9
+ * responses back into the base shape for clients on the old version, and old
10
+ * requests forward into the target shape — so nothing in the controllers
11
+ * changes.
12
+ *
13
+ * A transform:
14
+ * { method, path, code?, side: 'response'|'request', kind, at: [steps], …kind fields }
15
+ * rename { from, to } move a property inside the object at `at`
16
+ * convert { field, from, to } change a scalar's JSON type at `at`
17
+ * enum { field, from, to } map one enum value to another at `at`
18
+ * default { field, value } add a property when the client left it out
19
+ * unwrap { property } replace the root object by one of its properties
20
+ * steps: { prop } · { items } (every element) · { map } (every value)
21
+ *
22
+ * applyTransforms() here and the generated Java runtime implement the same
23
+ * rules; the CLI checks every transform on sample payloads before generating.
24
+ */
25
+
26
+ const CONVERTIBLE = ['string', 'integer', 'number', 'boolean'];
27
+
28
+ /** Collects, dedupes and verifies the transforms behind a fixSpec result. */
29
+ function buildShim(result, baseDoc, targetDoc) {
30
+ const seen = new Set();
31
+ const all = [];
32
+ const skipped = [];
33
+ for (const s of result.suggestions) {
34
+ for (const t of s.transforms) {
35
+ const n = normalize(t);
36
+ if (!n) { skipped.push(`${t.method} ${t.path}: a ${t.kind} inside oneOf/anyOf or of a non-scalar type is not supported`); continue; }
37
+ const key = JSON.stringify(n);
38
+ if (!seen.has(key)) { seen.add(key); all.push(n); }
39
+ }
40
+ }
41
+
42
+ // Verify per (operation, side, status): sample the shape one side speaks,
43
+ // transform it, validate against the other side's schema.
44
+ const groups = new Map();
45
+ for (const t of all) {
46
+ const k = `${t.method} ${t.path} ${t.side} ${t.code || ''}`;
47
+ if (!groups.has(k)) groups.set(k, []);
48
+ groups.get(k).push(t);
49
+ }
50
+ const transforms = [];
51
+ for (const list of groups.values()) {
52
+ const v = verify(list, baseDoc, targetDoc);
53
+ if (v.ok) transforms.push(...list);
54
+ else skipped.push(`${list[0].method} ${list[0].path} ${list[0].side}${list[0].code ? ` ${list[0].code}` : ''}: ${v.reason}`);
55
+ }
56
+ return { transforms: order(transforms), skipped };
57
+ }
58
+
59
+ function normalize(t) {
60
+ // rename/default act on the object holding the field; convert/enum on the
61
+ // field's value, addressed by its parent plus `field` (null = the array
62
+ // element itself); unwrap on the root.
63
+ const parent = t.kind === 'rename' || t.kind === 'default' ? t.parent
64
+ : t.kind === 'unwrap' ? [] : t.steps.slice(0, -1);
65
+ if (parent.some((s) => s.variant)) return null;
66
+ const at = parent.map((s) => (s.prop !== undefined ? { prop: s.prop } : s.items ? { items: true } : { map: true }));
67
+ const n = { method: t.method, path: t.path, code: t.code || null, side: t.side, kind: t.kind, at };
68
+ if (t.kind === 'rename') Object.assign(n, { from: t.from, to: t.to });
69
+ else if (t.kind === 'default') Object.assign(n, { field: t.field, value: t.value });
70
+ else if (t.kind === 'unwrap') Object.assign(n, { property: t.property });
71
+ else {
72
+ const last = t.steps[t.steps.length - 1];
73
+ if (!last || last.variant || last.map) return null;
74
+ if (last.items) { n.at.push({ items: true }); n.field = null; } else n.field = last.prop;
75
+ Object.assign(n, { from: t.from, to: t.to });
76
+ if (t.kind === 'convert') {
77
+ n.from = String(n.from).split(':')[0];
78
+ n.to = String(n.to).split(':')[0];
79
+ if (!CONVERTIBLE.includes(n.from) || !CONVERTIBLE.includes(n.to)) return null;
80
+ }
81
+ }
82
+ return n;
83
+ }
84
+
85
+ /**
86
+ * The order both runtimes apply. Value rewrites name fields as the OLD spec
87
+ * does, so a response (new → old) renames first and rewrites after, and a
88
+ * request (old → new) rewrites first and renames after. Defaults name new
89
+ * fields and come last on requests.
90
+ */
91
+ function order(list) {
92
+ const rank = {
93
+ response: { unwrap: 0, rename: 1, default: 2, convert: 3, enum: 4 },
94
+ request: { unwrap: 0, convert: 1, enum: 2, rename: 3, default: 4 },
95
+ };
96
+ return [...list].sort((a, b) => rank[a.side][a.kind] - rank[b.side][b.kind]);
97
+ }
98
+
99
+ // ─── runtime (mirrored in the generated Java) ───────────────────────────────
100
+
101
+ function applyTransforms(body, transforms) {
102
+ let root = body;
103
+ for (const t of order(transforms)) {
104
+ if (t.kind === 'unwrap') {
105
+ if (root && typeof root === 'object' && !Array.isArray(root) && t.property in root) root = root[t.property];
106
+ continue;
107
+ }
108
+ forEachAt(root, t.at, (obj, parentSetter) => applyOne(obj, t, parentSetter));
109
+ }
110
+ return root;
111
+ }
112
+
113
+ function forEachAt(node, steps, fn, setter = null) {
114
+ if (steps.length === 0) { fn(node, setter); return; }
115
+ const [s, ...rest] = steps;
116
+ if (node === null || typeof node !== 'object') return;
117
+ if (s.prop !== undefined) {
118
+ if (!Array.isArray(node) && s.prop in node) forEachAt(node[s.prop], rest, fn, (v) => { node[s.prop] = v; });
119
+ } else if (s.items) {
120
+ if (Array.isArray(node)) node.forEach((el, i) => forEachAt(el, rest, fn, (v) => { node[i] = v; }));
121
+ } else if (!Array.isArray(node)) {
122
+ for (const k of Object.keys(node)) forEachAt(node[k], rest, fn, (v) => { node[k] = v; });
123
+ }
124
+ }
125
+
126
+ function applyOne(node, t, setValue) {
127
+ if (t.kind === 'rename') {
128
+ if (isObject(node) && t.from in node && !(t.to in node)) {
129
+ node[t.to] = node[t.from];
130
+ delete node[t.from];
131
+ }
132
+ return;
133
+ }
134
+ if (t.kind === 'default') {
135
+ if (isObject(node) && !(t.field in node)) node[t.field] = t.value;
136
+ return;
137
+ }
138
+ // convert / enum act on a value: a property of `node`, or `node` itself (array items)
139
+ if (t.field === null) { if (setValue) setValue(rewrite(node, t)); return; }
140
+ if (isObject(node) && t.field in node) node[t.field] = rewrite(node[t.field], t);
141
+ }
142
+
143
+ function rewrite(v, t) {
144
+ if (t.kind === 'enum') return v === t.from ? t.to : v;
145
+ return convert(v, t.to);
146
+ }
147
+
148
+ /** Converts a JSON scalar; leaves it untouched when it has no faithful form in the target type. */
149
+ function convert(v, to) {
150
+ if (v === null || v === undefined) return v;
151
+ if (to === 'string') return typeof v === 'string' ? v : String(v);
152
+ if (to === 'boolean') {
153
+ if (typeof v === 'boolean') return v;
154
+ if (v === 'true' || v === 1) return true;
155
+ if (v === 'false' || v === 0) return false;
156
+ return v;
157
+ }
158
+ const n = typeof v === 'number' ? v : typeof v === 'string' && /^\s*-?\d+(\.\d+)?([eE][+-]?\d+)?\s*$/.test(v) ? Number(v) : NaN;
159
+ if (Number.isNaN(n)) return v;
160
+ if (to === 'integer') return Number.isInteger(n) ? n : v;
161
+ return n;
162
+ }
163
+
164
+ function isObject(v) {
165
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
166
+ }
167
+
168
+ // ─── verification ───────────────────────────────────────────────────────────
169
+
170
+ function verify(list, baseDoc, targetDoc) {
171
+ const t0 = list[0];
172
+ const from = t0.side === 'response' ? targetDoc : baseDoc;
173
+ const to = t0.side === 'response' ? baseDoc : targetDoc;
174
+ const fromPtr = schemaPtr(from, t0);
175
+ const toPtr = schemaPtr(to, t0);
176
+ if (!fromPtr || !toPtr) return { ok: false, reason: 'no JSON body schema on both sides' };
177
+ const fromSchema = L.inline(from, L.get(from, fromPtr));
178
+ const toSchema = L.inline(to, L.get(to, toPtr));
179
+ const prefer = new Set(list.filter((t) => t.kind === 'enum').map((t) => t.from));
180
+ // The fields the transforms act on — present in any real payload they'd matter for.
181
+ const keep = new Set(list.map((t) => t.property || (t.kind === 'rename' ? t.from : t.field)).filter(Boolean));
182
+ // Two samples: every optional property present, and only the required ones.
183
+ for (const full of [true, false]) {
184
+ const sample = sampleOf(fromSchema, { full, prefer, keep });
185
+ const out = applyTransforms(JSON.parse(JSON.stringify(sample)), list);
186
+ const v = validateBody(out, toSchema);
187
+ if (!v.ok) {
188
+ const e = v.errors[0];
189
+ return { ok: false, reason: `a transformed ${t0.side} still doesn't match the old schema (${e.path} ${e.message})` +
190
+ (e.keyword === 'required' ? ' — the new code no longer produces a field old clients require' : '') };
191
+ }
192
+ }
193
+ return { ok: true };
194
+ }
195
+
196
+ function schemaPtr(doc, t) {
197
+ return t.side === 'request'
198
+ ? L.requestSchemaPtr(doc, t.method, t.path)
199
+ : L.responseSchemaPtr(doc, t.method, t.path, t.code);
200
+ }
201
+
202
+ /** A deterministic example of `schema` (inlined). */
203
+ function sampleOf(schema, { full, prefer, keep = new Set() }, depth = 0) {
204
+ if (!schema || typeof schema !== 'object' || depth > 8) return null;
205
+ if (schema.example !== undefined && !schema.enum) return schema.example;
206
+ if (schema.allOf) return Object.assign({}, ...schema.allOf.map((s) => sampleOf(s, { full, prefer, keep }, depth + 1)));
207
+ if (schema.oneOf || schema.anyOf) return sampleOf((schema.oneOf || schema.anyOf)[0], { full, prefer, keep }, depth + 1);
208
+ if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum.find((v) => prefer.has(v)) ?? schema.enum[0];
209
+ const type = Array.isArray(schema.type) ? schema.type.find((x) => x !== 'null') : schema.type;
210
+ if (type === 'array') return [sampleOf(schema.items, { full, prefer, keep }, depth + 1)];
211
+ if (type === 'object' || schema.properties) {
212
+ const out = {};
213
+ const required = new Set(schema.required || []);
214
+ for (const [k, p] of Object.entries(schema.properties || {})) {
215
+ if (full || required.has(k) || keep.has(k)) out[k] = sampleOf(p, { full, prefer, keep }, depth + 1);
216
+ }
217
+ return out;
218
+ }
219
+ if (type === 'integer') return schema.minimum !== undefined ? Math.ceil(schema.minimum) : 1;
220
+ if (type === 'number') return schema.minimum !== undefined ? schema.minimum : 1.5;
221
+ if (type === 'boolean') return true;
222
+ if (type === 'string') {
223
+ const formats = { 'date-time': '2026-01-01T00:00:00Z', date: '2026-01-01', uuid: '00000000-0000-4000-8000-000000000000', email: 'a@b.co', uri: 'https://example.com' };
224
+ if (formats[schema.format]) return formats[schema.format];
225
+ // Numeric strings convert cleanly — the realistic case for a type change.
226
+ return '1';
227
+ }
228
+ return null;
229
+ }
230
+
231
+ module.exports = { buildShim, applyTransforms, convert, sampleOf, order };