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