@crvouga/mockingbird-service-junction 1.7.0 → 1.8.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 +19 -1
- package/dist/{chunk-WGRRZGPF.js → chunk-OW7EOZRN.js} +2 -2
- package/dist/{chunk-LUHSOIDO.js → chunk-WDRX5POF.js} +355 -22
- package/dist/chunk-WDRX5POF.js.map +7 -0
- package/dist/cli.js +2 -2
- package/dist/index.js +1 -1
- package/dist/server.js +2 -2
- package/package.json +2 -2
- package/dist/chunk-LUHSOIDO.js.map +0 -7
- /package/dist/{chunk-WGRRZGPF.js.map → chunk-OW7EOZRN.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../core/src/clock.ts", "../../core/src/collection.ts", "../../core/src/control.ts", "../../core/src/credentials.ts", "../../core/src/rng.ts", "../../core/src/faults.ts", "../../../openapi/core/src/refs.ts", "../../../openapi/core/src/types.ts", "../../../openapi/core/src/document.ts", "../../../http/codec/src/form.ts", "../../../http/codec/src/content.ts", "../../core/src/http.ts", "../../core/src/ids.ts", "../../core/src/journal.ts", "../../core/src/metrics.ts", "../../../core/src/timeline.ts", "../../../sqlite/src/default.ts", "../../../sqlite/src/migrate.ts", "../../../sqlite/src/schema.ts", "../../../ui/src/reset.ts", "../../core/src/admin-client.ts", "../../core/src/surface.ts", "../../core/src/admin-ui.ts", "../../../openapi/metadata/src/types.ts", "../../../openapi/metadata/src/read.ts", "../../core/src/service.ts", "../../core/src/validation.ts", "../../core/src/snapshot.ts", "../../core/src/state-view.ts", "../../core/src/version.ts", "../../core/src/webhooks.ts", "../../core/src/runtime.ts", "../src/catalog.ts", "../src/limits.ts", "../src/state.ts", "../src/lab-accounts.ts", "../src/lab-account-presets.ts", "../src/admin.ts", "../src/not-found.ts", "../src/scheduling.ts", "../src/orders.ts", "../src/fixtures.ts", "../src/generated/openapi.ts", "../src/results.ts", "../src/seed-from.ts", "../src/users.ts", "../src/coverage-corpus.ts", "../src/reshape.ts", "../src/prefetch.ts", "../src/corpus-tools.ts", "../src/webhooks.ts", "../src/runtime.ts", "../src/verify.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The single source of time for a service.\n *\n * Every timestamp a mock writes reads from here, so a suite moves time instead of\n * sleeping: appointment windows, result delays and expiries become reachable in\n * milliseconds. A frozen clock also makes timestamps reproducible from a seed.\n */\nexport type ClockState = {\n /** Current epoch milliseconds. */\n now: number\n /** True while time does not advance on its own. */\n frozen: boolean\n /** Milliseconds this clock adds to its underlying source. */\n offsetMs: number\n}\n\nexport type Clock = {\n now(): number\n /** Pin the clock to an exact instant, keeping it frozen if it already was. */\n set(epochMs: number): void\n /** Move the clock forward, or back with a negative delta. */\n advance(deltaMs: number): void\n /** Stop time at the current instant. */\n freeze(): void\n /** Resume from the current instant. */\n unfreeze(): void\n /** Drop back to the underlying source, live. */\n reset(): void\n state(): ClockState\n}\n\n/** A {@link Clock} over `source` (default `Date.now`), live and unfrozen. */\nexport const createClock = (source: () => number = Date.now): Clock => {\n let offsetMs = 0\n let frozenAt: number | undefined\n const now = () => frozenAt ?? source() + offsetMs\n return {\n now,\n set: (epochMs) => {\n if (frozenAt !== undefined) frozenAt = epochMs\n else offsetMs = epochMs - source()\n },\n advance: (deltaMs) => {\n if (frozenAt !== undefined) frozenAt += deltaMs\n else offsetMs += deltaMs\n },\n freeze: () => {\n frozenAt = now()\n },\n unfreeze: () => {\n if (frozenAt === undefined) return\n offsetMs = frozenAt - source()\n frozenAt = undefined\n },\n reset: () => {\n offsetMs = 0\n frozenAt = undefined\n },\n state: () => ({ now: now(), frozen: frozenAt !== undefined, offsetMs }),\n }\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/** Every stored record carries a monotonically increasing sequence for stable ordering. */\nexport type Stored<T> = { seq: number; value: T }\n\nexport type ListRecordsOptions<T> = {\n /** Keep only records passing the predicate. */\n where?: (value: T, seq: number) => boolean\n /** Sort order; default newest first. */\n order?: \"newest\" | \"oldest\"\n}\n\ntype RecordRow = { id: string; seq: number; value: string }\n\n/**\n * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion\n * sequence, never by id lexicographic order, so list semantics stay stable.\n */\nexport class Collection<T> {\n constructor(\n private readonly sqlite: SqliteClient,\n /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */\n readonly namespace: string,\n /** Table name inside the namespace. Stable across resets of the rows themselves. */\n readonly collectionName: string,\n ) {}\n\n private bumpCollectionSeq(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'\",\n )\n .get<{ value: number }>(this.namespace, this.collectionName)\n const next = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, this.collectionName, next)\n return next\n }\n\n nextSequence(): number {\n return this.sqlite.transaction(() => this.bumpCollectionSeq())\n }\n\n get(id: string): T | undefined {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ value: string }>(this.namespace, this.collectionName, id)\n if (!row) return undefined\n return (JSON.parse(row.value) as Stored<T>).value\n }\n\n has(id: string): boolean {\n const row = this.sqlite\n .prepare(\n \"SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ ok: number }>(this.namespace, this.collectionName, id)\n return row !== undefined\n }\n\n /** Insert a new record, assigning it the next sequence number. */\n insert(id: string, value: T): Stored<T> {\n return this.sqlite.transaction(() => {\n const seq = this.bumpCollectionSeq()\n const stored = { seq, value }\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_records (namespace, collection, id, seq, value)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`,\n )\n .run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored))\n return stored\n })\n }\n\n /** Replace an existing record's value, keeping its position. */\n update(id: string, value: T): Stored<T> | undefined {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ seq: number; value: string }>(this.namespace, this.collectionName, id)\n if (!row) return undefined\n const stored = { seq: row.seq, value }\n this.sqlite\n .prepare(\n \"UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .run(JSON.stringify(stored), this.namespace, this.collectionName, id)\n return stored\n })\n }\n\n delete(id: string): boolean {\n const result = this.sqlite\n .prepare(\"DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\")\n .run(this.namespace, this.collectionName, id)\n return result.changes > 0\n }\n\n /** How many records the collection holds, without reading them. */\n count(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .get<{ n: number }>(this.namespace, this.collectionName)\n return Number(row?.n ?? 0)\n }\n\n list(options: ListRecordsOptions<T> = {}): Array<Stored<T> & { id: string }> {\n const rows = this.sqlite\n .prepare(\n \"SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .all<RecordRow>(this.namespace, this.collectionName)\n const out: Array<Stored<T> & { id: string }> = []\n for (const row of rows) {\n const stored = JSON.parse(row.value) as Stored<T>\n if (options.where && !options.where(stored.value, stored.seq)) continue\n out.push({ id: row.id, seq: stored.seq, value: stored.value })\n }\n out.sort((a, b) => (options.order === \"oldest\" ? a.seq - b.seq : b.seq - a.seq))\n return out\n }\n}\n", "import type { Clock } from \"./clock.js\"\nimport type { FaultRegistry, FaultRule } from \"./faults.js\"\nimport type { Journal } from \"./journal.js\"\nimport type { Metrics } from \"./metrics.js\"\n\n/** Unauthenticated readiness probe, served ahead of every vendor auth gate. */\nexport const HEALTH_PATH = \"/health\"\n/** Prefix of every control-plane route; never part of a vendor contract. */\nexport const ADMIN_PREFIX = \"/__admin\"\n/** Carries the admin key, which is separate from any vendor credential. */\nexport const ADMIN_KEY_HEADER = \"x-mockingbird-admin-key\"\n/** Selects the isolated namespace a request reads and writes. */\nexport const NAMESPACE_HEADER = \"x-mockingbird-namespace\"\n\nexport type AdminRequest = {\n request: Request\n url: URL\n /** `:param` segments of the matched route. */\n params: Record<string, string>\n /** Namespace the request targets: `?namespace=`, then the header, then the default. */\n namespace: string\n /** Parsed JSON body, or `undefined` when there is none. */\n body: unknown\n}\n\nexport type AdminRoute = (request: AdminRequest) => Response | Promise<Response>\n\n/**\n * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with\n * `:param` segments \u2014 e.g. `\"POST /orders/:id/transition\"`.\n */\nexport type AdminRoutes = Record<string, AdminRoute>\n\nexport type ControlContext = {\n name: string\n startedAt: number\n wallNow: () => number\n clock: Clock\n faults: FaultRegistry\n metrics: Metrics\n journal: Journal\n defaultNamespace: string\n namespaces(): string[]\n reset(namespace: string | \"*\"): Promise<void>\n timeTravel: {\n checkpoint(\n namespace: string,\n branch: string,\n ): { id: string; branch: string; parent: string | null; at: number; records?: number }\n branch(\n name: string,\n options: { namespace: string; at?: string },\n ): { id: string; branch: string; parent: string | null; at: number }\n checkout(checkpoint: string, options: { namespace: string; branch: string }): void\n retain(namespace: string, checkpoint: string): void\n release(namespace: string, checkpoint: string): boolean\n inspect(namespace: string): {\n branches: Readonly<Record<string, string>>\n checkpoints: readonly { id: string; branch: string; parent: string | null; at: number }[]\n }\n }\n /** Extra fields for `GET /health`, such as the loaded corpus version. */\n describe(): Record<string, unknown>\n routes: AdminRoutes\n adminKey: string | undefined\n /** Expand a named fault preset; enables `POST /faults {\"preset\": \"<name>\"}`. */\n applyPreset?(name: string, namespace: string, overrides: Partial<FaultRule>): FaultRule[]\n}\n\nexport type ControlPlane = {\n /** The control-plane response for `request`, or `undefined` for a vendor request. */\n handle(request: Request): Promise<Response | undefined>\n /**\n * Namespace a vendor request targets, from {@link NAMESPACE_HEADER}. Only admin routes\n * also accept `?namespace=`, so a vendor query parameter of that name can never\n * silently reroute a request.\n */\n namespaceOf(request: Request): string\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n })\n\n/** Admin errors use one documented shape, distinct from any vendor's error body. */\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n}\n\n/** Milliseconds from a number, or a duration like `\"90s\"`, `\"15m\"`, `\"2h\"`, `\"3d\"`. */\nexport const parseDuration = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const match = /^(-?\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim())\n if (!match) return undefined\n return Number(match[1]) * (UNITS[match[2] as string] as number)\n}\n\n/** Epoch milliseconds from a number or an ISO-8601 string. */\nconst parseInstant = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const parsed = Date.parse(value)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nconst matchRoute = (pattern: string, path: string): Record<string, string> | undefined => {\n const want = pattern.split(\"/\").filter(Boolean)\n const have = path.split(\"/\").filter(Boolean)\n if (want.length !== have.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < want.length; i++) {\n const segment = want[i] as string\n const actual = have[i] as string\n if (segment.startsWith(\":\")) params[segment.slice(1)] = decodeURIComponent(actual)\n else if (segment !== actual) return undefined\n }\n return params\n}\n\nconst readJson = async (request: Request): Promise<unknown> => {\n const text = await request.text()\n if (text.trim() === \"\") return undefined\n return JSON.parse(text) as unknown\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nexport const createControlPlane = (context: ControlContext): ControlPlane => {\n // Legacy snapshot ids are opaque aliases to pinned Timeline checkpoints. Timeline remains the\n // only history owner; this map carries no state value and can be removed with the alias.\n const snapshots = new Map<string, { namespace: string; checkpoint: string }>()\n let snapshotCounter = 0\n\n const headerNamespace = (request: Request): string =>\n request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace\n const adminNamespace = (request: Request, url: URL): string =>\n url.searchParams.get(\"namespace\") ?? headerNamespace(request)\n\n const builtin: AdminRoutes = {\n \"GET /\": () =>\n json(200, {\n service: context.name,\n routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort(),\n }),\n\n \"POST /reset\": async ({ url, namespace }) => {\n const target = url.searchParams.get(\"all\") === \"1\" ? \"*\" : namespace\n await context.reset(target)\n return json(200, { status: \"ok\", reset: target === \"*\" ? context.namespaces() : [target] })\n },\n\n \"GET /namespaces\": () =>\n json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),\n\n \"GET /clock\": () => json(200, context.clock.state()),\n \"POST /clock\": ({ body }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n if (body.reset === true) context.clock.reset()\n if (body.set !== undefined) {\n const instant = parseInstant(body.set)\n if (instant === undefined) return adminError(400, \"set: expected epoch ms or ISO-8601\")\n context.clock.set(instant)\n }\n if (body.advance !== undefined) {\n const delta = parseDuration(body.advance)\n if (delta === undefined) return adminError(400, 'advance: expected ms or \"15m\"-style')\n context.clock.advance(delta)\n }\n if (body.freeze === true) context.clock.freeze()\n if (body.freeze === false) context.clock.unfreeze()\n return json(200, context.clock.state())\n },\n\n \"GET /faults\": () => json(200, { faults: context.faults.list() }),\n \"POST /faults\": ({ body, namespace }) => {\n if (isRecord(body) && typeof body.preset === \"string\") {\n if (!context.applyPreset) return adminError(400, `${context.name} has no fault presets`)\n const { preset, ...overrides } = body\n try {\n return json(201, {\n preset,\n rules: context.applyPreset(preset, namespace, overrides as Partial<FaultRule>),\n })\n } catch (error) {\n return adminError(404, error instanceof Error ? error.message : String(error))\n }\n }\n if (\n !isRecord(body) ||\n (typeof body.status !== \"number\" &&\n typeof body.delayMs !== \"number\" &&\n typeof body.latencyMs !== \"number\" &&\n body.drop !== true &&\n typeof body.effect !== \"string\")\n ) {\n return adminError(\n 400,\n \"a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset\",\n )\n }\n const rule = {\n // Scoped to the caller's namespace unless it asks for every one, so one worker's\n // injected failure never lands on another's request.\n namespace,\n ...body,\n id: typeof body.id === \"string\" ? body.id : `fault_${context.faults.list().length + 1}`,\n } as FaultRule\n return json(201, context.faults.add(rule))\n },\n \"DELETE /faults\": ({ url }) => {\n const id = url.searchParams.get(\"id\")\n if (id === null) {\n context.faults.clear()\n return json(200, { status: \"ok\" })\n }\n return context.faults.remove(id)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no fault ${id}`)\n },\n\n \"POST /snapshots\": ({ namespace }) => {\n const point = context.timeTravel.checkpoint(namespace, \"main\")\n context.timeTravel.retain(namespace, point.id)\n snapshotCounter++\n const id = `snap_${snapshotCounter}`\n snapshots.set(id, { namespace, checkpoint: point.id })\n return json(201, { id, namespace, records: point.records ?? 0 })\n },\n \"POST /snapshots/:id/restore\": ({ params, namespace }) => {\n const alias = snapshots.get(params.id as string)\n if (!alias) return adminError(404, `no snapshot ${params.id}`)\n if (alias.namespace !== namespace) {\n return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`)\n }\n context.timeTravel.checkout(alias.checkpoint, { namespace, branch: \"main\" })\n return json(200, { status: \"ok\", id: params.id, namespace })\n },\n \"DELETE /snapshots/:id\": ({ params }) => {\n const id = params.id as string\n const alias = snapshots.get(id)\n if (!alias) return adminError(404, `no snapshot ${id}`)\n snapshots.delete(id)\n context.timeTravel.release(alias.namespace, alias.checkpoint)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /timeline\": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),\n \"POST /checkpoints\": ({ body, namespace }) => {\n const branch = isRecord(body) && typeof body.branch === \"string\" ? body.branch : \"main\"\n try {\n return json(201, context.timeTravel.checkpoint(namespace, branch))\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name\": ({ params, body, namespace }) => {\n const at = isRecord(body) && typeof body.at === \"string\" ? body.at : undefined\n try {\n return json(\n 201,\n context.timeTravel.branch(params.name as string, {\n namespace,\n ...(at !== undefined ? { at } : {}),\n }),\n )\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name/checkout\": ({ params, body, namespace }) => {\n if (!isRecord(body) || typeof body.checkpoint !== \"string\") {\n return adminError(400, 'expected {\"checkpoint\":\"cp_...\"}')\n }\n try {\n context.timeTravel.checkout(body.checkpoint, {\n namespace,\n branch: params.name as string,\n })\n return json(200, { status: \"ok\", branch: params.name, checkpoint: body.checkpoint })\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n\n \"GET /requests\": ({ url, namespace }) => {\n const status = url.searchParams.get(\"status\")\n const since = url.searchParams.get(\"since\")\n const limit = url.searchParams.get(\"limit\")\n const sinceMs =\n since === null ? undefined : parseInstant(/^\\d+$/.test(since) ? Number(since) : since)\n if (since !== null && sinceMs === undefined) {\n return adminError(400, \"since: expected epoch ms or ISO-8601\")\n }\n if (status !== null && !/^\\d{3}$/.test(status))\n return adminError(400, \"status: expected an HTTP status\")\n if (limit !== null && !/^\\d+$/.test(limit)) return adminError(400, \"limit: expected a count\")\n const operationId = url.searchParams.get(\"operationId\")\n const everyNamespace = url.searchParams.get(\"all\") === \"1\"\n return json(200, {\n size: context.journal.size,\n requests: context.journal.list({\n ...(everyNamespace ? {} : { namespace }),\n ...(operationId !== null ? { operationId } : {}),\n ...(status !== null ? { status: Number(status) } : {}),\n ...(sinceMs !== undefined ? { since: sinceMs } : {}),\n ...(limit !== null ? { limit: Number(limit) } : {}),\n }),\n })\n },\n \"DELETE /requests\": ({ url, namespace }) => {\n context.journal.clear(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /metrics\": () => json(200, context.metrics.report()),\n \"DELETE /metrics\": () => {\n context.metrics.reset()\n return json(200, { status: \"ok\" })\n },\n }\n\n const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(\n ([key, handler]) => {\n const space = key.indexOf(\" \")\n return { method: key.slice(0, space), pattern: key.slice(space + 1), handler }\n },\n )\n\n return {\n namespaceOf: headerNamespace,\n async handle(request) {\n const url = new URL(request.url)\n if (url.pathname === HEALTH_PATH && request.method === \"GET\") {\n return json(200, {\n status: \"ok\",\n service: context.name,\n uptimeMs: context.wallNow() - context.startedAt,\n clock: context.clock.state(),\n namespaces: context.namespaces().length,\n adminUi: `${ADMIN_PREFIX}/ui`,\n ...context.describe(),\n })\n }\n if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {\n return undefined\n }\n const path = url.pathname.slice(ADMIN_PREFIX.length) || \"/\"\n // The shell has no data. Panel markup stays on GET /ui/manifest, which is locked.\n const shell = request.method === \"GET\" && (path === \"/ui\" || path === \"/ui/\")\n if (\n !shell &&\n context.adminKey !== undefined &&\n request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey\n ) {\n return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`)\n }\n for (const route of routes) {\n if (route.method !== request.method) continue\n const params = matchRoute(route.pattern, path)\n if (!params) continue\n let body: unknown\n try {\n body = await readJson(request)\n } catch {\n return adminError(400, \"request body is not valid JSON\")\n }\n return route.handler({\n request,\n url,\n params,\n namespace: adminNamespace(request, url),\n body,\n })\n }\n return adminError(\n 404,\n `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`,\n )\n },\n }\n}\n", "/**\n * Reading the vendor credential a request carries.\n *\n * Several vendor SDKs (Stripe, AWS, PostHog, Twilio) cannot add a namespace header, so a\n * runtime can also pick a request's namespace from its credential: a suite maps each\n * worker's API key, token or account SID to a namespace through `PUT /__admin/credentials`.\n * These helpers pull the credential out of the usual carriers.\n */\n\n/** The token after `Bearer `, or `undefined`. */\nexport const bearerToken = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Bearer\\s+(.+)$/i.exec(header.trim())\n return match?.[1]?.trim() || undefined\n}\n\nexport type BasicCredentials = { username: string; password: string }\n\n/** `{ username, password }` from `Authorization: Basic \u2026`, or `undefined`. */\nexport const basicAuth = (request: Request): BasicCredentials | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Basic\\s+(.+)$/i.exec(header.trim())\n if (!match?.[1]) return undefined\n let decoded: string\n try {\n decoded = atob(match[1].trim())\n } catch {\n return undefined\n }\n const colon = decoded.indexOf(\":\")\n if (colon < 0) return { username: decoded, password: \"\" }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) }\n}\n\n/**\n * The access key id of an AWS SigV4-signed request (`Credential=AKID/date/region/service/\u2026`),\n * from the `Authorization` header or a presigned `X-Amz-Credential` query parameter.\n */\nexport const sigV4AccessKeyId = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n const fromHeader = header ? /Credential=([^/,\\s]+)\\//.exec(header)?.[1] : undefined\n if (fromHeader) return fromHeader\n const query = new URL(request.url).searchParams.get(\"X-Amz-Credential\")\n return query ? (query.split(\"/\")[0] ?? undefined) : undefined\n}\n\n/** The credential in any of the common carriers: Bearer, Basic username, SigV4, or `x-api-key`. */\nexport const anyCredential = (request: Request): string | undefined =>\n bearerToken(request) ??\n basicAuth(request)?.username ??\n sigV4AccessKeyId(request) ??\n request.headers.get(\"x-api-key\") ??\n undefined\n\n/** Credential \u2192 namespace mapping behind `PUT /__admin/credentials`. */\nexport type CredentialRegistry = {\n set(credential: string, namespace: string): void\n get(credential: string): string | undefined\n remove(credential: string): boolean\n clear(): void\n entries(): { credential: string; namespace: string }[]\n}\n\nexport const createCredentialRegistry = (): CredentialRegistry => {\n const map = new Map<string, string>()\n return {\n set: (credential, namespace) => {\n map.set(credential, namespace)\n },\n get: (credential) => map.get(credential),\n remove: (credential) => map.delete(credential),\n clear: () => map.clear(),\n entries: () =>\n [...map]\n .map(([credential, namespace]) => ({ credential, namespace }))\n .sort((a, b) => a.credential.localeCompare(b.credential)),\n }\n}\n\n/** A credential shown in admin output: enough to recognise it, never the whole secret. */\nexport const maskCredential = (credential: string): string =>\n credential.length <= 8\n ? `${credential.slice(0, 2)}\u2026`\n : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`\n", "/**\n * Seeded pseudo-random numbers, so anything a mock invents \u2014 ids, jitter, which\n * request a percentage fault hits \u2014 is reproducible from a seed.\n *\n * mulberry32: small, fast, and stable across runtimes, which matters more here\n * than statistical quality.\n */\nexport type Rng = {\n /** Next value in `[0, 1)`. */\n next(): number\n /** Next integer in `[min, max]`. */\n int(min: number, max: number): number\n /** Restart the stream from its seed. */\n reset(): void\n /** Serializable engine state used by deterministic checkpoints. */\n state(): number\n /** Restore a state previously returned by {@link state}. */\n setState(state: number): void\n seed: number\n}\n\n/** Hash an arbitrary string into a 32-bit seed, so callers can seed by name. */\nexport const seedFrom = (value: string): number => {\n let hash = 2166136261\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return hash >>> 0\n}\n\nexport const createRng = (seed: number | string = 0): Rng => {\n const numeric = typeof seed === \"string\" ? seedFrom(seed) : seed >>> 0\n let state = numeric\n const next = () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n return {\n next,\n int: (min, max) => min + Math.floor(next() * (max - min + 1)),\n reset: () => {\n state = numeric\n },\n state: () => state,\n setState: (next) => {\n if (!Number.isSafeInteger(next) || next < 0 || next > 0xffffffff) {\n throw new RangeError(\"rng state must be an unsigned 32-bit integer\")\n }\n state = next >>> 0\n },\n seed: numeric,\n }\n}\n", "import { createRng, type Rng } from \"./rng.js\"\n\n/**\n * A deliberate failure injected in front of an operation.\n *\n * This is how a suite reaches the vendor's failure modes without the vendor: the\n * quota error that only appears when a shared sandbox is full, the 429 that only\n * appears under load, the 5xx that proves a retry path works.\n */\nexport type FaultRule = {\n /** Stable id, so a suite can retire exactly the rule it added. */\n id: string\n /** Fault only this operation. Omit to match every operation. */\n operationId?: string\n /** Fault only this HTTP method, case-insensitive. Omit to match every method. */\n method?: string\n /** Fault only paths starting with this prefix. Omit to match every path. */\n pathPrefix?: string\n /**\n * Fault only this namespace. Omit (or `\"*\"`) to fault every namespace \u2014 which is what\n * an in-process caller usually wants, and what a parallel worker usually does not:\n * rules added through `POST /__admin/faults` default to the calling namespace.\n */\n namespace?: string\n /**\n * Status of the injected response. Omit for a rule that only delays (`delayMs` /\n * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:\n * the request then still reaches the service.\n */\n status?: number\n /** Response body, serialized as JSON. A string is sent as-is. */\n body?: unknown\n headers?: Record<string, string>\n /** Retire the rule after this many faults. Omit to keep it until removed. */\n count?: number\n /** Fault this fraction of matching requests, `0`\u2013`1`. Default `1`. */\n rate?: number\n /** Hold the response back this long, to exercise timeouts. */\n delayMs?: number\n /** Alias of `delayMs`. */\n latencyMs?: number\n /**\n * Drop the connection instead of answering: an in-process `fetch` rejects with a\n * `TypeError`, and a served mock destroys the socket. Models \"unknown outcome\" failures.\n */\n drop?: boolean\n /**\n * A named service behaviour to switch on for the matching request instead of (or\n * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services\n * read it with `faultEffects(request)`.\n */\n effect?: string\n /** Parameters for `effect`. */\n params?: Record<string, unknown>\n /** From the preset this rule was expanded from, if any. */\n preset?: string\n}\n\n/** A fault that fired for one request. */\nexport type FaultHit = {\n id: string\n /** The injected response; absent when the rule only delays, drops, or sets an effect. */\n response?: Response\n drop?: boolean\n effect?: { name: string; params: Record<string, unknown> }\n}\n\n/**\n * A named, documented fault a suite switches on by name\n * (`POST /__admin/faults {\"preset\": \"rate_limited\"}`): one or more rules, and optionally a\n * webhook delivery fault.\n */\nexport type FaultPreset = {\n description: string\n rules?: Omit<FaultRule, \"id\">[]\n webhook?: { mode: \"duplicate\" | \"reorder\" | \"drop\"; count?: number }\n}\n\n/**\n * Body of `GET /__admin/faults/presets`.\n * `presets` is a list of named presets. A record keyed by name is not this type:\n * the admin page maps the list.\n */\nexport type FaultPresetList = {\n presets: readonly { name: string }[]\n}\n\ntype _AssertFaultPresetList<T extends FaultPresetList> = T\n// @ts-expect-error presets is a list of { name }, not a record keyed by name\ntype _RecordIsNotAPresetList = _AssertFaultPresetList<{ presets: Record<string, { name: string }> }>\n\n/** What a request looks like to the fault matcher. */\nexport type FaultCandidate = {\n operationId: string | undefined\n method: string\n path: string\n namespace: string\n}\n\nexport type FaultRegistry = {\n add(rule: FaultRule): FaultRule\n list(): (FaultRule & { remaining: number | null; hits: number })[]\n remove(id: string): boolean\n clear(): void\n /**\n * Every fault this request should get, in rule order, stopping at the first that answers\n * or drops (effect-only and delay-only rules let later rules match too). Consumes one of\n * each matching rule's remaining uses.\n */\n take(candidate: FaultCandidate): Promise<FaultHit[]>\n}\n\ntype Entry = { rule: FaultRule; remaining: number | null; hits: number }\n\nconst matches = (rule: FaultRule, candidate: FaultCandidate): boolean => {\n if (\n rule.namespace !== undefined &&\n rule.namespace !== \"*\" &&\n rule.namespace !== candidate.namespace\n ) {\n return false\n }\n if (rule.operationId !== undefined && rule.operationId !== candidate.operationId) return false\n if (rule.method !== undefined && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {\n return false\n }\n if (rule.pathPrefix !== undefined && !candidate.path.startsWith(rule.pathPrefix)) return false\n return true\n}\n\nconst faultResponse = (rule: FaultRule): Response => {\n const status = rule.status ?? 500\n const headers = { \"content-type\": \"application/json\", ...rule.headers }\n if (typeof rule.body === \"string\") return new Response(rule.body, { status, headers })\n if (rule.body === null) return new Response(null, { status, headers: rule.headers ?? {} })\n const body = rule.body === undefined ? { detail: \"Injected by Mockingbird\" } : rule.body\n return new Response(JSON.stringify(body), { status, headers })\n}\n\n/**\n * Rules are matched in the order they were added, so a narrow rule added first\n * wins over a later catch-all. `rate` draws from `rng`, which is seeded, so a\n * partial-failure run replays identically.\n */\nexport const createFaultRegistry = (\n rng: Rng = createRng(0),\n sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n): FaultRegistry => {\n const entries: Entry[] = []\n return {\n add(rule) {\n const existing = entries.findIndex((e) => e.rule.id === rule.id)\n const entry: Entry = { rule, remaining: rule.count ?? null, hits: 0 }\n if (existing >= 0) entries[existing] = entry\n else entries.push(entry)\n return rule\n },\n list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),\n remove(id) {\n const index = entries.findIndex((e) => e.rule.id === id)\n if (index < 0) return false\n entries.splice(index, 1)\n return true\n },\n clear() {\n entries.length = 0\n },\n async take(candidate) {\n const hits: FaultHit[] = []\n for (const entry of entries) {\n if (entry.remaining === 0) continue\n if (!matches(entry.rule, candidate)) continue\n const rate = entry.rule.rate ?? 1\n // Draw even when the rule always fires, so a seeded stream stays aligned.\n if (rng.next() >= rate) continue\n entry.hits++\n if (entry.remaining !== null) entry.remaining--\n const delay = entry.rule.delayMs ?? entry.rule.latencyMs\n if (delay !== undefined && delay > 0) {\n await sleep(delay)\n }\n const hit: FaultHit = { id: entry.rule.id }\n if (entry.rule.effect !== undefined) {\n hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} }\n }\n if (entry.rule.drop === true) hit.drop = true\n else if (entry.rule.status !== undefined) hit.response = faultResponse(entry.rule)\n hits.push(hit)\n if (hit.drop || hit.response) break\n }\n return hits\n },\n }\n}\n", "import type { OpenAPIDocument, ReferenceObject } from \"./types.js\"\n\nexport class OpenAPIReferenceError extends Error {\n constructor(readonly ref: string) {\n super(`unresolvable $ref: ${ref}`)\n this.name = \"OpenAPIReferenceError\"\n }\n}\n\nconst unescapePointer = (segment: string) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n\n/** True when `value` is a `{ $ref }` object. */\nexport const isReference = (value: unknown): value is ReferenceObject =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { $ref?: unknown }).$ref === \"string\"\n\n/** Resolve a local JSON pointer reference (`#/components/schemas/customer`) inside `document`. */\nexport const resolveRef = (document: OpenAPIDocument, ref: string): unknown => {\n if (!ref.startsWith(\"#/\")) throw new OpenAPIReferenceError(ref)\n let cursor: unknown = document\n for (const raw of ref.slice(2).split(\"/\")) {\n const segment = unescapePointer(raw)\n if (typeof cursor !== \"object\" || cursor === null || !(segment in cursor)) {\n throw new OpenAPIReferenceError(ref)\n }\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n if (cursor === undefined) throw new OpenAPIReferenceError(ref)\n return cursor\n}\n\n/**\n * Follow `$ref` chains until a concrete object is reached. Guards against cycles.\n * Sibling keys next to `$ref` are ignored, as in OpenAPI 3.0/3.1 for non-schema objects.\n */\nexport const deref = <T>(document: OpenAPIDocument, value: T | ReferenceObject): T => {\n let current: unknown = value\n const seen = new Set<string>()\n while (isReference(current)) {\n if (seen.has(current.$ref)) throw new OpenAPIReferenceError(`${current.$ref} (cycle)`)\n seen.add(current.$ref)\n current = resolveRef(document, current.$ref)\n }\n return current as T\n}\n\n/** The component name at the end of a `#/components/<kind>/<name>` reference, if any. */\nexport const componentNameOf = (ref: string): string | undefined => {\n const match = /^#\\/components\\/[^/]+\\/(.+)$/.exec(ref)\n return match?.[1] === undefined ? undefined : unescapePointer(match[1])\n}\n", "/**\n * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.\n * Unknown keys (including `x-*` extensions) are preserved on every object.\n */\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }\n\nexport type ReferenceObject = { $ref: string; description?: string; summary?: string }\n\nexport type SchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\"\n\nexport type SchemaObject = {\n $ref?: string\n type?: SchemaType | SchemaType[]\n title?: string\n description?: string\n format?: string\n enum?: JsonValue[]\n const?: JsonValue\n default?: JsonValue\n example?: JsonValue\n examples?: JsonValue[]\n nullable?: boolean\n deprecated?: boolean\n readOnly?: boolean\n writeOnly?: boolean\n minimum?: number\n maximum?: number\n exclusiveMinimum?: number\n exclusiveMaximum?: number\n multipleOf?: number\n minLength?: number\n maxLength?: number\n pattern?: string\n minItems?: number\n maxItems?: number\n uniqueItems?: boolean\n items?: SchemaObject\n prefixItems?: SchemaObject[]\n minProperties?: number\n maxProperties?: number\n required?: string[]\n properties?: Record<string, SchemaObject>\n additionalProperties?: boolean | SchemaObject\n propertyNames?: SchemaObject\n oneOf?: SchemaObject[]\n anyOf?: SchemaObject[]\n allOf?: SchemaObject[]\n not?: SchemaObject\n discriminator?: { propertyName: string; mapping?: Record<string, string> }\n [extension: `x-${string}`]: unknown\n}\n\nexport type ParameterLocation = \"path\" | \"query\" | \"header\" | \"cookie\"\n\nexport type ParameterObject = {\n name: string\n in: ParameterLocation\n description?: string\n required?: boolean\n deprecated?: boolean\n style?: string\n explode?: boolean\n schema?: SchemaObject\n content?: Record<string, MediaTypeObject>\n example?: JsonValue\n [extension: `x-${string}`]: unknown\n}\n\nexport type MediaTypeObject = {\n schema?: SchemaObject\n example?: JsonValue\n examples?: Record<string, unknown>\n encoding?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type RequestBodyObject = {\n description?: string\n required?: boolean\n content: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type HeaderObject = {\n description?: string\n required?: boolean\n schema?: SchemaObject\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponseObject = {\n description: string\n headers?: Record<string, HeaderObject | ReferenceObject>\n content?: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponsesObject = Record<string, ResponseObject | ReferenceObject>\n\nexport type SecurityRequirementObject = Record<string, string[]>\n\nexport type OperationObject = {\n operationId?: string\n summary?: string\n description?: string\n tags?: string[]\n deprecated?: boolean\n parameters?: Array<ParameterObject | ReferenceObject>\n requestBody?: RequestBodyObject | ReferenceObject\n responses: ResponsesObject\n security?: SecurityRequirementObject[]\n [extension: `x-${string}`]: unknown\n}\n\nexport const HTTP_METHODS = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nexport type PathItemObject = {\n summary?: string\n description?: string\n parameters?: Array<ParameterObject | ReferenceObject>\n [extension: `x-${string}`]: unknown\n} & Partial<Record<HttpMethod, OperationObject>>\n\nexport type SecuritySchemeObject = {\n type: \"apiKey\" | \"http\" | \"oauth2\" | \"openIdConnect\" | \"mutualTLS\"\n description?: string\n name?: string\n in?: ParameterLocation\n scheme?: string\n bearerFormat?: string\n flows?: Record<string, unknown>\n openIdConnectUrl?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type ComponentsObject = {\n schemas?: Record<string, SchemaObject>\n responses?: Record<string, ResponseObject>\n parameters?: Record<string, ParameterObject>\n requestBodies?: Record<string, RequestBodyObject>\n headers?: Record<string, HeaderObject>\n securitySchemes?: Record<string, SecuritySchemeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ServerObject = {\n url: string\n description?: string\n variables?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type InfoObject = {\n title: string\n version: string\n description?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type OpenAPIDocument = {\n openapi: string\n info: InfoObject\n servers?: ServerObject[]\n paths: Record<string, PathItemObject>\n components?: ComponentsObject\n security?: SecurityRequirementObject[]\n tags?: Array<{ name: string; description?: string }>\n [extension: `x-${string}`]: unknown\n}\n\n/** One concrete HTTP operation discovered in a document. */\nexport type Operation = {\n operationId: string\n method: HttpMethod\n /** OpenAPI path template, e.g. `/v1/customers/{customer}`. */\n path: string\n operation: OperationObject\n /** Path-level parameters merged with operation-level ones (operation wins), `$ref`s resolved. */\n parameters: ParameterObject[]\n requestBody: RequestBodyObject | undefined\n responses: Record<string, ResponseObject>\n}\n", "import { deref, isReference, resolveRef } from \"./refs.js\"\nimport {\n HTTP_METHODS,\n type HttpMethod,\n type OpenAPIDocument,\n type Operation,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n} from \"./types.js\"\n\nexport class OpenAPIDocumentError extends Error {\n constructor(readonly issues: string[]) {\n super(`invalid OpenAPI document:\\n${issues.map((issue) => ` - ${issue}`).join(\"\\n\")}`)\n this.name = \"OpenAPIDocumentError\"\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * Accept an already-parsed JSON/YAML value and return it typed as an {@link OpenAPIDocument}.\n * Performs the structural checks Mockingbird relies on (see {@link validateOpenAPIDocument}) and\n * throws {@link OpenAPIDocumentError} listing every problem.\n */\nexport const parseOpenAPIDocument = (value: unknown): OpenAPIDocument => {\n const issues: string[] = []\n if (!isRecord(value)) throw new OpenAPIDocumentError([\"document must be an object\"])\n if (typeof value.openapi !== \"string\" || !/^3\\.[01]\\./.test(value.openapi)) {\n issues.push(\n `openapi must be a 3.0.x or 3.1.x version string, got ${JSON.stringify(value.openapi)}`,\n )\n }\n if (\n !isRecord(value.info) ||\n typeof value.info.title !== \"string\" ||\n typeof value.info.version !== \"string\"\n ) {\n issues.push(\"info.title and info.version are required strings\")\n }\n if (!isRecord(value.paths)) issues.push(\"paths must be an object\")\n if (issues.length > 0) throw new OpenAPIDocumentError(issues)\n const document = value as unknown as OpenAPIDocument\n const problems = validateOpenAPIDocument(document)\n if (problems.length > 0) throw new OpenAPIDocumentError(problems)\n return document\n}\n\nconst walkRefs = (\n document: OpenAPIDocument,\n node: unknown,\n at: string,\n issues: string[],\n seen: Set<unknown>,\n) => {\n if (typeof node !== \"object\" || node === null || seen.has(node)) return\n seen.add(node)\n if (isReference(node)) {\n try {\n resolveRef(document, node.$ref)\n } catch {\n issues.push(`${at}: unresolvable $ref ${node.$ref}`)\n }\n }\n for (const [key, child] of Object.entries(node))\n walkRefs(document, child, `${at}/${key}`, issues, seen)\n}\n\nconst templateParams = (path: string) =>\n [...path.matchAll(/\\{([^}]+)\\}/g)].map((m) => m[1] as string)\n\n/**\n * Mockingbird's document rules:\n * - every operation has a unique `operationId`\n * - every `$ref` resolves\n * - every `{param}` in a path template has a matching required path parameter\n * - every path parameter appears in the template\n */\nexport const validateOpenAPIDocument = (document: OpenAPIDocument): string[] => {\n const issues: string[] = []\n walkRefs(document, document, \"#\", issues, new Set())\n if (issues.length > 0) return issues\n const seenIds = new Map<string, string>()\n for (const [path, item] of Object.entries(document.paths)) {\n if (!isRecord(item)) {\n issues.push(`paths.${path}: must be an object`)\n continue\n }\n const inTemplate = new Set(templateParams(path))\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation === undefined) continue\n const label = `${method.toUpperCase()} ${path}`\n if (typeof operation.operationId !== \"string\" || operation.operationId.length === 0) {\n issues.push(`${label}: operationId is required`)\n continue\n }\n const previous = seenIds.get(operation.operationId)\n if (previous !== undefined)\n issues.push(`${label}: duplicate operationId ${operation.operationId} (also ${previous})`)\n seenIds.set(operation.operationId, label)\n if (!isRecord(operation.responses) || Object.keys(operation.responses).length === 0) {\n issues.push(`${label}: responses must declare at least one status`)\n }\n const parameters = mergeParameters(document, item, operation.parameters)\n const declared = new Set(parameters.filter((p) => p.in === \"path\").map((p) => p.name))\n for (const name of inTemplate) {\n if (!declared.has(name)) issues.push(`${label}: path parameter {${name}} is not declared`)\n }\n for (const parameter of parameters) {\n if (parameter.in === \"path\") {\n if (!inTemplate.has(parameter.name))\n issues.push(`${label}: path parameter ${parameter.name} is not in the template`)\n if (parameter.required !== true)\n issues.push(`${label}: path parameter ${parameter.name} must be required`)\n }\n }\n }\n }\n return issues\n}\n\nconst mergeParameters = (\n document: OpenAPIDocument,\n item: PathItemObject,\n own: PathItemObject[\"parameters\"],\n): ParameterObject[] => {\n const merged = new Map<string, ParameterObject>()\n for (const raw of item.parameters ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n for (const raw of own ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n return [...merged.values()]\n}\n\n/** Enumerate every operation in the document in path, then method order. */\nexport const listOperations = (document: OpenAPIDocument): Operation[] => {\n const operations: Operation[] = []\n for (const [path, item] of Object.entries(document.paths)) {\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation?.operationId === undefined) continue\n const responses: Record<string, ResponseObject> = {}\n for (const [status, response] of Object.entries(operation.responses)) {\n responses[status] = deref<ResponseObject>(document, response)\n }\n operations.push({\n operationId: operation.operationId,\n method,\n path,\n operation,\n parameters: mergeParameters(document, item, operation.parameters),\n requestBody:\n operation.requestBody === undefined\n ? undefined\n : deref<RequestBodyObject>(document, operation.requestBody),\n responses,\n })\n }\n }\n return operations\n}\n\n/** Find one operation by id. */\nexport const findOperation = (\n document: OpenAPIDocument,\n operationId: string,\n): Operation | undefined =>\n listOperations(document).find((operation) => operation.operationId === operationId)\n\n/** Parameter names inside a path template, in order. */\nexport const pathTemplateParameters = templateParams\n\n/** Substitute `{name}` placeholders. Values are percent-encoded as path segments. */\nexport const expandPathTemplate = (template: string, values: Record<string, string>): string =>\n template.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = values[name]\n if (value === undefined) throw new RangeError(`missing path parameter ${name}`)\n return encodeURIComponent(value)\n })\n\n/** The response object matching an HTTP status: exact match, then `2XX`-style range, then `default`. */\nexport const responseForStatus = (\n responses: Record<string, ResponseObject>,\n status: number,\n): ResponseObject | undefined =>\n responses[String(status)] ?? responses[`${Math.floor(status / 100)}XX`] ?? responses.default\n\nexport type { HttpMethod }\n", "/**\n * Rails/PHP/Stripe-style bracket notation for `application/x-www-form-urlencoded` bodies and\n * query strings:\n *\n * address[city]=Paris -> { address: { city: \"Paris\" } }\n * items[0][name]=a -> { items: [{ name: \"a\" }] }\n * tags[]=x&tags[]=y -> { tags: [\"x\", \"y\"] }\n * metadata[k]=v -> { metadata: { k: \"v\" } }\n *\n * Decoding yields only strings, arrays and plain objects \u2014 coercion is the caller's concern,\n * exactly like a real HTTP server.\n */\n\nexport type FormValue = string | FormValue[] | { [key: string]: FormValue }\n\nexport type FormObject = { [key: string]: FormValue }\n\nconst encodeComponent = (value: string) =>\n encodeURIComponent(value).replace(\n /[!'()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n\nconst flatten = (prefix: string, value: unknown, out: Array<[string, string]>) => {\n if (value === undefined) return\n if (value === null) {\n out.push([prefix, \"\"])\n return\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n value.forEach((item, index) => {\n flatten(`${prefix}[${index}]`, item, out)\n })\n return\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n for (const [key, item] of entries) flatten(`${prefix}[${key}]`, item, out)\n return\n }\n out.push([prefix, String(value)])\n}\n\n/**\n * Encode a JSON-like value as bracket-notation pairs. Nested arrays use explicit indices\n * (`a[0]`), which every bracket parser (including Stripe's) accepts; empty arrays/objects\n * encode as an empty string, matching how Stripe unsets fields.\n */\nexport const encodeFormPairs = (value: Record<string, unknown>): Array<[string, string]> => {\n const out: Array<[string, string]> = []\n for (const [key, item] of Object.entries(value)) flatten(key, item, out)\n return out\n}\n\n/** Encode to a full `application/x-www-form-urlencoded` string. */\nexport const encodeForm = (value: Record<string, unknown>): string =>\n encodeFormPairs(value)\n .map(([k, v]) => `${encodeComponent(k)}=${encodeComponent(v)}`)\n .join(\"&\")\n\nconst parsePath = (rawKey: string): string[] => {\n const open = rawKey.indexOf(\"[\")\n if (open === -1) return [rawKey]\n const path = [rawKey.slice(0, open)]\n const rest = rawKey.slice(open)\n const pattern = /\\[([^\\]]*)\\]/g\n let match: RegExpExecArray | null = pattern.exec(rest)\n let consumed = 0\n while (match !== null) {\n if (match.index !== consumed) return [rawKey]\n path.push(match[1] ?? \"\")\n consumed = match.index + match[0].length\n match = pattern.exec(rest)\n }\n if (consumed !== rest.length) return [rawKey]\n return path\n}\n\nconst isIndex = (segment: string) => /^(0|[1-9][0-9]*)$/.test(segment)\n\n/**\n * Write an own property. `__proto__` is the one key with an inherited setter, so it needs\n * `defineProperty`; every other key shadows its inherited namesake by plain assignment.\n */\nconst put = (target: object, key: string | number, value: FormValue): void => {\n if (key === \"__proto__\") {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n })\n return\n }\n ;(target as Record<string | number, FormValue>)[key] = value\n}\n\nconst assign = (target: FormObject, path: string[], value: string) => {\n let cursor: FormValue = target\n for (let i = 0; i < path.length; i++) {\n const segment = path[i] as string\n const last = i === path.length - 1\n if (Array.isArray(cursor)) {\n const index: number | undefined =\n segment === \"\" ? cursor.length : isIndex(segment) ? Number(segment) : undefined\n if (index === undefined) return\n if (last) {\n put(cursor, index, value)\n return\n }\n const next: FormValue | undefined = Object.hasOwn(cursor, index)\n ? (cursor as Record<number, FormValue>)[index]\n : undefined\n if (next === undefined || typeof next === \"string\") {\n const created: FormValue = path[i + 1] === \"\" || isIndex(path[i + 1] as string) ? [] : {}\n put(cursor, index, created)\n cursor = created\n } else {\n cursor = next\n }\n continue\n }\n if (typeof cursor === \"string\") return\n if (last) {\n put(cursor, segment, value)\n return\n }\n const nextSegment = path[i + 1] as string\n const existing: FormValue | undefined = Object.hasOwn(cursor, segment)\n ? (cursor as Record<string, FormValue>)[segment]\n : undefined\n if (existing === undefined || typeof existing === \"string\") {\n const created: FormValue = nextSegment === \"\" || isIndex(nextSegment) ? [] : {}\n put(cursor, segment, created)\n cursor = created\n } else {\n cursor = existing\n }\n }\n}\n\n/** Decode `key=value&...` pairs (already percent-decoded) into a nested object. */\nexport const decodeFormPairs = (pairs: Iterable<[string, string]>): FormObject => {\n const out: FormObject = {}\n for (const [rawKey, value] of pairs) assign(out, parsePath(rawKey), value)\n return densify(out) as FormObject\n}\n\n/** Sparse arrays (`a[2]=x` without `a[0]`) become dense in bracket parsers. */\nconst densify = (value: FormValue): FormValue => {\n if (typeof value === \"string\") return value\n if (Array.isArray(value)) return value.filter((item) => item !== undefined).map(densify)\n const out: FormObject = {}\n for (const [key, item] of Object.entries(value)) put(out, key, densify(item))\n return out\n}\n\n/** Decode an `application/x-www-form-urlencoded` body or a query string (with or without `?`). */\nexport const decodeForm = (text: string): FormObject => {\n const source = text.startsWith(\"?\") ? text.slice(1) : text\n return decodeFormPairs(new URLSearchParams(source).entries())\n}\n", "import { decodeForm, encodeForm } from \"./form.js\"\n\nexport const JSON_MEDIA_TYPE = \"application/json\"\nexport const FORM_MEDIA_TYPE = \"application/x-www-form-urlencoded\"\n\n/** The essence of a `Content-Type` header: lower-cased media type without parameters. */\nexport const mediaTypeOf = (contentType: string | null | undefined): string | undefined => {\n if (!contentType) return undefined\n const essence = contentType.split(\";\")[0]?.trim().toLowerCase()\n return essence ? essence : undefined\n}\n\nconst isJsonMediaType = (mediaType: string) =>\n mediaType === JSON_MEDIA_TYPE || mediaType.endsWith(\"+json\") || mediaType === \"text/json\"\n\nexport type DecodedBody =\n | { kind: \"empty\" }\n | { kind: \"json\"; value: unknown }\n | { kind: \"form\"; value: Record<string, unknown> }\n | { kind: \"text\"; value: string }\n | { kind: \"bytes\"; value: Uint8Array }\n | { kind: \"invalid\"; mediaType: string; text: string; error: string }\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: false })\n\n/**\n * Decode raw bytes according to a `Content-Type`. Never throws: malformed payloads come back as\n * `{ kind: \"invalid\" }` so callers (mock servers, the differential runner) can respond like a real\n * server would instead of crashing.\n */\nexport const decodeBody = (\n contentType: string | null | undefined,\n bytes: Uint8Array,\n): DecodedBody => {\n if (bytes.byteLength === 0) return { kind: \"empty\" }\n const mediaType = mediaTypeOf(contentType)\n if (mediaType === undefined) return { kind: \"bytes\", value: bytes }\n if (isJsonMediaType(mediaType)) {\n const text = utf8.decode(bytes)\n try {\n return { kind: \"json\", value: JSON.parse(text) }\n } catch (error) {\n return {\n kind: \"invalid\",\n mediaType,\n text,\n error: error instanceof Error ? error.message : String(error),\n }\n }\n }\n if (mediaType === FORM_MEDIA_TYPE) {\n return { kind: \"form\", value: decodeForm(utf8.decode(bytes)) }\n }\n if (mediaType.startsWith(\"text/\")) return { kind: \"text\", value: utf8.decode(bytes) }\n return { kind: \"bytes\", value: bytes }\n}\n\n/** Read and decode a Request/Response body. */\nexport const readBody = async (message: Request | Response): Promise<DecodedBody> => {\n const bytes = new Uint8Array(await message.arrayBuffer())\n return decodeBody(message.headers.get(\"content-type\"), bytes)\n}\n\nexport type EncodedBody = {\n contentType: string\n body: string\n}\n\n/** Encode a JSON-like value for the given media type. Throws for unsupported media types. */\nexport const encodeBody = (mediaType: string, value: unknown): EncodedBody => {\n const essence = mediaTypeOf(mediaType) ?? mediaType\n if (isJsonMediaType(essence)) return { contentType: essence, body: JSON.stringify(value) }\n if (essence === FORM_MEDIA_TYPE) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${FORM_MEDIA_TYPE} bodies must be objects`)\n }\n return { contentType: essence, body: encodeForm(value as Record<string, unknown>) }\n }\n if (essence.startsWith(\"text/\")) return { contentType: essence, body: String(value) }\n throw new TypeError(`unsupported request media type: ${mediaType}`)\n}\n", "import { JSON_MEDIA_TYPE } from \"@crvouga/mockingbird-http-codec\"\n\n/** JSON response with a normalised content type. */\nexport const jsonRes = (\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": JSON_MEDIA_TYPE, ...headers },\n })\n\n/** Thrown by handlers to produce a provider-shaped error response via `onError`. */\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly body: unknown,\n readonly headers: Record<string, string> = {},\n ) {\n super(`HTTP ${status}`)\n this.name = \"HttpError\"\n }\n\n toResponse(): Response {\n const contentType = this.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (contentType === \"text/plain\") {\n return new Response(String(this.body), {\n status: this.status,\n headers: this.headers,\n })\n }\n return jsonRes(this.status, this.body, this.headers)\n }\n}\n\nexport type FieldResult<T> = { ok: true; value: T } | { ok: false; reason: string }\n\nconst ok = <T>(value: T): FieldResult<T> => ({ ok: true, value })\nconst fail = <T>(reason: string): FieldResult<T> => ({ ok: false, reason })\n\n/** Form bodies decode to strings; these coerce the way HTTP servers do, reporting why not. */\nexport const coerce = {\n string(value: unknown): FieldResult<string> {\n return typeof value === \"string\" ? ok(value) : fail(\"expected a string\")\n },\n integer(value: unknown): FieldResult<number> {\n if (typeof value === \"number\" && Number.isInteger(value)) return ok(value)\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n const parsed = Number(value)\n return Number.isSafeInteger(parsed) ? ok(parsed) : fail(\"integer out of range\")\n }\n return fail(\"expected an integer\")\n },\n boolean(value: unknown): FieldResult<boolean> {\n if (typeof value === \"boolean\") return ok(value)\n if (value === \"true\" || value === \"1\") return ok(true)\n if (value === \"false\" || value === \"0\") return ok(false)\n return fail(\"expected a boolean\")\n },\n enumeration<T extends string>(value: unknown, allowed: readonly T[]): FieldResult<T> {\n const match = allowed.find((candidate) => candidate === value)\n return match === undefined ? fail(`expected one of ${allowed.join(\", \")}`) : ok(match)\n },\n /** Flat string-to-string map, the shape of Stripe-style `metadata`. */\n stringMap(value: unknown): FieldResult<Record<string, string>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n return fail(\"expected an object\")\n const out: Record<string, string> = {}\n for (const [key, item] of Object.entries(value)) {\n if (typeof item !== \"string\") return fail(`expected a string at ${key}`)\n out[key] = item\n }\n return ok(out)\n },\n}\n\n/** Count Unicode code points, the way JSON Schema and most APIs measure string length. */\nexport const codePointLength = (value: string) => [...value].length\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\n/** FNV-1a over a string, mixed once more so consecutive counters look unrelated. */\nconst mix = (input: string): number => {\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n hash ^= hash >>> 16\n hash = Math.imul(hash, 0x85ebca6b) >>> 0\n hash ^= hash >>> 13\n return hash >>> 0\n}\n\n/** Deterministic, opaque-looking alphanumeric token of `length` characters derived from `input`. */\nexport const opaqueToken = (input: string, length: number): string => {\n let out = \"\"\n let round = 0\n while (out.length < length) {\n let hash = mix(`${input}:${round++}`)\n for (let i = 0; i < 5 && out.length < length; i++) {\n out += ALPHABET.charAt(hash % ALPHABET.length)\n hash = Math.floor(hash / ALPHABET.length)\n }\n }\n return out\n}\n\n/**\n * Sequential id source persisted in SQLite. Ids are deterministic for a given\n * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.\n */\nexport class IdSequence {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly salt = \"mockingbird\",\n ) {}\n\n next(prefix: string, length = 14): string {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'\",\n )\n .get<{ value: number }>(this.namespace, prefix)\n const value = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, prefix, value)\n return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`\n })\n }\n}\n", "import type { RequestLog } from \"./metrics.js\"\nimport type { BodyIssue } from \"./validation.js\"\n\n/** One journal entry: a request log stamped with when (on the mock clock) it was handled. */\nexport type JournalEntry = RequestLog & { at: string }\n\nexport type JournalQuery = {\n /** Only this namespace. Omit for every namespace, oldest first across all of them. */\n namespace?: string\n operationId?: string\n status?: number\n /** Only entries at or after this instant (epoch ms). */\n since?: number\n /** At most this many, the most recent kept. */\n limit?: number\n}\n\nexport type Journal = {\n readonly size: number\n record(entry: JournalEntry): void\n list(query?: JournalQuery): JournalEntry[]\n /** Forget one namespace's entries, or every namespace's. */\n clear(namespace?: string): void\n}\n\n/** Default number of entries each namespace keeps. */\nexport const DEFAULT_JOURNAL_SIZE = 1000\n\n/**\n * The last `size` requests per namespace, in a ring buffer: what the mock actually saw,\n * so a test can prove a request arrived (or never did) without reading logs.\n */\nexport const createJournal = (size: number = DEFAULT_JOURNAL_SIZE): Journal => {\n const capacity = Math.max(0, Math.floor(size))\n const rings = new Map<string, { entries: JournalEntry[]; next: number }>()\n let sequence = 0\n const order = new WeakMap<JournalEntry, number>()\n const inOrder = (ring: { entries: JournalEntry[]; next: number }): JournalEntry[] =>\n ring.entries.length < capacity\n ? ring.entries\n : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)]\n return {\n size: capacity,\n record(entry) {\n if (capacity === 0) return\n order.set(entry, sequence++)\n let ring = rings.get(entry.namespace)\n if (!ring) {\n ring = { entries: [], next: 0 }\n rings.set(entry.namespace, ring)\n }\n if (ring.entries.length < capacity) ring.entries.push(entry)\n else {\n ring.entries[ring.next] = entry\n ring.next = (ring.next + 1) % capacity\n }\n },\n list(query = {}) {\n const source =\n query.namespace !== undefined\n ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 })\n : [...rings.values()]\n .flatMap(inOrder)\n .sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))\n const matched = source.filter(\n (entry) =>\n (query.operationId === undefined || entry.operationId === query.operationId) &&\n (query.status === undefined || entry.status === query.status) &&\n (query.since === undefined || Date.parse(entry.at) >= query.since),\n )\n return query.limit !== undefined ? matched.slice(-Math.max(0, query.limit)) : matched\n },\n clear(namespace) {\n if (namespace === undefined) rings.clear()\n else rings.delete(namespace)\n },\n }\n}\n\n/** What a service knows about a request that the runtime cannot see from outside. */\nexport type ResponseNotes = {\n /** Resource ids the handler touched, e.g. `{ userId, orderId }`. */\n ids?: Record<string, string>\n /** Set when the handler created a resource the request referred to but did not exist. */\n adopted?: boolean\n /** The body validation issues behind a rejection; the runtime logs them, never the body. */\n issues?: BodyIssue[]\n}\n\nconst notes = new WeakMap<Response, ResponseNotes>()\n\n/**\n * Attach notes to a response for the request journal and structured log. They travel\n * beside the response, never in it, so nothing the vendor would not send reaches a client.\n */\nexport const annotateResponse = (response: Response, extra: ResponseNotes): Response => {\n const existing = notes.get(response)\n notes.set(response, {\n ...existing,\n ...extra,\n ...(existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}),\n })\n return response\n}\n\nexport const responseNotes = (response: Response): ResponseNotes | undefined => notes.get(response)\n", "import type { BodyIssue } from \"./validation.js\"\n\n/**\n * What the mock received from a request it rejected, so a 4xx can be attributed after the\n * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.\n */\nexport type RejectedRequest = {\n /** The raw `content-type` header, or `null` when the request sent none. */\n contentType: string | null\n /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */\n bodyBytes: number | null\n /** The raw `transfer-encoding` header (`chunked`), or `null`. */\n transferEncoding: string | null\n}\n\n/** One handled request, as the structured log sees it. */\nexport type RequestLog = {\n service: string\n namespace: string\n operationId: string | undefined\n method: string\n path: string\n status: number\n durationMs: number\n /** True when the path matched no operation in the contract. */\n unmatched: boolean\n /** Set when a fault rule produced the response. */\n faultId?: string\n /** Resource ids the handler touched (`userId`, `orderId`, \u2026), when the service reports them. */\n ids?: Record<string, string>\n /** Set when the service created a resource the request referred to but that did not exist. */\n adopted?: boolean\n /** Set on a rejection (status \u2265 400) the mock produced itself, never on a scripted fault. */\n request?: RejectedRequest\n /** The validation issues behind a rejection, when the service found any. */\n issues?: BodyIssue[]\n}\n\nexport type MetricsReport = {\n requests: number\n /** Counts keyed `<operationId> <status>`. */\n byOperation: Record<string, number>\n /**\n * Paths that matched no operation, most frequent first.\n *\n * This is the early-warning signal: a consumer calling something the mock does\n * not implement shows up here as a count, before it fails a suite as a 404.\n */\n unmatched: { method: string; path: string; count: number }[]\n faults: number\n totalDurationMs: number\n}\n\nexport type Metrics = {\n record(entry: RequestLog): void\n report(): MetricsReport\n reset(): void\n}\n\nexport const createMetrics = (): Metrics => {\n let requests = 0\n let faults = 0\n let totalDurationMs = 0\n const byOperation = new Map<string, number>()\n const unmatched = new Map<string, number>()\n return {\n record(entry) {\n requests++\n totalDurationMs += entry.durationMs\n if (entry.faultId !== undefined) faults++\n const key = `${entry.operationId ?? \"(unmatched)\"} ${entry.status}`\n byOperation.set(key, (byOperation.get(key) ?? 0) + 1)\n if (entry.unmatched) {\n const route = `${entry.method} ${entry.path}`\n unmatched.set(route, (unmatched.get(route) ?? 0) + 1)\n }\n },\n report: () => ({\n requests,\n byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),\n unmatched: [...unmatched]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([route, count]) => {\n const space = route.indexOf(\" \")\n return { method: route.slice(0, space), path: route.slice(space + 1), count }\n }),\n faults,\n totalDurationMs,\n }),\n reset() {\n requests = 0\n faults = 0\n totalDurationMs = 0\n byOperation.clear()\n unmatched.clear()\n },\n }\n}\n", "/** A stable identifier for a point in a {@link Timeline}. */\nexport type CheckpointId = string\n\n/** An immutable node in a timeline's checkpoint DAG. */\nexport type Checkpoint<T> = Readonly<{\n id: CheckpointId\n branch: string\n parent: CheckpointId | null\n /** Logical time supplied by the timeline's injected clock. */\n at: number\n value: T\n}>\n\nexport type TimelineOptions = {\n /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */\n now?: () => number\n /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */\n maxCheckpoints?: number\n /** Customize deterministic checkpoint IDs. */\n id?: (sequence: number) => CheckpointId\n}\n\nexport type CommitOptions = {\n branch?: string\n /** Parent checkpoint. Defaults to the selected branch's current head. */\n parent?: CheckpointId | null\n}\n\nexport type ForkOptions = {\n /** Checkpoint to fork from. Defaults to the main branch's head. */\n from?: CheckpointId\n}\n\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/**\n * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable\n * records, namespace images, or copy-on-write SQL engine snapshots.\n *\n * Values are retained by reference. Engines can therefore use persistent/COW snapshots while\n * simpler services can use immutable values. IDs and GC order are deterministic, and all IO\n * (the logical clock) is injected.\n */\nexport class Timeline<T> {\n readonly maxCheckpoints: number\n private readonly now: () => number\n private readonly makeId: (sequence: number) => CheckpointId\n private readonly nodes = new Map<CheckpointId, Checkpoint<T>>()\n private readonly heads = new Map<string, CheckpointId>()\n /** Unreferenced nodes in the exact order they became collectible. */\n private readonly evictable = new Set<CheckpointId>()\n /** Branch heads plus explicit retainers. Absent means zero. */\n private readonly references = new Map<CheckpointId, number>()\n private readonly explicitPins = new Map<CheckpointId, number>()\n private sequence = 0\n\n constructor(options: TimelineOptions = {}) {\n const max = options.maxCheckpoints ?? 1_000\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"maxCheckpoints must be a positive integer\")\n this.maxCheckpoints = max\n this.now = options.now ?? (() => this.sequence)\n this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, \"0\")}`)\n }\n\n /** Capture a new immutable value and move `branch` to it. */\n commit(value: T, options: CommitOptions = {}): Checkpoint<T> {\n const branch = options.branch ?? \"main\"\n this.assertBranch(branch)\n const parent = options.parent === undefined ? (this.heads.get(branch) ?? null) : options.parent\n if (parent !== null && !this.nodes.has(parent)) throw new RangeError(`no checkpoint ${parent}`)\n const id = this.makeId(++this.sequence)\n if (this.nodes.has(id)) throw new RangeError(`duplicate checkpoint id ${id}`)\n const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value })\n this.nodes.set(id, checkpoint)\n this.moveHead(branch, id)\n this.collect(this.maxCheckpoints)\n return checkpoint\n }\n\n /** Create a branch pointer without copying its checkpoint value. */\n fork(branch: string, options: ForkOptions = {}): Checkpoint<T> | undefined {\n this.assertBranch(branch)\n if (this.heads.has(branch)) throw new RangeError(`branch already exists: ${branch}`)\n const from = options.from ?? this.heads.get(\"main\")\n if (from === undefined) return undefined\n const checkpoint = this.get(from)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n /** Move a branch pointer to an existing checkpoint. */\n checkout(branch: string, id: CheckpointId): Checkpoint<T> {\n this.assertBranch(branch)\n const checkpoint = this.get(id)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n get(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.nodes.get(id)\n if (!checkpoint) throw new RangeError(`no checkpoint ${id}`)\n return checkpoint\n }\n\n head(branch = \"main\"): Checkpoint<T> | undefined {\n const id = this.heads.get(branch)\n return id === undefined ? undefined : this.get(id)\n }\n\n hasBranch(branch: string): boolean {\n return this.heads.has(branch)\n }\n\n branches(): Readonly<Record<string, CheckpointId>> {\n return Object.freeze(\n Object.fromEntries([...this.heads].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n )\n }\n\n checkpoints(): readonly Checkpoint<T>[] {\n return [...this.nodes.values()]\n }\n\n /** Number of retained checkpoints without allocating an array. */\n get size(): number {\n return this.nodes.size\n }\n\n /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */\n retain(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.get(id)\n this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1)\n this.addReference(id)\n return checkpoint\n }\n\n /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */\n release(id: CheckpointId): boolean {\n if (!this.nodes.has(id)) return false\n const pins = this.explicitPins.get(id) ?? 0\n if (pins === 0) return false\n if (pins === 1) this.explicitPins.delete(id)\n else this.explicitPins.set(id, pins - 1)\n this.removeReference(id)\n this.collect(this.maxCheckpoints)\n return true\n }\n\n deleteBranch(branch: string): boolean {\n if (branch === \"main\") throw new RangeError(\"cannot delete main branch\")\n const previous = this.heads.get(branch)\n const deleted = this.heads.delete(branch)\n if (previous !== undefined) this.removeReference(previous)\n this.collect(this.maxCheckpoints)\n return deleted\n }\n\n /**\n * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):\n * commits never scan pinned nodes or the retained history. Parents are metadata rather than a\n * storage dependency, so a retained node remains usable after pruning.\n */\n gc(max = this.maxCheckpoints): CheckpointId[] {\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"max must be a positive integer\")\n const removed: CheckpointId[] = []\n this.collect(max, removed)\n return removed\n }\n\n private collect(max: number, removed?: CheckpointId[]): void {\n while (this.nodes.size > max && this.evictable.size > 0) {\n const id = this.evictable.values().next().value as CheckpointId\n this.evictable.delete(id)\n this.nodes.delete(id)\n removed?.push(id)\n }\n }\n\n private moveHead(branch: string, id: CheckpointId): void {\n const previous = this.heads.get(branch)\n if (previous === id) return\n if (previous !== undefined) this.removeReference(previous)\n this.heads.set(branch, id)\n this.addReference(id)\n }\n\n private addReference(id: CheckpointId): void {\n this.references.set(id, (this.references.get(id) ?? 0) + 1)\n this.evictable.delete(id)\n }\n\n private removeReference(id: CheckpointId): void {\n const next = (this.references.get(id) ?? 0) - 1\n if (next > 0) this.references.set(id, next)\n else {\n this.references.delete(id)\n if (this.nodes.has(id)) this.evictable.add(id)\n }\n }\n\n private assertBranch(branch: string): void {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n }\n}\n", "import { Database } from \"@crvouga/mockingbird-service-sqlite\"\nimport type { SqliteClient } from \"./client.js\"\n\n/** Construct the default in-memory SQLite client (`@crvouga/mockingbird-service-sqlite`). */\nexport const createDefaultSqlite = (): SqliteClient => new Database()\n\n/** Use the injected client, or fall back to {@link createDefaultSqlite}. */\nexport const resolveSqlite = (sqlite?: SqliteClient): SqliteClient =>\n sqlite ?? createDefaultSqlite()\n", "import type { SqliteClient } from \"./client.js\"\n\n/** One named, ordered schema change applied exactly once per client. */\nexport type Migration = {\n /** Stable id stored in `schema_migrations`. Must be unique across the list. */\n id: string\n sql: string\n}\n\nconst ensureMigrationsTable = (sqlite: SqliteClient) => {\n sqlite.exec(`\n CREATE TABLE IF NOT EXISTS schema_migrations (\n id TEXT PRIMARY KEY NOT NULL,\n applied_at INTEGER NOT NULL\n )\n `)\n}\n\n/**\n * Apply pending migrations in order inside a single transaction.\n *\n * Idempotent: already-applied ids are skipped. Re-running with the same list\n * is a no-op after the first successful boot.\n */\nexport const migrate = (sqlite: SqliteClient, migrations: readonly Migration[]): void => {\n ensureMigrationsTable(sqlite)\n const applied = new Set(\n sqlite\n .prepare(\"SELECT id FROM schema_migrations\")\n .all<{ id: string }>()\n .map((row) => row.id),\n )\n const pending = migrations.filter((migration) => !applied.has(migration.id))\n if (pending.length === 0) return\n\n const insert = sqlite.prepare(\"INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)\")\n const now = Math.floor(Date.now() / 1000)\n sqlite.transaction(() => {\n for (const migration of pending) {\n sqlite.exec(migration.sql)\n insert.run(migration.id, now)\n }\n })\n}\n\n/** Applied migration ids in application order (by `applied_at`, then `id`). */\nexport const listAppliedMigrations = (sqlite: SqliteClient): string[] => {\n ensureMigrationsTable(sqlite)\n return sqlite\n .prepare(\"SELECT id FROM schema_migrations ORDER BY applied_at ASC, id ASC\")\n .all<{ id: string }>()\n .map((row) => row.id)\n}\n", "import type { SqliteClient } from \"./client.js\"\nimport { type Migration, migrate } from \"./migrate.js\"\n\n/**\n * Core Mockingbird service schema: namespaced JSON records and counters.\n *\n * Applied on every service boot via {@link migrateCore}.\n */\nexport const CORE_MIGRATIONS: readonly Migration[] = [\n {\n id: \"20260322_core_records_sequences\",\n sql: `\n CREATE TABLE IF NOT EXISTS mockingbird_records (\n namespace TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (namespace, collection, id)\n );\n CREATE INDEX IF NOT EXISTS mockingbird_records_seq\n ON mockingbird_records (namespace, collection, seq);\n CREATE TABLE IF NOT EXISTS mockingbird_sequences (\n namespace TEXT NOT NULL,\n name TEXT NOT NULL,\n kind TEXT NOT NULL,\n value INTEGER NOT NULL,\n PRIMARY KEY (namespace, name, kind)\n );\n `,\n },\n]\n\n/** Apply {@link CORE_MIGRATIONS} (idempotent). */\nexport const migrateCore = (sqlite: SqliteClient): void => {\n migrate(sqlite, CORE_MIGRATIONS)\n}\n\n/** Delete every record and sequence belonging to `namespace`. */\nexport const clearNamespace = (sqlite: SqliteClient, namespace: string): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n })\n}\n", "/**\n * Cross-browser baseline for every HTML surface this repo serves.\n *\n * `CSS_RESET` is the document sheet. `scopeReset(root)` is the same sheet\n * limited to a widget (`:where` so later component rules still win) and with\n * viewport heights rewritten to the widget's own box.\n *\n * `reset.css` is this string as a stylesheet. The package test fails when the\n * two drift.\n */\nexport const CSS_RESET = `*,\n*::before,\n*::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n\n* {\n scrollbar-width: thin;\n scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;\n}\n\n*::-webkit-scrollbar {\n width: 12px;\n height: 12px;\n}\n\n*::-webkit-scrollbar-track,\n*::-webkit-scrollbar-corner {\n background: Canvas;\n}\n\n*::-webkit-scrollbar-thumb {\n background: color-mix(in srgb, CanvasText 35%, Canvas);\n border: 3px solid Canvas;\n border-radius: 999px;\n}\n\nhtml {\n hanging-punctuation: first allow-end last;\n -webkit-text-size-adjust: none;\n text-size-adjust: none;\n tab-size: 4;\n font-family:\n ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI Variable\", \"Segoe UI\",\n \"Helvetica Neue\", Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\";\n font-size: 16px;\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: optimizeLegibility;\n -webkit-tap-highlight-color: transparent;\n scroll-behavior: smooth;\n background: Canvas;\n color: CanvasText;\n}\n\nbody {\n min-height: 100svh;\n line-height: 1.5;\n background: Canvas;\n color: CanvasText;\n}\n\nh1 {\n font-size: 2em;\n}\n\nh2 {\n font-size: 1.5em;\n}\n\nh3 {\n font-size: 1.17em;\n}\n\nh4 {\n font-size: 1em;\n}\n\nh5 {\n font-size: 0.83em;\n}\n\nh6 {\n font-size: 0.67em;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n font-weight: 700;\n line-height: 1.2;\n text-wrap: balance;\n overflow-wrap: break-word;\n}\n\np,\nli,\nfigcaption,\ndd,\ndt,\nblockquote {\n overflow-wrap: break-word;\n}\n\np,\nli,\nfigcaption,\nblockquote {\n text-wrap: pretty;\n}\n\nul,\nol,\nmenu {\n list-style: none;\n}\n\na {\n color: inherit;\n text-decoration: underline;\n text-decoration-thickness: 1px;\n text-underline-offset: 0.15em;\n text-decoration-skip-ink: auto;\n}\n\nb,\nstrong {\n font-weight: 700;\n}\n\nsmall {\n font-size: 0.875em;\n}\n\ncode,\nkbd,\nsamp,\npre {\n font-family: ui-monospace, \"SF Mono\", SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 1em;\n}\n\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\n\nsub {\n bottom: -0.25em;\n}\n\nsup {\n top: -0.5em;\n}\n\nabbr[title] {\n text-decoration: underline dotted;\n text-underline-offset: 0.15em;\n}\n\nmark {\n background: Mark;\n color: MarkText;\n}\n\nhr {\n height: 0;\n border: 0;\n border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);\n color: inherit;\n}\n\nimg,\npicture,\nvideo,\ncanvas {\n display: block;\n max-width: 100%;\n}\n\nimg,\nvideo {\n height: auto;\n}\n\nsvg {\n overflow: hidden;\n}\n\niframe {\n border: 0;\n max-width: 100%;\n}\n\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\n\nfieldset {\n border: 0;\n min-inline-size: 0;\n}\n\nlegend {\n padding: 0;\n}\n\nbutton,\ninput,\nselect,\ntextarea,\noptgroup {\n font: inherit;\n letter-spacing: inherit;\n color: inherit;\n margin: 0;\n vertical-align: middle;\n}\n\nbutton,\ninput[type=\"button\"],\ninput[type=\"submit\"],\ninput[type=\"reset\"] {\n appearance: none;\n background: none;\n border: 0;\n padding: 0;\n cursor: pointer;\n text-align: center;\n}\n\ninput,\ntextarea,\nselect {\n background-color: Canvas;\n border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);\n border-radius: 0;\n padding: 0.5em 0.65em;\n}\n\ninput[type=\"checkbox\"],\ninput[type=\"radio\"],\ninput[type=\"range\"],\ninput[type=\"file\"],\ninput[type=\"color\"],\ninput[type=\"button\"],\ninput[type=\"submit\"],\ninput[type=\"reset\"],\ninput[type=\"image\"],\ninput[type=\"hidden\"] {\n background: none;\n border: 0;\n padding: 0;\n border-radius: 0;\n}\n\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n accent-color: CanvasText;\n}\n\ninput[type=\"search\"] {\n appearance: none;\n background-color: Canvas;\n border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);\n}\n\ninput[type=\"search\"]::-webkit-search-decoration,\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-results-button,\ninput[type=\"search\"]::-webkit-search-results-decoration {\n -webkit-appearance: none;\n display: none;\n}\n\ninput[type=\"number\"] {\n appearance: textfield;\n background-color: Canvas;\n border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);\n}\n\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}\n\ntextarea {\n resize: vertical;\n}\n\n::placeholder {\n opacity: 1;\n color: color-mix(in srgb, CanvasText 45%, transparent);\n}\n\n:focus-visible {\n outline: 2px solid CanvasText;\n outline-offset: 2px;\n}\n\n:focus:not(:focus-visible) {\n outline: none;\n}\n\n:disabled,\n[disabled] {\n cursor: default;\n opacity: 0.6;\n}\n\nlabel,\nsummary,\nselect,\n[role=\"button\"] {\n cursor: pointer;\n}\n\nsummary {\n display: list-item;\n}\n\ndetails {\n display: block;\n}\n\ndialog {\n margin: auto;\n padding: 1rem;\n border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);\n background: Canvas;\n color: CanvasText;\n max-width: calc(100vw - 2rem);\n max-height: calc(100svh - 2rem);\n}\n\ndialog:not([open]) {\n display: none;\n}\n\n::backdrop {\n background: color-mix(in srgb, CanvasText 40%, transparent);\n}\n\n[hidden] {\n display: none !important;\n}\n\n::selection {\n background: Highlight;\n color: HighlightText;\n}\n\n@media (prefers-reduced-motion: reduce) {\n *,\n *::before,\n *::after {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n scroll-behavior: auto !important;\n }\n}\n\n@media (pointer: coarse) {\n input,\n select,\n textarea {\n font-size: max(16px, 1em);\n }\n}`\n\n/** Scope the reset to `root` without raising specificity above a single element. */\nexport function scopeReset(root: string): string {\n return scopeStylesheet(CSS_RESET, root)\n .replaceAll(\"100dvh\", \"100%\")\n .replaceAll(\"100svh\", \"100%\")\n .replaceAll(\"100vh\", \"100%\")\n}\n\nfunction scopeStylesheet(css: string, root: string): string {\n let out = \"\"\n let cursor = 0\n while (cursor < css.length) {\n const brace = css.indexOf(\"{\", cursor)\n if (brace === -1) {\n out += css.slice(cursor)\n break\n }\n const prelude = css.slice(cursor, brace)\n const trimmed = prelude.trimStart()\n if (trimmed.startsWith(\"@media\") || trimmed.startsWith(\"@supports\")) {\n const end = skipBlock(css, brace)\n const body = css.slice(brace + 1, end - 1)\n out += `${css.slice(cursor, brace + 1)}${scopeStylesheet(body, root)}}`\n cursor = end\n continue\n }\n if (trimmed.startsWith(\"@\")) {\n const end = skipBlock(css, brace)\n out += css.slice(cursor, end)\n cursor = end\n continue\n }\n const close = prelude.lastIndexOf(\"}\")\n const head = close === -1 ? \"\" : prelude.slice(0, close + 1)\n const selector = close === -1 ? prelude : prelude.slice(close + 1)\n out += `${head}${scopeSelectorList(selector, root)}{`\n cursor = brace + 1\n }\n return out\n}\n\nfunction scopeSelectorList(selector: string, root: string): string {\n const where = `:where(${root})`\n return splitSelectors(selector)\n .map((part) => scopeOne(part.trim(), where))\n .filter((part) => part !== \"\")\n .join(\",\\n\")\n}\n\nfunction scopeOne(selector: string, where: string): string {\n if (selector === \"html\" || selector === \"body\" || selector === \":root\") return where\n if (selector.startsWith(\"*\")) {\n const rest = selector.slice(1)\n return `${where}${rest},\\n${where} ${selector}`\n }\n if (selector.startsWith(\":\")) return `${where}${selector},\\n${where} ${selector}`\n return `${where} ${selector}`\n}\n\n/** Split a selector list on commas that are not inside parentheses. */\nfunction splitSelectors(selector: string): string[] {\n const parts: string[] = []\n let current = \"\"\n let depth = 0\n for (const char of selector) {\n if (char === \"(\") depth++\n else if (char === \")\") depth = Math.max(0, depth - 1)\n if (char === \",\" && depth === 0) {\n parts.push(current)\n current = \"\"\n continue\n }\n current += char\n }\n parts.push(current)\n return parts\n}\n\nfunction skipBlock(css: string, openBrace: number): number {\n let depth = 0\n for (let index = openBrace; index < css.length; index++) {\n const char = css[index]\n if (char === \"{\") depth++\n else if (char === \"}\") {\n depth--\n if (depth === 0) return index + 1\n }\n }\n return css.length\n}\n", "import type { ClockState } from \"./clock.js\"\nimport type { FaultPresetList } from \"./faults.js\"\nimport type { StateCollectionView, StateField, StateFieldKind, StateView } from \"./state-view.js\"\n\n/**\n * Admin page behavior. `adminClientSource` inlines these functions into the document.\n * They run in the browser, so they cannot close over module bindings \u2014 configuration\n * arrives as the argument to `bootAdmin`.\n */\nexport type AdminBootConfig = {\n standardRoutes: readonly string[]\n adminPrefix: string\n adminKeyHeader: string\n brandsUrl: string\n service: string\n}\n\nexport type AdminBrandEnv = {\n document: Document\n $: (id: string) => HTMLElement | null\n params: URLSearchParams\n location: { href: string; origin: string }\n fetch: typeof fetch\n brandsUrl: string\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n/** Paint the header chip from a brands catalog. Hostile URLs and markup are dropped. */\nexport function mountAdminBrand(\n doc: Document,\n host: HTMLElement,\n service: string,\n catalog: unknown,\n): void {\n const clip = (value: unknown, max: number): string | null => {\n if (typeof value !== \"string\") return null\n const trimmed = value.trim()\n if (trimmed === \"\") return null\n return trimmed.length > max ? trimmed.slice(0, max) : trimmed\n }\n const httpUrl = (value: unknown): string | null => {\n if (typeof value !== \"string\" || value.length > 2000) return null\n try {\n const url = new URL(value)\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return null\n return url.href\n } catch {\n return null\n }\n }\n const hexColor = (value: unknown): string | null => {\n if (typeof value !== \"string\") return null\n const raw = value.trim()\n return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null\n }\n const hostname = (value: string): string => {\n try {\n return new URL(value).hostname.replace(/^www\\./, \"\")\n } catch {\n return value\n }\n }\n host.replaceChildren()\n host.hidden = true\n if (!isRecord(catalog) || !Object.hasOwn(catalog, service)) return\n const row = catalog[service]\n if (!isRecord(row)) return\n const vendor = clip(row.vendor, 80)\n const website = httpUrl(row.website)\n const guide = httpUrl(row.guide)\n const docs = httpUrl(row.docs)\n const logo = httpUrl(row.logo)\n const color = hexColor(row.color)\n const description = clip(row.description, 280)\n if (vendor === null || (website === null && guide === null && docs === null)) return\n const add = <T extends Node>(node: T): T => {\n host.append(node)\n return node\n }\n if (logo !== null) {\n const img = doc.createElement(\"img\")\n img.alt = \"\"\n img.src = logo\n img.width = 16\n img.height = 16\n img.decoding = \"async\"\n img.referrerPolicy = \"no-referrer\"\n if (color !== null) img.style.borderColor = color\n add(img)\n }\n const name = doc.createElement(\"span\")\n name.className = \"vendor-name\"\n name.textContent = vendor\n if (description !== null) name.title = description\n add(name)\n const sep = (): HTMLSpanElement => {\n const node = doc.createElement(\"span\")\n node.className = \"vendor-sep\"\n node.setAttribute(\"aria-hidden\", \"true\")\n node.textContent = \"\u00B7\"\n return node\n }\n const link = (href: string, label: string, title: string): HTMLAnchorElement => {\n const node = doc.createElement(\"a\")\n node.className = \"vendor-link\"\n node.href = href\n node.target = \"_blank\"\n node.rel = \"noopener noreferrer\"\n node.referrerPolicy = \"no-referrer\"\n node.textContent = label\n node.title = title\n return node\n }\n if (website !== null) {\n add(sep())\n add(link(website, hostname(website), `${vendor} website`))\n }\n if (guide !== null) {\n add(sep())\n add(link(guide, \"Docs\", `Docs for ${vendor}`))\n }\n if (docs !== null) {\n add(sep())\n add(link(docs, \"API\", `${vendor} API reference`))\n }\n host.removeAttribute(\"hidden\")\n host.hidden = false\n}\n\n/** Fetch the brands catalog and paint `#vendor`. `?brands=` may name a local copy. */\nexport function startAdminBrand(env: AdminBrandEnv): void {\n const requested = env.params.get(\"brands\")\n let brandsUrl = env.brandsUrl\n if (requested) {\n try {\n const url = new URL(requested, env.location.href)\n const local =\n url.hostname === \"localhost\" ||\n url.hostname === \"127.0.0.1\" ||\n url.hostname === \"::1\" ||\n url.hostname === \"[::1]\" ||\n url.origin === env.location.origin\n if ((url.protocol === \"https:\" || url.protocol === \"http:\") && local) brandsUrl = url.href\n } catch {\n brandsUrl = env.brandsUrl\n }\n }\n const vendorHost = env.$(\"vendor\")\n const brandRoot = env.document.querySelector(\"[data-mockingbird-admin]\")\n const brandService = brandRoot?.getAttribute(\"data-service\") || \"\"\n if (vendorHost === null) return\n env\n .fetch(brandsUrl, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(5000),\n })\n .then(async (response) => {\n if (!response.ok) return null\n const catalog: unknown = await response.json()\n return catalog\n })\n .then((catalog) => {\n mountAdminBrand(env.document, vendorHost, brandService, catalog)\n })\n .catch(() => {})\n}\n\n/**\n * Names from `GET /__admin/faults/presets`.\n * The payload's `presets` field is a list. A record keyed by preset name is rejected\n * here, which is also a type error at the handler that builds a {@link FaultPresetList}.\n */\nexport function faultPresetList(value: unknown): FaultPresetList {\n if (!isRecord(value)) throw new Error(\"Fault presets response was not an object\")\n if (!Object.hasOwn(value, \"presets\") || value.presets === undefined || value.presets === null) {\n return { presets: [] }\n }\n if (!Array.isArray(value.presets)) throw new Error(\"Fault presets response was not a list\")\n return {\n presets: value.presets.flatMap((item) => {\n if (!isRecord(item) || typeof item.name !== \"string\") return []\n return [{ name: item.name }]\n }),\n }\n}\n\n/** Boot the admin document. Inlined into the page; do not close over module bindings. */\nexport function bootAdmin(config: AdminBootConfig): void {\n const fieldKinds = [\"string\", \"number\", \"boolean\", \"null\", \"object\", \"array\", \"unknown\"] as const\n const sources = [\"declared\", \"inferred\", \"mixed\"] as const\n const isFieldKind = (value: unknown): value is StateFieldKind =>\n typeof value === \"string\" && fieldKinds.some((kind) => kind === value)\n const isSource = (value: unknown): value is StateCollectionView[\"source\"] =>\n typeof value === \"string\" && sources.some((source) => source === value)\n const readJson = (text: string): unknown => {\n const value: unknown = JSON.parse(text)\n return value\n }\n const esc = (value: unknown): string =>\n String(value ?? \"\").replace(/[&<>\"']/g, (char) => {\n switch (char) {\n case \"&\":\n return \"&\"\n case \"<\":\n return \"<\"\n case \">\":\n return \">\"\n case '\"':\n return \""\"\n default:\n return \"'\"\n }\n })\n const el = <T extends HTMLElement>(id: string, kind: new () => T): T => {\n const node = document.getElementById(id)\n if (!(node instanceof kind)) throw new Error(`admin shell is missing #${id}`)\n return node\n }\n const errorMessage = (data: unknown, fallback: string): string => {\n if (!isRecord(data)) return fallback\n const error = data.error\n if (!isRecord(error) || typeof error.message !== \"string\" || error.message === \"\") {\n return fallback\n }\n return error.message\n }\n const requireList = (value: unknown, label: string): unknown[] => {\n if (value === undefined || value === null) return []\n if (!Array.isArray(value)) throw new Error(`${label} was not a list`)\n return value\n }\n\n const state: {\n namespace: string\n key: string\n view: string\n collection: string\n shape: StateView | null\n route: string | null\n editing: string | null\n } = {\n namespace: \"default\",\n key: sessionStorage.getItem(\"mockingbird-admin-key\") || \"\",\n view: \"overview\",\n collection: \"\",\n shape: null,\n route: null,\n editing: null,\n }\n const standard = new Set(config.standardRoutes)\n const banner = el(\"banner\", HTMLElement)\n const keyInput = el(\"admin-key\", HTMLInputElement)\n keyInput.value = state.key\n const params = new URLSearchParams(location.search)\n const queryKey = params.get(\"key\")\n if (queryKey) {\n state.key = queryKey\n keyInput.value = state.key\n sessionStorage.setItem(\"mockingbird-admin-key\", state.key)\n params.delete(\"key\")\n const next = params.toString()\n history.replaceState(null, \"\", location.pathname + (next ? `?${next}` : \"\"))\n }\n const queryNamespace = params.get(\"namespace\")\n if (queryNamespace) state.namespace = queryNamespace\n\n const showError = (error: unknown): void => {\n banner.textContent = error instanceof Error ? error.message : String(error)\n banner.classList.add(\"show\")\n }\n const clearError = (): void => {\n banner.classList.remove(\"show\")\n }\n\n const api = async (method: string, path: string, body?: unknown): Promise<unknown> => {\n const headers: Record<string, string> = { accept: \"application/json\" }\n if (state.key !== \"\") headers[config.adminKeyHeader] = state.key\n if (state.namespace !== \"\") headers[\"x-mockingbird-namespace\"] = state.namespace\n if (body !== undefined) headers[\"content-type\"] = \"application/json\"\n const init: RequestInit = { method, headers }\n if (body !== undefined) init.body = JSON.stringify(body)\n const response = await fetch(config.adminPrefix + path, init)\n const text = await response.text()\n let data: unknown = null\n if (text !== \"\") {\n try {\n data = readJson(text)\n } catch {\n data = { raw: text }\n }\n }\n if (response.status === 401) {\n keyInput.focus()\n throw new Error(errorMessage(data, \"Admin key required\"))\n }\n if (!response.ok) {\n throw new Error(errorMessage(data, `${response.status} ${method} ${path}`))\n }\n return data\n }\n const originGet = async (path: string): Promise<unknown> => {\n const response = await fetch(path, { headers: { accept: \"application/json\" } })\n if (!response.ok) throw new Error(`${response.status} ${path}`)\n const value: unknown = await response.json()\n return value\n }\n type PanelApi = {\n get: (path: string) => Promise<unknown>\n send: (method: string, path: string, body?: unknown) => Promise<unknown>\n namespace: () => string\n }\n const panelApi: PanelApi = {\n get: (path) => api(\"GET\", path),\n send: (method, path, body) => api(method, path, body),\n namespace: () => state.namespace,\n }\n const isPanelScript = (value: unknown): value is (root: HTMLElement, api: PanelApi) => void =>\n typeof value === \"function\"\n\n const setTheme = (theme: string | null): void => {\n if (theme) document.documentElement.dataset.theme = theme\n else delete document.documentElement.dataset.theme\n }\n const storedTheme = localStorage.getItem(\"mockingbird-admin-theme\")\n if (storedTheme) setTheme(storedTheme)\n el(\"theme\", HTMLButtonElement).addEventListener(\"click\", () => {\n const current = document.documentElement.dataset.theme\n const dark = current ? current === \"dark\" : matchMedia(\"(prefers-color-scheme: dark)\").matches\n const next = dark ? \"light\" : \"dark\"\n localStorage.setItem(\"mockingbird-admin-theme\", next)\n setTheme(next)\n })\n\n const show = (view: string): void => {\n state.view = view\n for (const button of document.querySelectorAll(\"#nav button\")) {\n if (!(button instanceof HTMLButtonElement)) continue\n button.setAttribute(\"aria-current\", button.dataset.view === view ? \"true\" : \"false\")\n }\n for (const section of document.querySelectorAll(\"main .view\")) {\n if (!(section instanceof HTMLElement)) continue\n section.hidden = section.id !== `view-${view}`\n }\n }\n el(\"nav\", HTMLElement).addEventListener(\"click\", (event) => {\n const target = event.target\n if (!(target instanceof Element)) return\n const button = target.closest(\"button[data-view]\")\n if (!(button instanceof HTMLButtonElement)) return\n const view = button.dataset.view\n if (view === undefined) return\n show(view)\n refresh().catch(showError)\n })\n\n const cards = (items: readonly { k: string; v: string }[]): string =>\n `<div class=\"grid\">${items\n .map(\n (item) =>\n `<article class=\"card\"><div class=\"k\">${item.k}</div><div class=\"v\">${item.v}</div></article>`,\n )\n .join(\"\")}</div>`\n const table = <Row extends object>(\n columns: readonly { label: string; cell: (row: Row) => string }[],\n rows: readonly Row[],\n ): string => {\n if (rows.length === 0) return '<p class=\"empty\">Nothing here yet.</p>'\n const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join(\"\")}</tr>`\n const body = rows\n .map((row) => {\n const cells = columns\n .map((column) => `<td data-label=\"${column.label}\">${column.cell(row)}</td>`)\n .join(\"\")\n const attrs = \"attrs\" in row && typeof row.attrs === \"string\" ? row.attrs : \"\"\n return `<tr${attrs}>${cells}</tr>`\n })\n .join(\"\")\n return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`\n }\n const preview = (value: unknown): string => {\n const text = JSON.stringify(value) ?? \"null\"\n return esc(text.length > 180 ? `${text.slice(0, 180)}\u2026` : text)\n }\n const when = (epoch: number): string => {\n const date = new Date(epoch)\n return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()\n }\n const clockCard = (epoch: number): string => {\n const date = new Date(epoch)\n if (Number.isNaN(date.getTime())) return esc(String(epoch))\n const iso = date.toISOString()\n return `${esc(iso.slice(0, 10))}<span class=\"clock-time\">${esc(iso.slice(11, 19))} UTC</span>`\n }\n const decodeClock = (value: unknown): ClockState => {\n if (\n !isRecord(value) ||\n typeof value.now !== \"number\" ||\n typeof value.offsetMs !== \"number\" ||\n typeof value.frozen !== \"boolean\"\n ) {\n throw new Error(\"Clock response was not a clock\")\n }\n return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen }\n }\n const decodeField = (value: unknown): StateField | undefined => {\n if (!isRecord(value) || typeof value.name !== \"string\" || !isFieldKind(value.kind)) {\n return undefined\n }\n const field: StateField = {\n name: value.name,\n kind: value.kind,\n optional: value.optional === true,\n }\n if (typeof value.description === \"string\") field.description = value.description\n if (Array.isArray(value.fields)) {\n field.fields = value.fields.flatMap((item) => {\n const child = decodeField(item)\n return child === undefined ? [] : [child]\n })\n }\n return field\n }\n const decodeCollection = (value: unknown): StateCollectionView | undefined => {\n if (!isRecord(value) || typeof value.name !== \"string\") return undefined\n const fields = Array.isArray(value.fields)\n ? value.fields.flatMap((item) => {\n const field = decodeField(item)\n return field === undefined ? [] : [field]\n })\n : []\n const collection: StateCollectionView = {\n name: value.name,\n label: typeof value.label === \"string\" ? value.label : value.name,\n count: typeof value.count === \"number\" ? value.count : 0,\n source: isSource(value.source) ? value.source : \"inferred\",\n fields,\n }\n if (typeof value.description === \"string\") collection.description = value.description\n return collection\n }\n const decodeState = (value: unknown): StateView => {\n if (!isRecord(value) || !Array.isArray(value.collections)) {\n throw new Error(\"State response has no collection list\")\n }\n return {\n namespace: typeof value.namespace === \"string\" ? value.namespace : state.namespace,\n storageNamespace: typeof value.storageNamespace === \"string\" ? value.storageNamespace : \"\",\n collections: value.collections.flatMap((item) => {\n const collection = decodeCollection(item)\n return collection === undefined ? [] : [collection]\n }),\n }\n }\n type RecordRow = { id: string; seq: number; value: unknown; attrs: string }\n const decodeRecords = (value: unknown): RecordRow[] =>\n requireList(isRecord(value) ? value.records : undefined, \"Records\").flatMap((item) => {\n if (!isRecord(item) || typeof item.id !== \"string\") return []\n return [\n {\n id: item.id,\n seq: typeof item.seq === \"number\" ? item.seq : 0,\n value: item.value,\n attrs: ` class=\"clickable\" data-id=\"${esc(item.id)}\"`,\n },\n ]\n })\n type JournalRow = {\n at: string\n method: string\n path: string\n status: string\n durationMs: string\n operationId: string\n }\n const textOf = (value: unknown): string =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n ? String(value)\n : \"\"\n const decodeJournal = (value: unknown): JournalRow[] =>\n requireList(isRecord(value) ? value.requests : undefined, \"Journal\").flatMap((item) => {\n if (!isRecord(item)) return []\n return [\n {\n at: textOf(item.at),\n method: textOf(item.method),\n path: textOf(item.path),\n status: textOf(item.status),\n durationMs: textOf(item.durationMs),\n operationId: textOf(item.operationId),\n },\n ]\n })\n type FaultRow = {\n id: string\n method: string | undefined\n pathPrefix: string | undefined\n operationId: string | undefined\n status: number | undefined\n effect: string | undefined\n drop: boolean | undefined\n latencyMs: number | undefined\n }\n const decodeFaults = (value: unknown): FaultRow[] =>\n requireList(isRecord(value) ? value.faults : undefined, \"Faults\").flatMap((item) => {\n if (!isRecord(item)) return []\n return [\n {\n id: textOf(item.id),\n method: typeof item.method === \"string\" ? item.method : undefined,\n pathPrefix: typeof item.pathPrefix === \"string\" ? item.pathPrefix : undefined,\n operationId: typeof item.operationId === \"string\" ? item.operationId : undefined,\n status: typeof item.status === \"number\" ? item.status : undefined,\n effect: typeof item.effect === \"string\" ? item.effect : undefined,\n drop: typeof item.drop === \"boolean\" ? item.drop : undefined,\n latencyMs: typeof item.latencyMs === \"number\" ? item.latencyMs : undefined,\n },\n ]\n })\n\n const loadNamespaces = async (): Promise<void> => {\n const data = await api(\"GET\", \"/namespaces\")\n const select = el(\"namespace\", HTMLSelectElement)\n const listed = requireList(isRecord(data) ? data.namespaces : undefined, \"Namespaces\")\n const fallback =\n isRecord(data) && typeof data.default === \"string\" && data.default !== \"\"\n ? data.default\n : \"default\"\n const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice()\n if (!names.includes(state.namespace)) names.unshift(state.namespace)\n select.innerHTML = names\n .map((name) => `<option value=\"${esc(name)}\">${esc(name)}</option>`)\n .join(\"\")\n select.value = state.namespace\n }\n\n const renderOverview = async (): Promise<void> => {\n const [health, shape, clock, journal] = await Promise.all([\n originGet(\"/health\"),\n api(\"GET\", \"/state\"),\n api(\"GET\", \"/clock\"),\n api(\"GET\", \"/requests?limit=8\"),\n ])\n if (!isRecord(health)) throw new Error(\"Health response was not an object\")\n const decoded = decodeState(shape)\n state.shape = decoded\n const time = decodeClock(clock)\n el(\"overview-cards\", HTMLElement).innerHTML = cards([\n {\n k: \"Service\",\n v: esc(\n typeof health.service === \"string\" && health.service !== \"\"\n ? health.service\n : config.service,\n ),\n },\n {\n k: \"Status\",\n v: esc(typeof health.status === \"string\" && health.status !== \"\" ? health.status : \"ok\"),\n },\n { k: \"Namespace\", v: esc(state.namespace) },\n { k: \"Collections\", v: String(decoded.collections.length) },\n {\n k: \"Records\",\n v: String(decoded.collections.reduce((sum, item) => sum + item.count, 0)),\n },\n { k: \"Clock\", v: clockCard(time.now) },\n ])\n el(\"overview-requests\", HTMLElement).innerHTML = table(\n [\n { label: \"Method\", cell: (row: JournalRow) => esc(row.method) },\n { label: \"Path\", cell: (row: JournalRow) => esc(row.path) },\n {\n label: \"Status\",\n cell: (row: JournalRow) =>\n `<span class=\"status-${row.status.charAt(0)}\">${esc(row.status)}</span>`,\n },\n { label: \"Operation\", cell: (row: JournalRow) => esc(row.operationId) },\n ],\n decodeJournal(journal),\n )\n }\n\n const schemaChips = (collection: StateCollectionView): string => {\n if (collection.fields.length === 0) {\n return '<p class=\"empty\">No fields yet. Add a record or declare the collection on the service.</p>'\n }\n return `<div class=\"chips\">${collection.fields\n .map(\n (field) =>\n `<span class=\"chip\">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? \"?\" : \"\"}</i></span>`,\n )\n .join(\"\")}</div>`\n }\n\n const renderState = async (): Promise<void> => {\n const shape = decodeState(await api(\"GET\", \"/state\"))\n state.shape = shape\n const host = el(\"collections\", HTMLElement)\n if (shape.collections.length === 0) {\n host.innerHTML = '<p class=\"empty\">This namespace has no collections yet.</p>'\n el(\"schema\", HTMLElement).innerHTML = \"\"\n el(\"records\", HTMLElement).innerHTML = \"\"\n return\n }\n if (!shape.collections.some((item) => item.name === state.collection)) {\n const first = shape.collections[0]\n if (first === undefined) return\n state.collection = first.name\n }\n host.innerHTML = shape.collections\n .map(\n (item) =>\n `<button type=\"button\" class=\"collection\" data-collection=\"${esc(item.name)}\" aria-current=\"${\n item.name === state.collection ? \"true\" : \"false\"\n }\"><strong>${esc(item.label)}</strong><small>${esc(item.count)} \u00B7 ${esc(item.source)}</small></button>`,\n )\n .join(\"\")\n const selected = shape.collections.find((item) => item.name === state.collection)\n if (selected === undefined) return\n const description = selected.description\n ? `<p class=\"lede\">${esc(selected.description)}</p>`\n : \"\"\n el(\"schema\", HTMLElement).innerHTML =\n `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`\n const page = await api(\"GET\", `/state/${encodeURIComponent(state.collection)}?limit=50`)\n el(\"records\", HTMLElement).innerHTML = table(\n [\n { label: \"Id\", cell: (row: RecordRow) => `<code>${esc(row.id)}</code>` },\n { label: \"Seq\", cell: (row: RecordRow) => esc(row.seq) },\n { label: \"Value\", cell: (row: RecordRow) => preview(row.value) },\n ],\n decodeRecords(page),\n )\n }\n\n const renderClock = async (): Promise<void> => {\n const clock = decodeClock(await api(\"GET\", \"/clock\"))\n el(\"clock-readout\", HTMLElement).innerHTML =\n `<div class=\"k\">Now</div><div class=\"v\">${esc(when(clock.now))}</div><p>${esc(clock.now)} ms \u00B7 offset ${esc(\n clock.offsetMs,\n )} ms ${\n clock.frozen\n ? \"<span class='badge warn'>frozen</span>\"\n : \"<span class='badge ok'>live</span>\"\n }</p>`\n const freeze = el(\"freeze\", HTMLButtonElement)\n freeze.textContent = clock.frozen ? \"Unfreeze\" : \"Freeze\"\n freeze.dataset.frozen = clock.frozen ? \"1\" : \"0\"\n }\n\n const renderFaults = async (): Promise<void> => {\n const [faults, presets] = await Promise.all([\n api(\"GET\", \"/faults\"),\n api(\"GET\", \"/faults/presets\").catch((): unknown => ({ presets: [] })),\n ])\n const select = el(\"fault-preset\", HTMLSelectElement)\n const current = select.value\n const list = faultPresetList(presets).presets\n select.innerHTML = `<option value=\"\">Custom rule</option>${list\n .map((preset) => `<option value=\"${esc(preset.name)}\">${esc(preset.name)}</option>`)\n .join(\"\")}`\n select.value = current\n el(\"fault-list\", HTMLElement).innerHTML = table(\n [\n { label: \"Id\", cell: (row: FaultRow) => esc(row.id) },\n {\n label: \"Match\",\n cell: (row: FaultRow) =>\n esc(\n [row.method, row.pathPrefix, row.operationId]\n .filter((part): part is string => Boolean(part))\n .join(\" \") || \"all\",\n ),\n },\n {\n label: \"Effect\",\n cell: (row: FaultRow) =>\n esc(row.status ?? row.effect ?? (row.drop ? \"drop\" : row.latencyMs || \"\")),\n },\n ],\n decodeFaults(faults),\n )\n }\n\n const renderJournal = async (): Promise<void> => {\n const journal = await api(\"GET\", \"/requests?limit=100\")\n el(\"journal\", HTMLElement).innerHTML = table(\n [\n { label: \"When\", cell: (row: JournalRow) => esc(row.at) },\n { label: \"Method\", cell: (row: JournalRow) => esc(row.method) },\n { label: \"Path\", cell: (row: JournalRow) => esc(row.path) },\n { label: \"Status\", cell: (row: JournalRow) => esc(row.status) },\n { label: \"ms\", cell: (row: JournalRow) => esc(row.durationMs) },\n ],\n decodeJournal(journal),\n )\n }\n\n const renderRoutes = async (): Promise<void> => {\n const data = await api(\"GET\", \"/\")\n if (!isRecord(data)) throw new Error(\"Route list was not an object\")\n const routes = requireList(data.routes, \"Routes\").map((route) => String(route))\n el(\"route-list\", HTMLElement).innerHTML = routes\n .map((route) => {\n const extra = standard.has(route) ? \"\" : \" <span class='badge'>extension</span>\"\n const parts = route.split(\" \")\n const method = parts[0] ?? \"\"\n const path = parts.slice(1).join(\" \")\n return `<div class=\"route\"><span class=\"method\">${esc(method)}</span><span>${esc(path)}${extra}</span><button class=\"btn\" type=\"button\" data-route=\"${esc(route)}\">Use</button></div>`\n })\n .join(\"\")\n }\n\n const renderers: Record<string, () => Promise<void>> = {\n overview: renderOverview,\n state: renderState,\n clock: renderClock,\n faults: renderFaults,\n journal: renderJournal,\n routes: renderRoutes,\n }\n async function refresh(): Promise<void> {\n clearError()\n const render = renderers[state.view]\n if (render) await render()\n }\n\n el(\"namespace\", HTMLSelectElement).addEventListener(\"change\", () => {\n state.namespace = el(\"namespace\", HTMLSelectElement).value\n refresh().catch(showError)\n })\n keyInput.addEventListener(\"change\", () => {\n state.key = keyInput.value.trim()\n sessionStorage.setItem(\"mockingbird-admin-key\", state.key)\n refresh().catch(showError)\n })\n el(\"refresh\", HTMLButtonElement).addEventListener(\"click\", () => {\n refresh().catch(showError)\n })\n\n el(\"collections\", HTMLElement).addEventListener(\"click\", (event) => {\n const target = event.target\n if (!(target instanceof Element)) return\n const button = target.closest(\"[data-collection]\")\n if (!(button instanceof HTMLElement)) return\n const collection = button.dataset.collection\n if (collection === undefined) return\n state.collection = collection\n renderState().catch(showError)\n })\n el(\"records\", HTMLElement).addEventListener(\"click\", (event) => {\n const target = event.target\n if (!(target instanceof Element)) return\n const row = target.closest(\"[data-id]\")\n if (!(row instanceof HTMLElement)) return\n const id = row.dataset.id\n if (id === undefined) return\n openEditor(id).catch(showError)\n })\n\n const editor = el(\"editor\", HTMLDialogElement)\n const editorId = el(\"editor-id\", HTMLInputElement)\n const editorValue = el(\"editor-value\", HTMLTextAreaElement)\n const editorDelete = el(\"editor-delete\", HTMLButtonElement)\n async function openEditor(id: string | null): Promise<void> {\n state.editing = id\n el(\"editor-title\", HTMLElement).textContent = id ? \"Edit record\" : \"New record\"\n editorId.value = id ?? \"\"\n editorId.readOnly = id !== null\n editorDelete.hidden = id === null\n if (id) {\n const record = await api(\n \"GET\",\n `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`,\n )\n if (!isRecord(record)) throw new Error(\"Record response was not an object\")\n editorValue.value = JSON.stringify(record.value, null, 2) ?? \"\"\n } else {\n editorValue.value = \"{\\n \\n}\"\n }\n editor.showModal()\n }\n el(\"new-record\", HTMLButtonElement).addEventListener(\"click\", () => {\n openEditor(null).catch(showError)\n })\n el(\"editor-form\", HTMLFormElement).addEventListener(\"submit\", (event) => {\n const submitter = event.submitter\n if (!(submitter instanceof HTMLButtonElement) || submitter.value !== \"save\") return\n event.preventDefault()\n let value: unknown\n try {\n value = readJson(editorValue.value)\n } catch {\n showError(new Error(\"Value is not JSON\"))\n return\n }\n const id = editorId.value.trim()\n const path = `/state/${encodeURIComponent(state.collection)}`\n const request = state.editing\n ? api(\"PUT\", `${path}/${encodeURIComponent(id)}`, { value })\n : api(\"POST\", path, { id: id || undefined, value })\n request\n .then(() => {\n editor.close()\n return renderState()\n })\n .catch(showError)\n })\n editorDelete.addEventListener(\"click\", () => {\n const id = state.editing\n if (!id) return\n api(\"DELETE\", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`)\n .then(() => {\n editor.close()\n return renderState()\n })\n .catch(showError)\n })\n\n for (const button of document.querySelectorAll(\"[data-advance]\")) {\n if (!(button instanceof HTMLButtonElement)) continue\n button.addEventListener(\"click\", () => {\n const raw = button.dataset.advance\n if (raw === undefined) return\n api(\"POST\", \"/clock\", { advance: Number(raw) })\n .then(() => renderClock())\n .catch(showError)\n })\n }\n el(\"freeze\", HTMLButtonElement).addEventListener(\"click\", () => {\n const frozen = el(\"freeze\", HTMLButtonElement).dataset.frozen === \"1\"\n api(\"POST\", \"/clock\", { freeze: !frozen })\n .then(() => renderClock())\n .catch(showError)\n })\n el(\"clock-reset\", HTMLButtonElement).addEventListener(\"click\", () => {\n api(\"POST\", \"/clock\", { reset: true })\n .then(() => renderClock())\n .catch(showError)\n })\n el(\"clock-set\", HTMLFormElement).addEventListener(\"submit\", (event) => {\n event.preventDefault()\n const raw = el(\"clock-instant\", HTMLInputElement).value.trim()\n const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw\n api(\"POST\", \"/clock\", { set })\n .then(() => renderClock())\n .catch(showError)\n })\n\n el(\"fault-form\", HTMLFormElement).addEventListener(\"submit\", (event) => {\n event.preventDefault()\n const preset = el(\"fault-preset\", HTMLSelectElement).value\n if (preset !== \"\") {\n api(\"POST\", \"/faults\", { preset })\n .then(() => renderFaults())\n .catch(showError)\n return\n }\n const status = Number(el(\"fault-status\", HTMLInputElement).value)\n if (!Number.isFinite(status)) {\n showError(new Error(\"Status must be a number, or choose a preset\"))\n return\n }\n const path = el(\"fault-path\", HTMLInputElement).value\n const method = el(\"fault-method\", HTMLInputElement).value\n api(\"POST\", \"/faults\", {\n status,\n ...(path !== \"\" ? { pathPrefix: path } : {}),\n ...(method !== \"\" ? { method } : {}),\n })\n .then(() => renderFaults())\n .catch(showError)\n })\n el(\"fault-clear\", HTMLButtonElement).addEventListener(\"click\", () => {\n api(\"DELETE\", \"/faults\")\n .then(() => renderFaults())\n .catch(showError)\n })\n el(\"journal-clear\", HTMLButtonElement).addEventListener(\"click\", () => {\n api(\"DELETE\", \"/requests\")\n .then(() => renderJournal())\n .catch(showError)\n })\n\n el(\"route-list\", HTMLElement).addEventListener(\"click\", (event) => {\n const target = event.target\n if (!(target instanceof Element)) return\n const button = target.closest(\"[data-route]\")\n if (!(button instanceof HTMLElement)) return\n const route = button.dataset.route\n if (route === undefined) return\n state.route = route\n el(\"route-title\", HTMLElement).textContent = route\n const method = route.split(\" \")[0] ?? \"\"\n el(\"route-body\", HTMLTextAreaElement).disabled = method === \"GET\" || method === \"DELETE\"\n })\n el(\"route-form\", HTMLFormElement).addEventListener(\"submit\", (event) => {\n event.preventDefault()\n const send = async (): Promise<void> => {\n if (state.route === null) throw new Error(\"Choose a route first\")\n const parts = state.route.split(\" \")\n const method = parts[0]\n const path = parts.slice(1).join(\" \")\n if (method === undefined) throw new Error(\"Choose a route first\")\n const concrete = path.replace(\n /:([A-Za-z0-9_]+)/g,\n (_match, key: string) => prompt(`Value for ${key}`) || \"\",\n )\n let body: unknown\n const routeBody = el(\"route-body\", HTMLTextAreaElement)\n if (method !== \"GET\" && method !== \"DELETE\" && routeBody.value.trim() !== \"\") {\n try {\n body = readJson(routeBody.value)\n } catch {\n throw new Error(\"Body is not JSON\")\n }\n }\n const data = await api(method, concrete, body)\n el(\"route-result\", HTMLElement).textContent = JSON.stringify(data, null, 2)\n }\n send().catch(showError)\n })\n\n type Panel = { id: string; title: string; description: string; html: string; script?: string }\n const decodePanel = (value: unknown): Panel | undefined => {\n if (!isRecord(value) || typeof value.id !== \"string\" || typeof value.title !== \"string\") {\n return undefined\n }\n const panel: Panel = {\n id: value.id,\n title: value.title,\n description: typeof value.description === \"string\" ? value.description : \"\",\n html: typeof value.html === \"string\" ? value.html : \"\",\n }\n if (typeof value.script === \"string\") panel.script = value.script\n return panel\n }\n const mountPanels = (panels: readonly Panel[]): void => {\n const nav = el(\"nav\", HTMLElement)\n const views = el(\"views\", HTMLElement)\n for (const panel of panels) {\n const button = document.createElement(\"button\")\n button.type = \"button\"\n button.dataset.view = panel.id\n button.textContent = panel.title\n nav.append(button)\n const section = document.createElement(\"section\")\n section.className = \"view\"\n section.id = `view-${panel.id}`\n section.hidden = true\n const title = document.createElement(\"h2\")\n title.textContent = panel.title\n const lede = document.createElement(\"p\")\n lede.className = \"lede\"\n lede.textContent = panel.description\n const body = document.createElement(\"div\")\n body.className = \"panel-body\"\n body.id = `panel-${panel.id}`\n body.innerHTML = panel.html\n section.append(title, lede, body)\n views.append(section)\n if (panel.script === undefined) continue\n try {\n const compiled: unknown = new Function(\"root\", \"api\", panel.script)\n if (!isPanelScript(compiled)) throw new Error(\"panel script did not compile\")\n compiled(body, panelApi)\n } catch (error) {\n const note = document.createElement(\"p\")\n note.className = \"banner show\"\n note.textContent = error instanceof Error ? error.message : String(error)\n body.append(note)\n }\n }\n }\n\n startAdminBrand({\n document,\n $: (id) => document.getElementById(id),\n params,\n location: { href: location.href, origin: location.origin },\n fetch,\n brandsUrl: config.brandsUrl,\n })\n loadNamespaces()\n .then(() => api(\"GET\", \"/ui/manifest\"))\n .then((manifest) => {\n const panels = requireList(\n isRecord(manifest) ? manifest.panels : undefined,\n \"Panels\",\n ).flatMap((panel) => {\n const decoded = decodePanel(panel)\n return decoded === undefined ? [] : [decoded]\n })\n mountPanels(panels)\n return refresh()\n })\n .catch(showError)\n}\n\nconst clientPrelude = [isRecord, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin]\n .map((fn) => fn.toString())\n .join(\"\\n\")\n\n/** The `<script>` embedded in the admin document, typechecked as {@link bootAdmin}. */\nexport const adminClientSource = (config: AdminBootConfig): string => {\n const payload = JSON.stringify(config).replace(/</g, \"\\\\u003c\")\n return `<script>\\n${clientPrelude}\\nbootAdmin(${payload});\\n</script>`\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Clock, ClockState } from \"./clock.js\"\nimport type { CredentialRegistry } from \"./credentials.js\"\nimport type { FaultRegistry, FaultRule } from \"./faults.js\"\nimport type { Journal } from \"./journal.js\"\nimport type { Metrics } from \"./metrics.js\"\nimport type { Rng } from \"./rng.js\"\nimport type { NamespaceSnapshot } from \"./snapshot.js\"\nimport type { StateView } from \"./state-view.js\"\n\n/**\n * What every mock can be called with. A service may accept more fields \u2014 accounts,\n * catalogs, webhook endpoints \u2014 and those stay optional so `createRuntime()` and\n * `createRuntime({ seed, adminKey })` work everywhere.\n */\nexport type MockCreateOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: number | string\n adminKey?: string\n}\n\n/** A checkpoint head the admin client can show. Services may return a richer object. */\nexport type MockCheckpoint = {\n readonly id: string\n readonly branch: string\n readonly parent: string | null\n readonly at: number\n}\n\n/** The instance behind one namespace. Vendor methods sit beside these, not instead of them. */\nexport type MockInstanceSurface = {\n fetch(request: Request): Promise<Response>\n reset(): Promise<void>\n}\n\n/**\n * The interface every mock runtime implements.\n *\n * Assignability is one way: a service may add methods (`tick`, a typed webhook hub,\n * account directories) and narrower property types. Removing or renaming a member\n * fails the typecheck. The HTTP control plane (`/health`, `/__admin/*`) is the same\n * contract on the wire; {@link STANDARD_ADMIN_ROUTES} is that list.\n */\nexport type MockSurface = {\n readonly name: string\n fetch(request: Request): Promise<Response>\n readonly clock: Clock\n readonly faults: FaultRegistry\n readonly metrics: Metrics\n readonly journal: Journal\n readonly rng: Rng\n readonly credentials: CredentialRegistry\n /** Present on every runtime. `undefined` when the service has no outbound webhooks. */\n readonly webhooks: unknown\n applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[]\n instance(namespace?: string): MockInstanceSurface\n namespaces(): string[]\n reset(namespace?: string): Promise<void>\n snapshot(namespace?: string): NamespaceSnapshot\n restore(snapshot: NamespaceSnapshot, namespace?: string): void\n checkpoint(namespace?: string, branch?: string): MockCheckpoint\n branch(name: string, options?: { namespace?: string; at?: string }): MockCheckpoint\n checkout(checkpoint: string, options?: { namespace?: string; branch?: string }): void\n timeline(namespace?: string): {\n head(branch?: string): { readonly id: string } | undefined\n branches(): Readonly<Record<string, string>>\n }\n /** Collections in `namespace`, declared by the service and inferred from stored rows. */\n state(namespace?: string): StateView\n readonly sqlite: SqliteClient\n}\n\n/**\n * Keep a service's own runtime type while proving it is a {@link MockSurface}.\n * Extra members stay. A missing member is a type error at the definition.\n */\nexport const defineMock = <T extends MockSurface>(runtime: T): T => runtime\n\n/** Clock state is part of the surface so admin clients can render it without a cast. */\nexport type MockClockState = ClockState\n\n/**\n * Admin routes every mock answers. A service adds its own keys beside these.\n * A key in this list keeps the shared handler, so the state API and the admin UI\n * stay the same when a service also ships vendor-specific controls.\n */\nexport const STANDARD_ADMIN_ROUTES = [\n \"GET /\",\n \"POST /reset\",\n \"GET /namespaces\",\n \"GET /clock\",\n \"POST /clock\",\n \"GET /faults\",\n \"POST /faults\",\n \"DELETE /faults\",\n \"POST /snapshots\",\n \"POST /snapshots/:id/restore\",\n \"DELETE /snapshots/:id\",\n \"GET /timeline\",\n \"POST /checkpoints\",\n \"POST /branches/:name\",\n \"POST /branches/:name/checkout\",\n \"GET /requests\",\n \"DELETE /requests\",\n \"GET /metrics\",\n \"DELETE /metrics\",\n \"GET /credentials\",\n \"PUT /credentials\",\n \"DELETE /credentials\",\n \"GET /state\",\n \"GET /state/:collection\",\n \"GET /state/:collection/:id\",\n \"POST /state/:collection\",\n \"PUT /state/:collection/:id\",\n \"PATCH /state/:collection/:id\",\n \"DELETE /state/:collection/:id\",\n \"GET /ui\",\n \"GET /ui/\",\n \"GET /ui/manifest\",\n] as const\n\nexport type StandardAdminRoute = (typeof STANDARD_ADMIN_ROUTES)[number]\n\n/** A panel the default admin shell mounts after the shared views. */\nexport type AdminPanel = {\n /** DOM id suffix. Lowercase letters, digits, and hyphens. */\n id: string\n title: string\n description?: string\n /** Markup placed inside the panel body. The service author owns it. */\n html: string\n /**\n * Function body called as `(root, api) => void` once the shell has loaded.\n * `root` is the panel body. `api` is `{ get, send, namespace }` against `/__admin`.\n */\n script?: string\n}\n\n/**\n * How a service customizes the admin UI without leaving the shared shell.\n * `panels` add views. `render` replaces the document and can call `defaultHtml()`\n * to wrap the shared shell instead of discarding it.\n */\nexport type AdminUi = {\n panels?: readonly AdminPanel[]\n render?: (input: { service: string; defaultHtml: () => string }) => string\n}\n\nconst PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/\n\n/** Reject a panel id the shell cannot mount. Called when the runtime is created. */\nexport const assertAdminUi = (ui: AdminUi | undefined): void => {\n if (!ui?.panels) return\n const seen = new Set<string>()\n for (const panel of ui.panels) {\n if (!PANEL_ID.test(panel.id)) {\n throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`)\n }\n if (seen.has(panel.id)) throw new RangeError(`duplicate admin panel id ${panel.id}`)\n seen.add(panel.id)\n if (panel.title.trim() === \"\") throw new RangeError(`admin panel ${panel.id} needs a title`)\n }\n}\n", "import { CSS_RESET } from \"@crvouga/mockingbird-ui\"\nimport { adminClientSource } from \"./admin-client.js\"\nimport type { AdminRoutes } from \"./control.js\"\nimport { ADMIN_KEY_HEADER, ADMIN_PREFIX } from \"./control.js\"\nimport type { AdminUi } from \"./surface.js\"\nimport { STANDARD_ADMIN_ROUTES } from \"./surface.js\"\n\nconst escapeHtml = (value: string): string =>\n value.replace(/[&<>\"']/g, (char) => {\n switch (char) {\n case \"&\":\n return \"&\"\n case \"<\":\n return \"<\"\n case \">\":\n return \">\"\n case '\"':\n return \""\"\n default:\n return \"'\"\n }\n })\n\n/**\n * Docs-site record of each service's logo, website, vendor API reference, and guide.\n * This address is the only brand data in the bundle. The payload is fetched when the\n * page opens, so a docs deploy updates every already-published admin.\n * `?brands=` may name a localhost or same-origin copy of that JSON.\n */\nexport const ADMIN_BRANDS_URL = \"https://mockingbird.chrisvouga.dev/brands.json\"\n\n/**\n * The default admin document. It talks only to `/__admin/*`, so every mock can serve it.\n * Bespoke panels arrive later from `GET /ui/manifest`, which stays behind the admin key.\n * The header chip is filled from {@link ADMIN_BRANDS_URL}; nothing about a vendor is inlined.\n */\nexport const renderAdminDocument = (service: string): string => {\n const name = escapeHtml(service)\n const script = adminClientSource({\n standardRoutes: STANDARD_ADMIN_ROUTES,\n adminPrefix: ADMIN_PREFIX,\n adminKeyHeader: ADMIN_KEY_HEADER,\n brandsUrl: ADMIN_BRANDS_URL,\n service,\n })\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta name=\"color-scheme\" content=\"light dark\">\n<link rel=\"icon\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='2' fill='%2327272a'/%3E%3C/svg%3E\">\n<title>${name} admin</title>\n<style>\n ${CSS_RESET}\n :root {\n color-scheme: light;\n --bg: #fafafa;\n --bg-elev: #ffffff;\n --bg-muted: #f4f4f5;\n --bg-inset: #f4f4f5;\n --line: #dedee3;\n --line-strong: #c4c4cc;\n --ink: #18181b;\n --muted: #62626b;\n --faint: #71717a;\n --accent: #27272a;\n --accent-ink: #ffffff;\n --accent-soft: #f4f4f5;\n --ok: #166534;\n --ok-soft: #f0fdf4;\n --warn: #a16207;\n --warn-soft: #fefce8;\n --err: #a82d32;\n --err-soft: #fef2f2;\n --shadow: none;\n --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --mono: ui-monospace, \"SF Mono\", SFMono-Regular, Menlo, Consolas, monospace;\n --radius: 10px;\n --header: 56px;\n --nav: 200px;\n }\n :root[data-theme=\"dark\"] {\n color-scheme: dark;\n --bg: #111113;\n --bg-elev: #19191c;\n --bg-muted: #242428;\n --bg-inset: #111113;\n --line: #36363c;\n --line-strong: #52525b;\n --ink: #f4f4f5;\n --muted: #a9a9b2;\n --faint: #71717a;\n --accent: #e4e4e7;\n --accent-ink: #18181b;\n --accent-soft: #242428;\n --ok: #86efac;\n --ok-soft: #14241b;\n --warn: #fde68a;\n --warn-soft: #2a2410;\n --err: #ffaaaa;\n --err-soft: #2c1516;\n --shadow: none;\n }\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n color-scheme: dark;\n --bg: #111113;\n --bg-elev: #19191c;\n --bg-muted: #242428;\n --bg-inset: #111113;\n --line: #36363c;\n --line-strong: #52525b;\n --ink: #f4f4f5;\n --muted: #a9a9b2;\n --faint: #71717a;\n --accent: #e4e4e7;\n --accent-ink: #18181b;\n --accent-soft: #242428;\n --ok: #86efac;\n --ok-soft: #14241b;\n --warn: #fde68a;\n --warn-soft: #2a2410;\n --err: #ffaaaa;\n --err-soft: #2c1516;\n --shadow: none;\n }\n }\n /* Fill the viewport, then grow with the content so the background covers the scroll. */\n html { height: 100%; }\n body {\n margin: 0;\n min-height: 100%;\n display: flex;\n flex-direction: column;\n font-family: var(--sans);\n background: var(--bg);\n color: var(--ink);\n line-height: 1.45;\n padding-left: env(safe-area-inset-left);\n padding-right: env(safe-area-inset-right);\n -webkit-text-size-adjust: 100%;\n }\n :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }\n .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }\n header.top {\n position: sticky; top: 0; z-index: 5;\n display: flex; align-items: center; gap: 12px;\n min-height: var(--header); padding: 10px 16px;\n background: var(--bg-elev);\n border-bottom: 1px solid var(--line);\n min-width: 0; max-width: 100%;\n }\n .brand {\n display: flex; flex-flow: row wrap; align-items: center; gap: 14px;\n min-width: 0; max-width: 100%; margin-right: auto;\n }\n .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }\n .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }\n .brand-id span { color: var(--faint); font-size: 12px; }\n .vendor {\n display: flex; flex-wrap: wrap; align-items: center; gap: 6px;\n min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);\n }\n .vendor[hidden] { display: none; }\n /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */\n .vendor img {\n width: 16px; height: 16px; padding: 2px; box-sizing: content-box;\n border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;\n }\n .vendor-name { color: var(--ink); font-weight: 600; }\n .vendor-sep { color: var(--faint); }\n .vendor-link { color: inherit; text-decoration: none; }\n .vendor-link:hover { color: var(--ink); text-decoration: underline; }\n .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }\n label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }\n label.field input, label.field select, .controls input[type=\"password\"] {\n background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;\n padding: 7px 8px; min-height: 36px;\n }\n .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {\n border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);\n background: var(--bg-elev);\n }\n .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }\n .btn-quiet { background: transparent; }\n .btn-danger { color: var(--err); }\n /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long\n record or the full nav row would widen the page past the viewport. */\n .layout {\n display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);\n flex: 1 0 auto; min-width: 0;\n }\n nav.side {\n border-right: 1px solid var(--line); padding: 12px;\n display: flex; flex-direction: column; gap: 4px;\n background: var(--bg-elev);\n }\n nav.side button {\n text-align: left; border: 0; background: transparent; border-radius: 9px;\n padding: 9px 10px; min-height: 40px; color: var(--muted);\n }\n nav.side button[aria-current=\"true\"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }\n main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }\n .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }\n .lede { margin: 0 0 16px; color: var(--muted); }\n .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: 12px; }\n .card {\n background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);\n padding: 14px 16px; box-shadow: var(--shadow);\n }\n .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }\n .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }\n .card .v .clock-time { font-size: 14px; color: var(--muted); }\n .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }\n .collection {\n width: 100%; text-align: left; border: 1px solid transparent; background: transparent;\n border-radius: 10px; padding: 8px 10px; min-height: 44px;\n }\n .collection[aria-current=\"true\"] { background: var(--bg-elev); border-color: var(--line); }\n .collection small { display: block; color: var(--faint); }\n .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }\n .chip {\n font-family: var(--mono); font-size: 12px; background: var(--bg-muted);\n border-radius: 999px; padding: 4px 8px;\n }\n .chip i { color: var(--faint); font-style: normal; }\n table { width: 100%; border-collapse: collapse; font-size: 14px; }\n th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }\n th { color: var(--faint); font-weight: 600; font-size: 12px; }\n tr.clickable { cursor: pointer; }\n tr.clickable:hover { background: var(--bg-muted); }\n pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }\n pre {\n margin: 0; white-space: pre-wrap; word-break: break-word;\n background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;\n }\n .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }\n .banner {\n display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;\n background: var(--err-soft); color: var(--err);\n }\n .banner.show { display: block; }\n .empty { color: var(--muted); padding: 24px 8px; }\n dialog {\n border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);\n color: var(--ink); width: min(640px, calc(100% - 24px)); max-width: calc(100vw - 24px); box-shadow: none;\n }\n dialog::backdrop { background: rgb(20 19 17 / 0.45); }\n dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }\n textarea {\n width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;\n border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;\n font-family: var(--mono); font-size: 12px;\n }\n .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }\n .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }\n .badge.ok { background: var(--ok-soft); color: var(--ok); }\n .badge.warn { background: var(--warn-soft); color: var(--warn); }\n .status-2 { color: var(--ok); }\n .status-4, .status-5, .status-0 { color: var(--err); }\n .stack { display: flex; flex-direction: column; gap: 12px; }\n .route {\n display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;\n padding: 8px 0; border-bottom: 1px solid var(--line);\n }\n .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }\n @media (max-width: 800px) {\n header.top {\n align-items: stretch; flex-direction: column;\n padding-top: max(10px, env(safe-area-inset-top));\n }\n input, select, textarea { font-size: 16px; }\n .brand, .vendor, .controls { width: 100%; }\n label.field, label.field select, label.field input { flex: 1; min-width: 0; }\n .layout { grid-template-columns: minmax(0, 1fr); }\n nav.side {\n flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;\n border-right: 0; border-bottom: 1px solid var(--line);\n padding: 8px;\n }\n nav.side button { white-space: nowrap; flex: none; }\n .split { grid-template-columns: minmax(0, 1fr); }\n main { padding: 14px; }\n table, thead, tbody, tr, th, td { display: block; }\n thead { display: none; }\n tr {\n border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;\n background: var(--bg-elev); min-width: 0;\n }\n td {\n border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;\n min-width: 0; overflow-wrap: anywhere;\n }\n td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }\n .route { grid-template-columns: 72px 1fr; }\n .route button { grid-column: 1 / -1; }\n }\n</style>\n</head>\n<body>\n<div class=\"app\" data-service=\"${name}\" data-mockingbird-admin>\n <header class=\"top\">\n <div class=\"brand\">\n <div class=\"brand-id\">\n <strong>${name}</strong>\n <span>Admin</span>\n </div>\n <div class=\"vendor\" id=\"vendor\" hidden></div>\n </div>\n <div class=\"controls\">\n <label class=\"field\">Namespace\n <select id=\"namespace\" aria-label=\"Namespace\"></select>\n </label>\n <label class=\"field\">Admin key\n <input id=\"admin-key\" type=\"password\" autocomplete=\"off\" spellcheck=\"false\" aria-label=\"Admin key\">\n </label>\n <button class=\"icon-btn\" id=\"theme\" type=\"button\" aria-label=\"Toggle color theme\">Theme</button>\n <button class=\"btn\" id=\"refresh\" type=\"button\">Refresh</button>\n </div>\n </header>\n <div class=\"layout\">\n <nav class=\"side\" id=\"nav\" aria-label=\"Admin sections\">\n <button type=\"button\" data-view=\"overview\" aria-current=\"true\">Overview</button>\n <button type=\"button\" data-view=\"state\">State</button>\n <button type=\"button\" data-view=\"clock\">Clock</button>\n <button type=\"button\" data-view=\"faults\">Faults</button>\n <button type=\"button\" data-view=\"journal\">Journal</button>\n <button type=\"button\" data-view=\"routes\">Routes</button>\n </nav>\n <main id=\"views\">\n <p class=\"banner\" id=\"banner\" role=\"alert\"></p>\n <section class=\"view\" id=\"view-overview\">\n <h2>Overview</h2>\n <p class=\"lede\">Health, clock, and the collections this namespace is holding.</p>\n <div class=\"grid\" id=\"overview-cards\"></div>\n <h3>Recent requests</h3>\n <div id=\"overview-requests\"></div>\n </section>\n <section class=\"view\" id=\"view-state\" hidden>\n <h2>State</h2>\n <p class=\"lede\">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>\n <div class=\"split\">\n <div id=\"collections\"></div>\n <div>\n <div id=\"schema\"></div>\n <div class=\"row-actions\">\n <button class=\"btn-primary\" id=\"new-record\" type=\"button\">New record</button>\n </div>\n <div id=\"records\"></div>\n </div>\n </div>\n </section>\n <section class=\"view\" id=\"view-clock\" hidden>\n <h2>Clock</h2>\n <p class=\"lede\">The clock every timestamp in this mock reads.</p>\n <div class=\"card\" id=\"clock-readout\"></div>\n <div class=\"row-actions\">\n <button class=\"btn\" type=\"button\" data-advance=\"60000\">+1m</button>\n <button class=\"btn\" type=\"button\" data-advance=\"900000\">+15m</button>\n <button class=\"btn\" type=\"button\" data-advance=\"3600000\">+1h</button>\n <button class=\"btn\" type=\"button\" data-advance=\"86400000\">+1d</button>\n <button class=\"btn\" type=\"button\" data-advance=\"-3600000\">\u22121h</button>\n <button class=\"btn\" id=\"freeze\" type=\"button\">Freeze</button>\n <button class=\"btn-quiet\" id=\"clock-reset\" type=\"button\">Reset</button>\n </div>\n <form id=\"clock-set\" class=\"row-actions\">\n <label class=\"field\">Set instant\n <input id=\"clock-instant\" type=\"text\" placeholder=\"2026-01-01T00:00:00Z or epoch ms\" size=\"32\">\n </label>\n <button class=\"btn-primary\" type=\"submit\">Set</button>\n </form>\n </section>\n <section class=\"view\" id=\"view-faults\" hidden>\n <h2>Faults</h2>\n <p class=\"lede\">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>\n <form id=\"fault-form\" class=\"card stack\">\n <label class=\"field\">Preset\n <select id=\"fault-preset\"><option value=\"\">Custom rule</option></select>\n </label>\n <label class=\"field\">Status\n <input id=\"fault-status\" inputmode=\"numeric\" placeholder=\"503\">\n </label>\n <label class=\"field\">Path prefix\n <input id=\"fault-path\" placeholder=\"/v1\">\n </label>\n <label class=\"field\">Method\n <input id=\"fault-method\" placeholder=\"GET\">\n </label>\n <div class=\"dialog-actions\">\n <button class=\"btn-primary\" type=\"submit\">Add fault</button>\n <button class=\"btn-danger\" id=\"fault-clear\" type=\"button\">Clear all</button>\n </div>\n </form>\n <div id=\"fault-list\"></div>\n </section>\n <section class=\"view\" id=\"view-journal\" hidden>\n <h2>Journal</h2>\n <p class=\"lede\">Requests this namespace has seen. Bodies are not stored.</p>\n <div class=\"row-actions\">\n <button class=\"btn-danger\" id=\"journal-clear\" type=\"button\">Clear journal</button>\n </div>\n <div id=\"journal\"></div>\n </section>\n <section class=\"view\" id=\"view-routes\" hidden>\n <h2>Routes</h2>\n <p class=\"lede\">Shared controls, plus any routes this mock adds. Extra routes are how a bespoke workflow shows up beside the default UI.</p>\n <div id=\"route-list\"></div>\n <form id=\"route-form\" class=\"card stack\">\n <strong id=\"route-title\">Select a route</strong>\n <label class=\"field\">JSON body\n <textarea id=\"route-body\" placeholder=\"{ }\"></textarea>\n </label>\n <div class=\"dialog-actions\">\n <button class=\"btn-primary\" type=\"submit\">Send</button>\n </div>\n <pre id=\"route-result\">Response will show here.</pre>\n </form>\n </section>\n </main>\n </div>\n</div>\n<dialog id=\"editor\">\n <form method=\"dialog\" id=\"editor-form\">\n <strong id=\"editor-title\">Record</strong>\n <label class=\"field\">Id\n <input id=\"editor-id\" required>\n </label>\n <label class=\"field\">JSON value\n <textarea id=\"editor-value\"></textarea>\n </label>\n <div class=\"dialog-actions\">\n <button class=\"btn-danger\" id=\"editor-delete\" type=\"button\" value=\"delete\">Delete</button>\n <button class=\"btn-quiet\" type=\"submit\" value=\"cancel\">Cancel</button>\n <button class=\"btn-primary\" type=\"submit\" value=\"save\">Save</button>\n </div>\n </form>\n</dialog>\n${script}\n</body>\n</html>`\n}\n\nconst htmlResponse = (body: string): Response =>\n new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n })\n\nconst json = (body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status: 200,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n })\n\n/** `GET /__admin/ui` plus the manifest a bespoke panel list is read from. */\nexport const adminUiRoutes = (service: string, ui: AdminUi | undefined): AdminRoutes => {\n const shell = () => renderAdminDocument(service)\n const document = () => (ui?.render ? ui.render({ service, defaultHtml: shell }) : shell())\n return {\n \"GET /ui\": () => htmlResponse(document()),\n \"GET /ui/\": () => htmlResponse(document()),\n \"GET /ui/manifest\": () =>\n json({\n service,\n panels: (ui?.panels ?? []).map((panel) => ({\n id: panel.id,\n title: panel.title,\n ...(panel.description !== undefined ? { description: panel.description } : {}),\n html: panel.html,\n ...(panel.script !== undefined ? { script: panel.script } : {}),\n })),\n }),\n }\n}\n", "/**\n * Mockingbird's OpenAPI extensions. They are deliberately generic: nothing here knows about any\n * particular provider. Provider specifics live in each provider's `openapi.yaml`.\n */\n\n/** `x-mockingbird` on an operation. */\nexport type OperationExtension = {\n /** `false` marks an operation the mock explicitly does not implement. Default `true`. */\n supported?: boolean\n /** Human explanation, required when `supported: false` or `parity.enabled: false`. */\n reason?: string\n parity?: {\n /** Whether the differential runner generates this operation. Defaults to `supported`. */\n enabled?: boolean\n /** `false` for operations that must never hit a real account (destructive, billing\u2026). Default `true`. */\n safe?: boolean\n reason?: string\n }\n}\n\nexport type OperationMetadata = {\n supported: boolean\n reason: string | undefined\n parity: { enabled: boolean; safe: boolean; reason: string | undefined }\n}\n\n/** `x-mockingbird-resource`: this string value is the identity of a resource. */\nexport type ResourceIdentityExtension = { type: string; identity: true }\n\n/** `x-mockingbird-resource-ref`: this value must reference an existing resource of `type`. */\nexport type ResourceRefExtension = {\n type: string\n /** A well-formed id that does not exist, used to exercise not-found behaviour. */\n missing?: string\n}\n\nexport const VOLATILE_KINDS = [\"id\", \"timestamp\", \"token\", \"url\", \"account\", \"opaque\"] as const\nexport type VolatileKind = (typeof VOLATILE_KINDS)[number]\n\n/** `x-mockingbird-volatile`: nondeterministic on the real side; compared by shape only. */\nexport type VolatileExtension = { kind: VolatileKind }\n\nexport const SCOPE_VALUES = [\"run-id\", \"walk-start-unix\", \"walk-start-iso\"] as const\nexport type ScopeValue = (typeof SCOPE_VALUES)[number]\n\n/** `x-mockingbird-scope`: always generate this run-scoped value instead of a random one. */\nexport type ScopeExtension = { value: ScopeValue }\n\n/** `x-mockingbird-unsupported`: the mock does not implement this parameter/property. */\nexport type UnsupportedExtension = true | { reason?: string }\n\nexport type SchemaMetadata = {\n resource: ResourceIdentityExtension | undefined\n resourceRef: ResourceRefExtension | undefined\n volatile: VolatileExtension | undefined\n scope: ScopeExtension | undefined\n unsupported: { reason: string | undefined } | undefined\n}\n\nexport const EXTENSION_KEYS = {\n operation: \"x-mockingbird\",\n resource: \"x-mockingbird-resource\",\n resourceRef: \"x-mockingbird-resource-ref\",\n volatile: \"x-mockingbird-volatile\",\n scope: \"x-mockingbird-scope\",\n unsupported: \"x-mockingbird-unsupported\",\n parityHeader: \"x-mockingbird-parity-header\",\n} as const\n", "import type {\n HeaderObject,\n OpenAPIDocument,\n OperationObject,\n ParameterObject,\n ResponseObject,\n SchemaObject,\n} from \"@crvouga/mockingbird-openapi\"\nimport { deref, resolveSchema } from \"@crvouga/mockingbird-openapi\"\nimport {\n EXTENSION_KEYS,\n type OperationExtension,\n type OperationMetadata,\n SCOPE_VALUES,\n type SchemaMetadata,\n VOLATILE_KINDS,\n} from \"./types.js\"\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst extensionOf = (holder: object, key: string): unknown =>\n (holder as Record<string, unknown>)[key]\n\n/** Read `x-mockingbird` from an operation, applying defaults. */\nexport const operationMetadata = (operation: OperationObject): OperationMetadata => {\n const raw = extensionOf(operation, EXTENSION_KEYS.operation)\n const ext: OperationExtension = isRecord(raw) ? (raw as OperationExtension) : {}\n const supported = ext.supported ?? true\n const parity = ext.parity ?? {}\n return {\n supported,\n reason: typeof ext.reason === \"string\" ? ext.reason : undefined,\n parity: {\n enabled: supported && (parity.enabled ?? true),\n safe: parity.safe ?? true,\n reason: typeof parity.reason === \"string\" ? parity.reason : undefined,\n },\n }\n}\n\nconst readResource = (raw: unknown): SchemaMetadata[\"resource\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\" || raw.identity !== true) return undefined\n return { type: raw.type, identity: true }\n}\n\nconst readResourceRef = (raw: unknown): SchemaMetadata[\"resourceRef\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return undefined\n return { type: raw.type, ...(typeof raw.missing === \"string\" ? { missing: raw.missing } : {}) }\n}\n\nconst readVolatile = (raw: unknown): SchemaMetadata[\"volatile\"] => {\n if (!isRecord(raw) || typeof raw.kind !== \"string\") return undefined\n const kind = VOLATILE_KINDS.find((k) => k === raw.kind)\n return kind === undefined ? undefined : { kind }\n}\n\nconst readScope = (raw: unknown): SchemaMetadata[\"scope\"] => {\n if (!isRecord(raw) || typeof raw.value !== \"string\") return undefined\n const value = SCOPE_VALUES.find((v) => v === raw.value)\n return value === undefined ? undefined : { value }\n}\n\nconst readUnsupported = (raw: unknown): SchemaMetadata[\"unsupported\"] => {\n if (raw === true) return { reason: undefined }\n if (isRecord(raw)) return { reason: typeof raw.reason === \"string\" ? raw.reason : undefined }\n return undefined\n}\n\n/**\n * Read Mockingbird's schema-level extensions from a (resolved) schema or parameter.\n * Extensions on a `$ref` wrapper win over the target's, matching {@link resolveSchema}.\n */\nexport const schemaMetadata = (holder: SchemaObject | ParameterObject): SchemaMetadata => ({\n resource: readResource(extensionOf(holder, EXTENSION_KEYS.resource)),\n resourceRef: readResourceRef(extensionOf(holder, EXTENSION_KEYS.resourceRef)),\n volatile: readVolatile(extensionOf(holder, EXTENSION_KEYS.volatile)),\n scope: readScope(extensionOf(holder, EXTENSION_KEYS.scope)),\n unsupported: readUnsupported(extensionOf(holder, EXTENSION_KEYS.unsupported)),\n})\n\n/** Metadata of a parameter: extensions on the parameter itself win over its schema's. */\nexport const parameterMetadata = (\n document: OpenAPIDocument,\n parameter: ParameterObject,\n): SchemaMetadata => {\n const own = schemaMetadata(parameter)\n const fromSchema = parameter.schema\n ? schemaMetadata(resolveSchema(document, parameter.schema))\n : undefined\n return {\n resource: own.resource ?? fromSchema?.resource,\n resourceRef: own.resourceRef ?? fromSchema?.resourceRef,\n volatile: own.volatile ?? fromSchema?.volatile,\n scope: own.scope ?? fromSchema?.scope,\n unsupported: own.unsupported ?? fromSchema?.unsupported,\n }\n}\n\n/** Lower-cased names of response headers flagged with `x-mockingbird-parity-header: true`. */\nexport const parityHeaders = (document: OpenAPIDocument, response: ResponseObject): string[] => {\n const names: string[] = []\n for (const [name, raw] of Object.entries(response.headers ?? {})) {\n const header = deref<HeaderObject>(document, raw)\n if (extensionOf(header, EXTENSION_KEYS.parityHeader) === true) names.push(name.toLowerCase())\n }\n return names.sort()\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type DecodedBody,\n decodeFormPairs,\n type FormObject,\n readBody,\n} from \"@crvouga/mockingbird-http-codec\"\nimport { listOperations, type OpenAPIDocument, type Operation } from \"@crvouga/mockingbird-openapi\"\nimport { operationMetadata } from \"@crvouga/mockingbird-openapi-metadata\"\nimport {\n clearNamespace,\n migrateCore,\n resolveSqlite,\n type SqliteClient,\n} from \"@crvouga/mockingbird-sqlite\"\nimport { type Context, Hono } from \"hono\"\nimport { annotateResponse } from \"./journal.js\"\nimport { recordedIssues } from \"./validation.js\"\n\n/** A rejection carries the issues `bodyIssues` found, for the runtime's log entry. */\nconst withIssues = (request: Request, response: Response): Response => {\n const issues = response.status >= 400 ? recordedIssues(request) : undefined\n return issues && issues.length > 0 ? annotateResponse(response, { issues }) : response\n}\n\n/** Options every provider constructor accepts. */\nexport type APIOptions = {\n /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Clock used for `created`-style fields. Default `Date.now`. */\n now?: () => number\n /**\n * Storage namespace for this instance's records. Instances sharing one SQLite\n * client stay isolated when their namespaces differ. Defaults to the service name.\n */\n namespace?: string\n}\n\nexport type OperationContext = {\n request: Request\n url: URL\n /** Path parameters. */\n params: Record<string, string>\n /** Query string decoded with bracket notation (`created[gte]=1` -> `{ created: { gte: \"1\" } }`). */\n query: FormObject\n body: DecodedBody\n /** Shared SQLite client for this service (already migrated). */\n sqlite: SqliteClient\n /** Service namespace used for records / sequences. */\n namespace: string\n operation: Operation\n /** The vendor contract the service was built from. */\n document: OpenAPIDocument\n now: () => number\n}\n\nexport type OperationHandler = (context: OperationContext) => Promise<Response> | Response\n\nexport type OperationHandlers = Record<string, OperationHandler>\n\n/** Identity helper that keeps handler maps type-checked against a fixed set of operation ids. */\nexport const defineOperations = <Id extends string>(\n handlers: Record<Id, OperationHandler>,\n): Record<Id, OperationHandler> => handlers\n\nexport class OperationRegistryError extends Error {\n constructor(readonly problems: string[]) {\n super(`operation registry is inconsistent:\\n${problems.map((p) => ` - ${p}`).join(\"\\n\")}`)\n this.name = \"OperationRegistryError\"\n }\n}\n\n/**\n * Cross-check handlers against the document: every supported operation needs exactly one\n * handler, no handler may target an unknown or unsupported operation, no duplicate ids.\n */\nexport const verifyOperations = (\n document: OpenAPIDocument,\n handlers: OperationHandlers,\n): string[] => {\n const problems: string[] = []\n const operations = listOperations(document)\n const seen = new Set<string>()\n for (const operation of operations) {\n if (seen.has(operation.operationId))\n problems.push(`duplicate operationId ${operation.operationId}`)\n seen.add(operation.operationId)\n const supported = operationMetadata(operation.operation).supported\n const handler = handlers[operation.operationId]\n if (supported && !handler)\n problems.push(`supported operation ${operation.operationId} has no handler`)\n if (!supported && handler)\n problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`)\n }\n for (const id of Object.keys(handlers)) {\n if (!seen.has(id)) problems.push(`handler ${id} has no OpenAPI operation`)\n }\n return problems\n}\n\nexport type ServiceOptions = {\n document: OpenAPIDocument\n handlers: OperationHandlers\n sqlite: SqliteClient\n /** Namespace isolating this service's records and sequences. */\n namespace: string\n now?: (() => number) | undefined\n /** Response for paths/methods outside the contract. */\n notFound: (request: Request) => Response | Promise<Response>\n /** Response for operations declared but marked `supported: false`. Default: `notFound`. */\n unsupported?: (request: Request, operation: Operation) => Response | Promise<Response>\n /** Convert handler exceptions into a provider-shaped response. */\n onError: (error: unknown, request: Request) => Response | Promise<Response>\n /** Runs before every operation; return a Response to short-circuit (e.g. authentication). */\n before?: (context: OperationContext) => Promise<Response | undefined> | Response | undefined\n}\n\nexport type Service = FetchAPI & {\n app: Hono\n sqlite: SqliteClient\n namespace: string\n /** Delete every record and sequence in the service namespace. */\n reset(): Promise<void>\n}\n\nconst honoPath = (template: string) => template.replace(/\\{([^}]+)\\}/g, \":$1\")\n\n/** Static segments before parameters so `/v1/customers/search` beats `/v1/customers/:id`. */\nconst routeOrder = (a: Operation, b: Operation) => {\n const sa = a.path.split(\"/\")\n const sb = b.path.split(\"/\")\n for (let i = 0; i < Math.max(sa.length, sb.length); i++) {\n const x = sa[i] ?? \"\"\n const y = sb[i] ?? \"\"\n const px = x.startsWith(\"{\")\n const py = y.startsWith(\"{\")\n if (px !== py) return px ? 1 : -1\n if (x !== y) return x < y ? -1 : 1\n }\n return 0\n}\n\nconst queryOf = (url: URL): FormObject => decodeFormPairs(url.searchParams.entries())\n\n/**\n * Resolve optional `sqlite`, run core migrations, and return the ready client.\n * Call this from every provider constructor before building state.\n */\nexport const bootSqlite = (sqlite?: SqliteClient): SqliteClient => {\n const client = resolveSqlite(sqlite)\n migrateCore(client)\n return client\n}\n\n/** Build a Fetch-native service whose routes are exactly the document's operations. */\nexport const createService = (options: ServiceOptions): Service => {\n const problems = verifyOperations(options.document, options.handlers)\n if (problems.length > 0) throw new OperationRegistryError(problems)\n migrateCore(options.sqlite)\n const now = options.now ?? (() => Date.now())\n const app = new Hono()\n app.notFound((c) => options.notFound(c.req.raw))\n app.onError((error, c) => options.onError(error, c.req.raw))\n\n const operations = [...listOperations(options.document)].sort(routeOrder)\n for (const operation of operations) {\n const metadata = operationMetadata(operation.operation)\n const handler = options.handlers[operation.operationId]\n const route = async (c: Context) => {\n const request = c.req.raw\n if (!metadata.supported || !handler) {\n return options.unsupported\n ? options.unsupported(request, operation)\n : options.notFound(request)\n }\n const url = new URL(request.url)\n const context: OperationContext = {\n request,\n url,\n params: c.req.param(),\n query: queryOf(url),\n body: await readBody(request),\n sqlite: options.sqlite,\n namespace: options.namespace,\n operation,\n document: options.document,\n now,\n }\n const short = await options.before?.(context)\n return withIssues(request, short ?? (await handler(context)))\n }\n app.on(operation.method.toUpperCase(), honoPath(operation.path), route)\n }\n\n return {\n app,\n sqlite: options.sqlite,\n namespace: options.namespace,\n fetch: async (request) => app.fetch(request),\n reset: async () => {\n clearNamespace(options.sqlite, options.namespace)\n },\n }\n}\n", "import { mediaTypeOf } from \"@crvouga/mockingbird-http-codec\"\nimport {\n deref,\n resolveSchema,\n type SchemaObject,\n validateValue,\n} from \"@crvouga/mockingbird-openapi\"\nimport type { OperationContext } from \"./service.js\"\n\n/**\n * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).\n * `kind` is `media_type` when the body is present but its media type is not one the operation\n * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when\n * the operation needs a body and none arrived, and `schema` for a contract violation.\n */\nexport type BodyIssue = {\n path: string\n message: string\n kind?: \"media_type\" | \"syntax\" | \"required\" | \"schema\"\n}\n\n/** What the runtime records about a request the mock rejected: never the body itself. */\nexport type UnsupportedMediaType = {\n /** The request's media type (`text/plain`), or `null` when it sent no `content-type`. */\n mediaType: string | null\n /** The media types the operation's contract accepts, as written (`application/*+json`). */\n accepted: string[]\n}\n\ntype ResolvedRequestBody = {\n required?: boolean\n content?: Record<string, { schema?: SchemaObject }>\n}\n\nconst requestBodyOf = (context: OperationContext): ResolvedRequestBody | undefined => {\n const requestBody = context.operation.operation.requestBody\n return requestBody ? (deref(context.document, requestBody) as ResolvedRequestBody) : undefined\n}\n\n/** `application/*+json` accepts `application/vnd.api+json`; a star on both sides accepts anything. */\nconst mediaTypeMatches = (accepted: string, actual: string): boolean => {\n const pattern = mediaTypeOf(accepted) ?? accepted.toLowerCase()\n if (pattern === actual || pattern === \"*/*\") return true\n const [type, subtype] = pattern.split(\"/\")\n const [actualType, actualSubtype] = actual.split(\"/\")\n if (type !== actualType && type !== \"*\") return false\n if (subtype === undefined || subtype === \"*\") return true\n if (subtype.startsWith(\"*+\")) return actualSubtype?.endsWith(subtype.slice(1)) === true\n return false\n}\n\n/**\n * Which key of the operation's `requestBody.content` the request's `content-type` selects,\n * or undefined when none matches (or the operation declares no body).\n */\nconst acceptedKeyFor = (\n content: Record<string, unknown> | undefined,\n mediaType: string | undefined,\n): string | undefined => {\n if (!content || mediaType === undefined) return undefined\n const keys = Object.keys(content)\n return (\n keys.find((key) => mediaTypeOf(key) === mediaType) ??\n keys.find((key) => mediaTypeMatches(key, mediaType))\n )\n}\n\n/**\n * The reason a request body cannot be read by this operation: its `content-type` is missing\n * or names a media type the contract does not list. Undefined when the operation declares no\n * body, the media type is accepted, or the body is empty (unless `includeEmpty`: ASP.NET\n * Core picks the input formatter from the header before looking at the body, so even an\n * empty body with no `content-type` is 415 there). A JSON body sent as `text/plain` or with\n * no header is the common case: ASP.NET Core, Spring and Rails answer it `415`, and it must\n * never read as \"request body is required\".\n */\nexport const unsupportedMediaType = (\n context: OperationContext,\n options: { includeEmpty?: boolean } = {},\n): UnsupportedMediaType | undefined => {\n if (context.body.kind === \"empty\" && options.includeEmpty !== true) return undefined\n const content = requestBodyOf(context)?.content\n if (!content || Object.keys(content).length === 0) return undefined\n const mediaType = mediaTypeOf(context.request.headers.get(\"content-type\"))\n if (acceptedKeyFor(content, mediaType) !== undefined) return undefined\n return { mediaType: mediaType ?? null, accepted: Object.keys(content) }\n}\n\n/** Issues recorded per request, for the runtime's log entry of a rejected request. */\nconst recorded = new WeakMap<Request, BodyIssue[]>()\n\n/** The issues `bodyIssues` last found for a request, if any. */\nexport const recordedIssues = (request: Request): BodyIssue[] | undefined => recorded.get(request)\n\n/**\n * Validate the decoded body against the operation's `requestBody` schema in the vendor\n * contract, for the media type the request sent (or `contentType` when it sent none that the\n * contract lists). Returns `[]` when valid, or when the operation declares no such body.\n * Services turn the issues into the vendor's own validation error shape; a `media_type`\n * issue is a body the operation cannot read at all (see `unsupportedMediaType`).\n */\nexport const bodyIssues = (\n context: OperationContext,\n contentType = \"application/json\",\n): BodyIssue[] => {\n const issues = findBodyIssues(context, contentType)\n if (issues.length > 0) recorded.set(context.request, issues)\n return issues\n}\n\nconst findBodyIssues = (context: OperationContext, contentType: string): BodyIssue[] => {\n const resolved = requestBodyOf(context)\n if (!resolved) return []\n const unsupported = unsupportedMediaType(context)\n if (unsupported) {\n return [\n {\n path: \"\",\n kind: \"media_type\",\n message:\n unsupported.mediaType === null\n ? \"request body has no content-type\"\n : `request body media type ${unsupported.mediaType} is not supported`,\n },\n ]\n }\n const key =\n acceptedKeyFor(resolved.content, mediaTypeOf(context.request.headers.get(\"content-type\"))) ??\n contentType\n const schema = resolved.content?.[key]?.schema\n if (!schema) return []\n if (context.body.kind === \"invalid\") {\n return [\n {\n path: \"\",\n kind: \"syntax\",\n message: `request body is not valid ${context.body.mediaType}`,\n },\n ]\n }\n const value =\n context.body.kind === \"json\" || context.body.kind === \"form\" || context.body.kind === \"text\"\n ? context.body.value\n : undefined\n if (value === undefined) {\n return resolved.required && context.body.kind === \"empty\"\n ? [{ path: \"\", kind: \"required\", message: \"request body is required\" }]\n : []\n }\n return validateValue(context.document, resolveSchema(context.document, schema), value).map(\n (issue) => ({ path: issue.path.join(\".\"), kind: \"schema\", message: issue.message }),\n )\n}\n\n/** Issues grouped Laravel-style: `{ \"patient.email\": [\"\u2026\"] }`. */\nexport const issuesByField = (issues: BodyIssue[]): Record<string, string[]> => {\n const out: Record<string, string[]> = {}\n for (const issue of issues) {\n const missing = /^missing required property (.+)$/.exec(issue.message)\n const field = missing\n ? [issue.path, missing[1]].filter(Boolean).join(\".\")\n : issue.path || \"body\"\n const message = missing\n ? `The ${field} field is required.`\n : `The ${field} field ${issue.message}.`\n out[field] = [...(out[field] ?? []), message]\n }\n return out\n}\n", "import { Timeline } from \"@crvouga/mockingbird-core\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/**\n * A point-in-time copy of everything a service namespace holds.\n *\n * All service state lives in the two core tables keyed by namespace, so a snapshot\n * is generic: any service gets per-test rollback without knowing its own schema.\n * Restoring is much cheaper than rebuilding a namespace from a corpus.\n */\nexport type NamespaceSnapshot = {\n namespace: string\n records: { collection: string; id: string; seq: number; value: string }[]\n sequences: { name: string; kind: string; value: number }[]\n}\n\n/**\n * @deprecated Low-level Timeline payload capture retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const snapshotNamespace = (sqlite: SqliteClient, namespace: string): NamespaceSnapshot => ({\n namespace,\n records: sqlite\n .prepare(\n \"SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq\",\n )\n .all<{ collection: string; id: string; seq: number; value: string }>(namespace),\n sequences: sqlite\n .prepare(\n \"SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind\",\n )\n .all<{ name: string; kind: string; value: number }>(namespace),\n})\n\n/**\n * Replace a namespace's contents with `snapshot`. The namespace is emptied first,\n * so restoring is an assignment, not a merge \u2014 records created since the snapshot\n * are gone afterwards.\n *\n * @deprecated Low-level Timeline payload restore retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const restoreNamespace = (\n sqlite: SqliteClient,\n namespace: string,\n snapshot: NamespaceSnapshot,\n): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n const record = sqlite.prepare(\n \"INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)\",\n )\n for (const row of snapshot.records) {\n record.run(namespace, row.collection, row.id, row.seq, row.value)\n }\n const sequence = sqlite.prepare(\n \"INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)\",\n )\n for (const row of snapshot.sequences) {\n sequence.run(namespace, row.name, row.kind, row.value)\n }\n })\n}\n\n/**\n * Execute asynchronous service work atomically using the canonical Timeline rollback primitive.\n * This is the prescribed escape hatch when the SQLite adapter cannot hold a transaction across\n * `await`; service code should not coordinate raw namespace snapshots itself.\n */\nexport const withNamespaceRollback = async <T>(\n sqlite: SqliteClient,\n namespace: string,\n run: () => Promise<T>,\n): Promise<T> => {\n const rollback = new Timeline<NamespaceSnapshot>({ maxCheckpoints: 1 })\n const before = rollback.commit(snapshotNamespace(sqlite, namespace))\n try {\n return await run()\n } catch (error) {\n restoreNamespace(sqlite, namespace, before.value)\n throw error\n }\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { Collection } from \"./collection.js\"\nimport type { AdminRoutes } from \"./control.js\"\n\nexport const STATE_FIELD_KINDS = [\n \"string\",\n \"number\",\n \"boolean\",\n \"null\",\n \"object\",\n \"array\",\n \"unknown\",\n] as const\n\nexport type StateFieldKind = (typeof STATE_FIELD_KINDS)[number]\n\n/** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */\nexport type StateMeta = Readonly<Record<string, string | number | boolean | null>>\n\nexport type StateField = {\n name: string\n kind: StateFieldKind\n optional: boolean\n description?: string\n /** One level of nested object fields. */\n fields?: StateField[]\n meta?: StateMeta\n}\n\n/**\n * What a service knows about a collection before any row exists.\n * Stored rows still appear, including fields this declaration does not mention.\n */\nexport type StateDeclaration = {\n name: string\n label?: string\n description?: string\n fields?: readonly StateField[]\n meta?: StateMeta\n}\n\nexport type StateCollectionView = {\n name: string\n label: string\n description?: string\n count: number\n /** `mixed` when a declaration and stored rows both contribute fields. */\n source: \"declared\" | \"inferred\" | \"mixed\"\n fields: StateField[]\n meta?: StateMeta\n}\n\n/** The shape of one namespace, for an admin UI that has never seen the service before. */\nexport type StateView = {\n namespace: string\n storageNamespace: string\n collections: StateCollectionView[]\n}\n\nexport type StateRecord = {\n id: string\n seq: number\n value: unknown\n}\n\nexport type StatePage = {\n collection: string\n count: number\n records: StateRecord[]\n next: number | null\n}\n\nexport type StateFailure = { ok: false; status: number; message: string }\nexport type StateResult<T> = { ok: true; value: T } | StateFailure\n\nconst COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/\nconst RECORD_ID = /^[^\\s/]{1,256}$/\nconst SAMPLE = 25\nconst WALK_LIMIT = 10_000\nconst SKIP_CTORS = new Set([\"Hono\", \"HonoRequest\", \"Router\"])\n\nconst fail = (status: number, message: string): StateFailure => ({ ok: false, status, message })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst kindOf = (value: unknown): StateFieldKind => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return \"array\"\n switch (typeof value) {\n case \"string\":\n return \"string\"\n case \"number\":\n return Number.isFinite(value) ? \"number\" : \"unknown\"\n case \"boolean\":\n return \"boolean\"\n case \"object\":\n return \"object\"\n default:\n return \"unknown\"\n }\n}\n\nconst humanize = (name: string): string => {\n const words = name.replace(/[@:_-]+/g, \" \").trim()\n if (words === \"\") return name\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/** Drop values that cannot ride in a JSON admin response. */\nexport const jsonValue = (value: unknown): StateResult<unknown> => {\n if (value === undefined) return fail(400, \"value is required\")\n try {\n return { ok: true, value: JSON.parse(JSON.stringify(value)) as unknown }\n } catch {\n return fail(400, \"value must be JSON\")\n }\n}\n\nconst ctorName = (value: object): string => {\n const ctor = (value as { constructor?: { name?: string } }).constructor\n return typeof ctor?.name === \"string\" ? ctor.name : \"\"\n}\n\nconst isSqlite = (value: object): boolean =>\n \"prepare\" in value &&\n typeof (value as { prepare?: unknown }).prepare === \"function\" &&\n \"transaction\" in value\n\n/** Every Collection hanging off `root`, including ones stored in maps. */\nexport const discoverCollections = (root: unknown): Collection<unknown>[] => {\n const found: Collection<unknown>[] = []\n const seen = new Set<object>()\n const visit = (value: unknown, depth: number): void => {\n if (found.length + seen.size > WALK_LIMIT) return\n if (value === null || typeof value !== \"object\") return\n if (seen.has(value)) return\n seen.add(value)\n if (value instanceof Collection) {\n found.push(value as Collection<unknown>)\n return\n }\n if (value instanceof Map) {\n for (const child of value.values()) visit(child, depth + 1)\n return\n }\n if (value instanceof Set) {\n for (const child of value.values()) visit(child, depth + 1)\n return\n }\n if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value))) return\n if (Array.isArray(value)) {\n const cap = Math.min(value.length, 32)\n for (let i = 0; i < cap; i++) visit(value[i], depth + 1)\n return\n }\n let children: unknown[]\n try {\n children = Object.values(value)\n } catch {\n return\n }\n for (const child of children) visit(child, depth + 1)\n }\n visit(root, 0)\n return found\n}\n\nconst storedNames = (sqlite: SqliteClient, namespace: string): string[] => {\n const records = sqlite\n .prepare(\"SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?\")\n .all<{ name: string }>(namespace)\n const sequences = sqlite\n .prepare(\n \"SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'\",\n )\n .all<{ name: string }>(namespace)\n return [...records, ...sequences].map((row) => row.name)\n}\n\ntype FieldAccum = {\n name: string\n kinds: Set<StateFieldKind>\n present: number\n nested: Map<string, FieldAccum>\n}\n\nconst blankAccum = (name: string): FieldAccum => ({\n name,\n kinds: new Set(),\n present: 0,\n nested: new Map(),\n})\n\nconst absorb = (accum: FieldAccum, value: unknown): void => {\n const kind = kindOf(value)\n accum.kinds.add(kind)\n accum.present++\n if (!isRecord(value)) return\n for (const [key, child] of Object.entries(value)) {\n const nested = accum.nested.get(key) ?? blankAccum(key)\n absorb(nested, child)\n accum.nested.set(key, nested)\n }\n}\n\nconst finishField = (accum: FieldAccum, samples: number): StateField => {\n const kinds = [...accum.kinds]\n const kind = kinds.length === 1 ? (kinds[0] as StateFieldKind) : \"unknown\"\n const field: StateField = {\n name: accum.name,\n kind,\n optional: accum.present < samples || kinds.includes(\"null\"),\n }\n if (accum.nested.size > 0) {\n field.fields = [...accum.nested.values()]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((child) => finishField(child, accum.present))\n }\n return field\n}\n\nconst inferFields = (records: StateRecord[]): StateField[] => {\n if (records.length === 0) return []\n const sample = records.slice(0, SAMPLE)\n const objects = sample.filter((record) => isRecord(record.value))\n if (objects.length === 0) {\n const kinds = new Set(sample.map((record) => kindOf(record.value)))\n const list = [...kinds]\n return [\n {\n name: \"(value)\",\n kind: list.length === 1 ? (list[0] as StateFieldKind) : \"unknown\",\n optional: false,\n },\n ]\n }\n const root = new Map<string, FieldAccum>()\n for (const record of objects) {\n for (const [key, value] of Object.entries(record.value as Record<string, unknown>)) {\n const accum = root.get(key) ?? blankAccum(key)\n absorb(accum, value)\n root.set(key, accum)\n }\n }\n return [...root.values()]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((accum) => finishField(accum, objects.length))\n}\n\nconst mergeFields = (\n declared: readonly StateField[] | undefined,\n inferred: StateField[],\n): StateField[] => {\n const byName = new Map<string, StateField>()\n for (const field of inferred) byName.set(field.name, field)\n const ordered: StateField[] = []\n const seen = new Set<string>()\n for (const field of declared ?? []) {\n const found = byName.get(field.name)\n seen.add(field.name)\n if (!found) {\n ordered.push({ ...field, optional: field.optional })\n continue\n }\n ordered.push({\n ...found,\n kind: field.kind === \"unknown\" ? found.kind : field.kind,\n optional: field.optional || found.optional,\n ...(field.description !== undefined ? { description: field.description } : {}),\n ...(field.meta !== undefined ? { meta: field.meta } : {}),\n ...(field.fields !== undefined\n ? { fields: mergeFields(field.fields, found.fields ?? []) }\n : {}),\n })\n }\n for (const field of inferred) {\n if (!seen.has(field.name)) ordered.push(field)\n }\n return ordered\n}\n\nconst collectionOf = (sqlite: SqliteClient, namespace: string, name: string) =>\n new Collection<unknown>(sqlite, namespace, name)\n\nconst readRecord = (collection: Collection<unknown>, id: string): StateRecord | undefined => {\n const rows = collection.list({ where: (_value, _seq) => true, order: \"oldest\" })\n const row = rows.find((entry) => entry.id === id)\n return row ? { id: row.id, seq: row.seq, value: row.value } : undefined\n}\n\nexport type StateScope = {\n sqlite: SqliteClient\n /** Public namespace name a request selects. */\n namespace: string\n /** Namespace key used in `mockingbird_records`. */\n storageNamespace: string\n /** Service instance, walked for Collection fields. */\n root: unknown\n declarations?: readonly StateDeclaration[]\n}\n\n/** Describe every collection in a namespace. Empty declared collections are included. */\nexport const inspectState = (scope: StateScope): StateView => {\n const declared = new Map<string, StateDeclaration>()\n for (const declaration of scope.declarations ?? []) {\n if (COLLECTION_NAME.test(declaration.name)) declared.set(declaration.name, declaration)\n }\n const names = new Set<string>(declared.keys())\n for (const name of storedNames(scope.sqlite, scope.storageNamespace)) names.add(name)\n for (const collection of discoverCollections(scope.root)) {\n if (collection.namespace === scope.storageNamespace) names.add(collection.collectionName)\n }\n const collections: StateCollectionView[] = []\n for (const name of names) {\n if (!COLLECTION_NAME.test(name)) continue\n const declaration = declared.get(name)\n const collection = collectionOf(scope.sqlite, scope.storageNamespace, name)\n const records = collection\n .list({ order: \"newest\" })\n .slice(0, SAMPLE)\n .map((row) => ({ id: row.id, seq: row.seq, value: row.value }))\n const inferred = inferFields(records)\n const fields = mergeFields(declaration?.fields, inferred)\n const source =\n declaration && records.length > 0 ? \"mixed\" : declaration ? \"declared\" : \"inferred\"\n collections.push({\n name,\n label: declaration?.label ?? humanize(name),\n ...(declaration?.description !== undefined ? { description: declaration.description } : {}),\n count: collection.count(),\n source,\n fields,\n ...(declaration?.meta !== undefined ? { meta: declaration.meta } : {}),\n })\n }\n const order = new Map<string, number>()\n for (const [index, item] of (scope.declarations ?? []).entries()) order.set(item.name, index)\n collections.sort((a, b) => {\n const left = order.get(a.name)\n const right = order.get(b.name)\n if (left !== undefined && right !== undefined) return left - right\n if (left !== undefined) return -1\n if (right !== undefined) return 1\n return a.name.localeCompare(b.name)\n })\n return {\n namespace: scope.namespace,\n storageNamespace: scope.storageNamespace,\n collections,\n }\n}\n\nexport type StateQuery = {\n limit?: number\n after?: number\n order?: \"newest\" | \"oldest\"\n}\n\nconst pageOf = (\n sqlite: SqliteClient,\n storageNamespace: string,\n name: string,\n query: StateQuery,\n): StateResult<StatePage> => {\n if (!COLLECTION_NAME.test(name)) return fail(400, \"collection name is not allowed\")\n const limit = query.limit ?? 50\n if (!Number.isInteger(limit) || limit < 1 || limit > 200) {\n return fail(400, \"limit must be an integer from 1 to 200\")\n }\n const order = query.order ?? \"newest\"\n if (order !== \"newest\" && order !== \"oldest\")\n return fail(400, 'order must be \"newest\" or \"oldest\"')\n const collection = collectionOf(sqlite, storageNamespace, name)\n const rows = collection.list({ order }).filter((row) => {\n if (query.after === undefined) return true\n return order === \"newest\" ? row.seq < query.after : row.seq > query.after\n })\n const slice = rows.slice(0, limit)\n const last = slice.at(-1)\n return {\n ok: true,\n value: {\n collection: name,\n count: collection.count(),\n records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),\n next: rows.length > limit && last ? last.seq : null,\n },\n }\n}\n\nexport const readStatePage = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n query: StateQuery = {},\n): StateResult<StatePage> => pageOf(scope.sqlite, scope.storageNamespace, name, query)\n\nexport const readStateRecord = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n id: string,\n): StateResult<StateRecord> => {\n if (!COLLECTION_NAME.test(name)) return fail(400, \"collection name is not allowed\")\n if (!RECORD_ID.test(id)) return fail(400, \"record id is not allowed\")\n const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id)\n return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`)\n}\n\nconst requireId = (id: string): StateResult<string> =>\n RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, \"id must be a single path segment\")\n\nexport const createStateRecord = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n input: { id?: string; value: unknown },\n): StateResult<StateRecord> => {\n if (!COLLECTION_NAME.test(name)) return fail(400, \"collection name is not allowed\")\n const parsed = jsonValue(input.value)\n if (!parsed.ok) return parsed\n const collection = collectionOf(scope.sqlite, scope.storageNamespace, name)\n const id = input.id ?? `${name}_${collection.nextSequence()}`\n const checked = requireId(id)\n if (!checked.ok) return checked\n if (collection.has(checked.value)) return fail(409, `record ${checked.value} already exists`)\n const stored = collection.insert(checked.value, parsed.value)\n return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } }\n}\n\nexport const replaceStateRecord = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n id: string,\n value: unknown,\n): StateResult<StateRecord> => {\n if (!COLLECTION_NAME.test(name)) return fail(400, \"collection name is not allowed\")\n const checked = requireId(id)\n if (!checked.ok) return checked\n const parsed = jsonValue(value)\n if (!parsed.ok) return parsed\n const collection = collectionOf(scope.sqlite, scope.storageNamespace, name)\n if (!collection.has(checked.value)) return fail(404, `no record ${checked.value} in ${name}`)\n const stored = collection.update(checked.value, parsed.value)\n if (!stored) return fail(404, `no record ${checked.value} in ${name}`)\n return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } }\n}\n\nexport const patchStateRecord = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n id: string,\n value: unknown,\n): StateResult<StateRecord> => {\n const current = readStateRecord(scope, name, id)\n if (!current.ok) return current\n const parsed = jsonValue(value)\n if (!parsed.ok) return parsed\n const next =\n isRecord(current.value.value) && isRecord(parsed.value)\n ? { ...current.value.value, ...parsed.value }\n : parsed.value\n return replaceStateRecord(scope, name, id, next)\n}\n\nexport const deleteStateRecord = (\n scope: Pick<StateScope, \"sqlite\" | \"storageNamespace\">,\n name: string,\n id: string,\n): StateResult<{ id: string }> => {\n if (!COLLECTION_NAME.test(name)) return fail(400, \"collection name is not allowed\")\n const checked = requireId(id)\n if (!checked.ok) return checked\n const collection = collectionOf(scope.sqlite, scope.storageNamespace, name)\n return collection.delete(checked.value)\n ? { ok: true, value: { id: checked.value } }\n : fail(404, `no record ${checked.value} in ${name}`)\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n })\n\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst fromResult = <T>(result: StateResult<T>, status: number): Response =>\n result.ok ? json(status, result.value) : adminError(result.status, result.message)\n\nconst integerParam = (value: string | null): number | undefined | \"bad\" => {\n if (value === null) return undefined\n if (!/^-?\\d+$/.test(value)) return \"bad\"\n return Number(value)\n}\n\nexport type StateRoutes = {\n /** Open the public namespace and return the scope the state routes read. */\n open(namespace: string): StateScope\n /** Called after a successful write so Timeline records the new rows. */\n afterWrite?(namespace: string): void\n}\n\n/** The shared `/__admin/state*` routes. Registered after service routes so this key always wins. */\nexport const stateAdminRoutes = (routes: StateRoutes): AdminRoutes => {\n const open = (namespace: string): StateResult<StateScope> => {\n try {\n return { ok: true, value: routes.open(namespace) }\n } catch (error) {\n return fail(400, error instanceof Error ? error.message : String(error))\n }\n }\n const wrote = (namespace: string) => {\n routes.afterWrite?.(namespace)\n }\n return {\n \"GET /state\": ({ namespace }) => {\n const scope = open(namespace)\n return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200)\n },\n \"GET /state/:collection\": ({ namespace, params, url }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 200)\n const limit = integerParam(url.searchParams.get(\"limit\"))\n const after = integerParam(url.searchParams.get(\"after\"))\n if (limit === \"bad\") return adminError(400, \"limit: expected an integer\")\n if (after === \"bad\") return adminError(400, \"after: expected a sequence number\")\n const order = url.searchParams.get(\"order\")\n return fromResult(\n readStatePage(scope.value, params.collection ?? \"\", {\n ...(limit !== undefined ? { limit } : {}),\n ...(after !== undefined ? { after } : {}),\n ...(order === \"newest\" || order === \"oldest\" ? { order } : {}),\n }),\n 200,\n )\n },\n \"GET /state/:collection/:id\": ({ namespace, params }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 200)\n return fromResult(readStateRecord(scope.value, params.collection ?? \"\", params.id ?? \"\"), 200)\n },\n \"POST /state/:collection\": ({ namespace, params, body }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 201)\n if (!isRecord(body) || !(\"value\" in body)) {\n return adminError(400, 'expected {\"id?\": \"<id>\", \"value\": <json>}')\n }\n const id = body.id\n if (id !== undefined && typeof id !== \"string\") return adminError(400, \"id must be a string\")\n const created = createStateRecord(scope.value, params.collection ?? \"\", {\n ...(typeof id === \"string\" ? { id } : {}),\n value: body.value,\n })\n if (created.ok) wrote(namespace)\n return fromResult(created, 201)\n },\n \"PUT /state/:collection/:id\": ({ namespace, params, body }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 200)\n if (!isRecord(body) || !(\"value\" in body))\n return adminError(400, 'expected {\"value\": <json>}')\n const replaced = replaceStateRecord(\n scope.value,\n params.collection ?? \"\",\n params.id ?? \"\",\n body.value,\n )\n if (replaced.ok) wrote(namespace)\n return fromResult(replaced, 200)\n },\n \"PATCH /state/:collection/:id\": ({ namespace, params, body }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 200)\n if (!isRecord(body) || !(\"value\" in body))\n return adminError(400, 'expected {\"value\": <json>}')\n const patched = patchStateRecord(\n scope.value,\n params.collection ?? \"\",\n params.id ?? \"\",\n body.value,\n )\n if (patched.ok) wrote(namespace)\n return fromResult(patched, 200)\n },\n \"DELETE /state/:collection/:id\": ({ namespace, params }) => {\n const scope = open(namespace)\n if (!scope.ok) return fromResult(scope, 200)\n const removed = deleteStateRecord(scope.value, params.collection ?? \"\", params.id ?? \"\")\n if (removed.ok) wrote(namespace)\n return fromResult(removed, 200)\n },\n }\n}\n", "/**\n * Set by `scripts/bundle-service.ts` when a service is bundled, and rewritten to the\n * released version when it is published. Undefined when running from source.\n */\ndeclare const __MOCKINGBIRD_PACKAGE_VERSION__: string | undefined\n\n/** Placeholder a bundle carries until `release:publish` writes the real version over it. */\nexport const UNRELEASED_VERSION = \"0.0.0-development\"\n\n/** The published version of the service package this code is bundled into. */\nexport const PACKAGE_VERSION: string =\n typeof __MOCKINGBIRD_PACKAGE_VERSION__ === \"string\"\n ? __MOCKINGBIRD_PACKAGE_VERSION__\n : UNRELEASED_VERSION\n", "import type { AdminRoutes } from \"./control.js\"\nimport { signSvix, signTimestamped, signTwilio } from \"./signing.js\"\n\n/**\n * Outbound webhooks, shared by every service that has them.\n *\n * A service publishes a message (the exact bytes the vendor would send); the hub fans it out\n * to every matching endpoint, signs each delivery with the vendor's scheme, retries on the\n * vendor's schedule, and keeps a record a suite can read, replay or flush through\n * `/__admin/webhooks*`. Signature timestamps use the wall clock unless a service injects\n * `now`: receivers check them against their own time, and an advanced mock clock would\n * otherwise fail every delivery. A service whose caller injected the clock (Stripe) passes it,\n * so a virtual-time receiver verifies at the mock's time.\n */\n\n/** What a signer sees for one delivery attempt. */\nexport type SignInput = {\n messageId: string\n /** Exact bytes about to be sent. */\n body: string\n /** Unix seconds of this attempt: wall clock, or the hub's injected `now`. */\n timestampSeconds: number\n /** Where the delivery is posted. */\n url: string\n /** The endpoint's secret, if it has one. */\n secret: string | undefined\n /** The endpoint's `signUrl` (the public URL the receiver verifies against), else `url`. */\n signUrl: string\n /** Form parameters, when the body is form-encoded (Twilio signs these, not the body). */\n form: Record<string, string> | undefined\n /** Stable event type and metadata captured with the message; avoids signer side-channel state. */\n type: string\n tags: Readonly<Record<string, string>>\n}\n\n/** Headers to add to one delivery. */\nexport type WebhookSigner = (\n input: SignInput,\n) => Record<string, string> | Promise<Record<string, string>>\n\n/** Named signers for the vendor schemes the catalog needs. */\nexport const signers = {\n /** No signature. */\n none: (): WebhookSigner => () => ({}),\n /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */\n svix:\n (options: { prefix?: \"svix\" | \"webhook\" } = {}): WebhookSigner =>\n async ({ messageId, body, timestampSeconds, secret }) => {\n if (!secret) return {}\n const prefix = options.prefix ?? \"svix\"\n return {\n [`${prefix}-id`]: messageId,\n [`${prefix}-timestamp`]: String(timestampSeconds),\n [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body),\n }\n },\n /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, \"t.body\")>`: Stripe, Persona, Fullscript. */\n timestamped:\n (header = \"Stripe-Signature\"): WebhookSigner =>\n async ({ body, timestampSeconds, secret }) =>\n secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},\n /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */\n twilio:\n (): WebhookSigner =>\n async ({ signUrl, form, secret }) =>\n secret ? { \"X-Twilio-Signature\": await signTwilio(secret, signUrl, form ?? {}) } : {},\n /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */\n header:\n (header: string, format: (secret: string) => string = (s) => s): WebhookSigner =>\n ({ secret }) =>\n secret ? { [header]: format(secret) } : {},\n /** Anything else: the service computes the headers itself. */\n custom: (sign: WebhookSigner): WebhookSigner => sign,\n}\n\nexport type WebhookEndpoint = {\n /** Stable id; generated when omitted. */\n id?: string\n url: string\n secret?: string\n /** Event types to deliver; omit or include `\"*\"` for every type. */\n events?: string[]\n /** Deliver only messages whose tags include all of these (e.g. `{ account: \"mso\" }`). */\n tags?: Record<string, string>\n /** The public URL the receiver verifies signatures against (Twilio), when it differs. */\n signUrl?: string\n headers?: Record<string, string>\n}\n\nexport type WebhookMessage = {\n id: string\n namespace: string\n type: string\n body: string\n contentType: string\n tags: Record<string, string>\n headers?: Record<string, string>\n /** Wall-clock ISO-8601 time of publication. */\n publishedAt: string\n}\n\nexport type WebhookAttempt = {\n attempt: number\n at: string\n status: number | null\n error: string | null\n durationMs: number\n /** Exact receiver response body, when one was returned. */\n responseBody?: string | null\n}\n\nexport type WebhookDelivery = {\n id: string\n messageId: string\n namespace: string\n type: string\n endpointId: string\n url: string\n state: \"pending\" | \"delivered\" | \"failed\" | \"dropped\"\n attempts: WebhookAttempt[]\n}\n\n/** A delivery-level fault: what happens to the next `count` messages in a namespace. */\nexport type WebhookFault = {\n mode: \"duplicate\" | \"reorder\" | \"drop\"\n /** Messages affected; default 1. */\n count?: number\n}\n\nexport type PublishInput = {\n namespace: string\n type: string\n /** Exact body; objects are JSON-encoded. */\n body: string | Record<string, unknown> | unknown[]\n /** Default `application/json`, or form-encoded when `form` is given. */\n contentType?: string\n /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */\n form?: Record<string, string>\n tags?: Record<string, string>\n /** Message-specific delivery headers, captured as part of durable message state. */\n headers?: Record<string, string>\n /** Message id; generated when omitted. */\n id?: string\n}\n\nexport type WebhookHubOptions = {\n signer: WebhookSigner\n /**\n * Delay before each attempt, in ms; the first entry delays the first attempt. Default:\n * immediately, then 5 s, 5 min, 30 min, 2 h.\n */\n retryDelaysMs?: readonly number[]\n /** Abort an attempt after this long. Default 15 s. */\n timeoutMs?: number\n /** Which receiver statuses count as delivered. Default 2xx. */\n delivered?: (status: number) => boolean\n /** Endpoints every namespace delivers to (from `--webhook-url`). */\n endpoints?: WebhookEndpoint[]\n fetch?: (request: Request) => Promise<Response>\n /** Called in-process for every published message, delivered or not. */\n onMessage?: (message: WebhookMessage) => void\n /** Messages kept per namespace for `GET /__admin/webhooks/events`. Default 500. */\n keep?: number\n /** Injectable clock (default wall clock) for signatures and attempt records. */\n now?: () => number\n /** Injectable deterministic identifier source. Receives `\"msg_\"` or `\"dlv_\"`. */\n id?: (prefix: string) => string\n /** Injectable scheduler used by timeouts and retries. */\n schedule?: (callback: () => void, delayMs: number) => unknown\n cancel?: (handle: unknown) => void\n}\n\nexport type WebhookHub = {\n publish(input: PublishInput): WebhookMessage\n /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */\n setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[]\n /** The endpoints a namespace delivers to: its own, plus the global ones. */\n endpoints(namespace: string): WebhookEndpoint[]\n messages(namespace?: string): WebhookMessage[]\n deliveries(namespace?: string): WebhookDelivery[]\n replay(deliveryId: string): Promise<WebhookDelivery | undefined>\n /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */\n flush(): Promise<void>\n /** Resolve once nothing is in flight. */\n idle(): Promise<void>\n fault(namespace: string, fault: WebhookFault): void\n clear(namespace?: string): void\n}\n\nconst DEFAULT_DELAYS = [0, 5_000, 300_000, 1_800_000, 7_200_000] as const\n\nconst unref = (timer: unknown) => {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\nconst randomId = (prefix: string) =>\n `${prefix}${crypto.randomUUID().replace(/-/g, \"\").slice(0, 24)}`\n\nconst matchesEndpoint = (endpoint: WebhookEndpoint, message: WebhookMessage): boolean => {\n const events = endpoint.events ?? [\"*\"]\n if (!events.includes(\"*\") && !events.includes(message.type)) return false\n for (const [key, value] of Object.entries(endpoint.tags ?? {})) {\n if (message.tags[key] !== value) return false\n }\n return true\n}\n\nexport const createWebhookHub = (options: WebhookHubOptions): WebhookHub => {\n const delays = options.retryDelaysMs ?? DEFAULT_DELAYS\n const timeoutMs = options.timeoutMs ?? 15_000\n const delivered = options.delivered ?? ((status: number) => status >= 200 && status < 300)\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const keep = options.keep ?? 500\n const now = options.now ?? Date.now\n const id = options.id ?? randomId\n const scheduleTimer =\n options.schedule ?? ((callback: () => void, delayMs: number) => setTimeout(callback, delayMs))\n const cancel =\n options.cancel ?? ((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>))\n const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }))\n const own = new Map<string, WebhookEndpoint[]>()\n const messages: WebhookMessage[] = []\n const deliveries = new Map<string, WebhookDelivery>()\n const pending = new Map<string, unknown | undefined>()\n const payloads = new Map<string, { message: WebhookMessage; endpoint: WebhookEndpoint }>()\n const faults = new Map<string, { mode: WebhookFault[\"mode\"]; remaining: number }[]>()\n const held = new Map<string, WebhookMessage[]>()\n const inFlight = new Set<Promise<void>>()\n // Immediate (delay 0) attempts chain onto this so two deliveries scheduled in the same tick\n // (e.g. a reorder fault's swap) hit the receiver in schedule order, not fetch-race order.\n let immediate: Promise<unknown> = Promise.resolve()\n\n const track = (work: Promise<void>) => {\n inFlight.add(work)\n void work.finally(() => inFlight.delete(work))\n }\n\n const attempt = async (delivery: WebhookDelivery): Promise<boolean> => {\n const entry = payloads.get(delivery.id)\n if (!entry) return false\n const { message, endpoint } = entry\n const timestampSeconds = Math.floor(now() / 1000)\n const started = now()\n const record: WebhookAttempt = {\n attempt: delivery.attempts.length + 1,\n at: new Date(started).toISOString(),\n status: null,\n error: null,\n durationMs: 0,\n responseBody: null,\n }\n const controller = new AbortController()\n const timer = scheduleTimer(() => controller.abort(), timeoutMs)\n try {\n const signed = await options.signer({\n messageId: message.id,\n body: message.body,\n timestampSeconds,\n url: endpoint.url,\n secret: endpoint.secret,\n signUrl: endpoint.signUrl ?? endpoint.url,\n form: message.contentType.startsWith(\"application/x-www-form-urlencoded\")\n ? Object.fromEntries(new URLSearchParams(message.body))\n : undefined,\n type: message.type,\n tags: message.tags,\n })\n const response = await send(\n new Request(endpoint.url, {\n method: \"POST\",\n headers: {\n \"content-type\": message.contentType,\n ...endpoint.headers,\n ...message.headers,\n ...signed,\n },\n body: message.body,\n signal: controller.signal,\n }),\n )\n record.status = response.status\n record.responseBody = await response.text()\n } catch (error) {\n record.error = controller.signal.aborted\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error)\n } finally {\n cancel(timer)\n record.durationMs = now() - started\n delivery.attempts.push(record)\n }\n return record.status !== null && delivered(record.status)\n }\n\n const schedule = (delivery: WebhookDelivery) => {\n const index = delivery.attempts.length\n if (index >= delays.length) {\n delivery.state = \"failed\"\n pending.delete(delivery.id)\n return\n }\n const settle = async () => {\n // `clear` can drop a delivery queued behind an earlier immediate attempt. Its attempt would\n // record nothing and reschedule at the same index forever, starving the event loop.\n if (!payloads.has(delivery.id)) return\n await attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n })\n }\n const delay = delays[index] ?? 0\n if (delay <= 0) {\n const task = immediate.then(settle)\n immediate = task.catch(() => {})\n track(task)\n return\n }\n const timer = scheduleTimer(() => {\n pending.delete(delivery.id)\n track(settle())\n }, delay)\n unref(timer)\n pending.set(delivery.id, timer)\n }\n\n const endpointsFor = (namespace: string) => [...(own.get(namespace) ?? []), ...global]\n\n const fanOut = (message: WebhookMessage, state: WebhookDelivery[\"state\"] = \"pending\") => {\n for (const endpoint of endpointsFor(message.namespace)) {\n if (!matchesEndpoint(endpoint, message)) continue\n const delivery: WebhookDelivery = {\n id: id(\"dlv_\"),\n messageId: message.id,\n namespace: message.namespace,\n type: message.type,\n endpointId: endpoint.id ?? \"we_unknown\",\n url: endpoint.url,\n state,\n attempts: [],\n }\n deliveries.set(delivery.id, delivery)\n payloads.set(delivery.id, { message, endpoint })\n if (state === \"pending\") schedule(delivery)\n }\n }\n\n const takeFault = (namespace: string): WebhookFault[\"mode\"] | undefined => {\n const queue = faults.get(namespace)\n const head = queue?.[0]\n if (!queue || !head) return undefined\n head.remaining--\n if (head.remaining <= 0) queue.shift()\n return head.mode\n }\n\n const releaseHeld = (namespace: string) => {\n const waiting = held.get(namespace)\n if (!waiting) return\n held.delete(namespace)\n for (const message of waiting) fanOut(message)\n }\n\n const hub: WebhookHub = {\n publish(input) {\n const contentType =\n input.contentType ?? (input.form ? \"application/x-www-form-urlencoded\" : \"application/json\")\n const body =\n typeof input.body === \"string\"\n ? input.body\n : input.form\n ? new URLSearchParams(input.form).toString()\n : JSON.stringify(input.body)\n const message: WebhookMessage = {\n id: input.id ?? id(\"msg_\"),\n namespace: input.namespace,\n type: input.type,\n body,\n contentType,\n tags: input.tags ?? {},\n headers: input.headers ?? {},\n publishedAt: new Date(now()).toISOString(),\n }\n messages.push(message)\n const ofNamespace = messages.filter((m) => m.namespace === message.namespace)\n const oldest = ofNamespace[0]\n if (ofNamespace.length > keep && oldest) messages.splice(messages.indexOf(oldest), 1)\n options.onMessage?.(message)\n const fault = takeFault(message.namespace)\n if (fault === \"drop\") {\n fanOut(message, \"dropped\")\n return message\n }\n if (fault === \"reorder\") {\n // Held until the next message goes out, so the receiver sees them swapped.\n held.set(message.namespace, [...(held.get(message.namespace) ?? []), message])\n return message\n }\n fanOut(message)\n if (fault === \"duplicate\") fanOut(message)\n releaseHeld(message.namespace)\n return message\n },\n setEndpoints(namespace, endpoints) {\n const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }))\n own.set(namespace, withIds)\n return withIds\n },\n endpoints: endpointsFor,\n messages: (namespace) =>\n namespace === undefined ? [...messages] : messages.filter((m) => m.namespace === namespace),\n deliveries: (namespace) =>\n [...deliveries.values()].filter((d) => namespace === undefined || d.namespace === namespace),\n async replay(id) {\n const delivery = deliveries.get(id)\n if (!delivery) return undefined\n const ok = await attempt(delivery)\n if (ok) delivery.state = \"delivered\"\n return delivery\n },\n async flush() {\n // Drains until nothing is held or scheduled: a retry that an attempt failing during this\n // flush schedules runs too, so a caller asserting after `flush` never catches a delivery\n // between attempts. Bounded, as every pass moves each delivery an attempt closer to\n // `delivered` or `failed`.\n for (;;) {\n for (const namespace of [...held.keys()]) releaseHeld(namespace)\n const waiting = [...pending.entries()]\n for (const [id, timer] of waiting) {\n if (timer === undefined) continue\n cancel(timer)\n pending.delete(id)\n const delivery = deliveries.get(id)\n if (!delivery) continue\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n await hub.idle()\n const scheduled = [...pending.values()].some((timer) => timer !== undefined)\n if (held.size === 0 && !scheduled) return\n }\n },\n async idle() {\n while (inFlight.size > 0) await Promise.allSettled([...inFlight])\n },\n fault(namespace, fault) {\n const queue = faults.get(namespace) ?? []\n queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) })\n faults.set(namespace, queue)\n },\n clear(namespace) {\n for (const [id, delivery] of deliveries) {\n if (namespace !== undefined && delivery.namespace !== namespace) continue\n const timer = pending.get(id)\n if (timer !== undefined) cancel(timer)\n pending.delete(id)\n deliveries.delete(id)\n payloads.delete(id)\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n if (namespace === undefined || messages[i]?.namespace === namespace) messages.splice(i, 1)\n }\n if (namespace === undefined) {\n held.clear()\n faults.clear()\n own.clear()\n } else {\n held.delete(namespace)\n faults.delete(namespace)\n own.delete(namespace)\n }\n },\n }\n return hub\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst parseEndpoint = (value: unknown): WebhookEndpoint | string => {\n if (!isRecord(value) || typeof value.url !== \"string\") return \"each endpoint needs a url\"\n try {\n new URL(value.url)\n } catch {\n return `not a URL: ${value.url}`\n }\n const endpoint: WebhookEndpoint = { url: value.url }\n if (typeof value.id === \"string\") endpoint.id = value.id\n if (typeof value.secret === \"string\") endpoint.secret = value.secret\n if (typeof value.signUrl === \"string\") endpoint.signUrl = value.signUrl\n const events = value.events ?? value.enabledEvents\n if (Array.isArray(events)) endpoint.events = events.map(String)\n if (isRecord(value.tags)) {\n endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]))\n }\n if (typeof value.account === \"string\")\n endpoint.tags = { ...endpoint.tags, account: value.account }\n if (isRecord(value.headers)) {\n endpoint.headers = Object.fromEntries(\n Object.entries(value.headers).map(([k, v]) => [k, String(v)]),\n )\n }\n return endpoint\n}\n\n/**\n * The standard webhook admin routes, for a runtime that owns `hub`:\n *\n * - `GET /webhooks` deliveries, `GET /webhooks/events` published messages (with bodies:\n * they are the mock's own output), `POST /webhooks/:id/replay`, `POST /webhooks/flush`\n * - `GET|PUT|DELETE /webhook-endpoints` per namespace\n * - `POST /webhooks/faults {mode: duplicate|reorder|drop, count?}`\n */\nexport const webhookAdminRoutes = (hub: WebhookHub): AdminRoutes => ({\n \"GET /webhooks\": ({ url, namespace }) =>\n json(200, {\n deliveries: hub\n .deliveries(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((d) => {\n const type = url.searchParams.get(\"type\")\n return type === null || d.type === type\n }),\n }),\n \"GET /webhooks/events\": ({ url, namespace }) => {\n const type = url.searchParams.get(\"type\")\n return json(200, {\n events: hub\n .messages(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((m) => type === null || m.type === type)\n .map((m) => ({ ...m, payload: parsePayload(m) })),\n })\n },\n \"POST /webhooks/:id/replay\": async ({ params }) => {\n const replayed = await hub.replay(params.id as string)\n return replayed ? json(200, replayed) : adminError(404, `no delivery ${params.id}`)\n },\n \"POST /webhooks/flush\": async () => {\n await hub.flush()\n return json(200, { status: \"ok\" })\n },\n \"POST /webhooks/faults\": ({ body, namespace }) => {\n if (!isRecord(body) || ![\"duplicate\", \"reorder\", \"drop\"].includes(String(body.mode))) {\n return adminError(400, \"mode must be duplicate, reorder or drop\")\n }\n const fault: WebhookFault = { mode: body.mode as WebhookFault[\"mode\"] }\n if (typeof body.count === \"number\") fault.count = body.count\n hub.fault(namespace, fault)\n return json(201, { namespace, ...fault })\n },\n \"GET /webhook-endpoints\": ({ namespace }) =>\n json(200, {\n endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({\n ...rest,\n secret: secret ? \"(set)\" : null,\n })),\n }),\n \"PUT /webhook-endpoints\": ({ body, namespace }) => {\n const list = Array.isArray(body) ? body : isRecord(body) ? body.endpoints : undefined\n if (!Array.isArray(list)) return adminError(400, \"expected [{url, secret?, events?}]\")\n const parsed: WebhookEndpoint[] = []\n for (const each of list) {\n const endpoint = parseEndpoint(each)\n if (typeof endpoint === \"string\") return adminError(400, endpoint)\n parsed.push(endpoint)\n }\n const set = hub.setEndpoints(namespace, parsed)\n return json(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? \"(set)\" : null })) })\n },\n \"DELETE /webhook-endpoints\": ({ namespace }) => {\n hub.setEndpoints(namespace, [])\n return json(200, { status: \"ok\" })\n },\n})\n\nconst parsePayload = (message: WebhookMessage): unknown => {\n if (message.contentType.startsWith(\"application/json\")) {\n try {\n return JSON.parse(message.body)\n } catch {\n return message.body\n }\n }\n if (message.contentType.startsWith(\"application/x-www-form-urlencoded\")) {\n return Object.fromEntries(new URLSearchParams(message.body))\n }\n return message.body\n}\n", "import { type Checkpoint, type FetchAPI, Timeline } from \"@crvouga/mockingbird-core\"\nimport { listOperations, type OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\nimport { clearNamespace, type SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { adminUiRoutes } from \"./admin-ui.js\"\nimport { type Clock, createClock } from \"./clock.js\"\nimport { type AdminRoutes, createControlPlane, NAMESPACE_HEADER } from \"./control.js\"\nimport { type CredentialRegistry, createCredentialRegistry, maskCredential } from \"./credentials.js\"\nimport {\n createFaultRegistry,\n type FaultHit,\n type FaultPreset,\n type FaultPresetList,\n type FaultRegistry,\n type FaultRule,\n} from \"./faults.js\"\nimport { createJournal, DEFAULT_JOURNAL_SIZE, type Journal, responseNotes } from \"./journal.js\"\nimport { createMetrics, type Metrics, type RejectedRequest, type RequestLog } from \"./metrics.js\"\nimport { createRng, type Rng, seedFrom } from \"./rng.js\"\nimport { bootSqlite } from \"./service.js\"\nimport { type NamespaceSnapshot, restoreNamespace, snapshotNamespace } from \"./snapshot.js\"\nimport {\n inspectState,\n type StateDeclaration,\n type StateView,\n stateAdminRoutes,\n} from \"./state-view.js\"\nimport { type AdminUi, assertAdminUi, defineMock, type MockSurface } from \"./surface.js\"\nimport { PACKAGE_VERSION } from \"./version.js\"\nimport { type WebhookHub, webhookAdminRoutes } from \"./webhooks.js\"\n\n/**\n * Stamped on every response the runtime returns \u2014 vendor, fault, admin and health alike \u2014\n * as `<service>@<version>; ns=<namespace>`, so a consumer can tell the mock from the vendor.\n */\nexport const MOCKINGBIRD_HEADER = \"x-mockingbird\"\n/** Selects a named copy-on-write history branch. `main` is the compatibility default. */\nexport const BRANCH_HEADER = \"x-mockingbird-branch\"\n/** Reads a historical checkpoint. With a branch header, initializes that branch from it. */\nexport const AT_HEADER = \"x-mockingbird-at\"\n/** Identifies the resulting checkpoint on successful mutations. */\nexport const CHECKPOINT_HEADER = \"x-mockingbird-checkpoint\"\n\n/** What the runtime needs from a service: a Fetch handler it can reset. */\nexport type ServiceInstance = FetchAPI & { reset(): Promise<void> }\n\n/** Everything an instance shares with the runtime that owns it. */\nexport type InstanceContext = {\n /** Storage namespace for this instance's records. */\n namespace: string\n /** The public namespace name a request selects it by. */\n publicNamespace: string\n sqlite: SqliteClient\n clock: Clock\n rng: Rng\n}\n\nexport type RuntimeOptions<T extends ServiceInstance> = {\n /** Service name, e.g. `\"junction\"`. Also the default namespace's storage key. */\n name: string\n /** Build the instance backing one namespace. Called once per namespace, on first use. */\n create: (context: InstanceContext) => T\n /** The vendor contract, used to name each request's operation in logs, metrics and faults. */\n document?: OpenAPIDocument\n /** Shared by every namespace. Defaults to a fresh `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Defaults to a live clock over `Date.now`. */\n clock?: Clock\n /** Seeds every random choice the runtime makes (fault rates). Default `0`. */\n seed?: number | string\n /** Extra `GET /health` fields, such as the loaded corpus version. */\n describe?: () => Record<string, unknown>\n /** Service-specific admin routes, given the runtime so they can reach any namespace. */\n admin?: (runtime: ServiceRuntime<T>) => AdminRoutes\n /** Require this value in `x-mockingbird-admin-key` on `/__admin/*`. Omit to leave admin open. */\n adminKey?: string\n /** Structured request log sink, called once per request. */\n onLog?: (entry: RequestLog) => void\n /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000; 0 turns it off. */\n journalSize?: number\n /** Reported in the `x-mockingbird` header. Default: the bundled package's version. */\n version?: string\n /**\n * The vendor credential a request carries (API key, token, account SID, AWS access key\n * id), for SDKs that cannot send `x-mockingbird-namespace`: a suite maps credentials to\n * namespaces with `PUT /__admin/credentials`. See `bearerToken`, `basicAuth`,\n * `sigV4AccessKeyId`.\n */\n credential?: (request: Request) => string | undefined\n /** Named faults, switched on with `POST /__admin/faults {\"preset\": \"<name>\"}`. */\n presets?: Record<string, FaultPreset>\n /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */\n webhooks?: WebhookHub\n /** Retained time-travel checkpoints per namespace. Default 1,000. */\n maxCheckpoints?: number\n /** Injectable process IO used for observability and delays; logical service time uses `clock`. */\n io?: Partial<RuntimeIO>\n /**\n * Collections the admin UI should show even before any row exists.\n * Stored collections are always included, whether or not they are declared.\n * A function may describe collections that depend on the live instance.\n */\n state?: readonly StateDeclaration[] | ((api: T, namespace: string) => readonly StateDeclaration[])\n /**\n * Panels added to the default admin UI, or a function that replaces the document.\n * `render` receives `defaultHtml()` so a bespoke UI can wrap the shared shell.\n */\n adminUi?: AdminUi\n}\n\nexport type RuntimeIO = {\n wallNow(): number\n monotonicNow(): number\n sleep(ms: number): Promise<void>\n}\n\nexport type ServiceTimelineState = Readonly<{\n snapshot: NamespaceSnapshot\n clock: Readonly<ReturnType<Clock[\"state\"]>>\n rngState: number\n}>\n\nexport type ServiceCheckpoint = Checkpoint<ServiceTimelineState>\n\nexport type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {\n readonly name: string\n readonly sqlite: SqliteClient\n readonly clock: Clock\n readonly faults: FaultRegistry\n readonly metrics: Metrics\n readonly journal: Journal\n readonly rng: Rng\n readonly credentials: CredentialRegistry\n /** The webhook hub, when the service has outbound webhooks. */\n readonly webhooks: WebhookHub | undefined\n /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */\n applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[]\n /** The instance behind `namespace` (the default one when omitted), created on first use. */\n instance(namespace?: string): T\n /** Public names of every namespace created so far. */\n namespaces(): string[]\n /** Reset one namespace, or every namespace with `\"*\"`. */\n reset(namespace?: string): Promise<void>\n snapshot(namespace?: string): NamespaceSnapshot\n restore(snapshot: NamespaceSnapshot, namespace?: string): void\n /** Capture the current branch. Mutating HTTP calls do this automatically. */\n checkpoint(namespace?: string, branch?: string): ServiceCheckpoint\n /** Create an isolated branch, optionally from a historical checkpoint. */\n branch(name: string, options?: { namespace?: string; at?: string }): ServiceCheckpoint\n /** Restore a branch, clock, and PRNG to a checkpoint. */\n checkout(checkpoint: string, options?: { namespace?: string; branch?: string }): void\n /** Inspect the retained history for a namespace. */\n timeline(namespace?: string): Timeline<ServiceTimelineState>\n /** Collections in one namespace: declared shape plus what the rows actually hold. */\n state(namespace?: string): StateView\n}\n\ntype _MockSurfaceProof = ServiceRuntime<ServiceInstance> extends MockSurface ? true : never\nconst mockSurfaceProof: _MockSurfaceProof = true\nvoid mockSurfaceProof\n\n/** The namespace used when a request names none. */\nexport const DEFAULT_NAMESPACE = \"default\"\n\nconst NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/** `/ns/<namespace>/\u2026`: the namespace carrier for SDKs that only take a base URL. */\nconst PATH_PREFIX = /^\\/ns\\/([^/]+)(\\/.*)?$/\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"])\n\nconst effects = new WeakMap<Request, FaultHit[\"effect\"][]>()\n\n/**\n * Merge two sorted snapshot row arrays, retaining byte-identical old objects. Unlike the previous\n * Map/string-key implementation this is allocation-free apart from the result array and O(n).\n */\nconst reuseSorted = <T>(\n fresh: T[],\n previous: T[] | undefined,\n compare: (left: T, right: T) => number,\n equal: (left: T, right: T) => boolean,\n): T[] => {\n if (!previous || previous.length === 0) return fresh.map((row) => Object.freeze(row))\n const result = new Array<T>(fresh.length)\n let unchanged = fresh.length === previous.length\n let oldIndex = 0\n for (let index = 0; index < fresh.length; index++) {\n const row = fresh[index] as T\n while (oldIndex < previous.length && compare(previous[oldIndex] as T, row) < 0) {\n oldIndex++\n }\n const old = previous[oldIndex]\n result[index] =\n old !== undefined && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row)\n if (result[index] !== previous[index]) unchanged = false\n }\n return unchanged ? previous : result\n}\n\n/**\n * The fault effects (`{\"effect\": \"created_but_500\"}` rules) that fired for this request, in\n * rule order. Handlers read this to switch on a named vendor misbehaviour.\n */\nexport const faultEffects = (\n request: Request,\n): { name: string; params: Record<string, unknown> }[] =>\n (effects.get(request) ?? []).filter((e): e is NonNullable<typeof e> => e !== undefined)\n\n/** Whether the named effect fired for this request; its params when it did. */\nexport const faultEffect = (request: Request, name: string): Record<string, unknown> | undefined =>\n faultEffects(request).find((e) => e.name === name)?.params\n\n/**\n * Thrown by an in-process `runtime.fetch` when a `drop` fault fires: the same thing a real\n * `fetch` does when the connection dies mid-request. A served mock destroys the socket.\n */\nexport class DroppedConnectionError extends TypeError {\n readonly code = \"MOCKINGBIRD_DROP\"\n constructor() {\n super(\"fetch failed: connection dropped by Mockingbird fault\")\n this.name = \"TypeError\"\n }\n}\n\ntype Matcher = { operationId: string; method: string; pattern: RegExp; params: number }\n\n/** Resolve a request to its operationId: static segments beat parameters, as in routing. */\nconst operationMatcher = (document: OpenAPIDocument) => {\n const matchers: Matcher[] = listOperations(document)\n .map((operation) => ({\n operationId: operation.operationId,\n method: operation.method.toUpperCase(),\n pattern: new RegExp(\n `^${operation.path\n .split(\"/\")\n .map((segment) =>\n segment.startsWith(\"{\") ? \"[^/]+\" : segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"),\n )\n .join(\"/\")}/?$`,\n ),\n params: (operation.path.match(/\\{/g) ?? []).length,\n }))\n .sort((a, b) => a.params - b.params)\n return (request: Request, path: string): string | undefined =>\n matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId\n}\n\n/**\n * Wrap a service in the shared Mockingbird contract: an unauthenticated `/health`,\n * the `/__admin/*` control plane, per-request namespaces, a controllable clock,\n * fault injection, and request metrics.\n *\n * Namespaces isolate parallel workers inside one process: each gets its own\n * instance over the same SQLite database, so rows are partitioned by namespace\n * and a worker's reset or restore never touches another worker's data.\n */\nexport const createRuntime = <T extends ServiceInstance>(\n options: RuntimeOptions<T>,\n): ServiceRuntime<T> => {\n assertAdminUi(options.adminUi)\n const sqlite = bootSqlite(options.sqlite)\n const clock = options.clock ?? createClock()\n const rng = createRng(options.seed ?? 0)\n const wallNow = options.io?.wallNow ?? Date.now\n const monotonicNow = options.io?.monotonicNow ?? (() => performance.now())\n const sleep =\n options.io?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep)\n const metrics = createMetrics()\n const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE)\n const version = options.version ?? PACKAGE_VERSION\n const instances = new Map<string, T>()\n const publicNamespaces = new Set<string>()\n const branchRngs = new Map<string, Rng>()\n const timelines = new Map<string, Timeline<ServiceTimelineState>>()\n const branchStorage = new Map<string, string>()\n const captured = new Map<string, NamespaceSnapshot>()\n const credentials = createCredentialRegistry()\n const operationIdFor = options.document ? operationMatcher(options.document) : () => undefined\n\n const storageNamespace = (name: string) =>\n name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`\n\n const instanceFor = (key: string, publicNamespace = key, isolatedRng?: Rng): T => {\n const existing = instances.get(key)\n if (existing) return existing\n if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {\n throw new RangeError(\n `namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`,\n )\n }\n const created = options.create({\n namespace: storageNamespace(key),\n publicNamespace,\n sqlite,\n clock,\n rng: isolatedRng ?? rng,\n })\n instances.set(key, created)\n publicNamespaces.add(publicNamespace)\n if (isolatedRng) branchRngs.set(key, isolatedRng)\n return created\n }\n\n const instance = (name: string = DEFAULT_NAMESPACE): T => instanceFor(name)\n\n const capture = (storage: string): ServiceTimelineState => {\n const fresh = snapshotNamespace(sqlite, storageNamespace(storage))\n const previous = captured.get(storage)\n const snapshot: NamespaceSnapshot = {\n namespace: fresh.namespace,\n records: reuseSorted(\n fresh.records,\n previous?.records,\n (left, right) =>\n left.collection < right.collection\n ? -1\n : left.collection > right.collection\n ? 1\n : left.seq - right.seq,\n (left, right) => left.id === right.id && left.value === right.value,\n ),\n sequences: reuseSorted(\n fresh.sequences,\n previous?.sequences,\n (left, right) =>\n left.name < right.name\n ? -1\n : left.name > right.name\n ? 1\n : left.kind < right.kind\n ? -1\n : left.kind > right.kind\n ? 1\n : 0,\n (left, right) => left.value === right.value,\n ),\n }\n Object.freeze(snapshot.records)\n Object.freeze(snapshot.sequences)\n Object.freeze(snapshot)\n captured.set(storage, snapshot)\n return Object.freeze({\n snapshot,\n clock: Object.freeze(clock.state()),\n rngState: (branchRngs.get(storage) ?? rng).state(),\n })\n }\n\n const timeline = (name: string = DEFAULT_NAMESPACE): Timeline<ServiceTimelineState> => {\n let found = timelines.get(name)\n if (found) return found\n instance(name)\n found = new Timeline<ServiceTimelineState>({\n now: clock.now,\n ...(options.maxCheckpoints !== undefined ? { maxCheckpoints: options.maxCheckpoints } : {}),\n })\n found.commit(capture(name))\n timelines.set(name, found)\n return found\n }\n\n const physicalBranch = (namespace: string, branch: string): string => {\n if (branch === \"main\") return namespace\n const mapKey = `${namespace}\\0${branch}`\n const existing = branchStorage.get(mapKey)\n if (existing) return existing\n // The hash keeps the internal instance key inside the 64-character namespace contract.\n const key = `branch_${seedFrom(`${options.name}\\0${namespace}\\0${branch}`).toString(36)}`\n branchStorage.set(mapKey, key)\n return key\n }\n\n const ensureBranch = (namespace: string, branch: string, at?: string): string => {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n const history = timeline(namespace)\n if (branch === \"main\") {\n if (at !== undefined) {\n const point = history.checkout(\"main\", at)\n restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot)\n captured.set(namespace, point.value.snapshot)\n rng.setState(point.value.rngState)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n }\n return namespace\n }\n const storage = physicalBranch(namespace, branch)\n if (!history.hasBranch(branch)) {\n // Capture unobserved background work before branching from the current main head.\n if (at === undefined) history.commit(capture(namespace))\n const point = history.fork(branch, at === undefined ? {} : { from: at })\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n if (point) restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n if (point) captured.set(storage, point.value.snapshot)\n } else if (at !== undefined && history.head(branch)?.id !== at) {\n const point = history.checkout(branch, at)\n if (!instances.has(storage)) {\n const branchRng = createRng(options.seed ?? 0)\n branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n branchRngs.get(storage)?.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n if (!instances.has(storage)) {\n const point = history.head(branch)\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n }\n return storage\n }\n\n const checkpoint = (namespace = DEFAULT_NAMESPACE, branch = \"main\"): ServiceCheckpoint => {\n const storage = ensureBranch(namespace, branch)\n return timeline(namespace).commit(capture(storage), { branch })\n }\n\n const branch = (\n name: string,\n branchOptions: { namespace?: string; at?: string } = {},\n ): ServiceCheckpoint => {\n const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE\n ensureBranch(namespace, name, branchOptions.at)\n const head = timeline(namespace).head(name)\n if (!head) throw new RangeError(`branch ${name} has no checkpoint`)\n return head\n }\n\n const checkout = (\n checkpointId: string,\n checkoutOptions: { namespace?: string; branch?: string } = {},\n ): void => {\n const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE\n const branchName = checkoutOptions.branch ?? \"main\"\n const history = timeline(namespace)\n const point = history.checkout(branchName, checkpointId)\n const storage = ensureBranch(namespace, branchName)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n ;(branchRngs.get(storage) ?? rng).setState(point.value.rngState)\n }\n\n const reset = async (name: string = DEFAULT_NAMESPACE): Promise<void> => {\n if (name === \"*\") {\n options.webhooks?.clear()\n for (const each of instances.values()) await each.reset()\n timelines.clear()\n branchStorage.clear()\n branchRngs.clear()\n captured.clear()\n return\n }\n options.webhooks?.clear(name)\n const target = instances.get(name)\n if (target) await target.reset()\n else clearNamespace(sqlite, storageNamespace(name))\n for (const [mapping, storage] of branchStorage) {\n if (!mapping.startsWith(`${name}\\0`)) continue\n const branchInstance = instances.get(storage)\n if (branchInstance) await branchInstance.reset()\n else clearNamespace(sqlite, storageNamespace(storage))\n branchStorage.delete(mapping)\n branchRngs.delete(storage)\n captured.delete(storage)\n }\n timelines.delete(name)\n captured.delete(name)\n }\n\n const snapshot = (name: string = DEFAULT_NAMESPACE): NamespaceSnapshot => {\n return checkpoint(name, \"main\").value.snapshot\n }\n\n const restore = (from: NamespaceSnapshot, name: string = DEFAULT_NAMESPACE): void => {\n instance(name)\n restoreNamespace(sqlite, storageNamespace(name), from)\n captured.set(name, from)\n // Import legacy snapshots into the canonical history instead of creating a second rollback\n // mechanism. The compatibility method stays synchronous and keeps its original return type.\n const history = timelines.get(name)\n if (history) history.commit(capture(name), { branch: \"main\" })\n else timeline(name)\n }\n\n const declarationsFor = (namespace: string): readonly StateDeclaration[] => {\n const declared = options.state\n if (!declared) return []\n return typeof declared === \"function\" ? declared(instance(namespace), namespace) : declared\n }\n\n const stateScope = (namespace: string) => ({\n sqlite,\n namespace,\n storageNamespace: storageNamespace(namespace),\n root: instance(namespace),\n declarations: declarationsFor(namespace),\n })\n\n const runtime: ServiceRuntime<T> = {\n name: options.name,\n sqlite,\n clock,\n faults,\n metrics,\n journal,\n rng,\n credentials,\n webhooks: options.webhooks,\n applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {\n const preset = options.presets?.[name]\n if (!preset) throw new RangeError(`no fault preset ${JSON.stringify(name)}`)\n const added = (preset.rules ?? []).map((rule, index) =>\n faults.add({\n namespace,\n ...rule,\n ...overrides,\n preset: name,\n id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : \"\"}`,\n } as FaultRule),\n )\n if (preset.webhook && options.webhooks) {\n options.webhooks.fault(namespace, {\n ...preset.webhook,\n ...(overrides.count !== undefined ? { count: overrides.count } : {}),\n })\n }\n return added\n },\n instance,\n namespaces: () => [...publicNamespaces].sort(),\n reset,\n snapshot,\n restore,\n checkpoint,\n branch,\n checkout,\n timeline,\n state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),\n fetch: async (incoming) => {\n let request = incoming\n // `/ns/<name>/\u2026` selects a namespace (and is stripped) for SDKs that cannot add headers.\n const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname)\n if (prefixed) {\n const url = new URL(request.url)\n url.pathname = prefixed[2] ?? \"/\"\n const headers = new Headers(request.headers)\n if (!headers.has(NAMESPACE_HEADER)) {\n headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1] as string))\n }\n const hasBody = request.method !== \"GET\" && request.method !== \"HEAD\"\n request = new Request(url, {\n method: request.method,\n headers,\n ...(hasBody ? { body: await request.arrayBuffer() } : {}),\n signal: request.signal,\n })\n }\n let namespace = control.namespaceOf(request)\n if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {\n const credential = options.credential(request)\n const mapped = credential !== undefined ? credentials.get(credential) : undefined\n if (mapped !== undefined) namespace = mapped\n }\n const selectedBranch = request.headers.get(BRANCH_HEADER) ?? \"main\"\n const at = request.headers.get(AT_HEADER) ?? undefined\n const stamp = (response: Response): Response => {\n // An invalid namespace is not echoed back.\n const value = NAMESPACE_PATTERN.test(namespace)\n ? `${options.name}@${version}; ns=${namespace}`\n : `${options.name}@${version}`\n try {\n response.headers.set(MOCKINGBIRD_HEADER, value)\n return response\n } catch {\n // Immutable headers (a response passed through from `fetch`): copy it.\n const copy = new Response(response.body, response)\n copy.headers.set(MOCKINGBIRD_HEADER, value)\n return copy\n }\n }\n const handled = await control.handle(request)\n if (handled) return stamp(handled)\n const started = monotonicNow()\n const url = new URL(request.url)\n const operationId = operationIdFor(request, url.pathname)\n // What a rejection records about the body. The runtime never reads the request stream \u2014\n // consuming it would break a streaming request (e.g. a bidirectional model stream) \u2014 so the\n // byte count comes from `content-length` when the client sent it, and is null otherwise.\n const contentLength = request.headers.get(\"content-length\")\n const received: RejectedRequest = {\n contentType: request.headers.get(\"content-type\"),\n bodyBytes:\n contentLength !== null && /^\\d+$/.test(contentLength) ? Number(contentLength) : null,\n transferEncoding: request.headers.get(\"transfer-encoding\"),\n }\n const log = (status: number, faultId?: string, response?: Response) => {\n const noted = response ? responseNotes(response) : undefined\n const rejected = status >= 400 && faultId === undefined\n const entry: RequestLog = {\n service: options.name,\n namespace,\n operationId,\n method: request.method,\n path: url.pathname,\n status,\n durationMs: Math.round((monotonicNow() - started) * 100) / 100,\n unmatched: options.document !== undefined && operationId === undefined,\n ...(faultId !== undefined ? { faultId } : {}),\n ...(noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {}),\n ...(noted?.adopted ? { adopted: true } : {}),\n ...(rejected ? { request: { ...received } } : {}),\n ...(rejected && noted?.issues && noted.issues.length > 0\n ? { issues: noted.issues.map((issue) => ({ ...issue })) }\n : {}),\n }\n metrics.record(entry)\n journal.record({ ...entry, at: new Date(clock.now()).toISOString() })\n options.onLog?.(entry)\n }\n if (!NAMESPACE_PATTERN.test(namespace)) {\n log(400)\n return stamp(\n new Response(\n JSON.stringify({\n error: {\n type: \"mockingbird_admin\",\n message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`,\n },\n }),\n { status: 400, headers: { \"content-type\": \"application/json\" } },\n ),\n )\n }\n if (!BRANCH_PATTERN.test(selectedBranch)) {\n log(400)\n return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN}`))\n }\n let storage: string\n try {\n if (\n at !== undefined &&\n selectedBranch === \"main\" &&\n !MUTATING_METHODS.has(request.method)\n ) {\n const point = timeline(namespace).get(at)\n storage = physicalBranch(namespace, `at_${at}`)\n let viewRng = branchRngs.get(storage)\n if (!viewRng) {\n viewRng = createRng(options.seed ?? 0)\n instanceFor(storage, namespace, viewRng)\n }\n viewRng.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n storage = ensureBranch(namespace, selectedBranch, at)\n }\n } catch (error) {\n log(409)\n return stamp(adminFail(409, error instanceof Error ? error.message : String(error)))\n }\n const hits = await faults.take({\n operationId,\n method: request.method,\n path: url.pathname,\n namespace,\n })\n const final = hits.find((hit) => hit.drop || hit.response)\n if (final?.drop) {\n log(0, final.id)\n throw new DroppedConnectionError()\n }\n if (final?.response) {\n log(final.response.status, final.id)\n return stamp(final.response)\n }\n const fired = hits.filter((hit) => hit.effect !== undefined)\n if (fired.length > 0)\n effects.set(\n request,\n fired.map((hit) => hit.effect),\n )\n let response = await instanceFor(storage, namespace).fetch(request)\n if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {\n const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch })\n response = mutableResponse(response)\n response.headers.set(CHECKPOINT_HEADER, point.id)\n }\n if (selectedBranch !== \"main\") {\n response = mutableResponse(response)\n response.headers.set(BRANCH_HEADER, selectedBranch)\n }\n if (at !== undefined) {\n response = mutableResponse(response)\n response.headers.set(AT_HEADER, at)\n }\n log(response.status, fired[0]?.id, response)\n return stamp(response)\n },\n }\n\n const control = createControlPlane({\n name: options.name,\n startedAt: wallNow(),\n wallNow,\n clock,\n faults,\n metrics,\n journal,\n defaultNamespace: DEFAULT_NAMESPACE,\n namespaces: runtime.namespaces,\n reset,\n timeTravel: {\n checkpoint: (name, branchName) => {\n const point = checkpoint(name, branchName)\n return {\n id: point.id,\n branch: point.branch,\n parent: point.parent,\n at: point.at,\n records: point.value.snapshot.records.length,\n }\n },\n branch: (branchName, branchOptions) => {\n const point = branch(branchName, branchOptions)\n return { id: point.id, branch: point.branch, parent: point.parent, at: point.at }\n },\n checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),\n retain: (name, checkpointId) => {\n timeline(name).retain(checkpointId)\n },\n release: (name, checkpointId) => timeline(name).release(checkpointId),\n inspect: (name) => {\n const history = timeline(name)\n return {\n branches: history.branches(),\n checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({\n id,\n branch: branchName,\n parent,\n at,\n })),\n }\n },\n },\n describe: options.describe ?? (() => ({})),\n ...(options.presets\n ? {\n applyPreset: (name: string, namespace: string, overrides: Partial<FaultRule>) =>\n runtime.applyPreset(name, namespace, overrides),\n }\n : {}),\n routes: {\n ...credentialRoutes(credentials),\n ...(options.webhooks ? webhookAdminRoutes(options.webhooks) : {}),\n ...(options.admin?.(runtime) ?? {}),\n // Shell routes win a colliding key. Fault presets are one of them: the admin page\n // maps `presets`, and a service route must not replace that list with a record.\n ...(options.presets ? presetRoutes(options.presets, runtime) : {}),\n ...stateAdminRoutes({\n open: stateScope,\n afterWrite: (namespace) => {\n checkpoint(namespace, \"main\")\n },\n }),\n ...adminUiRoutes(options.name, options.adminUi),\n },\n adminKey: options.adminKey,\n })\n\n return defineMock(runtime)\n}\n\nconst mutableResponse = (response: Response): Response => {\n try {\n response.headers.set(\"x-mockingbird-mutable-probe\", \"1\")\n response.headers.delete(\"x-mockingbird-mutable-probe\")\n return response\n } catch {\n return new Response(response.body, response)\n }\n}\n\nconst adminJson = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminFail = (status: number, message: string): Response =>\n adminJson(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * `PUT /__admin/credentials` accepts `{ credentials: { \"<credential>\": \"<namespace>\" } }`,\n * `[{ credential, namespace }]`, or `{ credentials: [\"<credential>\"] }` with `?namespace=`\n * (maps each to the calling namespace). `GET` lists them masked; `DELETE` removes one\n * (`?credential=`) or all.\n */\nconst credentialRoutes = (registry: CredentialRegistry): AdminRoutes => ({\n \"GET /credentials\": () =>\n adminJson(200, {\n credentials: registry.entries().map(({ credential, namespace }) => ({\n credential: maskCredential(credential),\n namespace,\n })),\n }),\n \"PUT /credentials\": ({ body, namespace }) => {\n const pairs: [string, string][] = []\n const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : undefined\n if (Array.isArray(list)) {\n for (const each of list) {\n if (typeof each === \"string\") pairs.push([each, namespace])\n else if (isObject(each) && typeof each.credential === \"string\") {\n pairs.push([\n each.credential,\n typeof each.namespace === \"string\" ? each.namespace : namespace,\n ])\n } else return adminFail(400, \"each entry is a credential string or {credential, namespace}\")\n }\n } else if (isObject(list)) {\n for (const [credential, target] of Object.entries(list)) {\n if (typeof target !== \"string\")\n return adminFail(400, `namespace for ${credential} must be a string`)\n pairs.push([credential, target])\n }\n } else if (isObject(body) && typeof body.credential === \"string\") {\n pairs.push([body.credential, typeof body.namespace === \"string\" ? body.namespace : namespace])\n } else {\n return adminFail(400, 'expected {\"credentials\": {\"<credential>\": \"<namespace>\"}}')\n }\n for (const [credential, target] of pairs) {\n if (!NAMESPACE_PATTERN.test(target))\n return adminFail(400, `bad namespace ${JSON.stringify(target)}`)\n registry.set(credential, target)\n }\n return adminJson(200, { mapped: pairs.length })\n },\n \"DELETE /credentials\": ({ url }) => {\n const credential = url.searchParams.get(\"credential\")\n if (credential === null) registry.clear()\n else registry.remove(credential)\n return adminJson(200, { status: \"ok\" })\n },\n})\n\nconst presetRoutes = <T extends ServiceInstance>(\n presets: Record<string, FaultPreset>,\n runtime: ServiceRuntime<T>,\n): AdminRoutes => ({\n \"GET /faults/presets\": () => {\n const body: FaultPresetList = {\n presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset })),\n }\n return adminJson(200, body)\n },\n \"POST /faults/presets/:name\": ({ params, body, namespace }) => {\n const name = params.name as string\n if (!presets[name])\n return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`)\n const overrides = isObject(body) ? (body as Partial<FaultRule>) : {}\n return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) })\n },\n})\n", "/** Lab-test catalog mirrored from the Junction sandbox (`GET /v3/lab_test`). */\nexport type CatalogMarker = {\n id: number\n name: string\n slug: string\n description: string | null\n lab_id: number | null\n provider_id: string | null\n type: string | null\n unit: string | null\n price: string | null\n aoe: unknown\n a_la_carte_enabled: boolean\n common_tat_days: number | null\n worst_case_tat_days: number | null\n is_orderable: boolean | null\n}\n\nexport type ExpectedResultLoinc = {\n id: number\n name: string\n slug: string\n code: string\n unit: string | null\n}\n\nexport type ExpectedResult = {\n id: number\n name: string\n slug: string\n lab_id: number | null\n provider_id: string | null\n required: boolean\n loinc: ExpectedResultLoinc | null\n}\n\nexport type LabTestRecord = {\n id: string\n slug: string\n name: string\n sample_type: string\n method: string\n price: number\n is_active: boolean\n status: string\n fasting: boolean\n lab: Record<string, unknown>\n markers: CatalogMarker[] | null\n is_delegated: boolean\n auto_generated: boolean\n has_collection_instructions: boolean | null\n common_tat_days: number | null\n worst_case_tat_days: number | null\n}\n\nexport const LAB_TEST_CATALOG: readonly LabTestRecord[] = [\n {\n id: \"c533549c-1e62-4afe-9a0e-0567a9b2bcc2\",\n slug: \"comprehensive_metabolic_panel\",\n name: \"CMP\",\n sample_type: \"serum\",\n method: \"walk_in_test\",\n price: 0,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n markers: [\n {\n id: 2075,\n name: \"Comp. Metabolic Panel (14)\",\n slug: \"comp-metabolic-panel-14\",\n description: \"Comp. Metabolic Panel (14)\",\n lab_id: 6,\n provider_id: \"322000\",\n type: \"biomarker\",\n unit: null,\n price: \"N/A\",\n aoe: {\n questions: [\n {\n id: 1,\n required: false,\n code: \"FSTING\",\n value: \"FASTING\",\n type: \"choice\",\n sequence: 1,\n answers: [\n { id: 1, code: \"N\", value: \"No\" },\n { id: 2, code: \"Y\", value: \"Yes\" },\n ],\n constraint: null,\n default: null,\n },\n ],\n },\n a_la_carte_enabled: true,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n is_orderable: true,\n },\n ],\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n },\n {\n id: \"0cb9f34f-c3df-4a13-8ca1-19429a82611b\",\n slug: \"general_wellness_female_002\",\n name: \"Female General Wellness\",\n sample_type: \"dried_blood_spot\",\n method: \"testkit\",\n price: 45,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 3,\n slug: \"ussl\",\n name: \"USSL\",\n first_line_address: \"15150 Avenue of Science, Suite 100\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n markers: null,\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: null,\n worst_case_tat_days: null,\n },\n {\n id: \"b439efda-1e07-4d2c-8afb-51771c7cc0cb\",\n slug: \"lipid_panel_athome\",\n name: \"Lipid Panel: At Home\",\n sample_type: \"serum\",\n method: \"at_home_phlebotomy\",\n price: 0,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n markers: [\n {\n id: 1975,\n name: \"Lipid Panel\",\n slug: \"lipid-panel\",\n description: \"Lipid Panel\",\n lab_id: 6,\n provider_id: \"303756\",\n type: \"biomarker\",\n unit: null,\n price: \"N/A\",\n aoe: {\n questions: [\n {\n id: 1,\n required: false,\n code: \"FSTING\",\n value: \"FASTING\",\n type: \"choice\",\n sequence: 1,\n answers: [\n { id: 1, code: \"N\", value: \"No\" },\n { id: 2, code: \"Y\", value: \"Yes\" },\n ],\n constraint: null,\n default: null,\n },\n ],\n },\n a_la_carte_enabled: true,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n is_orderable: true,\n },\n ],\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n },\n]\n\nexport const labTestById = (id: string): LabTestRecord | undefined =>\n LAB_TEST_CATALOG.find((test) => test.id === id)\n\n/**\n * Team lab inventory mirrored from the sandbox (`GET /v3/lab_tests/labs`). The endpoint\n * returns the team's full lab list \u2014 not just the labs referenced by catalog tests \u2014 in\n * this exact order.\n */\nexport const TEAM_LABS: readonly Record<string, unknown>[] = [\n {\n id: 24,\n slug: \"my_uti\",\n name: \"MyUTI\",\n first_line_address: \"No Address\",\n city: \"Chicago\",\n zipcode: \"00000\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 25,\n slug: \"sonora_quest\",\n name: \"Sonora Quest\",\n first_line_address: \"1255 West Washington Street\",\n city: \"Tempe\",\n zipcode: \"85281\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 26,\n slug: \"crl\",\n name: \"CRL\",\n first_line_address: \"11711 W 83rd Terrace\",\n city: \"Lenexa\",\n zipcode: \"66214\",\n collection_methods: [\"testkit\"],\n sample_types: [\"arm_collector\"],\n logo_url: null,\n },\n {\n id: 27,\n slug: \"mtl\",\n name: \"Molecular Testing Labs\",\n first_line_address: \"14401 SE 1st Street\",\n city: \"Vancouver\",\n zipcode: \"98684\",\n collection_methods: [\"testkit\"],\n sample_types: [\"saliva\"],\n logo_url: null,\n },\n {\n id: 22,\n slug: \"nexus\",\n name: \"Nexus\",\n first_line_address: \"313 Pleasant Street\",\n city: \"Watertown\",\n zipcode: \"02472\",\n collection_methods: [\"testkit\"],\n sample_types: [\"urine\", \"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 17,\n slug: \"precision_analytical\",\n name: \"Precision Analytical\",\n first_line_address: \"3138 NE Rivergate Street\",\n city: \"McMinnville\",\n zipcode: \"97128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 20,\n slug: \"boston_heart_at_home_kit\",\n name: \"Boston Heart At-Home Kit\",\n first_line_address: \"200 Crossing Boulevard\",\n city: \"Framingham\",\n zipcode: \"01702\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 7,\n slug: \"diagnosticsolutions\",\n name: \"Diagnostic Solutions\",\n first_line_address: \" 5895 Shiloh Rd\",\n city: \"Alpharetta\",\n zipcode: \"30005\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 8,\n slug: \"cellsciencesystems\",\n name: \"Cell Science Systems\",\n first_line_address: \"852 S. Military Trail\",\n city: \"Deerfield Beach\",\n zipcode: \"33442\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 13,\n slug: \"bioreference\",\n name: \"BioReference\",\n first_line_address: \"481 Edward H Ross Dr\",\n city: \"Elmwood park\",\n zipcode: \"07407\",\n collection_methods: [\"walk_in_test\", \"at_home_phlebotomy\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 40,\n slug: \"us_biotek\",\n name: \"US Biotek\",\n first_line_address: \"16020 Linden Ave N\",\n city: \"Shoreline\",\n zipcode: \"98133\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 21,\n slug: \"ihd\",\n name: \"IHD\",\n first_line_address: \"1936 E Deere Ave. Suite 115\",\n city: \"Santa Ana\",\n zipcode: \"92705\",\n collection_methods: [\"testkit\", \"at_home_phlebotomy\", \"walk_in_test\"],\n sample_types: [\"urine\", \"serum\"],\n logo_url: null,\n },\n {\n id: 4,\n slug: \"quest\",\n name: \"Quest\",\n first_line_address: \"Quest\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 23,\n slug: \"sanocardio\",\n name: \"SanoCardio\",\n first_line_address: \"N/A\",\n city: \"N/a\",\n zipcode: \"N/A\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 1,\n slug: \"ayumetrix\",\n name: \"Ayumetrix\",\n first_line_address: \"17387 SW 63rd Ave\",\n city: \"Lake Oswego\",\n zipcode: \"97035\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 9,\n slug: \"genova\",\n name: \"Genova Diagnostics\",\n first_line_address: \" P.O. Box 3220\",\n city: \"Asheville\",\n zipcode: \"28802\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 14,\n slug: \"zrt\",\n name: \"ZRT Laboratory\",\n first_line_address: \"8605 SW Creekside Pl\",\n city: \"Beaverton\",\n zipcode: \"97008\",\n collection_methods: [\"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 3,\n slug: \"ussl\",\n name: \"USSL\",\n first_line_address: \"15150 Avenue of Science, Suite 100\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 2,\n slug: \"spiriplex\",\n name: \"Spiriplex\",\n first_line_address: \"100 Tri State International #100\",\n city: \"Lincolnshire\",\n zipcode: \"60069\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n]\n\n/** Panel constituents mirrored from the sandbox (`GET /v3/lab_tests/{id}/markers`). */\nexport const EXPECTED_RESULTS: Readonly<Record<string, readonly ExpectedResult[]>> = {\n \"b439efda-1e07-4d2c-8afb-51771c7cc0cb\": [\n {\n id: 1109,\n name: \"Cholesterol, Total\",\n slug: \"cholesterol-total\",\n lab_id: 6,\n provider_id: \"001065\",\n required: true,\n loinc: {\n id: 11940,\n name: \"Cholesterol [Mass/Vol]\",\n slug: \"cholesterol-mass-vol\",\n code: \"2093-3\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1110,\n name: \"HDL Cholesterol\",\n slug: \"hdl-cholesterol\",\n lab_id: 6,\n provider_id: \"011817\",\n required: true,\n loinc: {\n id: 11858,\n name: \"Cholesterol in HDL [Mass/Vol]\",\n slug: \"cholesterol-in-hdl-mass-vol\",\n code: \"2085-9\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1112,\n name: \"Triglycerides\",\n slug: \"triglycerides\",\n lab_id: 6,\n provider_id: \"001172\",\n required: true,\n loinc: {\n id: 16384,\n name: \"Triglyceride [Mass/Vol]\",\n slug: \"triglyceride-mass-vol\",\n code: \"2571-8\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 242764,\n name: \"LDL Calc Comment:\",\n slug: \"ldl-calc-comment\",\n lab_id: 6,\n provider_id: \"011926\",\n required: true,\n loinc: {\n id: 53832,\n name: \"Service comment [Interp]\",\n slug: \"service-comment-interp\",\n code: \"8251-1\",\n unit: null,\n },\n },\n {\n id: 242780,\n name: \"VLDL Cholesterol Cal\",\n slug: \"vldl-cholesterol-cal\",\n lab_id: 6,\n provider_id: \"011925\",\n required: true,\n loinc: {\n id: 5062,\n name: \"Cholesterol in VLDL Calc [Mass/Vol]\",\n slug: \"cholesterol-in-vldl-calc-mass-vol\",\n code: \"13458-5\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 242790,\n name: \"LDL Chol Calc (NIH)\",\n slug: \"ldl-chol-calc-nih\",\n lab_id: 6,\n provider_id: \"012065\",\n required: true,\n loinc: {\n id: 5060,\n name: \"Cholesterol in LDL Calc [Mass/Vol]\",\n slug: \"cholesterol-in-ldl-calc-mass-vol\",\n code: \"13457-7\",\n unit: \"mg/dL\",\n },\n },\n ],\n \"c533549c-1e62-4afe-9a0e-0567a9b2bcc2\": [\n {\n id: 364,\n name: \"AST (SGOT)\",\n slug: \"ast-sgot\",\n lab_id: 6,\n provider_id: \"001123\",\n required: true,\n loinc: {\n id: 10684,\n name: \"AST [Catalytic activity/Vol]\",\n slug: \"ast-catalytic-activity-vol\",\n code: \"1920-8\",\n unit: \"U/L\",\n },\n },\n {\n id: 471,\n name: \"ALT (SGPT)\",\n slug: \"alt-sgpt\",\n lab_id: 6,\n provider_id: \"001545\",\n required: true,\n loinc: {\n id: 9362,\n name: \"ALT [Catalytic activity/Vol]\",\n slug: \"alt-catalytic-activity-vol\",\n code: \"1742-6\",\n unit: \"U/L\",\n },\n },\n {\n id: 1045,\n name: \"BUN\",\n slug: \"bun\",\n lab_id: 6,\n provider_id: \"001040\",\n required: true,\n loinc: {\n id: 19958,\n name: \"Urea nitrogen [Mass/Vol]\",\n slug: \"urea-nitrogen-mass-vol\",\n code: \"3094-0\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1050,\n name: \"eGFR\",\n slug: \"egfr\",\n lab_id: 6,\n provider_id: \"100779\",\n required: true,\n loinc: {\n id: 61049,\n name: \"GFR/1.73 sq M.predicted Creatinine-based formula (CKD-EPI 2021) (S/P/Bld) [Vol rate/Area]\",\n slug: \"gfr-1-73-sq-m-predicted-creatinine-based-formula-ckd-epi-2021-s-p-bld-vol-rate-area\",\n code: \"98979-8\",\n unit: \"mL/min/{1.73_m2}\",\n },\n },\n {\n id: 1051,\n name: \"Creatinine\",\n slug: \"creatinine\",\n lab_id: 6,\n provider_id: \"001370\",\n required: true,\n loinc: {\n id: 12675,\n name: \"Creatinine [Mass/Vol]\",\n slug: \"creatinine-mass-vol\",\n code: \"2160-0\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1238,\n name: \"Protein, Total\",\n slug: \"protein-total\",\n lab_id: 6,\n provider_id: \"001073\",\n required: true,\n loinc: {\n id: 18410,\n name: \"Protein [Mass/Vol]\",\n slug: \"protein-mass-vol\",\n code: \"2885-2\",\n unit: \"g/dL\",\n },\n },\n {\n id: 1266,\n name: \"Calcium\",\n slug: \"calcium\",\n lab_id: 6,\n provider_id: \"001016\",\n required: true,\n loinc: {\n id: 9833,\n name: \"Calcium [Mass/Vol]\",\n slug: \"calcium-mass-vol\",\n code: \"17861-6\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1267,\n name: \"BUN/Creatinine Ratio\",\n slug: \"bun-creatinine-ratio\",\n lab_id: 6,\n provider_id: \"011577\",\n required: true,\n loinc: {\n id: 19962,\n name: \"Urea nitrogen/Creatinine [Mass ratio]\",\n slug: \"urea-nitrogen-creatinine-mass-ratio\",\n code: \"3097-3\",\n unit: \"mg/mg{creat}\",\n },\n },\n {\n id: 1268,\n name: \"Carbon Dioxide, Total\",\n slug: \"carbon-dioxide-total\",\n lab_id: 6,\n provider_id: \"001578\",\n required: true,\n loinc: {\n id: 11320,\n name: \"CO2 [Moles/Vol]\",\n slug: \"co2-moles-vol\",\n code: \"2028-9\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1269,\n name: \"Glucose\",\n slug: \"glucose\",\n lab_id: 6,\n provider_id: \"001032\",\n required: true,\n loinc: {\n id: 14491,\n name: \"Glucose [Mass/Vol]\",\n slug: \"glucose-mass-vol\",\n code: \"2345-7\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1270,\n name: \"Potassium\",\n slug: \"potassium\",\n lab_id: 6,\n provider_id: \"001180\",\n required: true,\n loinc: {\n id: 18272,\n name: \"Potassium [Moles/Vol]\",\n slug: \"potassium-moles-vol\",\n code: \"2823-3\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1271,\n name: \"Sodium\",\n slug: \"sodium\",\n lab_id: 6,\n provider_id: \"001198\",\n required: true,\n loinc: {\n id: 18724,\n name: \"Sodium [Moles/Vol]\",\n slug: \"sodium-moles-vol\",\n code: \"2951-2\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1272,\n name: \"Chloride\",\n slug: \"chloride\",\n lab_id: 6,\n provider_id: \"001206\",\n required: true,\n loinc: {\n id: 11738,\n name: \"Chloride [Moles/Vol]\",\n slug: \"chloride-moles-vol\",\n code: \"2075-0\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1370,\n name: \"Bilirubin, Total\",\n slug: \"bilirubin-total\",\n lab_id: 6,\n provider_id: \"001099\",\n required: true,\n loinc: {\n id: 11239,\n name: \"Bilirubin [Mass/Vol]\",\n slug: \"bilirubin-mass-vol\",\n code: \"1975-2\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1956,\n name: \"Albumin\",\n slug: \"albumin\",\n lab_id: 6,\n provider_id: \"001081\",\n required: true,\n loinc: {\n id: 9462,\n name: \"Albumin [Mass/Vol]\",\n slug: \"albumin-mass-vol\",\n code: \"1751-7\",\n unit: \"g/dL\",\n },\n },\n {\n id: 2304,\n name: \"Globulin, Total\",\n slug: \"globulin-total\",\n lab_id: 6,\n provider_id: \"012039\",\n required: true,\n loinc: {\n id: 2951,\n name: \"Globulin Calc (S) [Mass/Vol]\",\n slug: \"globulin-calc-s-mass-vol\",\n code: \"10834-0\",\n unit: \"g/L\",\n },\n },\n {\n id: 13,\n name: \"Alkaline Phosphatase\",\n slug: \"alkaline-phosphatase\",\n lab_id: 6,\n provider_id: \"001107\",\n required: true,\n loinc: {\n id: 45530,\n name: \"ALP [Catalytic activity/Vol]\",\n slug: \"alp-catalytic-activity-vol\",\n code: \"6768-6\",\n unit: \"U/L\",\n },\n },\n ],\n}\n\nexport const expectedResultsFor = (labTestId: string): readonly ExpectedResult[] =>\n EXPECTED_RESULTS[labTestId] ?? []\n", "/**\n * Restrictions the Junction sandbox imposes that production does not. The mock exists\n * to escape them, so every one is off unless a suite asks for it.\n */\nimport { HttpError } from \"@crvouga/mockingbird-service\"\n\n/** Key prefixes of sandbox team keys. `corpus pull` and `verify` refuse any other key. */\nexport const SANDBOX_KEY_PREFIXES = [\"sk_us_\", \"sk_eu_\"] as const\n\nexport const isSandboxKey = (key: string): boolean =>\n SANDBOX_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))\n\nexport type JunctionLimits = {\n /**\n * Live users a team may hold; creating one more answers the sandbox's\n * \"maximum of 50 Sandbox users\" 400. Deleted users free their slot. `null`: unlimited.\n */\n maxUsers: number | null\n /** Refuse `POST /v3/order/{id}/test` unless the API key is a sandbox key (`sk_us_\u2026`/`sk_eu_\u2026`). */\n simulateRequiresSandbox: boolean\n /** Vendor requests per second per namespace before a 429. `null`: unlimited. */\n rateLimitPerSecond: number | null\n}\n\nexport type JunctionLimitsInput = {\n [K in keyof JunctionLimits]?: JunctionLimits[K] | undefined\n}\n\n/** Every limit off: what a default instance enforces. */\nexport const DEFAULT_LIMITS: Readonly<JunctionLimits> = {\n maxUsers: null,\n simulateRequiresSandbox: false,\n rateLimitPerSecond: null,\n}\n\n/** The 400 the sandbox answers once a team holds its 50th user, byte for byte. */\nexport const sandboxUserQuotaBody = (max: number) => ({\n detail: {\n error_type: \"INVALID_REQUEST\",\n error_message: `You have reached the maximum of ${max} Sandbox users`,\n },\n})\n\nconst positiveOrNull = (value: unknown, field: string): number | null => {\n if (value === null) return null\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)\n throw new TypeError(`${field} must be a non-negative integer, or null for unlimited`)\n return value\n}\n\n/** Apply `input` over `base`; `undefined` keeps a value, `null` lifts a numeric limit. */\nexport const mergeLimits = (base: JunctionLimits, input: unknown): JunctionLimits => {\n if (typeof input !== \"object\" || input === null || Array.isArray(input))\n throw new TypeError(\"limits must be an object\")\n const record = input as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (!(key in DEFAULT_LIMITS))\n throw new TypeError(`unknown limit ${key}; one of ${Object.keys(DEFAULT_LIMITS).join(\", \")}`)\n }\n const next = { ...base }\n if (record.maxUsers !== undefined) next.maxUsers = positiveOrNull(record.maxUsers, \"maxUsers\")\n if (record.rateLimitPerSecond !== undefined)\n next.rateLimitPerSecond = positiveOrNull(record.rateLimitPerSecond, \"rateLimitPerSecond\")\n if (record.simulateRequiresSandbox !== undefined) {\n if (typeof record.simulateRequiresSandbox !== \"boolean\")\n throw new TypeError(\"simulateRequiresSandbox must be a boolean\")\n next.simulateRequiresSandbox = record.simulateRequiresSandbox\n }\n return next\n}\n\n/** Throw the sandbox's quota error when one more user would exceed `maxUsers`. */\nexport const checkUserQuota = (limits: JunctionLimits, liveUsers: number): void => {\n if (limits.maxUsers !== null && liveUsers >= limits.maxUsers)\n throw new HttpError(400, sandboxUserQuotaBody(limits.maxUsers))\n}\n\n/**\n * The refusal for a simulate call outside the sandbox. Shape-plausible only: production\n * has not been observed answering it, and the mock never enforces it by default.\n */\nexport const checkSimulateAllowed = (limits: JunctionLimits, apiKey: string | null): void => {\n if (limits.simulateRequiresSandbox && !isSandboxKey(apiKey ?? \"\"))\n throw new HttpError(400, { detail: \"Order simulation is only available in sandbox\" })\n}\n\n/** A fixed one-second window of wall time; a frozen mock clock must not stall it. */\nexport class RateWindow {\n private windowStart = 0\n private count = 0\n\n /** Whether one more request fits under `perSecond` now. */\n take(perSecond: number | null, nowMs = Date.now()): boolean {\n if (perSecond === null) return true\n if (nowMs - this.windowStart >= 1000) {\n this.windowStart = nowMs\n this.count = 0\n }\n if (this.count >= perSecond) return false\n this.count++\n return true\n }\n}\n", "import { Collection, IdSequence, opaqueToken } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport {\n EXPECTED_RESULTS,\n type ExpectedResult,\n LAB_TEST_CATALOG,\n type LabTestRecord,\n TEAM_LABS,\n} from \"./catalog.js\"\nimport type { IdentityMode } from \"./fixtures.js\"\nimport { DEFAULT_LIMITS, type JunctionLimits } from \"./limits.js\"\n\nexport type { CatalogMarker, ExpectedResult, LabTestRecord } from \"./catalog.js\"\nexport { expectedResultsFor, LAB_TEST_CATALOG, labTestById, TEAM_LABS } from \"./catalog.js\"\n\nexport type GetCacheEntry = {\n status: number\n headers: Record<string, string>\n body: unknown\n}\n\nconst sortedQueryString = (params: URLSearchParams): string => {\n const entries = [...params.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => {\n const keyOrder = leftKey.localeCompare(rightKey)\n return keyOrder === 0 ? leftValue.localeCompare(rightValue) : keyOrder\n })\n return new URLSearchParams(entries).toString()\n}\n\nexport const observationCacheKey = (url: URL | string, method = \"GET\", body?: unknown): string => {\n const parsed = typeof url === \"string\" ? new URL(url, \"https://observation.local\") : url\n const query = sortedQueryString(parsed.searchParams)\n const pathAndQuery = `${parsed.pathname}${query ? `?${query}` : \"\"}`\n const head = `${method.toUpperCase()} ${pathAndQuery}`\n if (body === undefined) return head\n return `${head} ${JSON.stringify(body)}`\n}\n\nexport type UserInfoRecord = Record<string, unknown>\n\nexport type AppointmentModality = \"phlebotomy\" | \"patient_service_center\"\nexport type AppointmentProviderName = \"getlabs\" | \"phlebfinders\" | \"quest\"\nexport type AppointmentStatus =\n | \"confirmed\"\n | \"pending\"\n | \"reserved\"\n | \"in_progress\"\n | \"completed\"\n | \"cancelled\"\nexport type AppointmentEventStatus =\n | \"pending\"\n | \"reserved\"\n | \"scheduled\"\n | \"completed\"\n | \"cancelled\"\n | \"in_progress\"\n\nexport type AppointmentEventRecord = {\n created_at: string\n status: AppointmentEventStatus\n data: Record<string, unknown> | null\n}\n\nexport type AppointmentRecord = {\n id: string\n order_id: string\n user_id: string\n provider_id: string\n external_id: string | null\n type: AppointmentModality\n provider: AppointmentProviderName\n status: AppointmentStatus\n event_status: AppointmentEventStatus\n start_at: string | null\n end_at: string | null\n iana_timezone: string | null\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n can_reschedule: boolean\n booking_key: string | null\n site_code: string | null\n appointment_notes: string | null\n order_transaction_id: string | null\n event_data: Record<string, unknown> | null\n events: AppointmentEventRecord[]\n created_at: string\n updated_at: string\n}\n\nexport type BookingKeyRecord = {\n key: string\n start: string\n end: string\n expires_at: string | null\n price: number\n is_priority: boolean\n num_appointments_available: number\n modality: AppointmentModality\n provider: AppointmentProviderName\n site_code: string | null\n zip_code: string\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n consumed_by_order_id: string | null\n created_at: string\n}\n\nexport type PendingSimulateTransition = {\n order_id: string\n due_at: number\n final_status: string\n flags: Record<string, unknown> | null\n}\n\nexport type JunctionWebhookEvent = {\n event_type: \"labtest.order.created\" | \"labtest.order.updated\" | \"labtest.appointment.updated\"\n data: Record<string, unknown>\n team_id: string\n user_id: string\n client_user_id: string\n}\n\nexport type WebhookEventRecord = {\n sequence: number\n event: JunctionWebhookEvent\n}\n\nexport type WebhookDeliveryAttempt = {\n message_id: string\n event: JunctionWebhookEvent\n attempt: number\n scheduled_at: string\n timeout_ms: number\n acknowledged: boolean\n}\n\nexport const WEBHOOK_RETRY_DELAYS_MS = [\n 0, 5_000, 300_000, 1_800_000, 7_200_000, 18_000_000, 36_000_000, 36_000_000,\n] as const\n\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\nconst seededRandom = (seed: number) => {\n let value = seed >>> 0\n return () => {\n value = (value * 1664525 + 1013904223) >>> 0\n return value / 0x1_0000_0000\n }\n}\n\nexport type UserRecord = {\n user_id: string\n team_id: string\n client_user_id: string\n created_on: string\n connected_sources: unknown[]\n fallback_time_zone: { id: string; source_slug: string; updated_at: string } | null\n fallback_birth_date: { value: string; source_slug: string; updated_at: string } | null\n ingestion_start: string | null\n ingestion_end: string | null\n}\n\n/** Fixed mock team id \u2014 volatile on the real side, stable in the mock. */\nexport const MOCK_TEAM_ID = \"11111111-1111-4111-8111-111111111111\"\n\n/** Deterministic UUID derived from a salt + sequence (version/variant bits fixed). */\nexport const deterministicUuid = (input: string): string => {\n const raw = opaqueToken(input, 32)\n let hex = \"\"\n for (let i = 0; i < raw.length && hex.length < 32; i++) {\n hex += (raw.charCodeAt(i) % 16).toString(16)\n }\n hex = hex.padEnd(32, \"0\").slice(0, 32)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\nexport type OrderEventRecord = {\n id: number\n created_at: string\n status: string\n status_detail: null\n}\n\nexport type OrderTransactionEmbed = {\n id: string\n status: \"active\" | \"completed\" | \"cancelled\"\n orders: Array<{\n id: string\n low_level_status: string\n low_level_status_created_at: string\n origin: string\n parent_id: null\n created_at: string\n updated_at: string\n }>\n}\n\nexport type OrderRecord = {\n id: string\n user_id: string\n team_id: string\n patient_details: Record<string, unknown>\n patient_address: Record<string, unknown>\n lab_test: LabTestRecord\n details: Record<string, unknown>\n sample_id: string | null\n notes: null\n clinical_notes: string | null\n passthrough: string | null\n created_at: string\n updated_at: string\n events: OrderEventRecord[]\n status: string\n last_event: OrderEventRecord\n physician: { first_name: string; last_name: string; npi: string }\n health_insurance_id: null\n requisition_form_url: string | null\n shipping_details: null\n has_abn: boolean\n billing_type: string\n priority: boolean\n activate_by: null\n icd_codes: string[] | null\n interpretation: string | null\n has_missing_results: boolean | null\n result_types: string[] | null\n expected_result_by_date: string | null\n worst_case_result_by_date: string | null\n origin: string\n order_transaction: OrderTransactionEmbed\n}\n\n/**\n * A lab account as the ordering rules read it. Structurally `LabAccountRecord` from\n * lab-accounts.ts, restated here because that module imports this one.\n */\nexport type StoredLabAccount = {\n id: string\n lab: string\n org_id: string | null\n status: \"active\" | \"pending\" | \"suspended\" | \"ready_to_launch\"\n delegated_flow: \"order_delegated\" | \"result_delegated\" | \"fully_delegated\" | \"not_delegated\"\n provider_account_id: string\n account_name: string | null\n default_clinical_notes: string | null\n business_units: string[] | null\n allowed_billing: Record<string, readonly string[]>\n team_id_allowlist: readonly string[]\n}\n\n/**\n * A chosen result for one order, installed through the admin API. Replaces the\n * generated biomarker lines, so a suite can assert on an exact payload \u2014 an abnormal\n * panel, a critical value, a missing marker \u2014 instead of whatever the generator made.\n */\nexport type ResultFixture = {\n /** The fixture's name, for logs and `GET /__admin/results`. */\n name: string\n results?: unknown[]\n missing_results?: unknown[] | null\n interpretation?: string\n /** Served from `GET /v3/order/{id}/result/pdf` instead of the generated PDF. */\n pdf_base64?: string\n}\n\n/**\n * How serviceability reads answer a ZIP the loaded corpus has no record for.\n *\n * - `synthetic`: invent plausible coverage. Right for property tests that walk random ZIPs.\n * - `corpus`: refuse with a documented Mockingbird error. Right for a mock standing in for\n * the vendor, where invented coverage would silently disagree with production.\n */\nexport type GeoMode = \"synthetic\" | \"corpus\"\n\nexport type WebhookPublisher = (event: JunctionWebhookEvent) => void\n\nexport type JunctionWebhookOptions = {\n seed?: number\n jitterRatio?: number\n timeoutMs?: number\n}\n\nexport class JunctionState {\n private readonly publishEvent: WebhookPublisher | undefined\n private readonly webhookRandom: () => number\n private readonly webhookJitterRatio: number\n private readonly webhookTimeoutMs: number\n readonly users: Collection<UserRecord>\n readonly ids: IdSequence\n readonly byClientId: Collection<{ user_id: string }>\n readonly deletedUsers: Collection<{ user_id: string }>\n readonly userInfo: Collection<UserInfoRecord>\n readonly orders: Collection<OrderRecord>\n readonly orderIdempotency: Collection<{\n order_id: string\n response: unknown\n fingerprint: string\n }>\n readonly cancelIdempotency: Collection<{ order_id: string; response: unknown }>\n\n readonly appointments: Collection<AppointmentRecord>\n readonly appointmentsByOrder: Collection<{ appointment_id: string }>\n readonly bookingKeys: Collection<BookingKeyRecord>\n readonly pendingSimulateTransitions: Collection<PendingSimulateTransition>\n\n readonly orderByTransaction: Collection<{ order_id: string }>\n /**\n * The lab account each order was placed with (`null`: Junction's platform account). Kept\n * off the order record: Junction's `ClientFacingOrder` has no `lab_account_id`.\n */\n readonly orderLabAccounts: Collection<{ lab_account_id: string | null }>\n readonly webhookEvents: Collection<WebhookEventRecord>\n readonly webhookDeliveryAttempts: Collection<WebhookDeliveryAttempt>\n\n readonly labTests: Collection<LabTestRecord>\n readonly labs: Collection<Record<string, unknown>>\n readonly labAccounts: Collection<StoredLabAccount>\n readonly resultFixtures: Collection<ResultFixture>\n readonly expectedResults: Collection<ExpectedResult[]>\n readonly getCache: Collection<GetCacheEntry>\n\n /** Configuration, not data: set by JunctionAPI and re-applied on reset. */\n geoMode: GeoMode = \"synthetic\"\n /** The team this mock answers as: `team_id` on users and orders, and lab-account linking. */\n teamId: string = MOCK_TEAM_ID\n /** Sandbox-only restrictions to enforce; every one is off by default. */\n limits: JunctionLimits = { ...DEFAULT_LIMITS }\n /** Lab slug \u2192 the `billing_type` an order for that lab gets when it omits one. */\n defaultBillingTypes: Readonly<Record<string, string>> = {}\n /** Whether an unknown `user_id` is refused (`strict`) or created on first use. */\n identity: IdentityMode = \"strict\"\n private webhooksMuted = 0\n private readonly adoptedRequests = new WeakSet<Request>()\n /** ZIPs the loaded corpus has serviceability records for. */\n coveredZips: ReadonlySet<string> = new Set()\n /** Identifies the loaded corpus in errors and `/health`. */\n corpusLabel: string | undefined\n /**\n * The loaded corpus's recorded reads. Immutable and shared by every namespace, so it\n * lives outside SQLite: copying hundreds of large bodies into each namespace would\n * make a new namespace cost seconds, and snapshots would copy them too.\n */\n corpusObservations: ReadonlyMap<string, GetCacheEntry> = new Map()\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n publisher?: WebhookPublisher,\n webhookOptions: JunctionWebhookOptions = {},\n ) {\n this.publishEvent = publisher\n this.webhookRandom = seededRandom(webhookOptions.seed ?? 0x4a554e43)\n this.webhookJitterRatio = Math.max(0, Math.min(webhookOptions.jitterRatio ?? 0.1, 1))\n this.webhookTimeoutMs = Math.max(1, webhookOptions.timeoutMs ?? 15_000)\n this.users = new Collection(sqlite, namespace, \"users\")\n this.byClientId = new Collection(sqlite, namespace, \"users_by_client\")\n this.deletedUsers = new Collection(sqlite, namespace, \"users_deleted\")\n this.userInfo = new Collection(sqlite, namespace, \"user_info\")\n this.orders = new Collection(sqlite, namespace, \"orders\")\n this.orderIdempotency = new Collection(sqlite, namespace, \"orders_idempotency\")\n this.cancelIdempotency = new Collection(sqlite, namespace, \"cancel_idempotency\")\n this.appointments = new Collection(sqlite, namespace, \"appointments\")\n this.appointmentsByOrder = new Collection(sqlite, namespace, \"appointments_by_order\")\n this.bookingKeys = new Collection(sqlite, namespace, \"booking_keys\")\n this.pendingSimulateTransitions = new Collection(\n sqlite,\n namespace,\n \"pending_simulate_transitions\",\n )\n this.orderByTransaction = new Collection(sqlite, namespace, \"orders_by_transaction\")\n this.orderLabAccounts = new Collection(sqlite, namespace, \"order_lab_accounts\")\n this.webhookEvents = new Collection(sqlite, namespace, \"webhook_events\")\n this.webhookDeliveryAttempts = new Collection(sqlite, namespace, \"webhook_delivery_attempts\")\n this.labTests = new Collection(sqlite, namespace, \"lab_tests\")\n this.labs = new Collection(sqlite, namespace, \"labs\")\n this.labAccounts = new Collection(sqlite, namespace, \"lab_accounts\")\n this.resultFixtures = new Collection(sqlite, namespace, \"result_fixtures\")\n this.expectedResults = new Collection(sqlite, namespace, \"expected_results\")\n this.getCache = new Collection(sqlite, namespace, \"get_cache\")\n this.ids = new IdSequence(sqlite, namespace, \"junction\")\n this.seedDefaultCatalog()\n }\n\n seedDefaultCatalog(): void {\n this.replaceCatalog({\n labTests: [...LAB_TEST_CATALOG],\n labs: [...TEAM_LABS],\n expectedResults: Object.fromEntries(\n Object.entries(EXPECTED_RESULTS).map(([id, results]) => [id, [...results]]),\n ),\n })\n }\n\n private clearCollection<T>(collection: Collection<T>): void {\n for (const entry of collection.list()) collection.delete(entry.id)\n }\n\n labKeyOf(lab: Record<string, unknown>): string {\n if (lab.id !== undefined && lab.id !== null) return String(lab.id)\n if (typeof lab.slug === \"string\" && lab.slug.length > 0) return lab.slug\n return opaqueToken(`junction:lab:${JSON.stringify(lab)}`, 16)\n }\n\n labTestById(id: string): LabTestRecord | undefined {\n return this.labTests.get(id)\n }\n\n upsertLabTest(test: LabTestRecord, expectedResults?: readonly ExpectedResult[]): void {\n const existing = this.labTests.get(test.id)\n let next = clone(test)\n if (existing) {\n const incomingMarkers = next.markers?.length ?? 0\n const existingMarkers = existing.markers?.length ?? 0\n // Order embeds are often thinner than catalog GETs \u2014 keep richer marker/method\n // data so create_order method matching stays aligned with Vital.\n if (incomingMarkers === 0 && existingMarkers > 0) {\n next = { ...next, markers: existing.markers }\n }\n if (\n (typeof next.method !== \"string\" || next.method.length === 0) &&\n typeof existing.method === \"string\" &&\n existing.method.length > 0\n ) {\n next = { ...next, method: existing.method }\n }\n if (existing.auto_generated !== true && next.auto_generated === true) {\n next = {\n ...next,\n auto_generated: false,\n method: existing.method,\n name: existing.name,\n slug: existing.slug,\n }\n }\n this.labTests.update(test.id, next)\n } else {\n this.labTests.insert(test.id, next)\n }\n // Never clobber seeded panel expansions (e.g. Lipid \u2192 6 LOINCs) when callers\n // only pass the lab_test envelope from an order payload.\n if (expectedResults === undefined && this.expectedResults.get(test.id)) return\n const fromNested = (next.markers ?? []).flatMap((marker) => {\n const nested = (marker as { expected_results?: unknown }).expected_results\n if (!Array.isArray(nested) || nested.length === 0) return []\n return nested.filter(\n (entry): entry is ExpectedResult =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n })\n const expected =\n expectedResults ??\n (fromNested.length > 0\n ? fromNested\n : (next.markers ?? []).map((marker) => ({\n id: marker.id,\n name: marker.name,\n slug: marker.slug,\n lab_id: marker.lab_id,\n provider_id: marker.provider_id,\n required: true,\n loinc: null,\n })))\n if (this.expectedResults.get(test.id)) this.expectedResults.update(test.id, [...expected])\n else this.expectedResults.insert(test.id, [...expected])\n }\n\n listLabTests(): LabTestRecord[] {\n return this.labTests.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n listLabs(): Record<string, unknown>[] {\n return this.labs.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n listLabAccounts(): StoredLabAccount[] {\n return this.labAccounts.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n expectedResultsFor(labTestId: string): ExpectedResult[] {\n return this.expectedResults.get(labTestId) ?? []\n }\n\n replaceCatalog(input: {\n labTests: readonly LabTestRecord[]\n labs: readonly Record<string, unknown>[]\n expectedResults: Readonly<Record<string, readonly ExpectedResult[]>>\n }): void {\n this.clearCollection(this.labTests)\n this.clearCollection(this.labs)\n this.clearCollection(this.expectedResults)\n for (const test of input.labTests) this.labTests.insert(test.id, clone(test))\n for (const lab of input.labs) this.labs.insert(this.labKeyOf(lab), clone(lab))\n for (const [labTestId, results] of Object.entries(input.expectedResults)) {\n this.expectedResults.insert(labTestId, clone([...results]))\n }\n }\n\n replaceLabAccounts(entries: readonly StoredLabAccount[]): void {\n this.clearCollection(this.labAccounts)\n for (const entry of entries) this.labAccounts.insert(entry.id, clone(entry))\n }\n\n putGetCache(key: string, entry: GetCacheEntry): void {\n this.getCache.insert(key, clone(entry))\n }\n\n /** A recorded read: one seeded into this namespace first, then the shared corpus. */\n getGetCache(key: string): GetCacheEntry | undefined {\n const entry = this.getCache.get(key) ?? this.corpusObservations.get(key)\n return entry ? clone(entry) : undefined\n }\n\n installGetCache(entries: Iterable<[string, GetCacheEntry]>): void {\n for (const [key, entry] of entries) this.putGetCache(key, entry)\n }\n\n /**\n * Materialize booking_key records from a cached availability payload so subsequent\n * book/reschedule calls succeed against observation-seeded mocks.\n */\n hydrateBookingKeysFromAvailability(\n body: unknown,\n nowMs: number,\n zipCode = \"00000\",\n modalityHint?: AppointmentModality,\n ): void {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return\n const root = body as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n const slotEntries: unknown[] = []\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) {\n slotEntries.push(day)\n continue\n }\n const daySlots = (day as Record<string, unknown>).slots\n if (Array.isArray(daySlots)) slotEntries.push(...daySlots)\n else if (typeof (day as Record<string, unknown>).booking_key === \"string\") {\n slotEntries.push(day)\n }\n }\n const zip = /^\\d{5}/.test(zipCode) ? zipCode.slice(0, 5) : \"00000\"\n const zipPrefix = Number(zip.slice(0, 3))\n const cityState =\n zipPrefix >= 850 && zipPrefix <= 865\n ? { city: \"Phoenix\", state: \"AZ\" }\n : zipPrefix >= 900\n ? { city: \"Los Angeles\", state: \"CA\" }\n : zipPrefix >= 800\n ? { city: \"Denver\", state: \"CO\" }\n : zipPrefix >= 600\n ? { city: \"Chicago\", state: \"IL\" }\n : zipPrefix >= 300 && zipPrefix < 400\n ? { city: \"Atlanta\", state: \"GA\" }\n : { city: \"New York\", state: \"NY\" }\n const location =\n zip === \"85004\"\n ? { lat: 33.6242904, lng: -111.9283407 }\n : {\n lat: 30 + (zipPrefix % 20) * 0.4,\n lng: -120 + (zipPrefix % 30) * 0.5,\n }\n for (const entry of slotEntries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const slot = entry as Record<string, unknown>\n const bookingKey = typeof slot.booking_key === \"string\" ? slot.booking_key : \"\"\n if (bookingKey === \"\" || this.bookingKeys.get(bookingKey)) continue\n const start = typeof slot.start === \"string\" ? slot.start : new Date(nowMs).toISOString()\n const end =\n typeof slot.end === \"string\" ? slot.end : new Date(nowMs + 45 * 60_000).toISOString()\n const modality: AppointmentModality =\n modalityHint ??\n (typeof slot.site_code === \"string\" && slot.site_code.length > 0\n ? \"patient_service_center\"\n : \"phlebotomy\")\n this.bookingKeys.insert(bookingKey, {\n key: bookingKey,\n start,\n end,\n expires_at: typeof slot.expires_at === \"string\" ? slot.expires_at : null,\n price: typeof slot.price === \"number\" ? slot.price : 0,\n is_priority: slot.is_priority === true,\n num_appointments_available:\n typeof slot.num_appointments_available === \"number\" ? slot.num_appointments_available : 1,\n modality,\n provider: modality === \"patient_service_center\" ? \"quest\" : \"getlabs\",\n site_code: typeof slot.site_code === \"string\" ? slot.site_code : null,\n zip_code: zip,\n address: {\n first_line: \"1 Main St\",\n second_line: \"\",\n city: cityState.city,\n state: cityState.state,\n zip_code: zip,\n unit: null,\n access_notes: null,\n },\n location,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n })\n }\n }\n\n cacheKeyForRequest(\n method: string,\n pathname: string,\n searchParams?: URLSearchParams | string | Record<string, string> | null,\n body?: unknown,\n ): string {\n const params = new URLSearchParams()\n if (searchParams instanceof URLSearchParams) {\n for (const [key, value] of searchParams.entries()) params.append(key, value)\n } else if (typeof searchParams === \"string\") {\n const raw = searchParams.startsWith(\"?\") ? searchParams.slice(1) : searchParams\n for (const [key, value] of new URLSearchParams(raw).entries()) params.append(key, value)\n } else if (searchParams && typeof searchParams === \"object\") {\n for (const [key, value] of Object.entries(searchParams)) params.append(key, value)\n }\n const query = sortedQueryString(params)\n const url = `https://observation.local${pathname}${query ? `?${query}` : \"\"}`\n return observationCacheKey(url, method, body)\n }\n\n insertUser(user: UserRecord): void {\n this.users.insert(user.user_id, clone(user))\n this.byClientId.insert(user.client_user_id, { user_id: user.user_id })\n }\n\n insertOrder(order: OrderRecord): void {\n this.orders.insert(order.id, clone(order))\n const transactionId = order.order_transaction?.id\n if (typeof transactionId === \"string\" && transactionId.length > 0) {\n this.orderByTransaction.insert(transactionId, { order_id: order.id })\n }\n }\n\n insertAppointment(appointment: AppointmentRecord): void {\n this.appointments.insert(appointment.id, clone(appointment))\n this.appointmentsByOrder.insert(appointment.order_id, { appointment_id: appointment.id })\n }\n\n nextUserId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"usr_\")\n const id = deterministicUuid(`junction:user:${token}`)\n if (!this.users.has(id) && !this.deletedUsers.has(id)) return id\n }\n const token = this.ids.next(\"usr_\")\n return deterministicUuid(`junction:user:post-seed:${token}:${this.users.list().length}`)\n }\n\n nextOrderId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"ord_\")\n const id = deterministicUuid(`junction:order:${token}`)\n if (!this.orders.has(id)) return id\n }\n const token = this.ids.next(\"ord_\")\n return deterministicUuid(`junction:order:post-seed:${token}:${this.orders.list().length}`)\n }\n\n nextAppointmentId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"apt_\")\n const id = deterministicUuid(`junction:appointment:${token}`)\n if (!this.appointments.has(id)) return id\n }\n const token = this.ids.next(\"apt_\")\n return deterministicUuid(\n `junction:appointment:post-seed:${token}:${this.appointments.list().length}`,\n )\n }\n\n bookingKeyFor(input: string): string {\n return deterministicUuid(`junction:booking:${input}`)\n }\n\n appointmentProviderIdFor(input: string): string {\n return opaqueToken(`junction:appointment-provider:${input}`, 12)\n }\n\n transactionIdFor(orderId: string): string {\n return deterministicUuid(`junction:transaction:${orderId}`)\n }\n\n testkitIdFor(orderId: string): string {\n return deterministicUuid(`junction:testkit:${orderId}`)\n }\n\n /** Run `fn` without publishing any webhook: how fixtures load without side effects. */\n muteWebhooks<T>(fn: () => T): T {\n this.webhooksMuted++\n try {\n return fn()\n } finally {\n this.webhooksMuted--\n }\n }\n\n /** Record that handling `request` adopted an unknown user (see `requireUser`). */\n noteAdoption(request: Request): void {\n this.adoptedRequests.add(request)\n }\n\n adopted(request: Request): boolean {\n return this.adoptedRequests.has(request)\n }\n\n publishWebhook(event: JunctionWebhookEvent, now = Date.now()): void {\n if (this.webhooksMuted > 0) return\n const sequence = this.webhookEvents.nextSequence()\n const snapshot = clone(event)\n this.webhookEvents.insert(String(sequence), { sequence, event: snapshot })\n const messageId = deterministicUuid(`junction:webhook:${sequence}`)\n for (const [index, delay] of WEBHOOK_RETRY_DELAYS_MS.entries()) {\n const jitter =\n delay === 0 ? 0 : delay * this.webhookJitterRatio * (this.webhookRandom() * 2 - 1)\n const scheduledAt = new Date(now + Math.max(0, Math.round(delay + jitter))).toISOString()\n this.webhookDeliveryAttempts.insert(`${messageId}:${index + 1}`, {\n message_id: messageId,\n event: clone(snapshot),\n attempt: index + 1,\n scheduled_at: scheduledAt,\n timeout_ms: this.webhookTimeoutMs,\n acknowledged: index === 0,\n })\n }\n this.publishEvent?.(snapshot)\n }\n\n webhookEventsInOrder(): JunctionWebhookEvent[] {\n return this.webhookEvents.list({ order: \"oldest\" }).map((entry) => clone(entry.value.event))\n }\n\n webhookDeliveryAttemptsInOrder(): WebhookDeliveryAttempt[] {\n return this.webhookDeliveryAttempts.list({ order: \"oldest\" }).map((entry) => clone(entry.value))\n }\n\n publishOrderWebhook(\n order: OrderRecord,\n eventType: JunctionWebhookEvent[\"event_type\"],\n now = Date.now(),\n ): void {\n const user = this.users.get(order.user_id)\n if (!user) return\n this.publishWebhook(\n {\n event_type: eventType,\n data: order as unknown as Record<string, unknown>,\n team_id: order.team_id,\n user_id: order.user_id,\n client_user_id: user.client_user_id,\n },\n now,\n )\n }\n\n publishAppointmentWebhook(\n appointment: AppointmentRecord,\n teamId: string,\n now = Date.now(),\n ): void {\n const user = this.users.get(appointment.user_id)\n if (!user) return\n this.publishWebhook(\n {\n event_type: \"labtest.appointment.updated\",\n data: appointment as unknown as Record<string, unknown>,\n team_id: teamId,\n user_id: appointment.user_id,\n client_user_id: user.client_user_id,\n },\n now,\n )\n }\n\n queueSimulateTransition(transition: PendingSimulateTransition): void {\n this.pendingSimulateTransitions.insert(\n `${transition.order_id}:${transition.due_at}`,\n transition,\n )\n }\n\n /** Apply any simulate transitions whose delay has elapsed; called lazily on reads. */\n applyDueSimulateTransitions(\n nowMs: number,\n apply: (order: OrderRecord, finalStatus: string, flags: Record<string, unknown> | null) => void,\n ): void {\n for (const entry of this.pendingSimulateTransitions.list({ order: \"oldest\" })) {\n const transition = entry.value\n if (transition.due_at > nowMs) continue\n const order = this.orders.get(transition.order_id)\n if (order) apply(order, transition.final_status, transition.flags)\n this.pendingSimulateTransitions.delete(entry.id)\n }\n }\n\n isoNow(now: () => number): string {\n return new Date(now()).toISOString().replace(/\\.\\d{3}Z$/, \"+00:00\")\n }\n}\n", "/**\n * Team-level lab-account fixtures.\n *\n * Mirrors https://docs.junction.com/lab/overview/lab-accounts for a team-scoped API key:\n * the `ClientFacingLabAccount` shape, the account filters, the selection when\n * `lab_account_id` is omitted (as the sandbox applies it, see `selectLabAccount`), and the\n * `allowed_billing` rules.\n *\n * No fixture is placed on `ussl` \u2014 an account there would flip that lab from the\n * platform branch to the linked branches and change shipped order behavior. The\n * branch-fixture labs (`nexus`, `mtl`, `crl`, `ihd`) have no catalog lab tests, so the\n * property suite seeds synthetic tests for them.\n */\nimport { HttpError, opaqueToken } from \"@crvouga/mockingbird-service\"\nimport { TEAM_LABS } from \"./catalog.js\"\nimport { deterministicUuid, MOCK_TEAM_ID } from \"./state.js\"\n\nexport type LabAccountStatus = \"active\" | \"pending\" | \"suspended\" | \"ready_to_launch\"\nexport type LabAccountDelegatedFlow =\n | \"order_delegated\"\n | \"result_delegated\"\n | \"fully_delegated\"\n | \"not_delegated\"\n\nexport type LabAccountRecord = {\n id: string\n lab: string\n org_id: string | null\n status: LabAccountStatus\n delegated_flow: LabAccountDelegatedFlow\n provider_account_id: string\n account_name: string | null\n default_clinical_notes: string | null\n business_units: string[] | null\n allowed_billing: Record<string, readonly string[]>\n team_id_allowlist: readonly string[]\n}\n\n/** The 50 `USState` values from the docs, alphabetical by state name. */\nexport const US_STATES: readonly string[] = [\n \"AL\",\n \"AK\",\n \"AZ\",\n \"AR\",\n \"CA\",\n \"CO\",\n \"CT\",\n \"DE\",\n \"FL\",\n \"GA\",\n \"HI\",\n \"ID\",\n \"IL\",\n \"IN\",\n \"IA\",\n \"KS\",\n \"KY\",\n \"LA\",\n \"ME\",\n \"MD\",\n \"MA\",\n \"MI\",\n \"MN\",\n \"MS\",\n \"MO\",\n \"MT\",\n \"NE\",\n \"NV\",\n \"NH\",\n \"NJ\",\n \"NM\",\n \"NY\",\n \"NC\",\n \"ND\",\n \"OH\",\n \"OK\",\n \"OR\",\n \"PA\",\n \"RI\",\n \"SC\",\n \"SD\",\n \"TN\",\n \"TX\",\n \"UT\",\n \"VT\",\n \"VA\",\n \"WA\",\n \"WV\",\n \"WI\",\n \"WY\",\n]\n\nexport const ALL_BILLING_STATES: readonly string[] = US_STATES\n\n/** `billing_type` values the vendored create-order body accepts. */\nexport const BILLING_TYPES = [\n \"client_bill\",\n \"commercial_insurance\",\n \"patient_bill_passthrough\",\n \"patient_bill\",\n \"upfront_payment\",\n] as const\n\nexport type BillingType = (typeof BILLING_TYPES)[number]\n\n/**\n * Validate a lab slug \u2192 `billing_type` map: the billing type `create_order` evaluates for\n * that lab when the request omits `billing_type`. Junction documents `client_bill` as the\n * default, but a sandbox team was observed evaluating BioReference orders as\n * `patient_bill_passthrough`, so it is configurable per lab.\n */\nexport const defaultBillingTypesFrom = (input: unknown): Record<string, BillingType> => {\n if (typeof input !== \"object\" || input === null || Array.isArray(input))\n throw new TypeError(\"default billing types must map lab slugs to billing types\")\n const out: Record<string, BillingType> = {}\n for (const [lab, type] of Object.entries(input)) {\n if (lab.trim() === \"\") throw new TypeError(\"default billing types: lab slug is empty\")\n if (!(BILLING_TYPES as readonly unknown[]).includes(type))\n throw new TypeError(\n `default billing type for ${lab}: ${String(type)} is not a billing type (${BILLING_TYPES.join(\", \")})`,\n )\n out[lab.trim().toLowerCase()] = type as BillingType\n }\n return out\n}\n\nexport const LAB_ACCOUNT_STATUSES: readonly LabAccountStatus[] = [\n \"active\",\n \"pending\",\n \"suspended\",\n \"ready_to_launch\",\n]\n\nexport const MOCK_ORG_ID = deterministicUuid(\"junction:org:mock\")\n\n/** A team the mock is not, for fixtures that model another team's account. */\nexport const OTHER_TEAM_ID = deterministicUuid(\"junction:team:other\")\n\n/** Junction platform accounts support every billing type in every state. */\nconst PLATFORM_BILLING: Record<string, readonly string[]> = Object.fromEntries(\n BILLING_TYPES.map((type) => [type, ALL_BILLING_STATES]),\n)\n\nconst CLIENT_BILL_ONLY: Record<string, readonly string[]> = { client_bill: ALL_BILLING_STATES }\n\nconst account = (\n key: string,\n lab: string,\n fields: Pick<LabAccountRecord, \"status\" | \"allowed_billing\" | \"team_id_allowlist\"> &\n Partial<Pick<LabAccountRecord, \"account_name\" | \"business_units\" | \"org_id\">>,\n): LabAccountRecord => ({\n id: deterministicUuid(`junction:lab-account:${key}`),\n lab,\n org_id: fields.org_id ?? MOCK_ORG_ID,\n status: fields.status,\n delegated_flow: \"not_delegated\",\n provider_account_id: opaqueToken(`junction:lab-account-provider:${key}`, 16),\n account_name: fields.account_name ?? null,\n default_clinical_notes: null,\n business_units: fields.business_units ?? null,\n allowed_billing: fields.allowed_billing,\n team_id_allowlist: fields.team_id_allowlist,\n})\n\nexport const TEAM_LAB_ACCOUNTS: readonly LabAccountRecord[] = [\n // Exactly one active account linked for `quest`; the commercial-insurance state rule\n // lives on this account.\n account(\"quest-primary\", \"quest\", {\n status: \"active\",\n account_name: \"Quest Diagnostics \u2014 primary\",\n business_units: [\"core\", \"specialty\"],\n allowed_billing: {\n client_bill: ALL_BILLING_STATES,\n commercial_insurance: [\"AZ\", \"CA\"],\n },\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Listed but never selected; exercises `status` filters and the explicit-id rejection.\n account(\"quest-pending\", \"quest\", {\n status: \"pending\",\n account_name: \"Quest Diagnostics \u2014 pending\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Several active accounts linked for `nexus`: an omitted id selects the first.\n account(\"nexus-a\", \"nexus\", {\n status: \"active\",\n account_name: \"Nexus \u2014 A\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n account(\"nexus-b\", \"nexus\", {\n status: \"active\",\n account_name: \"Nexus \u2014 B\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Linked accounts, none active.\n account(\"mtl-suspended\", \"mtl\", {\n status: \"suspended\",\n account_name: \"Molecular Testing Labs \u2014 suspended\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n account(\"mtl-pending\", \"mtl\", {\n status: \"pending\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // `status` filter coverage for the enum's last value.\n account(\"crl-ready\", \"crl\", {\n status: \"ready_to_launch\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Org-owned account of another team: absent from the team listing, rejected when used.\n account(\"ihd-other-team\", \"ihd\", {\n status: \"active\",\n account_name: \"IHD \u2014 other team\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [OTHER_TEAM_ID],\n }),\n]\n\n/** Every lab slug in the team lab inventory \u2014 these labs have a Junction platform account. */\nexport const PLATFORM_ACCOUNT_LABS: readonly string[] = TEAM_LABS.map((lab) => String(lab.slug))\n\n/** Every caller passes the live list (`state.listLabAccounts()`), never the fixtures. */\nexport const labAccountById = (\n id: string,\n accounts: readonly LabAccountRecord[],\n): LabAccountRecord | undefined => accounts.find((entry) => entry.id === id)\n\n/**\n * Whether `teamId` may use an account. An empty `team_id_allowlist` counts as linked:\n * a real team's listing returns such accounts (Junction's own Quest, Labcorp and\n * BioReference accounts carry `[]`), and the sandbox places an order that names one by id\n * (corpus/lab-account-probes.json), so the mock treats them as the team's.\n */\nexport const isLinkedToTeam = (entry: LabAccountRecord, teamId: string): boolean =>\n entry.team_id_allowlist.length === 0 || entry.team_id_allowlist.includes(teamId)\n\n/** Team-linked accounts for a lab, in configured order. */\nexport const linkedLabAccounts = (\n labSlug: string,\n teamId: string,\n accounts: readonly LabAccountRecord[],\n): LabAccountRecord[] =>\n accounts.filter((entry) => entry.lab === labSlug && isLinkedToTeam(entry, teamId))\n\nexport const effectiveBilling = (\n account: LabAccountRecord | \"platform\",\n): Record<string, readonly string[]> =>\n account === \"platform\" ? PLATFORM_BILLING : account.allowed_billing\n\n/**\n * The selection rules as the sandbox applies them. An explicit id must exist, be linked to\n * the team and be active; the sandbox does **not** require it to belong to the ordered lab\n * (recorded in corpus/lab-account-probes.json: a Labcorp test ordered through Junction's\n * BioReference account was placed), although the lab-accounts guide says it must. With no id,\n * one active linked account for the lab is selected, several select the first in listing\n * order (a sandbox team with several was observed placing such an order, where the guide says\n * it \"may be rejected\"), and a lab with none falls back to Junction's platform account.\n */\nexport const selectLabAccount = (\n labSlug: string,\n requestedId: string | null,\n teamId: string,\n accounts: readonly LabAccountRecord[],\n): LabAccountRecord | \"platform\" => {\n if (requestedId !== null) {\n const linked = labAccountById(requestedId, accounts)\n if (!linked) throw new HttpError(400, { detail: \"Lab account does not exist\" })\n if (!isLinkedToTeam(linked, teamId))\n throw new HttpError(400, { detail: \"Lab account is not linked to your team\" })\n if (linked.status !== \"active\")\n throw new HttpError(400, { detail: \"Lab account is not active\" })\n return linked\n }\n const candidates = linkedLabAccounts(labSlug, teamId, accounts)\n if (candidates.length === 0) {\n if (PLATFORM_ACCOUNT_LABS.includes(labSlug)) return \"platform\"\n throw new HttpError(400, { detail: `No active lab account is available for lab ${labSlug}` })\n }\n const active = candidates.find((entry) => entry.status === \"active\")\n if (active) return active\n throw new HttpError(400, { detail: \"No active lab account is available for this lab\" })\n}\n\n/** Render only the documented `ClientFacingLabAccount` keys. */\nexport const renderLabAccount = (entry: LabAccountRecord): Record<string, unknown> => ({\n id: entry.id,\n lab: entry.lab,\n org_id: entry.org_id,\n status: entry.status,\n delegated_flow: entry.delegated_flow,\n provider_account_id: entry.provider_account_id,\n account_name: entry.account_name,\n default_clinical_notes: entry.default_clinical_notes,\n business_units: entry.business_units === null ? null : [...entry.business_units],\n allowed_billing: Object.fromEntries(\n Object.entries(entry.allowed_billing).map(([type, states]) => [type, [...states]]),\n ),\n team_id_allowlist: [...entry.team_id_allowlist],\n})\n\n/**\n * A lab account as a consumer configures it. Mirrors `ClientFacingLabAccount`, with\n * every field but `id` and `lab` optional, plus a `states` shorthand for the common\n * case of an account that client-bills in a fixed set of states.\n */\nexport type LabAccountInput = {\n id: string\n /** Lab slug, e.g. `\"quest\"`, `\"labcorp\"`, `\"bioreference\"`. */\n lab: string\n status?: LabAccountStatus\n delegated_flow?: LabAccountDelegatedFlow\n account_name?: string | null\n provider_account_id?: string\n org_id?: string | null\n business_units?: string[] | null\n default_clinical_notes?: string | null\n /** Billing type \u2192 states it is allowed in. Takes precedence over `states`. */\n allowed_billing?: Record<string, readonly string[]>\n /** Shorthand for `allowed_billing: { client_bill: states }`. Default: every state. */\n states?: readonly string[]\n /** Teams the account is linked to. Default: the configured team, so it is selectable. */\n team_id_allowlist?: readonly string[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst DELEGATED_FLOWS: readonly LabAccountDelegatedFlow[] = [\n \"order_delegated\",\n \"result_delegated\",\n \"fully_delegated\",\n \"not_delegated\",\n]\n\nconst checkStates = (value: unknown, where: string): void => {\n if (!Array.isArray(value)) throw new TypeError(`${where} must be an array of US state codes`)\n for (const state of value) {\n if (typeof state !== \"string\" || !US_STATES.includes(state))\n throw new TypeError(`${where}: ${String(state)} is not a US state code`)\n }\n}\n\nconst stringList = (value: unknown): string[] | undefined =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n ? [...(value as string[])]\n : undefined\n\n/**\n * Normalize a consumer's configuration into the record the ordering rules read.\n * `teamId` is the default allowlist, so an account is selectable unless told otherwise.\n */\nexport const labAccountFromInput = (\n input: LabAccountInput,\n teamId: string = MOCK_TEAM_ID,\n): LabAccountRecord => {\n if (!isRecord(input)) throw new TypeError(\"lab account must be an object\")\n if (typeof input.id !== \"string\" || input.id === \"\")\n throw new TypeError(\"lab account needs a non-empty id\")\n const where = `lab account ${input.id}`\n if (typeof input.lab !== \"string\" || input.lab === \"\")\n throw new TypeError(`${where}: lab must be a lab slug such as \"quest\"`)\n if (input.status !== undefined && !LAB_ACCOUNT_STATUSES.includes(input.status))\n throw new TypeError(`${where}: status must be one of ${LAB_ACCOUNT_STATUSES.join(\", \")}`)\n if (input.delegated_flow !== undefined && !DELEGATED_FLOWS.includes(input.delegated_flow))\n throw new TypeError(`${where}: delegated_flow must be one of ${DELEGATED_FLOWS.join(\", \")}`)\n if (input.states !== undefined) checkStates(input.states, `${where}: states`)\n if (input.allowed_billing !== undefined) {\n if (!isRecord(input.allowed_billing))\n throw new TypeError(`${where}: allowed_billing must map billing types to state lists`)\n for (const [type, states] of Object.entries(input.allowed_billing)) {\n if (!(BILLING_TYPES as readonly string[]).includes(type))\n throw new TypeError(\n `${where}: allowed_billing.${type} is not a billing type (${BILLING_TYPES.join(\", \")})`,\n )\n checkStates(states, `${where}: allowed_billing.${type}`)\n }\n }\n if (input.team_id_allowlist !== undefined && stringList(input.team_id_allowlist) === undefined)\n throw new TypeError(`${where}: team_id_allowlist must be an array of team ids`)\n if (input.business_units != null && stringList(input.business_units) === undefined)\n throw new TypeError(`${where}: business_units must be an array of strings or null`)\n for (const field of [\n \"account_name\",\n \"provider_account_id\",\n \"org_id\",\n \"default_clinical_notes\",\n ] as const) {\n const value = input[field]\n if (value != null && typeof value !== \"string\")\n throw new TypeError(`${where}: ${field} must be a string`)\n }\n return {\n id: input.id,\n lab: input.lab.toLowerCase(),\n org_id: input.org_id === undefined ? MOCK_ORG_ID : input.org_id,\n status: input.status ?? \"active\",\n delegated_flow: input.delegated_flow ?? \"not_delegated\",\n provider_account_id:\n input.provider_account_id ?? opaqueToken(`junction:lab-account-provider:${input.id}`, 16),\n account_name: input.account_name ?? null,\n default_clinical_notes: input.default_clinical_notes ?? null,\n business_units: input.business_units ?? null,\n allowed_billing: input.allowed_billing ?? { client_bill: input.states ?? ALL_BILLING_STATES },\n team_id_allowlist: input.team_id_allowlist ?? [teamId],\n }\n}\n\n/**\n * Merge `patch` onto a stored account. `states` replaces only the `client_bill` states,\n * so an account's other billing types survive a state change.\n */\nexport const patchLabAccount = (\n existing: LabAccountRecord,\n patch: Partial<LabAccountInput>,\n teamId: string,\n): LabAccountRecord => {\n if (!isRecord(patch)) throw new TypeError(\"lab account patch must be an object\")\n if (patch.id !== undefined && patch.id !== existing.id)\n throw new TypeError(`lab account ${existing.id}: id cannot be changed`)\n const { states, ...rest } = patch\n if (states !== undefined) checkStates(states, `lab account ${existing.id}: states`)\n const allowed_billing =\n rest.allowed_billing ??\n (states !== undefined\n ? { ...existing.allowed_billing, client_bill: states }\n : existing.allowed_billing)\n return labAccountFromInput(\n {\n ...existing,\n business_units: existing.business_units,\n ...rest,\n id: existing.id,\n allowed_billing,\n },\n teamId,\n )\n}\n\n/**\n * Read a `ClientFacingLabAccount` from a real team's listing (a pulled corpus).\n *\n * With `recordedTeamId` (a corpus that recorded its team) the allowlist is kept verbatim,\n * so an account the real team is not linked to stays unlinked. Without it (a version-1\n * corpus) the mock cannot tell, so each account is linked to the mock team as well \u2014 the\n * recorded ids are kept alongside, never replaced.\n */\nexport const labAccountFromClientFacing = (\n value: Record<string, unknown>,\n recordedTeamId?: string,\n): LabAccountRecord | undefined => {\n if (typeof value.id !== \"string\" || typeof value.lab !== \"string\") return undefined\n const billing: Record<string, readonly string[]> = {}\n if (isRecord(value.allowed_billing)) {\n for (const [type, states] of Object.entries(value.allowed_billing)) {\n const list = stringList(states)\n if (list) billing[type] = list\n }\n }\n const allowlist = stringList(value.team_id_allowlist) ?? []\n return {\n id: value.id,\n lab: value.lab.toLowerCase(),\n org_id: typeof value.org_id === \"string\" ? value.org_id : null,\n status: LAB_ACCOUNT_STATUSES.includes(value.status as LabAccountStatus)\n ? (value.status as LabAccountStatus)\n : \"active\",\n delegated_flow:\n typeof value.delegated_flow === \"string\"\n ? (value.delegated_flow as LabAccountDelegatedFlow)\n : \"not_delegated\",\n provider_account_id:\n typeof value.provider_account_id === \"string\"\n ? value.provider_account_id\n : opaqueToken(`junction:lab-account-provider:${value.id}`, 16),\n account_name: typeof value.account_name === \"string\" ? value.account_name : null,\n default_clinical_notes:\n typeof value.default_clinical_notes === \"string\" ? value.default_clinical_notes : null,\n business_units: stringList(value.business_units) ?? null,\n allowed_billing: billing,\n team_id_allowlist:\n recordedTeamId !== undefined || allowlist.includes(MOCK_TEAM_ID)\n ? allowlist\n : [...allowlist, MOCK_TEAM_ID],\n }\n}\n", "/**\n * Named lab accounts a suite can add in one call, modelled on a real team's recorded\n * listing (a BioReference-linked team, recorded 2026-09-21 from the Junction sandbox).\n *\n * Where a preset copies a recorded account, its states and billing types are the\n * recording's. `bioreference_ny_nj_delegated` is not a recorded account: it is the\n * NY/NJ client-bill shape a consumer asked for, kept because suites depend on it, and\n * listed in `SYNTHETIC_LAB_ACCOUNT_PRESETS`.\n *\n * `*_platform` presets are Junction's own accounts (`org_id: null`, allowlist `[]`); every\n * other active preset is customer-owned (it belongs to an Org and is linked to the team).\n */\nimport {\n type LabAccountInput,\n type LabAccountRecord,\n labAccountFromInput,\n US_STATES,\n} from \"./lab-accounts.js\"\nimport { deterministicUuid } from \"./state.js\"\n\nconst except = (...excluded: string[]): readonly string[] =>\n US_STATES.filter((state) => !excluded.includes(state))\n\n/** Junction's own Quest, Labcorp and BioReference accounts client-bill in these 47 states. */\nexport const PLATFORM_ACCOUNT_STATES: readonly string[] = except(\"NJ\", \"NY\", \"RI\")\n\n/** The recorded order-delegated BioReference account: every state but New York and New Jersey. */\nexport const DELEGATED_ACCOUNT_STATES: readonly string[] = except(\"NJ\", \"NY\")\n\ntype Preset = Omit<LabAccountInput, \"id\">\n\nconst bioreferencePlatform: Preset = {\n lab: \"bioreference\",\n account_name: \"Junction BioReference Account\",\n delegated_flow: \"not_delegated\",\n org_id: null,\n allowed_billing: { client_bill: PLATFORM_ACCOUNT_STATES },\n team_id_allowlist: [],\n}\nconst questPlatform: Preset = {\n lab: \"quest\",\n account_name: \"Junction Quest Account\",\n delegated_flow: \"not_delegated\",\n org_id: null,\n allowed_billing: { client_bill: PLATFORM_ACCOUNT_STATES },\n team_id_allowlist: [],\n}\nconst labcorpPlatform: Preset = {\n lab: \"labcorp\",\n account_name: \"Junction Labcorp Account\",\n delegated_flow: \"not_delegated\",\n org_id: null,\n allowed_billing: { client_bill: PLATFORM_ACCOUNT_STATES },\n team_id_allowlist: [],\n}\n\n/**\n * Every preset, without its id. A preset with no `team_id_allowlist` is linked to the\n * configured team; the platform presets carry `[]`, as Junction's own accounts do.\n */\nexport const LAB_ACCOUNT_PRESETS: Readonly<Record<string, Preset>> = {\n bioreference_ny_nj_delegated: {\n lab: \"bioreference\",\n delegated_flow: \"order_delegated\",\n allowed_billing: { client_bill: [\"NY\", \"NJ\"] },\n },\n bioreference_delegated_multi_state: {\n lab: \"bioreference\",\n delegated_flow: \"order_delegated\",\n allowed_billing: { client_bill: DELEGATED_ACCOUNT_STATES },\n },\n bioreference_platform: bioreferencePlatform,\n bioreference_patient_bill_passthrough: {\n lab: \"bioreference\",\n delegated_flow: \"not_delegated\",\n allowed_billing: { patient_bill_passthrough: [\"NJ\", \"NY\"] },\n },\n quest_platform: questPlatform,\n labcorp_platform: labcorpPlatform,\n suspended_bioreference: { ...bioreferencePlatform, status: \"suspended\" },\n suspended_quest: { ...questPlatform, status: \"suspended\" },\n suspended_labcorp: { ...labcorpPlatform, status: \"suspended\" },\n}\n\n/**\n * Deprecated preset names and the preset each stands for. An alias keeps its own default id,\n * so a suite that pinned `presetAccountId(alias)` still finds its account.\n */\nexport const LAB_ACCOUNT_PRESET_ALIASES: Readonly<Record<string, string>> = {\n /** Misnamed: the record is Junction's platform account, not a customer-owned one. */\n bioreference_customer_multi_state: \"bioreference_platform\",\n}\n\n/** Presets that model a shape consumers asked for, not an account recorded from a real team. */\nexport const SYNTHETIC_LAB_ACCOUNT_PRESETS: readonly string[] = [\"bioreference_ny_nj_delegated\"]\n\nconst presetNamed = (name: string): Preset | undefined => {\n const target = Object.hasOwn(LAB_ACCOUNT_PRESET_ALIASES, name)\n ? LAB_ACCOUNT_PRESET_ALIASES[name]\n : name\n return target !== undefined && Object.hasOwn(LAB_ACCOUNT_PRESETS, target)\n ? LAB_ACCOUNT_PRESETS[target]\n : undefined\n}\n\n/** A preset's id when none is given: stable across runs and namespaces. */\nexport const presetAccountId = (name: string): string =>\n deterministicUuid(`junction:lab-account:${name}`)\n\n/** The account a preset adds, or `undefined` for an unknown name. */\nexport const labAccountFromPreset = (\n name: string,\n options: { id?: string; teamId: string },\n): LabAccountRecord | undefined => {\n const preset = presetNamed(name)\n if (!preset) return undefined\n return labAccountFromInput({ ...preset, id: options.id ?? presetAccountId(name) }, options.teamId)\n}\n\n/**\n * A lab-account layout as a file or option declares it: a bare list of accounts, or\n * presets (by name, or `{ name, id }`) plus accounts, added in that order.\n */\nexport type LabAccountLayout =\n | readonly LabAccountInput[]\n | {\n presets?: readonly (string | { name: string; id?: string })[]\n accounts?: readonly LabAccountInput[]\n }\n\n/** Expand a layout into the records it declares. Throws naming the first bad entry. */\nexport const expandLabAccountLayout = (\n layout: LabAccountLayout,\n teamId: string,\n): LabAccountRecord[] => {\n if (Array.isArray(layout))\n return (layout as LabAccountInput[]).map((input) => labAccountFromInput(input, teamId))\n if (typeof layout !== \"object\" || layout === null)\n throw new TypeError('lab accounts must be an array, or { \"presets\": [...], \"accounts\": [...] }')\n const { presets = [], accounts = [] } = layout as Exclude<\n LabAccountLayout,\n readonly LabAccountInput[]\n >\n if (!Array.isArray(presets)) throw new TypeError(\"presets must be an array of preset names\")\n if (!Array.isArray(accounts)) throw new TypeError(\"accounts must be an array of lab accounts\")\n const records: LabAccountRecord[] = []\n for (const entry of presets) {\n const name = typeof entry === \"string\" ? entry : entry?.name\n const id = typeof entry === \"string\" ? undefined : entry?.id\n const record =\n typeof name === \"string\"\n ? labAccountFromPreset(name, { teamId, ...(id !== undefined ? { id } : {}) })\n : undefined\n if (!record)\n throw new TypeError(\n `no lab-account preset ${JSON.stringify(name)}; one of ${Object.keys(LAB_ACCOUNT_PRESETS).join(\", \")}`,\n )\n records.push(record)\n }\n for (const input of accounts) records.push(labAccountFromInput(input, teamId))\n const seen = new Set<string>()\n for (const record of records) {\n if (seen.has(record.id)) throw new TypeError(`lab account ${record.id} is declared twice`)\n seen.add(record.id)\n }\n return records\n}\n", "import {\n type AdminRequest,\n type AdminRoutes,\n type FaultPreset,\n type FaultRule,\n jsonRes,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport {\n fixtureErrorMessage,\n IDENTITY_MODES,\n type IdentityMode,\n type JunctionFixtures,\n type OrderFixture,\n type UserFixture,\n} from \"./fixtures.js\"\nimport type { JunctionAPI } from \"./index.js\"\nimport {\n LAB_ACCOUNT_PRESET_ALIASES,\n LAB_ACCOUNT_PRESETS,\n type LabAccountLayout,\n labAccountFromPreset,\n SYNTHETIC_LAB_ACCOUNT_PRESETS,\n} from \"./lab-account-presets.js\"\nimport { type BillingType, type LabAccountInput, renderLabAccount } from \"./lab-accounts.js\"\nimport { sandboxUserQuotaBody } from \"./limits.js\"\nimport type { GeoMode, ResultFixture } from \"./state.js\"\nimport type { WebhookDispatcher } from \"./webhooks.js\"\n\n/**\n * Every order status the contract defines, by collection method (from the vendored\n * OpenAPI enum). An admin transition may only target a status real Junction can emit.\n */\nexport const ORDER_STATUSES_BY_METHOD: Readonly<Record<string, readonly string[]>> = {\n at_home_phlebotomy: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.appointment_pending\",\n \"collecting_sample.appointment_scheduled\",\n \"collecting_sample.appointment_cancelled\",\n \"collecting_sample.draw_completed\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n on_site_collection: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"sample_with_lab.draw_completed\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n testkit: [\n \"received.ordered\",\n \"received.awaiting_registration\",\n \"received.registered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.transit_customer\",\n \"collecting_sample.out_for_delivery\",\n \"collecting_sample.with_customer\",\n \"collecting_sample.transit_lab\",\n \"collecting_sample.problem_in_transit_customer\",\n \"collecting_sample.problem_in_transit_lab\",\n \"sample_with_lab.delivered_to_lab\",\n \"sample_with_lab.lab_processing_blocked\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"cancelled.do_not_process\",\n \"failed.sample_error\",\n \"failed.failure_to_deliver_to_customer\",\n \"failed.failure_to_deliver_to_lab\",\n \"failed.lost\",\n ],\n walk_in_test: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.appointment_pending\",\n \"collecting_sample.appointment_scheduled\",\n \"collecting_sample.appointment_cancelled\",\n \"collecting_sample.redraw_available\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n}\n\n/**\n * Friendly transition targets, per method, mapped onto the contract's own statuses.\n * A name is absent for a method when no real status means it \u2014 walk-in tests have no\n * draw event, so `collected` is refused there rather than approximated.\n */\nexport const TRANSITION_ALIASES: Readonly<Record<string, Readonly<Record<string, string>>>> = {\n at_home_phlebotomy: {\n requisition_created: \"received.requisition_created\",\n scheduled: \"collecting_sample.appointment_scheduled\",\n collected: \"collecting_sample.draw_completed\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n on_site_collection: {\n requisition_created: \"received.requisition_created\",\n collected: \"sample_with_lab.draw_completed\",\n at_lab: \"sample_with_lab.draw_completed\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n testkit: {\n requisition_created: \"received.requisition_created\",\n shipped: \"collecting_sample.transit_customer\",\n delivered: \"collecting_sample.with_customer\",\n collected: \"collecting_sample.transit_lab\",\n at_lab: \"sample_with_lab.delivered_to_lab\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n walk_in_test: {\n requisition_created: \"received.requisition_created\",\n scheduled: \"collecting_sample.appointment_scheduled\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n}\n\n/**\n * Named results, as the flags `simulate_order` accepts. They steer the generator, so\n * the payload keeps Junction's exact shape; `PUT /__admin/results/{order}` installs an\n * exact payload instead.\n */\nexport const RESULT_FIXTURES: Readonly<Record<string, Record<string, unknown>>> = {\n normal: { interpretation: \"normal\" },\n abnormal: { interpretation: \"abnormal\" },\n critical: { interpretation: \"critical\" },\n missing_results: { interpretation: \"normal\", has_missing_results: true },\n}\n\n/**\n * Junction failure modes a suite can switch on by name. `sandbox_user_quota` reproduces\n * the shared-sandbox error byte for byte (message as observed from a real sandbox team);\n * the others are shape-plausible, not verified against Junction.\n */\nconst FAULT_PRESET_RULES = {\n sandbox_user_quota: {\n operationId: \"create_user_v2_user_post\",\n status: 400,\n body: sandboxUserQuotaBody(50),\n },\n rate_limited: {\n status: 429,\n body: { detail: \"Too Many Requests\" },\n headers: { \"retry-after\": \"1\" },\n },\n server_error: { status: 500, body: { detail: \"Internal Server Error\" } },\n bad_gateway: { status: 502, body: { detail: \"Bad Gateway\" } },\n unavailable: { status: 503, body: { detail: \"Service Unavailable\" } },\n} satisfies Record<string, Omit<FaultRule, \"id\">>\n\n/** Named Junction faults a suite can add with `runtime.faults.add`. */\nexport const FAULT_PRESETS: Readonly<Record<string, Omit<FaultRule, \"id\">>> = FAULT_PRESET_RULES\n\nconst FAULT_PRESET_DESCRIPTIONS = {\n sandbox_user_quota: \"create_user answers 400 when the sandbox user quota is full\",\n rate_limited: \"Every request answers 429 Too Many Requests\",\n server_error: \"Every request answers 500 Internal Server Error\",\n bad_gateway: \"Every request answers 502 Bad Gateway\",\n unavailable: \"Every request answers 503 Service Unavailable\",\n} satisfies { [Name in keyof typeof FAULT_PRESET_RULES]: string }\n\nconst faultPresetDescriptions: Readonly<Record<string, string>> = FAULT_PRESET_DESCRIPTIONS\n\n/** Shared fault presets. `GET /__admin/faults/presets` lists these by name. */\nexport const junctionFaultPresets = (): Record<string, FaultPreset> => {\n const presets: Record<string, FaultPreset> = {}\n for (const [name, rule] of Object.entries(FAULT_PRESET_RULES)) {\n const description = faultPresetDescriptions[name]\n if (description === undefined) continue\n presets[name] = { description, rules: [rule] }\n }\n return presets\n}\n\nconst methodOf = (order: { lab_test: { method?: unknown }; details?: { type?: unknown } }) =>\n typeof order.lab_test.method === \"string\" && order.lab_test.method !== \"\"\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type !== \"\"\n ? order.details.type\n : \"at_home_phlebotomy\"\n\n/** Resolve a target (`completed`, `completed.completed`, or a full status) for a method. */\nexport const resolveTransition = (\n method: string,\n target: string,\n): { status: string } | { error: string } => {\n const allowed = ORDER_STATUSES_BY_METHOD[method]\n if (!allowed) return { error: `unknown collection method ${method}` }\n const alias = TRANSITION_ALIASES[method]?.[target]\n const short = alias ?? (target.split(\".\").length === 3 ? null : target)\n if (short !== null && allowed.includes(short)) {\n const [phase, event] = short.split(\".\")\n return { status: `${phase}.${method}.${event}` }\n }\n if (target.split(\".\").length === 3) {\n const [phase, targetMethod, event] = target.split(\".\")\n if (targetMethod === method && allowed.includes(`${phase}.${event}`)) return { status: target }\n }\n const names = Object.keys(TRANSITION_ALIASES[method] ?? {})\n return {\n error: `${JSON.stringify(target)} is not a ${method} status. Use one of: ${names.join(\", \")}, or a full status such as ${allowed\n .slice(0, 2)\n .map((s) => `${s.split(\".\")[0]}.${method}.${s.split(\".\")[1]}`)\n .join(\", \")}`,\n }\n}\n\nconst adminError = (status: number, message: string) =>\n jsonRes(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * Run an admin mutation, turning a bad input into a 400 naming the field, a clash into a\n * 409, and a missing reference into a 404 \u2014 all in the admin error shape.\n */\nconst guarded = (run: () => Response): Response => {\n try {\n return run()\n } catch (error) {\n if (error instanceof TypeError) return adminError(400, error.message)\n if (error instanceof Error && error.name === \"LabAccountConflict\") {\n return adminError(409, error.message)\n }\n const { status, message } = fixtureErrorMessage(error)\n return adminError(status, message)\n }\n}\n\nexport type JunctionAdminOptions = {\n webhooks: WebhookDispatcher | undefined\n}\n\n/** Junction's admin routes, served under `/__admin` next to the shared ones. */\nexport const junctionAdminRoutes =\n (options: JunctionAdminOptions) =>\n (runtime: ServiceRuntime<JunctionAPI>): AdminRoutes => {\n const api = (request: AdminRequest) => runtime.instance(request.namespace)\n return {\n \"GET /orders\": (request) =>\n jsonRes(200, {\n orders: api(request)\n .orders()\n .map((order) => ({\n id: order.id,\n user_id: order.user_id,\n method: methodOf(order),\n status: order.last_event.status,\n updated_at: order.updated_at,\n lab_account_id: api(request).orderLabAccount(order.id) ?? null,\n })),\n }),\n\n \"POST /orders/:id/transition\": (request) => {\n const body = isRecord(request.body) ? request.body : {}\n const order = api(request).order(request.params.id as string)\n if (!order) return adminError(404, `no order ${request.params.id} in ${request.namespace}`)\n if (typeof body.to !== \"string\") {\n return adminError(400, 'body needs \"to\": a status like \"completed\" or \"at_lab\"')\n }\n const method = methodOf(order)\n const resolved = resolveTransition(method, body.to)\n if (\"error\" in resolved) return adminError(400, resolved.error)\n let flags = isRecord(body.flags) ? body.flags : null\n if (typeof body.result === \"string\") {\n const named = RESULT_FIXTURES[body.result]\n if (!named) {\n return adminError(\n 400,\n `no result fixture ${body.result}; one of ${Object.keys(RESULT_FIXTURES).join(\", \")}`,\n )\n }\n flags = { ...named, ...flags }\n }\n const updated = api(request).transitionOrder(order.id, resolved.status, {\n now: runtime.clock.now,\n flags,\n })\n return jsonRes(200, {\n id: order.id,\n status: updated?.last_event.status,\n events: updated?.events,\n })\n },\n\n \"GET /result-fixtures\": () => jsonRes(200, { fixtures: RESULT_FIXTURES }),\n \"GET /results/:id\": (request) => {\n const fixture = api(request).resultFixture(request.params.id as string)\n return fixture ? jsonRes(200, fixture) : adminError(404, \"no result fixture for that order\")\n },\n \"PUT /results/:id\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected a result fixture object\")\n const fixture = { name: \"custom\", ...request.body } as ResultFixture\n if (fixture.results !== undefined && !Array.isArray(fixture.results)) {\n return adminError(400, \"results must be an array of result lines\")\n }\n return api(request).installResultFixture(request.params.id as string, fixture)\n ? jsonRes(200, fixture)\n : adminError(404, `no order ${request.params.id} in ${request.namespace}`)\n },\n\n \"GET /lab-accounts\": (request) => jsonRes(200, { data: api(request).labAccounts() }),\n \"PUT /lab-accounts\": (request) => {\n const body = isRecord(request.body) ? request.body : {}\n const accounts = body.accounts\n const presets = body.presets\n if (\n (accounts === undefined && presets === undefined) ||\n (accounts !== undefined && accounts !== null && !Array.isArray(accounts)) ||\n (presets !== undefined && !Array.isArray(presets))\n ) {\n return adminError(\n 400,\n 'body needs \"accounts\": an array (or null to restore the default), and/or \"presets\": an array of preset names',\n )\n }\n const layout: LabAccountLayout | undefined =\n presets !== undefined\n ? {\n presets: presets as string[],\n ...(Array.isArray(accounts) ? { accounts: accounts as LabAccountInput[] } : {}),\n }\n : accounts === null\n ? undefined\n : (accounts as LabAccountInput[])\n return guarded(() => jsonRes(200, { data: api(request).configureLabAccounts(layout) }))\n },\n \"POST /lab-accounts\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected one lab account object\")\n const input = request.body as LabAccountInput\n return guarded(() => jsonRes(201, api(request).addLabAccount(input)))\n },\n \"PATCH /lab-accounts/:id\": (request) => {\n if (!isRecord(request.body))\n return adminError(400, \"expected an object of fields to change\")\n const patch = request.body as Partial<LabAccountInput>\n return guarded(() => {\n const updated = api(request).patchLabAccount(request.params.id as string, patch)\n return updated\n ? jsonRes(200, updated)\n : adminError(404, `no lab account ${request.params.id} in ${request.namespace}`)\n })\n },\n \"DELETE /lab-accounts/:id\": (request) =>\n api(request).removeLabAccount(request.params.id as string)\n ? jsonRes(200, { status: \"ok\" })\n : adminError(404, `no lab account ${request.params.id} in ${request.namespace}`),\n \"GET /lab-accounts/presets\": (request) =>\n jsonRes(200, {\n presets: Object.fromEntries(\n Object.keys(LAB_ACCOUNT_PRESETS).map((name) => {\n const record = labAccountFromPreset(name, { teamId: api(request).teamId })\n return [name, record ? renderLabAccount(record) : null]\n }),\n ),\n aliases: LAB_ACCOUNT_PRESET_ALIASES,\n synthetic: SYNTHETIC_LAB_ACCOUNT_PRESETS,\n }),\n \"POST /lab-accounts/presets/:name\": (request) => {\n const body = isRecord(request.body) ? request.body : {}\n if (body.id !== undefined && typeof body.id !== \"string\") {\n return adminError(400, \"id must be a string\")\n }\n const name = request.params.name as string\n return guarded(() => {\n const record = api(request).addLabAccountPreset(name, body.id as string | undefined)\n return record\n ? jsonRes(201, record)\n : adminError(\n 404,\n `no lab-account preset ${name}; one of ${Object.keys(LAB_ACCOUNT_PRESETS).join(\", \")}`,\n )\n })\n },\n\n \"GET /team\": (request) => jsonRes(200, { teamId: api(request).teamId }),\n\n \"GET /limits\": (request) => jsonRes(200, { limits: api(request).limits }),\n \"PUT /limits\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected an object of limits\")\n const input = request.body\n return guarded(() => jsonRes(200, { limits: api(request).configureLimits(input) }))\n },\n\n \"GET /default-billing-types\": (request) =>\n jsonRes(200, { defaultBillingTypes: api(request).defaultBillingTypes }),\n \"PUT /default-billing-types\": (request) => {\n const input = isRecord(request.body) ? request.body.defaultBillingTypes : undefined\n if (!isRecord(input))\n return adminError(\n 400,\n 'body needs \"defaultBillingTypes\": { \"<lab slug>\": \"<billing_type>\" } ({} restores client_bill)',\n )\n return guarded(() => {\n api(request).defaultBillingTypes = input as Record<string, BillingType>\n return jsonRes(200, { defaultBillingTypes: api(request).defaultBillingTypes })\n })\n },\n\n \"GET /identity\": (request) => jsonRes(200, { identity: api(request).identity }),\n \"PUT /identity\": (request) => {\n const mode = isRecord(request.body) ? request.body.mode : undefined\n if (!IDENTITY_MODES.includes(mode as IdentityMode)) {\n return adminError(400, `body needs \"mode\": one of ${IDENTITY_MODES.join(\", \")}`)\n }\n api(request).identity = mode as IdentityMode\n return jsonRes(200, { identity: mode })\n },\n\n \"POST /users\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected one user object\")\n const input = request.body as UserFixture\n return guarded(() => jsonRes(201, api(request).insertUsers([input])[0]))\n },\n \"POST /users/bulk\": (request) => {\n const users = isRecord(request.body) ? request.body.users : undefined\n if (!Array.isArray(users)) return adminError(400, 'body needs \"users\": an array')\n return guarded(() =>\n jsonRes(201, { users: api(request).insertUsers(users as UserFixture[]) }),\n )\n },\n \"DELETE /users/:id\": (request) =>\n api(request).hardDeleteUser(request.params.id as string)\n ? jsonRes(200, { status: \"ok\" })\n : adminError(404, `no user ${request.params.id} in ${request.namespace}`),\n \"POST /orders\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected one order object\")\n const { emitWebhooks, ...input } = request.body\n return guarded(() =>\n jsonRes(\n 201,\n api(request).insertOrders([input as OrderFixture], {\n emitWebhooks: emitWebhooks === true,\n })[0],\n ),\n )\n },\n \"POST /import\": (request) => {\n if (!isRecord(request.body)) {\n return adminError(400, 'expected { \"users\": [...], \"orders\": [...] }')\n }\n const { emitWebhooks, ...fixtures } = request.body\n return guarded(() => {\n const loaded = api(request).importFixtures(fixtures as JunctionFixtures, {\n emitWebhooks: emitWebhooks === true,\n })\n return jsonRes(201, loaded)\n })\n },\n\n \"GET /corpus\": (request) =>\n jsonRes(200, {\n corpus: api(request).corpusInfo() ?? null,\n geo: api(request).geoMode,\n }),\n \"PUT /geo\": (request) => {\n const mode = isRecord(request.body) ? request.body.mode : undefined\n if (mode !== \"corpus\" && mode !== \"synthetic\") {\n return adminError(400, 'body needs \"mode\": \"corpus\" or \"synthetic\"')\n }\n api(request).geoMode = mode as GeoMode\n return jsonRes(200, { geo: mode })\n },\n\n \"GET /webhooks/events\": (request) => jsonRes(200, { events: api(request).webhookEvents() }),\n \"GET /webhooks\": (request) =>\n options.webhooks\n ? jsonRes(200, { deliveries: options.webhooks.deliveries(request.namespace) })\n : adminError(\n 409,\n \"webhook delivery is off; serve with --webhook-url and --webhook-secret\",\n ),\n \"POST /webhooks/:id/replay\": async (request) => {\n if (!options.webhooks) return adminError(409, \"webhook delivery is off\")\n const delivery = await options.webhooks.replay(request.params.id as string)\n return delivery\n ? jsonRes(200, delivery)\n : adminError(404, `no message ${request.params.id}`)\n },\n \"POST /webhooks/flush\": async () => {\n if (!options.webhooks) return adminError(409, \"webhook delivery is off\")\n await options.webhooks.flush()\n return jsonRes(200, { status: \"ok\" })\n },\n }\n }\n", "/**\n * Junction's 404 bodies for an unknown resource, and the diagnostic headers the mock adds.\n *\n * The wording differs per endpoint \u2014 trailing period included \u2014 and that is Junction's,\n * not a typo: every string below was recorded from the sandbox with a random order UUID\n * (2026-09-20), and `verify` re-checks each one.\n */\nimport { HttpError } from \"@crvouga/mockingbird-service\"\nimport type { JunctionState } from \"./state.js\"\n\n/** The `detail` of each order-scoped operation's 404 for an order that does not exist. */\nexport const ORDER_NOT_FOUND: Readonly<Record<string, string>> = {\n get_order_v3_order__order_id__get: \"This order doesn't exist\",\n cancel_order_v3_order__order_id__cancel_post: \"Order doesn't exist\",\n simulate_order_v3_order__order_id__test_post: \"Order doesn't exist\",\n get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get: \"This order doesn't exist\",\n get_result_raw_v3_order__order_id__result_get: \"Order not found\",\n get_result_metadata_v3_order__order_id__result_metadata_get: \"Order not found\",\n get_result_pdf_v3_order__order_id__result_pdf_get: \"Order not found\",\n get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get:\n \"This order doesn't exist.\",\n book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post:\n \"This order doesn't exist.\",\n reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch:\n \"This order doesn't exist.\",\n cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch:\n \"This order doesn't exist.\",\n get_psc_appointment_v3_order__order_id__psc_appointment_get: \"This order doesn't exist.\",\n book_psc_appointment_v3_order__order_id__psc_appointment_book_post: \"This order doesn't exist.\",\n reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch:\n \"This order doesn't exist.\",\n cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch:\n \"This order doesn't exist.\",\n}\n\n/**\n * Names the missing resource: `order <id>`, `user <id>`, or `user client:<client_user_id>`\n * (the id percent-encoded). Never part of Junction's answer.\n */\nexport const MISS_HEADER = \"x-mockingbird-miss\"\n/** What the namespace does hold: `users=<n> orders=<n>`. */\nexport const KNOWN_HEADER = \"x-mockingbird-known\"\n\n/**\n * Throw Junction's 404 for a missing user or order. The body is Junction's, byte for\n * byte; the headers say what was looked up and what the namespace holds, so a mock 404\n * can be told apart from a sandbox one (and a split-brain setup spotted in one request).\n */\nexport function missing(\n state: JunctionState,\n kind: \"user\" | \"order\",\n id: string,\n detail: string,\n): never {\n throw new HttpError(\n 404,\n { detail },\n {\n // Percent-encoded: an id is caller input, and a header value must be ASCII.\n [MISS_HEADER]: `${kind} ${encodeURIComponent(id).replace(/%3A/gi, \":\")}`,\n [KNOWN_HEADER]: `users=${state.users.count()} orders=${state.orders.count()}`,\n },\n )\n}\n\n/** The 404 an order-scoped operation answers for an unknown order. */\nexport function orderMissing(state: JunctionState, operationId: string, id: string): never {\n return missing(state, \"order\", id, ORDER_NOT_FOUND[operationId] ?? \"This order doesn't exist\")\n}\n", "/**\n * Appointment scheduling surface: phlebotomy + PSC availability/booking lifecycle,\n * cancellation reasons, area serviceability, and PSC site info.\n *\n * Slot data is generated deterministically (seeded by zip/site/date), so walks are\n * reproducible without any provider-side state.\n */\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport { isLinkedToTeam, type LabAccountRecord, labAccountById } from \"./lab-accounts.js\"\nimport { orderMissing } from \"./not-found.js\"\nimport type {\n AppointmentEventRecord,\n AppointmentModality,\n AppointmentRecord,\n BookingKeyRecord,\n JunctionState,\n} from \"./state.js\"\n\n/** Status of the unknown-ZIP error: unused by Junction, and not retried by HTTP clients. */\nexport const UNKNOWN_ZIP_STATUS = 424\nexport const UNKNOWN_ZIP_ERROR_TYPE = \"MOCKINGBIRD_UNKNOWN_ZIP\"\n\n/**\n * In `corpus` geo mode, refuse a ZIP the corpus has no serviceability record for.\n *\n * The error is deliberately not Junction-shaped in status: a consumer that classifies\n * vendor errors must not mistake a fixture gap for a real validation failure and carry\n * on. It fails loudly, and says how to close the gap.\n */\nconst requireCoveredZip = (state: JunctionState, zip: string): void => {\n if (state.geoMode !== \"corpus\" || state.coveredZips.has(zip)) return\n throw new HttpError(UNKNOWN_ZIP_STATUS, {\n detail: {\n error_type: UNKNOWN_ZIP_ERROR_TYPE,\n error_message: `ZIP ${zip} is not in the loaded Junction corpus (${String(state.coveredZips.size)} ZIPs covered). Record it with \\`mockingbird-junction corpus pull --zip ${zip}\\`, or serve with --geo synthetic to invent coverage.`,\n zip_code: zip,\n corpus: state.corpusLabel ?? null,\n },\n })\n}\n\nconst cachedResponse = (state: JunctionState, context: OperationContext) => {\n const body =\n context.request.method.toUpperCase() === \"GET\" ||\n context.request.method.toUpperCase() === \"HEAD\"\n ? undefined\n : context.body.kind === \"json\"\n ? context.body.value\n : context.body.kind === \"form\"\n ? context.body.value\n : undefined\n const key = state.cacheKeyForRequest(\n context.request.method,\n context.url.pathname,\n context.url.searchParams,\n body,\n )\n const cached = state.getGetCache(key)\n if (!cached) return undefined\n if (key.toLowerCase().includes(\"availability\")) {\n materializeAvailabilityBookingKeys(state, context, cached.body)\n rotateAvailabilityBookingKeys(state, cached.body, context.now())\n }\n return responseFromCache(cached)\n}\n\nconst responseFromCache = (cached: { status: number; headers?: unknown; body: unknown }) => {\n const headers = new Headers(cached.headers as HeadersInit | undefined)\n // The recorded body is served uncompressed, so drop transfer/encoding headers captured\n // from the sandbox response or a client would try to decompress plain JSON.\n headers.delete(\"content-encoding\")\n headers.delete(\"content-length\")\n headers.delete(\"transfer-encoding\")\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n return new Response(JSON.stringify(cached.body), { status: cached.status, headers })\n}\n\n/**\n * Ensure booking_key records exist for a cached availability response.\n * Prefer deterministic slot generation (rich address/provider), then fill any remaining\n * oracle keys from the cached body using the request zip.\n */\nconst materializeAvailabilityBookingKeys = (\n state: JunctionState,\n context: OperationContext,\n cachedBody: unknown,\n) => {\n const requestBody =\n context.body.kind === \"json\" &&\n typeof context.body.value === \"object\" &&\n context.body.value !== null &&\n !Array.isArray(context.body.value)\n ? (context.body.value as Record<string, unknown>)\n : {}\n const zip =\n typeof requestBody.zip_code === \"string\" && /^\\d{5}/.test(requestBody.zip_code)\n ? requestBody.zip_code.slice(0, 5)\n : \"85004\"\n const path = context.url.pathname\n const modalityHint = path.includes(\"psc\")\n ? (\"patient_service_center\" as const)\n : path.includes(\"phlebotomy\")\n ? (\"phlebotomy\" as const)\n : undefined\n state.hydrateBookingKeysFromAvailability(cachedBody, context.now(), zip, modalityHint)\n // Normalize address/provider/modality on oracle keys so book/reschedule match generated shape.\n if (typeof cachedBody === \"object\" && cachedBody !== null && !Array.isArray(cachedBody)) {\n const root = cachedBody as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) continue\n const daySlots = (day as Record<string, unknown>).slots\n const slots = Array.isArray(daySlots) ? daySlots : [day]\n for (const entry of slots) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const slot = entry as Record<string, unknown>\n const bookingKey = typeof slot.booking_key === \"string\" ? slot.booking_key : \"\"\n if (!bookingKey) continue\n const record = state.bookingKeys.get(bookingKey)\n if (!record) continue\n if (modalityHint) record.modality = modalityHint\n record.zip_code = zip\n record.provider = record.modality === \"patient_service_center\" ? \"quest\" : \"getlabs\"\n record.address = addressFromAvailabilityRequest(requestBody, zip)\n record.location = zipLocation(zip)\n state.bookingKeys.update(bookingKey, record)\n }\n }\n }\n}\n\n/**\n * Vital mints fresh booking_key values on every availability response while the slot\n * skeleton stays stable, and previously issued keys remain bookable. Mirror that: each\n * serve registers a new record per slot position (deriving slot facts from the current\n * record for that position) and rewrites the served body, leaving stale keys bookable\n * until consumed/expired.\n */\nconst rotateAvailabilityBookingKeys = (\n state: JunctionState,\n cachedBody: unknown,\n nowMs: number,\n): void => {\n if (typeof cachedBody !== \"object\" || cachedBody === null || Array.isArray(cachedBody)) return\n const root = cachedBody as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) continue\n const daySlots = (day as Record<string, unknown>).slots\n const slots = Array.isArray(daySlots) ? daySlots : [day]\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const entry = slot as Record<string, unknown>\n const sealedKey = typeof entry.booking_key === \"string\" ? entry.booking_key : \"\"\n if (!sealedKey) continue\n const sealed = state.bookingKeys.get(sealedKey)\n if (!sealed) continue\n const freshKey = bookingKeyRotationFor(state, sealedKey, nowMs, index)\n const record: BookingKeyRecord = {\n ...sealed,\n key: freshKey,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(freshKey, record)\n entry.booking_key = freshKey\n }\n }\n}\n\n/**\n * Derive a fresh, unused booking key for a rotated slot. Mixing the sealed key, clock,\n * slot index, and an attempt counter keeps re-serves unique even under frozen test\n * clocks where consecutive serves share the same millisecond.\n */\nconst bookingKeyRotationFor = (\n state: JunctionState,\n sealedKey: string,\n nowMs: number,\n index: number,\n): string => {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const candidate = state.bookingKeyFor(`rotation:${sealedKey}:${nowMs}:${index}:${attempt}`)\n if (!state.bookingKeys.has(candidate)) return candidate\n }\n return state.bookingKeyFor(\n `rotation:${sealedKey}:${nowMs}:${index}:fallback:${state.bookingKeys.list().length}`,\n )\n}\n\n/**\n * Rotation for the generated (cache-miss) availability paths: newly created slot\n * records are replaced with fresh records on every serve so repeated reads mint\n * fresh keys like the oracle, and the served body carries only the fresh keys.\n * When `override` is given (phlebotomy \u2014 Vital echoes the availability request\n * address on book), the fresh record's address/location/zip are re-aligned.\n */\nconst rotateGeneratedAvailabilityKeys = (\n state: JunctionState,\n days: Array<Record<string, unknown>>,\n nowMs: number,\n override?: {\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n zip: string\n },\n): void => {\n for (const day of days) {\n const slots = Array.isArray(day.slots) ? day.slots : []\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const entry = slot as Record<string, unknown>\n const currentKey = typeof entry.booking_key === \"string\" ? entry.booking_key : \"\"\n if (!currentKey) continue\n const current = state.bookingKeys.get(currentKey)\n if (!current) continue\n const freshKey = bookingKeyRotationFor(state, currentKey, nowMs, index)\n const record: BookingKeyRecord = {\n ...current,\n key: freshKey,\n ...(override ?? {}),\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(freshKey, record)\n entry.booking_key = freshKey\n }\n }\n}\n\nconst PHLEBOTOMY_PROVIDERS = [\"getlabs\", \"phlebfinders\"] as const\ntype PhlebotomyProviderName = (typeof PHLEBOTOMY_PROVIDERS)[number]\n\nconst zipTimezone = (zip: string): string => {\n const prefix = Number(zip.slice(0, 3))\n if (!Number.isFinite(prefix) || prefix === 0) return \"America/New_York\"\n if (prefix < 500) return \"America/New_York\"\n if (prefix < 800) return \"America/Chicago\"\n // Arizona does not observe DST \u2014 Vital uses America/Phoenix for 850\u2013865.\n if (prefix >= 850 && prefix <= 865) return \"America/Phoenix\"\n if (prefix < 900) return \"America/Denver\"\n return \"America/Los_Angeles\"\n}\n\n/** Known Vital sandbox centroids for booking location parity. */\nconst ZIP_LOCATION: Readonly<Record<string, { lat: number; lng: number }>> = {\n \"85004\": { lat: 33.6242904, lng: -111.9283407 },\n}\n\nconst zipLocation = (zip: string): { lat: number; lng: number } => {\n const known = ZIP_LOCATION[zip.slice(0, 5)]\n if (known) return { ...known }\n // Deterministic fallback centroid so unknown zips stay stable across runs.\n const prefix = Number(zip.slice(0, 3)) || 0\n return {\n lat: 30 + (prefix % 20) * 0.4,\n lng: -120 + (prefix % 30) * 0.5,\n }\n}\n\nconst cityStateForZip = (zip: string): { city: string; state: string } => {\n const tz = zipTimezone(zip)\n if (tz === \"America/Phoenix\") return { city: \"Phoenix\", state: \"AZ\" }\n if (tz === \"America/Los_Angeles\") return { city: \"Los Angeles\", state: \"CA\" }\n if (tz === \"America/Denver\") return { city: \"Denver\", state: \"CO\" }\n if (tz === \"America/Chicago\") return { city: \"Chicago\", state: \"IL\" }\n return { city: \"New York\", state: \"NY\" }\n}\n\nexport const addressFromAvailabilityRequest = (\n requestBody: Record<string, unknown>,\n zip: string,\n): Record<string, unknown> => {\n const { city, state } = cityStateForZip(zip)\n const firstLine =\n typeof requestBody.first_line === \"string\" && requestBody.first_line.length > 0\n ? requestBody.first_line\n : \"1 Main St\"\n const secondLine =\n typeof requestBody.second_line === \"string\"\n ? requestBody.second_line\n : requestBody.second_line === null\n ? \"\"\n : \"\"\n return {\n first_line: firstLine,\n second_line: secondLine,\n city:\n typeof requestBody.city === \"string\" && requestBody.city.length > 0 ? requestBody.city : city,\n state:\n typeof requestBody.state === \"string\" && requestBody.state.length > 0\n ? requestBody.state\n : state,\n zip_code:\n typeof requestBody.zip_code === \"string\" && /^\\d{5}/.test(requestBody.zip_code)\n ? requestBody.zip_code.slice(0, 5)\n : zip,\n unit: typeof requestBody.unit === \"string\" ? requestBody.unit : null,\n access_notes: null,\n }\n}\n\nconst seededRandom = (seed: number): (() => number) => {\n let value = seed >>> 0 || 1\n return () => {\n value = (value * 1664525 + 1013904223) >>> 0\n return value / 0x1_0000_0000\n }\n}\n\nconst seedFor = (parts: ReadonlyArray<string | number>): number => {\n let hash = 0x811c9dc5\n for (const part of parts) {\n const text = String(part)\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n }\n return hash >>> 0\n}\n\nconst isoDate = (date: Date): string => date.toISOString().slice(0, 10)\n\nconst addDays = (iso: string, days: number): string => {\n const date = new Date(`${iso}T00:00:00Z`)\n date.setUTCDate(date.getUTCDate() + days)\n return isoDate(date)\n}\n\nconst SCHEDULED_ORDER_EVENT: Record<AppointmentModality, string> = {\n phlebotomy: \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n patient_service_center: \"collecting_sample.walk_in_test.appointment_scheduled\",\n}\n\nconst CANCELLED_ORDER_EVENT: Record<AppointmentModality, string> = {\n phlebotomy: \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n patient_service_center: \"collecting_sample.walk_in_test.appointment_cancelled\",\n}\n\nexport const CANCELLATION_REASONS = [\n {\n id: \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n name: \"Did not fast for appointment\",\n is_refundable: true,\n },\n { id: \"448c519c-64b4-4497-ae73-622fa93371b3\", name: \"Do not trust company\", is_refundable: true },\n {\n id: \"d378e152-12d1-433e-9dd1-e0410f9331dc\",\n name: \"Getlabs cannot deliver to my preferred lab\",\n is_refundable: true,\n },\n { id: \"7be75f90-303d-4656-8eed-9bd3e20cb2cc\", name: \"Getlabs - late\", is_refundable: true },\n {\n id: \"ae3ec4dc-387c-42ac-835a-bf88fc4e411b\",\n name: \"Getlabs -Phleb Out Sick\",\n is_refundable: true,\n },\n {\n id: \"e2396e00-dd49-4f38-a395-51d6304c3312\",\n name: \"Getlabs rescheduled time does not work for patient\",\n is_refundable: true,\n },\n { id: \"5330c863-ac80-4316-901b-d305d0df74d5\", name: \"No longer interested\", is_refundable: true },\n { id: \"2b9f23fd-163e-4483-bb10-90c74a67e0dc\", name: \"Other\", is_refundable: true },\n {\n id: \"98f861dd-fe61-4817-a9d6-1b99b19cd0fb\",\n name: \"Provider asked me to cancel\",\n is_refundable: true,\n },\n {\n id: \"7dfd7da5-ed6e-40bb-a7e4-c8003f0c10a9\",\n name: \"Scheduled for wrong patient\",\n is_refundable: true,\n },\n {\n id: \"796da8c8-e654-4347-8ded-1026410c1976\",\n name: \"Scheduled time no longer works\",\n is_refundable: true,\n },\n {\n id: \"ba02af35-a34f-4a7a-abe5-5f766e8f6cd1\",\n name: \"Unable to get lab order from provider\",\n is_refundable: true,\n },\n {\n id: \"0c9425db-f11e-49c5-b976-3c0d1d4a4ea8\",\n name: \"Wanted to book in-person appointment\",\n is_refundable: true,\n },\n {\n id: \"2599a0ea-0b4a-42fe-8df6-d8f7c68182e7\",\n name: \"Went to lab for appointment\",\n is_refundable: true,\n },\n] as const\n\n/** PSC offers a single cancellation reason in the sandbox. */\nexport const PSC_CANCELLATION_REASONS = [\n { id: \"226a6520-667c-495f-8500-c20722d231d0\", name: \"Other\", is_refundable: true },\n] as const\n\n/** The phlebotomy reason named \"Other\" requires explanatory notes. */\nexport const OTHER_CANCELLATION_REASON_ID = \"2b9f23fd-163e-4483-bb10-90c74a67e0dc\"\n\nconst PSC_LABS = [\n {\n lab_id: 25,\n slug: \"sonora_quest\",\n supported_bill_types: [\"client_bill\"],\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n {\n lab_id: 6,\n slug: \"labcorp\",\n supported_bill_types: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n capabilities: [],\n },\n {\n lab_id: 13,\n slug: \"bioreference\",\n supported_bill_types: [\"patient_bill_passthrough\"],\n capabilities: [],\n },\n {\n lab_id: 4,\n slug: \"quest\",\n supported_bill_types: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n] as const\n\n/** Lab 3 (USSL) exists in the catalog but is excluded from PSC info in the sandbox. */\nexport const UNSUPPORTED_PSC_LAB_ID = 3\n\nconst AREA_LAB_BILLS: Readonly<Record<string, readonly string[]>> = {\n sonora_quest: [\"client_bill\"],\n labcorp: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n bioreference: [\"patient_bill_passthrough\"],\n quest: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n}\n\nconst AREA_LABS: ReadonlyArray<{\n slug: string\n lab_id: number\n appointment_with_vital: boolean\n capabilities: readonly string[]\n}> = [\n { slug: \"sonora_quest\", lab_id: 25, appointment_with_vital: true, capabilities: [] },\n { slug: \"labcorp\", lab_id: 6, appointment_with_vital: false, capabilities: [] },\n { slug: \"bioreference\", lab_id: 13, appointment_with_vital: false, capabilities: [] },\n {\n slug: \"quest\",\n lab_id: 4,\n appointment_with_vital: true,\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n]\n\n/** Zips where getlabs phlebotomy is offered (mirrors sandbox coverage). */\nconst PHLEBOTOMY_SERVED_PREFIXES: readonly number[] = [850, 900, 303, 917, 891]\n\nconst phlebotomyServed = (zip: string): boolean => {\n const prefix = Number(zip.slice(0, 3))\n return PHLEBOTOMY_SERVED_PREFIXES.includes(prefix)\n}\n\n/**\n * Deterministic PSC inventory model: the true number of sites within the radius is a\n * seeded function of zip + lab scaled by radius (the sandbox derives it from real geo\n * data); `psc/info` returns the nearest sites capped at 30. Unserviced zip prefixes\n * (000, 96x territories with no national-lab coverage) have no inventory.\n */\nconst UNSERVICED_PSC_PREFIXES: readonly number[] = [0]\n\nconst withinRadiusFor = (zip: string, labSlug: string, radius: number): number => {\n if (UNSERVICED_PSC_PREFIXES.includes(Number(zip.slice(0, 3)))) return 0\n const seed = seedFor([\"psc-count\", zip, labSlug])\n const fraction = seededRandom(seed)()\n return Math.round(fraction * radius * 1.6)\n}\n\nconst PSC_SITE_NAMES = [\"Downtown\", \"Midtown\", \"Harbor\", \"Central\", \"University\", \"Parkside\"]\nconst PSC_SITE_HOURS: Readonly<Record<string, string>> = {\n monday: \"08:00-17:00\",\n tuesday: \"08:00-17:00\",\n wednesday: \"08:00-17:00\",\n thursday: \"08:00-17:00\",\n friday: \"08:00-14:00\",\n}\n\nconst pscSiteFor = (zip: string, labSlug: string, index: number, radius: number) => {\n const random = seededRandom(seedFor([\"psc-site\", zip, labSlug, index]))\n const prefix = Number(zip.slice(0, 3))\n const state = prefix >= 900 ? \"CA\" : prefix >= 600 ? \"CO\" : prefix >= 300 ? \"GA\" : \"NY\"\n const city = PSC_SITE_NAMES[index % PSC_SITE_NAMES.length]\n const siteCodeSeed = seededRandom(seedFor([\"psc-code\", labSlug, index]))\n const siteCode =\n labSlug === \"quest\" || labSlug === \"sonora_quest\"\n ? Array.from({ length: 3 }, () =>\n String.fromCharCode(65 + Math.floor(siteCodeSeed() * 26)),\n ).join(\"\")\n : String(10_000 + Math.floor(siteCodeSeed() * 89_999))\n return {\n name: `${labSlug.replace(\"_\", \" \")} - ${city}`,\n state,\n city,\n zip_code: zip,\n first_line: `${100 + Math.floor(random() * 800)} Main St`,\n phone_number: `+1${200 + Math.floor(random() * 700)}555${String(1000 + Math.floor(random() * 8999))}`,\n hours: PSC_SITE_HOURS,\n distance: Math.round((0.5 + random() * radius) * 10) / 10,\n site_code: siteCode,\n location: {\n lng: -122.4 + (random() - 0.5) * 0.2,\n lat: 37.77 + (random() - 0.5) * 0.2,\n },\n }\n}\n\n/**\n * Deterministic area model: `within_radius` mirrors the PSC inventory count per lab, the\n * phlebotomy section mirrors getlabs market coverage, and central_labs always lists the\n * four national labs with their billing/capability profiles.\n *\n * With a lab account, the availability check is scoped to that account: `central_labs`\n * contains only the account's lab (empty when the account's lab has no area profile) and\n * `supported_bill_types` comes from the account's `allowed_billing` keys.\n */\nconst areaInfoFor = (zip: string, radius: number, account: LabAccountRecord | null = null) => {\n const served = phlebotomyServed(zip)\n const centralLabs: Record<string, unknown> = {}\n const labs = account === null ? AREA_LABS : AREA_LABS.filter((lab) => lab.slug === account.lab)\n for (const lab of labs) {\n centralLabs[lab.slug] = {\n patient_service_centers: {\n appointment_with_vital: lab.appointment_with_vital,\n within_radius: withinRadiusFor(zip, lab.slug, radius),\n radius: String(radius),\n capabilities: [...lab.capabilities],\n },\n supported_bill_types:\n account === null\n ? [...(AREA_LAB_BILLS[lab.slug] ?? [])]\n : Object.keys(account.allowed_billing),\n lab_id: lab.lab_id,\n }\n }\n return {\n zip_code: zip,\n phlebotomy: {\n is_served: served,\n providers: served ? [{ name: \"getlabs\", service_types: [\"appointment-ready\"] }] : [],\n },\n central_labs: centralLabs,\n }\n}\n\nconst jsonObject = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\nconst isUuid = (value: string): boolean =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n\nconst uuidError = (value: string, loc: string[]) => {\n const characters = Array.from(value)\n const invalidIndex = characters.findIndex((character) => !/^[0-9a-f-]$/i.test(character))\n const error =\n invalidIndex >= 0\n ? `invalid character: expected an optional prefix of \\`urn:uuid:\\` followed by [0-9a-fA-F-], found \\`${characters[invalidIndex]}\\` at ${invalidIndex + 1}`\n : `invalid length: expected length 32 for simple format, found ${value.replaceAll(\"-\", \"\").length}`\n return {\n type: \"uuid_parsing\",\n loc,\n msg: `Input should be a valid UUID, ${error}`,\n input: value,\n ctx: { error },\n }\n}\n\nconst ALLOWED_RADII = [10, 20, 25, 50, 100] as const\nconst DEFAULT_RADIUS = 25\n\nconst radiusOf = (context: OperationContext): number => {\n const raw = context.query.radius\n if (raw === undefined) return DEFAULT_RADIUS\n const value = typeof raw === \"string\" && /^\\d+$/.test(raw) ? Number(raw) : Number.NaN\n if (!ALLOWED_RADII.includes(value as (typeof ALLOWED_RADII)[number])) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"radius\"],\n msg: \"Input should be '10', '20', '25', '50' or '100'\",\n input: raw,\n ctx: { expected: \"'10', '20', '25', '50' or '100'\" },\n },\n ],\n })\n }\n return value\n}\n\n/**\n * A recorded area/PSC read for the same query at another radius, or `undefined`.\n * `radius=25` and no `radius` are the same request (the sandbox's default is 25).\n */\nconst recordedAtRadius = (state: JunctionState, context: OperationContext, radius: number) => {\n const params = new URLSearchParams(context.url.searchParams)\n params.delete(\"radius\")\n const lookup = (query: URLSearchParams) =>\n state.getGetCache(state.cacheKeyForRequest(\"GET\", context.url.pathname, query))\n if (radius === DEFAULT_RADIUS) {\n const bare = lookup(params)\n if (bare) return bare\n }\n params.set(\"radius\", String(radius))\n return lookup(params)\n}\n\n/**\n * A covered ZIP's read at a radius the corpus did not record, answered from the recording.\n *\n * `psc/info`: the sandbox lists the nearest sites (at most 30) within the radius, so a smaller\n * radius is exactly the smallest wider recording's sites with `distance < radius` (`distance`\n * is rounded, and a recorded `25` is outside a 25-mile search). `area/info`: `within_radius`\n * counts cannot be derived, so only the default-radius equivalence applies. `undefined` when\n * nothing recorded answers it.\n */\nconst derivedFromRecording = (\n state: JunctionState,\n context: OperationContext,\n radius: number,\n): Response | undefined => {\n const same = recordedAtRadius(state, context, radius)\n if (same) return responseFromCache(same)\n if (!context.url.pathname.endsWith(\"/psc/info\")) return undefined\n for (const wider of ALLOWED_RADII) {\n if (wider <= radius) continue\n const recorded = recordedAtRadius(state, context, wider)\n if (!recorded) continue\n const body = recorded.body as Record<string, unknown> | null\n if (recorded.status !== 200 || !body || !Array.isArray(body.patient_service_centers))\n return undefined\n const centers = body.patient_service_centers.filter(\n (center) => Number((center as Record<string, unknown>).distance) < radius,\n )\n return responseFromCache({ ...recorded, body: { ...body, patient_service_centers: centers } })\n }\n return undefined\n}\n\n/**\n * In `corpus` geo mode, a covered ZIP's read the recording cannot answer fails like an\n * uncovered ZIP instead of inventing sites and labs next to recorded ones.\n */\nconst requireRecordedRead = (state: JunctionState, context: OperationContext, zip: string) => {\n if (state.geoMode !== \"corpus\") return\n const query = [...context.url.searchParams.entries()]\n .map(([key, value]) => `${key}=${value}`)\n .join(\"&\")\n throw new HttpError(UNKNOWN_ZIP_STATUS, {\n detail: {\n error_type: UNKNOWN_ZIP_ERROR_TYPE,\n error_message: `ZIP ${zip} is in the loaded Junction corpus, but GET ${context.url.pathname}?${query} was not recorded and cannot be derived from what was (a smaller psc/info radius is filtered from a wider recording; area/info needs its own). Record it, or serve with --geo synthetic to invent coverage.`,\n zip_code: zip,\n corpus: state.corpusLabel ?? null,\n },\n })\n}\n\nconst zipCodeOf = (context: OperationContext, required: boolean): string | undefined => {\n const raw = context.query.zip_code\n if (raw === undefined) {\n if (required) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"query\", \"zip_code\"],\n msg: \"Field required\",\n input: undefined,\n },\n ],\n })\n }\n return undefined\n }\n if (typeof raw !== \"string\") throw new HttpError(422, { detail: \"zip_code must be a string\" })\n return raw\n}\n\n/**\n * Optional `lab_account_id` for an availability check: it must be a UUID, exist for this\n * team, and be active \u2014 the same account rules Create Order applies.\n */\nconst labAccountOf = (state: JunctionState, context: OperationContext): LabAccountRecord | null => {\n const raw = context.query.lab_account_id\n if (raw === undefined) return null\n if (typeof raw !== \"string\" || !isUuid(raw)) {\n throw new HttpError(422, {\n detail: [uuidError(typeof raw === \"string\" ? raw : String(raw), [\"query\", \"lab_account_id\"])],\n })\n }\n const account = labAccountById(raw, state.listLabAccounts())\n if (!account || !isLinkedToTeam(account, state.teamId))\n throw new HttpError(404, { detail: \"Lab account does not exist\" })\n if (account.status !== \"active\") throw new HttpError(400, { detail: \"Lab account is not active\" })\n return account\n}\n\nconst startDateOf = (context: OperationContext, nowMs: number): string => {\n const raw = context.query.start_date\n if (raw === undefined) return addDays(isoDate(new Date(nowMs)), 1)\n if (typeof raw !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"date_from_datetime_parsing\",\n loc: [\"query\", \"start_date\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: raw,\n ctx: { error: \"invalid character in year\" },\n },\n ],\n })\n }\n return raw\n}\n\nconst appointmentOfOrder = (\n state: JunctionState,\n orderId: string,\n): AppointmentRecord | undefined => {\n const binding = state.appointmentsByOrder.get(orderId)\n if (!binding) return undefined\n return state.appointments.get(binding.appointment_id)\n}\n\nconst renderAppointment = (appointment: AppointmentRecord): Record<string, unknown> => ({\n id: appointment.id,\n user_id: appointment.user_id,\n order_id: appointment.order_id,\n address: appointment.address,\n location: appointment.location,\n start_at: appointment.start_at,\n end_at: appointment.end_at,\n iana_timezone: appointment.iana_timezone,\n type: appointment.type,\n provider: appointment.provider,\n status: appointment.status,\n provider_id: appointment.provider_id,\n external_id: appointment.external_id,\n can_reschedule: appointment.can_reschedule,\n event_status: appointment.event_status,\n event_data: appointment.event_data,\n order_transaction_id: appointment.order_transaction_id,\n appointment_notes: appointment.appointment_notes,\n events: appointment.events,\n})\n\ntype SlotSeed = {\n bookingKey: string\n start: string\n end: string\n expiresAt: string\n price: number\n isPriority: boolean\n numAppointmentsAvailable: number\n modality: AppointmentModality\n provider: \"getlabs\" | \"phlebfinders\" | \"quest\"\n siteCode: string | null\n zipCode: string\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n}\n\nconst phlebotomyAddress = (zip: string): Record<string, unknown> => {\n const { city, state } = cityStateForZip(zip)\n return {\n first_line: \"1 Main St\",\n second_line: \"\",\n city,\n state,\n zip_code: zip,\n unit: null,\n access_notes: null,\n }\n}\n\nconst persistSlot = (state: JunctionState, seed: SlotSeed, nowMs: number): BookingKeyRecord => {\n const record: BookingKeyRecord = {\n key: seed.bookingKey,\n start: seed.start,\n end: seed.end,\n expires_at: seed.expiresAt,\n price: seed.price,\n is_priority: seed.isPriority,\n num_appointments_available: seed.numAppointmentsAvailable,\n modality: seed.modality,\n provider: seed.provider,\n site_code: seed.siteCode,\n zip_code: seed.zipCode,\n address: seed.address,\n location: seed.location,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(seed.bookingKey, record)\n return record\n}\n\nconst generatePhlebotomySlots = (\n state: JunctionState,\n zip: string,\n startDate: string,\n provider: PhlebotomyProviderName,\n nowMs: number,\n): { timezone: string; days: Array<Record<string, unknown>> } => {\n const random = seededRandom(seedFor([\"phlebotomy\", provider, zip, startDate]))\n const timezone = zipTimezone(zip)\n const days: Array<Record<string, unknown>> = []\n for (let day = 0; day < 3; day++) {\n const date = addDays(startDate, day)\n const slots: Array<Record<string, unknown>> = []\n const slotCount = 2 + Math.floor(random() * 3)\n for (let slot = 0; slot < slotCount; slot++) {\n const hour = 8 + Math.floor(random() * 8)\n const minute = random() < 0.5 ? 0 : 30\n const start = new Date(`${date}T00:00:00Z`)\n start.setUTCHours(hour, minute, 0, 0)\n if (start.getTime() <= nowMs) continue\n const end = new Date(start.getTime() + 45 * 60_000)\n const salt = `${provider}:${zip}:${date}:${start.toISOString()}`\n const seed: SlotSeed = {\n bookingKey: state.bookingKeyFor(salt),\n start: start.toISOString(),\n end: end.toISOString(),\n expiresAt: new Date(start.getTime() - 60 * 60_000).toISOString(),\n price: random() < 0.5 ? 0 : 30,\n isPriority: random() < 0.3,\n numAppointmentsAvailable: 1 + Math.floor(random() * 4),\n modality: \"phlebotomy\",\n provider,\n siteCode: null,\n zipCode: zip,\n address: phlebotomyAddress(zip),\n location: zipLocation(zip),\n }\n const record = persistSlot(state, seed, nowMs)\n slots.push({\n booking_key: record.key,\n start: record.start,\n end: record.end,\n expires_at: record.expires_at,\n price: record.price,\n is_priority: record.is_priority,\n num_appointments_available: record.num_appointments_available,\n })\n }\n if (slots.length > 0) days.push({ date, slots })\n }\n return { timezone, days }\n}\n\nconst generatePscSlots = (\n state: JunctionState,\n zip: string,\n startDate: string,\n siteCodes: string[] | null,\n nowMs: number,\n): { timezone: string; days: Array<Record<string, unknown>> } => {\n const siteCount = Math.max(withinRadiusFor(zip, \"quest\", 25), 1)\n const sites = Array.from({ length: Math.min(siteCount, 30) }, (_, index) =>\n pscSiteFor(zip, \"quest\", index, 25),\n ).filter((site) => siteCodes === null || siteCodes.includes(site.site_code))\n const random = seededRandom(seedFor([\"psc\", zip, startDate, (siteCodes ?? []).sort().join(\"|\")]))\n const timezone = zipTimezone(zip)\n const days: Array<Record<string, unknown>> = []\n for (let day = 0; day < 3; day++) {\n const date = addDays(startDate, day)\n const slots: Array<Record<string, unknown>> = []\n const slotCount = 2 + Math.floor(random() * 3)\n for (let slot = 0; slot < slotCount; slot++) {\n const hour = 7 + Math.floor(random() * 9)\n const minute = random() < 0.5 ? 0 : 30\n const start = new Date(`${date}T00:00:00Z`)\n start.setUTCHours(hour, minute, 0, 0)\n if (start.getTime() <= nowMs) continue\n const end = new Date(start.getTime() + 15 * 60_000)\n const site = sites.length > 0 ? sites[slot % sites.length] : undefined\n const salt = `psc:${zip}:${site?.site_code ?? \"none\"}:${date}:${start.toISOString()}`\n const seed: SlotSeed = {\n bookingKey: state.bookingKeyFor(salt),\n start: start.toISOString(),\n end: end.toISOString(),\n expiresAt: new Date(start.getTime() - 60 * 60_000).toISOString(),\n price: 0,\n isPriority: false,\n numAppointmentsAvailable: 1 + Math.floor(random() * 6),\n modality: \"patient_service_center\",\n provider: \"quest\",\n siteCode: site?.site_code ?? null,\n zipCode: zip,\n address: site\n ? {\n first_line: site.first_line,\n second_line: null,\n city: site.city,\n state: site.state,\n zip_code: site.zip_code,\n unit: null,\n }\n : phlebotomyAddress(zip),\n location: site?.location ?? zipLocation(zip),\n }\n const record = persistSlot(state, seed, nowMs)\n slots.push({\n booking_key: record.key,\n start: record.start,\n end: record.end,\n expires_at: record.expires_at,\n price: record.price,\n is_priority: record.is_priority,\n num_appointments_available: record.num_appointments_available,\n site_code: record.site_code,\n })\n }\n if (slots.length > 0) days.push({ date, slots })\n }\n return { timezone, days }\n}\n\nfunction notFound(message: string): never {\n throw new HttpError(404, { detail: message })\n}\n\nfunction invalidBookingKey(): never {\n throw new HttpError(400, { detail: \"Invalid or expired booking key\" })\n}\n\ntype Order = NonNullable<ReturnType<JunctionState[\"orders\"][\"get\"]>>\n\nconst requireOrder = (state: JunctionState, orderId: string, context: OperationContext): Order => {\n if (!isUuid(orderId)) {\n throw new HttpError(422, { detail: [uuidError(orderId, [\"path\", \"order_id\"])] })\n }\n const loaded: Order =\n state.orders.get(orderId) ?? orderMissing(state, context.operation.operationId, orderId)\n state.applyDueSimulateTransitions(context.now(), (_due, finalStatus, flags) => {\n applySimulateTransition(state, loaded, finalStatus, flags, context)\n })\n return state.orders.get(orderId) ?? orderMissing(state, context.operation.operationId, orderId)\n}\n\nconst orderCollectionMethod = (order: Order): string => {\n if (typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0) {\n return order.lab_test.method\n }\n if (typeof order.details?.type === \"string\" && order.details.type.length > 0) {\n return order.details.type\n }\n return \"\"\n}\n\nconst requirePhlebotomyCapableOrder = (order: Order): void => {\n if (orderCollectionMethod(order) !== \"at_home_phlebotomy\") {\n notFound(\"This order doesn't have a phlebotomy order.\")\n }\n}\n\nconst requirePscCapableOrder = (order: Order): void => {\n const method = orderCollectionMethod(order)\n if (method !== \"walk_in_test\" && method !== \"on_site_collection\") {\n notFound(\"This order is not a walk-in phlebotomy order.\")\n }\n}\n\nconst requireOrderHasRequisition = (order: Order): void => {\n const hasRequisition = order.events.some(\n (entry) => typeof entry.status === \"string\" && entry.status.endsWith(\".requisition_created\"),\n )\n if (hasRequisition) return\n const lowLevel =\n typeof order.last_event?.status === \"string\"\n ? (order.last_event.status.split(\".\").at(-1) ?? order.last_event.status)\n : typeof order.status === \"string\" && order.status.length > 0\n ? order.status\n : \"ordered\"\n throw new HttpError(400, {\n detail: `This order does not have a requisition, it's still in state ${lowLevel}.`,\n })\n}\n\nconst appendOrderStatusEvent = (\n state: JunctionState,\n order: Order,\n status: string,\n context: Pick<OperationContext, \"now\">,\n): void => {\n const now = state.isoNow(context.now)\n const eventId =\n Number.parseInt(opaqueToken(`junction:order-event:${order.id}:${order.events.length}`, 8), 16) %\n 1_000_000_000 || order.events.length + 1\n const event = {\n id: eventId,\n created_at: now,\n status,\n status_detail: null,\n }\n order.status = status.split(\".\")[0] ?? order.status\n order.updated_at = now\n order.events.push(event)\n order.last_event = event\n if (status.endsWith(\".requisition_created\")) {\n if (order.sample_id === null) {\n order.sample_id = opaqueToken(`junction:sample:${order.id}`, 12).toUpperCase()\n }\n if (order.requisition_form_url === null) {\n order.requisition_form_url = `https://storage.googleapis.com/vital_labs_sandbox/mock/requisition_forms/${order.id}_${order.sample_id}.pdf`\n }\n }\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n if (transactionOrder) {\n transactionOrder.low_level_status = status.split(\".\").at(-1) ?? status\n transactionOrder.low_level_status_created_at = new Date(context.now()).toISOString()\n transactionOrder.updated_at = new Date(context.now()).toISOString()\n }\n if (status.startsWith(\"completed\")) order.order_transaction.status = \"completed\"\n if (status.startsWith(\"cancelled\")) order.order_transaction.status = \"cancelled\"\n}\n\nconst applySimulationFlags = (order: Order, flags: Record<string, unknown> | null): boolean => {\n if (!flags) return false\n let changed = false\n if (typeof flags.interpretation === \"string\") {\n order.interpretation = flags.interpretation\n changed = true\n }\n if (typeof flags.has_missing_results === \"boolean\") {\n order.has_missing_results = flags.has_missing_results\n changed = true\n }\n if (Array.isArray(flags.result_types)) {\n order.result_types = flags.result_types as string[]\n changed = true\n }\n return changed\n}\n\n/**\n * Mirror api.sandbox.tryvital.io `/v3/order/{id}/test` semantics (probed 2026-09):\n * - First call on a fresh order always creates `received.{method}.requisition_created`.\n * - `at_home_phlebotomy` (and other non-walk-in methods): further `/test` calls are no-ops.\n * - `walk_in_test` after requisition:\n * - matching `appointment_*` / `requisition_created` \u2192 no-op\n * - matching `partial_results` \u2192 append partial only (default interpretation normal)\n * - matching `ordered` / `completed` / `cancelled`, or any mismatched-method status \u2192\n * jump through partial then completed (+ result date fields)\n * - `failed.*` \u2192 append the failed status\n */\n/** Set the expected and worst-case result dates from the lab test's turnaround times. */\nconst markExpectedResultDates = (order: Order, nowMs: number): void => {\n const now = new Date(nowMs)\n const commonDays =\n typeof order.lab_test.common_tat_days === \"number\" && order.lab_test.common_tat_days > 0\n ? order.lab_test.common_tat_days\n : 3\n const worstDays =\n typeof order.lab_test.worst_case_tat_days === \"number\" && order.lab_test.worst_case_tat_days > 0\n ? order.lab_test.worst_case_tat_days\n : 5\n const expected = new Date(now)\n expected.setUTCDate(expected.getUTCDate() + commonDays)\n const worst = new Date(now)\n worst.setUTCDate(worst.getUTCDate() + worstDays)\n order.expected_result_by_date = expected.toISOString().slice(0, 10)\n order.worst_case_result_by_date = worst.toISOString().slice(0, 10)\n}\n\nconst applySimulateTransition = (\n state: JunctionState,\n order: Order,\n finalStatus: string,\n flags: Record<string, unknown> | null,\n context: OperationContext,\n): void => {\n const orderMethod =\n typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type.length > 0\n ? order.details.type\n : \"at_home_phlebotomy\"\n const hasCancelled = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.startsWith(\"cancelled.\") : false,\n )\n if (hasCancelled) return\n\n const hasRequisition = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".requisition_created\") : false,\n )\n const hasPartial = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".partial_results\") : false,\n )\n const hasCompleted = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".completed\") : false,\n )\n\n const requestedParts = finalStatus.split(\".\")\n const requestedMethod =\n requestedParts.length >= 3 ? (requestedParts[1] ?? orderMethod) : orderMethod\n const methodMismatch = requestedMethod !== orderMethod\n const normalizedTarget = (() => {\n if (requestedParts.length >= 3)\n return `${requestedParts[0]}.${orderMethod}.${requestedParts.slice(2).join(\".\")}`\n return finalStatus\n })()\n const targetTail = normalizedTarget.split(\".\").at(-1) ?? normalizedTarget\n\n let statusesToApply: string[] = []\n let applyFlags = false\n let markCompleteDates = false\n\n if (!hasRequisition) {\n statusesToApply = [`received.${orderMethod}.requisition_created`]\n } else if (orderMethod === \"walk_in_test\") {\n if (hasCompleted) {\n statusesToApply = []\n } else if (normalizedTarget.startsWith(\"failed.\")) {\n statusesToApply = [normalizedTarget]\n } else if (\n !methodMismatch &&\n (targetTail === \"appointment_pending\" ||\n targetTail === \"appointment_scheduled\" ||\n targetTail === \"appointment_cancelled\" ||\n targetTail === \"redraw_available\" ||\n targetTail === \"requisition_created\" ||\n targetTail === \"requisition_bypassed\")\n ) {\n statusesToApply = []\n } else if (!methodMismatch && targetTail === \"partial_results\") {\n if (!hasPartial) statusesToApply = [`sample_with_lab.${orderMethod}.partial_results`]\n applyFlags = true\n if (!flags || typeof flags.interpretation !== \"string\") {\n order.interpretation = order.interpretation ?? \"normal\"\n }\n } else {\n // ordered / completed / cancelled / mismatched-method \u2192 complete jump\n statusesToApply = []\n if (!hasPartial) statusesToApply.push(`sample_with_lab.${orderMethod}.partial_results`)\n statusesToApply.push(`completed.${orderMethod}.completed`)\n applyFlags = true\n markCompleteDates = true\n if (!flags || typeof flags.interpretation !== \"string\") {\n order.interpretation = order.interpretation ?? \"normal\"\n }\n }\n }\n\n if (statusesToApply.length === 0 && !applyFlags && !markCompleteDates) return\n\n for (const status of statusesToApply) {\n appendOrderStatusEvent(state, order, status, context)\n }\n if (applyFlags) applySimulationFlags(order, flags)\n if (markCompleteDates) markExpectedResultDates(order, context.now())\n state.orders.update(order.id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n}\n\nconst linkAppointmentToOrder = (\n state: JunctionState,\n order: Order,\n appointment: AppointmentRecord,\n status: string,\n nowIso: string,\n): void => {\n const data = order.details.data as Record<string, unknown> | null | undefined\n if (data && typeof data === \"object\") {\n data.appointment_id = appointment.id\n data.updated_at = nowIso\n }\n const event = {\n id: order.events.length + 1,\n created_at: nowIso,\n status,\n status_detail: null,\n }\n order.status = status.split(\".\")[0] ?? order.status\n order.updated_at = nowIso\n order.events.push(event)\n order.last_event = event\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n if (transactionOrder) {\n transactionOrder.low_level_status = status.split(\".\").at(-1) ?? status\n transactionOrder.low_level_status_created_at = nowIso\n transactionOrder.updated_at = nowIso\n }\n state.orders.update(order.id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\", new Date(nowIso).getTime())\n}\n\nconst appendAppointmentEvent = (\n appointment: AppointmentRecord,\n status: AppointmentEventRecord[\"status\"],\n at: string,\n): AppointmentEventRecord => {\n const event: AppointmentEventRecord = { created_at: at, status, data: null }\n appointment.events.push(event)\n appointment.event_status = status\n return event\n}\n\nconst cancelAppointment = (\n state: JunctionState,\n appointment: AppointmentRecord,\n order: Order,\n nowMs: number,\n): AppointmentRecord => {\n const nowIso = state.isoNow(() => nowMs)\n appointment.status = \"cancelled\"\n appendAppointmentEvent(appointment, \"cancelled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n const eventStatus = CANCELLED_ORDER_EVENT[appointment.type]\n const event = {\n id: order.events.length + 1,\n created_at: nowIso,\n status: eventStatus,\n status_detail: null,\n }\n order.status = \"collecting_sample\"\n order.updated_at = nowIso\n order.events.push(event)\n order.last_event = event\n state.orders.update(order.id, order)\n state.publishAppointmentWebhook(appointment, order.team_id, nowMs)\n state.publishOrderWebhook(order, \"labtest.order.updated\", nowMs)\n return appointment\n}\n\nexport const schedulingHandlers = (state: JunctionState) => ({\n get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get:\n async () => jsonRes(200, CANCELLATION_REASONS),\n\n get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get:\n async () => jsonRes(200, PSC_CANCELLATION_REASONS),\n\n get_area_info_v3_order_area_info_get: async (context: OperationContext) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const rawZip = zipCodeOf(context, true) ?? \"\"\n const radius = radiusOf(context)\n if (!/^\\d{5}(?:-?\\d{4})?$/.test(rawZip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_pattern_mismatch\",\n loc: [\"query\", \"zip_code\"],\n msg: \"String should match pattern '^\\\\d{5}(?:-?\\\\d{4})?$'\",\n input: rawZip,\n ctx: { pattern: \"^\\\\d{5}(?:-?\\\\d{4})?$\" },\n },\n ],\n })\n }\n const zip = rawZip.slice(0, 5)\n requireCoveredZip(state, zip)\n const account = labAccountOf(state, context)\n const derived = derivedFromRecording(state, context, radius)\n if (derived) return derived\n requireRecordedRead(state, context, zip)\n return jsonRes(200, areaInfoFor(zip, radius, account))\n },\n\n get_psc_info_v3_order_psc_info_get: async (context: OperationContext) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const zip = zipCodeOf(context, true) ?? \"\"\n const labIdRaw = context.query.lab_id\n if (labIdRaw === undefined) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"query\", \"lab_id\"],\n msg: \"Field required\",\n input: undefined,\n },\n ],\n })\n }\n if (typeof labIdRaw !== \"string\" || !/^-?\\d+$/.test(labIdRaw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"int_parsing\",\n loc: [\"query\", \"lab_id\"],\n msg: \"Input should be a valid integer, unable to parse string as an integer\",\n input: labIdRaw,\n ctx: { error: {} },\n },\n ],\n })\n }\n if (!/^\\d{5}$/.test(zip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_pattern_mismatch\",\n loc: [\"query\", \"zip_code\"],\n msg: \"String should match pattern '^\\\\d{5}$'\",\n input: zip,\n ctx: { pattern: \"^\\\\d{5}$\" },\n },\n ],\n })\n }\n const labId = Number(labIdRaw)\n const radius = radiusOf(context)\n const capabilitiesRaw = context.query.capabilities\n const capabilityList = Array.isArray(capabilitiesRaw)\n ? capabilitiesRaw.map(String)\n : capabilitiesRaw !== undefined\n ? [String(capabilitiesRaw)]\n : []\n const knownCapabilities = [\n \"stat\",\n \"appointment_scheduling_via_junction\",\n \"appointment_scheduling_with_lab\",\n ]\n if (capabilityList.some((capability) => !knownCapabilities.includes(capability))) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"capabilities\", 0],\n msg: \"Input should be 'stat', 'appointment_scheduling_via_junction' or 'appointment_scheduling_with_lab'\",\n input: capabilityList,\n ctx: {\n expected:\n \"'stat', 'appointment_scheduling_via_junction' or 'appointment_scheduling_with_lab'\",\n },\n },\n ],\n })\n }\n const lab = PSC_LABS.find((entry) => entry.lab_id === labId)\n if (labId === UNSUPPORTED_PSC_LAB_ID) {\n throw new HttpError(404, { detail: \"Lab not supported for PSC info.\" })\n }\n if (!lab) {\n throw new HttpError(404, { detail: \"Lab not found.\" })\n }\n requireCoveredZip(state, zip)\n const derived = derivedFromRecording(state, context, radius)\n if (derived) return derived\n requireRecordedRead(state, context, zip)\n // The sandbox returns the nearest sites within the radius, capped at 30 entries; the\n // mock synthesizes a deterministic inventory of the same contract.\n const within = withinRadiusFor(zip, lab.slug, radius)\n const centerCount = Math.min(within, 30)\n const centers = Array.from({ length: centerCount }, (_, index) => {\n const site = pscSiteFor(zip, lab.slug, index, radius)\n return {\n metadata: {\n name: site.name,\n state: site.state,\n city: site.city,\n zip_code: site.zip_code,\n first_line: site.first_line,\n second_line: null,\n phone_number: site.phone_number,\n fax_number: null,\n hours: site.hours,\n },\n distance: site.distance,\n site_code: site.site_code,\n supported_bill_types: [...lab.supported_bill_types],\n location: site.location,\n capabilities: [...lab.capabilities],\n }\n })\n return jsonRes(200, {\n lab_id: labId,\n slug: lab.slug,\n patient_service_centers: centers,\n })\n },\n\n get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post: async (\n context: OperationContext,\n ) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const body = jsonObject(context)\n const zip = typeof body.zip_code === \"string\" ? body.zip_code : \"\"\n if (!/^\\d{5}$/.test(zip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"value_error\",\n loc: [\"body\", \"zip_code\"],\n msg: `Value error, Invalid zip code: ${zip}`,\n input: body.zip_code,\n ctx: { error: {} },\n },\n ],\n })\n }\n if (typeof body.first_line !== \"string\" || typeof body.city !== \"string\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"body\", \"first_line\"],\n msg: \"Field required\",\n input: body,\n },\n ],\n })\n }\n requireCoveredZip(state, zip)\n const startDate = startDateOf(context, context.now())\n const { timezone, days } = generatePhlebotomySlots(\n state,\n zip,\n startDate,\n \"getlabs\",\n context.now(),\n )\n if (days.length === 0) notFound(\"No availability found\")\n // Align booking-key address/location with the availability request (Vital echoes it on book).\n rotateGeneratedAvailabilityKeys(state, days, context.now(), {\n address: addressFromAvailabilityRequest(body, zip),\n location: zipLocation(zip),\n zip,\n })\n return jsonRes(200, { timezone, slots: days })\n },\n\n get_psc_appointment_availability_v3_order_psc_appointment_availability_post: async (\n context: OperationContext,\n ) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const lab = context.query.lab\n if (lab !== \"quest\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"lab\"],\n msg: \"Input should be 'quest'\",\n input: lab,\n ctx: { expected: \"'quest'\" },\n },\n ],\n })\n }\n const zip = zipCodeOf(context, false)\n const startDate = startDateOf(context, context.now())\n const siteCodesRaw = context.query.site_codes\n let siteCodes: string[] | null = null\n if (siteCodesRaw !== undefined) {\n if (typeof siteCodesRaw !== \"string\") {\n throw new HttpError(422, { detail: \"site_codes must be a JSON array string\" })\n }\n try {\n const parsed: unknown = JSON.parse(siteCodesRaw)\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== \"string\")) {\n throw new Error(\"not an array of strings\")\n }\n siteCodes = parsed as string[]\n } catch {\n throw new HttpError(422, { detail: \"site_codes must be a JSON array of strings\" })\n }\n }\n if (zip !== undefined) requireCoveredZip(state, zip)\n const { timezone, days } = generatePscSlots(\n state,\n zip ?? \"\",\n startDate,\n siteCodes,\n context.now(),\n )\n if (days.length === 0) notFound(\"No slots found\")\n rotateGeneratedAvailabilityKeys(state, days, context.now())\n return jsonRes(200, { timezone, slots: days })\n },\n\n get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n return jsonRes(200, renderAppointment(appointment))\n },\n\n get_psc_appointment_v3_order__order_id__psc_appointment_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n return jsonRes(200, renderAppointment(appointment))\n },\n\n book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n requirePhlebotomyCapableOrder(order)\n requireOrderHasRequisition(order)\n const existing = appointmentOfOrder(state, order.id)\n if (existing && existing.status !== \"cancelled\") {\n throw new HttpError(400, { detail: \"Appointment already booked for this order\" })\n }\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record?.modality !== \"phlebotomy\" ||\n record.consumed_by_order_id !== null ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n const nowIso = state.isoNow(context.now)\n const appointmentId = state.nextAppointmentId()\n const appointment: AppointmentRecord = {\n id: appointmentId,\n order_id: order.id,\n user_id: order.user_id,\n provider_id: state.appointmentProviderIdFor(`${order.id}:${bookingKey}`),\n external_id: `getlabs-${state.appointmentProviderIdFor(orderId)}`,\n type: \"phlebotomy\",\n provider: record.provider as AppointmentRecord[\"provider\"],\n // Vital quirk: top-level status + events[0].status are pending, but event_status is scheduled.\n status: \"pending\",\n event_status: \"scheduled\",\n start_at: record.start,\n end_at: record.end,\n iana_timezone: zipTimezone(record.zip_code),\n address: record.address,\n location: record.location,\n can_reschedule: true,\n booking_key: record.key,\n site_code: null,\n appointment_notes: null,\n order_transaction_id: order.order_transaction.id,\n event_data: null,\n events: [],\n created_at: nowIso,\n updated_at: nowIso,\n }\n appendAppointmentEvent(appointment, \"pending\", nowIso)\n appointment.event_status = \"scheduled\"\n state.appointments.insert(appointmentId, appointment)\n state.appointmentsByOrder.insert(order.id, { appointment_id: appointmentId })\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n linkAppointmentToOrder(state, order, appointment, SCHEDULED_ORDER_EVENT.phlebotomy, nowIso)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n book_psc_appointment_v3_order__order_id__psc_appointment_book_post: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n requirePscCapableOrder(order)\n requireOrderHasRequisition(order)\n const idempotencyKey = context.request.headers.get(\"x-idempotency-key\")\n if (idempotencyKey !== null && idempotencyKey !== \"\") {\n const replay = state.cancelIdempotency.get(`psc-book:${idempotencyKey}`)\n if (replay) return jsonRes(200, replay.response)\n }\n const existing = appointmentOfOrder(state, order.id)\n if (existing && existing.status !== \"cancelled\") {\n throw new HttpError(400, { detail: \"Appointment already booked for this order\" })\n }\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const siteCode = typeof body.site_code === \"string\" ? body.site_code : \"\"\n if (siteCode === \"\") {\n throw new HttpError(400, { detail: \"site_code is required for PSC appointments\" })\n }\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n (record.modality === \"patient_service_center\" &&\n record.consumed_by_order_id !== null &&\n record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n if (record.modality !== \"patient_service_center\") {\n throw new HttpError(400, { detail: \"Booking key is not a patient service center slot\" })\n }\n if (record.site_code !== null && record.site_code !== siteCode) {\n throw new HttpError(400, { detail: \"Booking key does not match the requested site\" })\n }\n const nowIso = state.isoNow(context.now)\n const appointmentId = state.nextAppointmentId()\n const appointment: AppointmentRecord = {\n id: appointmentId,\n order_id: order.id,\n user_id: order.user_id,\n provider_id: state.appointmentProviderIdFor(`${order.id}:${record.key}`),\n external_id: `quest-${state.appointmentProviderIdFor(orderId)}`,\n type: \"patient_service_center\",\n provider: \"quest\",\n status: \"confirmed\",\n event_status: \"scheduled\",\n start_at: record.start,\n end_at: record.end,\n iana_timezone: zipTimezone(record.zip_code),\n address: record.address,\n location: record.location,\n can_reschedule: true,\n booking_key: record.key,\n site_code: siteCode,\n appointment_notes: null,\n order_transaction_id: order.order_transaction.id,\n event_data: null,\n events: [],\n created_at: nowIso,\n updated_at: nowIso,\n }\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.insert(appointmentId, appointment)\n state.appointmentsByOrder.insert(order.id, { appointment_id: appointmentId })\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n linkAppointmentToOrder(\n state,\n order,\n appointment,\n SCHEDULED_ORDER_EVENT.patient_service_center,\n nowIso,\n )\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n const response = renderAppointment(appointment)\n if (idempotencyKey !== null && idempotencyKey !== \"\") {\n state.cancelIdempotency.insert(`psc-book:${idempotencyKey}`, {\n order_id: order.id,\n response,\n })\n }\n return jsonRes(200, response)\n },\n\n reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch:\n async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n if (appointment.status === \"cancelled\")\n throw new HttpError(400, { detail: \"Cannot reschedule a cancelled appointment\" })\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n record.modality !== \"phlebotomy\" ||\n (record.consumed_by_order_id !== null && record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n const nowIso = state.isoNow(context.now)\n appointment.start_at = record.start\n appointment.end_at = record.end\n appointment.iana_timezone = zipTimezone(record.zip_code)\n appointment.address = record.address\n appointment.location = record.location\n appointment.booking_key = record.key\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n if (appointment.status === \"cancelled\")\n throw new HttpError(400, { detail: \"Cannot reschedule a cancelled appointment\" })\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n record.modality !== \"patient_service_center\" ||\n (record.consumed_by_order_id !== null && record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n if (record.site_code !== null && appointment.site_code !== record.site_code) {\n throw new HttpError(400, { detail: \"Booking key does not match the appointment site\" })\n }\n const nowIso = state.isoNow(context.now)\n appointment.start_at = record.start\n appointment.end_at = record.end\n appointment.iana_timezone = zipTimezone(record.zip_code)\n appointment.address = record.address\n appointment.location = record.location\n appointment.booking_key = record.key\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const reasonId =\n typeof body.cancellation_reason_id === \"string\" ? body.cancellation_reason_id : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n const reason = CANCELLATION_REASONS.find((entry) => entry.id === reasonId)\n if (!reason) {\n throw new HttpError(400, { detail: \"Invalid cancellation reason id\" })\n }\n if (reasonId === OTHER_CANCELLATION_REASON_ID && typeof body.notes !== \"string\") {\n throw new HttpError(400, { detail: \"notes is required for reason 'Other'\" })\n }\n if (appointment.status === \"cancelled\") return jsonRes(200, renderAppointment(appointment))\n appointment.appointment_notes = typeof body.notes === \"string\" ? body.notes : null\n cancelAppointment(state, appointment, order, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const reasonId = typeof body.cancellationReasonId === \"string\" ? body.cancellationReasonId : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n const reason = PSC_CANCELLATION_REASONS.find((entry) => entry.id === reasonId)\n if (!reason) {\n throw new HttpError(400, { detail: \"Invalid cancellation reason id\" })\n }\n if (appointment.status === \"cancelled\") return jsonRes(200, renderAppointment(appointment))\n appointment.appointment_notes = typeof body.note === \"string\" ? body.note : null\n cancelAppointment(state, appointment, order, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n})\n\n/** Cancels any active appointment linked to `orderId`; used by order cancellation cascade. */\nexport const cascadeCancelAppointments = (\n state: JunctionState,\n orderId: string,\n nowMs: number,\n): void => {\n const appointment = appointmentOfOrder(state, orderId)\n if (!appointment || appointment.status === \"cancelled\") return\n const order = state.orders.get(orderId)\n if (!order) return\n cancelAppointment(state, appointment, order, nowMs)\n}\n\n/**\n * Put an order straight into `status`, as the admin API does. Unlike `simulate_order`\n * it skips the sandbox's stepwise rules, but it records the same event, dates and\n * appointment cascade and publishes the same webhook a real transition does.\n */\nexport const forceOrderStatus = (\n state: JunctionState,\n order: Order,\n status: string,\n flags: Record<string, unknown> | null,\n context: Pick<OperationContext, \"now\">,\n): void => {\n const hasRequisition = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".requisition_created\") : false,\n )\n if (!hasRequisition && !status.startsWith(\"received.\")) {\n // A real order passes through requisition before anything else; keep the ids it mints.\n appendOrderStatusEvent(\n state,\n order,\n `received.${status.split(\".\")[1]}.requisition_created`,\n context,\n )\n }\n appendOrderStatusEvent(state, order, status, context)\n if (flags) applySimulationFlags(order, flags)\n if (status.startsWith(\"completed.\")) markExpectedResultDates(order, context.now())\n state.orders.update(order.id, order)\n if (status.startsWith(\"cancelled.\")) cascadeCancelAppointments(state, order.id, context.now())\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n}\n\nexport { applySimulateTransition, appointmentOfOrder, renderAppointment, requireOrder }\n", "import type { FormValue } from \"@crvouga/mockingbird-http-codec\"\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport { requireUser } from \"./fixtures.js\"\nimport {\n effectiveBilling,\n isLinkedToTeam,\n LAB_ACCOUNT_STATUSES,\n type LabAccountStatus,\n renderLabAccount,\n selectLabAccount,\n} from \"./lab-accounts.js\"\nimport { checkSimulateAllowed } from \"./limits.js\"\nimport { orderMissing } from \"./not-found.js\"\nimport { applySimulateTransition, cascadeCancelAppointments } from \"./scheduling.js\"\nimport type { JunctionState, LabTestRecord, OrderRecord } from \"./state.js\"\nimport { deterministicUuid } from \"./state.js\"\n\nconst RESULT_TYPES = [\"numeric\", \"range\", \"comment\", \"coded_value\"] as const\nconst INTERPRETATIONS = [\"normal\", \"abnormal\", \"critical\", \"unknown\"] as const\n\nconst simulationFlagsOf = (context: OperationContext): Record<string, unknown> | null => {\n const body = context.body\n if (body.kind !== \"json\") return null\n const value = body.value\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null\n const raw = value as Record<string, unknown>\n const flags: Record<string, unknown> = {}\n if (\n typeof raw.interpretation === \"string\" &&\n INTERPRETATIONS.includes(raw.interpretation as never)\n )\n flags.interpretation = raw.interpretation\n if (Array.isArray(raw.result_types)) {\n const types = raw.result_types.filter(\n (entry): entry is string =>\n typeof entry === \"string\" && RESULT_TYPES.includes(entry as never),\n )\n if (types.length > 0) flags.result_types = types\n }\n if (typeof raw.has_missing_results === \"boolean\")\n flags.has_missing_results = raw.has_missing_results\n return Object.keys(flags).length > 0 ? flags : null\n}\n\ntype AoeQuestion = {\n id: number\n required: boolean\n code: string\n value: string\n type: string\n sequence: number\n answers: Array<{ id: number; code: string; value: string }>\n constraint: unknown\n default: unknown\n}\n\nconst aoeQuestion = (\n state: JunctionState,\n markerId: number,\n questionId: number,\n): AoeQuestion | undefined => {\n for (const test of state.listLabTests()) {\n for (const marker of test.markers ?? []) {\n if (marker.id !== markerId) continue\n const aoe = marker.aoe as { questions?: AoeQuestion[] } | null | undefined\n if (!aoe) return undefined\n return aoe.questions?.find((question) => question.id === questionId) ?? undefined\n }\n }\n return undefined\n}\n\nfunction notFound(message: string): never {\n throw new HttpError(404, { detail: message })\n}\n\nconst queryInt = (context: OperationContext, name: string, fallback: number): number => {\n const raw = context.query[name]\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw))\n throw new HttpError(422, { detail: `${name} must be an integer` })\n return Number(raw)\n}\n\nconst MARKERS_DEFAULT_SIZE = 50\nconst MARKERS_MAX_SIZE = 100\n\nconst markersBoundsError = (name: string, value: string, bound: \"ge\" | \"le\", limit: number) => ({\n type: bound === \"ge\" ? \"greater_than_equal\" : \"less_than_equal\",\n loc: [\"query\", name],\n msg: `Input should be ${bound === \"ge\" ? \"greater than or equal to\" : \"less than or equal to\"} ${limit}`,\n input: value,\n ctx: bound === \"ge\" ? { ge: limit } : { le: limit },\n})\n\nconst parseMarkersInt = (raw: FormValue | undefined, name: string, fallback: number): number => {\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"int_parsing\",\n loc: [\"query\", name],\n msg: \"Input should be a valid integer, unable to parse string as an integer\",\n input: raw,\n },\n ],\n })\n }\n return Number(raw)\n}\n\n/**\n * Pagination mirrors the sandbox markers endpoints: `total` counts the returned page,\n * `pages` is ceil(overall/size) over the whole marker list, and page/size accept\n * 1..100 with 422s outside those bounds.\n */\nconst paginateMarkers = (\n query: OperationContext[\"query\"],\n markers: readonly Record<string, unknown>[],\n) => {\n const page = parseMarkersInt(query.page, \"page\", 1)\n const size = parseMarkersInt(query.size, \"size\", MARKERS_DEFAULT_SIZE)\n if (page < 1) {\n throw new HttpError(422, {\n detail: [markersBoundsError(\"page\", String(page), \"ge\", 1)],\n })\n }\n if (size < 1 || size > MARKERS_MAX_SIZE) {\n throw new HttpError(422, {\n detail: [\n markersBoundsError(\n \"size\",\n String(size),\n size < 1 ? \"ge\" : \"le\",\n size < 1 ? 1 : MARKERS_MAX_SIZE,\n ),\n ],\n })\n }\n const start = (page - 1) * size\n const pageMarkers = markers.slice(start, start + size)\n const pages = Math.ceil(markers.length / size)\n return {\n markers: pageMarkers,\n total: pageMarkers.length,\n page,\n size,\n pages,\n }\n}\n\nconst jsonObject = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\n/** Pydantic `str_strip_whitespace`: trim every string value before validation and use. */\nconst trimStrings = (value: unknown): unknown => {\n if (typeof value === \"string\") return value.trim()\n if (Array.isArray(value)) return value.map(trimStrings)\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) out[key] = trimStrings(entry)\n return out\n }\n return value\n}\n\nconst patientDetails = (input: Record<string, unknown>): Record<string, unknown> => ({\n ...input,\n dob:\n typeof input.dob === \"string\" && /^\\d{4}-\\d{2}-\\d{2}$/.test(input.dob)\n ? `${input.dob}T00:00:00+00:00`\n : input.dob,\n medical_proxy: null,\n race: null,\n ethnicity: null,\n sexual_orientation: null,\n gender_identity: null,\n})\n\nconst patientAddress = (input: Record<string, unknown>): Record<string, unknown> => ({\n ...input,\n second_line: null,\n access_notes: null,\n})\n\nconst missingError = (loc: Array<string | number>, input: unknown) => ({\n type: \"missing\",\n loc,\n msg: \"Field required\",\n input,\n})\n\nconst stringTypeError = (loc: string[], value: unknown) => ({\n type: \"string_type\",\n loc,\n msg: \"Input should be a valid string\",\n input: value,\n})\n\nconst stringTooShortError = (loc: string[], value: string) => ({\n type: \"string_too_short\",\n loc,\n msg: \"String should have at least 1 character\",\n input: value,\n ctx: { min_length: 1 },\n})\n\nconst patternError = (loc: string[], value: unknown, pattern: string) => ({\n type: \"string_pattern_mismatch\",\n loc,\n msg: `String should match pattern '${pattern}'`,\n input: value,\n ctx: { pattern },\n})\n\nconst stateError = (value: unknown) => ({\n type: \"value_error\",\n loc: [\"body\", \"patient_address\", \"state\"],\n msg: `Value error, Invalid state: ${value}`,\n input: value,\n ctx: { error: {} },\n})\n\nconst phoneError = (loc: string[], value: unknown) => ({\n type: \"value_error\",\n loc,\n msg: `Value error, Invalid phone number: ${value}`,\n input: value,\n ctx: { error: {} },\n})\n\nconst isUuid = (value: string): boolean =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n\nconst uuidError = (value: string, index?: number, loc?: string[]) => {\n const characters = Array.from(value)\n const invalidIndex = characters.findIndex((character) => !/^[0-9a-f-]$/i.test(character))\n const error =\n invalidIndex >= 0\n ? `invalid character: expected an optional prefix of \\`urn:uuid:\\` followed by [0-9a-fA-F-], found \\`${characters[invalidIndex]}\\` at ${invalidIndex + 1}`\n : `invalid length: expected length 32 for simple format, found ${value.replaceAll(\"-\", \"\").length}`\n return {\n type: \"uuid_parsing\",\n loc:\n loc ??\n (index === undefined\n ? [\"body\", \"lab_account_id\"]\n : [\"body\", \"order_set\", \"lab_test_ids\", index]),\n msg: `Input should be a valid UUID, ${error}`,\n input: value,\n ctx: { error },\n }\n}\n\n/** `GET /v3/lab_test/lab_account` query filters: Pydantic-shaped 422s, then exact match. */\nconst labAccountIdFilter = (context: OperationContext): string | null => {\n const raw = context.query.lab_account_id\n if (raw === undefined) return null\n if (typeof raw === \"string\" && isUuid(raw)) return raw\n throw new HttpError(422, {\n detail: [\n uuidError(typeof raw === \"string\" ? raw : String(raw), undefined, [\n \"query\",\n \"lab_account_id\",\n ]),\n ],\n })\n}\n\nconst labAccountStatusFilter = (context: OperationContext): LabAccountStatus | null => {\n const raw = context.query.status\n if (raw === undefined) return null\n if (typeof raw === \"string\" && LAB_ACCOUNT_STATUSES.includes(raw as LabAccountStatus)) {\n return raw as LabAccountStatus\n }\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"status\"],\n msg: \"Input should be 'active', 'pending', 'suspended' or 'ready_to_launch'\",\n input: raw,\n ctx: { expected: \"'active', 'pending', 'suspended' or 'ready_to_launch'\" },\n },\n ],\n })\n}\n\nconst enumError = (name: string, value: string, allowed: readonly string[]) => {\n const expected =\n allowed.length === 1\n ? `'${allowed[0]}'`\n : `${allowed\n .slice(0, -1)\n .map((entry) => `'${entry}'`)\n .join(\", \")} or '${allowed.at(-1)}'`\n return {\n type: \"enum\",\n loc: [\"query\", name],\n msg: `Input should be ${expected}`,\n input: value,\n ctx: { expected },\n }\n}\n\n/** A list query parameter: repeated (`?a=1&a=2`) or one JSON array, as the Vital SDK sends it. */\nconst listParam = (params: URLSearchParams, name: string): string[] | null => {\n const values = params.getAll(name)\n if (values.length === 0) return null\n if (values.length === 1 && values[0]?.trim().startsWith(\"[\")) {\n try {\n const parsed = JSON.parse(values[0]) as unknown\n if (Array.isArray(parsed)) return parsed.map(String)\n } catch {}\n }\n return values\n}\n\nconst LAB_TEST_FILTER_ENUMS: Readonly<Record<string, readonly string[]>> = {\n generation_method: [\"auto\", \"manual\", \"all\"],\n collection_method: [\"testkit\", \"walk_in_test\", \"at_home_phlebotomy\", \"on_site_collection\"],\n status: [\"active\", \"pending_approval\", \"inactive\"],\n order_key: [\"price\", \"created_at\", \"updated_at\"],\n order_direction: [\"asc\", \"desc\"],\n}\n\n/** `GET /v3/lab_tests` filters. Records carry no timestamps, so date keys keep catalog order. */\nconst filterLabTests = (tests: LabTestRecord[], params: URLSearchParams): LabTestRecord[] => {\n const errors: unknown[] = []\n const pick = (name: string): string | null => {\n const value = params.get(name)\n if (value === null) return null\n const allowed = LAB_TEST_FILTER_ENUMS[name]\n if (allowed && !allowed.includes(value)) errors.push(enumError(name, value, allowed))\n return value\n }\n const generation = pick(\"generation_method\") ?? \"manual\"\n const collection = pick(\"collection_method\")\n const status = pick(\"status\")\n const orderKey = pick(\"order_key\")\n const direction = pick(\"order_direction\") ?? \"asc\"\n const labSlug = params.get(\"lab_slug\")\n const name = params.get(\"name\")?.toLowerCase() ?? null\n const markerIds = listParam(params, \"marker_ids\")\n const providerIds = listParam(params, \"provider_ids\")\n for (const id of markerIds ?? []) {\n if (!/^-?\\d+$/.test(id))\n errors.push({\n type: \"int_parsing\",\n loc: [\"query\", \"marker_ids\", markerIds?.indexOf(id) ?? 0],\n msg: \"Input should be a valid integer, unable to parse string as an integer\",\n input: id,\n })\n }\n if (errors.length > 0) throw new HttpError(422, { detail: errors })\n const filtered = tests.filter((test) => {\n if (generation === \"manual\" && test.auto_generated === true) return false\n if (generation === \"auto\" && test.auto_generated !== true) return false\n if (collection !== null && test.method !== collection) return false\n if (status !== null && test.status !== status) return false\n if (labSlug !== null && String(test.lab?.slug ?? \"\") !== labSlug) return false\n if (name !== null && !test.name.toLowerCase().includes(name)) return false\n const markers = test.markers ?? []\n if (markerIds && !markerIds.every((id) => markers.some((m) => String(m.id) === id)))\n return false\n if (\n providerIds &&\n !providerIds.every((id) => markers.some((m) => String(m.provider_id ?? \"\") === id))\n )\n return false\n return true\n })\n const ordered =\n orderKey === \"price\" ? [...filtered].sort((a, b) => (a.price ?? 0) - (b.price ?? 0)) : filtered\n return direction === \"desc\" ? [...ordered].reverse() : ordered\n}\n\nconst isValidPhone = (value: string): boolean => {\n const digits = value.replace(/\\D/g, \"\")\n if (digits.length < 10 || digits.length > 15) return false\n if (/[a-zA-Z]/.test(value)) return false\n if (digits.length === 10 || digits.length === 11) {\n const area = digits.length === 11 ? digits.slice(1, 4) : digits.slice(0, 3)\n if (area[0] === \"0\" || area[0] === \"1\") return false\n }\n return true\n}\n\nconst isValidName = (value: string): boolean => {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$/.test(value)) return false\n if (/\\s\\s/.test(value)) return false\n return true\n}\n\nconst nameError = (field: string, value: unknown) => ({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", field],\n msg: \"Value error, The field must start with a letter (a-z or A-Z or 0-9) and can only contain -,. special characters, but cannot start with a space or hyphen.\",\n input: value,\n ctx: { error: {} },\n})\n\nconst pyIso = (value: string): string => {\n const d = new Date(value)\n const iso = d.toISOString()\n const [date, time = \"\"] = iso.split(\"T\")\n const match = time.match(/\\.(\\d+)Z$/)\n const ms = (match?.[1] ?? \"000\").padEnd(6, \"0\")\n return `${date}T${time.slice(0, 8)}.${ms}+00:00`\n}\n\nconst orderValidation = (\n body: Record<string, unknown>,\n now: () => number = Date.now,\n): unknown[] => {\n const errors: unknown[] = []\n const userId = body.user_id\n if (userId === undefined) errors.push(missingError([\"body\", \"user_id\"], body))\n else if (typeof userId !== \"string\") errors.push(stringTypeError([\"body\", \"user_id\"], userId))\n else if (!isUuid(userId)) errors.push(uuidError(userId))\n const labAccountId = body.lab_account_id\n if (typeof labAccountId === \"string\" && labAccountId.trim().length === 0) {\n errors.push({\n type: \"string_too_short\",\n loc: [\"body\", \"lab_account_id\"],\n msg: \"String should have at least 1 character\",\n input: labAccountId,\n })\n }\n const labTestId = body.lab_test_id\n if (labTestId !== undefined && labTestId !== null) {\n if (typeof labTestId !== \"string\")\n errors.push(stringTypeError([\"body\", \"lab_test_id\"], labTestId))\n else if (!isUuid(labTestId))\n errors.push(uuidError(labTestId, undefined, [\"body\", \"lab_test_id\"]))\n }\n const os = body.order_set\n const osWrongType =\n os !== undefined && (typeof os !== \"object\" || os === null || Array.isArray(os))\n if (osWrongType) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"order_set\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: os,\n })\n } else if (os !== undefined) {\n const o = os as Record<string, unknown>\n const ids = o.lab_test_ids\n if (ids === undefined) errors.push(missingError([\"body\", \"order_set\", \"lab_test_ids\"], o))\n else if (!Array.isArray(ids)) {\n errors.push({\n type: \"list_type\",\n loc: [\"body\", \"order_set\", \"lab_test_ids\"],\n msg: \"Input should be a valid list\",\n input: ids,\n })\n } else {\n ids.forEach((id, index) => {\n if (typeof id !== \"string\" || !isUuid(id)) errors.push(uuidError(String(id), index))\n })\n }\n }\n const pd = body.patient_details\n if (pd === undefined) {\n errors.push(missingError([\"body\", \"patient_details\"], body))\n } else if (typeof pd !== \"object\" || pd === null || Array.isArray(pd)) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"patient_details\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: pd,\n })\n } else {\n const p = pd as Record<string, unknown>\n for (const field of [\"first_name\", \"last_name\", \"dob\", \"gender\", \"phone_number\", \"email\"]) {\n if (p[field] === undefined) errors.push(missingError([\"body\", \"patient_details\", field], p))\n else if (field === \"gender\" && p[field] === null) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"gender\"],\n msg: \"Value error, gender cannot be None.\",\n input: null,\n ctx: { error: {} },\n })\n } else if (field === \"phone_number\" && p[field] === null) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"phone_number\"],\n msg: \"Value error, Phone number cannot be None\",\n input: null,\n ctx: { error: {} },\n })\n } else if (field === \"dob\" && typeof p[field] === \"number\") {\n const asSeconds = Math.abs(p[field] as number) < 1e12\n const normalized = new Date((p[field] as number) * (asSeconds ? 1000 : 1))\n .toISOString()\n .replace(/\\.\\d{3}Z$/, \"+00:00\")\n .replace(/Z$/, \"+00:00\")\n errors.push({\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: normalized,\n })\n } else if (field === \"dob\" && (p[field] === null || typeof p[field] === \"object\")) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, date of birth is not specified.\",\n input: p[field],\n ctx: { error: {} },\n })\n } else if (typeof p[field] !== \"string\")\n errors.push(stringTypeError([\"body\", \"patient_details\", field], p[field]))\n else if (\n (field === \"first_name\" || field === \"last_name\") &&\n typeof p[field] === \"string\" &&\n p[field].length === 0\n )\n errors.push(stringTooShortError([\"body\", \"patient_details\", field], p[field]))\n else if (\n (field === \"first_name\" || field === \"last_name\") &&\n !isValidName(p[field] as string)\n )\n errors.push(nameError(field, p[field]))\n else if (field === \"email\") {\n const emailError = userEmailError(p[field] as string)\n if (emailError) errors.push(emailError)\n } else if (field === \"dob\") {\n const dobError = orderDobError(p[field] as string, now())\n if (dobError) errors.push(dobError)\n } else if (field === \"phone_number\" && !isValidPhone(p[field] as string)) {\n errors.push(phoneError([\"body\", \"patient_details\", \"phone_number\"], p[field]))\n }\n }\n }\n const pa = body.patient_address\n if (pa === undefined) {\n errors.push(missingError([\"body\", \"patient_address\"], body))\n } else if (typeof pa !== \"object\" || pa === null || Array.isArray(pa)) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"patient_address\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: pa,\n })\n } else {\n const a = pa as Record<string, unknown>\n for (const field of [\"first_line\", \"city\", \"state\", \"zip\", \"country\"]) {\n if (a[field] === undefined) errors.push(missingError([\"body\", \"patient_address\", field], a))\n else if (typeof a[field] !== \"string\")\n errors.push(stringTypeError([\"body\", \"patient_address\", field], a[field]))\n }\n if (typeof a.state === \"string\" && !/^[A-Z]{2}$/.test(a.state)) {\n errors.push(stateError(a.state))\n }\n if (typeof a.zip === \"string\" && !/^\\d{5}(-\\d{4})?$/.test(a.zip)) {\n errors.push(patternError([\"body\", \"patient_address\", \"zip\"], a.zip, \"^\\\\d{5}(-\\\\d{4})?$\"))\n }\n if (typeof a.phone_number === \"string\" && !isValidPhone(a.phone_number)) {\n errors.push(phoneError([\"body\", \"patient_address\", \"phone_number\"], a.phone_number))\n }\n }\n return errors\n}\n\n/** Sandbox email validation for `patient_details.email` (only the missing-@ sign case is reachable here). */\nconst userEmailError = (value: string) => {\n if (!value.includes(\"@\")) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"email\"],\n msg: \"value is not a valid email address: An email address must have an @-sign.\",\n input: value,\n ctx: { reason: \"An email address must have an @-sign.\" },\n }\n }\n return undefined\n}\n\n/**\n * Sandbox dob validation for create_order: many string formats are accepted\n * (`1990-01-01`, `1990-01`, `1990/01/01`, `19900101`, ...); exact zero-time datetimes are\n * accepted, non-zero times produce `date_from_datetime_inexact` with a normalized input,\n * and unmatchable strings produce the \"Could not match\" value error.\n */\nconst orderDobError = (dob: string, nowMs: number) => {\n if (/^\\d{4}-\\d{2}-\\d{2}T/.test(dob)) {\n if (/^\\d{4}-\\d{2}-\\d{2}T00:00:00/.test(dob)) {\n const dateOnly = dob.slice(0, 10)\n if (new Date(`${dateOnly}T00:00:00Z`).getTime() > nowMs) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, dob cannot be in the future\",\n input: `${dateOnly}T00:00:00+00:00`,\n ctx: { error: {} },\n }\n }\n return undefined\n }\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: pyIso(dob),\n }\n }\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(dob)) {\n const [year = \"0\", month = \"0\", day = \"0\"] = dob.split(\"-\")\n const monthNumber = Number(month)\n const dayNumber = Number(day)\n if (monthNumber < 1 || monthNumber > 12) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: `Value error, month must be in 1..12, not ${monthNumber}`,\n input: dob,\n ctx: { error: {} },\n }\n }\n const daysInMonth = new Date(Date.UTC(Number(year), monthNumber, 0)).getUTCDate()\n if (dayNumber < 1 || dayNumber > daysInMonth) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: `Value error, day ${dayNumber} must be in range 1..${daysInMonth} for month ${monthNumber} in year ${year}`,\n input: dob,\n ctx: { error: {} },\n }\n }\n if (new Date(`${dob}T00:00:00Z`).getTime() > nowMs) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, dob cannot be in the future\",\n input: `${dob}T00:00:00+00:00`,\n ctx: { error: {} },\n }\n }\n return undefined\n }\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg:\n \"Value error, Could not match input '\" +\n dob +\n \"' to any of the following formats: YYYY-MM-DD, YYYY-M-DD, YYYY-M-D, YYYY/MM/DD, YYYY/M/DD, YYYY/M/D, YYYY.MM.DD, YYYY.M.DD, YYYY.M.D, YYYYMMDD, YYYY-DDDD, YYYYDDDD, YYYY-MM, YYYY/MM, YYYY.MM, YYYY, W.\",\n input: dob,\n ctx: { error: {} },\n }\n}\n\nconst aoeValidationError = (\n state: JunctionState,\n body: Record<string, unknown>,\n): string | undefined => {\n const answers = body.aoe_answers\n if (!Array.isArray(answers)) return undefined\n for (const answer of answers) {\n if (typeof answer !== \"object\" || answer === null || Array.isArray(answer)) continue\n const record = answer as Record<string, unknown>\n if (typeof record.marker_id !== \"number\") continue\n const marker = state\n .listLabTests()\n .flatMap((test) => test.markers ?? [])\n .find((entry) => entry.id === record.marker_id)\n if (!marker?.aoe) return `Marker id ${record.marker_id} does not have AOE.`\n const question = aoeQuestion(state, record.marker_id, record.question_id as number)\n if (!question)\n return `Invalid question_id ${String(record.question_id)} for marker id ${record.marker_id}.`\n const answerCode = typeof record.answer === \"string\" ? record.answer.toUpperCase() : \"\"\n if (!question.answers.some((entry) => entry.code === answerCode))\n return `Invalid answer ${answerCode} for question ${question.value}.`\n }\n return undefined\n}\n\nconst METHOD_DETAILS = (method: string, id: string, at: string) => {\n switch (method) {\n case \"testkit\":\n return {\n type: \"testkit\",\n data: { id, shipment: null, created_at: at, updated_at: at },\n }\n case \"walk_in_test\":\n case \"on_site_collection\":\n return {\n type: method,\n data: { id, appointment_id: null, created_at: at, updated_at: at },\n }\n default:\n return {\n type: method,\n data: { id, appointment_id: null, created_at: at, updated_at: at },\n }\n }\n}\n\nconst PHYSICIAN = { first_name: \"Leo\", last_name: \"Damasco\", npi: \"1134326366\" }\n\n/** Sandbox Labcorp rejects these patient states (`Lab Labcorp does not support state XX`). */\nconst LAB_UNSUPPORTED_STATES: Readonly<Record<string, readonly string[]>> = {\n labcorp: [\"NY\", \"NJ\", \"RI\"],\n}\n\n/** Low-level events that Junction allows transitioning to `cancelled.*.cancelled`. */\nconst CANCELLABLE_ORDER_EVENTS = new Set([\n \"received.walk_in_test.ordered\",\n \"received.walk_in_test.requisition_created\",\n \"received.walk_in_test.requisition_bypassed\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"collecting_sample.walk_in_test.appointment_cancelled\",\n \"collecting_sample.walk_in_test.appointment_pending\",\n \"received.at_home_phlebotomy.ordered\",\n \"received.at_home_phlebotomy.requisition_created\",\n \"received.at_home_phlebotomy.requisition_bypassed\",\n \"collecting_sample.at_home_phlebotomy.appointment_pending\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n \"collecting_sample.at_home_phlebotomy.draw_completed\",\n \"received.testkit.ordered\",\n \"received.testkit.awaiting_registration\",\n \"received.testkit.requisition_created\",\n \"received.testkit.requisition_bypassed\",\n \"received.testkit.testkit_registered\",\n \"received.on_site_collection.ordered\",\n \"received.on_site_collection.requisition_created\",\n \"received.on_site_collection.requisition_bypassed\",\n \"collecting_sample.on_site_collection.draw_completed\",\n])\n\nconst labStateSupportError = (\n labTest: { lab?: Record<string, unknown> | null },\n state: unknown,\n): string | undefined => {\n if (typeof state !== \"string\" || state.length === 0) return undefined\n const lab = labTest.lab\n if (!lab || typeof lab !== \"object\") return undefined\n const slug = typeof lab.slug === \"string\" ? lab.slug.toLowerCase() : \"\"\n const name = typeof lab.name === \"string\" ? lab.name : \"Lab\"\n const unsupported = LAB_UNSUPPORTED_STATES[slug]\n if (!unsupported) return undefined\n const normalized = state.trim().toUpperCase()\n if (!unsupported.includes(normalized)) return undefined\n return `Lab ${name} does not support state ${normalized}`\n}\nconst FINAL_STATUSES = [\n \"received.walk_in_test.ordered\",\n \"received.walk_in_test.requisition_created\",\n \"received.walk_in_test.requisition_bypassed\",\n \"completed.walk_in_test.completed\",\n \"sample_with_lab.walk_in_test.partial_results\",\n \"failed.walk_in_test.sample_error\",\n \"cancelled.walk_in_test.cancelled\",\n \"collecting_sample.walk_in_test.appointment_pending\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"collecting_sample.walk_in_test.appointment_cancelled\",\n \"collecting_sample.walk_in_test.redraw_available\",\n \"received.at_home_phlebotomy.ordered\",\n \"received.at_home_phlebotomy.requisition_created\",\n \"received.at_home_phlebotomy.requisition_bypassed\",\n \"collecting_sample.at_home_phlebotomy.appointment_pending\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"collecting_sample.at_home_phlebotomy.draw_completed\",\n \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n \"completed.at_home_phlebotomy.completed\",\n \"sample_with_lab.at_home_phlebotomy.partial_results\",\n \"cancelled.at_home_phlebotomy.cancelled\",\n \"failed.at_home_phlebotomy.sample_error\",\n \"received.testkit.ordered\",\n \"received.testkit.awaiting_registration\",\n \"received.testkit.requisition_created\",\n \"received.testkit.requisition_bypassed\",\n \"received.testkit.registered\",\n \"collecting_sample.testkit.transit_customer\",\n \"collecting_sample.testkit.out_for_delivery\",\n \"collecting_sample.testkit.with_customer\",\n \"collecting_sample.testkit.transit_lab\",\n \"sample_with_lab.testkit.delivered_to_lab\",\n \"sample_with_lab.testkit.lab_processing_blocked\",\n \"completed.testkit.completed\",\n \"failed.testkit.failure_to_deliver_to_customer\",\n \"failed.testkit.failure_to_deliver_to_lab\",\n \"failed.testkit.sample_error\",\n \"failed.testkit.lost\",\n \"cancelled.testkit.cancelled\",\n \"cancelled.testkit.do_not_process\",\n \"collecting_sample.testkit.problem_in_transit_customer\",\n \"collecting_sample.testkit.problem_in_transit_lab\",\n \"received.on_site_collection.ordered\",\n \"received.on_site_collection.requisition_created\",\n \"received.on_site_collection.requisition_bypassed\",\n \"sample_with_lab.on_site_collection.draw_completed\",\n \"completed.on_site_collection.completed\",\n \"cancelled.on_site_collection.cancelled\",\n \"sample_with_lab.on_site_collection.partial_results\",\n \"failed.on_site_collection.sample_error\",\n \"completed.walk_in_test.corrected\",\n \"completed.at_home_phlebotomy.corrected\",\n \"completed.on_site_collection.corrected\",\n \"completed.testkit.corrected\",\n] as const\n\nconst finalStatusError = (value: string) => ({\n type: \"enum\",\n loc: [\"query\", \"final_status\"],\n msg: `Input should be ${FINAL_STATUSES.map((status) => `'${status}'`)\n .join(\", \")\n .replace(/, ([^,]*)$/, \" or $1\")}`,\n input: value,\n ctx: { expected: FINAL_STATUSES.map((status) => `'${status}'`).join(\", \") },\n})\n\nexport const orderHandlers = (state: JunctionState) => ({\n get_paginated_lab_tests_for_team_v3_lab_test_get: async () =>\n jsonRes(200, {\n data: state.listLabTests().filter((test) => test.auto_generated !== true),\n next_cursor: null,\n }),\n\n // Deprecated upstream but still what team-catalog readers call: the same records as the\n // paged `/v3/lab_test`, as a bare array, filtered the way the real endpoint documents.\n get_lab_tests_for_team_v3_lab_tests_get: async (context: OperationContext) =>\n jsonRes(200, filterLabTests(state.listLabTests(), context.url.searchParams)),\n\n get_lab_test_for_team_v3_lab_tests__lab_test_id__get: async (context: OperationContext) => {\n const id = context.params.lab_test_id ?? \"\"\n const test = state.labTestById(id)\n if (!test) notFound(\"Lab test does not exist\")\n return jsonRes(200, test)\n },\n\n get_labs_v3_lab_tests_labs_get: async () => jsonRes(200, state.listLabs()),\n\n get_team_lab_accounts_v3_lab_test_lab_account_get: async (context: OperationContext) => {\n const requestedId = labAccountIdFilter(context)\n const status = labAccountStatusFilter(context)\n const data = state\n .listLabAccounts()\n .filter((entry) => isLinkedToTeam(entry, state.teamId))\n .filter((entry) => requestedId === null || entry.id === requestedId)\n .filter((entry) => status === null || entry.status === status)\n .map(renderLabAccount)\n return jsonRes(200, { data })\n },\n\n get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.lab_test_id ?? \"\"\n const test = state.labTestById(id)\n if (!test) notFound(\"Lab test does not exist\")\n const expected = state.expectedResultsFor(id)\n const markers = (test.markers ?? []).map((marker) => ({\n ...marker,\n expected_results: expected,\n }))\n return jsonRes(200, paginateMarkers(context.query, markers))\n },\n\n list_order_set_markers_v3_lab_tests_list_order_set_markers_post: async (\n context: OperationContext,\n ) => {\n const body = jsonObject(context)\n const orderSetId = body.order_set_id\n if (typeof orderSetId !== \"string\" || !isUuid(orderSetId)) {\n throw new HttpError(422, {\n detail: [uuidError(String(orderSetId ?? \"\"), 0, [\"body\", \"order_set_id\"])],\n })\n }\n const binding = state.orderByTransaction.get(orderSetId)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order set not found\")\n const providerId = typeof body.provider_id === \"string\" ? body.provider_id : null\n const markers = (order.lab_test.markers ?? [])\n .filter((marker) => providerId === null || marker.provider_id === providerId)\n .map((marker) => ({\n ...marker,\n expected_results: state.expectedResultsFor(order.lab_test.id),\n }))\n return jsonRes(200, paginateMarkers(context.query, markers))\n },\n\n create_order_v3_order_post: async (context: OperationContext) => {\n const rawBody = jsonObject(context)\n const body = trimStrings(rawBody) as Record<string, unknown>\n body.aoe_answers = rawBody.aoe_answers\n const patient = rawBody.patient_details\n if (typeof patient === \"object\" && patient !== null && !Array.isArray(patient)) {\n const details = patient as Record<string, unknown>\n const crashes = Object.entries(details).some(([key, value]) => {\n if (\n (key === \"first_name\" || key === \"last_name\") &&\n (typeof value === \"number\" || typeof value === \"boolean\")\n )\n return true\n if (key === \"gender\" && value !== null && typeof value !== \"string\") return true\n if (key === \"phone_number\" && value !== null && typeof value !== \"string\") return true\n if (key === \"dob\" && typeof value === \"boolean\") return true\n return false\n })\n if (crashes) {\n return new Response(\"Internal Server Error\", {\n status: 500,\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n })\n }\n }\n const errors = orderValidation(body, context.now)\n if (errors.length > 0) throw new HttpError(422, { detail: errors })\n const rawAddress = body.patient_address\n if (\n typeof rawAddress === \"object\" &&\n rawAddress !== null &&\n !Array.isArray(rawAddress) &&\n typeof (rawAddress as Record<string, unknown>).country === \"string\" &&\n /[^A-Za-z ]/.test((rawAddress as Record<string, string>).country ?? \"\")\n ) {\n return new Response(\"Internal Server Error\", {\n status: 500,\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n })\n }\n const userId = body.user_id\n if (typeof userId !== \"string\") throw new HttpError(422, { detail: \"user_id must be a string\" })\n requireUser(state, userId, context)\n const phone = (body.patient_details as Record<string, unknown> | undefined)?.phone_number\n if (typeof phone === \"string\" && /^\\+1\\d{10}$/.test(phone) && phone.slice(2, 5) === \"555\") {\n throw new HttpError(400, { detail: \"Phone number is not correct\" })\n }\n if (body.collection_method === \"testkit\")\n throw new HttpError(400, { detail: \"Cannot set collection_method to TESTKIT\" })\n const aoeError = aoeValidationError(state, body)\n if (aoeError) throw new HttpError(400, { detail: aoeError })\n const rawOrderSet = body.order_set\n // `lab_test_id` is the deprecated single-test form: it stands for an order set of one\n // test, and `order_set` wins when both are sent.\n const singleLabTestId = typeof body.lab_test_id === \"string\" ? body.lab_test_id : undefined\n if (rawOrderSet === undefined && singleLabTestId === undefined) {\n throw new HttpError(400, { detail: \"Either lab_test_id or order_set must be set\" })\n }\n if (\n typeof rawOrderSet === \"object\" &&\n rawOrderSet !== null &&\n !Array.isArray(rawOrderSet) &&\n (rawOrderSet as Record<string, unknown>).lab_test_ids === undefined &&\n (rawOrderSet as Record<string, unknown>).add_on === undefined\n ) {\n throw new HttpError(400, { detail: \"lab_test_ids or add_on must be set in order_set\" })\n }\n const details = body.patient_details as Record<string, unknown>\n const address = body.patient_address as Record<string, unknown>\n const orderSetIds =\n typeof rawOrderSet === \"object\" && rawOrderSet !== null\n ? (rawOrderSet as Record<string, unknown>).lab_test_ids\n : undefined\n const labTestIds = Array.isArray(orderSetIds)\n ? (orderSetIds as unknown[])\n : rawOrderSet === undefined && singleLabTestId !== undefined\n ? [singleLabTestId]\n : []\n // Vital: empty lab_test_ids \u2192 \"No markers found\u2026\"; unknown id \u2192 \"Test does not exist\";\n // known panels with markers:null (e.g. Female General Wellness) still create successfully.\n if (labTestIds.length === 0) {\n throw new HttpError(400, {\n detail: \"No markers found for the supplied lab tests. Please check the lab test ids\",\n })\n }\n const resolved = labTestIds.map((id) =>\n typeof id === \"string\" ? state.labTestById(id) : undefined,\n )\n if (resolved.some((test) => test === undefined)) {\n throw new HttpError(400, { detail: \"Test does not exist\" })\n }\n const labTests = resolved as NonNullable<(typeof resolved)[number]>[]\n const methods = new Set(\n labTests.map((test) =>\n typeof test.method === \"string\" && test.method.length > 0 ? test.method : \"\",\n ),\n )\n if (methods.size > 1) {\n throw new HttpError(400, {\n detail: \"Cannot order with lab tests with multiple collection methods\",\n })\n }\n const labTest = labTests[0]\n if (!labTest) throw new HttpError(400, { detail: \"Test does not exist\" })\n\n const stateError = labStateSupportError(labTest, address.state)\n if (stateError) throw new HttpError(400, { detail: stateError })\n\n // Lab-account routing: the account must be active, linked to the team and associated\n // with the ordered lab; with no explicit id, linked accounts decide the branch.\n const labSlug = typeof labTest.lab?.slug === \"string\" ? labTest.lab.slug.toLowerCase() : \"\"\n const labAccount = selectLabAccount(\n labSlug,\n typeof body.lab_account_id === \"string\" ? body.lab_account_id : null,\n state.teamId,\n state.listLabAccounts(),\n )\n const requestedBilling =\n typeof body.billing_type === \"string\" && body.billing_type !== \"\"\n ? body.billing_type\n : undefined\n const billingType = requestedBilling ?? state.defaultBillingTypes[labSlug] ?? \"client_bill\"\n const allowedStates = effectiveBilling(labAccount)[billingType]\n if (!allowedStates)\n throw new HttpError(400, {\n // An omitted billing_type that resolves to one the account lacks is reported against\n // the lab, as the sandbox words it.\n detail:\n requestedBilling === undefined\n ? `Lab ${String(labTest.lab?.id ?? labSlug)} does not support billing type ${billingType}`\n : `Billing type ${billingType} is not supported by the lab account used for this order`,\n })\n const patientState = String(address.state ?? \"\")\n .trim()\n .toUpperCase()\n if (patientState !== \"\" && !allowedStates.includes(patientState))\n throw new HttpError(400, {\n detail: `Billing type ${billingType} is not available in state ${patientState} for the lab account used for this order`,\n })\n const icdCodes = Array.isArray(body.icd_codes) ? ([...body.icd_codes] as string[]) : null\n if (billingType === \"commercial_insurance\" && (icdCodes === null || icdCodes.length === 0))\n throw new HttpError(400, {\n detail: \"Commercial insurance orders require at least one ICD code in icd_codes\",\n })\n\n const orderId = state.nextOrderId()\n const method =\n typeof body.collection_method === \"string\" ? body.collection_method : labTest.method\n // Sandbox: same collection_method as the panel \u2192 embed the panel as-is (even when\n // markers are null). Different method requires markers to synthesize auto_generated.\n const nativeMethod =\n typeof labTest.method === \"string\" && labTest.method.length > 0 ? labTest.method : method\n const markerCount = labTests.reduce((sum, test) => sum + (test.markers?.length ?? 0), 0)\n if (method !== nativeMethod && markerCount === 0) {\n throw new HttpError(400, {\n detail: \"No markers found for the supplied lab tests. Please check the lab test ids\",\n })\n }\n const idempotencyKey = body.idempotency_key\n const requestFingerprint = JSON.stringify(body)\n if (typeof idempotencyKey === \"string\" && idempotencyKey.length > 0) {\n const replay = state.orderIdempotency.get(idempotencyKey)\n if (replay) {\n if (replay.fingerprint !== requestFingerprint)\n throw new HttpError(400, {\n detail: \"Idempotency key was reused with a different request\",\n })\n return jsonRes(200, replay.response)\n }\n }\n const order = buildOrderRecord(\n state,\n {\n orderId,\n userId,\n labTest,\n method,\n patientDetails: details,\n patientAddress: address,\n billingType,\n icdCodes,\n clinicalNotes: typeof body.clinical_notes === \"string\" ? body.clinical_notes : null,\n passthrough: typeof body.passthrough === \"string\" ? body.passthrough : null,\n },\n context.now,\n )\n persistOrderRecord(state, order, labTest, details, address)\n state.orderLabAccounts.insert(orderId, {\n lab_account_id: labAccount === \"platform\" ? null : labAccount.id,\n })\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n const response = {\n order: responseOrder,\n status: \"success\",\n message: \"Order created successfully\",\n }\n if (typeof idempotencyKey === \"string\" && idempotencyKey.length > 0)\n state.orderIdempotency.insert(idempotencyKey, {\n order_id: orderId,\n response,\n fingerprint: requestFingerprint,\n })\n state.publishOrderWebhook(order, \"labtest.order.created\", context.now())\n return jsonRes(200, response)\n },\n\n cancel_order_v3_order__order_id__cancel_post: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n const order = state.orders.get(id) ?? orderMissing(state, context.operation.operationId, id)\n const alreadyCancelled = order.events.some(\n (entry) => typeof entry.status === \"string\" && entry.status.startsWith(\"cancelled.\"),\n )\n if (alreadyCancelled) {\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n return jsonRes(200, {\n order: responseOrder,\n status: \"success\",\n message: \"order already cancelled\",\n })\n }\n const lastEvent = order.last_event ?? order.events[order.events.length - 1]\n const lowLevel = typeof lastEvent?.status === \"string\" ? lastEvent.status : \"\"\n if (!CANCELLABLE_ORDER_EVENTS.has(lowLevel)) {\n throw new HttpError(400, {\n detail:\n \"This order is not in a Cancellable Status. Refer to the documentation to check the order lifecycle (https://docs.tryvital.io/lab/workflow/lab-test-lifecycle).\",\n })\n }\n const now = state.isoNow(context.now)\n const method =\n typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type.length > 0\n ? order.details.type\n : \"at_home_phlebotomy\"\n order.status = \"cancelled\"\n order.updated_at = now\n const event = {\n id: order.events.length + 1,\n created_at: now,\n status: `cancelled.${method}.cancelled`,\n status_detail: null,\n }\n order.events.push(event)\n order.last_event = event\n order.order_transaction.status = \"cancelled\"\n const transactionOrder = order.order_transaction.orders[0]\n if (transactionOrder) {\n transactionOrder.low_level_status = \"cancelled\"\n transactionOrder.updated_at = new Date(context.now()).toISOString()\n }\n state.orders.update(id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n // Junction auto-cancels mobile phlebotomy appointments on order cancel, but\n // leaves walk-in PSC appointments alone (patient may already be en route).\n if (method === \"at_home_phlebotomy\") {\n cascadeCancelAppointments(state, id, context.now())\n }\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n const response = {\n order: responseOrder,\n status: \"success\",\n message: \"order cancelled\",\n }\n return jsonRes(200, response)\n },\n\n simulate_order_v3_order__order_id__test_post: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n const finalStatus = context.query.final_status\n if (!isUuid(id))\n throw new HttpError(422, { detail: [uuidError(id, undefined, [\"path\", \"order_id\"])] })\n if (\n finalStatus !== undefined &&\n (typeof finalStatus !== \"string\" ||\n !FINAL_STATUSES.includes(finalStatus as (typeof FINAL_STATUSES)[number]))\n )\n throw new HttpError(422, { detail: [finalStatusError(String(finalStatus ?? \"\"))] })\n const delayRaw = context.query.delay\n let delaySeconds = 0\n if (delayRaw !== undefined) {\n if (typeof delayRaw !== \"string\" || !/^\\d+$/.test(delayRaw))\n throw new HttpError(422, { detail: \"delay must be a non-negative integer\" })\n delaySeconds = Number(delayRaw)\n }\n const body = context.body\n if (body.kind === \"json\") {\n const value = body.value\n if (typeof value !== \"object\" || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n }\n const order = state.orders.get(id) ?? orderMissing(state, context.operation.operationId, id)\n checkSimulateAllowed(state.limits, context.request.headers.get(\"x-vital-api-key\"))\n if (\n typeof finalStatus !== \"string\" ||\n !FINAL_STATUSES.includes(finalStatus as (typeof FINAL_STATUSES)[number])\n )\n throw new HttpError(422, { detail: [finalStatusError(String(finalStatus ?? \"\"))] })\n const flags = simulationFlagsOf(context)\n if (delaySeconds > 0) {\n state.queueSimulateTransition({\n order_id: id,\n due_at: context.now() + delaySeconds * 1000,\n final_status: finalStatus,\n flags,\n })\n return jsonRes(200, \"Success\")\n }\n applySimulateTransition(state, order, finalStatus, flags, context)\n return jsonRes(200, \"Success\")\n },\n\n get_order_v3_order__order_id__get: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n if (!state.orders.has(id)) orderMissing(state, context.operation.operationId, id)\n state.applyDueSimulateTransitions(context.now(), (due, finalStatus, flags) => {\n applySimulateTransition(state, due, finalStatus, flags, context)\n })\n const fresh = state.orders.get(id) ?? orderMissing(state, context.operation.operationId, id)\n const body = { ...fresh } as Record<string, unknown>\n if (body.result_types === null) delete body.result_types\n return jsonRes(200, body)\n },\n\n get_orders_v3_orders_get: async (context: OperationContext) => {\n const page = queryInt(context, \"page\", 1)\n const size = queryInt(context, \"size\", 50)\n if (page < 1 || size < 1 || size > 100)\n throw new HttpError(422, { detail: \"page must be >= 1 and size must be 1..100\" })\n const userId = context.query.user_id\n if (userId !== undefined && typeof userId !== \"string\")\n throw new HttpError(422, { detail: \"user_id must be a string\" })\n if (userId !== undefined) requireUser(state, userId, context)\n let all = state.orders.list({ order: \"oldest\" })\n if (userId !== undefined) all = all.filter((entry) => entry.value.user_id === userId)\n // Sandbox lists by updated_at desc (not created_at) \u2014 wrong order breaks\n // seedParity identity pairing on list pages, which then poisons get_order.\n all = [...all].sort((left, right) => {\n const leftAt = Date.parse(String(left.value.updated_at ?? left.value.created_at ?? \"\")) || 0\n const rightAt =\n Date.parse(String(right.value.updated_at ?? right.value.created_at ?? \"\")) || 0\n if (rightAt !== leftAt) return rightAt - leftAt\n // Frozen clocks make updated_at ties common; seq matches sandbox insertion order.\n return right.seq - left.seq\n })\n const pageItems = all.slice((page - 1) * size, page * size)\n return jsonRes(200, {\n orders: pageItems.map((entry) => {\n const order = { ...entry.value } as Record<string, unknown>\n if (order.result_types === null) delete order.result_types\n return order\n }),\n total: all.length,\n page,\n size,\n })\n },\n\n get_order_transaction_v3_order_transaction__transaction_id__get: async (\n context: OperationContext,\n ) => {\n const id = context.params.transaction_id ?? \"\"\n const binding = state.orderByTransaction.get(id)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order transaction not found\")\n return jsonRes(200, {\n id,\n team_id: state.teamId,\n status: order.order_transaction.status,\n orders: [orderSummary(order)],\n })\n },\n\n get_order_transaction_result_v3_order_transaction__transaction_id__result_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.transaction_id ?? \"\"\n const binding = state.orderByTransaction.get(id)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order transaction not found\")\n const user = order.user_id ? state.users.get(order.user_id) : undefined\n return jsonRes(200, {\n metadata: {\n age: \"41\",\n dob: \"1983-06-23\",\n patient: user?.client_user_id ?? order.user_id,\n date_reported: \"2024-11-02\",\n specimen_number: opaqueToken(`junction:specimen:${order.id}`, 24),\n status: \"final\",\n laboratory: \"Mockingbird Central Lab\",\n provider: null,\n interpretation: null,\n patient_id: null,\n account_id: null,\n date_collected: null,\n date_received: null,\n \"clia_#\": null,\n },\n results: biomarker(order, order.created_at),\n missing_results: null,\n sample_information: null,\n order_transaction: order.order_transaction,\n })\n },\n})\n\n/** What an order is built from, once the request (or an admin fixture) has been validated. */\nexport type OrderDraft = {\n orderId: string\n userId: string\n /** The catalog lab test ordered; embedded as-is when `method` is its native method. */\n labTest: LabTestRecord\n method: string\n patientDetails: Record<string, unknown>\n patientAddress: Record<string, unknown>\n billingType: string\n icdCodes: string[] | null\n clinicalNotes: string | null\n passthrough: string | null\n}\n\n/** The order record `create_order` stores, in its initial `received.<method>.ordered` state. */\nexport const buildOrderRecord = (\n state: JunctionState,\n draft: OrderDraft,\n now: () => number,\n): OrderRecord => {\n const { orderId, userId, labTest, method, billingType, icdCodes } = draft\n const details = draft.patientDetails\n const nowIso = state.isoNow(now)\n const nowMicro = new Date(now()).toISOString()\n const transactionId = state.transactionIdFor(orderId)\n const nativeMethod =\n typeof labTest.method === \"string\" && labTest.method.length > 0 ? labTest.method : method\n const eventStatus = `received.${method}.ordered`\n const eventId =\n Number.parseInt(opaqueToken(`junction:order-event:${orderId}`, 8), 16) % 1_000_000_000 || 1\n const event = {\n id: eventId,\n created_at: nowIso,\n status: eventStatus,\n status_detail: null,\n }\n let orderLabTest: typeof labTest\n if (method === nativeMethod) {\n orderLabTest = labTest\n } else {\n const markerFingerprint = (test: { markers?: Array<{ id: number }> | null }) =>\n (test.markers ?? [])\n .map((marker) => marker.id)\n .sort((a, b) => a - b)\n .join(\",\")\n const sourceFingerprint = markerFingerprint(labTest)\n const existingAuto = state\n .listLabTests()\n .find(\n (test) =>\n test.auto_generated === true &&\n test.method === method &&\n markerFingerprint(test) === sourceFingerprint,\n )\n const orderLabTestKey = `${labTest.id}:${method}`\n const orderLabTestName =\n existingAuto?.name ?? opaqueToken(`junction:order-lab-name:${orderLabTestKey}`, 16)\n orderLabTest = existingAuto ?? {\n ...labTest,\n id: deterministicUuid(`junction:order-lab-test:${orderLabTestKey}`),\n method,\n auto_generated: true,\n name: orderLabTestName,\n slug: `afd62b39-${orderLabTestName}`,\n }\n }\n const order: OrderRecord = {\n id: orderId,\n user_id: userId,\n team_id: state.teamId,\n patient_details: patientDetails(details),\n patient_address: patientAddress(draft.patientAddress),\n lab_test: orderLabTest,\n details: METHOD_DETAILS(method, state.testkitIdFor(orderId), nowIso),\n sample_id: null,\n notes: null,\n clinical_notes: draft.clinicalNotes,\n passthrough: draft.passthrough,\n created_at: nowIso,\n updated_at: nowIso,\n events: [event],\n status: \"received\",\n last_event: event,\n physician: PHYSICIAN,\n health_insurance_id: null,\n requisition_form_url: null,\n shipping_details: null,\n has_abn: false,\n billing_type: billingType,\n priority: false,\n activate_by: null,\n icd_codes: icdCodes,\n interpretation: null,\n has_missing_results: null,\n result_types: null,\n expected_result_by_date: null,\n worst_case_result_by_date: null,\n origin: \"initial\",\n order_transaction: {\n id: transactionId,\n status: \"active\",\n orders: [\n {\n id: orderId,\n low_level_status: \"ordered\",\n low_level_status_created_at: nowMicro,\n origin: \"initial\",\n parent_id: null,\n created_at: nowMicro,\n updated_at: nowMicro,\n },\n ],\n },\n }\n return order\n}\n\n/**\n * Store an order built by {@link buildOrderRecord}: the order, its transaction binding,\n * the lab test it embeds, and the patient's demographics \u2014 everything `create_order`\n * writes, so an order inserted any other way reads back the same.\n */\nexport const persistOrderRecord = (\n state: JunctionState,\n order: OrderRecord,\n labTest: LabTestRecord,\n details: Record<string, unknown>,\n address: Record<string, unknown>,\n): void => {\n const userId = order.user_id\n const orderLabTest = order.lab_test\n state.orders.insert(order.id, order)\n state.orderByTransaction.insert(order.order_transaction.id, { order_id: order.id })\n state.upsertLabTest(\n orderLabTest,\n orderLabTest.id === labTest.id ? undefined : state.expectedResultsFor(labTest.id),\n )\n const demographics = {\n first_name: details.first_name ?? null,\n last_name: details.last_name ?? null,\n dob: details.dob ?? null,\n gender: details.gender ?? null,\n phone_number: details.phone_number ?? null,\n email: details.email ?? null,\n gender_identity: null,\n sexual_orientation: null,\n race: null,\n ethnicity: null,\n medical_proxy: null,\n address: {\n first_line: address.first_line ?? \"\",\n second_line: typeof address.second_line === \"string\" ? address.second_line : \"\",\n country: address.country ?? \"\",\n zip: address.zip ?? \"\",\n city: address.city ?? \"\",\n state: address.state ?? \"\",\n access_notes: null,\n },\n }\n if (state.userInfo.get(userId)) state.userInfo.update(userId, demographics)\n else state.userInfo.insert(userId, demographics)\n}\n\nconst orderSummary = (order: OrderRecord) => {\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n return {\n id: order.id,\n origin: transactionOrder?.origin ?? \"initial\",\n parent_id: transactionOrder?.parent_id ?? null,\n last_status: transactionOrder?.low_level_status ?? \"ordered\",\n last_status_created_at: transactionOrder?.low_level_status_created_at ?? order.created_at,\n updated_at: order.updated_at,\n created_at: order.created_at,\n }\n}\n\nconst biomarker = (order: OrderRecord, created_at: string) =>\n (order.lab_test.markers ?? []).map((marker) => ({\n name: marker.name,\n slug: marker.slug,\n result: marker.slug,\n type: \"numeric\",\n unit: marker.unit,\n timestamp: created_at,\n reference_range: null,\n interpretation: \"normal\",\n performing_laboratory: \"Mockingbird Central Lab\",\n source_sample_id: null,\n }))\n", "/**\n * The test backdoor: users and orders put straight into a namespace, with ids a suite\n * chooses \u2014 the Junction `user_id`s a database fixture already carries, or an order\n * already in some status \u2014 plus the lenient identity mode that adopts unknown users.\n *\n * Everything inserted here goes through the records `create_user` and `create_order`\n * build, so no read path can tell a fixture from an API-created resource.\n */\nimport { HttpError, type OperationContext } from \"@crvouga/mockingbird-service\"\nimport { resolveTransition } from \"./admin.js\"\nimport { missing } from \"./not-found.js\"\nimport { buildOrderRecord, persistOrderRecord } from \"./orders.js\"\nimport { forceOrderStatus } from \"./scheduling.js\"\nimport type { JunctionState, OrderRecord, ResultFixture, UserRecord } from \"./state.js\"\n\n/** How requests referring to a user the namespace does not hold are answered. */\nexport type IdentityMode = \"strict\" | \"adopt-users\"\n\nexport const IDENTITY_MODES: readonly IdentityMode[] = [\"strict\", \"adopt-users\"]\n\nexport type UserFixture = {\n /** Default: a fresh id, as `create_user` would mint. */\n user_id?: string\n client_user_id: string\n /** ISO-8601. Default: the mock clock's now. */\n created_on?: string\n /** An IANA zone, or the full `{ id, source_slug, updated_at }` object. */\n fallback_time_zone?: string | UserRecord[\"fallback_time_zone\"]\n /** `YYYY-MM-DD`, or the full `{ value, source_slug, updated_at }` object. */\n fallback_birth_date?: string | UserRecord[\"fallback_birth_date\"]\n ingestion_start?: string | null\n ingestion_end?: string | null\n}\n\nexport type OrderFixture = {\n /** Default: a fresh id, as `create_order` would mint. */\n order_id?: string\n user_id: string\n lab_test_id: string\n lab_account_id?: string\n /** A transition target (`completed`, `at_lab`, or a full status). Default: just ordered. */\n status?: string\n /** Default: the lab test's own method. */\n collection_method?: string\n patient_details?: Record<string, unknown>\n patient_address?: Record<string, unknown>\n billing_type?: string\n icd_codes?: string[] | null\n passthrough?: string | null\n clinical_notes?: string | null\n /** ISO-8601. Default: the mock clock's now. */\n created_at?: string\n /** Results served for the order, as `PUT /__admin/results/{id}` takes them. */\n result_fixture?: Omit<ResultFixture, \"name\"> & { name?: string }\n}\n\nexport type JunctionFixtures = {\n users?: readonly UserFixture[]\n orders?: readonly OrderFixture[]\n}\n\nexport type InsertOptions = {\n /** Publish the webhooks the equivalent API calls would. Default `false`. */\n emitWebhooks?: boolean\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport const isUuid = (value: string): boolean => UUID.test(value)\n\n/** A backdoor failure: `status` 400 for a bad fixture, 404 for a missing reference, 409 for a clash. */\nexport class FixtureError extends Error {\n constructor(\n readonly status: 400 | 404 | 409,\n message: string,\n ) {\n super(message)\n this.name = \"FixtureError\"\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst instant = (value: unknown, field: string, fallback: string): string => {\n if (value === undefined) return fallback\n if (typeof value !== \"string\" || Number.isNaN(Date.parse(value)))\n throw new FixtureError(400, `${field} must be an ISO-8601 timestamp`)\n return value\n}\n\nconst DEFAULT_PATIENT_DETAILS = {\n first_name: \"Mockingbird\",\n last_name: \"Fixture\",\n dob: \"1990-01-01\",\n gender: \"female\",\n phone_number: \"+14155550100\",\n email: \"fixture@example.com\",\n}\n\nconst DEFAULT_PATIENT_ADDRESS = {\n first_line: \"1 Main St\",\n second_line: \"\",\n city: \"New York\",\n state: \"NY\",\n zip: \"10001\",\n country: \"US\",\n}\n\n/** The user record `create_user` would store for `input`, validated but not stored. */\nexport const buildUser = (\n state: JunctionState,\n input: UserFixture,\n now: () => number,\n): UserRecord => {\n if (!isRecord(input)) throw new FixtureError(400, \"a user fixture must be an object\")\n if (typeof input.client_user_id !== \"string\" || input.client_user_id === \"\")\n throw new FixtureError(400, \"client_user_id must be a non-empty string\")\n if (input.user_id !== undefined && (typeof input.user_id !== \"string\" || !isUuid(input.user_id)))\n throw new FixtureError(400, `user_id must be a UUID (got ${JSON.stringify(input.user_id)})`)\n const createdOn = instant(input.created_on, \"created_on\", state.isoNow(now))\n const zone = input.fallback_time_zone\n const birth = input.fallback_birth_date\n return {\n user_id: input.user_id ?? state.nextUserId(),\n team_id: state.teamId,\n client_user_id: input.client_user_id,\n created_on: createdOn,\n connected_sources: [],\n fallback_time_zone:\n typeof zone === \"string\"\n ? { id: zone, source_slug: \"manual\", updated_at: createdOn }\n : (zone ?? null),\n fallback_birth_date:\n typeof birth === \"string\"\n ? { value: birth, source_slug: \"manual\", updated_at: createdOn }\n : (birth ?? null),\n ingestion_start: input.ingestion_start ?? null,\n ingestion_end: input.ingestion_end ?? null,\n }\n}\n\n/** Insert every user, or none: all are validated (ids and client ids unique) first. */\nexport const insertUsers = (\n state: JunctionState,\n inputs: readonly UserFixture[],\n now: () => number,\n): UserRecord[] => {\n const users: UserRecord[] = []\n const ids = new Set<string>()\n const clientIds = new Set<string>()\n for (const input of inputs) {\n const user = buildUser(state, input, now)\n if (\n ids.has(user.user_id) ||\n state.users.has(user.user_id) ||\n state.deletedUsers.has(user.user_id)\n )\n throw new FixtureError(409, `user ${user.user_id} already exists`)\n if (clientIds.has(user.client_user_id) || state.byClientId.has(user.client_user_id))\n throw new FixtureError(409, `client_user_id ${user.client_user_id} already exists`)\n ids.add(user.user_id)\n clientIds.add(user.client_user_id)\n users.push(user)\n }\n for (const user of users) state.insertUser(user)\n return users\n}\n\n/** Remove a user outright: unlike `DELETE /v2/user/{id}` it leaves no deletion tombstone. */\nexport const hardDeleteUser = (state: JunctionState, userId: string): boolean => {\n const user = state.users.get(userId)\n const tombstoned = state.deletedUsers.delete(userId)\n if (!user) return tombstoned\n state.users.delete(userId)\n state.byClientId.delete(user.client_user_id)\n state.userInfo.delete(userId)\n return true\n}\n\ntype PreparedOrder = {\n input: OrderFixture\n order: OrderRecord\n labTest: NonNullable<ReturnType<JunctionState[\"labTestById\"]>>\n details: Record<string, unknown>\n address: Record<string, unknown>\n status: string | undefined\n}\n\n/**\n * Insert orders through `create_order`'s record builder. Request validation is skipped\n * (a fixture may hold what the API would refuse) but references are not: the user and\n * lab test must exist. Every order is checked before any is stored.\n */\nexport const insertOrders = (\n state: JunctionState,\n inputs: readonly OrderFixture[],\n now: () => number,\n options: InsertOptions = {},\n): OrderRecord[] => {\n const prepared: PreparedOrder[] = []\n const ids = new Set<string>()\n for (const input of inputs) {\n if (!isRecord(input)) throw new FixtureError(400, \"an order fixture must be an object\")\n if (typeof input.user_id !== \"string\") throw new FixtureError(400, \"user_id is required\")\n if (typeof input.lab_test_id !== \"string\")\n throw new FixtureError(400, \"lab_test_id is required\")\n if (!state.users.has(input.user_id) && !state.deletedUsers.has(input.user_id))\n throw new FixtureError(404, `no user ${input.user_id} in this namespace`)\n const labTest = state.labTestById(input.lab_test_id)\n if (!labTest) throw new FixtureError(404, `no lab test ${input.lab_test_id} in the catalog`)\n if (\n input.order_id !== undefined &&\n (typeof input.order_id !== \"string\" || !isUuid(input.order_id))\n )\n throw new FixtureError(400, `order_id must be a UUID (got ${JSON.stringify(input.order_id)})`)\n const orderId = input.order_id ?? state.nextOrderId()\n if (ids.has(orderId) || state.orders.has(orderId))\n throw new FixtureError(409, `order ${orderId} already exists`)\n ids.add(orderId)\n const method =\n typeof input.collection_method === \"string\" && input.collection_method !== \"\"\n ? input.collection_method\n : typeof labTest.method === \"string\" && labTest.method !== \"\"\n ? labTest.method\n : \"at_home_phlebotomy\"\n let status: string | undefined\n if (input.status !== undefined) {\n if (typeof input.status !== \"string\") throw new FixtureError(400, \"status must be a string\")\n const resolved = resolveTransition(method, input.status)\n if (\"error\" in resolved) throw new FixtureError(400, resolved.error)\n status = resolved.status\n }\n const details = { ...DEFAULT_PATIENT_DETAILS, ...input.patient_details }\n const address = { ...DEFAULT_PATIENT_ADDRESS, ...input.patient_address }\n const createdAt = input.created_at\n const createdMs =\n createdAt === undefined ? undefined : Date.parse(instant(createdAt, \"created_at\", \"\"))\n const order = buildOrderRecord(\n state,\n {\n orderId,\n userId: input.user_id,\n labTest,\n method,\n patientDetails: details,\n patientAddress: address,\n billingType: input.billing_type ?? \"client_bill\",\n icdCodes: input.icd_codes ?? null,\n clinicalNotes: input.clinical_notes ?? null,\n passthrough: input.passthrough ?? null,\n },\n createdMs === undefined ? now : () => createdMs,\n )\n prepared.push({ input, order, labTest, details, address, status })\n }\n const run = () => {\n for (const { input, order, labTest, details, address, status } of prepared) {\n persistOrderRecord(state, order, labTest, details, address)\n state.orderLabAccounts.insert(order.id, { lab_account_id: input.lab_account_id ?? null })\n state.publishOrderWebhook(order, \"labtest.order.created\", now())\n if (status !== undefined) {\n const stored = state.orders.get(order.id)\n if (stored) forceOrderStatus(state, stored, status, null, { now })\n }\n if (input.result_fixture !== undefined) {\n state.resultFixtures.insert(order.id, { name: \"custom\", ...input.result_fixture })\n if (input.result_fixture.interpretation !== undefined) {\n const stored = state.orders.get(order.id)\n if (stored) {\n stored.interpretation = input.result_fixture.interpretation\n state.orders.update(order.id, stored)\n }\n }\n }\n }\n }\n if (options.emitWebhooks === true) run()\n else state.muteWebhooks(run)\n return prepared.flatMap(({ order }) => state.orders.get(order.id) ?? [])\n}\n\n/** Load users, then orders, in one call: how `POST /__admin/import` and `serve --fixtures` work. */\nexport const importFixtures = (\n state: JunctionState,\n fixtures: JunctionFixtures,\n now: () => number,\n options: InsertOptions = {},\n): { users: UserRecord[]; orders: OrderRecord[] } => {\n if (!isRecord(fixtures))\n throw new FixtureError(400, 'fixtures must be { \"users\": [...], \"orders\": [...] }')\n const { users = [], orders = [] } = fixtures\n if (!Array.isArray(users)) throw new FixtureError(400, \"users must be an array\")\n if (!Array.isArray(orders)) throw new FixtureError(400, \"orders must be an array\")\n // Orders reference users from the same file, so users go in first; a failed order\n // check then leaves those users behind unless the whole import is rolled back.\n const inserted = insertUsers(state, users, now)\n try {\n return { users: inserted, orders: insertOrders(state, orders, now, options) }\n } catch (error) {\n for (const user of inserted) hardDeleteUser(state, user.user_id)\n throw error\n }\n}\n\n/**\n * The one place a request's `user_id` is resolved. In `strict` mode an unknown user is\n * Junction's 404; in `adopt-users` mode a well-formed UUID is created on first use (the\n * adoption is noted for the request journal). A deleted user still resolves, as in Junction.\n */\nexport const requireUser = (\n state: JunctionState,\n userId: string,\n context: Pick<OperationContext, \"request\" | \"now\">,\n detail = \"User does not exist on this team\",\n): void => {\n if (state.users.has(userId) || state.deletedUsers.has(userId)) return\n if (state.identity === \"adopt-users\" && isUuid(userId)) {\n insertUsers(state, [{ user_id: userId, client_user_id: userId }], context.now)\n state.noteAdoption(context.request)\n return\n }\n missing(state, \"user\", userId, detail)\n}\n\n/** An admin-style error for a {@link FixtureError}; anything else is rethrown. */\nexport const fixtureErrorMessage = (error: unknown): { status: number; message: string } => {\n if (error instanceof FixtureError) return { status: error.status, message: error.message }\n if (error instanceof HttpError) {\n const detail = isRecord(error.body) ? error.body.detail : error.body\n return {\n status: error.status,\n message: typeof detail === \"string\" ? detail : JSON.stringify(detail),\n }\n }\n throw error\n}\n", "// Generated by @crvouga/mockingbird-openapi-codegen from openapi.yaml. Do not edit.\n\nimport type { OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\n\nexport const document: OpenAPIDocument = JSON.parse(`{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Junction API (Mockingbird subset)\",\"description\":\"Stateful mock subset of the Junction (Vital) API.\\\\nDocs: https://docs.junction.com/\\\\nAuth: https://docs.junction.com/api-details/junction-api\\\\nCreate user: https://docs.junction.com/api-reference/user/create-user\\\\nGet user: https://docs.junction.com/api-reference/user/get-user\\\\nDelete user: https://docs.junction.com/api-reference/user/delete-user\\\\nResolve user: https://docs.junction.com/api-reference/user/resolve-user\\\\nUpdate user: https://docs.junction.com/api-reference/user/patch-user\\\\nGet users: https://docs.junction.com/api-reference/user/get-users\\\\nCreate order: https://docs.junction.com/api-reference/lab-testing/create-order\\\\nGet order: https://docs.junction.com/api-reference/lab-testing/get-order\\\\nGet orders: https://docs.junction.com/api-reference/lab-testing/get-orders\\\\nGet order transaction: https://docs.junction.com/api-reference/lab-testing/order-transactions/get-order-transaction\\\\nGet order transaction result: https://docs.junction.com/api-reference/lab-testing/results/get-order-transaction-results\\\\nLab tests: https://docs.junction.com/api-reference/lab-testing/tests-paginated\\\\nLab tests (deprecated, unpaged): https://docs.junction.com/api-reference/lab-testing/tests/get-lab-tests\\\\nAppointment availability: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment-availability\\\\nBook appointment: https://docs.junction.com/api-reference/lab-testing/appointments/book-appointment\\\\nGet appointment: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment\\\\nReschedule appointment: https://docs.junction.com/api-reference/lab-testing/appointments/reschedule-appointment\\\\nCancel appointment: https://docs.junction.com/api-reference/lab-testing/appointments/cancel-appointment\\\\nAppointment cancellation reasons: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment-cancellation-reasons\\\\nArea info: https://docs.junction.com/api-reference/lab-testing/service-areas/get-area-info\\\\nPSC info: https://docs.junction.com/api-reference/lab-testing/service-areas/get-psc-info\\\\nLab locations: https://docs.junction.com/api-reference/lab-testing/service-areas/get-lab-locations\\\\nRaw results: https://docs.junction.com/api-reference/lab-testing/results/get-lab-results\\\\nResult metadata: https://docs.junction.com/api-reference/lab-testing/results/get-lab-results-metadata\\\\nResult PDF: https://docs.junction.com/api-reference/lab-testing/results/get-lab-result-pdf\\\\nRequisition form PDF: https://docs.junction.com/api-reference/lab-testing/orders/get-requisition-form\\\\nList labs: https://docs.junction.com/api-reference/lab-testing/tests/get-labs\\\\nTest markers: https://docs.junction.com/api-reference/lab-testing/tests/get-markers-for-lab-test\\\\nOrder-set markers: https://docs.junction.com/api-reference/lab-testing/results/get-order-set-markers\\\\nLatest user info: https://docs.junction.com/api-reference/user/get-latest-user-info\\\\n\",\"version\":\"0.4.758\",\"x-mockingbird-upstream\":{\"docs\":\"https://docs.junction.com/\",\"note\":\"Hand-authored subset from Junction public OpenAPI snippets in the docs.\"}},\"servers\":[{\"url\":\"https://api.sandbox.us.junction.com\"}],\"security\":[{\"apiKeyAuth\":[]}],\"paths\":{\"/v2/user\":{\"post\":{\"operationId\":\"create_user_v2_user_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserCreateBody\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}}}},\"400\":{\"description\":\"Bad Request\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientUserIDConflictResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"get\":{\"operationId\":\"get_teams_users_v2_user_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"offset\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\"}},{\"name\":\"limit\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"maximum\":500}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PaginatedUsersResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"500\":{\"description\":\"Internal Server Error\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}}}}},\"/v2/user/{user_id}\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_user_v2_user__user_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"delete\":{\"operationId\":\"delete_user_v2_user__user_id__delete\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserSuccessResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"patch\":{\"operationId\":\"patch_user_v2_user__user_id__patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserPatchBody\"}}}},\"responses\":{\"204\":{\"description\":\"Successful Response\"},\"400\":{\"description\":\"Nothing to patch\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"409\":{\"description\":\"Conflict\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/resolve/{client_user_id}\":{\"parameters\":[{\"name\":\"client_user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"minLength\":1}}],\"get\":{\"operationId\":\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingUser\"},{\"$ref\":\"#/components/schemas/PaginatedUsersResponse\"}]}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/{user_id}/info\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"patch_user_info_v2_user__user_id__info_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfoPatchBody\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/{user_id}/info/latest\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_test\":{\"get\":{\"operationId\":\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabTestResourcesResponse\"}}}}}}},\"/v3/lab_test/lab_account\":{\"get\":{\"operationId\":\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"lab-account inventory is fixture-owned; the mock models the documented shape, filters and routing rules, not a live account inventory\"}},\"parameters\":[{\"name\":\"lab_account_id\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]}},{\"name\":\"status\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/LabAccountStatus\"},{\"type\":\"null\"}]}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetTeamLabAccountsResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests\":{\"get\":{\"operationId\":\"get_lab_tests_for_team_v3_lab_tests_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"summary\":\"Get Lab Tests For Team\",\"description\":\"GET all the lab tests the team has access to.\",\"deprecated\":true,\"parameters\":[{\"name\":\"generation_method\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/LabTestGenerationMethodFilter\",\"description\":\"Filter on whether auto-generated lab tests created by Vital, manually created lab tests, or all lab tests should be returned.\",\"default\":\"manual\"},\"description\":\"Filter on whether auto-generated lab tests created by Vital, manually created lab tests, or all lab tests should be returned.\"},{\"name\":\"lab_slug\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"description\":\"Filter by the slug of the lab for these lab tests.\",\"title\":\"Lab Slug\"},\"description\":\"Filter by the slug of the lab for these lab tests.\"},{\"name\":\"collection_method\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"},{\"type\":\"null\"}],\"description\":\"Filter by the collection method for these lab tests.\",\"title\":\"Collection Method\"},\"description\":\"Filter by the collection method for these lab tests.\"},{\"name\":\"status\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/LabTestStatus\"},{\"type\":\"null\"}],\"description\":\"Filter by the status of these lab tests.\",\"title\":\"Status\"},\"description\":\"Filter by the status of these lab tests.\"},{\"name\":\"marker_ids\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"integer\"}},{\"type\":\"null\"}],\"description\":\"Filter to only include lab tests containing these marker IDs.\",\"title\":\"Marker Ids\"},\"description\":\"Filter to only include lab tests containing these marker IDs.\"},{\"name\":\"provider_ids\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"null\"}],\"description\":\"Filter to only include lab tests containing these provider IDs.\",\"title\":\"Provider Ids\"},\"description\":\"Filter to only include lab tests containing these provider IDs.\"},{\"name\":\"name\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"description\":\"Filter by the name of the lab test (a case-insensitive substring search).\",\"title\":\"Name\"},\"description\":\"Filter by the name of the lab test (a case-insensitive substring search).\"},{\"name\":\"order_key\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"enum\":[\"price\",\"created_at\",\"updated_at\"],\"type\":\"string\"},{\"type\":\"null\"}],\"title\":\"Order Key\"}},{\"name\":\"order_direction\",\"in\":\"query\",\"required\":false,\"schema\":{\"enum\":[\"asc\",\"desc\"],\"type\":\"string\",\"default\":\"asc\",\"title\":\"Order Direction\"}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"},\"title\":\"Response Get Lab Tests For Team V3 Lab Tests Get\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/{lab_test_id}\":{\"parameters\":[{\"name\":\"lab_test_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/labs\":{\"get\":{\"operationId\":\"get_labs_v3_lab_tests_labs_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLab\"}}}}}}}},\"/v3/lab_tests/{lab_test_id}/markers\":{\"parameters\":[{\"name\":\"lab_test_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}},{\"name\":\"page\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"default\":1}},{\"name\":\"size\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100,\"default\":50}},{\"name\":\"provider_id\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"get\":{\"operationId\":\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetMarkersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/list_order_set_markers\":{\"post\":{\"operationId\":\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ListOrderSetMarkersRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetMarkersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order\":{\"post\":{\"operationId\":\"create_order_v3_order_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CreateOrderRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PostOrderResponse\"}}}},\"400\":{\"description\":\"Bad Request\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"500\":{\"description\":\"Internal Server Error\"}}}},\"/v3/order/area/info\":{\"get\":{\"operationId\":\"get_area_info_v3_order_area_info_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"central_labs presence, within_radius counts and getlabs market coverage are provider-owned geo data that a mock cannot replicate per-zip; covered by the client-parity scenario shape checks instead\"}},\"parameters\":[{\"name\":\"zip_code\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}(?:-?\\\\\\\\d{4})?$\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"lab_account_id\",\"in\":\"query\",\"required\":false,\"description\":\"Lab Account ID to use for availability checks\",\"schema\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AreaInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/psc/info\":{\"get\":{\"operationId\":\"get_psc_info_v3_order_psc_info_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"patient_service_centers are real site inventories per zip (thousands of sites, result-capped at 30) that a fixture mock cannot replicate per-zip; covered by the client-parity scenario shape checks instead\"}},\"parameters\":[{\"name\":\"zip_code\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}$\"}},{\"name\":\"lab_id\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"integer\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"capabilities\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/phlebotomy/appointment/availability\":{\"post\":{\"operationId\":\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"availability slots are provider-side data whose values shift between sandbox calls; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"start_date\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"format\":\"date\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UsAddress\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentAvailabilitySlots\"}}}},\"400\":{\"description\":\"Availability not bookable for this address\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No availability found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/phlebotomy/appointment/cancellation-reasons\":{\"get\":{\"operationId\":\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentCancellationReason\"}}}}}}}},\"/v3/order/psc/appointment/availability\":{\"post\":{\"operationId\":\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"availability slots are provider-side data whose values shift between sandbox calls; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"lab\",\"in\":\"query\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/AppointmentPscLabs\"}},{\"name\":\"start_date\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"format\":\"date\"}},{\"name\":\"site_codes\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"description\":\"JSON-encoded array of site codes\"}},{\"name\":\"zip_code\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"allow_stale\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"boolean\"}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentAvailabilitySlots\"}}}},\"400\":{\"description\":\"Availability not bookable for this address\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No slots found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/psc/appointment/cancellation-reasons\":{\"get\":{\"operationId\":\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentCancellationReason\"}}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"appointment payloads embed provider-side slot data; covered by the mock-internal scheduling property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/book\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"booking depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentBookingRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Booking failed\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Order not found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/reschedule\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"rescheduling depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentRescheduleRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid or expired booking key\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"cancellation depends on live provider appointment state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PhlebotomyAppointmentCancelRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid cancellation reason\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"appointment payloads embed provider-side slot data; covered by the mock-internal scheduling property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/book\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"booking depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"x-idempotency-key\",\"in\":\"header\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscAppointmentBookingRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Booking failed\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Order not found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/reschedule\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"rescheduling depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentRescheduleRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid or expired booking key\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"cancellation depends on live provider appointment state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscAppointmentCancelRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid cancellation reason\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_v3_order__order_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"cancel_order_v3_order__order_id__cancel_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PostOrderResponse\"}}}},\"400\":{\"description\":\"Order is not in a cancellable status\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/test\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"simulate_order_v3_order__order_id__test_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"final_status\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"enum\":[\"received.walk_in_test.ordered\",\"received.walk_in_test.requisition_created\",\"received.walk_in_test.requisition_bypassed\",\"completed.walk_in_test.completed\",\"sample_with_lab.walk_in_test.partial_results\",\"failed.walk_in_test.sample_error\",\"cancelled.walk_in_test.cancelled\",\"collecting_sample.walk_in_test.appointment_pending\",\"collecting_sample.walk_in_test.appointment_scheduled\",\"collecting_sample.walk_in_test.appointment_cancelled\",\"collecting_sample.walk_in_test.redraw_available\",\"received.at_home_phlebotomy.ordered\",\"received.at_home_phlebotomy.requisition_created\",\"received.at_home_phlebotomy.requisition_bypassed\",\"collecting_sample.at_home_phlebotomy.appointment_pending\",\"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\"collecting_sample.at_home_phlebotomy.draw_completed\",\"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\"completed.at_home_phlebotomy.completed\",\"sample_with_lab.at_home_phlebotomy.partial_results\",\"cancelled.at_home_phlebotomy.cancelled\",\"failed.at_home_phlebotomy.sample_error\",\"received.testkit.ordered\",\"received.testkit.awaiting_registration\",\"received.testkit.requisition_created\",\"received.testkit.requisition_bypassed\",\"received.testkit.registered\",\"collecting_sample.testkit.transit_customer\",\"collecting_sample.testkit.out_for_delivery\",\"collecting_sample.testkit.with_customer\",\"collecting_sample.testkit.transit_lab\",\"sample_with_lab.testkit.delivered_to_lab\",\"sample_with_lab.testkit.lab_processing_blocked\",\"completed.testkit.completed\",\"failed.testkit.failure_to_deliver_to_customer\",\"failed.testkit.failure_to_deliver_to_lab\",\"failed.testkit.sample_error\",\"failed.testkit.lost\",\"cancelled.testkit.cancelled\",\"cancelled.testkit.do_not_process\",\"collecting_sample.testkit.problem_in_transit_customer\",\"collecting_sample.testkit.problem_in_transit_lab\",\"received.on_site_collection.ordered\",\"received.on_site_collection.requisition_created\",\"received.on_site_collection.requisition_bypassed\",\"sample_with_lab.on_site_collection.draw_completed\",\"completed.on_site_collection.completed\",\"cancelled.on_site_collection.cancelled\",\"sample_with_lab.on_site_collection.partial_results\",\"failed.on_site_collection.sample_error\",\"completed.walk_in_test.corrected\",\"completed.at_home_phlebotomy.corrected\",\"completed.on_site_collection.corrected\",\"completed.testkit.corrected\"]}},{\"name\":\"delay\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Seconds to defer the status transition\"}}],\"requestBody\":{\"required\":false,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/SimulationFlags\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\",\"examples\":[\"Success\"]}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_raw_v3_order__order_id__result_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"results carry provider-side specimen data; covered by the mock-internal results property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsRaw\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result/metadata\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsMetadata\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result/pdf\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"PDF bytes are provider-rendered; compared by shape (byteLength) only in the scenario script\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/pdf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/requisition/pdf\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"PDF bytes are provider-rendered; compared by shape (byteLength) only in the scenario script\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/pdf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/orders\":{\"get\":{\"operationId\":\"get_orders_v3_orders_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"user_id\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}},{\"name\":\"page\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"default\":1}},{\"name\":\"size\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100,\"default\":50}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetOrdersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order_transaction/{transaction_id}\":{\"parameters\":[{\"name\":\"transaction_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"order transactions are not available to the sandbox team (feature not available)\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetOrderTransactionResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order_transaction/{transaction_id}/result\":{\"parameters\":[{\"name\":\"transaction_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"lab results are not available to the sandbox team (feature not available)\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsRaw\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}}},\"components\":{\"securitySchemes\":{\"apiKeyAuth\":{\"type\":\"apiKey\",\"in\":\"header\",\"name\":\"x-vital-api-key\"}},\"schemas\":{\"UserCreateBody\":{\"type\":\"object\",\"required\":[\"client_user_id\"],\"properties\":{\"client_user_id\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"mbr_8891\",\"patient-1042\",\"user.profile_52\"]},\"fallback_time_zone\":{\"type\":[\"string\",\"null\"],\"enum\":[\"America/Los_Angeles\",\"America/New_York\",\"Europe/London\",\"UTC\",null]}}},\"ClientFacingUser\":{\"type\":\"object\",\"required\":[\"user_id\",\"team_id\",\"client_user_id\",\"created_on\",\"connected_sources\",\"fallback_time_zone\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"user\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"client_user_id\":{\"type\":\"string\"},\"created_on\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"connected_sources\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"additionalProperties\":true}},\"fallback_time_zone\":{\"type\":[\"object\",\"null\"],\"properties\":{\"id\":{\"type\":\"string\"},\"source_slug\":{\"type\":\"string\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"fallback_birth_date\":{\"type\":[\"object\",\"null\"],\"properties\":{\"value\":{\"type\":\"string\"},\"source_slug\":{\"type\":\"string\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ingestion_start\":{\"type\":[\"string\",\"null\"]},\"ingestion_end\":{\"type\":[\"string\",\"null\"]}}},\"UserInfoPatchBody\":{\"type\":\"object\",\"properties\":{\"first_name\":{\"type\":[\"string\",\"null\"]},\"last_name\":{\"type\":[\"string\",\"null\"]},\"dob\":{\"type\":[\"string\",\"null\"]},\"gender\":{\"type\":[\"string\",\"null\"]},\"phone_number\":{\"type\":[\"string\",\"null\"]},\"email\":{\"type\":[\"string\",\"null\"]},\"address\":{\"type\":[\"object\",\"null\"],\"additionalProperties\":true}}},\"UserInfo\":{\"type\":\"object\",\"additionalProperties\":true},\"ClientUserIDConflictResponse\":{\"type\":\"object\",\"required\":[\"detail\"],\"properties\":{\"detail\":{\"type\":\"object\",\"required\":[\"error_type\",\"error_message\",\"user_id\",\"created_on\"],\"properties\":{\"error_type\":{\"type\":\"string\"},\"error_message\":{\"type\":\"string\"},\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"created_on\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}}}},\"UserSuccessResponse\":{\"type\":\"object\",\"required\":[\"success\"],\"properties\":{\"success\":{\"type\":\"boolean\"}}},\"PaginatedUsersResponse\":{\"type\":\"object\",\"required\":[\"users\",\"total\",\"offset\",\"limit\"],\"properties\":{\"users\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}},\"total\":{\"type\":\"integer\"},\"offset\":{\"type\":\"integer\"},\"limit\":{\"type\":\"integer\"}}},\"UserPatchBody\":{\"type\":\"object\",\"properties\":{\"fallback_time_zone\":{\"type\":[\"string\",\"null\"]},\"fallback_birth_date\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"ingestion_start\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"ingestion_end\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"client_user_id\":{\"type\":[\"string\",\"null\"]}}},\"LabTestCollectionMethod\":{\"type\":\"string\",\"enum\":[\"testkit\",\"walk_in_test\",\"at_home_phlebotomy\",\"on_site_collection\"]},\"LabTestGenerationMethodFilter\":{\"type\":\"string\",\"enum\":[\"auto\",\"manual\",\"all\"]},\"LabTestSampleType\":{\"type\":\"string\",\"enum\":[\"dried_blood_spot\",\"arm_collector\",\"serum\",\"saliva\",\"urine\",\"stool\"]},\"LabTestStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"pending_approval\",\"inactive\"]},\"MarkerType\":{\"type\":\"string\",\"enum\":[\"biomarker\",\"panel\"]},\"ClientFacingLab\":{\"type\":\"object\",\"required\":[\"id\",\"slug\",\"name\",\"first_line_address\",\"city\",\"zipcode\",\"collection_methods\",\"sample_types\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"slug\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"first_line_address\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"},\"zipcode\":{\"type\":\"string\"},\"collection_methods\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"}},\"sample_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabTestSampleType\"}},\"logo_url\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingMarker\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"description\":{\"type\":[\"string\",\"null\"]},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/MarkerType\"},{\"type\":\"null\"}]},\"unit\":{\"type\":[\"string\",\"null\"]},\"price\":{\"type\":[\"string\",\"null\"]},\"aoe\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"a_la_carte_enabled\":{\"type\":\"boolean\",\"default\":false},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]},\"is_orderable\":{\"type\":[\"boolean\",\"null\"],\"default\":true}}},\"ClientFacingLabTest\":{\"type\":\"object\",\"required\":[\"id\",\"slug\",\"name\",\"sample_type\",\"method\",\"price\",\"is_active\",\"status\",\"lab\",\"markers\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"lab_test\",\"identity\":true}},\"slug\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"name\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"sample_type\":{\"$ref\":\"#/components/schemas/LabTestSampleType\"},\"method\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"},\"price\":{\"type\":\"number\"},\"is_active\":{\"type\":\"boolean\"},\"status\":{\"$ref\":\"#/components/schemas/LabTestStatus\"},\"fasting\":{\"type\":\"boolean\",\"default\":false},\"lab\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingLab\"},{\"type\":\"null\"}]},\"markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingMarker\"}},{\"type\":\"null\"}]},\"is_delegated\":{\"type\":\"boolean\",\"default\":false},\"auto_generated\":{\"type\":\"boolean\",\"default\":false},\"has_collection_instructions\":{\"type\":[\"boolean\",\"null\"]},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]}}},\"LabTestResourcesResponse\":{\"type\":\"object\",\"required\":[\"data\",\"next_cursor\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"}},\"next_cursor\":{\"type\":[\"string\",\"null\"]}}},\"LabAccountStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"pending\",\"suspended\",\"ready_to_launch\"]},\"LabAccountDelegatedFlow\":{\"type\":\"string\",\"enum\":[\"order_delegated\",\"result_delegated\",\"fully_delegated\",\"not_delegated\"]},\"USState\":{\"type\":\"string\",\"enum\":[\"AL\",\"AK\",\"AZ\",\"AR\",\"CA\",\"CO\",\"CT\",\"DE\",\"FL\",\"GA\",\"HI\",\"ID\",\"IL\",\"IN\",\"IA\",\"KS\",\"KY\",\"LA\",\"ME\",\"MD\",\"MA\",\"MI\",\"MN\",\"MS\",\"MO\",\"MT\",\"NE\",\"NV\",\"NH\",\"NJ\",\"NM\",\"NY\",\"NC\",\"ND\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VT\",\"VA\",\"WA\",\"WV\",\"WI\",\"WY\"]},\"Labs\":{\"type\":\"string\",\"enum\":[\"ayumetrix\",\"spiriplex\",\"ussl\",\"quest\",\"sonora_quest\",\"labcorp\",\"bioreference\",\"us_biotek\",\"manual\",\"sanocardio\",\"ihd\",\"nexus\",\"my_uti\",\"crl\",\"mtl\"]},\"ClientFacingLabAccount\":{\"type\":\"object\",\"required\":[\"id\",\"lab\",\"status\",\"delegated_flow\",\"provider_account_id\",\"allowed_billing\",\"team_id_allowlist\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"lab_account\",\"identity\":true}},\"lab\":{\"$ref\":\"#/components/schemas/Labs\"},\"org_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"status\":{\"$ref\":\"#/components/schemas/LabAccountStatus\"},\"delegated_flow\":{\"$ref\":\"#/components/schemas/LabAccountDelegatedFlow\"},\"provider_account_id\":{\"type\":\"string\"},\"account_name\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"default_clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"business_units\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"null\"}]},\"allowed_billing\":{\"type\":\"object\",\"propertyNames\":{\"$ref\":\"#/components/schemas/Billing\"},\"additionalProperties\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/USState\"}}},\"team_id_allowlist\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}}},\"GetTeamLabAccountsResponse\":{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabAccount\"}}}},\"ClientFacingResult\":{\"type\":\"object\",\"required\":[\"name\",\"slug\",\"type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"$ref\":\"#/components/schemas/ResultType\"},\"value\":{\"type\":[\"number\",\"null\"]},\"unit\":{\"type\":[\"string\",\"null\"]},\"low_value\":{\"type\":[\"number\",\"null\"]},\"high_value\":{\"type\":[\"number\",\"null\"]},\"string_value\":{\"type\":[\"string\",\"null\"]},\"coded_value\":{\"type\":[\"string\",\"null\"]},\"is_abnormal\":{\"type\":\"boolean\",\"default\":false},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"GetMarkersResponse\":{\"type\":\"object\",\"required\":[\"markers\"],\"properties\":{\"markers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingMarkerComplete\"}},\"total\":{\"type\":[\"integer\",\"null\"]},\"page\":{\"type\":[\"integer\",\"null\"]},\"size\":{\"type\":[\"integer\",\"null\"]},\"pages\":{\"type\":[\"integer\",\"null\"]}}},\"ClientFacingExpectedResult\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\",\"required\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"required\":{\"type\":\"boolean\"},\"loinc\":{\"type\":[\"object\",\"null\"],\"required\":[\"id\",\"name\",\"slug\",\"code\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"code\":{\"type\":\"string\"},\"unit\":{\"type\":[\"string\",\"null\"]}}}}},\"ClientFacingMarkerComplete\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\",\"expected_results\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"description\":{\"type\":[\"string\",\"null\"]},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/MarkerType\"},{\"type\":\"null\"}]},\"unit\":{\"type\":[\"string\",\"null\"]},\"price\":{\"type\":[\"string\",\"null\"]},\"a_la_carte_enabled\":{\"type\":\"boolean\",\"default\":false},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]},\"is_orderable\":{\"type\":[\"boolean\",\"null\"],\"default\":true},\"expected_results\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingExpectedResult\"}}}},\"ListOrderSetMarkersRequest\":{\"type\":\"object\",\"required\":[\"order_set_id\"],\"properties\":{\"order_set_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}},\"provider_id\":{\"type\":[\"string\",\"null\"]}}},\"AllowedRadius\":{\"type\":\"integer\",\"enum\":[10,20,25,50,100]},\"AppointmentPscLabs\":{\"type\":\"string\",\"enum\":[\"quest\"]},\"AppointmentProvider\":{\"type\":\"string\",\"enum\":[\"getlabs\",\"phlebfinders\",\"quest\"]},\"AppointmentType\":{\"type\":\"string\",\"enum\":[\"phlebotomy\",\"patient_service_center\"]},\"AppointmentStatus\":{\"type\":\"string\",\"enum\":[\"confirmed\",\"pending\",\"reserved\",\"in_progress\",\"completed\",\"cancelled\"]},\"AppointmentEventStatus\":{\"type\":\"string\",\"enum\":[\"pending\",\"reserved\",\"scheduled\",\"completed\",\"cancelled\",\"in_progress\"]},\"AppointmentServiceType\":{\"type\":\"string\",\"enum\":[\"appointment-ready\",\"appointment-request\"]},\"Billing\":{\"type\":\"string\",\"enum\":[\"client_bill\",\"commercial_insurance\",\"patient_bill_passthrough\",\"patient_bill\"]},\"LabLocationCapability\":{\"type\":\"string\",\"enum\":[\"stat\",\"appointment_scheduling_via_junction\",\"appointment_scheduling_with_lab\"]},\"LngLat\":{\"type\":\"object\",\"required\":[\"lng\",\"lat\"],\"properties\":{\"lng\":{\"type\":\"number\"},\"lat\":{\"type\":\"number\"}}},\"UsAddress\":{\"type\":\"object\",\"required\":[\"first_line\",\"city\",\"state\",\"zip_code\"],\"properties\":{\"first_line\":{\"type\":\"string\",\"minLength\":1},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\",\"minLength\":1},\"state\":{\"type\":\"string\",\"minLength\":1},\"zip_code\":{\"type\":\"string\",\"minLength\":1},\"unit\":{\"type\":[\"string\",\"null\"]}}},\"AppointmentLocation\":{\"type\":\"object\",\"required\":[\"location\",\"address\",\"code\",\"name\"],\"properties\":{\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"distance\":{\"type\":[\"number\",\"null\"]},\"address\":{\"$ref\":\"#/components/schemas/UsAddress\"},\"code\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"iana_timezone\":{\"type\":[\"string\",\"null\"]}}},\"TimeSlot\":{\"type\":\"object\",\"required\":[\"start\",\"end\",\"price\",\"is_priority\",\"num_appointments_available\"],\"properties\":{\"booking_key\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-resource\":{\"type\":\"booking_key\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"start\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"end\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"expires_at\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"price\":{\"type\":\"number\"},\"is_priority\":{\"type\":\"boolean\"},\"num_appointments_available\":{\"type\":\"integer\"}}},\"DaySlots\":{\"type\":\"object\",\"required\":[\"date\",\"slots\"],\"properties\":{\"location\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/AppointmentLocation\"},{\"type\":\"null\"}]},\"date\":{\"type\":\"string\",\"format\":\"date\"},\"slots\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/TimeSlot\"}}}},\"AppointmentAvailabilitySlots\":{\"type\":\"object\",\"required\":[\"slots\"],\"properties\":{\"slots\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/DaySlots\"}},\"timezone\":{\"type\":[\"string\",\"null\"]}}},\"AppointmentBookingRequest\":{\"type\":\"object\",\"required\":[\"booking_key\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}}}},\"AppointmentRescheduleRequest\":{\"type\":\"object\",\"required\":[\"booking_key\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}}}},\"PscAppointmentBookingRequest\":{\"type\":\"object\",\"required\":[\"booking_key\",\"site_code\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}},\"site_code\":{\"type\":\"string\",\"minLength\":1}}},\"PhlebotomyAppointmentCancelRequest\":{\"type\":\"object\",\"required\":[\"cancellation_reason_id\"],\"properties\":{\"cancellation_reason_id\":{\"type\":\"string\",\"minLength\":1},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"PscAppointmentCancelRequest\":{\"type\":\"object\",\"required\":[\"cancellationReasonId\"],\"properties\":{\"cancellationReasonId\":{\"type\":\"string\",\"minLength\":1},\"note\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingAppointmentEvent\":{\"type\":\"object\",\"required\":[\"created_at\",\"status\"],\"properties\":{\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"$ref\":\"#/components/schemas/AppointmentEventStatus\"},\"data\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}}},\"ClientFacingAppointment\":{\"type\":\"object\",\"required\":[\"id\",\"user_id\",\"order_id\",\"address\",\"location\",\"type\",\"provider\",\"status\",\"provider_id\",\"can_reschedule\",\"event_status\",\"events\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"appointment\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\"}},\"order_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\"}},\"address\":{\"$ref\":\"#/components/schemas/UsAddress\"},\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"start_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"end_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"iana_timezone\":{\"type\":[\"string\",\"null\"]},\"type\":{\"$ref\":\"#/components/schemas/AppointmentType\"},\"provider\":{\"$ref\":\"#/components/schemas/AppointmentProvider\"},\"status\":{\"$ref\":\"#/components/schemas/AppointmentStatus\"},\"provider_id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"external_id\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"can_reschedule\":{\"type\":\"boolean\"},\"event_status\":{\"$ref\":\"#/components/schemas/AppointmentEventStatus\"},\"event_data\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"order_transaction_id\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\"}},\"appointment_notes\":{\"type\":[\"string\",\"null\"]},\"events\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentEvent\"}}}},\"ClientFacingAppointmentCancellationReason\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"is_refundable\"],\"properties\":{\"id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"is_refundable\":{\"type\":\"boolean\"}}},\"PhlebotomyAreaInfo\":{\"type\":\"object\",\"required\":[\"is_served\",\"providers\"],\"properties\":{\"is_served\":{\"type\":\"boolean\"},\"providers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PhlebotomyProviderInfo\"}}}},\"PhlebotomyProviderInfo\":{\"type\":\"object\",\"required\":[\"name\",\"service_types\"],\"properties\":{\"name\":{\"$ref\":\"#/components/schemas/AppointmentProvider\"},\"service_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/AppointmentServiceType\"}}}},\"PscAreaInfoDetails\":{\"type\":\"object\",\"required\":[\"appointment_with_vital\",\"within_radius\",\"radius\"],\"properties\":{\"appointment_with_vital\":{\"type\":\"boolean\"},\"within_radius\":{\"type\":\"number\"},\"radius\":{\"type\":\"string\"},\"capabilities\":{\"type\":[\"array\",\"null\"],\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}},\"PscAreaInfo\":{\"type\":\"object\",\"required\":[\"patient_service_centers\",\"supported_bill_types\",\"lab_id\"],\"properties\":{\"patient_service_centers\":{\"$ref\":\"#/components/schemas/PscAreaInfoDetails\"},\"supported_bill_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Billing\"}},\"lab_id\":{\"type\":\"integer\"}}},\"AreaInfo\":{\"type\":\"object\",\"required\":[\"zip_code\",\"phlebotomy\",\"central_labs\"],\"properties\":{\"zip_code\":{\"type\":\"string\"},\"phlebotomy\":{\"$ref\":\"#/components/schemas/PhlebotomyAreaInfo\"},\"central_labs\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/PscAreaInfo\"}}}},\"LabLocationMetadata\":{\"type\":\"object\",\"required\":[\"name\",\"state\",\"city\",\"zip_code\",\"first_line\"],\"properties\":{\"name\":{\"type\":\"string\"},\"state\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"},\"zip_code\":{\"type\":\"string\"},\"first_line\":{\"type\":\"string\"},\"second_line\":{\"type\":[\"string\",\"null\"]},\"phone_number\":{\"type\":[\"string\",\"null\"]},\"fax_number\":{\"type\":[\"string\",\"null\"]},\"hours\":{\"type\":[\"object\",\"null\"],\"additionalProperties\":true}}},\"ClientFacingLabLocation\":{\"type\":\"object\",\"required\":[\"metadata\",\"distance\",\"site_code\",\"supported_bill_types\",\"location\",\"capabilities\"],\"properties\":{\"metadata\":{\"$ref\":\"#/components/schemas/LabLocationMetadata\"},\"distance\":{\"type\":\"number\"},\"site_code\":{\"type\":\"string\"},\"supported_bill_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Billing\"}},\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"capabilities\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}},\"PscInfo\":{\"type\":\"object\",\"required\":[\"lab_id\",\"slug\",\"patient_service_centers\"],\"properties\":{\"lab_id\":{\"type\":\"integer\"},\"slug\":{\"type\":\"string\"},\"patient_service_centers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabLocation\"}}}},\"OrderTopLevelStatus\":{\"type\":\"string\",\"enum\":[\"received\",\"collecting_sample\",\"sample_with_lab\",\"completed\",\"cancelled\",\"failed\"]},\"OrderLowLevelStatus\":{\"type\":\"string\",\"enum\":[\"ordered\",\"requisition_created\",\"requisition_bypassed\",\"transit_customer\",\"out_for_delivery\",\"with_customer\",\"transit_lab\",\"delivered_to_lab\",\"completed\",\"failure_to_deliver_to_lab\",\"failure_to_deliver_to_customer\",\"problem_in_transit_lab\",\"problem_in_transit_customer\",\"sample_error\",\"appointment_scheduled\",\"appointment_cancelled\",\"appointment_pending\",\"draw_completed\",\"cancelled\",\"lost\",\"do_not_process\",\"partial_results\",\"awaiting_registration\",\"registered\",\"redraw_available\",\"corrected\",\"lab_processing_blocked\"]},\"OrderStatus\":{\"type\":\"string\",\"enum\":[\"received.walk_in_test.ordered\",\"received.walk_in_test.requisition_created\",\"received.walk_in_test.requisition_bypassed\",\"completed.walk_in_test.completed\",\"sample_with_lab.walk_in_test.partial_results\",\"failed.walk_in_test.sample_error\",\"cancelled.walk_in_test.cancelled\",\"collecting_sample.walk_in_test.appointment_pending\",\"collecting_sample.walk_in_test.appointment_scheduled\",\"collecting_sample.walk_in_test.appointment_cancelled\",\"collecting_sample.walk_in_test.redraw_available\",\"received.at_home_phlebotomy.ordered\",\"received.at_home_phlebotomy.requisition_created\",\"received.at_home_phlebotomy.requisition_bypassed\",\"collecting_sample.at_home_phlebotomy.appointment_pending\",\"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\"collecting_sample.at_home_phlebotomy.draw_completed\",\"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\"completed.at_home_phlebotomy.completed\",\"sample_with_lab.at_home_phlebotomy.partial_results\",\"cancelled.at_home_phlebotomy.cancelled\",\"failed.at_home_phlebotomy.sample_error\",\"received.testkit.ordered\",\"received.testkit.awaiting_registration\",\"received.testkit.requisition_created\",\"received.testkit.requisition_bypassed\",\"received.testkit.registered\",\"collecting_sample.testkit.transit_customer\",\"collecting_sample.testkit.out_for_delivery\",\"collecting_sample.testkit.with_customer\",\"collecting_sample.testkit.transit_lab\",\"sample_with_lab.testkit.delivered_to_lab\",\"sample_with_lab.testkit.lab_processing_blocked\",\"completed.testkit.completed\",\"failed.testkit.failure_to_deliver_to_customer\",\"failed.testkit.failure_to_deliver_to_lab\",\"failed.testkit.sample_error\",\"failed.testkit.lost\",\"cancelled.testkit.cancelled\",\"cancelled.testkit.do_not_process\",\"collecting_sample.testkit.problem_in_transit_customer\",\"collecting_sample.testkit.problem_in_transit_lab\",\"received.on_site_collection.ordered\",\"received.on_site_collection.requisition_created\",\"received.on_site_collection.requisition_bypassed\",\"sample_with_lab.on_site_collection.draw_completed\",\"completed.on_site_collection.completed\",\"cancelled.on_site_collection.cancelled\",\"sample_with_lab.on_site_collection.partial_results\",\"failed.on_site_collection.sample_error\",\"completed.walk_in_test.corrected\",\"completed.at_home_phlebotomy.corrected\",\"completed.on_site_collection.corrected\",\"completed.testkit.corrected\"]},\"OrderStatusDetail\":{\"type\":\"string\",\"enum\":[\"fulfillment_error\",\"date_of_collection_unspecified\",\"demographic_information_unspecified\",\"demographic_information_mismatch\",\"sample_quantity_not_sufficient\",\"sample_contaminated\",\"sample_stability_exceeded\",\"sample_hemolyzed\",\"sample_improper_collection\"]},\"OrderTransactionStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"completed\",\"cancelled\"]},\"ClientFacingOrderEvent\":{\"type\":\"object\",\"required\":[\"id\",\"created_at\",\"status\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderStatus\"},\"status_detail\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderStatusDetail\"},{\"type\":\"null\"}]}}},\"ShippingAddress\":{\"type\":\"object\",\"required\":[\"receiver_name\",\"first_line\",\"city\",\"state\",\"zip\",\"country\",\"phone_number\"],\"properties\":{\"receiver_name\":{\"type\":\"string\"},\"first_line\":{\"type\":\"string\"},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\"},\"state\":{\"type\":\"string\"},\"zip\":{\"type\":\"string\"},\"country\":{\"type\":\"string\"},\"phone_number\":{\"type\":\"string\"}}},\"ClientFacingPhysician\":{\"type\":\"object\",\"required\":[\"first_name\",\"last_name\",\"npi\"],\"properties\":{\"first_name\":{\"type\":\"string\"},\"last_name\":{\"type\":\"string\"},\"npi\":{\"type\":\"string\"}}},\"ClientFacingShipment\":{\"type\":\"object\",\"required\":[\"id\",\"outbound_tracking_number\",\"outbound_tracking_url\",\"inbound_tracking_number\",\"inbound_tracking_url\",\"outbound_courier\",\"inbound_courier\",\"notes\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"outbound_tracking_number\":{\"type\":[\"string\",\"null\"]},\"outbound_tracking_url\":{\"type\":[\"string\",\"null\"]},\"inbound_tracking_number\":{\"type\":[\"string\",\"null\"]},\"inbound_tracking_url\":{\"type\":[\"string\",\"null\"]},\"outbound_courier\":{\"type\":[\"string\",\"null\"]},\"inbound_courier\":{\"type\":[\"string\",\"null\"]},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingTestkitOrder\":{\"type\":\"object\",\"required\":[\"id\",\"shipment\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"shipment\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingShipment\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingWalkInOrder\":{\"type\":\"object\",\"required\":[\"id\",\"appointment_id\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"appointment_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingTestKitOrderDetails\":{\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"testkit\",\"walk_in_test\",\"at_home_phlebotomy\",\"on_site_collection\"]},\"data\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingTestkitOrder\"},{\"$ref\":\"#/components/schemas/ClientFacingWalkInOrder\"},{\"type\":\"null\"}]}}},\"ClientFacingPatientDetailsCompatible\":{\"type\":\"object\",\"required\":[\"first_name\",\"last_name\",\"dob\",\"gender\",\"phone_number\",\"email\"],\"properties\":{\"first_name\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$\",\"examples\":[\"Ada\",\"Chris\",\"Maria\",\"Jun\"]},\"last_name\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$\",\"examples\":[\"Lovelace\",\"Vouga\",\"Delgado\",\"Park\"]},\"dob\":{\"type\":\"string\",\"format\":\"date-time\",\"examples\":[\"1990-06-15T00:00:00.000Z\",\"1983-02-02T00:00:00.000Z\"]},\"gender\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"male\",\"female\",\"other\",\"prefer_not_to_say\"]},\"phone_number\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^\\\\\\\\+1[2-9]\\\\\\\\d{9}$\",\"examples\":[\"+14155550123\",\"+12125550987\",\"+13105554444\"]},\"email\":{\"type\":\"string\",\"format\":\"email\",\"minLength\":1,\"examples\":[\"ada@example.com\",\"chris@example.com\",\"maria@example.com\"]}}},\"PatientAddressCompatible\":{\"type\":\"object\",\"required\":[\"first_line\",\"city\",\"state\",\"zip\",\"country\"],\"properties\":{\"receiver_name\":{\"type\":\"string\",\"default\":\"\",\"examples\":[\"Ada Lovelace\",\"Chris Vouga\"]},\"first_line\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"1 Main St\",\"450 Market St\",\"88 Kearny St\"]},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"San Diego\",\"San Francisco\",\"New York\"]},\"state\":{\"type\":\"string\",\"minLength\":1,\"enum\":[\"AL\",\"AK\",\"AZ\",\"AR\",\"CA\",\"CO\",\"CT\",\"DE\",\"FL\",\"GA\",\"HI\",\"ID\",\"IL\",\"IN\",\"IA\",\"KS\",\"KY\",\"LA\",\"ME\",\"MD\",\"MA\",\"MI\",\"MN\",\"MS\",\"MO\",\"MT\",\"NE\",\"NV\",\"NH\",\"NJ\",\"NM\",\"NY\",\"NC\",\"ND\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VT\",\"VA\",\"WA\",\"WV\",\"WI\",\"WY\"]},\"zip\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}(-\\\\\\\\d{4})?$\",\"examples\":[\"92101\",\"94105\",\"10001\"]},\"country\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"US\"]},\"access_notes\":{\"type\":[\"string\",\"null\"],\"examples\":[null]},\"phone_number\":{\"type\":[\"string\",\"null\"],\"examples\":[\"+14155550123\",null]}}},\"AoeAnswerRequest\":{\"type\":\"object\",\"required\":[\"marker_id\",\"question_id\",\"answer\"],\"properties\":{\"marker_id\":{\"type\":\"integer\",\"examples\":[2075,1975]},\"question_id\":{\"type\":\"integer\",\"examples\":[1]},\"answer\":{\"type\":\"string\",\"minLength\":1,\"examples\":[\"No\",\"Yes\"]}}},\"ClientFacingOrderInTransaction\":{\"type\":\"object\",\"required\":[\"id\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\"},\"low_level_status\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderLowLevelStatus\"},{\"type\":\"null\"}]},\"low_level_status_created_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingOrderTransaction\":{\"type\":\"object\",\"required\":[\"id\",\"status\",\"orders\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order_transaction\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderTransactionStatus\"},\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrderInTransaction\"}}}},\"OrderSummary\":{\"type\":\"object\",\"required\":[\"id\",\"last_status\",\"last_status_created_at\",\"updated_at\",\"created_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\"},\"origin\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"initial\",\"redraw\",\"recreation\"]},{\"type\":\"null\"}]},\"parent_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"last_status\":{\"$ref\":\"#/components/schemas/OrderLowLevelStatus\"},\"last_status_created_at\":{\"type\":\"string\",\"format\":\"date-time\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\"},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\"}}},\"GetOrderTransactionResponse\":{\"type\":\"object\",\"required\":[\"id\",\"team_id\",\"status\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order_transaction\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderTransactionStatus\"},\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/OrderSummary\"}}}},\"ClientFacingOrder\":{\"type\":\"object\",\"required\":[\"user_id\",\"id\",\"team_id\",\"patient_details\",\"patient_address\",\"lab_test\",\"details\",\"sample_id\",\"notes\",\"created_at\",\"updated_at\",\"events\",\"last_event\",\"health_insurance_id\",\"requisition_form_url\",\"shipping_details\",\"has_abn\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"patient_details\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingPatientDetailsCompatible\"},{\"type\":\"null\"}]},\"patient_address\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/PatientAddressCompatible\"},{\"type\":\"null\"}]},\"lab_test\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"},\"details\":{\"$ref\":\"#/components/schemas/ClientFacingTestKitOrderDetails\"},\"sample_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"events\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrderEvent\"}},\"status\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderTopLevelStatus\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"last_event\":{\"$ref\":\"#/components/schemas/ClientFacingOrderEvent\"},\"physician\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingPhysician\"},{\"type\":\"null\"}]},\"health_insurance_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"requisition_form_url\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"url\"}},\"priority\":{\"type\":\"boolean\",\"default\":false},\"shipping_details\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ShippingAddress\"},{\"type\":\"null\"}]},\"activate_by\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"passthrough\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"billing_type\":{\"type\":\"string\",\"enum\":[\"client_bill\",\"commercial_insurance\",\"patient_bill_passthrough\",\"patient_bill\",\"upfront_payment\"],\"default\":\"client_bill\"},\"icd_codes\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"null\"}]},\"has_abn\":{\"type\":\"boolean\"},\"interpretation\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"normal\",\"abnormal\",\"critical\",\"unknown\"]},{\"type\":\"null\"}]},\"has_missing_results\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"null\"}]},\"expected_result_by_date\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"worst_case_result_by_date\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"origin\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"initial\",\"redraw\",\"recreation\"]},{\"type\":\"null\"}]},\"order_transaction\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingOrderTransaction\"},{\"type\":\"null\"}]}}},\"OrderSetRequest\":{\"type\":\"object\",\"required\":[\"lab_test_ids\"],\"properties\":{\"lab_test_ids\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}}},\"CreateOrderRequest\":{\"type\":\"object\",\"required\":[\"user_id\",\"patient_details\",\"patient_address\",\"order_set\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}},\"patient_details\":{\"$ref\":\"#/components/schemas/ClientFacingPatientDetailsCompatible\"},\"patient_address\":{\"$ref\":\"#/components/schemas/PatientAddressCompatible\"},\"order_set\":{\"$ref\":\"#/components/schemas/OrderSetRequest\"},\"clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"passthrough\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"collection_method\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"},\"lab_account_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"idempotency_key\":{\"type\":[\"string\",\"null\"]},\"idempotency_error\":{\"type\":[\"string\",\"null\"]},\"aoe_answers\":{\"type\":[\"array\",\"null\"],\"items\":{\"$ref\":\"#/components/schemas/AoeAnswerRequest\"}}}},\"PostOrderResponse\":{\"type\":\"object\",\"required\":[\"order\",\"status\",\"message\"],\"properties\":{\"order\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"},\"status\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}},\"ResultType\":{\"type\":\"string\",\"enum\":[\"numeric\",\"range\",\"comment\",\"coded_value\"]},\"ParentBiomarkerData\":{\"type\":\"object\",\"required\":[\"marker_id\",\"name\",\"slug\"],\"properties\":{\"marker_id\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"provider_id\":{\"type\":[\"string\",\"null\"]}}},\"BiomarkerResult\":{\"type\":\"object\",\"required\":[\"name\",\"result\",\"type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\",\"default\":\"\"},\"value\":{\"anyOf\":[{\"type\":\"number\"},{\"type\":\"null\"}]},\"result\":{\"type\":\"string\"},\"type\":{\"$ref\":\"#/components/schemas/ResultType\"},\"unit\":{\"type\":[\"string\",\"null\"]},\"timestamp\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"notes\":{\"type\":[\"string\",\"null\"]},\"reference_range\":{\"type\":[\"string\",\"null\"]},\"min_range_value\":{\"type\":[\"number\",\"null\"]},\"max_range_value\":{\"type\":[\"number\",\"null\"]},\"is_above_max_range\":{\"type\":[\"boolean\",\"null\"]},\"is_below_min_range\":{\"type\":[\"boolean\",\"null\"]},\"interpretation\":{\"type\":\"string\",\"default\":\"normal\"},\"source_interpretation\":{\"type\":\"string\",\"default\":\"\"},\"loinc\":{\"type\":[\"string\",\"null\"]},\"loinc_slug\":{\"type\":[\"string\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"source_markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ParentBiomarkerData\"}},{\"type\":\"null\"}]},\"performing_laboratory\":{\"type\":[\"string\",\"null\"]},\"source_sample_id\":{\"type\":[\"string\",\"null\"]}}},\"FailureType\":{\"type\":\"string\",\"enum\":[\"quantity_not_sufficient_failure\",\"collection_process_failure\",\"drop_off_failure\",\"internal_lab_failure\",\"order_entry_failure\",\"non_failure\",\"unknown_failure\",\"patient_condition_failure\",\"missing_result_calc_failure\",\"missing_demo_aoe_calc_failure\",\"insufficient_volume\"]},\"MissingBiomarkerResult\":{\"type\":\"object\",\"required\":[\"name\",\"slug\",\"inferred_failure_type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"inferred_failure_type\":{\"$ref\":\"#/components/schemas/FailureType\"},\"note\":{\"type\":[\"string\",\"null\"]},\"loinc\":{\"type\":[\"string\",\"null\"]},\"loinc_slug\":{\"type\":[\"string\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"source_markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ParentBiomarkerData\"}},{\"type\":\"null\"}]}}},\"SampleData\":{\"type\":\"object\",\"properties\":{\"sample_id\":{\"type\":[\"string\",\"null\"]},\"control_number\":{\"type\":[\"string\",\"null\"]},\"date_collected\":{\"type\":[\"string\",\"null\"]},\"date_received\":{\"type\":[\"string\",\"null\"]},\"date_reported\":{\"type\":[\"string\",\"null\"]},\"performing_laboratories\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"clinical_information\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}}},\"LabResultsMetadata\":{\"type\":\"object\",\"required\":[\"age\",\"dob\",\"patient\",\"date_reported\",\"specimen_number\"],\"properties\":{\"age\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"dob\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"clia_#\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"patient\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"provider\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"laboratory\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"date_reported\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"date_collected\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"specimen_number\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"date_received\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"type\":\"string\",\"default\":\"final\"},\"interpretation\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"patient_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"account_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"id\"}}}},\"LabResultsRaw\":{\"type\":\"object\",\"required\":[\"metadata\",\"results\"],\"properties\":{\"metadata\":{\"$ref\":\"#/components/schemas/LabResultsMetadata\"},\"results\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/BiomarkerResult\"}},{\"type\":\"object\",\"additionalProperties\":true}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"missing_results\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/MissingBiomarkerResult\"}},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"sample_information\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/SampleData\"}},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"order_transaction\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingOrderTransaction\"},{\"type\":\"null\"}]}}},\"SimulationFlags\":{\"type\":\"object\",\"properties\":{\"interpretation\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"normal\",\"abnormal\",\"critical\",\"unknown\"]},{\"type\":\"null\"}]},\"result_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ResultType\"}},\"has_missing_results\":{\"type\":\"boolean\"}}},\"GetOrdersResponse\":{\"type\":\"object\",\"required\":[\"orders\"],\"properties\":{\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"}},\"total\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]},\"page\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]},\"size\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]}}},\"HTTPValidationError\":{\"type\":\"object\",\"properties\":{\"detail\":{\"title\":\"Detail\"}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"get_teams_users_v2_user_get\" | \"create_user_v2_user_post\" | \"get_user_v2_user__user_id__get\" | \"delete_user_v2_user__user_id__delete\" | \"patch_user_v2_user__user_id__patch\" | \"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\" | \"patch_user_info_v2_user__user_id__info_patch\" | \"get_latest_user_info_user_v2_user__user_id__info_latest_get\" | \"get_paginated_lab_tests_for_team_v3_lab_test_get\" | \"get_team_lab_accounts_v3_lab_test_lab_account_get\" | \"get_lab_tests_for_team_v3_lab_tests_get\" | \"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\" | \"get_labs_v3_lab_tests_labs_get\" | \"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\" | \"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\" | \"create_order_v3_order_post\" | \"get_area_info_v3_order_area_info_get\" | \"get_psc_info_v3_order_psc_info_get\" | \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\" | \"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\" | \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\" | \"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\" | \"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\" | \"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\" | \"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\" | \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\" | \"get_psc_appointment_v3_order__order_id__psc_appointment_get\" | \"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\" | \"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\" | \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\" | \"get_order_v3_order__order_id__get\" | \"cancel_order_v3_order__order_id__cancel_post\" | \"simulate_order_v3_order__order_id__test_post\" | \"get_result_raw_v3_order__order_id__result_get\" | \"get_result_metadata_v3_order__order_id__result_metadata_get\" | \"get_result_pdf_v3_order__order_id__result_pdf_get\" | \"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\" | \"get_orders_v3_orders_get\" | \"get_order_transaction_v3_order_transaction__transaction_id__get\" | \"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"\nexport type SupportedOperationId = \"get_teams_users_v2_user_get\" | \"create_user_v2_user_post\" | \"get_user_v2_user__user_id__get\" | \"delete_user_v2_user__user_id__delete\" | \"patch_user_v2_user__user_id__patch\" | \"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\" | \"patch_user_info_v2_user__user_id__info_patch\" | \"get_latest_user_info_user_v2_user__user_id__info_latest_get\" | \"get_paginated_lab_tests_for_team_v3_lab_test_get\" | \"get_team_lab_accounts_v3_lab_test_lab_account_get\" | \"get_lab_tests_for_team_v3_lab_tests_get\" | \"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\" | \"get_labs_v3_lab_tests_labs_get\" | \"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\" | \"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\" | \"create_order_v3_order_post\" | \"get_area_info_v3_order_area_info_get\" | \"get_psc_info_v3_order_psc_info_get\" | \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\" | \"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\" | \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\" | \"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\" | \"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\" | \"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\" | \"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\" | \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\" | \"get_psc_appointment_v3_order__order_id__psc_appointment_get\" | \"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\" | \"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\" | \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\" | \"get_order_v3_order__order_id__get\" | \"cancel_order_v3_order__order_id__cancel_post\" | \"simulate_order_v3_order__order_id__test_post\" | \"get_result_raw_v3_order__order_id__result_get\" | \"get_result_metadata_v3_order__order_id__result_metadata_get\" | \"get_result_pdf_v3_order__order_id__result_pdf_get\" | \"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\" | \"get_orders_v3_orders_get\" | \"get_order_transaction_v3_order_transaction__transaction_id__get\" | \"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"\nexport const operationIds = [\"get_teams_users_v2_user_get\",\"create_user_v2_user_post\",\"get_user_v2_user__user_id__get\",\"delete_user_v2_user__user_id__delete\",\"patch_user_v2_user__user_id__patch\",\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"patch_user_info_v2_user__user_id__info_patch\",\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"get_lab_tests_for_team_v3_lab_tests_get\",\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"get_labs_v3_lab_tests_labs_get\",\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"create_order_v3_order_post\",\"get_area_info_v3_order_area_info_get\",\"get_psc_info_v3_order_psc_info_get\",\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"get_order_v3_order__order_id__get\",\"cancel_order_v3_order__order_id__cancel_post\",\"simulate_order_v3_order__order_id__test_post\",\"get_result_raw_v3_order__order_id__result_get\",\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"get_orders_v3_orders_get\",\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"] as const\nexport const supportedOperationIds = [\"get_teams_users_v2_user_get\",\"create_user_v2_user_post\",\"get_user_v2_user__user_id__get\",\"delete_user_v2_user__user_id__delete\",\"patch_user_v2_user__user_id__patch\",\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"patch_user_info_v2_user__user_id__info_patch\",\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"get_lab_tests_for_team_v3_lab_tests_get\",\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"get_labs_v3_lab_tests_labs_get\",\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"create_order_v3_order_post\",\"get_area_info_v3_order_area_info_get\",\"get_psc_info_v3_order_psc_info_get\",\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"get_order_v3_order__order_id__get\",\"cancel_order_v3_order__order_id__cancel_post\",\"simulate_order_v3_order__order_id__test_post\",\"get_result_raw_v3_order__order_id__result_get\",\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"get_orders_v3_orders_get\",\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"] as const\n", "/** Lab-results surface: raw results, metadata, and deterministic PDF artifacts. */\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport { applySimulateTransition, requireOrder } from \"./scheduling.js\"\nimport type { JunctionState, OrderRecord } from \"./state.js\"\n\nconst RESULT_TYPES = [\"numeric\", \"range\", \"comment\", \"coded_value\"] as const\ntype ResultType = (typeof RESULT_TYPES)[number]\n\nconst INTERPRETATIONS = [\"normal\", \"abnormal\", \"critical\", \"unknown\"] as const\ntype Interpretation = (typeof INTERPRETATIONS)[number]\n\n/** Statuses from which results exist (sample has been drawn and reported). */\nconst RESULT_READY_STATUSES = [\"sample_with_lab\", \"completed\"]\n\nconst resultsReady = (order: OrderRecord): boolean =>\n RESULT_READY_STATUSES.some((prefix) => order.status.startsWith(prefix)) ||\n order.last_event.status.endsWith(\"draw_completed\")\n\nconst parseInterpretation = (value: unknown): Interpretation =>\n INTERPRETATIONS.includes(value as Interpretation) ? (value as Interpretation) : \"normal\"\n\nconst pickResultType = (value: unknown, index: number): ResultType => {\n if (Array.isArray(value) && value.length > 0) {\n const entry = value[index % value.length]\n if (typeof entry === \"string\" && RESULT_TYPES.includes(entry as ResultType))\n return entry as ResultType\n }\n return \"numeric\"\n}\n\nconst numericValueFor = (slug: string): number => {\n let hash = 0\n for (let i = 0; i < slug.length; i++) hash = (hash * 31 + slug.charCodeAt(i)) % 1000\n return Math.round((40 + (hash % 160)) * 10) / 10\n}\n\ntype BiomarkerLine = {\n name: string\n slug: string\n result: string\n type: ResultType\n value: number | null\n unit: string | null\n timestamp: string\n reference_range: string | null\n interpretation: Interpretation\n performing_laboratory: string\n source_sample_id: string | null\n notes: string | null\n string_value: string | null\n coded_value: string | null\n low_value: number | null\n high_value: number | null\n provider_id: string | null\n}\n\nconst biomarkerLines = (order: OrderRecord, flags: SimulationFlagsState): BiomarkerLine[] => {\n const collected = order.last_event.created_at\n return (order.lab_test.markers ?? []).map((marker, index) => {\n const type = pickResultType(flags.resultTypes, index)\n const base: BiomarkerLine = {\n name: marker.name,\n slug: marker.slug,\n result: marker.slug,\n type,\n value: null,\n unit: marker.unit,\n timestamp: collected,\n reference_range: null,\n interpretation: flags.interpretation,\n performing_laboratory: \"Mockingbird Central Lab\",\n source_sample_id: order.sample_id,\n notes: null,\n string_value: null,\n coded_value: null,\n low_value: null,\n high_value: null,\n provider_id: marker.provider_id,\n }\n if (type === \"numeric\") {\n base.value = numericValueFor(marker.slug)\n base.result = String(base.value)\n base.reference_range = \"0-200\"\n base.low_value = 0\n base.high_value = 200\n } else if (type === \"range\") {\n base.low_value = 0\n base.high_value = 200\n base.value = numericValueFor(marker.slug)\n base.reference_range = \"0-200\"\n base.result = `${base.low_value}-${base.high_value}`\n } else if (type === \"comment\") {\n base.string_value = \"No abnormal findings reported.\"\n base.result = base.string_value\n } else {\n base.coded_value = flags.interpretation === \"normal\" ? \"N\" : \"A\"\n base.result = base.coded_value\n }\n return base\n })\n}\n\nexport type SimulationFlagsState = {\n interpretation: Interpretation\n resultTypes: readonly string[] | null\n hasMissingResults: boolean\n}\n\nconst flagsOf = (order: OrderRecord): SimulationFlagsState => {\n const raw = order.result_types\n const resultTypes =\n Array.isArray(raw) && raw.length > 0\n ? raw.filter((entry): entry is string => typeof entry === \"string\")\n : null\n return {\n interpretation: parseInterpretation(order.interpretation),\n resultTypes,\n hasMissingResults: order.has_missing_results === true,\n }\n}\n\nconst ageFromDob = (dob: string, nowIso: string) => {\n const born = Date.parse(`${dob}T00:00:00.000Z`)\n const now = Date.parse(nowIso)\n if (!Number.isFinite(born) || !Number.isFinite(now) || now < born) return \"0\"\n const years = Math.floor((now - born) / (365.25 * 24 * 60 * 60 * 1000))\n return String(Math.max(0, years))\n}\n\nconst metadataOf = (order: OrderRecord, _userClient: string) => {\n const details = order.patient_details ?? {}\n const first =\n typeof details.first_name === \"string\" && details.first_name.length > 0\n ? details.first_name\n : \"Patient\"\n const last =\n typeof details.last_name === \"string\" && details.last_name.length > 0 ? details.last_name : \"\"\n const dob = typeof details.dob === \"string\" && details.dob.length > 0 ? details.dob : \"1990-01-01\"\n const labName =\n order.lab_test.lab && typeof order.lab_test.lab.name === \"string\"\n ? order.lab_test.lab.name\n : \"Labcorp\"\n const reportedAt = order.last_event.created_at\n return {\n age: ageFromDob(dob, reportedAt),\n dob,\n patient: `${first} ${last}`.trim(),\n date_reported: reportedAt,\n specimen_number: opaqueToken(`junction:specimen:${order.id}`, 24),\n status: \"final\",\n laboratory: labName,\n provider: order.physician\n ? `${order.physician.first_name} ${order.physician.last_name}`.trim()\n : null,\n interpretation: order.interpretation,\n patient_id: order.user_id,\n account_id: null,\n date_collected: reportedAt,\n date_received: reportedAt,\n \"clia_#\": null,\n }\n}\n\n/** Minimal single-page PDF with a deterministic title; valid enough for byte-shape checks. */\nconst deterministicPdf = (title: string): Uint8Array => {\n const text = `BT /F1 14 Tf 72 720 Td (${title}) Tj ET`\n const objects = [\n \"<< /Type /Catalog /Pages 2 0 R >>\",\n \"<< /Type /Pages /Kids [3 0 R] /Count 1 >>\",\n \"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\",\n `<< /Length ${text.length} >>\\nstream\\n${text}\\nendstream`,\n \"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\",\n ]\n let body = \"%PDF-1.4\\n\"\n const offsets: number[] = []\n objects.forEach((entry, index) => {\n offsets.push(body.length)\n body += `${index + 1} 0 obj\\n${entry}\\nendobj\\n`\n })\n const xrefStart = body.length\n body += `xref\\n0 ${objects.length + 1}\\n0000000000 65535 f \\n`\n for (const offset of offsets) body += `${String(offset).padStart(10, \"0\")} 00000 n \\n`\n body += `trailer\\n<< /Size ${objects.length + 1} /Root 1 0 R >>\\nstartxref\\n${xrefStart}\\n%%EOF\\n`\n return new TextEncoder().encode(body)\n}\n\nfunction resultsNotAvailable(orderId: string): never {\n throw new HttpError(404, {\n detail: `Results are not available for order - ${orderId}. Did you receive a webhook for this order?`,\n })\n}\n\nexport const resultsHandlers = (state: JunctionState) => ({\n get_result_raw_v3_order__order_id__result_get: async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const user = state.users.get(order.user_id)\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const flags = flagsOf(order)\n const fixture = state.resultFixtures.get(order.id)\n const results = fixture?.results ?? biomarkerLines(order, flags)\n const missing =\n fixture?.missing_results !== undefined\n ? fixture.missing_results\n : flags.hasMissingResults\n ? [\n {\n name: (order.lab_test.markers ?? [])[0]?.name ?? \"Unknown marker\",\n slug: (order.lab_test.markers ?? [])[0]?.slug ?? \"unknown-marker\",\n inferred_failure_type: \"quantity_not_sufficient_failure\",\n note: \"Specimen quantity was not sufficient to run this marker.\",\n loinc: null,\n loinc_slug: null,\n provider_id: (order.lab_test.markers ?? [])[0]?.provider_id ?? null,\n source_markers: null,\n },\n ]\n : null\n return jsonRes(200, {\n metadata: metadataOf(order, user?.client_user_id ?? order.user_id),\n results,\n missing_results: missing,\n sample_information: {\n [order.sample_id ?? opaqueToken(`junction:sample:${order.id}`, 16)]: {\n sample_id: order.sample_id ?? opaqueToken(`junction:sample:${order.id}`, 16),\n control_number: order.sample_id,\n date_collected: order.last_event.created_at,\n date_received: order.last_event.created_at,\n date_reported: order.last_event.created_at,\n performing_laboratories: null,\n clinical_information: null,\n },\n },\n order_transaction: order.order_transaction,\n })\n },\n\n get_result_metadata_v3_order__order_id__result_metadata_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const user = state.users.get(order.user_id)\n return jsonRes(200, metadataOf(order, user?.client_user_id ?? order.user_id))\n },\n\n get_result_pdf_v3_order__order_id__result_pdf_get: async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const fixturePdf = state.resultFixtures.get(order.id)?.pdf_base64\n const bytes =\n fixturePdf !== undefined\n ? Uint8Array.from(atob(fixturePdf), (char) => char.charCodeAt(0))\n : deterministicPdf(`Lab results ${order.id}`)\n return new Response(bytes as unknown as BodyInit, {\n status: 200,\n headers: { \"content-type\": \"application/pdf\" },\n })\n },\n\n get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const bytes = deterministicPdf(`Requisition ${order.id}`)\n return new Response(bytes as unknown as BodyInit, {\n status: 200,\n headers: { \"content-type\": \"application/pdf\" },\n })\n },\n})\n\nexport { applySimulateTransition }\n", "import { addressFromAvailabilityRequest } from \"./scheduling.js\"\nimport type {\n AppointmentModality,\n AppointmentRecord,\n ExpectedResult,\n GetCacheEntry,\n JunctionState,\n LabTestRecord,\n OrderRecord,\n UserInfoRecord,\n UserRecord,\n} from \"./state.js\"\n\nexport type SeedSource = {\n fetch: (request: Request) => Promise<Response>\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport type SeedObservations = {\n getCache?: ReadonlyMap<string, GetCacheEntry>\n}\n\nexport type SeedReport = {\n users: number\n orders: number\n appointments: number\n catalogTests: number\n labs: number\n cacheEntries: number\n}\n\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\n/**\n * Parse the availability POST body embedded in an observation cache key\n * (`\"<METHOD> <path>?<query> <JSON body>\"`).\n */\nconst parseAvailabilityRequestBody = (cacheKey: string): Record<string, unknown> | undefined => {\n const jsonStart = cacheKey.indexOf(\" {\")\n if (jsonStart === -1) return undefined\n try {\n const parsed: unknown = JSON.parse(cacheKey.slice(jsonStart + 1))\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return undefined\n }\n return undefined\n}\n\n/**\n * Vital echoes the availability request address on book/reschedule. Re-stamp every\n * booking-key record hydrated from one availability observation so its address matches\n * the availability request \u2014 the oracle's behavior for both modalities.\n */\nconst alignBookingKeyAddresses = (\n state: JunctionState,\n body: unknown,\n requestBody: Record<string, unknown>,\n zip: string,\n modalityHint?: AppointmentModality,\n): void => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return\n const root = body as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n const slots = Array.isArray((day as Record<string, unknown>)?.slots)\n ? ((day as Record<string, unknown>).slots as unknown[])\n : [day]\n for (const slot of slots) {\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const bookingKey = (slot as Record<string, unknown>).booking_key\n if (typeof bookingKey !== \"string\" || bookingKey === \"\") continue\n const record = state.bookingKeys.get(bookingKey)\n if (!record || (modalityHint !== undefined && record.modality !== modalityHint)) continue\n record.address = addressFromAvailabilityRequest(requestBody, zip)\n state.bookingKeys.update(bookingKey, record)\n }\n }\n}\n\nconst request = async (\n source: SeedSource,\n method: string,\n path: string,\n init: RequestInit = {},\n): Promise<Response> => {\n const url = new URL(path, source.baseUrl.endsWith(\"/\") ? source.baseUrl : `${source.baseUrl}/`)\n const headers = new Headers(init.headers)\n for (const [name, value] of Object.entries(source.headers)) headers.set(name, value)\n return source.fetch(new Request(url, { ...init, method, headers }))\n}\n\nconst readJson = async (response: Response): Promise<unknown> => {\n if (response.status === 204) return null\n const text = await response.text()\n if (text.trim() === \"\") return null\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined\n\nconst mapUser = (value: unknown): UserRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const userId = asString(record.user_id)\n const clientUserId = asString(record.client_user_id)\n if (!userId || !clientUserId) return undefined\n return {\n user_id: userId,\n team_id: asString(record.team_id) ?? \"00000000-0000-4000-8000-000000000000\",\n client_user_id: clientUserId,\n created_on: asString(record.created_on) ?? new Date(0).toISOString(),\n connected_sources: Array.isArray(record.connected_sources) ? record.connected_sources : [],\n fallback_time_zone:\n typeof record.fallback_time_zone === \"object\" && record.fallback_time_zone !== null\n ? (record.fallback_time_zone as UserRecord[\"fallback_time_zone\"])\n : null,\n fallback_birth_date:\n typeof record.fallback_birth_date === \"object\" && record.fallback_birth_date !== null\n ? (record.fallback_birth_date as UserRecord[\"fallback_birth_date\"])\n : null,\n ingestion_start: asString(record.ingestion_start) ?? null,\n ingestion_end: asString(record.ingestion_end) ?? null,\n }\n}\n\nexport const mapLabTest = (value: unknown): LabTestRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n if (!id) return undefined\n return clone(record) as LabTestRecord\n}\n\nconst mapOrder = (value: unknown): OrderRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n const userId = asString(record.user_id)\n if (!id || !userId) return undefined\n return clone(record) as OrderRecord\n}\n\nconst mapAppointment = (\n value: unknown,\n orderId: string,\n userId: string,\n): AppointmentRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n if (!id) return undefined\n return {\n ...(clone(record) as AppointmentRecord),\n id,\n order_id: asString(record.order_id) ?? orderId,\n user_id: asString(record.user_id) ?? userId,\n }\n}\n\nconst demographicsFromOrder = (order: OrderRecord): UserInfoRecord => {\n const details =\n order.patient_details && typeof order.patient_details === \"object\"\n ? (order.patient_details as Record<string, unknown>)\n : {}\n const address =\n order.patient_address && typeof order.patient_address === \"object\"\n ? (order.patient_address as Record<string, unknown>)\n : {}\n return {\n first_name: details.first_name ?? null,\n last_name: details.last_name ?? null,\n dob: details.dob ?? null,\n gender: details.gender ?? null,\n phone_number: details.phone_number ?? null,\n email: details.email ?? null,\n gender_identity: null,\n sexual_orientation: null,\n race: null,\n ethnicity: null,\n medical_proxy: null,\n address: {\n first_line: address.first_line ?? \"\",\n second_line: typeof address.second_line === \"string\" ? address.second_line : \"\",\n country: address.country ?? \"\",\n zip: address.zip ?? \"\",\n city: address.city ?? \"\",\n state: address.state ?? \"\",\n access_notes: null,\n },\n }\n}\n\nconst ensureUserInfoForOrder = async (\n state: JunctionState,\n source: SeedSource,\n order: OrderRecord,\n): Promise<void> => {\n if (state.userInfo.get(order.user_id)) return\n const infoResponse = await request(source, \"GET\", `/v2/user/${order.user_id}/info/latest`)\n if (infoResponse.ok) {\n const info = asRecord(await readJson(infoResponse))\n if (info) {\n state.userInfo.insert(order.user_id, info as UserInfoRecord)\n return\n }\n }\n state.userInfo.insert(order.user_id, demographicsFromOrder(order))\n}\n\nconst expectedFromMarkers = (labTest: LabTestRecord): ExpectedResult[] => {\n const markers = labTest.markers ?? []\n return markers.map((marker) => ({\n id: marker.id,\n name: marker.name,\n slug: marker.slug,\n lab_id: marker.lab_id,\n provider_id: marker.provider_id,\n required: true,\n loinc: null,\n }))\n}\n\nexport const expectedFromMarkersResponse = async (\n source: SeedSource,\n test: LabTestRecord,\n): Promise<ExpectedResult[]> => {\n const markersResponse = await request(source, \"GET\", `/v3/lab_tests/${test.id}/markers`)\n if (!markersResponse.ok) return expectedFromMarkers(test)\n const markersPayload = asRecord(await readJson(markersResponse))\n const markers = markersPayload?.markers\n if (!Array.isArray(markers) || markers.length === 0) return expectedFromMarkers(test)\n const expected: ExpectedResult[] = []\n const cleaned: NonNullable<LabTestRecord[\"markers\"]> = []\n for (const entry of markers) {\n const record = asRecord(entry)\n if (!record) continue\n const expectedField = record.expected_results\n if (Array.isArray(expectedField) && expectedField.length > 0 && expected.length === 0) {\n for (const item of expectedField) {\n const expectedRecord = asRecord(item)\n if (expectedRecord) expected.push(clone(expectedRecord) as ExpectedResult)\n }\n }\n const { expected_results: _ignored, ...rest } = record\n cleaned.push(rest as NonNullable<LabTestRecord[\"markers\"]>[number])\n }\n test.markers = cleaned\n return expected.length > 0 ? expected : expectedFromMarkers(test)\n}\n\nexport const ensureLabTests = async (\n state: JunctionState,\n source: SeedSource,\n ids: readonly string[],\n): Promise<number> => {\n let added = 0\n for (const id of ids) {\n if (!id) continue\n const response = await request(source, \"GET\", `/v3/lab_tests/${id}`)\n if (!response.ok) continue\n const test = mapLabTest(await readJson(response))\n if (!test) continue\n const expected = await expectedFromMarkersResponse(source, test)\n const existed = Boolean(state.labTestById(id))\n state.upsertLabTest(test, expected)\n if (!existed) added += 1\n }\n return added\n}\n\n/**\n * Pull any warmup-registered orders that user-list seeding missed (e.g. orders whose\n * user was deleted during warmup and therefore no longer appears in `/v2/user`).\n */\nexport const ensureOrders = async (\n state: JunctionState,\n source: SeedSource,\n ids: readonly string[],\n): Promise<number> => {\n let added = 0\n for (const id of ids) {\n if (!id) continue\n const orderResponse = await request(source, \"GET\", `/v3/order/${id}`)\n if (!orderResponse.ok) continue\n const order = mapOrder(await readJson(orderResponse))\n if (!order) continue\n if (!state.users.has(order.user_id) && !state.deletedUsers.has(order.user_id)) {\n const userResponse = await request(source, \"GET\", `/v2/user/${order.user_id}`)\n if (userResponse.ok) {\n const user = mapUser(await readJson(userResponse))\n if (user) state.insertUser(user)\n } else {\n state.deletedUsers.insert(order.user_id, { user_id: order.user_id })\n }\n }\n const existed = Boolean(state.orders.get(id))\n if (existed) state.orders.update(id, order)\n else state.insertOrder(order)\n if (order.lab_test?.id) state.upsertLabTest(order.lab_test)\n await ensureUserInfoForOrder(state, source, order)\n if (!existed) added += 1\n }\n return added\n}\n\nexport const seedFrom = async (\n state: JunctionState,\n source: SeedSource,\n observations?: SeedObservations,\n): Promise<SeedReport> => {\n let cacheEntries = 0\n if (observations?.getCache) {\n state.installGetCache(observations.getCache)\n cacheEntries = observations.getCache.size\n const nowMs = Date.now()\n for (const [key, entry] of observations.getCache) {\n if (!key.toLowerCase().includes(\"availability\")) continue\n const zipMatch = key.match(/\"zip_code\":\"(\\d{5})\"/)\n const modality = key.toLowerCase().includes(\"psc\")\n ? (\"patient_service_center\" as const)\n : key.toLowerCase().includes(\"phlebotomy\")\n ? (\"phlebotomy\" as const)\n : undefined\n const zip = zipMatch?.[1] ?? \"85004\"\n state.hydrateBookingKeysFromAvailability(entry.body, nowMs, zip, modality)\n // Vital echoes the availability request address on book/reschedule. Align the\n // freshly hydrated oracle-key records with the request address embedded in the\n // observation cache key so book/reschedule render the same address as the\n // oracle instead of the hydrate placeholder.\n const requestBody = parseAvailabilityRequestBody(key)\n if (requestBody) alignBookingKeyAddresses(state, entry.body, requestBody, zip, modality)\n }\n }\n\n const labTests: LabTestRecord[] = []\n let cursor: string | null = null\n for (;;) {\n const path =\n cursor === null ? \"/v3/lab_test\" : `/v3/lab_test?next_cursor=${encodeURIComponent(cursor)}`\n const response = await request(source, \"GET\", path)\n if (!response.ok) break\n const payload = asRecord(await readJson(response))\n const data = payload?.data\n if (Array.isArray(data)) {\n for (const entry of data) {\n const test = mapLabTest(entry)\n if (test) labTests.push(test)\n }\n }\n cursor = asString(payload?.next_cursor) ?? null\n if (cursor === null) break\n }\n\n const labsResponse = await request(source, \"GET\", \"/v3/lab_tests/labs\")\n const labsPayload = labsResponse.ok ? await readJson(labsResponse) : []\n const labs = Array.isArray(labsPayload)\n ? labsPayload.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n : []\n\n const expectedResults: Record<string, ExpectedResult[]> = {}\n for (const test of labTests) {\n expectedResults[test.id] = await expectedFromMarkersResponse(source, test)\n }\n\n if (labTests.length > 0 || labs.length > 0) {\n const currentTests = state.listLabTests()\n const currentLabs = state.listLabs()\n const currentExpected = Object.fromEntries(\n currentTests.map((test) => [test.id, state.expectedResultsFor(test.id)]),\n )\n state.replaceCatalog({\n labTests: labTests.length > 0 ? labTests : currentTests,\n labs: labs.length > 0 ? labs : currentLabs,\n expectedResults: Object.keys(expectedResults).length > 0 ? expectedResults : currentExpected,\n })\n }\n\n let users = 0\n let orders = 0\n let appointments = 0\n const pendingOrders: Array<{\n order: OrderRecord\n appointments: AppointmentRecord[]\n /** Position in the oracle's newest-first team-wide list \u2014 the oracle's own tie order. */\n listPosition?: number\n }> = []\n let offset = 0\n const limit = 100\n for (;;) {\n const listResponse = await request(source, \"GET\", `/v2/user?offset=${offset}&limit=${limit}`)\n if (!listResponse.ok) break\n const listPayload = asRecord(await readJson(listResponse))\n const listed = Array.isArray(listPayload?.users) ? listPayload.users : []\n if (listed.length === 0) break\n for (const entry of listed) {\n const listedUser = mapUser(entry)\n if (!listedUser) continue\n const detailResponse = await request(source, \"GET\", `/v2/user/${listedUser.user_id}`)\n const user = detailResponse.ok\n ? (mapUser(await readJson(detailResponse)) ?? listedUser)\n : listedUser\n state.insertUser(user)\n users += 1\n\n const infoResponse = await request(source, \"GET\", `/v2/user/${user.user_id}/info/latest`)\n if (infoResponse.ok) {\n const info = asRecord(await readJson(infoResponse))\n if (info) state.userInfo.insert(user.user_id, info as UserInfoRecord)\n }\n\n let page = 1\n for (;;) {\n const ordersResponse = await request(\n source,\n \"GET\",\n `/v3/orders?user_id=${encodeURIComponent(user.user_id)}&page=${page}&size=100`,\n )\n if (!ordersResponse.ok) break\n const ordersPayload = asRecord(await readJson(ordersResponse))\n const orderEntries = Array.isArray(ordersPayload?.orders)\n ? ordersPayload.orders\n : Array.isArray(ordersPayload?.data)\n ? ordersPayload.data\n : []\n if (orderEntries.length === 0) break\n for (const orderEntry of orderEntries) {\n const summary = asRecord(orderEntry)\n const orderId = asString(summary?.id) ?? asString(summary?.order_id)\n if (!orderId) continue\n const orderResponse = await request(source, \"GET\", `/v3/order/${orderId}`)\n if (!orderResponse.ok) continue\n const order = mapOrder(await readJson(orderResponse))\n if (!order) continue\n const orderAppointments: AppointmentRecord[] = []\n for (const modality of [\"phlebotomy\", \"psc\"] as const) {\n const path =\n modality === \"phlebotomy\"\n ? `/v3/order/${order.id}/phlebotomy/appointment`\n : `/v3/order/${order.id}/psc/appointment`\n const appointmentResponse = await request(source, \"GET\", path)\n if (!appointmentResponse.ok) continue\n const appointment = mapAppointment(\n await readJson(appointmentResponse),\n order.id,\n order.user_id,\n )\n if (!appointment) continue\n orderAppointments.push(appointment)\n }\n pendingOrders.push({ order, appointments: orderAppointments })\n }\n const total = typeof ordersPayload?.total === \"number\" ? ordersPayload.total : undefined\n if (total !== undefined && page * 100 >= total) break\n if (orderEntries.length < 100) break\n page += 1\n }\n }\n offset += listed.length\n if (listed.length < limit) break\n }\n\n // Team-wide order pass: /v2/user can be empty while orphan orders remain\n // (users deleted, orders retained). List payloads are full ClientFacingOrder\n // objects, so we can seed without per-id GETs.\n {\n let page = 1\n for (;;) {\n const ordersResponse = await request(source, \"GET\", `/v3/orders?page=${page}&size=100`)\n if (!ordersResponse.ok) break\n const ordersPayload = asRecord(await readJson(ordersResponse))\n const orderEntries = Array.isArray(ordersPayload?.orders)\n ? ordersPayload.orders\n : Array.isArray(ordersPayload?.data)\n ? ordersPayload.data\n : []\n if (orderEntries.length === 0) break\n let listPosition = (page - 1) * 100\n for (const orderEntry of orderEntries) {\n const order = mapOrder(orderEntry)\n if (!order) continue\n // Do not resurrect users that are absent from /v2/user \u2014 orphan orders\n // keep their user_id but the team user list must match sandbox membership.\n if (!state.users.has(order.user_id) && !state.deletedUsers.has(order.user_id)) {\n state.deletedUsers.insert(order.user_id, { user_id: order.user_id })\n }\n listPosition += 1\n const existing = pendingOrders.find((pending) => pending.order.id === order.id)\n if (existing) {\n // Team-wide list order is the oracle's own tie order \u2014 restamp even for\n // orders first discovered through the per-user pass.\n existing.listPosition = listPosition\n continue\n }\n pendingOrders.push({ order, appointments: [], listPosition })\n }\n const total = typeof ordersPayload?.total === \"number\" ? ordersPayload.total : undefined\n if (total !== undefined && page * 100 >= total) break\n if (orderEntries.length < 100) break\n page += 1\n }\n }\n\n // Insert oldest-first so collection seq matches the oracle's list order: primary key\n // is updated_at asc, ties follow the oracle's newest-first list position (reversed),\n // because the sandbox orders same-instant rows by creation order there too.\n pendingOrders.sort((left, right) => {\n const leftAt = Date.parse(String(left.order.updated_at ?? left.order.created_at ?? \"\")) || 0\n const rightAt = Date.parse(String(right.order.updated_at ?? right.order.created_at ?? \"\")) || 0\n if (leftAt !== rightAt) return leftAt - rightAt\n if (left.listPosition !== undefined && right.listPosition !== undefined) {\n return right.listPosition - left.listPosition\n }\n // Orders discovered only via per-user detail fetches keep id order as a stable fallback.\n return left.order.id.localeCompare(right.order.id)\n })\n for (const pending of pendingOrders) {\n const labTest = pending.order.lab_test\n if (labTest?.id && (labTest.markers?.length ?? 0) === 0) {\n const expected = await expectedFromMarkersResponse(source, labTest)\n pending.order.lab_test = labTest\n if (state.orders.get(pending.order.id)) {\n state.orders.update(pending.order.id, pending.order)\n }\n state.upsertLabTest(labTest, expected)\n }\n if (state.orders.get(pending.order.id)) {\n state.orders.update(pending.order.id, pending.order)\n if (pending.order.lab_test?.id) state.upsertLabTest(pending.order.lab_test)\n continue\n }\n state.insertOrder(pending.order)\n if (pending.order.lab_test?.id) state.upsertLabTest(pending.order.lab_test)\n await ensureUserInfoForOrder(state, source, pending.order)\n orders += 1\n for (const appointment of pending.appointments) {\n if (state.appointments.get(appointment.id)) continue\n state.insertAppointment(appointment)\n appointments += 1\n }\n }\n\n // Refresh panels that still lack markers so create_order matches Vital.\n await ensureLabTests(\n state,\n source,\n state\n .listLabTests()\n .filter((test) => (test.markers?.length ?? 0) === 0)\n .map((test) => test.id),\n )\n\n return {\n users,\n orders,\n appointments,\n catalogTests: state.listLabTests().length,\n labs: state.listLabs().length,\n cacheEntries,\n }\n}\n", "import { HttpError, jsonRes, type OperationContext } from \"@crvouga/mockingbird-service\"\nimport { checkUserQuota } from \"./limits.js\"\nimport { missing } from \"./not-found.js\"\nimport type { JunctionState, UserRecord } from \"./state.js\"\n\nconst jsonBody = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\nconst render = (user: UserRecord, rawEnd = false) => ({\n user_id: user.user_id,\n team_id: user.team_id,\n client_user_id: user.client_user_id,\n created_on: user.created_on,\n connected_sources: user.connected_sources,\n fallback_time_zone: user.fallback_time_zone,\n fallback_birth_date: user.fallback_birth_date,\n ingestion_start: user.ingestion_start,\n ingestion_end: rawEnd\n ? user.ingestion_end\n : user.ingestion_start === null\n ? null\n : (user.ingestion_end ?? \"0001-01-01\"),\n})\n\nconst listUsers = (state: JunctionState, offset: number, limit: number) => {\n // Sandbox lists by created_on desc; same-second ties follow creation order\n // (collection newest), not UUID lexicographic order.\n const all = [...state.users.list({ order: \"newest\" })].sort((left, right) => {\n const leftAt = Date.parse(String(left.value.created_on ?? \"\")) || 0\n const rightAt = Date.parse(String(right.value.created_on ?? \"\")) || 0\n if (rightAt !== leftAt) return rightAt - leftAt\n return 0\n })\n const users = all.slice(offset, offset + limit).map((entry) => render(entry.value, true))\n return {\n users,\n total: users.length === 0 ? 0 : all.length,\n offset,\n limit,\n }\n}\n\nconst isValidUuid = (value: string): boolean =>\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value)\n\nfunction notFound(state: JunctionState, id: string, detail: string): never {\n return missing(state, \"user\", id, detail)\n}\n\nconst queryInt = (context: OperationContext, name: string, fallback: number): number => {\n const raw = context.query[name]\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw))\n throw new HttpError(422, { detail: `${name} must be an integer` })\n return Number(raw)\n}\n\nconst isValidIanaTimezone = (value: string): boolean => {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: value })\n return true\n } catch {\n return false\n }\n}\n\nconst isValidDate = (value: string): boolean => {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return false\n const [year, month, day] = value.split(\"-\").map(Number)\n const y = year ?? 0\n const m = month ?? 0\n const d = day ?? 0\n const date = new Date(Date.UTC(y, m - 1, d))\n return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d\n}\n\nconst stringError = (path: string, value: unknown) => ({\n type: \"string_type\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid string\",\n input: value,\n})\n\nconst missingError = (path: string, input: unknown) => ({\n type: \"missing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Field required\",\n input,\n})\n\nconst dateError = (path: string, value: unknown) => {\n const input = String(value)\n if (input.length <= 7) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid date or datetime, input is too short\",\n input: value,\n ctx: { error: \"input is too short\" },\n }\n }\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n}\n\n/** Pydantic-style email validation mirroring the sandbox's error reasons. */\nconst emailErrorOf = (value: string): { msg: string; reason: string } | undefined => {\n if (!value.includes(\"@\")) {\n return {\n msg: \"value is not a valid email address: An email address must have an @-sign.\",\n reason: \"An email address must have an @-sign.\",\n }\n }\n const [local = \"\", ...domainParts] = value.split(\"@\")\n const domain = domainParts.join(\"@\")\n if (local === \"\") {\n return {\n msg: \"value is not a valid email address: There must be something before the @-sign.\",\n reason: \"There must be something before the @-sign.\",\n }\n }\n if (domain === \"\") {\n return {\n msg: \"value is not a valid email address: There must be something after the @-sign.\",\n reason: \"There must be something after the @-sign.\",\n }\n }\n if (/\\s/.test(local)) {\n return {\n msg: `value is not a valid email address: The email address contains invalid characters before the @-sign: ${describeLocalChar(local)}.`,\n reason: `The email address contains invalid characters before the @-sign: ${describeLocalChar(local)}.`,\n }\n }\n if (domain.includes(\"@\") || /[^a-zA-Z0-9.\\-_]/.test(domain)) {\n return {\n msg: `value is not a valid email address: The part after the @-sign contains invalid characters: '@'.`,\n reason: `The part after the @-sign contains invalid characters: '@'.`,\n }\n }\n if (!domain.includes(\".\")) {\n return {\n msg: \"value is not a valid email address: The part after the @-sign is not valid. It should have a period.\",\n reason: \"The part after the @-sign is not valid. It should have a period.\",\n }\n }\n return undefined\n}\n\nconst describeLocalChar = (local: string): string => {\n for (const character of local) {\n if (/\\s/.test(character)) return character === \" \" ? \"SPACE\" : \"WS\"\n }\n return characterDescription(local)\n}\n\nconst characterDescription = (value: string): string => {\n for (const character of value) {\n if (!/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]/.test(character)) {\n const code = character.codePointAt(0) ?? 0\n if (code > 126) return \"NON printable\"\n return `'${character}'`\n }\n }\n return \"SPACE\"\n}\n\nconst emailValidationError = (value: string) => {\n const error = emailErrorOf(value)\n if (!error) return undefined\n return {\n type: \"value_error\",\n loc: [\"body\", \"email\"],\n msg: error.msg,\n input: value,\n ctx: { reason: error.reason },\n }\n}\n\n/** Pydantic date parsing mirroring the sandbox's `date` field error taxonomy. */\nconst dobValidationError = (value: unknown) => {\n if (typeof value === \"string\") {\n const codePoints = [...value]\n if (codePoints.some((character) => (character.codePointAt(0) ?? 0) > 127)) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n if (/^\\d+$/.test(value)) {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n if (value.length < 10) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, input is too short\",\n input: value,\n ctx: { error: \"input is too short\" },\n }\n }\n const iso = value.match(/^(\\d{4})([-/])(\\d{2}|[^-])\\2(\\d{2}|[^-]*)(.*)$/)\n if (iso === null) {\n // Pydantic/speedate: once four year digits are consumed, a non-`-` next\n // character is reported as a separator error (not an invalid year char).\n if (/^\\d{4}/.test(value)) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid date separator, expected `-`\",\n input: value,\n ctx: { error: \"invalid date separator, expected `-`\" },\n }\n }\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n const [, year = \"\", separator = \"-\", monthRaw = \"\", dayRaw = \"\", rest = \"\"] = iso\n if (separator !== \"-\") {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid date separator, expected `-`\",\n input: value,\n ctx: { error: \"invalid date separator, expected `-`\" },\n }\n }\n if (!/^\\d+$/.test(year ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n if (!/^\\d+$/.test(monthRaw ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in month\",\n input: value,\n ctx: { error: \"invalid character in month\" },\n }\n }\n if (!/^\\d+$/.test(dayRaw ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in day\",\n input: value,\n ctx: { error: \"invalid character in day\" },\n }\n }\n const month = Number(monthRaw)\n if (month < 1 || month > 12) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, month value is outside expected range of 1-12\",\n input: value,\n ctx: { error: \"month value is outside expected range of 1-12\" },\n }\n }\n const day = Number(dayRaw)\n const yearNumber = Number(year)\n const daysInMonth = new Date(Date.UTC(yearNumber, month, 0)).getUTCDate()\n if (day < 1 || day > daysInMonth) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, day value is outside expected range\",\n input: value,\n ctx: { error: \"day value is outside expected range\" },\n }\n }\n if (rest !== \"\" && !/^T00:00:00(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$/.test(rest)) {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n return undefined\n }\n if (typeof value === \"number\") {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n return {\n type: \"date_type\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date\",\n input: value,\n }\n}\n\nconst userInfoValidationErrors = (body: Record<string, unknown>): unknown[] => {\n const errors: unknown[] = []\n const push = (error: unknown) => {\n if (error) errors.push(error)\n }\n\n // Field-by-field, in the sandbox's fixed order; each field emits its missing OR\n // type/value error before moving to the next.\n for (const field of [\"first_name\", \"last_name\"] as const) {\n const value = body[field]\n if (value === undefined) push(missingError(field, body))\n else if (typeof value !== \"string\") push(stringError(field, value))\n }\n\n const email = body.email\n if (email === undefined) push(missingError(\"email\", body))\n else if (typeof email !== \"string\") push(stringError(\"email\", email))\n else push(emailValidationError(email))\n\n const phone = body.phone_number\n if (phone === undefined) push(missingError(\"phone_number\", body))\n else if (phone === null) {\n push({\n type: \"value_error\",\n loc: [\"body\", \"phone_number\"],\n msg: \"Value error, Phone number cannot be None\",\n input: null,\n ctx: { error: {} },\n })\n } else if (typeof phone === \"string\") {\n const digits = phone.replace(/\\D/g, \"\")\n if (digits.length < 10 || !/^[\\d\\s()+-]*$/.test(phone)) {\n push({\n type: \"value_error\",\n loc: [\"body\", \"phone_number\"],\n msg: `Value error, Invalid phone number: ${phone}`,\n input: phone,\n ctx: { error: {} },\n })\n }\n }\n\n const gender = body.gender\n if (gender === undefined) push(missingError(\"gender\", body))\n else if (typeof gender !== \"string\") push(stringError(\"gender\", gender))\n\n if (body.dob === undefined) push(missingError(\"dob\", body))\n else push(dobValidationError(body.dob))\n\n const address = body.address\n if (address === undefined) push(missingError(\"address\", body))\n else if (address === null || typeof address !== \"object\" || Array.isArray(address)) {\n push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"address\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: address,\n })\n } else {\n const addressRecord = address as Record<string, unknown>\n for (const field of [\"first_line\", \"country\", \"zip\", \"city\", \"state\"] as const) {\n const value = addressRecord[field]\n if (value === undefined) push(missingError(`address.${field}`, addressRecord))\n else if (typeof value !== \"string\") push(stringError(`address.${field}`, value))\n }\n if (addressRecord.second_line !== undefined && typeof addressRecord.second_line !== \"string\") {\n push(stringError(\"address.second_line\", addressRecord.second_line))\n }\n }\n return errors\n}\n\nexport const userHandlers = (state: JunctionState) => ({\n patch_user_info_v2_user__user_id__info_patch: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const body = jsonBody(context)\n const errors = userInfoValidationErrors(body)\n if (errors.length > 0) throw new HttpError(422, { detail: errors })\n if (!state.users.has(id)) notFound(state, id, \"User not found\")\n const existing = state.userInfo.get(id) ?? {}\n const rawAddress =\n typeof body.address === \"object\" && body.address !== null && !Array.isArray(body.address)\n ? (body.address as Record<string, unknown>)\n : undefined\n const info = {\n ...existing,\n ...body,\n ...(rawAddress === undefined\n ? {}\n : {\n address: {\n first_line: rawAddress.first_line ?? \"\",\n second_line: typeof rawAddress.second_line === \"string\" ? rawAddress.second_line : \"\",\n country: rawAddress.country ?? \"\",\n zip: rawAddress.zip ?? \"\",\n city: rawAddress.city ?? \"\",\n state: rawAddress.state ?? \"\",\n access_notes:\n typeof rawAddress.access_notes === \"string\" ? rawAddress.access_notes : null,\n },\n }),\n }\n state.userInfo.insert(id, info)\n return jsonRes(200, info)\n },\n\n create_user_v2_user_post: async (context: OperationContext) => {\n const body = jsonBody(context)\n const clientUserId = body.client_user_id\n if (clientUserId === undefined) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"body\", \"client_user_id\"],\n msg: \"Field required\",\n input: body,\n },\n ],\n })\n }\n if (typeof clientUserId !== \"string\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_type\",\n loc: [\"body\", \"client_user_id\"],\n msg: \"Input should be a valid string\",\n input: clientUserId,\n },\n ],\n })\n }\n const existing = state.byClientId.get(clientUserId)\n if (existing) {\n const user = state.users.get(existing.user_id)\n throw new HttpError(400, {\n detail: {\n error_type: \"INVALID_REQUEST\",\n error_message: \"Client user id already exists.\",\n user_id: existing.user_id,\n created_on: user?.created_on ?? state.isoNow(context.now),\n },\n })\n }\n checkUserQuota(state.limits, state.users.count())\n const userId = state.nextUserId()\n const createdOn = state.isoNow(context.now)\n const tz =\n typeof body.fallback_time_zone === \"string\"\n ? { id: body.fallback_time_zone, source_slug: \"manual\", updated_at: createdOn }\n : null\n const user: UserRecord = {\n user_id: userId,\n team_id: state.teamId,\n client_user_id: clientUserId,\n created_on: createdOn,\n connected_sources: [],\n fallback_time_zone: tz,\n fallback_birth_date: null,\n ingestion_start: null,\n ingestion_end: null,\n }\n state.users.insert(userId, user)\n state.byClientId.insert(clientUserId, { user_id: userId })\n return jsonRes(200, render(user))\n },\n\n get_user_v2_user__user_id__get: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n if (!isValidUuid(id)) {\n throw new HttpError(422, {\n detail: `Invalid format for parameter user_id: error unmarshaling '${id}' text as *uuid.UUID: invalid UUID length: ${id.length}`,\n })\n }\n const user = state.users.get(id)\n if (user) return jsonRes(200, render(user))\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, { detail: \"You have scheduled this user for deletion.\" })\n }\n notFound(state, id, \"Not found\")\n },\n\n delete_user_v2_user__user_id__delete: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const user = state.users.get(id)\n if (!user) {\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, {\n detail: \"The user has been scheduled for deletion as per your previous request\",\n })\n }\n notFound(state, id, \"The user does not or no longer exists in this team\")\n }\n state.users.delete(id)\n state.byClientId.delete(user.client_user_id)\n state.deletedUsers.insert(id, { user_id: id })\n return jsonRes(200, { success: true })\n },\n\n get_user_by_client_user_id_v2_user_resolve__client_user_id__get: async (\n context: OperationContext,\n ) => {\n const clientUserId = context.params.client_user_id ?? \"\"\n const binding =\n state.byClientId.get(clientUserId) ??\n notFound(state, `client:${clientUserId}`, \"User not found\")\n const user =\n state.users.get(binding.user_id) ?? notFound(state, binding.user_id, \"User not found\")\n return jsonRes(200, render(user))\n },\n\n patch_user_v2_user__user_id__patch: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const user = state.users.get(id)\n if (!user) {\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, {\n detail: \"The user has been scheduled for deletion as per your previous request\",\n })\n }\n notFound(state, id, \"The user does not or no longer exists in this team\")\n }\n const body = jsonBody(context)\n const now = state.isoNow(context.now)\n const patchable = [\n \"client_user_id\",\n \"fallback_time_zone\",\n \"fallback_birth_date\",\n \"ingestion_start\",\n \"ingestion_end\",\n ]\n if (!patchable.some((key) => body[key] !== undefined)) {\n throw new HttpError(400, { detail: \"Nothing to patch\" })\n }\n const validationError = (): unknown => {\n const tz = body.fallback_time_zone\n if (tz !== undefined && tz !== null) {\n if (typeof tz !== \"string\") return stringError(\"fallback_time_zone\", tz)\n if (!isValidIanaTimezone(tz)) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"fallback_time_zone\"],\n msg: `Value error, Invalid IANA time zone: ${tz}`,\n input: tz,\n ctx: { error: {} },\n }\n }\n }\n const birth = body.fallback_birth_date\n if (birth !== undefined && birth !== null) {\n if (typeof birth !== \"string\") return stringError(\"fallback_birth_date\", birth)\n if (!isValidDate(birth)) return dateError(\"fallback_birth_date\", birth)\n }\n const start = body.ingestion_start\n if (start !== undefined && start !== null) {\n if (typeof start !== \"string\") return stringError(\"ingestion_start\", start)\n if (!isValidDate(start)) return dateError(\"ingestion_start\", start)\n }\n const end = body.ingestion_end\n if (end !== undefined && end !== null) {\n if (typeof end !== \"string\") return stringError(\"ingestion_end\", end)\n if (!isValidDate(end)) return dateError(\"ingestion_end\", end)\n }\n const cid = body.client_user_id\n if (cid !== undefined) {\n if (cid === null) {\n return {\n type: \"value_error\",\n loc: [\"body\"],\n msg: \"Value error, client_user_id is not a field that can be reset to null.\",\n input: body,\n ctx: { error: {} },\n }\n }\n if (typeof cid !== \"string\") return stringError(\"client_user_id\", cid)\n }\n return undefined\n }\n const error = validationError()\n if (error) throw new HttpError(422, { detail: [error] })\n if (body.client_user_id !== undefined) {\n const raw = body.client_user_id as string\n const taken = state.byClientId.get(raw)\n if (taken && taken.user_id !== id)\n throw new HttpError(409, { detail: \"Client user id already exists\" })\n state.byClientId.delete(user.client_user_id)\n state.byClientId.insert(raw, { user_id: id })\n user.client_user_id = raw\n }\n if (body.fallback_time_zone !== undefined) {\n const raw = body.fallback_time_zone\n user.fallback_time_zone =\n typeof raw === \"string\" ? { id: raw, source_slug: \"manual\", updated_at: now } : null\n }\n if (body.fallback_birth_date !== undefined) {\n const raw = body.fallback_birth_date\n user.fallback_birth_date =\n typeof raw === \"string\" ? { value: raw, source_slug: \"manual\", updated_at: now } : null\n }\n const startProvided = body.ingestion_start !== undefined\n const endProvided = body.ingestion_end !== undefined\n if (startProvided) {\n const raw = body.ingestion_start\n user.ingestion_start = typeof raw === \"string\" ? raw : null\n }\n if (endProvided) {\n const rawEnd = body.ingestion_end\n user.ingestion_end = typeof rawEnd === \"string\" ? rawEnd : null\n }\n state.users.update(id, user)\n return new Response(null, { status: 204 })\n },\n\n get_latest_user_info_user_v2_user__user_id__info_latest_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.user_id ?? \"\"\n if (!isValidUuid(id)) {\n throw new HttpError(422, {\n detail: `Invalid format for parameter user_id: error unmarshaling '${id}' text as *uuid.UUID: invalid UUID length: ${id.length}`,\n })\n }\n if (!state.users.has(id) && !state.deletedUsers.has(id)) notFound(state, id, \"User not found\")\n const info = state.userInfo.get(id) ?? notFound(state, id, \"User demographics data not found\")\n return jsonRes(200, info)\n },\n\n get_teams_users_v2_user_get: async (context: OperationContext) => {\n const offset = queryInt(context, \"offset\", 0)\n const limit = queryInt(context, \"limit\", 100)\n if (offset < 0 || limit < 0 || limit > 500) {\n throw new HttpError(500, \"Internal Server Error\", { \"content-type\": \"text/plain\" })\n }\n return jsonRes(200, listUsers(state, offset, limit))\n },\n})\n", "/** High-signal ZIPs for availability prefetch (full routing corpus still used for area/psc). */\nexport const PSC_AVAILABILITY_ZIPS = [\n \"85004\",\n \"85234\",\n \"11050\",\n \"10006\",\n \"90012\",\n \"96101\",\n \"92101\",\n \"60601\",\n \"33130\",\n \"98104\",\n \"75034\",\n \"07030\",\n] as const\n\n/**\n * Phlebotomy availability is only served for a narrow Vital sandbox set.\n * Probed: 85004 works; broader scheduling zips often 400. Keep prefetch/reshape sealed.\n */\nexport const PHLEBOTOMY_AVAILABILITY_ZIPS = [\"85004\"] as const\n\n/** City/state/first_line seals so availability cache keys match Vital + prefetch. */\nexport const ZIP_ADDRESSES: Readonly<\n Record<string, { first_line: string; city: string; state: string }>\n> = {\n \"85004\": { first_line: \"1 N Central Ave\", city: \"Phoenix\", state: \"AZ\" },\n \"85234\": { first_line: \"1 Main St\", city: \"Gilbert\", state: \"AZ\" },\n \"11050\": { first_line: \"1 Main St\", city: \"Port Washington\", state: \"NY\" },\n \"10006\": { first_line: \"1 Main St\", city: \"New York\", state: \"NY\" },\n \"90012\": { first_line: \"200 N Spring St\", city: \"Los Angeles\", state: \"CA\" },\n \"96101\": { first_line: \"1 Main St\", city: \"Alturas\", state: \"CA\" },\n \"92101\": { first_line: \"1 Main St\", city: \"San Diego\", state: \"CA\" },\n \"60601\": { first_line: \"121 N LaSalle St\", city: \"Chicago\", state: \"IL\" },\n \"33130\": { first_line: \"3500 Pan American Dr\", city: \"Miami\", state: \"FL\" },\n \"98104\": { first_line: \"1 Main St\", city: \"Seattle\", state: \"WA\" },\n \"75034\": { first_line: \"1 Main St\", city: \"Frisco\", state: \"TX\" },\n \"07030\": { first_line: \"1 Main St\", city: \"Hoboken\", state: \"NJ\" },\n}\n\nexport const availabilityAddressForZip = (zip: string) => {\n const known = ZIP_ADDRESSES[zip]\n return {\n first_line: known?.first_line ?? \"1 Main St\",\n second_line: null as string | null,\n city: known?.city ?? \"Phoenix\",\n state: known?.state ?? \"AZ\",\n zip_code: zip,\n unit: null as string | null,\n }\n}\n\n/**\n * Curated real ZIPs used as this package's parity coverage corpus (one per US state plus DC,\n * plus scheduling pins). Prefetched into the observation cache so area/PSC parity is sealed\n * for those geos.\n */\nexport const COVERAGE_ZIPS = [\n \"02108\",\n \"02903\",\n \"03101\",\n \"04101\",\n \"05401\",\n \"06103\",\n \"07030\",\n \"11050\",\n \"17316\",\n \"19107\",\n \"19801\",\n \"20001\",\n \"21201\",\n \"23219\",\n \"25301\",\n \"28202\",\n \"29201\",\n \"30303\",\n \"33130\",\n \"35203\",\n \"37219\",\n \"39201\",\n \"40202\",\n \"43215\",\n \"46204\",\n \"47630\",\n \"48226\",\n \"50309\",\n \"53202\",\n \"54977\",\n \"55415\",\n \"57104\",\n \"58102\",\n \"59101\",\n \"60601\",\n \"64106\",\n \"67202\",\n \"68102\",\n \"70112\",\n \"72201\",\n \"73102\",\n \"75034\",\n \"77002\",\n \"80202\",\n \"82001\",\n \"83702\",\n \"84111\",\n \"85004\",\n \"85234\",\n \"87102\",\n \"89101\",\n \"90012\",\n \"96101\",\n \"96813\",\n \"97204\",\n \"98104\",\n \"99501\",\n] as const\n\n/** Lab ids exercised by walk-in / PSC parity flows (quest, labcorp, bioreference, sonora). */\nexport const PSC_LAB_IDS = [4, 6, 13, 25] as const\n\n/** Sealed patient + address shapes for order parity (avoids junk 422 divergence). */\nexport const COVERAGE_ORDER_ADDRESSES = [\n {\n first_line: \"1 N Central Ave\",\n city: \"Phoenix\",\n state: \"AZ\",\n zip: \"85004\",\n country: \"US\",\n },\n {\n first_line: \"200 N Spring St\",\n city: \"Los Angeles\",\n state: \"CA\",\n zip: \"90012\",\n country: \"US\",\n },\n {\n first_line: \"121 N LaSalle St\",\n city: \"Chicago\",\n state: \"IL\",\n zip: \"60601\",\n country: \"US\",\n },\n {\n first_line: \"1 Main St\",\n city: \"Port Washington\",\n state: \"NY\",\n zip: \"11050\",\n country: \"US\",\n },\n {\n first_line: \"3500 Pan American Dr\",\n city: \"Miami\",\n state: \"FL\",\n zip: \"33130\",\n country: \"US\",\n },\n {\n first_line: \"1437 Bannock St\",\n city: \"Denver\",\n state: \"CO\",\n zip: \"80202\",\n country: \"US\",\n },\n] as const\n\nexport const COVERAGE_PATIENT = {\n first_name: \"Ada\",\n last_name: \"Lovelace\",\n dob: \"1990-01-01\",\n gender: \"female\",\n phone_number: \"+14155551234\",\n email: \"ada.lovelace@example.com\",\n} as const\n", "import type { ExploreRng, ExploreState, LogicalCommand } from \"@crvouga/mockingbird-commands\"\nimport {\n availabilityAddressForZip,\n COVERAGE_ORDER_ADDRESSES,\n COVERAGE_PATIENT,\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nimport { CANCELLATION_REASONS, PSC_CANCELLATION_REASONS } from \"./scheduling.js\"\n\nconst GEO_AREA = \"get_area_info_v3_order_area_info_get\"\nconst GEO_PSC = \"get_psc_info_v3_order_psc_info_get\"\nconst AVAIL_PHLEB =\n \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\"\nconst AVAIL_PSC = \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\"\n\n/** Stable address fields so availability observation-cache keys match prefetch (85004). */\nexport const AVAILABILITY_ADDRESS = {\n first_line: \"1 N Central Ave\",\n second_line: null as string | null,\n city: \"Phoenix\",\n state: \"AZ\",\n unit: null as string | null,\n} as const\n\n/** Far-future start date so slots are always generated relative to frozen test clocks. */\nexport const AVAILABILITY_START_DATE = \"2099-06-15\"\n\nconst pickZip = (rng: ExploreRng, zips: readonly string[]) =>\n zips[rng.nextInt(Math.max(0, zips.length - 1))] ?? zips[0] ?? \"85004\"\n\nconst pickLabId = (rng: ExploreRng, labs: readonly number[]) =>\n labs[rng.nextInt(Math.max(0, labs.length - 1))] ?? labs[0] ?? 4\n\nconst availabilityBody = (zip: string) => availabilityAddressForZip(zip)\n\n/**\n * Pin geo / availability params onto the coverage corpus so observation-cache hits stay\n * sealed during seedParity compare walks.\n */\nexport const reshapeCoverageGeoCommand = (\n command: LogicalCommand,\n _state: ExploreState,\n rng: ExploreRng,\n options?: {\n zips?: readonly string[]\n schedulingZips?: readonly string[]\n phlebotomyZips?: readonly string[]\n labIds?: readonly number[]\n },\n): LogicalCommand => {\n const zips = options?.zips ?? COVERAGE_ZIPS\n const schedulingZips = options?.schedulingZips ?? PSC_AVAILABILITY_ZIPS\n const phlebotomyZips = options?.phlebotomyZips ?? PHLEBOTOMY_AVAILABILITY_ZIPS\n const labIds = options?.labIds ?? PSC_LAB_IDS\n const id = command.operationId\n\n if (id === \"create_order_v3_order_post\") {\n const address =\n COVERAGE_ORDER_ADDRESSES[rng.nextInt(COVERAGE_ORDER_ADDRESSES.length - 1)] ??\n COVERAGE_ORDER_ADDRESSES[0]\n const raw =\n typeof command.body === \"object\" && command.body !== null && !Array.isArray(command.body)\n ? (command.body as Record<string, unknown>)\n : {}\n const rawOrderSet =\n typeof raw.order_set === \"object\" && raw.order_set !== null && !Array.isArray(raw.order_set)\n ? (raw.order_set as Record<string, unknown>)\n : {}\n const rawIds = Array.isArray(rawOrderSet.lab_test_ids) ? rawOrderSet.lab_test_ids : []\n const labTestId =\n rawIds.find(\n (entry) =>\n (typeof entry === \"string\" && entry.length > 0) ||\n (typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n (entry as Record<string, unknown>).$mockingbird === \"ref\"),\n ) ??\n (typeof raw.lab_test_id === \"string\" ||\n (typeof raw.lab_test_id === \"object\" &&\n raw.lab_test_id !== null &&\n !Array.isArray(raw.lab_test_id) &&\n (raw.lab_test_id as Record<string, unknown>).$mockingbird === \"ref\")\n ? raw.lab_test_id\n : undefined)\n // Junction and the mock default collection_method to the panel's native method.\n // Random mismatches force sandbox auto_generated lab_tests whose UUIDs Vital\n // allocates opaquely; keep a low rate so we still exercise that path after seed.\n const methods = [\"at_home_phlebotomy\", \"walk_in_test\"] as const\n const forceMismatch = rng.next() < 0.12\n const body: Record<string, unknown> = {\n user_id: raw.user_id,\n patient_details: { ...COVERAGE_PATIENT },\n patient_address: {\n receiver_name: \"Ada Lovelace\",\n first_line: address?.first_line,\n city: address?.city,\n state: address?.state,\n zip: address?.zip,\n country: address?.country,\n phone_number: COVERAGE_PATIENT.phone_number,\n },\n order_set: labTestId === undefined ? { lab_test_ids: [] } : { lab_test_ids: [labTestId] },\n clinical_notes: null,\n passthrough: null,\n aoe_answers: null,\n lab_account_id: null,\n }\n if (forceMismatch) {\n body.collection_method = methods[rng.nextInt(methods.length - 1)] ?? \"at_home_phlebotomy\"\n }\n return {\n ...command,\n body,\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"get_teams_users_v2_user_get\") {\n // Team user lists are newest-first with same-second ties; across seed + lockstep\n // creates the 2nd+ slots are still racy. Parity only needs membership/total \u2014\n // pin limit=1 so we compare the newest user + totals without slot races.\n const raw =\n typeof command.parameters === \"object\" && command.parameters !== null\n ? (command.parameters as Record<string, unknown>)\n : {}\n const offsetRaw = raw.offset\n const offset =\n typeof offsetRaw === \"string\" && /^-?\\d+$/.test(offsetRaw) ? Number(offsetRaw) : 0\n return {\n ...command,\n parameters: {\n offset: String(Math.max(0, offset)),\n limit: \"1\",\n },\n invalid: undefined,\n }\n }\n if (id === GEO_AREA) {\n return {\n ...command,\n parameters: { zip_code: pickZip(rng, zips) },\n }\n }\n if (id === GEO_PSC) {\n return {\n ...command,\n parameters: {\n zip_code: pickZip(rng, zips),\n lab_id: String(pickLabId(rng, labIds)),\n },\n }\n }\n if (id === AVAIL_PHLEB) {\n const zip = pickZip(rng, phlebotomyZips)\n return {\n ...command,\n parameters: {\n start_date: AVAILABILITY_START_DATE,\n },\n body: availabilityBody(zip),\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === AVAIL_PSC) {\n const zip = pickZip(rng, schedulingZips)\n return {\n ...command,\n parameters: {\n lab: \"quest\",\n start_date: AVAILABILITY_START_DATE,\n },\n body: availabilityBody(zip),\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"simulate_order_v3_order__order_id__test_post\") {\n const statuses = [\n \"received.at_home_phlebotomy.ordered\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"sample_with_lab.at_home_phlebotomy.partial_results\",\n \"completed.at_home_phlebotomy.completed\",\n \"received.walk_in_test.ordered\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"completed.walk_in_test.completed\",\n ] as const\n return {\n ...command,\n parameters: {\n order_id: command.parameters?.order_id,\n final_status: statuses[rng.nextInt(statuses.length - 1)] ?? statuses[0],\n },\n body: {},\n mediaType: \"application/json\",\n invalid: undefined,\n }\n }\n if (\n id === \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\"\n ) {\n const reason =\n CANCELLATION_REASONS.find((entry) => entry.name !== \"Other\") ?? CANCELLATION_REASONS[0]\n return {\n ...command,\n body: {\n cancellation_reason_id: reason?.id ?? \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n notes: null,\n },\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\") {\n const reason = PSC_CANCELLATION_REASONS[0]\n return {\n ...command,\n body: {\n cancellationReasonId: reason?.id ?? \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n note: null,\n },\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n return command\n}\n", "import type { SeedCacheEntry } from \"@crvouga/mockingbird-parity\"\nimport {\n availabilityAddressForZip,\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nimport { AVAILABILITY_START_DATE } from \"./reshape.js\"\nimport { observationCacheKey } from \"./state.js\"\n\nexport type PrefetchTarget = {\n baseUrl: string\n fetch: (request: Request) => Promise<Response>\n headers: () => Promise<Record<string, string>> | Record<string, string>\n}\n\nexport const recordObservation = async (\n target: PrefetchTarget,\n method: string,\n pathAndQuery: string,\n getCache: Map<string, SeedCacheEntry>,\n body?: unknown,\n): Promise<unknown> => {\n const headers: Record<string, string> = {\n ...(await target.headers()),\n accept: \"application/json\",\n }\n if (body !== undefined) headers[\"content-type\"] = \"application/json\"\n const url = `${target.baseUrl}${pathAndQuery}`\n const response = await target.fetch(\n new Request(url, {\n method,\n headers,\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n }),\n )\n const text = await response.text()\n let parsed: unknown = text\n try {\n parsed = text === \"\" ? undefined : (JSON.parse(text) as unknown)\n } catch {\n parsed = text\n }\n const headerRecord: Record<string, string> = {}\n response.headers.forEach((value, name) => {\n headerRecord[name.toLowerCase()] = value\n })\n const cacheKey = observationCacheKey(url, method, body)\n // Seal-once: a walk-local warmup seal for this request is authoritative \u2014 prefetch\n // must not clobber it, because the oracle rotates booking_key per serve and only the\n // sealed observation's keys were paired into the walk's resource table.\n if (getCache.has(cacheKey)) return getCache.get(cacheKey)?.body\n getCache.set(cacheKey, {\n status: response.status,\n headers: headerRecord,\n body: parsed,\n })\n return parsed\n}\n\n/**\n * Seal coverage-corpus routing ZIPs + availability POSTs into the seed observation cache.\n * Call after warmup, before `seedFrom`, so compare walks can forceInclude geo/scheduling reads.\n */\nexport const prefetchCoverageObservations = async (args: {\n real: PrefetchTarget\n getCache: Map<string, SeedCacheEntry>\n zips?: readonly string[]\n /** ZIPs that also get PSC availability POST seals. Defaults to scheduling corpus. */\n schedulingZips?: readonly string[]\n /** ZIPs for phlebotomy availability (narrow served set). Defaults to PHLEBOTOMY_ZIPS. */\n phlebotomyZips?: readonly string[]\n labIds?: readonly number[]\n /** Also prefetch phlebotomy + PSC availability. Default true. */\n includeAvailability?: boolean\n sleep?: (ms: number) => Promise<void>\n minIntervalMs?: number\n}) => {\n const zips = args.zips ?? COVERAGE_ZIPS\n const schedulingZips = args.schedulingZips ?? PSC_AVAILABILITY_ZIPS\n const phlebotomyZips = args.phlebotomyZips ?? PHLEBOTOMY_AVAILABILITY_ZIPS\n const labIds = args.labIds ?? PSC_LAB_IDS\n const includeAvailability = args.includeAvailability !== false\n const sleep = args.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))\n const gap = args.minIntervalMs ?? 50\n\n for (const zip of zips) {\n await recordObservation(args.real, \"GET\", `/v3/order/area/info?zip_code=${zip}`, args.getCache)\n await sleep(gap)\n for (const labId of labIds) {\n await recordObservation(\n args.real,\n \"GET\",\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}`,\n args.getCache,\n )\n await sleep(gap)\n }\n }\n\n if (!includeAvailability) return\n for (const zip of phlebotomyZips) {\n const body = availabilityAddressForZip(zip)\n await recordObservation(\n args.real,\n \"POST\",\n `/v3/order/phlebotomy/appointment/availability?start_date=${AVAILABILITY_START_DATE}`,\n args.getCache,\n body,\n )\n await sleep(gap)\n }\n for (const zip of schedulingZips) {\n const body = availabilityAddressForZip(zip)\n await recordObservation(\n args.real,\n \"POST\",\n `/v3/order/psc/appointment/availability?lab=quest&start_date=${AVAILABILITY_START_DATE}`,\n args.getCache,\n body,\n )\n await sleep(gap)\n }\n}\n\n/** Extract every `central_labs[*].lab_id` from an area-serviceability body. */\nconst labIdsFromAreaBody = (body: unknown): number[] => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return []\n const central = (body as Record<string, unknown>).central_labs\n if (central === null || typeof central !== \"object\") return []\n const entries = Array.isArray(central)\n ? central\n : Object.values(central as Record<string, unknown>)\n const ids: number[] = []\n for (const entry of entries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const labId = (entry as Record<string, unknown>).lab_id\n if (typeof labId === \"number\" && Number.isInteger(labId)) ids.push(labId)\n }\n return ids\n}\n\n/**\n * Record the parameter-stable provider reads a sealed corpus covers: area serviceability and\n * PSC site inventory for every coverage ZIP, in both the SDK-shaped `radius=100` request and\n * the bare query the parity walks use. Availability is deliberately not recorded \u2014 its slot\n * dates and single-use `booking_key`s can never match a live cache key.\n */\nexport const recordSandboxCorpus = async (args: {\n real: PrefetchTarget\n getCache: Map<string, SeedCacheEntry>\n zips?: readonly string[]\n labIds?: readonly number[]\n sleep?: (ms: number) => Promise<void>\n minIntervalMs?: number\n}): Promise<{ observations: number; labIds: number[] }> => {\n const zips = args.zips ?? COVERAGE_ZIPS\n const sleep = args.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))\n const gap = args.minIntervalMs ?? 50\n const discovered = new Set<number>(args.labIds ?? PSC_LAB_IDS)\n\n for (const zip of zips) {\n for (const path of [\n `/v3/order/area/info?zip_code=${zip}&radius=100`,\n `/v3/order/area/info?zip_code=${zip}`,\n ]) {\n const body = await recordObservation(args.real, \"GET\", path, args.getCache)\n for (const labId of labIdsFromAreaBody(body)) discovered.add(labId)\n await sleep(gap)\n }\n }\n\n const labIds = [...discovered].sort((a, b) => a - b)\n for (const zip of zips) {\n for (const labId of labIds) {\n for (const path of [\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}&radius=100`,\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}`,\n ]) {\n await recordObservation(args.real, \"GET\", path, args.getCache)\n await sleep(gap)\n }\n }\n }\n\n return { observations: args.getCache.size, labIds }\n}\n", "import { COVERAGE_ZIPS } from \"./coverage-corpus.js\"\nimport { type PrefetchTarget, recordObservation, recordSandboxCorpus } from \"./prefetch.js\"\nimport { SEALED_CORPUS_VERSION, type SealedCorpus } from \"./sealed-corpus.js\"\nimport { expectedFromMarkersResponse, mapLabTest, type SeedSource } from \"./seed-from.js\"\nimport type { ExpectedResult, GetCacheEntry, LabTestRecord } from \"./state.js\"\n\nexport const DEFAULT_JUNCTION_BASE_URL = \"https://api.sandbox.tryvital.io\"\n\nexport { isSandboxKey, SANDBOX_KEY_PREFIXES } from \"./limits.js\"\n\nexport type PullCorpusOptions = {\n apiKey: string\n baseUrl?: string\n /** ZIPs to record area and PSC coverage for. Default: the shipped coverage set. */\n zips?: readonly string[]\n /**\n * Refresh only `zips` on top of this corpus, keeping everything else. How a single\n * ZIP is added to a committed corpus without re-recording the whole thing.\n */\n base?: SealedCorpus\n /** Skip the team's catalog and lab accounts (coverage only). */\n coverageOnly?: boolean\n fetch?: (request: Request) => Promise<Response>\n /** Pause between vendor calls, to stay under rate limits. Default 50 ms. */\n minIntervalMs?: number\n onProgress?: (message: string) => void\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\n/** `GET /v3/lab_test/lab_account` answers `{ data: [...] }`; older recordings saved a bare array. */\nconst listOf = (body: unknown): Record<string, unknown>[] => {\n const items = Array.isArray(body) ? body : asRecord(body)?.data\n return Array.isArray(items)\n ? items.map(asRecord).filter((entry): entry is Record<string, unknown> => !!entry)\n : []\n}\n\n/** JSON with object keys sorted, so equal content always serializes identically. */\nexport const canonicalJson = (value: unknown): string =>\n JSON.stringify(value, (_key, inner: unknown) => {\n const record = asRecord(inner)\n if (!record) return inner\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .map((key) => [key, record[key]]),\n )\n })\n\n/** SHA-256 over a corpus's content \u2014 not its recording time \u2014 so a re-pull of unchanged data matches. */\nexport const fingerprintCorpus = async (corpus: SealedCorpus): Promise<string> => {\n const content = canonicalJson({\n observations: corpus.observations,\n catalog: corpus.catalog,\n labAccounts: corpus.labAccounts,\n // Absent from version-1 corpora, whose fingerprints stay what they were.\n ...(corpus.teamId !== undefined ? { teamId: corpus.teamId } : {}),\n })\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(content))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * The calling team's id, read without writing anything: a listed user's `team_id`, else\n * the one team every non-empty lab-account allowlist names. `undefined` when neither\n * says (a team with no users and no linked accounts).\n */\nexport const readTeamId = async (\n real: PrefetchTarget,\n labAccounts: readonly Record<string, unknown>[],\n): Promise<string | undefined> => {\n const headers = { ...(await real.headers()), accept: \"application/json\" }\n const response = await real\n .fetch(new Request(`${real.baseUrl}/v2/user?offset=0&limit=1`, { headers }))\n .catch(() => undefined)\n if (response?.ok) {\n const body = asRecord(await response.json().catch(() => undefined))\n const first = Array.isArray(body?.users) ? asRecord(body.users[0]) : undefined\n if (typeof first?.team_id === \"string\" && UUID.test(first.team_id)) return first.team_id\n }\n const named = new Set<string>()\n for (const account of labAccounts) {\n const allowlist = account.team_id_allowlist\n if (!Array.isArray(allowlist) || allowlist.length === 0) continue\n const ids = allowlist.filter((id): id is string => typeof id === \"string\")\n if (named.size === 0) for (const id of ids) named.add(id)\n else for (const id of [...named]) if (!ids.includes(id)) named.delete(id)\n }\n return named.size === 1 ? [...named][0] : undefined\n}\n\n/** Record a sealed corpus from a real Junction team. Read-only: it only issues GETs. */\nexport const pullCorpus = async (options: PullCorpusOptions): Promise<SealedCorpus> => {\n const baseUrl = (options.baseUrl ?? DEFAULT_JUNCTION_BASE_URL).replace(/\\/$/, \"\")\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const headers = { \"x-vital-api-key\": options.apiKey }\n const gap = options.minIntervalMs ?? 50\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n const progress = options.onProgress ?? (() => {})\n const real: PrefetchTarget = { baseUrl, fetch: send, headers: () => headers }\n const source: SeedSource = { baseUrl, fetch: send, headers }\n const getCache = new Map<string, GetCacheEntry>()\n\n const zips = options.zips ?? (options.base ? [] : COVERAGE_ZIPS)\n if (zips.length > 0) {\n progress(`recording area + PSC coverage for ${zips.length} ZIP(s)`)\n const { labIds } = await recordSandboxCorpus({ real, getCache, zips, minIntervalMs: gap })\n progress(`coverage recorded across ${labIds.length} PSC lab(s)`)\n }\n\n let catalog = options.base?.catalog ?? { labTests: [], labs: [], expectedResults: {} }\n let labAccounts = options.base?.labAccounts ?? []\n if (!options.coverageOnly) {\n progress(\"recording lab-test catalog\")\n const labTests: LabTestRecord[] = []\n let cursor: string | null = null\n for (;;) {\n const path =\n cursor === null ? \"/v3/lab_test\" : `/v3/lab_test?next_cursor=${encodeURIComponent(cursor)}`\n const body = asRecord(await recordObservation(real, \"GET\", path, getCache))\n for (const entry of Array.isArray(body?.data) ? body.data : []) {\n const test = mapLabTest(entry)\n if (test) labTests.push(test)\n }\n cursor = typeof body?.next_cursor === \"string\" ? body.next_cursor : null\n if (cursor === null) break\n await sleep(gap)\n }\n const labs = listOf(await recordObservation(real, \"GET\", \"/v3/lab_tests/labs\", getCache))\n const expectedResults: Record<string, ExpectedResult[]> = {}\n for (const test of labTests) {\n await recordObservation(real, \"GET\", `/v3/lab_tests/${test.id}/markers`, getCache)\n expectedResults[test.id] = await expectedFromMarkersResponse(source, test)\n await sleep(gap)\n }\n catalog = { labTests, labs, expectedResults }\n progress(`catalog: ${labTests.length} lab test(s), ${labs.length} lab(s)`)\n labAccounts = listOf(await recordObservation(real, \"GET\", \"/v3/lab_test/lab_account\", getCache))\n progress(`lab accounts: ${labAccounts.length}`)\n }\n\n const observations = Object.fromEntries(\n [...Object.entries(options.base?.observations ?? {}), ...getCache.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n )\n const teamId = (await readTeamId(real, labAccounts)) ?? options.base?.teamId\n const corpus: SealedCorpus = {\n version: SEALED_CORPUS_VERSION,\n recordedAt: new Date().toISOString(),\n source: baseUrl,\n ...(teamId !== undefined ? { teamId } : {}),\n observations,\n catalog,\n labAccounts,\n }\n corpus.fingerprint = await fingerprintCorpus(corpus)\n return corpus\n}\n\nexport type SetDiff = { added: string[]; removed: string[]; changed: string[] }\n\nexport type CorpusDiff = {\n identical: boolean\n /** Set when the recorded team differs (or one side recorded none). */\n teamId?: { before: string | null; after: string | null }\n observations: SetDiff\n labTests: SetDiff\n labAccounts: SetDiff\n zips: { added: string[]; removed: string[] }\n}\n\nconst diffById = <T>(before: Iterable<[string, T]>, after: Iterable<[string, T]>): SetDiff => {\n const a = new Map(before)\n const b = new Map(after)\n const sorted = (values: string[]) => values.sort()\n return {\n added: sorted([...b.keys()].filter((key) => !a.has(key))),\n removed: sorted([...a.keys()].filter((key) => !b.has(key))),\n changed: sorted(\n [...b.keys()].filter(\n (key) => a.has(key) && canonicalJson(a.get(key)) !== canonicalJson(b.get(key)),\n ),\n ),\n }\n}\n\nconst zipsOf = (corpus: SealedCorpus): Set<string> =>\n new Set(\n Object.keys(corpus.observations).flatMap((key) => {\n const zip = /\\/v3\\/order\\/(?:area|psc)\\/info\\?.*zip_code=(\\d{5})/.exec(key)?.[1]\n return zip ? [zip] : []\n }),\n )\n\n/** What changed between two recordings: coverage, catalog, accounts and raw observations. */\nexport const diffCorpus = (before: SealedCorpus, after: SealedCorpus): CorpusDiff => {\n const observations = diffById(\n Object.entries(before.observations),\n Object.entries(after.observations),\n )\n const labTests = diffById(\n before.catalog.labTests.map((test) => [test.id, test] as [string, unknown]),\n after.catalog.labTests.map((test) => [test.id, test] as [string, unknown]),\n )\n const accountEntries = (corpus: SealedCorpus) =>\n corpus.labAccounts.map((account) => [String(account.id), account] as [string, unknown])\n const labAccounts = diffById(accountEntries(before), accountEntries(after))\n const beforeZips = zipsOf(before)\n const afterZips = zipsOf(after)\n const zips = {\n added: [...afterZips].filter((zip) => !beforeZips.has(zip)).sort(),\n removed: [...beforeZips].filter((zip) => !afterZips.has(zip)).sort(),\n }\n const empty = (d: SetDiff) => d.added.length + d.removed.length + d.changed.length === 0\n const teamChanged = (before.teamId ?? null) !== (after.teamId ?? null)\n return {\n identical: empty(observations) && empty(labTests) && empty(labAccounts) && !teamChanged,\n ...(teamChanged\n ? { teamId: { before: before.teamId ?? null, after: after.teamId ?? null } }\n : {}),\n observations,\n labTests,\n labAccounts,\n zips,\n }\n}\n", "import { opaqueToken } from \"@crvouga/mockingbird-service\"\nimport { type JunctionWebhookEvent, WEBHOOK_RETRY_DELAYS_MS } from \"./state.js\"\n\n/**\n * Signed webhook delivery, the way Junction delivers through Svix.\n *\n * Signing lives here, next to the events, so a consumer never hand-rolls it. The\n * signature is standard Svix \u2014 `v1,` + base64 HMAC-SHA256, keyed by the base64 part of\n * `whsec_\u2026`, over `\"<svix-id>.<svix-timestamp>.<body>\"` \u2014 so the official `svix`\n * verifier, and a receiver written for real Junction webhooks, accept it unchanged.\n */\nexport type WebhookEndpoint = {\n url: string\n /** Svix signing secret, `whsec_<base64>`. A bare base64 secret is accepted too. */\n secret: string\n /**\n * Delay before each attempt, in ms; the first entry delays the first attempt. Default:\n * Svix's schedule (immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h).\n */\n retryDelaysMs?: readonly number[]\n /** Abort an attempt that takes longer than this. Default 15 s, like Svix. */\n timeoutMs?: number\n /** Added to every delivery, e.g. a routing scope for a shared receiver. */\n headers?: Record<string, string>\n fetch?: (request: Request) => Promise<Response>\n /** Injectable wall clock for signatures and delivery records. */\n now?: () => number\n /** Injectable scheduler for timeouts and retry delays. */\n schedule?: (callback: () => void, delayMs: number) => unknown\n cancel?: (handle: unknown) => void\n}\n\nexport type WebhookAttempt = {\n attempt: number\n /** Wall-clock time of the attempt, ISO-8601. */\n at: string\n /** Receiver's status code, or `null` when the request never completed. */\n status: number | null\n error: string | null\n durationMs: number\n}\n\nexport type WebhookDelivery = {\n messageId: string\n namespace: string\n event: JunctionWebhookEvent\n state: \"pending\" | \"delivered\" | \"failed\"\n attempts: WebhookAttempt[]\n}\n\nexport type WebhookDispatcher = {\n /** Queue an event for delivery. Returns immediately; delivery runs in the background. */\n publish(event: JunctionWebhookEvent, namespace: string): WebhookDelivery\n deliveries(namespace?: string): WebhookDelivery[]\n /** Deliver a message again now, as a new attempt, whatever its state. */\n replay(messageId: string): Promise<WebhookDelivery | undefined>\n /** Run every pending retry now instead of waiting out its delay. */\n flush(): Promise<void>\n /** Resolve once no delivery is in flight. */\n idle(): Promise<void>\n /** Cancel pending retries and forget every delivery. */\n clear(namespace?: string): void\n}\n\nconst encoder = new TextEncoder()\n\nconst base64 = (bytes: ArrayBuffer): string => {\n let binary = \"\"\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nconst secretBytes = (secret: string): Uint8Array => {\n const raw = secret.startsWith(\"whsec_\") ? secret.slice(\"whsec_\".length) : secret\n try {\n return Uint8Array.from(atob(raw), (char) => char.charCodeAt(0))\n } catch {\n throw new TypeError(\"webhook secret must be whsec_<base64> (as Svix issues it)\")\n }\n}\n\n/** The `svix-signature` value for one message: `v1,<base64 HMAC-SHA256>`. */\nexport const signSvix = async (\n secret: string,\n messageId: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> => {\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes(secret) as BufferSource,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n )\n const signed = await crypto.subtle.sign(\n \"HMAC\",\n key,\n encoder.encode(`${messageId}.${timestampSeconds}.${body}`),\n )\n return `v1,${base64(signed)}`\n}\n\n/**\n * Check a delivery's signature the way the `svix` verifier does: any `v1,` entry in the\n * space-separated header matches, and the timestamp is within `toleranceSeconds`.\n */\nexport const verifySvix = async (\n secret: string,\n headers: { \"svix-id\": string; \"svix-timestamp\": string; \"svix-signature\": string },\n body: string,\n options: { toleranceSeconds?: number; now?: () => number } = {},\n): Promise<boolean> => {\n const timestamp = Number.parseInt(headers[\"svix-timestamp\"], 10)\n if (!Number.isFinite(timestamp)) return false\n const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000)\n if (Math.abs(nowSeconds - timestamp) > (options.toleranceSeconds ?? 300)) return false\n const expected = await signSvix(secret, headers[\"svix-id\"], timestamp, body)\n return headers[\"svix-signature\"].split(\" \").some((entry) => entry === expected)\n}\n\ntype Pending = { delivery: WebhookDelivery; timer: unknown | undefined }\n\n/** Keep a long retry from holding the process open, where the runtime supports it. */\nconst unref = (timer: unknown) => {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\nexport const createWebhookDispatcher = (endpoint: WebhookEndpoint): WebhookDispatcher => {\n // Validate up front so a bad secret fails at boot, not on the first event.\n secretBytes(endpoint.secret)\n const delays = endpoint.retryDelaysMs ?? WEBHOOK_RETRY_DELAYS_MS\n const timeoutMs = endpoint.timeoutMs ?? 15_000\n const send = endpoint.fetch ?? ((request: Request) => fetch(request))\n const now = endpoint.now ?? Date.now\n const scheduleTimer =\n endpoint.schedule ?? ((callback: () => void, delayMs: number) => setTimeout(callback, delayMs))\n const cancel =\n endpoint.cancel ?? ((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>))\n const deliveries = new Map<string, WebhookDelivery>()\n const pending = new Map<string, Pending>()\n const inFlight = new Set<Promise<void>>()\n let sequence = 0\n\n const attempt = async (delivery: WebhookDelivery): Promise<boolean> => {\n const body = JSON.stringify(delivery.event)\n // Wall-clock, never the mock clock: receivers reject timestamps outside ~5 minutes\n // of their own clock, and an advanced mock clock would fail every delivery.\n const timestamp = Math.floor(now() / 1000)\n const started = now()\n const record: WebhookAttempt = {\n attempt: delivery.attempts.length + 1,\n at: new Date(started).toISOString(),\n status: null,\n error: null,\n durationMs: 0,\n }\n const controller = new AbortController()\n const timer = scheduleTimer(() => controller.abort(), timeoutMs)\n try {\n const response = await send(\n new Request(endpoint.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...endpoint.headers,\n \"svix-id\": delivery.messageId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": await signSvix(endpoint.secret, delivery.messageId, timestamp, body),\n },\n body,\n signal: controller.signal,\n }),\n )\n record.status = response.status\n await response.body?.cancel()\n } catch (error) {\n record.error = controller.signal.aborted\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error)\n } finally {\n cancel(timer)\n record.durationMs = now() - started\n delivery.attempts.push(record)\n }\n // Svix treats any 2xx as delivered and retries everything else.\n return record.status !== null && record.status >= 200 && record.status < 300\n }\n\n const track = (work: Promise<void>) => {\n inFlight.add(work)\n void work.finally(() => inFlight.delete(work))\n }\n\n const schedule = (delivery: WebhookDelivery) => {\n const index = delivery.attempts.length\n if (index >= delays.length) {\n delivery.state = \"failed\"\n pending.delete(delivery.messageId)\n return\n }\n const run = () => {\n pending.delete(delivery.messageId)\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n const delay = delays[index] ?? 0\n if (delay <= 0) {\n run()\n return\n }\n const timer = scheduleTimer(run, delay)\n unref(timer)\n pending.set(delivery.messageId, { delivery, timer })\n }\n\n return {\n publish(event, namespace) {\n sequence++\n const delivery: WebhookDelivery = {\n messageId: `msg_${opaqueToken(`junction:webhook:${namespace}:${sequence}`, 27)}`,\n namespace,\n event,\n state: \"pending\",\n attempts: [],\n }\n deliveries.set(delivery.messageId, delivery)\n schedule(delivery)\n return delivery\n },\n deliveries: (namespace) =>\n [...deliveries.values()].filter((d) => namespace === undefined || d.namespace === namespace),\n async replay(messageId) {\n const delivery = deliveries.get(messageId)\n if (!delivery) return undefined\n const queued = pending.get(messageId)\n if (queued?.timer !== undefined) cancel(queued.timer)\n pending.delete(messageId)\n const ok = await attempt(delivery)\n delivery.state = ok ? \"delivered\" : \"failed\"\n return delivery\n },\n async flush() {\n for (const [id, queued] of [...pending]) {\n if (queued.timer !== undefined) cancel(queued.timer)\n pending.delete(id)\n track(\n attempt(queued.delivery).then((ok) => {\n if (ok) queued.delivery.state = \"delivered\"\n else schedule(queued.delivery)\n }),\n )\n }\n await Promise.all([...inFlight])\n },\n async idle() {\n while (inFlight.size > 0) await Promise.all([...inFlight])\n },\n clear(namespace) {\n for (const [id, delivery] of [...deliveries]) {\n if (namespace !== undefined && delivery.namespace !== namespace) continue\n const queued = pending.get(id)\n if (queued?.timer !== undefined) cancel(queued.timer)\n pending.delete(id)\n deliveries.delete(id)\n }\n },\n }\n}\n", "import {\n type Clock,\n createRuntime as createServiceRuntime,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { junctionAdminRoutes, junctionFaultPresets } from \"./admin.js\"\nimport type { IdentityMode, JunctionFixtures } from \"./fixtures.js\"\nimport { document } from \"./generated/openapi.js\"\nimport { JUNCTION_NAMESPACE, JunctionAPI } from \"./index.js\"\nimport type { LabAccountLayout } from \"./lab-account-presets.js\"\nimport type { BillingType } from \"./lab-accounts.js\"\nimport type { JunctionLimitsInput } from \"./limits.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\nimport type { GeoMode, WebhookPublisher } from \"./state.js\"\nimport {\n createWebhookDispatcher,\n type WebhookDispatcher,\n type WebhookEndpoint,\n} from \"./webhooks.js\"\n\nexport type JunctionRuntimeOptions = {\n /**\n * Recorded vendor data every namespace starts from. The served mock loads the corpus\n * shipped at `@crvouga/mockingbird-service-junction/corpus` unless told otherwise.\n */\n corpus?: SealedCorpus\n /** Default: `corpus` when a corpus is loaded, otherwise `synthetic`. */\n geo?: GeoMode\n /** The team's lab accounts, or `{ presets, accounts }`; see {@link JunctionAPIOptions.labAccounts}. */\n labAccounts?: LabAccountLayout\n /** The team the mock answers as. Default: the corpus's recorded team, else a fixed id. */\n teamId?: string\n /** Sandbox-only restrictions, every one off by default; per namespace via `PUT /__admin/limits`. */\n limits?: JunctionLimitsInput\n /** `adopt-users` creates unknown user ids on first use. Default `strict`. */\n identity?: IdentityMode\n /**\n * Lab slug \u2192 `billing_type` for orders that omit it; see\n * {@link JunctionAPIOptions.defaultBillingTypes}. Per namespace via `PUT /__admin/default-billing-types`.\n */\n defaultBillingTypes?: Partial<Record<string, BillingType>>\n /** Users and orders every namespace starts with, re-applied on each reset. */\n fixtures?: JunctionFixtures\n /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000. */\n journalSize?: number\n /** Deliver signed webhooks here, with Svix's retry schedule. */\n webhooks?: WebhookEndpoint\n /** Called in-process for every webhook event, delivered or not. */\n onWebhook?: (event: Parameters<WebhookPublisher>[0], namespace: string) => void\n sqlite?: SqliteClient\n clock?: Clock\n /** Seeds fault rates and webhook retry jitter. */\n seed?: number | string\n /** Require `x-mockingbird-admin-key` on `/__admin/*`. */\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n}\n\nexport type JunctionRuntime = ServiceRuntime<JunctionAPI> & {\n /** Signed delivery, when `webhooks` was configured. */\n readonly webhooks: WebhookDispatcher | undefined\n}\n\n/**\n * The Junction mock with Mockingbird's full service contract: unauthenticated\n * `/health`, the `/__admin/*` control plane, per-request namespaces\n * (`x-mockingbird-namespace`), clock control, fault injection and request metrics.\n * Runtime-neutral: serve it with any Fetch-native server, or use `./server` for Node.\n */\nexport const createRuntime = (options: JunctionRuntimeOptions = {}): JunctionRuntime => {\n const webhooks = options.webhooks ? createWebhookDispatcher(options.webhooks) : undefined\n const runtime: ServiceRuntime<JunctionAPI> = createServiceRuntime<JunctionAPI>({\n name: JUNCTION_NAMESPACE,\n document,\n ...(options.sqlite ? { sqlite: options.sqlite } : {}),\n ...(options.clock ? { clock: options.clock } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.adminKey !== undefined ? { adminKey: options.adminKey } : {}),\n ...(options.onLog ? { onLog: options.onLog } : {}),\n ...(options.journalSize !== undefined ? { journalSize: options.journalSize } : {}),\n create: ({ namespace, publicNamespace, sqlite, clock, rng }) => {\n const api = new JunctionAPI({\n sqlite,\n namespace,\n now: clock.now,\n webhook: { seed: rng.seed },\n ...(options.corpus ? { corpus: options.corpus } : {}),\n ...(options.geo ? { geo: options.geo } : {}),\n ...(options.labAccounts ? { labAccounts: options.labAccounts } : {}),\n ...(options.teamId !== undefined ? { teamId: options.teamId } : {}),\n ...(options.limits ? { limits: options.limits } : {}),\n ...(options.identity ? { identity: options.identity } : {}),\n ...(options.defaultBillingTypes\n ? { defaultBillingTypes: options.defaultBillingTypes }\n : {}),\n ...(options.fixtures ? { fixtures: options.fixtures } : {}),\n onWebhook: (event) => {\n options.onWebhook?.(event, publicNamespace)\n webhooks?.publish(event, publicNamespace)\n },\n })\n // A namespace reset also forgets that namespace's deliveries and pending retries.\n const reset = api.reset.bind(api)\n api.reset = async () => {\n webhooks?.clear(publicNamespace)\n await reset()\n }\n return api\n },\n describe: (): Record<string, unknown> => {\n const info = runtime.instance().corpusInfo()\n return {\n corpus: info?.label ?? null,\n geo: runtime.instance().geoMode,\n teamId: runtime.instance().teamId,\n webhooks: webhooks ? \"on\" : \"off\",\n }\n },\n presets: junctionFaultPresets(),\n admin: junctionAdminRoutes({ webhooks }),\n })\n return Object.assign(runtime, { webhooks })\n}\n", "import { canonicalJson, DEFAULT_JUNCTION_BASE_URL } from \"./corpus-tools.js\"\nimport { ORDER_NOT_FOUND } from \"./not-found.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\n\n/**\n * Differential verification: the same requests against real Junction and the mock,\n * with every divergence reported. Two checks:\n *\n * - drift: each recorded corpus observation re-fetched from the real API. A stale\n * entry means the corpus no longer matches production and should be re-pulled.\n * - scenario: a fixed script of stateful calls (users, catalog, serviceability, and\n * optionally orders) run against both sides, comparing status codes, response\n * shapes, and \u2014 for the documented error bodies \u2014 exact bytes.\n *\n * The scenario also replays every order-scoped operation against a random unknown order\n * (each 404 body compared exactly) and, with `orders` and a corpus holding an account whose\n * `team_id_allowlist` is empty, orders through that account with and without its id. With\n * `orders`, it also orders through every other active account by id with `billing_type`\n * omitted, which shows the billing type the team defaults to.\n *\n * Only a sandbox team should be used: the scenario creates, and always deletes, one\n * user (and, with `orders`, places and cancels its orders).\n */\nexport type VerifyOptions = {\n realKey: string\n realUrl?: string\n /** The mock under test, e.g. `createRuntime({ corpus })`. */\n mock: { fetch(request: Request): Promise<Response> }\n corpus: SealedCorpus\n /** Re-fetch at most this many observations (spread evenly). Default: all of them. */\n sample?: number\n /** Skip the drift check. */\n skipDrift?: boolean\n /** Also place, read and cancel an order on the real team. */\n orders?: boolean\n fetch?: (request: Request) => Promise<Response>\n minIntervalMs?: number\n onProgress?: (message: string) => void\n}\n\nexport type Divergence = {\n check: string\n kind: \"status\" | \"shape\" | \"body\" | \"error\"\n /** JSON path of the first difference, when there is one. */\n at?: string\n real: unknown\n mock: unknown\n}\n\nexport type VerifyReport = {\n ok: boolean\n drift: { checked: number; stale: number }\n scenario: { steps: number; divergent: number }\n divergences: Divergence[]\n}\n\ntype Side = \"real\" | \"mock\"\ntype Reply = { status: number; body: unknown }\n\nconst readReply = async (response: Response): Promise<Reply> => {\n const text = await response.text()\n try {\n return { status: response.status, body: text === \"\" ? null : JSON.parse(text) }\n } catch {\n return { status: response.status, body: text }\n }\n}\n\n/** The structure of a JSON value: object keys and value types, never the values. */\nexport const shapeOf = (value: unknown): unknown => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return value.length === 0 ? [] : [shapeOf(value[0])]\n if (typeof value === \"object\") {\n const record = value as Record<string, unknown>\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .map((key) => [key, shapeOf(record[key])]),\n )\n }\n return typeof value\n}\n\n/** Path to the first place two JSON values differ, or `undefined` when they are equal. */\nexport const firstDifference = (a: unknown, b: unknown, path = \"$\"): string | undefined => {\n if (canonicalJson(a) === canonicalJson(b)) return undefined\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return path\n if (Array.isArray(a) !== Array.isArray(b)) return path\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of [...keys].sort()) {\n const at = Array.isArray(a) ? `${path}[${key}]` : `${path}.${key}`\n const found = firstDifference(\n (a as Record<string, unknown>)[key],\n (b as Record<string, unknown>)[key],\n at,\n )\n if (found) return found\n }\n return path\n}\n\ntype Context = {\n clientUserId: string\n userId?: string\n orderId?: string\n /** Orders placed by the lab-account probes, cancelled with the rest. */\n extraOrders: string[]\n}\n\n/** How to reach each order-scoped operation for an unknown order, past its validation. */\nconst orderScopedCalls = (\n orderId: string,\n): Record<string, { method: string; path: string; body?: unknown }> => {\n const base = `/v3/order/${orderId}`\n const key = { booking_key: \"00000000-0000-4000-8000-00000000b00c\" }\n const reason = { cancellation_reason_id: \"00000000-0000-4000-8000-00000000c0de\" }\n return {\n get_order_v3_order__order_id__get: { method: \"GET\", path: base },\n cancel_order_v3_order__order_id__cancel_post: { method: \"POST\", path: `${base}/cancel` },\n simulate_order_v3_order__order_id__test_post: {\n method: \"POST\",\n path: `${base}/test?final_status=completed.at_home_phlebotomy.completed`,\n body: {},\n },\n get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get: {\n method: \"GET\",\n path: `${base}/requisition/pdf`,\n },\n get_result_raw_v3_order__order_id__result_get: { method: \"GET\", path: `${base}/result` },\n get_result_metadata_v3_order__order_id__result_metadata_get: {\n method: \"GET\",\n path: `${base}/result/metadata`,\n },\n get_result_pdf_v3_order__order_id__result_pdf_get: {\n method: \"GET\",\n path: `${base}/result/pdf`,\n },\n get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get: {\n method: \"GET\",\n path: `${base}/phlebotomy/appointment`,\n },\n book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post: {\n method: \"POST\",\n path: `${base}/phlebotomy/appointment/book`,\n body: key,\n },\n reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch: {\n method: \"PATCH\",\n path: `${base}/phlebotomy/appointment/reschedule`,\n body: key,\n },\n cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch: {\n method: \"PATCH\",\n path: `${base}/phlebotomy/appointment/cancel`,\n body: reason,\n },\n get_psc_appointment_v3_order__order_id__psc_appointment_get: {\n method: \"GET\",\n path: `${base}/psc/appointment`,\n },\n book_psc_appointment_v3_order__order_id__psc_appointment_book_post: {\n method: \"POST\",\n path: `${base}/psc/appointment/book`,\n body: key,\n },\n reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch: {\n method: \"PATCH\",\n path: `${base}/psc/appointment/reschedule`,\n body: key,\n },\n cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch: {\n method: \"PATCH\",\n path: `${base}/psc/appointment/cancel`,\n body: reason,\n },\n }\n}\n\nconst orderBody = (\n userId: string | undefined,\n labTestId: string,\n extra: Record<string, unknown> = {},\n) => ({\n user_id: userId,\n patient_details: {\n first_name: \"Mockingbird\",\n last_name: \"Verify\",\n dob: \"1990-01-01\",\n gender: \"female\",\n phone_number: \"+14155551234\",\n email: \"verify@example.com\",\n },\n patient_address: {\n first_line: \"1 Main St\",\n city: \"San Diego\",\n state: \"CA\",\n zip: \"92101\",\n country: \"US\",\n },\n order_set: { lab_test_ids: [labTestId] },\n ...extra,\n})\n\nconst captureExtraOrder = (reply: Reply, ctx: Context) => {\n const id = (reply.body as { order?: { id?: unknown } } | null)?.order?.id\n if (typeof id === \"string\") ctx.extraOrders.push(id)\n}\n\ntype Step = {\n name: string\n /** `exact`: bodies must match byte for byte; `shape`: structure and types only. */\n compare: \"exact\" | \"shape\"\n skip?: (ctx: Record<Side, Context>) => boolean\n request(ctx: Context): { method: string; path: string; body?: unknown }\n capture?(reply: Reply, ctx: Context): void\n}\n\nconst scenario = (corpus: SealedCorpus, withOrders: boolean): Step[] => {\n const zip =\n Object.keys(corpus.observations)\n .map((key) => /\\/v3\\/order\\/area\\/info\\?.*zip_code=(\\d{5})/.exec(key)?.[1])\n .find((found) => found !== undefined) ?? \"92101\"\n const labTestId = corpus.catalog.labTests[0]?.id\n const steps: Step[] = [\n {\n name: \"user.create\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v2/user\",\n body: { client_user_id: ctx.clientUserId },\n }),\n capture: (reply, ctx) => {\n const id = (reply.body as { user_id?: unknown } | null)?.user_id\n if (typeof id === \"string\") ctx.userId = id\n },\n },\n {\n name: \"user.create duplicate\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v2/user\",\n body: { client_user_id: ctx.clientUserId },\n }),\n },\n {\n name: \"user.get\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/${ctx.userId}` }),\n },\n {\n name: \"user.getByClientUserId\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/resolve/${ctx.clientUserId}` }),\n },\n {\n name: \"user.get unknown (documented 404 body)\",\n compare: \"exact\",\n request: () => ({ method: \"GET\", path: \"/v2/user/00000000-0000-4000-8000-000000000000\" }),\n },\n {\n name: \"user.getByClientUserId unknown (documented 404 body)\",\n compare: \"exact\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/resolve/${ctx.clientUserId}-missing` }),\n },\n {\n name: \"labs\",\n compare: \"shape\",\n request: () => ({ method: \"GET\", path: \"/v3/lab_tests/labs\" }),\n },\n {\n name: \"lab tests (bare array)\",\n compare: \"shape\",\n request: () => ({ method: \"GET\", path: \"/v3/lab_tests\" }),\n },\n {\n name: `area info ${zip}`,\n compare: \"exact\",\n request: () => ({ method: \"GET\", path: `/v3/order/area/info?zip_code=${zip}&radius=100` }),\n },\n ]\n if (withOrders && labTestId) {\n steps.push(\n {\n name: \"order.create\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: orderBody(ctx.userId, labTestId),\n }),\n capture: (reply, ctx) => {\n const id = (reply.body as { order?: { id?: unknown } } | null)?.order?.id\n if (typeof id === \"string\") ctx.orderId = id\n },\n },\n {\n name: \"order.get\",\n compare: \"shape\",\n skip: (ctx) => !ctx.real.orderId || !ctx.mock.orderId,\n request: (ctx) => ({ method: \"GET\", path: `/v3/order/${ctx.orderId}` }),\n },\n {\n name: \"order.cancel\",\n compare: \"shape\",\n skip: (ctx) => !ctx.real.orderId || !ctx.mock.orderId,\n request: (ctx) => ({ method: \"POST\", path: `/v3/order/${ctx.orderId}/cancel` }),\n },\n )\n }\n // Unknown-order 404s: Junction words each endpoint's differently, so every one is exact.\n const unknownOrder = crypto.randomUUID()\n const calls = orderScopedCalls(unknownOrder)\n for (const operationId of Object.keys(ORDER_NOT_FOUND)) {\n const call = calls[operationId]\n if (!call) continue\n steps.push({\n name: `unknown order 404 ${operationId}`,\n compare: \"exact\",\n request: () => call,\n })\n }\n // What an empty `team_id_allowlist` means for ordering is unverified (SUPPORT.md): order\n // through such an account by explicit id, and with the id omitted, and compare.\n const openAccount = corpus.labAccounts.find(\n (account) =>\n Array.isArray(account.team_id_allowlist) &&\n account.team_id_allowlist.length === 0 &&\n account.status === \"active\",\n )\n const openLabTest = openAccount\n ? corpus.catalog.labTests.find(\n (test) =>\n String(test.lab?.slug ?? \"\").toLowerCase() === String(openAccount.lab).toLowerCase(),\n )\n : undefined\n if (withOrders && openAccount && openLabTest) {\n steps.push(\n {\n name: `order.create via empty-allowlist account ${String(openAccount.id)}`,\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: orderBody(ctx.userId, openLabTest.id, { lab_account_id: openAccount.id }),\n }),\n capture: captureExtraOrder,\n },\n {\n name: `order.create for ${String(openAccount.lab)} with lab_account_id omitted`,\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: orderBody(ctx.userId, openLabTest.id),\n }),\n capture: captureExtraOrder,\n },\n )\n }\n // Several active accounts for one lab with the id omitted: the mock places the order with\n // the first (a consumer's sandbox team was observed doing so, #136); a team with that layout\n // checks it here.\n if (withOrders) {\n const byLab = new Map<string, number>()\n for (const account of corpus.labAccounts) {\n if (account.status !== \"active\") continue\n const lab = String(account.lab).toLowerCase()\n byLab.set(lab, (byLab.get(lab) ?? 0) + 1)\n }\n for (const [lab, count] of byLab) {\n if (count < 2 || lab === String(openAccount?.lab ?? \"\").toLowerCase()) continue\n const labTest = corpus.catalog.labTests.find(\n (test) => String(test.lab?.slug ?? \"\").toLowerCase() === lab,\n )\n if (!labTest) continue\n steps.push({\n name: `order.create for ${lab} with lab_account_id omitted (${count} active accounts)`,\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: orderBody(ctx.userId, labTest.id),\n }),\n capture: captureExtraOrder,\n })\n }\n }\n // Which billing_type an order that omits it is evaluated as is not visible from outside\n // (documented: client_bill; one sandbox team evaluated BioReference as\n // patient_bill_passthrough). Order through each active account by id with billing_type\n // omitted, so a mock whose `defaultBillingTypes` disagree with the team diverges here.\n if (withOrders) {\n const labTestFor = (lab: unknown) =>\n corpus.catalog.labTests.find(\n (test) => String(test.lab?.slug ?? \"\").toLowerCase() === String(lab).toLowerCase(),\n )\n for (const account of corpus.labAccounts) {\n const labTest = labTestFor(account.lab)\n if (account.status !== \"active\" || account === openAccount || !labTest) continue\n steps.push({\n name: `order.create via ${String(account.lab)} account ${String(account.id)} with billing_type omitted`,\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: orderBody(ctx.userId, labTest.id, { lab_account_id: account.id }),\n }),\n capture: captureExtraOrder,\n })\n }\n }\n steps.push({\n name: \"user.delete\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"DELETE\", path: `/v2/user/${ctx.userId}` }),\n capture: (_reply, ctx) => {\n delete ctx.userId\n },\n })\n return steps\n}\n\nexport const verifyAgainstReal = async (options: VerifyOptions): Promise<VerifyReport> => {\n const realUrl = (options.realUrl ?? DEFAULT_JUNCTION_BASE_URL).replace(/\\/$/, \"\")\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const gap = options.minIntervalMs ?? 50\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n const progress = options.onProgress ?? (() => {})\n const divergences: Divergence[] = []\n\n const call = async (side: Side, method: string, path: string, body?: unknown): Promise<Reply> => {\n const base = side === \"real\" ? realUrl : \"http://mock.mockingbird.local\"\n const request = new Request(`${base}${path}`, {\n method,\n headers: {\n \"x-vital-api-key\": side === \"real\" ? options.realKey : \"sk_us_mockingbird_verify\",\n ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n })\n const response = side === \"real\" ? await send(request) : await options.mock.fetch(request)\n return readReply(response)\n }\n\n // \u2500\u2500 drift \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let checked = 0\n let stale = 0\n if (!options.skipDrift) {\n const keys = Object.keys(options.corpus.observations).filter((key) => key.startsWith(\"GET \"))\n const limit = options.sample ?? keys.length\n const stride = Math.max(1, Math.floor(keys.length / Math.max(1, limit)))\n const picked = keys.filter((_, index) => index % stride === 0).slice(0, limit)\n progress(`drift: re-fetching ${picked.length} of ${keys.length} recorded observations`)\n for (const key of picked) {\n const path = key.slice(\"GET \".length)\n const recorded = options.corpus.observations[key]\n if (!recorded) continue\n checked++\n try {\n const live = await call(\"real\", \"GET\", path)\n if (live.status !== recorded.status) {\n stale++\n divergences.push({\n check: `drift ${key}`,\n kind: \"status\",\n real: live.status,\n mock: recorded.status,\n })\n } else {\n const at = firstDifference(live.body, recorded.body)\n if (at) {\n stale++\n divergences.push({\n check: `drift ${key}`,\n kind: \"body\",\n at,\n real: live.body,\n mock: recorded.body,\n })\n }\n }\n } catch (error) {\n stale++\n divergences.push({ check: `drift ${key}`, kind: \"error\", real: String(error), mock: null })\n }\n await sleep(gap)\n }\n }\n\n // \u2500\u2500 scenario \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const clientUserId = `mockingbird-verify-${Date.now().toString(36)}`\n const ctx: Record<Side, Context> = {\n real: { clientUserId, extraOrders: [] },\n mock: { clientUserId, extraOrders: [] },\n }\n const steps = scenario(options.corpus, options.orders === true)\n let ran = 0\n let divergent = 0\n progress(`scenario: ${steps.length} steps as client_user_id ${clientUserId}`)\n try {\n for (const step of steps) {\n if (step.skip?.(ctx)) continue\n ran++\n const replies = {} as Record<Side, Reply>\n for (const side of [\"real\", \"mock\"] as const) {\n const { method, path, body } = step.request(ctx[side])\n replies[side] = await call(side, method, path, body)\n step.capture?.(replies[side], ctx[side])\n }\n const { real, mock } = replies\n let divergence: Divergence | undefined\n if (real.status !== mock.status) {\n divergence = { check: step.name, kind: \"status\", real: real.status, mock: mock.status }\n } else if (step.compare === \"exact\") {\n const at = firstDifference(real.body, mock.body)\n if (at)\n divergence = { check: step.name, kind: \"body\", at, real: real.body, mock: mock.body }\n } else {\n const at = firstDifference(shapeOf(real.body), shapeOf(mock.body))\n if (at) {\n divergence = {\n check: step.name,\n kind: \"shape\",\n at,\n real: shapeOf(real.body),\n mock: shapeOf(mock.body),\n }\n }\n }\n if (divergence) {\n divergent++\n divergences.push(divergence)\n }\n progress(` ${divergence ? \"DIVERGED\" : \"ok\"} ${step.name}`)\n await sleep(gap)\n }\n } finally {\n // Never leave the verify user behind on the real team: it counts against the sandbox cap.\n for (const orderId of [ctx.real.orderId, ...ctx.real.extraOrders]) {\n if (orderId === undefined) continue\n await call(\"real\", \"POST\", `/v3/order/${orderId}/cancel`).catch(() => undefined)\n }\n if (ctx.real.userId) {\n await call(\"real\", \"DELETE\", `/v2/user/${ctx.real.userId}`).catch(() => undefined)\n }\n }\n\n return {\n ok: divergences.length === 0,\n drift: { checked, stale },\n scenario: { steps: ran, divergent },\n divergences,\n }\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n bootSqlite,\n createService,\n defineOperations,\n HttpError,\n jsonRes,\n opaqueToken,\n type Service,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport {\n fixtureErrorMessage,\n hardDeleteUser,\n IDENTITY_MODES,\n type IdentityMode,\n type InsertOptions,\n importFixtures,\n insertOrders,\n insertUsers,\n type JunctionFixtures,\n type OrderFixture,\n type UserFixture,\n} from \"./fixtures.js\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport {\n expandLabAccountLayout,\n type LabAccountLayout,\n labAccountFromPreset,\n} from \"./lab-account-presets.js\"\nimport {\n type BillingType,\n defaultBillingTypesFrom,\n type LabAccountInput,\n labAccountFromClientFacing,\n labAccountFromInput,\n patchLabAccount as patchLabAccountRecord,\n TEAM_LAB_ACCOUNTS,\n} from \"./lab-accounts.js\"\nimport {\n DEFAULT_LIMITS,\n type JunctionLimits,\n type JunctionLimitsInput,\n mergeLimits,\n RateWindow,\n} from \"./limits.js\"\nimport { orderHandlers } from \"./orders.js\"\nimport { resultsHandlers } from \"./results.js\"\nimport { forceOrderStatus, schedulingHandlers } from \"./scheduling.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\nimport {\n ensureLabTests as ensureLabTestsFrom,\n ensureOrders as ensureOrdersFrom,\n type SeedObservations,\n type SeedReport,\n type SeedSource,\n seedFrom as seedStateFrom,\n} from \"./seed-from.js\"\nimport {\n type GeoMode,\n type GetCacheEntry,\n JunctionState,\n type JunctionWebhookEvent,\n type JunctionWebhookOptions,\n MOCK_TEAM_ID,\n type OrderRecord,\n type ResultFixture,\n type StoredLabAccount,\n type UserRecord,\n type WebhookPublisher,\n} from \"./state.js\"\nimport { userHandlers } from \"./users.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type { JunctionAdminOptions } from \"./admin.js\"\nexport {\n FAULT_PRESETS,\n ORDER_STATUSES_BY_METHOD,\n RESULT_FIXTURES,\n resolveTransition,\n TRANSITION_ALIASES,\n} from \"./admin.js\"\nexport type { CorpusDiff, PullCorpusOptions, SetDiff } from \"./corpus-tools.js\"\nexport {\n DEFAULT_JUNCTION_BASE_URL,\n diffCorpus,\n fingerprintCorpus,\n isSandboxKey,\n pullCorpus,\n SANDBOX_KEY_PREFIXES,\n} from \"./corpus-tools.js\"\nexport {\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nexport type {\n IdentityMode,\n InsertOptions,\n JunctionFixtures,\n OrderFixture,\n UserFixture,\n} from \"./fixtures.js\"\nexport { FixtureError, IDENTITY_MODES } from \"./fixtures.js\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type { LabAccountLayout } from \"./lab-account-presets.js\"\nexport {\n DELEGATED_ACCOUNT_STATES,\n LAB_ACCOUNT_PRESET_ALIASES,\n LAB_ACCOUNT_PRESETS,\n PLATFORM_ACCOUNT_STATES,\n presetAccountId,\n SYNTHETIC_LAB_ACCOUNT_PRESETS,\n} from \"./lab-account-presets.js\"\nexport type {\n BillingType,\n LabAccountDelegatedFlow,\n LabAccountInput,\n LabAccountRecord,\n LabAccountStatus,\n} from \"./lab-accounts.js\"\nexport {\n BILLING_TYPES,\n isLinkedToTeam,\n labAccountFromInput,\n OTHER_TEAM_ID,\n TEAM_LAB_ACCOUNTS,\n US_STATES,\n} from \"./lab-accounts.js\"\nexport type { JunctionLimits, JunctionLimitsInput } from \"./limits.js\"\nexport { DEFAULT_LIMITS, sandboxUserQuotaBody } from \"./limits.js\"\nexport { KNOWN_HEADER, MISS_HEADER, ORDER_NOT_FOUND } from \"./not-found.js\"\nexport { prefetchCoverageObservations } from \"./prefetch.js\"\nexport {\n AVAILABILITY_ADDRESS,\n AVAILABILITY_START_DATE,\n reshapeCoverageGeoCommand,\n} from \"./reshape.js\"\nexport type { JunctionRuntime, JunctionRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime } from \"./runtime.js\"\nexport { UNKNOWN_ZIP_ERROR_TYPE, UNKNOWN_ZIP_STATUS } from \"./scheduling.js\"\nexport {\n parseSealedCorpus,\n SEALED_CORPUS_VERSION,\n type SealedCorpus,\n SUPPORTED_SEALED_CORPUS_VERSIONS,\n} from \"./sealed-corpus.js\"\nexport type { SeedObservations, SeedReport, SeedSource } from \"./seed-from.js\"\nexport type {\n GeoMode,\n GetCacheEntry,\n JunctionWebhookEvent,\n JunctionWebhookOptions,\n OrderRecord,\n ResultFixture,\n StoredLabAccount,\n UserRecord,\n WebhookPublisher,\n} from \"./state.js\"\nexport { MOCK_TEAM_ID, observationCacheKey } from \"./state.js\"\nexport type { Divergence, VerifyOptions, VerifyReport } from \"./verify.js\"\nexport { verifyAgainstReal } from \"./verify.js\"\nexport type {\n WebhookAttempt,\n WebhookDelivery,\n WebhookDispatcher,\n WebhookEndpoint,\n} from \"./webhooks.js\"\nexport { createWebhookDispatcher, signSvix, verifySvix } from \"./webhooks.js\"\n\nexport const JUNCTION_NAMESPACE = \"junction\"\n\n/**\n * Stateful mock of the Junction (Vital) API user and lab-testing surfaces.\n *\n * Docs: https://docs.junction.com/\n * Auth: `x-vital-api-key` \u2014 https://docs.junction.com/api-details/junction-api\n */\nexport type JunctionAPIOptions = APIOptions & {\n onWebhook?: WebhookPublisher\n webhook?: JunctionWebhookOptions\n /** Install a recorded corpus at construction; it is re-applied on every `reset()`. */\n corpus?: SealedCorpus\n /**\n * How serviceability reads answer a ZIP the corpus does not cover. Default: `corpus`\n * when a corpus is given (refuse, loudly), otherwise `synthetic` (invent coverage).\n */\n geo?: GeoMode\n /**\n * The team's lab accounts, replacing the built-in fixtures (and any from the corpus):\n * a list of accounts, or `{ presets: [...], accounts: [...] }`. `create_order` routes,\n * accepts and rejects `lab_account_id` against these.\n */\n labAccounts?: LabAccountLayout\n /**\n * The team the mock answers as: `team_id` on users and orders, and the team lab-account\n * allowlists are checked against. Default: the corpus's recorded team, else a fixed id.\n */\n teamId?: string\n /** Sandbox-only restrictions to enforce. Every one is off unless set here. */\n limits?: JunctionLimitsInput\n /** `adopt-users` creates an unknown (well-formed) `user_id` on first use. Default `strict`. */\n identity?: IdentityMode\n /**\n * Lab slug \u2192 the `billing_type` `create_order` uses when the request omits it, e.g.\n * `{ bioreference: \"patient_bill_passthrough\" }`. Unlisted labs use Junction's documented\n * default, `client_bill`.\n */\n defaultBillingTypes?: Partial<Record<string, BillingType>>\n /** Users and orders to load into every namespace, re-applied on every `reset()`. */\n fixtures?: JunctionFixtures\n}\n\n/** What a loaded corpus covers, for `/health` and startup logs. */\nexport type CorpusInfo = {\n label: string\n recordedAt: string\n source: string\n observations: number\n labTests: number\n labAccounts: number\n zips: number\n /** The recording team, when the corpus recorded one (version 2+). */\n teamId?: string\n}\n\nconst observationMaps = new WeakMap<SealedCorpus, ReadonlyMap<string, GetCacheEntry>>()\n\n/** One read-only map per corpus object, shared by every namespace that loads it. */\nconst observationsOf = (corpus: SealedCorpus): ReadonlyMap<string, GetCacheEntry> => {\n let map = observationMaps.get(corpus)\n if (!map) {\n map = new Map(Object.entries(corpus.observations))\n observationMaps.set(corpus, map)\n }\n return map\n}\n\n/** A ZIP appears in a corpus when an area or PSC observation was recorded for it. */\nconst coveredZipsOf = (corpus: SealedCorpus): Set<string> => {\n const zips = new Set<string>()\n for (const key of Object.keys(corpus.observations)) {\n if (!/ \\/v3\\/order\\/(?:area|psc)\\/info\\?/.test(key)) continue\n const zip = /[?&]zip_code=(\\d{5})/.exec(key)?.[1]\n if (zip) zips.add(zip)\n }\n return zips\n}\n\n/** A short, stable name for a corpus: its recording date plus a digest of what it holds. */\nexport const corpusLabel = (corpus: SealedCorpus): string => {\n const digest =\n corpus.fingerprint ??\n opaqueToken(\n JSON.stringify([\n Object.keys(corpus.observations).sort(),\n corpus.catalog.labTests.map((test) => test.id).sort(),\n corpus.labAccounts.map((account) => account.id).sort(),\n ]),\n 12,\n )\n return `v${String(corpus.version)}-${corpus.recordedAt.slice(0, 10)}-${digest.slice(0, 12)}`\n}\n\nexport class JunctionAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n private readonly service: Service\n private readonly state: JunctionState\n private readonly now: () => number\n private readonly explicitTeamId: string | undefined\n private readonly fixtures: JunctionFixtures | undefined\n private readonly rateWindow = new RateWindow()\n private corpus: SealedCorpus | undefined\n private labAccountConfig: StoredLabAccount[] | undefined\n\n constructor(options: JunctionAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? JUNCTION_NAMESPACE\n const state = new JunctionState(sqlite, namespace, options.onWebhook, options.webhook)\n this.state = state\n this.now = options.now ?? (() => Date.now())\n this.explicitTeamId = options.teamId\n state.teamId = options.teamId ?? options.corpus?.teamId ?? MOCK_TEAM_ID\n state.limits = mergeLimits(DEFAULT_LIMITS, options.limits ?? {})\n if (options.identity !== undefined && !IDENTITY_MODES.includes(options.identity))\n throw new TypeError(`identity must be one of ${IDENTITY_MODES.join(\", \")}`)\n state.identity = options.identity ?? \"strict\"\n state.defaultBillingTypes = defaultBillingTypesFrom(options.defaultBillingTypes ?? {})\n const handlers = defineOperations<SupportedOperationId>({\n ...userHandlers(state),\n ...orderHandlers(state),\n ...schedulingHandlers(state),\n ...resultsHandlers(state),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: options.now,\n notFound: () => jsonRes(404, { detail: \"Not Found\" }),\n onError: (error) => {\n if (error instanceof HttpError) return error.toResponse()\n throw error\n },\n before: (context) =>\n context.request.headers.has(\"x-vital-api-key\")\n ? undefined\n : jsonRes(401, { detail: \"Missing x-vital-api-key\" }),\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n this.labAccountConfig = options.labAccounts\n ? expandLabAccountLayout(options.labAccounts, state.teamId)\n : undefined\n if (options.corpus) this.installCorpus(options.corpus)\n else this.seedLabAccounts()\n state.geoMode = options.geo ?? (options.corpus ? \"corpus\" : \"synthetic\")\n this.fixtures = options.fixtures\n if (this.fixtures) importFixturesInto(state, this.fixtures, this.now)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (!this.rateWindow.take(this.state.limits.rateLimitPerSecond)) {\n return jsonRes(429, { detail: \"Too Many Requests\" }, { \"retry-after\": \"1\" })\n }\n const normalized = normalizePath(request)\n const sent = requestJson(normalized)\n const response = await this.service.fetch(normalized)\n const ids = await touchedIds(normalized, await sent, response)\n return annotateResponse(response, {\n ...(Object.keys(ids).length > 0 ? { ids } : {}),\n ...(this.state.adopted(normalized) ? { adopted: true } : {}),\n })\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n if (this.corpus) this.installCorpus(this.corpus)\n else {\n this.state.seedDefaultCatalog()\n this.seedLabAccounts()\n }\n if (this.fixtures) importFixturesInto(this.state, this.fixtures, this.now)\n }\n\n /**\n * Install a sealed sandbox recording: seed the observation cache and replace the catalog,\n * labs, and lab accounts with the recording's exact values. Re-applied on `reset()`.\n */\n installCorpus(corpus: SealedCorpus): void {\n this.state.corpusObservations = observationsOf(corpus)\n if (corpus.catalog.labTests.length > 0) {\n this.state.replaceCatalog(corpus.catalog)\n }\n this.corpus = corpus\n this.state.teamId = this.explicitTeamId ?? corpus.teamId ?? MOCK_TEAM_ID\n this.state.coveredZips = coveredZipsOf(corpus)\n this.state.corpusLabel = corpusLabel(corpus)\n this.seedLabAccounts()\n }\n\n /**\n * Which lab accounts the ordering rules see, in order of precedence: the configured\n * ones, then a corpus's real accounts, then the built-in fixtures (which a corpus\n * recorded from a team with no accounts leaves in place).\n */\n private seedLabAccounts(): void {\n const recorded = (this.corpus?.labAccounts ?? [])\n .map((entry) => labAccountFromClientFacing(entry, this.corpus?.teamId))\n .filter((entry): entry is StoredLabAccount => entry !== undefined)\n this.state.replaceLabAccounts(\n this.labAccountConfig ?? (recorded.length > 0 ? recorded : [...TEAM_LAB_ACCOUNTS]),\n )\n }\n\n /** The team this namespace answers as. */\n get teamId(): string {\n return this.state.teamId\n }\n\n /**\n * Replace the team's lab accounts (a list, or `{ presets, accounts }`); `undefined`\n * restores the default. Kept across `reset()`, per namespace.\n */\n configureLabAccounts(accounts: LabAccountLayout | undefined): StoredLabAccount[] {\n this.labAccountConfig = accounts\n ? expandLabAccountLayout(accounts, this.state.teamId)\n : undefined\n this.seedLabAccounts()\n return this.state.listLabAccounts()\n }\n\n labAccounts(): StoredLabAccount[] {\n return this.state.listLabAccounts()\n }\n\n /** Apply one change to the effective account list and keep it as this namespace's config. */\n private editLabAccounts(edit: (accounts: StoredLabAccount[]) => StoredLabAccount[]): void {\n this.labAccountConfig = edit([...(this.labAccountConfig ?? this.state.listLabAccounts())])\n this.seedLabAccounts()\n }\n\n /** Add one account. Throws `LabAccountConflict` when the id is taken. Kept across resets. */\n addLabAccount(input: LabAccountInput | StoredLabAccount): StoredLabAccount {\n const record = labAccountFromInput(input as LabAccountInput, this.state.teamId)\n if (this.state.labAccounts.has(record.id)) throw new LabAccountConflict(record.id)\n this.editLabAccounts((accounts) => [...accounts, record])\n return record\n }\n\n /** Add a named preset (see `LAB_ACCOUNT_PRESETS`); `undefined` for an unknown name. */\n addLabAccountPreset(name: string, id?: string): StoredLabAccount | undefined {\n const record = labAccountFromPreset(name, {\n teamId: this.state.teamId,\n ...(id !== undefined ? { id } : {}),\n })\n return record ? this.addLabAccount(record) : undefined\n }\n\n /** Merge fields into an account; `undefined` when there is none with that id. */\n patchLabAccount(id: string, patch: Partial<LabAccountInput>): StoredLabAccount | undefined {\n const existing = this.state.labAccounts.get(id)\n if (!existing) return undefined\n const next = patchLabAccountRecord(existing, patch, this.state.teamId)\n this.editLabAccounts((accounts) => accounts.map((entry) => (entry.id === id ? next : entry)))\n return next\n }\n\n removeLabAccount(id: string): boolean {\n if (!this.state.labAccounts.has(id)) return false\n this.editLabAccounts((accounts) => accounts.filter((entry) => entry.id !== id))\n return true\n }\n\n /** The sandbox limits this namespace enforces. Every one is off unless configured. */\n get limits(): JunctionLimits {\n return { ...this.state.limits }\n }\n\n /** Change some limits (`null` lifts a numeric one); kept across `reset()`. */\n configureLimits(input: JunctionLimitsInput): JunctionLimits {\n this.state.limits = mergeLimits(this.state.limits, input)\n return this.limits\n }\n\n /** Lab slug \u2192 the `billing_type` an order gets when it omits one. Kept across `reset()`. */\n get defaultBillingTypes(): Record<string, BillingType> {\n return { ...this.state.defaultBillingTypes } as Record<string, BillingType>\n }\n\n /** Replace the per-lab default billing types (`{}` restores `client_bill` everywhere). */\n set defaultBillingTypes(input: Partial<Record<string, BillingType>>) {\n this.state.defaultBillingTypes = defaultBillingTypesFrom(input)\n }\n\n get identity(): IdentityMode {\n return this.state.identity\n }\n\n set identity(mode: IdentityMode) {\n if (!IDENTITY_MODES.includes(mode))\n throw new TypeError(`identity must be one of ${IDENTITY_MODES.join(\", \")}`)\n this.state.identity = mode\n }\n\n /** Insert users with chosen ids, all or none. Throws `FixtureError` (400/404/409). */\n insertUsers(users: readonly UserFixture[]): UserRecord[] {\n return insertUsers(this.state, users, this.now)\n }\n\n /** Remove a user outright, leaving no deletion tombstone. */\n hardDeleteUser(userId: string): boolean {\n return hardDeleteUser(this.state, userId)\n }\n\n /** Insert orders, optionally already in a status. No webhook fires unless asked. */\n insertOrders(orders: readonly OrderFixture[], options: InsertOptions = {}): OrderRecord[] {\n return insertOrders(this.state, orders, this.now, options)\n }\n\n /** Load users, then orders, in one call. */\n importFixtures(\n fixtures: JunctionFixtures,\n options: InsertOptions = {},\n ): { users: UserRecord[]; orders: OrderRecord[] } {\n return importFixtures(this.state, fixtures, this.now, options)\n }\n\n corpusInfo(): CorpusInfo | undefined {\n const corpus = this.corpus\n if (!corpus) return undefined\n return {\n label: corpusLabel(corpus),\n recordedAt: corpus.recordedAt,\n source: corpus.source,\n observations: Object.keys(corpus.observations).length,\n labTests: corpus.catalog.labTests.length,\n labAccounts: corpus.labAccounts.length,\n zips: this.state.coveredZips.size,\n ...(corpus.teamId !== undefined ? { teamId: corpus.teamId } : {}),\n }\n }\n\n get geoMode(): GeoMode {\n return this.state.geoMode\n }\n\n set geoMode(mode: GeoMode) {\n this.state.geoMode = mode\n }\n\n order(id: string): OrderRecord | undefined {\n return this.state.orders.get(id)\n }\n\n orders(): OrderRecord[] {\n return this.state.orders.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n /**\n * The lab account an order was placed with: its id, `null` for Junction's platform account,\n * or `undefined` for an unknown order. Junction's order has no such field, so this is the\n * only place the mock reports it.\n */\n orderLabAccount(id: string): string | null | undefined {\n return this.state.orderLabAccounts.get(id)?.lab_account_id\n }\n\n /**\n * Put an order straight into a status (a full `<status>.<method>.<event>` value) and\n * publish the webhook a real transition would. `flags` takes the same keys as\n * `simulate_order`'s body: `interpretation`, `result_types`, `has_missing_results`.\n */\n transitionOrder(\n id: string,\n status: string,\n options: { now: () => number; flags?: Record<string, unknown> | null },\n ): OrderRecord | undefined {\n const order = this.state.orders.get(id)\n if (!order) return undefined\n forceOrderStatus(this.state, order, status, options.flags ?? null, { now: options.now })\n return this.state.orders.get(id)\n }\n\n /** Serve `fixture` as this order's results, replacing the generated ones. */\n installResultFixture(orderId: string, fixture: ResultFixture): boolean {\n const order = this.state.orders.get(orderId)\n if (!order) return false\n if (fixture.interpretation !== undefined) {\n order.interpretation = fixture.interpretation\n this.state.orders.update(orderId, order)\n }\n this.state.resultFixtures.insert(orderId, fixture)\n return true\n }\n\n resultFixture(orderId: string): ResultFixture | undefined {\n return this.state.resultFixtures.get(orderId)\n }\n\n seedFrom(source: SeedSource, observations?: SeedObservations): Promise<SeedReport> {\n return seedStateFrom(this.state, source, observations)\n }\n\n ensureLabTests(source: SeedSource, ids: readonly string[]): Promise<number> {\n return ensureLabTestsFrom(this.state, source, ids)\n }\n\n ensureOrders(source: SeedSource, ids: readonly string[]): Promise<number> {\n return ensureOrdersFrom(this.state, source, ids)\n }\n\n markUserDeleted(userId: string): void {\n this.state.users.delete(userId)\n this.state.deletedUsers.insert(userId, { user_id: userId })\n }\n\n webhookEvents(): JunctionWebhookEvent[] {\n return this.state.webhookEventsInOrder()\n }\n\n webhookDeliveryAttempts() {\n return this.state.webhookDeliveryAttemptsInOrder()\n }\n}\n\n/** Raised by `addLabAccount` for an id the namespace already has. */\nexport class LabAccountConflict extends Error {\n constructor(readonly id: string) {\n super(`lab account ${id} already exists`)\n this.name = \"LabAccountConflict\"\n }\n}\n\n/** Load construction-time fixtures without webhooks; a broken fixture file fails loudly. */\nconst importFixturesInto = (\n state: JunctionState,\n fixtures: JunctionFixtures,\n now: () => number,\n): void => {\n try {\n importFixtures(state, fixtures, now)\n } catch (error) {\n const { message } = fixtureErrorMessage(error)\n throw new Error(`junction fixtures: ${message}`)\n }\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst isJson = (headers: Headers): boolean =>\n (headers.get(\"content-type\") ?? \"\").toLowerCase().includes(\"json\")\n\n/** A request's JSON body, read from a clone so the handler still gets the original. */\nconst requestJson = async (request: Request): Promise<Record<string, unknown> | undefined> => {\n if (request.method === \"GET\" || request.method === \"HEAD\" || !isJson(request.headers))\n return undefined\n return asRecord(\n await request\n .clone()\n .json()\n .catch(() => undefined),\n )\n}\n\nconst UUID_SEGMENT = \"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\"\nconst USER_PATH = new RegExp(`^/v2/user/(${UUID_SEGMENT})(?:/|$)`)\nconst ORDER_PATH = new RegExp(`^/v3/order/(${UUID_SEGMENT})(?:/|$)`)\n\n/**\n * The user, order and lab-account ids a request touched \u2014 from its path, query and body,\n * and from what it created \u2014 for the request journal. Bodies are read, never recorded.\n */\nconst touchedIds = async (\n request: Request,\n body: Record<string, unknown> | undefined,\n response: Response,\n): Promise<Record<string, string>> => {\n const ids: Record<string, string> = {}\n const put = (key: string, value: unknown) => {\n if (typeof value === \"string\" && value !== \"\" && ids[key] === undefined) ids[key] = value\n }\n const url = new URL(request.url)\n put(\"userId\", USER_PATH.exec(url.pathname)?.[1])\n put(\"orderId\", ORDER_PATH.exec(url.pathname)?.[1])\n put(\"userId\", url.searchParams.get(\"user_id\"))\n put(\"orderId\", url.searchParams.get(\"order_id\"))\n put(\"labAccountId\", url.searchParams.get(\"lab_account_id\"))\n put(\"userId\", body?.user_id)\n put(\"labAccountId\", body?.lab_account_id)\n // Only a POST creates an id worth reading back; other bodies (availability, catalogs)\n // are large and already named by the path.\n if (request.method === \"POST\" && response.ok && isJson(response.headers)) {\n const created = asRecord(\n await response\n .clone()\n .json()\n .catch(() => undefined),\n )\n const order = asRecord(created?.order)\n put(\"orderId\", order?.id)\n put(\"userId\", order?.user_id)\n put(\"userId\", created?.user_id)\n }\n return ids\n}\n\n/** Collapse `.`/`..` path segments the way the real server does before routing. */\nconst normalizePath = (request: Request): Request => {\n if (!request.url.includes(\"/./\") && !request.url.includes(\"/../\") && !/%2f/i.test(request.url)) {\n return request\n }\n const url = new URL(request.url)\n const pathname = url.pathname.replace(/%2f/gi, \"/\")\n const segments = pathname.split(\"/\")\n const out: string[] = []\n for (const segment of segments) {\n if (segment === \".\") continue\n if (segment === \"..\") {\n out.pop()\n continue\n }\n out.push(segment)\n }\n while (out.length > 1 && out[out.length - 1] === \"\") out.pop()\n const normalized = out.join(\"/\")\n if (normalized === url.pathname) return request\n const next = new URL(url)\n next.pathname = normalized\n return new Request(next, request)\n}\n"],
|
|
5
|
-
"mappings": ";;;;;AAgCO,IAAM,cAAc,CAAC,SAAuB,KAAK,QAAc;AACpE,MAAI,WAAW;AACf,MAAI;AACJ,QAAM,MAAM,MAAM,YAAY,OAAM,IAAK;AACzC,SAAO;IACL;IACA,KAAK,CAAC,YAAW;AACf,UAAI,aAAa;AAAW,mBAAW;;AAClC,mBAAW,UAAU,OAAM;IAClC;IACA,SAAS,CAAC,YAAW;AACnB,UAAI,aAAa;AAAW,oBAAY;;AACnC,oBAAY;IACnB;IACA,QAAQ,MAAK;AACX,iBAAW,IAAG;IAChB;IACA,UAAU,MAAK;AACb,UAAI,aAAa;AAAW;AAC5B,iBAAW,WAAW,OAAM;AAC5B,iBAAW;IACb;IACA,OAAO,MAAK;AACV,iBAAW;AACX,iBAAW;IACb;IACA,OAAO,OAAO,EAAE,KAAK,IAAG,GAAI,QAAQ,aAAa,QAAW,SAAQ;;AAExE;;;AC1CM,IAAO,aAAP,MAAiB;EAEF;EAER;EAEA;EALX,YACmB,QAER,WAEA,gBAAsB;AAJd,SAAA,SAAA;AAER,SAAA,YAAA;AAEA,SAAA,iBAAA;EACR;EAEK,oBAAiB;AACvB,UAAM,MAAM,KAAK,OACd,QACC,kGAAkG,EAEnG,IAAuB,KAAK,WAAW,KAAK,cAAc;AAC7D,UAAM,QAAQ,KAAK,SAAS,KAAK;AACjC,SAAK,OACF,QACC;iFACyE,EAE1E,IAAI,KAAK,WAAW,KAAK,gBAAgB,IAAI;AAChD,WAAO;EACT;EAEA,eAAY;AACV,WAA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AI,SAAS,KAAK,IAAI,IAAI,SAAS,CAAC,MAAM,GAAI,KAAI,IAAI;AAC7D,QAAM,aAAa,IAAI,KAAK,GAAG;AAC/B,MAAI,eAAe,IAAI,SAAU,QAAOA;AACxC,QAAM,OAAO,IAAI,IAAI,GAAG;AACxB,OAAK,WAAW;AAChB,SAAO,IAAI,QAAQ,MAAMA,QAAO;AAClC;",
|
|
6
|
-
"names": ["request", "instant", "next", "document", "document", "isRecord", "readJson", "render", "request", "json", "document", "isRecord", "request", "request", "document", "isRecord", "json", "adminError", "json", "adminError", "isRecord", "BRANCH_PATTERN", "document", "request", "snapshot", "branch", "BRANCH_PATTERN", "history", "url", "response", "location", "token", "request", "account", "isRecord", "adminError", "isRecord", "request", "seededRandom", "account", "recorded", "notFound", "jsonObject", "isUuid", "uuidError", "name", "details", "stateError", "responseOrder", "isUuid", "isRecord", "document", "RESULT_TYPES", "INTERPRETATIONS", "missing", "clone", "readJson", "seedFrom", "notFound", "queryInt", "missingError", "user", "asRecord", "UUID", "account", "request", "request", "createRuntime", "document", "account", "request", "recorded", "account", "document", "request", "recorded", "seedFrom", "asRecord", "put"]
|
|
7
|
-
}
|