@crvouga/mockingbird-service-caretalk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +124 -0
- package/dist/chunk-PO4JZHCF.js +357 -0
- package/dist/chunk-PO4JZHCF.js.map +7 -0
- package/dist/chunk-QWI3RIVV.js +3043 -0
- package/dist/chunk-QWI3RIVV.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1010 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1324 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +87 -0
|
@@ -0,0 +1,3043 @@
|
|
|
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 text2 = await request.text();
|
|
165
|
+
if (text2.trim() === "")
|
|
166
|
+
return void 0;
|
|
167
|
+
return JSON.parse(text2);
|
|
168
|
+
};
|
|
169
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
170
|
+
var createControlPlane = (context) => {
|
|
171
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
172
|
+
let snapshotCounter = 0;
|
|
173
|
+
const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
|
|
174
|
+
const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
|
|
175
|
+
const builtin = {
|
|
176
|
+
"GET /": () => json(200, {
|
|
177
|
+
service: context.name,
|
|
178
|
+
routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
|
|
179
|
+
}),
|
|
180
|
+
"POST /reset": async ({ url, namespace }) => {
|
|
181
|
+
const target = url.searchParams.get("all") === "1" ? "*" : namespace;
|
|
182
|
+
await context.reset(target);
|
|
183
|
+
return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
|
|
184
|
+
},
|
|
185
|
+
"GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
|
|
186
|
+
"GET /clock": () => json(200, context.clock.state()),
|
|
187
|
+
"POST /clock": ({ body }) => {
|
|
188
|
+
if (!isRecord(body))
|
|
189
|
+
return adminError(400, "expected a JSON object");
|
|
190
|
+
if (body.reset === true)
|
|
191
|
+
context.clock.reset();
|
|
192
|
+
if (body.set !== void 0) {
|
|
193
|
+
const instant = parseInstant(body.set);
|
|
194
|
+
if (instant === void 0)
|
|
195
|
+
return adminError(400, "set: expected epoch ms or ISO-8601");
|
|
196
|
+
context.clock.set(instant);
|
|
197
|
+
}
|
|
198
|
+
if (body.advance !== void 0) {
|
|
199
|
+
const delta = parseDuration(body.advance);
|
|
200
|
+
if (delta === void 0)
|
|
201
|
+
return adminError(400, 'advance: expected ms or "15m"-style');
|
|
202
|
+
context.clock.advance(delta);
|
|
203
|
+
}
|
|
204
|
+
if (body.freeze === true)
|
|
205
|
+
context.clock.freeze();
|
|
206
|
+
if (body.freeze === false)
|
|
207
|
+
context.clock.unfreeze();
|
|
208
|
+
return json(200, context.clock.state());
|
|
209
|
+
},
|
|
210
|
+
"GET /faults": () => json(200, { faults: context.faults.list() }),
|
|
211
|
+
"POST /faults": ({ body, namespace }) => {
|
|
212
|
+
if (isRecord(body) && typeof body.preset === "string") {
|
|
213
|
+
if (!context.applyPreset)
|
|
214
|
+
return adminError(400, `${context.name} has no fault presets`);
|
|
215
|
+
const { preset, ...overrides } = body;
|
|
216
|
+
try {
|
|
217
|
+
return json(201, {
|
|
218
|
+
preset,
|
|
219
|
+
rules: context.applyPreset(preset, namespace, overrides)
|
|
220
|
+
});
|
|
221
|
+
} catch (error) {
|
|
222
|
+
return adminError(404, error instanceof Error ? error.message : String(error));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
|
|
226
|
+
return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
|
|
227
|
+
}
|
|
228
|
+
const rule = {
|
|
229
|
+
// Scoped to the caller's namespace unless it asks for every one, so one worker's
|
|
230
|
+
// injected failure never lands on another's request.
|
|
231
|
+
namespace,
|
|
232
|
+
...body,
|
|
233
|
+
id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
|
|
234
|
+
};
|
|
235
|
+
return json(201, context.faults.add(rule));
|
|
236
|
+
},
|
|
237
|
+
"DELETE /faults": ({ url }) => {
|
|
238
|
+
const id = url.searchParams.get("id");
|
|
239
|
+
if (id === null) {
|
|
240
|
+
context.faults.clear();
|
|
241
|
+
return json(200, { status: "ok" });
|
|
242
|
+
}
|
|
243
|
+
return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
|
|
244
|
+
},
|
|
245
|
+
"POST /snapshots": ({ namespace }) => {
|
|
246
|
+
const point = context.timeTravel.checkpoint(namespace, "main");
|
|
247
|
+
context.timeTravel.retain(namespace, point.id);
|
|
248
|
+
snapshotCounter++;
|
|
249
|
+
const id = `snap_${snapshotCounter}`;
|
|
250
|
+
snapshots.set(id, { namespace, checkpoint: point.id });
|
|
251
|
+
return json(201, { id, namespace, records: point.records ?? 0 });
|
|
252
|
+
},
|
|
253
|
+
"POST /snapshots/:id/restore": ({ params, namespace }) => {
|
|
254
|
+
const alias = snapshots.get(params.id);
|
|
255
|
+
if (!alias)
|
|
256
|
+
return adminError(404, `no snapshot ${params.id}`);
|
|
257
|
+
if (alias.namespace !== namespace) {
|
|
258
|
+
return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
|
|
259
|
+
}
|
|
260
|
+
context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
|
|
261
|
+
return json(200, { status: "ok", id: params.id, namespace });
|
|
262
|
+
},
|
|
263
|
+
"DELETE /snapshots/:id": ({ params }) => {
|
|
264
|
+
const id = params.id;
|
|
265
|
+
const alias = snapshots.get(id);
|
|
266
|
+
if (!alias)
|
|
267
|
+
return adminError(404, `no snapshot ${id}`);
|
|
268
|
+
snapshots.delete(id);
|
|
269
|
+
context.timeTravel.release(alias.namespace, alias.checkpoint);
|
|
270
|
+
return json(200, { status: "ok" });
|
|
271
|
+
},
|
|
272
|
+
"GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
|
|
273
|
+
"POST /checkpoints": ({ body, namespace }) => {
|
|
274
|
+
const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
|
|
275
|
+
try {
|
|
276
|
+
return json(201, context.timeTravel.checkpoint(namespace, branch));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
"POST /branches/:name": ({ params, body, namespace }) => {
|
|
282
|
+
const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
|
|
283
|
+
try {
|
|
284
|
+
return json(201, context.timeTravel.branch(params.name, {
|
|
285
|
+
namespace,
|
|
286
|
+
...at !== void 0 ? { at } : {}
|
|
287
|
+
}));
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
"POST /branches/:name/checkout": ({ params, body, namespace }) => {
|
|
293
|
+
if (!isRecord(body) || typeof body.checkpoint !== "string") {
|
|
294
|
+
return adminError(400, 'expected {"checkpoint":"cp_..."}');
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
context.timeTravel.checkout(body.checkpoint, {
|
|
298
|
+
namespace,
|
|
299
|
+
branch: params.name
|
|
300
|
+
});
|
|
301
|
+
return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
|
|
302
|
+
} catch (error) {
|
|
303
|
+
return adminError(409, error instanceof Error ? error.message : String(error));
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
"GET /requests": ({ url, namespace }) => {
|
|
307
|
+
const status = url.searchParams.get("status");
|
|
308
|
+
const since = url.searchParams.get("since");
|
|
309
|
+
const limit = url.searchParams.get("limit");
|
|
310
|
+
const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
|
|
311
|
+
if (since !== null && sinceMs === void 0) {
|
|
312
|
+
return adminError(400, "since: expected epoch ms or ISO-8601");
|
|
313
|
+
}
|
|
314
|
+
if (status !== null && !/^\d{3}$/.test(status))
|
|
315
|
+
return adminError(400, "status: expected an HTTP status");
|
|
316
|
+
if (limit !== null && !/^\d+$/.test(limit))
|
|
317
|
+
return adminError(400, "limit: expected a count");
|
|
318
|
+
const operationId = url.searchParams.get("operationId");
|
|
319
|
+
const everyNamespace = url.searchParams.get("all") === "1";
|
|
320
|
+
return json(200, {
|
|
321
|
+
size: context.journal.size,
|
|
322
|
+
requests: context.journal.list({
|
|
323
|
+
...everyNamespace ? {} : { namespace },
|
|
324
|
+
...operationId !== null ? { operationId } : {},
|
|
325
|
+
...status !== null ? { status: Number(status) } : {},
|
|
326
|
+
...sinceMs !== void 0 ? { since: sinceMs } : {},
|
|
327
|
+
...limit !== null ? { limit: Number(limit) } : {}
|
|
328
|
+
})
|
|
329
|
+
});
|
|
330
|
+
},
|
|
331
|
+
"DELETE /requests": ({ url, namespace }) => {
|
|
332
|
+
context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
|
|
333
|
+
return json(200, { status: "ok" });
|
|
334
|
+
},
|
|
335
|
+
"GET /metrics": () => json(200, context.metrics.report()),
|
|
336
|
+
"DELETE /metrics": () => {
|
|
337
|
+
context.metrics.reset();
|
|
338
|
+
return json(200, { status: "ok" });
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
|
|
342
|
+
const space = key.indexOf(" ");
|
|
343
|
+
return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
|
|
344
|
+
});
|
|
345
|
+
return {
|
|
346
|
+
namespaceOf: headerNamespace,
|
|
347
|
+
async handle(request) {
|
|
348
|
+
const url = new URL(request.url);
|
|
349
|
+
if (url.pathname === HEALTH_PATH && request.method === "GET") {
|
|
350
|
+
return json(200, {
|
|
351
|
+
status: "ok",
|
|
352
|
+
service: context.name,
|
|
353
|
+
uptimeMs: context.wallNow() - context.startedAt,
|
|
354
|
+
clock: context.clock.state(),
|
|
355
|
+
namespaces: context.namespaces().length,
|
|
356
|
+
...context.describe()
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
|
|
360
|
+
return void 0;
|
|
361
|
+
}
|
|
362
|
+
if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
|
|
363
|
+
return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
|
|
364
|
+
}
|
|
365
|
+
const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
|
|
366
|
+
for (const route of routes) {
|
|
367
|
+
if (route.method !== request.method)
|
|
368
|
+
continue;
|
|
369
|
+
const params = matchRoute(route.pattern, path);
|
|
370
|
+
if (!params)
|
|
371
|
+
continue;
|
|
372
|
+
let body;
|
|
373
|
+
try {
|
|
374
|
+
body = await readJson(request);
|
|
375
|
+
} catch {
|
|
376
|
+
return adminError(400, "request body is not valid JSON");
|
|
377
|
+
}
|
|
378
|
+
return route.handler({
|
|
379
|
+
request,
|
|
380
|
+
url,
|
|
381
|
+
params,
|
|
382
|
+
namespace: adminNamespace(request, url),
|
|
383
|
+
body
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// ../core/dist/credentials.js
|
|
392
|
+
var bearerToken = (request) => {
|
|
393
|
+
const header = request.headers.get("authorization");
|
|
394
|
+
if (!header)
|
|
395
|
+
return void 0;
|
|
396
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
397
|
+
return match?.[1]?.trim() || void 0;
|
|
398
|
+
};
|
|
399
|
+
var createCredentialRegistry = () => {
|
|
400
|
+
const map = /* @__PURE__ */ new Map();
|
|
401
|
+
return {
|
|
402
|
+
set: (credential, namespace) => {
|
|
403
|
+
map.set(credential, namespace);
|
|
404
|
+
},
|
|
405
|
+
get: (credential) => map.get(credential),
|
|
406
|
+
remove: (credential) => map.delete(credential),
|
|
407
|
+
clear: () => map.clear(),
|
|
408
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
412
|
+
|
|
413
|
+
// ../core/dist/rng.js
|
|
414
|
+
var seedFrom = (value) => {
|
|
415
|
+
let hash = 2166136261;
|
|
416
|
+
for (let i = 0; i < value.length; i++) {
|
|
417
|
+
hash ^= value.charCodeAt(i);
|
|
418
|
+
hash = Math.imul(hash, 16777619);
|
|
419
|
+
}
|
|
420
|
+
return hash >>> 0;
|
|
421
|
+
};
|
|
422
|
+
var createRng = (seed = 0) => {
|
|
423
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
424
|
+
let state = numeric;
|
|
425
|
+
const next = () => {
|
|
426
|
+
state = state + 1831565813 >>> 0;
|
|
427
|
+
let t = state;
|
|
428
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
429
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
430
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
431
|
+
};
|
|
432
|
+
return {
|
|
433
|
+
next,
|
|
434
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
435
|
+
reset: () => {
|
|
436
|
+
state = numeric;
|
|
437
|
+
},
|
|
438
|
+
state: () => state,
|
|
439
|
+
setState: (next2) => {
|
|
440
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
441
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
442
|
+
}
|
|
443
|
+
state = next2 >>> 0;
|
|
444
|
+
},
|
|
445
|
+
seed: numeric
|
|
446
|
+
};
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// ../core/dist/faults.js
|
|
450
|
+
var matches = (rule, candidate) => {
|
|
451
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
455
|
+
return false;
|
|
456
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
460
|
+
return false;
|
|
461
|
+
return true;
|
|
462
|
+
};
|
|
463
|
+
var faultResponse = (rule) => {
|
|
464
|
+
const status = rule.status ?? 500;
|
|
465
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
466
|
+
if (typeof rule.body === "string")
|
|
467
|
+
return new Response(rule.body, { status, headers });
|
|
468
|
+
if (rule.body === null)
|
|
469
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
470
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
471
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
472
|
+
};
|
|
473
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
474
|
+
const entries = [];
|
|
475
|
+
return {
|
|
476
|
+
add(rule) {
|
|
477
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
478
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
479
|
+
if (existing >= 0)
|
|
480
|
+
entries[existing] = entry;
|
|
481
|
+
else
|
|
482
|
+
entries.push(entry);
|
|
483
|
+
return rule;
|
|
484
|
+
},
|
|
485
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
486
|
+
remove(id) {
|
|
487
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
488
|
+
if (index < 0)
|
|
489
|
+
return false;
|
|
490
|
+
entries.splice(index, 1);
|
|
491
|
+
return true;
|
|
492
|
+
},
|
|
493
|
+
clear() {
|
|
494
|
+
entries.length = 0;
|
|
495
|
+
},
|
|
496
|
+
async take(candidate) {
|
|
497
|
+
const hits = [];
|
|
498
|
+
for (const entry of entries) {
|
|
499
|
+
if (entry.remaining === 0)
|
|
500
|
+
continue;
|
|
501
|
+
if (!matches(entry.rule, candidate))
|
|
502
|
+
continue;
|
|
503
|
+
const rate = entry.rule.rate ?? 1;
|
|
504
|
+
if (rng.next() >= rate)
|
|
505
|
+
continue;
|
|
506
|
+
entry.hits++;
|
|
507
|
+
if (entry.remaining !== null)
|
|
508
|
+
entry.remaining--;
|
|
509
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
510
|
+
if (delay !== void 0 && delay > 0) {
|
|
511
|
+
await sleep(delay);
|
|
512
|
+
}
|
|
513
|
+
const hit = { id: entry.rule.id };
|
|
514
|
+
if (entry.rule.effect !== void 0) {
|
|
515
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
516
|
+
}
|
|
517
|
+
if (entry.rule.drop === true)
|
|
518
|
+
hit.drop = true;
|
|
519
|
+
else if (entry.rule.status !== void 0)
|
|
520
|
+
hit.response = faultResponse(entry.rule);
|
|
521
|
+
hits.push(hit);
|
|
522
|
+
if (hit.drop || hit.response)
|
|
523
|
+
break;
|
|
524
|
+
}
|
|
525
|
+
return hits;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
// ../../openapi/core/dist/refs.js
|
|
531
|
+
var OpenAPIReferenceError = class extends Error {
|
|
532
|
+
ref;
|
|
533
|
+
constructor(ref) {
|
|
534
|
+
super(`unresolvable $ref: ${ref}`);
|
|
535
|
+
this.ref = ref;
|
|
536
|
+
this.name = "OpenAPIReferenceError";
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
540
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
541
|
+
var resolveRef = (document2, ref) => {
|
|
542
|
+
if (!ref.startsWith("#/"))
|
|
543
|
+
throw new OpenAPIReferenceError(ref);
|
|
544
|
+
let cursor = document2;
|
|
545
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
546
|
+
const segment = unescapePointer(raw);
|
|
547
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
548
|
+
throw new OpenAPIReferenceError(ref);
|
|
549
|
+
}
|
|
550
|
+
cursor = cursor[segment];
|
|
551
|
+
}
|
|
552
|
+
if (cursor === void 0)
|
|
553
|
+
throw new OpenAPIReferenceError(ref);
|
|
554
|
+
return cursor;
|
|
555
|
+
};
|
|
556
|
+
var deref = (document2, value) => {
|
|
557
|
+
let current = value;
|
|
558
|
+
const seen = /* @__PURE__ */ new Set();
|
|
559
|
+
while (isReference(current)) {
|
|
560
|
+
if (seen.has(current.$ref))
|
|
561
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
562
|
+
seen.add(current.$ref);
|
|
563
|
+
current = resolveRef(document2, current.$ref);
|
|
564
|
+
}
|
|
565
|
+
return current;
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
// ../../openapi/core/dist/types.js
|
|
569
|
+
var HTTP_METHODS = [
|
|
570
|
+
"get",
|
|
571
|
+
"put",
|
|
572
|
+
"post",
|
|
573
|
+
"delete",
|
|
574
|
+
"options",
|
|
575
|
+
"head",
|
|
576
|
+
"patch",
|
|
577
|
+
"trace"
|
|
578
|
+
];
|
|
579
|
+
|
|
580
|
+
// ../../openapi/core/dist/document.js
|
|
581
|
+
var mergeParameters = (document2, item, own) => {
|
|
582
|
+
const merged = /* @__PURE__ */ new Map();
|
|
583
|
+
for (const raw of item.parameters ?? []) {
|
|
584
|
+
const parameter = deref(document2, raw);
|
|
585
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
586
|
+
}
|
|
587
|
+
for (const raw of own ?? []) {
|
|
588
|
+
const parameter = deref(document2, raw);
|
|
589
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
590
|
+
}
|
|
591
|
+
return [...merged.values()];
|
|
592
|
+
};
|
|
593
|
+
var listOperations = (document2) => {
|
|
594
|
+
const operations = [];
|
|
595
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
596
|
+
for (const method of HTTP_METHODS) {
|
|
597
|
+
const operation = item[method];
|
|
598
|
+
if (operation?.operationId === void 0)
|
|
599
|
+
continue;
|
|
600
|
+
const responses = {};
|
|
601
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
602
|
+
responses[status] = deref(document2, response);
|
|
603
|
+
}
|
|
604
|
+
operations.push({
|
|
605
|
+
operationId: operation.operationId,
|
|
606
|
+
method,
|
|
607
|
+
path,
|
|
608
|
+
operation,
|
|
609
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
610
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
611
|
+
responses
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return operations;
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
// ../../openapi/core/dist/schema.js
|
|
619
|
+
var resolveSchema = (document2, schema) => {
|
|
620
|
+
let current = schema;
|
|
621
|
+
const seen = /* @__PURE__ */ new Set();
|
|
622
|
+
while (typeof current.$ref === "string") {
|
|
623
|
+
const ref = current.$ref;
|
|
624
|
+
if (seen.has(ref))
|
|
625
|
+
break;
|
|
626
|
+
seen.add(ref);
|
|
627
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
628
|
+
const target = resolveRef(document2, ref);
|
|
629
|
+
current = { ...target, ...siblings };
|
|
630
|
+
}
|
|
631
|
+
if (current.nullable === true) {
|
|
632
|
+
const { nullable: _nullable, ...rest } = current;
|
|
633
|
+
const types = schemaTypes(rest);
|
|
634
|
+
if (types.length > 0 && !types.includes("null"))
|
|
635
|
+
current = { ...rest, type: [...types, "null"] };
|
|
636
|
+
else
|
|
637
|
+
current = rest;
|
|
638
|
+
}
|
|
639
|
+
return current;
|
|
640
|
+
};
|
|
641
|
+
var schemaTypes = (schema) => {
|
|
642
|
+
if (Array.isArray(schema.type))
|
|
643
|
+
return schema.type;
|
|
644
|
+
if (schema.type !== void 0)
|
|
645
|
+
return [schema.type];
|
|
646
|
+
const inferred = [];
|
|
647
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
648
|
+
inferred.push("object");
|
|
649
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
650
|
+
inferred.push("array");
|
|
651
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
652
|
+
inferred.push("string");
|
|
653
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
654
|
+
inferred.push("number");
|
|
655
|
+
return inferred;
|
|
656
|
+
};
|
|
657
|
+
var jsonTypeOf = (value) => {
|
|
658
|
+
if (value === null)
|
|
659
|
+
return "null";
|
|
660
|
+
if (Array.isArray(value))
|
|
661
|
+
return "array";
|
|
662
|
+
switch (typeof value) {
|
|
663
|
+
case "string":
|
|
664
|
+
return "string";
|
|
665
|
+
case "boolean":
|
|
666
|
+
return "boolean";
|
|
667
|
+
case "number":
|
|
668
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
669
|
+
case "object":
|
|
670
|
+
return "object";
|
|
671
|
+
default:
|
|
672
|
+
return "undefined";
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
var deepEqual = (a, b) => {
|
|
676
|
+
if (a === b)
|
|
677
|
+
return true;
|
|
678
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
679
|
+
return false;
|
|
680
|
+
if (Array.isArray(a)) {
|
|
681
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
682
|
+
}
|
|
683
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
684
|
+
const ka = Object.keys(a);
|
|
685
|
+
const kb = Object.keys(b);
|
|
686
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
687
|
+
}
|
|
688
|
+
return false;
|
|
689
|
+
};
|
|
690
|
+
var FORMAT_PATTERNS = {
|
|
691
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
|
692
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
693
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
694
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
695
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
696
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
697
|
+
};
|
|
698
|
+
var graphemeLength = (value) => [...value].length;
|
|
699
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
700
|
+
const errors = [];
|
|
701
|
+
const s = resolveSchema(document2, schema);
|
|
702
|
+
const fail = (message) => errors.push({ path, message });
|
|
703
|
+
const actual = jsonTypeOf(value);
|
|
704
|
+
if (actual === "undefined") {
|
|
705
|
+
fail("value is undefined");
|
|
706
|
+
return errors;
|
|
707
|
+
}
|
|
708
|
+
const types = schemaTypes(s);
|
|
709
|
+
if (types.length > 0) {
|
|
710
|
+
const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
711
|
+
if (!ok) {
|
|
712
|
+
fail(`expected type ${types.join("|")}, got ${actual}`);
|
|
713
|
+
return errors;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
717
|
+
fail("value not in enum");
|
|
718
|
+
}
|
|
719
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
720
|
+
fail("value does not equal const");
|
|
721
|
+
if (typeof value === "string") {
|
|
722
|
+
const length = graphemeLength(value);
|
|
723
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
724
|
+
fail(`length ${length} < minLength ${s.minLength}`);
|
|
725
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
726
|
+
fail(`length ${length} > maxLength ${s.maxLength}`);
|
|
727
|
+
if (s.pattern !== void 0) {
|
|
728
|
+
try {
|
|
729
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
730
|
+
fail(`does not match pattern ${s.pattern}`);
|
|
731
|
+
} catch {
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (s.format !== void 0) {
|
|
735
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
736
|
+
if (pattern && !pattern.test(value))
|
|
737
|
+
fail(`does not match format ${s.format}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (typeof value === "number") {
|
|
741
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
742
|
+
fail(`${value} < minimum ${s.minimum}`);
|
|
743
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
744
|
+
fail(`${value} > maximum ${s.maximum}`);
|
|
745
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
746
|
+
fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
747
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
748
|
+
fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
749
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
750
|
+
fail(`${value} is not a multiple of ${s.multipleOf}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (Array.isArray(value)) {
|
|
754
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
755
|
+
fail(`${value.length} items < minItems ${s.minItems}`);
|
|
756
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
757
|
+
fail(`${value.length} items > maxItems ${s.maxItems}`);
|
|
758
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
759
|
+
fail("items are not unique");
|
|
760
|
+
value.forEach((item, i) => {
|
|
761
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
762
|
+
if (itemSchema)
|
|
763
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
if (actual === "object") {
|
|
767
|
+
const record = value;
|
|
768
|
+
const keys = Object.keys(record);
|
|
769
|
+
for (const name of s.required ?? [])
|
|
770
|
+
if (!(name in record))
|
|
771
|
+
fail(`missing required property ${name}`);
|
|
772
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
773
|
+
fail(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
774
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
775
|
+
fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
776
|
+
for (const key of keys) {
|
|
777
|
+
const property = s.properties?.[key];
|
|
778
|
+
if (property) {
|
|
779
|
+
errors.push(...validateValue(document2, property, record[key], [...path, key]));
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (s.additionalProperties === false)
|
|
783
|
+
fail(`unexpected property ${key}`);
|
|
784
|
+
else if (typeof s.additionalProperties === "object") {
|
|
785
|
+
errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
|
|
786
|
+
}
|
|
787
|
+
if (s.propertyNames) {
|
|
788
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
789
|
+
if (nameErrors.length > 0)
|
|
790
|
+
fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (s.allOf)
|
|
795
|
+
for (const branch of s.allOf)
|
|
796
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
797
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
798
|
+
fail("matches no anyOf branch");
|
|
799
|
+
if (s.oneOf) {
|
|
800
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
801
|
+
if (matches2 !== 1)
|
|
802
|
+
fail(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
803
|
+
}
|
|
804
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
805
|
+
fail("matches forbidden `not` schema");
|
|
806
|
+
return errors;
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
// ../../http/codec/dist/form.js
|
|
810
|
+
var parsePath = (rawKey) => {
|
|
811
|
+
const open = rawKey.indexOf("[");
|
|
812
|
+
if (open === -1)
|
|
813
|
+
return [rawKey];
|
|
814
|
+
const path = [rawKey.slice(0, open)];
|
|
815
|
+
const rest = rawKey.slice(open);
|
|
816
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
817
|
+
let match = pattern.exec(rest);
|
|
818
|
+
let consumed = 0;
|
|
819
|
+
while (match !== null) {
|
|
820
|
+
if (match.index !== consumed)
|
|
821
|
+
return [rawKey];
|
|
822
|
+
path.push(match[1] ?? "");
|
|
823
|
+
consumed = match.index + match[0].length;
|
|
824
|
+
match = pattern.exec(rest);
|
|
825
|
+
}
|
|
826
|
+
if (consumed !== rest.length)
|
|
827
|
+
return [rawKey];
|
|
828
|
+
return path;
|
|
829
|
+
};
|
|
830
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
831
|
+
var put = (target, key, value) => {
|
|
832
|
+
if (key === "__proto__") {
|
|
833
|
+
Object.defineProperty(target, key, {
|
|
834
|
+
value,
|
|
835
|
+
enumerable: true,
|
|
836
|
+
writable: true,
|
|
837
|
+
configurable: true
|
|
838
|
+
});
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
;
|
|
842
|
+
target[key] = value;
|
|
843
|
+
};
|
|
844
|
+
var assign = (target, path, value) => {
|
|
845
|
+
let cursor = target;
|
|
846
|
+
for (let i = 0; i < path.length; i++) {
|
|
847
|
+
const segment = path[i];
|
|
848
|
+
const last = i === path.length - 1;
|
|
849
|
+
if (Array.isArray(cursor)) {
|
|
850
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
851
|
+
if (index === void 0)
|
|
852
|
+
return;
|
|
853
|
+
if (last) {
|
|
854
|
+
put(cursor, index, value);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
858
|
+
if (next === void 0 || typeof next === "string") {
|
|
859
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
860
|
+
put(cursor, index, created);
|
|
861
|
+
cursor = created;
|
|
862
|
+
} else {
|
|
863
|
+
cursor = next;
|
|
864
|
+
}
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if (typeof cursor === "string")
|
|
868
|
+
return;
|
|
869
|
+
if (last) {
|
|
870
|
+
put(cursor, segment, value);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
const nextSegment = path[i + 1];
|
|
874
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
875
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
876
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
877
|
+
put(cursor, segment, created);
|
|
878
|
+
cursor = created;
|
|
879
|
+
} else {
|
|
880
|
+
cursor = existing;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
var decodeFormPairs = (pairs) => {
|
|
885
|
+
const out = {};
|
|
886
|
+
for (const [rawKey, value] of pairs)
|
|
887
|
+
assign(out, parsePath(rawKey), value);
|
|
888
|
+
return densify(out);
|
|
889
|
+
};
|
|
890
|
+
var densify = (value) => {
|
|
891
|
+
if (typeof value === "string")
|
|
892
|
+
return value;
|
|
893
|
+
if (Array.isArray(value))
|
|
894
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
895
|
+
const out = {};
|
|
896
|
+
for (const [key, item] of Object.entries(value))
|
|
897
|
+
put(out, key, densify(item));
|
|
898
|
+
return out;
|
|
899
|
+
};
|
|
900
|
+
var decodeForm = (text2) => {
|
|
901
|
+
const source = text2.startsWith("?") ? text2.slice(1) : text2;
|
|
902
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
903
|
+
};
|
|
904
|
+
|
|
905
|
+
// ../../http/codec/dist/content.js
|
|
906
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
907
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
908
|
+
var mediaTypeOf = (contentType) => {
|
|
909
|
+
if (!contentType)
|
|
910
|
+
return void 0;
|
|
911
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
912
|
+
return essence ? essence : void 0;
|
|
913
|
+
};
|
|
914
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
915
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
916
|
+
var decodeBody = (contentType, bytes) => {
|
|
917
|
+
if (bytes.byteLength === 0)
|
|
918
|
+
return { kind: "empty" };
|
|
919
|
+
const mediaType = mediaTypeOf(contentType);
|
|
920
|
+
if (mediaType === void 0)
|
|
921
|
+
return { kind: "bytes", value: bytes };
|
|
922
|
+
if (isJsonMediaType(mediaType)) {
|
|
923
|
+
const text2 = utf8.decode(bytes);
|
|
924
|
+
try {
|
|
925
|
+
return { kind: "json", value: JSON.parse(text2) };
|
|
926
|
+
} catch (error) {
|
|
927
|
+
return {
|
|
928
|
+
kind: "invalid",
|
|
929
|
+
mediaType,
|
|
930
|
+
text: text2,
|
|
931
|
+
error: error instanceof Error ? error.message : String(error)
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
936
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
937
|
+
}
|
|
938
|
+
if (mediaType.startsWith("text/"))
|
|
939
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
940
|
+
return { kind: "bytes", value: bytes };
|
|
941
|
+
};
|
|
942
|
+
var readBody = async (message) => {
|
|
943
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
944
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
945
|
+
};
|
|
946
|
+
|
|
947
|
+
// ../core/dist/http.js
|
|
948
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
949
|
+
status,
|
|
950
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
951
|
+
});
|
|
952
|
+
var HttpError = class extends Error {
|
|
953
|
+
status;
|
|
954
|
+
body;
|
|
955
|
+
headers;
|
|
956
|
+
constructor(status, body, headers = {}) {
|
|
957
|
+
super(`HTTP ${status}`);
|
|
958
|
+
this.status = status;
|
|
959
|
+
this.body = body;
|
|
960
|
+
this.headers = headers;
|
|
961
|
+
this.name = "HttpError";
|
|
962
|
+
}
|
|
963
|
+
toResponse() {
|
|
964
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
965
|
+
if (contentType === "text/plain") {
|
|
966
|
+
return new Response(String(this.body), {
|
|
967
|
+
status: this.status,
|
|
968
|
+
headers: this.headers
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
// ../core/dist/ids.js
|
|
976
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
977
|
+
var mix = (input) => {
|
|
978
|
+
let hash = 2166136261;
|
|
979
|
+
for (let i = 0; i < input.length; i++) {
|
|
980
|
+
hash ^= input.charCodeAt(i);
|
|
981
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
982
|
+
}
|
|
983
|
+
hash ^= hash >>> 16;
|
|
984
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
985
|
+
hash ^= hash >>> 13;
|
|
986
|
+
return hash >>> 0;
|
|
987
|
+
};
|
|
988
|
+
var opaqueToken = (input, length) => {
|
|
989
|
+
let out = "";
|
|
990
|
+
let round = 0;
|
|
991
|
+
while (out.length < length) {
|
|
992
|
+
let hash = mix(`${input}:${round++}`);
|
|
993
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
994
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
995
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return out;
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
// ../core/dist/journal.js
|
|
1002
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1003
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1004
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1005
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1006
|
+
let sequence = 0;
|
|
1007
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1008
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1009
|
+
return {
|
|
1010
|
+
size: capacity,
|
|
1011
|
+
record(entry) {
|
|
1012
|
+
if (capacity === 0)
|
|
1013
|
+
return;
|
|
1014
|
+
order.set(entry, sequence++);
|
|
1015
|
+
let ring = rings.get(entry.namespace);
|
|
1016
|
+
if (!ring) {
|
|
1017
|
+
ring = { entries: [], next: 0 };
|
|
1018
|
+
rings.set(entry.namespace, ring);
|
|
1019
|
+
}
|
|
1020
|
+
if (ring.entries.length < capacity)
|
|
1021
|
+
ring.entries.push(entry);
|
|
1022
|
+
else {
|
|
1023
|
+
ring.entries[ring.next] = entry;
|
|
1024
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
list(query = {}) {
|
|
1028
|
+
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));
|
|
1029
|
+
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));
|
|
1030
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1031
|
+
},
|
|
1032
|
+
clear(namespace) {
|
|
1033
|
+
if (namespace === void 0)
|
|
1034
|
+
rings.clear();
|
|
1035
|
+
else
|
|
1036
|
+
rings.delete(namespace);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
};
|
|
1040
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1041
|
+
var annotateResponse = (response, extra) => {
|
|
1042
|
+
const existing = notes.get(response);
|
|
1043
|
+
notes.set(response, {
|
|
1044
|
+
...existing,
|
|
1045
|
+
...extra,
|
|
1046
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1047
|
+
});
|
|
1048
|
+
return response;
|
|
1049
|
+
};
|
|
1050
|
+
var responseNotes = (response) => notes.get(response);
|
|
1051
|
+
|
|
1052
|
+
// ../core/dist/metrics.js
|
|
1053
|
+
var createMetrics = () => {
|
|
1054
|
+
let requests = 0;
|
|
1055
|
+
let faults = 0;
|
|
1056
|
+
let totalDurationMs = 0;
|
|
1057
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1058
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1059
|
+
return {
|
|
1060
|
+
record(entry) {
|
|
1061
|
+
requests++;
|
|
1062
|
+
totalDurationMs += entry.durationMs;
|
|
1063
|
+
if (entry.faultId !== void 0)
|
|
1064
|
+
faults++;
|
|
1065
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1066
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1067
|
+
if (entry.unmatched) {
|
|
1068
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1069
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1070
|
+
}
|
|
1071
|
+
},
|
|
1072
|
+
report: () => ({
|
|
1073
|
+
requests,
|
|
1074
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1075
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1076
|
+
const space = route.indexOf(" ");
|
|
1077
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1078
|
+
}),
|
|
1079
|
+
faults,
|
|
1080
|
+
totalDurationMs
|
|
1081
|
+
}),
|
|
1082
|
+
reset() {
|
|
1083
|
+
requests = 0;
|
|
1084
|
+
faults = 0;
|
|
1085
|
+
totalDurationMs = 0;
|
|
1086
|
+
byOperation.clear();
|
|
1087
|
+
unmatched.clear();
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
};
|
|
1091
|
+
|
|
1092
|
+
// ../../core/dist/timeline.js
|
|
1093
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1094
|
+
var Timeline = class {
|
|
1095
|
+
maxCheckpoints;
|
|
1096
|
+
now;
|
|
1097
|
+
makeId;
|
|
1098
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1099
|
+
heads = /* @__PURE__ */ new Map();
|
|
1100
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1101
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1102
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1103
|
+
references = /* @__PURE__ */ new Map();
|
|
1104
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1105
|
+
sequence = 0;
|
|
1106
|
+
constructor(options = {}) {
|
|
1107
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1108
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1109
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1110
|
+
this.maxCheckpoints = max;
|
|
1111
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1112
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1113
|
+
}
|
|
1114
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1115
|
+
commit(value, options = {}) {
|
|
1116
|
+
const branch = options.branch ?? "main";
|
|
1117
|
+
this.assertBranch(branch);
|
|
1118
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1119
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1120
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1121
|
+
const id = this.makeId(++this.sequence);
|
|
1122
|
+
if (this.nodes.has(id))
|
|
1123
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1124
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1125
|
+
this.nodes.set(id, checkpoint);
|
|
1126
|
+
this.moveHead(branch, id);
|
|
1127
|
+
this.collect(this.maxCheckpoints);
|
|
1128
|
+
return checkpoint;
|
|
1129
|
+
}
|
|
1130
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1131
|
+
fork(branch, options = {}) {
|
|
1132
|
+
this.assertBranch(branch);
|
|
1133
|
+
if (this.heads.has(branch))
|
|
1134
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1135
|
+
const from = options.from ?? this.heads.get("main");
|
|
1136
|
+
if (from === void 0)
|
|
1137
|
+
return void 0;
|
|
1138
|
+
const checkpoint = this.get(from);
|
|
1139
|
+
this.moveHead(branch, checkpoint.id);
|
|
1140
|
+
return checkpoint;
|
|
1141
|
+
}
|
|
1142
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1143
|
+
checkout(branch, id) {
|
|
1144
|
+
this.assertBranch(branch);
|
|
1145
|
+
const checkpoint = this.get(id);
|
|
1146
|
+
this.moveHead(branch, checkpoint.id);
|
|
1147
|
+
return checkpoint;
|
|
1148
|
+
}
|
|
1149
|
+
get(id) {
|
|
1150
|
+
const checkpoint = this.nodes.get(id);
|
|
1151
|
+
if (!checkpoint)
|
|
1152
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1153
|
+
return checkpoint;
|
|
1154
|
+
}
|
|
1155
|
+
head(branch = "main") {
|
|
1156
|
+
const id = this.heads.get(branch);
|
|
1157
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1158
|
+
}
|
|
1159
|
+
hasBranch(branch) {
|
|
1160
|
+
return this.heads.has(branch);
|
|
1161
|
+
}
|
|
1162
|
+
branches() {
|
|
1163
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1164
|
+
}
|
|
1165
|
+
checkpoints() {
|
|
1166
|
+
return [...this.nodes.values()];
|
|
1167
|
+
}
|
|
1168
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1169
|
+
get size() {
|
|
1170
|
+
return this.nodes.size;
|
|
1171
|
+
}
|
|
1172
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1173
|
+
retain(id) {
|
|
1174
|
+
const checkpoint = this.get(id);
|
|
1175
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1176
|
+
this.addReference(id);
|
|
1177
|
+
return checkpoint;
|
|
1178
|
+
}
|
|
1179
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1180
|
+
release(id) {
|
|
1181
|
+
if (!this.nodes.has(id))
|
|
1182
|
+
return false;
|
|
1183
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1184
|
+
if (pins === 0)
|
|
1185
|
+
return false;
|
|
1186
|
+
if (pins === 1)
|
|
1187
|
+
this.explicitPins.delete(id);
|
|
1188
|
+
else
|
|
1189
|
+
this.explicitPins.set(id, pins - 1);
|
|
1190
|
+
this.removeReference(id);
|
|
1191
|
+
this.collect(this.maxCheckpoints);
|
|
1192
|
+
return true;
|
|
1193
|
+
}
|
|
1194
|
+
deleteBranch(branch) {
|
|
1195
|
+
if (branch === "main")
|
|
1196
|
+
throw new RangeError("cannot delete main branch");
|
|
1197
|
+
const previous = this.heads.get(branch);
|
|
1198
|
+
const deleted = this.heads.delete(branch);
|
|
1199
|
+
if (previous !== void 0)
|
|
1200
|
+
this.removeReference(previous);
|
|
1201
|
+
this.collect(this.maxCheckpoints);
|
|
1202
|
+
return deleted;
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1206
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1207
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1208
|
+
*/
|
|
1209
|
+
gc(max = this.maxCheckpoints) {
|
|
1210
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1211
|
+
throw new RangeError("max must be a positive integer");
|
|
1212
|
+
const removed = [];
|
|
1213
|
+
this.collect(max, removed);
|
|
1214
|
+
return removed;
|
|
1215
|
+
}
|
|
1216
|
+
collect(max, removed) {
|
|
1217
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1218
|
+
const id = this.evictable.values().next().value;
|
|
1219
|
+
this.evictable.delete(id);
|
|
1220
|
+
this.nodes.delete(id);
|
|
1221
|
+
removed?.push(id);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
moveHead(branch, id) {
|
|
1225
|
+
const previous = this.heads.get(branch);
|
|
1226
|
+
if (previous === id)
|
|
1227
|
+
return;
|
|
1228
|
+
if (previous !== void 0)
|
|
1229
|
+
this.removeReference(previous);
|
|
1230
|
+
this.heads.set(branch, id);
|
|
1231
|
+
this.addReference(id);
|
|
1232
|
+
}
|
|
1233
|
+
addReference(id) {
|
|
1234
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1235
|
+
this.evictable.delete(id);
|
|
1236
|
+
}
|
|
1237
|
+
removeReference(id) {
|
|
1238
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1239
|
+
if (next > 0)
|
|
1240
|
+
this.references.set(id, next);
|
|
1241
|
+
else {
|
|
1242
|
+
this.references.delete(id);
|
|
1243
|
+
if (this.nodes.has(id))
|
|
1244
|
+
this.evictable.add(id);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
assertBranch(branch) {
|
|
1248
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1249
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
// ../../sqlite/dist/default.js
|
|
1254
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1255
|
+
var createDefaultSqlite = () => new Database();
|
|
1256
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1257
|
+
|
|
1258
|
+
// ../../sqlite/dist/migrate.js
|
|
1259
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1260
|
+
sqlite.exec(`
|
|
1261
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1262
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1263
|
+
applied_at INTEGER NOT NULL
|
|
1264
|
+
)
|
|
1265
|
+
`);
|
|
1266
|
+
};
|
|
1267
|
+
var migrate = (sqlite, migrations) => {
|
|
1268
|
+
ensureMigrationsTable(sqlite);
|
|
1269
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1270
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1271
|
+
if (pending.length === 0)
|
|
1272
|
+
return;
|
|
1273
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1274
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1275
|
+
sqlite.transaction(() => {
|
|
1276
|
+
for (const migration of pending) {
|
|
1277
|
+
sqlite.exec(migration.sql);
|
|
1278
|
+
insert.run(migration.id, now);
|
|
1279
|
+
}
|
|
1280
|
+
});
|
|
1281
|
+
};
|
|
1282
|
+
|
|
1283
|
+
// ../../sqlite/dist/schema.js
|
|
1284
|
+
var CORE_MIGRATIONS = [
|
|
1285
|
+
{
|
|
1286
|
+
id: "20260322_core_records_sequences",
|
|
1287
|
+
sql: `
|
|
1288
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1289
|
+
namespace TEXT NOT NULL,
|
|
1290
|
+
collection TEXT NOT NULL,
|
|
1291
|
+
id TEXT NOT NULL,
|
|
1292
|
+
seq INTEGER NOT NULL,
|
|
1293
|
+
value TEXT NOT NULL,
|
|
1294
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1295
|
+
);
|
|
1296
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1297
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1298
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1299
|
+
namespace TEXT NOT NULL,
|
|
1300
|
+
name TEXT NOT NULL,
|
|
1301
|
+
kind TEXT NOT NULL,
|
|
1302
|
+
value INTEGER NOT NULL,
|
|
1303
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1304
|
+
);
|
|
1305
|
+
`
|
|
1306
|
+
}
|
|
1307
|
+
];
|
|
1308
|
+
var migrateCore = (sqlite) => {
|
|
1309
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1310
|
+
};
|
|
1311
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1312
|
+
sqlite.transaction(() => {
|
|
1313
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1314
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1315
|
+
});
|
|
1316
|
+
};
|
|
1317
|
+
|
|
1318
|
+
// ../../openapi/metadata/dist/types.js
|
|
1319
|
+
var EXTENSION_KEYS = {
|
|
1320
|
+
operation: "x-mockingbird",
|
|
1321
|
+
resource: "x-mockingbird-resource",
|
|
1322
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1323
|
+
volatile: "x-mockingbird-volatile",
|
|
1324
|
+
scope: "x-mockingbird-scope",
|
|
1325
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1326
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1327
|
+
};
|
|
1328
|
+
|
|
1329
|
+
// ../../openapi/metadata/dist/read.js
|
|
1330
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1331
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1332
|
+
var operationMetadata = (operation) => {
|
|
1333
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1334
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1335
|
+
const supported = ext.supported ?? true;
|
|
1336
|
+
const parity = ext.parity ?? {};
|
|
1337
|
+
return {
|
|
1338
|
+
supported,
|
|
1339
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1340
|
+
parity: {
|
|
1341
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1342
|
+
safe: parity.safe ?? true,
|
|
1343
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
};
|
|
1347
|
+
|
|
1348
|
+
// ../core/dist/service.js
|
|
1349
|
+
import { Hono } from "hono";
|
|
1350
|
+
var defineOperations = (handlers) => handlers;
|
|
1351
|
+
var OperationRegistryError = class extends Error {
|
|
1352
|
+
problems;
|
|
1353
|
+
constructor(problems) {
|
|
1354
|
+
super(`operation registry is inconsistent:
|
|
1355
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1356
|
+
this.problems = problems;
|
|
1357
|
+
this.name = "OperationRegistryError";
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
var verifyOperations = (document2, handlers) => {
|
|
1361
|
+
const problems = [];
|
|
1362
|
+
const operations = listOperations(document2);
|
|
1363
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1364
|
+
for (const operation of operations) {
|
|
1365
|
+
if (seen.has(operation.operationId))
|
|
1366
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1367
|
+
seen.add(operation.operationId);
|
|
1368
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1369
|
+
const handler = handlers[operation.operationId];
|
|
1370
|
+
if (supported && !handler)
|
|
1371
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1372
|
+
if (!supported && handler)
|
|
1373
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1374
|
+
}
|
|
1375
|
+
for (const id of Object.keys(handlers)) {
|
|
1376
|
+
if (!seen.has(id))
|
|
1377
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1378
|
+
}
|
|
1379
|
+
return problems;
|
|
1380
|
+
};
|
|
1381
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1382
|
+
var routeOrder = (a, b) => {
|
|
1383
|
+
const sa = a.path.split("/");
|
|
1384
|
+
const sb = b.path.split("/");
|
|
1385
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1386
|
+
const x = sa[i] ?? "";
|
|
1387
|
+
const y = sb[i] ?? "";
|
|
1388
|
+
const px = x.startsWith("{");
|
|
1389
|
+
const py = y.startsWith("{");
|
|
1390
|
+
if (px !== py)
|
|
1391
|
+
return px ? 1 : -1;
|
|
1392
|
+
if (x !== y)
|
|
1393
|
+
return x < y ? -1 : 1;
|
|
1394
|
+
}
|
|
1395
|
+
return 0;
|
|
1396
|
+
};
|
|
1397
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1398
|
+
var bootSqlite = (sqlite) => {
|
|
1399
|
+
const client = resolveSqlite(sqlite);
|
|
1400
|
+
migrateCore(client);
|
|
1401
|
+
return client;
|
|
1402
|
+
};
|
|
1403
|
+
var createService = (options) => {
|
|
1404
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1405
|
+
if (problems.length > 0)
|
|
1406
|
+
throw new OperationRegistryError(problems);
|
|
1407
|
+
migrateCore(options.sqlite);
|
|
1408
|
+
const now = options.now ?? (() => Date.now());
|
|
1409
|
+
const app = new Hono();
|
|
1410
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1411
|
+
app.onError((error, c) => options.onError(error, c.req.raw));
|
|
1412
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1413
|
+
for (const operation of operations) {
|
|
1414
|
+
const metadata = operationMetadata(operation.operation);
|
|
1415
|
+
const handler = options.handlers[operation.operationId];
|
|
1416
|
+
const route = async (c) => {
|
|
1417
|
+
const request = c.req.raw;
|
|
1418
|
+
if (!metadata.supported || !handler) {
|
|
1419
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1420
|
+
}
|
|
1421
|
+
const url = new URL(request.url);
|
|
1422
|
+
const context = {
|
|
1423
|
+
request,
|
|
1424
|
+
url,
|
|
1425
|
+
params: c.req.param(),
|
|
1426
|
+
query: queryOf(url),
|
|
1427
|
+
body: await readBody(request),
|
|
1428
|
+
sqlite: options.sqlite,
|
|
1429
|
+
namespace: options.namespace,
|
|
1430
|
+
operation,
|
|
1431
|
+
document: options.document,
|
|
1432
|
+
now
|
|
1433
|
+
};
|
|
1434
|
+
const short = await options.before?.(context);
|
|
1435
|
+
if (short)
|
|
1436
|
+
return short;
|
|
1437
|
+
return handler(context);
|
|
1438
|
+
};
|
|
1439
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1440
|
+
}
|
|
1441
|
+
return {
|
|
1442
|
+
app,
|
|
1443
|
+
sqlite: options.sqlite,
|
|
1444
|
+
namespace: options.namespace,
|
|
1445
|
+
fetch: async (request) => app.fetch(request),
|
|
1446
|
+
reset: async () => {
|
|
1447
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
};
|
|
1451
|
+
|
|
1452
|
+
// ../core/dist/snapshot.js
|
|
1453
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1454
|
+
namespace,
|
|
1455
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1456
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1457
|
+
});
|
|
1458
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1459
|
+
sqlite.transaction(() => {
|
|
1460
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1461
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1462
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1463
|
+
for (const row of snapshot.records) {
|
|
1464
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1465
|
+
}
|
|
1466
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1467
|
+
for (const row of snapshot.sequences) {
|
|
1468
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1471
|
+
};
|
|
1472
|
+
|
|
1473
|
+
// ../core/dist/version.js
|
|
1474
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1475
|
+
|
|
1476
|
+
// ../core/dist/signing.js
|
|
1477
|
+
var encoder = new TextEncoder();
|
|
1478
|
+
var toBase64 = (bytes) => {
|
|
1479
|
+
let binary = "";
|
|
1480
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1481
|
+
binary += String.fromCharCode(byte);
|
|
1482
|
+
}
|
|
1483
|
+
return btoa(binary);
|
|
1484
|
+
};
|
|
1485
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1486
|
+
|
|
1487
|
+
// ../core/dist/webhooks.js
|
|
1488
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1489
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1490
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1491
|
+
var parseEndpoint = (value) => {
|
|
1492
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1493
|
+
return "each endpoint needs a url";
|
|
1494
|
+
try {
|
|
1495
|
+
new URL(value.url);
|
|
1496
|
+
} catch {
|
|
1497
|
+
return `not a URL: ${value.url}`;
|
|
1498
|
+
}
|
|
1499
|
+
const endpoint = { url: value.url };
|
|
1500
|
+
if (typeof value.id === "string")
|
|
1501
|
+
endpoint.id = value.id;
|
|
1502
|
+
if (typeof value.secret === "string")
|
|
1503
|
+
endpoint.secret = value.secret;
|
|
1504
|
+
if (typeof value.signUrl === "string")
|
|
1505
|
+
endpoint.signUrl = value.signUrl;
|
|
1506
|
+
const events = value.events ?? value.enabledEvents;
|
|
1507
|
+
if (Array.isArray(events))
|
|
1508
|
+
endpoint.events = events.map(String);
|
|
1509
|
+
if (isRecord3(value.tags)) {
|
|
1510
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1511
|
+
}
|
|
1512
|
+
if (typeof value.account === "string")
|
|
1513
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1514
|
+
if (isRecord3(value.headers)) {
|
|
1515
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1516
|
+
}
|
|
1517
|
+
return endpoint;
|
|
1518
|
+
};
|
|
1519
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1520
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1521
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1522
|
+
const type = url.searchParams.get("type");
|
|
1523
|
+
return type === null || d.type === type;
|
|
1524
|
+
})
|
|
1525
|
+
}),
|
|
1526
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1527
|
+
const type = url.searchParams.get("type");
|
|
1528
|
+
return json2(200, {
|
|
1529
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1530
|
+
});
|
|
1531
|
+
},
|
|
1532
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1533
|
+
const replayed = await hub.replay(params.id);
|
|
1534
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1535
|
+
},
|
|
1536
|
+
"POST /webhooks/flush": async () => {
|
|
1537
|
+
await hub.flush();
|
|
1538
|
+
return json2(200, { status: "ok" });
|
|
1539
|
+
},
|
|
1540
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1541
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1542
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1543
|
+
}
|
|
1544
|
+
const fault = { mode: body.mode };
|
|
1545
|
+
if (typeof body.count === "number")
|
|
1546
|
+
fault.count = body.count;
|
|
1547
|
+
hub.fault(namespace, fault);
|
|
1548
|
+
return json2(201, { namespace, ...fault });
|
|
1549
|
+
},
|
|
1550
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1551
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1552
|
+
...rest,
|
|
1553
|
+
secret: secret ? "(set)" : null
|
|
1554
|
+
}))
|
|
1555
|
+
}),
|
|
1556
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1557
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1558
|
+
if (!Array.isArray(list))
|
|
1559
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1560
|
+
const parsed = [];
|
|
1561
|
+
for (const each of list) {
|
|
1562
|
+
const endpoint = parseEndpoint(each);
|
|
1563
|
+
if (typeof endpoint === "string")
|
|
1564
|
+
return adminError2(400, endpoint);
|
|
1565
|
+
parsed.push(endpoint);
|
|
1566
|
+
}
|
|
1567
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1568
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1569
|
+
},
|
|
1570
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1571
|
+
hub.setEndpoints(namespace, []);
|
|
1572
|
+
return json2(200, { status: "ok" });
|
|
1573
|
+
}
|
|
1574
|
+
});
|
|
1575
|
+
var parsePayload = (message) => {
|
|
1576
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1577
|
+
try {
|
|
1578
|
+
return JSON.parse(message.body);
|
|
1579
|
+
} catch {
|
|
1580
|
+
return message.body;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1584
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1585
|
+
}
|
|
1586
|
+
return message.body;
|
|
1587
|
+
};
|
|
1588
|
+
|
|
1589
|
+
// ../core/dist/runtime.js
|
|
1590
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1591
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1592
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1593
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1594
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1595
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1596
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1597
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1598
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1599
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1600
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1601
|
+
if (!previous || previous.length === 0)
|
|
1602
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1603
|
+
const result = new Array(fresh.length);
|
|
1604
|
+
let unchanged = fresh.length === previous.length;
|
|
1605
|
+
let oldIndex = 0;
|
|
1606
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1607
|
+
const row = fresh[index];
|
|
1608
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1609
|
+
oldIndex++;
|
|
1610
|
+
}
|
|
1611
|
+
const old = previous[oldIndex];
|
|
1612
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1613
|
+
if (result[index] !== previous[index])
|
|
1614
|
+
unchanged = false;
|
|
1615
|
+
}
|
|
1616
|
+
return unchanged ? previous : result;
|
|
1617
|
+
};
|
|
1618
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1619
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1620
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1621
|
+
code = "MOCKINGBIRD_DROP";
|
|
1622
|
+
constructor() {
|
|
1623
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1624
|
+
this.name = "TypeError";
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
var operationMatcher = (document2) => {
|
|
1628
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1629
|
+
operationId: operation.operationId,
|
|
1630
|
+
method: operation.method.toUpperCase(),
|
|
1631
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1632
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1633
|
+
})).sort((a, b) => a.params - b.params);
|
|
1634
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1635
|
+
};
|
|
1636
|
+
var createRuntime = (options) => {
|
|
1637
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1638
|
+
const clock = options.clock ?? createClock();
|
|
1639
|
+
const rng = createRng(options.seed ?? 0);
|
|
1640
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1641
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1642
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1643
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1644
|
+
const metrics = createMetrics();
|
|
1645
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1646
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1647
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1648
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1649
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1650
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1651
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1652
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1653
|
+
const credentials = createCredentialRegistry();
|
|
1654
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1655
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1656
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1657
|
+
const existing = instances.get(key);
|
|
1658
|
+
if (existing)
|
|
1659
|
+
return existing;
|
|
1660
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1661
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1662
|
+
}
|
|
1663
|
+
const created = options.create({
|
|
1664
|
+
namespace: storageNamespace(key),
|
|
1665
|
+
publicNamespace,
|
|
1666
|
+
sqlite,
|
|
1667
|
+
clock,
|
|
1668
|
+
rng: isolatedRng ?? rng
|
|
1669
|
+
});
|
|
1670
|
+
instances.set(key, created);
|
|
1671
|
+
publicNamespaces.add(publicNamespace);
|
|
1672
|
+
if (isolatedRng)
|
|
1673
|
+
branchRngs.set(key, isolatedRng);
|
|
1674
|
+
return created;
|
|
1675
|
+
};
|
|
1676
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1677
|
+
const capture = (storage) => {
|
|
1678
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1679
|
+
const previous = captured.get(storage);
|
|
1680
|
+
const snapshot2 = {
|
|
1681
|
+
namespace: fresh.namespace,
|
|
1682
|
+
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),
|
|
1683
|
+
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)
|
|
1684
|
+
};
|
|
1685
|
+
Object.freeze(snapshot2.records);
|
|
1686
|
+
Object.freeze(snapshot2.sequences);
|
|
1687
|
+
Object.freeze(snapshot2);
|
|
1688
|
+
captured.set(storage, snapshot2);
|
|
1689
|
+
return Object.freeze({
|
|
1690
|
+
snapshot: snapshot2,
|
|
1691
|
+
clock: Object.freeze(clock.state()),
|
|
1692
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1693
|
+
});
|
|
1694
|
+
};
|
|
1695
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1696
|
+
let found = timelines.get(name);
|
|
1697
|
+
if (found)
|
|
1698
|
+
return found;
|
|
1699
|
+
instance(name);
|
|
1700
|
+
found = new Timeline({
|
|
1701
|
+
now: clock.now,
|
|
1702
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1703
|
+
});
|
|
1704
|
+
found.commit(capture(name));
|
|
1705
|
+
timelines.set(name, found);
|
|
1706
|
+
return found;
|
|
1707
|
+
};
|
|
1708
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1709
|
+
if (branch2 === "main")
|
|
1710
|
+
return namespace;
|
|
1711
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1712
|
+
const existing = branchStorage.get(mapKey);
|
|
1713
|
+
if (existing)
|
|
1714
|
+
return existing;
|
|
1715
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1716
|
+
branchStorage.set(mapKey, key);
|
|
1717
|
+
return key;
|
|
1718
|
+
};
|
|
1719
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1720
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1721
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1722
|
+
const history = timeline(namespace);
|
|
1723
|
+
if (branch2 === "main") {
|
|
1724
|
+
if (at !== void 0) {
|
|
1725
|
+
const point = history.checkout("main", at);
|
|
1726
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1727
|
+
captured.set(namespace, point.value.snapshot);
|
|
1728
|
+
rng.setState(point.value.rngState);
|
|
1729
|
+
clock.set(point.value.clock.now);
|
|
1730
|
+
if (point.value.clock.frozen)
|
|
1731
|
+
clock.freeze();
|
|
1732
|
+
else
|
|
1733
|
+
clock.unfreeze();
|
|
1734
|
+
}
|
|
1735
|
+
return namespace;
|
|
1736
|
+
}
|
|
1737
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1738
|
+
if (!history.hasBranch(branch2)) {
|
|
1739
|
+
if (at === void 0)
|
|
1740
|
+
history.commit(capture(namespace));
|
|
1741
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1742
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1743
|
+
if (point)
|
|
1744
|
+
branchRng.setState(point.value.rngState);
|
|
1745
|
+
instanceFor(storage, namespace, branchRng);
|
|
1746
|
+
if (point)
|
|
1747
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1748
|
+
if (point)
|
|
1749
|
+
captured.set(storage, point.value.snapshot);
|
|
1750
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1751
|
+
const point = history.checkout(branch2, at);
|
|
1752
|
+
if (!instances.has(storage)) {
|
|
1753
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1754
|
+
branchRng.setState(point.value.rngState);
|
|
1755
|
+
instanceFor(storage, namespace, branchRng);
|
|
1756
|
+
}
|
|
1757
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1758
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1759
|
+
captured.set(storage, point.value.snapshot);
|
|
1760
|
+
} else {
|
|
1761
|
+
if (!instances.has(storage)) {
|
|
1762
|
+
const point = history.head(branch2);
|
|
1763
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1764
|
+
if (point)
|
|
1765
|
+
branchRng.setState(point.value.rngState);
|
|
1766
|
+
instanceFor(storage, namespace, branchRng);
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
return storage;
|
|
1770
|
+
};
|
|
1771
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1772
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1773
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1774
|
+
};
|
|
1775
|
+
const branch = (name, branchOptions = {}) => {
|
|
1776
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1777
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1778
|
+
const head = timeline(namespace).head(name);
|
|
1779
|
+
if (!head)
|
|
1780
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1781
|
+
return head;
|
|
1782
|
+
};
|
|
1783
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1784
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1785
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1786
|
+
const history = timeline(namespace);
|
|
1787
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1788
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1789
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1790
|
+
captured.set(storage, point.value.snapshot);
|
|
1791
|
+
clock.set(point.value.clock.now);
|
|
1792
|
+
if (point.value.clock.frozen)
|
|
1793
|
+
clock.freeze();
|
|
1794
|
+
else
|
|
1795
|
+
clock.unfreeze();
|
|
1796
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1797
|
+
};
|
|
1798
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1799
|
+
if (name === "*") {
|
|
1800
|
+
options.webhooks?.clear();
|
|
1801
|
+
for (const each of instances.values())
|
|
1802
|
+
await each.reset();
|
|
1803
|
+
timelines.clear();
|
|
1804
|
+
branchStorage.clear();
|
|
1805
|
+
branchRngs.clear();
|
|
1806
|
+
captured.clear();
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
options.webhooks?.clear(name);
|
|
1810
|
+
const target = instances.get(name);
|
|
1811
|
+
if (target)
|
|
1812
|
+
await target.reset();
|
|
1813
|
+
else
|
|
1814
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1815
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1816
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1817
|
+
continue;
|
|
1818
|
+
const branchInstance = instances.get(storage);
|
|
1819
|
+
if (branchInstance)
|
|
1820
|
+
await branchInstance.reset();
|
|
1821
|
+
else
|
|
1822
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1823
|
+
branchStorage.delete(mapping);
|
|
1824
|
+
branchRngs.delete(storage);
|
|
1825
|
+
captured.delete(storage);
|
|
1826
|
+
}
|
|
1827
|
+
timelines.delete(name);
|
|
1828
|
+
captured.delete(name);
|
|
1829
|
+
};
|
|
1830
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1831
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1832
|
+
};
|
|
1833
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1834
|
+
instance(name);
|
|
1835
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1836
|
+
captured.set(name, from);
|
|
1837
|
+
const history = timelines.get(name);
|
|
1838
|
+
if (history)
|
|
1839
|
+
history.commit(capture(name), { branch: "main" });
|
|
1840
|
+
else
|
|
1841
|
+
timeline(name);
|
|
1842
|
+
};
|
|
1843
|
+
const runtime = {
|
|
1844
|
+
name: options.name,
|
|
1845
|
+
sqlite,
|
|
1846
|
+
clock,
|
|
1847
|
+
faults,
|
|
1848
|
+
metrics,
|
|
1849
|
+
journal,
|
|
1850
|
+
rng,
|
|
1851
|
+
credentials,
|
|
1852
|
+
webhooks: options.webhooks,
|
|
1853
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1854
|
+
const preset = options.presets?.[name];
|
|
1855
|
+
if (!preset)
|
|
1856
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1857
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1858
|
+
namespace,
|
|
1859
|
+
...rule,
|
|
1860
|
+
...overrides,
|
|
1861
|
+
preset: name,
|
|
1862
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1863
|
+
}));
|
|
1864
|
+
if (preset.webhook && options.webhooks) {
|
|
1865
|
+
options.webhooks.fault(namespace, {
|
|
1866
|
+
...preset.webhook,
|
|
1867
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1868
|
+
});
|
|
1869
|
+
}
|
|
1870
|
+
return added;
|
|
1871
|
+
},
|
|
1872
|
+
instance,
|
|
1873
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1874
|
+
reset,
|
|
1875
|
+
snapshot,
|
|
1876
|
+
restore,
|
|
1877
|
+
checkpoint,
|
|
1878
|
+
branch,
|
|
1879
|
+
checkout,
|
|
1880
|
+
timeline,
|
|
1881
|
+
fetch: async (incoming) => {
|
|
1882
|
+
let request = incoming;
|
|
1883
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1884
|
+
if (prefixed) {
|
|
1885
|
+
const url2 = new URL(request.url);
|
|
1886
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1887
|
+
const headers = new Headers(request.headers);
|
|
1888
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1889
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1890
|
+
}
|
|
1891
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1892
|
+
request = new Request(url2, {
|
|
1893
|
+
method: request.method,
|
|
1894
|
+
headers,
|
|
1895
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1896
|
+
signal: request.signal
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
let namespace = control.namespaceOf(request);
|
|
1900
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1901
|
+
const credential = options.credential(request);
|
|
1902
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1903
|
+
if (mapped !== void 0)
|
|
1904
|
+
namespace = mapped;
|
|
1905
|
+
}
|
|
1906
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1907
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1908
|
+
const stamp = (response2) => {
|
|
1909
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1910
|
+
try {
|
|
1911
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1912
|
+
return response2;
|
|
1913
|
+
} catch {
|
|
1914
|
+
const copy = new Response(response2.body, response2);
|
|
1915
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1916
|
+
return copy;
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
const handled = await control.handle(request);
|
|
1920
|
+
if (handled)
|
|
1921
|
+
return stamp(handled);
|
|
1922
|
+
const started = monotonicNow();
|
|
1923
|
+
const url = new URL(request.url);
|
|
1924
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1925
|
+
const log = (status, faultId, response2) => {
|
|
1926
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1927
|
+
const entry = {
|
|
1928
|
+
service: options.name,
|
|
1929
|
+
namespace,
|
|
1930
|
+
operationId,
|
|
1931
|
+
method: request.method,
|
|
1932
|
+
path: url.pathname,
|
|
1933
|
+
status,
|
|
1934
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1935
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1936
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1937
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1938
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1939
|
+
};
|
|
1940
|
+
metrics.record(entry);
|
|
1941
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
1942
|
+
options.onLog?.(entry);
|
|
1943
|
+
};
|
|
1944
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
1945
|
+
log(400);
|
|
1946
|
+
return stamp(new Response(JSON.stringify({
|
|
1947
|
+
error: {
|
|
1948
|
+
type: "mockingbird_admin",
|
|
1949
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
1950
|
+
}
|
|
1951
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1952
|
+
}
|
|
1953
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
1954
|
+
log(400);
|
|
1955
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
1956
|
+
}
|
|
1957
|
+
let storage;
|
|
1958
|
+
try {
|
|
1959
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
1960
|
+
const point = timeline(namespace).get(at);
|
|
1961
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
1962
|
+
let viewRng = branchRngs.get(storage);
|
|
1963
|
+
if (!viewRng) {
|
|
1964
|
+
viewRng = createRng(options.seed ?? 0);
|
|
1965
|
+
instanceFor(storage, namespace, viewRng);
|
|
1966
|
+
}
|
|
1967
|
+
viewRng.setState(point.value.rngState);
|
|
1968
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1969
|
+
captured.set(storage, point.value.snapshot);
|
|
1970
|
+
} else {
|
|
1971
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
1972
|
+
}
|
|
1973
|
+
} catch (error) {
|
|
1974
|
+
log(409);
|
|
1975
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
1976
|
+
}
|
|
1977
|
+
const hits = await faults.take({
|
|
1978
|
+
operationId,
|
|
1979
|
+
method: request.method,
|
|
1980
|
+
path: url.pathname,
|
|
1981
|
+
namespace
|
|
1982
|
+
});
|
|
1983
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
1984
|
+
if (final?.drop) {
|
|
1985
|
+
log(0, final.id);
|
|
1986
|
+
throw new DroppedConnectionError();
|
|
1987
|
+
}
|
|
1988
|
+
if (final?.response) {
|
|
1989
|
+
log(final.response.status, final.id);
|
|
1990
|
+
return stamp(final.response);
|
|
1991
|
+
}
|
|
1992
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
1993
|
+
if (fired.length > 0)
|
|
1994
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
1995
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
1996
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
1997
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
1998
|
+
response = mutableResponse(response);
|
|
1999
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2000
|
+
}
|
|
2001
|
+
if (selectedBranch !== "main") {
|
|
2002
|
+
response = mutableResponse(response);
|
|
2003
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2004
|
+
}
|
|
2005
|
+
if (at !== void 0) {
|
|
2006
|
+
response = mutableResponse(response);
|
|
2007
|
+
response.headers.set(AT_HEADER, at);
|
|
2008
|
+
}
|
|
2009
|
+
log(response.status, fired[0]?.id, response);
|
|
2010
|
+
return stamp(response);
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
const control = createControlPlane({
|
|
2014
|
+
name: options.name,
|
|
2015
|
+
startedAt: wallNow(),
|
|
2016
|
+
wallNow,
|
|
2017
|
+
clock,
|
|
2018
|
+
faults,
|
|
2019
|
+
metrics,
|
|
2020
|
+
journal,
|
|
2021
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2022
|
+
namespaces: runtime.namespaces,
|
|
2023
|
+
reset,
|
|
2024
|
+
timeTravel: {
|
|
2025
|
+
checkpoint: (name, branchName) => {
|
|
2026
|
+
const point = checkpoint(name, branchName);
|
|
2027
|
+
return {
|
|
2028
|
+
id: point.id,
|
|
2029
|
+
branch: point.branch,
|
|
2030
|
+
parent: point.parent,
|
|
2031
|
+
at: point.at,
|
|
2032
|
+
records: point.value.snapshot.records.length
|
|
2033
|
+
};
|
|
2034
|
+
},
|
|
2035
|
+
branch: (branchName, branchOptions) => {
|
|
2036
|
+
const point = branch(branchName, branchOptions);
|
|
2037
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2038
|
+
},
|
|
2039
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2040
|
+
retain: (name, checkpointId) => {
|
|
2041
|
+
timeline(name).retain(checkpointId);
|
|
2042
|
+
},
|
|
2043
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2044
|
+
inspect: (name) => {
|
|
2045
|
+
const history = timeline(name);
|
|
2046
|
+
return {
|
|
2047
|
+
branches: history.branches(),
|
|
2048
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2049
|
+
id,
|
|
2050
|
+
branch: branchName,
|
|
2051
|
+
parent,
|
|
2052
|
+
at
|
|
2053
|
+
}))
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
},
|
|
2057
|
+
describe: options.describe ?? (() => ({})),
|
|
2058
|
+
...options.presets ? {
|
|
2059
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2060
|
+
} : {},
|
|
2061
|
+
routes: {
|
|
2062
|
+
...credentialRoutes(credentials),
|
|
2063
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2064
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2065
|
+
...options.admin?.(runtime) ?? {}
|
|
2066
|
+
},
|
|
2067
|
+
adminKey: options.adminKey
|
|
2068
|
+
});
|
|
2069
|
+
return runtime;
|
|
2070
|
+
};
|
|
2071
|
+
var mutableResponse = (response) => {
|
|
2072
|
+
try {
|
|
2073
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2074
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2075
|
+
return response;
|
|
2076
|
+
} catch {
|
|
2077
|
+
return new Response(response.body, response);
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2081
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2082
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2083
|
+
var credentialRoutes = (registry) => ({
|
|
2084
|
+
"GET /credentials": () => adminJson(200, {
|
|
2085
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2086
|
+
credential: maskCredential(credential),
|
|
2087
|
+
namespace
|
|
2088
|
+
}))
|
|
2089
|
+
}),
|
|
2090
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2091
|
+
const pairs = [];
|
|
2092
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2093
|
+
if (Array.isArray(list)) {
|
|
2094
|
+
for (const each of list) {
|
|
2095
|
+
if (typeof each === "string")
|
|
2096
|
+
pairs.push([each, namespace]);
|
|
2097
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2098
|
+
pairs.push([
|
|
2099
|
+
each.credential,
|
|
2100
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2101
|
+
]);
|
|
2102
|
+
} else
|
|
2103
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2104
|
+
}
|
|
2105
|
+
} else if (isObject(list)) {
|
|
2106
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2107
|
+
if (typeof target !== "string")
|
|
2108
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2109
|
+
pairs.push([credential, target]);
|
|
2110
|
+
}
|
|
2111
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2112
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2113
|
+
} else {
|
|
2114
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2115
|
+
}
|
|
2116
|
+
for (const [credential, target] of pairs) {
|
|
2117
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2118
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2119
|
+
registry.set(credential, target);
|
|
2120
|
+
}
|
|
2121
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2122
|
+
},
|
|
2123
|
+
"DELETE /credentials": ({ url }) => {
|
|
2124
|
+
const credential = url.searchParams.get("credential");
|
|
2125
|
+
if (credential === null)
|
|
2126
|
+
registry.clear();
|
|
2127
|
+
else
|
|
2128
|
+
registry.remove(credential);
|
|
2129
|
+
return adminJson(200, { status: "ok" });
|
|
2130
|
+
}
|
|
2131
|
+
});
|
|
2132
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2133
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2134
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2135
|
+
}),
|
|
2136
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2137
|
+
const name = params.name;
|
|
2138
|
+
if (!presets[name])
|
|
2139
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2140
|
+
const overrides = isObject(body) ? body : {};
|
|
2141
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2142
|
+
}
|
|
2143
|
+
});
|
|
2144
|
+
|
|
2145
|
+
// ../core/dist/validation.js
|
|
2146
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2147
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2148
|
+
if (!requestBody)
|
|
2149
|
+
return [];
|
|
2150
|
+
const resolved = deref(context.document, requestBody);
|
|
2151
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2152
|
+
if (!schema)
|
|
2153
|
+
return [];
|
|
2154
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2155
|
+
if (context.body.kind === "invalid") {
|
|
2156
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2157
|
+
}
|
|
2158
|
+
if (value === void 0) {
|
|
2159
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2160
|
+
}
|
|
2161
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2162
|
+
};
|
|
2163
|
+
var issuesByField = (issues) => {
|
|
2164
|
+
const out = {};
|
|
2165
|
+
for (const issue of issues) {
|
|
2166
|
+
const missing = /^missing required property (.+)$/.exec(issue.message);
|
|
2167
|
+
const field = missing ? [issue.path, missing[1]].filter(Boolean).join(".") : issue.path || "body";
|
|
2168
|
+
const message = missing ? `The ${field} field is required.` : `The ${field} field ${issue.message}.`;
|
|
2169
|
+
out[field] = [...out[field] ?? [], message];
|
|
2170
|
+
}
|
|
2171
|
+
return out;
|
|
2172
|
+
};
|
|
2173
|
+
|
|
2174
|
+
// src/forms.ts
|
|
2175
|
+
var CREATED = "2025-01-15T00:00:00";
|
|
2176
|
+
var answer = (id, questionId, text2, complexity = null) => ({
|
|
2177
|
+
id,
|
|
2178
|
+
answer: text2,
|
|
2179
|
+
freeAnswerText: null,
|
|
2180
|
+
questionId,
|
|
2181
|
+
complexity,
|
|
2182
|
+
isChecked: false,
|
|
2183
|
+
updatedAt: null,
|
|
2184
|
+
createdAt: CREATED,
|
|
2185
|
+
deletedAt: null,
|
|
2186
|
+
description: null
|
|
2187
|
+
});
|
|
2188
|
+
var question = (id, groupId, text2, answerTypeId, answers = [], order = 1) => ({
|
|
2189
|
+
id,
|
|
2190
|
+
questionText: text2,
|
|
2191
|
+
groupId,
|
|
2192
|
+
sectionId: null,
|
|
2193
|
+
answerTypeId,
|
|
2194
|
+
alignment: null,
|
|
2195
|
+
answerText: null,
|
|
2196
|
+
answerComplexity: 0,
|
|
2197
|
+
questionOrder: order,
|
|
2198
|
+
isMainQuestion: false,
|
|
2199
|
+
isTrueFalseQuestion: null,
|
|
2200
|
+
updatedAt: CREATED,
|
|
2201
|
+
createdAt: CREATED,
|
|
2202
|
+
deletedAt: null,
|
|
2203
|
+
tfValue: null,
|
|
2204
|
+
caption: null,
|
|
2205
|
+
questionAnswers: answers.map(
|
|
2206
|
+
([aid, text22, complexity]) => answer(aid, id, text22, complexity ?? null)
|
|
2207
|
+
)
|
|
2208
|
+
});
|
|
2209
|
+
var group = (id, formId, name, questions) => ({
|
|
2210
|
+
id,
|
|
2211
|
+
name,
|
|
2212
|
+
formId,
|
|
2213
|
+
parentGroupId: null,
|
|
2214
|
+
updatedAt: null,
|
|
2215
|
+
createdAt: CREATED,
|
|
2216
|
+
deletedAt: null,
|
|
2217
|
+
description: null,
|
|
2218
|
+
caption: null,
|
|
2219
|
+
groupQuestions: questions.map((q, i) => ({
|
|
2220
|
+
questionId: q.id,
|
|
2221
|
+
groupId: id,
|
|
2222
|
+
question: q,
|
|
2223
|
+
questionOrder: i + 1
|
|
2224
|
+
})),
|
|
2225
|
+
mainQuestion: null,
|
|
2226
|
+
subGroups: []
|
|
2227
|
+
});
|
|
2228
|
+
var DEFAULT_FORMS = [
|
|
2229
|
+
{
|
|
2230
|
+
id: 101,
|
|
2231
|
+
name: "Health History",
|
|
2232
|
+
isAllowMultible: false,
|
|
2233
|
+
slug: "health-history",
|
|
2234
|
+
description: "Baseline health history for new members",
|
|
2235
|
+
updatedAt: CREATED,
|
|
2236
|
+
createdAt: CREATED,
|
|
2237
|
+
deletedAt: null,
|
|
2238
|
+
groups: [
|
|
2239
|
+
group(201, 101, "General", [
|
|
2240
|
+
question(1001, 201, "Do you currently smoke?", 2, [
|
|
2241
|
+
[5001, "Yes"],
|
|
2242
|
+
[5002, "No"]
|
|
2243
|
+
]),
|
|
2244
|
+
question(
|
|
2245
|
+
1002,
|
|
2246
|
+
201,
|
|
2247
|
+
"Which conditions have you been diagnosed with?",
|
|
2248
|
+
3,
|
|
2249
|
+
[
|
|
2250
|
+
[5003, "Hypertension"],
|
|
2251
|
+
[5004, "Diabetes"],
|
|
2252
|
+
[5005, "Other", 1]
|
|
2253
|
+
],
|
|
2254
|
+
2
|
|
2255
|
+
),
|
|
2256
|
+
question(1003, 201, "List your current medications", 1, [], 3)
|
|
2257
|
+
]),
|
|
2258
|
+
group(202, 101, "Before you begin", [
|
|
2259
|
+
question(1004, 202, "Answer honestly; your provider reviews every response.", 5)
|
|
2260
|
+
])
|
|
2261
|
+
]
|
|
2262
|
+
},
|
|
2263
|
+
{
|
|
2264
|
+
id: 102,
|
|
2265
|
+
name: "AOE Questions",
|
|
2266
|
+
isAllowMultible: true,
|
|
2267
|
+
slug: "aoe-questions",
|
|
2268
|
+
description: null,
|
|
2269
|
+
updatedAt: CREATED,
|
|
2270
|
+
createdAt: CREATED,
|
|
2271
|
+
deletedAt: null,
|
|
2272
|
+
groups: [
|
|
2273
|
+
group(203, 102, "Ask on order entry", [
|
|
2274
|
+
question(1101, 203, "Are you fasting?", 4, [
|
|
2275
|
+
[5101, "Yes"],
|
|
2276
|
+
[5102, "No"]
|
|
2277
|
+
])
|
|
2278
|
+
])
|
|
2279
|
+
]
|
|
2280
|
+
}
|
|
2281
|
+
];
|
|
2282
|
+
var STATES = [
|
|
2283
|
+
["AL", "Alabama"],
|
|
2284
|
+
["AK", "Alaska"],
|
|
2285
|
+
["AZ", "Arizona"],
|
|
2286
|
+
["AR", "Arkansas"],
|
|
2287
|
+
["CA", "California"],
|
|
2288
|
+
["CO", "Colorado"],
|
|
2289
|
+
["CT", "Connecticut"],
|
|
2290
|
+
["DE", "Delaware"],
|
|
2291
|
+
["DC", "District of Columbia"],
|
|
2292
|
+
["FL", "Florida"],
|
|
2293
|
+
["GA", "Georgia"],
|
|
2294
|
+
["HI", "Hawaii"],
|
|
2295
|
+
["ID", "Idaho"],
|
|
2296
|
+
["IL", "Illinois"],
|
|
2297
|
+
["IN", "Indiana"],
|
|
2298
|
+
["IA", "Iowa"],
|
|
2299
|
+
["KS", "Kansas"],
|
|
2300
|
+
["KY", "Kentucky"],
|
|
2301
|
+
["LA", "Louisiana"],
|
|
2302
|
+
["ME", "Maine"],
|
|
2303
|
+
["MD", "Maryland"],
|
|
2304
|
+
["MA", "Massachusetts"],
|
|
2305
|
+
["MI", "Michigan"],
|
|
2306
|
+
["MN", "Minnesota"],
|
|
2307
|
+
["MS", "Mississippi"],
|
|
2308
|
+
["MO", "Missouri"],
|
|
2309
|
+
["MT", "Montana"],
|
|
2310
|
+
["NE", "Nebraska"],
|
|
2311
|
+
["NV", "Nevada"],
|
|
2312
|
+
["NH", "New Hampshire"],
|
|
2313
|
+
["NJ", "New Jersey"],
|
|
2314
|
+
["NM", "New Mexico"],
|
|
2315
|
+
["NY", "New York"],
|
|
2316
|
+
["NC", "North Carolina"],
|
|
2317
|
+
["ND", "North Dakota"],
|
|
2318
|
+
["OH", "Ohio"],
|
|
2319
|
+
["OK", "Oklahoma"],
|
|
2320
|
+
["OR", "Oregon"],
|
|
2321
|
+
["PA", "Pennsylvania"],
|
|
2322
|
+
["RI", "Rhode Island"],
|
|
2323
|
+
["SC", "South Carolina"],
|
|
2324
|
+
["SD", "South Dakota"],
|
|
2325
|
+
["TN", "Tennessee"],
|
|
2326
|
+
["TX", "Texas"],
|
|
2327
|
+
["UT", "Utah"],
|
|
2328
|
+
["VT", "Vermont"],
|
|
2329
|
+
["VA", "Virginia"],
|
|
2330
|
+
["WA", "Washington"],
|
|
2331
|
+
["WV", "West Virginia"],
|
|
2332
|
+
["WI", "Wisconsin"],
|
|
2333
|
+
["WY", "Wyoming"]
|
|
2334
|
+
];
|
|
2335
|
+
var US_STATES = STATES.map(([abbreviation, name], index) => ({
|
|
2336
|
+
id: index + 1,
|
|
2337
|
+
stateUid: `st-${abbreviation.toLowerCase()}`,
|
|
2338
|
+
name,
|
|
2339
|
+
abbreviation,
|
|
2340
|
+
physiciansStateLicenseds: [],
|
|
2341
|
+
users: [],
|
|
2342
|
+
stateLocationCapabilities: []
|
|
2343
|
+
}));
|
|
2344
|
+
var DEFAULT_DOCTORS = [
|
|
2345
|
+
{ doctorId: 7, doctorName: "Dr. Ada Mock", medicalSpecialty: "Internal Medicine" },
|
|
2346
|
+
{ doctorId: 8, doctorName: "Dr. Grace Mock", medicalSpecialty: "Endocrinology" }
|
|
2347
|
+
];
|
|
2348
|
+
|
|
2349
|
+
// src/generated/openapi.ts
|
|
2350
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"CareTalk external API (Mockingbird subset)","description":"Stateful mock subset of CareTalk's \`/externalapi\`: client login, form definitions (GetForm), saving patient forms, patient search and insert, states, free slots and appointments. Hand-authored from the consumer (caretalk-client.service.ts, caretalk.types.ts, caretalk-forms.type.ts); the vendor publishes no spec.\\n","version":"1","x-mockingbird-upstream":{"note":"Wire shapes from apps/backend/src/modules/global-services/services/caretalk/*.ts (zod schemas and interfaces)."}},"servers":[{"url":"https://api.caretalkbeta.com"}],"security":[{"bearerAuth":[]}],"paths":{"/externalapi/Auth/client-login":{"post":{"operationId":"ClientLogin","description":"Exchange the API user's credentials for a bearer token.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthResponse"}}}},"400":{"description":"Validation failed (ASP.NET ProblemDetails)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}},"401":{"description":"Bad credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Message"}}}}},"security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginBody"}}}}}},"/externalapi/Forms/GetForm/{formName}":{"get":{"operationId":"GetForm","description":"A form definition by name or slug (an unknown form is an empty list). With AppointmentId / PatientId, the patient's latest saved round of it.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Matching forms","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CareTalkForm"}}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"parameters":[{"name":"formName","in":"path","required":true,"schema":{"type":"string","enum":["Health History","health-history","AOE Questions","aoe-questions","unknown-form"]}},{"name":"AppointmentId","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":5}},{"name":"PatientId","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":5}}]}},"/externalapi/Forms/SavePatientForm":{"post":{"operationId":"SavePatientForm","description":"Save a patient's answers to a form (the form-submission queue's call).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Saved","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SaveResult"}}}},"400":{"description":"Validation failed (ASP.NET ProblemDetails)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"},"404":{"description":"Unknown patient or form","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FormSubmission"}}}},"parameters":[{"name":"patientId","in":"query","required":true,"schema":{"type":"integer","minimum":1,"maximum":5}},{"name":"patientAppointmentId","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":5}}]}},"/externalapi/Patients/SearchForPatient":{"get":{"operationId":"SearchForPatient","description":"Find a patient by name, ZIP and date of birth (any of YYYY-MM-DD, MM/DD/YYYY or ISO). Not found is a 400.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchResult"}}}},"400":{"description":"Not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchMiss"}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"parameters":[{"name":"FirstName","in":"query","required":true,"schema":{"type":"string","enum":["Ada","Grace"]}},{"name":"LastName","in":"query","required":true,"schema":{"type":"string","enum":["Lovelace","Hopper"]}},{"name":"zipCode","in":"query","required":true,"schema":{"type":"string","enum":["84101","10001"]}},{"name":"DateOfBirth","in":"query","required":true,"schema":{"type":"string","enum":["1985-12-10","12/10/1985","1990-01-02"]}}]}},"/externalapi/States":{"get":{"operationId":"ListStates","description":"Every US state CareTalk licenses in.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"States","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/State"}}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}}}},"/externalapi/Patients":{"post":{"operationId":"InsertPatient","description":"Create a patient (the account backfill).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"The patient","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Patient"}}}},"400":{"description":"Validation failed (ASP.NET ProblemDetails)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientBody"}}}}}},"/externalapi/PatientAppointments/GetFreeSlots":{"get":{"operationId":"GetFreeSlots","description":"Open slots on a date.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Slots","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FreeSlot"}}}}},"400":{"description":"Validation failed (ASP.NET ProblemDetails)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"parameters":[{"name":"date","in":"query","required":true,"schema":{"type":"string","enum":["2026-10-05","2026-10-06"]}},{"name":"programId","in":"query","required":true,"schema":{"type":"integer","enum":[21]}},{"name":"eligibleId","in":"query","required":true,"schema":{"type":"integer","minimum":1,"maximum":5}}]}},"/externalapi/PatientAppointments":{"post":{"operationId":"ScheduleAppointment","description":"Book a slot for an eligible patient.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Booked","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScheduledAppointment"}}}},"400":{"description":"Validation failed (ASP.NET ProblemDetails)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProblemDetails"}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScheduleBody"}}}}}},"/externalapi/PatientAppointments/GetPatientAppointmentsByEligibleId/{eligibleId}":{"get":{"operationId":"GetPatientAppointments","description":"A patient's appointments.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Appointments","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Appointment"}}}}},"401":{"description":"Missing, unknown or expired bearer token (empty body, WWW-Authenticate: Bearer)"}},"parameters":[{"name":"eligibleId","in":"path","required":true,"schema":{"type":"integer","minimum":1,"maximum":5}}]}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"schemas":{"LoginBody":{"type":"object","required":["userName","password"],"properties":{"userName":{"type":"string","minLength":1,"maxLength":64},"password":{"type":"string","minLength":1,"maxLength":64}}},"AuthResponse":{"type":"object","required":["token"],"properties":{"token":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"expiration":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"Message":{"type":"object","required":["message"],"properties":{"message":{"type":"string"}}},"ProblemDetails":{"type":"object","required":["title","status"],"properties":{"type":{"type":"string"},"title":{"type":"string"},"status":{"type":"integer"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}},"traceId":{"type":"string","x-mockingbird-volatile":{"kind":"opaque"}}}},"QuestionAnswer":{"type":"object","required":["id","answer","questionId","isChecked","createdAt"],"properties":{"id":{"type":"integer"},"answer":{"type":"string"},"freeAnswerText":{"type":["string","null"]},"questionId":{"type":"integer"},"complexity":{"type":["integer","null"]},"isChecked":{"type":"boolean"},"updatedAt":{"type":["string","null"]},"createdAt":{"type":"string"},"deletedAt":{"type":["string","null"]},"description":{"type":["string","null"]}}},"Question":{"type":"object","required":["id","questionText","groupId","answerTypeId","questionAnswers"],"properties":{"id":{"type":"integer"},"questionText":{"type":"string"},"groupId":{"type":"integer"},"sectionId":{"type":["integer","null"]},"answerTypeId":{"type":"integer","enum":[1,2,3,4,5]},"alignment":{"type":["integer","null"]},"answerText":{"type":["string","null"]},"answerComplexity":{"type":"integer"},"questionOrder":{"type":["integer","null"]},"isMainQuestion":{"type":"boolean"},"isTrueFalseQuestion":{"type":["boolean","null"]},"updatedAt":{"type":"string"},"createdAt":{"type":"string"},"deletedAt":{"type":["string","null"]},"tfValue":{"type":["boolean","null"]},"caption":{"type":["string","null"]},"questionAnswers":{"type":"array","items":{"$ref":"#/components/schemas/QuestionAnswer"}}}},"FormGroup":{"type":"object","required":["id","name","formId","groupQuestions","subGroups"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"formId":{"type":"integer"},"parentGroupId":{"type":["integer","null"]},"updatedAt":{"type":["string","null"]},"createdAt":{"type":"string"},"deletedAt":{"type":["string","null"]},"description":{"type":["string","null"]},"caption":{"type":["string","null"]},"groupQuestions":{"type":"array","items":{"type":"object","required":["questionId","groupId","question"],"properties":{"questionId":{"type":"integer"},"groupId":{"type":"integer"},"question":{"$ref":"#/components/schemas/Question"},"questionOrder":{"type":["integer","null"]}}}},"mainQuestion":{"type":["object","null"]},"subGroups":{"type":"array","items":{"type":"object"}}}},"CareTalkForm":{"type":"object","required":["formRoundId","patientAppointmentId","submitDate","fullFormDto"],"properties":{"formRoundId":{"type":"integer"},"patientAppointmentId":{"type":["integer","null"]},"submitDate":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"fullFormDto":{"type":"object","required":["id","name","isAllowMultible","slug","groups"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"isAllowMultible":{"type":"boolean"},"slug":{"type":"string"},"description":{"type":["string","null"]},"updatedAt":{"type":"string"},"createdAt":{"type":"string"},"deletedAt":{"type":["string","null"]},"groups":{"type":"array","items":{"$ref":"#/components/schemas/FormGroup"}}}}}},"FormSubmission":{"type":"object","required":["fullFormDto"],"properties":{"fullFormDto":{"type":"object","required":["id","name","groups"],"properties":{"id":{"type":"integer","minimum":1,"examples":[101,102]},"name":{"type":"string","minLength":1,"maxLength":80},"groups":{"type":"array","maxItems":2,"items":{"type":"object","required":["groupQuestions"],"properties":{"groupQuestions":{"type":"array","maxItems":3,"items":{"type":"object","required":["questionId","question"],"properties":{"questionId":{"type":"integer","minimum":0,"examples":[1001,1002,1003,1101]},"question":{"type":"object","required":["id","questionAnswers"],"properties":{"id":{"type":"integer","minimum":0,"examples":[1001,1002,1003,1101]},"questionAnswers":{"type":"array","maxItems":2,"items":{"type":"object","required":["id","answer"],"properties":{"id":{"type":"integer","minimum":0,"examples":[0,5001,5002,5003,5101]},"answer":{"type":"string","minLength":1,"maxLength":40},"freeAnswerText":{"type":"string","maxLength":200}}}}}}}}}}}}}}}},"SaveResult":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"},"message":{"type":"string"}}},"SearchResult":{"type":"object","required":["isExists","eligibleId","programId"],"properties":{"isExists":{"type":"boolean"},"eligibleId":{"type":"integer"},"programId":{"type":"integer"}}},"SearchMiss":{"type":"object","required":["isExists","message"],"properties":{"isExists":{"type":"boolean"},"message":{"type":"string"}}},"State":{"type":"object","required":["id","stateUid","name","abbreviation"],"properties":{"id":{"type":"integer"},"stateUid":{"type":"string"},"name":{"type":"string"},"abbreviation":{"type":"string"},"physiciansStateLicenseds":{"type":"array"},"users":{"type":"array"},"stateLocationCapabilities":{"type":"array"}}},"PatientBody":{"type":"object","required":["dateOfBirth","programId","recordStatus","recordId","height","weight","highBloodPressure","lowBloodPressure","dateFinalized","tokenDate"],"properties":{"firstName":{"type":"string","examples":["Ada","Grace"],"maxLength":80},"lastName":{"type":"string","examples":["Lovelace","Hopper"],"maxLength":80},"mobilePhone":{"type":"string","maxLength":20},"email":{"type":"string","maxLength":80},"dateOfBirth":{"type":"string","examples":["1985-12-10T00:00:00.000Z","1990-01-02T00:00:00.000Z"],"maxLength":80},"gender":{"type":"integer","examples":[0,1,2]},"address":{"type":"string","maxLength":80},"state":{"type":"string","examples":["UT","NY"],"maxLength":80},"city":{"type":"string","maxLength":40},"userStateId":{"type":"integer","minimum":1,"maximum":51},"programId":{"type":"integer","examples":[21]},"zipCode":{"type":"string","examples":["84101","10001"],"maxLength":80},"height":{"type":"number","minimum":0,"maximum":100},"weight":{"type":"number","minimum":0,"maximum":500},"highBloodPressure":{"type":"number","minimum":0,"maximum":250},"lowBloodPressure":{"type":"number","minimum":0,"maximum":200},"recordStatus":{"type":"string","examples":["Active","Finalized"],"maxLength":80},"recordId":{"type":"string","examples":["GV-001","GV-1234"],"maxLength":20},"dateFinalized":{"type":"string","examples":["2026-09-20T00:00:00.000Z"],"maxLength":80},"tokenDate":{"type":"string","examples":["2026-09-20T00:00:00.000Z"],"maxLength":80}}},"Patient":{"type":"object","required":["id","programId","recordStatus","clientId","createdAt"],"properties":{"id":{"type":"integer"},"firstName":{"type":["string","null"]},"middleInitial":{"type":["string","null"]},"lastName":{"type":["string","null"]},"mobilePhone":{"type":["string","null"]},"homePhone":{"type":["string","null"]},"token":{"type":["string","null"]},"tokenDate":{"type":["string","null"]},"apptStatus":{"type":["string","null"]},"email":{"type":["string","null"]},"dateOfBirth":{"type":["string","null"]},"gender":{"type":["integer","null"]},"address":{"type":["string","null"]},"state":{"type":["string","null"]},"city":{"type":["string","null"]},"userStateId":{"type":["integer","null"]},"userState":{"type":["string","null"]},"zipCode":{"type":["string","null"]},"recordStatus":{"type":"string"},"clientStatus":{"type":["string","null"]},"clientBatchId":{"type":["string","null"]},"authorization":{"type":["boolean","null"]},"mbi":{"type":["string","null"]},"ssn":{"type":["string","null"]},"mspPatientId":{"type":["string","null"]},"recordId":{"type":["string","null"]},"height":{"type":["number","null"]},"weight":{"type":["number","null"]},"highBloodPressure":{"type":["number","null"]},"lowBloodPressure":{"type":["number","null"]},"dateFinalized":{"type":["string","null"]},"programId":{"type":"integer"},"eligibilityId":{"type":["integer","null"]},"clientId":{"type":"integer"},"fileId":{"type":["integer","null"]},"oldId":{"type":["integer","null"]},"formattedUserMobile":{"type":["string","null"]},"planName":{"type":["string","null"]},"healthGorillaId":{"type":["string","null"]},"hG_P360_Retrieve_location":{"type":["string","null"]},"hG_P360_Retrieve_Status":{"type":["string","null"]},"hG_P360_Retrieve_json":{"type":["string","null"]},"program":{"type":["string","null"]},"client":{"type":["string","null"]},"patientMedications":{"type":["array","null"]},"patientDiagnostics":{"type":["array","null"]},"patientAppointments":{"type":["array","null"]},"patientAppointment":{},"formRounds":{"type":["array","null"]},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updatedAt":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"deletedAt":{"type":["string","null"]}}},"FreeSlot":{"type":"object","required":["id","doctorId","doctorName","timeZone","from","to"],"properties":{"id":{"type":"integer"},"medicalSpecialty":{"type":["string","null"]},"doctorId":{"type":"integer"},"doctorName":{"type":"string"},"doctor":{"type":["string","null"]},"doctorUid":{"type":["integer","null"]},"timeZone":{"type":"string"},"offset":{"type":["number","null"]},"from":{"type":"string"},"to":{"type":"string"}}},"ScheduleBody":{"type":"object","required":["doctorId","patientId","from","to"],"properties":{"doctorId":{"type":"integer","minimum":1,"examples":[7,8]},"patientId":{"type":"integer","minimum":1,"maximum":5},"from":{"type":"string","examples":["2026-10-05T09:00:00","2026-10-05T10:00:00"],"maxLength":40,"minLength":10},"to":{"type":"string","examples":["2026-10-05T09:30:00","2026-10-05T10:30:00"],"maxLength":40,"minLength":10}}},"ScheduledAppointment":{"type":"object","required":["id","patientId","eligibilityId","appointmentStatus","physicianId"],"properties":{"id":{"type":"integer"},"patientId":{"type":"null"},"eligibilityId":{"type":"integer"},"appointmentStatus":{"type":"integer"},"physicianId":{"type":"integer"}}},"Appointment":{"type":"object","required":["id","patientId","eligibilityId","createdAt","appointmentStatus","physicianId","startDateTime","endDateTime"],"properties":{"id":{"type":"integer"},"patientId":{"type":["integer","null"]},"eligibilityId":{"type":"integer"},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"appointmentStatus":{"type":"integer"},"physicianId":{"type":"integer"},"startDateTime":{"type":"string"},"endDateTime":{"type":"string"}}}}}}`);
|
|
2351
|
+
var operationIds = ["ClientLogin", "GetForm", "SavePatientForm", "SearchForPatient", "ListStates", "InsertPatient", "GetFreeSlots", "ScheduleAppointment", "GetPatientAppointments"];
|
|
2352
|
+
var supportedOperationIds = ["ClientLogin", "GetForm", "SavePatientForm", "SearchForPatient", "ListStates", "InsertPatient", "GetFreeSlots", "ScheduleAppointment", "GetPatientAppointments"];
|
|
2353
|
+
|
|
2354
|
+
// src/state.ts
|
|
2355
|
+
var DEFAULT_SETTINGS = {
|
|
2356
|
+
tokenTtlSeconds: 3600,
|
|
2357
|
+
users: [],
|
|
2358
|
+
apiKeys: [],
|
|
2359
|
+
programId: 21
|
|
2360
|
+
};
|
|
2361
|
+
var CareTalkState = class {
|
|
2362
|
+
constructor(sqlite, namespace, seed) {
|
|
2363
|
+
this.seed = seed;
|
|
2364
|
+
this.forms = new Collection(sqlite, namespace, "forms");
|
|
2365
|
+
this.patients = new Collection(sqlite, namespace, "patients");
|
|
2366
|
+
this.rounds = new Collection(sqlite, namespace, "form_rounds");
|
|
2367
|
+
this.appointments = new Collection(sqlite, namespace, "appointments");
|
|
2368
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2369
|
+
this.counters = new Collection(sqlite, namespace, "counters");
|
|
2370
|
+
this.ensureSeeded();
|
|
2371
|
+
}
|
|
2372
|
+
seed;
|
|
2373
|
+
forms;
|
|
2374
|
+
patients;
|
|
2375
|
+
rounds;
|
|
2376
|
+
appointments;
|
|
2377
|
+
settings;
|
|
2378
|
+
counters;
|
|
2379
|
+
ensureSeeded() {
|
|
2380
|
+
if (this.forms.count() === 0) {
|
|
2381
|
+
for (const form of this.seed.forms.length > 0 ? this.seed.forms : DEFAULT_FORMS) {
|
|
2382
|
+
this.forms.insert(String(form.id), form);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
if (!this.settings.has("settings")) {
|
|
2386
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
current() {
|
|
2390
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2391
|
+
}
|
|
2392
|
+
update(patch) {
|
|
2393
|
+
const next = { ...this.current(), ...patch };
|
|
2394
|
+
this.settings.insert("settings", next);
|
|
2395
|
+
return next;
|
|
2396
|
+
}
|
|
2397
|
+
/** CareTalk ids are integers: one counter per kind. */
|
|
2398
|
+
next(kind) {
|
|
2399
|
+
const current = this.counters.get("counters") ?? { patient: 0, round: 0, appointment: 0 };
|
|
2400
|
+
const next = { ...current, [kind]: current[kind] + 1 };
|
|
2401
|
+
this.counters.insert("counters", next);
|
|
2402
|
+
return next[kind];
|
|
2403
|
+
}
|
|
2404
|
+
/** A form by name or slug, case-insensitively (the app passes either). */
|
|
2405
|
+
findForm(nameOrSlug) {
|
|
2406
|
+
const wanted = nameOrSlug.trim().toLowerCase();
|
|
2407
|
+
return this.forms.list({ order: "oldest" }).map((r) => r.value).find((f) => f.name.toLowerCase() === wanted || f.slug.toLowerCase() === wanted);
|
|
2408
|
+
}
|
|
2409
|
+
};
|
|
2410
|
+
|
|
2411
|
+
// src/runtime.ts
|
|
2412
|
+
var API = "/externalapi/";
|
|
2413
|
+
var AUTHENTICATED = [
|
|
2414
|
+
"GetForm",
|
|
2415
|
+
"SavePatientForm",
|
|
2416
|
+
"SearchForPatient",
|
|
2417
|
+
"ListStates",
|
|
2418
|
+
"InsertPatient",
|
|
2419
|
+
"GetFreeSlots",
|
|
2420
|
+
"ScheduleAppointment",
|
|
2421
|
+
"GetPatientAppointments"
|
|
2422
|
+
];
|
|
2423
|
+
var CARETALK_PRESETS = {
|
|
2424
|
+
login_failure: {
|
|
2425
|
+
description: "client-login answers 500 (our client throws 'Failed to get auth token')",
|
|
2426
|
+
rules: [{ operationId: "ClientLogin", status: 500, body: { message: "An error occurred." } }]
|
|
2427
|
+
},
|
|
2428
|
+
invalid_credentials: {
|
|
2429
|
+
description: "client-login answers 401 Invalid username or password",
|
|
2430
|
+
rules: [
|
|
2431
|
+
{
|
|
2432
|
+
operationId: "ClientLogin",
|
|
2433
|
+
status: 401,
|
|
2434
|
+
body: { message: "Invalid username or password." }
|
|
2435
|
+
}
|
|
2436
|
+
]
|
|
2437
|
+
},
|
|
2438
|
+
token_expired: {
|
|
2439
|
+
description: "Authenticated calls answer 401 before the cached token's hour is up (our client logs in again and retries once); count applies per operation",
|
|
2440
|
+
// One rule per authenticated operation, so client-login never uses up the count.
|
|
2441
|
+
rules: AUTHENTICATED.map((operationId) => ({ operationId, effect: "token_expired" }))
|
|
2442
|
+
},
|
|
2443
|
+
server_error: {
|
|
2444
|
+
description: "Every call answers 500 ProblemDetails",
|
|
2445
|
+
rules: [
|
|
2446
|
+
{
|
|
2447
|
+
pathPrefix: API,
|
|
2448
|
+
status: 500,
|
|
2449
|
+
body: { title: "An unexpected error occurred.", status: 500 }
|
|
2450
|
+
}
|
|
2451
|
+
]
|
|
2452
|
+
},
|
|
2453
|
+
gateway_html: {
|
|
2454
|
+
description: "Every call answers a 502 HTML page (our client's JSON parse throws)",
|
|
2455
|
+
rules: [
|
|
2456
|
+
{
|
|
2457
|
+
pathPrefix: API,
|
|
2458
|
+
status: 502,
|
|
2459
|
+
body: "<html><body>502 Bad Gateway</body></html>",
|
|
2460
|
+
headers: { "content-type": "text/html" }
|
|
2461
|
+
}
|
|
2462
|
+
]
|
|
2463
|
+
},
|
|
2464
|
+
form_not_found: {
|
|
2465
|
+
description: "GetForm answers an empty list",
|
|
2466
|
+
rules: [{ operationId: "GetForm", effect: "form_not_found" }]
|
|
2467
|
+
},
|
|
2468
|
+
patient_not_found: {
|
|
2469
|
+
description: "SearchForPatient answers 400 (our client reads it as 'no such patient')",
|
|
2470
|
+
rules: [{ operationId: "SearchForPatient", effect: "patient_not_found" }]
|
|
2471
|
+
},
|
|
2472
|
+
save_rejected: {
|
|
2473
|
+
description: "SavePatientForm answers 400 ProblemDetails",
|
|
2474
|
+
rules: [{ operationId: "SavePatientForm", effect: "save_rejected" }]
|
|
2475
|
+
},
|
|
2476
|
+
connection_drop: {
|
|
2477
|
+
description: "The connection drops before any answer (fetch rejects)",
|
|
2478
|
+
rules: [{ pathPrefix: API, drop: true }]
|
|
2479
|
+
},
|
|
2480
|
+
slow: {
|
|
2481
|
+
description: "Every call answers after 10 s",
|
|
2482
|
+
rules: [{ pathPrefix: API, latencyMs: 1e4 }]
|
|
2483
|
+
}
|
|
2484
|
+
};
|
|
2485
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2486
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2487
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2488
|
+
var adminRoutes = (runtime) => ({
|
|
2489
|
+
"GET /patients": ({ namespace }) => json3(200, { patients: runtime.instance(namespace).patients() }),
|
|
2490
|
+
"POST /patients": ({ body, namespace }) => {
|
|
2491
|
+
if (!isRecord4(body))
|
|
2492
|
+
return adminError3(400, "expected a patient object (the Patients POST body)");
|
|
2493
|
+
return json3(201, runtime.instance(namespace).addPatient(body));
|
|
2494
|
+
},
|
|
2495
|
+
"GET /form-submissions": ({ namespace, url }) => {
|
|
2496
|
+
const patientId = url.searchParams.get("patientId");
|
|
2497
|
+
const rounds = runtime.instance(namespace).rounds().filter((r) => patientId === null || String(r.patientId) === patientId);
|
|
2498
|
+
return json3(200, { submissions: rounds });
|
|
2499
|
+
},
|
|
2500
|
+
"GET /forms": ({ namespace }) => json3(200, {
|
|
2501
|
+
forms: runtime.instance(namespace).state.forms.list({ order: "oldest" }).map((r) => r.value)
|
|
2502
|
+
}),
|
|
2503
|
+
"PUT /forms/:id": ({ params, body, namespace }) => {
|
|
2504
|
+
if (!isRecord4(body) || typeof body.name !== "string" || !Array.isArray(body.groups)) {
|
|
2505
|
+
return adminError3(400, "expected a fullFormDto {id, name, slug, groups, \u2026}");
|
|
2506
|
+
}
|
|
2507
|
+
const form = { ...body, id: Number(params.id) };
|
|
2508
|
+
return json3(200, runtime.instance(namespace).upsertForm(form));
|
|
2509
|
+
},
|
|
2510
|
+
"POST /appointments/:id/status": ({ params, body, namespace }) => {
|
|
2511
|
+
if (!isRecord4(body) || typeof body.appointmentStatus !== "number") {
|
|
2512
|
+
return adminError3(400, 'expected {"appointmentStatus": <number>}');
|
|
2513
|
+
}
|
|
2514
|
+
const appointment = runtime.instance(namespace).setAppointmentStatus(Number(params.id), body.appointmentStatus);
|
|
2515
|
+
return appointment ? json3(200, appointment) : adminError3(404, `no appointment ${params.id}`);
|
|
2516
|
+
},
|
|
2517
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2518
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2519
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2520
|
+
const patch = {};
|
|
2521
|
+
if (body.tokenTtlSeconds !== void 0) {
|
|
2522
|
+
if (typeof body.tokenTtlSeconds !== "number")
|
|
2523
|
+
return adminError3(400, "tokenTtlSeconds: number");
|
|
2524
|
+
patch.tokenTtlSeconds = body.tokenTtlSeconds;
|
|
2525
|
+
}
|
|
2526
|
+
if (body.users !== void 0) {
|
|
2527
|
+
if (!Array.isArray(body.users)) return adminError3(400, "users: [{userName, password}]");
|
|
2528
|
+
patch.users = body.users.filter(isRecord4).map((u) => ({
|
|
2529
|
+
userName: String(u.userName),
|
|
2530
|
+
password: String(u.password)
|
|
2531
|
+
}));
|
|
2532
|
+
}
|
|
2533
|
+
if (body.apiKeys !== void 0) {
|
|
2534
|
+
if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
|
|
2535
|
+
patch.apiKeys = body.apiKeys.map(String);
|
|
2536
|
+
}
|
|
2537
|
+
if (body.programId !== void 0) {
|
|
2538
|
+
if (typeof body.programId !== "number") return adminError3(400, "programId: number");
|
|
2539
|
+
patch.programId = body.programId;
|
|
2540
|
+
}
|
|
2541
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2542
|
+
}
|
|
2543
|
+
});
|
|
2544
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2545
|
+
name: CARETALK_NAMESPACE,
|
|
2546
|
+
document,
|
|
2547
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2548
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2549
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2550
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2551
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2552
|
+
credential: tokenCredential,
|
|
2553
|
+
presets: CARETALK_PRESETS,
|
|
2554
|
+
create: ({ sqlite, namespace, clock }) => new CareTalkAPI({
|
|
2555
|
+
sqlite,
|
|
2556
|
+
namespace,
|
|
2557
|
+
now: clock.now,
|
|
2558
|
+
...options.forms ? { forms: options.forms } : {},
|
|
2559
|
+
...options.settings ? { settings: options.settings } : {}
|
|
2560
|
+
}),
|
|
2561
|
+
admin: adminRoutes
|
|
2562
|
+
});
|
|
2563
|
+
|
|
2564
|
+
// src/index.ts
|
|
2565
|
+
var CARETALK_NAMESPACE = "caretalk";
|
|
2566
|
+
var TOKEN_PREFIX = "ct_";
|
|
2567
|
+
var base64url = (value) => toBase64(new TextEncoder().encode(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2568
|
+
var fromBase64url = (value) => {
|
|
2569
|
+
try {
|
|
2570
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(
|
|
2571
|
+
fromBase64(value.replace(/-/g, "+").replace(/_/g, "/"))
|
|
2572
|
+
);
|
|
2573
|
+
} catch {
|
|
2574
|
+
return void 0;
|
|
2575
|
+
}
|
|
2576
|
+
};
|
|
2577
|
+
var sign = (userName, issuedAt) => opaqueToken(`caretalk:${userName}:${issuedAt}`, 32);
|
|
2578
|
+
var tokenCredential = (request) => {
|
|
2579
|
+
const token = bearerToken(request);
|
|
2580
|
+
if (!token?.startsWith(TOKEN_PREFIX)) return token;
|
|
2581
|
+
const [encoded] = token.slice(TOKEN_PREFIX.length).split(".");
|
|
2582
|
+
return encoded ? fromBase64url(encoded) : void 0;
|
|
2583
|
+
};
|
|
2584
|
+
var problem = (status, title, errors) => jsonRes(status, {
|
|
2585
|
+
type: "https://tools.ietf.org/html/rfc9110#section-15.5.1",
|
|
2586
|
+
title,
|
|
2587
|
+
status,
|
|
2588
|
+
...errors ? { errors } : {},
|
|
2589
|
+
traceId: "00-00000000000000000000000000000000-0000000000000000-00"
|
|
2590
|
+
});
|
|
2591
|
+
var unauthorized = (description) => new Response(null, {
|
|
2592
|
+
status: 401,
|
|
2593
|
+
headers: {
|
|
2594
|
+
"www-authenticate": description ? `Bearer error="invalid_token", error_description="${description}"` : "Bearer"
|
|
2595
|
+
}
|
|
2596
|
+
});
|
|
2597
|
+
var normalizeDate = (value) => {
|
|
2598
|
+
if (typeof value !== "string") return void 0;
|
|
2599
|
+
const us = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value.trim());
|
|
2600
|
+
if (us) return `${us[3]}-${us[1]}-${us[2]}`;
|
|
2601
|
+
const iso = /^(\d{4}-\d{2}-\d{2})/.exec(value.trim());
|
|
2602
|
+
return iso?.[1];
|
|
2603
|
+
};
|
|
2604
|
+
var text = (value) => typeof value === "string" ? value : null;
|
|
2605
|
+
var num = (value) => typeof value === "number" ? value : null;
|
|
2606
|
+
var pad = (n) => String(n).padStart(2, "0");
|
|
2607
|
+
var CareTalkAPI = class {
|
|
2608
|
+
app;
|
|
2609
|
+
sqlite;
|
|
2610
|
+
state;
|
|
2611
|
+
service;
|
|
2612
|
+
now;
|
|
2613
|
+
constructor(options = {}) {
|
|
2614
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2615
|
+
const namespace = options.namespace ?? CARETALK_NAMESPACE;
|
|
2616
|
+
this.now = options.now ?? (() => Date.now());
|
|
2617
|
+
this.state = new CareTalkState(sqlite, namespace, {
|
|
2618
|
+
forms: options.forms ?? [],
|
|
2619
|
+
settings: options.settings ?? {}
|
|
2620
|
+
});
|
|
2621
|
+
const handlers = defineOperations({
|
|
2622
|
+
ClientLogin: (context) => this.login(context),
|
|
2623
|
+
GetForm: (context) => this.getForm(context),
|
|
2624
|
+
SavePatientForm: (context) => this.saveForm(context),
|
|
2625
|
+
SearchForPatient: (context) => this.search(context),
|
|
2626
|
+
ListStates: () => jsonRes(200, US_STATES),
|
|
2627
|
+
InsertPatient: (context) => this.insertPatient(context),
|
|
2628
|
+
GetFreeSlots: (context) => this.freeSlots(context),
|
|
2629
|
+
ScheduleAppointment: (context) => this.schedule(context),
|
|
2630
|
+
GetPatientAppointments: (context) => {
|
|
2631
|
+
const eligibleId = Number(context.params.eligibleId);
|
|
2632
|
+
return jsonRes(
|
|
2633
|
+
200,
|
|
2634
|
+
this.state.appointments.list({ order: "oldest", where: (a) => a.eligibilityId === eligibleId }).map(({ value: a }) => ({
|
|
2635
|
+
id: a.id,
|
|
2636
|
+
patientId: this.patient(eligibleId)?.id ?? null,
|
|
2637
|
+
eligibilityId: a.eligibilityId,
|
|
2638
|
+
createdAt: a.createdAt,
|
|
2639
|
+
appointmentStatus: a.appointmentStatus,
|
|
2640
|
+
physicianId: a.physicianId,
|
|
2641
|
+
startDateTime: a.startDateTime,
|
|
2642
|
+
endDateTime: a.endDateTime
|
|
2643
|
+
}))
|
|
2644
|
+
);
|
|
2645
|
+
}
|
|
2646
|
+
});
|
|
2647
|
+
this.service = createService({
|
|
2648
|
+
document,
|
|
2649
|
+
handlers,
|
|
2650
|
+
sqlite,
|
|
2651
|
+
namespace,
|
|
2652
|
+
now: this.now,
|
|
2653
|
+
notFound: () => new Response(null, { status: 404 }),
|
|
2654
|
+
onError: (error) => {
|
|
2655
|
+
if (error instanceof HttpError) return error.toResponse();
|
|
2656
|
+
throw error;
|
|
2657
|
+
},
|
|
2658
|
+
before: (context) => {
|
|
2659
|
+
if (context.operation.operationId === "ClientLogin") return void 0;
|
|
2660
|
+
const token = bearerToken(context.request);
|
|
2661
|
+
if (!token) return unauthorized();
|
|
2662
|
+
if (faultEffect(context.request, "token_expired") !== void 0) {
|
|
2663
|
+
return unauthorized("The token expired");
|
|
2664
|
+
}
|
|
2665
|
+
return this.checkToken(token);
|
|
2666
|
+
}
|
|
2667
|
+
});
|
|
2668
|
+
this.app = this.service.app;
|
|
2669
|
+
this.sqlite = this.service.sqlite;
|
|
2670
|
+
}
|
|
2671
|
+
fetch(request) {
|
|
2672
|
+
return this.service.fetch(request);
|
|
2673
|
+
}
|
|
2674
|
+
async reset() {
|
|
2675
|
+
await this.service.reset();
|
|
2676
|
+
this.state.ensureSeeded();
|
|
2677
|
+
}
|
|
2678
|
+
iso() {
|
|
2679
|
+
return new Date(this.now()).toISOString().replace("Z", "");
|
|
2680
|
+
}
|
|
2681
|
+
checkToken(token) {
|
|
2682
|
+
const settings = this.state.current();
|
|
2683
|
+
if (!token.startsWith(TOKEN_PREFIX)) {
|
|
2684
|
+
return settings.apiKeys.length === 0 || settings.apiKeys.includes(token) ? void 0 : unauthorized();
|
|
2685
|
+
}
|
|
2686
|
+
const [encoded, issued, signature] = token.slice(TOKEN_PREFIX.length).split(".");
|
|
2687
|
+
const userName = encoded ? fromBase64url(encoded) : void 0;
|
|
2688
|
+
const issuedAt = Number(issued);
|
|
2689
|
+
if (userName === void 0 || !Number.isInteger(issuedAt) || signature !== sign(userName, issuedAt)) {
|
|
2690
|
+
return unauthorized();
|
|
2691
|
+
}
|
|
2692
|
+
if (this.now() / 1e3 >= issuedAt + settings.tokenTtlSeconds) {
|
|
2693
|
+
return unauthorized("The token expired");
|
|
2694
|
+
}
|
|
2695
|
+
return void 0;
|
|
2696
|
+
}
|
|
2697
|
+
json(context) {
|
|
2698
|
+
const issues = bodyIssues(context);
|
|
2699
|
+
if (issues.length > 0) {
|
|
2700
|
+
throw new HttpError(400, {
|
|
2701
|
+
type: "https://tools.ietf.org/html/rfc9110#section-15.5.1",
|
|
2702
|
+
title: "One or more validation errors occurred.",
|
|
2703
|
+
status: 400,
|
|
2704
|
+
errors: issuesByField(issues),
|
|
2705
|
+
traceId: "00-00000000000000000000000000000000-0000000000000000-00"
|
|
2706
|
+
});
|
|
2707
|
+
}
|
|
2708
|
+
return context.body.kind === "json" ? context.body.value : {};
|
|
2709
|
+
}
|
|
2710
|
+
login(context) {
|
|
2711
|
+
const body = this.json(context);
|
|
2712
|
+
const users = this.state.current().users;
|
|
2713
|
+
const userName = String(body.userName);
|
|
2714
|
+
if (users.length > 0 && !users.some((u) => u.userName === userName && u.password === body.password)) {
|
|
2715
|
+
return jsonRes(401, { message: "Invalid username or password." });
|
|
2716
|
+
}
|
|
2717
|
+
const issuedAt = Math.floor(this.now() / 1e3);
|
|
2718
|
+
return jsonRes(200, {
|
|
2719
|
+
token: `${TOKEN_PREFIX}${base64url(userName)}.${issuedAt}.${sign(userName, issuedAt)}`,
|
|
2720
|
+
expiration: new Date((issuedAt + this.state.current().tokenTtlSeconds) * 1e3).toISOString()
|
|
2721
|
+
});
|
|
2722
|
+
}
|
|
2723
|
+
patient(id) {
|
|
2724
|
+
return this.state.patients.get(String(id)) ?? this.state.patients.list({ where: (p) => p.eligibilityId === id }).at(0)?.value;
|
|
2725
|
+
}
|
|
2726
|
+
getForm(context) {
|
|
2727
|
+
if (faultEffect(context.request, "form_not_found") !== void 0) return jsonRes(200, []);
|
|
2728
|
+
const form = this.state.findForm(context.params.formName ?? "");
|
|
2729
|
+
if (!form) return jsonRes(200, []);
|
|
2730
|
+
const patientId = Number(context.query.PatientId ?? Number.NaN);
|
|
2731
|
+
const appointmentId = Number(context.query.AppointmentId ?? Number.NaN);
|
|
2732
|
+
const round = Number.isInteger(patientId) ? this.state.rounds.list({
|
|
2733
|
+
where: (r) => r.formId === form.id && r.patientId === patientId && (!Number.isInteger(appointmentId) || appointmentId === 0 || r.patientAppointmentId === appointmentId)
|
|
2734
|
+
}).at(0)?.value : void 0;
|
|
2735
|
+
return annotateResponse(
|
|
2736
|
+
jsonRes(200, [
|
|
2737
|
+
{
|
|
2738
|
+
formRoundId: round?.formRoundId ?? 0,
|
|
2739
|
+
patientAppointmentId: round?.patientAppointmentId ?? null,
|
|
2740
|
+
submitDate: round?.submitDate ?? null,
|
|
2741
|
+
fullFormDto: round ? this.answered(form, round) : form
|
|
2742
|
+
}
|
|
2743
|
+
]),
|
|
2744
|
+
{
|
|
2745
|
+
ids: {
|
|
2746
|
+
formId: String(form.id),
|
|
2747
|
+
...round ? { formRoundId: String(round.formRoundId) } : {}
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
);
|
|
2751
|
+
}
|
|
2752
|
+
/** The form with a round's answers checked (and free text echoed), as GetForm returns it. */
|
|
2753
|
+
answered(form, round) {
|
|
2754
|
+
const byQuestion = new Map(round.answers.map((a) => [a.questionId, a]));
|
|
2755
|
+
return {
|
|
2756
|
+
...form,
|
|
2757
|
+
groups: form.groups.map((group2) => ({
|
|
2758
|
+
...group2,
|
|
2759
|
+
groupQuestions: group2.groupQuestions.map((gq) => {
|
|
2760
|
+
const saved = byQuestion.get(gq.questionId);
|
|
2761
|
+
const answers = gq.question.questionAnswers.map((a) => ({
|
|
2762
|
+
...a,
|
|
2763
|
+
isChecked: saved?.answerIds.includes(a.id) ?? false,
|
|
2764
|
+
freeAnswerText: saved?.freeAnswerText[String(a.id)] ?? null
|
|
2765
|
+
}));
|
|
2766
|
+
return {
|
|
2767
|
+
...gq,
|
|
2768
|
+
question: {
|
|
2769
|
+
...gq.question,
|
|
2770
|
+
answerText: gq.question.answerTypeId === 1 ? saved?.freeAnswerText["0"] ?? null : null,
|
|
2771
|
+
questionAnswers: answers
|
|
2772
|
+
}
|
|
2773
|
+
};
|
|
2774
|
+
})
|
|
2775
|
+
}))
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
saveForm(context) {
|
|
2779
|
+
const body = this.json(context);
|
|
2780
|
+
if (faultEffect(context.request, "save_rejected") !== void 0) {
|
|
2781
|
+
return problem(400, "The form could not be saved.", { form: ["The form is locked."] });
|
|
2782
|
+
}
|
|
2783
|
+
const patientId = Number(context.query.patientId);
|
|
2784
|
+
if (!Number.isInteger(patientId) || !this.state.patients.get(String(patientId))) {
|
|
2785
|
+
return problem(404, `Patient ${context.query.patientId} not found.`);
|
|
2786
|
+
}
|
|
2787
|
+
const submitted = body.fullFormDto;
|
|
2788
|
+
const form = this.state.forms.get(String(submitted.id));
|
|
2789
|
+
if (!form) return problem(404, `Form ${submitted.id} not found.`);
|
|
2790
|
+
const questions = new Map(
|
|
2791
|
+
form.groups.flatMap(
|
|
2792
|
+
(g) => g.groupQuestions.map((gq) => [gq.questionId, gq.question])
|
|
2793
|
+
)
|
|
2794
|
+
);
|
|
2795
|
+
const errors = {};
|
|
2796
|
+
const answers = [];
|
|
2797
|
+
submitted.groups.forEach((group2, g) => {
|
|
2798
|
+
group2.groupQuestions.forEach((gq, i) => {
|
|
2799
|
+
const path = `fullFormDto.groups[${g}].groupQuestions[${i}]`;
|
|
2800
|
+
const question2 = questions.get(gq.questionId);
|
|
2801
|
+
if (!question2) {
|
|
2802
|
+
errors[`${path}.questionId`] = [
|
|
2803
|
+
`Question ${gq.questionId} is not part of form ${form.id}.`
|
|
2804
|
+
];
|
|
2805
|
+
return;
|
|
2806
|
+
}
|
|
2807
|
+
const free = {};
|
|
2808
|
+
const ids = [];
|
|
2809
|
+
for (const a of gq.question.questionAnswers) {
|
|
2810
|
+
if (question2.answerTypeId === 1) {
|
|
2811
|
+
free["0"] = a.answer;
|
|
2812
|
+
continue;
|
|
2813
|
+
}
|
|
2814
|
+
if (!question2.questionAnswers.some((option) => option.id === a.id)) {
|
|
2815
|
+
errors[`${path}.question.questionAnswers`] = [
|
|
2816
|
+
`Answer ${a.id} is not an option of question ${question2.id}.`
|
|
2817
|
+
];
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
ids.push(a.id);
|
|
2821
|
+
if (a.freeAnswerText) free[String(a.id)] = a.freeAnswerText;
|
|
2822
|
+
}
|
|
2823
|
+
if ((question2.answerTypeId === 2 || question2.answerTypeId === 4) && ids.length > 1) {
|
|
2824
|
+
errors[`${path}.question.questionAnswers`] = [`Question ${question2.id} takes one answer.`];
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
answers.push({ questionId: question2.id, answerIds: ids, freeAnswerText: free });
|
|
2828
|
+
});
|
|
2829
|
+
});
|
|
2830
|
+
if (Object.keys(errors).length > 0) {
|
|
2831
|
+
return problem(400, "One or more validation errors occurred.", errors);
|
|
2832
|
+
}
|
|
2833
|
+
const appointment = context.query.patientAppointmentId;
|
|
2834
|
+
const round = {
|
|
2835
|
+
formRoundId: this.state.next("round"),
|
|
2836
|
+
formId: form.id,
|
|
2837
|
+
patientId,
|
|
2838
|
+
patientAppointmentId: appointment === void 0 ? null : Number(appointment),
|
|
2839
|
+
submitDate: this.iso(),
|
|
2840
|
+
answers
|
|
2841
|
+
};
|
|
2842
|
+
this.state.rounds.insert(String(round.formRoundId), round);
|
|
2843
|
+
return annotateResponse(jsonRes(200, { success: true, message: "Form saved successfully." }), {
|
|
2844
|
+
ids: {
|
|
2845
|
+
patientId: String(patientId),
|
|
2846
|
+
formId: String(form.id),
|
|
2847
|
+
formRoundId: String(round.formRoundId)
|
|
2848
|
+
}
|
|
2849
|
+
});
|
|
2850
|
+
}
|
|
2851
|
+
search(context) {
|
|
2852
|
+
const miss = () => jsonRes(400, { isExists: false, message: "Patient not found." });
|
|
2853
|
+
if (faultEffect(context.request, "patient_not_found") !== void 0) return miss();
|
|
2854
|
+
const q = context.query;
|
|
2855
|
+
const first = String(q.FirstName ?? "").trim().toLowerCase();
|
|
2856
|
+
const last = String(q.LastName ?? "").trim().toLowerCase();
|
|
2857
|
+
const zip = String(q.zipCode ?? "").trim();
|
|
2858
|
+
const dob = normalizeDate(q.DateOfBirth);
|
|
2859
|
+
if (!first || !last || !zip || !dob) return miss();
|
|
2860
|
+
const found = this.state.patients.list({ order: "oldest" }).map((r) => r.value).find(
|
|
2861
|
+
(p) => p.firstName?.toLowerCase() === first && p.lastName?.toLowerCase() === last && p.zipCode === zip && normalizeDate(p.dateOfBirth) === dob
|
|
2862
|
+
);
|
|
2863
|
+
if (!found) return miss();
|
|
2864
|
+
return annotateResponse(
|
|
2865
|
+
jsonRes(200, { isExists: true, eligibleId: found.eligibilityId, programId: found.programId }),
|
|
2866
|
+
{ ids: { patientId: String(found.id) } }
|
|
2867
|
+
);
|
|
2868
|
+
}
|
|
2869
|
+
/** Create a patient, echoing CareTalk's full patient record. */
|
|
2870
|
+
addPatient(body) {
|
|
2871
|
+
const id = this.state.next("patient");
|
|
2872
|
+
const phone = text(body.mobilePhone);
|
|
2873
|
+
const stateId = num(body.userStateId);
|
|
2874
|
+
const patient = {
|
|
2875
|
+
firstName: text(body.firstName),
|
|
2876
|
+
middleInitial: text(body.middleInitial),
|
|
2877
|
+
lastName: text(body.lastName),
|
|
2878
|
+
mobilePhone: phone,
|
|
2879
|
+
homePhone: text(body.homePhone),
|
|
2880
|
+
token: text(body.token),
|
|
2881
|
+
tokenDate: text(body.tokenDate),
|
|
2882
|
+
apptStatus: text(body.apptStatus),
|
|
2883
|
+
email: text(body.email),
|
|
2884
|
+
dateOfBirth: text(body.dateOfBirth),
|
|
2885
|
+
gender: num(body.gender),
|
|
2886
|
+
address: text(body.address),
|
|
2887
|
+
state: text(body.state),
|
|
2888
|
+
city: text(body.city),
|
|
2889
|
+
userStateId: stateId,
|
|
2890
|
+
userState: US_STATES.find((s) => s.id === stateId)?.name ?? null,
|
|
2891
|
+
zipCode: text(body.zipCode),
|
|
2892
|
+
recordStatus: text(body.recordStatus) ?? "Active",
|
|
2893
|
+
clientStatus: text(body.clientStatus),
|
|
2894
|
+
clientBatchId: text(body.clientBatchId),
|
|
2895
|
+
authorization: typeof body.authorization === "boolean" ? body.authorization : null,
|
|
2896
|
+
mbi: null,
|
|
2897
|
+
ssn: null,
|
|
2898
|
+
mspPatientId: null,
|
|
2899
|
+
recordId: text(body.recordId),
|
|
2900
|
+
height: num(body.height),
|
|
2901
|
+
weight: num(body.weight),
|
|
2902
|
+
highBloodPressure: num(body.highBloodPressure),
|
|
2903
|
+
lowBloodPressure: num(body.lowBloodPressure),
|
|
2904
|
+
dateFinalized: text(body.dateFinalized),
|
|
2905
|
+
programId: num(body.programId) ?? this.state.current().programId,
|
|
2906
|
+
eligibilityId: id,
|
|
2907
|
+
clientId: 1,
|
|
2908
|
+
fileId: null,
|
|
2909
|
+
oldId: null,
|
|
2910
|
+
formattedUserMobile: phone ? phone.replace(/\D/g, "") : null,
|
|
2911
|
+
planName: null,
|
|
2912
|
+
healthGorillaId: text(body.healthGorillaId),
|
|
2913
|
+
hG_P360_Retrieve_location: null,
|
|
2914
|
+
hG_P360_Retrieve_Status: null,
|
|
2915
|
+
hG_P360_Retrieve_json: null,
|
|
2916
|
+
program: null,
|
|
2917
|
+
client: null,
|
|
2918
|
+
patientMedications: null,
|
|
2919
|
+
patientDiagnostics: null,
|
|
2920
|
+
patientAppointments: null,
|
|
2921
|
+
patientAppointment: null,
|
|
2922
|
+
formRounds: null,
|
|
2923
|
+
id,
|
|
2924
|
+
createdAt: this.iso(),
|
|
2925
|
+
updatedAt: null,
|
|
2926
|
+
deletedAt: null
|
|
2927
|
+
};
|
|
2928
|
+
this.state.patients.insert(String(id), patient);
|
|
2929
|
+
return patient;
|
|
2930
|
+
}
|
|
2931
|
+
insertPatient(context) {
|
|
2932
|
+
const patient = this.addPatient(this.json(context));
|
|
2933
|
+
return annotateResponse(jsonRes(200, patient), { ids: { patientId: String(patient.id) } });
|
|
2934
|
+
}
|
|
2935
|
+
/** Every 30-minute slot 09:00–16:30 per doctor on a date, minus booked ones. */
|
|
2936
|
+
slots(date) {
|
|
2937
|
+
const booked = new Set(
|
|
2938
|
+
this.state.appointments.list().map((r) => `${r.value.physicianId}@${r.value.startDateTime}`)
|
|
2939
|
+
);
|
|
2940
|
+
const day = Number(date.replace(/-/g, "")) % 1e6;
|
|
2941
|
+
return DEFAULT_DOCTORS.flatMap(
|
|
2942
|
+
(doctor) => Array.from({ length: 8 }, (_, i) => {
|
|
2943
|
+
const hour = 9 + i;
|
|
2944
|
+
const from = `${date}T${pad(hour)}:00:00`;
|
|
2945
|
+
return {
|
|
2946
|
+
id: doctor.doctorId * 1e8 + day * 100 + hour,
|
|
2947
|
+
medicalSpecialty: doctor.medicalSpecialty,
|
|
2948
|
+
doctorId: doctor.doctorId,
|
|
2949
|
+
doctorName: doctor.doctorName,
|
|
2950
|
+
doctor: null,
|
|
2951
|
+
doctorUid: null,
|
|
2952
|
+
timeZone: "Mountain Standard Time",
|
|
2953
|
+
offset: -7,
|
|
2954
|
+
from,
|
|
2955
|
+
to: `${date}T${pad(hour)}:30:00`
|
|
2956
|
+
};
|
|
2957
|
+
}).filter((slot) => !booked.has(`${slot.doctorId}@${slot.from}`))
|
|
2958
|
+
);
|
|
2959
|
+
}
|
|
2960
|
+
freeSlots(context) {
|
|
2961
|
+
const date = String(context.query.date ?? "");
|
|
2962
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
2963
|
+
return problem(400, "One or more validation errors occurred.", {
|
|
2964
|
+
date: [`The value '${date}' is not valid.`]
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
if (!this.patient(Number(context.query.eligibleId))) {
|
|
2968
|
+
return problem(400, "Eligible patient not found.");
|
|
2969
|
+
}
|
|
2970
|
+
return jsonRes(200, this.slots(date));
|
|
2971
|
+
}
|
|
2972
|
+
schedule(context) {
|
|
2973
|
+
const body = this.json(context);
|
|
2974
|
+
const eligibility = Number(body.patientId);
|
|
2975
|
+
const patient = this.patient(eligibility);
|
|
2976
|
+
if (!patient) return problem(400, "Eligible patient not found.");
|
|
2977
|
+
const doctorId = Number(body.doctorId);
|
|
2978
|
+
const from = String(body.from);
|
|
2979
|
+
const slot = this.slots(from.slice(0, 10)).find(
|
|
2980
|
+
(s) => s.doctorId === doctorId && s.from === from
|
|
2981
|
+
);
|
|
2982
|
+
if (!slot) {
|
|
2983
|
+
return problem(400, "The selected slot is not available.", {
|
|
2984
|
+
from: [`Doctor ${doctorId} has no free slot at ${from}.`]
|
|
2985
|
+
});
|
|
2986
|
+
}
|
|
2987
|
+
const appointment = {
|
|
2988
|
+
id: this.state.next("appointment"),
|
|
2989
|
+
eligibilityId: patient.eligibilityId,
|
|
2990
|
+
physicianId: doctorId,
|
|
2991
|
+
appointmentStatus: 1,
|
|
2992
|
+
startDateTime: from,
|
|
2993
|
+
endDateTime: String(body.to),
|
|
2994
|
+
createdAt: this.iso()
|
|
2995
|
+
};
|
|
2996
|
+
this.state.appointments.insert(String(appointment.id), appointment);
|
|
2997
|
+
return annotateResponse(
|
|
2998
|
+
jsonRes(200, {
|
|
2999
|
+
id: appointment.id,
|
|
3000
|
+
patientId: null,
|
|
3001
|
+
eligibilityId: appointment.eligibilityId,
|
|
3002
|
+
appointmentStatus: appointment.appointmentStatus,
|
|
3003
|
+
physicianId: appointment.physicianId
|
|
3004
|
+
}),
|
|
3005
|
+
{ ids: { appointmentId: String(appointment.id) } }
|
|
3006
|
+
);
|
|
3007
|
+
}
|
|
3008
|
+
/** Change an appointment's status code (e.g. 3 cancelled), as CareTalk staff would. */
|
|
3009
|
+
setAppointmentStatus(id, status) {
|
|
3010
|
+
const appointment = this.state.appointments.get(String(id));
|
|
3011
|
+
if (!appointment) return void 0;
|
|
3012
|
+
const next = { ...appointment, appointmentStatus: status };
|
|
3013
|
+
this.state.appointments.update(String(id), next);
|
|
3014
|
+
return next;
|
|
3015
|
+
}
|
|
3016
|
+
upsertForm(form) {
|
|
3017
|
+
this.state.forms.insert(String(form.id), form);
|
|
3018
|
+
return form;
|
|
3019
|
+
}
|
|
3020
|
+
rounds() {
|
|
3021
|
+
return this.state.rounds.list({ order: "oldest" }).map((r) => r.value);
|
|
3022
|
+
}
|
|
3023
|
+
patients() {
|
|
3024
|
+
return this.state.patients.list({ order: "oldest" }).map((r) => r.value);
|
|
3025
|
+
}
|
|
3026
|
+
};
|
|
3027
|
+
|
|
3028
|
+
export {
|
|
3029
|
+
DEFAULT_FORMS,
|
|
3030
|
+
US_STATES,
|
|
3031
|
+
DEFAULT_DOCTORS,
|
|
3032
|
+
document,
|
|
3033
|
+
operationIds,
|
|
3034
|
+
supportedOperationIds,
|
|
3035
|
+
CARETALK_PRESETS,
|
|
3036
|
+
createRuntime2 as createRuntime,
|
|
3037
|
+
CARETALK_NAMESPACE,
|
|
3038
|
+
tokenCredential,
|
|
3039
|
+
problem,
|
|
3040
|
+
normalizeDate,
|
|
3041
|
+
CareTalkAPI
|
|
3042
|
+
};
|
|
3043
|
+
//# sourceMappingURL=chunk-QWI3RIVV.js.map
|