@crvouga/mockingbird-service-pharmetika 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 +175 -0
- package/dist/chunk-I6QERCU4.js +395 -0
- package/dist/chunk-I6QERCU4.js.map +7 -0
- package/dist/chunk-SQBTC6SN.js +3474 -0
- package/dist/chunk-SQBTC6SN.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1036 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1342 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
|
@@ -0,0 +1,3474 @@
|
|
|
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 (error2) {
|
|
222
|
+
return adminError(404, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
278
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
289
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
303
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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 basicAuth = (request) => {
|
|
393
|
+
const header = request.headers.get("authorization");
|
|
394
|
+
if (!header)
|
|
395
|
+
return void 0;
|
|
396
|
+
const match = /^Basic\s+(.+)$/i.exec(header.trim());
|
|
397
|
+
if (!match?.[1])
|
|
398
|
+
return void 0;
|
|
399
|
+
let decoded;
|
|
400
|
+
try {
|
|
401
|
+
decoded = atob(match[1].trim());
|
|
402
|
+
} catch {
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
const colon = decoded.indexOf(":");
|
|
406
|
+
if (colon < 0)
|
|
407
|
+
return { username: decoded, password: "" };
|
|
408
|
+
return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };
|
|
409
|
+
};
|
|
410
|
+
var createCredentialRegistry = () => {
|
|
411
|
+
const map = /* @__PURE__ */ new Map();
|
|
412
|
+
return {
|
|
413
|
+
set: (credential, namespace) => {
|
|
414
|
+
map.set(credential, namespace);
|
|
415
|
+
},
|
|
416
|
+
get: (credential) => map.get(credential),
|
|
417
|
+
remove: (credential) => map.delete(credential),
|
|
418
|
+
clear: () => map.clear(),
|
|
419
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
423
|
+
|
|
424
|
+
// ../core/dist/rng.js
|
|
425
|
+
var seedFrom = (value) => {
|
|
426
|
+
let hash = 2166136261;
|
|
427
|
+
for (let i = 0; i < value.length; i++) {
|
|
428
|
+
hash ^= value.charCodeAt(i);
|
|
429
|
+
hash = Math.imul(hash, 16777619);
|
|
430
|
+
}
|
|
431
|
+
return hash >>> 0;
|
|
432
|
+
};
|
|
433
|
+
var createRng = (seed = 0) => {
|
|
434
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
435
|
+
let state = numeric;
|
|
436
|
+
const next = () => {
|
|
437
|
+
state = state + 1831565813 >>> 0;
|
|
438
|
+
let t = state;
|
|
439
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
440
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
441
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
442
|
+
};
|
|
443
|
+
return {
|
|
444
|
+
next,
|
|
445
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
446
|
+
reset: () => {
|
|
447
|
+
state = numeric;
|
|
448
|
+
},
|
|
449
|
+
state: () => state,
|
|
450
|
+
setState: (next2) => {
|
|
451
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
452
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
453
|
+
}
|
|
454
|
+
state = next2 >>> 0;
|
|
455
|
+
},
|
|
456
|
+
seed: numeric
|
|
457
|
+
};
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
// ../core/dist/faults.js
|
|
461
|
+
var matches = (rule, candidate) => {
|
|
462
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
466
|
+
return false;
|
|
467
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
471
|
+
return false;
|
|
472
|
+
return true;
|
|
473
|
+
};
|
|
474
|
+
var faultResponse = (rule) => {
|
|
475
|
+
const status = rule.status ?? 500;
|
|
476
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
477
|
+
if (typeof rule.body === "string")
|
|
478
|
+
return new Response(rule.body, { status, headers });
|
|
479
|
+
if (rule.body === null)
|
|
480
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
481
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
482
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
483
|
+
};
|
|
484
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
485
|
+
const entries = [];
|
|
486
|
+
return {
|
|
487
|
+
add(rule) {
|
|
488
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
489
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
490
|
+
if (existing >= 0)
|
|
491
|
+
entries[existing] = entry;
|
|
492
|
+
else
|
|
493
|
+
entries.push(entry);
|
|
494
|
+
return rule;
|
|
495
|
+
},
|
|
496
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
497
|
+
remove(id) {
|
|
498
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
499
|
+
if (index < 0)
|
|
500
|
+
return false;
|
|
501
|
+
entries.splice(index, 1);
|
|
502
|
+
return true;
|
|
503
|
+
},
|
|
504
|
+
clear() {
|
|
505
|
+
entries.length = 0;
|
|
506
|
+
},
|
|
507
|
+
async take(candidate) {
|
|
508
|
+
const hits = [];
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
if (entry.remaining === 0)
|
|
511
|
+
continue;
|
|
512
|
+
if (!matches(entry.rule, candidate))
|
|
513
|
+
continue;
|
|
514
|
+
const rate = entry.rule.rate ?? 1;
|
|
515
|
+
if (rng.next() >= rate)
|
|
516
|
+
continue;
|
|
517
|
+
entry.hits++;
|
|
518
|
+
if (entry.remaining !== null)
|
|
519
|
+
entry.remaining--;
|
|
520
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
521
|
+
if (delay !== void 0 && delay > 0) {
|
|
522
|
+
await sleep(delay);
|
|
523
|
+
}
|
|
524
|
+
const hit = { id: entry.rule.id };
|
|
525
|
+
if (entry.rule.effect !== void 0) {
|
|
526
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
527
|
+
}
|
|
528
|
+
if (entry.rule.drop === true)
|
|
529
|
+
hit.drop = true;
|
|
530
|
+
else if (entry.rule.status !== void 0)
|
|
531
|
+
hit.response = faultResponse(entry.rule);
|
|
532
|
+
hits.push(hit);
|
|
533
|
+
if (hit.drop || hit.response)
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
return hits;
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// ../../openapi/core/dist/refs.js
|
|
542
|
+
var OpenAPIReferenceError = class extends Error {
|
|
543
|
+
ref;
|
|
544
|
+
constructor(ref) {
|
|
545
|
+
super(`unresolvable $ref: ${ref}`);
|
|
546
|
+
this.ref = ref;
|
|
547
|
+
this.name = "OpenAPIReferenceError";
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
551
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
552
|
+
var resolveRef = (document2, ref) => {
|
|
553
|
+
if (!ref.startsWith("#/"))
|
|
554
|
+
throw new OpenAPIReferenceError(ref);
|
|
555
|
+
let cursor = document2;
|
|
556
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
557
|
+
const segment = unescapePointer(raw);
|
|
558
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
559
|
+
throw new OpenAPIReferenceError(ref);
|
|
560
|
+
}
|
|
561
|
+
cursor = cursor[segment];
|
|
562
|
+
}
|
|
563
|
+
if (cursor === void 0)
|
|
564
|
+
throw new OpenAPIReferenceError(ref);
|
|
565
|
+
return cursor;
|
|
566
|
+
};
|
|
567
|
+
var deref = (document2, value) => {
|
|
568
|
+
let current = value;
|
|
569
|
+
const seen = /* @__PURE__ */ new Set();
|
|
570
|
+
while (isReference(current)) {
|
|
571
|
+
if (seen.has(current.$ref))
|
|
572
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
573
|
+
seen.add(current.$ref);
|
|
574
|
+
current = resolveRef(document2, current.$ref);
|
|
575
|
+
}
|
|
576
|
+
return current;
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
// ../../openapi/core/dist/types.js
|
|
580
|
+
var HTTP_METHODS = [
|
|
581
|
+
"get",
|
|
582
|
+
"put",
|
|
583
|
+
"post",
|
|
584
|
+
"delete",
|
|
585
|
+
"options",
|
|
586
|
+
"head",
|
|
587
|
+
"patch",
|
|
588
|
+
"trace"
|
|
589
|
+
];
|
|
590
|
+
|
|
591
|
+
// ../../openapi/core/dist/document.js
|
|
592
|
+
var mergeParameters = (document2, item, own) => {
|
|
593
|
+
const merged = /* @__PURE__ */ new Map();
|
|
594
|
+
for (const raw of item.parameters ?? []) {
|
|
595
|
+
const parameter = deref(document2, raw);
|
|
596
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
597
|
+
}
|
|
598
|
+
for (const raw of own ?? []) {
|
|
599
|
+
const parameter = deref(document2, raw);
|
|
600
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
601
|
+
}
|
|
602
|
+
return [...merged.values()];
|
|
603
|
+
};
|
|
604
|
+
var listOperations = (document2) => {
|
|
605
|
+
const operations = [];
|
|
606
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
607
|
+
for (const method of HTTP_METHODS) {
|
|
608
|
+
const operation = item[method];
|
|
609
|
+
if (operation?.operationId === void 0)
|
|
610
|
+
continue;
|
|
611
|
+
const responses = {};
|
|
612
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
613
|
+
responses[status] = deref(document2, response);
|
|
614
|
+
}
|
|
615
|
+
operations.push({
|
|
616
|
+
operationId: operation.operationId,
|
|
617
|
+
method,
|
|
618
|
+
path,
|
|
619
|
+
operation,
|
|
620
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
621
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
622
|
+
responses
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return operations;
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
// ../../openapi/core/dist/schema.js
|
|
630
|
+
var resolveSchema = (document2, schema) => {
|
|
631
|
+
let current = schema;
|
|
632
|
+
const seen = /* @__PURE__ */ new Set();
|
|
633
|
+
while (typeof current.$ref === "string") {
|
|
634
|
+
const ref = current.$ref;
|
|
635
|
+
if (seen.has(ref))
|
|
636
|
+
break;
|
|
637
|
+
seen.add(ref);
|
|
638
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
639
|
+
const target = resolveRef(document2, ref);
|
|
640
|
+
current = { ...target, ...siblings };
|
|
641
|
+
}
|
|
642
|
+
if (current.nullable === true) {
|
|
643
|
+
const { nullable: _nullable, ...rest } = current;
|
|
644
|
+
const types = schemaTypes(rest);
|
|
645
|
+
if (types.length > 0 && !types.includes("null"))
|
|
646
|
+
current = { ...rest, type: [...types, "null"] };
|
|
647
|
+
else
|
|
648
|
+
current = rest;
|
|
649
|
+
}
|
|
650
|
+
return current;
|
|
651
|
+
};
|
|
652
|
+
var schemaTypes = (schema) => {
|
|
653
|
+
if (Array.isArray(schema.type))
|
|
654
|
+
return schema.type;
|
|
655
|
+
if (schema.type !== void 0)
|
|
656
|
+
return [schema.type];
|
|
657
|
+
const inferred = [];
|
|
658
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
659
|
+
inferred.push("object");
|
|
660
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
661
|
+
inferred.push("array");
|
|
662
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
663
|
+
inferred.push("string");
|
|
664
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
665
|
+
inferred.push("number");
|
|
666
|
+
return inferred;
|
|
667
|
+
};
|
|
668
|
+
var jsonTypeOf = (value) => {
|
|
669
|
+
if (value === null)
|
|
670
|
+
return "null";
|
|
671
|
+
if (Array.isArray(value))
|
|
672
|
+
return "array";
|
|
673
|
+
switch (typeof value) {
|
|
674
|
+
case "string":
|
|
675
|
+
return "string";
|
|
676
|
+
case "boolean":
|
|
677
|
+
return "boolean";
|
|
678
|
+
case "number":
|
|
679
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
680
|
+
case "object":
|
|
681
|
+
return "object";
|
|
682
|
+
default:
|
|
683
|
+
return "undefined";
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
var deepEqual = (a, b) => {
|
|
687
|
+
if (a === b)
|
|
688
|
+
return true;
|
|
689
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
690
|
+
return false;
|
|
691
|
+
if (Array.isArray(a)) {
|
|
692
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
693
|
+
}
|
|
694
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
695
|
+
const ka = Object.keys(a);
|
|
696
|
+
const kb = Object.keys(b);
|
|
697
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
698
|
+
}
|
|
699
|
+
return false;
|
|
700
|
+
};
|
|
701
|
+
var FORMAT_PATTERNS = {
|
|
702
|
+
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,
|
|
703
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
704
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
705
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
706
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
707
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
708
|
+
};
|
|
709
|
+
var graphemeLength = (value) => [...value].length;
|
|
710
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
711
|
+
const errors = [];
|
|
712
|
+
const s = resolveSchema(document2, schema);
|
|
713
|
+
const fail = (message) => errors.push({ path, message });
|
|
714
|
+
const actual = jsonTypeOf(value);
|
|
715
|
+
if (actual === "undefined") {
|
|
716
|
+
fail("value is undefined");
|
|
717
|
+
return errors;
|
|
718
|
+
}
|
|
719
|
+
const types = schemaTypes(s);
|
|
720
|
+
if (types.length > 0) {
|
|
721
|
+
const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
722
|
+
if (!ok) {
|
|
723
|
+
fail(`expected type ${types.join("|")}, got ${actual}`);
|
|
724
|
+
return errors;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
728
|
+
fail("value not in enum");
|
|
729
|
+
}
|
|
730
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
731
|
+
fail("value does not equal const");
|
|
732
|
+
if (typeof value === "string") {
|
|
733
|
+
const length = graphemeLength(value);
|
|
734
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
735
|
+
fail(`length ${length} < minLength ${s.minLength}`);
|
|
736
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
737
|
+
fail(`length ${length} > maxLength ${s.maxLength}`);
|
|
738
|
+
if (s.pattern !== void 0) {
|
|
739
|
+
try {
|
|
740
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
741
|
+
fail(`does not match pattern ${s.pattern}`);
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (s.format !== void 0) {
|
|
746
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
747
|
+
if (pattern && !pattern.test(value))
|
|
748
|
+
fail(`does not match format ${s.format}`);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (typeof value === "number") {
|
|
752
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
753
|
+
fail(`${value} < minimum ${s.minimum}`);
|
|
754
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
755
|
+
fail(`${value} > maximum ${s.maximum}`);
|
|
756
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
757
|
+
fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
758
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
759
|
+
fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
760
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
761
|
+
fail(`${value} is not a multiple of ${s.multipleOf}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (Array.isArray(value)) {
|
|
765
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
766
|
+
fail(`${value.length} items < minItems ${s.minItems}`);
|
|
767
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
768
|
+
fail(`${value.length} items > maxItems ${s.maxItems}`);
|
|
769
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
770
|
+
fail("items are not unique");
|
|
771
|
+
value.forEach((item, i) => {
|
|
772
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
773
|
+
if (itemSchema)
|
|
774
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
if (actual === "object") {
|
|
778
|
+
const record2 = value;
|
|
779
|
+
const keys = Object.keys(record2);
|
|
780
|
+
for (const name of s.required ?? [])
|
|
781
|
+
if (!(name in record2))
|
|
782
|
+
fail(`missing required property ${name}`);
|
|
783
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
784
|
+
fail(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
785
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
786
|
+
fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
787
|
+
for (const key of keys) {
|
|
788
|
+
const property = s.properties?.[key];
|
|
789
|
+
if (property) {
|
|
790
|
+
errors.push(...validateValue(document2, property, record2[key], [...path, key]));
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (s.additionalProperties === false)
|
|
794
|
+
fail(`unexpected property ${key}`);
|
|
795
|
+
else if (typeof s.additionalProperties === "object") {
|
|
796
|
+
errors.push(...validateValue(document2, s.additionalProperties, record2[key], [...path, key]));
|
|
797
|
+
}
|
|
798
|
+
if (s.propertyNames) {
|
|
799
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
800
|
+
if (nameErrors.length > 0)
|
|
801
|
+
fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
if (s.allOf)
|
|
806
|
+
for (const branch of s.allOf)
|
|
807
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
808
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
809
|
+
fail("matches no anyOf branch");
|
|
810
|
+
if (s.oneOf) {
|
|
811
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
812
|
+
if (matches2 !== 1)
|
|
813
|
+
fail(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
814
|
+
}
|
|
815
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
816
|
+
fail("matches forbidden `not` schema");
|
|
817
|
+
return errors;
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
// ../../http/codec/dist/form.js
|
|
821
|
+
var parsePath = (rawKey) => {
|
|
822
|
+
const open = rawKey.indexOf("[");
|
|
823
|
+
if (open === -1)
|
|
824
|
+
return [rawKey];
|
|
825
|
+
const path = [rawKey.slice(0, open)];
|
|
826
|
+
const rest = rawKey.slice(open);
|
|
827
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
828
|
+
let match = pattern.exec(rest);
|
|
829
|
+
let consumed = 0;
|
|
830
|
+
while (match !== null) {
|
|
831
|
+
if (match.index !== consumed)
|
|
832
|
+
return [rawKey];
|
|
833
|
+
path.push(match[1] ?? "");
|
|
834
|
+
consumed = match.index + match[0].length;
|
|
835
|
+
match = pattern.exec(rest);
|
|
836
|
+
}
|
|
837
|
+
if (consumed !== rest.length)
|
|
838
|
+
return [rawKey];
|
|
839
|
+
return path;
|
|
840
|
+
};
|
|
841
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
842
|
+
var put = (target, key, value) => {
|
|
843
|
+
if (key === "__proto__") {
|
|
844
|
+
Object.defineProperty(target, key, {
|
|
845
|
+
value,
|
|
846
|
+
enumerable: true,
|
|
847
|
+
writable: true,
|
|
848
|
+
configurable: true
|
|
849
|
+
});
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
;
|
|
853
|
+
target[key] = value;
|
|
854
|
+
};
|
|
855
|
+
var assign = (target, path, value) => {
|
|
856
|
+
let cursor = target;
|
|
857
|
+
for (let i = 0; i < path.length; i++) {
|
|
858
|
+
const segment = path[i];
|
|
859
|
+
const last = i === path.length - 1;
|
|
860
|
+
if (Array.isArray(cursor)) {
|
|
861
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
862
|
+
if (index === void 0)
|
|
863
|
+
return;
|
|
864
|
+
if (last) {
|
|
865
|
+
put(cursor, index, value);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
869
|
+
if (next === void 0 || typeof next === "string") {
|
|
870
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
871
|
+
put(cursor, index, created);
|
|
872
|
+
cursor = created;
|
|
873
|
+
} else {
|
|
874
|
+
cursor = next;
|
|
875
|
+
}
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
if (typeof cursor === "string")
|
|
879
|
+
return;
|
|
880
|
+
if (last) {
|
|
881
|
+
put(cursor, segment, value);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const nextSegment = path[i + 1];
|
|
885
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
886
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
887
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
888
|
+
put(cursor, segment, created);
|
|
889
|
+
cursor = created;
|
|
890
|
+
} else {
|
|
891
|
+
cursor = existing;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
var decodeFormPairs = (pairs) => {
|
|
896
|
+
const out = {};
|
|
897
|
+
for (const [rawKey, value] of pairs)
|
|
898
|
+
assign(out, parsePath(rawKey), value);
|
|
899
|
+
return densify(out);
|
|
900
|
+
};
|
|
901
|
+
var densify = (value) => {
|
|
902
|
+
if (typeof value === "string")
|
|
903
|
+
return value;
|
|
904
|
+
if (Array.isArray(value))
|
|
905
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
906
|
+
const out = {};
|
|
907
|
+
for (const [key, item] of Object.entries(value))
|
|
908
|
+
put(out, key, densify(item));
|
|
909
|
+
return out;
|
|
910
|
+
};
|
|
911
|
+
var decodeForm = (text) => {
|
|
912
|
+
const source = text.startsWith("?") ? text.slice(1) : text;
|
|
913
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
// ../../http/codec/dist/content.js
|
|
917
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
918
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
919
|
+
var mediaTypeOf = (contentType) => {
|
|
920
|
+
if (!contentType)
|
|
921
|
+
return void 0;
|
|
922
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
923
|
+
return essence ? essence : void 0;
|
|
924
|
+
};
|
|
925
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
926
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
927
|
+
var decodeBody = (contentType, bytes) => {
|
|
928
|
+
if (bytes.byteLength === 0)
|
|
929
|
+
return { kind: "empty" };
|
|
930
|
+
const mediaType = mediaTypeOf(contentType);
|
|
931
|
+
if (mediaType === void 0)
|
|
932
|
+
return { kind: "bytes", value: bytes };
|
|
933
|
+
if (isJsonMediaType(mediaType)) {
|
|
934
|
+
const text = utf8.decode(bytes);
|
|
935
|
+
try {
|
|
936
|
+
return { kind: "json", value: JSON.parse(text) };
|
|
937
|
+
} catch (error2) {
|
|
938
|
+
return {
|
|
939
|
+
kind: "invalid",
|
|
940
|
+
mediaType,
|
|
941
|
+
text,
|
|
942
|
+
error: error2 instanceof Error ? error2.message : String(error2)
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
947
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
948
|
+
}
|
|
949
|
+
if (mediaType.startsWith("text/"))
|
|
950
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
951
|
+
return { kind: "bytes", value: bytes };
|
|
952
|
+
};
|
|
953
|
+
var readBody = async (message) => {
|
|
954
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
955
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// ../core/dist/http.js
|
|
959
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
960
|
+
status,
|
|
961
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
962
|
+
});
|
|
963
|
+
var HttpError = class extends Error {
|
|
964
|
+
status;
|
|
965
|
+
body;
|
|
966
|
+
headers;
|
|
967
|
+
constructor(status, body, headers = {}) {
|
|
968
|
+
super(`HTTP ${status}`);
|
|
969
|
+
this.status = status;
|
|
970
|
+
this.body = body;
|
|
971
|
+
this.headers = headers;
|
|
972
|
+
this.name = "HttpError";
|
|
973
|
+
}
|
|
974
|
+
toResponse() {
|
|
975
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
976
|
+
if (contentType === "text/plain") {
|
|
977
|
+
return new Response(String(this.body), {
|
|
978
|
+
status: this.status,
|
|
979
|
+
headers: this.headers
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
|
|
986
|
+
// ../core/dist/idempotency.js
|
|
987
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
988
|
+
var IdempotencyStore = class {
|
|
989
|
+
namespace;
|
|
990
|
+
responses;
|
|
991
|
+
constructor(sqlite, namespace, name = "idempotency") {
|
|
992
|
+
this.namespace = namespace;
|
|
993
|
+
this.responses = new Collection(sqlite, namespace, name);
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Run `handler` once per `key`. `fingerprint` identifies the request's parameters (e.g.
|
|
997
|
+
* the method, path and canonical body). Only `replayable` responses are stored (default:
|
|
998
|
+
* every status below 500, as Stripe does), so a transient failure can be retried.
|
|
999
|
+
*/
|
|
1000
|
+
async run(key, fingerprint, errors, handler, replayable = (status) => status < 500) {
|
|
1001
|
+
const slot = `${this.namespace}\0${key}`;
|
|
1002
|
+
const stored = this.responses.get(key);
|
|
1003
|
+
if (stored) {
|
|
1004
|
+
if (stored.fingerprint !== fingerprint)
|
|
1005
|
+
return errors.mismatch();
|
|
1006
|
+
return new Response(stored.body, {
|
|
1007
|
+
status: stored.status,
|
|
1008
|
+
headers: [...stored.headers, ["idempotent-replayed", "true"]]
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
if (inFlight.has(slot))
|
|
1012
|
+
return errors.conflict();
|
|
1013
|
+
let release = () => {
|
|
1014
|
+
};
|
|
1015
|
+
inFlight.set(slot, new Promise((resolve) => {
|
|
1016
|
+
release = resolve;
|
|
1017
|
+
}));
|
|
1018
|
+
try {
|
|
1019
|
+
const response = await handler();
|
|
1020
|
+
if (!replayable(response.status))
|
|
1021
|
+
return response;
|
|
1022
|
+
const body = await response.clone().text();
|
|
1023
|
+
this.responses.insert(key, {
|
|
1024
|
+
fingerprint,
|
|
1025
|
+
status: response.status,
|
|
1026
|
+
headers: [...response.headers],
|
|
1027
|
+
body
|
|
1028
|
+
});
|
|
1029
|
+
return response;
|
|
1030
|
+
} finally {
|
|
1031
|
+
inFlight.delete(slot);
|
|
1032
|
+
release();
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
var stableStringify = (value) => {
|
|
1037
|
+
if (Array.isArray(value))
|
|
1038
|
+
return `[${value.map(stableStringify).join(",")}]`;
|
|
1039
|
+
if (value && typeof value === "object") {
|
|
1040
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
|
|
1041
|
+
}
|
|
1042
|
+
return JSON.stringify(value) ?? "undefined";
|
|
1043
|
+
};
|
|
1044
|
+
|
|
1045
|
+
// ../core/dist/ids.js
|
|
1046
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
1047
|
+
var mix = (input) => {
|
|
1048
|
+
let hash = 2166136261;
|
|
1049
|
+
for (let i = 0; i < input.length; i++) {
|
|
1050
|
+
hash ^= input.charCodeAt(i);
|
|
1051
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
1052
|
+
}
|
|
1053
|
+
hash ^= hash >>> 16;
|
|
1054
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
1055
|
+
hash ^= hash >>> 13;
|
|
1056
|
+
return hash >>> 0;
|
|
1057
|
+
};
|
|
1058
|
+
var opaqueToken = (input, length) => {
|
|
1059
|
+
let out = "";
|
|
1060
|
+
let round = 0;
|
|
1061
|
+
while (out.length < length) {
|
|
1062
|
+
let hash = mix(`${input}:${round++}`);
|
|
1063
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
1064
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
1065
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return out;
|
|
1069
|
+
};
|
|
1070
|
+
|
|
1071
|
+
// ../core/dist/journal.js
|
|
1072
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1073
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1074
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1075
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1076
|
+
let sequence = 0;
|
|
1077
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1078
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1079
|
+
return {
|
|
1080
|
+
size: capacity,
|
|
1081
|
+
record(entry) {
|
|
1082
|
+
if (capacity === 0)
|
|
1083
|
+
return;
|
|
1084
|
+
order.set(entry, sequence++);
|
|
1085
|
+
let ring = rings.get(entry.namespace);
|
|
1086
|
+
if (!ring) {
|
|
1087
|
+
ring = { entries: [], next: 0 };
|
|
1088
|
+
rings.set(entry.namespace, ring);
|
|
1089
|
+
}
|
|
1090
|
+
if (ring.entries.length < capacity)
|
|
1091
|
+
ring.entries.push(entry);
|
|
1092
|
+
else {
|
|
1093
|
+
ring.entries[ring.next] = entry;
|
|
1094
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1095
|
+
}
|
|
1096
|
+
},
|
|
1097
|
+
list(query = {}) {
|
|
1098
|
+
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));
|
|
1099
|
+
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));
|
|
1100
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1101
|
+
},
|
|
1102
|
+
clear(namespace) {
|
|
1103
|
+
if (namespace === void 0)
|
|
1104
|
+
rings.clear();
|
|
1105
|
+
else
|
|
1106
|
+
rings.delete(namespace);
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
};
|
|
1110
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1111
|
+
var annotateResponse = (response, extra) => {
|
|
1112
|
+
const existing = notes.get(response);
|
|
1113
|
+
notes.set(response, {
|
|
1114
|
+
...existing,
|
|
1115
|
+
...extra,
|
|
1116
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1117
|
+
});
|
|
1118
|
+
return response;
|
|
1119
|
+
};
|
|
1120
|
+
var responseNotes = (response) => notes.get(response);
|
|
1121
|
+
|
|
1122
|
+
// ../core/dist/metrics.js
|
|
1123
|
+
var createMetrics = () => {
|
|
1124
|
+
let requests = 0;
|
|
1125
|
+
let faults = 0;
|
|
1126
|
+
let totalDurationMs = 0;
|
|
1127
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1128
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1129
|
+
return {
|
|
1130
|
+
record(entry) {
|
|
1131
|
+
requests++;
|
|
1132
|
+
totalDurationMs += entry.durationMs;
|
|
1133
|
+
if (entry.faultId !== void 0)
|
|
1134
|
+
faults++;
|
|
1135
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1136
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1137
|
+
if (entry.unmatched) {
|
|
1138
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1139
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1140
|
+
}
|
|
1141
|
+
},
|
|
1142
|
+
report: () => ({
|
|
1143
|
+
requests,
|
|
1144
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1145
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1146
|
+
const space = route.indexOf(" ");
|
|
1147
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1148
|
+
}),
|
|
1149
|
+
faults,
|
|
1150
|
+
totalDurationMs
|
|
1151
|
+
}),
|
|
1152
|
+
reset() {
|
|
1153
|
+
requests = 0;
|
|
1154
|
+
faults = 0;
|
|
1155
|
+
totalDurationMs = 0;
|
|
1156
|
+
byOperation.clear();
|
|
1157
|
+
unmatched.clear();
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
};
|
|
1161
|
+
|
|
1162
|
+
// ../../core/dist/timeline.js
|
|
1163
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1164
|
+
var Timeline = class {
|
|
1165
|
+
maxCheckpoints;
|
|
1166
|
+
now;
|
|
1167
|
+
makeId;
|
|
1168
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1169
|
+
heads = /* @__PURE__ */ new Map();
|
|
1170
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1171
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1172
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1173
|
+
references = /* @__PURE__ */ new Map();
|
|
1174
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1175
|
+
sequence = 0;
|
|
1176
|
+
constructor(options = {}) {
|
|
1177
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1178
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1179
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1180
|
+
this.maxCheckpoints = max;
|
|
1181
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1182
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1183
|
+
}
|
|
1184
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1185
|
+
commit(value, options = {}) {
|
|
1186
|
+
const branch = options.branch ?? "main";
|
|
1187
|
+
this.assertBranch(branch);
|
|
1188
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1189
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1190
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1191
|
+
const id = this.makeId(++this.sequence);
|
|
1192
|
+
if (this.nodes.has(id))
|
|
1193
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1194
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1195
|
+
this.nodes.set(id, checkpoint);
|
|
1196
|
+
this.moveHead(branch, id);
|
|
1197
|
+
this.collect(this.maxCheckpoints);
|
|
1198
|
+
return checkpoint;
|
|
1199
|
+
}
|
|
1200
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1201
|
+
fork(branch, options = {}) {
|
|
1202
|
+
this.assertBranch(branch);
|
|
1203
|
+
if (this.heads.has(branch))
|
|
1204
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1205
|
+
const from = options.from ?? this.heads.get("main");
|
|
1206
|
+
if (from === void 0)
|
|
1207
|
+
return void 0;
|
|
1208
|
+
const checkpoint = this.get(from);
|
|
1209
|
+
this.moveHead(branch, checkpoint.id);
|
|
1210
|
+
return checkpoint;
|
|
1211
|
+
}
|
|
1212
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1213
|
+
checkout(branch, id) {
|
|
1214
|
+
this.assertBranch(branch);
|
|
1215
|
+
const checkpoint = this.get(id);
|
|
1216
|
+
this.moveHead(branch, checkpoint.id);
|
|
1217
|
+
return checkpoint;
|
|
1218
|
+
}
|
|
1219
|
+
get(id) {
|
|
1220
|
+
const checkpoint = this.nodes.get(id);
|
|
1221
|
+
if (!checkpoint)
|
|
1222
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1223
|
+
return checkpoint;
|
|
1224
|
+
}
|
|
1225
|
+
head(branch = "main") {
|
|
1226
|
+
const id = this.heads.get(branch);
|
|
1227
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1228
|
+
}
|
|
1229
|
+
hasBranch(branch) {
|
|
1230
|
+
return this.heads.has(branch);
|
|
1231
|
+
}
|
|
1232
|
+
branches() {
|
|
1233
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1234
|
+
}
|
|
1235
|
+
checkpoints() {
|
|
1236
|
+
return [...this.nodes.values()];
|
|
1237
|
+
}
|
|
1238
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1239
|
+
get size() {
|
|
1240
|
+
return this.nodes.size;
|
|
1241
|
+
}
|
|
1242
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1243
|
+
retain(id) {
|
|
1244
|
+
const checkpoint = this.get(id);
|
|
1245
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1246
|
+
this.addReference(id);
|
|
1247
|
+
return checkpoint;
|
|
1248
|
+
}
|
|
1249
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1250
|
+
release(id) {
|
|
1251
|
+
if (!this.nodes.has(id))
|
|
1252
|
+
return false;
|
|
1253
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1254
|
+
if (pins === 0)
|
|
1255
|
+
return false;
|
|
1256
|
+
if (pins === 1)
|
|
1257
|
+
this.explicitPins.delete(id);
|
|
1258
|
+
else
|
|
1259
|
+
this.explicitPins.set(id, pins - 1);
|
|
1260
|
+
this.removeReference(id);
|
|
1261
|
+
this.collect(this.maxCheckpoints);
|
|
1262
|
+
return true;
|
|
1263
|
+
}
|
|
1264
|
+
deleteBranch(branch) {
|
|
1265
|
+
if (branch === "main")
|
|
1266
|
+
throw new RangeError("cannot delete main branch");
|
|
1267
|
+
const previous = this.heads.get(branch);
|
|
1268
|
+
const deleted = this.heads.delete(branch);
|
|
1269
|
+
if (previous !== void 0)
|
|
1270
|
+
this.removeReference(previous);
|
|
1271
|
+
this.collect(this.maxCheckpoints);
|
|
1272
|
+
return deleted;
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1276
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1277
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1278
|
+
*/
|
|
1279
|
+
gc(max = this.maxCheckpoints) {
|
|
1280
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1281
|
+
throw new RangeError("max must be a positive integer");
|
|
1282
|
+
const removed = [];
|
|
1283
|
+
this.collect(max, removed);
|
|
1284
|
+
return removed;
|
|
1285
|
+
}
|
|
1286
|
+
collect(max, removed) {
|
|
1287
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1288
|
+
const id = this.evictable.values().next().value;
|
|
1289
|
+
this.evictable.delete(id);
|
|
1290
|
+
this.nodes.delete(id);
|
|
1291
|
+
removed?.push(id);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
moveHead(branch, id) {
|
|
1295
|
+
const previous = this.heads.get(branch);
|
|
1296
|
+
if (previous === id)
|
|
1297
|
+
return;
|
|
1298
|
+
if (previous !== void 0)
|
|
1299
|
+
this.removeReference(previous);
|
|
1300
|
+
this.heads.set(branch, id);
|
|
1301
|
+
this.addReference(id);
|
|
1302
|
+
}
|
|
1303
|
+
addReference(id) {
|
|
1304
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1305
|
+
this.evictable.delete(id);
|
|
1306
|
+
}
|
|
1307
|
+
removeReference(id) {
|
|
1308
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1309
|
+
if (next > 0)
|
|
1310
|
+
this.references.set(id, next);
|
|
1311
|
+
else {
|
|
1312
|
+
this.references.delete(id);
|
|
1313
|
+
if (this.nodes.has(id))
|
|
1314
|
+
this.evictable.add(id);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
assertBranch(branch) {
|
|
1318
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1319
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
|
|
1323
|
+
// ../../sqlite/dist/default.js
|
|
1324
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1325
|
+
var createDefaultSqlite = () => new Database();
|
|
1326
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1327
|
+
|
|
1328
|
+
// ../../sqlite/dist/migrate.js
|
|
1329
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1330
|
+
sqlite.exec(`
|
|
1331
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1332
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1333
|
+
applied_at INTEGER NOT NULL
|
|
1334
|
+
)
|
|
1335
|
+
`);
|
|
1336
|
+
};
|
|
1337
|
+
var migrate = (sqlite, migrations) => {
|
|
1338
|
+
ensureMigrationsTable(sqlite);
|
|
1339
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1340
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1341
|
+
if (pending.length === 0)
|
|
1342
|
+
return;
|
|
1343
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1344
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1345
|
+
sqlite.transaction(() => {
|
|
1346
|
+
for (const migration of pending) {
|
|
1347
|
+
sqlite.exec(migration.sql);
|
|
1348
|
+
insert.run(migration.id, now);
|
|
1349
|
+
}
|
|
1350
|
+
});
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
// ../../sqlite/dist/schema.js
|
|
1354
|
+
var CORE_MIGRATIONS = [
|
|
1355
|
+
{
|
|
1356
|
+
id: "20260322_core_records_sequences",
|
|
1357
|
+
sql: `
|
|
1358
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1359
|
+
namespace TEXT NOT NULL,
|
|
1360
|
+
collection TEXT NOT NULL,
|
|
1361
|
+
id TEXT NOT NULL,
|
|
1362
|
+
seq INTEGER NOT NULL,
|
|
1363
|
+
value TEXT NOT NULL,
|
|
1364
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1365
|
+
);
|
|
1366
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1367
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1368
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1369
|
+
namespace TEXT NOT NULL,
|
|
1370
|
+
name TEXT NOT NULL,
|
|
1371
|
+
kind TEXT NOT NULL,
|
|
1372
|
+
value INTEGER NOT NULL,
|
|
1373
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1374
|
+
);
|
|
1375
|
+
`
|
|
1376
|
+
}
|
|
1377
|
+
];
|
|
1378
|
+
var migrateCore = (sqlite) => {
|
|
1379
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1380
|
+
};
|
|
1381
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1382
|
+
sqlite.transaction(() => {
|
|
1383
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1384
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1385
|
+
});
|
|
1386
|
+
};
|
|
1387
|
+
|
|
1388
|
+
// ../../openapi/metadata/dist/types.js
|
|
1389
|
+
var EXTENSION_KEYS = {
|
|
1390
|
+
operation: "x-mockingbird",
|
|
1391
|
+
resource: "x-mockingbird-resource",
|
|
1392
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1393
|
+
volatile: "x-mockingbird-volatile",
|
|
1394
|
+
scope: "x-mockingbird-scope",
|
|
1395
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1396
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1397
|
+
};
|
|
1398
|
+
|
|
1399
|
+
// ../../openapi/metadata/dist/read.js
|
|
1400
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1401
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1402
|
+
var operationMetadata = (operation) => {
|
|
1403
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1404
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1405
|
+
const supported = ext.supported ?? true;
|
|
1406
|
+
const parity = ext.parity ?? {};
|
|
1407
|
+
return {
|
|
1408
|
+
supported,
|
|
1409
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1410
|
+
parity: {
|
|
1411
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1412
|
+
safe: parity.safe ?? true,
|
|
1413
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
};
|
|
1417
|
+
|
|
1418
|
+
// ../core/dist/service.js
|
|
1419
|
+
import { Hono } from "hono";
|
|
1420
|
+
var defineOperations = (handlers) => handlers;
|
|
1421
|
+
var OperationRegistryError = class extends Error {
|
|
1422
|
+
problems;
|
|
1423
|
+
constructor(problems) {
|
|
1424
|
+
super(`operation registry is inconsistent:
|
|
1425
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1426
|
+
this.problems = problems;
|
|
1427
|
+
this.name = "OperationRegistryError";
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
var verifyOperations = (document2, handlers) => {
|
|
1431
|
+
const problems = [];
|
|
1432
|
+
const operations = listOperations(document2);
|
|
1433
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1434
|
+
for (const operation of operations) {
|
|
1435
|
+
if (seen.has(operation.operationId))
|
|
1436
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1437
|
+
seen.add(operation.operationId);
|
|
1438
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1439
|
+
const handler = handlers[operation.operationId];
|
|
1440
|
+
if (supported && !handler)
|
|
1441
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1442
|
+
if (!supported && handler)
|
|
1443
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1444
|
+
}
|
|
1445
|
+
for (const id of Object.keys(handlers)) {
|
|
1446
|
+
if (!seen.has(id))
|
|
1447
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1448
|
+
}
|
|
1449
|
+
return problems;
|
|
1450
|
+
};
|
|
1451
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1452
|
+
var routeOrder = (a, b) => {
|
|
1453
|
+
const sa = a.path.split("/");
|
|
1454
|
+
const sb = b.path.split("/");
|
|
1455
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1456
|
+
const x = sa[i] ?? "";
|
|
1457
|
+
const y = sb[i] ?? "";
|
|
1458
|
+
const px = x.startsWith("{");
|
|
1459
|
+
const py = y.startsWith("{");
|
|
1460
|
+
if (px !== py)
|
|
1461
|
+
return px ? 1 : -1;
|
|
1462
|
+
if (x !== y)
|
|
1463
|
+
return x < y ? -1 : 1;
|
|
1464
|
+
}
|
|
1465
|
+
return 0;
|
|
1466
|
+
};
|
|
1467
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1468
|
+
var bootSqlite = (sqlite) => {
|
|
1469
|
+
const client = resolveSqlite(sqlite);
|
|
1470
|
+
migrateCore(client);
|
|
1471
|
+
return client;
|
|
1472
|
+
};
|
|
1473
|
+
var createService = (options) => {
|
|
1474
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1475
|
+
if (problems.length > 0)
|
|
1476
|
+
throw new OperationRegistryError(problems);
|
|
1477
|
+
migrateCore(options.sqlite);
|
|
1478
|
+
const now = options.now ?? (() => Date.now());
|
|
1479
|
+
const app = new Hono();
|
|
1480
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1481
|
+
app.onError((error2, c) => options.onError(error2, c.req.raw));
|
|
1482
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1483
|
+
for (const operation of operations) {
|
|
1484
|
+
const metadata = operationMetadata(operation.operation);
|
|
1485
|
+
const handler = options.handlers[operation.operationId];
|
|
1486
|
+
const route = async (c) => {
|
|
1487
|
+
const request = c.req.raw;
|
|
1488
|
+
if (!metadata.supported || !handler) {
|
|
1489
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1490
|
+
}
|
|
1491
|
+
const url = new URL(request.url);
|
|
1492
|
+
const context = {
|
|
1493
|
+
request,
|
|
1494
|
+
url,
|
|
1495
|
+
params: c.req.param(),
|
|
1496
|
+
query: queryOf(url),
|
|
1497
|
+
body: await readBody(request),
|
|
1498
|
+
sqlite: options.sqlite,
|
|
1499
|
+
namespace: options.namespace,
|
|
1500
|
+
operation,
|
|
1501
|
+
document: options.document,
|
|
1502
|
+
now
|
|
1503
|
+
};
|
|
1504
|
+
const short = await options.before?.(context);
|
|
1505
|
+
if (short)
|
|
1506
|
+
return short;
|
|
1507
|
+
return handler(context);
|
|
1508
|
+
};
|
|
1509
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1510
|
+
}
|
|
1511
|
+
return {
|
|
1512
|
+
app,
|
|
1513
|
+
sqlite: options.sqlite,
|
|
1514
|
+
namespace: options.namespace,
|
|
1515
|
+
fetch: async (request) => app.fetch(request),
|
|
1516
|
+
reset: async () => {
|
|
1517
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1518
|
+
}
|
|
1519
|
+
};
|
|
1520
|
+
};
|
|
1521
|
+
|
|
1522
|
+
// ../core/dist/snapshot.js
|
|
1523
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1524
|
+
namespace,
|
|
1525
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1526
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1527
|
+
});
|
|
1528
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1529
|
+
sqlite.transaction(() => {
|
|
1530
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1531
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1532
|
+
const record2 = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1533
|
+
for (const row of snapshot.records) {
|
|
1534
|
+
record2.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1535
|
+
}
|
|
1536
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1537
|
+
for (const row of snapshot.sequences) {
|
|
1538
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1539
|
+
}
|
|
1540
|
+
});
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
// ../core/dist/version.js
|
|
1544
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1545
|
+
|
|
1546
|
+
// ../core/dist/signing.js
|
|
1547
|
+
var encoder = new TextEncoder();
|
|
1548
|
+
var toBase64 = (bytes) => {
|
|
1549
|
+
let binary = "";
|
|
1550
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1551
|
+
binary += String.fromCharCode(byte);
|
|
1552
|
+
}
|
|
1553
|
+
return btoa(binary);
|
|
1554
|
+
};
|
|
1555
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1556
|
+
var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1557
|
+
var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
|
|
1558
|
+
var hmac = async (algorithm, key, message, encoding = "hex") => {
|
|
1559
|
+
const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
1560
|
+
const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
|
|
1561
|
+
return encoding === "hex" ? toHex(signed) : toBase64(signed);
|
|
1562
|
+
};
|
|
1563
|
+
var svixSecretBytes = (secret) => {
|
|
1564
|
+
const raw = secret.replace(/^f?whsec_/, "");
|
|
1565
|
+
try {
|
|
1566
|
+
return fromBase64(raw);
|
|
1567
|
+
} catch {
|
|
1568
|
+
throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
|
|
1572
|
+
var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
|
|
1573
|
+
var signTwilio = async (authToken, url, params) => {
|
|
1574
|
+
const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
|
|
1575
|
+
return hmac("SHA-1", authToken, payload, "base64");
|
|
1576
|
+
};
|
|
1577
|
+
|
|
1578
|
+
// ../core/dist/webhooks.js
|
|
1579
|
+
var signers = {
|
|
1580
|
+
/** No signature. */
|
|
1581
|
+
none: () => () => ({}),
|
|
1582
|
+
/** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
|
|
1583
|
+
svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
|
|
1584
|
+
if (!secret)
|
|
1585
|
+
return {};
|
|
1586
|
+
const prefix = options.prefix ?? "svix";
|
|
1587
|
+
return {
|
|
1588
|
+
[`${prefix}-id`]: messageId,
|
|
1589
|
+
[`${prefix}-timestamp`]: String(timestampSeconds),
|
|
1590
|
+
[`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
|
|
1591
|
+
};
|
|
1592
|
+
},
|
|
1593
|
+
/** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
|
|
1594
|
+
timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
|
|
1595
|
+
/** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
|
|
1596
|
+
twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
|
|
1597
|
+
/** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
|
|
1598
|
+
header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
|
|
1599
|
+
/** Anything else: the service computes the headers itself. */
|
|
1600
|
+
custom: (sign) => sign
|
|
1601
|
+
};
|
|
1602
|
+
var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
|
|
1603
|
+
var unref = (timer) => {
|
|
1604
|
+
;
|
|
1605
|
+
timer.unref?.();
|
|
1606
|
+
};
|
|
1607
|
+
var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
1608
|
+
var matchesEndpoint = (endpoint, message) => {
|
|
1609
|
+
const events = endpoint.events ?? ["*"];
|
|
1610
|
+
if (!events.includes("*") && !events.includes(message.type))
|
|
1611
|
+
return false;
|
|
1612
|
+
for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
|
|
1613
|
+
if (message.tags[key] !== value)
|
|
1614
|
+
return false;
|
|
1615
|
+
}
|
|
1616
|
+
return true;
|
|
1617
|
+
};
|
|
1618
|
+
var createWebhookHub = (options) => {
|
|
1619
|
+
const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
|
|
1620
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
1621
|
+
const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
|
|
1622
|
+
const send = options.fetch ?? ((request) => fetch(request));
|
|
1623
|
+
const keep = options.keep ?? 500;
|
|
1624
|
+
const now = options.now ?? Date.now;
|
|
1625
|
+
const id = options.id ?? randomId;
|
|
1626
|
+
const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
|
1627
|
+
const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
|
1628
|
+
const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
|
|
1629
|
+
const own = /* @__PURE__ */ new Map();
|
|
1630
|
+
const messages = [];
|
|
1631
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
1632
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1633
|
+
const payloads = /* @__PURE__ */ new Map();
|
|
1634
|
+
const faults = /* @__PURE__ */ new Map();
|
|
1635
|
+
const held = /* @__PURE__ */ new Map();
|
|
1636
|
+
const inFlight2 = /* @__PURE__ */ new Set();
|
|
1637
|
+
const track = (work) => {
|
|
1638
|
+
inFlight2.add(work);
|
|
1639
|
+
void work.finally(() => inFlight2.delete(work));
|
|
1640
|
+
};
|
|
1641
|
+
const attempt = async (delivery) => {
|
|
1642
|
+
const entry = payloads.get(delivery.id);
|
|
1643
|
+
if (!entry)
|
|
1644
|
+
return false;
|
|
1645
|
+
const { message, endpoint } = entry;
|
|
1646
|
+
const timestampSeconds = Math.floor(now() / 1e3);
|
|
1647
|
+
const started = now();
|
|
1648
|
+
const record2 = {
|
|
1649
|
+
attempt: delivery.attempts.length + 1,
|
|
1650
|
+
at: new Date(started).toISOString(),
|
|
1651
|
+
status: null,
|
|
1652
|
+
error: null,
|
|
1653
|
+
durationMs: 0,
|
|
1654
|
+
responseBody: null
|
|
1655
|
+
};
|
|
1656
|
+
const controller = new AbortController();
|
|
1657
|
+
const timer = scheduleTimer(() => controller.abort(), timeoutMs);
|
|
1658
|
+
try {
|
|
1659
|
+
const signed = await options.signer({
|
|
1660
|
+
messageId: message.id,
|
|
1661
|
+
body: message.body,
|
|
1662
|
+
timestampSeconds,
|
|
1663
|
+
url: endpoint.url,
|
|
1664
|
+
secret: endpoint.secret,
|
|
1665
|
+
signUrl: endpoint.signUrl ?? endpoint.url,
|
|
1666
|
+
form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
|
|
1667
|
+
type: message.type,
|
|
1668
|
+
tags: message.tags
|
|
1669
|
+
});
|
|
1670
|
+
const response = await send(new Request(endpoint.url, {
|
|
1671
|
+
method: "POST",
|
|
1672
|
+
headers: {
|
|
1673
|
+
"content-type": message.contentType,
|
|
1674
|
+
...endpoint.headers,
|
|
1675
|
+
...message.headers,
|
|
1676
|
+
...signed
|
|
1677
|
+
},
|
|
1678
|
+
body: message.body,
|
|
1679
|
+
signal: controller.signal
|
|
1680
|
+
}));
|
|
1681
|
+
record2.status = response.status;
|
|
1682
|
+
record2.responseBody = await response.text();
|
|
1683
|
+
} catch (error2) {
|
|
1684
|
+
record2.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error2 instanceof Error ? error2.message : String(error2);
|
|
1685
|
+
} finally {
|
|
1686
|
+
cancel(timer);
|
|
1687
|
+
record2.durationMs = now() - started;
|
|
1688
|
+
delivery.attempts.push(record2);
|
|
1689
|
+
}
|
|
1690
|
+
return record2.status !== null && delivered(record2.status);
|
|
1691
|
+
};
|
|
1692
|
+
const schedule = (delivery) => {
|
|
1693
|
+
const index = delivery.attempts.length;
|
|
1694
|
+
if (index >= delays.length) {
|
|
1695
|
+
delivery.state = "failed";
|
|
1696
|
+
pending.delete(delivery.id);
|
|
1697
|
+
return;
|
|
1698
|
+
}
|
|
1699
|
+
const run = () => {
|
|
1700
|
+
pending.delete(delivery.id);
|
|
1701
|
+
track(attempt(delivery).then((ok) => {
|
|
1702
|
+
if (ok)
|
|
1703
|
+
delivery.state = "delivered";
|
|
1704
|
+
else
|
|
1705
|
+
schedule(delivery);
|
|
1706
|
+
}));
|
|
1707
|
+
};
|
|
1708
|
+
const delay = delays[index] ?? 0;
|
|
1709
|
+
if (delay <= 0) {
|
|
1710
|
+
pending.set(delivery.id, void 0);
|
|
1711
|
+
run();
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
const timer = scheduleTimer(run, delay);
|
|
1715
|
+
unref(timer);
|
|
1716
|
+
pending.set(delivery.id, timer);
|
|
1717
|
+
};
|
|
1718
|
+
const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
|
|
1719
|
+
const fanOut = (message, state = "pending") => {
|
|
1720
|
+
for (const endpoint of endpointsFor(message.namespace)) {
|
|
1721
|
+
if (!matchesEndpoint(endpoint, message))
|
|
1722
|
+
continue;
|
|
1723
|
+
const delivery = {
|
|
1724
|
+
id: id("dlv_"),
|
|
1725
|
+
messageId: message.id,
|
|
1726
|
+
namespace: message.namespace,
|
|
1727
|
+
type: message.type,
|
|
1728
|
+
endpointId: endpoint.id ?? "we_unknown",
|
|
1729
|
+
url: endpoint.url,
|
|
1730
|
+
state,
|
|
1731
|
+
attempts: []
|
|
1732
|
+
};
|
|
1733
|
+
deliveries.set(delivery.id, delivery);
|
|
1734
|
+
payloads.set(delivery.id, { message, endpoint });
|
|
1735
|
+
if (state === "pending")
|
|
1736
|
+
schedule(delivery);
|
|
1737
|
+
}
|
|
1738
|
+
};
|
|
1739
|
+
const takeFault = (namespace) => {
|
|
1740
|
+
const queue = faults.get(namespace);
|
|
1741
|
+
const head = queue?.[0];
|
|
1742
|
+
if (!queue || !head)
|
|
1743
|
+
return void 0;
|
|
1744
|
+
head.remaining--;
|
|
1745
|
+
if (head.remaining <= 0)
|
|
1746
|
+
queue.shift();
|
|
1747
|
+
return head.mode;
|
|
1748
|
+
};
|
|
1749
|
+
const releaseHeld = (namespace) => {
|
|
1750
|
+
const waiting = held.get(namespace);
|
|
1751
|
+
if (!waiting)
|
|
1752
|
+
return;
|
|
1753
|
+
held.delete(namespace);
|
|
1754
|
+
for (const message of waiting)
|
|
1755
|
+
fanOut(message);
|
|
1756
|
+
};
|
|
1757
|
+
const hub = {
|
|
1758
|
+
publish(input) {
|
|
1759
|
+
const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
|
|
1760
|
+
const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
|
|
1761
|
+
const message = {
|
|
1762
|
+
id: input.id ?? id("msg_"),
|
|
1763
|
+
namespace: input.namespace,
|
|
1764
|
+
type: input.type,
|
|
1765
|
+
body,
|
|
1766
|
+
contentType,
|
|
1767
|
+
tags: input.tags ?? {},
|
|
1768
|
+
headers: input.headers ?? {},
|
|
1769
|
+
publishedAt: new Date(now()).toISOString()
|
|
1770
|
+
};
|
|
1771
|
+
messages.push(message);
|
|
1772
|
+
const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
|
|
1773
|
+
const oldest = ofNamespace[0];
|
|
1774
|
+
if (ofNamespace.length > keep && oldest)
|
|
1775
|
+
messages.splice(messages.indexOf(oldest), 1);
|
|
1776
|
+
options.onMessage?.(message);
|
|
1777
|
+
const fault = takeFault(message.namespace);
|
|
1778
|
+
if (fault === "drop") {
|
|
1779
|
+
fanOut(message, "dropped");
|
|
1780
|
+
return message;
|
|
1781
|
+
}
|
|
1782
|
+
if (fault === "reorder") {
|
|
1783
|
+
held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
|
|
1784
|
+
return message;
|
|
1785
|
+
}
|
|
1786
|
+
fanOut(message);
|
|
1787
|
+
if (fault === "duplicate")
|
|
1788
|
+
fanOut(message);
|
|
1789
|
+
releaseHeld(message.namespace);
|
|
1790
|
+
return message;
|
|
1791
|
+
},
|
|
1792
|
+
setEndpoints(namespace, endpoints) {
|
|
1793
|
+
const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
|
|
1794
|
+
own.set(namespace, withIds);
|
|
1795
|
+
return withIds;
|
|
1796
|
+
},
|
|
1797
|
+
endpoints: endpointsFor,
|
|
1798
|
+
messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
|
|
1799
|
+
deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
|
|
1800
|
+
async replay(id2) {
|
|
1801
|
+
const delivery = deliveries.get(id2);
|
|
1802
|
+
if (!delivery)
|
|
1803
|
+
return void 0;
|
|
1804
|
+
const ok = await attempt(delivery);
|
|
1805
|
+
if (ok)
|
|
1806
|
+
delivery.state = "delivered";
|
|
1807
|
+
return delivery;
|
|
1808
|
+
},
|
|
1809
|
+
async flush() {
|
|
1810
|
+
for (const namespace of [...held.keys()])
|
|
1811
|
+
releaseHeld(namespace);
|
|
1812
|
+
const waiting = [...pending.entries()];
|
|
1813
|
+
for (const [id2, timer] of waiting) {
|
|
1814
|
+
if (timer === void 0)
|
|
1815
|
+
continue;
|
|
1816
|
+
cancel(timer);
|
|
1817
|
+
pending.delete(id2);
|
|
1818
|
+
const delivery = deliveries.get(id2);
|
|
1819
|
+
if (!delivery)
|
|
1820
|
+
continue;
|
|
1821
|
+
track(attempt(delivery).then((ok) => {
|
|
1822
|
+
if (ok)
|
|
1823
|
+
delivery.state = "delivered";
|
|
1824
|
+
else
|
|
1825
|
+
schedule(delivery);
|
|
1826
|
+
}));
|
|
1827
|
+
}
|
|
1828
|
+
await hub.idle();
|
|
1829
|
+
},
|
|
1830
|
+
async idle() {
|
|
1831
|
+
while (inFlight2.size > 0)
|
|
1832
|
+
await Promise.allSettled([...inFlight2]);
|
|
1833
|
+
},
|
|
1834
|
+
fault(namespace, fault) {
|
|
1835
|
+
const queue = faults.get(namespace) ?? [];
|
|
1836
|
+
queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
|
|
1837
|
+
faults.set(namespace, queue);
|
|
1838
|
+
},
|
|
1839
|
+
clear(namespace) {
|
|
1840
|
+
for (const [id2, delivery] of deliveries) {
|
|
1841
|
+
if (namespace !== void 0 && delivery.namespace !== namespace)
|
|
1842
|
+
continue;
|
|
1843
|
+
const timer = pending.get(id2);
|
|
1844
|
+
if (timer !== void 0)
|
|
1845
|
+
cancel(timer);
|
|
1846
|
+
pending.delete(id2);
|
|
1847
|
+
deliveries.delete(id2);
|
|
1848
|
+
payloads.delete(id2);
|
|
1849
|
+
}
|
|
1850
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1851
|
+
if (namespace === void 0 || messages[i]?.namespace === namespace)
|
|
1852
|
+
messages.splice(i, 1);
|
|
1853
|
+
}
|
|
1854
|
+
if (namespace === void 0) {
|
|
1855
|
+
held.clear();
|
|
1856
|
+
faults.clear();
|
|
1857
|
+
own.clear();
|
|
1858
|
+
} else {
|
|
1859
|
+
held.delete(namespace);
|
|
1860
|
+
faults.delete(namespace);
|
|
1861
|
+
own.delete(namespace);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
};
|
|
1865
|
+
return hub;
|
|
1866
|
+
};
|
|
1867
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1868
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1869
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1870
|
+
var parseEndpoint = (value) => {
|
|
1871
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1872
|
+
return "each endpoint needs a url";
|
|
1873
|
+
try {
|
|
1874
|
+
new URL(value.url);
|
|
1875
|
+
} catch {
|
|
1876
|
+
return `not a URL: ${value.url}`;
|
|
1877
|
+
}
|
|
1878
|
+
const endpoint = { url: value.url };
|
|
1879
|
+
if (typeof value.id === "string")
|
|
1880
|
+
endpoint.id = value.id;
|
|
1881
|
+
if (typeof value.secret === "string")
|
|
1882
|
+
endpoint.secret = value.secret;
|
|
1883
|
+
if (typeof value.signUrl === "string")
|
|
1884
|
+
endpoint.signUrl = value.signUrl;
|
|
1885
|
+
const events = value.events ?? value.enabledEvents;
|
|
1886
|
+
if (Array.isArray(events))
|
|
1887
|
+
endpoint.events = events.map(String);
|
|
1888
|
+
if (isRecord3(value.tags)) {
|
|
1889
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1890
|
+
}
|
|
1891
|
+
if (typeof value.account === "string")
|
|
1892
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1893
|
+
if (isRecord3(value.headers)) {
|
|
1894
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1895
|
+
}
|
|
1896
|
+
return endpoint;
|
|
1897
|
+
};
|
|
1898
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1899
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1900
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1901
|
+
const type = url.searchParams.get("type");
|
|
1902
|
+
return type === null || d.type === type;
|
|
1903
|
+
})
|
|
1904
|
+
}),
|
|
1905
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1906
|
+
const type = url.searchParams.get("type");
|
|
1907
|
+
return json2(200, {
|
|
1908
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1909
|
+
});
|
|
1910
|
+
},
|
|
1911
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1912
|
+
const replayed = await hub.replay(params.id);
|
|
1913
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1914
|
+
},
|
|
1915
|
+
"POST /webhooks/flush": async () => {
|
|
1916
|
+
await hub.flush();
|
|
1917
|
+
return json2(200, { status: "ok" });
|
|
1918
|
+
},
|
|
1919
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1920
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1921
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1922
|
+
}
|
|
1923
|
+
const fault = { mode: body.mode };
|
|
1924
|
+
if (typeof body.count === "number")
|
|
1925
|
+
fault.count = body.count;
|
|
1926
|
+
hub.fault(namespace, fault);
|
|
1927
|
+
return json2(201, { namespace, ...fault });
|
|
1928
|
+
},
|
|
1929
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1930
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1931
|
+
...rest,
|
|
1932
|
+
secret: secret ? "(set)" : null
|
|
1933
|
+
}))
|
|
1934
|
+
}),
|
|
1935
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1936
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1937
|
+
if (!Array.isArray(list))
|
|
1938
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1939
|
+
const parsed = [];
|
|
1940
|
+
for (const each of list) {
|
|
1941
|
+
const endpoint = parseEndpoint(each);
|
|
1942
|
+
if (typeof endpoint === "string")
|
|
1943
|
+
return adminError2(400, endpoint);
|
|
1944
|
+
parsed.push(endpoint);
|
|
1945
|
+
}
|
|
1946
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1947
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1948
|
+
},
|
|
1949
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1950
|
+
hub.setEndpoints(namespace, []);
|
|
1951
|
+
return json2(200, { status: "ok" });
|
|
1952
|
+
}
|
|
1953
|
+
});
|
|
1954
|
+
var parsePayload = (message) => {
|
|
1955
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1956
|
+
try {
|
|
1957
|
+
return JSON.parse(message.body);
|
|
1958
|
+
} catch {
|
|
1959
|
+
return message.body;
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1963
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1964
|
+
}
|
|
1965
|
+
return message.body;
|
|
1966
|
+
};
|
|
1967
|
+
|
|
1968
|
+
// ../core/dist/runtime.js
|
|
1969
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1970
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1971
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1972
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1973
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1974
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1975
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1976
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1977
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1978
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1979
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1980
|
+
if (!previous || previous.length === 0)
|
|
1981
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1982
|
+
const result = new Array(fresh.length);
|
|
1983
|
+
let unchanged = fresh.length === previous.length;
|
|
1984
|
+
let oldIndex = 0;
|
|
1985
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1986
|
+
const row = fresh[index];
|
|
1987
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1988
|
+
oldIndex++;
|
|
1989
|
+
}
|
|
1990
|
+
const old = previous[oldIndex];
|
|
1991
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1992
|
+
if (result[index] !== previous[index])
|
|
1993
|
+
unchanged = false;
|
|
1994
|
+
}
|
|
1995
|
+
return unchanged ? previous : result;
|
|
1996
|
+
};
|
|
1997
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1998
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1999
|
+
var DroppedConnectionError = class extends TypeError {
|
|
2000
|
+
code = "MOCKINGBIRD_DROP";
|
|
2001
|
+
constructor() {
|
|
2002
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
2003
|
+
this.name = "TypeError";
|
|
2004
|
+
}
|
|
2005
|
+
};
|
|
2006
|
+
var operationMatcher = (document2) => {
|
|
2007
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
2008
|
+
operationId: operation.operationId,
|
|
2009
|
+
method: operation.method.toUpperCase(),
|
|
2010
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
2011
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
2012
|
+
})).sort((a, b) => a.params - b.params);
|
|
2013
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
2014
|
+
};
|
|
2015
|
+
var createRuntime = (options) => {
|
|
2016
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2017
|
+
const clock = options.clock ?? createClock();
|
|
2018
|
+
const rng = createRng(options.seed ?? 0);
|
|
2019
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
2020
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
2021
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
2022
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
2023
|
+
const metrics = createMetrics();
|
|
2024
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
2025
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
2026
|
+
const instances = /* @__PURE__ */ new Map();
|
|
2027
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
2028
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
2029
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
2030
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
2031
|
+
const captured = /* @__PURE__ */ new Map();
|
|
2032
|
+
const credentials = createCredentialRegistry();
|
|
2033
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
2034
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
2035
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
2036
|
+
const existing = instances.get(key);
|
|
2037
|
+
if (existing)
|
|
2038
|
+
return existing;
|
|
2039
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
2040
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
2041
|
+
}
|
|
2042
|
+
const created = options.create({
|
|
2043
|
+
namespace: storageNamespace(key),
|
|
2044
|
+
publicNamespace,
|
|
2045
|
+
sqlite,
|
|
2046
|
+
clock,
|
|
2047
|
+
rng: isolatedRng ?? rng
|
|
2048
|
+
});
|
|
2049
|
+
instances.set(key, created);
|
|
2050
|
+
publicNamespaces.add(publicNamespace);
|
|
2051
|
+
if (isolatedRng)
|
|
2052
|
+
branchRngs.set(key, isolatedRng);
|
|
2053
|
+
return created;
|
|
2054
|
+
};
|
|
2055
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
2056
|
+
const capture = (storage) => {
|
|
2057
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
2058
|
+
const previous = captured.get(storage);
|
|
2059
|
+
const snapshot2 = {
|
|
2060
|
+
namespace: fresh.namespace,
|
|
2061
|
+
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),
|
|
2062
|
+
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)
|
|
2063
|
+
};
|
|
2064
|
+
Object.freeze(snapshot2.records);
|
|
2065
|
+
Object.freeze(snapshot2.sequences);
|
|
2066
|
+
Object.freeze(snapshot2);
|
|
2067
|
+
captured.set(storage, snapshot2);
|
|
2068
|
+
return Object.freeze({
|
|
2069
|
+
snapshot: snapshot2,
|
|
2070
|
+
clock: Object.freeze(clock.state()),
|
|
2071
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
2072
|
+
});
|
|
2073
|
+
};
|
|
2074
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
2075
|
+
let found = timelines.get(name);
|
|
2076
|
+
if (found)
|
|
2077
|
+
return found;
|
|
2078
|
+
instance(name);
|
|
2079
|
+
found = new Timeline({
|
|
2080
|
+
now: clock.now,
|
|
2081
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
2082
|
+
});
|
|
2083
|
+
found.commit(capture(name));
|
|
2084
|
+
timelines.set(name, found);
|
|
2085
|
+
return found;
|
|
2086
|
+
};
|
|
2087
|
+
const physicalBranch = (namespace, branch2) => {
|
|
2088
|
+
if (branch2 === "main")
|
|
2089
|
+
return namespace;
|
|
2090
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
2091
|
+
const existing = branchStorage.get(mapKey);
|
|
2092
|
+
if (existing)
|
|
2093
|
+
return existing;
|
|
2094
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
2095
|
+
branchStorage.set(mapKey, key);
|
|
2096
|
+
return key;
|
|
2097
|
+
};
|
|
2098
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
2099
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
2100
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
2101
|
+
const history = timeline(namespace);
|
|
2102
|
+
if (branch2 === "main") {
|
|
2103
|
+
if (at !== void 0) {
|
|
2104
|
+
const point = history.checkout("main", at);
|
|
2105
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
2106
|
+
captured.set(namespace, point.value.snapshot);
|
|
2107
|
+
rng.setState(point.value.rngState);
|
|
2108
|
+
clock.set(point.value.clock.now);
|
|
2109
|
+
if (point.value.clock.frozen)
|
|
2110
|
+
clock.freeze();
|
|
2111
|
+
else
|
|
2112
|
+
clock.unfreeze();
|
|
2113
|
+
}
|
|
2114
|
+
return namespace;
|
|
2115
|
+
}
|
|
2116
|
+
const storage = physicalBranch(namespace, branch2);
|
|
2117
|
+
if (!history.hasBranch(branch2)) {
|
|
2118
|
+
if (at === void 0)
|
|
2119
|
+
history.commit(capture(namespace));
|
|
2120
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
2121
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2122
|
+
if (point)
|
|
2123
|
+
branchRng.setState(point.value.rngState);
|
|
2124
|
+
instanceFor(storage, namespace, branchRng);
|
|
2125
|
+
if (point)
|
|
2126
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2127
|
+
if (point)
|
|
2128
|
+
captured.set(storage, point.value.snapshot);
|
|
2129
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
2130
|
+
const point = history.checkout(branch2, at);
|
|
2131
|
+
if (!instances.has(storage)) {
|
|
2132
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2133
|
+
branchRng.setState(point.value.rngState);
|
|
2134
|
+
instanceFor(storage, namespace, branchRng);
|
|
2135
|
+
}
|
|
2136
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
2137
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2138
|
+
captured.set(storage, point.value.snapshot);
|
|
2139
|
+
} else {
|
|
2140
|
+
if (!instances.has(storage)) {
|
|
2141
|
+
const point = history.head(branch2);
|
|
2142
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2143
|
+
if (point)
|
|
2144
|
+
branchRng.setState(point.value.rngState);
|
|
2145
|
+
instanceFor(storage, namespace, branchRng);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
return storage;
|
|
2149
|
+
};
|
|
2150
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
2151
|
+
const storage = ensureBranch(namespace, branch2);
|
|
2152
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
2153
|
+
};
|
|
2154
|
+
const branch = (name, branchOptions = {}) => {
|
|
2155
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2156
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
2157
|
+
const head = timeline(namespace).head(name);
|
|
2158
|
+
if (!head)
|
|
2159
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
2160
|
+
return head;
|
|
2161
|
+
};
|
|
2162
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
2163
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2164
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
2165
|
+
const history = timeline(namespace);
|
|
2166
|
+
const point = history.checkout(branchName, checkpointId);
|
|
2167
|
+
const storage = ensureBranch(namespace, branchName);
|
|
2168
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2169
|
+
captured.set(storage, point.value.snapshot);
|
|
2170
|
+
clock.set(point.value.clock.now);
|
|
2171
|
+
if (point.value.clock.frozen)
|
|
2172
|
+
clock.freeze();
|
|
2173
|
+
else
|
|
2174
|
+
clock.unfreeze();
|
|
2175
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
2176
|
+
};
|
|
2177
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
2178
|
+
if (name === "*") {
|
|
2179
|
+
options.webhooks?.clear();
|
|
2180
|
+
for (const each of instances.values())
|
|
2181
|
+
await each.reset();
|
|
2182
|
+
timelines.clear();
|
|
2183
|
+
branchStorage.clear();
|
|
2184
|
+
branchRngs.clear();
|
|
2185
|
+
captured.clear();
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
options.webhooks?.clear(name);
|
|
2189
|
+
const target = instances.get(name);
|
|
2190
|
+
if (target)
|
|
2191
|
+
await target.reset();
|
|
2192
|
+
else
|
|
2193
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
2194
|
+
for (const [mapping, storage] of branchStorage) {
|
|
2195
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
2196
|
+
continue;
|
|
2197
|
+
const branchInstance = instances.get(storage);
|
|
2198
|
+
if (branchInstance)
|
|
2199
|
+
await branchInstance.reset();
|
|
2200
|
+
else
|
|
2201
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
2202
|
+
branchStorage.delete(mapping);
|
|
2203
|
+
branchRngs.delete(storage);
|
|
2204
|
+
captured.delete(storage);
|
|
2205
|
+
}
|
|
2206
|
+
timelines.delete(name);
|
|
2207
|
+
captured.delete(name);
|
|
2208
|
+
};
|
|
2209
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
2210
|
+
return checkpoint(name, "main").value.snapshot;
|
|
2211
|
+
};
|
|
2212
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
2213
|
+
instance(name);
|
|
2214
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
2215
|
+
captured.set(name, from);
|
|
2216
|
+
const history = timelines.get(name);
|
|
2217
|
+
if (history)
|
|
2218
|
+
history.commit(capture(name), { branch: "main" });
|
|
2219
|
+
else
|
|
2220
|
+
timeline(name);
|
|
2221
|
+
};
|
|
2222
|
+
const runtime = {
|
|
2223
|
+
name: options.name,
|
|
2224
|
+
sqlite,
|
|
2225
|
+
clock,
|
|
2226
|
+
faults,
|
|
2227
|
+
metrics,
|
|
2228
|
+
journal,
|
|
2229
|
+
rng,
|
|
2230
|
+
credentials,
|
|
2231
|
+
webhooks: options.webhooks,
|
|
2232
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
2233
|
+
const preset = options.presets?.[name];
|
|
2234
|
+
if (!preset)
|
|
2235
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
2236
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
2237
|
+
namespace,
|
|
2238
|
+
...rule,
|
|
2239
|
+
...overrides,
|
|
2240
|
+
preset: name,
|
|
2241
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
2242
|
+
}));
|
|
2243
|
+
if (preset.webhook && options.webhooks) {
|
|
2244
|
+
options.webhooks.fault(namespace, {
|
|
2245
|
+
...preset.webhook,
|
|
2246
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
2247
|
+
});
|
|
2248
|
+
}
|
|
2249
|
+
return added;
|
|
2250
|
+
},
|
|
2251
|
+
instance,
|
|
2252
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
2253
|
+
reset,
|
|
2254
|
+
snapshot,
|
|
2255
|
+
restore,
|
|
2256
|
+
checkpoint,
|
|
2257
|
+
branch,
|
|
2258
|
+
checkout,
|
|
2259
|
+
timeline,
|
|
2260
|
+
fetch: async (incoming) => {
|
|
2261
|
+
let request = incoming;
|
|
2262
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
2263
|
+
if (prefixed) {
|
|
2264
|
+
const url2 = new URL(request.url);
|
|
2265
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
2266
|
+
const headers = new Headers(request.headers);
|
|
2267
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
2268
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
2269
|
+
}
|
|
2270
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
2271
|
+
request = new Request(url2, {
|
|
2272
|
+
method: request.method,
|
|
2273
|
+
headers,
|
|
2274
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
2275
|
+
signal: request.signal
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
let namespace = control.namespaceOf(request);
|
|
2279
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
2280
|
+
const credential = options.credential(request);
|
|
2281
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
2282
|
+
if (mapped !== void 0)
|
|
2283
|
+
namespace = mapped;
|
|
2284
|
+
}
|
|
2285
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
2286
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
2287
|
+
const stamp = (response2) => {
|
|
2288
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
2289
|
+
try {
|
|
2290
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2291
|
+
return response2;
|
|
2292
|
+
} catch {
|
|
2293
|
+
const copy = new Response(response2.body, response2);
|
|
2294
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2295
|
+
return copy;
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
2298
|
+
const handled = await control.handle(request);
|
|
2299
|
+
if (handled)
|
|
2300
|
+
return stamp(handled);
|
|
2301
|
+
const started = monotonicNow();
|
|
2302
|
+
const url = new URL(request.url);
|
|
2303
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
2304
|
+
const log = (status, faultId, response2) => {
|
|
2305
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
2306
|
+
const entry = {
|
|
2307
|
+
service: options.name,
|
|
2308
|
+
namespace,
|
|
2309
|
+
operationId,
|
|
2310
|
+
method: request.method,
|
|
2311
|
+
path: url.pathname,
|
|
2312
|
+
status,
|
|
2313
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
2314
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
2315
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
2316
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
2317
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
2318
|
+
};
|
|
2319
|
+
metrics.record(entry);
|
|
2320
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2321
|
+
options.onLog?.(entry);
|
|
2322
|
+
};
|
|
2323
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2324
|
+
log(400);
|
|
2325
|
+
return stamp(new Response(JSON.stringify({
|
|
2326
|
+
error: {
|
|
2327
|
+
type: "mockingbird_admin",
|
|
2328
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2329
|
+
}
|
|
2330
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2331
|
+
}
|
|
2332
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2333
|
+
log(400);
|
|
2334
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2335
|
+
}
|
|
2336
|
+
let storage;
|
|
2337
|
+
try {
|
|
2338
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2339
|
+
const point = timeline(namespace).get(at);
|
|
2340
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2341
|
+
let viewRng = branchRngs.get(storage);
|
|
2342
|
+
if (!viewRng) {
|
|
2343
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2344
|
+
instanceFor(storage, namespace, viewRng);
|
|
2345
|
+
}
|
|
2346
|
+
viewRng.setState(point.value.rngState);
|
|
2347
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2348
|
+
captured.set(storage, point.value.snapshot);
|
|
2349
|
+
} else {
|
|
2350
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2351
|
+
}
|
|
2352
|
+
} catch (error2) {
|
|
2353
|
+
log(409);
|
|
2354
|
+
return stamp(adminFail(409, error2 instanceof Error ? error2.message : String(error2)));
|
|
2355
|
+
}
|
|
2356
|
+
const hits = await faults.take({
|
|
2357
|
+
operationId,
|
|
2358
|
+
method: request.method,
|
|
2359
|
+
path: url.pathname,
|
|
2360
|
+
namespace
|
|
2361
|
+
});
|
|
2362
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2363
|
+
if (final?.drop) {
|
|
2364
|
+
log(0, final.id);
|
|
2365
|
+
throw new DroppedConnectionError();
|
|
2366
|
+
}
|
|
2367
|
+
if (final?.response) {
|
|
2368
|
+
log(final.response.status, final.id);
|
|
2369
|
+
return stamp(final.response);
|
|
2370
|
+
}
|
|
2371
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2372
|
+
if (fired.length > 0)
|
|
2373
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2374
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2375
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2376
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2377
|
+
response = mutableResponse(response);
|
|
2378
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2379
|
+
}
|
|
2380
|
+
if (selectedBranch !== "main") {
|
|
2381
|
+
response = mutableResponse(response);
|
|
2382
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2383
|
+
}
|
|
2384
|
+
if (at !== void 0) {
|
|
2385
|
+
response = mutableResponse(response);
|
|
2386
|
+
response.headers.set(AT_HEADER, at);
|
|
2387
|
+
}
|
|
2388
|
+
log(response.status, fired[0]?.id, response);
|
|
2389
|
+
return stamp(response);
|
|
2390
|
+
}
|
|
2391
|
+
};
|
|
2392
|
+
const control = createControlPlane({
|
|
2393
|
+
name: options.name,
|
|
2394
|
+
startedAt: wallNow(),
|
|
2395
|
+
wallNow,
|
|
2396
|
+
clock,
|
|
2397
|
+
faults,
|
|
2398
|
+
metrics,
|
|
2399
|
+
journal,
|
|
2400
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2401
|
+
namespaces: runtime.namespaces,
|
|
2402
|
+
reset,
|
|
2403
|
+
timeTravel: {
|
|
2404
|
+
checkpoint: (name, branchName) => {
|
|
2405
|
+
const point = checkpoint(name, branchName);
|
|
2406
|
+
return {
|
|
2407
|
+
id: point.id,
|
|
2408
|
+
branch: point.branch,
|
|
2409
|
+
parent: point.parent,
|
|
2410
|
+
at: point.at,
|
|
2411
|
+
records: point.value.snapshot.records.length
|
|
2412
|
+
};
|
|
2413
|
+
},
|
|
2414
|
+
branch: (branchName, branchOptions) => {
|
|
2415
|
+
const point = branch(branchName, branchOptions);
|
|
2416
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2417
|
+
},
|
|
2418
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2419
|
+
retain: (name, checkpointId) => {
|
|
2420
|
+
timeline(name).retain(checkpointId);
|
|
2421
|
+
},
|
|
2422
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2423
|
+
inspect: (name) => {
|
|
2424
|
+
const history = timeline(name);
|
|
2425
|
+
return {
|
|
2426
|
+
branches: history.branches(),
|
|
2427
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2428
|
+
id,
|
|
2429
|
+
branch: branchName,
|
|
2430
|
+
parent,
|
|
2431
|
+
at
|
|
2432
|
+
}))
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
},
|
|
2436
|
+
describe: options.describe ?? (() => ({})),
|
|
2437
|
+
...options.presets ? {
|
|
2438
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2439
|
+
} : {},
|
|
2440
|
+
routes: {
|
|
2441
|
+
...credentialRoutes(credentials),
|
|
2442
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2443
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2444
|
+
...options.admin?.(runtime) ?? {}
|
|
2445
|
+
},
|
|
2446
|
+
adminKey: options.adminKey
|
|
2447
|
+
});
|
|
2448
|
+
return runtime;
|
|
2449
|
+
};
|
|
2450
|
+
var mutableResponse = (response) => {
|
|
2451
|
+
try {
|
|
2452
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2453
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2454
|
+
return response;
|
|
2455
|
+
} catch {
|
|
2456
|
+
return new Response(response.body, response);
|
|
2457
|
+
}
|
|
2458
|
+
};
|
|
2459
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2460
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2461
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2462
|
+
var credentialRoutes = (registry) => ({
|
|
2463
|
+
"GET /credentials": () => adminJson(200, {
|
|
2464
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2465
|
+
credential: maskCredential(credential),
|
|
2466
|
+
namespace
|
|
2467
|
+
}))
|
|
2468
|
+
}),
|
|
2469
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2470
|
+
const pairs = [];
|
|
2471
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2472
|
+
if (Array.isArray(list)) {
|
|
2473
|
+
for (const each of list) {
|
|
2474
|
+
if (typeof each === "string")
|
|
2475
|
+
pairs.push([each, namespace]);
|
|
2476
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2477
|
+
pairs.push([
|
|
2478
|
+
each.credential,
|
|
2479
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2480
|
+
]);
|
|
2481
|
+
} else
|
|
2482
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2483
|
+
}
|
|
2484
|
+
} else if (isObject(list)) {
|
|
2485
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2486
|
+
if (typeof target !== "string")
|
|
2487
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2488
|
+
pairs.push([credential, target]);
|
|
2489
|
+
}
|
|
2490
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2491
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2492
|
+
} else {
|
|
2493
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2494
|
+
}
|
|
2495
|
+
for (const [credential, target] of pairs) {
|
|
2496
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2497
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2498
|
+
registry.set(credential, target);
|
|
2499
|
+
}
|
|
2500
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2501
|
+
},
|
|
2502
|
+
"DELETE /credentials": ({ url }) => {
|
|
2503
|
+
const credential = url.searchParams.get("credential");
|
|
2504
|
+
if (credential === null)
|
|
2505
|
+
registry.clear();
|
|
2506
|
+
else
|
|
2507
|
+
registry.remove(credential);
|
|
2508
|
+
return adminJson(200, { status: "ok" });
|
|
2509
|
+
}
|
|
2510
|
+
});
|
|
2511
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2512
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2513
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2514
|
+
}),
|
|
2515
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2516
|
+
const name = params.name;
|
|
2517
|
+
if (!presets[name])
|
|
2518
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2519
|
+
const overrides = isObject(body) ? body : {};
|
|
2520
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2521
|
+
}
|
|
2522
|
+
});
|
|
2523
|
+
|
|
2524
|
+
// ../core/dist/validation.js
|
|
2525
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2526
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2527
|
+
if (!requestBody)
|
|
2528
|
+
return [];
|
|
2529
|
+
const resolved = deref(context.document, requestBody);
|
|
2530
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2531
|
+
if (!schema)
|
|
2532
|
+
return [];
|
|
2533
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2534
|
+
if (context.body.kind === "invalid") {
|
|
2535
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2536
|
+
}
|
|
2537
|
+
if (value === void 0) {
|
|
2538
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2539
|
+
}
|
|
2540
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2541
|
+
};
|
|
2542
|
+
|
|
2543
|
+
// src/generated/openapi.ts
|
|
2544
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Pharmetika provider portal API (Mockingbird subset)","description":"Stateful mock subset of the Pharmetika compounding-pharmacy provider portal: clinic and\\npatient lookup, patient create, medication-order validate / EPCS prepare / submit / lookup,\\nthe v7 cancel, and the medication-template catalog. Hand-authored from the consumer's\\nadapters (the vendor publishes no spec). Every response carries Pharmetika's \`success\`\\nflag: an HTTP 200 with \`success: 0\` is a failure, and the mock produces it.\\n","version":"5","x-mockingbird-upstream":{"note":"Hand-authored from the wire shapes our consumer reads and writes (pharmetika-fulfillment.adapter.ts, pharmetika-live.client.ts, and the adapter spec's recorded bodies)."}},"servers":[{"url":"https://testreviverx.pharmetika.com"}],"security":[{"pmkToken":[]}],"paths":{"/api/v5/provider_portal/clinic/clinic_list":{"get":{"operationId":"ListClinics","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The provider's clinics","content":{"application/json":{"schema":{"type":"object","required":["success","data"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Clinic"}}}}}}},"401":{"$ref":"#/components/responses/Unauthenticated"}}}},"/api/v5/provider_portal/provider/patient_list":{"get":{"operationId":"ListPatients","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The provider's patient roster","content":{"application/json":{"schema":{"type":"object","required":["success","data"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"data":{"type":"array","items":{"$ref":"#/components/schemas/PatientListEntry"}}}}}}},"401":{"$ref":"#/components/responses/Unauthenticated"}}}},"/api/v5/provider_portal/patient/create_new":{"post":{"operationId":"CreatePatient","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FhirPatient"}}}},"responses":{"200":{"description":"Created (\`success: true\`, \`patient_id\`), or a possible duplicate (\`success: 0\` with \`duplicate_entries\`), or a validation failure (\`success: 0\` with \`messages\`).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreatePatientResponse"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"}}}},"/api/v5/provider_portal/medication_order/id/{orderId}/validate":{"parameters":[{"$ref":"#/components/parameters/NewOrderId"}],"put":{"operationId":"ValidateMedicationOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MedicationOrderBody"}}}},"responses":{"200":{"description":"Validation result. \`success: 1\` with the pharmacy's view of each entry (including \`controlled\` / \`control_level\`), or \`success: 0\` with \`messages\`.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateResponse"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"},"422":{"$ref":"#/components/responses/Rejected"}}}},"/api/v5/provider_portal/medication_order/id/{orderId}":{"put":{"operationId":"PrepareMedicationOrder","parameters":[{"$ref":"#/components/parameters/NewOrderId"}],"description":"EPCS prepare for controlled substances. The order parks as \`pending_prescriber_approval\` and is never submitted: the prescriber signs it in the portal (an admin transition to \`signed\`).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MedicationOrderBody"}}}},"responses":{"200":{"description":"Prepared, or \`success: 0\` with \`messages\`","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderAck"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"},"422":{"$ref":"#/components/responses/Rejected"}}},"get":{"operationId":"GetMedicationOrder","parameters":[{"$ref":"#/components/parameters/OrderId"}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The order and its workflow status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderLookup"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"},"404":{"$ref":"#/components/responses/Rejected"}}}},"/api/v5/provider_portal/medication_order/id/{orderId}/submit":{"parameters":[{"$ref":"#/components/parameters/NewOrderId"}],"put":{"operationId":"SubmitMedicationOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MedicationOrderBody"}}}},"responses":{"200":{"description":"Submitted (\`success: 1\`), or \`success: 0\` with \`messages\` (validation, a controlled substance, or an identifier already submitted with different contents).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderAck"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"},"409":{"$ref":"#/components/responses/Rejected"},"422":{"$ref":"#/components/responses/Rejected"}}}},"/api/v7/provider_portal/medication_order/entry/cancel":{"put":{"operationId":"CancelMedicationOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["prescriber_order_number"],"properties":{"note":{"type":"string","maxLength":500},"prescriber_order_number":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"medication_order","missing":"0190c6a4-0000-7000-8000-000000000000"}}}}}}},"responses":{"200":{"description":"Cancelled (\`success: 1\`), or \`success: 0\` with \`messages\`","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Envelope"}}}},"401":{"$ref":"#/components/responses/Unauthenticated"}}}},"/api/pharmetika/provider_access/profile/medication_templates":{"get":{"operationId":"ListMedicationTemplates","description":"Our catalog client sends \`x-pmk-authentication-token\`, else Basic \`PHARMETIKA_USERNAME:PASSWORD\`, else nothing; the mock accepts all three unless \`anonymousCatalog\` is off.","security":[{"pmkToken":[]},{"basicAuth":[]},{}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Medication templates","content":{"application/json":{"schema":{"type":"object","required":["success","data"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"data":{"type":"array","items":{"$ref":"#/components/schemas/MedicationTemplate"}}}}}}},"401":{"$ref":"#/components/responses/Unauthenticated"}}}}},"components":{"securitySchemes":{"pmkToken":{"type":"apiKey","in":"header","name":"x-pmk-authentication-token"},"basicAuth":{"type":"http","scheme":"basic"}},"parameters":{"NewOrderId":{"name":"orderId","in":"path","required":true,"description":"Our UUIDv7 \`medication_order_identifier\`, chosen by the client.","schema":{"type":"string","pattern":"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},"OrderId":{"name":"orderId","in":"path","required":true,"description":"Our UUIDv7 \`medication_order_identifier\`.","schema":{"type":"string","pattern":"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$","x-mockingbird-resource-ref":{"type":"medication_order","missing":"0190c6a4-0000-7000-8000-000000000000"}}}},"responses":{"Unauthenticated":{"description":"Missing or rejected credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Envelope"}}}},"Rejected":{"description":"A \`success: 0\` body with \`messages\`","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Envelope"}}}}},"schemas":{"Success":{"description":"Pharmetika's success flag. Only \`true\` or \`1\` means success; \`0\`, \`false\` and (under the \`success_string\` preset) \`\\"1\\"\` do not.","oneOf":[{"type":"integer","enum":[0,1]},{"type":"boolean"},{"type":"string"}]},"Message":{"type":"object","required":["message","type"],"properties":{"message":{"type":"string"},"type":{"type":"string","enum":["info","warning","error"]}}},"Envelope":{"type":"object","required":["success","messages"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/Message"}}}},"Clinic":{"type":"object","required":["identifier","data"],"properties":{"identifier":{"type":"string","x-mockingbird-resource":{"type":"clinic","identity":true}},"data":{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}}},"PatientListEntry":{"type":"object","required":["patient_id","demographics"],"properties":{"patient_id":{"type":"integer"},"demographics":{"type":"object","required":["first_name","last_name","DOB"],"properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"DOB":{"type":"string"},"email":{"type":"string"},"phone_primary":{"type":"string"},"line_1":{"type":"string"},"postal_code":{"type":"string"}}}}},"FhirPatient":{"type":"object","required":["resourceType","birthDate","gender","name","clinic_identifier"],"properties":{"active":{"type":"boolean"},"resourceType":{"type":"string","enum":["Patient"]},"birthDate":{"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","other","unknown"]},"name":{"type":"array","minItems":1,"maxItems":2,"items":{"type":"object","required":["family","given"],"properties":{"family":{"type":"string","minLength":1,"maxLength":40},"given":{"type":"array","minItems":1,"maxItems":3,"items":{"type":"string","maxLength":40}},"use":{"type":"string"}}}},"address":{"type":"array","maxItems":2,"items":{"type":"object","properties":{"line":{"type":"array","maxItems":2,"items":{"type":"string","maxLength":80}},"city":{"type":"string","maxLength":40},"state":{"type":"string","maxLength":2},"postalCode":{"type":"string","maxLength":10},"country":{"type":"string","maxLength":2},"use":{"type":"string"}}}},"telecom":{"type":"array","maxItems":3,"items":{"type":"object","required":["system","value"],"properties":{"system":{"type":"string","enum":["email","phone"]},"value":{"type":"string","maxLength":120},"use":{"type":"string"}}}},"communication":{"type":"array","items":{"type":"object"}},"identifier":{"type":"array","items":{"type":"object"}},"extension":{"type":"array","items":{"type":"object"}},"meta":{"type":"object"},"species":{"type":"string"},"clinic_identifier":{"type":"string","x-mockingbird-resource-ref":{"type":"clinic","missing":"clinic-missing"}},"practitioner_identifier":{"type":"string","maxLength":64}}},"CreatePatientResponse":{"type":"object","required":["success","messages"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"patient_id":{"type":"integer"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/Message"}},"duplicate_entry_count":{"type":"integer"},"duplicate_entries":{"type":"array","items":{"$ref":"#/components/schemas/PatientListEntry"}}}},"MedicationRequest":{"type":"object","required":["product_identification","quantity_authorized","sig"],"properties":{"product_identification":{"type":"object","required":["product_identifier"],"properties":{"product_identifier":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"product","missing":"PMK-MISSING"}}}},"medication":{"type":"string","maxLength":120},"dose":{"type":"string","maxLength":60},"quantity_authorized":{"type":"number","exclusiveMinimum":0,"maximum":1000},"days_supply":{"type":["integer","null"],"minimum":1,"maximum":365},"unit_of_measure":{"type":"string","maxLength":20},"refills_authorized":{"type":"integer","minimum":0,"maximum":12},"sig":{"type":"string","maxLength":500},"reason_for_compounding":{"type":["object","null"]},"authorization_for_emergency_dispensing":{"type":"boolean"},"authorization_for_emergency_dispensing_date_written":{"type":["string","null"]},"do_not_refill":{"type":"boolean"},"do_not_fill":{"type":"boolean"},"patient_contact_requested":{"type":"boolean"},"date_issued":{"type":"string","maxLength":40},"medication_order_entry_identifier":{"type":"string","maxLength":64},"controlled":{"type":"integer"},"control_level":{"type":"integer"},"is_reauthorization":{"type":"boolean"}}},"MedicationOrderBody":{"type":"object","required":["clinic_identifier","medication_order_identifier","patient","medication_requests"],"properties":{"clinic_identifier":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"clinic","missing":"clinic-missing"}},"practitioner_identifier":{"type":"string","maxLength":64},"prepared_by":{"type":["string","null"],"maxLength":64},"medication_order_identifier":{"type":"string","pattern":"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},"patient":{"type":"object","required":["identification"],"properties":{"identification":{"type":"object","required":["patient_id"],"properties":{"patient_id":{"type":"integer","minimum":1}}},"name":{"type":"object","properties":{"last_name":{"type":"string","maxLength":40},"first_name":{"type":"string","maxLength":40},"suffix":{"type":["string","null"]}}},"gender":{"type":"string","enum":["M","F","O","U"]},"DOB":{"type":"string","maxLength":10},"species":{"type":"string"},"address":{"type":"object","properties":{"line_1":{"type":"string","maxLength":80},"line_2":{"type":"string","maxLength":80},"city":{"type":"string","maxLength":40},"state":{"type":"string","maxLength":2},"postal_code":{"type":"string","maxLength":10}}},"email":{"type":"string","maxLength":120},"phone_primary":{"type":"string","maxLength":20}}},"medication_requests":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/MedicationRequest"}},"ancillary_order_data":{"type":"object","properties":{"patient_handoff_method":{"type":"string"},"patient_handoff_method_text":{"type":"string"},"priority":{"type":"string"},"medication_order_status":{"type":"object"},"documents":{"type":"array","items":{"type":"object"}}}}}},"ValidatedEntry":{"type":"object","required":["product_identification","medication_order_entry_identifier","controlled","control_level"],"properties":{"product_identification":{"type":"object","properties":{"product_identifier":{"type":"string"}}},"medication":{"type":"string"},"dose":{"type":"string"},"quantity_authorized":{"type":"number"},"sig":{"type":"string"},"medication_order_entry_identifier":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"controlled":{"type":"integer"},"control_level":{"type":"integer"}}},"ValidateResponse":{"type":"object","required":["success","messages"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/Message"}},"data":{"type":"object","required":["controlled_substance_list_count","medication_list"],"properties":{"controlled_substance_list_count":{"type":["integer","string"]},"medication_list":{"type":"array","items":{"$ref":"#/components/schemas/ValidatedEntry"}}}}}},"OrderAck":{"type":"object","required":["success","messages"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/Message"}},"data":{"type":"object","required":["medication_order_identifier","order_status"],"properties":{"medication_order_identifier":{"type":"string","x-mockingbird-resource":{"type":"medication_order","identity":true}},"order_status":{"type":"string"}}}}},"OrderStatus":{"type":"object","required":["workflow_status","tracking_id"],"properties":{"workflow_status":{"type":"string"},"tracking_id":{"type":["string","null"]}}},"OrderLookup":{"type":"object","required":["success","messages","data"],"properties":{"success":{"$ref":"#/components/schemas/Success"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/Message"}},"data":{"type":"object","required":["medication_order_identifier","order_status","data"],"properties":{"medication_order_identifier":{"type":"string"},"electronic_prescription_order_number":{"type":"string"},"order_status":{"type":"string"},"data":{"type":"object","required":["order_status","clinic_identifier","patient_id","ancillary_order_data"],"properties":{"order_status":{"type":"string"},"clinic_identifier":{"type":"string"},"patient_id":{"type":"integer"},"product_identifiers":{"type":"array","items":{"type":"string"}},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"ancillary_order_data":{"type":"object","required":["medication_order_status"],"properties":{"medication_order_status":{"$ref":"#/components/schemas/OrderStatus"}}}}}}}}},"MedicationTemplate":{"type":"object","required":["template_identifier","medication_display_name","map_dose_to_product","qty_options","default_sigs","available_states"],"properties":{"template_identifier":{"type":"string"},"medication_display_name":{"type":"string"},"description":{"type":["string","null"]},"map_dose_to_product":{"type":"object","additionalProperties":{"type":"string","x-mockingbird-resource":{"type":"product","identity":true}}},"qty_options":{"type":"array","items":{"type":"number"}},"default_sigs":{"type":"array","items":{"type":"string"}},"available_states":{"type":"array","items":{"type":"string"}},"controlled":{"type":"integer"}}}}}}`);
|
|
2545
|
+
var operationIds = ["ListClinics", "ListPatients", "CreatePatient", "ValidateMedicationOrder", "GetMedicationOrder", "PrepareMedicationOrder", "SubmitMedicationOrder", "CancelMedicationOrder", "ListMedicationTemplates"];
|
|
2546
|
+
var supportedOperationIds = ["ListClinics", "ListPatients", "CreatePatient", "ValidateMedicationOrder", "GetMedicationOrder", "PrepareMedicationOrder", "SubmitMedicationOrder", "CancelMedicationOrder", "ListMedicationTemplates"];
|
|
2547
|
+
|
|
2548
|
+
// src/catalog.ts
|
|
2549
|
+
var STATES = [
|
|
2550
|
+
"AZ",
|
|
2551
|
+
"CA",
|
|
2552
|
+
"CO",
|
|
2553
|
+
"FL",
|
|
2554
|
+
"GA",
|
|
2555
|
+
"IL",
|
|
2556
|
+
"NC",
|
|
2557
|
+
"NJ",
|
|
2558
|
+
"NV",
|
|
2559
|
+
"NY",
|
|
2560
|
+
"OH",
|
|
2561
|
+
"PA",
|
|
2562
|
+
"TX",
|
|
2563
|
+
"UT",
|
|
2564
|
+
"VA",
|
|
2565
|
+
"WA"
|
|
2566
|
+
];
|
|
2567
|
+
var DEFAULT_TEMPLATES = [
|
|
2568
|
+
{
|
|
2569
|
+
template_identifier: "tmpl-testosterone-cypionate",
|
|
2570
|
+
medication_display_name: "Testosterone Cypionate (Grapeseed Oil) Injectable",
|
|
2571
|
+
description: "Sterile solution, multi-dose vial",
|
|
2572
|
+
map_dose_to_product: { "200 mg/mL": "PMK-TESTCYP-200" },
|
|
2573
|
+
qty_options: [5, 10],
|
|
2574
|
+
default_sigs: ["Inject 0.5 mL intramuscularly once weekly"],
|
|
2575
|
+
available_states: STATES,
|
|
2576
|
+
controlled: 3
|
|
2577
|
+
},
|
|
2578
|
+
{
|
|
2579
|
+
template_identifier: "tmpl-sermorelin",
|
|
2580
|
+
medication_display_name: "Sermorelin Acetate Injectable",
|
|
2581
|
+
description: "Lyophilized powder for reconstitution, vial",
|
|
2582
|
+
map_dose_to_product: { "9 mg": "PMK-SERM-9", "15 mg": "PMK-SERM-15" },
|
|
2583
|
+
qty_options: [1, 2],
|
|
2584
|
+
default_sigs: ["Inject 300 mcg subcutaneously nightly"],
|
|
2585
|
+
available_states: STATES,
|
|
2586
|
+
controlled: 0
|
|
2587
|
+
},
|
|
2588
|
+
{
|
|
2589
|
+
template_identifier: "tmpl-enclomiphene",
|
|
2590
|
+
medication_display_name: "Enclomiphene Citrate Capsule",
|
|
2591
|
+
description: "Oral capsule",
|
|
2592
|
+
map_dose_to_product: { "12.5 mg": "PMK-ENCLO-12", "25 mg": "PMK-ENCLO-25" },
|
|
2593
|
+
qty_options: [30, 90],
|
|
2594
|
+
default_sigs: ["Take 1 capsule by mouth daily"],
|
|
2595
|
+
available_states: STATES,
|
|
2596
|
+
controlled: 0
|
|
2597
|
+
},
|
|
2598
|
+
{
|
|
2599
|
+
template_identifier: "tmpl-oxytocin-troche",
|
|
2600
|
+
medication_display_name: "Oxytocin Troche",
|
|
2601
|
+
description: "Sublingual troche",
|
|
2602
|
+
map_dose_to_product: { "100 IU": "PMK-OXY-100" },
|
|
2603
|
+
qty_options: [30],
|
|
2604
|
+
default_sigs: ["Dissolve 1 troche under the tongue as needed"],
|
|
2605
|
+
available_states: ["AZ", "TX", "FL"],
|
|
2606
|
+
controlled: 0
|
|
2607
|
+
}
|
|
2608
|
+
];
|
|
2609
|
+
var DEFAULT_CLINICS = [
|
|
2610
|
+
{ identifier: "clinic-geviti-0001", data: { name: "Geviti" } },
|
|
2611
|
+
{ identifier: "clinic-geviti-west-0002", data: { name: "Geviti West" } }
|
|
2612
|
+
];
|
|
2613
|
+
|
|
2614
|
+
// src/state.ts
|
|
2615
|
+
var SANDBOX_PATIENT = {
|
|
2616
|
+
patient_id: 1,
|
|
2617
|
+
clinic_identifier: "clinic-geviti-0001",
|
|
2618
|
+
demographics: {
|
|
2619
|
+
first_name: "Sandbox",
|
|
2620
|
+
last_name: "Patient",
|
|
2621
|
+
DOB: "1970-01-01",
|
|
2622
|
+
email: "sandbox.patient@example.com",
|
|
2623
|
+
phone_primary: "6025550100",
|
|
2624
|
+
line_1: "100 Test Ave",
|
|
2625
|
+
postal_code: "85004"
|
|
2626
|
+
}
|
|
2627
|
+
};
|
|
2628
|
+
var DEFAULT_SETTINGS = {
|
|
2629
|
+
tokens: [],
|
|
2630
|
+
basic: [],
|
|
2631
|
+
anonymousCatalog: true,
|
|
2632
|
+
webhookVariant: "workflow_status",
|
|
2633
|
+
autoAdvance: null
|
|
2634
|
+
};
|
|
2635
|
+
var PharmetikaState = class {
|
|
2636
|
+
constructor(sqlite, namespace, seed) {
|
|
2637
|
+
this.seed = seed;
|
|
2638
|
+
this.orders = new Collection(sqlite, namespace, "orders");
|
|
2639
|
+
this.patients = new Collection(sqlite, namespace, "patients");
|
|
2640
|
+
this.clinics = new Collection(sqlite, namespace, "clinics");
|
|
2641
|
+
this.templates = new Collection(sqlite, namespace, "templates");
|
|
2642
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2643
|
+
this.ensureSeeded();
|
|
2644
|
+
}
|
|
2645
|
+
seed;
|
|
2646
|
+
orders;
|
|
2647
|
+
patients;
|
|
2648
|
+
clinics;
|
|
2649
|
+
templates;
|
|
2650
|
+
settings;
|
|
2651
|
+
/** Re-apply the catalog, clinics and settings after a reset. */
|
|
2652
|
+
ensureSeeded() {
|
|
2653
|
+
if (this.templates.count() === 0) {
|
|
2654
|
+
const rows = this.seed.templates.length > 0 ? this.seed.templates : DEFAULT_TEMPLATES;
|
|
2655
|
+
for (const row of rows) this.templates.insert(row.template_identifier, row);
|
|
2656
|
+
}
|
|
2657
|
+
if (this.clinics.count() === 0) {
|
|
2658
|
+
const rows = this.seed.clinics.length > 0 ? this.seed.clinics : DEFAULT_CLINICS;
|
|
2659
|
+
for (const row of rows) this.clinics.insert(row.identifier, row);
|
|
2660
|
+
}
|
|
2661
|
+
if (this.patients.count() === 0) {
|
|
2662
|
+
for (const row of this.seed.patients) this.patients.insert(String(row.patient_id), row);
|
|
2663
|
+
}
|
|
2664
|
+
if (!this.settings.has("settings")) {
|
|
2665
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
current() {
|
|
2669
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2670
|
+
}
|
|
2671
|
+
update(patch) {
|
|
2672
|
+
const next = { ...this.current(), ...patch };
|
|
2673
|
+
this.settings.insert("settings", next);
|
|
2674
|
+
return next;
|
|
2675
|
+
}
|
|
2676
|
+
/** The template (and dose) a `product_identifier` belongs to. */
|
|
2677
|
+
product(productIdentifier) {
|
|
2678
|
+
for (const { value: template } of this.templates.list({ order: "oldest" })) {
|
|
2679
|
+
for (const [dose, id] of Object.entries(template.map_dose_to_product)) {
|
|
2680
|
+
if (id === productIdentifier) return { template, dose };
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
return void 0;
|
|
2684
|
+
}
|
|
2685
|
+
nextPatientId() {
|
|
2686
|
+
return 1 + this.patients.count();
|
|
2687
|
+
}
|
|
2688
|
+
};
|
|
2689
|
+
|
|
2690
|
+
// src/statuses.ts
|
|
2691
|
+
var SUBMITTED_STATUS = "prescription_entered";
|
|
2692
|
+
var PENDING_APPROVAL_STATUS = "pending_prescriber_approval";
|
|
2693
|
+
var KNOWN_STATUSES = [
|
|
2694
|
+
SUBMITTED_STATUS,
|
|
2695
|
+
PENDING_APPROVAL_STATUS,
|
|
2696
|
+
"signed",
|
|
2697
|
+
"data_entry_queue",
|
|
2698
|
+
"data_entry",
|
|
2699
|
+
"data_entry_clarification",
|
|
2700
|
+
"data_entry_rework",
|
|
2701
|
+
"data_entry_verification",
|
|
2702
|
+
"lab_formulation",
|
|
2703
|
+
"contacting_patient",
|
|
2704
|
+
"compounding",
|
|
2705
|
+
"compounding-in-progress",
|
|
2706
|
+
"filled",
|
|
2707
|
+
"dispensed",
|
|
2708
|
+
"dispense_checked",
|
|
2709
|
+
"dispense_verified",
|
|
2710
|
+
"verified",
|
|
2711
|
+
"checked",
|
|
2712
|
+
"order_reconciliation",
|
|
2713
|
+
"ready",
|
|
2714
|
+
"ready-ship",
|
|
2715
|
+
"shipping",
|
|
2716
|
+
"shipped",
|
|
2717
|
+
"Completed Orders",
|
|
2718
|
+
"shipped-received",
|
|
2719
|
+
"completed",
|
|
2720
|
+
"delivered",
|
|
2721
|
+
"cancelled"
|
|
2722
|
+
];
|
|
2723
|
+
var norm = (status) => status.trim().toLowerCase();
|
|
2724
|
+
var isShippedOrLater = (status) => ["shipped", "completed orders", "shipped-received", "completed", "delivered"].includes(
|
|
2725
|
+
norm(status)
|
|
2726
|
+
);
|
|
2727
|
+
var isFinal = (status) => ["cancelled", "shipped-received", "completed", "delivered"].includes(norm(status));
|
|
2728
|
+
var isCancellable = (status) => !isShippedOrLater(status) && !isFinal(status);
|
|
2729
|
+
|
|
2730
|
+
// src/runtime.ts
|
|
2731
|
+
var WEBHOOK_SECRET_HEADER = "x-pharmetika-webhook-secret";
|
|
2732
|
+
var PORTAL = "/api/v5/provider_portal";
|
|
2733
|
+
var PHARMETIKA_PRESETS = {
|
|
2734
|
+
validate_success_zero: {
|
|
2735
|
+
description: "Validate answers HTTP 200 with success: 0 and a message (e.g. Invalid DEA)",
|
|
2736
|
+
rules: [{ operationId: "ValidateMedicationOrder", effect: "validate_success_zero" }]
|
|
2737
|
+
},
|
|
2738
|
+
submit_success_zero: {
|
|
2739
|
+
description: "Submit answers HTTP 200 with success: 0 (our client must treat it as a failure)",
|
|
2740
|
+
rules: [{ operationId: "SubmitMedicationOrder", effect: "submit_success_zero" }]
|
|
2741
|
+
},
|
|
2742
|
+
prepare_success_zero: {
|
|
2743
|
+
description: "EPCS prepare answers HTTP 200 with success: 0",
|
|
2744
|
+
rules: [{ operationId: "PrepareMedicationOrder", effect: "prepare_success_zero" }]
|
|
2745
|
+
},
|
|
2746
|
+
lookup_success_zero: {
|
|
2747
|
+
description: "Order lookup answers HTTP 200 with success: 0 (the status refresh returns null)",
|
|
2748
|
+
rules: [{ operationId: "GetMedicationOrder", effect: "lookup_success_zero" }]
|
|
2749
|
+
},
|
|
2750
|
+
validate_422: {
|
|
2751
|
+
description: "Validate answers 422 with success: 0 and messages [{message}]",
|
|
2752
|
+
rules: [
|
|
2753
|
+
{
|
|
2754
|
+
operationId: "ValidateMedicationOrder",
|
|
2755
|
+
status: 422,
|
|
2756
|
+
body: { success: 0, messages: [{ message: "Please provide instructions", type: "error" }] }
|
|
2757
|
+
}
|
|
2758
|
+
]
|
|
2759
|
+
},
|
|
2760
|
+
success_boolean: {
|
|
2761
|
+
description: "Every success answers success: true instead of 1 (accepted, except by cancel)",
|
|
2762
|
+
rules: [{ pathPrefix: "/api/", effect: "success_boolean" }]
|
|
2763
|
+
},
|
|
2764
|
+
success_string: {
|
|
2765
|
+
description: 'Every success answers success: "1" (a string: our client treats it as failure)',
|
|
2766
|
+
rules: [{ pathPrefix: "/api/", effect: "success_string" }]
|
|
2767
|
+
},
|
|
2768
|
+
cancel_success_true: {
|
|
2769
|
+
description: "Cancel answers success: true; our cancel checks success === 1 strictly",
|
|
2770
|
+
rules: [{ operationId: "CancelMedicationOrder", effect: "cancel_success_true" }]
|
|
2771
|
+
},
|
|
2772
|
+
submitted_but_500: {
|
|
2773
|
+
description: "Submit records the order, then answers 500 (unknown outcome; retry replays)",
|
|
2774
|
+
rules: [{ operationId: "SubmitMedicationOrder", effect: "submitted_but_500" }]
|
|
2775
|
+
},
|
|
2776
|
+
patient_create_duplicate: {
|
|
2777
|
+
description: "Patient create answers success: 0 with duplicate_entries naming the patient",
|
|
2778
|
+
rules: [{ operationId: "CreatePatient", effect: "patient_create_duplicate" }]
|
|
2779
|
+
},
|
|
2780
|
+
patient_create_500: {
|
|
2781
|
+
description: "Patient create answers 500",
|
|
2782
|
+
rules: [
|
|
2783
|
+
{
|
|
2784
|
+
operationId: "CreatePatient",
|
|
2785
|
+
status: 500,
|
|
2786
|
+
body: { success: 0, messages: [{ message: "Server Error", type: "error" }] }
|
|
2787
|
+
}
|
|
2788
|
+
]
|
|
2789
|
+
},
|
|
2790
|
+
clinic_list_keyed: {
|
|
2791
|
+
description: "clinic_list answers data as an object keyed by identifier, not an array",
|
|
2792
|
+
rules: [{ operationId: "ListClinics", effect: "clinic_list_keyed" }]
|
|
2793
|
+
},
|
|
2794
|
+
controlled_count_string: {
|
|
2795
|
+
description: 'Validate answers controlled_substance_list_count as a string ("1")',
|
|
2796
|
+
rules: [{ operationId: "ValidateMedicationOrder", effect: "controlled_count_string" }]
|
|
2797
|
+
},
|
|
2798
|
+
controlled_nested_requests: {
|
|
2799
|
+
description: "Validate answers the entries under data.medication_requests",
|
|
2800
|
+
rules: [{ operationId: "ValidateMedicationOrder", effect: "controlled_nested_requests" }]
|
|
2801
|
+
},
|
|
2802
|
+
unauthorized: {
|
|
2803
|
+
description: "Every call answers 401 (a revoked PHARMETIKA_API_TOKEN)",
|
|
2804
|
+
rules: [{ pathPrefix: "/api/", effect: "unauthorized" }]
|
|
2805
|
+
},
|
|
2806
|
+
server_error: {
|
|
2807
|
+
description: "Every provider-portal call answers 500",
|
|
2808
|
+
rules: [
|
|
2809
|
+
{
|
|
2810
|
+
pathPrefix: PORTAL,
|
|
2811
|
+
status: 500,
|
|
2812
|
+
body: { success: 0, messages: [{ message: "Server Error", type: "error" }] }
|
|
2813
|
+
}
|
|
2814
|
+
]
|
|
2815
|
+
},
|
|
2816
|
+
webhook_duplicate: {
|
|
2817
|
+
description: "The next status webhook is delivered twice",
|
|
2818
|
+
webhook: { mode: "duplicate" }
|
|
2819
|
+
},
|
|
2820
|
+
webhook_reorder: {
|
|
2821
|
+
description: "The next two status webhooks arrive swapped",
|
|
2822
|
+
webhook: { mode: "reorder" }
|
|
2823
|
+
},
|
|
2824
|
+
webhook_drop: {
|
|
2825
|
+
description: "The next status webhook is never delivered",
|
|
2826
|
+
webhook: { mode: "drop" }
|
|
2827
|
+
}
|
|
2828
|
+
};
|
|
2829
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2830
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2831
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2832
|
+
var VARIANTS = ["workflow_status", "status", "flat"];
|
|
2833
|
+
var parseAutoAdvance = (value) => {
|
|
2834
|
+
if (value === null) return null;
|
|
2835
|
+
if (!isRecord4(value)) return "autoAdvance must be {afterMs, path} or null";
|
|
2836
|
+
if (typeof value.afterMs !== "number" || value.afterMs < 0)
|
|
2837
|
+
return "autoAdvance.afterMs must be ms";
|
|
2838
|
+
if (!Array.isArray(value.path) || value.path.some((s) => typeof s !== "string")) {
|
|
2839
|
+
return "autoAdvance.path must be a list of workflow statuses";
|
|
2840
|
+
}
|
|
2841
|
+
return { afterMs: value.afterMs, path: value.path };
|
|
2842
|
+
};
|
|
2843
|
+
var parseSettings = (body) => {
|
|
2844
|
+
const patch = {};
|
|
2845
|
+
if (body.tokens !== void 0) {
|
|
2846
|
+
if (!Array.isArray(body.tokens)) return "tokens: string[]";
|
|
2847
|
+
patch.tokens = body.tokens.map(String);
|
|
2848
|
+
}
|
|
2849
|
+
if (body.basic !== void 0) {
|
|
2850
|
+
if (!Array.isArray(body.basic)) return "basic: [{username, password}]";
|
|
2851
|
+
patch.basic = body.basic.filter(isRecord4).map((b) => ({
|
|
2852
|
+
username: String(b.username),
|
|
2853
|
+
password: String(b.password)
|
|
2854
|
+
}));
|
|
2855
|
+
}
|
|
2856
|
+
if (body.anonymousCatalog !== void 0) {
|
|
2857
|
+
if (typeof body.anonymousCatalog !== "boolean") return "anonymousCatalog: boolean";
|
|
2858
|
+
patch.anonymousCatalog = body.anonymousCatalog;
|
|
2859
|
+
}
|
|
2860
|
+
if (body.webhookVariant !== void 0) {
|
|
2861
|
+
if (!VARIANTS.includes(body.webhookVariant)) {
|
|
2862
|
+
return `webhookVariant: one of ${VARIANTS.join(", ")}`;
|
|
2863
|
+
}
|
|
2864
|
+
patch.webhookVariant = body.webhookVariant;
|
|
2865
|
+
}
|
|
2866
|
+
if (body.autoAdvance !== void 0) {
|
|
2867
|
+
const parsed = parseAutoAdvance(body.autoAdvance);
|
|
2868
|
+
if (typeof parsed === "string") return parsed;
|
|
2869
|
+
patch.autoAdvance = parsed;
|
|
2870
|
+
}
|
|
2871
|
+
return patch;
|
|
2872
|
+
};
|
|
2873
|
+
var parsePatient = (value, id) => {
|
|
2874
|
+
if (!isRecord4(value)) return "expected a patient object";
|
|
2875
|
+
const d = isRecord4(value.demographics) ? value.demographics : value;
|
|
2876
|
+
for (const key of ["first_name", "last_name", "DOB"]) {
|
|
2877
|
+
if (typeof d[key] !== "string" || !d[key].trim()) return `${key} is required`;
|
|
2878
|
+
}
|
|
2879
|
+
const text = (key) => typeof d[key] === "string" ? d[key] : "";
|
|
2880
|
+
return {
|
|
2881
|
+
patient_id: typeof value.patient_id === "number" ? value.patient_id : id,
|
|
2882
|
+
clinic_identifier: typeof value.clinic_identifier === "string" ? value.clinic_identifier : "clinic-geviti-0001",
|
|
2883
|
+
demographics: {
|
|
2884
|
+
first_name: text("first_name"),
|
|
2885
|
+
last_name: text("last_name"),
|
|
2886
|
+
DOB: text("DOB"),
|
|
2887
|
+
email: text("email"),
|
|
2888
|
+
phone_primary: text("phone_primary"),
|
|
2889
|
+
line_1: text("line_1"),
|
|
2890
|
+
postal_code: text("postal_code")
|
|
2891
|
+
}
|
|
2892
|
+
};
|
|
2893
|
+
};
|
|
2894
|
+
var adminRoutes = (runtime) => ({
|
|
2895
|
+
"GET /orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).orders() }),
|
|
2896
|
+
"POST /orders/:id/transition": ({ params, body, namespace }) => {
|
|
2897
|
+
if (!isRecord4(body) || typeof body.to !== "string" || !body.to.trim()) {
|
|
2898
|
+
return adminError3(400, 'expected {"to": "<workflow status>", "tracking_id"?}');
|
|
2899
|
+
}
|
|
2900
|
+
const order = runtime.instance(namespace).transition(params.id, {
|
|
2901
|
+
to: body.to,
|
|
2902
|
+
...typeof body.tracking_id === "string" ? { tracking_id: body.tracking_id } : {}
|
|
2903
|
+
});
|
|
2904
|
+
return order ? json3(200, order) : adminError3(404, `no order ${params.id}`);
|
|
2905
|
+
},
|
|
2906
|
+
"GET /patients": ({ namespace }) => json3(200, {
|
|
2907
|
+
patients: runtime.instance(namespace).state.patients.list({ order: "oldest" }).map((row) => row.value)
|
|
2908
|
+
}),
|
|
2909
|
+
"POST /patients": ({ body, namespace }) => {
|
|
2910
|
+
const state = runtime.instance(namespace).state;
|
|
2911
|
+
const parsed = parsePatient(body, state.nextPatientId());
|
|
2912
|
+
if (typeof parsed === "string") return adminError3(400, parsed);
|
|
2913
|
+
state.patients.insert(String(parsed.patient_id), parsed);
|
|
2914
|
+
return json3(201, parsed);
|
|
2915
|
+
},
|
|
2916
|
+
"PUT /templates": ({ body, namespace }) => {
|
|
2917
|
+
const rows = isRecord4(body) ? body.templates : body;
|
|
2918
|
+
if (!Array.isArray(rows)) return adminError3(400, 'expected {"templates": [...]}');
|
|
2919
|
+
const state = runtime.instance(namespace).state;
|
|
2920
|
+
for (const { id } of state.templates.list()) state.templates.delete(id);
|
|
2921
|
+
for (const row of rows) {
|
|
2922
|
+
if (!isRecord4(row) || typeof row.template_identifier !== "string") {
|
|
2923
|
+
return adminError3(400, "every template needs template_identifier");
|
|
2924
|
+
}
|
|
2925
|
+
state.templates.insert(row.template_identifier, { ...row, controlled: row.controlled ?? 0 });
|
|
2926
|
+
}
|
|
2927
|
+
return json3(200, { templates: rows.length });
|
|
2928
|
+
},
|
|
2929
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2930
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2931
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2932
|
+
const patch = parseSettings(body);
|
|
2933
|
+
if (typeof patch === "string") return adminError3(400, patch);
|
|
2934
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2935
|
+
},
|
|
2936
|
+
"POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
|
|
2937
|
+
});
|
|
2938
|
+
var createRuntime2 = (options = {}) => {
|
|
2939
|
+
const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
|
|
2940
|
+
const hub = createWebhookHub({
|
|
2941
|
+
signer: signers.header(WEBHOOK_SECRET_HEADER),
|
|
2942
|
+
...retryDelaysMs ? { retryDelaysMs } : {},
|
|
2943
|
+
...send ? { fetch: send } : {},
|
|
2944
|
+
endpoints: options.webhooks ? [endpoint] : []
|
|
2945
|
+
});
|
|
2946
|
+
const runtime = createRuntime({
|
|
2947
|
+
name: PHARMETIKA_NAMESPACE,
|
|
2948
|
+
document,
|
|
2949
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2950
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2951
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2952
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2953
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2954
|
+
credential: tokenCredential,
|
|
2955
|
+
presets: PHARMETIKA_PRESETS,
|
|
2956
|
+
webhooks: hub,
|
|
2957
|
+
create: ({ sqlite, namespace, publicNamespace, clock }) => new PharmetikaAPI({
|
|
2958
|
+
sqlite,
|
|
2959
|
+
namespace,
|
|
2960
|
+
now: clock.now,
|
|
2961
|
+
...options.templates ? { templates: options.templates } : {},
|
|
2962
|
+
...options.clinics ? { clinics: options.clinics } : {},
|
|
2963
|
+
...options.patients ? { patients: options.patients } : {},
|
|
2964
|
+
...options.settings ? { settings: options.settings } : {},
|
|
2965
|
+
onWebhook: (event) => hub.publish({
|
|
2966
|
+
namespace: publicNamespace,
|
|
2967
|
+
type: "medication_order.status_updated",
|
|
2968
|
+
body: event.body,
|
|
2969
|
+
id: `${event.orderId}:${clock.now()}:${event.status}`
|
|
2970
|
+
})
|
|
2971
|
+
}),
|
|
2972
|
+
describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
|
|
2973
|
+
admin: adminRoutes
|
|
2974
|
+
});
|
|
2975
|
+
let timer;
|
|
2976
|
+
if (options.tickMs !== void 0 && options.tickMs > 0) {
|
|
2977
|
+
timer = setInterval(() => {
|
|
2978
|
+
for (const name of runtime.namespaces()) runtime.instance(name).tick();
|
|
2979
|
+
}, options.tickMs);
|
|
2980
|
+
timer.unref?.();
|
|
2981
|
+
}
|
|
2982
|
+
return Object.assign(runtime, {
|
|
2983
|
+
webhooks: hub,
|
|
2984
|
+
stop: () => {
|
|
2985
|
+
if (timer !== void 0) clearInterval(timer);
|
|
2986
|
+
}
|
|
2987
|
+
});
|
|
2988
|
+
};
|
|
2989
|
+
|
|
2990
|
+
// src/index.ts
|
|
2991
|
+
var PHARMETIKA_NAMESPACE = "pharmetika";
|
|
2992
|
+
var TOKEN_HEADER = "x-pmk-authentication-token";
|
|
2993
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
2994
|
+
var error = (message) => ({ message, type: "error" });
|
|
2995
|
+
var tokenCredential = (request) => request.headers.get(TOKEN_HEADER)?.trim() || basicAuth(request)?.username || void 0;
|
|
2996
|
+
var record = (context) => {
|
|
2997
|
+
if (context.body.kind !== "json" || typeof context.body.value !== "object" || !context.body.value || Array.isArray(context.body.value)) {
|
|
2998
|
+
throw new HttpError(200, {
|
|
2999
|
+
success: 0,
|
|
3000
|
+
messages: [error("The request body must be a JSON object.")]
|
|
3001
|
+
});
|
|
3002
|
+
}
|
|
3003
|
+
return context.body.value;
|
|
3004
|
+
};
|
|
3005
|
+
var failure = (messages, status = 200) => jsonRes(status, { success: 0, messages });
|
|
3006
|
+
var PharmetikaAPI = class {
|
|
3007
|
+
app;
|
|
3008
|
+
sqlite;
|
|
3009
|
+
state;
|
|
3010
|
+
service;
|
|
3011
|
+
idempotency;
|
|
3012
|
+
now;
|
|
3013
|
+
onWebhook;
|
|
3014
|
+
constructor(options = {}) {
|
|
3015
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
3016
|
+
const namespace = options.namespace ?? PHARMETIKA_NAMESPACE;
|
|
3017
|
+
this.now = options.now ?? (() => Date.now());
|
|
3018
|
+
this.onWebhook = options.onWebhook;
|
|
3019
|
+
this.state = new PharmetikaState(sqlite, namespace, {
|
|
3020
|
+
templates: options.templates ?? [],
|
|
3021
|
+
clinics: options.clinics ?? [],
|
|
3022
|
+
patients: options.patients ?? [SANDBOX_PATIENT],
|
|
3023
|
+
settings: options.settings ?? {}
|
|
3024
|
+
});
|
|
3025
|
+
this.idempotency = new IdempotencyStore(sqlite, namespace, "submit_idempotency");
|
|
3026
|
+
const handlers = defineOperations({
|
|
3027
|
+
ListClinics: (context) => this.listClinics(context),
|
|
3028
|
+
ListPatients: (context) => this.ok(context, {
|
|
3029
|
+
data: this.state.patients.list({ order: "oldest" }).map(({ value }) => ({
|
|
3030
|
+
patient_id: value.patient_id,
|
|
3031
|
+
demographics: value.demographics
|
|
3032
|
+
}))
|
|
3033
|
+
}),
|
|
3034
|
+
CreatePatient: (context) => this.createPatient(context),
|
|
3035
|
+
ValidateMedicationOrder: (context) => this.validate(context),
|
|
3036
|
+
PrepareMedicationOrder: (context) => this.prepare(context),
|
|
3037
|
+
SubmitMedicationOrder: (context) => this.submit(context),
|
|
3038
|
+
GetMedicationOrder: (context) => this.getOrder(context),
|
|
3039
|
+
CancelMedicationOrder: (context) => this.cancel(context),
|
|
3040
|
+
ListMedicationTemplates: (context) => this.ok(context, {
|
|
3041
|
+
data: this.state.templates.list({ order: "oldest" }).map(({ value }) => value)
|
|
3042
|
+
})
|
|
3043
|
+
});
|
|
3044
|
+
this.service = createService({
|
|
3045
|
+
document,
|
|
3046
|
+
handlers,
|
|
3047
|
+
sqlite,
|
|
3048
|
+
namespace,
|
|
3049
|
+
now: this.now,
|
|
3050
|
+
notFound: () => jsonRes(404, { success: 0, messages: [error("Not Found")] }),
|
|
3051
|
+
onError: (thrown) => {
|
|
3052
|
+
if (thrown instanceof HttpError) return thrown.toResponse();
|
|
3053
|
+
throw thrown;
|
|
3054
|
+
},
|
|
3055
|
+
before: (context) => {
|
|
3056
|
+
this.tick();
|
|
3057
|
+
return this.authenticate(context);
|
|
3058
|
+
}
|
|
3059
|
+
});
|
|
3060
|
+
this.app = this.service.app;
|
|
3061
|
+
this.sqlite = this.service.sqlite;
|
|
3062
|
+
}
|
|
3063
|
+
fetch(request) {
|
|
3064
|
+
return this.service.fetch(request);
|
|
3065
|
+
}
|
|
3066
|
+
async reset() {
|
|
3067
|
+
await this.service.reset();
|
|
3068
|
+
this.state.ensureSeeded();
|
|
3069
|
+
}
|
|
3070
|
+
iso() {
|
|
3071
|
+
return new Date(this.now()).toISOString();
|
|
3072
|
+
}
|
|
3073
|
+
authenticate(context) {
|
|
3074
|
+
const settings = this.state.current();
|
|
3075
|
+
const rejected = failure([error("Invalid authentication token.")], 401);
|
|
3076
|
+
if (faultEffect(context.request, "unauthorized") !== void 0) return rejected;
|
|
3077
|
+
const token = context.request.headers.get(TOKEN_HEADER)?.trim();
|
|
3078
|
+
if (token) {
|
|
3079
|
+
return settings.tokens.length === 0 || settings.tokens.includes(token) ? void 0 : rejected;
|
|
3080
|
+
}
|
|
3081
|
+
if (context.operation.operationId !== "ListMedicationTemplates") {
|
|
3082
|
+
return failure([error("Authentication token is required.")], 401);
|
|
3083
|
+
}
|
|
3084
|
+
const basic = basicAuth(context.request);
|
|
3085
|
+
if (basic) {
|
|
3086
|
+
const known = settings.basic.length === 0 || settings.basic.some((b) => b.username === basic.username && b.password === basic.password);
|
|
3087
|
+
return known ? void 0 : rejected;
|
|
3088
|
+
}
|
|
3089
|
+
return settings.anonymousCatalog ? void 0 : rejected;
|
|
3090
|
+
}
|
|
3091
|
+
/** `success: 1`, or the value a success-flag preset substitutes. */
|
|
3092
|
+
successFlag(context) {
|
|
3093
|
+
if (faultEffect(context.request, "success_string") !== void 0) return "1";
|
|
3094
|
+
if (faultEffect(context.request, "success_boolean") !== void 0) return true;
|
|
3095
|
+
return 1;
|
|
3096
|
+
}
|
|
3097
|
+
ok(context, body, messages = []) {
|
|
3098
|
+
return jsonRes(200, { success: this.successFlag(context), messages, ...body });
|
|
3099
|
+
}
|
|
3100
|
+
listClinics(context) {
|
|
3101
|
+
const clinics = this.state.clinics.list({ order: "oldest" }).map(({ value }) => value);
|
|
3102
|
+
if (faultEffect(context.request, "clinic_list_keyed") !== void 0) {
|
|
3103
|
+
return this.ok(context, { data: Object.fromEntries(clinics.map((c) => [c.identifier, c])) });
|
|
3104
|
+
}
|
|
3105
|
+
return this.ok(context, { data: clinics });
|
|
3106
|
+
}
|
|
3107
|
+
createPatient(context) {
|
|
3108
|
+
const body = record(context);
|
|
3109
|
+
const issues = bodyIssues(context);
|
|
3110
|
+
if (issues.length > 0) {
|
|
3111
|
+
return failure(issues.map((i) => error(`${i.path || "body"}: ${i.message}`)));
|
|
3112
|
+
}
|
|
3113
|
+
const clinic = String(body.clinic_identifier);
|
|
3114
|
+
if (!this.state.clinics.has(clinic)) return failure([error(`Unknown clinic ${clinic}.`)]);
|
|
3115
|
+
const name = body.name[0];
|
|
3116
|
+
const telecom = body.telecom ?? [];
|
|
3117
|
+
const address = body.address?.[0];
|
|
3118
|
+
const demographics = {
|
|
3119
|
+
first_name: name.given[0] ?? "",
|
|
3120
|
+
last_name: name.family,
|
|
3121
|
+
DOB: String(body.birthDate),
|
|
3122
|
+
email: telecom.find((t) => t.system === "email")?.value ?? "",
|
|
3123
|
+
phone_primary: telecom.find((t) => t.system === "phone")?.value ?? "",
|
|
3124
|
+
line_1: address?.line?.[0] ?? "",
|
|
3125
|
+
postal_code: address?.postalCode ?? ""
|
|
3126
|
+
};
|
|
3127
|
+
const same = (p) => p.demographics.first_name.trim().toLowerCase() === demographics.first_name.trim().toLowerCase() && p.demographics.last_name.trim().toLowerCase() === demographics.last_name.trim().toLowerCase() && p.demographics.DOB.slice(0, 10) === demographics.DOB.slice(0, 10);
|
|
3128
|
+
let duplicates = this.state.patients.list({ where: same }).map(({ value }) => value);
|
|
3129
|
+
if (duplicates.length === 0 && faultEffect(context.request, "patient_create_duplicate")) {
|
|
3130
|
+
duplicates = [this.insertPatient(clinic, demographics)];
|
|
3131
|
+
}
|
|
3132
|
+
if (duplicates.length > 0) {
|
|
3133
|
+
return annotateResponse(
|
|
3134
|
+
jsonRes(200, {
|
|
3135
|
+
success: 0,
|
|
3136
|
+
messages: [{ message: "Possible duplicate patient found.", type: "warning" }],
|
|
3137
|
+
duplicate_entry_count: duplicates.length,
|
|
3138
|
+
duplicate_entries: duplicates.map((p) => ({
|
|
3139
|
+
patient_id: p.patient_id,
|
|
3140
|
+
demographics: p.demographics
|
|
3141
|
+
}))
|
|
3142
|
+
}),
|
|
3143
|
+
{ ids: { patientId: String(duplicates[0]?.patient_id) } }
|
|
3144
|
+
);
|
|
3145
|
+
}
|
|
3146
|
+
const created = this.insertPatient(clinic, demographics);
|
|
3147
|
+
return annotateResponse(
|
|
3148
|
+
this.ok(context, { patient_id: created.patient_id }, [
|
|
3149
|
+
{ message: "Added Patient!", type: "info" }
|
|
3150
|
+
]),
|
|
3151
|
+
{ ids: { patientId: String(created.patient_id) } }
|
|
3152
|
+
);
|
|
3153
|
+
}
|
|
3154
|
+
insertPatient(clinic, demographics) {
|
|
3155
|
+
const patient = {
|
|
3156
|
+
patient_id: this.state.nextPatientId(),
|
|
3157
|
+
clinic_identifier: clinic,
|
|
3158
|
+
demographics
|
|
3159
|
+
};
|
|
3160
|
+
this.state.patients.insert(String(patient.patient_id), patient);
|
|
3161
|
+
return patient;
|
|
3162
|
+
}
|
|
3163
|
+
/** Every check validate, prepare and submit share. A `Response` is the vendor's refusal. */
|
|
3164
|
+
check(context) {
|
|
3165
|
+
const body = record(context);
|
|
3166
|
+
const issues = bodyIssues(context);
|
|
3167
|
+
if (issues.length > 0) {
|
|
3168
|
+
return failure(issues.map((i) => error(`${i.path || "body"}: ${i.message}`)));
|
|
3169
|
+
}
|
|
3170
|
+
const id = context.params.orderId ?? "";
|
|
3171
|
+
if (!UUID.test(id)) {
|
|
3172
|
+
return failure([error("medication_order_identifier must be a UUID.")]);
|
|
3173
|
+
}
|
|
3174
|
+
const clinic = String(body.clinic_identifier);
|
|
3175
|
+
if (!this.state.clinics.has(clinic)) return failure([error(`Unknown clinic ${clinic}.`)]);
|
|
3176
|
+
const patientId = body.patient.identification.patient_id;
|
|
3177
|
+
if (!this.state.patients.has(String(patientId))) {
|
|
3178
|
+
return failure([error(`Patient ${patientId} was not found.`)]);
|
|
3179
|
+
}
|
|
3180
|
+
const messages = [];
|
|
3181
|
+
const lines = body.medication_requests.map((line) => {
|
|
3182
|
+
const productId = line.product_identification.product_identifier;
|
|
3183
|
+
const product = this.state.product(productId);
|
|
3184
|
+
if (!product) messages.push(error(`Unknown product_identifier ${productId}.`));
|
|
3185
|
+
if (line.sig.trim().length === 0) messages.push(error("Please provide instructions"));
|
|
3186
|
+
return { ...line, controlled: product?.template.controlled ?? 0 };
|
|
3187
|
+
});
|
|
3188
|
+
if (messages.length > 0) return failure(messages);
|
|
3189
|
+
return {
|
|
3190
|
+
id,
|
|
3191
|
+
body,
|
|
3192
|
+
clinic,
|
|
3193
|
+
practitioner: typeof body.practitioner_identifier === "string" ? body.practitioner_identifier : null,
|
|
3194
|
+
patientId,
|
|
3195
|
+
lines,
|
|
3196
|
+
controlled: Math.max(0, ...lines.map((l) => l.controlled))
|
|
3197
|
+
};
|
|
3198
|
+
}
|
|
3199
|
+
validate(context) {
|
|
3200
|
+
const checked = this.check(context);
|
|
3201
|
+
if (checked instanceof Response) return checked;
|
|
3202
|
+
if (faultEffect(context.request, "validate_success_zero") !== void 0) {
|
|
3203
|
+
return failure([error("Invalid DEA")]);
|
|
3204
|
+
}
|
|
3205
|
+
const entries = checked.lines.map((line, index) => ({
|
|
3206
|
+
...line,
|
|
3207
|
+
medication_order_entry_identifier: line.medication_order_entry_identifier ?? `${checked.id.slice(0, 24)}${String(index).padStart(12, "0")}`,
|
|
3208
|
+
controlled: line.controlled,
|
|
3209
|
+
control_level: line.controlled
|
|
3210
|
+
}));
|
|
3211
|
+
const count = entries.filter((e) => e.controlled > 0).length;
|
|
3212
|
+
const data = faultEffect(context.request, "controlled_nested_requests") !== void 0 ? (
|
|
3213
|
+
// The adapter also finds the entries under `data.medication_requests`.
|
|
3214
|
+
{ controlled_substance_list_count: count, medication_requests: entries }
|
|
3215
|
+
) : {
|
|
3216
|
+
controlled_substance_list_count: faultEffect(context.request, "controlled_count_string") !== void 0 ? String(count) : count,
|
|
3217
|
+
medication_list: entries
|
|
3218
|
+
};
|
|
3219
|
+
return annotateResponse(this.ok(context, { data }), { ids: { orderId: checked.id } });
|
|
3220
|
+
}
|
|
3221
|
+
newOrder(checked, status) {
|
|
3222
|
+
const now = this.iso();
|
|
3223
|
+
return {
|
|
3224
|
+
medication_order_identifier: checked.id,
|
|
3225
|
+
clinic_identifier: checked.clinic,
|
|
3226
|
+
practitioner_identifier: checked.practitioner,
|
|
3227
|
+
patient_id: checked.patientId,
|
|
3228
|
+
product_identifiers: checked.lines.map((l) => l.product_identification.product_identifier),
|
|
3229
|
+
controlled: checked.controlled,
|
|
3230
|
+
workflow_status: status,
|
|
3231
|
+
tracking_id: null,
|
|
3232
|
+
created_at: now,
|
|
3233
|
+
updated_at: now,
|
|
3234
|
+
createdAtMs: this.now(),
|
|
3235
|
+
advanced: 0
|
|
3236
|
+
};
|
|
3237
|
+
}
|
|
3238
|
+
ack(context, order, message) {
|
|
3239
|
+
return annotateResponse(
|
|
3240
|
+
this.ok(
|
|
3241
|
+
context,
|
|
3242
|
+
{
|
|
3243
|
+
data: {
|
|
3244
|
+
medication_order_identifier: order.medication_order_identifier,
|
|
3245
|
+
order_status: order.workflow_status
|
|
3246
|
+
}
|
|
3247
|
+
},
|
|
3248
|
+
[{ message, type: "info" }]
|
|
3249
|
+
),
|
|
3250
|
+
{ ids: { orderId: order.medication_order_identifier } }
|
|
3251
|
+
);
|
|
3252
|
+
}
|
|
3253
|
+
prepare(context) {
|
|
3254
|
+
const checked = this.check(context);
|
|
3255
|
+
if (checked instanceof Response) return checked;
|
|
3256
|
+
if (faultEffect(context.request, "prepare_success_zero") !== void 0) {
|
|
3257
|
+
return failure([error("Prescriber is not enrolled for EPCS.")]);
|
|
3258
|
+
}
|
|
3259
|
+
if (typeof checked.body.prepared_by !== "string" || checked.body.prepared_by.length === 0) {
|
|
3260
|
+
return failure([error("prepared_by is required to prepare an order.")]);
|
|
3261
|
+
}
|
|
3262
|
+
const existing = this.state.orders.get(checked.id);
|
|
3263
|
+
if (existing && existing.workflow_status !== PENDING_APPROVAL_STATUS) {
|
|
3264
|
+
return failure([error(`Medication order ${checked.id} has already been submitted.`)]);
|
|
3265
|
+
}
|
|
3266
|
+
const order = existing ?? this.newOrder(checked, PENDING_APPROVAL_STATUS);
|
|
3267
|
+
if (!existing) this.state.orders.insert(order.medication_order_identifier, order);
|
|
3268
|
+
return this.ack(context, order, "Order prepared; awaiting prescriber approval.");
|
|
3269
|
+
}
|
|
3270
|
+
/**
|
|
3271
|
+
* What makes two submits "the same order" for idempotency: the clinic, patient and the
|
|
3272
|
+
* products, quantities and sigs. Our adapter regenerates `date_issued` and each entry id on
|
|
3273
|
+
* every attempt, so those are left out.
|
|
3274
|
+
*/
|
|
3275
|
+
fingerprint(checked) {
|
|
3276
|
+
return stableStringify({
|
|
3277
|
+
clinic: checked.clinic,
|
|
3278
|
+
patient: checked.patientId,
|
|
3279
|
+
lines: checked.lines.map((l) => [
|
|
3280
|
+
l.product_identification.product_identifier,
|
|
3281
|
+
l.quantity_authorized,
|
|
3282
|
+
l.sig.trim()
|
|
3283
|
+
])
|
|
3284
|
+
});
|
|
3285
|
+
}
|
|
3286
|
+
async submit(context) {
|
|
3287
|
+
const checked = this.check(context);
|
|
3288
|
+
if (checked instanceof Response) return checked;
|
|
3289
|
+
if (checked.controlled > 0) {
|
|
3290
|
+
return failure([
|
|
3291
|
+
error("Controlled substances must be prepared and signed by the prescriber (EPCS).")
|
|
3292
|
+
]);
|
|
3293
|
+
}
|
|
3294
|
+
if (faultEffect(context.request, "submit_success_zero") !== void 0) {
|
|
3295
|
+
return failure([error("Order could not be submitted.")]);
|
|
3296
|
+
}
|
|
3297
|
+
const fingerprint = this.fingerprint(checked);
|
|
3298
|
+
const conflict = () => failure(
|
|
3299
|
+
[error(`Medication order ${checked.id} is already being submitted with other contents.`)],
|
|
3300
|
+
409
|
|
3301
|
+
);
|
|
3302
|
+
return this.idempotency.run(
|
|
3303
|
+
checked.id,
|
|
3304
|
+
fingerprint,
|
|
3305
|
+
{
|
|
3306
|
+
mismatch: conflict,
|
|
3307
|
+
conflict: () => failure([error(`Medication order ${checked.id} is still being submitted.`)], 409)
|
|
3308
|
+
},
|
|
3309
|
+
() => {
|
|
3310
|
+
const existing = this.state.orders.get(checked.id);
|
|
3311
|
+
if (existing) {
|
|
3312
|
+
return existing.workflow_status === PENDING_APPROVAL_STATUS ? failure([error(`Medication order ${checked.id} awaits prescriber approval.`)]) : this.ack(context, existing, "Order submitted.");
|
|
3313
|
+
}
|
|
3314
|
+
const order = this.newOrder(checked, SUBMITTED_STATUS);
|
|
3315
|
+
this.state.orders.insert(order.medication_order_identifier, order);
|
|
3316
|
+
if (faultEffect(context.request, "submitted_but_500") !== void 0) {
|
|
3317
|
+
return annotateResponse(failure([error("Server Error")], 500), {
|
|
3318
|
+
ids: { orderId: order.medication_order_identifier }
|
|
3319
|
+
});
|
|
3320
|
+
}
|
|
3321
|
+
return this.ack(context, order, "Order submitted.");
|
|
3322
|
+
}
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
lookupBody(order) {
|
|
3326
|
+
return {
|
|
3327
|
+
medication_order_identifier: order.medication_order_identifier,
|
|
3328
|
+
electronic_prescription_order_number: order.medication_order_identifier,
|
|
3329
|
+
order_status: order.workflow_status,
|
|
3330
|
+
data: {
|
|
3331
|
+
order_status: order.workflow_status,
|
|
3332
|
+
clinic_identifier: order.clinic_identifier,
|
|
3333
|
+
patient_id: order.patient_id,
|
|
3334
|
+
product_identifiers: order.product_identifiers,
|
|
3335
|
+
created_at: order.created_at,
|
|
3336
|
+
updated_at: order.updated_at,
|
|
3337
|
+
ancillary_order_data: {
|
|
3338
|
+
medication_order_status: {
|
|
3339
|
+
workflow_status: order.workflow_status,
|
|
3340
|
+
tracking_id: order.tracking_id
|
|
3341
|
+
}
|
|
3342
|
+
}
|
|
3343
|
+
}
|
|
3344
|
+
};
|
|
3345
|
+
}
|
|
3346
|
+
getOrder(context) {
|
|
3347
|
+
const id = context.params.orderId ?? "";
|
|
3348
|
+
const order = this.state.orders.get(id);
|
|
3349
|
+
if (!order) return failure([error(`Medication order ${id} was not found.`)], 404);
|
|
3350
|
+
if (faultEffect(context.request, "lookup_success_zero") !== void 0) {
|
|
3351
|
+
return failure([error("Order lookup is temporarily unavailable.")]);
|
|
3352
|
+
}
|
|
3353
|
+
return annotateResponse(this.ok(context, { data: this.lookupBody(order) }), {
|
|
3354
|
+
ids: { orderId: id }
|
|
3355
|
+
});
|
|
3356
|
+
}
|
|
3357
|
+
cancel(context) {
|
|
3358
|
+
const body = record(context);
|
|
3359
|
+
const issues = bodyIssues(context);
|
|
3360
|
+
if (issues.length > 0) {
|
|
3361
|
+
return failure(issues.map((i) => error(`${i.path || "body"}: ${i.message}`)));
|
|
3362
|
+
}
|
|
3363
|
+
const id = String(body.prescriber_order_number);
|
|
3364
|
+
const order = this.state.orders.get(id);
|
|
3365
|
+
if (!order) return failure([error(`Medication order ${id} was not found.`)]);
|
|
3366
|
+
if (!isCancellable(order.workflow_status)) {
|
|
3367
|
+
return failure([
|
|
3368
|
+
error(`Medication order ${id} cannot be cancelled in status ${order.workflow_status}.`)
|
|
3369
|
+
]);
|
|
3370
|
+
}
|
|
3371
|
+
this.transition(id, { to: "cancelled" });
|
|
3372
|
+
const success = faultEffect(context.request, "cancel_success_true") !== void 0 ? true : 1;
|
|
3373
|
+
return annotateResponse(jsonRes(200, { success, messages: [] }), { ids: { orderId: id } });
|
|
3374
|
+
}
|
|
3375
|
+
/** Move an order to a workflow status and emit the status webhook. */
|
|
3376
|
+
transition(id, input) {
|
|
3377
|
+
const order = this.state.orders.get(id);
|
|
3378
|
+
if (!order) return void 0;
|
|
3379
|
+
const tracking_id = input.tracking_id ?? order.tracking_id ?? (isShippedOrLater(input.to) ? `1Z${opaqueToken(id, 16).toUpperCase()}` : null);
|
|
3380
|
+
const next = {
|
|
3381
|
+
...order,
|
|
3382
|
+
workflow_status: input.to,
|
|
3383
|
+
tracking_id,
|
|
3384
|
+
updated_at: this.iso()
|
|
3385
|
+
};
|
|
3386
|
+
this.state.orders.update(id, next);
|
|
3387
|
+
this.onWebhook?.({ orderId: id, status: input.to, body: this.webhookBody(next) });
|
|
3388
|
+
return this.state.orders.get(id);
|
|
3389
|
+
}
|
|
3390
|
+
/** The webhook body in the namespace's variant (each is one of our receiver's fallbacks). */
|
|
3391
|
+
webhookBody(order) {
|
|
3392
|
+
const id = order.medication_order_identifier;
|
|
3393
|
+
const tracking = order.tracking_id ? { tracking_id: order.tracking_id } : {};
|
|
3394
|
+
switch (this.state.current().webhookVariant) {
|
|
3395
|
+
case "status":
|
|
3396
|
+
return {
|
|
3397
|
+
event_type: "medication_order.status_updated",
|
|
3398
|
+
event_data: {
|
|
3399
|
+
medication_order_identifier: id,
|
|
3400
|
+
status: order.workflow_status,
|
|
3401
|
+
...tracking
|
|
3402
|
+
}
|
|
3403
|
+
};
|
|
3404
|
+
case "flat":
|
|
3405
|
+
return {
|
|
3406
|
+
medication_order_identifier: id,
|
|
3407
|
+
medication_order_workflow_status: order.workflow_status,
|
|
3408
|
+
...tracking
|
|
3409
|
+
};
|
|
3410
|
+
default:
|
|
3411
|
+
return {
|
|
3412
|
+
event_type: "medication_order.status_updated",
|
|
3413
|
+
event_data: {
|
|
3414
|
+
electronic_prescription_order_number: id,
|
|
3415
|
+
medication_order_identifier: id,
|
|
3416
|
+
medication_order_status: {
|
|
3417
|
+
workflow_status: order.workflow_status,
|
|
3418
|
+
tracking_id: order.tracking_id
|
|
3419
|
+
},
|
|
3420
|
+
...tracking,
|
|
3421
|
+
updated_at: order.updated_at
|
|
3422
|
+
}
|
|
3423
|
+
};
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
/**
|
|
3427
|
+
* Apply every auto-advance step that is due on the mock clock. Runs before each vendor
|
|
3428
|
+
* request, on `POST /__admin/tick`, and from the served runtime's background ticker.
|
|
3429
|
+
* Orders awaiting prescriber approval never move on their own.
|
|
3430
|
+
*/
|
|
3431
|
+
tick() {
|
|
3432
|
+
const plan = this.state.current().autoAdvance;
|
|
3433
|
+
if (!plan || plan.path.length === 0) return 0;
|
|
3434
|
+
let applied = 0;
|
|
3435
|
+
for (const { value: order } of this.state.orders.list({ order: "oldest" })) {
|
|
3436
|
+
if (order.workflow_status === PENDING_APPROVAL_STATUS) continue;
|
|
3437
|
+
let current = order;
|
|
3438
|
+
while (current.advanced < plan.path.length) {
|
|
3439
|
+
const due = current.createdAtMs + plan.afterMs * (current.advanced + 1);
|
|
3440
|
+
if (this.now() < due) break;
|
|
3441
|
+
const to = plan.path[current.advanced];
|
|
3442
|
+
const moved = this.transition(current.medication_order_identifier, { to });
|
|
3443
|
+
if (!moved) break;
|
|
3444
|
+
current = { ...moved, advanced: current.advanced + 1 };
|
|
3445
|
+
this.state.orders.update(current.medication_order_identifier, current);
|
|
3446
|
+
applied++;
|
|
3447
|
+
}
|
|
3448
|
+
}
|
|
3449
|
+
return applied;
|
|
3450
|
+
}
|
|
3451
|
+
orders() {
|
|
3452
|
+
return this.state.orders.list({ order: "oldest" }).map((row) => row.value);
|
|
3453
|
+
}
|
|
3454
|
+
};
|
|
3455
|
+
|
|
3456
|
+
export {
|
|
3457
|
+
document,
|
|
3458
|
+
operationIds,
|
|
3459
|
+
supportedOperationIds,
|
|
3460
|
+
DEFAULT_TEMPLATES,
|
|
3461
|
+
DEFAULT_CLINICS,
|
|
3462
|
+
SANDBOX_PATIENT,
|
|
3463
|
+
SUBMITTED_STATUS,
|
|
3464
|
+
PENDING_APPROVAL_STATUS,
|
|
3465
|
+
KNOWN_STATUSES,
|
|
3466
|
+
WEBHOOK_SECRET_HEADER,
|
|
3467
|
+
PHARMETIKA_PRESETS,
|
|
3468
|
+
createRuntime2 as createRuntime,
|
|
3469
|
+
PHARMETIKA_NAMESPACE,
|
|
3470
|
+
TOKEN_HEADER,
|
|
3471
|
+
tokenCredential,
|
|
3472
|
+
PharmetikaAPI
|
|
3473
|
+
};
|
|
3474
|
+
//# sourceMappingURL=chunk-SQBTC6SN.js.map
|