@crvouga/mockingbird-service-rxvortex 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 +124 -0
- package/dist/chunk-DNELVPK4.js +3191 -0
- package/dist/chunk-DNELVPK4.js.map +7 -0
- package/dist/chunk-ZAM35JQO.js +384 -0
- package/dist/chunk-ZAM35JQO.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +966 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1294 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
|
@@ -0,0 +1,3191 @@
|
|
|
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
|
+
// ../../openapi/core/dist/schema.js
|
|
619
|
+
var resolveSchema = (document2, schema) => {
|
|
620
|
+
let current = schema;
|
|
621
|
+
const seen = /* @__PURE__ */ new Set();
|
|
622
|
+
while (typeof current.$ref === "string") {
|
|
623
|
+
const ref = current.$ref;
|
|
624
|
+
if (seen.has(ref))
|
|
625
|
+
break;
|
|
626
|
+
seen.add(ref);
|
|
627
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
628
|
+
const target = resolveRef(document2, ref);
|
|
629
|
+
current = { ...target, ...siblings };
|
|
630
|
+
}
|
|
631
|
+
if (current.nullable === true) {
|
|
632
|
+
const { nullable: _nullable, ...rest } = current;
|
|
633
|
+
const types = schemaTypes(rest);
|
|
634
|
+
if (types.length > 0 && !types.includes("null"))
|
|
635
|
+
current = { ...rest, type: [...types, "null"] };
|
|
636
|
+
else
|
|
637
|
+
current = rest;
|
|
638
|
+
}
|
|
639
|
+
return current;
|
|
640
|
+
};
|
|
641
|
+
var schemaTypes = (schema) => {
|
|
642
|
+
if (Array.isArray(schema.type))
|
|
643
|
+
return schema.type;
|
|
644
|
+
if (schema.type !== void 0)
|
|
645
|
+
return [schema.type];
|
|
646
|
+
const inferred = [];
|
|
647
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
648
|
+
inferred.push("object");
|
|
649
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
650
|
+
inferred.push("array");
|
|
651
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
652
|
+
inferred.push("string");
|
|
653
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
654
|
+
inferred.push("number");
|
|
655
|
+
return inferred;
|
|
656
|
+
};
|
|
657
|
+
var jsonTypeOf = (value) => {
|
|
658
|
+
if (value === null)
|
|
659
|
+
return "null";
|
|
660
|
+
if (Array.isArray(value))
|
|
661
|
+
return "array";
|
|
662
|
+
switch (typeof value) {
|
|
663
|
+
case "string":
|
|
664
|
+
return "string";
|
|
665
|
+
case "boolean":
|
|
666
|
+
return "boolean";
|
|
667
|
+
case "number":
|
|
668
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
669
|
+
case "object":
|
|
670
|
+
return "object";
|
|
671
|
+
default:
|
|
672
|
+
return "undefined";
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
var deepEqual = (a, b) => {
|
|
676
|
+
if (a === b)
|
|
677
|
+
return true;
|
|
678
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
679
|
+
return false;
|
|
680
|
+
if (Array.isArray(a)) {
|
|
681
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
682
|
+
}
|
|
683
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
684
|
+
const ka = Object.keys(a);
|
|
685
|
+
const kb = Object.keys(b);
|
|
686
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
687
|
+
}
|
|
688
|
+
return false;
|
|
689
|
+
};
|
|
690
|
+
var FORMAT_PATTERNS = {
|
|
691
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
|
692
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
693
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
694
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
695
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
696
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
697
|
+
};
|
|
698
|
+
var graphemeLength = (value) => [...value].length;
|
|
699
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
700
|
+
const errors = [];
|
|
701
|
+
const s = resolveSchema(document2, schema);
|
|
702
|
+
const fail = (message) => errors.push({ path, message });
|
|
703
|
+
const actual = jsonTypeOf(value);
|
|
704
|
+
if (actual === "undefined") {
|
|
705
|
+
fail("value is undefined");
|
|
706
|
+
return errors;
|
|
707
|
+
}
|
|
708
|
+
const types = schemaTypes(s);
|
|
709
|
+
if (types.length > 0) {
|
|
710
|
+
const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
711
|
+
if (!ok) {
|
|
712
|
+
fail(`expected type ${types.join("|")}, got ${actual}`);
|
|
713
|
+
return errors;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
717
|
+
fail("value not in enum");
|
|
718
|
+
}
|
|
719
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
720
|
+
fail("value does not equal const");
|
|
721
|
+
if (typeof value === "string") {
|
|
722
|
+
const length = graphemeLength(value);
|
|
723
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
724
|
+
fail(`length ${length} < minLength ${s.minLength}`);
|
|
725
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
726
|
+
fail(`length ${length} > maxLength ${s.maxLength}`);
|
|
727
|
+
if (s.pattern !== void 0) {
|
|
728
|
+
try {
|
|
729
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
730
|
+
fail(`does not match pattern ${s.pattern}`);
|
|
731
|
+
} catch {
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (s.format !== void 0) {
|
|
735
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
736
|
+
if (pattern && !pattern.test(value))
|
|
737
|
+
fail(`does not match format ${s.format}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (typeof value === "number") {
|
|
741
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
742
|
+
fail(`${value} < minimum ${s.minimum}`);
|
|
743
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
744
|
+
fail(`${value} > maximum ${s.maximum}`);
|
|
745
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
746
|
+
fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
747
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
748
|
+
fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
749
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
750
|
+
fail(`${value} is not a multiple of ${s.multipleOf}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (Array.isArray(value)) {
|
|
754
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
755
|
+
fail(`${value.length} items < minItems ${s.minItems}`);
|
|
756
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
757
|
+
fail(`${value.length} items > maxItems ${s.maxItems}`);
|
|
758
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
759
|
+
fail("items are not unique");
|
|
760
|
+
value.forEach((item, i) => {
|
|
761
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
762
|
+
if (itemSchema)
|
|
763
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
if (actual === "object") {
|
|
767
|
+
const record2 = value;
|
|
768
|
+
const keys = Object.keys(record2);
|
|
769
|
+
for (const name of s.required ?? [])
|
|
770
|
+
if (!(name in record2))
|
|
771
|
+
fail(`missing required property ${name}`);
|
|
772
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
773
|
+
fail(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
774
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
775
|
+
fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
776
|
+
for (const key of keys) {
|
|
777
|
+
const property = s.properties?.[key];
|
|
778
|
+
if (property) {
|
|
779
|
+
errors.push(...validateValue(document2, property, record2[key], [...path, key]));
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (s.additionalProperties === false)
|
|
783
|
+
fail(`unexpected property ${key}`);
|
|
784
|
+
else if (typeof s.additionalProperties === "object") {
|
|
785
|
+
errors.push(...validateValue(document2, s.additionalProperties, record2[key], [...path, key]));
|
|
786
|
+
}
|
|
787
|
+
if (s.propertyNames) {
|
|
788
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
789
|
+
if (nameErrors.length > 0)
|
|
790
|
+
fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (s.allOf)
|
|
795
|
+
for (const branch of s.allOf)
|
|
796
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
797
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
798
|
+
fail("matches no anyOf branch");
|
|
799
|
+
if (s.oneOf) {
|
|
800
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
801
|
+
if (matches2 !== 1)
|
|
802
|
+
fail(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
803
|
+
}
|
|
804
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
805
|
+
fail("matches forbidden `not` schema");
|
|
806
|
+
return errors;
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
// ../../http/codec/dist/form.js
|
|
810
|
+
var parsePath = (rawKey) => {
|
|
811
|
+
const open = rawKey.indexOf("[");
|
|
812
|
+
if (open === -1)
|
|
813
|
+
return [rawKey];
|
|
814
|
+
const path = [rawKey.slice(0, open)];
|
|
815
|
+
const rest = rawKey.slice(open);
|
|
816
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
817
|
+
let match = pattern.exec(rest);
|
|
818
|
+
let consumed = 0;
|
|
819
|
+
while (match !== null) {
|
|
820
|
+
if (match.index !== consumed)
|
|
821
|
+
return [rawKey];
|
|
822
|
+
path.push(match[1] ?? "");
|
|
823
|
+
consumed = match.index + match[0].length;
|
|
824
|
+
match = pattern.exec(rest);
|
|
825
|
+
}
|
|
826
|
+
if (consumed !== rest.length)
|
|
827
|
+
return [rawKey];
|
|
828
|
+
return path;
|
|
829
|
+
};
|
|
830
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
831
|
+
var put = (target, key, value) => {
|
|
832
|
+
if (key === "__proto__") {
|
|
833
|
+
Object.defineProperty(target, key, {
|
|
834
|
+
value,
|
|
835
|
+
enumerable: true,
|
|
836
|
+
writable: true,
|
|
837
|
+
configurable: true
|
|
838
|
+
});
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
;
|
|
842
|
+
target[key] = value;
|
|
843
|
+
};
|
|
844
|
+
var assign = (target, path, value) => {
|
|
845
|
+
let cursor = target;
|
|
846
|
+
for (let i = 0; i < path.length; i++) {
|
|
847
|
+
const segment = path[i];
|
|
848
|
+
const last = i === path.length - 1;
|
|
849
|
+
if (Array.isArray(cursor)) {
|
|
850
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
851
|
+
if (index === void 0)
|
|
852
|
+
return;
|
|
853
|
+
if (last) {
|
|
854
|
+
put(cursor, index, value);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
858
|
+
if (next === void 0 || typeof next === "string") {
|
|
859
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
860
|
+
put(cursor, index, created);
|
|
861
|
+
cursor = created;
|
|
862
|
+
} else {
|
|
863
|
+
cursor = next;
|
|
864
|
+
}
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if (typeof cursor === "string")
|
|
868
|
+
return;
|
|
869
|
+
if (last) {
|
|
870
|
+
put(cursor, segment, value);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
const nextSegment = path[i + 1];
|
|
874
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
875
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
876
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
877
|
+
put(cursor, segment, created);
|
|
878
|
+
cursor = created;
|
|
879
|
+
} else {
|
|
880
|
+
cursor = existing;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
var decodeFormPairs = (pairs) => {
|
|
885
|
+
const out = {};
|
|
886
|
+
for (const [rawKey, value] of pairs)
|
|
887
|
+
assign(out, parsePath(rawKey), value);
|
|
888
|
+
return densify(out);
|
|
889
|
+
};
|
|
890
|
+
var densify = (value) => {
|
|
891
|
+
if (typeof value === "string")
|
|
892
|
+
return value;
|
|
893
|
+
if (Array.isArray(value))
|
|
894
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
895
|
+
const out = {};
|
|
896
|
+
for (const [key, item] of Object.entries(value))
|
|
897
|
+
put(out, key, densify(item));
|
|
898
|
+
return out;
|
|
899
|
+
};
|
|
900
|
+
var decodeForm = (text) => {
|
|
901
|
+
const source = text.startsWith("?") ? text.slice(1) : text;
|
|
902
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
903
|
+
};
|
|
904
|
+
|
|
905
|
+
// ../../http/codec/dist/content.js
|
|
906
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
907
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
908
|
+
var mediaTypeOf = (contentType) => {
|
|
909
|
+
if (!contentType)
|
|
910
|
+
return void 0;
|
|
911
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
912
|
+
return essence ? essence : void 0;
|
|
913
|
+
};
|
|
914
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
915
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
916
|
+
var decodeBody = (contentType, bytes) => {
|
|
917
|
+
if (bytes.byteLength === 0)
|
|
918
|
+
return { kind: "empty" };
|
|
919
|
+
const mediaType = mediaTypeOf(contentType);
|
|
920
|
+
if (mediaType === void 0)
|
|
921
|
+
return { kind: "bytes", value: bytes };
|
|
922
|
+
if (isJsonMediaType(mediaType)) {
|
|
923
|
+
const text = utf8.decode(bytes);
|
|
924
|
+
try {
|
|
925
|
+
return { kind: "json", value: JSON.parse(text) };
|
|
926
|
+
} catch (error) {
|
|
927
|
+
return {
|
|
928
|
+
kind: "invalid",
|
|
929
|
+
mediaType,
|
|
930
|
+
text,
|
|
931
|
+
error: error instanceof Error ? error.message : String(error)
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
936
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
937
|
+
}
|
|
938
|
+
if (mediaType.startsWith("text/"))
|
|
939
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
940
|
+
return { kind: "bytes", value: bytes };
|
|
941
|
+
};
|
|
942
|
+
var readBody = async (message) => {
|
|
943
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
944
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
945
|
+
};
|
|
946
|
+
|
|
947
|
+
// ../core/dist/http.js
|
|
948
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
949
|
+
status,
|
|
950
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
951
|
+
});
|
|
952
|
+
var HttpError = class extends Error {
|
|
953
|
+
status;
|
|
954
|
+
body;
|
|
955
|
+
headers;
|
|
956
|
+
constructor(status, body, headers = {}) {
|
|
957
|
+
super(`HTTP ${status}`);
|
|
958
|
+
this.status = status;
|
|
959
|
+
this.body = body;
|
|
960
|
+
this.headers = headers;
|
|
961
|
+
this.name = "HttpError";
|
|
962
|
+
}
|
|
963
|
+
toResponse() {
|
|
964
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
965
|
+
if (contentType === "text/plain") {
|
|
966
|
+
return new Response(String(this.body), {
|
|
967
|
+
status: this.status,
|
|
968
|
+
headers: this.headers
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
// ../core/dist/ids.js
|
|
976
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
977
|
+
var mix = (input) => {
|
|
978
|
+
let hash = 2166136261;
|
|
979
|
+
for (let i = 0; i < input.length; i++) {
|
|
980
|
+
hash ^= input.charCodeAt(i);
|
|
981
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
982
|
+
}
|
|
983
|
+
hash ^= hash >>> 16;
|
|
984
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
985
|
+
hash ^= hash >>> 13;
|
|
986
|
+
return hash >>> 0;
|
|
987
|
+
};
|
|
988
|
+
var opaqueToken = (input, length) => {
|
|
989
|
+
let out = "";
|
|
990
|
+
let round = 0;
|
|
991
|
+
while (out.length < length) {
|
|
992
|
+
let hash = mix(`${input}:${round++}`);
|
|
993
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
994
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
995
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return out;
|
|
999
|
+
};
|
|
1000
|
+
var IdSequence = class {
|
|
1001
|
+
sqlite;
|
|
1002
|
+
namespace;
|
|
1003
|
+
salt;
|
|
1004
|
+
constructor(sqlite, namespace, salt = "mockingbird") {
|
|
1005
|
+
this.sqlite = sqlite;
|
|
1006
|
+
this.namespace = namespace;
|
|
1007
|
+
this.salt = salt;
|
|
1008
|
+
}
|
|
1009
|
+
next(prefix, length = 14) {
|
|
1010
|
+
return this.sqlite.transaction(() => {
|
|
1011
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
|
|
1012
|
+
const value = (row?.value ?? 0) + 1;
|
|
1013
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
|
|
1014
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
|
|
1015
|
+
return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
|
|
1020
|
+
// ../core/dist/journal.js
|
|
1021
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1022
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1023
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1024
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1025
|
+
let sequence = 0;
|
|
1026
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1027
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1028
|
+
return {
|
|
1029
|
+
size: capacity,
|
|
1030
|
+
record(entry) {
|
|
1031
|
+
if (capacity === 0)
|
|
1032
|
+
return;
|
|
1033
|
+
order.set(entry, sequence++);
|
|
1034
|
+
let ring = rings.get(entry.namespace);
|
|
1035
|
+
if (!ring) {
|
|
1036
|
+
ring = { entries: [], next: 0 };
|
|
1037
|
+
rings.set(entry.namespace, ring);
|
|
1038
|
+
}
|
|
1039
|
+
if (ring.entries.length < capacity)
|
|
1040
|
+
ring.entries.push(entry);
|
|
1041
|
+
else {
|
|
1042
|
+
ring.entries[ring.next] = entry;
|
|
1043
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1044
|
+
}
|
|
1045
|
+
},
|
|
1046
|
+
list(query = {}) {
|
|
1047
|
+
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));
|
|
1048
|
+
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));
|
|
1049
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1050
|
+
},
|
|
1051
|
+
clear(namespace) {
|
|
1052
|
+
if (namespace === void 0)
|
|
1053
|
+
rings.clear();
|
|
1054
|
+
else
|
|
1055
|
+
rings.delete(namespace);
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
};
|
|
1059
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1060
|
+
var annotateResponse = (response, extra) => {
|
|
1061
|
+
const existing = notes.get(response);
|
|
1062
|
+
notes.set(response, {
|
|
1063
|
+
...existing,
|
|
1064
|
+
...extra,
|
|
1065
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1066
|
+
});
|
|
1067
|
+
return response;
|
|
1068
|
+
};
|
|
1069
|
+
var responseNotes = (response) => notes.get(response);
|
|
1070
|
+
|
|
1071
|
+
// ../core/dist/metrics.js
|
|
1072
|
+
var createMetrics = () => {
|
|
1073
|
+
let requests = 0;
|
|
1074
|
+
let faults = 0;
|
|
1075
|
+
let totalDurationMs = 0;
|
|
1076
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1077
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1078
|
+
return {
|
|
1079
|
+
record(entry) {
|
|
1080
|
+
requests++;
|
|
1081
|
+
totalDurationMs += entry.durationMs;
|
|
1082
|
+
if (entry.faultId !== void 0)
|
|
1083
|
+
faults++;
|
|
1084
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1085
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1086
|
+
if (entry.unmatched) {
|
|
1087
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1088
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1089
|
+
}
|
|
1090
|
+
},
|
|
1091
|
+
report: () => ({
|
|
1092
|
+
requests,
|
|
1093
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1094
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1095
|
+
const space = route.indexOf(" ");
|
|
1096
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1097
|
+
}),
|
|
1098
|
+
faults,
|
|
1099
|
+
totalDurationMs
|
|
1100
|
+
}),
|
|
1101
|
+
reset() {
|
|
1102
|
+
requests = 0;
|
|
1103
|
+
faults = 0;
|
|
1104
|
+
totalDurationMs = 0;
|
|
1105
|
+
byOperation.clear();
|
|
1106
|
+
unmatched.clear();
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
};
|
|
1110
|
+
|
|
1111
|
+
// ../../core/dist/timeline.js
|
|
1112
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1113
|
+
var Timeline = class {
|
|
1114
|
+
maxCheckpoints;
|
|
1115
|
+
now;
|
|
1116
|
+
makeId;
|
|
1117
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1118
|
+
heads = /* @__PURE__ */ new Map();
|
|
1119
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1120
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1121
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1122
|
+
references = /* @__PURE__ */ new Map();
|
|
1123
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1124
|
+
sequence = 0;
|
|
1125
|
+
constructor(options = {}) {
|
|
1126
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1127
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1128
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1129
|
+
this.maxCheckpoints = max;
|
|
1130
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1131
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1132
|
+
}
|
|
1133
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1134
|
+
commit(value, options = {}) {
|
|
1135
|
+
const branch = options.branch ?? "main";
|
|
1136
|
+
this.assertBranch(branch);
|
|
1137
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1138
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1139
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1140
|
+
const id = this.makeId(++this.sequence);
|
|
1141
|
+
if (this.nodes.has(id))
|
|
1142
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1143
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1144
|
+
this.nodes.set(id, checkpoint);
|
|
1145
|
+
this.moveHead(branch, id);
|
|
1146
|
+
this.collect(this.maxCheckpoints);
|
|
1147
|
+
return checkpoint;
|
|
1148
|
+
}
|
|
1149
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1150
|
+
fork(branch, options = {}) {
|
|
1151
|
+
this.assertBranch(branch);
|
|
1152
|
+
if (this.heads.has(branch))
|
|
1153
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1154
|
+
const from = options.from ?? this.heads.get("main");
|
|
1155
|
+
if (from === void 0)
|
|
1156
|
+
return void 0;
|
|
1157
|
+
const checkpoint = this.get(from);
|
|
1158
|
+
this.moveHead(branch, checkpoint.id);
|
|
1159
|
+
return checkpoint;
|
|
1160
|
+
}
|
|
1161
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1162
|
+
checkout(branch, id) {
|
|
1163
|
+
this.assertBranch(branch);
|
|
1164
|
+
const checkpoint = this.get(id);
|
|
1165
|
+
this.moveHead(branch, checkpoint.id);
|
|
1166
|
+
return checkpoint;
|
|
1167
|
+
}
|
|
1168
|
+
get(id) {
|
|
1169
|
+
const checkpoint = this.nodes.get(id);
|
|
1170
|
+
if (!checkpoint)
|
|
1171
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1172
|
+
return checkpoint;
|
|
1173
|
+
}
|
|
1174
|
+
head(branch = "main") {
|
|
1175
|
+
const id = this.heads.get(branch);
|
|
1176
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1177
|
+
}
|
|
1178
|
+
hasBranch(branch) {
|
|
1179
|
+
return this.heads.has(branch);
|
|
1180
|
+
}
|
|
1181
|
+
branches() {
|
|
1182
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1183
|
+
}
|
|
1184
|
+
checkpoints() {
|
|
1185
|
+
return [...this.nodes.values()];
|
|
1186
|
+
}
|
|
1187
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1188
|
+
get size() {
|
|
1189
|
+
return this.nodes.size;
|
|
1190
|
+
}
|
|
1191
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1192
|
+
retain(id) {
|
|
1193
|
+
const checkpoint = this.get(id);
|
|
1194
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1195
|
+
this.addReference(id);
|
|
1196
|
+
return checkpoint;
|
|
1197
|
+
}
|
|
1198
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1199
|
+
release(id) {
|
|
1200
|
+
if (!this.nodes.has(id))
|
|
1201
|
+
return false;
|
|
1202
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1203
|
+
if (pins === 0)
|
|
1204
|
+
return false;
|
|
1205
|
+
if (pins === 1)
|
|
1206
|
+
this.explicitPins.delete(id);
|
|
1207
|
+
else
|
|
1208
|
+
this.explicitPins.set(id, pins - 1);
|
|
1209
|
+
this.removeReference(id);
|
|
1210
|
+
this.collect(this.maxCheckpoints);
|
|
1211
|
+
return true;
|
|
1212
|
+
}
|
|
1213
|
+
deleteBranch(branch) {
|
|
1214
|
+
if (branch === "main")
|
|
1215
|
+
throw new RangeError("cannot delete main branch");
|
|
1216
|
+
const previous = this.heads.get(branch);
|
|
1217
|
+
const deleted = this.heads.delete(branch);
|
|
1218
|
+
if (previous !== void 0)
|
|
1219
|
+
this.removeReference(previous);
|
|
1220
|
+
this.collect(this.maxCheckpoints);
|
|
1221
|
+
return deleted;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1225
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1226
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1227
|
+
*/
|
|
1228
|
+
gc(max = this.maxCheckpoints) {
|
|
1229
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1230
|
+
throw new RangeError("max must be a positive integer");
|
|
1231
|
+
const removed = [];
|
|
1232
|
+
this.collect(max, removed);
|
|
1233
|
+
return removed;
|
|
1234
|
+
}
|
|
1235
|
+
collect(max, removed) {
|
|
1236
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1237
|
+
const id = this.evictable.values().next().value;
|
|
1238
|
+
this.evictable.delete(id);
|
|
1239
|
+
this.nodes.delete(id);
|
|
1240
|
+
removed?.push(id);
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
moveHead(branch, id) {
|
|
1244
|
+
const previous = this.heads.get(branch);
|
|
1245
|
+
if (previous === id)
|
|
1246
|
+
return;
|
|
1247
|
+
if (previous !== void 0)
|
|
1248
|
+
this.removeReference(previous);
|
|
1249
|
+
this.heads.set(branch, id);
|
|
1250
|
+
this.addReference(id);
|
|
1251
|
+
}
|
|
1252
|
+
addReference(id) {
|
|
1253
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1254
|
+
this.evictable.delete(id);
|
|
1255
|
+
}
|
|
1256
|
+
removeReference(id) {
|
|
1257
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1258
|
+
if (next > 0)
|
|
1259
|
+
this.references.set(id, next);
|
|
1260
|
+
else {
|
|
1261
|
+
this.references.delete(id);
|
|
1262
|
+
if (this.nodes.has(id))
|
|
1263
|
+
this.evictable.add(id);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
assertBranch(branch) {
|
|
1267
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1268
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1269
|
+
}
|
|
1270
|
+
};
|
|
1271
|
+
|
|
1272
|
+
// ../../sqlite/dist/default.js
|
|
1273
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1274
|
+
var createDefaultSqlite = () => new Database();
|
|
1275
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1276
|
+
|
|
1277
|
+
// ../../sqlite/dist/migrate.js
|
|
1278
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1279
|
+
sqlite.exec(`
|
|
1280
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1281
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1282
|
+
applied_at INTEGER NOT NULL
|
|
1283
|
+
)
|
|
1284
|
+
`);
|
|
1285
|
+
};
|
|
1286
|
+
var migrate = (sqlite, migrations) => {
|
|
1287
|
+
ensureMigrationsTable(sqlite);
|
|
1288
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1289
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1290
|
+
if (pending.length === 0)
|
|
1291
|
+
return;
|
|
1292
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1293
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1294
|
+
sqlite.transaction(() => {
|
|
1295
|
+
for (const migration of pending) {
|
|
1296
|
+
sqlite.exec(migration.sql);
|
|
1297
|
+
insert.run(migration.id, now);
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
};
|
|
1301
|
+
|
|
1302
|
+
// ../../sqlite/dist/schema.js
|
|
1303
|
+
var CORE_MIGRATIONS = [
|
|
1304
|
+
{
|
|
1305
|
+
id: "20260322_core_records_sequences",
|
|
1306
|
+
sql: `
|
|
1307
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1308
|
+
namespace TEXT NOT NULL,
|
|
1309
|
+
collection TEXT NOT NULL,
|
|
1310
|
+
id TEXT NOT NULL,
|
|
1311
|
+
seq INTEGER NOT NULL,
|
|
1312
|
+
value TEXT NOT NULL,
|
|
1313
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1314
|
+
);
|
|
1315
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1316
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1317
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1318
|
+
namespace TEXT NOT NULL,
|
|
1319
|
+
name TEXT NOT NULL,
|
|
1320
|
+
kind TEXT NOT NULL,
|
|
1321
|
+
value INTEGER NOT NULL,
|
|
1322
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1323
|
+
);
|
|
1324
|
+
`
|
|
1325
|
+
}
|
|
1326
|
+
];
|
|
1327
|
+
var migrateCore = (sqlite) => {
|
|
1328
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1329
|
+
};
|
|
1330
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1331
|
+
sqlite.transaction(() => {
|
|
1332
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1333
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1334
|
+
});
|
|
1335
|
+
};
|
|
1336
|
+
|
|
1337
|
+
// ../../openapi/metadata/dist/types.js
|
|
1338
|
+
var EXTENSION_KEYS = {
|
|
1339
|
+
operation: "x-mockingbird",
|
|
1340
|
+
resource: "x-mockingbird-resource",
|
|
1341
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1342
|
+
volatile: "x-mockingbird-volatile",
|
|
1343
|
+
scope: "x-mockingbird-scope",
|
|
1344
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1345
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1346
|
+
};
|
|
1347
|
+
|
|
1348
|
+
// ../../openapi/metadata/dist/read.js
|
|
1349
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1350
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1351
|
+
var operationMetadata = (operation) => {
|
|
1352
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1353
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1354
|
+
const supported = ext.supported ?? true;
|
|
1355
|
+
const parity = ext.parity ?? {};
|
|
1356
|
+
return {
|
|
1357
|
+
supported,
|
|
1358
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1359
|
+
parity: {
|
|
1360
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1361
|
+
safe: parity.safe ?? true,
|
|
1362
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1363
|
+
}
|
|
1364
|
+
};
|
|
1365
|
+
};
|
|
1366
|
+
|
|
1367
|
+
// ../core/dist/service.js
|
|
1368
|
+
import { Hono } from "hono";
|
|
1369
|
+
var defineOperations = (handlers) => handlers;
|
|
1370
|
+
var OperationRegistryError = class extends Error {
|
|
1371
|
+
problems;
|
|
1372
|
+
constructor(problems) {
|
|
1373
|
+
super(`operation registry is inconsistent:
|
|
1374
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1375
|
+
this.problems = problems;
|
|
1376
|
+
this.name = "OperationRegistryError";
|
|
1377
|
+
}
|
|
1378
|
+
};
|
|
1379
|
+
var verifyOperations = (document2, handlers) => {
|
|
1380
|
+
const problems = [];
|
|
1381
|
+
const operations = listOperations(document2);
|
|
1382
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1383
|
+
for (const operation of operations) {
|
|
1384
|
+
if (seen.has(operation.operationId))
|
|
1385
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1386
|
+
seen.add(operation.operationId);
|
|
1387
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1388
|
+
const handler = handlers[operation.operationId];
|
|
1389
|
+
if (supported && !handler)
|
|
1390
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1391
|
+
if (!supported && handler)
|
|
1392
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1393
|
+
}
|
|
1394
|
+
for (const id of Object.keys(handlers)) {
|
|
1395
|
+
if (!seen.has(id))
|
|
1396
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1397
|
+
}
|
|
1398
|
+
return problems;
|
|
1399
|
+
};
|
|
1400
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1401
|
+
var routeOrder = (a, b) => {
|
|
1402
|
+
const sa = a.path.split("/");
|
|
1403
|
+
const sb = b.path.split("/");
|
|
1404
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1405
|
+
const x = sa[i] ?? "";
|
|
1406
|
+
const y = sb[i] ?? "";
|
|
1407
|
+
const px = x.startsWith("{");
|
|
1408
|
+
const py = y.startsWith("{");
|
|
1409
|
+
if (px !== py)
|
|
1410
|
+
return px ? 1 : -1;
|
|
1411
|
+
if (x !== y)
|
|
1412
|
+
return x < y ? -1 : 1;
|
|
1413
|
+
}
|
|
1414
|
+
return 0;
|
|
1415
|
+
};
|
|
1416
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1417
|
+
var bootSqlite = (sqlite) => {
|
|
1418
|
+
const client = resolveSqlite(sqlite);
|
|
1419
|
+
migrateCore(client);
|
|
1420
|
+
return client;
|
|
1421
|
+
};
|
|
1422
|
+
var createService = (options) => {
|
|
1423
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1424
|
+
if (problems.length > 0)
|
|
1425
|
+
throw new OperationRegistryError(problems);
|
|
1426
|
+
migrateCore(options.sqlite);
|
|
1427
|
+
const now = options.now ?? (() => Date.now());
|
|
1428
|
+
const app = new Hono();
|
|
1429
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1430
|
+
app.onError((error, c) => options.onError(error, c.req.raw));
|
|
1431
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1432
|
+
for (const operation of operations) {
|
|
1433
|
+
const metadata = operationMetadata(operation.operation);
|
|
1434
|
+
const handler = options.handlers[operation.operationId];
|
|
1435
|
+
const route = async (c) => {
|
|
1436
|
+
const request = c.req.raw;
|
|
1437
|
+
if (!metadata.supported || !handler) {
|
|
1438
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1439
|
+
}
|
|
1440
|
+
const url = new URL(request.url);
|
|
1441
|
+
const context = {
|
|
1442
|
+
request,
|
|
1443
|
+
url,
|
|
1444
|
+
params: c.req.param(),
|
|
1445
|
+
query: queryOf(url),
|
|
1446
|
+
body: await readBody(request),
|
|
1447
|
+
sqlite: options.sqlite,
|
|
1448
|
+
namespace: options.namespace,
|
|
1449
|
+
operation,
|
|
1450
|
+
document: options.document,
|
|
1451
|
+
now
|
|
1452
|
+
};
|
|
1453
|
+
const short = await options.before?.(context);
|
|
1454
|
+
if (short)
|
|
1455
|
+
return short;
|
|
1456
|
+
return handler(context);
|
|
1457
|
+
};
|
|
1458
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1459
|
+
}
|
|
1460
|
+
return {
|
|
1461
|
+
app,
|
|
1462
|
+
sqlite: options.sqlite,
|
|
1463
|
+
namespace: options.namespace,
|
|
1464
|
+
fetch: async (request) => app.fetch(request),
|
|
1465
|
+
reset: async () => {
|
|
1466
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1467
|
+
}
|
|
1468
|
+
};
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
// ../core/dist/snapshot.js
|
|
1472
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1473
|
+
namespace,
|
|
1474
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1475
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1476
|
+
});
|
|
1477
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1478
|
+
sqlite.transaction(() => {
|
|
1479
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1480
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1481
|
+
const record2 = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1482
|
+
for (const row of snapshot.records) {
|
|
1483
|
+
record2.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1484
|
+
}
|
|
1485
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1486
|
+
for (const row of snapshot.sequences) {
|
|
1487
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1488
|
+
}
|
|
1489
|
+
});
|
|
1490
|
+
};
|
|
1491
|
+
|
|
1492
|
+
// ../core/dist/version.js
|
|
1493
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1494
|
+
|
|
1495
|
+
// ../core/dist/signing.js
|
|
1496
|
+
var encoder = new TextEncoder();
|
|
1497
|
+
var toBase64 = (bytes) => {
|
|
1498
|
+
let binary = "";
|
|
1499
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1500
|
+
binary += String.fromCharCode(byte);
|
|
1501
|
+
}
|
|
1502
|
+
return btoa(binary);
|
|
1503
|
+
};
|
|
1504
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1505
|
+
var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1506
|
+
var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
|
|
1507
|
+
var hmac = async (algorithm, key, message, encoding = "hex") => {
|
|
1508
|
+
const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
1509
|
+
const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
|
|
1510
|
+
return encoding === "hex" ? toHex(signed) : toBase64(signed);
|
|
1511
|
+
};
|
|
1512
|
+
var svixSecretBytes = (secret) => {
|
|
1513
|
+
const raw = secret.replace(/^f?whsec_/, "");
|
|
1514
|
+
try {
|
|
1515
|
+
return fromBase64(raw);
|
|
1516
|
+
} catch {
|
|
1517
|
+
throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
|
|
1518
|
+
}
|
|
1519
|
+
};
|
|
1520
|
+
var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
|
|
1521
|
+
var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
|
|
1522
|
+
var signTwilio = async (authToken, url, params) => {
|
|
1523
|
+
const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
|
|
1524
|
+
return hmac("SHA-1", authToken, payload, "base64");
|
|
1525
|
+
};
|
|
1526
|
+
|
|
1527
|
+
// ../core/dist/webhooks.js
|
|
1528
|
+
var signers = {
|
|
1529
|
+
/** No signature. */
|
|
1530
|
+
none: () => () => ({}),
|
|
1531
|
+
/** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
|
|
1532
|
+
svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
|
|
1533
|
+
if (!secret)
|
|
1534
|
+
return {};
|
|
1535
|
+
const prefix = options.prefix ?? "svix";
|
|
1536
|
+
return {
|
|
1537
|
+
[`${prefix}-id`]: messageId,
|
|
1538
|
+
[`${prefix}-timestamp`]: String(timestampSeconds),
|
|
1539
|
+
[`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
|
|
1540
|
+
};
|
|
1541
|
+
},
|
|
1542
|
+
/** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
|
|
1543
|
+
timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
|
|
1544
|
+
/** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
|
|
1545
|
+
twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
|
|
1546
|
+
/** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
|
|
1547
|
+
header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
|
|
1548
|
+
/** Anything else: the service computes the headers itself. */
|
|
1549
|
+
custom: (sign) => sign
|
|
1550
|
+
};
|
|
1551
|
+
var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
|
|
1552
|
+
var unref = (timer) => {
|
|
1553
|
+
;
|
|
1554
|
+
timer.unref?.();
|
|
1555
|
+
};
|
|
1556
|
+
var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
1557
|
+
var matchesEndpoint = (endpoint, message) => {
|
|
1558
|
+
const events = endpoint.events ?? ["*"];
|
|
1559
|
+
if (!events.includes("*") && !events.includes(message.type))
|
|
1560
|
+
return false;
|
|
1561
|
+
for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
|
|
1562
|
+
if (message.tags[key] !== value)
|
|
1563
|
+
return false;
|
|
1564
|
+
}
|
|
1565
|
+
return true;
|
|
1566
|
+
};
|
|
1567
|
+
var createWebhookHub = (options) => {
|
|
1568
|
+
const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
|
|
1569
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
1570
|
+
const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
|
|
1571
|
+
const send = options.fetch ?? ((request) => fetch(request));
|
|
1572
|
+
const keep = options.keep ?? 500;
|
|
1573
|
+
const now = options.now ?? Date.now;
|
|
1574
|
+
const id = options.id ?? randomId;
|
|
1575
|
+
const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
|
1576
|
+
const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
|
1577
|
+
const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
|
|
1578
|
+
const own = /* @__PURE__ */ new Map();
|
|
1579
|
+
const messages = [];
|
|
1580
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
1581
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1582
|
+
const payloads = /* @__PURE__ */ new Map();
|
|
1583
|
+
const faults = /* @__PURE__ */ new Map();
|
|
1584
|
+
const held = /* @__PURE__ */ new Map();
|
|
1585
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
1586
|
+
const track = (work) => {
|
|
1587
|
+
inFlight.add(work);
|
|
1588
|
+
void work.finally(() => inFlight.delete(work));
|
|
1589
|
+
};
|
|
1590
|
+
const attempt = async (delivery) => {
|
|
1591
|
+
const entry = payloads.get(delivery.id);
|
|
1592
|
+
if (!entry)
|
|
1593
|
+
return false;
|
|
1594
|
+
const { message, endpoint } = entry;
|
|
1595
|
+
const timestampSeconds = Math.floor(now() / 1e3);
|
|
1596
|
+
const started = now();
|
|
1597
|
+
const record2 = {
|
|
1598
|
+
attempt: delivery.attempts.length + 1,
|
|
1599
|
+
at: new Date(started).toISOString(),
|
|
1600
|
+
status: null,
|
|
1601
|
+
error: null,
|
|
1602
|
+
durationMs: 0,
|
|
1603
|
+
responseBody: null
|
|
1604
|
+
};
|
|
1605
|
+
const controller = new AbortController();
|
|
1606
|
+
const timer = scheduleTimer(() => controller.abort(), timeoutMs);
|
|
1607
|
+
try {
|
|
1608
|
+
const signed = await options.signer({
|
|
1609
|
+
messageId: message.id,
|
|
1610
|
+
body: message.body,
|
|
1611
|
+
timestampSeconds,
|
|
1612
|
+
url: endpoint.url,
|
|
1613
|
+
secret: endpoint.secret,
|
|
1614
|
+
signUrl: endpoint.signUrl ?? endpoint.url,
|
|
1615
|
+
form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
|
|
1616
|
+
type: message.type,
|
|
1617
|
+
tags: message.tags
|
|
1618
|
+
});
|
|
1619
|
+
const response = await send(new Request(endpoint.url, {
|
|
1620
|
+
method: "POST",
|
|
1621
|
+
headers: {
|
|
1622
|
+
"content-type": message.contentType,
|
|
1623
|
+
...endpoint.headers,
|
|
1624
|
+
...message.headers,
|
|
1625
|
+
...signed
|
|
1626
|
+
},
|
|
1627
|
+
body: message.body,
|
|
1628
|
+
signal: controller.signal
|
|
1629
|
+
}));
|
|
1630
|
+
record2.status = response.status;
|
|
1631
|
+
record2.responseBody = await response.text();
|
|
1632
|
+
} catch (error) {
|
|
1633
|
+
record2.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
|
|
1634
|
+
} finally {
|
|
1635
|
+
cancel(timer);
|
|
1636
|
+
record2.durationMs = now() - started;
|
|
1637
|
+
delivery.attempts.push(record2);
|
|
1638
|
+
}
|
|
1639
|
+
return record2.status !== null && delivered(record2.status);
|
|
1640
|
+
};
|
|
1641
|
+
const schedule = (delivery) => {
|
|
1642
|
+
const index = delivery.attempts.length;
|
|
1643
|
+
if (index >= delays.length) {
|
|
1644
|
+
delivery.state = "failed";
|
|
1645
|
+
pending.delete(delivery.id);
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
const run = () => {
|
|
1649
|
+
pending.delete(delivery.id);
|
|
1650
|
+
track(attempt(delivery).then((ok) => {
|
|
1651
|
+
if (ok)
|
|
1652
|
+
delivery.state = "delivered";
|
|
1653
|
+
else
|
|
1654
|
+
schedule(delivery);
|
|
1655
|
+
}));
|
|
1656
|
+
};
|
|
1657
|
+
const delay = delays[index] ?? 0;
|
|
1658
|
+
if (delay <= 0) {
|
|
1659
|
+
pending.set(delivery.id, void 0);
|
|
1660
|
+
run();
|
|
1661
|
+
return;
|
|
1662
|
+
}
|
|
1663
|
+
const timer = scheduleTimer(run, delay);
|
|
1664
|
+
unref(timer);
|
|
1665
|
+
pending.set(delivery.id, timer);
|
|
1666
|
+
};
|
|
1667
|
+
const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
|
|
1668
|
+
const fanOut = (message, state = "pending") => {
|
|
1669
|
+
for (const endpoint of endpointsFor(message.namespace)) {
|
|
1670
|
+
if (!matchesEndpoint(endpoint, message))
|
|
1671
|
+
continue;
|
|
1672
|
+
const delivery = {
|
|
1673
|
+
id: id("dlv_"),
|
|
1674
|
+
messageId: message.id,
|
|
1675
|
+
namespace: message.namespace,
|
|
1676
|
+
type: message.type,
|
|
1677
|
+
endpointId: endpoint.id ?? "we_unknown",
|
|
1678
|
+
url: endpoint.url,
|
|
1679
|
+
state,
|
|
1680
|
+
attempts: []
|
|
1681
|
+
};
|
|
1682
|
+
deliveries.set(delivery.id, delivery);
|
|
1683
|
+
payloads.set(delivery.id, { message, endpoint });
|
|
1684
|
+
if (state === "pending")
|
|
1685
|
+
schedule(delivery);
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
const takeFault = (namespace) => {
|
|
1689
|
+
const queue = faults.get(namespace);
|
|
1690
|
+
const head = queue?.[0];
|
|
1691
|
+
if (!queue || !head)
|
|
1692
|
+
return void 0;
|
|
1693
|
+
head.remaining--;
|
|
1694
|
+
if (head.remaining <= 0)
|
|
1695
|
+
queue.shift();
|
|
1696
|
+
return head.mode;
|
|
1697
|
+
};
|
|
1698
|
+
const releaseHeld = (namespace) => {
|
|
1699
|
+
const waiting = held.get(namespace);
|
|
1700
|
+
if (!waiting)
|
|
1701
|
+
return;
|
|
1702
|
+
held.delete(namespace);
|
|
1703
|
+
for (const message of waiting)
|
|
1704
|
+
fanOut(message);
|
|
1705
|
+
};
|
|
1706
|
+
const hub = {
|
|
1707
|
+
publish(input) {
|
|
1708
|
+
const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
|
|
1709
|
+
const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
|
|
1710
|
+
const message = {
|
|
1711
|
+
id: input.id ?? id("msg_"),
|
|
1712
|
+
namespace: input.namespace,
|
|
1713
|
+
type: input.type,
|
|
1714
|
+
body,
|
|
1715
|
+
contentType,
|
|
1716
|
+
tags: input.tags ?? {},
|
|
1717
|
+
headers: input.headers ?? {},
|
|
1718
|
+
publishedAt: new Date(now()).toISOString()
|
|
1719
|
+
};
|
|
1720
|
+
messages.push(message);
|
|
1721
|
+
const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
|
|
1722
|
+
const oldest = ofNamespace[0];
|
|
1723
|
+
if (ofNamespace.length > keep && oldest)
|
|
1724
|
+
messages.splice(messages.indexOf(oldest), 1);
|
|
1725
|
+
options.onMessage?.(message);
|
|
1726
|
+
const fault = takeFault(message.namespace);
|
|
1727
|
+
if (fault === "drop") {
|
|
1728
|
+
fanOut(message, "dropped");
|
|
1729
|
+
return message;
|
|
1730
|
+
}
|
|
1731
|
+
if (fault === "reorder") {
|
|
1732
|
+
held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
|
|
1733
|
+
return message;
|
|
1734
|
+
}
|
|
1735
|
+
fanOut(message);
|
|
1736
|
+
if (fault === "duplicate")
|
|
1737
|
+
fanOut(message);
|
|
1738
|
+
releaseHeld(message.namespace);
|
|
1739
|
+
return message;
|
|
1740
|
+
},
|
|
1741
|
+
setEndpoints(namespace, endpoints) {
|
|
1742
|
+
const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
|
|
1743
|
+
own.set(namespace, withIds);
|
|
1744
|
+
return withIds;
|
|
1745
|
+
},
|
|
1746
|
+
endpoints: endpointsFor,
|
|
1747
|
+
messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
|
|
1748
|
+
deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
|
|
1749
|
+
async replay(id2) {
|
|
1750
|
+
const delivery = deliveries.get(id2);
|
|
1751
|
+
if (!delivery)
|
|
1752
|
+
return void 0;
|
|
1753
|
+
const ok = await attempt(delivery);
|
|
1754
|
+
if (ok)
|
|
1755
|
+
delivery.state = "delivered";
|
|
1756
|
+
return delivery;
|
|
1757
|
+
},
|
|
1758
|
+
async flush() {
|
|
1759
|
+
for (const namespace of [...held.keys()])
|
|
1760
|
+
releaseHeld(namespace);
|
|
1761
|
+
const waiting = [...pending.entries()];
|
|
1762
|
+
for (const [id2, timer] of waiting) {
|
|
1763
|
+
if (timer === void 0)
|
|
1764
|
+
continue;
|
|
1765
|
+
cancel(timer);
|
|
1766
|
+
pending.delete(id2);
|
|
1767
|
+
const delivery = deliveries.get(id2);
|
|
1768
|
+
if (!delivery)
|
|
1769
|
+
continue;
|
|
1770
|
+
track(attempt(delivery).then((ok) => {
|
|
1771
|
+
if (ok)
|
|
1772
|
+
delivery.state = "delivered";
|
|
1773
|
+
else
|
|
1774
|
+
schedule(delivery);
|
|
1775
|
+
}));
|
|
1776
|
+
}
|
|
1777
|
+
await hub.idle();
|
|
1778
|
+
},
|
|
1779
|
+
async idle() {
|
|
1780
|
+
while (inFlight.size > 0)
|
|
1781
|
+
await Promise.allSettled([...inFlight]);
|
|
1782
|
+
},
|
|
1783
|
+
fault(namespace, fault) {
|
|
1784
|
+
const queue = faults.get(namespace) ?? [];
|
|
1785
|
+
queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
|
|
1786
|
+
faults.set(namespace, queue);
|
|
1787
|
+
},
|
|
1788
|
+
clear(namespace) {
|
|
1789
|
+
for (const [id2, delivery] of deliveries) {
|
|
1790
|
+
if (namespace !== void 0 && delivery.namespace !== namespace)
|
|
1791
|
+
continue;
|
|
1792
|
+
const timer = pending.get(id2);
|
|
1793
|
+
if (timer !== void 0)
|
|
1794
|
+
cancel(timer);
|
|
1795
|
+
pending.delete(id2);
|
|
1796
|
+
deliveries.delete(id2);
|
|
1797
|
+
payloads.delete(id2);
|
|
1798
|
+
}
|
|
1799
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1800
|
+
if (namespace === void 0 || messages[i]?.namespace === namespace)
|
|
1801
|
+
messages.splice(i, 1);
|
|
1802
|
+
}
|
|
1803
|
+
if (namespace === void 0) {
|
|
1804
|
+
held.clear();
|
|
1805
|
+
faults.clear();
|
|
1806
|
+
own.clear();
|
|
1807
|
+
} else {
|
|
1808
|
+
held.delete(namespace);
|
|
1809
|
+
faults.delete(namespace);
|
|
1810
|
+
own.delete(namespace);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
return hub;
|
|
1815
|
+
};
|
|
1816
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1817
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1818
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1819
|
+
var parseEndpoint = (value) => {
|
|
1820
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1821
|
+
return "each endpoint needs a url";
|
|
1822
|
+
try {
|
|
1823
|
+
new URL(value.url);
|
|
1824
|
+
} catch {
|
|
1825
|
+
return `not a URL: ${value.url}`;
|
|
1826
|
+
}
|
|
1827
|
+
const endpoint = { url: value.url };
|
|
1828
|
+
if (typeof value.id === "string")
|
|
1829
|
+
endpoint.id = value.id;
|
|
1830
|
+
if (typeof value.secret === "string")
|
|
1831
|
+
endpoint.secret = value.secret;
|
|
1832
|
+
if (typeof value.signUrl === "string")
|
|
1833
|
+
endpoint.signUrl = value.signUrl;
|
|
1834
|
+
const events = value.events ?? value.enabledEvents;
|
|
1835
|
+
if (Array.isArray(events))
|
|
1836
|
+
endpoint.events = events.map(String);
|
|
1837
|
+
if (isRecord3(value.tags)) {
|
|
1838
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1839
|
+
}
|
|
1840
|
+
if (typeof value.account === "string")
|
|
1841
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1842
|
+
if (isRecord3(value.headers)) {
|
|
1843
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1844
|
+
}
|
|
1845
|
+
return endpoint;
|
|
1846
|
+
};
|
|
1847
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1848
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1849
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1850
|
+
const type = url.searchParams.get("type");
|
|
1851
|
+
return type === null || d.type === type;
|
|
1852
|
+
})
|
|
1853
|
+
}),
|
|
1854
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1855
|
+
const type = url.searchParams.get("type");
|
|
1856
|
+
return json2(200, {
|
|
1857
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1858
|
+
});
|
|
1859
|
+
},
|
|
1860
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1861
|
+
const replayed = await hub.replay(params.id);
|
|
1862
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1863
|
+
},
|
|
1864
|
+
"POST /webhooks/flush": async () => {
|
|
1865
|
+
await hub.flush();
|
|
1866
|
+
return json2(200, { status: "ok" });
|
|
1867
|
+
},
|
|
1868
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1869
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1870
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1871
|
+
}
|
|
1872
|
+
const fault = { mode: body.mode };
|
|
1873
|
+
if (typeof body.count === "number")
|
|
1874
|
+
fault.count = body.count;
|
|
1875
|
+
hub.fault(namespace, fault);
|
|
1876
|
+
return json2(201, { namespace, ...fault });
|
|
1877
|
+
},
|
|
1878
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1879
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1880
|
+
...rest,
|
|
1881
|
+
secret: secret ? "(set)" : null
|
|
1882
|
+
}))
|
|
1883
|
+
}),
|
|
1884
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1885
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1886
|
+
if (!Array.isArray(list))
|
|
1887
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1888
|
+
const parsed = [];
|
|
1889
|
+
for (const each of list) {
|
|
1890
|
+
const endpoint = parseEndpoint(each);
|
|
1891
|
+
if (typeof endpoint === "string")
|
|
1892
|
+
return adminError2(400, endpoint);
|
|
1893
|
+
parsed.push(endpoint);
|
|
1894
|
+
}
|
|
1895
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1896
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1897
|
+
},
|
|
1898
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1899
|
+
hub.setEndpoints(namespace, []);
|
|
1900
|
+
return json2(200, { status: "ok" });
|
|
1901
|
+
}
|
|
1902
|
+
});
|
|
1903
|
+
var parsePayload = (message) => {
|
|
1904
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1905
|
+
try {
|
|
1906
|
+
return JSON.parse(message.body);
|
|
1907
|
+
} catch {
|
|
1908
|
+
return message.body;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1912
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1913
|
+
}
|
|
1914
|
+
return message.body;
|
|
1915
|
+
};
|
|
1916
|
+
|
|
1917
|
+
// ../core/dist/runtime.js
|
|
1918
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1919
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1920
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1921
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1922
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1923
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1924
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1925
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1926
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1927
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1928
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1929
|
+
if (!previous || previous.length === 0)
|
|
1930
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1931
|
+
const result = new Array(fresh.length);
|
|
1932
|
+
let unchanged = fresh.length === previous.length;
|
|
1933
|
+
let oldIndex = 0;
|
|
1934
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1935
|
+
const row = fresh[index];
|
|
1936
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1937
|
+
oldIndex++;
|
|
1938
|
+
}
|
|
1939
|
+
const old = previous[oldIndex];
|
|
1940
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1941
|
+
if (result[index] !== previous[index])
|
|
1942
|
+
unchanged = false;
|
|
1943
|
+
}
|
|
1944
|
+
return unchanged ? previous : result;
|
|
1945
|
+
};
|
|
1946
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1947
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1948
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1949
|
+
code = "MOCKINGBIRD_DROP";
|
|
1950
|
+
constructor() {
|
|
1951
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1952
|
+
this.name = "TypeError";
|
|
1953
|
+
}
|
|
1954
|
+
};
|
|
1955
|
+
var operationMatcher = (document2) => {
|
|
1956
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1957
|
+
operationId: operation.operationId,
|
|
1958
|
+
method: operation.method.toUpperCase(),
|
|
1959
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1960
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1961
|
+
})).sort((a, b) => a.params - b.params);
|
|
1962
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1963
|
+
};
|
|
1964
|
+
var createRuntime = (options) => {
|
|
1965
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1966
|
+
const clock = options.clock ?? createClock();
|
|
1967
|
+
const rng = createRng(options.seed ?? 0);
|
|
1968
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1969
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1970
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1971
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1972
|
+
const metrics = createMetrics();
|
|
1973
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1974
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1975
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1976
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1977
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1978
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1979
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1980
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1981
|
+
const credentials = createCredentialRegistry();
|
|
1982
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1983
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1984
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1985
|
+
const existing = instances.get(key);
|
|
1986
|
+
if (existing)
|
|
1987
|
+
return existing;
|
|
1988
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1989
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1990
|
+
}
|
|
1991
|
+
const created = options.create({
|
|
1992
|
+
namespace: storageNamespace(key),
|
|
1993
|
+
publicNamespace,
|
|
1994
|
+
sqlite,
|
|
1995
|
+
clock,
|
|
1996
|
+
rng: isolatedRng ?? rng
|
|
1997
|
+
});
|
|
1998
|
+
instances.set(key, created);
|
|
1999
|
+
publicNamespaces.add(publicNamespace);
|
|
2000
|
+
if (isolatedRng)
|
|
2001
|
+
branchRngs.set(key, isolatedRng);
|
|
2002
|
+
return created;
|
|
2003
|
+
};
|
|
2004
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
2005
|
+
const capture = (storage) => {
|
|
2006
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
2007
|
+
const previous = captured.get(storage);
|
|
2008
|
+
const snapshot2 = {
|
|
2009
|
+
namespace: fresh.namespace,
|
|
2010
|
+
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),
|
|
2011
|
+
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)
|
|
2012
|
+
};
|
|
2013
|
+
Object.freeze(snapshot2.records);
|
|
2014
|
+
Object.freeze(snapshot2.sequences);
|
|
2015
|
+
Object.freeze(snapshot2);
|
|
2016
|
+
captured.set(storage, snapshot2);
|
|
2017
|
+
return Object.freeze({
|
|
2018
|
+
snapshot: snapshot2,
|
|
2019
|
+
clock: Object.freeze(clock.state()),
|
|
2020
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
2021
|
+
});
|
|
2022
|
+
};
|
|
2023
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
2024
|
+
let found = timelines.get(name);
|
|
2025
|
+
if (found)
|
|
2026
|
+
return found;
|
|
2027
|
+
instance(name);
|
|
2028
|
+
found = new Timeline({
|
|
2029
|
+
now: clock.now,
|
|
2030
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
2031
|
+
});
|
|
2032
|
+
found.commit(capture(name));
|
|
2033
|
+
timelines.set(name, found);
|
|
2034
|
+
return found;
|
|
2035
|
+
};
|
|
2036
|
+
const physicalBranch = (namespace, branch2) => {
|
|
2037
|
+
if (branch2 === "main")
|
|
2038
|
+
return namespace;
|
|
2039
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
2040
|
+
const existing = branchStorage.get(mapKey);
|
|
2041
|
+
if (existing)
|
|
2042
|
+
return existing;
|
|
2043
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
2044
|
+
branchStorage.set(mapKey, key);
|
|
2045
|
+
return key;
|
|
2046
|
+
};
|
|
2047
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
2048
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
2049
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
2050
|
+
const history = timeline(namespace);
|
|
2051
|
+
if (branch2 === "main") {
|
|
2052
|
+
if (at !== void 0) {
|
|
2053
|
+
const point = history.checkout("main", at);
|
|
2054
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
2055
|
+
captured.set(namespace, point.value.snapshot);
|
|
2056
|
+
rng.setState(point.value.rngState);
|
|
2057
|
+
clock.set(point.value.clock.now);
|
|
2058
|
+
if (point.value.clock.frozen)
|
|
2059
|
+
clock.freeze();
|
|
2060
|
+
else
|
|
2061
|
+
clock.unfreeze();
|
|
2062
|
+
}
|
|
2063
|
+
return namespace;
|
|
2064
|
+
}
|
|
2065
|
+
const storage = physicalBranch(namespace, branch2);
|
|
2066
|
+
if (!history.hasBranch(branch2)) {
|
|
2067
|
+
if (at === void 0)
|
|
2068
|
+
history.commit(capture(namespace));
|
|
2069
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
2070
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2071
|
+
if (point)
|
|
2072
|
+
branchRng.setState(point.value.rngState);
|
|
2073
|
+
instanceFor(storage, namespace, branchRng);
|
|
2074
|
+
if (point)
|
|
2075
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2076
|
+
if (point)
|
|
2077
|
+
captured.set(storage, point.value.snapshot);
|
|
2078
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
2079
|
+
const point = history.checkout(branch2, at);
|
|
2080
|
+
if (!instances.has(storage)) {
|
|
2081
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2082
|
+
branchRng.setState(point.value.rngState);
|
|
2083
|
+
instanceFor(storage, namespace, branchRng);
|
|
2084
|
+
}
|
|
2085
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
2086
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2087
|
+
captured.set(storage, point.value.snapshot);
|
|
2088
|
+
} else {
|
|
2089
|
+
if (!instances.has(storage)) {
|
|
2090
|
+
const point = history.head(branch2);
|
|
2091
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2092
|
+
if (point)
|
|
2093
|
+
branchRng.setState(point.value.rngState);
|
|
2094
|
+
instanceFor(storage, namespace, branchRng);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
return storage;
|
|
2098
|
+
};
|
|
2099
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
2100
|
+
const storage = ensureBranch(namespace, branch2);
|
|
2101
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
2102
|
+
};
|
|
2103
|
+
const branch = (name, branchOptions = {}) => {
|
|
2104
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2105
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
2106
|
+
const head = timeline(namespace).head(name);
|
|
2107
|
+
if (!head)
|
|
2108
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
2109
|
+
return head;
|
|
2110
|
+
};
|
|
2111
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
2112
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2113
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
2114
|
+
const history = timeline(namespace);
|
|
2115
|
+
const point = history.checkout(branchName, checkpointId);
|
|
2116
|
+
const storage = ensureBranch(namespace, branchName);
|
|
2117
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2118
|
+
captured.set(storage, point.value.snapshot);
|
|
2119
|
+
clock.set(point.value.clock.now);
|
|
2120
|
+
if (point.value.clock.frozen)
|
|
2121
|
+
clock.freeze();
|
|
2122
|
+
else
|
|
2123
|
+
clock.unfreeze();
|
|
2124
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
2125
|
+
};
|
|
2126
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
2127
|
+
if (name === "*") {
|
|
2128
|
+
options.webhooks?.clear();
|
|
2129
|
+
for (const each of instances.values())
|
|
2130
|
+
await each.reset();
|
|
2131
|
+
timelines.clear();
|
|
2132
|
+
branchStorage.clear();
|
|
2133
|
+
branchRngs.clear();
|
|
2134
|
+
captured.clear();
|
|
2135
|
+
return;
|
|
2136
|
+
}
|
|
2137
|
+
options.webhooks?.clear(name);
|
|
2138
|
+
const target = instances.get(name);
|
|
2139
|
+
if (target)
|
|
2140
|
+
await target.reset();
|
|
2141
|
+
else
|
|
2142
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
2143
|
+
for (const [mapping, storage] of branchStorage) {
|
|
2144
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
2145
|
+
continue;
|
|
2146
|
+
const branchInstance = instances.get(storage);
|
|
2147
|
+
if (branchInstance)
|
|
2148
|
+
await branchInstance.reset();
|
|
2149
|
+
else
|
|
2150
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
2151
|
+
branchStorage.delete(mapping);
|
|
2152
|
+
branchRngs.delete(storage);
|
|
2153
|
+
captured.delete(storage);
|
|
2154
|
+
}
|
|
2155
|
+
timelines.delete(name);
|
|
2156
|
+
captured.delete(name);
|
|
2157
|
+
};
|
|
2158
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
2159
|
+
return checkpoint(name, "main").value.snapshot;
|
|
2160
|
+
};
|
|
2161
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
2162
|
+
instance(name);
|
|
2163
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
2164
|
+
captured.set(name, from);
|
|
2165
|
+
const history = timelines.get(name);
|
|
2166
|
+
if (history)
|
|
2167
|
+
history.commit(capture(name), { branch: "main" });
|
|
2168
|
+
else
|
|
2169
|
+
timeline(name);
|
|
2170
|
+
};
|
|
2171
|
+
const runtime = {
|
|
2172
|
+
name: options.name,
|
|
2173
|
+
sqlite,
|
|
2174
|
+
clock,
|
|
2175
|
+
faults,
|
|
2176
|
+
metrics,
|
|
2177
|
+
journal,
|
|
2178
|
+
rng,
|
|
2179
|
+
credentials,
|
|
2180
|
+
webhooks: options.webhooks,
|
|
2181
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
2182
|
+
const preset = options.presets?.[name];
|
|
2183
|
+
if (!preset)
|
|
2184
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
2185
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
2186
|
+
namespace,
|
|
2187
|
+
...rule,
|
|
2188
|
+
...overrides,
|
|
2189
|
+
preset: name,
|
|
2190
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
2191
|
+
}));
|
|
2192
|
+
if (preset.webhook && options.webhooks) {
|
|
2193
|
+
options.webhooks.fault(namespace, {
|
|
2194
|
+
...preset.webhook,
|
|
2195
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
2196
|
+
});
|
|
2197
|
+
}
|
|
2198
|
+
return added;
|
|
2199
|
+
},
|
|
2200
|
+
instance,
|
|
2201
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
2202
|
+
reset,
|
|
2203
|
+
snapshot,
|
|
2204
|
+
restore,
|
|
2205
|
+
checkpoint,
|
|
2206
|
+
branch,
|
|
2207
|
+
checkout,
|
|
2208
|
+
timeline,
|
|
2209
|
+
fetch: async (incoming) => {
|
|
2210
|
+
let request = incoming;
|
|
2211
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
2212
|
+
if (prefixed) {
|
|
2213
|
+
const url2 = new URL(request.url);
|
|
2214
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
2215
|
+
const headers = new Headers(request.headers);
|
|
2216
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
2217
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
2218
|
+
}
|
|
2219
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
2220
|
+
request = new Request(url2, {
|
|
2221
|
+
method: request.method,
|
|
2222
|
+
headers,
|
|
2223
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
2224
|
+
signal: request.signal
|
|
2225
|
+
});
|
|
2226
|
+
}
|
|
2227
|
+
let namespace = control.namespaceOf(request);
|
|
2228
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
2229
|
+
const credential = options.credential(request);
|
|
2230
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
2231
|
+
if (mapped !== void 0)
|
|
2232
|
+
namespace = mapped;
|
|
2233
|
+
}
|
|
2234
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
2235
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
2236
|
+
const stamp = (response2) => {
|
|
2237
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
2238
|
+
try {
|
|
2239
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2240
|
+
return response2;
|
|
2241
|
+
} catch {
|
|
2242
|
+
const copy = new Response(response2.body, response2);
|
|
2243
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2244
|
+
return copy;
|
|
2245
|
+
}
|
|
2246
|
+
};
|
|
2247
|
+
const handled = await control.handle(request);
|
|
2248
|
+
if (handled)
|
|
2249
|
+
return stamp(handled);
|
|
2250
|
+
const started = monotonicNow();
|
|
2251
|
+
const url = new URL(request.url);
|
|
2252
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
2253
|
+
const log = (status, faultId, response2) => {
|
|
2254
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
2255
|
+
const entry = {
|
|
2256
|
+
service: options.name,
|
|
2257
|
+
namespace,
|
|
2258
|
+
operationId,
|
|
2259
|
+
method: request.method,
|
|
2260
|
+
path: url.pathname,
|
|
2261
|
+
status,
|
|
2262
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
2263
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
2264
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
2265
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
2266
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
2267
|
+
};
|
|
2268
|
+
metrics.record(entry);
|
|
2269
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2270
|
+
options.onLog?.(entry);
|
|
2271
|
+
};
|
|
2272
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2273
|
+
log(400);
|
|
2274
|
+
return stamp(new Response(JSON.stringify({
|
|
2275
|
+
error: {
|
|
2276
|
+
type: "mockingbird_admin",
|
|
2277
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2278
|
+
}
|
|
2279
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2280
|
+
}
|
|
2281
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2282
|
+
log(400);
|
|
2283
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2284
|
+
}
|
|
2285
|
+
let storage;
|
|
2286
|
+
try {
|
|
2287
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2288
|
+
const point = timeline(namespace).get(at);
|
|
2289
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2290
|
+
let viewRng = branchRngs.get(storage);
|
|
2291
|
+
if (!viewRng) {
|
|
2292
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2293
|
+
instanceFor(storage, namespace, viewRng);
|
|
2294
|
+
}
|
|
2295
|
+
viewRng.setState(point.value.rngState);
|
|
2296
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2297
|
+
captured.set(storage, point.value.snapshot);
|
|
2298
|
+
} else {
|
|
2299
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2300
|
+
}
|
|
2301
|
+
} catch (error) {
|
|
2302
|
+
log(409);
|
|
2303
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
2304
|
+
}
|
|
2305
|
+
const hits = await faults.take({
|
|
2306
|
+
operationId,
|
|
2307
|
+
method: request.method,
|
|
2308
|
+
path: url.pathname,
|
|
2309
|
+
namespace
|
|
2310
|
+
});
|
|
2311
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2312
|
+
if (final?.drop) {
|
|
2313
|
+
log(0, final.id);
|
|
2314
|
+
throw new DroppedConnectionError();
|
|
2315
|
+
}
|
|
2316
|
+
if (final?.response) {
|
|
2317
|
+
log(final.response.status, final.id);
|
|
2318
|
+
return stamp(final.response);
|
|
2319
|
+
}
|
|
2320
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2321
|
+
if (fired.length > 0)
|
|
2322
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2323
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2324
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2325
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2326
|
+
response = mutableResponse(response);
|
|
2327
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2328
|
+
}
|
|
2329
|
+
if (selectedBranch !== "main") {
|
|
2330
|
+
response = mutableResponse(response);
|
|
2331
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2332
|
+
}
|
|
2333
|
+
if (at !== void 0) {
|
|
2334
|
+
response = mutableResponse(response);
|
|
2335
|
+
response.headers.set(AT_HEADER, at);
|
|
2336
|
+
}
|
|
2337
|
+
log(response.status, fired[0]?.id, response);
|
|
2338
|
+
return stamp(response);
|
|
2339
|
+
}
|
|
2340
|
+
};
|
|
2341
|
+
const control = createControlPlane({
|
|
2342
|
+
name: options.name,
|
|
2343
|
+
startedAt: wallNow(),
|
|
2344
|
+
wallNow,
|
|
2345
|
+
clock,
|
|
2346
|
+
faults,
|
|
2347
|
+
metrics,
|
|
2348
|
+
journal,
|
|
2349
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2350
|
+
namespaces: runtime.namespaces,
|
|
2351
|
+
reset,
|
|
2352
|
+
timeTravel: {
|
|
2353
|
+
checkpoint: (name, branchName) => {
|
|
2354
|
+
const point = checkpoint(name, branchName);
|
|
2355
|
+
return {
|
|
2356
|
+
id: point.id,
|
|
2357
|
+
branch: point.branch,
|
|
2358
|
+
parent: point.parent,
|
|
2359
|
+
at: point.at,
|
|
2360
|
+
records: point.value.snapshot.records.length
|
|
2361
|
+
};
|
|
2362
|
+
},
|
|
2363
|
+
branch: (branchName, branchOptions) => {
|
|
2364
|
+
const point = branch(branchName, branchOptions);
|
|
2365
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2366
|
+
},
|
|
2367
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2368
|
+
retain: (name, checkpointId) => {
|
|
2369
|
+
timeline(name).retain(checkpointId);
|
|
2370
|
+
},
|
|
2371
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2372
|
+
inspect: (name) => {
|
|
2373
|
+
const history = timeline(name);
|
|
2374
|
+
return {
|
|
2375
|
+
branches: history.branches(),
|
|
2376
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2377
|
+
id,
|
|
2378
|
+
branch: branchName,
|
|
2379
|
+
parent,
|
|
2380
|
+
at
|
|
2381
|
+
}))
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
},
|
|
2385
|
+
describe: options.describe ?? (() => ({})),
|
|
2386
|
+
...options.presets ? {
|
|
2387
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2388
|
+
} : {},
|
|
2389
|
+
routes: {
|
|
2390
|
+
...credentialRoutes(credentials),
|
|
2391
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2392
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2393
|
+
...options.admin?.(runtime) ?? {}
|
|
2394
|
+
},
|
|
2395
|
+
adminKey: options.adminKey
|
|
2396
|
+
});
|
|
2397
|
+
return runtime;
|
|
2398
|
+
};
|
|
2399
|
+
var mutableResponse = (response) => {
|
|
2400
|
+
try {
|
|
2401
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2402
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2403
|
+
return response;
|
|
2404
|
+
} catch {
|
|
2405
|
+
return new Response(response.body, response);
|
|
2406
|
+
}
|
|
2407
|
+
};
|
|
2408
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2409
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2410
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2411
|
+
var credentialRoutes = (registry) => ({
|
|
2412
|
+
"GET /credentials": () => adminJson(200, {
|
|
2413
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2414
|
+
credential: maskCredential(credential),
|
|
2415
|
+
namespace
|
|
2416
|
+
}))
|
|
2417
|
+
}),
|
|
2418
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2419
|
+
const pairs = [];
|
|
2420
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2421
|
+
if (Array.isArray(list)) {
|
|
2422
|
+
for (const each of list) {
|
|
2423
|
+
if (typeof each === "string")
|
|
2424
|
+
pairs.push([each, namespace]);
|
|
2425
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2426
|
+
pairs.push([
|
|
2427
|
+
each.credential,
|
|
2428
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2429
|
+
]);
|
|
2430
|
+
} else
|
|
2431
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2432
|
+
}
|
|
2433
|
+
} else if (isObject(list)) {
|
|
2434
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2435
|
+
if (typeof target !== "string")
|
|
2436
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2437
|
+
pairs.push([credential, target]);
|
|
2438
|
+
}
|
|
2439
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2440
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2441
|
+
} else {
|
|
2442
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2443
|
+
}
|
|
2444
|
+
for (const [credential, target] of pairs) {
|
|
2445
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2446
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2447
|
+
registry.set(credential, target);
|
|
2448
|
+
}
|
|
2449
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2450
|
+
},
|
|
2451
|
+
"DELETE /credentials": ({ url }) => {
|
|
2452
|
+
const credential = url.searchParams.get("credential");
|
|
2453
|
+
if (credential === null)
|
|
2454
|
+
registry.clear();
|
|
2455
|
+
else
|
|
2456
|
+
registry.remove(credential);
|
|
2457
|
+
return adminJson(200, { status: "ok" });
|
|
2458
|
+
}
|
|
2459
|
+
});
|
|
2460
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2461
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2462
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2463
|
+
}),
|
|
2464
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2465
|
+
const name = params.name;
|
|
2466
|
+
if (!presets[name])
|
|
2467
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2468
|
+
const overrides = isObject(body) ? body : {};
|
|
2469
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2470
|
+
}
|
|
2471
|
+
});
|
|
2472
|
+
|
|
2473
|
+
// ../core/dist/validation.js
|
|
2474
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2475
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2476
|
+
if (!requestBody)
|
|
2477
|
+
return [];
|
|
2478
|
+
const resolved = deref(context.document, requestBody);
|
|
2479
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2480
|
+
if (!schema)
|
|
2481
|
+
return [];
|
|
2482
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2483
|
+
if (context.body.kind === "invalid") {
|
|
2484
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2485
|
+
}
|
|
2486
|
+
if (value === void 0) {
|
|
2487
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2488
|
+
}
|
|
2489
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2490
|
+
};
|
|
2491
|
+
var issuesByField = (issues) => {
|
|
2492
|
+
const out = {};
|
|
2493
|
+
for (const issue of issues) {
|
|
2494
|
+
const missing = /^missing required property (.+)$/.exec(issue.message);
|
|
2495
|
+
const field = missing ? [issue.path, missing[1]].filter(Boolean).join(".") : issue.path || "body";
|
|
2496
|
+
const message = missing ? `The ${field} field is required.` : `The ${field} field ${issue.message}.`;
|
|
2497
|
+
out[field] = [...out[field] ?? [], message];
|
|
2498
|
+
}
|
|
2499
|
+
return out;
|
|
2500
|
+
};
|
|
2501
|
+
|
|
2502
|
+
// src/generated/openapi.ts
|
|
2503
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"RxVortex (Strive) pharmacy API (Mockingbird subset)","description":"Stateful mock subset of the RxVortex / Strive compounding-pharmacy API: client-credentials\\ntoken, order submit, status, cancel, lookup by sender order id (recovery), and the preset\\ncatalog. Hand-authored from the consumer's adapters (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from the wire shapes our consumer reads and writes (rxvortex-auth.service.ts, rxvortex-fulfillment.adapter.ts, rxvortex-live.client.ts)."}},"servers":[{"url":"https://sandbox.rxvortex.com"}],"security":[{"bearerAuth":[]}],"paths":{"/api/v1/generate-access-token":{"post":{"operationId":"GenerateAccessToken","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["client_id","client_secret"],"properties":{"client_id":{"type":"string","minLength":1,"maxLength":64},"client_secret":{"type":"string","minLength":1,"maxLength":64}}}}}},"responses":{"200":{"description":"Access token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TokenResponse"}}}},"401":{"description":"Bad credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"422":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}}}}},"/api/v1/orders":{"post":{"operationId":"CreateOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderBody"}}}},"responses":{"200":{"description":"Order accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderResponse"}}}},"401":{"description":"Unauthenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Duplicate sender_order_id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"422":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}}}}},"/api/v1/orders/{orderId}":{"parameters":[{"name":"orderId","in":"path","required":true,"description":"The vendor order tracking id, or the sender order id (our payment id).","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"order","missing":"RXV-00000000-MISSING"}}}],"get":{"operationId":"GetOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Order status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderStatus"}}}},"401":{"description":"Unauthenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}},"delete":{"operationId":"CancelOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Cancelled","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelResponse"}}}},"401":{"description":"Unauthenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Not cancellable in its current status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/api/v1/preset-catalog-items":{"get":{"operationId":"ListPresetCatalogItems","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Preset catalog","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/CatalogItem"}}}}}}},"401":{"description":"Unauthenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"schemas":{"TokenResponse":{"type":"object","required":["access_token","token_type","expires_in"],"properties":{"access_token":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"token_type":{"type":"string","enum":["Bearer"]},"expires_in":{"type":"integer"}}},"Address":{"type":"object","required":["line1","city","state","postal_code","country"],"properties":{"line1":{"type":"string","minLength":1,"maxLength":80},"line2":{"type":"string","maxLength":80},"city":{"type":"string","minLength":1,"maxLength":40},"state":{"type":"string","pattern":"^[A-Z]{2}$"},"postal_code":{"type":"string","pattern":"^[0-9]{5}(-[0-9]{4})?$"},"country":{"type":"string","enum":["US"]}}},"Patient":{"type":"object","required":["sender_patient_id","first_name","last_name","dob","gender","email","phone","address"],"properties":{"sender_patient_id":{"type":"string","minLength":1,"maxLength":64},"first_name":{"type":"string","minLength":1,"maxLength":40},"last_name":{"type":"string","minLength":1,"maxLength":40},"dob":{"type":"string","pattern":"^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$"},"gender":{"type":"string","enum":["male","female"]},"email":{"type":"string","format":"email","maxLength":120},"phone":{"type":"string","pattern":"^[0-9]{3}-[0-9]{3}-[0-9]{4}$"},"address":{"$ref":"#/components/schemas/Address"}}},"Prescriber":{"type":"object","required":["first_name","last_name","npi"],"properties":{"first_name":{"type":"string","minLength":1,"maxLength":40},"last_name":{"type":"string","minLength":1,"maxLength":40},"npi":{"type":"string","pattern":"^[0-9]{10}$"},"dea_number":{"type":"string","maxLength":20},"license_number":{"type":"string","maxLength":20},"license_state":{"type":"string","maxLength":2},"phone":{"type":"string","maxLength":20},"address":{"$ref":"#/components/schemas/Address"}}},"MedicationRequest":{"type":"object","required":["type","preset_catalog_id","sender_med_request_id","medication_name","quantity","quantity_units","days_supply_duration","refills","instructions"],"properties":{"type":{"type":"string","enum":["new"]},"preset_catalog_id":{"type":"string","x-mockingbird-resource-ref":{"type":"catalog_item","missing":"00000000-0000-4000-8000-000000000000"}},"sender_med_request_id":{"type":"string","minLength":1,"maxLength":64},"medication_name":{"type":"string","minLength":1,"maxLength":120},"medication_strength":{"type":"string","maxLength":60},"medication_form":{"type":"string","maxLength":40},"quantity":{"type":"number","exclusiveMinimum":0,"maximum":1000},"quantity_units":{"type":"string","enum":["mL","grams","each"]},"days_supply_duration":{"type":"integer","minimum":1,"maximum":365},"refills":{"type":"integer","minimum":0,"maximum":12},"instructions":{"type":"string","minLength":1,"maxLength":500},"note":{"type":"string","maxLength":1000},"authored_on_datetime":{"type":"string","maxLength":40},"clinical_difference":{"type":"string","maxLength":1000},"schedule_code":{"type":"string","enum":["2","3","4","5"]}}},"ClinicalList":{"type":"object","properties":{"has_known_allergies":{"type":"boolean"},"has_known_diseases":{"type":"boolean"},"has_known_medications":{"type":"boolean"},"entries":{"type":"array","maxItems":5,"items":{"type":"object","required":["description"],"properties":{"description":{"type":"string","maxLength":200}}}}}},"CreateOrderBody":{"type":"object","required":["patient","prescriber","order","medication_requests"],"properties":{"patient":{"$ref":"#/components/schemas/Patient"},"prescriber":{"$ref":"#/components/schemas/Prescriber"},"order":{"type":"object","required":["bill_to","ship_to","sender_order_id"],"properties":{"bill_to":{"type":"string","enum":["practice","patient"]},"ship_to":{"type":"string","enum":["patient","practice"]},"sender_order_id":{"type":"string","minLength":1,"maxLength":64}}},"medication_requests":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/MedicationRequest"}},"clinical":{"type":"object","properties":{"allergies":{"$ref":"#/components/schemas/ClinicalList"},"diseases":{"$ref":"#/components/schemas/ClinicalList"},"medications":{"$ref":"#/components/schemas/ClinicalList"}}},"shipment":{"type":"object","properties":{"recipient_first_name":{"type":"string","maxLength":40},"recipient_last_name":{"type":"string","maxLength":40},"recipient_email":{"type":"string","maxLength":80},"recipient_phone":{"type":"string","maxLength":20},"address":{"$ref":"#/components/schemas/Address"}}}}},"CreateOrderResponse":{"type":"object","required":["success","message","order_tracking_id","sender_order_id","status"],"properties":{"success":{"type":"boolean"},"message":{"type":"string"},"order_tracking_id":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"sender_order_id":{"type":"string"},"status":{"type":"string"}}},"OrderStatus":{"type":"object","required":["order_tracking_id","tracking_id","orderReferenceID","sender_order_id","rxstatus","orderstatus","shipping_status","cancellable","created_at","updated_at"],"properties":{"order_tracking_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"tracking_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"orderReferenceID":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"sender_order_id":{"type":"string"},"rxstatus":{"type":"string"},"orderstatus":{"type":"string"},"shipping_status":{"type":"string"},"delivered_date":{"type":["string","null"]},"trackingnumber":{"type":["string","null"]},"shippingservice":{"type":["string","null"]},"shippingcarrier":{"type":["string","null"]},"shipmenttrackingurl":{"type":["string","null"]},"cancellable":{"type":"boolean"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"CancelResponse":{"type":"object","required":["success","message","order_tracking_id","rxstatus"],"properties":{"success":{"type":"boolean"},"message":{"type":"string"},"order_tracking_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"rxstatus":{"type":"string"}}},"CatalogItem":{"type":"object","required":["catalog_id","medication_name","status"],"properties":{"catalog_id":{"type":"string","x-mockingbird-resource":{"type":"catalog_item","identity":true}},"medication_name":{"type":"string"},"medication_strength":{"type":["string","null"]},"package_size":{"type":["string","null"]},"quantity":{"type":["number","null"]},"quantity_units":{"type":["string","null"]},"medication_form":{"type":["string","null"]},"route":{"type":["string","null"]},"states":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["active","inactive"]}}},"ErrorBody":{"type":"object","required":["message"],"properties":{"message":{"type":"string"},"success":{"type":"boolean"}}},"ValidationError":{"type":"object","required":["message","errors"],"properties":{"message":{"type":"string"},"errors":{"oneOf":[{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}},{"type":"array","items":{"type":"object"}}]}}}}}}`);
|
|
2504
|
+
var operationIds = ["GenerateAccessToken", "CreateOrder", "GetOrder", "CancelOrder", "ListPresetCatalogItems"];
|
|
2505
|
+
var supportedOperationIds = ["GenerateAccessToken", "CreateOrder", "GetOrder", "CancelOrder", "ListPresetCatalogItems"];
|
|
2506
|
+
|
|
2507
|
+
// src/catalog.ts
|
|
2508
|
+
var CUSTOM_CREAM_ANCHOR_PRESET_ID = "e404ad76-0f82-4b04-8f25-841650e2e819";
|
|
2509
|
+
var ALL_STATES = [
|
|
2510
|
+
"AZ",
|
|
2511
|
+
"CA",
|
|
2512
|
+
"CO",
|
|
2513
|
+
"FL",
|
|
2514
|
+
"GA",
|
|
2515
|
+
"IL",
|
|
2516
|
+
"MA",
|
|
2517
|
+
"NC",
|
|
2518
|
+
"NJ",
|
|
2519
|
+
"NV",
|
|
2520
|
+
"NY",
|
|
2521
|
+
"OH",
|
|
2522
|
+
"PA",
|
|
2523
|
+
"TX",
|
|
2524
|
+
"UT",
|
|
2525
|
+
"VA",
|
|
2526
|
+
"WA"
|
|
2527
|
+
];
|
|
2528
|
+
var DEFAULT_CATALOG = [
|
|
2529
|
+
{
|
|
2530
|
+
catalog_id: CUSTOM_CREAM_ANCHOR_PRESET_ID,
|
|
2531
|
+
medication_name: "CUSTOM",
|
|
2532
|
+
medication_strength: null,
|
|
2533
|
+
package_size: "30 grams",
|
|
2534
|
+
quantity: 30,
|
|
2535
|
+
quantity_units: "grams",
|
|
2536
|
+
medication_form: "Cream",
|
|
2537
|
+
route: "Topical",
|
|
2538
|
+
states: ALL_STATES,
|
|
2539
|
+
status: "active"
|
|
2540
|
+
},
|
|
2541
|
+
{
|
|
2542
|
+
catalog_id: "1c0b7f7e-3c5f-4d57-9d0a-0d8f1d3a2b10",
|
|
2543
|
+
medication_name: "Testosterone Cypionate",
|
|
2544
|
+
medication_strength: "200 mg/mL",
|
|
2545
|
+
package_size: "10 mL vial",
|
|
2546
|
+
quantity: 10,
|
|
2547
|
+
quantity_units: "mL",
|
|
2548
|
+
medication_form: "Injectable",
|
|
2549
|
+
route: "Intramuscular",
|
|
2550
|
+
states: ALL_STATES,
|
|
2551
|
+
status: "active"
|
|
2552
|
+
},
|
|
2553
|
+
{
|
|
2554
|
+
catalog_id: "5d2e9a41-8b7c-4f0e-a1d3-6c5b4a392817",
|
|
2555
|
+
medication_name: "Sermorelin Acetate",
|
|
2556
|
+
medication_strength: "9 mg",
|
|
2557
|
+
package_size: "1 vial",
|
|
2558
|
+
quantity: 1,
|
|
2559
|
+
quantity_units: "each",
|
|
2560
|
+
medication_form: "Lyophilized powder",
|
|
2561
|
+
route: "Subcutaneous",
|
|
2562
|
+
states: ALL_STATES,
|
|
2563
|
+
status: "active"
|
|
2564
|
+
},
|
|
2565
|
+
{
|
|
2566
|
+
catalog_id: "9f3a6b2c-1d4e-4a5b-8c7d-0e1f2a3b4c5d",
|
|
2567
|
+
medication_name: "Enclomiphene Citrate",
|
|
2568
|
+
medication_strength: "25 mg",
|
|
2569
|
+
package_size: "30 capsules",
|
|
2570
|
+
quantity: 30,
|
|
2571
|
+
quantity_units: "each",
|
|
2572
|
+
medication_form: "Capsule",
|
|
2573
|
+
route: "Oral",
|
|
2574
|
+
states: ALL_STATES,
|
|
2575
|
+
status: "active"
|
|
2576
|
+
},
|
|
2577
|
+
{
|
|
2578
|
+
catalog_id: "0a1b2c3d-4e5f-4a6b-9c8d-7e6f5a4b3c2d",
|
|
2579
|
+
medication_name: "Anastrozole",
|
|
2580
|
+
medication_strength: "0.5 mg",
|
|
2581
|
+
package_size: "30 capsules",
|
|
2582
|
+
quantity: 30,
|
|
2583
|
+
quantity_units: "each",
|
|
2584
|
+
medication_form: "Capsule",
|
|
2585
|
+
route: "Oral",
|
|
2586
|
+
states: ALL_STATES,
|
|
2587
|
+
status: "inactive"
|
|
2588
|
+
}
|
|
2589
|
+
];
|
|
2590
|
+
|
|
2591
|
+
// src/state.ts
|
|
2592
|
+
var DEFAULT_SETTINGS = {
|
|
2593
|
+
tokenTtlSeconds: 86400,
|
|
2594
|
+
staticTokens: [],
|
|
2595
|
+
clients: [],
|
|
2596
|
+
autoAdvance: null
|
|
2597
|
+
};
|
|
2598
|
+
var RxVortexState = class {
|
|
2599
|
+
constructor(sqlite, namespace, seed) {
|
|
2600
|
+
this.seed = seed;
|
|
2601
|
+
this.orders = new Collection(sqlite, namespace, "orders");
|
|
2602
|
+
this.catalog = new Collection(sqlite, namespace, "catalog");
|
|
2603
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2604
|
+
this.ids = new IdSequence(sqlite, namespace, "rxvortex");
|
|
2605
|
+
this.ensureSeeded();
|
|
2606
|
+
}
|
|
2607
|
+
seed;
|
|
2608
|
+
orders;
|
|
2609
|
+
catalog;
|
|
2610
|
+
settings;
|
|
2611
|
+
ids;
|
|
2612
|
+
/** Re-apply the catalog and settings after a reset. */
|
|
2613
|
+
ensureSeeded() {
|
|
2614
|
+
if (this.catalog.count() === 0) {
|
|
2615
|
+
for (const item of this.seed.catalog.length > 0 ? this.seed.catalog : DEFAULT_CATALOG) {
|
|
2616
|
+
this.catalog.insert(item.catalog_id, item);
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
if (!this.settings.has("settings")) {
|
|
2620
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
current() {
|
|
2624
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2625
|
+
}
|
|
2626
|
+
update(patch) {
|
|
2627
|
+
const next = { ...this.current(), ...patch };
|
|
2628
|
+
this.settings.insert("settings", next);
|
|
2629
|
+
return next;
|
|
2630
|
+
}
|
|
2631
|
+
/** By vendor tracking id first, then by our sender order id (the recovery lookup). */
|
|
2632
|
+
findOrder(id) {
|
|
2633
|
+
return this.orders.get(id) ?? this.orders.list({ where: (order) => order.sender_order_id === id }).at(0)?.value;
|
|
2634
|
+
}
|
|
2635
|
+
nextTrackingId() {
|
|
2636
|
+
return this.ids.next("RXV-", 12).toUpperCase();
|
|
2637
|
+
}
|
|
2638
|
+
};
|
|
2639
|
+
|
|
2640
|
+
// src/statuses.ts
|
|
2641
|
+
var TRIPLES = {
|
|
2642
|
+
created: { rxstatus: "Created", orderstatus: "Created", shipping_status: "Pending" },
|
|
2643
|
+
fill: { rxstatus: "Fill", orderstatus: "Processing", shipping_status: "Pending" },
|
|
2644
|
+
"pv1 complete": {
|
|
2645
|
+
rxstatus: "PV1 Complete",
|
|
2646
|
+
orderstatus: "Processing",
|
|
2647
|
+
shipping_status: "Pending"
|
|
2648
|
+
},
|
|
2649
|
+
compound: { rxstatus: "Compound", orderstatus: "Processing", shipping_status: "Pending" },
|
|
2650
|
+
"out of stock": { rxstatus: "Out of Stock", orderstatus: "On Hold", shipping_status: "Pending" },
|
|
2651
|
+
"on hold": { rxstatus: "On Hold", orderstatus: "On Hold", shipping_status: "Pending" },
|
|
2652
|
+
shipping: {
|
|
2653
|
+
rxstatus: "Fulfillment Complete",
|
|
2654
|
+
orderstatus: "Shipping",
|
|
2655
|
+
shipping_status: "In Transit"
|
|
2656
|
+
},
|
|
2657
|
+
shipped: {
|
|
2658
|
+
rxstatus: "Fulfillment Complete",
|
|
2659
|
+
orderstatus: "Shipping",
|
|
2660
|
+
shipping_status: "In Transit"
|
|
2661
|
+
},
|
|
2662
|
+
delivered: {
|
|
2663
|
+
rxstatus: "Fulfillment Complete",
|
|
2664
|
+
orderstatus: "Completed Orders",
|
|
2665
|
+
shipping_status: "Delivered"
|
|
2666
|
+
},
|
|
2667
|
+
cancelled: { rxstatus: "Cancelled", orderstatus: "Cancelled", shipping_status: "Cancelled" },
|
|
2668
|
+
canceled: { rxstatus: "Cancelled", orderstatus: "Cancelled", shipping_status: "Cancelled" },
|
|
2669
|
+
error: { rxstatus: "Error", orderstatus: "Error", shipping_status: "Pending" },
|
|
2670
|
+
rejected: { rxstatus: "Rejected", orderstatus: "Rejected", shipping_status: "Pending" }
|
|
2671
|
+
};
|
|
2672
|
+
var triple = (to) => TRIPLES[to.trim().toLowerCase()] ?? { rxstatus: to, orderstatus: to, shipping_status: "Pending" };
|
|
2673
|
+
var isShippedOrLater = (to) => ["shipping", "shipped", "delivered"].includes(to.trim().toLowerCase());
|
|
2674
|
+
var isTerminal = (status) => /cancel|deliver|reject|error/i.test(`${status.rxstatus} ${status.shipping_status}`);
|
|
2675
|
+
|
|
2676
|
+
// src/runtime.ts
|
|
2677
|
+
var WEBHOOK_SECRET_HEADER = "x-rxvortex-webhook-secret";
|
|
2678
|
+
var RXVORTEX_PRESETS = {
|
|
2679
|
+
duplicate_sender_order_id: {
|
|
2680
|
+
description: "Submit answers 409: an order with this sender_order_id already exists (it does)",
|
|
2681
|
+
rules: [{ operationId: "CreateOrder", effect: "duplicate_sender_order_id" }]
|
|
2682
|
+
},
|
|
2683
|
+
created_but_500: {
|
|
2684
|
+
description: "Submit creates the order, then answers 500; recovery by paymentId finds it",
|
|
2685
|
+
rules: [{ operationId: "CreateOrder", effect: "created_but_500" }]
|
|
2686
|
+
},
|
|
2687
|
+
numeric_tracking_id: {
|
|
2688
|
+
description: "Submit answers order_tracking_id as a number (our client treats it as an error)",
|
|
2689
|
+
rules: [{ operationId: "CreateOrder", effect: "numeric_tracking_id" }]
|
|
2690
|
+
},
|
|
2691
|
+
token_expired: {
|
|
2692
|
+
description: "Every authenticated call answers 401 Token has expired, before 24 h",
|
|
2693
|
+
rules: [
|
|
2694
|
+
{ pathPrefix: "/api/v1/orders", effect: "token_expired" },
|
|
2695
|
+
{ pathPrefix: "/api/v1/preset-catalog-items", effect: "token_expired" }
|
|
2696
|
+
]
|
|
2697
|
+
},
|
|
2698
|
+
stale_error_with_delivered_date: {
|
|
2699
|
+
description: "Status answers an Error status next to a non-empty delivered_date",
|
|
2700
|
+
rules: [{ operationId: "GetOrder", effect: "stale_error_with_delivered_date" }]
|
|
2701
|
+
},
|
|
2702
|
+
validation_errors_array: {
|
|
2703
|
+
description: "Submit answers 422 with errors as a non-empty array",
|
|
2704
|
+
rules: [{ operationId: "CreateOrder", effect: "validation_errors_array" }]
|
|
2705
|
+
},
|
|
2706
|
+
validation_errors_object: {
|
|
2707
|
+
description: "Submit answers 422 with errors as an object keyed by field",
|
|
2708
|
+
rules: [{ operationId: "CreateOrder", effect: "validation_errors_object" }]
|
|
2709
|
+
},
|
|
2710
|
+
validation_errors_empty: {
|
|
2711
|
+
description: "Submit answers 422 with an empty errors array",
|
|
2712
|
+
rules: [{ operationId: "CreateOrder", effect: "validation_errors_empty" }]
|
|
2713
|
+
},
|
|
2714
|
+
server_error: {
|
|
2715
|
+
description: "Every call answers 500 Server Error",
|
|
2716
|
+
rules: [{ status: 500, body: { message: "Server Error" } }]
|
|
2717
|
+
},
|
|
2718
|
+
webhook_duplicate: {
|
|
2719
|
+
description: "The next status webhook is delivered twice",
|
|
2720
|
+
webhook: { mode: "duplicate" }
|
|
2721
|
+
},
|
|
2722
|
+
webhook_reorder: {
|
|
2723
|
+
description: "The next two status webhooks arrive swapped",
|
|
2724
|
+
webhook: { mode: "reorder" }
|
|
2725
|
+
},
|
|
2726
|
+
webhook_drop: {
|
|
2727
|
+
description: "The next status webhook is never delivered",
|
|
2728
|
+
webhook: { mode: "drop" }
|
|
2729
|
+
}
|
|
2730
|
+
};
|
|
2731
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2732
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2733
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2734
|
+
var parseAutoAdvance = (value) => {
|
|
2735
|
+
if (value === null) return null;
|
|
2736
|
+
if (!isRecord4(value)) return "autoAdvance must be {afterMs, path} or null";
|
|
2737
|
+
if (typeof value.afterMs !== "number" || value.afterMs < 0)
|
|
2738
|
+
return "autoAdvance.afterMs must be ms";
|
|
2739
|
+
if (!Array.isArray(value.path) || value.path.some((s) => typeof s !== "string")) {
|
|
2740
|
+
return "autoAdvance.path must be a list of vendor statuses";
|
|
2741
|
+
}
|
|
2742
|
+
return { afterMs: value.afterMs, path: value.path };
|
|
2743
|
+
};
|
|
2744
|
+
var adminRoutes = (runtime) => ({
|
|
2745
|
+
"GET /orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).orders() }),
|
|
2746
|
+
"POST /orders/:id/transition": ({ params, body, namespace }) => {
|
|
2747
|
+
if (!isRecord4(body) || typeof body.to !== "string") {
|
|
2748
|
+
return adminError3(
|
|
2749
|
+
400,
|
|
2750
|
+
'expected {"to": "<vendor status>", "trackingnumber"?, "shippingcarrier"?}'
|
|
2751
|
+
);
|
|
2752
|
+
}
|
|
2753
|
+
const optional = (key) => typeof body[key] === "string" ? { [key]: body[key] } : {};
|
|
2754
|
+
const order = runtime.instance(namespace).transition(params.id, {
|
|
2755
|
+
to: body.to,
|
|
2756
|
+
...optional("trackingnumber"),
|
|
2757
|
+
...optional("shippingcarrier"),
|
|
2758
|
+
...optional("shippingservice"),
|
|
2759
|
+
...optional("delivered_date")
|
|
2760
|
+
});
|
|
2761
|
+
return order ? json3(200, order) : adminError3(404, `no order ${params.id}`);
|
|
2762
|
+
},
|
|
2763
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2764
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2765
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2766
|
+
const patch = {};
|
|
2767
|
+
if (body.tokenTtlSeconds !== void 0) {
|
|
2768
|
+
if (typeof body.tokenTtlSeconds !== "number")
|
|
2769
|
+
return adminError3(400, "tokenTtlSeconds: number");
|
|
2770
|
+
patch.tokenTtlSeconds = body.tokenTtlSeconds;
|
|
2771
|
+
}
|
|
2772
|
+
if (body.staticTokens !== void 0) {
|
|
2773
|
+
if (!Array.isArray(body.staticTokens)) return adminError3(400, "staticTokens: string[]");
|
|
2774
|
+
patch.staticTokens = body.staticTokens.map(String);
|
|
2775
|
+
}
|
|
2776
|
+
if (body.clients !== void 0) {
|
|
2777
|
+
if (!Array.isArray(body.clients))
|
|
2778
|
+
return adminError3(400, "clients: [{client_id, client_secret}]");
|
|
2779
|
+
patch.clients = body.clients.filter(isRecord4).map((c) => ({
|
|
2780
|
+
client_id: String(c.client_id),
|
|
2781
|
+
client_secret: String(c.client_secret)
|
|
2782
|
+
}));
|
|
2783
|
+
}
|
|
2784
|
+
if (body.autoAdvance !== void 0) {
|
|
2785
|
+
const parsed = parseAutoAdvance(body.autoAdvance);
|
|
2786
|
+
if (typeof parsed === "string") return adminError3(400, parsed);
|
|
2787
|
+
patch.autoAdvance = parsed;
|
|
2788
|
+
}
|
|
2789
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2790
|
+
},
|
|
2791
|
+
"POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
|
|
2792
|
+
});
|
|
2793
|
+
var createRuntime2 = (options = {}) => {
|
|
2794
|
+
const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
|
|
2795
|
+
const hub = createWebhookHub({
|
|
2796
|
+
signer: signers.header(WEBHOOK_SECRET_HEADER),
|
|
2797
|
+
...retryDelaysMs ? { retryDelaysMs } : {},
|
|
2798
|
+
...send ? { fetch: send } : {},
|
|
2799
|
+
endpoints: options.webhooks ? [endpoint] : []
|
|
2800
|
+
});
|
|
2801
|
+
const runtime = createRuntime({
|
|
2802
|
+
name: RXVORTEX_NAMESPACE,
|
|
2803
|
+
document,
|
|
2804
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2805
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2806
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2807
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2808
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2809
|
+
credential: tokenCredential,
|
|
2810
|
+
presets: RXVORTEX_PRESETS,
|
|
2811
|
+
webhooks: hub,
|
|
2812
|
+
create: ({ sqlite, namespace, publicNamespace, clock }) => new RxVortexAPI({
|
|
2813
|
+
sqlite,
|
|
2814
|
+
namespace,
|
|
2815
|
+
now: clock.now,
|
|
2816
|
+
...options.catalog ? { catalog: options.catalog } : {},
|
|
2817
|
+
...options.settings ? { settings: options.settings } : {},
|
|
2818
|
+
onWebhook: (event) => hub.publish({
|
|
2819
|
+
namespace: publicNamespace,
|
|
2820
|
+
type: event.event,
|
|
2821
|
+
body: event,
|
|
2822
|
+
id: `${event.order_tracking_id}:${event.updated_at}:${event.rxstatus}`
|
|
2823
|
+
})
|
|
2824
|
+
}),
|
|
2825
|
+
describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
|
|
2826
|
+
admin: adminRoutes
|
|
2827
|
+
});
|
|
2828
|
+
let timer;
|
|
2829
|
+
if (options.tickMs !== void 0 && options.tickMs > 0) {
|
|
2830
|
+
timer = setInterval(() => {
|
|
2831
|
+
for (const name of runtime.namespaces()) runtime.instance(name).tick();
|
|
2832
|
+
}, options.tickMs);
|
|
2833
|
+
timer.unref?.();
|
|
2834
|
+
}
|
|
2835
|
+
return Object.assign(runtime, {
|
|
2836
|
+
webhooks: hub,
|
|
2837
|
+
stop: () => {
|
|
2838
|
+
if (timer !== void 0) clearInterval(timer);
|
|
2839
|
+
}
|
|
2840
|
+
});
|
|
2841
|
+
};
|
|
2842
|
+
|
|
2843
|
+
// src/index.ts
|
|
2844
|
+
var RXVORTEX_NAMESPACE = "rxvortex";
|
|
2845
|
+
var TOKEN_PREFIX = "rxv_";
|
|
2846
|
+
var base64url = (value) => toBase64(new TextEncoder().encode(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2847
|
+
var fromBase64url = (value) => {
|
|
2848
|
+
try {
|
|
2849
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(
|
|
2850
|
+
fromBase64(value.replace(/-/g, "+").replace(/_/g, "/"))
|
|
2851
|
+
);
|
|
2852
|
+
} catch {
|
|
2853
|
+
return void 0;
|
|
2854
|
+
}
|
|
2855
|
+
};
|
|
2856
|
+
var tokenCredential = (request) => {
|
|
2857
|
+
const token = bearerToken(request);
|
|
2858
|
+
if (!token) return void 0;
|
|
2859
|
+
if (!token.startsWith(TOKEN_PREFIX)) return token;
|
|
2860
|
+
const [encoded] = token.slice(TOKEN_PREFIX.length).split(".");
|
|
2861
|
+
return encoded ? fromBase64url(encoded) : void 0;
|
|
2862
|
+
};
|
|
2863
|
+
var issueToken = (clientId, issuedAtSeconds) => {
|
|
2864
|
+
const signature = opaqueToken(`rxvortex:${clientId}:${issuedAtSeconds}`, 32);
|
|
2865
|
+
return `${TOKEN_PREFIX}${base64url(clientId)}.${issuedAtSeconds}.${signature}`;
|
|
2866
|
+
};
|
|
2867
|
+
var checkToken = (token, settings, nowMs) => {
|
|
2868
|
+
if (settings.staticTokens.includes(token)) return { ok: true };
|
|
2869
|
+
if (!token.startsWith(TOKEN_PREFIX)) return { ok: false, message: "Unauthenticated." };
|
|
2870
|
+
const [encoded, issued, signature] = token.slice(TOKEN_PREFIX.length).split(".");
|
|
2871
|
+
const clientId = encoded ? fromBase64url(encoded) : void 0;
|
|
2872
|
+
const issuedAt = Number(issued);
|
|
2873
|
+
if (clientId === void 0 || !Number.isInteger(issuedAt) || !signature) {
|
|
2874
|
+
return { ok: false, message: "Unauthenticated." };
|
|
2875
|
+
}
|
|
2876
|
+
if (signature !== opaqueToken(`rxvortex:${clientId}:${issuedAt}`, 32)) {
|
|
2877
|
+
return { ok: false, message: "Unauthenticated." };
|
|
2878
|
+
}
|
|
2879
|
+
if (nowMs / 1e3 >= issuedAt + settings.tokenTtlSeconds) {
|
|
2880
|
+
return { ok: false, message: "Token has expired." };
|
|
2881
|
+
}
|
|
2882
|
+
return { ok: true };
|
|
2883
|
+
};
|
|
2884
|
+
var record = (context) => {
|
|
2885
|
+
if (context.body.kind !== "json" || typeof context.body.value !== "object" || !context.body.value) {
|
|
2886
|
+
throw new HttpError(422, {
|
|
2887
|
+
message: "The given data was invalid.",
|
|
2888
|
+
errors: { body: ["The request body must be a JSON object."] }
|
|
2889
|
+
});
|
|
2890
|
+
}
|
|
2891
|
+
return context.body.value;
|
|
2892
|
+
};
|
|
2893
|
+
var statusBody = (order) => ({
|
|
2894
|
+
order_tracking_id: order.order_tracking_id,
|
|
2895
|
+
tracking_id: order.order_tracking_id,
|
|
2896
|
+
orderReferenceID: order.order_tracking_id,
|
|
2897
|
+
sender_order_id: order.sender_order_id,
|
|
2898
|
+
rxstatus: order.rxstatus,
|
|
2899
|
+
orderstatus: order.orderstatus,
|
|
2900
|
+
shipping_status: order.shipping_status,
|
|
2901
|
+
delivered_date: order.delivered_date,
|
|
2902
|
+
trackingnumber: order.trackingnumber,
|
|
2903
|
+
shippingservice: order.shippingservice,
|
|
2904
|
+
shippingcarrier: order.shippingcarrier,
|
|
2905
|
+
shipmenttrackingurl: order.shipmenttrackingurl,
|
|
2906
|
+
cancellable: order.cancellable,
|
|
2907
|
+
created_at: order.created_at,
|
|
2908
|
+
updated_at: order.updated_at
|
|
2909
|
+
});
|
|
2910
|
+
var RxVortexAPI = class {
|
|
2911
|
+
app;
|
|
2912
|
+
sqlite;
|
|
2913
|
+
state;
|
|
2914
|
+
service;
|
|
2915
|
+
now;
|
|
2916
|
+
onWebhook;
|
|
2917
|
+
constructor(options = {}) {
|
|
2918
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2919
|
+
const namespace = options.namespace ?? RXVORTEX_NAMESPACE;
|
|
2920
|
+
this.now = options.now ?? (() => Date.now());
|
|
2921
|
+
this.onWebhook = options.onWebhook;
|
|
2922
|
+
this.state = new RxVortexState(sqlite, namespace, {
|
|
2923
|
+
catalog: options.catalog ?? [],
|
|
2924
|
+
settings: options.settings ?? {}
|
|
2925
|
+
});
|
|
2926
|
+
const handlers = defineOperations({
|
|
2927
|
+
GenerateAccessToken: (context) => this.generateToken(context),
|
|
2928
|
+
CreateOrder: (context) => this.createOrder(context),
|
|
2929
|
+
GetOrder: (context) => this.getOrder(context),
|
|
2930
|
+
CancelOrder: (context) => this.cancelOrder(context),
|
|
2931
|
+
ListPresetCatalogItems: () => jsonRes(200, {
|
|
2932
|
+
data: this.state.catalog.list({ order: "oldest" }).map((row) => row.value)
|
|
2933
|
+
})
|
|
2934
|
+
});
|
|
2935
|
+
this.service = createService({
|
|
2936
|
+
document,
|
|
2937
|
+
handlers,
|
|
2938
|
+
sqlite,
|
|
2939
|
+
namespace,
|
|
2940
|
+
now: this.now,
|
|
2941
|
+
notFound: () => jsonRes(404, { message: "Not Found" }),
|
|
2942
|
+
onError: (error) => {
|
|
2943
|
+
if (error instanceof HttpError) return error.toResponse();
|
|
2944
|
+
throw error;
|
|
2945
|
+
},
|
|
2946
|
+
before: (context) => {
|
|
2947
|
+
if (context.operation.operationId === "GenerateAccessToken") return void 0;
|
|
2948
|
+
this.tick();
|
|
2949
|
+
const token = bearerToken(context.request);
|
|
2950
|
+
if (!token) return jsonRes(401, { message: "Unauthenticated." });
|
|
2951
|
+
if (faultEffect(context.request, "token_expired") !== void 0) {
|
|
2952
|
+
return jsonRes(401, { message: "Token has expired." });
|
|
2953
|
+
}
|
|
2954
|
+
const check = checkToken(token, this.state.current(), this.now());
|
|
2955
|
+
return check.ok ? void 0 : jsonRes(401, { message: check.message });
|
|
2956
|
+
}
|
|
2957
|
+
});
|
|
2958
|
+
this.app = this.service.app;
|
|
2959
|
+
this.sqlite = this.service.sqlite;
|
|
2960
|
+
}
|
|
2961
|
+
fetch(request) {
|
|
2962
|
+
return this.service.fetch(request);
|
|
2963
|
+
}
|
|
2964
|
+
async reset() {
|
|
2965
|
+
await this.service.reset();
|
|
2966
|
+
this.state.ensureSeeded();
|
|
2967
|
+
}
|
|
2968
|
+
iso() {
|
|
2969
|
+
return new Date(this.now()).toISOString();
|
|
2970
|
+
}
|
|
2971
|
+
generateToken(context) {
|
|
2972
|
+
const body = record(context);
|
|
2973
|
+
const issues = bodyIssues(context);
|
|
2974
|
+
if (issues.length > 0) {
|
|
2975
|
+
return jsonRes(422, { message: "The given data was invalid.", errors: issuesByField(issues) });
|
|
2976
|
+
}
|
|
2977
|
+
const clientId = String(body.client_id);
|
|
2978
|
+
const clients = this.state.current().clients;
|
|
2979
|
+
if (clients.length > 0 && !clients.some((c) => c.client_id === clientId && c.client_secret === body.client_secret)) {
|
|
2980
|
+
return jsonRes(401, { message: "Invalid client credentials." });
|
|
2981
|
+
}
|
|
2982
|
+
const ttl = this.state.current().tokenTtlSeconds;
|
|
2983
|
+
return jsonRes(200, {
|
|
2984
|
+
access_token: issueToken(clientId, Math.floor(this.now() / 1e3)),
|
|
2985
|
+
token_type: "Bearer",
|
|
2986
|
+
expires_in: ttl
|
|
2987
|
+
});
|
|
2988
|
+
}
|
|
2989
|
+
createOrder(context) {
|
|
2990
|
+
const body = record(context);
|
|
2991
|
+
if (faultEffect(context.request, "validation_errors_array") !== void 0) {
|
|
2992
|
+
return jsonRes(422, {
|
|
2993
|
+
message: "The given data was invalid.",
|
|
2994
|
+
errors: [{ field: "patient.phone", message: "The patient.phone format is invalid." }]
|
|
2995
|
+
});
|
|
2996
|
+
}
|
|
2997
|
+
if (faultEffect(context.request, "validation_errors_object") !== void 0) {
|
|
2998
|
+
return jsonRes(422, {
|
|
2999
|
+
message: "The given data was invalid.",
|
|
3000
|
+
errors: { "patient.phone": ["The patient.phone format is invalid."] }
|
|
3001
|
+
});
|
|
3002
|
+
}
|
|
3003
|
+
if (faultEffect(context.request, "validation_errors_empty") !== void 0) {
|
|
3004
|
+
return jsonRes(422, { message: "The given data was invalid.", errors: [] });
|
|
3005
|
+
}
|
|
3006
|
+
const issues = bodyIssues(context);
|
|
3007
|
+
if (issues.length > 0) {
|
|
3008
|
+
return jsonRes(422, { message: "The given data was invalid.", errors: issuesByField(issues) });
|
|
3009
|
+
}
|
|
3010
|
+
const order = body.order;
|
|
3011
|
+
const meds = body.medication_requests;
|
|
3012
|
+
const unknown = meds.find((med) => {
|
|
3013
|
+
const item = this.state.catalog.get(med.preset_catalog_id);
|
|
3014
|
+
return !item || item.status !== "active";
|
|
3015
|
+
});
|
|
3016
|
+
if (unknown) {
|
|
3017
|
+
return jsonRes(422, {
|
|
3018
|
+
message: "The given data was invalid.",
|
|
3019
|
+
errors: {
|
|
3020
|
+
"medication_requests.0.preset_catalog_id": [
|
|
3021
|
+
`The selected preset catalog id ${unknown.preset_catalog_id} is invalid.`
|
|
3022
|
+
]
|
|
3023
|
+
}
|
|
3024
|
+
});
|
|
3025
|
+
}
|
|
3026
|
+
const existing = this.state.findOrder(order.sender_order_id);
|
|
3027
|
+
if (existing) {
|
|
3028
|
+
return annotateResponse(
|
|
3029
|
+
jsonRes(409, {
|
|
3030
|
+
success: false,
|
|
3031
|
+
message: `An order with sender_order_id ${order.sender_order_id} already exists.`
|
|
3032
|
+
}),
|
|
3033
|
+
{ ids: { orderId: existing.order_tracking_id } }
|
|
3034
|
+
);
|
|
3035
|
+
}
|
|
3036
|
+
const now = this.iso();
|
|
3037
|
+
const created = {
|
|
3038
|
+
order_tracking_id: this.state.nextTrackingId(),
|
|
3039
|
+
sender_order_id: order.sender_order_id,
|
|
3040
|
+
...triple("Created"),
|
|
3041
|
+
delivered_date: null,
|
|
3042
|
+
trackingnumber: null,
|
|
3043
|
+
shippingservice: null,
|
|
3044
|
+
shippingcarrier: null,
|
|
3045
|
+
shipmenttrackingurl: null,
|
|
3046
|
+
cancellable: true,
|
|
3047
|
+
created_at: now,
|
|
3048
|
+
updated_at: now,
|
|
3049
|
+
createdAtMs: this.now(),
|
|
3050
|
+
preset_catalog_ids: meds.map((m) => m.preset_catalog_id),
|
|
3051
|
+
advanced: 0
|
|
3052
|
+
};
|
|
3053
|
+
this.state.orders.insert(created.order_tracking_id, created);
|
|
3054
|
+
const ids = { orderId: created.order_tracking_id, senderOrderId: created.sender_order_id };
|
|
3055
|
+
if (faultEffect(context.request, "created_but_500") !== void 0) {
|
|
3056
|
+
return annotateResponse(jsonRes(500, { message: "Server Error" }), { ids });
|
|
3057
|
+
}
|
|
3058
|
+
if (faultEffect(context.request, "duplicate_sender_order_id") !== void 0) {
|
|
3059
|
+
return annotateResponse(
|
|
3060
|
+
jsonRes(409, {
|
|
3061
|
+
success: false,
|
|
3062
|
+
message: `An order with sender_order_id ${created.sender_order_id} already exists.`
|
|
3063
|
+
}),
|
|
3064
|
+
{ ids }
|
|
3065
|
+
);
|
|
3066
|
+
}
|
|
3067
|
+
const numeric = faultEffect(context.request, "numeric_tracking_id") !== void 0;
|
|
3068
|
+
return annotateResponse(
|
|
3069
|
+
jsonRes(200, {
|
|
3070
|
+
success: true,
|
|
3071
|
+
message: "Order created successfully.",
|
|
3072
|
+
order_tracking_id: numeric ? Number.parseInt(created.order_tracking_id.replace(/\D/g, "") || "1", 10) : created.order_tracking_id,
|
|
3073
|
+
sender_order_id: created.sender_order_id,
|
|
3074
|
+
status: created.rxstatus
|
|
3075
|
+
}),
|
|
3076
|
+
{ ids }
|
|
3077
|
+
);
|
|
3078
|
+
}
|
|
3079
|
+
getOrder(context) {
|
|
3080
|
+
const order = this.state.findOrder(context.params.orderId ?? "");
|
|
3081
|
+
if (!order) return jsonRes(404, { message: "Order not found." });
|
|
3082
|
+
const body = statusBody(order);
|
|
3083
|
+
if (faultEffect(context.request, "stale_error_with_delivered_date") !== void 0) {
|
|
3084
|
+
Object.assign(body, {
|
|
3085
|
+
rxstatus: "Error",
|
|
3086
|
+
orderstatus: "Error",
|
|
3087
|
+
delivered_date: order.delivered_date ?? this.iso().slice(0, 10)
|
|
3088
|
+
});
|
|
3089
|
+
}
|
|
3090
|
+
return annotateResponse(jsonRes(200, body), { ids: { orderId: order.order_tracking_id } });
|
|
3091
|
+
}
|
|
3092
|
+
cancelOrder(context) {
|
|
3093
|
+
const order = this.state.findOrder(context.params.orderId ?? "");
|
|
3094
|
+
if (!order) return jsonRes(404, { message: "Order not found." });
|
|
3095
|
+
if (!order.cancellable) {
|
|
3096
|
+
return jsonRes(409, {
|
|
3097
|
+
success: false,
|
|
3098
|
+
message: `Order ${order.order_tracking_id} cannot be cancelled in status ${order.rxstatus}.`
|
|
3099
|
+
});
|
|
3100
|
+
}
|
|
3101
|
+
const updated = this.transition(order.order_tracking_id, { to: "Cancelled" });
|
|
3102
|
+
return annotateResponse(
|
|
3103
|
+
jsonRes(200, {
|
|
3104
|
+
success: true,
|
|
3105
|
+
message: "Order cancelled.",
|
|
3106
|
+
order_tracking_id: order.order_tracking_id,
|
|
3107
|
+
rxstatus: updated?.rxstatus ?? "Cancelled"
|
|
3108
|
+
}),
|
|
3109
|
+
{ ids: { orderId: order.order_tracking_id } }
|
|
3110
|
+
);
|
|
3111
|
+
}
|
|
3112
|
+
/** Move an order to a vendor status, set the three fields coherently, emit the webhook. */
|
|
3113
|
+
transition(id, input) {
|
|
3114
|
+
const order = this.state.findOrder(id);
|
|
3115
|
+
if (!order) return void 0;
|
|
3116
|
+
const status = triple(input.to);
|
|
3117
|
+
const shipped = isShippedOrLater(input.to);
|
|
3118
|
+
const delivered = /deliver/i.test(status.shipping_status);
|
|
3119
|
+
const trackingnumber = input.trackingnumber ?? order.trackingnumber ?? (shipped ? `1Z${opaqueToken(order.order_tracking_id, 16).toUpperCase()}` : null);
|
|
3120
|
+
const carrier = input.shippingcarrier ?? order.shippingcarrier ?? (shipped ? "UPS" : null);
|
|
3121
|
+
const next = {
|
|
3122
|
+
...order,
|
|
3123
|
+
...status,
|
|
3124
|
+
trackingnumber,
|
|
3125
|
+
shippingcarrier: carrier,
|
|
3126
|
+
shippingservice: input.shippingservice ?? order.shippingservice ?? (shipped ? "Ground" : null),
|
|
3127
|
+
shipmenttrackingurl: trackingnumber && carrier === "UPS" ? `https://www.ups.com/track?tracknum=${trackingnumber}` : order.shipmenttrackingurl,
|
|
3128
|
+
delivered_date: input.delivered_date ?? (delivered ? this.iso().slice(0, 10) : order.delivered_date),
|
|
3129
|
+
cancellable: !shipped && !isTerminal(status),
|
|
3130
|
+
updated_at: this.iso()
|
|
3131
|
+
};
|
|
3132
|
+
this.state.orders.update(order.order_tracking_id, next);
|
|
3133
|
+
this.onWebhook?.({
|
|
3134
|
+
event: "order.status_updated",
|
|
3135
|
+
orderReferenceID: next.order_tracking_id,
|
|
3136
|
+
order_tracking_id: next.order_tracking_id,
|
|
3137
|
+
tracking_id: next.order_tracking_id,
|
|
3138
|
+
sender_order_id: next.sender_order_id,
|
|
3139
|
+
rxstatus: next.rxstatus,
|
|
3140
|
+
orderstatus: next.orderstatus,
|
|
3141
|
+
shipping_status: next.shipping_status,
|
|
3142
|
+
delivered_date: next.delivered_date,
|
|
3143
|
+
trackingnumber: next.trackingnumber,
|
|
3144
|
+
shippingcarrier: next.shippingcarrier,
|
|
3145
|
+
shippingservice: next.shippingservice,
|
|
3146
|
+
shipmenttrackingurl: next.shipmenttrackingurl,
|
|
3147
|
+
updated_at: next.updated_at
|
|
3148
|
+
});
|
|
3149
|
+
return this.state.orders.get(order.order_tracking_id);
|
|
3150
|
+
}
|
|
3151
|
+
/**
|
|
3152
|
+
* Apply every auto-advance step that is due on the mock clock. Runs before each vendor
|
|
3153
|
+
* request, on `POST /__admin/tick`, and from the served runtime's background ticker.
|
|
3154
|
+
*/
|
|
3155
|
+
tick() {
|
|
3156
|
+
const plan = this.state.current().autoAdvance;
|
|
3157
|
+
if (!plan || plan.path.length === 0) return 0;
|
|
3158
|
+
let applied = 0;
|
|
3159
|
+
for (const { value: order } of this.state.orders.list({ order: "oldest" })) {
|
|
3160
|
+
let current = order;
|
|
3161
|
+
while (current.advanced < plan.path.length) {
|
|
3162
|
+
const due = current.createdAtMs + plan.afterMs * (current.advanced + 1);
|
|
3163
|
+
if (this.now() < due) break;
|
|
3164
|
+
const to = plan.path[current.advanced];
|
|
3165
|
+
const moved = this.transition(current.order_tracking_id, { to });
|
|
3166
|
+
if (!moved) break;
|
|
3167
|
+
current = { ...moved, advanced: current.advanced + 1 };
|
|
3168
|
+
this.state.orders.update(current.order_tracking_id, current);
|
|
3169
|
+
applied++;
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
return applied;
|
|
3173
|
+
}
|
|
3174
|
+
orders() {
|
|
3175
|
+
return this.state.orders.list({ order: "oldest" }).map((row) => row.value);
|
|
3176
|
+
}
|
|
3177
|
+
};
|
|
3178
|
+
|
|
3179
|
+
export {
|
|
3180
|
+
document,
|
|
3181
|
+
operationIds,
|
|
3182
|
+
supportedOperationIds,
|
|
3183
|
+
CUSTOM_CREAM_ANCHOR_PRESET_ID,
|
|
3184
|
+
DEFAULT_CATALOG,
|
|
3185
|
+
RXVORTEX_PRESETS,
|
|
3186
|
+
createRuntime2 as createRuntime,
|
|
3187
|
+
RXVORTEX_NAMESPACE,
|
|
3188
|
+
tokenCredential,
|
|
3189
|
+
RxVortexAPI
|
|
3190
|
+
};
|
|
3191
|
+
//# sourceMappingURL=chunk-DNELVPK4.js.map
|