@shreyanshrathaur/shapewatch 0.0.0-stage → 0.2.0
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.
- package/dist/cli.cjs +404 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +11 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.js +376 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +759 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +70 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +722 -0
- package/dist/index.js.map +1 -0
- package/dist/storage/file.cjs +83 -0
- package/dist/storage/file.cjs.map +1 -0
- package/dist/storage/file.d.cts +20 -0
- package/dist/storage/file.d.ts +20 -0
- package/dist/storage/file.js +60 -0
- package/dist/storage/file.js.map +1 -0
- package/dist/storage/localstorage.cjs +55 -0
- package/dist/storage/localstorage.cjs.map +1 -0
- package/dist/storage/localstorage.d.cts +16 -0
- package/dist/storage/localstorage.d.ts +16 -0
- package/dist/storage/localstorage.js +53 -0
- package/dist/storage/localstorage.js.map +1 -0
- package/dist/storage/memory.cjs +24 -0
- package/dist/storage/memory.cjs.map +1 -0
- package/dist/storage/memory.d.cts +12 -0
- package/dist/storage/memory.d.ts +12 -0
- package/dist/storage/memory.js +22 -0
- package/dist/storage/memory.js.map +1 -0
- package/dist/types-CtCc79uW.d.cts +82 -0
- package/dist/types-CtCc79uW.d.ts +82 -0
- package/dist/types-N86So-w4.d.cts +82 -0
- package/dist/types-N86So-w4.d.ts +82 -0
- package/package.json +98 -4
- package/README.md +0 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
|
|
6
|
+
function _interopNamespace(e) {
|
|
7
|
+
if (e && e.__esModule) return e;
|
|
8
|
+
var n = Object.create(null);
|
|
9
|
+
if (e) {
|
|
10
|
+
Object.keys(e).forEach(function (k) {
|
|
11
|
+
if (k !== 'default') {
|
|
12
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
13
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function () { return e[k]; }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
n.default = e;
|
|
21
|
+
return Object.freeze(n);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
25
|
+
var path__namespace = /*#__PURE__*/_interopNamespace(path);
|
|
26
|
+
|
|
27
|
+
// src/walk.ts
|
|
28
|
+
function escapePathKey(key) {
|
|
29
|
+
if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
30
|
+
return key;
|
|
31
|
+
}
|
|
32
|
+
return `["${key.replace(/["\\]/g, "\\$&")}"]`;
|
|
33
|
+
}
|
|
34
|
+
function buildObjectPath(parentPath, key) {
|
|
35
|
+
if (parentPath === "$") {
|
|
36
|
+
if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
37
|
+
return `$.${key}`;
|
|
38
|
+
}
|
|
39
|
+
return `$["${key.replace(/["\\]/g, "\\$&")}"]`;
|
|
40
|
+
}
|
|
41
|
+
if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
42
|
+
return `${parentPath}.${key}`;
|
|
43
|
+
}
|
|
44
|
+
return `${parentPath}["${key.replace(/["\\]/g, "\\$&")}"]`;
|
|
45
|
+
}
|
|
46
|
+
function buildArrayElementPath(parentPath) {
|
|
47
|
+
return `${parentPath}[]`;
|
|
48
|
+
}
|
|
49
|
+
function isPathIgnored(path2, ignorePatterns) {
|
|
50
|
+
if (!ignorePatterns || ignorePatterns.length === 0) return false;
|
|
51
|
+
for (const pattern of ignorePatterns) {
|
|
52
|
+
if (path2 === pattern) return true;
|
|
53
|
+
if (path2.startsWith(pattern + ".") || path2.startsWith(pattern + "[") || path2.startsWith(pattern + "[]")) {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
function getTypeString(val) {
|
|
60
|
+
if (val === null) return "null";
|
|
61
|
+
if (Array.isArray(val)) return "array";
|
|
62
|
+
const t = typeof val;
|
|
63
|
+
if (t === "string") return "string";
|
|
64
|
+
if (t === "number") {
|
|
65
|
+
return Number.isFinite(val) ? "number" : "number";
|
|
66
|
+
}
|
|
67
|
+
if (t === "boolean") return "boolean";
|
|
68
|
+
if (t === "object") return "object";
|
|
69
|
+
return t;
|
|
70
|
+
}
|
|
71
|
+
function walkValue(value, options = {}) {
|
|
72
|
+
const maxDepth = options.maxDepth ?? 10;
|
|
73
|
+
const maxArrayItems = options.maxArrayItems ?? 20;
|
|
74
|
+
const ignorePatterns = options.ignorePaths;
|
|
75
|
+
const results = /* @__PURE__ */ new Map();
|
|
76
|
+
const visitedObjects = /* @__PURE__ */ new WeakSet();
|
|
77
|
+
function traverse(current, path2, depth) {
|
|
78
|
+
if (isPathIgnored(path2, ignorePatterns)) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const typeStr = getTypeString(current);
|
|
82
|
+
const isNull = current === null;
|
|
83
|
+
if (!results.has(path2)) {
|
|
84
|
+
results.set(path2, { path: path2, type: typeStr, isNull });
|
|
85
|
+
}
|
|
86
|
+
if (isNull || depth >= maxDepth) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (Array.isArray(current)) {
|
|
90
|
+
const elemPath = buildArrayElementPath(path2);
|
|
91
|
+
if (isPathIgnored(elemPath, ignorePatterns)) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const limit = Math.min(current.length, maxArrayItems);
|
|
95
|
+
for (let i = 0; i < limit; i++) {
|
|
96
|
+
traverse(current[i], elemPath, depth + 1);
|
|
97
|
+
}
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (typeof current === "object" && current !== null) {
|
|
101
|
+
if (visitedObjects.has(current)) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
visitedObjects.add(current);
|
|
105
|
+
const keys = Object.keys(current);
|
|
106
|
+
for (const key of keys) {
|
|
107
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
let childVal;
|
|
111
|
+
try {
|
|
112
|
+
childVal = current[key];
|
|
113
|
+
} catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const childPath = buildObjectPath(path2, key);
|
|
117
|
+
traverse(childVal, childPath, depth + 1);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
traverse(value, "$", 0);
|
|
122
|
+
return results;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/baseline.ts
|
|
126
|
+
var BaselineManager = class {
|
|
127
|
+
baselines = /* @__PURE__ */ new Map();
|
|
128
|
+
maxEndpoints;
|
|
129
|
+
learnSamples;
|
|
130
|
+
requiredThreshold;
|
|
131
|
+
walkOptions;
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
this.learnSamples = options.learnSamples ?? 20;
|
|
134
|
+
this.requiredThreshold = options.requiredThreshold ?? 0.95;
|
|
135
|
+
this.maxEndpoints = options.maxEndpoints ?? 1e3;
|
|
136
|
+
this.walkOptions = {
|
|
137
|
+
maxDepth: options.maxDepth,
|
|
138
|
+
maxArrayItems: options.maxArrayItems,
|
|
139
|
+
ignorePaths: options.ignorePaths
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
getBaseline(endpoint) {
|
|
143
|
+
return this.baselines.get(endpoint);
|
|
144
|
+
}
|
|
145
|
+
isFrozen(endpoint) {
|
|
146
|
+
const b = this.baselines.get(endpoint);
|
|
147
|
+
return b ? b.frozen : false;
|
|
148
|
+
}
|
|
149
|
+
getOrCreateBaseline(endpoint) {
|
|
150
|
+
let baseline = this.baselines.get(endpoint);
|
|
151
|
+
if (!baseline) {
|
|
152
|
+
if (this.baselines.size >= this.maxEndpoints) {
|
|
153
|
+
throw new Error(`Endpoint capacity limit reached (${this.maxEndpoints})`);
|
|
154
|
+
}
|
|
155
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
156
|
+
baseline = {
|
|
157
|
+
endpoint,
|
|
158
|
+
samples: 0,
|
|
159
|
+
fields: {},
|
|
160
|
+
frozen: false,
|
|
161
|
+
createdAt: now,
|
|
162
|
+
updatedAt: now
|
|
163
|
+
};
|
|
164
|
+
this.baselines.set(endpoint, baseline);
|
|
165
|
+
}
|
|
166
|
+
return baseline;
|
|
167
|
+
}
|
|
168
|
+
recordSample(endpoint, data) {
|
|
169
|
+
const baseline = this.getOrCreateBaseline(endpoint);
|
|
170
|
+
if (baseline.frozen) {
|
|
171
|
+
return baseline;
|
|
172
|
+
}
|
|
173
|
+
const observedFields = walkValue(data, this.walkOptions);
|
|
174
|
+
baseline.samples += 1;
|
|
175
|
+
baseline.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
176
|
+
for (const [path2, obs] of observedFields) {
|
|
177
|
+
let stat = baseline.fields[path2];
|
|
178
|
+
if (!stat) {
|
|
179
|
+
stat = {
|
|
180
|
+
path: path2,
|
|
181
|
+
seen: 0,
|
|
182
|
+
eligible: baseline.samples - 1,
|
|
183
|
+
// missed prior samples
|
|
184
|
+
presentRatio: 0,
|
|
185
|
+
typeCounts: {},
|
|
186
|
+
nullCount: 0,
|
|
187
|
+
allowedTypes: [],
|
|
188
|
+
allowsNull: false,
|
|
189
|
+
required: false
|
|
190
|
+
};
|
|
191
|
+
baseline.fields[path2] = stat;
|
|
192
|
+
}
|
|
193
|
+
stat.seen += 1;
|
|
194
|
+
stat.eligible += 1;
|
|
195
|
+
stat.presentRatio = stat.eligible > 0 ? stat.seen / stat.eligible : 1;
|
|
196
|
+
if (obs.isNull) {
|
|
197
|
+
stat.nullCount += 1;
|
|
198
|
+
stat.allowsNull = true;
|
|
199
|
+
} else {
|
|
200
|
+
stat.typeCounts[obs.type] = (stat.typeCounts[obs.type] || 0) + 1;
|
|
201
|
+
if (!stat.allowedTypes.includes(obs.type)) {
|
|
202
|
+
stat.allowedTypes.push(obs.type);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
for (const [path2, stat] of Object.entries(baseline.fields)) {
|
|
207
|
+
if (!observedFields.has(path2)) {
|
|
208
|
+
stat.eligible += 1;
|
|
209
|
+
stat.presentRatio = stat.eligible > 0 ? stat.seen / stat.eligible : 0;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (baseline.samples >= this.learnSamples) {
|
|
213
|
+
this.freezeBaseline(baseline);
|
|
214
|
+
}
|
|
215
|
+
return baseline;
|
|
216
|
+
}
|
|
217
|
+
freezeBaseline(baseline) {
|
|
218
|
+
baseline.frozen = true;
|
|
219
|
+
for (const stat of Object.values(baseline.fields)) {
|
|
220
|
+
stat.required = stat.presentRatio >= this.requiredThreshold && stat.eligible > 0;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
reset(endpoint) {
|
|
224
|
+
if (endpoint) {
|
|
225
|
+
this.baselines.delete(endpoint);
|
|
226
|
+
} else {
|
|
227
|
+
this.baselines.clear();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
exportAll(endpoint) {
|
|
231
|
+
const result = {};
|
|
232
|
+
if (endpoint) {
|
|
233
|
+
const b = this.baselines.get(endpoint);
|
|
234
|
+
if (b) {
|
|
235
|
+
result[endpoint] = JSON.parse(JSON.stringify(b));
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
for (const [ep, b] of this.baselines.entries()) {
|
|
239
|
+
result[ep] = JSON.parse(JSON.stringify(b));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
importAll(snapshot) {
|
|
245
|
+
for (const [ep, b] of Object.entries(snapshot)) {
|
|
246
|
+
this.baselines.set(ep, JSON.parse(JSON.stringify(b)));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
// src/compare.ts
|
|
252
|
+
function compareObservation(endpoint, baseline, data, options = {}) {
|
|
253
|
+
const drifts = [];
|
|
254
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
255
|
+
const observedFields = walkValue(data, options);
|
|
256
|
+
const baselineFields = baseline.fields;
|
|
257
|
+
const suppressedPrefixes = /* @__PURE__ */ new Set();
|
|
258
|
+
const sortedBaselinePaths = Object.keys(baselineFields).sort();
|
|
259
|
+
for (const path2 of sortedBaselinePaths) {
|
|
260
|
+
const stat = baselineFields[path2];
|
|
261
|
+
if (!stat || !stat.required) continue;
|
|
262
|
+
let isSuppressed = false;
|
|
263
|
+
for (const prefix of suppressedPrefixes) {
|
|
264
|
+
if (path2.startsWith(prefix + ".") || path2.startsWith(prefix + "[") || path2.startsWith(prefix + "[]")) {
|
|
265
|
+
isSuppressed = true;
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (isSuppressed) continue;
|
|
270
|
+
if (!observedFields.has(path2)) {
|
|
271
|
+
drifts.push({
|
|
272
|
+
endpoint,
|
|
273
|
+
kind: "FIELD_REMOVED",
|
|
274
|
+
severity: "breaking",
|
|
275
|
+
path: path2,
|
|
276
|
+
expected: stat.allowedTypes.join(" | ") || (stat.allowsNull ? "null" : "defined"),
|
|
277
|
+
actual: "undefined",
|
|
278
|
+
count: 1,
|
|
279
|
+
firstSeen: now,
|
|
280
|
+
lastSeen: now
|
|
281
|
+
});
|
|
282
|
+
suppressedPrefixes.add(path2);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const addedPrefixes = /* @__PURE__ */ new Set();
|
|
286
|
+
const sortedObservedPaths = Array.from(observedFields.keys()).sort();
|
|
287
|
+
for (const path2 of sortedObservedPaths) {
|
|
288
|
+
const obs = observedFields.get(path2);
|
|
289
|
+
const stat = baselineFields[path2];
|
|
290
|
+
if (!stat) {
|
|
291
|
+
let isChildOfAdded = false;
|
|
292
|
+
for (const prefix of addedPrefixes) {
|
|
293
|
+
if (path2.startsWith(prefix + ".") || path2.startsWith(prefix + "[") || path2.startsWith(prefix + "[]")) {
|
|
294
|
+
isChildOfAdded = true;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (!isChildOfAdded) {
|
|
299
|
+
drifts.push({
|
|
300
|
+
endpoint,
|
|
301
|
+
kind: "FIELD_ADDED",
|
|
302
|
+
severity: "info",
|
|
303
|
+
path: path2,
|
|
304
|
+
expected: "undefined",
|
|
305
|
+
actual: obs.isNull ? "null" : obs.type,
|
|
306
|
+
count: 1,
|
|
307
|
+
firstSeen: now,
|
|
308
|
+
lastSeen: now
|
|
309
|
+
});
|
|
310
|
+
addedPrefixes.add(path2);
|
|
311
|
+
}
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (obs.isNull) {
|
|
315
|
+
if (!stat.allowsNull) {
|
|
316
|
+
drifts.push({
|
|
317
|
+
endpoint,
|
|
318
|
+
kind: "UNEXPECTED_NULL",
|
|
319
|
+
severity: "warning",
|
|
320
|
+
path: path2,
|
|
321
|
+
expected: stat.allowedTypes.join(" | ") || "non-null",
|
|
322
|
+
actual: "null",
|
|
323
|
+
count: 1,
|
|
324
|
+
firstSeen: now,
|
|
325
|
+
lastSeen: now
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
} else {
|
|
329
|
+
if (stat.allowedTypes.length > 0 && !stat.allowedTypes.includes(obs.type)) {
|
|
330
|
+
drifts.push({
|
|
331
|
+
endpoint,
|
|
332
|
+
kind: "TYPE_CHANGED",
|
|
333
|
+
severity: "breaking",
|
|
334
|
+
path: path2,
|
|
335
|
+
expected: stat.allowedTypes.join(" | "),
|
|
336
|
+
actual: obs.type,
|
|
337
|
+
count: 1,
|
|
338
|
+
firstSeen: now,
|
|
339
|
+
lastSeen: now
|
|
340
|
+
});
|
|
341
|
+
suppressedPrefixes.add(path2);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return drifts;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/reporter.ts
|
|
349
|
+
var Reporter = class {
|
|
350
|
+
driftsMap = /* @__PURE__ */ new Map();
|
|
351
|
+
maxDriftKeys;
|
|
352
|
+
constructor(maxDriftKeys = 5e3) {
|
|
353
|
+
this.maxDriftKeys = maxDriftKeys;
|
|
354
|
+
}
|
|
355
|
+
makeKey(endpoint, kind, path2) {
|
|
356
|
+
return `${endpoint}::${kind}::${path2}`;
|
|
357
|
+
}
|
|
358
|
+
recordDrifts(newDrifts) {
|
|
359
|
+
const recorded = [];
|
|
360
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
361
|
+
for (const drift of newDrifts) {
|
|
362
|
+
const key = this.makeKey(drift.endpoint, drift.kind, drift.path);
|
|
363
|
+
const existing = this.driftsMap.get(key);
|
|
364
|
+
if (existing) {
|
|
365
|
+
existing.count += 1;
|
|
366
|
+
existing.lastSeen = now;
|
|
367
|
+
existing.actual = drift.actual;
|
|
368
|
+
recorded.push({ ...existing });
|
|
369
|
+
} else {
|
|
370
|
+
if (this.driftsMap.size < this.maxDriftKeys) {
|
|
371
|
+
const fresh = {
|
|
372
|
+
...drift,
|
|
373
|
+
count: 1,
|
|
374
|
+
firstSeen: now,
|
|
375
|
+
lastSeen: now
|
|
376
|
+
};
|
|
377
|
+
this.driftsMap.set(key, fresh);
|
|
378
|
+
recorded.push({ ...fresh });
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return recorded;
|
|
383
|
+
}
|
|
384
|
+
getReport() {
|
|
385
|
+
const list = Array.from(this.driftsMap.values()).sort((a, b) => {
|
|
386
|
+
if (a.endpoint !== b.endpoint) return a.endpoint.localeCompare(b.endpoint);
|
|
387
|
+
if (a.path !== b.path) return a.path.localeCompare(b.path);
|
|
388
|
+
return a.kind.localeCompare(b.kind);
|
|
389
|
+
});
|
|
390
|
+
let breaking = 0;
|
|
391
|
+
let warning = 0;
|
|
392
|
+
let info = 0;
|
|
393
|
+
for (const d of list) {
|
|
394
|
+
if (d.severity === "breaking") breaking++;
|
|
395
|
+
else if (d.severity === "warning") warning++;
|
|
396
|
+
else if (d.severity === "info") info++;
|
|
397
|
+
}
|
|
398
|
+
return {
|
|
399
|
+
drifts: list,
|
|
400
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
401
|
+
summary: {
|
|
402
|
+
total: list.length,
|
|
403
|
+
breaking,
|
|
404
|
+
warning,
|
|
405
|
+
info
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
reset() {
|
|
410
|
+
this.driftsMap.clear();
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
// src/normalize.ts
|
|
415
|
+
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
416
|
+
var NUMERIC_ID_REGEX = /^\d+$/;
|
|
417
|
+
function normalizeEndpoint(urlOrPath, method = "GET") {
|
|
418
|
+
let cleanMethod = (method || "GET").toUpperCase();
|
|
419
|
+
let pathname = urlOrPath.trim();
|
|
420
|
+
const methodMatch = pathname.match(/^([A-Z]+)\s+(.+)$/i);
|
|
421
|
+
if (methodMatch && methodMatch[1] && methodMatch[2]) {
|
|
422
|
+
cleanMethod = methodMatch[1].toUpperCase();
|
|
423
|
+
pathname = methodMatch[2];
|
|
424
|
+
}
|
|
425
|
+
try {
|
|
426
|
+
if (pathname.startsWith("http://") || pathname.startsWith("https://")) {
|
|
427
|
+
const parsed = new URL(pathname);
|
|
428
|
+
pathname = parsed.pathname;
|
|
429
|
+
} else {
|
|
430
|
+
const questionIdx = pathname.indexOf("?");
|
|
431
|
+
if (questionIdx !== -1) {
|
|
432
|
+
pathname = pathname.substring(0, questionIdx);
|
|
433
|
+
}
|
|
434
|
+
const hashIdx = pathname.indexOf("#");
|
|
435
|
+
if (hashIdx !== -1) {
|
|
436
|
+
pathname = pathname.substring(0, hashIdx);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
}
|
|
441
|
+
const segments = pathname.split("/").map((seg) => {
|
|
442
|
+
if (!seg) return seg;
|
|
443
|
+
if (UUID_REGEX.test(seg) || NUMERIC_ID_REGEX.test(seg)) {
|
|
444
|
+
return ":id";
|
|
445
|
+
}
|
|
446
|
+
return seg;
|
|
447
|
+
});
|
|
448
|
+
const normalizedPath = segments.join("/") || "/";
|
|
449
|
+
return `${cleanMethod} ${normalizedPath}`;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// src/errors.ts
|
|
453
|
+
var ShapewatchDriftError = class _ShapewatchDriftError extends Error {
|
|
454
|
+
drifts;
|
|
455
|
+
constructor(drifts) {
|
|
456
|
+
const summary = drifts.map((d) => `[${d.severity.toUpperCase()}] ${d.kind} at ${d.path} (${d.endpoint})`).join("; ");
|
|
457
|
+
super(`API response shape drift detected: ${summary}`);
|
|
458
|
+
this.name = "ShapewatchDriftError";
|
|
459
|
+
this.drifts = drifts;
|
|
460
|
+
Object.setPrototypeOf(this, _ShapewatchDriftError.prototype);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
// src/adapters/fetch.ts
|
|
465
|
+
function createFetchWrapper(sw, customNormalize) {
|
|
466
|
+
return function wrapFetch(fetchImpl) {
|
|
467
|
+
const wrapped = async function(input, init) {
|
|
468
|
+
const response = await fetchImpl.apply(this, [input, init]);
|
|
469
|
+
try {
|
|
470
|
+
const status = response.status;
|
|
471
|
+
if (status < 200 || status >= 300 || status === 204) {
|
|
472
|
+
return response;
|
|
473
|
+
}
|
|
474
|
+
const contentType = response.headers.get("content-type") || "";
|
|
475
|
+
const isJson = contentType.includes("application/json") || contentType.includes("+json");
|
|
476
|
+
if (!isJson) {
|
|
477
|
+
return response;
|
|
478
|
+
}
|
|
479
|
+
let urlStr = "";
|
|
480
|
+
let method = "GET";
|
|
481
|
+
if (typeof input === "string") {
|
|
482
|
+
urlStr = input;
|
|
483
|
+
} else if (input instanceof URL) {
|
|
484
|
+
urlStr = input.toString();
|
|
485
|
+
} else if (typeof Request !== "undefined" && input instanceof Request) {
|
|
486
|
+
urlStr = input.url;
|
|
487
|
+
method = input.method;
|
|
488
|
+
}
|
|
489
|
+
if (init && init.method) {
|
|
490
|
+
method = init.method;
|
|
491
|
+
}
|
|
492
|
+
const endpointKey = customNormalize ? customNormalize(urlStr, method) : void 0;
|
|
493
|
+
const clone = response.clone();
|
|
494
|
+
clone.json().then((jsonData) => {
|
|
495
|
+
sw.observe(endpointKey || `${method.toUpperCase()} ${urlStr}`, jsonData);
|
|
496
|
+
}).catch(() => {
|
|
497
|
+
});
|
|
498
|
+
} catch {
|
|
499
|
+
}
|
|
500
|
+
return response;
|
|
501
|
+
};
|
|
502
|
+
return wrapped;
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// src/adapters/axios.ts
|
|
507
|
+
function createAxiosInterceptor(sw, customNormalize) {
|
|
508
|
+
return function axiosResponseInterceptor(response) {
|
|
509
|
+
try {
|
|
510
|
+
if (response && response.status >= 200 && response.status < 300 && response.data !== void 0) {
|
|
511
|
+
const config = response.config || {};
|
|
512
|
+
const method = (config.method || "GET").toUpperCase();
|
|
513
|
+
let url = config.url || "";
|
|
514
|
+
if (config.baseURL && !url.startsWith("http://") && !url.startsWith("https://")) {
|
|
515
|
+
url = `${config.baseURL.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
|
|
516
|
+
}
|
|
517
|
+
const endpointKey = customNormalize ? customNormalize(url, method) : normalizeEndpoint(url, method);
|
|
518
|
+
sw.observe(endpointKey, response.data);
|
|
519
|
+
}
|
|
520
|
+
} catch (err) {
|
|
521
|
+
if (err && err.name === "ShapewatchDriftError") {
|
|
522
|
+
throw err;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return response;
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/storage/memory.ts
|
|
530
|
+
var MemoryStorage = class {
|
|
531
|
+
baselines = /* @__PURE__ */ new Map();
|
|
532
|
+
lastReport = null;
|
|
533
|
+
loadBaseline(endpoint) {
|
|
534
|
+
const found = this.baselines.get(endpoint);
|
|
535
|
+
return found ? JSON.parse(JSON.stringify(found)) : null;
|
|
536
|
+
}
|
|
537
|
+
saveBaseline(endpoint, baseline) {
|
|
538
|
+
this.baselines.set(endpoint, JSON.parse(JSON.stringify(baseline)));
|
|
539
|
+
}
|
|
540
|
+
loadReport() {
|
|
541
|
+
return this.lastReport ? JSON.parse(JSON.stringify(this.lastReport)) : null;
|
|
542
|
+
}
|
|
543
|
+
saveReport(report) {
|
|
544
|
+
this.lastReport = JSON.parse(JSON.stringify(report));
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
var FileStorage = class {
|
|
548
|
+
baseDir;
|
|
549
|
+
constructor(options = {}) {
|
|
550
|
+
this.baseDir = options.baseDir || path__namespace.resolve(".shapewatch");
|
|
551
|
+
}
|
|
552
|
+
ensureDir() {
|
|
553
|
+
if (!fs__namespace.existsSync(this.baseDir)) {
|
|
554
|
+
fs__namespace.mkdirSync(this.baseDir, { recursive: true });
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
getBaselineFilePath() {
|
|
558
|
+
return path__namespace.join(this.baseDir, "baselines.json");
|
|
559
|
+
}
|
|
560
|
+
getReportFilePath() {
|
|
561
|
+
return path__namespace.join(this.baseDir, "report.json");
|
|
562
|
+
}
|
|
563
|
+
readJson(filePath) {
|
|
564
|
+
if (!fs__namespace.existsSync(filePath)) {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
try {
|
|
568
|
+
const content = fs__namespace.readFileSync(filePath, "utf-8");
|
|
569
|
+
return JSON.parse(content);
|
|
570
|
+
} catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
writeJsonAtomic(filePath, data) {
|
|
575
|
+
this.ensureDir();
|
|
576
|
+
const tempPath = `${filePath}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
577
|
+
const serialized = JSON.stringify(data, null, 2);
|
|
578
|
+
fs__namespace.writeFileSync(tempPath, serialized, "utf-8");
|
|
579
|
+
fs__namespace.renameSync(tempPath, filePath);
|
|
580
|
+
}
|
|
581
|
+
loadBaseline(endpoint) {
|
|
582
|
+
const fileData = this.readJson(this.getBaselineFilePath());
|
|
583
|
+
if (!fileData) return null;
|
|
584
|
+
return fileData[endpoint] || null;
|
|
585
|
+
}
|
|
586
|
+
saveBaseline(endpoint, baseline) {
|
|
587
|
+
const filePath = this.getBaselineFilePath();
|
|
588
|
+
const fileData = this.readJson(filePath) || {};
|
|
589
|
+
fileData[endpoint] = baseline;
|
|
590
|
+
this.writeJsonAtomic(filePath, fileData);
|
|
591
|
+
}
|
|
592
|
+
loadReport() {
|
|
593
|
+
return this.readJson(this.getReportFilePath());
|
|
594
|
+
}
|
|
595
|
+
saveReport(report) {
|
|
596
|
+
this.writeJsonAtomic(this.getReportFilePath(), report);
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
// src/storage/localstorage.ts
|
|
601
|
+
var LocalStorageAdapter = class {
|
|
602
|
+
prefix;
|
|
603
|
+
constructor(options = {}) {
|
|
604
|
+
this.prefix = options.prefix || "shapewatch:";
|
|
605
|
+
}
|
|
606
|
+
get isAvailable() {
|
|
607
|
+
try {
|
|
608
|
+
return typeof window !== "undefined" && !!window.localStorage;
|
|
609
|
+
} catch {
|
|
610
|
+
return false;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
loadBaseline(endpoint) {
|
|
614
|
+
if (!this.isAvailable) return null;
|
|
615
|
+
try {
|
|
616
|
+
const raw = window.localStorage.getItem(`${this.prefix}baseline:${endpoint}`);
|
|
617
|
+
return raw ? JSON.parse(raw) : null;
|
|
618
|
+
} catch {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
saveBaseline(endpoint, baseline) {
|
|
623
|
+
if (!this.isAvailable) return;
|
|
624
|
+
try {
|
|
625
|
+
window.localStorage.setItem(
|
|
626
|
+
`${this.prefix}baseline:${endpoint}`,
|
|
627
|
+
JSON.stringify(baseline)
|
|
628
|
+
);
|
|
629
|
+
} catch {
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
loadReport() {
|
|
633
|
+
if (!this.isAvailable) return null;
|
|
634
|
+
try {
|
|
635
|
+
const raw = window.localStorage.getItem(`${this.prefix}report`);
|
|
636
|
+
return raw ? JSON.parse(raw) : null;
|
|
637
|
+
} catch {
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
saveReport(report) {
|
|
642
|
+
if (!this.isAvailable) return;
|
|
643
|
+
try {
|
|
644
|
+
window.localStorage.setItem(`${this.prefix}report`, JSON.stringify(report));
|
|
645
|
+
} catch {
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
// src/index.ts
|
|
651
|
+
function createShapewatch(options = {}) {
|
|
652
|
+
let mode = options.mode || "watch";
|
|
653
|
+
const sampleRate = options.sampleRate ?? 1;
|
|
654
|
+
const customNormalize = options.normalizeEndpoint;
|
|
655
|
+
const onDrift = options.onDrift;
|
|
656
|
+
const baselineManager = new BaselineManager({
|
|
657
|
+
learnSamples: options.learnSamples,
|
|
658
|
+
requiredThreshold: options.requiredThreshold,
|
|
659
|
+
maxDepth: options.maxDepth,
|
|
660
|
+
maxArrayItems: options.maxArrayItems,
|
|
661
|
+
ignorePaths: options.ignorePaths,
|
|
662
|
+
maxEndpoints: options.maxEndpoints
|
|
663
|
+
});
|
|
664
|
+
const reporter = new Reporter(options.maxDriftKeys);
|
|
665
|
+
const storage = options.storage;
|
|
666
|
+
const instance = {
|
|
667
|
+
observe(endpointInput, data) {
|
|
668
|
+
if (mode === "off") {
|
|
669
|
+
return [];
|
|
670
|
+
}
|
|
671
|
+
if (sampleRate < 1 && Math.random() > sampleRate) {
|
|
672
|
+
return [];
|
|
673
|
+
}
|
|
674
|
+
const endpoint = customNormalize ? customNormalize(endpointInput) : normalizeEndpoint(endpointInput);
|
|
675
|
+
let baseline = baselineManager.getBaseline(endpoint);
|
|
676
|
+
if (!baseline && storage) {
|
|
677
|
+
const stored = storage.loadBaseline(endpoint);
|
|
678
|
+
if (stored && !(stored instanceof Promise)) {
|
|
679
|
+
baselineManager.importAll({ [endpoint]: stored });
|
|
680
|
+
baseline = baselineManager.getBaseline(endpoint);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (mode === "learn" || !baseline || !baseline.frozen) {
|
|
684
|
+
const updated = baselineManager.recordSample(endpoint, data);
|
|
685
|
+
if (storage && updated.frozen) {
|
|
686
|
+
storage.saveBaseline(endpoint, updated);
|
|
687
|
+
}
|
|
688
|
+
return [];
|
|
689
|
+
}
|
|
690
|
+
const rawDrifts = compareObservation(endpoint, baseline, data, {
|
|
691
|
+
maxDepth: options.maxDepth,
|
|
692
|
+
maxArrayItems: options.maxArrayItems,
|
|
693
|
+
ignorePaths: options.ignorePaths
|
|
694
|
+
});
|
|
695
|
+
if (rawDrifts.length === 0) {
|
|
696
|
+
return [];
|
|
697
|
+
}
|
|
698
|
+
const recordedDrifts = reporter.recordDrifts(rawDrifts);
|
|
699
|
+
if (storage && storage.saveReport) {
|
|
700
|
+
storage.saveReport(reporter.getReport());
|
|
701
|
+
}
|
|
702
|
+
for (const drift of recordedDrifts) {
|
|
703
|
+
if (onDrift) {
|
|
704
|
+
try {
|
|
705
|
+
onDrift(drift);
|
|
706
|
+
} catch {
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (mode === "strict" && recordedDrifts.length > 0) {
|
|
711
|
+
throw new ShapewatchDriftError(recordedDrifts);
|
|
712
|
+
}
|
|
713
|
+
return recordedDrifts;
|
|
714
|
+
},
|
|
715
|
+
report() {
|
|
716
|
+
return reporter.getReport();
|
|
717
|
+
},
|
|
718
|
+
setMode(newMode) {
|
|
719
|
+
mode = newMode;
|
|
720
|
+
},
|
|
721
|
+
reset(endpoint) {
|
|
722
|
+
baselineManager.reset(endpoint);
|
|
723
|
+
if (!endpoint) {
|
|
724
|
+
reporter.reset();
|
|
725
|
+
}
|
|
726
|
+
},
|
|
727
|
+
exportBaseline(endpoint) {
|
|
728
|
+
return baselineManager.exportAll(endpoint);
|
|
729
|
+
},
|
|
730
|
+
importBaseline(snapshot) {
|
|
731
|
+
baselineManager.importAll(snapshot);
|
|
732
|
+
},
|
|
733
|
+
wrapFetch(fetchImpl) {
|
|
734
|
+
return createFetchWrapper(instance, customNormalize)(fetchImpl);
|
|
735
|
+
},
|
|
736
|
+
axiosInterceptor() {
|
|
737
|
+
return createAxiosInterceptor(instance, customNormalize);
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
return instance;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
exports.BaselineManager = BaselineManager;
|
|
744
|
+
exports.FileStorage = FileStorage;
|
|
745
|
+
exports.LocalStorageAdapter = LocalStorageAdapter;
|
|
746
|
+
exports.MemoryStorage = MemoryStorage;
|
|
747
|
+
exports.Reporter = Reporter;
|
|
748
|
+
exports.ShapewatchDriftError = ShapewatchDriftError;
|
|
749
|
+
exports.buildArrayElementPath = buildArrayElementPath;
|
|
750
|
+
exports.buildObjectPath = buildObjectPath;
|
|
751
|
+
exports.compareObservation = compareObservation;
|
|
752
|
+
exports.createShapewatch = createShapewatch;
|
|
753
|
+
exports.escapePathKey = escapePathKey;
|
|
754
|
+
exports.getTypeString = getTypeString;
|
|
755
|
+
exports.isPathIgnored = isPathIgnored;
|
|
756
|
+
exports.normalizeEndpoint = normalizeEndpoint;
|
|
757
|
+
exports.walkValue = walkValue;
|
|
758
|
+
//# sourceMappingURL=index.cjs.map
|
|
759
|
+
//# sourceMappingURL=index.cjs.map
|