@crvouga/mockingbird-service-textract 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 +49 -0
- package/dist/chunk-CW2HHK2L.js +330 -0
- package/dist/chunk-CW2HHK2L.js.map +7 -0
- package/dist/chunk-TLZAWBGK.js +2774 -0
- package/dist/chunk-TLZAWBGK.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +864 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1212 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +85 -0
|
@@ -0,0 +1,2774 @@
|
|
|
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/signing.js
|
|
1443
|
+
var encoder = new TextEncoder();
|
|
1444
|
+
var toBase64 = (bytes) => {
|
|
1445
|
+
let binary = "";
|
|
1446
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1447
|
+
binary += String.fromCharCode(byte);
|
|
1448
|
+
}
|
|
1449
|
+
return btoa(binary);
|
|
1450
|
+
};
|
|
1451
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1452
|
+
var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1453
|
+
var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
|
|
1454
|
+
var hmac = async (algorithm, key, message, encoding = "hex") => {
|
|
1455
|
+
const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
1456
|
+
const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
|
|
1457
|
+
return encoding === "hex" ? toHex(signed) : toBase64(signed);
|
|
1458
|
+
};
|
|
1459
|
+
var svixSecretBytes = (secret) => {
|
|
1460
|
+
const raw = secret.replace(/^f?whsec_/, "");
|
|
1461
|
+
try {
|
|
1462
|
+
return fromBase64(raw);
|
|
1463
|
+
} catch {
|
|
1464
|
+
throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
|
|
1465
|
+
}
|
|
1466
|
+
};
|
|
1467
|
+
var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
|
|
1468
|
+
var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
|
|
1469
|
+
var signTwilio = async (authToken, url, params) => {
|
|
1470
|
+
const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
|
|
1471
|
+
return hmac("SHA-1", authToken, payload, "base64");
|
|
1472
|
+
};
|
|
1473
|
+
|
|
1474
|
+
// ../core/dist/webhooks.js
|
|
1475
|
+
var signers = {
|
|
1476
|
+
/** No signature. */
|
|
1477
|
+
none: () => () => ({}),
|
|
1478
|
+
/** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
|
|
1479
|
+
svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
|
|
1480
|
+
if (!secret)
|
|
1481
|
+
return {};
|
|
1482
|
+
const prefix = options.prefix ?? "svix";
|
|
1483
|
+
return {
|
|
1484
|
+
[`${prefix}-id`]: messageId,
|
|
1485
|
+
[`${prefix}-timestamp`]: String(timestampSeconds),
|
|
1486
|
+
[`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
|
|
1487
|
+
};
|
|
1488
|
+
},
|
|
1489
|
+
/** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
|
|
1490
|
+
timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
|
|
1491
|
+
/** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
|
|
1492
|
+
twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
|
|
1493
|
+
/** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
|
|
1494
|
+
header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
|
|
1495
|
+
/** Anything else: the service computes the headers itself. */
|
|
1496
|
+
custom: (sign) => sign
|
|
1497
|
+
};
|
|
1498
|
+
var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
|
|
1499
|
+
var unref = (timer) => {
|
|
1500
|
+
;
|
|
1501
|
+
timer.unref?.();
|
|
1502
|
+
};
|
|
1503
|
+
var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
1504
|
+
var matchesEndpoint = (endpoint, message) => {
|
|
1505
|
+
const events = endpoint.events ?? ["*"];
|
|
1506
|
+
if (!events.includes("*") && !events.includes(message.type))
|
|
1507
|
+
return false;
|
|
1508
|
+
for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
|
|
1509
|
+
if (message.tags[key] !== value)
|
|
1510
|
+
return false;
|
|
1511
|
+
}
|
|
1512
|
+
return true;
|
|
1513
|
+
};
|
|
1514
|
+
var createWebhookHub = (options) => {
|
|
1515
|
+
const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
|
|
1516
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
1517
|
+
const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
|
|
1518
|
+
const send = options.fetch ?? ((request) => fetch(request));
|
|
1519
|
+
const keep = options.keep ?? 500;
|
|
1520
|
+
const now = options.now ?? Date.now;
|
|
1521
|
+
const id = options.id ?? randomId;
|
|
1522
|
+
const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
|
1523
|
+
const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
|
1524
|
+
const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
|
|
1525
|
+
const own = /* @__PURE__ */ new Map();
|
|
1526
|
+
const messages = [];
|
|
1527
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
1528
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1529
|
+
const payloads = /* @__PURE__ */ new Map();
|
|
1530
|
+
const faults = /* @__PURE__ */ new Map();
|
|
1531
|
+
const held = /* @__PURE__ */ new Map();
|
|
1532
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
1533
|
+
const track = (work) => {
|
|
1534
|
+
inFlight.add(work);
|
|
1535
|
+
void work.finally(() => inFlight.delete(work));
|
|
1536
|
+
};
|
|
1537
|
+
const attempt = async (delivery) => {
|
|
1538
|
+
const entry = payloads.get(delivery.id);
|
|
1539
|
+
if (!entry)
|
|
1540
|
+
return false;
|
|
1541
|
+
const { message, endpoint } = entry;
|
|
1542
|
+
const timestampSeconds = Math.floor(now() / 1e3);
|
|
1543
|
+
const started = now();
|
|
1544
|
+
const record = {
|
|
1545
|
+
attempt: delivery.attempts.length + 1,
|
|
1546
|
+
at: new Date(started).toISOString(),
|
|
1547
|
+
status: null,
|
|
1548
|
+
error: null,
|
|
1549
|
+
durationMs: 0,
|
|
1550
|
+
responseBody: null
|
|
1551
|
+
};
|
|
1552
|
+
const controller = new AbortController();
|
|
1553
|
+
const timer = scheduleTimer(() => controller.abort(), timeoutMs);
|
|
1554
|
+
try {
|
|
1555
|
+
const signed = await options.signer({
|
|
1556
|
+
messageId: message.id,
|
|
1557
|
+
body: message.body,
|
|
1558
|
+
timestampSeconds,
|
|
1559
|
+
url: endpoint.url,
|
|
1560
|
+
secret: endpoint.secret,
|
|
1561
|
+
signUrl: endpoint.signUrl ?? endpoint.url,
|
|
1562
|
+
form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
|
|
1563
|
+
type: message.type,
|
|
1564
|
+
tags: message.tags
|
|
1565
|
+
});
|
|
1566
|
+
const response = await send(new Request(endpoint.url, {
|
|
1567
|
+
method: "POST",
|
|
1568
|
+
headers: {
|
|
1569
|
+
"content-type": message.contentType,
|
|
1570
|
+
...endpoint.headers,
|
|
1571
|
+
...message.headers,
|
|
1572
|
+
...signed
|
|
1573
|
+
},
|
|
1574
|
+
body: message.body,
|
|
1575
|
+
signal: controller.signal
|
|
1576
|
+
}));
|
|
1577
|
+
record.status = response.status;
|
|
1578
|
+
record.responseBody = await response.text();
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
record.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
|
|
1581
|
+
} finally {
|
|
1582
|
+
cancel(timer);
|
|
1583
|
+
record.durationMs = now() - started;
|
|
1584
|
+
delivery.attempts.push(record);
|
|
1585
|
+
}
|
|
1586
|
+
return record.status !== null && delivered(record.status);
|
|
1587
|
+
};
|
|
1588
|
+
const schedule = (delivery) => {
|
|
1589
|
+
const index = delivery.attempts.length;
|
|
1590
|
+
if (index >= delays.length) {
|
|
1591
|
+
delivery.state = "failed";
|
|
1592
|
+
pending.delete(delivery.id);
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
const run = () => {
|
|
1596
|
+
pending.delete(delivery.id);
|
|
1597
|
+
track(attempt(delivery).then((ok) => {
|
|
1598
|
+
if (ok)
|
|
1599
|
+
delivery.state = "delivered";
|
|
1600
|
+
else
|
|
1601
|
+
schedule(delivery);
|
|
1602
|
+
}));
|
|
1603
|
+
};
|
|
1604
|
+
const delay = delays[index] ?? 0;
|
|
1605
|
+
if (delay <= 0) {
|
|
1606
|
+
pending.set(delivery.id, void 0);
|
|
1607
|
+
run();
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1610
|
+
const timer = scheduleTimer(run, delay);
|
|
1611
|
+
unref(timer);
|
|
1612
|
+
pending.set(delivery.id, timer);
|
|
1613
|
+
};
|
|
1614
|
+
const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
|
|
1615
|
+
const fanOut = (message, state = "pending") => {
|
|
1616
|
+
for (const endpoint of endpointsFor(message.namespace)) {
|
|
1617
|
+
if (!matchesEndpoint(endpoint, message))
|
|
1618
|
+
continue;
|
|
1619
|
+
const delivery = {
|
|
1620
|
+
id: id("dlv_"),
|
|
1621
|
+
messageId: message.id,
|
|
1622
|
+
namespace: message.namespace,
|
|
1623
|
+
type: message.type,
|
|
1624
|
+
endpointId: endpoint.id ?? "we_unknown",
|
|
1625
|
+
url: endpoint.url,
|
|
1626
|
+
state,
|
|
1627
|
+
attempts: []
|
|
1628
|
+
};
|
|
1629
|
+
deliveries.set(delivery.id, delivery);
|
|
1630
|
+
payloads.set(delivery.id, { message, endpoint });
|
|
1631
|
+
if (state === "pending")
|
|
1632
|
+
schedule(delivery);
|
|
1633
|
+
}
|
|
1634
|
+
};
|
|
1635
|
+
const takeFault = (namespace) => {
|
|
1636
|
+
const queue = faults.get(namespace);
|
|
1637
|
+
const head = queue?.[0];
|
|
1638
|
+
if (!queue || !head)
|
|
1639
|
+
return void 0;
|
|
1640
|
+
head.remaining--;
|
|
1641
|
+
if (head.remaining <= 0)
|
|
1642
|
+
queue.shift();
|
|
1643
|
+
return head.mode;
|
|
1644
|
+
};
|
|
1645
|
+
const releaseHeld = (namespace) => {
|
|
1646
|
+
const waiting = held.get(namespace);
|
|
1647
|
+
if (!waiting)
|
|
1648
|
+
return;
|
|
1649
|
+
held.delete(namespace);
|
|
1650
|
+
for (const message of waiting)
|
|
1651
|
+
fanOut(message);
|
|
1652
|
+
};
|
|
1653
|
+
const hub = {
|
|
1654
|
+
publish(input) {
|
|
1655
|
+
const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
|
|
1656
|
+
const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
|
|
1657
|
+
const message = {
|
|
1658
|
+
id: input.id ?? id("msg_"),
|
|
1659
|
+
namespace: input.namespace,
|
|
1660
|
+
type: input.type,
|
|
1661
|
+
body,
|
|
1662
|
+
contentType,
|
|
1663
|
+
tags: input.tags ?? {},
|
|
1664
|
+
headers: input.headers ?? {},
|
|
1665
|
+
publishedAt: new Date(now()).toISOString()
|
|
1666
|
+
};
|
|
1667
|
+
messages.push(message);
|
|
1668
|
+
const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
|
|
1669
|
+
const oldest = ofNamespace[0];
|
|
1670
|
+
if (ofNamespace.length > keep && oldest)
|
|
1671
|
+
messages.splice(messages.indexOf(oldest), 1);
|
|
1672
|
+
options.onMessage?.(message);
|
|
1673
|
+
const fault = takeFault(message.namespace);
|
|
1674
|
+
if (fault === "drop") {
|
|
1675
|
+
fanOut(message, "dropped");
|
|
1676
|
+
return message;
|
|
1677
|
+
}
|
|
1678
|
+
if (fault === "reorder") {
|
|
1679
|
+
held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
|
|
1680
|
+
return message;
|
|
1681
|
+
}
|
|
1682
|
+
fanOut(message);
|
|
1683
|
+
if (fault === "duplicate")
|
|
1684
|
+
fanOut(message);
|
|
1685
|
+
releaseHeld(message.namespace);
|
|
1686
|
+
return message;
|
|
1687
|
+
},
|
|
1688
|
+
setEndpoints(namespace, endpoints) {
|
|
1689
|
+
const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
|
|
1690
|
+
own.set(namespace, withIds);
|
|
1691
|
+
return withIds;
|
|
1692
|
+
},
|
|
1693
|
+
endpoints: endpointsFor,
|
|
1694
|
+
messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
|
|
1695
|
+
deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
|
|
1696
|
+
async replay(id2) {
|
|
1697
|
+
const delivery = deliveries.get(id2);
|
|
1698
|
+
if (!delivery)
|
|
1699
|
+
return void 0;
|
|
1700
|
+
const ok = await attempt(delivery);
|
|
1701
|
+
if (ok)
|
|
1702
|
+
delivery.state = "delivered";
|
|
1703
|
+
return delivery;
|
|
1704
|
+
},
|
|
1705
|
+
async flush() {
|
|
1706
|
+
for (const namespace of [...held.keys()])
|
|
1707
|
+
releaseHeld(namespace);
|
|
1708
|
+
const waiting = [...pending.entries()];
|
|
1709
|
+
for (const [id2, timer] of waiting) {
|
|
1710
|
+
if (timer === void 0)
|
|
1711
|
+
continue;
|
|
1712
|
+
cancel(timer);
|
|
1713
|
+
pending.delete(id2);
|
|
1714
|
+
const delivery = deliveries.get(id2);
|
|
1715
|
+
if (!delivery)
|
|
1716
|
+
continue;
|
|
1717
|
+
track(attempt(delivery).then((ok) => {
|
|
1718
|
+
if (ok)
|
|
1719
|
+
delivery.state = "delivered";
|
|
1720
|
+
else
|
|
1721
|
+
schedule(delivery);
|
|
1722
|
+
}));
|
|
1723
|
+
}
|
|
1724
|
+
await hub.idle();
|
|
1725
|
+
},
|
|
1726
|
+
async idle() {
|
|
1727
|
+
while (inFlight.size > 0)
|
|
1728
|
+
await Promise.allSettled([...inFlight]);
|
|
1729
|
+
},
|
|
1730
|
+
fault(namespace, fault) {
|
|
1731
|
+
const queue = faults.get(namespace) ?? [];
|
|
1732
|
+
queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
|
|
1733
|
+
faults.set(namespace, queue);
|
|
1734
|
+
},
|
|
1735
|
+
clear(namespace) {
|
|
1736
|
+
for (const [id2, delivery] of deliveries) {
|
|
1737
|
+
if (namespace !== void 0 && delivery.namespace !== namespace)
|
|
1738
|
+
continue;
|
|
1739
|
+
const timer = pending.get(id2);
|
|
1740
|
+
if (timer !== void 0)
|
|
1741
|
+
cancel(timer);
|
|
1742
|
+
pending.delete(id2);
|
|
1743
|
+
deliveries.delete(id2);
|
|
1744
|
+
payloads.delete(id2);
|
|
1745
|
+
}
|
|
1746
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1747
|
+
if (namespace === void 0 || messages[i]?.namespace === namespace)
|
|
1748
|
+
messages.splice(i, 1);
|
|
1749
|
+
}
|
|
1750
|
+
if (namespace === void 0) {
|
|
1751
|
+
held.clear();
|
|
1752
|
+
faults.clear();
|
|
1753
|
+
own.clear();
|
|
1754
|
+
} else {
|
|
1755
|
+
held.delete(namespace);
|
|
1756
|
+
faults.delete(namespace);
|
|
1757
|
+
own.delete(namespace);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
};
|
|
1761
|
+
return hub;
|
|
1762
|
+
};
|
|
1763
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1764
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1765
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1766
|
+
var parseEndpoint = (value) => {
|
|
1767
|
+
if (!isRecord2(value) || typeof value.url !== "string")
|
|
1768
|
+
return "each endpoint needs a url";
|
|
1769
|
+
try {
|
|
1770
|
+
new URL(value.url);
|
|
1771
|
+
} catch {
|
|
1772
|
+
return `not a URL: ${value.url}`;
|
|
1773
|
+
}
|
|
1774
|
+
const endpoint = { url: value.url };
|
|
1775
|
+
if (typeof value.id === "string")
|
|
1776
|
+
endpoint.id = value.id;
|
|
1777
|
+
if (typeof value.secret === "string")
|
|
1778
|
+
endpoint.secret = value.secret;
|
|
1779
|
+
if (typeof value.signUrl === "string")
|
|
1780
|
+
endpoint.signUrl = value.signUrl;
|
|
1781
|
+
const events = value.events ?? value.enabledEvents;
|
|
1782
|
+
if (Array.isArray(events))
|
|
1783
|
+
endpoint.events = events.map(String);
|
|
1784
|
+
if (isRecord2(value.tags)) {
|
|
1785
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1786
|
+
}
|
|
1787
|
+
if (typeof value.account === "string")
|
|
1788
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1789
|
+
if (isRecord2(value.headers)) {
|
|
1790
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1791
|
+
}
|
|
1792
|
+
return endpoint;
|
|
1793
|
+
};
|
|
1794
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1795
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1796
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1797
|
+
const type = url.searchParams.get("type");
|
|
1798
|
+
return type === null || d.type === type;
|
|
1799
|
+
})
|
|
1800
|
+
}),
|
|
1801
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1802
|
+
const type = url.searchParams.get("type");
|
|
1803
|
+
return json2(200, {
|
|
1804
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1805
|
+
});
|
|
1806
|
+
},
|
|
1807
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1808
|
+
const replayed = await hub.replay(params.id);
|
|
1809
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1810
|
+
},
|
|
1811
|
+
"POST /webhooks/flush": async () => {
|
|
1812
|
+
await hub.flush();
|
|
1813
|
+
return json2(200, { status: "ok" });
|
|
1814
|
+
},
|
|
1815
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1816
|
+
if (!isRecord2(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1817
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1818
|
+
}
|
|
1819
|
+
const fault = { mode: body.mode };
|
|
1820
|
+
if (typeof body.count === "number")
|
|
1821
|
+
fault.count = body.count;
|
|
1822
|
+
hub.fault(namespace, fault);
|
|
1823
|
+
return json2(201, { namespace, ...fault });
|
|
1824
|
+
},
|
|
1825
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1826
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1827
|
+
...rest,
|
|
1828
|
+
secret: secret ? "(set)" : null
|
|
1829
|
+
}))
|
|
1830
|
+
}),
|
|
1831
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1832
|
+
const list = Array.isArray(body) ? body : isRecord2(body) ? body.endpoints : void 0;
|
|
1833
|
+
if (!Array.isArray(list))
|
|
1834
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1835
|
+
const parsed = [];
|
|
1836
|
+
for (const each of list) {
|
|
1837
|
+
const endpoint = parseEndpoint(each);
|
|
1838
|
+
if (typeof endpoint === "string")
|
|
1839
|
+
return adminError2(400, endpoint);
|
|
1840
|
+
parsed.push(endpoint);
|
|
1841
|
+
}
|
|
1842
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1843
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1844
|
+
},
|
|
1845
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1846
|
+
hub.setEndpoints(namespace, []);
|
|
1847
|
+
return json2(200, { status: "ok" });
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
var parsePayload = (message) => {
|
|
1851
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1852
|
+
try {
|
|
1853
|
+
return JSON.parse(message.body);
|
|
1854
|
+
} catch {
|
|
1855
|
+
return message.body;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1859
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1860
|
+
}
|
|
1861
|
+
return message.body;
|
|
1862
|
+
};
|
|
1863
|
+
|
|
1864
|
+
// ../core/dist/runtime.js
|
|
1865
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1866
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1867
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1868
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1869
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1870
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1871
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1872
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1873
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1874
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1875
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1876
|
+
if (!previous || previous.length === 0)
|
|
1877
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1878
|
+
const result = new Array(fresh.length);
|
|
1879
|
+
let unchanged = fresh.length === previous.length;
|
|
1880
|
+
let oldIndex = 0;
|
|
1881
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1882
|
+
const row = fresh[index];
|
|
1883
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1884
|
+
oldIndex++;
|
|
1885
|
+
}
|
|
1886
|
+
const old = previous[oldIndex];
|
|
1887
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1888
|
+
if (result[index] !== previous[index])
|
|
1889
|
+
unchanged = false;
|
|
1890
|
+
}
|
|
1891
|
+
return unchanged ? previous : result;
|
|
1892
|
+
};
|
|
1893
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1894
|
+
code = "MOCKINGBIRD_DROP";
|
|
1895
|
+
constructor() {
|
|
1896
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1897
|
+
this.name = "TypeError";
|
|
1898
|
+
}
|
|
1899
|
+
};
|
|
1900
|
+
var operationMatcher = (document2) => {
|
|
1901
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1902
|
+
operationId: operation.operationId,
|
|
1903
|
+
method: operation.method.toUpperCase(),
|
|
1904
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1905
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1906
|
+
})).sort((a, b) => a.params - b.params);
|
|
1907
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1908
|
+
};
|
|
1909
|
+
var createRuntime = (options) => {
|
|
1910
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1911
|
+
const clock = options.clock ?? createClock();
|
|
1912
|
+
const rng = createRng(options.seed ?? 0);
|
|
1913
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1914
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1915
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1916
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1917
|
+
const metrics = createMetrics();
|
|
1918
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1919
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1920
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1921
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1922
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1923
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1924
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1925
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1926
|
+
const credentials = createCredentialRegistry();
|
|
1927
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1928
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1929
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1930
|
+
const existing = instances.get(key);
|
|
1931
|
+
if (existing)
|
|
1932
|
+
return existing;
|
|
1933
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1934
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1935
|
+
}
|
|
1936
|
+
const created = options.create({
|
|
1937
|
+
namespace: storageNamespace(key),
|
|
1938
|
+
publicNamespace,
|
|
1939
|
+
sqlite,
|
|
1940
|
+
clock,
|
|
1941
|
+
rng: isolatedRng ?? rng
|
|
1942
|
+
});
|
|
1943
|
+
instances.set(key, created);
|
|
1944
|
+
publicNamespaces.add(publicNamespace);
|
|
1945
|
+
if (isolatedRng)
|
|
1946
|
+
branchRngs.set(key, isolatedRng);
|
|
1947
|
+
return created;
|
|
1948
|
+
};
|
|
1949
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1950
|
+
const capture = (storage) => {
|
|
1951
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1952
|
+
const previous = captured.get(storage);
|
|
1953
|
+
const snapshot2 = {
|
|
1954
|
+
namespace: fresh.namespace,
|
|
1955
|
+
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),
|
|
1956
|
+
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)
|
|
1957
|
+
};
|
|
1958
|
+
Object.freeze(snapshot2.records);
|
|
1959
|
+
Object.freeze(snapshot2.sequences);
|
|
1960
|
+
Object.freeze(snapshot2);
|
|
1961
|
+
captured.set(storage, snapshot2);
|
|
1962
|
+
return Object.freeze({
|
|
1963
|
+
snapshot: snapshot2,
|
|
1964
|
+
clock: Object.freeze(clock.state()),
|
|
1965
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1966
|
+
});
|
|
1967
|
+
};
|
|
1968
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1969
|
+
let found = timelines.get(name);
|
|
1970
|
+
if (found)
|
|
1971
|
+
return found;
|
|
1972
|
+
instance(name);
|
|
1973
|
+
found = new Timeline({
|
|
1974
|
+
now: clock.now,
|
|
1975
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1976
|
+
});
|
|
1977
|
+
found.commit(capture(name));
|
|
1978
|
+
timelines.set(name, found);
|
|
1979
|
+
return found;
|
|
1980
|
+
};
|
|
1981
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1982
|
+
if (branch2 === "main")
|
|
1983
|
+
return namespace;
|
|
1984
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1985
|
+
const existing = branchStorage.get(mapKey);
|
|
1986
|
+
if (existing)
|
|
1987
|
+
return existing;
|
|
1988
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1989
|
+
branchStorage.set(mapKey, key);
|
|
1990
|
+
return key;
|
|
1991
|
+
};
|
|
1992
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1993
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1994
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1995
|
+
const history = timeline(namespace);
|
|
1996
|
+
if (branch2 === "main") {
|
|
1997
|
+
if (at !== void 0) {
|
|
1998
|
+
const point = history.checkout("main", at);
|
|
1999
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
2000
|
+
captured.set(namespace, point.value.snapshot);
|
|
2001
|
+
rng.setState(point.value.rngState);
|
|
2002
|
+
clock.set(point.value.clock.now);
|
|
2003
|
+
if (point.value.clock.frozen)
|
|
2004
|
+
clock.freeze();
|
|
2005
|
+
else
|
|
2006
|
+
clock.unfreeze();
|
|
2007
|
+
}
|
|
2008
|
+
return namespace;
|
|
2009
|
+
}
|
|
2010
|
+
const storage = physicalBranch(namespace, branch2);
|
|
2011
|
+
if (!history.hasBranch(branch2)) {
|
|
2012
|
+
if (at === void 0)
|
|
2013
|
+
history.commit(capture(namespace));
|
|
2014
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
2015
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2016
|
+
if (point)
|
|
2017
|
+
branchRng.setState(point.value.rngState);
|
|
2018
|
+
instanceFor(storage, namespace, branchRng);
|
|
2019
|
+
if (point)
|
|
2020
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2021
|
+
if (point)
|
|
2022
|
+
captured.set(storage, point.value.snapshot);
|
|
2023
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
2024
|
+
const point = history.checkout(branch2, at);
|
|
2025
|
+
if (!instances.has(storage)) {
|
|
2026
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2027
|
+
branchRng.setState(point.value.rngState);
|
|
2028
|
+
instanceFor(storage, namespace, branchRng);
|
|
2029
|
+
}
|
|
2030
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
2031
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2032
|
+
captured.set(storage, point.value.snapshot);
|
|
2033
|
+
} else {
|
|
2034
|
+
if (!instances.has(storage)) {
|
|
2035
|
+
const point = history.head(branch2);
|
|
2036
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2037
|
+
if (point)
|
|
2038
|
+
branchRng.setState(point.value.rngState);
|
|
2039
|
+
instanceFor(storage, namespace, branchRng);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
return storage;
|
|
2043
|
+
};
|
|
2044
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
2045
|
+
const storage = ensureBranch(namespace, branch2);
|
|
2046
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
2047
|
+
};
|
|
2048
|
+
const branch = (name, branchOptions = {}) => {
|
|
2049
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2050
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
2051
|
+
const head = timeline(namespace).head(name);
|
|
2052
|
+
if (!head)
|
|
2053
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
2054
|
+
return head;
|
|
2055
|
+
};
|
|
2056
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
2057
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2058
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
2059
|
+
const history = timeline(namespace);
|
|
2060
|
+
const point = history.checkout(branchName, checkpointId);
|
|
2061
|
+
const storage = ensureBranch(namespace, branchName);
|
|
2062
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2063
|
+
captured.set(storage, point.value.snapshot);
|
|
2064
|
+
clock.set(point.value.clock.now);
|
|
2065
|
+
if (point.value.clock.frozen)
|
|
2066
|
+
clock.freeze();
|
|
2067
|
+
else
|
|
2068
|
+
clock.unfreeze();
|
|
2069
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
2070
|
+
};
|
|
2071
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
2072
|
+
if (name === "*") {
|
|
2073
|
+
options.webhooks?.clear();
|
|
2074
|
+
for (const each of instances.values())
|
|
2075
|
+
await each.reset();
|
|
2076
|
+
timelines.clear();
|
|
2077
|
+
branchStorage.clear();
|
|
2078
|
+
branchRngs.clear();
|
|
2079
|
+
captured.clear();
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
options.webhooks?.clear(name);
|
|
2083
|
+
const target = instances.get(name);
|
|
2084
|
+
if (target)
|
|
2085
|
+
await target.reset();
|
|
2086
|
+
else
|
|
2087
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
2088
|
+
for (const [mapping, storage] of branchStorage) {
|
|
2089
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
2090
|
+
continue;
|
|
2091
|
+
const branchInstance = instances.get(storage);
|
|
2092
|
+
if (branchInstance)
|
|
2093
|
+
await branchInstance.reset();
|
|
2094
|
+
else
|
|
2095
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
2096
|
+
branchStorage.delete(mapping);
|
|
2097
|
+
branchRngs.delete(storage);
|
|
2098
|
+
captured.delete(storage);
|
|
2099
|
+
}
|
|
2100
|
+
timelines.delete(name);
|
|
2101
|
+
captured.delete(name);
|
|
2102
|
+
};
|
|
2103
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
2104
|
+
return checkpoint(name, "main").value.snapshot;
|
|
2105
|
+
};
|
|
2106
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
2107
|
+
instance(name);
|
|
2108
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
2109
|
+
captured.set(name, from);
|
|
2110
|
+
const history = timelines.get(name);
|
|
2111
|
+
if (history)
|
|
2112
|
+
history.commit(capture(name), { branch: "main" });
|
|
2113
|
+
else
|
|
2114
|
+
timeline(name);
|
|
2115
|
+
};
|
|
2116
|
+
const runtime = {
|
|
2117
|
+
name: options.name,
|
|
2118
|
+
sqlite,
|
|
2119
|
+
clock,
|
|
2120
|
+
faults,
|
|
2121
|
+
metrics,
|
|
2122
|
+
journal,
|
|
2123
|
+
rng,
|
|
2124
|
+
credentials,
|
|
2125
|
+
webhooks: options.webhooks,
|
|
2126
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
2127
|
+
const preset = options.presets?.[name];
|
|
2128
|
+
if (!preset)
|
|
2129
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
2130
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
2131
|
+
namespace,
|
|
2132
|
+
...rule,
|
|
2133
|
+
...overrides,
|
|
2134
|
+
preset: name,
|
|
2135
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
2136
|
+
}));
|
|
2137
|
+
if (preset.webhook && options.webhooks) {
|
|
2138
|
+
options.webhooks.fault(namespace, {
|
|
2139
|
+
...preset.webhook,
|
|
2140
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
2141
|
+
});
|
|
2142
|
+
}
|
|
2143
|
+
return added;
|
|
2144
|
+
},
|
|
2145
|
+
instance,
|
|
2146
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
2147
|
+
reset,
|
|
2148
|
+
snapshot,
|
|
2149
|
+
restore,
|
|
2150
|
+
checkpoint,
|
|
2151
|
+
branch,
|
|
2152
|
+
checkout,
|
|
2153
|
+
timeline,
|
|
2154
|
+
fetch: async (incoming) => {
|
|
2155
|
+
let request = incoming;
|
|
2156
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
2157
|
+
if (prefixed) {
|
|
2158
|
+
const url2 = new URL(request.url);
|
|
2159
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
2160
|
+
const headers = new Headers(request.headers);
|
|
2161
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
2162
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
2163
|
+
}
|
|
2164
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
2165
|
+
request = new Request(url2, {
|
|
2166
|
+
method: request.method,
|
|
2167
|
+
headers,
|
|
2168
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
2169
|
+
signal: request.signal
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
let namespace = control.namespaceOf(request);
|
|
2173
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
2174
|
+
const credential = options.credential(request);
|
|
2175
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
2176
|
+
if (mapped !== void 0)
|
|
2177
|
+
namespace = mapped;
|
|
2178
|
+
}
|
|
2179
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
2180
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
2181
|
+
const stamp = (response2) => {
|
|
2182
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
2183
|
+
try {
|
|
2184
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2185
|
+
return response2;
|
|
2186
|
+
} catch {
|
|
2187
|
+
const copy2 = new Response(response2.body, response2);
|
|
2188
|
+
copy2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2189
|
+
return copy2;
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
const handled = await control.handle(request);
|
|
2193
|
+
if (handled)
|
|
2194
|
+
return stamp(handled);
|
|
2195
|
+
const started = monotonicNow();
|
|
2196
|
+
const url = new URL(request.url);
|
|
2197
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
2198
|
+
const log = (status, faultId, response2) => {
|
|
2199
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
2200
|
+
const entry = {
|
|
2201
|
+
service: options.name,
|
|
2202
|
+
namespace,
|
|
2203
|
+
operationId,
|
|
2204
|
+
method: request.method,
|
|
2205
|
+
path: url.pathname,
|
|
2206
|
+
status,
|
|
2207
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
2208
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
2209
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
2210
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
2211
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
2212
|
+
};
|
|
2213
|
+
metrics.record(entry);
|
|
2214
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2215
|
+
options.onLog?.(entry);
|
|
2216
|
+
};
|
|
2217
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2218
|
+
log(400);
|
|
2219
|
+
return stamp(new Response(JSON.stringify({
|
|
2220
|
+
error: {
|
|
2221
|
+
type: "mockingbird_admin",
|
|
2222
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2223
|
+
}
|
|
2224
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2225
|
+
}
|
|
2226
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2227
|
+
log(400);
|
|
2228
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2229
|
+
}
|
|
2230
|
+
let storage;
|
|
2231
|
+
try {
|
|
2232
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2233
|
+
const point = timeline(namespace).get(at);
|
|
2234
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2235
|
+
let viewRng = branchRngs.get(storage);
|
|
2236
|
+
if (!viewRng) {
|
|
2237
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2238
|
+
instanceFor(storage, namespace, viewRng);
|
|
2239
|
+
}
|
|
2240
|
+
viewRng.setState(point.value.rngState);
|
|
2241
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2242
|
+
captured.set(storage, point.value.snapshot);
|
|
2243
|
+
} else {
|
|
2244
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2245
|
+
}
|
|
2246
|
+
} catch (error) {
|
|
2247
|
+
log(409);
|
|
2248
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
2249
|
+
}
|
|
2250
|
+
const hits = await faults.take({
|
|
2251
|
+
operationId,
|
|
2252
|
+
method: request.method,
|
|
2253
|
+
path: url.pathname,
|
|
2254
|
+
namespace
|
|
2255
|
+
});
|
|
2256
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2257
|
+
if (final?.drop) {
|
|
2258
|
+
log(0, final.id);
|
|
2259
|
+
throw new DroppedConnectionError();
|
|
2260
|
+
}
|
|
2261
|
+
if (final?.response) {
|
|
2262
|
+
log(final.response.status, final.id);
|
|
2263
|
+
return stamp(final.response);
|
|
2264
|
+
}
|
|
2265
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2266
|
+
if (fired.length > 0)
|
|
2267
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2268
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2269
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2270
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2271
|
+
response = mutableResponse(response);
|
|
2272
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2273
|
+
}
|
|
2274
|
+
if (selectedBranch !== "main") {
|
|
2275
|
+
response = mutableResponse(response);
|
|
2276
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2277
|
+
}
|
|
2278
|
+
if (at !== void 0) {
|
|
2279
|
+
response = mutableResponse(response);
|
|
2280
|
+
response.headers.set(AT_HEADER, at);
|
|
2281
|
+
}
|
|
2282
|
+
log(response.status, fired[0]?.id, response);
|
|
2283
|
+
return stamp(response);
|
|
2284
|
+
}
|
|
2285
|
+
};
|
|
2286
|
+
const control = createControlPlane({
|
|
2287
|
+
name: options.name,
|
|
2288
|
+
startedAt: wallNow(),
|
|
2289
|
+
wallNow,
|
|
2290
|
+
clock,
|
|
2291
|
+
faults,
|
|
2292
|
+
metrics,
|
|
2293
|
+
journal,
|
|
2294
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2295
|
+
namespaces: runtime.namespaces,
|
|
2296
|
+
reset,
|
|
2297
|
+
timeTravel: {
|
|
2298
|
+
checkpoint: (name, branchName) => {
|
|
2299
|
+
const point = checkpoint(name, branchName);
|
|
2300
|
+
return {
|
|
2301
|
+
id: point.id,
|
|
2302
|
+
branch: point.branch,
|
|
2303
|
+
parent: point.parent,
|
|
2304
|
+
at: point.at,
|
|
2305
|
+
records: point.value.snapshot.records.length
|
|
2306
|
+
};
|
|
2307
|
+
},
|
|
2308
|
+
branch: (branchName, branchOptions) => {
|
|
2309
|
+
const point = branch(branchName, branchOptions);
|
|
2310
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2311
|
+
},
|
|
2312
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2313
|
+
retain: (name, checkpointId) => {
|
|
2314
|
+
timeline(name).retain(checkpointId);
|
|
2315
|
+
},
|
|
2316
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2317
|
+
inspect: (name) => {
|
|
2318
|
+
const history = timeline(name);
|
|
2319
|
+
return {
|
|
2320
|
+
branches: history.branches(),
|
|
2321
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2322
|
+
id,
|
|
2323
|
+
branch: branchName,
|
|
2324
|
+
parent,
|
|
2325
|
+
at
|
|
2326
|
+
}))
|
|
2327
|
+
};
|
|
2328
|
+
}
|
|
2329
|
+
},
|
|
2330
|
+
describe: options.describe ?? (() => ({})),
|
|
2331
|
+
...options.presets ? {
|
|
2332
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2333
|
+
} : {},
|
|
2334
|
+
routes: {
|
|
2335
|
+
...credentialRoutes(credentials),
|
|
2336
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2337
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2338
|
+
...options.admin?.(runtime) ?? {}
|
|
2339
|
+
},
|
|
2340
|
+
adminKey: options.adminKey
|
|
2341
|
+
});
|
|
2342
|
+
return runtime;
|
|
2343
|
+
};
|
|
2344
|
+
var mutableResponse = (response) => {
|
|
2345
|
+
try {
|
|
2346
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2347
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2348
|
+
return response;
|
|
2349
|
+
} catch {
|
|
2350
|
+
return new Response(response.body, response);
|
|
2351
|
+
}
|
|
2352
|
+
};
|
|
2353
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2354
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2355
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2356
|
+
var credentialRoutes = (registry) => ({
|
|
2357
|
+
"GET /credentials": () => adminJson(200, {
|
|
2358
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2359
|
+
credential: maskCredential(credential),
|
|
2360
|
+
namespace
|
|
2361
|
+
}))
|
|
2362
|
+
}),
|
|
2363
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2364
|
+
const pairs = [];
|
|
2365
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2366
|
+
if (Array.isArray(list)) {
|
|
2367
|
+
for (const each of list) {
|
|
2368
|
+
if (typeof each === "string")
|
|
2369
|
+
pairs.push([each, namespace]);
|
|
2370
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2371
|
+
pairs.push([
|
|
2372
|
+
each.credential,
|
|
2373
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2374
|
+
]);
|
|
2375
|
+
} else
|
|
2376
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2377
|
+
}
|
|
2378
|
+
} else if (isObject(list)) {
|
|
2379
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2380
|
+
if (typeof target !== "string")
|
|
2381
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2382
|
+
pairs.push([credential, target]);
|
|
2383
|
+
}
|
|
2384
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2385
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2386
|
+
} else {
|
|
2387
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2388
|
+
}
|
|
2389
|
+
for (const [credential, target] of pairs) {
|
|
2390
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2391
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2392
|
+
registry.set(credential, target);
|
|
2393
|
+
}
|
|
2394
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2395
|
+
},
|
|
2396
|
+
"DELETE /credentials": ({ url }) => {
|
|
2397
|
+
const credential = url.searchParams.get("credential");
|
|
2398
|
+
if (credential === null)
|
|
2399
|
+
registry.clear();
|
|
2400
|
+
else
|
|
2401
|
+
registry.remove(credential);
|
|
2402
|
+
return adminJson(200, { status: "ok" });
|
|
2403
|
+
}
|
|
2404
|
+
});
|
|
2405
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2406
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2407
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2408
|
+
}),
|
|
2409
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2410
|
+
const name = params.name;
|
|
2411
|
+
if (!presets[name])
|
|
2412
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2413
|
+
const overrides = isObject(body) ? body : {};
|
|
2414
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2415
|
+
}
|
|
2416
|
+
});
|
|
2417
|
+
|
|
2418
|
+
// src/generated/openapi.ts
|
|
2419
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Amazon Textract (Mockingbird subset)","version":"2018-06-27","description":"AWS JSON contract used by the pinned Textract client."},"servers":[{"url":"https://textract.us-east-1.amazonaws.com"}],"paths":{"/":{"post":{"operationId":"TextractRpc","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"X-Amz-Target","in":"header","required":true,"schema":{"type":"string","pattern":"^Textract\\\\.[A-Za-z]+$"}}],"requestBody":{"required":true,"content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}},"application/json":{"schema":{"type":"object","additionalProperties":true}}}},"responses":{"200":{"description":"Operation response","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}}}},"400":{"description":"Textract exception","content":{"application/x-amz-json-1.1":{"schema":{"type":"object","additionalProperties":true}}}}}}}}}`);
|
|
2420
|
+
var operationIds = ["TextractRpc"];
|
|
2421
|
+
var supportedOperationIds = ["TextractRpc"];
|
|
2422
|
+
|
|
2423
|
+
// src/state.ts
|
|
2424
|
+
var TextractState = class {
|
|
2425
|
+
corpora;
|
|
2426
|
+
jobs;
|
|
2427
|
+
ids;
|
|
2428
|
+
constructor(sqlite, namespace) {
|
|
2429
|
+
this.corpora = new Collection(sqlite, namespace, "textract_corpora");
|
|
2430
|
+
this.jobs = new Collection(sqlite, namespace, "textract_jobs");
|
|
2431
|
+
this.ids = new IdSequence(sqlite, namespace, "textract");
|
|
2432
|
+
}
|
|
2433
|
+
corpusId(bucket, name, version) {
|
|
2434
|
+
return `${bucket}\0${name}\0${version ?? ""}`;
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
|
|
2438
|
+
// src/runtime.ts
|
|
2439
|
+
var TEXTRACT_PRESETS = {
|
|
2440
|
+
throttled: {
|
|
2441
|
+
description: "Textract answers ThrottlingException",
|
|
2442
|
+
rules: [
|
|
2443
|
+
{
|
|
2444
|
+
status: 400,
|
|
2445
|
+
body: { __type: "ThrottlingException", message: "Rate exceeded" },
|
|
2446
|
+
headers: { "content-type": "application/x-amz-json-1.1" }
|
|
2447
|
+
}
|
|
2448
|
+
]
|
|
2449
|
+
},
|
|
2450
|
+
throughput_exceeded: {
|
|
2451
|
+
description: "Textract answers ProvisionedThroughputExceededException",
|
|
2452
|
+
rules: [
|
|
2453
|
+
{
|
|
2454
|
+
status: 400,
|
|
2455
|
+
body: {
|
|
2456
|
+
__type: "ProvisionedThroughputExceededException",
|
|
2457
|
+
message: "Provisioned throughput exceeded"
|
|
2458
|
+
},
|
|
2459
|
+
headers: { "content-type": "application/x-amz-json-1.1" }
|
|
2460
|
+
}
|
|
2461
|
+
]
|
|
2462
|
+
},
|
|
2463
|
+
unavailable: { description: "The next request loses its connection", rules: [{ drop: true }] }
|
|
2464
|
+
};
|
|
2465
|
+
var problem = (status, message) => Response.json({ error: { type: "mockingbird_admin", message } }, { status });
|
|
2466
|
+
var admin = (runtime) => ({
|
|
2467
|
+
"GET /corpora": ({ namespace }) => Response.json({
|
|
2468
|
+
corpora: runtime.instance(namespace).state.corpora.list().map(({ value }) => value)
|
|
2469
|
+
}),
|
|
2470
|
+
"POST /corpora": ({ namespace, body }) => {
|
|
2471
|
+
const input = body;
|
|
2472
|
+
if (!input || typeof input.bucket !== "string" || typeof input.name !== "string" || !Array.isArray(input.blocks))
|
|
2473
|
+
return problem(400, "bucket, name and blocks are required");
|
|
2474
|
+
return Response.json(runtime.instance(namespace).putCorpus(input), { status: 201 });
|
|
2475
|
+
},
|
|
2476
|
+
"GET /jobs": ({ namespace }) => Response.json({
|
|
2477
|
+
jobs: runtime.instance(namespace).state.jobs.list({ order: "oldest" }).map(({ value }) => value)
|
|
2478
|
+
}),
|
|
2479
|
+
"GET /jobs/:id": ({ namespace, params }) => {
|
|
2480
|
+
const job = runtime.instance(namespace).state.jobs.get(params.id);
|
|
2481
|
+
return job ? Response.json(job) : problem(404, "job not found");
|
|
2482
|
+
},
|
|
2483
|
+
"POST /jobs/:id/transition": ({ namespace, params, body }) => {
|
|
2484
|
+
const input = body;
|
|
2485
|
+
const allowed = /* @__PURE__ */ new Set(["SUCCEEDED", "PARTIAL_SUCCESS", "FAILED"]);
|
|
2486
|
+
if (!input || typeof input.status !== "string" || !allowed.has(input.status))
|
|
2487
|
+
return problem(400, "a terminal status is required");
|
|
2488
|
+
const moved = runtime.instance(namespace).transition(
|
|
2489
|
+
params.id,
|
|
2490
|
+
input.status,
|
|
2491
|
+
typeof input.statusMessage === "string" ? input.statusMessage : void 0
|
|
2492
|
+
);
|
|
2493
|
+
return moved ? Response.json(moved) : problem(409, "job not found or already terminal");
|
|
2494
|
+
}
|
|
2495
|
+
});
|
|
2496
|
+
var createRuntime2 = (options = {}) => {
|
|
2497
|
+
const hub = createWebhookHub({
|
|
2498
|
+
signer: signers.none(),
|
|
2499
|
+
endpoints: options.webhooks?.endpoints ?? [],
|
|
2500
|
+
...options.webhooks?.retryDelaysMs ? { retryDelaysMs: options.webhooks.retryDelaysMs } : {},
|
|
2501
|
+
...options.webhooks?.fetch ? { fetch: options.webhooks.fetch } : {}
|
|
2502
|
+
});
|
|
2503
|
+
const runtime = createRuntime({
|
|
2504
|
+
name: TEXTRACT_NAMESPACE,
|
|
2505
|
+
document,
|
|
2506
|
+
presets: TEXTRACT_PRESETS,
|
|
2507
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2508
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2509
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2510
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2511
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2512
|
+
credential: accessKeyCredential,
|
|
2513
|
+
create: ({ sqlite, namespace, clock }) => new TextractAPI({
|
|
2514
|
+
sqlite,
|
|
2515
|
+
namespace,
|
|
2516
|
+
now: clock.now,
|
|
2517
|
+
...options.corpora ? { corpora: options.corpora } : {},
|
|
2518
|
+
onNotification: (event) => hub.publish({ namespace, type: `textract:${event.Status.toLowerCase()}`, body: event })
|
|
2519
|
+
}),
|
|
2520
|
+
admin
|
|
2521
|
+
});
|
|
2522
|
+
return Object.assign(runtime, { webhooks: hub });
|
|
2523
|
+
};
|
|
2524
|
+
|
|
2525
|
+
// src/index.ts
|
|
2526
|
+
var TEXTRACT_NAMESPACE = "textract";
|
|
2527
|
+
var accessKeyCredential = sigV4AccessKeyId;
|
|
2528
|
+
var stable = (value) => {
|
|
2529
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
|
|
2530
|
+
if (value && typeof value === "object")
|
|
2531
|
+
return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${stable(item)}`).join(",")}}`;
|
|
2532
|
+
return JSON.stringify(value);
|
|
2533
|
+
};
|
|
2534
|
+
var copy = (value) => structuredClone(value);
|
|
2535
|
+
var read = (input, name) => input[name] ?? input[`${name[0]?.toUpperCase()}${name.slice(1)}`] ?? Object.entries(input).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
|
|
2536
|
+
var wire = (value) => {
|
|
2537
|
+
if (Array.isArray(value)) return value.map(wire);
|
|
2538
|
+
if (!value || typeof value !== "object") return value;
|
|
2539
|
+
return Object.fromEntries(
|
|
2540
|
+
Object.entries(value).map(([key, item]) => [
|
|
2541
|
+
`${key[0]?.toUpperCase()}${key.slice(1)}`,
|
|
2542
|
+
wire(item)
|
|
2543
|
+
])
|
|
2544
|
+
);
|
|
2545
|
+
};
|
|
2546
|
+
var TextractAPI = class {
|
|
2547
|
+
constructor(options = {}) {
|
|
2548
|
+
this.options = options;
|
|
2549
|
+
this.sqlite = bootSqlite(options.sqlite);
|
|
2550
|
+
this.namespace = options.namespace ?? TEXTRACT_NAMESPACE;
|
|
2551
|
+
this.now = options.now ?? Date.now;
|
|
2552
|
+
this.state = new TextractState(this.sqlite, this.namespace);
|
|
2553
|
+
this.seed();
|
|
2554
|
+
}
|
|
2555
|
+
options;
|
|
2556
|
+
state;
|
|
2557
|
+
sqlite;
|
|
2558
|
+
namespace;
|
|
2559
|
+
now;
|
|
2560
|
+
seed() {
|
|
2561
|
+
for (const corpus of this.options.corpora ?? []) this.putCorpus(corpus);
|
|
2562
|
+
}
|
|
2563
|
+
async reset() {
|
|
2564
|
+
clearNamespace(this.sqlite, this.namespace);
|
|
2565
|
+
this.seed();
|
|
2566
|
+
}
|
|
2567
|
+
putCorpus(corpus) {
|
|
2568
|
+
const value = copy(corpus);
|
|
2569
|
+
this.state.corpora.insert(
|
|
2570
|
+
this.state.corpusId(corpus.bucket, corpus.name, corpus.version),
|
|
2571
|
+
value
|
|
2572
|
+
);
|
|
2573
|
+
return value;
|
|
2574
|
+
}
|
|
2575
|
+
response(body, status = 200) {
|
|
2576
|
+
return new Response(JSON.stringify(body), {
|
|
2577
|
+
status,
|
|
2578
|
+
headers: {
|
|
2579
|
+
"content-type": "application/x-amz-json-1.1",
|
|
2580
|
+
"x-amzn-requestid": this.state.ids.next("req-", 20)
|
|
2581
|
+
}
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
error(type, message) {
|
|
2585
|
+
return this.response({ __type: type, message }, 400);
|
|
2586
|
+
}
|
|
2587
|
+
s3(input) {
|
|
2588
|
+
if (!input || typeof input !== "object") return void 0;
|
|
2589
|
+
const object = read(input, "s3Object");
|
|
2590
|
+
if (!object || typeof object !== "object") return void 0;
|
|
2591
|
+
const value = object;
|
|
2592
|
+
const bucket = read(value, "bucket");
|
|
2593
|
+
const name = read(value, "name");
|
|
2594
|
+
const version = read(value, "version");
|
|
2595
|
+
if (typeof bucket !== "string" || typeof name !== "string") return void 0;
|
|
2596
|
+
return {
|
|
2597
|
+
bucket,
|
|
2598
|
+
name,
|
|
2599
|
+
...typeof version === "string" ? { version } : {}
|
|
2600
|
+
};
|
|
2601
|
+
}
|
|
2602
|
+
corpus(documentLocation) {
|
|
2603
|
+
const location = this.s3(documentLocation);
|
|
2604
|
+
if (!location) return void 0;
|
|
2605
|
+
return this.state.corpora.get(
|
|
2606
|
+
this.state.corpusId(location.bucket, location.name, location.version)
|
|
2607
|
+
);
|
|
2608
|
+
}
|
|
2609
|
+
notify(job) {
|
|
2610
|
+
if (job.status === "IN_PROGRESS" || !job.notificationChannel?.snsTopicArn) return;
|
|
2611
|
+
this.options.onNotification?.({
|
|
2612
|
+
JobId: job.id,
|
|
2613
|
+
Status: job.status,
|
|
2614
|
+
API: "StartDocumentAnalysis",
|
|
2615
|
+
...job.jobTag ? { JobTag: job.jobTag } : {},
|
|
2616
|
+
Timestamp: this.now(),
|
|
2617
|
+
DocumentLocation: {
|
|
2618
|
+
S3ObjectName: job.document.name,
|
|
2619
|
+
S3Bucket: job.document.bucket
|
|
2620
|
+
}
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
transition(id, status, statusMessage) {
|
|
2624
|
+
const current = this.state.jobs.get(id);
|
|
2625
|
+
if (current?.status !== "IN_PROGRESS") return void 0;
|
|
2626
|
+
const next = {
|
|
2627
|
+
...current,
|
|
2628
|
+
status,
|
|
2629
|
+
...statusMessage ? { statusMessage } : {}
|
|
2630
|
+
};
|
|
2631
|
+
this.state.jobs.insert(id, next);
|
|
2632
|
+
this.notify(next);
|
|
2633
|
+
return next;
|
|
2634
|
+
}
|
|
2635
|
+
result(input) {
|
|
2636
|
+
return {
|
|
2637
|
+
DocumentMetadata: { Pages: input.pages },
|
|
2638
|
+
Blocks: wire(copy(input.blocks)),
|
|
2639
|
+
AnalyzeDocumentModelVersion: input.modelVersion,
|
|
2640
|
+
...input.warnings?.length ? { Warnings: wire(copy(input.warnings)) } : {}
|
|
2641
|
+
};
|
|
2642
|
+
}
|
|
2643
|
+
token(jobId, offset) {
|
|
2644
|
+
return btoa(JSON.stringify({ jobId, offset }));
|
|
2645
|
+
}
|
|
2646
|
+
parseToken(token, jobId) {
|
|
2647
|
+
if (token === void 0) return 0;
|
|
2648
|
+
if (typeof token !== "string") return void 0;
|
|
2649
|
+
try {
|
|
2650
|
+
const decoded = JSON.parse(atob(token));
|
|
2651
|
+
return decoded.jobId === jobId && Number.isInteger(decoded.offset) && Number(decoded.offset) >= 0 ? Number(decoded.offset) : void 0;
|
|
2652
|
+
} catch {
|
|
2653
|
+
return void 0;
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
async fetch(request) {
|
|
2657
|
+
if (request.method !== "POST")
|
|
2658
|
+
return this.error("InvalidParameterException", "Only POST is supported");
|
|
2659
|
+
const operation = (request.headers.get("x-amz-target") ?? "").split(".").at(-1) ?? "";
|
|
2660
|
+
const input = await request.json().catch(() => ({}));
|
|
2661
|
+
if (operation === "AnalyzeDocument") {
|
|
2662
|
+
const featureTypesInput = read(input, "featureTypes");
|
|
2663
|
+
const featureTypes = Array.isArray(featureTypesInput) ? featureTypesInput : [];
|
|
2664
|
+
if (!featureTypes.length)
|
|
2665
|
+
return this.error("InvalidParameterException", "FeatureTypes is required");
|
|
2666
|
+
const corpus = this.corpus(read(input, "document"));
|
|
2667
|
+
if (!corpus)
|
|
2668
|
+
return this.error("InvalidS3ObjectException", "Unable to access the requested S3 object");
|
|
2669
|
+
return this.response(
|
|
2670
|
+
this.result({
|
|
2671
|
+
blocks: corpus.blocks,
|
|
2672
|
+
pages: corpus.pages ?? Math.max(1, corpus.blocks.filter((b) => b.blockType === "PAGE").length),
|
|
2673
|
+
...corpus.warnings ? { warnings: corpus.warnings } : {},
|
|
2674
|
+
modelVersion: corpus.modelVersion ?? "1.0"
|
|
2675
|
+
})
|
|
2676
|
+
);
|
|
2677
|
+
}
|
|
2678
|
+
if (operation === "StartDocumentAnalysis") {
|
|
2679
|
+
const documentLocation = read(input, "documentLocation");
|
|
2680
|
+
const location = this.s3(documentLocation);
|
|
2681
|
+
if (!location)
|
|
2682
|
+
return this.error("InvalidParameterException", "DocumentLocation.S3Object is required");
|
|
2683
|
+
const featureTypesInput = read(input, "featureTypes");
|
|
2684
|
+
const featureTypes = Array.isArray(featureTypesInput) ? featureTypesInput.filter((item) => typeof item === "string") : [];
|
|
2685
|
+
if (!featureTypes.length)
|
|
2686
|
+
return this.error("InvalidParameterException", "FeatureTypes is required");
|
|
2687
|
+
const corpus = this.corpus(documentLocation);
|
|
2688
|
+
if (!corpus)
|
|
2689
|
+
return this.error("InvalidS3ObjectException", "Unable to access the requested S3 object");
|
|
2690
|
+
const requestShape = {
|
|
2691
|
+
documentLocation,
|
|
2692
|
+
featureTypes: featureTypesInput,
|
|
2693
|
+
jobTag: read(input, "jobTag"),
|
|
2694
|
+
notificationChannel: read(input, "notificationChannel"),
|
|
2695
|
+
outputConfig: read(input, "outputConfig"),
|
|
2696
|
+
kmsKeyId: read(input, "kmsKeyId"),
|
|
2697
|
+
adaptersConfig: read(input, "adaptersConfig")
|
|
2698
|
+
};
|
|
2699
|
+
const fingerprint = stable(requestShape);
|
|
2700
|
+
const clientRequestToken = typeof read(input, "clientRequestToken") === "string" ? read(input, "clientRequestToken") : void 0;
|
|
2701
|
+
const prior = clientRequestToken ? this.state.jobs.list({ where: (job2) => job2.clientRequestToken === clientRequestToken }).map(({ value }) => value)[0] : void 0;
|
|
2702
|
+
if (prior)
|
|
2703
|
+
return prior.requestFingerprint === fingerprint ? this.response({ JobId: prior.id }) : this.error(
|
|
2704
|
+
"IdempotentParameterMismatchException",
|
|
2705
|
+
"Parameters differ from the previous request with this ClientRequestToken"
|
|
2706
|
+
);
|
|
2707
|
+
const id = this.state.ids.next("job-", 48);
|
|
2708
|
+
const notification = read(input, "notificationChannel") && typeof read(input, "notificationChannel") === "object" ? read(input, "notificationChannel") : void 0;
|
|
2709
|
+
const job = {
|
|
2710
|
+
id,
|
|
2711
|
+
status: "IN_PROGRESS",
|
|
2712
|
+
document: location,
|
|
2713
|
+
featureTypes,
|
|
2714
|
+
requestFingerprint: fingerprint,
|
|
2715
|
+
blocks: copy(corpus.blocks),
|
|
2716
|
+
pages: corpus.pages ?? Math.max(1, corpus.blocks.filter((b) => b.blockType === "PAGE").length),
|
|
2717
|
+
...corpus.warnings ? { warnings: copy(corpus.warnings) } : {},
|
|
2718
|
+
modelVersion: corpus.modelVersion ?? "1.0",
|
|
2719
|
+
...corpus.pageSize ? { pageSize: corpus.pageSize } : {},
|
|
2720
|
+
...clientRequestToken ? { clientRequestToken } : {},
|
|
2721
|
+
...typeof read(input, "jobTag") === "string" ? { jobTag: read(input, "jobTag") } : {},
|
|
2722
|
+
...notification ? {
|
|
2723
|
+
notificationChannel: {
|
|
2724
|
+
...typeof read(notification, "roleArn") === "string" ? { roleArn: read(notification, "roleArn") } : {},
|
|
2725
|
+
...typeof read(notification, "snsTopicArn") === "string" ? { snsTopicArn: read(notification, "snsTopicArn") } : {}
|
|
2726
|
+
}
|
|
2727
|
+
} : {},
|
|
2728
|
+
createdAt: this.now()
|
|
2729
|
+
};
|
|
2730
|
+
this.state.jobs.insert(id, job);
|
|
2731
|
+
return this.response({ JobId: id });
|
|
2732
|
+
}
|
|
2733
|
+
if (operation === "GetDocumentAnalysis") {
|
|
2734
|
+
const jobId = read(input, "jobId");
|
|
2735
|
+
if (typeof jobId !== "string")
|
|
2736
|
+
return this.error("InvalidParameterException", "JobId is required");
|
|
2737
|
+
const job = this.state.jobs.get(jobId);
|
|
2738
|
+
if (!job) return this.error("InvalidJobIdException", "The specified JobId is invalid");
|
|
2739
|
+
if (job.status === "IN_PROGRESS") return this.response({ JobStatus: job.status });
|
|
2740
|
+
const offset = this.parseToken(read(input, "nextToken"), job.id);
|
|
2741
|
+
if (offset === void 0)
|
|
2742
|
+
return this.error("InvalidParameterException", "NextToken is invalid for this job");
|
|
2743
|
+
const requested = Number(read(input, "maxResults") ?? job.pageSize ?? 1e3);
|
|
2744
|
+
if (!Number.isInteger(requested) || requested < 1 || requested > 1e3)
|
|
2745
|
+
return this.error("InvalidParameterException", "MaxResults must be between 1 and 1000");
|
|
2746
|
+
const blocks = job.status === "FAILED" ? [] : job.blocks.slice(offset, offset + requested);
|
|
2747
|
+
const nextOffset = offset + blocks.length;
|
|
2748
|
+
return this.response({
|
|
2749
|
+
JobStatus: job.status,
|
|
2750
|
+
...job.statusMessage ? { StatusMessage: job.statusMessage } : {},
|
|
2751
|
+
...this.result({
|
|
2752
|
+
blocks,
|
|
2753
|
+
pages: job.pages,
|
|
2754
|
+
...job.warnings ? { warnings: job.warnings } : {},
|
|
2755
|
+
modelVersion: job.modelVersion
|
|
2756
|
+
}),
|
|
2757
|
+
...job.status !== "FAILED" && nextOffset < job.blocks.length ? { NextToken: this.token(job.id, nextOffset) } : {}
|
|
2758
|
+
});
|
|
2759
|
+
}
|
|
2760
|
+
return this.error("InvalidParameterException", `Unknown operation ${operation}`);
|
|
2761
|
+
}
|
|
2762
|
+
};
|
|
2763
|
+
|
|
2764
|
+
export {
|
|
2765
|
+
document,
|
|
2766
|
+
operationIds,
|
|
2767
|
+
supportedOperationIds,
|
|
2768
|
+
TEXTRACT_PRESETS,
|
|
2769
|
+
createRuntime2 as createRuntime,
|
|
2770
|
+
TEXTRACT_NAMESPACE,
|
|
2771
|
+
accessKeyCredential,
|
|
2772
|
+
TextractAPI
|
|
2773
|
+
};
|
|
2774
|
+
//# sourceMappingURL=chunk-TLZAWBGK.js.map
|