@crvouga/mockingbird-service-step-functions 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 +57 -0
- package/dist/chunk-KFFQOSA5.js +330 -0
- package/dist/chunk-KFFQOSA5.js.map +7 -0
- package/dist/chunk-MFKAN6YO.js +2436 -0
- package/dist/chunk-MFKAN6YO.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +857 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1205 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +85 -0
|
@@ -0,0 +1,2436 @@
|
|
|
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 match2 = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
|
|
135
|
+
if (!match2)
|
|
136
|
+
return void 0;
|
|
137
|
+
return Number(match2[1]) * UNITS[match2[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 sigV4AccessKeyId = (request) => {
|
|
393
|
+
const header = request.headers.get("authorization");
|
|
394
|
+
const fromHeader = header ? /Credential=([^/,\s]+)\//.exec(header)?.[1] : void 0;
|
|
395
|
+
if (fromHeader)
|
|
396
|
+
return fromHeader;
|
|
397
|
+
const query = new URL(request.url).searchParams.get("X-Amz-Credential");
|
|
398
|
+
return query ? query.split("/")[0] ?? void 0 : void 0;
|
|
399
|
+
};
|
|
400
|
+
var createCredentialRegistry = () => {
|
|
401
|
+
const map = /* @__PURE__ */ new Map();
|
|
402
|
+
return {
|
|
403
|
+
set: (credential, namespace) => {
|
|
404
|
+
map.set(credential, namespace);
|
|
405
|
+
},
|
|
406
|
+
get: (credential) => map.get(credential),
|
|
407
|
+
remove: (credential) => map.delete(credential),
|
|
408
|
+
clear: () => map.clear(),
|
|
409
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
410
|
+
};
|
|
411
|
+
};
|
|
412
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
413
|
+
|
|
414
|
+
// ../core/dist/rng.js
|
|
415
|
+
var seedFrom = (value) => {
|
|
416
|
+
let hash = 2166136261;
|
|
417
|
+
for (let i = 0; i < value.length; i++) {
|
|
418
|
+
hash ^= value.charCodeAt(i);
|
|
419
|
+
hash = Math.imul(hash, 16777619);
|
|
420
|
+
}
|
|
421
|
+
return hash >>> 0;
|
|
422
|
+
};
|
|
423
|
+
var createRng = (seed = 0) => {
|
|
424
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
425
|
+
let state = numeric;
|
|
426
|
+
const next = () => {
|
|
427
|
+
state = state + 1831565813 >>> 0;
|
|
428
|
+
let t = state;
|
|
429
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
430
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
431
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
432
|
+
};
|
|
433
|
+
return {
|
|
434
|
+
next,
|
|
435
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
436
|
+
reset: () => {
|
|
437
|
+
state = numeric;
|
|
438
|
+
},
|
|
439
|
+
state: () => state,
|
|
440
|
+
setState: (next2) => {
|
|
441
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
442
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
443
|
+
}
|
|
444
|
+
state = next2 >>> 0;
|
|
445
|
+
},
|
|
446
|
+
seed: numeric
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
// ../core/dist/faults.js
|
|
451
|
+
var matches = (rule, candidate) => {
|
|
452
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
456
|
+
return false;
|
|
457
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
461
|
+
return false;
|
|
462
|
+
return true;
|
|
463
|
+
};
|
|
464
|
+
var faultResponse = (rule) => {
|
|
465
|
+
const status = rule.status ?? 500;
|
|
466
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
467
|
+
if (typeof rule.body === "string")
|
|
468
|
+
return new Response(rule.body, { status, headers });
|
|
469
|
+
if (rule.body === null)
|
|
470
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
471
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
472
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
473
|
+
};
|
|
474
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
475
|
+
const entries = [];
|
|
476
|
+
return {
|
|
477
|
+
add(rule) {
|
|
478
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
479
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
480
|
+
if (existing >= 0)
|
|
481
|
+
entries[existing] = entry;
|
|
482
|
+
else
|
|
483
|
+
entries.push(entry);
|
|
484
|
+
return rule;
|
|
485
|
+
},
|
|
486
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
487
|
+
remove(id) {
|
|
488
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
489
|
+
if (index < 0)
|
|
490
|
+
return false;
|
|
491
|
+
entries.splice(index, 1);
|
|
492
|
+
return true;
|
|
493
|
+
},
|
|
494
|
+
clear() {
|
|
495
|
+
entries.length = 0;
|
|
496
|
+
},
|
|
497
|
+
async take(candidate) {
|
|
498
|
+
const hits = [];
|
|
499
|
+
for (const entry of entries) {
|
|
500
|
+
if (entry.remaining === 0)
|
|
501
|
+
continue;
|
|
502
|
+
if (!matches(entry.rule, candidate))
|
|
503
|
+
continue;
|
|
504
|
+
const rate = entry.rule.rate ?? 1;
|
|
505
|
+
if (rng.next() >= rate)
|
|
506
|
+
continue;
|
|
507
|
+
entry.hits++;
|
|
508
|
+
if (entry.remaining !== null)
|
|
509
|
+
entry.remaining--;
|
|
510
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
511
|
+
if (delay !== void 0 && delay > 0) {
|
|
512
|
+
await sleep(delay);
|
|
513
|
+
}
|
|
514
|
+
const hit = { id: entry.rule.id };
|
|
515
|
+
if (entry.rule.effect !== void 0) {
|
|
516
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
517
|
+
}
|
|
518
|
+
if (entry.rule.drop === true)
|
|
519
|
+
hit.drop = true;
|
|
520
|
+
else if (entry.rule.status !== void 0)
|
|
521
|
+
hit.response = faultResponse(entry.rule);
|
|
522
|
+
hits.push(hit);
|
|
523
|
+
if (hit.drop || hit.response)
|
|
524
|
+
break;
|
|
525
|
+
}
|
|
526
|
+
return hits;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
// ../../openapi/core/dist/refs.js
|
|
532
|
+
var OpenAPIReferenceError = class extends Error {
|
|
533
|
+
ref;
|
|
534
|
+
constructor(ref) {
|
|
535
|
+
super(`unresolvable $ref: ${ref}`);
|
|
536
|
+
this.ref = ref;
|
|
537
|
+
this.name = "OpenAPIReferenceError";
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
541
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
542
|
+
var resolveRef = (document2, ref) => {
|
|
543
|
+
if (!ref.startsWith("#/"))
|
|
544
|
+
throw new OpenAPIReferenceError(ref);
|
|
545
|
+
let cursor = document2;
|
|
546
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
547
|
+
const segment = unescapePointer(raw);
|
|
548
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
549
|
+
throw new OpenAPIReferenceError(ref);
|
|
550
|
+
}
|
|
551
|
+
cursor = cursor[segment];
|
|
552
|
+
}
|
|
553
|
+
if (cursor === void 0)
|
|
554
|
+
throw new OpenAPIReferenceError(ref);
|
|
555
|
+
return cursor;
|
|
556
|
+
};
|
|
557
|
+
var deref = (document2, value) => {
|
|
558
|
+
let current = value;
|
|
559
|
+
const seen = /* @__PURE__ */ new Set();
|
|
560
|
+
while (isReference(current)) {
|
|
561
|
+
if (seen.has(current.$ref))
|
|
562
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
563
|
+
seen.add(current.$ref);
|
|
564
|
+
current = resolveRef(document2, current.$ref);
|
|
565
|
+
}
|
|
566
|
+
return current;
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
// ../../openapi/core/dist/types.js
|
|
570
|
+
var HTTP_METHODS = [
|
|
571
|
+
"get",
|
|
572
|
+
"put",
|
|
573
|
+
"post",
|
|
574
|
+
"delete",
|
|
575
|
+
"options",
|
|
576
|
+
"head",
|
|
577
|
+
"patch",
|
|
578
|
+
"trace"
|
|
579
|
+
];
|
|
580
|
+
|
|
581
|
+
// ../../openapi/core/dist/document.js
|
|
582
|
+
var mergeParameters = (document2, item, own) => {
|
|
583
|
+
const merged = /* @__PURE__ */ new Map();
|
|
584
|
+
for (const raw of item.parameters ?? []) {
|
|
585
|
+
const parameter = deref(document2, raw);
|
|
586
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
587
|
+
}
|
|
588
|
+
for (const raw of own ?? []) {
|
|
589
|
+
const parameter = deref(document2, raw);
|
|
590
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
591
|
+
}
|
|
592
|
+
return [...merged.values()];
|
|
593
|
+
};
|
|
594
|
+
var listOperations = (document2) => {
|
|
595
|
+
const operations = [];
|
|
596
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
597
|
+
for (const method of HTTP_METHODS) {
|
|
598
|
+
const operation = item[method];
|
|
599
|
+
if (operation?.operationId === void 0)
|
|
600
|
+
continue;
|
|
601
|
+
const responses = {};
|
|
602
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
603
|
+
responses[status] = deref(document2, response);
|
|
604
|
+
}
|
|
605
|
+
operations.push({
|
|
606
|
+
operationId: operation.operationId,
|
|
607
|
+
method,
|
|
608
|
+
path,
|
|
609
|
+
operation,
|
|
610
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
611
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
612
|
+
responses
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return operations;
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
// ../core/dist/ids.js
|
|
620
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
621
|
+
var mix = (input) => {
|
|
622
|
+
let hash = 2166136261;
|
|
623
|
+
for (let i = 0; i < input.length; i++) {
|
|
624
|
+
hash ^= input.charCodeAt(i);
|
|
625
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
626
|
+
}
|
|
627
|
+
hash ^= hash >>> 16;
|
|
628
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
629
|
+
hash ^= hash >>> 13;
|
|
630
|
+
return hash >>> 0;
|
|
631
|
+
};
|
|
632
|
+
var opaqueToken = (input, length) => {
|
|
633
|
+
let out = "";
|
|
634
|
+
let round = 0;
|
|
635
|
+
while (out.length < length) {
|
|
636
|
+
let hash = mix(`${input}:${round++}`);
|
|
637
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
638
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
639
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return out;
|
|
643
|
+
};
|
|
644
|
+
var IdSequence = class {
|
|
645
|
+
sqlite;
|
|
646
|
+
namespace;
|
|
647
|
+
salt;
|
|
648
|
+
constructor(sqlite, namespace, salt = "mockingbird") {
|
|
649
|
+
this.sqlite = sqlite;
|
|
650
|
+
this.namespace = namespace;
|
|
651
|
+
this.salt = salt;
|
|
652
|
+
}
|
|
653
|
+
next(prefix, length = 14) {
|
|
654
|
+
return this.sqlite.transaction(() => {
|
|
655
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
|
|
656
|
+
const value = (row?.value ?? 0) + 1;
|
|
657
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
|
|
658
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
|
|
659
|
+
return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
|
|
664
|
+
// ../core/dist/journal.js
|
|
665
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
666
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
667
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
668
|
+
const rings = /* @__PURE__ */ new Map();
|
|
669
|
+
let sequence = 0;
|
|
670
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
671
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
672
|
+
return {
|
|
673
|
+
size: capacity,
|
|
674
|
+
record(entry) {
|
|
675
|
+
if (capacity === 0)
|
|
676
|
+
return;
|
|
677
|
+
order.set(entry, sequence++);
|
|
678
|
+
let ring = rings.get(entry.namespace);
|
|
679
|
+
if (!ring) {
|
|
680
|
+
ring = { entries: [], next: 0 };
|
|
681
|
+
rings.set(entry.namespace, ring);
|
|
682
|
+
}
|
|
683
|
+
if (ring.entries.length < capacity)
|
|
684
|
+
ring.entries.push(entry);
|
|
685
|
+
else {
|
|
686
|
+
ring.entries[ring.next] = entry;
|
|
687
|
+
ring.next = (ring.next + 1) % capacity;
|
|
688
|
+
}
|
|
689
|
+
},
|
|
690
|
+
list(query = {}) {
|
|
691
|
+
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));
|
|
692
|
+
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));
|
|
693
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
694
|
+
},
|
|
695
|
+
clear(namespace) {
|
|
696
|
+
if (namespace === void 0)
|
|
697
|
+
rings.clear();
|
|
698
|
+
else
|
|
699
|
+
rings.delete(namespace);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
};
|
|
703
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
704
|
+
var responseNotes = (response) => notes.get(response);
|
|
705
|
+
|
|
706
|
+
// ../core/dist/metrics.js
|
|
707
|
+
var createMetrics = () => {
|
|
708
|
+
let requests = 0;
|
|
709
|
+
let faults = 0;
|
|
710
|
+
let totalDurationMs = 0;
|
|
711
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
712
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
713
|
+
return {
|
|
714
|
+
record(entry) {
|
|
715
|
+
requests++;
|
|
716
|
+
totalDurationMs += entry.durationMs;
|
|
717
|
+
if (entry.faultId !== void 0)
|
|
718
|
+
faults++;
|
|
719
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
720
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
721
|
+
if (entry.unmatched) {
|
|
722
|
+
const route = `${entry.method} ${entry.path}`;
|
|
723
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
724
|
+
}
|
|
725
|
+
},
|
|
726
|
+
report: () => ({
|
|
727
|
+
requests,
|
|
728
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
729
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
730
|
+
const space = route.indexOf(" ");
|
|
731
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
732
|
+
}),
|
|
733
|
+
faults,
|
|
734
|
+
totalDurationMs
|
|
735
|
+
}),
|
|
736
|
+
reset() {
|
|
737
|
+
requests = 0;
|
|
738
|
+
faults = 0;
|
|
739
|
+
totalDurationMs = 0;
|
|
740
|
+
byOperation.clear();
|
|
741
|
+
unmatched.clear();
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
};
|
|
745
|
+
|
|
746
|
+
// ../../core/dist/timeline.js
|
|
747
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
748
|
+
var Timeline = class {
|
|
749
|
+
maxCheckpoints;
|
|
750
|
+
now;
|
|
751
|
+
makeId;
|
|
752
|
+
nodes = /* @__PURE__ */ new Map();
|
|
753
|
+
heads = /* @__PURE__ */ new Map();
|
|
754
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
755
|
+
evictable = /* @__PURE__ */ new Set();
|
|
756
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
757
|
+
references = /* @__PURE__ */ new Map();
|
|
758
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
759
|
+
sequence = 0;
|
|
760
|
+
constructor(options = {}) {
|
|
761
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
762
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
763
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
764
|
+
this.maxCheckpoints = max;
|
|
765
|
+
this.now = options.now ?? (() => this.sequence);
|
|
766
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
767
|
+
}
|
|
768
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
769
|
+
commit(value, options = {}) {
|
|
770
|
+
const branch = options.branch ?? "main";
|
|
771
|
+
this.assertBranch(branch);
|
|
772
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
773
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
774
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
775
|
+
const id = this.makeId(++this.sequence);
|
|
776
|
+
if (this.nodes.has(id))
|
|
777
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
778
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
779
|
+
this.nodes.set(id, checkpoint);
|
|
780
|
+
this.moveHead(branch, id);
|
|
781
|
+
this.collect(this.maxCheckpoints);
|
|
782
|
+
return checkpoint;
|
|
783
|
+
}
|
|
784
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
785
|
+
fork(branch, options = {}) {
|
|
786
|
+
this.assertBranch(branch);
|
|
787
|
+
if (this.heads.has(branch))
|
|
788
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
789
|
+
const from = options.from ?? this.heads.get("main");
|
|
790
|
+
if (from === void 0)
|
|
791
|
+
return void 0;
|
|
792
|
+
const checkpoint = this.get(from);
|
|
793
|
+
this.moveHead(branch, checkpoint.id);
|
|
794
|
+
return checkpoint;
|
|
795
|
+
}
|
|
796
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
797
|
+
checkout(branch, id) {
|
|
798
|
+
this.assertBranch(branch);
|
|
799
|
+
const checkpoint = this.get(id);
|
|
800
|
+
this.moveHead(branch, checkpoint.id);
|
|
801
|
+
return checkpoint;
|
|
802
|
+
}
|
|
803
|
+
get(id) {
|
|
804
|
+
const checkpoint = this.nodes.get(id);
|
|
805
|
+
if (!checkpoint)
|
|
806
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
807
|
+
return checkpoint;
|
|
808
|
+
}
|
|
809
|
+
head(branch = "main") {
|
|
810
|
+
const id = this.heads.get(branch);
|
|
811
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
812
|
+
}
|
|
813
|
+
hasBranch(branch) {
|
|
814
|
+
return this.heads.has(branch);
|
|
815
|
+
}
|
|
816
|
+
branches() {
|
|
817
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
818
|
+
}
|
|
819
|
+
checkpoints() {
|
|
820
|
+
return [...this.nodes.values()];
|
|
821
|
+
}
|
|
822
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
823
|
+
get size() {
|
|
824
|
+
return this.nodes.size;
|
|
825
|
+
}
|
|
826
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
827
|
+
retain(id) {
|
|
828
|
+
const checkpoint = this.get(id);
|
|
829
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
830
|
+
this.addReference(id);
|
|
831
|
+
return checkpoint;
|
|
832
|
+
}
|
|
833
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
834
|
+
release(id) {
|
|
835
|
+
if (!this.nodes.has(id))
|
|
836
|
+
return false;
|
|
837
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
838
|
+
if (pins === 0)
|
|
839
|
+
return false;
|
|
840
|
+
if (pins === 1)
|
|
841
|
+
this.explicitPins.delete(id);
|
|
842
|
+
else
|
|
843
|
+
this.explicitPins.set(id, pins - 1);
|
|
844
|
+
this.removeReference(id);
|
|
845
|
+
this.collect(this.maxCheckpoints);
|
|
846
|
+
return true;
|
|
847
|
+
}
|
|
848
|
+
deleteBranch(branch) {
|
|
849
|
+
if (branch === "main")
|
|
850
|
+
throw new RangeError("cannot delete main branch");
|
|
851
|
+
const previous = this.heads.get(branch);
|
|
852
|
+
const deleted = this.heads.delete(branch);
|
|
853
|
+
if (previous !== void 0)
|
|
854
|
+
this.removeReference(previous);
|
|
855
|
+
this.collect(this.maxCheckpoints);
|
|
856
|
+
return deleted;
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
860
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
861
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
862
|
+
*/
|
|
863
|
+
gc(max = this.maxCheckpoints) {
|
|
864
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
865
|
+
throw new RangeError("max must be a positive integer");
|
|
866
|
+
const removed = [];
|
|
867
|
+
this.collect(max, removed);
|
|
868
|
+
return removed;
|
|
869
|
+
}
|
|
870
|
+
collect(max, removed) {
|
|
871
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
872
|
+
const id = this.evictable.values().next().value;
|
|
873
|
+
this.evictable.delete(id);
|
|
874
|
+
this.nodes.delete(id);
|
|
875
|
+
removed?.push(id);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
moveHead(branch, id) {
|
|
879
|
+
const previous = this.heads.get(branch);
|
|
880
|
+
if (previous === id)
|
|
881
|
+
return;
|
|
882
|
+
if (previous !== void 0)
|
|
883
|
+
this.removeReference(previous);
|
|
884
|
+
this.heads.set(branch, id);
|
|
885
|
+
this.addReference(id);
|
|
886
|
+
}
|
|
887
|
+
addReference(id) {
|
|
888
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
889
|
+
this.evictable.delete(id);
|
|
890
|
+
}
|
|
891
|
+
removeReference(id) {
|
|
892
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
893
|
+
if (next > 0)
|
|
894
|
+
this.references.set(id, next);
|
|
895
|
+
else {
|
|
896
|
+
this.references.delete(id);
|
|
897
|
+
if (this.nodes.has(id))
|
|
898
|
+
this.evictable.add(id);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
assertBranch(branch) {
|
|
902
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
903
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
// ../../sqlite/dist/default.js
|
|
908
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
909
|
+
var createDefaultSqlite = () => new Database();
|
|
910
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
911
|
+
|
|
912
|
+
// ../../sqlite/dist/migrate.js
|
|
913
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
914
|
+
sqlite.exec(`
|
|
915
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
916
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
917
|
+
applied_at INTEGER NOT NULL
|
|
918
|
+
)
|
|
919
|
+
`);
|
|
920
|
+
};
|
|
921
|
+
var migrate = (sqlite, migrations) => {
|
|
922
|
+
ensureMigrationsTable(sqlite);
|
|
923
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
924
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
925
|
+
if (pending.length === 0)
|
|
926
|
+
return;
|
|
927
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
928
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
929
|
+
sqlite.transaction(() => {
|
|
930
|
+
for (const migration of pending) {
|
|
931
|
+
sqlite.exec(migration.sql);
|
|
932
|
+
insert.run(migration.id, now);
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
};
|
|
936
|
+
|
|
937
|
+
// ../../sqlite/dist/schema.js
|
|
938
|
+
var CORE_MIGRATIONS = [
|
|
939
|
+
{
|
|
940
|
+
id: "20260322_core_records_sequences",
|
|
941
|
+
sql: `
|
|
942
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
943
|
+
namespace TEXT NOT NULL,
|
|
944
|
+
collection TEXT NOT NULL,
|
|
945
|
+
id TEXT NOT NULL,
|
|
946
|
+
seq INTEGER NOT NULL,
|
|
947
|
+
value TEXT NOT NULL,
|
|
948
|
+
PRIMARY KEY (namespace, collection, id)
|
|
949
|
+
);
|
|
950
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
951
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
952
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
953
|
+
namespace TEXT NOT NULL,
|
|
954
|
+
name TEXT NOT NULL,
|
|
955
|
+
kind TEXT NOT NULL,
|
|
956
|
+
value INTEGER NOT NULL,
|
|
957
|
+
PRIMARY KEY (namespace, name, kind)
|
|
958
|
+
);
|
|
959
|
+
`
|
|
960
|
+
}
|
|
961
|
+
];
|
|
962
|
+
var migrateCore = (sqlite) => {
|
|
963
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
964
|
+
};
|
|
965
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
966
|
+
sqlite.transaction(() => {
|
|
967
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
968
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
969
|
+
});
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
// ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request/constants.js
|
|
973
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
974
|
+
|
|
975
|
+
// ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/body.js
|
|
976
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
977
|
+
const { all = false, dot = false } = options;
|
|
978
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
979
|
+
const contentType = headers.get("Content-Type");
|
|
980
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
981
|
+
return parseFormData(request, { all, dot });
|
|
982
|
+
}
|
|
983
|
+
return {};
|
|
984
|
+
};
|
|
985
|
+
async function parseFormData(request, options) {
|
|
986
|
+
const formData = await request.formData();
|
|
987
|
+
if (formData) {
|
|
988
|
+
return convertFormDataToBodyData(formData, options);
|
|
989
|
+
}
|
|
990
|
+
return {};
|
|
991
|
+
}
|
|
992
|
+
function convertFormDataToBodyData(formData, options) {
|
|
993
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
994
|
+
formData.forEach((value, key) => {
|
|
995
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
996
|
+
if (!shouldParseAllValues) {
|
|
997
|
+
form[key] = value;
|
|
998
|
+
} else {
|
|
999
|
+
handleParsingAllValues(form, key, value);
|
|
1000
|
+
}
|
|
1001
|
+
});
|
|
1002
|
+
if (options.dot) {
|
|
1003
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
1004
|
+
const shouldParseDotValues = key.includes(".");
|
|
1005
|
+
if (shouldParseDotValues) {
|
|
1006
|
+
handleParsingNestedValues(form, key, value);
|
|
1007
|
+
delete form[key];
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
return form;
|
|
1012
|
+
}
|
|
1013
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
1014
|
+
if (form[key] !== void 0) {
|
|
1015
|
+
if (Array.isArray(form[key])) {
|
|
1016
|
+
;
|
|
1017
|
+
form[key].push(value);
|
|
1018
|
+
} else {
|
|
1019
|
+
form[key] = [form[key], value];
|
|
1020
|
+
}
|
|
1021
|
+
} else {
|
|
1022
|
+
if (!key.endsWith("[]")) {
|
|
1023
|
+
form[key] = value;
|
|
1024
|
+
} else {
|
|
1025
|
+
form[key] = [value];
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
1030
|
+
let nestedForm = form;
|
|
1031
|
+
const keys = key.split(".");
|
|
1032
|
+
keys.forEach((key2, index) => {
|
|
1033
|
+
if (index === keys.length - 1) {
|
|
1034
|
+
nestedForm[key2] = value;
|
|
1035
|
+
} else {
|
|
1036
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
1037
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
1038
|
+
}
|
|
1039
|
+
nestedForm = nestedForm[key2];
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
};
|
|
1043
|
+
|
|
1044
|
+
// ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/utils/url.js
|
|
1045
|
+
var tryDecode = (str, decoder) => {
|
|
1046
|
+
try {
|
|
1047
|
+
return decoder(str);
|
|
1048
|
+
} catch {
|
|
1049
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
1050
|
+
try {
|
|
1051
|
+
return decoder(match2);
|
|
1052
|
+
} catch {
|
|
1053
|
+
return match2;
|
|
1054
|
+
}
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
var _decodeURI = (value) => {
|
|
1059
|
+
if (!/[%+]/.test(value)) {
|
|
1060
|
+
return value;
|
|
1061
|
+
}
|
|
1062
|
+
if (value.indexOf("+") !== -1) {
|
|
1063
|
+
value = value.replace(/\+/g, " ");
|
|
1064
|
+
}
|
|
1065
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
1066
|
+
};
|
|
1067
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
1068
|
+
let encoded;
|
|
1069
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
1070
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
1071
|
+
if (keyIndex2 === -1) {
|
|
1072
|
+
return void 0;
|
|
1073
|
+
}
|
|
1074
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
1075
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1076
|
+
}
|
|
1077
|
+
while (keyIndex2 !== -1) {
|
|
1078
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
1079
|
+
if (trailingKeyCode === 61) {
|
|
1080
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
1081
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
1082
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
1083
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
1084
|
+
return "";
|
|
1085
|
+
}
|
|
1086
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1087
|
+
}
|
|
1088
|
+
encoded = /[%+]/.test(url);
|
|
1089
|
+
if (!encoded) {
|
|
1090
|
+
return void 0;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
const results = {};
|
|
1094
|
+
encoded ??= /[%+]/.test(url);
|
|
1095
|
+
let keyIndex = url.indexOf("?", 8);
|
|
1096
|
+
while (keyIndex !== -1) {
|
|
1097
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
1098
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
1099
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
1100
|
+
valueIndex = -1;
|
|
1101
|
+
}
|
|
1102
|
+
let name = url.slice(
|
|
1103
|
+
keyIndex + 1,
|
|
1104
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
1105
|
+
);
|
|
1106
|
+
if (encoded) {
|
|
1107
|
+
name = _decodeURI(name);
|
|
1108
|
+
}
|
|
1109
|
+
keyIndex = nextKeyIndex;
|
|
1110
|
+
if (name === "") {
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
let value;
|
|
1114
|
+
if (valueIndex === -1) {
|
|
1115
|
+
value = "";
|
|
1116
|
+
} else {
|
|
1117
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
1118
|
+
if (encoded) {
|
|
1119
|
+
value = _decodeURI(value);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
if (multiple) {
|
|
1123
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1124
|
+
results[name] = [];
|
|
1125
|
+
}
|
|
1126
|
+
;
|
|
1127
|
+
results[name].push(value);
|
|
1128
|
+
} else {
|
|
1129
|
+
results[name] ??= value;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
return key ? results[key] : results;
|
|
1133
|
+
};
|
|
1134
|
+
var getQueryParam = _getQueryParam;
|
|
1135
|
+
var getQueryParams = (url, key) => {
|
|
1136
|
+
return _getQueryParam(url, key, true);
|
|
1137
|
+
};
|
|
1138
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1139
|
+
|
|
1140
|
+
// ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request.js
|
|
1141
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1142
|
+
var HonoRequest = class {
|
|
1143
|
+
/**
|
|
1144
|
+
* `.raw` can get the raw Request object.
|
|
1145
|
+
*
|
|
1146
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1147
|
+
*
|
|
1148
|
+
* @example
|
|
1149
|
+
* ```ts
|
|
1150
|
+
* // For Cloudflare Workers
|
|
1151
|
+
* app.post('/', async (c) => {
|
|
1152
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1153
|
+
* ...
|
|
1154
|
+
* })
|
|
1155
|
+
* ```
|
|
1156
|
+
*/
|
|
1157
|
+
raw;
|
|
1158
|
+
#validatedData;
|
|
1159
|
+
// Short name of validatedData
|
|
1160
|
+
#matchResult;
|
|
1161
|
+
routeIndex = 0;
|
|
1162
|
+
/**
|
|
1163
|
+
* `.path` can get the pathname of the request.
|
|
1164
|
+
*
|
|
1165
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1166
|
+
*
|
|
1167
|
+
* @example
|
|
1168
|
+
* ```ts
|
|
1169
|
+
* app.get('/about/me', (c) => {
|
|
1170
|
+
* const pathname = c.req.path // `/about/me`
|
|
1171
|
+
* })
|
|
1172
|
+
* ```
|
|
1173
|
+
*/
|
|
1174
|
+
path;
|
|
1175
|
+
bodyCache = {};
|
|
1176
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1177
|
+
this.raw = request;
|
|
1178
|
+
this.path = path;
|
|
1179
|
+
this.#matchResult = matchResult;
|
|
1180
|
+
this.#validatedData = {};
|
|
1181
|
+
}
|
|
1182
|
+
param(key) {
|
|
1183
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1184
|
+
}
|
|
1185
|
+
#getDecodedParam(key) {
|
|
1186
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1187
|
+
const param = this.#getParamValue(paramKey);
|
|
1188
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1189
|
+
}
|
|
1190
|
+
#getAllDecodedParams() {
|
|
1191
|
+
const decoded = {};
|
|
1192
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1193
|
+
for (const key of keys) {
|
|
1194
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1195
|
+
if (value !== void 0) {
|
|
1196
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return decoded;
|
|
1200
|
+
}
|
|
1201
|
+
#getParamValue(paramKey) {
|
|
1202
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1203
|
+
}
|
|
1204
|
+
query(key) {
|
|
1205
|
+
return getQueryParam(this.url, key);
|
|
1206
|
+
}
|
|
1207
|
+
queries(key) {
|
|
1208
|
+
return getQueryParams(this.url, key);
|
|
1209
|
+
}
|
|
1210
|
+
header(name) {
|
|
1211
|
+
if (name) {
|
|
1212
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1213
|
+
}
|
|
1214
|
+
const headerData = {};
|
|
1215
|
+
this.raw.headers.forEach((value, key) => {
|
|
1216
|
+
headerData[key] = value;
|
|
1217
|
+
});
|
|
1218
|
+
return headerData;
|
|
1219
|
+
}
|
|
1220
|
+
async parseBody(options) {
|
|
1221
|
+
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
1222
|
+
}
|
|
1223
|
+
#cachedBody = (key) => {
|
|
1224
|
+
const { bodyCache, raw } = this;
|
|
1225
|
+
const cachedBody = bodyCache[key];
|
|
1226
|
+
if (cachedBody) {
|
|
1227
|
+
return cachedBody;
|
|
1228
|
+
}
|
|
1229
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1230
|
+
if (anyCachedKey) {
|
|
1231
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1232
|
+
if (anyCachedKey === "json") {
|
|
1233
|
+
body = JSON.stringify(body);
|
|
1234
|
+
}
|
|
1235
|
+
return new Response(body)[key]();
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
return bodyCache[key] = raw[key]();
|
|
1239
|
+
};
|
|
1240
|
+
/**
|
|
1241
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1242
|
+
*
|
|
1243
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1244
|
+
*
|
|
1245
|
+
* @example
|
|
1246
|
+
* ```ts
|
|
1247
|
+
* app.post('/entry', async (c) => {
|
|
1248
|
+
* const body = await c.req.json()
|
|
1249
|
+
* })
|
|
1250
|
+
* ```
|
|
1251
|
+
*/
|
|
1252
|
+
json() {
|
|
1253
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1257
|
+
*
|
|
1258
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1259
|
+
*
|
|
1260
|
+
* @example
|
|
1261
|
+
* ```ts
|
|
1262
|
+
* app.post('/entry', async (c) => {
|
|
1263
|
+
* const body = await c.req.text()
|
|
1264
|
+
* })
|
|
1265
|
+
* ```
|
|
1266
|
+
*/
|
|
1267
|
+
text() {
|
|
1268
|
+
return this.#cachedBody("text");
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1272
|
+
*
|
|
1273
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1274
|
+
*
|
|
1275
|
+
* @example
|
|
1276
|
+
* ```ts
|
|
1277
|
+
* app.post('/entry', async (c) => {
|
|
1278
|
+
* const body = await c.req.arrayBuffer()
|
|
1279
|
+
* })
|
|
1280
|
+
* ```
|
|
1281
|
+
*/
|
|
1282
|
+
arrayBuffer() {
|
|
1283
|
+
return this.#cachedBody("arrayBuffer");
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Parses the request body as a `Blob`.
|
|
1287
|
+
* @example
|
|
1288
|
+
* ```ts
|
|
1289
|
+
* app.post('/entry', async (c) => {
|
|
1290
|
+
* const body = await c.req.blob();
|
|
1291
|
+
* });
|
|
1292
|
+
* ```
|
|
1293
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
1294
|
+
*/
|
|
1295
|
+
blob() {
|
|
1296
|
+
return this.#cachedBody("blob");
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Parses the request body as `FormData`.
|
|
1300
|
+
* @example
|
|
1301
|
+
* ```ts
|
|
1302
|
+
* app.post('/entry', async (c) => {
|
|
1303
|
+
* const body = await c.req.formData();
|
|
1304
|
+
* });
|
|
1305
|
+
* ```
|
|
1306
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
1307
|
+
*/
|
|
1308
|
+
formData() {
|
|
1309
|
+
return this.#cachedBody("formData");
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Adds validated data to the request.
|
|
1313
|
+
*
|
|
1314
|
+
* @param target - The target of the validation.
|
|
1315
|
+
* @param data - The validated data to add.
|
|
1316
|
+
*/
|
|
1317
|
+
addValidatedData(target, data) {
|
|
1318
|
+
this.#validatedData[target] = data;
|
|
1319
|
+
}
|
|
1320
|
+
valid(target) {
|
|
1321
|
+
return this.#validatedData[target];
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* `.url()` can get the request url strings.
|
|
1325
|
+
*
|
|
1326
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
1327
|
+
*
|
|
1328
|
+
* @example
|
|
1329
|
+
* ```ts
|
|
1330
|
+
* app.get('/about/me', (c) => {
|
|
1331
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
1332
|
+
* ...
|
|
1333
|
+
* })
|
|
1334
|
+
* ```
|
|
1335
|
+
*/
|
|
1336
|
+
get url() {
|
|
1337
|
+
return this.raw.url;
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* `.method()` can get the method name of the request.
|
|
1341
|
+
*
|
|
1342
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
1343
|
+
*
|
|
1344
|
+
* @example
|
|
1345
|
+
* ```ts
|
|
1346
|
+
* app.get('/about/me', (c) => {
|
|
1347
|
+
* const method = c.req.method // `GET`
|
|
1348
|
+
* })
|
|
1349
|
+
* ```
|
|
1350
|
+
*/
|
|
1351
|
+
get method() {
|
|
1352
|
+
return this.raw.method;
|
|
1353
|
+
}
|
|
1354
|
+
get [GET_MATCH_RESULT]() {
|
|
1355
|
+
return this.#matchResult;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
1359
|
+
*
|
|
1360
|
+
* @deprecated
|
|
1361
|
+
*
|
|
1362
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
1363
|
+
*
|
|
1364
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
1365
|
+
*
|
|
1366
|
+
* @example
|
|
1367
|
+
* ```ts
|
|
1368
|
+
* app.use('*', async function logger(c, next) {
|
|
1369
|
+
* await next()
|
|
1370
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
1371
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
1372
|
+
* console.log(
|
|
1373
|
+
* method,
|
|
1374
|
+
* ' ',
|
|
1375
|
+
* path,
|
|
1376
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
1377
|
+
* name,
|
|
1378
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
1379
|
+
* )
|
|
1380
|
+
* })
|
|
1381
|
+
* })
|
|
1382
|
+
* ```
|
|
1383
|
+
*/
|
|
1384
|
+
get matchedRoutes() {
|
|
1385
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
1389
|
+
*
|
|
1390
|
+
* @deprecated
|
|
1391
|
+
*
|
|
1392
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
1393
|
+
*
|
|
1394
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
1395
|
+
*
|
|
1396
|
+
* @example
|
|
1397
|
+
* ```ts
|
|
1398
|
+
* app.get('/posts/:id', (c) => {
|
|
1399
|
+
* return c.json({ path: c.req.routePath })
|
|
1400
|
+
* })
|
|
1401
|
+
* ```
|
|
1402
|
+
*/
|
|
1403
|
+
get routePath() {
|
|
1404
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1405
|
+
}
|
|
1406
|
+
};
|
|
1407
|
+
|
|
1408
|
+
// ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
1409
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
1410
|
+
|
|
1411
|
+
// ../core/dist/service.js
|
|
1412
|
+
var bootSqlite = (sqlite) => {
|
|
1413
|
+
const client = resolveSqlite(sqlite);
|
|
1414
|
+
migrateCore(client);
|
|
1415
|
+
return client;
|
|
1416
|
+
};
|
|
1417
|
+
|
|
1418
|
+
// ../core/dist/snapshot.js
|
|
1419
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1420
|
+
namespace,
|
|
1421
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1422
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1423
|
+
});
|
|
1424
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1425
|
+
sqlite.transaction(() => {
|
|
1426
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1427
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1428
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1429
|
+
for (const row of snapshot.records) {
|
|
1430
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1431
|
+
}
|
|
1432
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1433
|
+
for (const row of snapshot.sequences) {
|
|
1434
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
};
|
|
1438
|
+
|
|
1439
|
+
// ../core/dist/version.js
|
|
1440
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1441
|
+
|
|
1442
|
+
// ../core/dist/webhooks.js
|
|
1443
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1444
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1445
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1446
|
+
var parseEndpoint = (value) => {
|
|
1447
|
+
if (!isRecord2(value) || typeof value.url !== "string")
|
|
1448
|
+
return "each endpoint needs a url";
|
|
1449
|
+
try {
|
|
1450
|
+
new URL(value.url);
|
|
1451
|
+
} catch {
|
|
1452
|
+
return `not a URL: ${value.url}`;
|
|
1453
|
+
}
|
|
1454
|
+
const endpoint = { url: value.url };
|
|
1455
|
+
if (typeof value.id === "string")
|
|
1456
|
+
endpoint.id = value.id;
|
|
1457
|
+
if (typeof value.secret === "string")
|
|
1458
|
+
endpoint.secret = value.secret;
|
|
1459
|
+
if (typeof value.signUrl === "string")
|
|
1460
|
+
endpoint.signUrl = value.signUrl;
|
|
1461
|
+
const events = value.events ?? value.enabledEvents;
|
|
1462
|
+
if (Array.isArray(events))
|
|
1463
|
+
endpoint.events = events.map(String);
|
|
1464
|
+
if (isRecord2(value.tags)) {
|
|
1465
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1466
|
+
}
|
|
1467
|
+
if (typeof value.account === "string")
|
|
1468
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1469
|
+
if (isRecord2(value.headers)) {
|
|
1470
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1471
|
+
}
|
|
1472
|
+
return endpoint;
|
|
1473
|
+
};
|
|
1474
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1475
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1476
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1477
|
+
const type = url.searchParams.get("type");
|
|
1478
|
+
return type === null || d.type === type;
|
|
1479
|
+
})
|
|
1480
|
+
}),
|
|
1481
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1482
|
+
const type = url.searchParams.get("type");
|
|
1483
|
+
return json2(200, {
|
|
1484
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1485
|
+
});
|
|
1486
|
+
},
|
|
1487
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1488
|
+
const replayed = await hub.replay(params.id);
|
|
1489
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1490
|
+
},
|
|
1491
|
+
"POST /webhooks/flush": async () => {
|
|
1492
|
+
await hub.flush();
|
|
1493
|
+
return json2(200, { status: "ok" });
|
|
1494
|
+
},
|
|
1495
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1496
|
+
if (!isRecord2(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1497
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1498
|
+
}
|
|
1499
|
+
const fault = { mode: body.mode };
|
|
1500
|
+
if (typeof body.count === "number")
|
|
1501
|
+
fault.count = body.count;
|
|
1502
|
+
hub.fault(namespace, fault);
|
|
1503
|
+
return json2(201, { namespace, ...fault });
|
|
1504
|
+
},
|
|
1505
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1506
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1507
|
+
...rest,
|
|
1508
|
+
secret: secret ? "(set)" : null
|
|
1509
|
+
}))
|
|
1510
|
+
}),
|
|
1511
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1512
|
+
const list = Array.isArray(body) ? body : isRecord2(body) ? body.endpoints : void 0;
|
|
1513
|
+
if (!Array.isArray(list))
|
|
1514
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1515
|
+
const parsed = [];
|
|
1516
|
+
for (const each of list) {
|
|
1517
|
+
const endpoint = parseEndpoint(each);
|
|
1518
|
+
if (typeof endpoint === "string")
|
|
1519
|
+
return adminError2(400, endpoint);
|
|
1520
|
+
parsed.push(endpoint);
|
|
1521
|
+
}
|
|
1522
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1523
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1524
|
+
},
|
|
1525
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1526
|
+
hub.setEndpoints(namespace, []);
|
|
1527
|
+
return json2(200, { status: "ok" });
|
|
1528
|
+
}
|
|
1529
|
+
});
|
|
1530
|
+
var parsePayload = (message) => {
|
|
1531
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1532
|
+
try {
|
|
1533
|
+
return JSON.parse(message.body);
|
|
1534
|
+
} catch {
|
|
1535
|
+
return message.body;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1539
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1540
|
+
}
|
|
1541
|
+
return message.body;
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1544
|
+
// ../core/dist/runtime.js
|
|
1545
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1546
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1547
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1548
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1549
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1550
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1551
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1552
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1553
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1554
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1555
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1556
|
+
if (!previous || previous.length === 0)
|
|
1557
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1558
|
+
const result = new Array(fresh.length);
|
|
1559
|
+
let unchanged = fresh.length === previous.length;
|
|
1560
|
+
let oldIndex = 0;
|
|
1561
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1562
|
+
const row = fresh[index];
|
|
1563
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1564
|
+
oldIndex++;
|
|
1565
|
+
}
|
|
1566
|
+
const old = previous[oldIndex];
|
|
1567
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1568
|
+
if (result[index] !== previous[index])
|
|
1569
|
+
unchanged = false;
|
|
1570
|
+
}
|
|
1571
|
+
return unchanged ? previous : result;
|
|
1572
|
+
};
|
|
1573
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1574
|
+
code = "MOCKINGBIRD_DROP";
|
|
1575
|
+
constructor() {
|
|
1576
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1577
|
+
this.name = "TypeError";
|
|
1578
|
+
}
|
|
1579
|
+
};
|
|
1580
|
+
var operationMatcher = (document2) => {
|
|
1581
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1582
|
+
operationId: operation.operationId,
|
|
1583
|
+
method: operation.method.toUpperCase(),
|
|
1584
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1585
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1586
|
+
})).sort((a, b) => a.params - b.params);
|
|
1587
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1588
|
+
};
|
|
1589
|
+
var createRuntime = (options) => {
|
|
1590
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1591
|
+
const clock = options.clock ?? createClock();
|
|
1592
|
+
const rng = createRng(options.seed ?? 0);
|
|
1593
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1594
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1595
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1596
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1597
|
+
const metrics = createMetrics();
|
|
1598
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1599
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1600
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1601
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1602
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1603
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1604
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1605
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1606
|
+
const credentials = createCredentialRegistry();
|
|
1607
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1608
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1609
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1610
|
+
const existing = instances.get(key);
|
|
1611
|
+
if (existing)
|
|
1612
|
+
return existing;
|
|
1613
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1614
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1615
|
+
}
|
|
1616
|
+
const created = options.create({
|
|
1617
|
+
namespace: storageNamespace(key),
|
|
1618
|
+
publicNamespace,
|
|
1619
|
+
sqlite,
|
|
1620
|
+
clock,
|
|
1621
|
+
rng: isolatedRng ?? rng
|
|
1622
|
+
});
|
|
1623
|
+
instances.set(key, created);
|
|
1624
|
+
publicNamespaces.add(publicNamespace);
|
|
1625
|
+
if (isolatedRng)
|
|
1626
|
+
branchRngs.set(key, isolatedRng);
|
|
1627
|
+
return created;
|
|
1628
|
+
};
|
|
1629
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1630
|
+
const capture = (storage) => {
|
|
1631
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1632
|
+
const previous = captured.get(storage);
|
|
1633
|
+
const snapshot2 = {
|
|
1634
|
+
namespace: fresh.namespace,
|
|
1635
|
+
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),
|
|
1636
|
+
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)
|
|
1637
|
+
};
|
|
1638
|
+
Object.freeze(snapshot2.records);
|
|
1639
|
+
Object.freeze(snapshot2.sequences);
|
|
1640
|
+
Object.freeze(snapshot2);
|
|
1641
|
+
captured.set(storage, snapshot2);
|
|
1642
|
+
return Object.freeze({
|
|
1643
|
+
snapshot: snapshot2,
|
|
1644
|
+
clock: Object.freeze(clock.state()),
|
|
1645
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1646
|
+
});
|
|
1647
|
+
};
|
|
1648
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1649
|
+
let found = timelines.get(name);
|
|
1650
|
+
if (found)
|
|
1651
|
+
return found;
|
|
1652
|
+
instance(name);
|
|
1653
|
+
found = new Timeline({
|
|
1654
|
+
now: clock.now,
|
|
1655
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1656
|
+
});
|
|
1657
|
+
found.commit(capture(name));
|
|
1658
|
+
timelines.set(name, found);
|
|
1659
|
+
return found;
|
|
1660
|
+
};
|
|
1661
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1662
|
+
if (branch2 === "main")
|
|
1663
|
+
return namespace;
|
|
1664
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1665
|
+
const existing = branchStorage.get(mapKey);
|
|
1666
|
+
if (existing)
|
|
1667
|
+
return existing;
|
|
1668
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1669
|
+
branchStorage.set(mapKey, key);
|
|
1670
|
+
return key;
|
|
1671
|
+
};
|
|
1672
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1673
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1674
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1675
|
+
const history = timeline(namespace);
|
|
1676
|
+
if (branch2 === "main") {
|
|
1677
|
+
if (at !== void 0) {
|
|
1678
|
+
const point = history.checkout("main", at);
|
|
1679
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1680
|
+
captured.set(namespace, point.value.snapshot);
|
|
1681
|
+
rng.setState(point.value.rngState);
|
|
1682
|
+
clock.set(point.value.clock.now);
|
|
1683
|
+
if (point.value.clock.frozen)
|
|
1684
|
+
clock.freeze();
|
|
1685
|
+
else
|
|
1686
|
+
clock.unfreeze();
|
|
1687
|
+
}
|
|
1688
|
+
return namespace;
|
|
1689
|
+
}
|
|
1690
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1691
|
+
if (!history.hasBranch(branch2)) {
|
|
1692
|
+
if (at === void 0)
|
|
1693
|
+
history.commit(capture(namespace));
|
|
1694
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1695
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1696
|
+
if (point)
|
|
1697
|
+
branchRng.setState(point.value.rngState);
|
|
1698
|
+
instanceFor(storage, namespace, branchRng);
|
|
1699
|
+
if (point)
|
|
1700
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1701
|
+
if (point)
|
|
1702
|
+
captured.set(storage, point.value.snapshot);
|
|
1703
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1704
|
+
const point = history.checkout(branch2, at);
|
|
1705
|
+
if (!instances.has(storage)) {
|
|
1706
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1707
|
+
branchRng.setState(point.value.rngState);
|
|
1708
|
+
instanceFor(storage, namespace, branchRng);
|
|
1709
|
+
}
|
|
1710
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1711
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1712
|
+
captured.set(storage, point.value.snapshot);
|
|
1713
|
+
} else {
|
|
1714
|
+
if (!instances.has(storage)) {
|
|
1715
|
+
const point = history.head(branch2);
|
|
1716
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1717
|
+
if (point)
|
|
1718
|
+
branchRng.setState(point.value.rngState);
|
|
1719
|
+
instanceFor(storage, namespace, branchRng);
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
return storage;
|
|
1723
|
+
};
|
|
1724
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1725
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1726
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1727
|
+
};
|
|
1728
|
+
const branch = (name, branchOptions = {}) => {
|
|
1729
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1730
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1731
|
+
const head = timeline(namespace).head(name);
|
|
1732
|
+
if (!head)
|
|
1733
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1734
|
+
return head;
|
|
1735
|
+
};
|
|
1736
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1737
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1738
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1739
|
+
const history = timeline(namespace);
|
|
1740
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1741
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1742
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1743
|
+
captured.set(storage, point.value.snapshot);
|
|
1744
|
+
clock.set(point.value.clock.now);
|
|
1745
|
+
if (point.value.clock.frozen)
|
|
1746
|
+
clock.freeze();
|
|
1747
|
+
else
|
|
1748
|
+
clock.unfreeze();
|
|
1749
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1750
|
+
};
|
|
1751
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1752
|
+
if (name === "*") {
|
|
1753
|
+
options.webhooks?.clear();
|
|
1754
|
+
for (const each of instances.values())
|
|
1755
|
+
await each.reset();
|
|
1756
|
+
timelines.clear();
|
|
1757
|
+
branchStorage.clear();
|
|
1758
|
+
branchRngs.clear();
|
|
1759
|
+
captured.clear();
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
options.webhooks?.clear(name);
|
|
1763
|
+
const target = instances.get(name);
|
|
1764
|
+
if (target)
|
|
1765
|
+
await target.reset();
|
|
1766
|
+
else
|
|
1767
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1768
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1769
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1770
|
+
continue;
|
|
1771
|
+
const branchInstance = instances.get(storage);
|
|
1772
|
+
if (branchInstance)
|
|
1773
|
+
await branchInstance.reset();
|
|
1774
|
+
else
|
|
1775
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1776
|
+
branchStorage.delete(mapping);
|
|
1777
|
+
branchRngs.delete(storage);
|
|
1778
|
+
captured.delete(storage);
|
|
1779
|
+
}
|
|
1780
|
+
timelines.delete(name);
|
|
1781
|
+
captured.delete(name);
|
|
1782
|
+
};
|
|
1783
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1784
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1785
|
+
};
|
|
1786
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1787
|
+
instance(name);
|
|
1788
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1789
|
+
captured.set(name, from);
|
|
1790
|
+
const history = timelines.get(name);
|
|
1791
|
+
if (history)
|
|
1792
|
+
history.commit(capture(name), { branch: "main" });
|
|
1793
|
+
else
|
|
1794
|
+
timeline(name);
|
|
1795
|
+
};
|
|
1796
|
+
const runtime = {
|
|
1797
|
+
name: options.name,
|
|
1798
|
+
sqlite,
|
|
1799
|
+
clock,
|
|
1800
|
+
faults,
|
|
1801
|
+
metrics,
|
|
1802
|
+
journal,
|
|
1803
|
+
rng,
|
|
1804
|
+
credentials,
|
|
1805
|
+
webhooks: options.webhooks,
|
|
1806
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1807
|
+
const preset = options.presets?.[name];
|
|
1808
|
+
if (!preset)
|
|
1809
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1810
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1811
|
+
namespace,
|
|
1812
|
+
...rule,
|
|
1813
|
+
...overrides,
|
|
1814
|
+
preset: name,
|
|
1815
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1816
|
+
}));
|
|
1817
|
+
if (preset.webhook && options.webhooks) {
|
|
1818
|
+
options.webhooks.fault(namespace, {
|
|
1819
|
+
...preset.webhook,
|
|
1820
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
return added;
|
|
1824
|
+
},
|
|
1825
|
+
instance,
|
|
1826
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1827
|
+
reset,
|
|
1828
|
+
snapshot,
|
|
1829
|
+
restore,
|
|
1830
|
+
checkpoint,
|
|
1831
|
+
branch,
|
|
1832
|
+
checkout,
|
|
1833
|
+
timeline,
|
|
1834
|
+
fetch: async (incoming) => {
|
|
1835
|
+
let request = incoming;
|
|
1836
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1837
|
+
if (prefixed) {
|
|
1838
|
+
const url2 = new URL(request.url);
|
|
1839
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1840
|
+
const headers = new Headers(request.headers);
|
|
1841
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1842
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1843
|
+
}
|
|
1844
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1845
|
+
request = new Request(url2, {
|
|
1846
|
+
method: request.method,
|
|
1847
|
+
headers,
|
|
1848
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1849
|
+
signal: request.signal
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
let namespace = control.namespaceOf(request);
|
|
1853
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1854
|
+
const credential = options.credential(request);
|
|
1855
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1856
|
+
if (mapped !== void 0)
|
|
1857
|
+
namespace = mapped;
|
|
1858
|
+
}
|
|
1859
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1860
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1861
|
+
const stamp = (response2) => {
|
|
1862
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1863
|
+
try {
|
|
1864
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1865
|
+
return response2;
|
|
1866
|
+
} catch {
|
|
1867
|
+
const copy = new Response(response2.body, response2);
|
|
1868
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1869
|
+
return copy;
|
|
1870
|
+
}
|
|
1871
|
+
};
|
|
1872
|
+
const handled = await control.handle(request);
|
|
1873
|
+
if (handled)
|
|
1874
|
+
return stamp(handled);
|
|
1875
|
+
const started = monotonicNow();
|
|
1876
|
+
const url = new URL(request.url);
|
|
1877
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1878
|
+
const log = (status, faultId, response2) => {
|
|
1879
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1880
|
+
const entry = {
|
|
1881
|
+
service: options.name,
|
|
1882
|
+
namespace,
|
|
1883
|
+
operationId,
|
|
1884
|
+
method: request.method,
|
|
1885
|
+
path: url.pathname,
|
|
1886
|
+
status,
|
|
1887
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1888
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1889
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1890
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1891
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1892
|
+
};
|
|
1893
|
+
metrics.record(entry);
|
|
1894
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
1895
|
+
options.onLog?.(entry);
|
|
1896
|
+
};
|
|
1897
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
1898
|
+
log(400);
|
|
1899
|
+
return stamp(new Response(JSON.stringify({
|
|
1900
|
+
error: {
|
|
1901
|
+
type: "mockingbird_admin",
|
|
1902
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
1903
|
+
}
|
|
1904
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1905
|
+
}
|
|
1906
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
1907
|
+
log(400);
|
|
1908
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
1909
|
+
}
|
|
1910
|
+
let storage;
|
|
1911
|
+
try {
|
|
1912
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
1913
|
+
const point = timeline(namespace).get(at);
|
|
1914
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
1915
|
+
let viewRng = branchRngs.get(storage);
|
|
1916
|
+
if (!viewRng) {
|
|
1917
|
+
viewRng = createRng(options.seed ?? 0);
|
|
1918
|
+
instanceFor(storage, namespace, viewRng);
|
|
1919
|
+
}
|
|
1920
|
+
viewRng.setState(point.value.rngState);
|
|
1921
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1922
|
+
captured.set(storage, point.value.snapshot);
|
|
1923
|
+
} else {
|
|
1924
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
1925
|
+
}
|
|
1926
|
+
} catch (error) {
|
|
1927
|
+
log(409);
|
|
1928
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
1929
|
+
}
|
|
1930
|
+
const hits = await faults.take({
|
|
1931
|
+
operationId,
|
|
1932
|
+
method: request.method,
|
|
1933
|
+
path: url.pathname,
|
|
1934
|
+
namespace
|
|
1935
|
+
});
|
|
1936
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
1937
|
+
if (final?.drop) {
|
|
1938
|
+
log(0, final.id);
|
|
1939
|
+
throw new DroppedConnectionError();
|
|
1940
|
+
}
|
|
1941
|
+
if (final?.response) {
|
|
1942
|
+
log(final.response.status, final.id);
|
|
1943
|
+
return stamp(final.response);
|
|
1944
|
+
}
|
|
1945
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
1946
|
+
if (fired.length > 0)
|
|
1947
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
1948
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
1949
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
1950
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
1951
|
+
response = mutableResponse(response);
|
|
1952
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
1953
|
+
}
|
|
1954
|
+
if (selectedBranch !== "main") {
|
|
1955
|
+
response = mutableResponse(response);
|
|
1956
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
1957
|
+
}
|
|
1958
|
+
if (at !== void 0) {
|
|
1959
|
+
response = mutableResponse(response);
|
|
1960
|
+
response.headers.set(AT_HEADER, at);
|
|
1961
|
+
}
|
|
1962
|
+
log(response.status, fired[0]?.id, response);
|
|
1963
|
+
return stamp(response);
|
|
1964
|
+
}
|
|
1965
|
+
};
|
|
1966
|
+
const control = createControlPlane({
|
|
1967
|
+
name: options.name,
|
|
1968
|
+
startedAt: wallNow(),
|
|
1969
|
+
wallNow,
|
|
1970
|
+
clock,
|
|
1971
|
+
faults,
|
|
1972
|
+
metrics,
|
|
1973
|
+
journal,
|
|
1974
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
1975
|
+
namespaces: runtime.namespaces,
|
|
1976
|
+
reset,
|
|
1977
|
+
timeTravel: {
|
|
1978
|
+
checkpoint: (name, branchName) => {
|
|
1979
|
+
const point = checkpoint(name, branchName);
|
|
1980
|
+
return {
|
|
1981
|
+
id: point.id,
|
|
1982
|
+
branch: point.branch,
|
|
1983
|
+
parent: point.parent,
|
|
1984
|
+
at: point.at,
|
|
1985
|
+
records: point.value.snapshot.records.length
|
|
1986
|
+
};
|
|
1987
|
+
},
|
|
1988
|
+
branch: (branchName, branchOptions) => {
|
|
1989
|
+
const point = branch(branchName, branchOptions);
|
|
1990
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
1991
|
+
},
|
|
1992
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
1993
|
+
retain: (name, checkpointId) => {
|
|
1994
|
+
timeline(name).retain(checkpointId);
|
|
1995
|
+
},
|
|
1996
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
1997
|
+
inspect: (name) => {
|
|
1998
|
+
const history = timeline(name);
|
|
1999
|
+
return {
|
|
2000
|
+
branches: history.branches(),
|
|
2001
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2002
|
+
id,
|
|
2003
|
+
branch: branchName,
|
|
2004
|
+
parent,
|
|
2005
|
+
at
|
|
2006
|
+
}))
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
},
|
|
2010
|
+
describe: options.describe ?? (() => ({})),
|
|
2011
|
+
...options.presets ? {
|
|
2012
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2013
|
+
} : {},
|
|
2014
|
+
routes: {
|
|
2015
|
+
...credentialRoutes(credentials),
|
|
2016
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2017
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2018
|
+
...options.admin?.(runtime) ?? {}
|
|
2019
|
+
},
|
|
2020
|
+
adminKey: options.adminKey
|
|
2021
|
+
});
|
|
2022
|
+
return runtime;
|
|
2023
|
+
};
|
|
2024
|
+
var mutableResponse = (response) => {
|
|
2025
|
+
try {
|
|
2026
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2027
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2028
|
+
return response;
|
|
2029
|
+
} catch {
|
|
2030
|
+
return new Response(response.body, response);
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2034
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2035
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2036
|
+
var credentialRoutes = (registry) => ({
|
|
2037
|
+
"GET /credentials": () => adminJson(200, {
|
|
2038
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2039
|
+
credential: maskCredential(credential),
|
|
2040
|
+
namespace
|
|
2041
|
+
}))
|
|
2042
|
+
}),
|
|
2043
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2044
|
+
const pairs = [];
|
|
2045
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2046
|
+
if (Array.isArray(list)) {
|
|
2047
|
+
for (const each of list) {
|
|
2048
|
+
if (typeof each === "string")
|
|
2049
|
+
pairs.push([each, namespace]);
|
|
2050
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2051
|
+
pairs.push([
|
|
2052
|
+
each.credential,
|
|
2053
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2054
|
+
]);
|
|
2055
|
+
} else
|
|
2056
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2057
|
+
}
|
|
2058
|
+
} else if (isObject(list)) {
|
|
2059
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2060
|
+
if (typeof target !== "string")
|
|
2061
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2062
|
+
pairs.push([credential, target]);
|
|
2063
|
+
}
|
|
2064
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2065
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2066
|
+
} else {
|
|
2067
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2068
|
+
}
|
|
2069
|
+
for (const [credential, target] of pairs) {
|
|
2070
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2071
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2072
|
+
registry.set(credential, target);
|
|
2073
|
+
}
|
|
2074
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2075
|
+
},
|
|
2076
|
+
"DELETE /credentials": ({ url }) => {
|
|
2077
|
+
const credential = url.searchParams.get("credential");
|
|
2078
|
+
if (credential === null)
|
|
2079
|
+
registry.clear();
|
|
2080
|
+
else
|
|
2081
|
+
registry.remove(credential);
|
|
2082
|
+
return adminJson(200, { status: "ok" });
|
|
2083
|
+
}
|
|
2084
|
+
});
|
|
2085
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2086
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2087
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2088
|
+
}),
|
|
2089
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2090
|
+
const name = params.name;
|
|
2091
|
+
if (!presets[name])
|
|
2092
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2093
|
+
const overrides = isObject(body) ? body : {};
|
|
2094
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2095
|
+
}
|
|
2096
|
+
});
|
|
2097
|
+
|
|
2098
|
+
// src/generated/openapi.ts
|
|
2099
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"AWS Step Functions (Mockingbird subset)","version":"2016-11-23","description":"AWS JSON contract used by the pinned SFN client."},"servers":[{"url":"https://states.us-east-1.amazonaws.com"}],"paths":{"/":{"post":{"operationId":"StepFunctionsRpc","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"X-Amz-Target","in":"header","required":true,"schema":{"type":"string","pattern":"^AWSStepFunctions\\\\\\\\.[A-Za-z]+$"}}],"requestBody":{"required":true,"content":{"application/x-amz-json-1.0":{"schema":{"type":"object","additionalProperties":true}},"application/json":{"schema":{"type":"object","additionalProperties":true}}}},"responses":{"200":{"description":"Operation response","content":{"application/x-amz-json-1.0":{"schema":{"type":"object","additionalProperties":true}}}},"400":{"description":"SFN exception","content":{"application/x-amz-json-1.0":{"schema":{"type":"object","additionalProperties":true}}}}}}}}}`);
|
|
2100
|
+
var operationIds = ["StepFunctionsRpc"];
|
|
2101
|
+
var supportedOperationIds = ["StepFunctionsRpc"];
|
|
2102
|
+
|
|
2103
|
+
// src/state.ts
|
|
2104
|
+
var StepFunctionsState = class {
|
|
2105
|
+
machines;
|
|
2106
|
+
executions;
|
|
2107
|
+
history;
|
|
2108
|
+
ids;
|
|
2109
|
+
constructor(sqlite, namespace) {
|
|
2110
|
+
this.machines = new Collection(sqlite, namespace, "sfn_machines");
|
|
2111
|
+
this.executions = new Collection(sqlite, namespace, "sfn_executions");
|
|
2112
|
+
this.history = new Collection(sqlite, namespace, "sfn_history");
|
|
2113
|
+
this.ids = new IdSequence(sqlite, namespace, "sfn");
|
|
2114
|
+
}
|
|
2115
|
+
};
|
|
2116
|
+
|
|
2117
|
+
// src/runtime.ts
|
|
2118
|
+
var STEP_FUNCTIONS_PRESETS = {
|
|
2119
|
+
throttled: {
|
|
2120
|
+
description: "Step Functions answers ThrottlingException",
|
|
2121
|
+
rules: [
|
|
2122
|
+
{
|
|
2123
|
+
status: 400,
|
|
2124
|
+
body: { __type: "ThrottlingException", message: "Rate exceeded" },
|
|
2125
|
+
headers: { "content-type": "application/x-amz-json-1.0" }
|
|
2126
|
+
}
|
|
2127
|
+
]
|
|
2128
|
+
},
|
|
2129
|
+
unavailable: { description: "The next request loses its connection", rules: [{ drop: true }] }
|
|
2130
|
+
};
|
|
2131
|
+
var problem = (status, message) => Response.json({ error: { type: "mockingbird_admin", message } }, { status });
|
|
2132
|
+
var admin = (runtime) => ({
|
|
2133
|
+
"GET /state-machines": ({ namespace }) => Response.json({
|
|
2134
|
+
stateMachines: runtime.instance(namespace).state.machines.list().map(({ value }) => value)
|
|
2135
|
+
}),
|
|
2136
|
+
"POST /state-machines": ({ namespace, body }) => {
|
|
2137
|
+
const input = body;
|
|
2138
|
+
if (!input || typeof input.name !== "string") return problem(400, "name is required");
|
|
2139
|
+
return Response.json(runtime.instance(namespace).register(input), { status: 201 });
|
|
2140
|
+
},
|
|
2141
|
+
"GET /executions": ({ namespace }) => Response.json({
|
|
2142
|
+
executions: runtime.instance(namespace).state.executions.list({ order: "oldest" }).map(({ value }) => ({ ...value, taskToken: value.taskToken ? "[REDACTED]" : void 0 }))
|
|
2143
|
+
}),
|
|
2144
|
+
"GET /executions/:arn/task-token": ({ namespace, params }) => {
|
|
2145
|
+
const execution = runtime.instance(namespace).state.executions.get(params.arn);
|
|
2146
|
+
return execution?.taskToken ? Response.json({ taskToken: execution.taskToken }) : problem(404, "active callback token not found");
|
|
2147
|
+
},
|
|
2148
|
+
"POST /executions/:arn/transition": ({ namespace, params, body }) => {
|
|
2149
|
+
const input = body;
|
|
2150
|
+
const allowed = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "TIMED_OUT", "ABORTED"]);
|
|
2151
|
+
if (!input || typeof input.status !== "string" || !allowed.has(input.status))
|
|
2152
|
+
return problem(400, "terminal status is required");
|
|
2153
|
+
const moved = runtime.instance(namespace).transition(params.arn, input.status, {
|
|
2154
|
+
...typeof input.output === "string" ? { output: input.output } : {},
|
|
2155
|
+
...typeof input.error === "string" ? { error: input.error } : {},
|
|
2156
|
+
...typeof input.cause === "string" ? { cause: input.cause } : {}
|
|
2157
|
+
});
|
|
2158
|
+
return moved ? Response.json(moved) : problem(404, "running execution not found");
|
|
2159
|
+
}
|
|
2160
|
+
});
|
|
2161
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2162
|
+
name: STEP_FUNCTIONS_NAMESPACE,
|
|
2163
|
+
document,
|
|
2164
|
+
presets: STEP_FUNCTIONS_PRESETS,
|
|
2165
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2166
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2167
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2168
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2169
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2170
|
+
credential: accessKeyCredential,
|
|
2171
|
+
create: ({ sqlite, namespace, clock }) => new StepFunctionsAPI({
|
|
2172
|
+
sqlite,
|
|
2173
|
+
namespace,
|
|
2174
|
+
now: clock.now,
|
|
2175
|
+
...options.region ? { region: options.region } : {},
|
|
2176
|
+
...options.accountId ? { accountId: options.accountId } : {},
|
|
2177
|
+
...options.stateMachines ? { stateMachines: options.stateMachines } : {}
|
|
2178
|
+
}),
|
|
2179
|
+
admin
|
|
2180
|
+
});
|
|
2181
|
+
|
|
2182
|
+
// src/index.ts
|
|
2183
|
+
var STEP_FUNCTIONS_NAMESPACE = "step-functions";
|
|
2184
|
+
var accessKeyCredential = sigV4AccessKeyId;
|
|
2185
|
+
var StepFunctionsAPI = class {
|
|
2186
|
+
constructor(options = {}) {
|
|
2187
|
+
this.options = options;
|
|
2188
|
+
this.sqlite = bootSqlite(options.sqlite);
|
|
2189
|
+
this.namespace = options.namespace ?? STEP_FUNCTIONS_NAMESPACE;
|
|
2190
|
+
this.now = options.now ?? Date.now;
|
|
2191
|
+
this.region = options.region ?? "us-east-1";
|
|
2192
|
+
this.accountId = options.accountId ?? "000000000000";
|
|
2193
|
+
this.state = new StepFunctionsState(this.sqlite, this.namespace);
|
|
2194
|
+
this.seed();
|
|
2195
|
+
}
|
|
2196
|
+
options;
|
|
2197
|
+
state;
|
|
2198
|
+
sqlite;
|
|
2199
|
+
namespace;
|
|
2200
|
+
now;
|
|
2201
|
+
region;
|
|
2202
|
+
accountId;
|
|
2203
|
+
seed() {
|
|
2204
|
+
for (const machine of this.options.stateMachines ?? []) this.register(machine);
|
|
2205
|
+
}
|
|
2206
|
+
async reset() {
|
|
2207
|
+
clearNamespace(this.sqlite, this.namespace);
|
|
2208
|
+
this.seed();
|
|
2209
|
+
}
|
|
2210
|
+
register(input) {
|
|
2211
|
+
const machine = {
|
|
2212
|
+
...input,
|
|
2213
|
+
arn: input.arn ?? `arn:aws:states:${this.region}:${this.accountId}:stateMachine:${input.name}`
|
|
2214
|
+
};
|
|
2215
|
+
this.state.machines.insert(machine.arn, machine);
|
|
2216
|
+
return machine;
|
|
2217
|
+
}
|
|
2218
|
+
response(body, status = 200) {
|
|
2219
|
+
const id = this.state.ids.next("req-", 20);
|
|
2220
|
+
return new Response(JSON.stringify(body), {
|
|
2221
|
+
status,
|
|
2222
|
+
headers: { "content-type": "application/x-amz-json-1.0", "x-amzn-requestid": id }
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
error(type, message) {
|
|
2226
|
+
return this.response({ __type: type, message }, 400);
|
|
2227
|
+
}
|
|
2228
|
+
execution(arn) {
|
|
2229
|
+
return typeof arn === "string" ? this.state.executions.get(arn) : void 0;
|
|
2230
|
+
}
|
|
2231
|
+
events(arn) {
|
|
2232
|
+
return this.state.history.list({ where: (event) => event.executionArn === arn, order: "oldest" }).map(({ value }) => value);
|
|
2233
|
+
}
|
|
2234
|
+
event(execution, type, details) {
|
|
2235
|
+
const existing = this.events(execution.arn);
|
|
2236
|
+
const event = {
|
|
2237
|
+
id: existing.length + 1,
|
|
2238
|
+
executionArn: execution.arn,
|
|
2239
|
+
timestamp: this.now(),
|
|
2240
|
+
type,
|
|
2241
|
+
previousEventId: existing.at(-1)?.id ?? 0,
|
|
2242
|
+
...details ? { details } : {}
|
|
2243
|
+
};
|
|
2244
|
+
this.state.history.insert(`${execution.arn}:${event.id}`, event);
|
|
2245
|
+
return event;
|
|
2246
|
+
}
|
|
2247
|
+
json(value, type) {
|
|
2248
|
+
if (typeof value !== "string") throw new SyntaxError(`${type} must be a JSON string`);
|
|
2249
|
+
try {
|
|
2250
|
+
JSON.parse(value);
|
|
2251
|
+
} catch {
|
|
2252
|
+
throw new SyntaxError(`InvalidExecution${type === "input" ? "Input" : "Output"}`);
|
|
2253
|
+
}
|
|
2254
|
+
return value;
|
|
2255
|
+
}
|
|
2256
|
+
refresh(execution) {
|
|
2257
|
+
if (execution.status === "RUNNING" && execution.dueAt !== void 0 && execution.dueAt <= this.now()) {
|
|
2258
|
+
const machine = this.state.machines.get(execution.stateMachineArn);
|
|
2259
|
+
const scripted = machine?.scripted;
|
|
2260
|
+
if (scripted)
|
|
2261
|
+
return this.transition(execution.arn, scripted.status, {
|
|
2262
|
+
...scripted.output !== void 0 ? { output: scripted.output } : {},
|
|
2263
|
+
...scripted.error !== void 0 ? { error: scripted.error } : {},
|
|
2264
|
+
...scripted.cause !== void 0 ? { cause: scripted.cause } : {}
|
|
2265
|
+
}) ?? execution;
|
|
2266
|
+
}
|
|
2267
|
+
return execution;
|
|
2268
|
+
}
|
|
2269
|
+
transition(arn, status, values = {}) {
|
|
2270
|
+
const current = this.state.executions.get(arn);
|
|
2271
|
+
if (current?.status !== "RUNNING") return void 0;
|
|
2272
|
+
if (values.output !== void 0) this.json(values.output, "output");
|
|
2273
|
+
const next = {
|
|
2274
|
+
...current,
|
|
2275
|
+
status,
|
|
2276
|
+
stopDate: this.now(),
|
|
2277
|
+
...values.output !== void 0 ? { output: values.output } : {},
|
|
2278
|
+
...values.error !== void 0 ? { error: values.error } : {},
|
|
2279
|
+
...values.cause !== void 0 ? { cause: values.cause } : {}
|
|
2280
|
+
};
|
|
2281
|
+
this.state.executions.insert(arn, next);
|
|
2282
|
+
const suffix = status === "SUCCEEDED" ? "Succeeded" : status === "FAILED" ? "Failed" : status === "TIMED_OUT" ? "TimedOut" : "Aborted";
|
|
2283
|
+
this.event(next, `Execution${suffix}`, {
|
|
2284
|
+
...next.output !== void 0 ? { output: next.output } : {},
|
|
2285
|
+
...next.error !== void 0 ? { error: next.error } : {},
|
|
2286
|
+
...next.cause !== void 0 ? { cause: next.cause } : {}
|
|
2287
|
+
});
|
|
2288
|
+
return next;
|
|
2289
|
+
}
|
|
2290
|
+
publicExecution(execution) {
|
|
2291
|
+
const current = this.refresh(execution);
|
|
2292
|
+
return {
|
|
2293
|
+
executionArn: current.arn,
|
|
2294
|
+
stateMachineArn: current.stateMachineArn,
|
|
2295
|
+
name: current.name,
|
|
2296
|
+
status: current.status,
|
|
2297
|
+
startDate: current.startDate / 1e3,
|
|
2298
|
+
...current.stopDate !== void 0 ? { stopDate: current.stopDate / 1e3 } : {},
|
|
2299
|
+
input: current.input,
|
|
2300
|
+
...current.output !== void 0 ? { output: current.output } : {},
|
|
2301
|
+
...current.error !== void 0 ? { error: current.error } : {},
|
|
2302
|
+
...current.cause !== void 0 ? { cause: current.cause } : {},
|
|
2303
|
+
...current.traceHeader ? { traceHeader: current.traceHeader } : {}
|
|
2304
|
+
};
|
|
2305
|
+
}
|
|
2306
|
+
callback(token) {
|
|
2307
|
+
return typeof token === "string" ? this.state.executions.list({
|
|
2308
|
+
where: (execution) => execution.status === "RUNNING" && execution.taskToken === token
|
|
2309
|
+
}).map(({ value }) => value)[0] : void 0;
|
|
2310
|
+
}
|
|
2311
|
+
async fetch(request) {
|
|
2312
|
+
if (request.method !== "POST")
|
|
2313
|
+
return this.error("InvalidExecutionInput", "Only POST is supported");
|
|
2314
|
+
const operation = (request.headers.get("x-amz-target") ?? "").split(".").at(-1) ?? "";
|
|
2315
|
+
const input = await request.json().catch(() => ({}));
|
|
2316
|
+
try {
|
|
2317
|
+
if (operation === "StartExecution") {
|
|
2318
|
+
const arn = typeof input.stateMachineArn === "string" ? input.stateMachineArn : "";
|
|
2319
|
+
if (!arn.startsWith("arn:")) return this.error("InvalidArn", "Invalid Arn");
|
|
2320
|
+
const machine = this.state.machines.get(arn);
|
|
2321
|
+
if (!machine)
|
|
2322
|
+
return this.error("StateMachineDoesNotExist", `State Machine Does Not Exist: '${arn}'`);
|
|
2323
|
+
const executionInput = this.json(input.input ?? "{}", "input");
|
|
2324
|
+
const name = typeof input.name === "string" ? input.name : this.state.ids.next("exec-", 20);
|
|
2325
|
+
const prior = this.state.executions.list({
|
|
2326
|
+
where: (execution2) => execution2.stateMachineArn === arn && execution2.name === name
|
|
2327
|
+
}).map(({ value }) => value)[0];
|
|
2328
|
+
if (prior) {
|
|
2329
|
+
const current = this.refresh(prior);
|
|
2330
|
+
if (current.status === "RUNNING" && current.input === executionInput)
|
|
2331
|
+
return this.response({ executionArn: current.arn, startDate: current.startDate / 1e3 });
|
|
2332
|
+
return this.error("ExecutionAlreadyExists", `Execution Already Exists: '${current.arn}'`);
|
|
2333
|
+
}
|
|
2334
|
+
const executionArn = `${arn.replace(":stateMachine:", ":execution:")}:${name}`;
|
|
2335
|
+
const execution = {
|
|
2336
|
+
arn: executionArn,
|
|
2337
|
+
stateMachineArn: arn,
|
|
2338
|
+
name,
|
|
2339
|
+
input: executionInput,
|
|
2340
|
+
status: "RUNNING",
|
|
2341
|
+
startDate: this.now(),
|
|
2342
|
+
...typeof input.traceHeader === "string" ? { traceHeader: input.traceHeader } : {},
|
|
2343
|
+
...machine.taskToken ? { taskToken: this.state.ids.next("task-", 48) } : {},
|
|
2344
|
+
...machine.scripted?.afterMs !== void 0 ? { dueAt: this.now() + machine.scripted.afterMs } : {}
|
|
2345
|
+
};
|
|
2346
|
+
this.state.executions.insert(executionArn, execution);
|
|
2347
|
+
this.event(execution, "ExecutionStarted", {
|
|
2348
|
+
input: executionInput,
|
|
2349
|
+
...execution.traceHeader ? { traceHeader: execution.traceHeader } : {}
|
|
2350
|
+
});
|
|
2351
|
+
if (execution.taskToken) {
|
|
2352
|
+
this.event(execution, "TaskScheduled", { resource: "mockingbird:callback" });
|
|
2353
|
+
this.event(execution, "TaskStarted", { taskToken: execution.taskToken });
|
|
2354
|
+
}
|
|
2355
|
+
return this.response({ executionArn, startDate: execution.startDate / 1e3 });
|
|
2356
|
+
}
|
|
2357
|
+
if (operation === "DescribeExecution") {
|
|
2358
|
+
const execution = this.execution(input.executionArn);
|
|
2359
|
+
return execution ? this.response(this.publicExecution(execution)) : this.error(
|
|
2360
|
+
"ExecutionDoesNotExist",
|
|
2361
|
+
`Execution Does Not Exist: '${String(input.executionArn)}'`
|
|
2362
|
+
);
|
|
2363
|
+
}
|
|
2364
|
+
if (operation === "StopExecution") {
|
|
2365
|
+
const execution = this.execution(input.executionArn);
|
|
2366
|
+
if (!execution) return this.error("ExecutionDoesNotExist", "Execution does not exist");
|
|
2367
|
+
const moved = this.transition(execution.arn, "ABORTED", {
|
|
2368
|
+
...typeof input.error === "string" ? { error: input.error } : {},
|
|
2369
|
+
...typeof input.cause === "string" ? { cause: input.cause } : {}
|
|
2370
|
+
});
|
|
2371
|
+
return this.response({
|
|
2372
|
+
stopDate: (moved?.stopDate ?? execution.stopDate ?? this.now()) / 1e3
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
if (operation === "GetExecutionHistory") {
|
|
2376
|
+
const execution = this.execution(input.executionArn);
|
|
2377
|
+
if (!execution) return this.error("ExecutionDoesNotExist", "Execution does not exist");
|
|
2378
|
+
this.refresh(execution);
|
|
2379
|
+
const all = this.events(execution.arn);
|
|
2380
|
+
const offset = typeof input.nextToken === "string" ? Number(atob(input.nextToken)) : 0;
|
|
2381
|
+
const max = Math.max(1, Math.min(1e3, Number(input.maxResults ?? 100)));
|
|
2382
|
+
let selected = all.slice(offset, offset + max);
|
|
2383
|
+
if (input.reverseOrder === true) selected = [...all].reverse().slice(offset, offset + max);
|
|
2384
|
+
const events = selected.map((event) => ({
|
|
2385
|
+
timestamp: event.timestamp / 1e3,
|
|
2386
|
+
type: event.type,
|
|
2387
|
+
id: event.id,
|
|
2388
|
+
previousEventId: event.previousEventId,
|
|
2389
|
+
...event.details ? {
|
|
2390
|
+
[`${event.type[0]?.toLowerCase()}${event.type.slice(1)}EventDetails`]: event.details
|
|
2391
|
+
} : {}
|
|
2392
|
+
}));
|
|
2393
|
+
return this.response({
|
|
2394
|
+
events,
|
|
2395
|
+
...offset + max < all.length ? { nextToken: btoa(String(offset + max)) } : {}
|
|
2396
|
+
});
|
|
2397
|
+
}
|
|
2398
|
+
if (["SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat"].includes(operation)) {
|
|
2399
|
+
const execution = this.callback(input.taskToken);
|
|
2400
|
+
if (!execution) return this.error("TaskDoesNotExist", "Task Token does not exist");
|
|
2401
|
+
if (operation === "SendTaskHeartbeat") return this.response({});
|
|
2402
|
+
if (operation === "SendTaskSuccess") {
|
|
2403
|
+
const output = this.json(input.output ?? "{}", "output");
|
|
2404
|
+
this.event(execution, "TaskSucceeded", { output });
|
|
2405
|
+
this.transition(execution.arn, "SUCCEEDED", { output });
|
|
2406
|
+
} else {
|
|
2407
|
+
this.event(execution, "TaskFailed", { error: input.error, cause: input.cause });
|
|
2408
|
+
this.transition(execution.arn, "FAILED", {
|
|
2409
|
+
...typeof input.error === "string" ? { error: input.error } : {},
|
|
2410
|
+
...typeof input.cause === "string" ? { cause: input.cause } : {}
|
|
2411
|
+
});
|
|
2412
|
+
}
|
|
2413
|
+
return this.response({});
|
|
2414
|
+
}
|
|
2415
|
+
return this.error("InvalidExecutionInput", `Unknown operation ${operation}`);
|
|
2416
|
+
} catch (error) {
|
|
2417
|
+
const message = error instanceof Error ? error.message : "Invalid input";
|
|
2418
|
+
return this.error(
|
|
2419
|
+
message.startsWith("InvalidExecution") ? message : "InvalidExecutionInput",
|
|
2420
|
+
message
|
|
2421
|
+
);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
};
|
|
2425
|
+
|
|
2426
|
+
export {
|
|
2427
|
+
document,
|
|
2428
|
+
operationIds,
|
|
2429
|
+
supportedOperationIds,
|
|
2430
|
+
STEP_FUNCTIONS_PRESETS,
|
|
2431
|
+
createRuntime2 as createRuntime,
|
|
2432
|
+
STEP_FUNCTIONS_NAMESPACE,
|
|
2433
|
+
accessKeyCredential,
|
|
2434
|
+
StepFunctionsAPI
|
|
2435
|
+
};
|
|
2436
|
+
//# sourceMappingURL=chunk-MFKAN6YO.js.map
|