@crvouga/mockingbird-service-easypost 0.1.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/CHANGELOG.md +5 -0
- package/README.md +117 -0
- package/dist/chunk-HWAUA7CP.js +347 -0
- package/dist/chunk-HWAUA7CP.js.map +7 -0
- package/dist/chunk-SPPBQVDT.js +2633 -0
- package/dist/chunk-SPPBQVDT.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +914 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1238 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +87 -0
|
@@ -0,0 +1,2633 @@
|
|
|
1
|
+
// ../core/dist/clock.js
|
|
2
|
+
var createClock = (source = Date.now) => {
|
|
3
|
+
let offsetMs = 0;
|
|
4
|
+
let frozenAt;
|
|
5
|
+
const now = () => frozenAt ?? source() + offsetMs;
|
|
6
|
+
return {
|
|
7
|
+
now,
|
|
8
|
+
set: (epochMs) => {
|
|
9
|
+
if (frozenAt !== void 0)
|
|
10
|
+
frozenAt = epochMs;
|
|
11
|
+
else
|
|
12
|
+
offsetMs = epochMs - source();
|
|
13
|
+
},
|
|
14
|
+
advance: (deltaMs) => {
|
|
15
|
+
if (frozenAt !== void 0)
|
|
16
|
+
frozenAt += deltaMs;
|
|
17
|
+
else
|
|
18
|
+
offsetMs += deltaMs;
|
|
19
|
+
},
|
|
20
|
+
freeze: () => {
|
|
21
|
+
frozenAt = now();
|
|
22
|
+
},
|
|
23
|
+
unfreeze: () => {
|
|
24
|
+
if (frozenAt === void 0)
|
|
25
|
+
return;
|
|
26
|
+
offsetMs = frozenAt - source();
|
|
27
|
+
frozenAt = void 0;
|
|
28
|
+
},
|
|
29
|
+
reset: () => {
|
|
30
|
+
offsetMs = 0;
|
|
31
|
+
frozenAt = void 0;
|
|
32
|
+
},
|
|
33
|
+
state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// ../core/dist/collection.js
|
|
38
|
+
var Collection = class {
|
|
39
|
+
sqlite;
|
|
40
|
+
namespace;
|
|
41
|
+
name;
|
|
42
|
+
constructor(sqlite, namespace, name) {
|
|
43
|
+
this.sqlite = sqlite;
|
|
44
|
+
this.namespace = namespace;
|
|
45
|
+
this.name = name;
|
|
46
|
+
}
|
|
47
|
+
bumpCollectionSeq() {
|
|
48
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
|
|
49
|
+
const next = (row?.value ?? 0) + 1;
|
|
50
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
|
|
51
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
|
|
52
|
+
return next;
|
|
53
|
+
}
|
|
54
|
+
nextSequence() {
|
|
55
|
+
return this.sqlite.transaction(() => this.bumpCollectionSeq());
|
|
56
|
+
}
|
|
57
|
+
get(id) {
|
|
58
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
59
|
+
if (!row)
|
|
60
|
+
return void 0;
|
|
61
|
+
return JSON.parse(row.value).value;
|
|
62
|
+
}
|
|
63
|
+
has(id) {
|
|
64
|
+
const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
65
|
+
return row !== void 0;
|
|
66
|
+
}
|
|
67
|
+
/** Insert a new record, assigning it the next sequence number. */
|
|
68
|
+
insert(id, value) {
|
|
69
|
+
return this.sqlite.transaction(() => {
|
|
70
|
+
const seq = this.bumpCollectionSeq();
|
|
71
|
+
const stored = { seq, value };
|
|
72
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
|
|
73
|
+
VALUES (?, ?, ?, ?, ?)
|
|
74
|
+
ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
|
|
75
|
+
return stored;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** Replace an existing record's value, keeping its position. */
|
|
79
|
+
update(id, value) {
|
|
80
|
+
return this.sqlite.transaction(() => {
|
|
81
|
+
const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
82
|
+
if (!row)
|
|
83
|
+
return void 0;
|
|
84
|
+
const stored = { seq: row.seq, value };
|
|
85
|
+
this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
|
|
86
|
+
return stored;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
delete(id) {
|
|
90
|
+
const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
|
|
91
|
+
return result.changes > 0;
|
|
92
|
+
}
|
|
93
|
+
/** How many records the collection holds, without reading them. */
|
|
94
|
+
count() {
|
|
95
|
+
const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
|
|
96
|
+
return Number(row?.n ?? 0);
|
|
97
|
+
}
|
|
98
|
+
list(options = {}) {
|
|
99
|
+
const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const row of rows) {
|
|
102
|
+
const stored = JSON.parse(row.value);
|
|
103
|
+
if (options.where && !options.where(stored.value, stored.seq))
|
|
104
|
+
continue;
|
|
105
|
+
out.push({ id: row.id, seq: stored.seq, value: stored.value });
|
|
106
|
+
}
|
|
107
|
+
out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// ../core/dist/control.js
|
|
113
|
+
var HEALTH_PATH = "/health";
|
|
114
|
+
var ADMIN_PREFIX = "/__admin";
|
|
115
|
+
var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
|
|
116
|
+
var NAMESPACE_HEADER = "x-mockingbird-namespace";
|
|
117
|
+
var json = (status, body) => new Response(JSON.stringify(body), {
|
|
118
|
+
status,
|
|
119
|
+
headers: { "content-type": "application/json" }
|
|
120
|
+
});
|
|
121
|
+
var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
|
|
122
|
+
var UNITS = {
|
|
123
|
+
ms: 1,
|
|
124
|
+
s: 1e3,
|
|
125
|
+
m: 6e4,
|
|
126
|
+
h: 36e5,
|
|
127
|
+
d: 864e5
|
|
128
|
+
};
|
|
129
|
+
var parseDuration = (value) => {
|
|
130
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
131
|
+
return value;
|
|
132
|
+
if (typeof value !== "string")
|
|
133
|
+
return void 0;
|
|
134
|
+
const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
|
|
135
|
+
if (!match)
|
|
136
|
+
return void 0;
|
|
137
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
138
|
+
};
|
|
139
|
+
var parseInstant = (value) => {
|
|
140
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
141
|
+
return value;
|
|
142
|
+
if (typeof value !== "string")
|
|
143
|
+
return void 0;
|
|
144
|
+
const parsed = Date.parse(value);
|
|
145
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
146
|
+
};
|
|
147
|
+
var matchRoute = (pattern, path) => {
|
|
148
|
+
const want = pattern.split("/").filter(Boolean);
|
|
149
|
+
const have = path.split("/").filter(Boolean);
|
|
150
|
+
if (want.length !== have.length)
|
|
151
|
+
return void 0;
|
|
152
|
+
const params = {};
|
|
153
|
+
for (let i = 0; i < want.length; i++) {
|
|
154
|
+
const segment = want[i];
|
|
155
|
+
const actual = have[i];
|
|
156
|
+
if (segment.startsWith(":"))
|
|
157
|
+
params[segment.slice(1)] = decodeURIComponent(actual);
|
|
158
|
+
else if (segment !== actual)
|
|
159
|
+
return void 0;
|
|
160
|
+
}
|
|
161
|
+
return params;
|
|
162
|
+
};
|
|
163
|
+
var readJson = async (request) => {
|
|
164
|
+
const text = await request.text();
|
|
165
|
+
if (text.trim() === "")
|
|
166
|
+
return void 0;
|
|
167
|
+
return JSON.parse(text);
|
|
168
|
+
};
|
|
169
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
170
|
+
var createControlPlane = (context) => {
|
|
171
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
172
|
+
let snapshotCounter = 0;
|
|
173
|
+
const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
|
|
174
|
+
const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
|
|
175
|
+
const builtin = {
|
|
176
|
+
"GET /": () => json(200, {
|
|
177
|
+
service: context.name,
|
|
178
|
+
routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
|
|
179
|
+
}),
|
|
180
|
+
"POST /reset": async ({ url, namespace }) => {
|
|
181
|
+
const target = url.searchParams.get("all") === "1" ? "*" : namespace;
|
|
182
|
+
await context.reset(target);
|
|
183
|
+
return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
|
|
184
|
+
},
|
|
185
|
+
"GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
|
|
186
|
+
"GET /clock": () => json(200, context.clock.state()),
|
|
187
|
+
"POST /clock": ({ body }) => {
|
|
188
|
+
if (!isRecord(body))
|
|
189
|
+
return adminError(400, "expected a JSON object");
|
|
190
|
+
if (body.reset === true)
|
|
191
|
+
context.clock.reset();
|
|
192
|
+
if (body.set !== void 0) {
|
|
193
|
+
const instant = parseInstant(body.set);
|
|
194
|
+
if (instant === void 0)
|
|
195
|
+
return adminError(400, "set: expected epoch ms or ISO-8601");
|
|
196
|
+
context.clock.set(instant);
|
|
197
|
+
}
|
|
198
|
+
if (body.advance !== void 0) {
|
|
199
|
+
const delta = parseDuration(body.advance);
|
|
200
|
+
if (delta === void 0)
|
|
201
|
+
return adminError(400, 'advance: expected ms or "15m"-style');
|
|
202
|
+
context.clock.advance(delta);
|
|
203
|
+
}
|
|
204
|
+
if (body.freeze === true)
|
|
205
|
+
context.clock.freeze();
|
|
206
|
+
if (body.freeze === false)
|
|
207
|
+
context.clock.unfreeze();
|
|
208
|
+
return json(200, context.clock.state());
|
|
209
|
+
},
|
|
210
|
+
"GET /faults": () => json(200, { faults: context.faults.list() }),
|
|
211
|
+
"POST /faults": ({ body, namespace }) => {
|
|
212
|
+
if (isRecord(body) && typeof body.preset === "string") {
|
|
213
|
+
if (!context.applyPreset)
|
|
214
|
+
return adminError(400, `${context.name} has no fault presets`);
|
|
215
|
+
const { preset, ...overrides } = body;
|
|
216
|
+
try {
|
|
217
|
+
return json(201, {
|
|
218
|
+
preset,
|
|
219
|
+
rules: context.applyPreset(preset, namespace, overrides)
|
|
220
|
+
});
|
|
221
|
+
} catch (error) {
|
|
222
|
+
return adminError(404, error instanceof Error ? error.message : String(error));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
|
|
226
|
+
return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
|
|
227
|
+
}
|
|
228
|
+
const rule = {
|
|
229
|
+
// Scoped to the caller's namespace unless it asks for every one, so one worker's
|
|
230
|
+
// injected failure never lands on another's request.
|
|
231
|
+
namespace,
|
|
232
|
+
...body,
|
|
233
|
+
id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
|
|
234
|
+
};
|
|
235
|
+
return json(201, context.faults.add(rule));
|
|
236
|
+
},
|
|
237
|
+
"DELETE /faults": ({ url }) => {
|
|
238
|
+
const id = url.searchParams.get("id");
|
|
239
|
+
if (id === null) {
|
|
240
|
+
context.faults.clear();
|
|
241
|
+
return json(200, { status: "ok" });
|
|
242
|
+
}
|
|
243
|
+
return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
|
|
244
|
+
},
|
|
245
|
+
"POST /snapshots": ({ namespace }) => {
|
|
246
|
+
const point = context.timeTravel.checkpoint(namespace, "main");
|
|
247
|
+
context.timeTravel.retain(namespace, point.id);
|
|
248
|
+
snapshotCounter++;
|
|
249
|
+
const id = `snap_${snapshotCounter}`;
|
|
250
|
+
snapshots.set(id, { namespace, checkpoint: point.id });
|
|
251
|
+
return json(201, { id, namespace, records: point.records ?? 0 });
|
|
252
|
+
},
|
|
253
|
+
"POST /snapshots/:id/restore": ({ params, namespace }) => {
|
|
254
|
+
const alias = snapshots.get(params.id);
|
|
255
|
+
if (!alias)
|
|
256
|
+
return adminError(404, `no snapshot ${params.id}`);
|
|
257
|
+
if (alias.namespace !== namespace) {
|
|
258
|
+
return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
|
|
259
|
+
}
|
|
260
|
+
context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
|
|
261
|
+
return json(200, { status: "ok", id: params.id, namespace });
|
|
262
|
+
},
|
|
263
|
+
"DELETE /snapshots/:id": ({ params }) => {
|
|
264
|
+
const id = params.id;
|
|
265
|
+
const alias = snapshots.get(id);
|
|
266
|
+
if (!alias)
|
|
267
|
+
return adminError(404, `no snapshot ${id}`);
|
|
268
|
+
snapshots.delete(id);
|
|
269
|
+
context.timeTravel.release(alias.namespace, alias.checkpoint);
|
|
270
|
+
return json(200, { status: "ok" });
|
|
271
|
+
},
|
|
272
|
+
"GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
|
|
273
|
+
"POST /checkpoints": ({ body, namespace }) => {
|
|
274
|
+
const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
|
|
275
|
+
try {
|
|
276
|
+
return json(201, context.timeTravel.checkpoint(namespace, branch));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
"POST /branches/:name": ({ params, body, namespace }) => {
|
|
282
|
+
const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
|
|
283
|
+
try {
|
|
284
|
+
return json(201, context.timeTravel.branch(params.name, {
|
|
285
|
+
namespace,
|
|
286
|
+
...at !== void 0 ? { at } : {}
|
|
287
|
+
}));
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
"POST /branches/:name/checkout": ({ params, body, namespace }) => {
|
|
293
|
+
if (!isRecord(body) || typeof body.checkpoint !== "string") {
|
|
294
|
+
return adminError(400, 'expected {"checkpoint":"cp_..."}');
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
context.timeTravel.checkout(body.checkpoint, {
|
|
298
|
+
namespace,
|
|
299
|
+
branch: params.name
|
|
300
|
+
});
|
|
301
|
+
return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
|
|
302
|
+
} catch (error) {
|
|
303
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
"GET /requests": ({ url, namespace }) => {
|
|
307
|
+
const status = url.searchParams.get("status");
|
|
308
|
+
const since = url.searchParams.get("since");
|
|
309
|
+
const limit = url.searchParams.get("limit");
|
|
310
|
+
const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
|
|
311
|
+
if (since !== null && sinceMs === void 0) {
|
|
312
|
+
return adminError(400, "since: expected epoch ms or ISO-8601");
|
|
313
|
+
}
|
|
314
|
+
if (status !== null && !/^\d{3}$/.test(status))
|
|
315
|
+
return adminError(400, "status: expected an HTTP status");
|
|
316
|
+
if (limit !== null && !/^\d+$/.test(limit))
|
|
317
|
+
return adminError(400, "limit: expected a count");
|
|
318
|
+
const operationId = url.searchParams.get("operationId");
|
|
319
|
+
const everyNamespace = url.searchParams.get("all") === "1";
|
|
320
|
+
return json(200, {
|
|
321
|
+
size: context.journal.size,
|
|
322
|
+
requests: context.journal.list({
|
|
323
|
+
...everyNamespace ? {} : { namespace },
|
|
324
|
+
...operationId !== null ? { operationId } : {},
|
|
325
|
+
...status !== null ? { status: Number(status) } : {},
|
|
326
|
+
...sinceMs !== void 0 ? { since: sinceMs } : {},
|
|
327
|
+
...limit !== null ? { limit: Number(limit) } : {}
|
|
328
|
+
})
|
|
329
|
+
});
|
|
330
|
+
},
|
|
331
|
+
"DELETE /requests": ({ url, namespace }) => {
|
|
332
|
+
context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
|
|
333
|
+
return json(200, { status: "ok" });
|
|
334
|
+
},
|
|
335
|
+
"GET /metrics": () => json(200, context.metrics.report()),
|
|
336
|
+
"DELETE /metrics": () => {
|
|
337
|
+
context.metrics.reset();
|
|
338
|
+
return json(200, { status: "ok" });
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
|
|
342
|
+
const space = key.indexOf(" ");
|
|
343
|
+
return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
|
|
344
|
+
});
|
|
345
|
+
return {
|
|
346
|
+
namespaceOf: headerNamespace,
|
|
347
|
+
async handle(request) {
|
|
348
|
+
const url = new URL(request.url);
|
|
349
|
+
if (url.pathname === HEALTH_PATH && request.method === "GET") {
|
|
350
|
+
return json(200, {
|
|
351
|
+
status: "ok",
|
|
352
|
+
service: context.name,
|
|
353
|
+
uptimeMs: context.wallNow() - context.startedAt,
|
|
354
|
+
clock: context.clock.state(),
|
|
355
|
+
namespaces: context.namespaces().length,
|
|
356
|
+
...context.describe()
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
|
|
360
|
+
return void 0;
|
|
361
|
+
}
|
|
362
|
+
if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
|
|
363
|
+
return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
|
|
364
|
+
}
|
|
365
|
+
const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
|
|
366
|
+
for (const route of routes) {
|
|
367
|
+
if (route.method !== request.method)
|
|
368
|
+
continue;
|
|
369
|
+
const params = matchRoute(route.pattern, path);
|
|
370
|
+
if (!params)
|
|
371
|
+
continue;
|
|
372
|
+
let body;
|
|
373
|
+
try {
|
|
374
|
+
body = await readJson(request);
|
|
375
|
+
} catch {
|
|
376
|
+
return adminError(400, "request body is not valid JSON");
|
|
377
|
+
}
|
|
378
|
+
return route.handler({
|
|
379
|
+
request,
|
|
380
|
+
url,
|
|
381
|
+
params,
|
|
382
|
+
namespace: adminNamespace(request, url),
|
|
383
|
+
body
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// ../core/dist/credentials.js
|
|
392
|
+
var basicAuth = (request) => {
|
|
393
|
+
const header = request.headers.get("authorization");
|
|
394
|
+
if (!header)
|
|
395
|
+
return void 0;
|
|
396
|
+
const match = /^Basic\s+(.+)$/i.exec(header.trim());
|
|
397
|
+
if (!match?.[1])
|
|
398
|
+
return void 0;
|
|
399
|
+
let decoded;
|
|
400
|
+
try {
|
|
401
|
+
decoded = atob(match[1].trim());
|
|
402
|
+
} catch {
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
const colon = decoded.indexOf(":");
|
|
406
|
+
if (colon < 0)
|
|
407
|
+
return { username: decoded, password: "" };
|
|
408
|
+
return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };
|
|
409
|
+
};
|
|
410
|
+
var createCredentialRegistry = () => {
|
|
411
|
+
const map = /* @__PURE__ */ new Map();
|
|
412
|
+
return {
|
|
413
|
+
set: (credential, namespace) => {
|
|
414
|
+
map.set(credential, namespace);
|
|
415
|
+
},
|
|
416
|
+
get: (credential) => map.get(credential),
|
|
417
|
+
remove: (credential) => map.delete(credential),
|
|
418
|
+
clear: () => map.clear(),
|
|
419
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
423
|
+
|
|
424
|
+
// ../core/dist/rng.js
|
|
425
|
+
var seedFrom = (value) => {
|
|
426
|
+
let hash = 2166136261;
|
|
427
|
+
for (let i = 0; i < value.length; i++) {
|
|
428
|
+
hash ^= value.charCodeAt(i);
|
|
429
|
+
hash = Math.imul(hash, 16777619);
|
|
430
|
+
}
|
|
431
|
+
return hash >>> 0;
|
|
432
|
+
};
|
|
433
|
+
var createRng = (seed = 0) => {
|
|
434
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
435
|
+
let state = numeric;
|
|
436
|
+
const next = () => {
|
|
437
|
+
state = state + 1831565813 >>> 0;
|
|
438
|
+
let t = state;
|
|
439
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
440
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
441
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
442
|
+
};
|
|
443
|
+
return {
|
|
444
|
+
next,
|
|
445
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
446
|
+
reset: () => {
|
|
447
|
+
state = numeric;
|
|
448
|
+
},
|
|
449
|
+
state: () => state,
|
|
450
|
+
setState: (next2) => {
|
|
451
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
452
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
453
|
+
}
|
|
454
|
+
state = next2 >>> 0;
|
|
455
|
+
},
|
|
456
|
+
seed: numeric
|
|
457
|
+
};
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
// ../core/dist/faults.js
|
|
461
|
+
var matches = (rule, candidate) => {
|
|
462
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
466
|
+
return false;
|
|
467
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
471
|
+
return false;
|
|
472
|
+
return true;
|
|
473
|
+
};
|
|
474
|
+
var faultResponse = (rule) => {
|
|
475
|
+
const status = rule.status ?? 500;
|
|
476
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
477
|
+
if (typeof rule.body === "string")
|
|
478
|
+
return new Response(rule.body, { status, headers });
|
|
479
|
+
if (rule.body === null)
|
|
480
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
481
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
482
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
483
|
+
};
|
|
484
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
485
|
+
const entries = [];
|
|
486
|
+
return {
|
|
487
|
+
add(rule) {
|
|
488
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
489
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
490
|
+
if (existing >= 0)
|
|
491
|
+
entries[existing] = entry;
|
|
492
|
+
else
|
|
493
|
+
entries.push(entry);
|
|
494
|
+
return rule;
|
|
495
|
+
},
|
|
496
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
497
|
+
remove(id) {
|
|
498
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
499
|
+
if (index < 0)
|
|
500
|
+
return false;
|
|
501
|
+
entries.splice(index, 1);
|
|
502
|
+
return true;
|
|
503
|
+
},
|
|
504
|
+
clear() {
|
|
505
|
+
entries.length = 0;
|
|
506
|
+
},
|
|
507
|
+
async take(candidate) {
|
|
508
|
+
const hits = [];
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
if (entry.remaining === 0)
|
|
511
|
+
continue;
|
|
512
|
+
if (!matches(entry.rule, candidate))
|
|
513
|
+
continue;
|
|
514
|
+
const rate = entry.rule.rate ?? 1;
|
|
515
|
+
if (rng.next() >= rate)
|
|
516
|
+
continue;
|
|
517
|
+
entry.hits++;
|
|
518
|
+
if (entry.remaining !== null)
|
|
519
|
+
entry.remaining--;
|
|
520
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
521
|
+
if (delay !== void 0 && delay > 0) {
|
|
522
|
+
await sleep(delay);
|
|
523
|
+
}
|
|
524
|
+
const hit = { id: entry.rule.id };
|
|
525
|
+
if (entry.rule.effect !== void 0) {
|
|
526
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
527
|
+
}
|
|
528
|
+
if (entry.rule.drop === true)
|
|
529
|
+
hit.drop = true;
|
|
530
|
+
else if (entry.rule.status !== void 0)
|
|
531
|
+
hit.response = faultResponse(entry.rule);
|
|
532
|
+
hits.push(hit);
|
|
533
|
+
if (hit.drop || hit.response)
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
return hits;
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// ../../openapi/core/dist/refs.js
|
|
542
|
+
var OpenAPIReferenceError = class extends Error {
|
|
543
|
+
ref;
|
|
544
|
+
constructor(ref) {
|
|
545
|
+
super(`unresolvable $ref: ${ref}`);
|
|
546
|
+
this.ref = ref;
|
|
547
|
+
this.name = "OpenAPIReferenceError";
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
551
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
552
|
+
var resolveRef = (document2, ref) => {
|
|
553
|
+
if (!ref.startsWith("#/"))
|
|
554
|
+
throw new OpenAPIReferenceError(ref);
|
|
555
|
+
let cursor = document2;
|
|
556
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
557
|
+
const segment = unescapePointer(raw);
|
|
558
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
559
|
+
throw new OpenAPIReferenceError(ref);
|
|
560
|
+
}
|
|
561
|
+
cursor = cursor[segment];
|
|
562
|
+
}
|
|
563
|
+
if (cursor === void 0)
|
|
564
|
+
throw new OpenAPIReferenceError(ref);
|
|
565
|
+
return cursor;
|
|
566
|
+
};
|
|
567
|
+
var deref = (document2, value) => {
|
|
568
|
+
let current = value;
|
|
569
|
+
const seen = /* @__PURE__ */ new Set();
|
|
570
|
+
while (isReference(current)) {
|
|
571
|
+
if (seen.has(current.$ref))
|
|
572
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
573
|
+
seen.add(current.$ref);
|
|
574
|
+
current = resolveRef(document2, current.$ref);
|
|
575
|
+
}
|
|
576
|
+
return current;
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
// ../../openapi/core/dist/types.js
|
|
580
|
+
var HTTP_METHODS = [
|
|
581
|
+
"get",
|
|
582
|
+
"put",
|
|
583
|
+
"post",
|
|
584
|
+
"delete",
|
|
585
|
+
"options",
|
|
586
|
+
"head",
|
|
587
|
+
"patch",
|
|
588
|
+
"trace"
|
|
589
|
+
];
|
|
590
|
+
|
|
591
|
+
// ../../openapi/core/dist/document.js
|
|
592
|
+
var mergeParameters = (document2, item, own) => {
|
|
593
|
+
const merged = /* @__PURE__ */ new Map();
|
|
594
|
+
for (const raw of item.parameters ?? []) {
|
|
595
|
+
const parameter = deref(document2, raw);
|
|
596
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
597
|
+
}
|
|
598
|
+
for (const raw of own ?? []) {
|
|
599
|
+
const parameter = deref(document2, raw);
|
|
600
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
601
|
+
}
|
|
602
|
+
return [...merged.values()];
|
|
603
|
+
};
|
|
604
|
+
var listOperations = (document2) => {
|
|
605
|
+
const operations = [];
|
|
606
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
607
|
+
for (const method of HTTP_METHODS) {
|
|
608
|
+
const operation = item[method];
|
|
609
|
+
if (operation?.operationId === void 0)
|
|
610
|
+
continue;
|
|
611
|
+
const responses = {};
|
|
612
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
613
|
+
responses[status] = deref(document2, response);
|
|
614
|
+
}
|
|
615
|
+
operations.push({
|
|
616
|
+
operationId: operation.operationId,
|
|
617
|
+
method,
|
|
618
|
+
path,
|
|
619
|
+
operation,
|
|
620
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
621
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
622
|
+
responses
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return operations;
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
// ../../openapi/core/dist/schema.js
|
|
630
|
+
var resolveSchema = (document2, schema) => {
|
|
631
|
+
let current = schema;
|
|
632
|
+
const seen = /* @__PURE__ */ new Set();
|
|
633
|
+
while (typeof current.$ref === "string") {
|
|
634
|
+
const ref = current.$ref;
|
|
635
|
+
if (seen.has(ref))
|
|
636
|
+
break;
|
|
637
|
+
seen.add(ref);
|
|
638
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
639
|
+
const target = resolveRef(document2, ref);
|
|
640
|
+
current = { ...target, ...siblings };
|
|
641
|
+
}
|
|
642
|
+
if (current.nullable === true) {
|
|
643
|
+
const { nullable: _nullable, ...rest } = current;
|
|
644
|
+
const types = schemaTypes(rest);
|
|
645
|
+
if (types.length > 0 && !types.includes("null"))
|
|
646
|
+
current = { ...rest, type: [...types, "null"] };
|
|
647
|
+
else
|
|
648
|
+
current = rest;
|
|
649
|
+
}
|
|
650
|
+
return current;
|
|
651
|
+
};
|
|
652
|
+
var schemaTypes = (schema) => {
|
|
653
|
+
if (Array.isArray(schema.type))
|
|
654
|
+
return schema.type;
|
|
655
|
+
if (schema.type !== void 0)
|
|
656
|
+
return [schema.type];
|
|
657
|
+
const inferred = [];
|
|
658
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
659
|
+
inferred.push("object");
|
|
660
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
661
|
+
inferred.push("array");
|
|
662
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
663
|
+
inferred.push("string");
|
|
664
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
665
|
+
inferred.push("number");
|
|
666
|
+
return inferred;
|
|
667
|
+
};
|
|
668
|
+
var jsonTypeOf = (value) => {
|
|
669
|
+
if (value === null)
|
|
670
|
+
return "null";
|
|
671
|
+
if (Array.isArray(value))
|
|
672
|
+
return "array";
|
|
673
|
+
switch (typeof value) {
|
|
674
|
+
case "string":
|
|
675
|
+
return "string";
|
|
676
|
+
case "boolean":
|
|
677
|
+
return "boolean";
|
|
678
|
+
case "number":
|
|
679
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
680
|
+
case "object":
|
|
681
|
+
return "object";
|
|
682
|
+
default:
|
|
683
|
+
return "undefined";
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
var deepEqual = (a, b) => {
|
|
687
|
+
if (a === b)
|
|
688
|
+
return true;
|
|
689
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
690
|
+
return false;
|
|
691
|
+
if (Array.isArray(a)) {
|
|
692
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
693
|
+
}
|
|
694
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
695
|
+
const ka = Object.keys(a);
|
|
696
|
+
const kb = Object.keys(b);
|
|
697
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
698
|
+
}
|
|
699
|
+
return false;
|
|
700
|
+
};
|
|
701
|
+
var FORMAT_PATTERNS = {
|
|
702
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
|
703
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
704
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
705
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
706
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
707
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
708
|
+
};
|
|
709
|
+
var graphemeLength = (value) => [...value].length;
|
|
710
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
711
|
+
const errors = [];
|
|
712
|
+
const s = resolveSchema(document2, schema);
|
|
713
|
+
const fail2 = (message) => errors.push({ path, message });
|
|
714
|
+
const actual = jsonTypeOf(value);
|
|
715
|
+
if (actual === "undefined") {
|
|
716
|
+
fail2("value is undefined");
|
|
717
|
+
return errors;
|
|
718
|
+
}
|
|
719
|
+
const types = schemaTypes(s);
|
|
720
|
+
if (types.length > 0) {
|
|
721
|
+
const ok2 = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
722
|
+
if (!ok2) {
|
|
723
|
+
fail2(`expected type ${types.join("|")}, got ${actual}`);
|
|
724
|
+
return errors;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
728
|
+
fail2("value not in enum");
|
|
729
|
+
}
|
|
730
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
731
|
+
fail2("value does not equal const");
|
|
732
|
+
if (typeof value === "string") {
|
|
733
|
+
const length = graphemeLength(value);
|
|
734
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
735
|
+
fail2(`length ${length} < minLength ${s.minLength}`);
|
|
736
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
737
|
+
fail2(`length ${length} > maxLength ${s.maxLength}`);
|
|
738
|
+
if (s.pattern !== void 0) {
|
|
739
|
+
try {
|
|
740
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
741
|
+
fail2(`does not match pattern ${s.pattern}`);
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (s.format !== void 0) {
|
|
746
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
747
|
+
if (pattern && !pattern.test(value))
|
|
748
|
+
fail2(`does not match format ${s.format}`);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (typeof value === "number") {
|
|
752
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
753
|
+
fail2(`${value} < minimum ${s.minimum}`);
|
|
754
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
755
|
+
fail2(`${value} > maximum ${s.maximum}`);
|
|
756
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
757
|
+
fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
758
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
759
|
+
fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
760
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
761
|
+
fail2(`${value} is not a multiple of ${s.multipleOf}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (Array.isArray(value)) {
|
|
765
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
766
|
+
fail2(`${value.length} items < minItems ${s.minItems}`);
|
|
767
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
768
|
+
fail2(`${value.length} items > maxItems ${s.maxItems}`);
|
|
769
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
770
|
+
fail2("items are not unique");
|
|
771
|
+
value.forEach((item, i) => {
|
|
772
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
773
|
+
if (itemSchema)
|
|
774
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
if (actual === "object") {
|
|
778
|
+
const record = value;
|
|
779
|
+
const keys = Object.keys(record);
|
|
780
|
+
for (const name of s.required ?? [])
|
|
781
|
+
if (!(name in record))
|
|
782
|
+
fail2(`missing required property ${name}`);
|
|
783
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
784
|
+
fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
785
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
786
|
+
fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
787
|
+
for (const key of keys) {
|
|
788
|
+
const property = s.properties?.[key];
|
|
789
|
+
if (property) {
|
|
790
|
+
errors.push(...validateValue(document2, property, record[key], [...path, key]));
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (s.additionalProperties === false)
|
|
794
|
+
fail2(`unexpected property ${key}`);
|
|
795
|
+
else if (typeof s.additionalProperties === "object") {
|
|
796
|
+
errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
|
|
797
|
+
}
|
|
798
|
+
if (s.propertyNames) {
|
|
799
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
800
|
+
if (nameErrors.length > 0)
|
|
801
|
+
fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
if (s.allOf)
|
|
806
|
+
for (const branch of s.allOf)
|
|
807
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
808
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
809
|
+
fail2("matches no anyOf branch");
|
|
810
|
+
if (s.oneOf) {
|
|
811
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
812
|
+
if (matches2 !== 1)
|
|
813
|
+
fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
814
|
+
}
|
|
815
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
816
|
+
fail2("matches forbidden `not` schema");
|
|
817
|
+
return errors;
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
// ../../http/codec/dist/form.js
|
|
821
|
+
var parsePath = (rawKey) => {
|
|
822
|
+
const open = rawKey.indexOf("[");
|
|
823
|
+
if (open === -1)
|
|
824
|
+
return [rawKey];
|
|
825
|
+
const path = [rawKey.slice(0, open)];
|
|
826
|
+
const rest = rawKey.slice(open);
|
|
827
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
828
|
+
let match = pattern.exec(rest);
|
|
829
|
+
let consumed = 0;
|
|
830
|
+
while (match !== null) {
|
|
831
|
+
if (match.index !== consumed)
|
|
832
|
+
return [rawKey];
|
|
833
|
+
path.push(match[1] ?? "");
|
|
834
|
+
consumed = match.index + match[0].length;
|
|
835
|
+
match = pattern.exec(rest);
|
|
836
|
+
}
|
|
837
|
+
if (consumed !== rest.length)
|
|
838
|
+
return [rawKey];
|
|
839
|
+
return path;
|
|
840
|
+
};
|
|
841
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
842
|
+
var put = (target, key, value) => {
|
|
843
|
+
if (key === "__proto__") {
|
|
844
|
+
Object.defineProperty(target, key, {
|
|
845
|
+
value,
|
|
846
|
+
enumerable: true,
|
|
847
|
+
writable: true,
|
|
848
|
+
configurable: true
|
|
849
|
+
});
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
;
|
|
853
|
+
target[key] = value;
|
|
854
|
+
};
|
|
855
|
+
var assign = (target, path, value) => {
|
|
856
|
+
let cursor = target;
|
|
857
|
+
for (let i = 0; i < path.length; i++) {
|
|
858
|
+
const segment = path[i];
|
|
859
|
+
const last = i === path.length - 1;
|
|
860
|
+
if (Array.isArray(cursor)) {
|
|
861
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
862
|
+
if (index === void 0)
|
|
863
|
+
return;
|
|
864
|
+
if (last) {
|
|
865
|
+
put(cursor, index, value);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
869
|
+
if (next === void 0 || typeof next === "string") {
|
|
870
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
871
|
+
put(cursor, index, created);
|
|
872
|
+
cursor = created;
|
|
873
|
+
} else {
|
|
874
|
+
cursor = next;
|
|
875
|
+
}
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
if (typeof cursor === "string")
|
|
879
|
+
return;
|
|
880
|
+
if (last) {
|
|
881
|
+
put(cursor, segment, value);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const nextSegment = path[i + 1];
|
|
885
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
886
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
887
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
888
|
+
put(cursor, segment, created);
|
|
889
|
+
cursor = created;
|
|
890
|
+
} else {
|
|
891
|
+
cursor = existing;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
var decodeFormPairs = (pairs) => {
|
|
896
|
+
const out = {};
|
|
897
|
+
for (const [rawKey, value] of pairs)
|
|
898
|
+
assign(out, parsePath(rawKey), value);
|
|
899
|
+
return densify(out);
|
|
900
|
+
};
|
|
901
|
+
var densify = (value) => {
|
|
902
|
+
if (typeof value === "string")
|
|
903
|
+
return value;
|
|
904
|
+
if (Array.isArray(value))
|
|
905
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
906
|
+
const out = {};
|
|
907
|
+
for (const [key, item] of Object.entries(value))
|
|
908
|
+
put(out, key, densify(item));
|
|
909
|
+
return out;
|
|
910
|
+
};
|
|
911
|
+
var decodeForm = (text) => {
|
|
912
|
+
const source = text.startsWith("?") ? text.slice(1) : text;
|
|
913
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
// ../../http/codec/dist/content.js
|
|
917
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
918
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
919
|
+
var mediaTypeOf = (contentType) => {
|
|
920
|
+
if (!contentType)
|
|
921
|
+
return void 0;
|
|
922
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
923
|
+
return essence ? essence : void 0;
|
|
924
|
+
};
|
|
925
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
926
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
927
|
+
var decodeBody = (contentType, bytes) => {
|
|
928
|
+
if (bytes.byteLength === 0)
|
|
929
|
+
return { kind: "empty" };
|
|
930
|
+
const mediaType = mediaTypeOf(contentType);
|
|
931
|
+
if (mediaType === void 0)
|
|
932
|
+
return { kind: "bytes", value: bytes };
|
|
933
|
+
if (isJsonMediaType(mediaType)) {
|
|
934
|
+
const text = utf8.decode(bytes);
|
|
935
|
+
try {
|
|
936
|
+
return { kind: "json", value: JSON.parse(text) };
|
|
937
|
+
} catch (error) {
|
|
938
|
+
return {
|
|
939
|
+
kind: "invalid",
|
|
940
|
+
mediaType,
|
|
941
|
+
text,
|
|
942
|
+
error: error instanceof Error ? error.message : String(error)
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
947
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
948
|
+
}
|
|
949
|
+
if (mediaType.startsWith("text/"))
|
|
950
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
951
|
+
return { kind: "bytes", value: bytes };
|
|
952
|
+
};
|
|
953
|
+
var readBody = async (message) => {
|
|
954
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
955
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// ../core/dist/http.js
|
|
959
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
960
|
+
status,
|
|
961
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
962
|
+
});
|
|
963
|
+
var HttpError = class extends Error {
|
|
964
|
+
status;
|
|
965
|
+
body;
|
|
966
|
+
headers;
|
|
967
|
+
constructor(status, body, headers = {}) {
|
|
968
|
+
super(`HTTP ${status}`);
|
|
969
|
+
this.status = status;
|
|
970
|
+
this.body = body;
|
|
971
|
+
this.headers = headers;
|
|
972
|
+
this.name = "HttpError";
|
|
973
|
+
}
|
|
974
|
+
toResponse() {
|
|
975
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
976
|
+
if (contentType === "text/plain") {
|
|
977
|
+
return new Response(String(this.body), {
|
|
978
|
+
status: this.status,
|
|
979
|
+
headers: this.headers
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
var ok = (value) => ({ ok: true, value });
|
|
986
|
+
var fail = (reason) => ({ ok: false, reason });
|
|
987
|
+
var coerce = {
|
|
988
|
+
string(value) {
|
|
989
|
+
return typeof value === "string" ? ok(value) : fail("expected a string");
|
|
990
|
+
},
|
|
991
|
+
integer(value) {
|
|
992
|
+
if (typeof value === "number" && Number.isInteger(value))
|
|
993
|
+
return ok(value);
|
|
994
|
+
if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
|
|
995
|
+
const parsed = Number(value);
|
|
996
|
+
return Number.isSafeInteger(parsed) ? ok(parsed) : fail("integer out of range");
|
|
997
|
+
}
|
|
998
|
+
return fail("expected an integer");
|
|
999
|
+
},
|
|
1000
|
+
boolean(value) {
|
|
1001
|
+
if (typeof value === "boolean")
|
|
1002
|
+
return ok(value);
|
|
1003
|
+
if (value === "true" || value === "1")
|
|
1004
|
+
return ok(true);
|
|
1005
|
+
if (value === "false" || value === "0")
|
|
1006
|
+
return ok(false);
|
|
1007
|
+
return fail("expected a boolean");
|
|
1008
|
+
},
|
|
1009
|
+
enumeration(value, allowed) {
|
|
1010
|
+
const match = allowed.find((candidate) => candidate === value);
|
|
1011
|
+
return match === void 0 ? fail(`expected one of ${allowed.join(", ")}`) : ok(match);
|
|
1012
|
+
},
|
|
1013
|
+
/** Flat string-to-string map, the shape of Stripe-style `metadata`. */
|
|
1014
|
+
stringMap(value) {
|
|
1015
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
1016
|
+
return fail("expected an object");
|
|
1017
|
+
const out = {};
|
|
1018
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1019
|
+
if (typeof item !== "string")
|
|
1020
|
+
return fail(`expected a string at ${key}`);
|
|
1021
|
+
out[key] = item;
|
|
1022
|
+
}
|
|
1023
|
+
return ok(out);
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
// ../core/dist/ids.js
|
|
1028
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
1029
|
+
var mix = (input) => {
|
|
1030
|
+
let hash = 2166136261;
|
|
1031
|
+
for (let i = 0; i < input.length; i++) {
|
|
1032
|
+
hash ^= input.charCodeAt(i);
|
|
1033
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
1034
|
+
}
|
|
1035
|
+
hash ^= hash >>> 16;
|
|
1036
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
1037
|
+
hash ^= hash >>> 13;
|
|
1038
|
+
return hash >>> 0;
|
|
1039
|
+
};
|
|
1040
|
+
var opaqueToken = (input, length) => {
|
|
1041
|
+
let out = "";
|
|
1042
|
+
let round = 0;
|
|
1043
|
+
while (out.length < length) {
|
|
1044
|
+
let hash = mix(`${input}:${round++}`);
|
|
1045
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
1046
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
1047
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return out;
|
|
1051
|
+
};
|
|
1052
|
+
var IdSequence = class {
|
|
1053
|
+
sqlite;
|
|
1054
|
+
namespace;
|
|
1055
|
+
salt;
|
|
1056
|
+
constructor(sqlite, namespace, salt = "mockingbird") {
|
|
1057
|
+
this.sqlite = sqlite;
|
|
1058
|
+
this.namespace = namespace;
|
|
1059
|
+
this.salt = salt;
|
|
1060
|
+
}
|
|
1061
|
+
next(prefix, length = 14) {
|
|
1062
|
+
return this.sqlite.transaction(() => {
|
|
1063
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
|
|
1064
|
+
const value = (row?.value ?? 0) + 1;
|
|
1065
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
|
|
1066
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
|
|
1067
|
+
return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
|
|
1072
|
+
// ../core/dist/journal.js
|
|
1073
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1074
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1075
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1076
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1077
|
+
let sequence = 0;
|
|
1078
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1079
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1080
|
+
return {
|
|
1081
|
+
size: capacity,
|
|
1082
|
+
record(entry) {
|
|
1083
|
+
if (capacity === 0)
|
|
1084
|
+
return;
|
|
1085
|
+
order.set(entry, sequence++);
|
|
1086
|
+
let ring = rings.get(entry.namespace);
|
|
1087
|
+
if (!ring) {
|
|
1088
|
+
ring = { entries: [], next: 0 };
|
|
1089
|
+
rings.set(entry.namespace, ring);
|
|
1090
|
+
}
|
|
1091
|
+
if (ring.entries.length < capacity)
|
|
1092
|
+
ring.entries.push(entry);
|
|
1093
|
+
else {
|
|
1094
|
+
ring.entries[ring.next] = entry;
|
|
1095
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1096
|
+
}
|
|
1097
|
+
},
|
|
1098
|
+
list(query = {}) {
|
|
1099
|
+
const source = query.namespace !== void 0 ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 }) : [...rings.values()].flatMap(inOrder).sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
|
|
1100
|
+
const matched = source.filter((entry) => (query.operationId === void 0 || entry.operationId === query.operationId) && (query.status === void 0 || entry.status === query.status) && (query.since === void 0 || Date.parse(entry.at) >= query.since));
|
|
1101
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1102
|
+
},
|
|
1103
|
+
clear(namespace) {
|
|
1104
|
+
if (namespace === void 0)
|
|
1105
|
+
rings.clear();
|
|
1106
|
+
else
|
|
1107
|
+
rings.delete(namespace);
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
};
|
|
1111
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1112
|
+
var annotateResponse = (response, extra) => {
|
|
1113
|
+
const existing = notes.get(response);
|
|
1114
|
+
notes.set(response, {
|
|
1115
|
+
...existing,
|
|
1116
|
+
...extra,
|
|
1117
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1118
|
+
});
|
|
1119
|
+
return response;
|
|
1120
|
+
};
|
|
1121
|
+
var responseNotes = (response) => notes.get(response);
|
|
1122
|
+
|
|
1123
|
+
// ../core/dist/metrics.js
|
|
1124
|
+
var createMetrics = () => {
|
|
1125
|
+
let requests = 0;
|
|
1126
|
+
let faults = 0;
|
|
1127
|
+
let totalDurationMs = 0;
|
|
1128
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1129
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1130
|
+
return {
|
|
1131
|
+
record(entry) {
|
|
1132
|
+
requests++;
|
|
1133
|
+
totalDurationMs += entry.durationMs;
|
|
1134
|
+
if (entry.faultId !== void 0)
|
|
1135
|
+
faults++;
|
|
1136
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1137
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1138
|
+
if (entry.unmatched) {
|
|
1139
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1140
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1141
|
+
}
|
|
1142
|
+
},
|
|
1143
|
+
report: () => ({
|
|
1144
|
+
requests,
|
|
1145
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1146
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1147
|
+
const space = route.indexOf(" ");
|
|
1148
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1149
|
+
}),
|
|
1150
|
+
faults,
|
|
1151
|
+
totalDurationMs
|
|
1152
|
+
}),
|
|
1153
|
+
reset() {
|
|
1154
|
+
requests = 0;
|
|
1155
|
+
faults = 0;
|
|
1156
|
+
totalDurationMs = 0;
|
|
1157
|
+
byOperation.clear();
|
|
1158
|
+
unmatched.clear();
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
};
|
|
1162
|
+
|
|
1163
|
+
// ../../core/dist/timeline.js
|
|
1164
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1165
|
+
var Timeline = class {
|
|
1166
|
+
maxCheckpoints;
|
|
1167
|
+
now;
|
|
1168
|
+
makeId;
|
|
1169
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1170
|
+
heads = /* @__PURE__ */ new Map();
|
|
1171
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1172
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1173
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1174
|
+
references = /* @__PURE__ */ new Map();
|
|
1175
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1176
|
+
sequence = 0;
|
|
1177
|
+
constructor(options = {}) {
|
|
1178
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1179
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1180
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1181
|
+
this.maxCheckpoints = max;
|
|
1182
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1183
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1184
|
+
}
|
|
1185
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1186
|
+
commit(value, options = {}) {
|
|
1187
|
+
const branch = options.branch ?? "main";
|
|
1188
|
+
this.assertBranch(branch);
|
|
1189
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1190
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1191
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1192
|
+
const id = this.makeId(++this.sequence);
|
|
1193
|
+
if (this.nodes.has(id))
|
|
1194
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1195
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1196
|
+
this.nodes.set(id, checkpoint);
|
|
1197
|
+
this.moveHead(branch, id);
|
|
1198
|
+
this.collect(this.maxCheckpoints);
|
|
1199
|
+
return checkpoint;
|
|
1200
|
+
}
|
|
1201
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1202
|
+
fork(branch, options = {}) {
|
|
1203
|
+
this.assertBranch(branch);
|
|
1204
|
+
if (this.heads.has(branch))
|
|
1205
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1206
|
+
const from = options.from ?? this.heads.get("main");
|
|
1207
|
+
if (from === void 0)
|
|
1208
|
+
return void 0;
|
|
1209
|
+
const checkpoint = this.get(from);
|
|
1210
|
+
this.moveHead(branch, checkpoint.id);
|
|
1211
|
+
return checkpoint;
|
|
1212
|
+
}
|
|
1213
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1214
|
+
checkout(branch, id) {
|
|
1215
|
+
this.assertBranch(branch);
|
|
1216
|
+
const checkpoint = this.get(id);
|
|
1217
|
+
this.moveHead(branch, checkpoint.id);
|
|
1218
|
+
return checkpoint;
|
|
1219
|
+
}
|
|
1220
|
+
get(id) {
|
|
1221
|
+
const checkpoint = this.nodes.get(id);
|
|
1222
|
+
if (!checkpoint)
|
|
1223
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1224
|
+
return checkpoint;
|
|
1225
|
+
}
|
|
1226
|
+
head(branch = "main") {
|
|
1227
|
+
const id = this.heads.get(branch);
|
|
1228
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1229
|
+
}
|
|
1230
|
+
hasBranch(branch) {
|
|
1231
|
+
return this.heads.has(branch);
|
|
1232
|
+
}
|
|
1233
|
+
branches() {
|
|
1234
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1235
|
+
}
|
|
1236
|
+
checkpoints() {
|
|
1237
|
+
return [...this.nodes.values()];
|
|
1238
|
+
}
|
|
1239
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1240
|
+
get size() {
|
|
1241
|
+
return this.nodes.size;
|
|
1242
|
+
}
|
|
1243
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1244
|
+
retain(id) {
|
|
1245
|
+
const checkpoint = this.get(id);
|
|
1246
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1247
|
+
this.addReference(id);
|
|
1248
|
+
return checkpoint;
|
|
1249
|
+
}
|
|
1250
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1251
|
+
release(id) {
|
|
1252
|
+
if (!this.nodes.has(id))
|
|
1253
|
+
return false;
|
|
1254
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1255
|
+
if (pins === 0)
|
|
1256
|
+
return false;
|
|
1257
|
+
if (pins === 1)
|
|
1258
|
+
this.explicitPins.delete(id);
|
|
1259
|
+
else
|
|
1260
|
+
this.explicitPins.set(id, pins - 1);
|
|
1261
|
+
this.removeReference(id);
|
|
1262
|
+
this.collect(this.maxCheckpoints);
|
|
1263
|
+
return true;
|
|
1264
|
+
}
|
|
1265
|
+
deleteBranch(branch) {
|
|
1266
|
+
if (branch === "main")
|
|
1267
|
+
throw new RangeError("cannot delete main branch");
|
|
1268
|
+
const previous = this.heads.get(branch);
|
|
1269
|
+
const deleted = this.heads.delete(branch);
|
|
1270
|
+
if (previous !== void 0)
|
|
1271
|
+
this.removeReference(previous);
|
|
1272
|
+
this.collect(this.maxCheckpoints);
|
|
1273
|
+
return deleted;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1277
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1278
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1279
|
+
*/
|
|
1280
|
+
gc(max = this.maxCheckpoints) {
|
|
1281
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1282
|
+
throw new RangeError("max must be a positive integer");
|
|
1283
|
+
const removed = [];
|
|
1284
|
+
this.collect(max, removed);
|
|
1285
|
+
return removed;
|
|
1286
|
+
}
|
|
1287
|
+
collect(max, removed) {
|
|
1288
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1289
|
+
const id = this.evictable.values().next().value;
|
|
1290
|
+
this.evictable.delete(id);
|
|
1291
|
+
this.nodes.delete(id);
|
|
1292
|
+
removed?.push(id);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
moveHead(branch, id) {
|
|
1296
|
+
const previous = this.heads.get(branch);
|
|
1297
|
+
if (previous === id)
|
|
1298
|
+
return;
|
|
1299
|
+
if (previous !== void 0)
|
|
1300
|
+
this.removeReference(previous);
|
|
1301
|
+
this.heads.set(branch, id);
|
|
1302
|
+
this.addReference(id);
|
|
1303
|
+
}
|
|
1304
|
+
addReference(id) {
|
|
1305
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1306
|
+
this.evictable.delete(id);
|
|
1307
|
+
}
|
|
1308
|
+
removeReference(id) {
|
|
1309
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1310
|
+
if (next > 0)
|
|
1311
|
+
this.references.set(id, next);
|
|
1312
|
+
else {
|
|
1313
|
+
this.references.delete(id);
|
|
1314
|
+
if (this.nodes.has(id))
|
|
1315
|
+
this.evictable.add(id);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
assertBranch(branch) {
|
|
1319
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1320
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
|
|
1324
|
+
// ../../sqlite/dist/default.js
|
|
1325
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1326
|
+
var createDefaultSqlite = () => new Database();
|
|
1327
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1328
|
+
|
|
1329
|
+
// ../../sqlite/dist/migrate.js
|
|
1330
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1331
|
+
sqlite.exec(`
|
|
1332
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1333
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1334
|
+
applied_at INTEGER NOT NULL
|
|
1335
|
+
)
|
|
1336
|
+
`);
|
|
1337
|
+
};
|
|
1338
|
+
var migrate = (sqlite, migrations) => {
|
|
1339
|
+
ensureMigrationsTable(sqlite);
|
|
1340
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1341
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1342
|
+
if (pending.length === 0)
|
|
1343
|
+
return;
|
|
1344
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1345
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1346
|
+
sqlite.transaction(() => {
|
|
1347
|
+
for (const migration of pending) {
|
|
1348
|
+
sqlite.exec(migration.sql);
|
|
1349
|
+
insert.run(migration.id, now);
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
};
|
|
1353
|
+
|
|
1354
|
+
// ../../sqlite/dist/schema.js
|
|
1355
|
+
var CORE_MIGRATIONS = [
|
|
1356
|
+
{
|
|
1357
|
+
id: "20260322_core_records_sequences",
|
|
1358
|
+
sql: `
|
|
1359
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1360
|
+
namespace TEXT NOT NULL,
|
|
1361
|
+
collection TEXT NOT NULL,
|
|
1362
|
+
id TEXT NOT NULL,
|
|
1363
|
+
seq INTEGER NOT NULL,
|
|
1364
|
+
value TEXT NOT NULL,
|
|
1365
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1366
|
+
);
|
|
1367
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1368
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1369
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1370
|
+
namespace TEXT NOT NULL,
|
|
1371
|
+
name TEXT NOT NULL,
|
|
1372
|
+
kind TEXT NOT NULL,
|
|
1373
|
+
value INTEGER NOT NULL,
|
|
1374
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1375
|
+
);
|
|
1376
|
+
`
|
|
1377
|
+
}
|
|
1378
|
+
];
|
|
1379
|
+
var migrateCore = (sqlite) => {
|
|
1380
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1381
|
+
};
|
|
1382
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1383
|
+
sqlite.transaction(() => {
|
|
1384
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1385
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1386
|
+
});
|
|
1387
|
+
};
|
|
1388
|
+
|
|
1389
|
+
// ../../openapi/metadata/dist/types.js
|
|
1390
|
+
var EXTENSION_KEYS = {
|
|
1391
|
+
operation: "x-mockingbird",
|
|
1392
|
+
resource: "x-mockingbird-resource",
|
|
1393
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1394
|
+
volatile: "x-mockingbird-volatile",
|
|
1395
|
+
scope: "x-mockingbird-scope",
|
|
1396
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1397
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1398
|
+
};
|
|
1399
|
+
|
|
1400
|
+
// ../../openapi/metadata/dist/read.js
|
|
1401
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1402
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1403
|
+
var operationMetadata = (operation) => {
|
|
1404
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1405
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1406
|
+
const supported = ext.supported ?? true;
|
|
1407
|
+
const parity = ext.parity ?? {};
|
|
1408
|
+
return {
|
|
1409
|
+
supported,
|
|
1410
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1411
|
+
parity: {
|
|
1412
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1413
|
+
safe: parity.safe ?? true,
|
|
1414
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1415
|
+
}
|
|
1416
|
+
};
|
|
1417
|
+
};
|
|
1418
|
+
|
|
1419
|
+
// ../core/dist/service.js
|
|
1420
|
+
import { Hono } from "hono";
|
|
1421
|
+
var defineOperations = (handlers) => handlers;
|
|
1422
|
+
var OperationRegistryError = class extends Error {
|
|
1423
|
+
problems;
|
|
1424
|
+
constructor(problems) {
|
|
1425
|
+
super(`operation registry is inconsistent:
|
|
1426
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1427
|
+
this.problems = problems;
|
|
1428
|
+
this.name = "OperationRegistryError";
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
var verifyOperations = (document2, handlers) => {
|
|
1432
|
+
const problems = [];
|
|
1433
|
+
const operations = listOperations(document2);
|
|
1434
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1435
|
+
for (const operation of operations) {
|
|
1436
|
+
if (seen.has(operation.operationId))
|
|
1437
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1438
|
+
seen.add(operation.operationId);
|
|
1439
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1440
|
+
const handler = handlers[operation.operationId];
|
|
1441
|
+
if (supported && !handler)
|
|
1442
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1443
|
+
if (!supported && handler)
|
|
1444
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1445
|
+
}
|
|
1446
|
+
for (const id of Object.keys(handlers)) {
|
|
1447
|
+
if (!seen.has(id))
|
|
1448
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1449
|
+
}
|
|
1450
|
+
return problems;
|
|
1451
|
+
};
|
|
1452
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1453
|
+
var routeOrder = (a, b) => {
|
|
1454
|
+
const sa = a.path.split("/");
|
|
1455
|
+
const sb = b.path.split("/");
|
|
1456
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1457
|
+
const x = sa[i] ?? "";
|
|
1458
|
+
const y = sb[i] ?? "";
|
|
1459
|
+
const px = x.startsWith("{");
|
|
1460
|
+
const py = y.startsWith("{");
|
|
1461
|
+
if (px !== py)
|
|
1462
|
+
return px ? 1 : -1;
|
|
1463
|
+
if (x !== y)
|
|
1464
|
+
return x < y ? -1 : 1;
|
|
1465
|
+
}
|
|
1466
|
+
return 0;
|
|
1467
|
+
};
|
|
1468
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1469
|
+
var bootSqlite = (sqlite) => {
|
|
1470
|
+
const client = resolveSqlite(sqlite);
|
|
1471
|
+
migrateCore(client);
|
|
1472
|
+
return client;
|
|
1473
|
+
};
|
|
1474
|
+
var createService = (options) => {
|
|
1475
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1476
|
+
if (problems.length > 0)
|
|
1477
|
+
throw new OperationRegistryError(problems);
|
|
1478
|
+
migrateCore(options.sqlite);
|
|
1479
|
+
const now = options.now ?? (() => Date.now());
|
|
1480
|
+
const app = new Hono();
|
|
1481
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1482
|
+
app.onError((error, c) => options.onError(error, c.req.raw));
|
|
1483
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1484
|
+
for (const operation of operations) {
|
|
1485
|
+
const metadata = operationMetadata(operation.operation);
|
|
1486
|
+
const handler = options.handlers[operation.operationId];
|
|
1487
|
+
const route = async (c) => {
|
|
1488
|
+
const request = c.req.raw;
|
|
1489
|
+
if (!metadata.supported || !handler) {
|
|
1490
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1491
|
+
}
|
|
1492
|
+
const url = new URL(request.url);
|
|
1493
|
+
const context = {
|
|
1494
|
+
request,
|
|
1495
|
+
url,
|
|
1496
|
+
params: c.req.param(),
|
|
1497
|
+
query: queryOf(url),
|
|
1498
|
+
body: await readBody(request),
|
|
1499
|
+
sqlite: options.sqlite,
|
|
1500
|
+
namespace: options.namespace,
|
|
1501
|
+
operation,
|
|
1502
|
+
document: options.document,
|
|
1503
|
+
now
|
|
1504
|
+
};
|
|
1505
|
+
const short = await options.before?.(context);
|
|
1506
|
+
if (short)
|
|
1507
|
+
return short;
|
|
1508
|
+
return handler(context);
|
|
1509
|
+
};
|
|
1510
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1511
|
+
}
|
|
1512
|
+
return {
|
|
1513
|
+
app,
|
|
1514
|
+
sqlite: options.sqlite,
|
|
1515
|
+
namespace: options.namespace,
|
|
1516
|
+
fetch: async (request) => app.fetch(request),
|
|
1517
|
+
reset: async () => {
|
|
1518
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
};
|
|
1522
|
+
|
|
1523
|
+
// ../core/dist/snapshot.js
|
|
1524
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1525
|
+
namespace,
|
|
1526
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1527
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1528
|
+
});
|
|
1529
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1530
|
+
sqlite.transaction(() => {
|
|
1531
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1532
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1533
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1534
|
+
for (const row of snapshot.records) {
|
|
1535
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1536
|
+
}
|
|
1537
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1538
|
+
for (const row of snapshot.sequences) {
|
|
1539
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1540
|
+
}
|
|
1541
|
+
});
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1544
|
+
// ../core/dist/version.js
|
|
1545
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1546
|
+
|
|
1547
|
+
// ../core/dist/webhooks.js
|
|
1548
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1549
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1550
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1551
|
+
var parseEndpoint = (value) => {
|
|
1552
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1553
|
+
return "each endpoint needs a url";
|
|
1554
|
+
try {
|
|
1555
|
+
new URL(value.url);
|
|
1556
|
+
} catch {
|
|
1557
|
+
return `not a URL: ${value.url}`;
|
|
1558
|
+
}
|
|
1559
|
+
const endpoint = { url: value.url };
|
|
1560
|
+
if (typeof value.id === "string")
|
|
1561
|
+
endpoint.id = value.id;
|
|
1562
|
+
if (typeof value.secret === "string")
|
|
1563
|
+
endpoint.secret = value.secret;
|
|
1564
|
+
if (typeof value.signUrl === "string")
|
|
1565
|
+
endpoint.signUrl = value.signUrl;
|
|
1566
|
+
const events = value.events ?? value.enabledEvents;
|
|
1567
|
+
if (Array.isArray(events))
|
|
1568
|
+
endpoint.events = events.map(String);
|
|
1569
|
+
if (isRecord3(value.tags)) {
|
|
1570
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1571
|
+
}
|
|
1572
|
+
if (typeof value.account === "string")
|
|
1573
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1574
|
+
if (isRecord3(value.headers)) {
|
|
1575
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1576
|
+
}
|
|
1577
|
+
return endpoint;
|
|
1578
|
+
};
|
|
1579
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1580
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1581
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1582
|
+
const type = url.searchParams.get("type");
|
|
1583
|
+
return type === null || d.type === type;
|
|
1584
|
+
})
|
|
1585
|
+
}),
|
|
1586
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1587
|
+
const type = url.searchParams.get("type");
|
|
1588
|
+
return json2(200, {
|
|
1589
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1590
|
+
});
|
|
1591
|
+
},
|
|
1592
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1593
|
+
const replayed = await hub.replay(params.id);
|
|
1594
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1595
|
+
},
|
|
1596
|
+
"POST /webhooks/flush": async () => {
|
|
1597
|
+
await hub.flush();
|
|
1598
|
+
return json2(200, { status: "ok" });
|
|
1599
|
+
},
|
|
1600
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1601
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1602
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1603
|
+
}
|
|
1604
|
+
const fault = { mode: body.mode };
|
|
1605
|
+
if (typeof body.count === "number")
|
|
1606
|
+
fault.count = body.count;
|
|
1607
|
+
hub.fault(namespace, fault);
|
|
1608
|
+
return json2(201, { namespace, ...fault });
|
|
1609
|
+
},
|
|
1610
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1611
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1612
|
+
...rest,
|
|
1613
|
+
secret: secret ? "(set)" : null
|
|
1614
|
+
}))
|
|
1615
|
+
}),
|
|
1616
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1617
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1618
|
+
if (!Array.isArray(list))
|
|
1619
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1620
|
+
const parsed = [];
|
|
1621
|
+
for (const each of list) {
|
|
1622
|
+
const endpoint = parseEndpoint(each);
|
|
1623
|
+
if (typeof endpoint === "string")
|
|
1624
|
+
return adminError2(400, endpoint);
|
|
1625
|
+
parsed.push(endpoint);
|
|
1626
|
+
}
|
|
1627
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1628
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1629
|
+
},
|
|
1630
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1631
|
+
hub.setEndpoints(namespace, []);
|
|
1632
|
+
return json2(200, { status: "ok" });
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
var parsePayload = (message) => {
|
|
1636
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1637
|
+
try {
|
|
1638
|
+
return JSON.parse(message.body);
|
|
1639
|
+
} catch {
|
|
1640
|
+
return message.body;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1644
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1645
|
+
}
|
|
1646
|
+
return message.body;
|
|
1647
|
+
};
|
|
1648
|
+
|
|
1649
|
+
// ../core/dist/runtime.js
|
|
1650
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1651
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1652
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1653
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1654
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1655
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1656
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1657
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1658
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1659
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1660
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1661
|
+
if (!previous || previous.length === 0)
|
|
1662
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1663
|
+
const result = new Array(fresh.length);
|
|
1664
|
+
let unchanged = fresh.length === previous.length;
|
|
1665
|
+
let oldIndex = 0;
|
|
1666
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1667
|
+
const row = fresh[index];
|
|
1668
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1669
|
+
oldIndex++;
|
|
1670
|
+
}
|
|
1671
|
+
const old = previous[oldIndex];
|
|
1672
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1673
|
+
if (result[index] !== previous[index])
|
|
1674
|
+
unchanged = false;
|
|
1675
|
+
}
|
|
1676
|
+
return unchanged ? previous : result;
|
|
1677
|
+
};
|
|
1678
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1679
|
+
code = "MOCKINGBIRD_DROP";
|
|
1680
|
+
constructor() {
|
|
1681
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1682
|
+
this.name = "TypeError";
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
var operationMatcher = (document2) => {
|
|
1686
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1687
|
+
operationId: operation.operationId,
|
|
1688
|
+
method: operation.method.toUpperCase(),
|
|
1689
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1690
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1691
|
+
})).sort((a, b) => a.params - b.params);
|
|
1692
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1693
|
+
};
|
|
1694
|
+
var createRuntime = (options) => {
|
|
1695
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1696
|
+
const clock = options.clock ?? createClock();
|
|
1697
|
+
const rng = createRng(options.seed ?? 0);
|
|
1698
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1699
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1700
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1701
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1702
|
+
const metrics = createMetrics();
|
|
1703
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1704
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1705
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1706
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1707
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1708
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1709
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1710
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1711
|
+
const credentials = createCredentialRegistry();
|
|
1712
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1713
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1714
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1715
|
+
const existing = instances.get(key);
|
|
1716
|
+
if (existing)
|
|
1717
|
+
return existing;
|
|
1718
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1719
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1720
|
+
}
|
|
1721
|
+
const created = options.create({
|
|
1722
|
+
namespace: storageNamespace(key),
|
|
1723
|
+
publicNamespace,
|
|
1724
|
+
sqlite,
|
|
1725
|
+
clock,
|
|
1726
|
+
rng: isolatedRng ?? rng
|
|
1727
|
+
});
|
|
1728
|
+
instances.set(key, created);
|
|
1729
|
+
publicNamespaces.add(publicNamespace);
|
|
1730
|
+
if (isolatedRng)
|
|
1731
|
+
branchRngs.set(key, isolatedRng);
|
|
1732
|
+
return created;
|
|
1733
|
+
};
|
|
1734
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1735
|
+
const capture = (storage) => {
|
|
1736
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1737
|
+
const previous = captured.get(storage);
|
|
1738
|
+
const snapshot2 = {
|
|
1739
|
+
namespace: fresh.namespace,
|
|
1740
|
+
records: reuseSorted(fresh.records, previous?.records, (left, right) => left.collection < right.collection ? -1 : left.collection > right.collection ? 1 : left.seq - right.seq, (left, right) => left.id === right.id && left.value === right.value),
|
|
1741
|
+
sequences: reuseSorted(fresh.sequences, previous?.sequences, (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.kind < right.kind ? -1 : left.kind > right.kind ? 1 : 0, (left, right) => left.value === right.value)
|
|
1742
|
+
};
|
|
1743
|
+
Object.freeze(snapshot2.records);
|
|
1744
|
+
Object.freeze(snapshot2.sequences);
|
|
1745
|
+
Object.freeze(snapshot2);
|
|
1746
|
+
captured.set(storage, snapshot2);
|
|
1747
|
+
return Object.freeze({
|
|
1748
|
+
snapshot: snapshot2,
|
|
1749
|
+
clock: Object.freeze(clock.state()),
|
|
1750
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1751
|
+
});
|
|
1752
|
+
};
|
|
1753
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1754
|
+
let found = timelines.get(name);
|
|
1755
|
+
if (found)
|
|
1756
|
+
return found;
|
|
1757
|
+
instance(name);
|
|
1758
|
+
found = new Timeline({
|
|
1759
|
+
now: clock.now,
|
|
1760
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1761
|
+
});
|
|
1762
|
+
found.commit(capture(name));
|
|
1763
|
+
timelines.set(name, found);
|
|
1764
|
+
return found;
|
|
1765
|
+
};
|
|
1766
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1767
|
+
if (branch2 === "main")
|
|
1768
|
+
return namespace;
|
|
1769
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1770
|
+
const existing = branchStorage.get(mapKey);
|
|
1771
|
+
if (existing)
|
|
1772
|
+
return existing;
|
|
1773
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1774
|
+
branchStorage.set(mapKey, key);
|
|
1775
|
+
return key;
|
|
1776
|
+
};
|
|
1777
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1778
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1779
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1780
|
+
const history = timeline(namespace);
|
|
1781
|
+
if (branch2 === "main") {
|
|
1782
|
+
if (at !== void 0) {
|
|
1783
|
+
const point = history.checkout("main", at);
|
|
1784
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1785
|
+
captured.set(namespace, point.value.snapshot);
|
|
1786
|
+
rng.setState(point.value.rngState);
|
|
1787
|
+
clock.set(point.value.clock.now);
|
|
1788
|
+
if (point.value.clock.frozen)
|
|
1789
|
+
clock.freeze();
|
|
1790
|
+
else
|
|
1791
|
+
clock.unfreeze();
|
|
1792
|
+
}
|
|
1793
|
+
return namespace;
|
|
1794
|
+
}
|
|
1795
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1796
|
+
if (!history.hasBranch(branch2)) {
|
|
1797
|
+
if (at === void 0)
|
|
1798
|
+
history.commit(capture(namespace));
|
|
1799
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1800
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1801
|
+
if (point)
|
|
1802
|
+
branchRng.setState(point.value.rngState);
|
|
1803
|
+
instanceFor(storage, namespace, branchRng);
|
|
1804
|
+
if (point)
|
|
1805
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1806
|
+
if (point)
|
|
1807
|
+
captured.set(storage, point.value.snapshot);
|
|
1808
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1809
|
+
const point = history.checkout(branch2, at);
|
|
1810
|
+
if (!instances.has(storage)) {
|
|
1811
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1812
|
+
branchRng.setState(point.value.rngState);
|
|
1813
|
+
instanceFor(storage, namespace, branchRng);
|
|
1814
|
+
}
|
|
1815
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1816
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1817
|
+
captured.set(storage, point.value.snapshot);
|
|
1818
|
+
} else {
|
|
1819
|
+
if (!instances.has(storage)) {
|
|
1820
|
+
const point = history.head(branch2);
|
|
1821
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1822
|
+
if (point)
|
|
1823
|
+
branchRng.setState(point.value.rngState);
|
|
1824
|
+
instanceFor(storage, namespace, branchRng);
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
return storage;
|
|
1828
|
+
};
|
|
1829
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1830
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1831
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1832
|
+
};
|
|
1833
|
+
const branch = (name, branchOptions = {}) => {
|
|
1834
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1835
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1836
|
+
const head = timeline(namespace).head(name);
|
|
1837
|
+
if (!head)
|
|
1838
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1839
|
+
return head;
|
|
1840
|
+
};
|
|
1841
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1842
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1843
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1844
|
+
const history = timeline(namespace);
|
|
1845
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1846
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1847
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1848
|
+
captured.set(storage, point.value.snapshot);
|
|
1849
|
+
clock.set(point.value.clock.now);
|
|
1850
|
+
if (point.value.clock.frozen)
|
|
1851
|
+
clock.freeze();
|
|
1852
|
+
else
|
|
1853
|
+
clock.unfreeze();
|
|
1854
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1855
|
+
};
|
|
1856
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1857
|
+
if (name === "*") {
|
|
1858
|
+
options.webhooks?.clear();
|
|
1859
|
+
for (const each of instances.values())
|
|
1860
|
+
await each.reset();
|
|
1861
|
+
timelines.clear();
|
|
1862
|
+
branchStorage.clear();
|
|
1863
|
+
branchRngs.clear();
|
|
1864
|
+
captured.clear();
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
options.webhooks?.clear(name);
|
|
1868
|
+
const target = instances.get(name);
|
|
1869
|
+
if (target)
|
|
1870
|
+
await target.reset();
|
|
1871
|
+
else
|
|
1872
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1873
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1874
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1875
|
+
continue;
|
|
1876
|
+
const branchInstance = instances.get(storage);
|
|
1877
|
+
if (branchInstance)
|
|
1878
|
+
await branchInstance.reset();
|
|
1879
|
+
else
|
|
1880
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1881
|
+
branchStorage.delete(mapping);
|
|
1882
|
+
branchRngs.delete(storage);
|
|
1883
|
+
captured.delete(storage);
|
|
1884
|
+
}
|
|
1885
|
+
timelines.delete(name);
|
|
1886
|
+
captured.delete(name);
|
|
1887
|
+
};
|
|
1888
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1889
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1890
|
+
};
|
|
1891
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1892
|
+
instance(name);
|
|
1893
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1894
|
+
captured.set(name, from);
|
|
1895
|
+
const history = timelines.get(name);
|
|
1896
|
+
if (history)
|
|
1897
|
+
history.commit(capture(name), { branch: "main" });
|
|
1898
|
+
else
|
|
1899
|
+
timeline(name);
|
|
1900
|
+
};
|
|
1901
|
+
const runtime = {
|
|
1902
|
+
name: options.name,
|
|
1903
|
+
sqlite,
|
|
1904
|
+
clock,
|
|
1905
|
+
faults,
|
|
1906
|
+
metrics,
|
|
1907
|
+
journal,
|
|
1908
|
+
rng,
|
|
1909
|
+
credentials,
|
|
1910
|
+
webhooks: options.webhooks,
|
|
1911
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1912
|
+
const preset = options.presets?.[name];
|
|
1913
|
+
if (!preset)
|
|
1914
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1915
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1916
|
+
namespace,
|
|
1917
|
+
...rule,
|
|
1918
|
+
...overrides,
|
|
1919
|
+
preset: name,
|
|
1920
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1921
|
+
}));
|
|
1922
|
+
if (preset.webhook && options.webhooks) {
|
|
1923
|
+
options.webhooks.fault(namespace, {
|
|
1924
|
+
...preset.webhook,
|
|
1925
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
return added;
|
|
1929
|
+
},
|
|
1930
|
+
instance,
|
|
1931
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1932
|
+
reset,
|
|
1933
|
+
snapshot,
|
|
1934
|
+
restore,
|
|
1935
|
+
checkpoint,
|
|
1936
|
+
branch,
|
|
1937
|
+
checkout,
|
|
1938
|
+
timeline,
|
|
1939
|
+
fetch: async (incoming) => {
|
|
1940
|
+
let request = incoming;
|
|
1941
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1942
|
+
if (prefixed) {
|
|
1943
|
+
const url2 = new URL(request.url);
|
|
1944
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1945
|
+
const headers = new Headers(request.headers);
|
|
1946
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1947
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1948
|
+
}
|
|
1949
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1950
|
+
request = new Request(url2, {
|
|
1951
|
+
method: request.method,
|
|
1952
|
+
headers,
|
|
1953
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1954
|
+
signal: request.signal
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1957
|
+
let namespace = control.namespaceOf(request);
|
|
1958
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1959
|
+
const credential = options.credential(request);
|
|
1960
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1961
|
+
if (mapped !== void 0)
|
|
1962
|
+
namespace = mapped;
|
|
1963
|
+
}
|
|
1964
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1965
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1966
|
+
const stamp = (response2) => {
|
|
1967
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1968
|
+
try {
|
|
1969
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1970
|
+
return response2;
|
|
1971
|
+
} catch {
|
|
1972
|
+
const copy = new Response(response2.body, response2);
|
|
1973
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1974
|
+
return copy;
|
|
1975
|
+
}
|
|
1976
|
+
};
|
|
1977
|
+
const handled = await control.handle(request);
|
|
1978
|
+
if (handled)
|
|
1979
|
+
return stamp(handled);
|
|
1980
|
+
const started = monotonicNow();
|
|
1981
|
+
const url = new URL(request.url);
|
|
1982
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1983
|
+
const log = (status, faultId, response2) => {
|
|
1984
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1985
|
+
const entry = {
|
|
1986
|
+
service: options.name,
|
|
1987
|
+
namespace,
|
|
1988
|
+
operationId,
|
|
1989
|
+
method: request.method,
|
|
1990
|
+
path: url.pathname,
|
|
1991
|
+
status,
|
|
1992
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1993
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1994
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1995
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1996
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1997
|
+
};
|
|
1998
|
+
metrics.record(entry);
|
|
1999
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2000
|
+
options.onLog?.(entry);
|
|
2001
|
+
};
|
|
2002
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2003
|
+
log(400);
|
|
2004
|
+
return stamp(new Response(JSON.stringify({
|
|
2005
|
+
error: {
|
|
2006
|
+
type: "mockingbird_admin",
|
|
2007
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2008
|
+
}
|
|
2009
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2010
|
+
}
|
|
2011
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2012
|
+
log(400);
|
|
2013
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2014
|
+
}
|
|
2015
|
+
let storage;
|
|
2016
|
+
try {
|
|
2017
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2018
|
+
const point = timeline(namespace).get(at);
|
|
2019
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2020
|
+
let viewRng = branchRngs.get(storage);
|
|
2021
|
+
if (!viewRng) {
|
|
2022
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2023
|
+
instanceFor(storage, namespace, viewRng);
|
|
2024
|
+
}
|
|
2025
|
+
viewRng.setState(point.value.rngState);
|
|
2026
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2027
|
+
captured.set(storage, point.value.snapshot);
|
|
2028
|
+
} else {
|
|
2029
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2030
|
+
}
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
log(409);
|
|
2033
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
2034
|
+
}
|
|
2035
|
+
const hits = await faults.take({
|
|
2036
|
+
operationId,
|
|
2037
|
+
method: request.method,
|
|
2038
|
+
path: url.pathname,
|
|
2039
|
+
namespace
|
|
2040
|
+
});
|
|
2041
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2042
|
+
if (final?.drop) {
|
|
2043
|
+
log(0, final.id);
|
|
2044
|
+
throw new DroppedConnectionError();
|
|
2045
|
+
}
|
|
2046
|
+
if (final?.response) {
|
|
2047
|
+
log(final.response.status, final.id);
|
|
2048
|
+
return stamp(final.response);
|
|
2049
|
+
}
|
|
2050
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2051
|
+
if (fired.length > 0)
|
|
2052
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2053
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2054
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2055
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2056
|
+
response = mutableResponse(response);
|
|
2057
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2058
|
+
}
|
|
2059
|
+
if (selectedBranch !== "main") {
|
|
2060
|
+
response = mutableResponse(response);
|
|
2061
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2062
|
+
}
|
|
2063
|
+
if (at !== void 0) {
|
|
2064
|
+
response = mutableResponse(response);
|
|
2065
|
+
response.headers.set(AT_HEADER, at);
|
|
2066
|
+
}
|
|
2067
|
+
log(response.status, fired[0]?.id, response);
|
|
2068
|
+
return stamp(response);
|
|
2069
|
+
}
|
|
2070
|
+
};
|
|
2071
|
+
const control = createControlPlane({
|
|
2072
|
+
name: options.name,
|
|
2073
|
+
startedAt: wallNow(),
|
|
2074
|
+
wallNow,
|
|
2075
|
+
clock,
|
|
2076
|
+
faults,
|
|
2077
|
+
metrics,
|
|
2078
|
+
journal,
|
|
2079
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2080
|
+
namespaces: runtime.namespaces,
|
|
2081
|
+
reset,
|
|
2082
|
+
timeTravel: {
|
|
2083
|
+
checkpoint: (name, branchName) => {
|
|
2084
|
+
const point = checkpoint(name, branchName);
|
|
2085
|
+
return {
|
|
2086
|
+
id: point.id,
|
|
2087
|
+
branch: point.branch,
|
|
2088
|
+
parent: point.parent,
|
|
2089
|
+
at: point.at,
|
|
2090
|
+
records: point.value.snapshot.records.length
|
|
2091
|
+
};
|
|
2092
|
+
},
|
|
2093
|
+
branch: (branchName, branchOptions) => {
|
|
2094
|
+
const point = branch(branchName, branchOptions);
|
|
2095
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2096
|
+
},
|
|
2097
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2098
|
+
retain: (name, checkpointId) => {
|
|
2099
|
+
timeline(name).retain(checkpointId);
|
|
2100
|
+
},
|
|
2101
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2102
|
+
inspect: (name) => {
|
|
2103
|
+
const history = timeline(name);
|
|
2104
|
+
return {
|
|
2105
|
+
branches: history.branches(),
|
|
2106
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2107
|
+
id,
|
|
2108
|
+
branch: branchName,
|
|
2109
|
+
parent,
|
|
2110
|
+
at
|
|
2111
|
+
}))
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
},
|
|
2115
|
+
describe: options.describe ?? (() => ({})),
|
|
2116
|
+
...options.presets ? {
|
|
2117
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2118
|
+
} : {},
|
|
2119
|
+
routes: {
|
|
2120
|
+
...credentialRoutes(credentials),
|
|
2121
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2122
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2123
|
+
...options.admin?.(runtime) ?? {}
|
|
2124
|
+
},
|
|
2125
|
+
adminKey: options.adminKey
|
|
2126
|
+
});
|
|
2127
|
+
return runtime;
|
|
2128
|
+
};
|
|
2129
|
+
var mutableResponse = (response) => {
|
|
2130
|
+
try {
|
|
2131
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2132
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2133
|
+
return response;
|
|
2134
|
+
} catch {
|
|
2135
|
+
return new Response(response.body, response);
|
|
2136
|
+
}
|
|
2137
|
+
};
|
|
2138
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2139
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2140
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2141
|
+
var credentialRoutes = (registry) => ({
|
|
2142
|
+
"GET /credentials": () => adminJson(200, {
|
|
2143
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2144
|
+
credential: maskCredential(credential),
|
|
2145
|
+
namespace
|
|
2146
|
+
}))
|
|
2147
|
+
}),
|
|
2148
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2149
|
+
const pairs = [];
|
|
2150
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2151
|
+
if (Array.isArray(list)) {
|
|
2152
|
+
for (const each of list) {
|
|
2153
|
+
if (typeof each === "string")
|
|
2154
|
+
pairs.push([each, namespace]);
|
|
2155
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2156
|
+
pairs.push([
|
|
2157
|
+
each.credential,
|
|
2158
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2159
|
+
]);
|
|
2160
|
+
} else
|
|
2161
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2162
|
+
}
|
|
2163
|
+
} else if (isObject(list)) {
|
|
2164
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2165
|
+
if (typeof target !== "string")
|
|
2166
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2167
|
+
pairs.push([credential, target]);
|
|
2168
|
+
}
|
|
2169
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2170
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2171
|
+
} else {
|
|
2172
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2173
|
+
}
|
|
2174
|
+
for (const [credential, target] of pairs) {
|
|
2175
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2176
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2177
|
+
registry.set(credential, target);
|
|
2178
|
+
}
|
|
2179
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2180
|
+
},
|
|
2181
|
+
"DELETE /credentials": ({ url }) => {
|
|
2182
|
+
const credential = url.searchParams.get("credential");
|
|
2183
|
+
if (credential === null)
|
|
2184
|
+
registry.clear();
|
|
2185
|
+
else
|
|
2186
|
+
registry.remove(credential);
|
|
2187
|
+
return adminJson(200, { status: "ok" });
|
|
2188
|
+
}
|
|
2189
|
+
});
|
|
2190
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2191
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2192
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2193
|
+
}),
|
|
2194
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2195
|
+
const name = params.name;
|
|
2196
|
+
if (!presets[name])
|
|
2197
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2198
|
+
const overrides = isObject(body) ? body : {};
|
|
2199
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2200
|
+
}
|
|
2201
|
+
});
|
|
2202
|
+
|
|
2203
|
+
// ../core/dist/validation.js
|
|
2204
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2205
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2206
|
+
if (!requestBody)
|
|
2207
|
+
return [];
|
|
2208
|
+
const resolved = deref(context.document, requestBody);
|
|
2209
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2210
|
+
if (!schema)
|
|
2211
|
+
return [];
|
|
2212
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2213
|
+
if (context.body.kind === "invalid") {
|
|
2214
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2215
|
+
}
|
|
2216
|
+
if (value === void 0) {
|
|
2217
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2218
|
+
}
|
|
2219
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2220
|
+
};
|
|
2221
|
+
|
|
2222
|
+
// src/generated/openapi.ts
|
|
2223
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"EasyPost Trackers API (Mockingbird subset)","description":"Stateful mock subset of the EasyPost v2 API: create (or re-use) a tracker for a tracking\\ncode, retrieve it, and list trackers. Trimmed from EasyPost's published reference to what\\nour genomics tracking lookup calls, plus the two reads that make parity walks meaningful.\\n","version":"2","x-mockingbird-upstream":{"note":"Shapes from https://docs.easypost.com/docs/trackers; request/response fields our consumer reads come from packages/lib/src/shipment-tracking-status/easypost-client.ts."}},"servers":[{"url":"https://api.easypost.com"}],"security":[{"basicAuth":[]}],"paths":{"/v2/trackers":{"post":{"operationId":"CreateTracker","description":"Creates a tracker, or answers the existing one when the same tracking code (and carrier) was already tracked. EasyPost's test codes (EZ1000000001 \u2026 EZ7000000007) answer their documented fixed statuses.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/CreateTrackerBody"}},"application/json":{"schema":{"$ref":"#/components/schemas/CreateTrackerBody"}}}},"responses":{"201":{"description":"The tracker (new or re-used)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Tracker"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"Missing tracking code or invalid carrier","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}},"get":{"operationId":"ListTrackers","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"tracking_code","in":"query","required":false,"schema":{"type":"string","maxLength":40}},{"name":"carrier","in":"query","required":false,"schema":{"type":"string","enum":["USPS","UPS","FedEx","DHLExpress"]}},{"name":"page_size","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100}}],"responses":{"200":{"description":"Newest trackers first","content":{"application/json":{"schema":{"type":"object","required":["trackers","has_more"],"properties":{"trackers":{"type":"array","items":{"$ref":"#/components/schemas/Tracker"}},"has_more":{"type":"boolean"}}}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"Invalid query parameter","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v2/trackers/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"tracker","missing":"trk_00000000000000000000000000000000"}}}],"get":{"operationId":"RetrieveTracker","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The tracker","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Tracker"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown tracker","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"securitySchemes":{"basicAuth":{"type":"http","scheme":"basic","description":"The API key as the username, an empty password (\`Basic base64(key:)\`)."}},"schemas":{"CreateTrackerBody":{"type":"object","required":["tracker"],"properties":{"tracker":{"type":"object","required":["tracking_code"],"properties":{"tracking_code":{"type":"string","minLength":1,"maxLength":40,"examples":["EZ1000000001","EZ4000000004","1Z999AA10123456784"]},"carrier":{"type":"string","enum":["USPS","UPS","FedEx","DHL","DHLExpress"]}}}}},"Tracker":{"type":"object","required":["id","object","mode","tracking_code","status","status_detail","carrier","tracking_details","public_url","created_at","updated_at"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"tracker","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"object":{"type":"string","enum":["Tracker"]},"mode":{"type":"string","enum":["test","production"]},"tracking_code":{"type":"string"},"status":{"type":"string","enum":["unknown","pre_transit","in_transit","out_for_delivery","delivered","available_for_pickup","return_to_sender","failure","cancelled","error"]},"status_detail":{"type":"string"},"carrier":{"type":"string"},"signed_by":{"type":["string","null"]},"weight":{"type":["number","null"]},"est_delivery_date":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"shipment_id":{"type":["string","null"]},"tracking_details":{"type":"array","items":{"$ref":"#/components/schemas/TrackingDetail"}},"carrier_detail":{"type":["object","null"]},"public_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"fees":{"type":"array","items":{"type":"object"}},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"TrackingDetail":{"type":"object","required":["object","message","status","status_detail","datetime","source"],"properties":{"object":{"type":"string","enum":["TrackingDetail"]},"message":{"type":"string"},"status":{"type":"string"},"status_detail":{"type":"string"},"datetime":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"source":{"type":"string"},"tracking_location":{"type":"object"}}},"Error":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string"},"message":{"type":"string"},"errors":{"type":"array","items":{"type":"object"}}}}}}}}}`);
|
|
2224
|
+
var operationIds = ["ListTrackers", "CreateTracker", "RetrieveTracker"];
|
|
2225
|
+
var supportedOperationIds = ["ListTrackers", "CreateTracker", "RetrieveTracker"];
|
|
2226
|
+
|
|
2227
|
+
// src/state.ts
|
|
2228
|
+
var TRACKER_STATUSES = [
|
|
2229
|
+
"unknown",
|
|
2230
|
+
"pre_transit",
|
|
2231
|
+
"in_transit",
|
|
2232
|
+
"out_for_delivery",
|
|
2233
|
+
"delivered",
|
|
2234
|
+
"available_for_pickup",
|
|
2235
|
+
"return_to_sender",
|
|
2236
|
+
"failure",
|
|
2237
|
+
"cancelled",
|
|
2238
|
+
"error"
|
|
2239
|
+
];
|
|
2240
|
+
var TEST_TRACKING_CODES = {
|
|
2241
|
+
EZ1000000001: { status: "pre_transit", status_detail: "status_update" },
|
|
2242
|
+
EZ2000000002: { status: "in_transit", status_detail: "arrived_at_facility" },
|
|
2243
|
+
EZ3000000003: { status: "out_for_delivery", status_detail: "out_for_delivery" },
|
|
2244
|
+
EZ4000000004: { status: "delivered", status_detail: "arrived_at_destination" },
|
|
2245
|
+
EZ5000000005: { status: "return_to_sender", status_detail: "return" },
|
|
2246
|
+
EZ6000000006: { status: "failure", status_detail: "unknown" },
|
|
2247
|
+
EZ7000000007: { status: "unknown", status_detail: "unknown" }
|
|
2248
|
+
};
|
|
2249
|
+
var DEFAULT_SETTINGS = { apiKeys: [] };
|
|
2250
|
+
var EasyPostState = class {
|
|
2251
|
+
constructor(sqlite, namespace, seed) {
|
|
2252
|
+
this.seed = seed;
|
|
2253
|
+
this.trackers = new Collection(sqlite, namespace, "trackers");
|
|
2254
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2255
|
+
this.ids = new IdSequence(sqlite, namespace, "easypost");
|
|
2256
|
+
this.ensureSeeded();
|
|
2257
|
+
}
|
|
2258
|
+
seed;
|
|
2259
|
+
trackers;
|
|
2260
|
+
settings;
|
|
2261
|
+
ids;
|
|
2262
|
+
ensureSeeded() {
|
|
2263
|
+
if (!this.settings.has("settings")) {
|
|
2264
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
current() {
|
|
2268
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2269
|
+
}
|
|
2270
|
+
update(patch) {
|
|
2271
|
+
const next = { ...this.current(), ...patch };
|
|
2272
|
+
this.settings.insert("settings", next);
|
|
2273
|
+
return next;
|
|
2274
|
+
}
|
|
2275
|
+
/** By tracker id, or by tracking code (newest tracker for it). */
|
|
2276
|
+
find(idOrCode) {
|
|
2277
|
+
return this.trackers.get(idOrCode) ?? this.trackers.list({ where: (t) => t.tracking_code === idOrCode }).at(0)?.value;
|
|
2278
|
+
}
|
|
2279
|
+
/** The tracker EasyPost re-uses for this code and carrier (same code, same carrier). */
|
|
2280
|
+
existing(code, carrier) {
|
|
2281
|
+
return this.trackers.list({ where: (t) => t.tracking_code === code && t.carrier === carrier }).at(0)?.value;
|
|
2282
|
+
}
|
|
2283
|
+
nextId() {
|
|
2284
|
+
return this.ids.next("trk_", 32).toLowerCase();
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2287
|
+
|
|
2288
|
+
// src/runtime.ts
|
|
2289
|
+
var errorBody = (code, message) => ({ error: { code, message, errors: [] } });
|
|
2290
|
+
var EASYPOST_PRESETS = {
|
|
2291
|
+
rate_limited: {
|
|
2292
|
+
description: "Trackers answer 429 RATE_LIMITED (our client reports status unknown)",
|
|
2293
|
+
rules: [
|
|
2294
|
+
{
|
|
2295
|
+
pathPrefix: "/v2/trackers",
|
|
2296
|
+
status: 429,
|
|
2297
|
+
body: errorBody("RATE_LIMITED", "You have exceeded the rate limit for this endpoint.")
|
|
2298
|
+
}
|
|
2299
|
+
]
|
|
2300
|
+
},
|
|
2301
|
+
server_error: {
|
|
2302
|
+
description: "Trackers answer 500 INTERNAL_SERVER_ERROR",
|
|
2303
|
+
rules: [
|
|
2304
|
+
{
|
|
2305
|
+
pathPrefix: "/v2/trackers",
|
|
2306
|
+
status: 500,
|
|
2307
|
+
body: errorBody("INTERNAL_SERVER_ERROR", "Something went wrong on our end.")
|
|
2308
|
+
}
|
|
2309
|
+
]
|
|
2310
|
+
},
|
|
2311
|
+
invalid_api_key: {
|
|
2312
|
+
description: "Every call answers 401 APIKEY.INACTIVE, as if EASYPOST_API_KEY were revoked",
|
|
2313
|
+
rules: [
|
|
2314
|
+
{
|
|
2315
|
+
pathPrefix: "/v2/",
|
|
2316
|
+
status: 401,
|
|
2317
|
+
body: errorBody(
|
|
2318
|
+
"APIKEY.INACTIVE",
|
|
2319
|
+
"We couldn't authenticate you. Please check your API key and try again."
|
|
2320
|
+
)
|
|
2321
|
+
}
|
|
2322
|
+
]
|
|
2323
|
+
},
|
|
2324
|
+
gateway_html: {
|
|
2325
|
+
description: "Trackers answer a 502 HTML page (no JSON: our client falls back to its own message)",
|
|
2326
|
+
rules: [
|
|
2327
|
+
{
|
|
2328
|
+
pathPrefix: "/v2/trackers",
|
|
2329
|
+
status: 502,
|
|
2330
|
+
body: "<html><body><h1>502 Bad Gateway</h1></body></html>",
|
|
2331
|
+
headers: { "content-type": "text/html" }
|
|
2332
|
+
}
|
|
2333
|
+
]
|
|
2334
|
+
},
|
|
2335
|
+
connection_drop: {
|
|
2336
|
+
description: "The connection drops before any answer (fetch rejects)",
|
|
2337
|
+
rules: [{ pathPrefix: "/v2/trackers", drop: true }]
|
|
2338
|
+
},
|
|
2339
|
+
slow: {
|
|
2340
|
+
description: "Trackers answer after 5 s",
|
|
2341
|
+
rules: [{ pathPrefix: "/v2/trackers", latencyMs: 5e3 }]
|
|
2342
|
+
}
|
|
2343
|
+
};
|
|
2344
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2345
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2346
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2347
|
+
var adminRoutes = (runtime) => ({
|
|
2348
|
+
"GET /trackers": ({ namespace }) => json3(200, { trackers: runtime.instance(namespace).trackers() }),
|
|
2349
|
+
"POST /trackers/:code/transition": ({ params, body, namespace }) => {
|
|
2350
|
+
if (!isRecord4(body) || !isTrackerStatus(body.status)) {
|
|
2351
|
+
return adminError3(
|
|
2352
|
+
400,
|
|
2353
|
+
'expected {"status": "<unknown|pre_transit|in_transit|out_for_delivery|delivered|available_for_pickup|return_to_sender|failure|cancelled|error>", "status_detail"?, "message"?, "carrier"?}'
|
|
2354
|
+
);
|
|
2355
|
+
}
|
|
2356
|
+
const text = (key) => typeof body[key] === "string" ? { [key]: body[key] } : {};
|
|
2357
|
+
const tracker = runtime.instance(namespace).transition(
|
|
2358
|
+
params.code,
|
|
2359
|
+
{ status: body.status, ...text("status_detail"), ...text("message"), ...text("signed_by") },
|
|
2360
|
+
typeof body.carrier === "string" ? body.carrier : void 0
|
|
2361
|
+
);
|
|
2362
|
+
return json3(200, tracker);
|
|
2363
|
+
},
|
|
2364
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2365
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2366
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2367
|
+
const patch = {};
|
|
2368
|
+
if (body.apiKeys !== void 0) {
|
|
2369
|
+
if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
|
|
2370
|
+
patch.apiKeys = body.apiKeys.map(String);
|
|
2371
|
+
}
|
|
2372
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2373
|
+
}
|
|
2374
|
+
});
|
|
2375
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2376
|
+
name: EASYPOST_NAMESPACE,
|
|
2377
|
+
document,
|
|
2378
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2379
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2380
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2381
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2382
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2383
|
+
credential: apiKeyCredential,
|
|
2384
|
+
presets: EASYPOST_PRESETS,
|
|
2385
|
+
create: ({ sqlite, namespace, clock }) => new EasyPostAPI({
|
|
2386
|
+
sqlite,
|
|
2387
|
+
namespace,
|
|
2388
|
+
now: clock.now,
|
|
2389
|
+
...options.settings ? { settings: options.settings } : {}
|
|
2390
|
+
}),
|
|
2391
|
+
admin: adminRoutes
|
|
2392
|
+
});
|
|
2393
|
+
|
|
2394
|
+
// src/index.ts
|
|
2395
|
+
var EASYPOST_NAMESPACE = "easypost";
|
|
2396
|
+
var easyPostError = (status, code, message, errors = []) => jsonRes(status, { error: { code, message, errors } });
|
|
2397
|
+
var apiKeyCredential = (request) => basicAuth(request)?.username || void 0;
|
|
2398
|
+
var CARRIER_ALIASES = {
|
|
2399
|
+
usps: "USPS",
|
|
2400
|
+
ups: "UPS",
|
|
2401
|
+
fedex: "FedEx",
|
|
2402
|
+
dhl: "DHLExpress",
|
|
2403
|
+
dhlexpress: "DHLExpress"
|
|
2404
|
+
};
|
|
2405
|
+
var detectCarrier = (code) => {
|
|
2406
|
+
const cleaned = code.trim().toUpperCase();
|
|
2407
|
+
if (/^1Z[A-Z0-9]{16}$/.test(cleaned)) return "UPS";
|
|
2408
|
+
if (/^(420\d{4,5}\d{20,22}|9[0-9]{21,27}|[A-Z]{2}[0-9]{9}US)$/.test(cleaned)) return "USPS";
|
|
2409
|
+
if (/^[0-9]{12,22}$/.test(cleaned)) return "FedEx";
|
|
2410
|
+
if (/^[0-9]{10,11}$/.test(cleaned)) return "DHLExpress";
|
|
2411
|
+
return "USPS";
|
|
2412
|
+
};
|
|
2413
|
+
var DEFAULT_DETAIL = {
|
|
2414
|
+
unknown: "unknown",
|
|
2415
|
+
pre_transit: "status_update",
|
|
2416
|
+
in_transit: "arrived_at_facility",
|
|
2417
|
+
out_for_delivery: "out_for_delivery",
|
|
2418
|
+
delivered: "arrived_at_destination",
|
|
2419
|
+
available_for_pickup: "arrived_at_pickup_location",
|
|
2420
|
+
return_to_sender: "return",
|
|
2421
|
+
failure: "unknown",
|
|
2422
|
+
cancelled: "cancelled",
|
|
2423
|
+
error: "unknown"
|
|
2424
|
+
};
|
|
2425
|
+
var MESSAGES = {
|
|
2426
|
+
unknown: "Status unknown",
|
|
2427
|
+
pre_transit: "Pre-Shipment Info Sent to USPS",
|
|
2428
|
+
in_transit: "Arrived at USPS Facility",
|
|
2429
|
+
out_for_delivery: "Out for Delivery",
|
|
2430
|
+
delivered: "Delivered",
|
|
2431
|
+
available_for_pickup: "Available for Pickup",
|
|
2432
|
+
return_to_sender: "Returned to Sender",
|
|
2433
|
+
failure: "Delivery Exception",
|
|
2434
|
+
cancelled: "Shipment Cancelled",
|
|
2435
|
+
error: "Carrier Error"
|
|
2436
|
+
};
|
|
2437
|
+
var isTrackerStatus = (value) => typeof value === "string" && TRACKER_STATUSES.includes(value);
|
|
2438
|
+
var EasyPostAPI = class {
|
|
2439
|
+
app;
|
|
2440
|
+
sqlite;
|
|
2441
|
+
state;
|
|
2442
|
+
service;
|
|
2443
|
+
now;
|
|
2444
|
+
constructor(options = {}) {
|
|
2445
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2446
|
+
const namespace = options.namespace ?? EASYPOST_NAMESPACE;
|
|
2447
|
+
this.now = options.now ?? (() => Date.now());
|
|
2448
|
+
this.state = new EasyPostState(sqlite, namespace, options.settings ?? {});
|
|
2449
|
+
const handlers = defineOperations({
|
|
2450
|
+
CreateTracker: (context) => this.createTracker(context),
|
|
2451
|
+
ListTrackers: (context) => this.listTrackers(context),
|
|
2452
|
+
RetrieveTracker: (context) => {
|
|
2453
|
+
const tracker = this.state.trackers.get(context.params.id ?? "");
|
|
2454
|
+
if (!tracker) {
|
|
2455
|
+
return easyPostError(404, "NOT_FOUND", "The requested resource could not be found.");
|
|
2456
|
+
}
|
|
2457
|
+
return annotateResponse(jsonRes(200, tracker), { ids: { trackerId: tracker.id } });
|
|
2458
|
+
}
|
|
2459
|
+
});
|
|
2460
|
+
this.service = createService({
|
|
2461
|
+
document,
|
|
2462
|
+
handlers,
|
|
2463
|
+
sqlite,
|
|
2464
|
+
namespace,
|
|
2465
|
+
now: this.now,
|
|
2466
|
+
notFound: () => easyPostError(404, "NOT_FOUND", "The requested resource could not be found."),
|
|
2467
|
+
onError: (error) => {
|
|
2468
|
+
if (error instanceof HttpError) return error.toResponse();
|
|
2469
|
+
throw error;
|
|
2470
|
+
},
|
|
2471
|
+
before: (context) => {
|
|
2472
|
+
const key = apiKeyCredential(context.request);
|
|
2473
|
+
const message = "We couldn't authenticate you. Please check your API key and try again.";
|
|
2474
|
+
if (!key) return easyPostError(401, "APIKEY.REQUIRED", message);
|
|
2475
|
+
const allowed = this.state.current().apiKeys;
|
|
2476
|
+
if (allowed.length > 0 && !allowed.includes(key)) {
|
|
2477
|
+
return easyPostError(401, "APIKEY.INACTIVE", message);
|
|
2478
|
+
}
|
|
2479
|
+
return void 0;
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
this.app = this.service.app;
|
|
2483
|
+
this.sqlite = this.service.sqlite;
|
|
2484
|
+
}
|
|
2485
|
+
fetch(request) {
|
|
2486
|
+
return this.service.fetch(request);
|
|
2487
|
+
}
|
|
2488
|
+
async reset() {
|
|
2489
|
+
await this.service.reset();
|
|
2490
|
+
this.state.ensureSeeded();
|
|
2491
|
+
}
|
|
2492
|
+
iso() {
|
|
2493
|
+
return new Date(this.now()).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
2494
|
+
}
|
|
2495
|
+
detail(status, statusDetail, carrier) {
|
|
2496
|
+
return {
|
|
2497
|
+
object: "TrackingDetail",
|
|
2498
|
+
message: MESSAGES[status],
|
|
2499
|
+
status,
|
|
2500
|
+
status_detail: statusDetail,
|
|
2501
|
+
datetime: this.iso(),
|
|
2502
|
+
source: carrier,
|
|
2503
|
+
tracking_location: {
|
|
2504
|
+
object: "TrackingLocation",
|
|
2505
|
+
city: status === "unknown" ? null : "SALT LAKE CITY",
|
|
2506
|
+
state: status === "unknown" ? null : "UT",
|
|
2507
|
+
country: status === "unknown" ? null : "US",
|
|
2508
|
+
zip: status === "unknown" ? null : "84101"
|
|
2509
|
+
}
|
|
2510
|
+
};
|
|
2511
|
+
}
|
|
2512
|
+
/** Build a new tracker the way EasyPost does on first sight of a code. */
|
|
2513
|
+
build(code, carrier, mode) {
|
|
2514
|
+
const fixed = mode === "test" ? TEST_TRACKING_CODES[code] : void 0;
|
|
2515
|
+
const status = fixed?.status ?? "unknown";
|
|
2516
|
+
const statusDetail = fixed?.status_detail ?? "unknown";
|
|
2517
|
+
const id = this.state.nextId();
|
|
2518
|
+
const now = this.iso();
|
|
2519
|
+
return {
|
|
2520
|
+
id,
|
|
2521
|
+
object: "Tracker",
|
|
2522
|
+
mode,
|
|
2523
|
+
tracking_code: code,
|
|
2524
|
+
status,
|
|
2525
|
+
status_detail: statusDetail,
|
|
2526
|
+
carrier,
|
|
2527
|
+
signed_by: status === "delivered" ? "John Tester" : null,
|
|
2528
|
+
weight: null,
|
|
2529
|
+
est_delivery_date: fixed ? now : null,
|
|
2530
|
+
shipment_id: null,
|
|
2531
|
+
tracking_details: status === "unknown" ? [] : [this.detail(status, statusDetail, carrier)],
|
|
2532
|
+
carrier_detail: null,
|
|
2533
|
+
public_url: `https://track.easypost.com/${id}`,
|
|
2534
|
+
fees: [],
|
|
2535
|
+
created_at: now,
|
|
2536
|
+
updated_at: now
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
createTracker(context) {
|
|
2540
|
+
const media = context.body.kind === "json" ? "application/json" : void 0;
|
|
2541
|
+
const issues = bodyIssues(context, media ?? "application/x-www-form-urlencoded");
|
|
2542
|
+
const body = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2543
|
+
const code = body?.tracker?.tracking_code;
|
|
2544
|
+
if (typeof code !== "string" || code.trim().length === 0) {
|
|
2545
|
+
return easyPostError(422, "PARAMETER.REQUIRED", "Missing required parameter.", [
|
|
2546
|
+
{ field: "tracker.tracking_code", message: "cannot be blank" }
|
|
2547
|
+
]);
|
|
2548
|
+
}
|
|
2549
|
+
if (issues.length > 0) {
|
|
2550
|
+
return easyPostError(
|
|
2551
|
+
422,
|
|
2552
|
+
"PARAMETER.INVALID",
|
|
2553
|
+
"Invalid parameter.",
|
|
2554
|
+
issues.map((issue) => ({ field: issue.path || "tracker", message: issue.message }))
|
|
2555
|
+
);
|
|
2556
|
+
}
|
|
2557
|
+
const trackingCode = code.trim();
|
|
2558
|
+
const hint = typeof body?.tracker?.carrier === "string" ? body.tracker.carrier : void 0;
|
|
2559
|
+
const carrier = hint ? CARRIER_ALIASES[hint.toLowerCase()] ?? hint : detectCarrier(trackingCode);
|
|
2560
|
+
const key = apiKeyCredential(context.request) ?? "";
|
|
2561
|
+
const mode = key.startsWith("EZAK") ? "production" : "test";
|
|
2562
|
+
const tracker = this.state.existing(trackingCode, carrier) ?? this.build(trackingCode, carrier, mode);
|
|
2563
|
+
if (!this.state.trackers.has(tracker.id)) this.state.trackers.insert(tracker.id, tracker);
|
|
2564
|
+
return annotateResponse(jsonRes(201, tracker), { ids: { trackerId: tracker.id } });
|
|
2565
|
+
}
|
|
2566
|
+
listTrackers(context) {
|
|
2567
|
+
let size = 20;
|
|
2568
|
+
if (context.query.page_size !== void 0) {
|
|
2569
|
+
const parsed = coerce.integer(context.query.page_size);
|
|
2570
|
+
if (!parsed.ok || parsed.value < 1 || parsed.value > 100) {
|
|
2571
|
+
return easyPostError(422, "PARAMETER.INVALID", "Invalid parameter.", [
|
|
2572
|
+
{ field: "page_size", message: "must be an integer between 1 and 100" }
|
|
2573
|
+
]);
|
|
2574
|
+
}
|
|
2575
|
+
size = parsed.value;
|
|
2576
|
+
}
|
|
2577
|
+
const code = typeof context.query.tracking_code === "string" ? context.query.tracking_code : "";
|
|
2578
|
+
const carrier = typeof context.query.carrier === "string" ? context.query.carrier : "";
|
|
2579
|
+
const rows = this.state.trackers.list({
|
|
2580
|
+
where: (t) => (code === "" || t.tracking_code === code) && (carrier === "" || t.carrier === carrier)
|
|
2581
|
+
}).map((row) => row.value);
|
|
2582
|
+
return jsonRes(200, { trackers: rows.slice(0, size), has_more: rows.length > size });
|
|
2583
|
+
}
|
|
2584
|
+
/**
|
|
2585
|
+
* Move a tracker (by id or tracking code) to a status, appending a tracking detail. When no
|
|
2586
|
+
* tracker exists for the code yet, one is registered first, so the app's next lookup of that
|
|
2587
|
+
* code re-uses it and sees the status.
|
|
2588
|
+
*/
|
|
2589
|
+
transition(idOrCode, input, carrierHint) {
|
|
2590
|
+
const existing = this.state.find(idOrCode);
|
|
2591
|
+
const base = existing ?? this.build(
|
|
2592
|
+
idOrCode,
|
|
2593
|
+
carrierHint ? CARRIER_ALIASES[carrierHint.toLowerCase()] ?? carrierHint : detectCarrier(idOrCode),
|
|
2594
|
+
"test"
|
|
2595
|
+
);
|
|
2596
|
+
if (!existing) this.state.trackers.insert(base.id, base);
|
|
2597
|
+
const statusDetail = input.status_detail ?? DEFAULT_DETAIL[input.status];
|
|
2598
|
+
const detail = this.detail(input.status, statusDetail, base.carrier);
|
|
2599
|
+
const next = {
|
|
2600
|
+
...base,
|
|
2601
|
+
status: input.status,
|
|
2602
|
+
status_detail: statusDetail,
|
|
2603
|
+
signed_by: input.signed_by ?? (input.status === "delivered" ? "John Tester" : base.signed_by),
|
|
2604
|
+
tracking_details: [
|
|
2605
|
+
...base.tracking_details,
|
|
2606
|
+
input.message ? { ...detail, message: input.message } : detail
|
|
2607
|
+
],
|
|
2608
|
+
updated_at: this.iso()
|
|
2609
|
+
};
|
|
2610
|
+
this.state.trackers.update(base.id, next);
|
|
2611
|
+
return next;
|
|
2612
|
+
}
|
|
2613
|
+
trackers() {
|
|
2614
|
+
return this.state.trackers.list({ order: "oldest" }).map((row) => row.value);
|
|
2615
|
+
}
|
|
2616
|
+
};
|
|
2617
|
+
|
|
2618
|
+
export {
|
|
2619
|
+
document,
|
|
2620
|
+
operationIds,
|
|
2621
|
+
supportedOperationIds,
|
|
2622
|
+
TRACKER_STATUSES,
|
|
2623
|
+
TEST_TRACKING_CODES,
|
|
2624
|
+
EASYPOST_PRESETS,
|
|
2625
|
+
createRuntime2 as createRuntime,
|
|
2626
|
+
EASYPOST_NAMESPACE,
|
|
2627
|
+
easyPostError,
|
|
2628
|
+
apiKeyCredential,
|
|
2629
|
+
detectCarrier,
|
|
2630
|
+
isTrackerStatus,
|
|
2631
|
+
EasyPostAPI
|
|
2632
|
+
};
|
|
2633
|
+
//# sourceMappingURL=chunk-SPPBQVDT.js.map
|