@crvouga/mockingbird-service-dynamodb 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 +56 -0
- package/dist/chunk-CR54OR5S.js +2709 -0
- package/dist/chunk-CR54OR5S.js.map +7 -0
- package/dist/chunk-TCM6WKQB.js +330 -0
- package/dist/chunk-TCM6WKQB.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +895 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1243 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +85 -0
|
@@ -0,0 +1,2709 @@
|
|
|
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 set2 = hub.setEndpoints(namespace, parsed);
|
|
1523
|
+
return json2(200, { endpoints: set2.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, equal2) => {
|
|
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 && equal2(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":"Amazon DynamoDB (Mockingbird subset)","version":"2012-08-10","description":"AWS JSON DynamoDB contract used by AWS SDK v3."},"servers":[{"url":"https://dynamodb.us-east-1.amazonaws.com"}],"paths":{"/":{"post":{"operationId":"DynamoDbRpc","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"X-Amz-Target","in":"header","required":true,"schema":{"type":"string","pattern":"^DynamoDB_20120810\\\\\\\\.[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":"DynamoDB exception","content":{"application/x-amz-json-1.0":{"schema":{"type":"object","additionalProperties":true}}}}}}}}}`);
|
|
2100
|
+
var operationIds = ["DynamoDbRpc"];
|
|
2101
|
+
var supportedOperationIds = ["DynamoDbRpc"];
|
|
2102
|
+
|
|
2103
|
+
// src/state.ts
|
|
2104
|
+
var DynamoState = class {
|
|
2105
|
+
tables;
|
|
2106
|
+
items;
|
|
2107
|
+
streams;
|
|
2108
|
+
ids;
|
|
2109
|
+
constructor(sqlite, namespace) {
|
|
2110
|
+
this.tables = new Collection(sqlite, namespace, "dynamodb_tables");
|
|
2111
|
+
this.items = new Collection(sqlite, namespace, "dynamodb_items");
|
|
2112
|
+
this.streams = new Collection(sqlite, namespace, "dynamodb_streams");
|
|
2113
|
+
this.ids = new IdSequence(sqlite, namespace, "dynamodb");
|
|
2114
|
+
}
|
|
2115
|
+
};
|
|
2116
|
+
|
|
2117
|
+
// src/runtime.ts
|
|
2118
|
+
var DYNAMODB_PRESETS = {
|
|
2119
|
+
throttled: {
|
|
2120
|
+
description: "DynamoDB answers ProvisionedThroughputExceededException",
|
|
2121
|
+
rules: [
|
|
2122
|
+
{
|
|
2123
|
+
status: 400,
|
|
2124
|
+
body: {
|
|
2125
|
+
__type: "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException",
|
|
2126
|
+
message: "The level of configured provisioned throughput was exceeded."
|
|
2127
|
+
},
|
|
2128
|
+
headers: { "content-type": "application/x-amz-json-1.0" }
|
|
2129
|
+
}
|
|
2130
|
+
]
|
|
2131
|
+
},
|
|
2132
|
+
unavailable: {
|
|
2133
|
+
description: "The next DynamoDB request loses its connection",
|
|
2134
|
+
rules: [{ drop: true, count: 1 }]
|
|
2135
|
+
}
|
|
2136
|
+
};
|
|
2137
|
+
var admin = (runtime) => ({
|
|
2138
|
+
"GET /tables": ({ namespace }) => Response.json({
|
|
2139
|
+
tables: runtime.instance(namespace).state.tables.list().map(({ value }) => ({
|
|
2140
|
+
...value,
|
|
2141
|
+
itemCount: runtime.instance(namespace).state.items.list({ where: (item) => item.table === value.name }).length
|
|
2142
|
+
}))
|
|
2143
|
+
}),
|
|
2144
|
+
"GET /items": ({ namespace, url }) => {
|
|
2145
|
+
const table = url.searchParams.get("table");
|
|
2146
|
+
return Response.json({
|
|
2147
|
+
items: runtime.instance(namespace).state.items.list({ where: (item) => !table || item.table === table }).map(({ value }) => value)
|
|
2148
|
+
});
|
|
2149
|
+
},
|
|
2150
|
+
"GET /streams": ({ namespace, url }) => {
|
|
2151
|
+
const table = url.searchParams.get("table");
|
|
2152
|
+
return Response.json({
|
|
2153
|
+
records: runtime.instance(namespace).state.streams.list({
|
|
2154
|
+
where: (record) => !table || record.table === table,
|
|
2155
|
+
order: "oldest"
|
|
2156
|
+
}).map(({ value }) => value)
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
});
|
|
2160
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2161
|
+
name: DYNAMODB_NAMESPACE,
|
|
2162
|
+
document,
|
|
2163
|
+
presets: DYNAMODB_PRESETS,
|
|
2164
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2165
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2166
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2167
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2168
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2169
|
+
credential: accessKeyCredential,
|
|
2170
|
+
create: ({ sqlite, namespace, clock }) => new DynamoAPI({
|
|
2171
|
+
sqlite,
|
|
2172
|
+
namespace,
|
|
2173
|
+
now: clock.now,
|
|
2174
|
+
...options.region ? { region: options.region } : {},
|
|
2175
|
+
...options.accountId ? { accountId: options.accountId } : {},
|
|
2176
|
+
...options.tables ? { tables: options.tables } : {}
|
|
2177
|
+
}),
|
|
2178
|
+
admin
|
|
2179
|
+
});
|
|
2180
|
+
|
|
2181
|
+
// src/index.ts
|
|
2182
|
+
var DYNAMODB_NAMESPACE = "dynamodb";
|
|
2183
|
+
var accessKeyCredential = sigV4AccessKeyId;
|
|
2184
|
+
var clone = (value) => structuredClone(value);
|
|
2185
|
+
var scalar = (value) => value?.S ?? (value?.N !== void 0 ? Number(value.N) : value?.BOOL ?? value?.B);
|
|
2186
|
+
var equal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
2187
|
+
var resolveName = (name, names) => name.split(".").map((part) => names[part] ?? part).join(".");
|
|
2188
|
+
var get = (item, path, names) => {
|
|
2189
|
+
const parts = resolveName(path.trim(), names).split(".");
|
|
2190
|
+
let value = item[parts.shift()];
|
|
2191
|
+
for (const part of parts) value = value?.M?.[part];
|
|
2192
|
+
return value;
|
|
2193
|
+
};
|
|
2194
|
+
var set = (item, path, value, names) => {
|
|
2195
|
+
const parts = resolveName(path.trim(), names).split(".");
|
|
2196
|
+
const leaf = parts.pop();
|
|
2197
|
+
if (parts.length === 0) {
|
|
2198
|
+
item[leaf] = clone(value);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
let current = item;
|
|
2202
|
+
for (const part of parts) {
|
|
2203
|
+
const existing = current[part];
|
|
2204
|
+
if (!existing?.M) current[part] = { M: {} };
|
|
2205
|
+
current = current[part]?.M;
|
|
2206
|
+
}
|
|
2207
|
+
current[leaf] = clone(value);
|
|
2208
|
+
};
|
|
2209
|
+
var remove = (item, path, names) => {
|
|
2210
|
+
const parts = resolveName(path.trim(), names).split(".");
|
|
2211
|
+
const leaf = parts.pop();
|
|
2212
|
+
let current = item;
|
|
2213
|
+
for (const part of parts) current = current?.[part]?.M;
|
|
2214
|
+
if (current) delete current[leaf];
|
|
2215
|
+
};
|
|
2216
|
+
var splitTop = (value, separator = ",") => {
|
|
2217
|
+
const out = [];
|
|
2218
|
+
let depth = 0;
|
|
2219
|
+
let start = 0;
|
|
2220
|
+
for (let i = 0; i < value.length; i++) {
|
|
2221
|
+
if (value[i] === "(") depth++;
|
|
2222
|
+
else if (value[i] === ")") depth--;
|
|
2223
|
+
else if (value.slice(i, i + separator.length) === separator && depth === 0) {
|
|
2224
|
+
out.push(value.slice(start, i).trim());
|
|
2225
|
+
start = i + separator.length;
|
|
2226
|
+
i += separator.length - 1;
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
out.push(value.slice(start).trim());
|
|
2230
|
+
return out.filter(Boolean);
|
|
2231
|
+
};
|
|
2232
|
+
var condition = (expression, item, names, values) => {
|
|
2233
|
+
if (typeof expression !== "string" || !expression.trim()) return true;
|
|
2234
|
+
const source = expression.trim().replace(/^\((.*)\)$/, "$1");
|
|
2235
|
+
const ors = source.split(/\s+OR\s+/i);
|
|
2236
|
+
if (ors.length > 1) return ors.some((part) => condition(part, item, names, values));
|
|
2237
|
+
const ands = source.split(/\s+AND\s+/i);
|
|
2238
|
+
if (ands.length > 1 && !/\s+BETWEEN\s+/i.test(source))
|
|
2239
|
+
return ands.every((part) => condition(part, item, names, values));
|
|
2240
|
+
const exists = /^attribute_(not_)?exists\s*\(([^)]+)\)$/i.exec(source);
|
|
2241
|
+
if (exists)
|
|
2242
|
+
return exists[1] ? get(item ?? {}, exists[2], names) === void 0 : get(item ?? {}, exists[2], names) !== void 0;
|
|
2243
|
+
const begins = /^begins_with\s*\(([^,]+),\s*(:\w+)\)$/i.exec(source);
|
|
2244
|
+
if (begins)
|
|
2245
|
+
return String(scalar(get(item ?? {}, begins[1], names)) ?? "").startsWith(
|
|
2246
|
+
String(scalar(values[begins[2]]) ?? "")
|
|
2247
|
+
);
|
|
2248
|
+
const between = /^(.+?)\s+BETWEEN\s+(:\w+)\s+AND\s+(:\w+)$/i.exec(source);
|
|
2249
|
+
if (between) {
|
|
2250
|
+
const actual = scalar(get(item ?? {}, between[1], names));
|
|
2251
|
+
const low = scalar(values[between[2]]);
|
|
2252
|
+
const high = scalar(values[between[3]]);
|
|
2253
|
+
return actual !== void 0 && low !== void 0 && high !== void 0 && actual >= low && actual <= high;
|
|
2254
|
+
}
|
|
2255
|
+
const comparison = /^(.+?)\s*(=|<>|<=|>=|<|>)\s*(:\w+)$/.exec(source);
|
|
2256
|
+
if (comparison) {
|
|
2257
|
+
const leftValue = get(item ?? {}, comparison[1], names);
|
|
2258
|
+
const rightValue = values[comparison[3]];
|
|
2259
|
+
const left = scalar(leftValue);
|
|
2260
|
+
const right = scalar(rightValue);
|
|
2261
|
+
switch (comparison[2]) {
|
|
2262
|
+
case "=":
|
|
2263
|
+
return equal(leftValue, rightValue);
|
|
2264
|
+
case "<>":
|
|
2265
|
+
return !equal(leftValue, rightValue);
|
|
2266
|
+
case "<":
|
|
2267
|
+
return left !== void 0 && right !== void 0 && left < right;
|
|
2268
|
+
case "<=":
|
|
2269
|
+
return left !== void 0 && right !== void 0 && left <= right;
|
|
2270
|
+
case ">":
|
|
2271
|
+
return left !== void 0 && right !== void 0 && left > right;
|
|
2272
|
+
case ">=":
|
|
2273
|
+
return left !== void 0 && right !== void 0 && left >= right;
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
throw new SyntaxError(`Unsupported expression: ${expression}`);
|
|
2277
|
+
};
|
|
2278
|
+
var project = (item, expression, names) => typeof expression !== "string" ? clone(item) : Object.fromEntries(
|
|
2279
|
+
splitTop(expression).map((path) => [resolveName(path, names), get(item, path, names)]).filter((entry) => entry[1] !== void 0)
|
|
2280
|
+
);
|
|
2281
|
+
var DynamoAPI = class {
|
|
2282
|
+
constructor(options = {}) {
|
|
2283
|
+
this.options = options;
|
|
2284
|
+
this.sqlite = bootSqlite(options.sqlite);
|
|
2285
|
+
this.namespace = options.namespace ?? DYNAMODB_NAMESPACE;
|
|
2286
|
+
this.now = options.now ?? Date.now;
|
|
2287
|
+
this.region = options.region ?? "us-east-1";
|
|
2288
|
+
this.accountId = options.accountId ?? "000000000000";
|
|
2289
|
+
this.state = new DynamoState(this.sqlite, this.namespace);
|
|
2290
|
+
this.seed();
|
|
2291
|
+
}
|
|
2292
|
+
options;
|
|
2293
|
+
state;
|
|
2294
|
+
sqlite;
|
|
2295
|
+
namespace;
|
|
2296
|
+
now;
|
|
2297
|
+
region;
|
|
2298
|
+
accountId;
|
|
2299
|
+
seed() {
|
|
2300
|
+
for (const input of this.options.tables ?? []) {
|
|
2301
|
+
const table = this.createTable(
|
|
2302
|
+
input.name,
|
|
2303
|
+
input.keySchema,
|
|
2304
|
+
input.attributeDefinitions ?? [],
|
|
2305
|
+
input.globalSecondaryIndexes ?? [],
|
|
2306
|
+
input.ttlAttribute
|
|
2307
|
+
);
|
|
2308
|
+
for (const item of input.items ?? []) this.store(table, item);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
async reset() {
|
|
2312
|
+
clearNamespace(this.sqlite, this.namespace);
|
|
2313
|
+
this.seed();
|
|
2314
|
+
}
|
|
2315
|
+
response(body, status = 200) {
|
|
2316
|
+
const id = this.state.ids.next("req-", 20);
|
|
2317
|
+
return new Response(JSON.stringify(body), {
|
|
2318
|
+
status,
|
|
2319
|
+
headers: { "content-type": "application/x-amz-json-1.0", "x-amzn-requestid": id }
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
error(type, message, status = 400) {
|
|
2323
|
+
return this.response({ __type: `com.amazonaws.dynamodb.v20120810#${type}`, message }, status);
|
|
2324
|
+
}
|
|
2325
|
+
createTable(name, keySchema, definitions, indexes, ttlAttribute) {
|
|
2326
|
+
const table = {
|
|
2327
|
+
name,
|
|
2328
|
+
arn: `arn:aws:dynamodb:${this.region}:${this.accountId}:table/${name}`,
|
|
2329
|
+
id: this.state.ids.next("tbl-", 24),
|
|
2330
|
+
createdAt: this.now(),
|
|
2331
|
+
keySchema: clone(keySchema),
|
|
2332
|
+
attributeDefinitions: clone(definitions),
|
|
2333
|
+
globalSecondaryIndexes: clone(indexes),
|
|
2334
|
+
...ttlAttribute ? { ttlAttribute } : {}
|
|
2335
|
+
};
|
|
2336
|
+
this.state.tables.insert(name, table);
|
|
2337
|
+
return table;
|
|
2338
|
+
}
|
|
2339
|
+
table(name) {
|
|
2340
|
+
return typeof name === "string" ? this.state.tables.get(name) : void 0;
|
|
2341
|
+
}
|
|
2342
|
+
key(table, item) {
|
|
2343
|
+
const key = Object.fromEntries(
|
|
2344
|
+
table.keySchema.map(({ AttributeName }) => [AttributeName, item[AttributeName]])
|
|
2345
|
+
);
|
|
2346
|
+
if (Object.values(key).some((value) => value === void 0))
|
|
2347
|
+
throw new TypeError("One of the required keys was not given a value");
|
|
2348
|
+
return JSON.stringify(key);
|
|
2349
|
+
}
|
|
2350
|
+
keyItem(table, item) {
|
|
2351
|
+
return Object.fromEntries(
|
|
2352
|
+
table.keySchema.map(({ AttributeName }) => [
|
|
2353
|
+
AttributeName,
|
|
2354
|
+
clone(item[AttributeName])
|
|
2355
|
+
])
|
|
2356
|
+
);
|
|
2357
|
+
}
|
|
2358
|
+
rows(table) {
|
|
2359
|
+
this.expire(table);
|
|
2360
|
+
return this.state.items.list({ where: (row) => row.table === table.name }).map(({ value }) => value).sort((a, b) => this.compare(table, a.value, b.value));
|
|
2361
|
+
}
|
|
2362
|
+
compare(table, left, right, schema = table.keySchema) {
|
|
2363
|
+
for (const key of schema) {
|
|
2364
|
+
const a = scalar(left[key.AttributeName]);
|
|
2365
|
+
const b = scalar(right[key.AttributeName]);
|
|
2366
|
+
if (a === b) continue;
|
|
2367
|
+
return a !== void 0 && b !== void 0 && a < b ? -1 : 1;
|
|
2368
|
+
}
|
|
2369
|
+
return 0;
|
|
2370
|
+
}
|
|
2371
|
+
store(table, value) {
|
|
2372
|
+
const key = this.key(table, value);
|
|
2373
|
+
const prior = this.state.items.get(`${table.name}:${key}`);
|
|
2374
|
+
this.state.items.insert(`${table.name}:${key}`, {
|
|
2375
|
+
table: table.name,
|
|
2376
|
+
key,
|
|
2377
|
+
value: clone(value),
|
|
2378
|
+
updatedAt: this.now()
|
|
2379
|
+
});
|
|
2380
|
+
this.emit(table, prior ? "MODIFY" : "INSERT", prior?.value, value);
|
|
2381
|
+
return prior?.value;
|
|
2382
|
+
}
|
|
2383
|
+
delete(table, keyValue) {
|
|
2384
|
+
const key = this.key(table, keyValue);
|
|
2385
|
+
const id = `${table.name}:${key}`;
|
|
2386
|
+
const prior = this.state.items.get(id);
|
|
2387
|
+
if (prior) {
|
|
2388
|
+
this.state.items.delete(id);
|
|
2389
|
+
this.emit(table, "REMOVE", prior.value);
|
|
2390
|
+
}
|
|
2391
|
+
return prior?.value;
|
|
2392
|
+
}
|
|
2393
|
+
emit(table, eventName, oldImage, newImage) {
|
|
2394
|
+
const image = newImage ?? oldImage ?? {};
|
|
2395
|
+
const record = {
|
|
2396
|
+
id: this.state.ids.next("str-", 24),
|
|
2397
|
+
table: table.name,
|
|
2398
|
+
eventName,
|
|
2399
|
+
keys: this.keyItem(table, image),
|
|
2400
|
+
...oldImage ? { oldImage: clone(oldImage) } : {},
|
|
2401
|
+
...newImage ? { newImage: clone(newImage) } : {},
|
|
2402
|
+
createdAt: this.now()
|
|
2403
|
+
};
|
|
2404
|
+
this.state.streams.insert(record.id, record);
|
|
2405
|
+
this.options.onStreamRecord?.(record);
|
|
2406
|
+
return record;
|
|
2407
|
+
}
|
|
2408
|
+
expire(table) {
|
|
2409
|
+
if (!table.ttlAttribute) return;
|
|
2410
|
+
for (const row of this.state.items.list({ where: (value) => value.table === table.name })) {
|
|
2411
|
+
const expires = Number(row.value.value[table.ttlAttribute]?.N);
|
|
2412
|
+
if (Number.isFinite(expires) && expires <= Math.floor(this.now() / 1e3))
|
|
2413
|
+
this.delete(table, row.value.value);
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
names(input) {
|
|
2417
|
+
return input.ExpressionAttributeNames ?? {};
|
|
2418
|
+
}
|
|
2419
|
+
values(input) {
|
|
2420
|
+
return input.ExpressionAttributeValues ?? {};
|
|
2421
|
+
}
|
|
2422
|
+
applyUpdate(item, expression, names, values) {
|
|
2423
|
+
if (typeof expression !== "string") throw new SyntaxError("UpdateExpression is required");
|
|
2424
|
+
const clauses = [...expression.matchAll(/(?:^|\s)(SET|ADD|REMOVE|DELETE)\s+/gi)];
|
|
2425
|
+
for (let index = 0; index < clauses.length; index++) {
|
|
2426
|
+
const clause = clauses[index];
|
|
2427
|
+
const kind = clause[1].toUpperCase();
|
|
2428
|
+
const start = clause.index + clause[0].length;
|
|
2429
|
+
const end = index + 1 < clauses.length ? clauses[index + 1]?.index : expression.length;
|
|
2430
|
+
const body = expression.slice(start, end).trim();
|
|
2431
|
+
if (kind === "SET")
|
|
2432
|
+
for (const assignment of splitTop(body)) {
|
|
2433
|
+
const [path, raw = ""] = assignment.split(/\s*=\s*/, 2);
|
|
2434
|
+
const fallback = /^if_not_exists\(([^,]+),\s*(:\w+)\)(?:\s*\+\s*(:\w+))?$/.exec(raw);
|
|
2435
|
+
const addition = /^(.+?)\s*\+\s*(:\w+)$/.exec(raw);
|
|
2436
|
+
if (fallback) {
|
|
2437
|
+
const base = get(item, fallback[1], names) ?? values[fallback[2]];
|
|
2438
|
+
const plus = fallback[3] ? Number(base?.N ?? "0") + Number(values[fallback[3]]?.N ?? "0") : void 0;
|
|
2439
|
+
set(
|
|
2440
|
+
item,
|
|
2441
|
+
path,
|
|
2442
|
+
plus === void 0 ? base : { N: String(plus) },
|
|
2443
|
+
names
|
|
2444
|
+
);
|
|
2445
|
+
} else if (addition) {
|
|
2446
|
+
const base = Number(get(item, addition[1], names)?.N ?? "0");
|
|
2447
|
+
set(
|
|
2448
|
+
item,
|
|
2449
|
+
path,
|
|
2450
|
+
{ N: String(base + Number(values[addition[2]]?.N ?? "0")) },
|
|
2451
|
+
names
|
|
2452
|
+
);
|
|
2453
|
+
} else {
|
|
2454
|
+
const value = values[raw.trim()];
|
|
2455
|
+
if (!value) throw new SyntaxError(`Unknown value ${raw}`);
|
|
2456
|
+
set(item, path, value, names);
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
else if (kind === "ADD")
|
|
2460
|
+
for (const addition of splitTop(body)) {
|
|
2461
|
+
const [path, token] = addition.split(/\s+/);
|
|
2462
|
+
const value = values[token];
|
|
2463
|
+
const prior = get(item, path, names);
|
|
2464
|
+
if (value?.N !== void 0)
|
|
2465
|
+
set(item, path, { N: String(Number(prior?.N ?? 0) + Number(value.N)) }, names);
|
|
2466
|
+
else if (value?.SS)
|
|
2467
|
+
set(
|
|
2468
|
+
item,
|
|
2469
|
+
path,
|
|
2470
|
+
{ SS: [.../* @__PURE__ */ new Set([...prior?.SS ?? [], ...value.SS])] },
|
|
2471
|
+
names
|
|
2472
|
+
);
|
|
2473
|
+
else throw new SyntaxError("ADD supports numbers and string sets");
|
|
2474
|
+
}
|
|
2475
|
+
else if (kind === "REMOVE") for (const path of splitTop(body)) remove(item, path, names);
|
|
2476
|
+
else if (kind === "DELETE")
|
|
2477
|
+
for (const deletion of splitTop(body)) {
|
|
2478
|
+
const [path, token] = deletion.split(/\s+/);
|
|
2479
|
+
const value = values[token];
|
|
2480
|
+
const prior = get(item, path, names);
|
|
2481
|
+
if (value?.SS && prior?.SS)
|
|
2482
|
+
set(
|
|
2483
|
+
item,
|
|
2484
|
+
path,
|
|
2485
|
+
{ SS: prior.SS.filter((entry) => !value.SS?.includes(entry)) },
|
|
2486
|
+
names
|
|
2487
|
+
);
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
readPage(table, input, query) {
|
|
2492
|
+
const names = this.names(input);
|
|
2493
|
+
const values = this.values(input);
|
|
2494
|
+
const index = typeof input.IndexName === "string" ? table.globalSecondaryIndexes.find((value) => value.IndexName === input.IndexName) : void 0;
|
|
2495
|
+
const schema = index?.KeySchema ?? table.keySchema;
|
|
2496
|
+
let rows = this.rows(table).sort((a, b) => this.compare(table, a.value, b.value, schema));
|
|
2497
|
+
if (query && input.ScanIndexForward === false) rows.reverse();
|
|
2498
|
+
if (input.ExclusiveStartKey && typeof input.ExclusiveStartKey === "object") {
|
|
2499
|
+
const start = this.key(table, input.ExclusiveStartKey);
|
|
2500
|
+
const found = rows.findIndex((row) => row.key === start);
|
|
2501
|
+
if (found >= 0) rows = rows.slice(found + 1);
|
|
2502
|
+
}
|
|
2503
|
+
const matching = rows.filter(
|
|
2504
|
+
(row) => !query || condition(input.KeyConditionExpression, row.value, names, values)
|
|
2505
|
+
);
|
|
2506
|
+
const limit = input.Limit === void 0 ? matching.length : Math.max(0, Number(input.Limit));
|
|
2507
|
+
const evaluated = matching.slice(0, limit);
|
|
2508
|
+
const filtered = evaluated.filter(
|
|
2509
|
+
(row) => condition(input.FilterExpression, row.value, names, values)
|
|
2510
|
+
);
|
|
2511
|
+
const last = matching.length > evaluated.length ? evaluated.at(-1) : void 0;
|
|
2512
|
+
return {
|
|
2513
|
+
Items: filtered.map((row) => project(row.value, input.ProjectionExpression, names)),
|
|
2514
|
+
Count: filtered.length,
|
|
2515
|
+
ScannedCount: evaluated.length,
|
|
2516
|
+
...last ? { LastEvaluatedKey: this.keyItem(table, last.value) } : {}
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
async fetch(request) {
|
|
2520
|
+
if (request.method !== "POST")
|
|
2521
|
+
return this.error("ValidationException", "Only POST is supported");
|
|
2522
|
+
const operation = (request.headers.get("x-amz-target") ?? "").split(".").at(-1) ?? "";
|
|
2523
|
+
const input = await request.json().catch(() => ({}));
|
|
2524
|
+
try {
|
|
2525
|
+
if (operation === "CreateTable") {
|
|
2526
|
+
const name = String(input.TableName ?? "");
|
|
2527
|
+
if (!name) return this.error("ValidationException", "TableName is required");
|
|
2528
|
+
if (this.table(name)) return this.error("ResourceInUseException", "Table already exists");
|
|
2529
|
+
const table2 = this.createTable(
|
|
2530
|
+
name,
|
|
2531
|
+
input.KeySchema ?? [],
|
|
2532
|
+
input.AttributeDefinitions ?? [],
|
|
2533
|
+
input.GlobalSecondaryIndexes ?? []
|
|
2534
|
+
);
|
|
2535
|
+
return this.response({ TableDescription: this.describe(table2) });
|
|
2536
|
+
}
|
|
2537
|
+
if (operation === "DescribeTable") {
|
|
2538
|
+
const table2 = this.table(input.TableName);
|
|
2539
|
+
return table2 ? this.response({ Table: this.describe(table2) }) : this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2540
|
+
}
|
|
2541
|
+
const table = this.table(input.TableName);
|
|
2542
|
+
if (!table && !["BatchGetItem", "BatchWriteItem", "TransactGetItems", "TransactWriteItems"].includes(
|
|
2543
|
+
operation
|
|
2544
|
+
))
|
|
2545
|
+
return this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2546
|
+
if (operation === "GetItem") {
|
|
2547
|
+
this.expire(table);
|
|
2548
|
+
const row = this.state.items.get(
|
|
2549
|
+
`${table?.name}:${this.key(table, input.Key)}`
|
|
2550
|
+
);
|
|
2551
|
+
return this.response(
|
|
2552
|
+
row ? { Item: project(row.value, input.ProjectionExpression, this.names(input)) } : {}
|
|
2553
|
+
);
|
|
2554
|
+
}
|
|
2555
|
+
if (operation === "PutItem") {
|
|
2556
|
+
const item = input.Item;
|
|
2557
|
+
const key = this.key(table, item);
|
|
2558
|
+
const prior = this.state.items.get(`${table?.name}:${key}`)?.value;
|
|
2559
|
+
if (!condition(input.ConditionExpression, prior, this.names(input), this.values(input)))
|
|
2560
|
+
return this.error("ConditionalCheckFailedException", "The conditional request failed");
|
|
2561
|
+
this.store(table, item);
|
|
2562
|
+
return this.response(input.ReturnValues === "ALL_OLD" && prior ? { Attributes: prior } : {});
|
|
2563
|
+
}
|
|
2564
|
+
if (operation === "DeleteItem") {
|
|
2565
|
+
const key = input.Key;
|
|
2566
|
+
const prior = this.state.items.get(
|
|
2567
|
+
`${table?.name}:${this.key(table, key)}`
|
|
2568
|
+
)?.value;
|
|
2569
|
+
if (!condition(input.ConditionExpression, prior, this.names(input), this.values(input)))
|
|
2570
|
+
return this.error("ConditionalCheckFailedException", "The conditional request failed");
|
|
2571
|
+
const deleted = this.delete(table, key);
|
|
2572
|
+
return this.response(
|
|
2573
|
+
input.ReturnValues === "ALL_OLD" && deleted ? { Attributes: deleted } : {}
|
|
2574
|
+
);
|
|
2575
|
+
}
|
|
2576
|
+
if (operation === "UpdateItem") {
|
|
2577
|
+
const key = input.Key;
|
|
2578
|
+
const id = `${table?.name}:${this.key(table, key)}`;
|
|
2579
|
+
const prior = this.state.items.get(id)?.value;
|
|
2580
|
+
if (!condition(input.ConditionExpression, prior, this.names(input), this.values(input)))
|
|
2581
|
+
return this.error("ConditionalCheckFailedException", "The conditional request failed");
|
|
2582
|
+
const next = clone(prior ?? key);
|
|
2583
|
+
this.applyUpdate(next, input.UpdateExpression, this.names(input), this.values(input));
|
|
2584
|
+
this.store(table, next);
|
|
2585
|
+
return this.response(
|
|
2586
|
+
input.ReturnValues === "ALL_NEW" ? { Attributes: next } : input.ReturnValues === "ALL_OLD" && prior ? { Attributes: prior } : {}
|
|
2587
|
+
);
|
|
2588
|
+
}
|
|
2589
|
+
if (operation === "Query")
|
|
2590
|
+
return this.response(this.readPage(table, input, true));
|
|
2591
|
+
if (operation === "Scan")
|
|
2592
|
+
return this.response(this.readPage(table, input, false));
|
|
2593
|
+
if (operation === "BatchGetItem") return this.batchGet(input);
|
|
2594
|
+
if (operation === "BatchWriteItem") return this.batchWrite(input);
|
|
2595
|
+
if (operation === "TransactGetItems") return this.transactGet(input);
|
|
2596
|
+
if (operation === "TransactWriteItems") return this.transactWrite(input);
|
|
2597
|
+
return this.error("ValidationException", `Unknown operation ${operation}`);
|
|
2598
|
+
} catch (error) {
|
|
2599
|
+
return this.error(
|
|
2600
|
+
"ValidationException",
|
|
2601
|
+
error instanceof Error ? error.message : "Invalid request"
|
|
2602
|
+
);
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
describe(table) {
|
|
2606
|
+
return {
|
|
2607
|
+
TableName: table.name,
|
|
2608
|
+
TableArn: table.arn,
|
|
2609
|
+
TableId: table.id,
|
|
2610
|
+
TableStatus: "ACTIVE",
|
|
2611
|
+
CreationDateTime: table.createdAt / 1e3,
|
|
2612
|
+
ItemCount: this.rows(table).length,
|
|
2613
|
+
TableSizeBytes: 0,
|
|
2614
|
+
KeySchema: table.keySchema,
|
|
2615
|
+
AttributeDefinitions: table.attributeDefinitions,
|
|
2616
|
+
GlobalSecondaryIndexes: table.globalSecondaryIndexes.map((index) => ({
|
|
2617
|
+
...index,
|
|
2618
|
+
IndexArn: `${table.arn}/index/${index.IndexName}`,
|
|
2619
|
+
IndexStatus: "ACTIVE",
|
|
2620
|
+
ItemCount: this.rows(table).length,
|
|
2621
|
+
IndexSizeBytes: 0
|
|
2622
|
+
}))
|
|
2623
|
+
};
|
|
2624
|
+
}
|
|
2625
|
+
batchGet(input) {
|
|
2626
|
+
const responses = {};
|
|
2627
|
+
for (const [name, request] of Object.entries(
|
|
2628
|
+
input.RequestItems ?? {}
|
|
2629
|
+
)) {
|
|
2630
|
+
const table = this.table(name);
|
|
2631
|
+
if (!table) return this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2632
|
+
responses[name] = (request.Keys ?? []).flatMap((key) => {
|
|
2633
|
+
const row = this.state.items.get(`${name}:${this.key(table, key)}`);
|
|
2634
|
+
return row ? [project(row.value, request.ProjectionExpression, this.names(request))] : [];
|
|
2635
|
+
});
|
|
2636
|
+
}
|
|
2637
|
+
return this.response({ Responses: responses, UnprocessedKeys: {} });
|
|
2638
|
+
}
|
|
2639
|
+
batchWrite(input) {
|
|
2640
|
+
for (const [name, requests] of Object.entries(
|
|
2641
|
+
input.RequestItems ?? {}
|
|
2642
|
+
)) {
|
|
2643
|
+
const table = this.table(name);
|
|
2644
|
+
if (!table) return this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2645
|
+
for (const request of requests) {
|
|
2646
|
+
if (request.PutRequest) this.store(table, request.PutRequest.Item);
|
|
2647
|
+
if (request.DeleteRequest) this.delete(table, request.DeleteRequest.Key);
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
return this.response({ UnprocessedItems: {} });
|
|
2651
|
+
}
|
|
2652
|
+
transactGet(input) {
|
|
2653
|
+
const responses = [];
|
|
2654
|
+
for (const request of input.TransactItems ?? []) {
|
|
2655
|
+
const getInput = request.Get;
|
|
2656
|
+
const table = this.table(getInput.TableName);
|
|
2657
|
+
if (!table) return this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2658
|
+
const row = this.state.items.get(`${table.name}:${this.key(table, getInput.Key)}`);
|
|
2659
|
+
responses.push(
|
|
2660
|
+
row ? { Item: project(row.value, getInput.ProjectionExpression, this.names(getInput)) } : {}
|
|
2661
|
+
);
|
|
2662
|
+
}
|
|
2663
|
+
return this.response({ Responses: responses });
|
|
2664
|
+
}
|
|
2665
|
+
transactWrite(input) {
|
|
2666
|
+
const actions = input.TransactItems ?? [];
|
|
2667
|
+
for (const action of actions) {
|
|
2668
|
+
const request = action.Put ?? action.Update ?? action.Delete ?? action.ConditionCheck;
|
|
2669
|
+
const table = this.table(request.TableName);
|
|
2670
|
+
if (!table) return this.error("ResourceNotFoundException", "Requested resource not found");
|
|
2671
|
+
const keyItem = request.Item ?? request.Key;
|
|
2672
|
+
const prior = this.state.items.get(`${table.name}:${this.key(table, keyItem)}`)?.value;
|
|
2673
|
+
if (!condition(request.ConditionExpression, prior, this.names(request), this.values(request)))
|
|
2674
|
+
return this.error(
|
|
2675
|
+
"TransactionCanceledException",
|
|
2676
|
+
"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"
|
|
2677
|
+
);
|
|
2678
|
+
}
|
|
2679
|
+
for (const action of actions) {
|
|
2680
|
+
if (action.Put) {
|
|
2681
|
+
const request = action.Put;
|
|
2682
|
+
this.store(this.table(request.TableName), request.Item);
|
|
2683
|
+
} else if (action.Delete) {
|
|
2684
|
+
const request = action.Delete;
|
|
2685
|
+
this.delete(this.table(request.TableName), request.Key);
|
|
2686
|
+
} else if (action.Update) {
|
|
2687
|
+
const request = action.Update;
|
|
2688
|
+
const table = this.table(request.TableName);
|
|
2689
|
+
const id = `${table.name}:${this.key(table, request.Key)}`;
|
|
2690
|
+
const next = clone(this.state.items.get(id)?.value ?? request.Key);
|
|
2691
|
+
this.applyUpdate(next, request.UpdateExpression, this.names(request), this.values(request));
|
|
2692
|
+
this.store(table, next);
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
return this.response({});
|
|
2696
|
+
}
|
|
2697
|
+
};
|
|
2698
|
+
|
|
2699
|
+
export {
|
|
2700
|
+
document,
|
|
2701
|
+
operationIds,
|
|
2702
|
+
supportedOperationIds,
|
|
2703
|
+
DYNAMODB_PRESETS,
|
|
2704
|
+
createRuntime2 as createRuntime,
|
|
2705
|
+
DYNAMODB_NAMESPACE,
|
|
2706
|
+
accessKeyCredential,
|
|
2707
|
+
DynamoAPI
|
|
2708
|
+
};
|
|
2709
|
+
//# sourceMappingURL=chunk-CR54OR5S.js.map
|