@crvouga/mockingbird-service-aha 3.14.0 → 3.15.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.
@@ -0,0 +1,710 @@
1
+ import {
2
+ __export,
3
+ __reExport,
4
+ define_MOCKINGBIRD_ADMIN_BRAND_default
5
+ } from "./chunk-FIU4XWP6.js";
6
+
7
+ // mockingbird-service-runtime:@crvouga/mockingbird-runtime/service
8
+ var service_exports = {};
9
+ __export(service_exports, {
10
+ PACKAGE_VERSION: () => PACKAGE_VERSION,
11
+ createRuntime: () => createRuntime
12
+ });
13
+ __reExport(service_exports, service_star);
14
+ import * as service_star from "@crvouga/mockingbird-runtime/service";
15
+ import { PACKAGE_VERSION as SHARED_VERSION, createRuntime as sharedRuntime } from "@crvouga/mockingbird-runtime/service";
16
+ var PACKAGE_VERSION = true ? "3.15.0" : SHARED_VERSION;
17
+ var ADMIN_BRAND = typeof define_MOCKINGBIRD_ADMIN_BRAND_default === "object" ? define_MOCKINGBIRD_ADMIN_BRAND_default : void 0;
18
+ var createRuntime = (options) => sharedRuntime({
19
+ ...options,
20
+ version: options.version ?? PACKAGE_VERSION,
21
+ adminBrand: options.adminBrand ?? ADMIN_BRAND
22
+ });
23
+
24
+ // src/generated/openapi.ts
25
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"AHA (Advanced Health Academy) partner API (Mockingbird subset)","description":"Stateful emulator of the AHA at-home phlebotomy partner API: create-or-update order and cancel.\\nThe vendor has no pull API; order state reaches the partner only as inbound webhooks, which\\nthe emulator emits from admin transitions (see the README). Hand-authored from the consumer's\\nwire shapes (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from aha.service.ts, aha.types.ts (zod request/response schemas) and aha.lab-provider.ts. Success responses come in one of two envelopes (raw, or {success, data}) because our two clients disagree (G-A1); the mock serves either."}},"servers":[{"url":"https://stage-api.mobileaha.com"}],"security":[{"hmacKey":[],"hmacTimestamp":[],"hmacSignature":[]},{"legacyKey":[]}],"paths":{"/v1/{partner}/create-order":{"post":{"operationId":"CreateOrder","description":"Create an order, or update it when partner_order_id already exists (the same order_number is returned). Honors X-Idempotency-Key.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderBody"}}}},"responses":{"200":{"description":"Order created or updated (raw or wrapped envelope, per namespace setting)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CreateOrderResponse"},{"$ref":"#/components/schemas/WrappedCreateOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/v1/{partner}/cancel":{"post":{"operationId":"CancelOrder","description":"Cancel an order by partner_order_id. The emulator also accepts the AHA order_number here, because our lab-provider client sends it in that field (G-A1).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderBody"}}}},"responses":{"200":{"description":"Cancel outcome (raw or wrapped envelope; status ERROR when not cancellable)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CancelOrderResponse"},{"$ref":"#/components/schemas/WrappedCancelOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown partner order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"hmacKey":{"type":"apiKey","in":"header","name":"X-API-KEY"},"hmacTimestamp":{"type":"apiKey","in":"header","name":"X-TIMESTAMP","description":"Unix epoch milliseconds."},"hmacSignature":{"type":"apiKey","in":"header","name":"X-SIGNATURE","description":"base64(HMAC-SHA256(apiSecret, \\"<apiKey>:<path>:<timestamp>\\"))."},"legacyKey":{"type":"apiKey","in":"header","name":"X-Acme-Auth-Key","description":"Legacy mode (AHA_USE_LEGACY_AUTH=true), sent with X-API-Version 1.0. The real header embeds the partner's name (\`X-<Partner>-Auth-Key\`); the emulator accepts any partner name."}},"parameters":{"Partner":{"name":"partner","in":"path","required":true,"description":"The partner segment AHA assigns your account (its slug), e.g. \`acme\`.","schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$","examples":["acme"]}},"IdempotencyKey":{"name":"X-Idempotency-Key","in":"header","required":false,"description":"Sent by the lab-provider client; the same key and body replays the stored response.","schema":{"type":"string","pattern":"^[A-Za-z0-9:_.-]{1,128}$"}}},"schemas":{"TestCode":{"type":"object","required":["test_code","test_description"],"properties":{"test_code":{"type":"string","minLength":1,"maxLength":64},"test_description":{"type":"string","maxLength":200}}},"CreateOrderBody":{"type":"object","required":["partner_order_id","patient_first_name","patient_id","patient_last_name","biological_sex","patient_dob","patient_phone_number","patient_address_line1","patient_city","patient_state","patient_zipcode","service_type","npi","ordering_physician","test_codes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64},"patient_first_name":{"type":"string","minLength":1,"maxLength":60},"patient_id":{"type":"string","minLength":1,"maxLength":64},"patient_middle_initial":{"type":"string","maxLength":5},"patient_last_name":{"type":"string","minLength":1,"maxLength":60},"biological_sex":{"type":"string","enum":["Male","Female","Non-binary"]},"patient_dob":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"patient_phone_number":{"type":"string","description":"10 digits from AhaService; the lab-provider client may send +1XXXXXXXXXX.","maxLength":20},"patient_email_address":{"type":"string","maxLength":120},"patient_address_line1":{"type":"string","minLength":1,"maxLength":120},"patient_address_line2":{"type":"string","maxLength":120},"patient_city":{"type":"string","minLength":1,"maxLength":60},"patient_state":{"type":"string","minLength":1,"maxLength":20},"patient_zipcode":{"type":"string","minLength":1,"maxLength":10},"service_type":{"type":"string","enum":["Full Service","Draw Only","Pickup Only"]},"preferred_schedule_date":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"preferred_schedule_time":{"type":"string","description":"HH:MM","maxLength":8},"patient_timezone":{"type":"string","description":"IANA zone, e.g. America/New_York","maxLength":64},"npi":{"type":"string","minLength":1,"maxLength":20},"ordering_physician":{"type":"string","minLength":1,"maxLength":120},"test_codes":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/TestCode"}}}},"CancelOrderBody":{"type":"object","required":["partner_order_id","notes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"order","missing":"AC-999999999"}},"notes":{"type":"array","maxItems":5,"items":{"type":"object","required":["note_type","notes"],"properties":{"note_type":{"type":"string","enum":["CANCELLATION"]},"notes":{"type":"string","maxLength":500}}}}}},"CreateOrderResponse":{"type":"object","required":["content","message","status"],"properties":{"content":{"type":"object","required":["partner_order_id","order_number"],"properties":{"partner_order_id":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true}},"order_number":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}},"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCreateOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CreateOrderResponse"}}},"CancelOrderResponse":{"type":"object","required":["message","status"],"properties":{"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCancelOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CancelOrderResponse"}}},"ErrorBody":{"type":"object","required":["status","message"],"properties":{"status":{"type":"string","enum":["ERROR"]},"message":{"type":"string"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}}}}}`);
26
+ var operationIds = ["CreateOrder", "CancelOrder"];
27
+ var supportedOperationIds = ["CreateOrder", "CancelOrder"];
28
+
29
+ // src/state.ts
30
+ var DEFAULT_SETTINGS = {
31
+ envelope: "raw",
32
+ credentials: [],
33
+ allowLegacy: true,
34
+ timestampToleranceMs: 3e5,
35
+ autoSchedule: null,
36
+ defaultTimeZone: "America/New_York",
37
+ cancelWebhook: true
38
+ };
39
+ var AhaState = class {
40
+ constructor(sqlite, namespace, seed) {
41
+ this.seed = seed;
42
+ this.orders = new service_exports.Collection(sqlite, namespace, "orders");
43
+ this.settings = new service_exports.Collection(sqlite, namespace, "settings");
44
+ this.ids = new service_exports.IdSequence(sqlite, namespace, "aha");
45
+ this.idempotency = new service_exports.IdempotencyStore(sqlite, namespace);
46
+ this.ensureSeeded();
47
+ }
48
+ seed;
49
+ orders;
50
+ settings;
51
+ ids;
52
+ idempotency;
53
+ ensureSeeded() {
54
+ if (!this.settings.has("settings")) {
55
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
56
+ }
57
+ }
58
+ current() {
59
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
60
+ }
61
+ update(patch) {
62
+ const next = { ...this.current(), ...patch };
63
+ this.settings.insert("settings", next);
64
+ return next;
65
+ }
66
+ /** By partner order id, then by AHA order number (our lab-provider cancels with the latter). */
67
+ findOrder(id) {
68
+ return this.orders.get(id) ?? this.orders.list({ where: (order) => order.order_number === id }).at(0)?.value;
69
+ }
70
+ nextOrderNumber() {
71
+ return this.ids.next("AHA-", 10).toUpperCase();
72
+ }
73
+ };
74
+
75
+ // src/statuses.ts
76
+ var ORDER_STATUSES = [
77
+ "Scheduled",
78
+ "Rescheduled",
79
+ "Cancelled",
80
+ "Check In",
81
+ "Check Out",
82
+ "Lab Testing In Progress",
83
+ "Non Scheduled Update"
84
+ ];
85
+ var DRAW_STATUSES = [
86
+ "Sample Collected",
87
+ "Completed",
88
+ "Patient Refused",
89
+ "UTO",
90
+ "Patient Not Home",
91
+ "Patient Rescheduled",
92
+ "Order Cancelled",
93
+ "Others",
94
+ "Patient Asked to Reschedule"
95
+ ];
96
+ var ORDER_PLACED = "Order Placed";
97
+ var key = (value) => value.trim().toLowerCase().replace(/[\s_]+/g, " ");
98
+ var canonical = (known, value) => known.find((candidate) => key(candidate) === key(value)) ?? value.trim();
99
+ var orderStatus = (value) => canonical(ORDER_STATUSES, value);
100
+ var drawStatus = (value) => canonical(DRAW_STATUSES, value);
101
+ var isScheduling = (status) => status === "Scheduled" || status === "Rescheduled";
102
+ var isDrawn = (draw) => draw === "Sample Collected" || draw === "Completed";
103
+
104
+ // src/time.ts
105
+ var isTimeZone = (zone) => {
106
+ try {
107
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ }
112
+ };
113
+ var formatters = /* @__PURE__ */ new Map();
114
+ var formatter = (zone) => {
115
+ let found = formatters.get(zone);
116
+ if (!found) {
117
+ found = new Intl.DateTimeFormat("en-US", {
118
+ timeZone: zone,
119
+ hourCycle: "h23",
120
+ year: "numeric",
121
+ month: "2-digit",
122
+ day: "2-digit",
123
+ hour: "2-digit",
124
+ minute: "2-digit",
125
+ second: "2-digit"
126
+ });
127
+ formatters.set(zone, found);
128
+ }
129
+ return found;
130
+ };
131
+ var zonedParts = (epochMs, zone) => {
132
+ const parts = {};
133
+ for (const part of formatter(zone).formatToParts(new Date(epochMs))) parts[part.type] = part.value;
134
+ const hour = parts.hour === "24" ? "00" : parts.hour;
135
+ return {
136
+ date: `${parts.year}-${parts.month}-${parts.day}`,
137
+ time: `${hour}:${parts.minute}`,
138
+ timeWithSeconds: `${hour}:${parts.minute}:${parts.second}`
139
+ };
140
+ };
141
+ var zonedToEpoch = (date, time, zone) => {
142
+ const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
143
+ const t = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(time);
144
+ if (!d || !t) return void 0;
145
+ const asUtc = Date.UTC(
146
+ Number(d[1]),
147
+ Number(d[2]) - 1,
148
+ Number(d[3]),
149
+ Number(t[1]),
150
+ Number(t[2]),
151
+ Number(t[3] ?? 0)
152
+ );
153
+ let guess = asUtc;
154
+ for (let i = 0; i < 2; i++) {
155
+ const local = zonedParts(guess, zone);
156
+ const localAsUtc = Date.parse(`${local.date}T${local.timeWithSeconds}Z`);
157
+ guess += asUtc - localAsUtc;
158
+ }
159
+ return guess;
160
+ };
161
+
162
+ // src/runtime.ts
163
+ var WEBHOOK_PATH = "/bloodwork/aha-webhook";
164
+ var AHA_PRESETS = {
165
+ bad_signature: {
166
+ description: "Every call answers 401 Invalid signature (AHA_API_ERROR / upstream)",
167
+ rules: [{ pathPrefix: "/v1/", effect: "bad_signature" }]
168
+ },
169
+ rate_limited: {
170
+ description: "Every call answers 429 (the lab-provider client maps it to rate_limit, retryable)",
171
+ rules: [
172
+ {
173
+ pathPrefix: "/v1/",
174
+ status: 429,
175
+ body: { status: "ERROR", message: "Too many requests" }
176
+ }
177
+ ]
178
+ },
179
+ server_error: {
180
+ description: "Every call answers 500",
181
+ rules: [
182
+ {
183
+ pathPrefix: "/v1/",
184
+ status: 500,
185
+ body: { status: "ERROR", message: "Internal server error" }
186
+ }
187
+ ]
188
+ },
189
+ order_error: {
190
+ description: "create-order / cancel answer 200 with inner status ERROR (the lab provider fails it; AhaService does not check)",
191
+ rules: [{ pathPrefix: "/v1/", effect: "order_error" }]
192
+ },
193
+ invalid_response: {
194
+ description: "create-order / cancel answer 200 with a body neither client's zod schema accepts",
195
+ rules: [{ pathPrefix: "/v1/", effect: "invalid_response" }]
196
+ },
197
+ webhook_duplicate: {
198
+ description: "The next webhook is delivered twice",
199
+ webhook: { mode: "duplicate" }
200
+ },
201
+ webhook_reorder: {
202
+ description: "The next two webhooks arrive swapped",
203
+ webhook: { mode: "reorder" }
204
+ },
205
+ webhook_drop: {
206
+ description: "The next webhook is never delivered",
207
+ webhook: { mode: "drop" }
208
+ }
209
+ };
210
+ var json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
211
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
212
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
213
+ var parseAutoSchedule = (value) => {
214
+ if (value === null) return null;
215
+ if (typeof value === "number" && value >= 0) return { afterMs: value };
216
+ if (!isRecord(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
217
+ return "autoSchedule must be {afterMs, leadMs?}, a number of ms, or null";
218
+ }
219
+ if (value.leadMs !== void 0 && typeof value.leadMs !== "number") return "leadMs: number";
220
+ return {
221
+ afterMs: value.afterMs,
222
+ ...typeof value.leadMs === "number" ? { leadMs: value.leadMs } : {}
223
+ };
224
+ };
225
+ var parseCredentials = (value) => {
226
+ if (!Array.isArray(value)) return "credentials: [{apiKey, apiSecret?}]";
227
+ const out = [];
228
+ for (const each of value) {
229
+ if (!isRecord(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
230
+ out.push({
231
+ apiKey: each.apiKey,
232
+ ...typeof each.apiSecret === "string" ? { apiSecret: each.apiSecret } : {}
233
+ });
234
+ }
235
+ return out;
236
+ };
237
+ var visible = (settings) => ({
238
+ ...settings,
239
+ credentials: settings.credentials.map((c) => ({
240
+ apiKey: c.apiKey,
241
+ ...c.apiSecret !== void 0 ? { apiSecret: "***" } : {}
242
+ }))
243
+ });
244
+ var adminRoutes = (runtime) => ({
245
+ "GET /orders": ({ namespace }) => json(200, { orders: runtime.instance(namespace).orders() }),
246
+ "POST /orders/:partnerOrderId/transition": ({ params, body, namespace }) => {
247
+ if (!isRecord(body) || typeof body.status !== "string") {
248
+ return adminError(
249
+ 400,
250
+ 'expected {"status": "<AHA status>", "drawStatus"?, "scheduledAt"?, "timeZone"?}'
251
+ );
252
+ }
253
+ const input = { status: body.status };
254
+ if (typeof body.drawStatus === "string") input.drawStatus = body.drawStatus;
255
+ if (typeof body.scheduledAt === "string" || typeof body.scheduledAt === "number") {
256
+ input.scheduledAt = body.scheduledAt;
257
+ }
258
+ if (typeof body.timeZone === "string") input.timeZone = body.timeZone;
259
+ try {
260
+ const moved = runtime.instance(namespace).transition(params.partnerOrderId, input);
261
+ return moved ? json(200, moved) : adminError(404, `no order ${params.partnerOrderId}`);
262
+ } catch (err) {
263
+ if (err instanceof RangeError) return adminError(400, err.message);
264
+ throw err;
265
+ }
266
+ },
267
+ "GET /settings": ({ namespace }) => json(200, visible(runtime.instance(namespace).state.current())),
268
+ "PUT /settings": ({ body, namespace }) => {
269
+ if (!isRecord(body)) return adminError(400, "expected a JSON object");
270
+ const patch = {};
271
+ if (body.envelope !== void 0) {
272
+ if (body.envelope !== "raw" && body.envelope !== "wrapped")
273
+ return adminError(400, 'envelope: "raw" | "wrapped"');
274
+ patch.envelope = body.envelope;
275
+ }
276
+ if (body.credentials !== void 0) {
277
+ const parsed = parseCredentials(body.credentials);
278
+ if (typeof parsed === "string") return adminError(400, parsed);
279
+ patch.credentials = parsed;
280
+ }
281
+ for (const flag of ["allowLegacy", "cancelWebhook"]) {
282
+ if (body[flag] !== void 0) {
283
+ if (typeof body[flag] !== "boolean") return adminError(400, `${flag}: boolean`);
284
+ patch[flag] = body[flag];
285
+ }
286
+ }
287
+ if (body.timestampToleranceMs !== void 0) {
288
+ if (typeof body.timestampToleranceMs !== "number")
289
+ return adminError(400, "timestampToleranceMs: number");
290
+ patch.timestampToleranceMs = body.timestampToleranceMs;
291
+ }
292
+ if (body.defaultTimeZone !== void 0) {
293
+ if (typeof body.defaultTimeZone !== "string")
294
+ return adminError(400, "defaultTimeZone: IANA zone");
295
+ patch.defaultTimeZone = body.defaultTimeZone;
296
+ }
297
+ if (body.autoSchedule !== void 0) {
298
+ const parsed = parseAutoSchedule(body.autoSchedule);
299
+ if (typeof parsed === "string") return adminError(400, parsed);
300
+ patch.autoSchedule = parsed;
301
+ }
302
+ return json(200, visible(runtime.instance(namespace).state.update(patch)));
303
+ },
304
+ "POST /tick": ({ namespace }) => json(200, { applied: runtime.instance(namespace).tick() })
305
+ });
306
+ var createRuntime2 = (options = {}) => {
307
+ const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
308
+ const hub = (0, service_exports.createWebhookHub)({
309
+ signer: service_exports.signers.header("Authorization", (secret) => `Token ${secret}`),
310
+ ...retryDelaysMs ? { retryDelaysMs } : {},
311
+ ...send ? { fetch: send } : {},
312
+ endpoints: options.webhooks ? [endpoint] : []
313
+ });
314
+ const runtime = createRuntime({
315
+ name: AHA_NAMESPACE,
316
+ document,
317
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
318
+ ...options.clock ? { clock: options.clock } : {},
319
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
320
+ ...options.adminPrefix !== void 0 ? { adminPrefix: options.adminPrefix } : {},
321
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
322
+ ...options.adminControls !== void 0 ? { adminControls: options.adminControls } : {},
323
+ ...options.onLog ? { onLog: options.onLog } : {},
324
+ credential: apiKeyCredential,
325
+ presets: AHA_PRESETS,
326
+ webhooks: hub,
327
+ create: ({ sqlite, namespace, publicNamespace, clock }) => new AhaAPI({
328
+ sqlite,
329
+ namespace,
330
+ now: clock.now,
331
+ ...options.wallClock ? { wallClock: options.wallClock } : {},
332
+ ...options.settings ? { settings: options.settings } : {},
333
+ onWebhook: (event) => hub.publish({
334
+ namespace: publicNamespace,
335
+ type: event.status,
336
+ body: event
337
+ })
338
+ }),
339
+ describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
340
+ admin: adminRoutes
341
+ });
342
+ let timer;
343
+ if (options.tickMs !== void 0 && options.tickMs > 0) {
344
+ timer = setInterval(() => {
345
+ for (const name of runtime.namespaces()) runtime.instance(name).tick();
346
+ }, options.tickMs);
347
+ timer.unref?.();
348
+ }
349
+ return Object.assign(runtime, {
350
+ webhooks: hub,
351
+ stop: () => {
352
+ if (timer !== void 0) clearInterval(timer);
353
+ }
354
+ });
355
+ };
356
+
357
+ // src/index.ts
358
+ var AHA_NAMESPACE = "aha";
359
+ var DAY_MS = 864e5;
360
+ var error = (status, message, extra = {}) => (0, service_exports.jsonRes)(status, { status: "ERROR", message, ...extra });
361
+ var record = (context) => {
362
+ if (context.body.kind !== "json" || typeof context.body.value !== "object" || !context.body.value || Array.isArray(context.body.value)) {
363
+ throw new service_exports.HttpError(400, { status: "ERROR", message: "Request body must be a JSON object" });
364
+ }
365
+ return context.body.value;
366
+ };
367
+ var isBase64Sha256 = (value) => {
368
+ try {
369
+ return (0, service_exports.fromBase64)(value).length === 32;
370
+ } catch {
371
+ return false;
372
+ }
373
+ };
374
+ var legacyAuthKey = (request) => {
375
+ for (const [name, value] of request.headers) {
376
+ if (/^x-[a-z0-9_-]+-auth-key$/.test(name) && value) return value;
377
+ }
378
+ return void 0;
379
+ };
380
+ var verifyAuth = async (request, path, settings, wallNow) => {
381
+ const apiKey = request.headers.get("x-api-key");
382
+ if (apiKey) {
383
+ const timestamp = request.headers.get("x-timestamp");
384
+ const signature = request.headers.get("x-signature");
385
+ if (!timestamp || !signature) return "Missing X-TIMESTAMP or X-SIGNATURE";
386
+ if (!/^\d{10,16}$/.test(timestamp)) return "X-TIMESTAMP must be epoch milliseconds";
387
+ if (settings.timestampToleranceMs > 0 && Math.abs(wallNow - Number(timestamp)) > settings.timestampToleranceMs) {
388
+ return "Request timestamp outside the allowed window";
389
+ }
390
+ const known = settings.credentials.find((c) => c.apiKey === apiKey);
391
+ if (settings.credentials.length > 0 && !known) return "Invalid API key";
392
+ if (known?.apiSecret !== void 0) {
393
+ const expected = await (0, service_exports.hmac)(
394
+ "SHA-256",
395
+ known.apiSecret,
396
+ `${apiKey}:${path}:${timestamp}`,
397
+ "base64"
398
+ );
399
+ return (0, service_exports.timingSafeEqual)(expected, signature) ? void 0 : "Invalid signature";
400
+ }
401
+ if (settings.credentials.length > 0) return "API key has no secret; use legacy auth";
402
+ return isBase64Sha256(signature) ? void 0 : "Invalid signature";
403
+ }
404
+ const legacy = legacyAuthKey(request);
405
+ if (legacy) {
406
+ if (!settings.allowLegacy) return "Legacy authentication is disabled";
407
+ if (settings.credentials.length > 0 && !settings.credentials.some((c) => c.apiKey === legacy)) {
408
+ return "Invalid API key";
409
+ }
410
+ return void 0;
411
+ }
412
+ return "Missing authentication headers";
413
+ };
414
+ var apiKeyCredential = (request) => request.headers.get("x-api-key") ?? legacyAuthKey(request);
415
+ var AhaAPI = class {
416
+ app;
417
+ sqlite;
418
+ state;
419
+ service;
420
+ now;
421
+ wallClock;
422
+ onWebhook;
423
+ constructor(options = {}) {
424
+ const sqlite = (0, service_exports.bootSqlite)(options.sqlite);
425
+ const namespace = options.namespace ?? AHA_NAMESPACE;
426
+ this.now = options.now ?? (() => Date.now());
427
+ this.wallClock = options.wallClock ?? (() => Date.now());
428
+ this.onWebhook = options.onWebhook;
429
+ this.state = new AhaState(sqlite, namespace, options.settings ?? {});
430
+ const handlers = (0, service_exports.defineOperations)({
431
+ CreateOrder: (context) => this.idempotent(context, () => this.createOrder(context)),
432
+ CancelOrder: (context) => this.idempotent(context, () => this.cancelOrder(context))
433
+ });
434
+ this.service = (0, service_exports.createService)({
435
+ document,
436
+ handlers,
437
+ sqlite,
438
+ namespace,
439
+ now: this.now,
440
+ notFound: () => error(404, "Not Found"),
441
+ onError: (err) => {
442
+ if (err instanceof service_exports.HttpError) return err.toResponse();
443
+ throw err;
444
+ },
445
+ before: async (context) => {
446
+ this.tick();
447
+ if ((0, service_exports.faultEffect)(context.request, "bad_signature") !== void 0) {
448
+ return error(401, "Invalid signature");
449
+ }
450
+ const problem = await verifyAuth(
451
+ context.request,
452
+ context.url.pathname,
453
+ this.state.current(),
454
+ this.wallClock()
455
+ );
456
+ return problem === void 0 ? void 0 : error(401, problem);
457
+ }
458
+ });
459
+ this.app = this.service.app;
460
+ this.sqlite = this.service.sqlite;
461
+ }
462
+ fetch(request) {
463
+ return this.service.fetch(request);
464
+ }
465
+ async reset() {
466
+ await this.service.reset();
467
+ this.state.ensureSeeded();
468
+ }
469
+ iso() {
470
+ return new Date(this.now()).toISOString();
471
+ }
472
+ /** The success body in the namespace's envelope. */
473
+ envelope(body) {
474
+ return (0, service_exports.jsonRes)(
475
+ 200,
476
+ this.state.current().envelope === "wrapped" ? { success: true, data: body } : body
477
+ );
478
+ }
479
+ async idempotent(context, handler) {
480
+ const key2 = context.request.headers.get("x-idempotency-key");
481
+ if (!key2) return handler();
482
+ const body = context.body.kind === "json" ? context.body.value : null;
483
+ return this.state.idempotency.run(
484
+ key2,
485
+ (0, service_exports.requestFingerprint)(context.request.method, context.url.pathname, body),
486
+ {
487
+ mismatch: () => error(409, "Idempotency key already used with a different request"),
488
+ conflict: () => error(409, "A request with this idempotency key is still in progress")
489
+ },
490
+ handler
491
+ );
492
+ }
493
+ validate(context) {
494
+ const issues = (0, service_exports.bodyIssues)(context);
495
+ return issues.length > 0 ? error(400, "Invalid request", { errors: (0, service_exports.issuesByField)(issues) }) : void 0;
496
+ }
497
+ createOrder(context) {
498
+ const body = record(context);
499
+ const invalid = this.validate(context);
500
+ if (invalid) return invalid;
501
+ const partnerOrderId = String(body.partner_order_id);
502
+ const zone = typeof body.patient_timezone === "string" && isTimeZone(body.patient_timezone) ? body.patient_timezone : this.state.current().defaultTimeZone;
503
+ const preferred = typeof body.preferred_schedule_date === "string" && typeof body.preferred_schedule_time === "string" ? zonedToEpoch(body.preferred_schedule_date, body.preferred_schedule_time, zone) : void 0;
504
+ const existing = this.state.orders.get(partnerOrderId);
505
+ const now = this.iso();
506
+ const order = existing ? {
507
+ ...existing,
508
+ timeZone: zone,
509
+ scheduledAt: preferred !== void 0 ? new Date(preferred).toISOString() : existing.scheduledAt,
510
+ updated_at: now
511
+ } : {
512
+ partner_order_id: partnerOrderId,
513
+ order_number: this.state.nextOrderNumber(),
514
+ status: ORDER_PLACED,
515
+ drawStatus: null,
516
+ scheduledAt: preferred !== void 0 ? new Date(preferred).toISOString() : null,
517
+ timeZone: zone,
518
+ cancelled: false,
519
+ created_at: now,
520
+ updated_at: now,
521
+ createdAtMs: this.now(),
522
+ autoScheduled: false
523
+ };
524
+ this.state.orders.insert(partnerOrderId, order);
525
+ const ids = { partnerOrderId, orderNumber: order.order_number };
526
+ if ((0, service_exports.faultEffect)(context.request, "invalid_response") !== void 0) {
527
+ return (0, service_exports.annotateResponse)((0, service_exports.jsonRes)(200, { ok: true }), { ids });
528
+ }
529
+ if ((0, service_exports.faultEffect)(context.request, "order_error") !== void 0) {
530
+ return (0, service_exports.annotateResponse)(
531
+ this.envelope({
532
+ content: { partner_order_id: partnerOrderId, order_number: "" },
533
+ message: "Unable to create order: patient address could not be verified",
534
+ status: "ERROR"
535
+ }),
536
+ { ids }
537
+ );
538
+ }
539
+ return (0, service_exports.annotateResponse)(
540
+ this.envelope({
541
+ content: { partner_order_id: partnerOrderId, order_number: order.order_number },
542
+ message: existing ? "Order updated successfully" : "Order created successfully",
543
+ status: "SUCCESS"
544
+ }),
545
+ { ids }
546
+ );
547
+ }
548
+ cancelOrder(context) {
549
+ const body = record(context);
550
+ const invalid = this.validate(context);
551
+ if (invalid) return invalid;
552
+ const order = this.state.findOrder(String(body.partner_order_id));
553
+ if (!order) return error(404, `Order ${String(body.partner_order_id)} not found`);
554
+ const ids = { partnerOrderId: order.partner_order_id, orderNumber: order.order_number };
555
+ if ((0, service_exports.faultEffect)(context.request, "invalid_response") !== void 0) {
556
+ return (0, service_exports.annotateResponse)((0, service_exports.jsonRes)(200, { ok: true }), { ids });
557
+ }
558
+ if ((0, service_exports.faultEffect)(context.request, "order_error") !== void 0 || isDrawn(order.drawStatus)) {
559
+ return (0, service_exports.annotateResponse)(
560
+ this.envelope({
561
+ message: `Order ${order.partner_order_id} cannot be cancelled after the sample was collected`,
562
+ status: "ERROR"
563
+ }),
564
+ { ids }
565
+ );
566
+ }
567
+ if (!order.cancelled) {
568
+ if (this.state.current().cancelWebhook) {
569
+ this.transition(order.partner_order_id, { status: "Cancelled" });
570
+ } else {
571
+ this.state.orders.update(order.partner_order_id, {
572
+ ...order,
573
+ status: "Cancelled",
574
+ cancelled: true,
575
+ updated_at: this.iso()
576
+ });
577
+ }
578
+ }
579
+ return (0, service_exports.annotateResponse)(
580
+ this.envelope({
581
+ message: order.cancelled ? "Order already cancelled" : "Order cancelled successfully",
582
+ status: "SUCCESS"
583
+ }),
584
+ { ids }
585
+ );
586
+ }
587
+ /**
588
+ * Move an order to a vendor status and emit the webhook with every field our handler reads.
589
+ * Throws `RangeError` for a bad zone or appointment time.
590
+ */
591
+ transition(id, input) {
592
+ const order = this.state.findOrder(id);
593
+ if (!order) return void 0;
594
+ const status = orderStatus(input.status);
595
+ const zone = input.timeZone ?? order.timeZone;
596
+ if (!isTimeZone(zone))
597
+ throw new RangeError(`timeZone ${JSON.stringify(zone)} is not an IANA zone`);
598
+ const nowMs = this.now();
599
+ const nowLocal = zonedParts(nowMs, zone);
600
+ const draw = status === "Check Out" ? drawStatus(input.drawStatus ?? "Sample Collected") : null;
601
+ let scheduledAt = order.scheduledAt;
602
+ if (isScheduling(status)) {
603
+ if (input.scheduledAt !== void 0) {
604
+ const parsed = typeof input.scheduledAt === "number" ? input.scheduledAt : Date.parse(input.scheduledAt);
605
+ if (!Number.isFinite(parsed)) {
606
+ throw new RangeError(`scheduledAt ${JSON.stringify(input.scheduledAt)} is not a date`);
607
+ }
608
+ scheduledAt = new Date(parsed).toISOString();
609
+ } else if (status === "Rescheduled" && order.scheduledAt) {
610
+ scheduledAt = new Date(Date.parse(order.scheduledAt) + DAY_MS).toISOString();
611
+ } else if (!scheduledAt) {
612
+ scheduledAt = new Date(Math.ceil((nowMs + DAY_MS) / 36e5) * 36e5).toISOString();
613
+ }
614
+ }
615
+ const webhook = {
616
+ status,
617
+ partnerOrderId: order.partner_order_id,
618
+ ahaOrderId: order.order_number
619
+ };
620
+ if (isScheduling(status) && scheduledAt) {
621
+ const at = zonedParts(Date.parse(scheduledAt), zone);
622
+ Object.assign(webhook, {
623
+ scheduleServiceTime: `${at.date}T${at.timeWithSeconds}`,
624
+ scheduleServiceTimeZone: zone,
625
+ scheduledServiceDate: at.date,
626
+ scheduledServiceTime: at.time,
627
+ scheduledServiceTimeZone: zone,
628
+ scheduleConfirmationDate: nowLocal.date,
629
+ scheduleConfirmationTime: nowLocal.time,
630
+ scheduleConfirmationTimeZone: zone
631
+ });
632
+ }
633
+ if (status === "Check In") {
634
+ Object.assign(webhook, {
635
+ checkInDate: nowLocal.date,
636
+ checkInTime: nowLocal.time,
637
+ checkInTimeZone: zone
638
+ });
639
+ }
640
+ if (draw !== null) {
641
+ Object.assign(webhook, {
642
+ drawStatus: draw,
643
+ drawStatusDate: nowLocal.date,
644
+ drawStatusTime: nowLocal.time,
645
+ drawStatusTimeZone: zone
646
+ });
647
+ }
648
+ if (status === "Lab Testing In Progress") {
649
+ Object.assign(webhook, {
650
+ dropOffDate: nowLocal.date,
651
+ dropOffTime: nowLocal.time,
652
+ dropOffTimeZone: zone
653
+ });
654
+ }
655
+ const next = {
656
+ ...order,
657
+ status,
658
+ drawStatus: draw ?? order.drawStatus,
659
+ scheduledAt,
660
+ timeZone: zone,
661
+ cancelled: order.cancelled || status === "Cancelled",
662
+ updated_at: this.iso()
663
+ };
664
+ this.state.orders.update(order.partner_order_id, next);
665
+ this.onWebhook?.(webhook);
666
+ return { order: next, webhook };
667
+ }
668
+ /**
669
+ * Emit `Scheduled` for every order whose `autoSchedule` delay has passed on the mock clock.
670
+ * Runs before each vendor request, on `POST /__admin/tick`, and from the served ticker.
671
+ */
672
+ tick() {
673
+ const plan = this.state.current().autoSchedule;
674
+ if (!plan) return 0;
675
+ let applied = 0;
676
+ for (const { value: order } of this.state.orders.list({ order: "oldest" })) {
677
+ if (order.autoScheduled || order.cancelled || order.status !== ORDER_PLACED) continue;
678
+ if (this.now() < order.createdAtMs + plan.afterMs) continue;
679
+ this.state.orders.update(order.partner_order_id, { ...order, autoScheduled: true });
680
+ this.transition(order.partner_order_id, {
681
+ status: "Scheduled",
682
+ ...order.scheduledAt ? {} : { scheduledAt: order.createdAtMs + (plan.leadMs ?? DAY_MS) }
683
+ });
684
+ applied++;
685
+ }
686
+ return applied;
687
+ }
688
+ orders() {
689
+ return this.state.orders.list({ order: "oldest" }).map((row) => row.value);
690
+ }
691
+ };
692
+
693
+ export {
694
+ document,
695
+ operationIds,
696
+ supportedOperationIds,
697
+ ORDER_STATUSES,
698
+ DRAW_STATUSES,
699
+ isTimeZone,
700
+ zonedParts,
701
+ zonedToEpoch,
702
+ WEBHOOK_PATH,
703
+ AHA_PRESETS,
704
+ createRuntime2 as createRuntime,
705
+ AHA_NAMESPACE,
706
+ verifyAuth,
707
+ apiKeyCredential,
708
+ AhaAPI
709
+ };
710
+ //# sourceMappingURL=chunk-JQVVORIA.js.map