@crvouga/mockingbird-service-vpi 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +164 -0
- package/dist/chunk-32KSYN2C.js +3210 -0
- package/dist/chunk-32KSYN2C.js.map +7 -0
- package/dist/chunk-JYMS3YHP.js +348 -0
- package/dist/chunk-JYMS3YHP.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1038 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1344 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +89 -0
|
@@ -0,0 +1,7 @@
|
|
|
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", "../../../openapi/core/src/schema.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", "../../../openapi/metadata/src/types.ts", "../../../openapi/metadata/src/read.ts", "../../core/src/service.ts", "../../core/src/snapshot.ts", "../../core/src/version.ts", "../../core/src/signing.ts", "../../core/src/webhooks.ts", "../../core/src/runtime.ts", "../../core/src/validation.ts", "../src/catalog.ts", "../src/generated/openapi.ts", "../src/state.ts", "../src/statuses.ts", "../src/runtime.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 private readonly namespace: string,\n private readonly name: 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.name)\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.name, 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.name, 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.name, 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.name, 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.name, 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.name, 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.name, 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.name)\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.name)\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 ...context.describe(),\n })\n }\n if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {\n return undefined\n }\n if (\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 const path = url.pathname.slice(ADMIN_PREFIX.length) || \"/\"\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/** 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", "import { resolveRef } from \"./refs.js\"\nimport type { JsonValue, OpenAPIDocument, SchemaObject, SchemaType } from \"./types.js\"\n\n/**\n * Resolve a schema's `$ref` (merging sibling keywords, as JSON Schema 2020-12 allows) and\n * normalise OpenAPI 3.0 `nullable` into a 3.1 type array.\n */\nexport const resolveSchema = (document: OpenAPIDocument, schema: SchemaObject): SchemaObject => {\n let current = schema\n const seen = new Set<string>()\n while (typeof current.$ref === \"string\") {\n const ref = current.$ref\n if (seen.has(ref)) break\n seen.add(ref)\n const { $ref: _ignored, ...siblings } = current\n const target = resolveRef(document, ref) as SchemaObject\n current = { ...target, ...siblings }\n }\n if (current.nullable === true) {\n const { nullable: _nullable, ...rest } = current\n const types = schemaTypes(rest)\n if (types.length > 0 && !types.includes(\"null\")) current = { ...rest, type: [...types, \"null\"] }\n else current = rest\n }\n return current\n}\n\n/** Declared JSON types of a schema (empty when unconstrained). */\nexport const schemaTypes = (schema: SchemaObject): SchemaType[] => {\n if (Array.isArray(schema.type)) return schema.type\n if (schema.type !== undefined) return [schema.type]\n const inferred: SchemaType[] = []\n if (schema.properties || schema.required || schema.additionalProperties !== undefined)\n inferred.push(\"object\")\n if (\n schema.items ||\n schema.prefixItems ||\n schema.minItems !== undefined ||\n schema.maxItems !== undefined\n )\n inferred.push(\"array\")\n if (\n schema.minLength !== undefined ||\n schema.maxLength !== undefined ||\n schema.pattern !== undefined\n )\n inferred.push(\"string\")\n if (\n schema.minimum !== undefined ||\n schema.maximum !== undefined ||\n schema.multipleOf !== undefined\n )\n inferred.push(\"number\")\n return inferred\n}\n\n/** The JSON type name of a runtime value. */\nexport const jsonTypeOf = (value: unknown): SchemaType | \"undefined\" => {\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 \"boolean\":\n return \"boolean\"\n case \"number\":\n return Number.isInteger(value) ? \"integer\" : \"number\"\n case \"object\":\n return \"object\"\n default:\n return \"undefined\"\n }\n}\n\nexport type SchemaVisitor = (schema: SchemaObject, path: string[]) => void\n\n/**\n * Depth-first walk over a schema tree, resolving `$ref`s. Each resolved schema is visited once per\n * call: the annotation consumers (identities, refs, volatile/scope marks) only care that a node is\n * reachable, and visiting per path is exponential on densely cross-referenced documents.\n */\nexport const walkSchema = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n visit: SchemaVisitor,\n path: string[] = [],\n) => {\n const seen = new Set<SchemaObject>()\n const go = (node: SchemaObject, at: string[]) => {\n const resolved = resolveSchema(document, node)\n if (seen.has(resolved)) return\n seen.add(resolved)\n visit(resolved, at)\n for (const [name, child] of Object.entries(resolved.properties ?? {}))\n go(child, [...at, \"properties\", name])\n if (typeof resolved.additionalProperties === \"object\")\n go(resolved.additionalProperties, [...at, \"additionalProperties\"])\n if (resolved.items) go(resolved.items, [...at, \"items\"])\n resolved.prefixItems?.forEach((child, i) => {\n go(child, [...at, \"prefixItems\", String(i)])\n })\n resolved.propertyNames && go(resolved.propertyNames, [...at, \"propertyNames\"])\n for (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n resolved[keyword]?.forEach((child, i) => {\n go(child, [...at, keyword, String(i)])\n })\n }\n resolved.not && go(resolved.not, [...at, \"not\"])\n }\n go(schema, path)\n}\nexport type ValidationError = { path: Array<string | number>; message: string }\n\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true\n if (typeof a !== typeof b || a === null || b === null) return false\n if (Array.isArray(a)) {\n return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]))\n }\n if (typeof a === \"object\" && typeof b === \"object\" && !Array.isArray(b)) {\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n return (\n ka.length === kb.length &&\n ka.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n )\n }\n return false\n}\n\nconst FORMAT_PATTERNS: Record<string, RegExp> = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,\n date: /^\\d{4}-\\d{2}-\\d{2}$/,\n \"date-time\": /^\\d{4}-\\d{2}-\\d{2}[Tt ]\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/,\n email: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\\s]*$/,\n ipv4: /^(25[0-5]|2[0-4]\\d|1?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$/,\n}\n\nconst graphemeLength = (value: string) => [...value].length\n\n/**\n * Validate `value` against `schema`. Supports the JSON Schema subset Mockingbird generates from\n * (see `@crvouga/mockingbird-openapi-arbitrary`). Returns an empty array when valid.\n */\nexport const validateValue = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n value: unknown,\n path: Array<string | number> = [],\n): ValidationError[] => {\n const errors: ValidationError[] = []\n const s = resolveSchema(document, schema)\n const fail = (message: string) => errors.push({ path, message })\n const actual = jsonTypeOf(value)\n if (actual === \"undefined\") {\n fail(\"value is undefined\")\n return errors\n }\n const types = schemaTypes(s)\n if (types.length > 0) {\n const ok = types.some((t) => t === actual || (t === \"number\" && actual === \"integer\"))\n if (!ok) {\n fail(`expected type ${types.join(\"|\")}, got ${actual}`)\n return errors\n }\n }\n // OpenAPI commonly pairs `type: [\"string\",\"null\"]` with an enum of the non-null values;\n // null is admitted by the type union and must not fail the enum check.\n if (\n s.enum &&\n !(value === null && types.includes(\"null\")) &&\n !s.enum.some((candidate) => deepEqual(candidate, value))\n ) {\n fail(\"value not in enum\")\n }\n if (s.const !== undefined && !deepEqual(s.const, value)) fail(\"value does not equal const\")\n if (typeof value === \"string\") {\n const length = graphemeLength(value)\n if (s.minLength !== undefined && length < s.minLength)\n fail(`length ${length} < minLength ${s.minLength}`)\n if (s.maxLength !== undefined && length > s.maxLength)\n fail(`length ${length} > maxLength ${s.maxLength}`)\n if (s.pattern !== undefined) {\n try {\n if (!new RegExp(s.pattern, \"u\").test(value)) fail(`does not match pattern ${s.pattern}`)\n } catch {\n // unsupported pattern syntax: skip, matching lenient validators\n }\n }\n if (s.format !== undefined) {\n const pattern = FORMAT_PATTERNS[s.format]\n if (pattern && !pattern.test(value)) fail(`does not match format ${s.format}`)\n }\n }\n if (typeof value === \"number\") {\n if (s.minimum !== undefined && value < s.minimum) fail(`${value} < minimum ${s.minimum}`)\n if (s.maximum !== undefined && value > s.maximum) fail(`${value} > maximum ${s.maximum}`)\n if (s.exclusiveMinimum !== undefined && value <= s.exclusiveMinimum)\n fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`)\n if (s.exclusiveMaximum !== undefined && value >= s.exclusiveMaximum)\n fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`)\n if (\n s.multipleOf !== undefined &&\n Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9\n ) {\n fail(`${value} is not a multiple of ${s.multipleOf}`)\n }\n }\n if (Array.isArray(value)) {\n if (s.minItems !== undefined && value.length < s.minItems)\n fail(`${value.length} items < minItems ${s.minItems}`)\n if (s.maxItems !== undefined && value.length > s.maxItems)\n fail(`${value.length} items > maxItems ${s.maxItems}`)\n if (\n s.uniqueItems &&\n value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item)))\n )\n fail(\"items are not unique\")\n value.forEach((item, i) => {\n const itemSchema = s.prefixItems?.[i] ?? s.items\n if (itemSchema) errors.push(...validateValue(document, itemSchema, item, [...path, i]))\n })\n }\n if (actual === \"object\") {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record)\n for (const name of s.required ?? [])\n if (!(name in record)) fail(`missing required property ${name}`)\n if (s.minProperties !== undefined && keys.length < s.minProperties)\n fail(`${keys.length} properties < minProperties ${s.minProperties}`)\n if (s.maxProperties !== undefined && keys.length > s.maxProperties)\n fail(`${keys.length} properties > maxProperties ${s.maxProperties}`)\n for (const key of keys) {\n const property = s.properties?.[key]\n if (property) {\n errors.push(...validateValue(document, property, record[key], [...path, key]))\n continue\n }\n if (s.additionalProperties === false) fail(`unexpected property ${key}`)\n else if (typeof s.additionalProperties === \"object\") {\n errors.push(...validateValue(document, s.additionalProperties, record[key], [...path, key]))\n }\n if (s.propertyNames) {\n const nameErrors = validateValue(document, s.propertyNames, key, [...path, key])\n if (nameErrors.length > 0)\n fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`)\n }\n }\n }\n if (s.allOf)\n for (const branch of s.allOf) errors.push(...validateValue(document, branch, value, path))\n if (s.anyOf && !s.anyOf.some((branch) => validateValue(document, branch, value).length === 0))\n fail(\"matches no anyOf branch\")\n if (s.oneOf) {\n const matches = s.oneOf.filter(\n (branch) => validateValue(document, branch, value).length === 0,\n ).length\n if (matches !== 1) fail(`matches ${matches} oneOf branches, expected exactly 1`)\n }\n if (s.not && validateValue(document, s.not, value).length === 0)\n fail(\"matches forbidden `not` schema\")\n return errors\n}\n\nexport const isValid = (document: OpenAPIDocument, schema: SchemaObject, value: unknown) =>\n validateValue(document, schema, value).length === 0\n\nexport type { JsonValue }\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\"\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}\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", "/** 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}\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 * 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\"\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 if (short) return short\n return 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 { 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", "/**\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", "/**\n * HMAC and encoding primitives for vendor webhook signatures, over WebCrypto so they run\n * wherever the mocks do (Node, Bun, workers).\n */\n\nexport type HmacAlgorithm = \"SHA-1\" | \"SHA-256\" | \"SHA-512\"\nexport type ByteEncoding = \"hex\" | \"base64\"\n\nconst encoder = new TextEncoder()\n\nexport const toBase64 = (bytes: ArrayBuffer | Uint8Array): string => {\n let binary = \"\"\n for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary)\n}\n\nexport const fromBase64 = (value: string): Uint8Array =>\n Uint8Array.from(atob(value), (char) => char.charCodeAt(0))\n\nexport const toHex = (bytes: ArrayBuffer | Uint8Array): string =>\n [...(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")\n\nconst keyBytes = (key: string | Uint8Array): Uint8Array =>\n typeof key === \"string\" ? encoder.encode(key) : key\n\n/** HMAC of `message` under `key` (a UTF-8 string or raw bytes), encoded as hex or base64. */\nexport const hmac = async (\n algorithm: HmacAlgorithm,\n key: string | Uint8Array,\n message: string | Uint8Array,\n encoding: ByteEncoding = \"hex\",\n): Promise<string> => {\n const imported = await crypto.subtle.importKey(\n \"raw\",\n keyBytes(key) as BufferSource,\n { name: \"HMAC\", hash: algorithm },\n false,\n [\"sign\"],\n )\n const signed = await crypto.subtle.sign(\n \"HMAC\",\n imported,\n (typeof message === \"string\" ? encoder.encode(message) : message) as BufferSource,\n )\n return encoding === \"hex\" ? toHex(signed) : toBase64(signed)\n}\n\n/** SHA digest of `input`, hex-encoded. */\nexport const sha = async (\n algorithm: \"SHA-1\" | \"SHA-256\" | \"SHA-512\",\n input: string | Uint8Array,\n): Promise<string> =>\n toHex(\n await crypto.subtle.digest(\n algorithm,\n (typeof input === \"string\" ? encoder.encode(input) : input) as BufferSource,\n ),\n )\n\n/**\n * The raw key of a Svix-style secret: `whsec_<base64>` (Svix, Resend, Junction) or\n * `fwhsec_<base64>` (Flex). A bare base64 secret is accepted too.\n */\nexport const svixSecretBytes = (secret: string): Uint8Array => {\n const raw = secret.replace(/^f?whsec_/, \"\")\n try {\n return fromBase64(raw)\n } catch {\n throw new TypeError(\"webhook secret must be whsec_<base64> (as Svix issues it)\")\n }\n}\n\n/** `v1,<base64 HMAC-SHA256>` over `\"<id>.<timestamp>.<body>\"`, as Svix signs. */\nexport const signSvix = async (\n secret: string,\n messageId: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `v1,${await hmac(\"SHA-256\", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, \"base64\")}`\n\n/** `t=<unix>,v1=<hex HMAC-SHA256(secret, \"<t>.<body>\")>`, as Stripe (and Persona) sign. */\nexport const signTimestamped = async (\n secret: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `t=${timestampSeconds},v1=${await hmac(\"SHA-256\", secret, `${timestampSeconds}.${body}`, \"hex\")}`\n\n/**\n * Twilio's `X-Twilio-Signature`: base64 HMAC-SHA1 of the full URL followed by every form\n * parameter as `key + value`, keys sorted. Sign against the public URL the app is\n * configured with, not the address the request is actually posted to.\n */\nexport const signTwilio = async (\n authToken: string,\n url: string,\n params: Record<string, string>,\n): Promise<string> => {\n const payload =\n url +\n Object.keys(params)\n .sort()\n .map((key) => `${key}${params[key]}`)\n .join(\"\")\n return hmac(\"SHA-1\", authToken, payload, \"base64\")\n}\n\n/** Constant-time string comparison, so a verifier in a test double does not leak timing. */\nexport const timingSafeEqual = (a: string, b: string): boolean => {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\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 always use the wall clock, never the mock\n * clock: receivers check them against their own time, and an advanced mock clock would\n * otherwise fail every delivery.\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 /** Wall-clock unix seconds of this attempt. */\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 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. */\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\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 run = () => {\n pending.delete(delivery.id)\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 pending.set(delivery.id, undefined)\n run()\n return\n }\n const timer = scheduleTimer(run, 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 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 },\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 { 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 FaultRegistry,\n type FaultRule,\n} from \"./faults.js\"\nimport { createJournal, DEFAULT_JOURNAL_SIZE, type Journal, responseNotes } from \"./journal.js\"\nimport { createMetrics, type Metrics, 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 { 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\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}\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 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 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 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 const log = (status: number, faultId?: string, response?: Response) => {\n const noted = response ? responseNotes(response) : 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 }\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.presets ? presetRoutes(options.presets, runtime) : {}),\n ...(options.webhooks ? webhookAdminRoutes(options.webhooks) : {}),\n ...(options.admin?.(runtime) ?? {}),\n },\n adminKey: options.adminKey,\n })\n\n return 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 adminJson(200, {\n presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset })),\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", "import {\n deref,\n resolveSchema,\n type SchemaObject,\n validateValue,\n} from \"@crvouga/mockingbird-openapi\"\nimport type { OperationContext } from \"./service.js\"\n\n/** One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`). */\nexport type BodyIssue = { path: string; message: string }\n\n/**\n * Validate the decoded JSON body against the operation's `requestBody` schema in the vendor\n * contract. Returns `[]` when valid, or when the operation declares no JSON body. Services\n * turn the issues into the vendor's own validation error shape.\n */\nexport const bodyIssues = (\n context: OperationContext,\n contentType = \"application/json\",\n): BodyIssue[] => {\n const requestBody = context.operation.operation.requestBody\n if (!requestBody) return []\n const resolved = deref(context.document, requestBody) as {\n required?: boolean\n content?: Record<string, { schema?: SchemaObject }>\n }\n const schema = resolved.content?.[contentType]?.schema\n if (!schema) return []\n const value =\n context.body.kind === \"json\" || context.body.kind === \"form\" ? context.body.value : undefined\n if (context.body.kind === \"invalid\") {\n return [{ path: \"\", message: `request body is not valid ${context.body.mediaType}` }]\n }\n if (value === undefined) {\n return resolved.required ? [{ path: \"\", message: \"request body is required\" }] : []\n }\n return validateValue(context.document, resolveSchema(context.document, schema), value).map(\n (issue) => ({ path: issue.path.join(\".\"), 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", "/**\n * The seed every namespace starts with: one clinic, one location, the authenticated clinic\n * user, two providers, a small product catalog in VPI's own field names, and one patient.\n * Synthesised in the shapes our client's zod contracts accept (no sandbox recording exists);\n * pass `seed` to `createRuntime` to replace any of it.\n */\n\n/** The clinic user every authenticated account resolves to unless `accounts` names others. */\nexport const DEFAULT_USER_ID = \"65a1c0de00000000000000a1\"\nexport const DEFAULT_CLINIC_ID = \"65a1c0de00000000000000c1\"\nexport const DEFAULT_CLINIC_LOCATION_ID = \"65a1c0de00000000000000d1\"\nexport const DEFAULT_PROVIDER_ID = \"65a1c0de00000000000000e1\"\nexport const DEFAULT_PATIENT_ID = \"65a1c0de00000000000000f1\"\n\n/** A product as VPI stores it; the list, details and discount endpoints project from it. */\nexport type Product = {\n /** Mongo id: what every endpoint (details, discounts, day supply, save) keys on. */\n id: string\n /** VPI catalog code, e.g. `2185_INJ`. */\n productId: string\n name: string\n unitPrice: number\n family: string\n subCategory1: string\n subCategory2: string\n commonName: string\n sigOptions: string[]\n productSize: string\n medicalAccessories: \"0\" | \"1\"\n coldShipped: \"0\" | \"1\"\n controlledSubstance: \"0\" | \"1\"\n dispenseType: string\n reasonForCompoundedMedication: string[] | null\n isReasonForCompoundedMedicationNeeded: boolean\n productType: \"S\" | \"NS\"\n patientPayAmount: number | null\n ndc: number | null\n /** The clinic's discount, in percent. */\n discountedPercentage: number\n}\n\nexport type Provider = {\n id: string\n firstName: string\n lastName: string\n npi: string | null\n clinicLocationId: string\n}\n\nexport type ClinicLocation = {\n id: string\n clinicId: string\n locationName: string\n email: string | null\n fax: string | null\n addressLine1: string | null\n addressLine2: string | null\n city: string | null\n zipcode: string | null\n state: string | null\n}\n\nexport type PatientAddress = {\n id: string\n addressLine1: string\n addressLine2: string | null\n city: string\n state: string\n zipcode: string\n}\n\n/** A clinic patient; VPI patient creation is not captured by our client, so suites seed them. */\nexport type Patient = {\n id: string\n clinicId: string\n firstName: string\n lastName: string\n dateOfBirth: string\n email: string | null\n phoneNumber: string | null\n cellPhone: string | null\n addresses: PatientAddress[]\n}\n\nconst REASONS = [\n \"Product Discontinued - commercial product no longer available or in shortage\",\n \"Dosage Form Change - patient needs a different dosage form\",\n \"Different Strength - patient needs a strength not commercially available\",\n \"Excipient Allergy - patient is allergic to an inactive ingredient\",\n \"Other - reason not otherwise listed\",\n]\n\nexport const DEFAULT_PRODUCTS: readonly Product[] = [\n {\n id: \"64f1c2a9e4b0a1b2c3d4e5f6\",\n productId: \"2185_INJ\",\n name: \"Testosterone Cypionate\",\n unitPrice: 45.5,\n family: \"Hormone Restoration\",\n subCategory1: \"Testosterone\",\n subCategory2: \"Injectables\",\n commonName: \"Testosterone Cypionate\",\n sigOptions: [\"Inject 0.5 mL intramuscularly once weekly\"],\n productSize: \"10mL\",\n medicalAccessories: \"0\",\n coldShipped: \"0\",\n controlledSubstance: \"0\",\n dispenseType: \"Vial\",\n reasonForCompoundedMedication: REASONS,\n isReasonForCompoundedMedicationNeeded: true,\n productType: \"S\",\n patientPayAmount: 62.5,\n ndc: 12345678901,\n discountedPercentage: 10,\n },\n {\n id: \"64f1c2a9e4b0a1b2c3d4e5f7\",\n productId: \"3097_POW\",\n name: \"Semaglutide / B6 Troche\",\n unitPrice: 7.5,\n family: \"Weight Management\",\n subCategory1: \"GLP-1\",\n subCategory2: \"Troches\",\n commonName: \"Semaglutide\",\n sigOptions: [\"Dissolve 1 troche under the tongue daily\"],\n productSize: \"30ea\",\n medicalAccessories: \"0\",\n coldShipped: \"1\",\n controlledSubstance: \"0\",\n dispenseType: \"Troche\",\n reasonForCompoundedMedication: REASONS,\n isReasonForCompoundedMedicationNeeded: true,\n productType: \"NS\",\n patientPayAmount: 30,\n ndc: null,\n discountedPercentage: 0,\n },\n {\n id: \"64f1c2a9e4b0a1b2c3d4e5f8\",\n productId: \"4410_CAP\",\n name: \"Enclomiphene Citrate 25 mg\",\n unitPrice: 1.2,\n family: \"Hormone Restoration\",\n subCategory1: \"Testosterone\",\n subCategory2: \"Capsules\",\n commonName: \"Enclomiphene\",\n sigOptions: [\"Take 1 capsule by mouth daily\"],\n productSize: \"30ea\",\n medicalAccessories: \"0\",\n coldShipped: \"0\",\n controlledSubstance: \"0\",\n dispenseType: \"Capsule\",\n reasonForCompoundedMedication: null,\n isReasonForCompoundedMedicationNeeded: false,\n productType: \"NS\",\n patientPayAmount: 40,\n ndc: null,\n discountedPercentage: 5,\n },\n {\n id: \"64f1c2a9e4b0a1b2c3d4e5f9\",\n productId: \"5120_INJ\",\n name: \"Nandrolone Decanoate\",\n unitPrice: 55,\n family: \"Hormone Restoration\",\n subCategory1: \"Testosterone\",\n subCategory2: \"Injectables\",\n commonName: \"Nandrolone\",\n sigOptions: [],\n productSize: \"5mL\",\n medicalAccessories: \"0\",\n coldShipped: \"0\",\n controlledSubstance: \"1\",\n dispenseType: \"Vial\",\n reasonForCompoundedMedication: REASONS,\n isReasonForCompoundedMedicationNeeded: true,\n productType: \"S\",\n patientPayAmount: 80,\n ndc: null,\n discountedPercentage: 0,\n },\n]\n\nexport const DEFAULT_CLINIC_LOCATION: ClinicLocation = {\n id: DEFAULT_CLINIC_LOCATION_ID,\n clinicId: DEFAULT_CLINIC_ID,\n locationName: \"Geviti Main\",\n email: \"pharmacy@example.com\",\n fax: \"5555550100\",\n addressLine1: \"100 Clinic Way\",\n addressLine2: null,\n city: \"Phoenix\",\n zipcode: \"85004\",\n state: \"AZ\",\n}\n\nexport const DEFAULT_PROVIDERS: readonly Provider[] = [\n {\n id: DEFAULT_PROVIDER_ID,\n firstName: \"Grace\",\n lastName: \"Hopper\",\n npi: \"1234567893\",\n clinicLocationId: DEFAULT_CLINIC_LOCATION_ID,\n },\n {\n id: \"65a1c0de00000000000000e2\",\n firstName: \"Alan\",\n lastName: \"Turing\",\n npi: \"1987654320\",\n clinicLocationId: DEFAULT_CLINIC_LOCATION_ID,\n },\n]\n\nexport const DEFAULT_PATIENTS: readonly Patient[] = [\n {\n id: DEFAULT_PATIENT_ID,\n clinicId: DEFAULT_CLINIC_ID,\n firstName: \"Ada\",\n lastName: \"Lovelace\",\n dateOfBirth: \"1985-02-14\",\n email: \"ada@example.com\",\n phoneNumber: \"6025550142\",\n cellPhone: null,\n addresses: [\n {\n id: \"65a1c0de0000000000000af1\",\n addressLine1: \"1 Main St\",\n addressLine2: null,\n city: \"Phoenix\",\n state: \"AZ\",\n zipcode: \"85004\",\n },\n ],\n },\n]\n\n/** Every state VPI ships to, by the full name its API uses (sterile shipping excluded in two). */\nexport const SHIPPING_STATES: readonly {\n name: string\n booleanCheck: boolean\n nonSterile: boolean\n sterile: boolean\n}[] = [\n \"Alabama\",\n \"Alaska\",\n \"Arizona\",\n \"Arkansas\",\n \"California\",\n \"Colorado\",\n \"Connecticut\",\n \"Delaware\",\n \"Florida\",\n \"Georgia\",\n \"Hawaii\",\n \"Idaho\",\n \"Illinois\",\n \"Indiana\",\n \"Iowa\",\n \"Kansas\",\n \"Kentucky\",\n \"Louisiana\",\n \"Maine\",\n \"Maryland\",\n \"Massachusetts\",\n \"Michigan\",\n \"Minnesota\",\n \"Mississippi\",\n \"Missouri\",\n \"Montana\",\n \"Nebraska\",\n \"Nevada\",\n \"New Hampshire\",\n \"New Jersey\",\n \"New Mexico\",\n \"New York\",\n \"North Carolina\",\n \"North Dakota\",\n \"Ohio\",\n \"Oklahoma\",\n \"Oregon\",\n \"Pennsylvania\",\n \"Rhode Island\",\n \"South Carolina\",\n \"South Dakota\",\n \"Tennessee\",\n \"Texas\",\n \"Utah\",\n \"Vermont\",\n \"Virginia\",\n \"Washington\",\n \"West Virginia\",\n \"Wisconsin\",\n \"Wyoming\",\n \"District of Columbia\",\n].map((name) => ({\n name,\n booleanCheck: name !== \"District of Columbia\",\n nonSterile: true,\n sterile: name !== \"Alabama\" && name !== \"District of Columbia\",\n}))\n\n/** Full state name \u2194 2-letter code, for the canonical-name checks and the shipping-rate lookup. */\nexport const STATE_CODES: Readonly<Record<string, string>> = {\n Alabama: \"AL\",\n Alaska: \"AK\",\n Arizona: \"AZ\",\n Arkansas: \"AR\",\n California: \"CA\",\n Colorado: \"CO\",\n Connecticut: \"CT\",\n Delaware: \"DE\",\n Florida: \"FL\",\n Georgia: \"GA\",\n Hawaii: \"HI\",\n Idaho: \"ID\",\n Illinois: \"IL\",\n Indiana: \"IN\",\n Iowa: \"IA\",\n Kansas: \"KS\",\n Kentucky: \"KY\",\n Louisiana: \"LA\",\n Maine: \"ME\",\n Maryland: \"MD\",\n Massachusetts: \"MA\",\n Michigan: \"MI\",\n Minnesota: \"MN\",\n Mississippi: \"MS\",\n Missouri: \"MO\",\n Montana: \"MT\",\n Nebraska: \"NE\",\n Nevada: \"NV\",\n \"New Hampshire\": \"NH\",\n \"New Jersey\": \"NJ\",\n \"New Mexico\": \"NM\",\n \"New York\": \"NY\",\n \"North Carolina\": \"NC\",\n \"North Dakota\": \"ND\",\n Ohio: \"OH\",\n Oklahoma: \"OK\",\n Oregon: \"OR\",\n Pennsylvania: \"PA\",\n \"Rhode Island\": \"RI\",\n \"South Carolina\": \"SC\",\n \"South Dakota\": \"SD\",\n Tennessee: \"TN\",\n Texas: \"TX\",\n Utah: \"UT\",\n Vermont: \"VT\",\n Virginia: \"VA\",\n Washington: \"WA\",\n \"West Virginia\": \"WV\",\n Wisconsin: \"WI\",\n Wyoming: \"WY\",\n \"District of Columbia\": \"DC\",\n \"American Samoa\": \"AS\",\n Guam: \"GU\",\n \"Northern Mariana Islands\": \"MP\",\n \"Puerto Rico\": \"PR\",\n \"U.S. Virgin Islands\": \"VI\",\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\":\"VPI compounding pharmacy API (Mockingbird subset)\",\"description\":\"Stateful mock subset of the VPI (vpicompounding.net) clinic API our backend drives as a\\\\ndraft-only eRx rail: JWT authentication, product taxonomy/details/discounts, day supply,\\\\nshipping states and rates, clinic location, providers, patients, the provider-signature\\\\nduplicate check, saveNewPrescription, and the three paged prescription status lists.\\\\nHand-derived from the consumer's zod contracts (the vendor publishes no spec).\\\\n\",\"version\":\"1\",\"x-mockingbird-upstream\":{\"note\":\"Hand-derived from apps/backend/src/modules/erx/clients/vpi-api.contracts.ts and the client-local schemas in vpi-api.client.ts (request bodies are exactly what the client sends; responses are what its zod schemas accept).\"}},\"servers\":[{\"url\":\"https://api.vpicompounding.net\"}],\"security\":[{\"bearerAuth\":[]}],\"paths\":{\"/accounts/authenticate\":{\"post\":{\"operationId\":\"Authenticate\",\"security\":[],\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"email\",\"password\"],\"properties\":{\"email\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":120},\"password\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":120},\"isPatientLogin\":{\"type\":\"boolean\"}}}}}},\"responses\":{\"200\":{\"description\":\"JWT and refresh token\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AuthTokens\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/products/getAllFamiliesAndCategories\":{\"get\":{\"operationId\":\"GetAllFamiliesAndCategories\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Product families and their categories (subCategory1)\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"family\",\"categories\"],\"properties\":{\"family\":{\"type\":\"string\"},\"categories\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}}}}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/products/getProductsByCategory\":{\"post\":{\"operationId\":\"GetProductsByCategory\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"category\",\"subCategory1\"],\"examples\":[{\"category\":\"Hormone Restoration\",\"subCategory1\":\"Testosterone\"},{\"category\":\"Weight Management\",\"subCategory1\":\"GLP-1\"}],\"properties\":{\"category\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80,\"examples\":[\"Hormone Restoration\",\"Weight Management\"]},\"subCategory1\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80,\"examples\":[\"Testosterone\",\"GLP-1\"]}}}}}},\"responses\":{\"200\":{\"description\":\"Products grouped by subCategory2, then common name\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"subCategory2_item\",\"commonNames\"],\"properties\":{\"subCategory2_item\":{\"type\":\"string\"},\"commonNames\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"commonName\",\"products\"],\"properties\":{\"commonName\":{\"type\":\"string\"},\"products\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ProductSummary\"}}}}}}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/products/getProductDetailsByProductId/{productId}\":{\"parameters\":[{\"name\":\"productId\",\"in\":\"path\",\"required\":true,\"description\":\"The product's Mongo id (\\`id\\`), not its catalog code.\",\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}}}],\"get\":{\"operationId\":\"GetProductDetailsByProductId\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Product details\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ProductDetails\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/products/getProductDiscountByProductIds\":{\"post\":{\"operationId\":\"GetProductDiscountByProductIds\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicId\",\"productIds\"],\"properties\":{\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"},\"productIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":5,\"items\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}}}}}}}},\"responses\":{\"200\":{\"description\":\"The clinic's discount for each known product\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ProductDiscount\"}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/products/calculateDaySupply\":{\"post\":{\"operationId\":\"CalculateDaySupply\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"productId\",\"quantity\",\"sig\"],\"properties\":{\"productId\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}},\"quantity\":{\"type\":\"number\",\"exclusiveMinimum\":0,\"maximum\":1000},\"sig\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":500}}}}}},\"responses\":{\"200\":{\"description\":\"Day supply\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"daySupply\"],\"properties\":{\"daySupply\":{\"type\":\"integer\",\"minimum\":1},\"daySupplyReason\":{\"type\":[\"string\",\"null\"]}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/admin/rxOrdering/getShippingStates\":{\"get\":{\"operationId\":\"GetShippingStates\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"States VPI ships to, by full name\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"states\"],\"properties\":{\"states\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"name\",\"booleanCheck\",\"nonSterile\",\"sterile\"],\"properties\":{\"name\":{\"type\":\"string\"},\"booleanCheck\":{\"type\":\"boolean\"},\"nonSterile\":{\"type\":\"boolean\"},\"sterile\":{\"type\":\"boolean\"}}}}}}}}}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/portal/getShippingRate\":{\"post\":{\"operationId\":\"GetShippingRate\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicId\",\"clinicLocationId\",\"patientId\",\"productIds\",\"shippingState\",\"isRushOrder\"],\"properties\":{\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"},\"clinicLocationId\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"},\"patientId\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"patient\",\"missing\":0}},\"productIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":5,\"items\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}}},\"shippingState\":{\"type\":\"string\",\"pattern\":\"^[A-Za-z]{2}$\",\"examples\":[\"AZ\",\"TX\",\"NY\"]},\"isRushOrder\":{\"type\":\"boolean\"}}}}}},\"responses\":{\"200\":{\"description\":\"Shipping method and rush cost\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"shippingMethod\",\"rushOrderCost\",\"rushOrderMethod\",\"isSignatureRequired\"],\"properties\":{\"shippingMethod\":{\"type\":\"string\"},\"rushOrderCost\":{\"type\":\"number\",\"minimum\":0},\"rushOrderMethod\":{\"type\":\"string\"},\"isSignatureRequired\":{\"type\":\"boolean\"}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/clinic/rxOrdering/checkProviderSignatureNeededDuplicate\":{\"post\":{\"operationId\":\"CheckProviderSignatureNeededDuplicate\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicId\",\"patientIds\",\"productIds\",\"clinicLocationIds\"],\"properties\":{\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"},\"patientIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":3,\"items\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"patient\",\"missing\":0}}},\"productIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":3,\"items\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}}},\"clinicLocationIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":3,\"items\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"}}}}}}},\"responses\":{\"200\":{\"description\":\"Duplicate and provider-signature flags\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"isDuplicate\",\"isProviderSignatureNeeded\"],\"properties\":{\"isDuplicate\":{\"type\":\"boolean\"},\"isProviderSignatureNeeded\":{\"type\":\"boolean\"}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/clinic/rxOrdering/saveNewPrescription\":{\"post\":{\"operationId\":\"SaveNewPrescription\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/SavePrescriptionBody\"}}}},\"responses\":{\"200\":{\"description\":\"Draft saved (awaiting provider signature)\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"message\",\"prescriptionId\",\"isRefillRequest\",\"refillFromPrescriptionId\"],\"properties\":{\"message\":{\"type\":\"string\"},\"prescriptionId\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"prescription\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"isRefillRequest\":{\"type\":\"boolean\"},\"refillFromPrescriptionId\":{\"type\":[\"string\",\"null\"]}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"},\"409\":{\"$ref\":\"#/components/responses/Conflict\"},\"429\":{\"$ref\":\"#/components/responses/Conflict\"}}}},\"/patients/getPatientByPatientId\":{\"post\":{\"operationId\":\"GetPatientByPatientId\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PatientLookupBody\"}}}},\"responses\":{\"200\":{\"description\":\"Patient\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Patient\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/patients/getPatientAddressesByPatientId\":{\"post\":{\"operationId\":\"GetPatientAddressesByPatientId\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PatientLookupBody\"}}}},\"responses\":{\"200\":{\"description\":\"The patient's addresses\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"addresses\"],\"properties\":{\"addresses\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Address\"}}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/patients/getPatientsInClinic\":{\"post\":{\"operationId\":\"GetPatientsInClinic\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicId\",\"userId\",\"limit\",\"currentPage\"],\"examples\":[{\"clinicId\":\"65a1c0de00000000000000c1\",\"userId\":\"65a1c0de00000000000000a1\",\"limit\":100,\"currentPage\":1}],\"properties\":{\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"},\"userId\":{\"$ref\":\"#/components/schemas/UserId\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100},\"currentPage\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":50}}}}}},\"responses\":{\"200\":{\"description\":\"One page of the clinic's patient roster\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"pagination\",\"patients\"],\"properties\":{\"pagination\":{\"type\":\"object\",\"required\":[\"hasNextPage\"],\"properties\":{\"hasNextPage\":{\"type\":\"boolean\"},\"currentPage\":{\"type\":\"integer\"},\"limit\":{\"type\":\"integer\"},\"totalCount\":{\"type\":\"integer\"}}},\"patients\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Patient\"}}}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/staffs/getAllProvidersByClinicLocationId\":{\"post\":{\"operationId\":\"GetAllProvidersByClinicLocationId\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicLocationId\",\"clinicId\"],\"properties\":{\"clinicLocationId\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"},\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"}}}}}},\"responses\":{\"200\":{\"description\":\"Providers at the location\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Provider\"}}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/clinicLocations/getClinicLocationByClinicLocationId\":{\"post\":{\"operationId\":\"GetClinicLocationByClinicLocationId\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"clinicLocationId\"],\"properties\":{\"clinicLocationId\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"}}}}}},\"responses\":{\"200\":{\"description\":\"Clinic location\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClinicLocation\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/clinic/rxOrdering/getIncompleteSavedPrescriptionsInClinicLocation\":{\"post\":{\"operationId\":\"GetIncompleteSavedPrescriptionsInClinicLocation\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PrescriptionPageBody\"}}}},\"responses\":{\"200\":{\"$ref\":\"#/components/responses/PrescriptionRows\"},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/clinic/rxOrdering/getSubmittedPrescriptionsInClinicLocation\":{\"post\":{\"operationId\":\"GetSubmittedPrescriptionsInClinicLocation\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PrescriptionPageBody\"}}}},\"responses\":{\"200\":{\"$ref\":\"#/components/responses/PrescriptionRows\"},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/clinic/rxOrdering/getArchivedPrescriptionsInClinic\":{\"post\":{\"operationId\":\"GetArchivedPrescriptionsInClinic\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PrescriptionPageBody\"}}}},\"responses\":{\"200\":{\"$ref\":\"#/components/responses/PrescriptionRows\"},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}}},\"components\":{\"securitySchemes\":{\"bearerAuth\":{\"type\":\"http\",\"scheme\":\"bearer\",\"bearerFormat\":\"JWT\"}},\"responses\":{\"BadRequest\":{\"description\":\"Invalid request body\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorBody\"}}}},\"Unauthorized\":{\"description\":\"Missing, invalid or expired JWT (or bad credentials)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorBody\"}}}},\"NotFound\":{\"description\":\"Unknown clinic, location, patient, product or provider\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorBody\"}}}},\"Conflict\":{\"description\":\"The request could not be completed right now\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorBody\"}}}},\"PrescriptionRows\":{\"description\":\"One page of prescription status rows, in one of the four envelopes our client accepts (bare array, {prescriptions}, {message: [...]}, {message: {prescriptions}}).\",\"content\":{\"application/json\":{\"schema\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PrescriptionRow\"}},{\"type\":\"object\",\"required\":[\"prescriptions\"],\"properties\":{\"prescriptions\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PrescriptionRow\"}}}},{\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PrescriptionRow\"}},{\"type\":\"object\",\"required\":[\"prescriptions\"],\"properties\":{\"prescriptions\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PrescriptionRow\"}}}}]}}}]}}}}},\"schemas\":{\"ErrorBody\":{\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"type\":\"string\"},\"errors\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"path\",\"message\"],\"properties\":{\"path\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}}}}},\"ClinicId\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"65a1c0de00000000000000c1\"]},\"ClinicLocationId\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"65a1c0de00000000000000d1\"]},\"UserId\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"65a1c0de00000000000000a1\"]},\"AuthTokens\":{\"type\":\"object\",\"required\":[\"id\",\"jwtToken\",\"refreshToken\"],\"properties\":{\"id\":{\"type\":\"string\"},\"jwtToken\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"refreshToken\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}}}},\"ProductSummary\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"unitPrice\",\"productId\",\"productSize\",\"medicalAccessories\",\"coldShipped\",\"controlledSubstance\",\"dispenseType\",\"productType\",\"isReasonForCompoundedMedicationNeeded\"],\"properties\":{\"id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"product\",\"identity\":true}},\"name\":{\"type\":\"string\"},\"unitPrice\":{\"type\":\"number\",\"minimum\":0},\"productId\":{\"type\":\"string\"},\"productSize\":{\"type\":\"string\"},\"medicalAccessories\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"coldShipped\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"controlledSubstance\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"dispenseType\":{\"type\":\"string\"},\"productType\":{\"type\":\"string\",\"enum\":[\"S\",\"NS\"]},\"isReasonForCompoundedMedicationNeeded\":{\"type\":\"boolean\"}}},\"ProductDetails\":{\"type\":\"object\",\"required\":[\"id\",\"productId\",\"name\",\"unitPrice\",\"family\",\"subCategory1\",\"subCategory2\",\"commonName\",\"sigOptions\",\"productSize\",\"medicalAccessories\",\"coldShipped\",\"controlledSubstance\",\"dispenseType\",\"isReasonForCompoundedMedicationNeeded\",\"productType\"],\"properties\":{\"id\":{\"type\":\"string\"},\"productId\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"unitPrice\":{\"type\":\"number\",\"minimum\":0},\"family\":{\"type\":\"string\"},\"subCategory1\":{\"type\":\"string\"},\"subCategory2\":{\"type\":\"string\"},\"commonName\":{\"type\":\"string\"},\"sigOptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"productSize\":{\"type\":\"string\"},\"medicalAccessories\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"coldShipped\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"controlledSubstance\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"dispenseType\":{\"type\":\"string\"},\"reasonForCompoundedMedication\":{\"type\":[\"array\",\"null\"],\"items\":{\"type\":\"string\"}},\"isReasonForCompoundedMedicationNeeded\":{\"type\":\"boolean\"},\"productType\":{\"type\":\"string\",\"enum\":[\"S\",\"NS\"]},\"patientPayAmount\":{\"type\":[\"number\",\"null\"]},\"ndc\":{\"type\":[\"number\",\"null\"]},\"isActive\":{\"type\":\"boolean\"},\"isAvailable\":{\"type\":\"boolean\"}}},\"ProductDiscount\":{\"type\":\"object\",\"required\":[\"id\",\"productId\",\"discountedPrice\",\"unitPrice\",\"discountedPercentage\",\"controlledSubstance\"],\"properties\":{\"id\":{\"type\":\"string\"},\"productId\":{\"type\":\"string\"},\"discountedPrice\":{\"type\":\"number\",\"minimum\":0},\"unitPrice\":{\"type\":\"number\",\"minimum\":0},\"discountedPercentage\":{\"type\":\"number\",\"minimum\":0,\"maximum\":100},\"controlledSubstance\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]}}},\"Patient\":{\"type\":\"object\",\"required\":[\"id\",\"firstName\",\"lastName\",\"dateOfBirth\"],\"properties\":{\"id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"patient\",\"identity\":true}},\"firstName\":{\"type\":\"string\"},\"lastName\":{\"type\":\"string\"},\"dateOfBirth\":{\"type\":\"string\"},\"email\":{\"type\":[\"string\",\"null\"]},\"phoneNumber\":{\"type\":[\"string\",\"null\"]},\"cellPhone\":{\"type\":[\"string\",\"null\"]}}},\"Address\":{\"type\":\"object\",\"required\":[\"id\",\"addressLine1\",\"addressLine2\",\"city\",\"state\",\"zipcode\"],\"properties\":{\"id\":{\"type\":\"string\"},\"addressLine1\":{\"type\":\"string\"},\"addressLine2\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\"},\"state\":{\"type\":\"string\"},\"zipcode\":{\"type\":\"string\"}}},\"Provider\":{\"type\":\"object\",\"required\":[\"id\",\"firstName\",\"lastName\",\"npi\"],\"properties\":{\"id\":{\"type\":\"string\"},\"firstName\":{\"type\":\"string\"},\"lastName\":{\"type\":\"string\"},\"npi\":{\"type\":[\"string\",\"null\"]},\"deaInfo\":{\"type\":\"array\",\"items\":{\"type\":\"object\"}},\"providerLicenses\":{\"type\":\"array\",\"items\":{\"type\":\"object\"}},\"allowExostar\":{\"type\":\"boolean\"},\"isSuperUserSameAsProvider\":{\"type\":\"boolean\"}}},\"ClinicLocation\":{\"type\":\"object\",\"required\":[\"id\",\"clinicId\",\"locationName\"],\"properties\":{\"id\":{\"type\":\"string\"},\"clinicId\":{\"type\":\"string\"},\"locationName\":{\"type\":\"string\"},\"email\":{\"type\":[\"string\",\"null\"]},\"fax\":{\"type\":[\"string\",\"null\"]},\"addressLine1\":{\"type\":[\"string\",\"null\"]},\"addressLine2\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":[\"string\",\"null\"]},\"zipcode\":{\"type\":[\"string\",\"null\"]},\"state\":{\"type\":[\"string\",\"null\"]}}},\"PatientLookupBody\":{\"type\":\"object\",\"required\":[\"patientId\",\"userId\"],\"properties\":{\"patientId\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"patient\",\"missing\":0}},\"userId\":{\"$ref\":\"#/components/schemas/UserId\"}}},\"PrescriptionPageBody\":{\"type\":\"object\",\"required\":[\"clinicLocationId\",\"userId\",\"limit\",\"currentPage\"],\"properties\":{\"clinicLocationId\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"},\"userId\":{\"$ref\":\"#/components/schemas/UserId\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100},\"currentPage\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":50}}},\"PrescriptionRow\":{\"type\":\"object\",\"required\":[\"prescriptionStatus\"],\"properties\":{\"prescriptionId\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"prescriptionStatus\":{\"type\":\"string\"},\"trackingNumber\":{\"type\":[\"string\",\"null\"]},\"patientId\":{\"type\":\"string\"},\"createdAt\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"SavePrescriptionProduct\":{\"type\":\"object\",\"required\":[\"id\",\"productId\",\"name\",\"unitPrice\",\"family\",\"subCategory1\",\"subCategory2\",\"commonName\",\"sigOptions\",\"productSize\",\"medicalAccessories\",\"coldShipped\",\"controlledSubstance\",\"dispenseType\",\"reasonForCompoundedMedication\",\"isReasonForCompoundedMedicationNeeded\",\"productType\",\"patientPay\",\"ndc\",\"quantity\",\"sig\",\"daySupply\",\"daySupplyReason\",\"refills\",\"isCustomSig\",\"discountedPercentage\",\"discountedPrice\",\"displayedGeneratedSig\"],\"properties\":{\"id\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"product\",\"missing\":0}},\"productId\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"name\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":120},\"unitPrice\":{\"type\":\"number\",\"minimum\":0,\"maximum\":10000},\"family\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80},\"subCategory1\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80},\"subCategory2\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80},\"commonName\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":120},\"sigOptions\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":120}},\"productSize\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"medicalAccessories\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\"}},\"coldShipped\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"]},\"controlledSubstance\":{\"description\":\"VPI's API rail excludes controlled substances.\",\"type\":\"string\",\"enum\":[\"0\"]},\"dispenseType\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"reasonForCompoundedMedication\":{\"type\":\"string\",\"maxLength\":200},\"isReasonForCompoundedMedicationNeeded\":{\"type\":\"boolean\"},\"productType\":{\"type\":\"string\",\"enum\":[\"S\",\"NS\"]},\"patientPay\":{\"type\":\"number\",\"minimum\":0,\"maximum\":10000},\"ndc\":{\"type\":\"string\",\"maxLength\":11},\"quantity\":{\"type\":\"number\",\"exclusiveMinimum\":0,\"maximum\":1000},\"sig\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":500},\"daySupply\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":365},\"daySupplyReason\":{\"type\":\"string\",\"maxLength\":200},\"refills\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":12},\"isCustomSig\":{\"type\":\"boolean\"},\"discountedPercentage\":{\"type\":\"number\",\"minimum\":0,\"maximum\":100},\"discountedPrice\":{\"type\":\"number\",\"minimum\":0,\"maximum\":10000},\"displayedGeneratedSig\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":500}}},\"SavePrescriptionBody\":{\"type\":\"object\",\"required\":[\"patientIds\",\"clinicLocationId\",\"providerId\",\"clinicId\",\"userId\",\"products\",\"rxPadProducts\",\"shippingInfo\",\"patientNotificationRecipients\"],\"properties\":{\"patientIds\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":1,\"items\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"patient\",\"missing\":0}}},\"clinicLocationId\":{\"$ref\":\"#/components/schemas/ClinicLocationId\"},\"providerId\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"65a1c0de00000000000000e1\"]},\"clinicId\":{\"$ref\":\"#/components/schemas/ClinicId\"},\"userId\":{\"$ref\":\"#/components/schemas/UserId\"},\"products\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":2,\"items\":{\"$ref\":\"#/components/schemas/SavePrescriptionProduct\"}},\"rxPadProducts\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\"}},\"shippingInfo\":{\"type\":\"object\",\"required\":[\"isRushOrder\",\"isSignatureRequired\",\"orderNotes\",\"shipTo\",\"isNewAddressUsed\",\"shippingMethod\",\"shippingAddress\",\"rushOrderCost\",\"rushOrderMethod\"],\"properties\":{\"isRushOrder\":{\"type\":\"boolean\"},\"isSignatureRequired\":{\"type\":\"boolean\"},\"orderNotes\":{\"type\":\"string\",\"maxLength\":500},\"shipTo\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"isNewAddressUsed\":{\"type\":\"boolean\"},\"shippingMethod\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"shippingAddress\":{\"type\":\"object\",\"required\":[\"addressLine1\",\"addressLine2\",\"city\",\"state\",\"zipcode\"],\"properties\":{\"addressLine1\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80},\"addressLine2\":{\"type\":\"string\",\"maxLength\":80},\"city\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"state\":{\"description\":\"The canonical full state name (never the 2-letter code).\",\"type\":\"string\",\"enum\":[\"Alabama\",\"Alaska\",\"Arizona\",\"Arkansas\",\"California\",\"Colorado\",\"Connecticut\",\"Delaware\",\"Florida\",\"Georgia\",\"Hawaii\",\"Idaho\",\"Illinois\",\"Indiana\",\"Iowa\",\"Kansas\",\"Kentucky\",\"Louisiana\",\"Maine\",\"Maryland\",\"Massachusetts\",\"Michigan\",\"Minnesota\",\"Mississippi\",\"Missouri\",\"Montana\",\"Nebraska\",\"Nevada\",\"New Hampshire\",\"New Jersey\",\"New Mexico\",\"New York\",\"North Carolina\",\"North Dakota\",\"Ohio\",\"Oklahoma\",\"Oregon\",\"Pennsylvania\",\"Rhode Island\",\"South Carolina\",\"South Dakota\",\"Tennessee\",\"Texas\",\"Utah\",\"Vermont\",\"Virginia\",\"Washington\",\"West Virginia\",\"Wisconsin\",\"Wyoming\",\"District of Columbia\",\"American Samoa\",\"Guam\",\"Northern Mariana Islands\",\"Puerto Rico\",\"U.S. Virgin Islands\"]},\"zipcode\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":10}}},\"rushOrderCost\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1000},\"rushOrderMethod\":{\"type\":\"string\",\"maxLength\":40}}},\"creditRequested\":{\"type\":\"boolean\"},\"encryptedBillingInfo\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":2000},\"patientNotificationRecipients\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\"}}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"Authenticate\" | \"GetAllFamiliesAndCategories\" | \"GetProductsByCategory\" | \"GetProductDetailsByProductId\" | \"GetProductDiscountByProductIds\" | \"CalculateDaySupply\" | \"GetShippingStates\" | \"GetShippingRate\" | \"CheckProviderSignatureNeededDuplicate\" | \"SaveNewPrescription\" | \"GetPatientByPatientId\" | \"GetPatientAddressesByPatientId\" | \"GetPatientsInClinic\" | \"GetAllProvidersByClinicLocationId\" | \"GetClinicLocationByClinicLocationId\" | \"GetIncompleteSavedPrescriptionsInClinicLocation\" | \"GetSubmittedPrescriptionsInClinicLocation\" | \"GetArchivedPrescriptionsInClinic\"\nexport type SupportedOperationId = \"Authenticate\" | \"GetAllFamiliesAndCategories\" | \"GetProductsByCategory\" | \"GetProductDetailsByProductId\" | \"GetProductDiscountByProductIds\" | \"CalculateDaySupply\" | \"GetShippingStates\" | \"GetShippingRate\" | \"CheckProviderSignatureNeededDuplicate\" | \"SaveNewPrescription\" | \"GetPatientByPatientId\" | \"GetPatientAddressesByPatientId\" | \"GetPatientsInClinic\" | \"GetAllProvidersByClinicLocationId\" | \"GetClinicLocationByClinicLocationId\" | \"GetIncompleteSavedPrescriptionsInClinicLocation\" | \"GetSubmittedPrescriptionsInClinicLocation\" | \"GetArchivedPrescriptionsInClinic\"\nexport const operationIds = [\"Authenticate\",\"GetAllFamiliesAndCategories\",\"GetProductsByCategory\",\"GetProductDetailsByProductId\",\"GetProductDiscountByProductIds\",\"CalculateDaySupply\",\"GetShippingStates\",\"GetShippingRate\",\"CheckProviderSignatureNeededDuplicate\",\"SaveNewPrescription\",\"GetPatientByPatientId\",\"GetPatientAddressesByPatientId\",\"GetPatientsInClinic\",\"GetAllProvidersByClinicLocationId\",\"GetClinicLocationByClinicLocationId\",\"GetIncompleteSavedPrescriptionsInClinicLocation\",\"GetSubmittedPrescriptionsInClinicLocation\",\"GetArchivedPrescriptionsInClinic\"] as const\nexport const supportedOperationIds = [\"Authenticate\",\"GetAllFamiliesAndCategories\",\"GetProductsByCategory\",\"GetProductDetailsByProductId\",\"GetProductDiscountByProductIds\",\"CalculateDaySupply\",\"GetShippingStates\",\"GetShippingRate\",\"CheckProviderSignatureNeededDuplicate\",\"SaveNewPrescription\",\"GetPatientByPatientId\",\"GetPatientAddressesByPatientId\",\"GetPatientsInClinic\",\"GetAllProvidersByClinicLocationId\",\"GetClinicLocationByClinicLocationId\",\"GetIncompleteSavedPrescriptionsInClinicLocation\",\"GetSubmittedPrescriptionsInClinicLocation\",\"GetArchivedPrescriptionsInClinic\"] as const\n", "import { Collection } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport {\n type ClinicLocation,\n DEFAULT_CLINIC_LOCATION,\n DEFAULT_PATIENTS,\n DEFAULT_PRODUCTS,\n DEFAULT_PROVIDERS,\n type Patient,\n type Product,\n type Provider,\n} from \"./catalog.js\"\nimport type { PrescriptionList } from \"./statuses.js\"\n\n/**\n * One saved prescription as VPI tracks it. Only ids and status are kept: the product and\n * shipping details of the save payload are validated, never stored or echoed back.\n */\nexport type PrescriptionRecord = {\n prescriptionId: string\n clinicId: string\n clinicLocationId: string\n patientId: string\n providerId: string\n productIds: string[]\n prescriptionStatus: string\n list: PrescriptionList\n trackingNumber: string | null\n createdAt: string\n updatedAt: string\n}\n\n/** A login `POST /accounts/authenticate` accepts, and the user id its JWT carries. */\nexport type Account = { email: string; password: string; id: string }\n\n/**\n * The envelope the three status lists answer in. `vendor` mirrors what our client's spec\n * records per endpoint (submitted `{message: {prescriptions}}`, archived `{message: [...]}` with\n * `id` rows, incomplete a bare array); the others force one envelope everywhere.\n */\nexport type StatusEnvelope =\n | \"vendor\"\n | \"array\"\n | \"prescriptions\"\n | \"message\"\n | \"message.prescriptions\"\n\n/** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */\nexport type Settings = {\n /** JWT lifetime on the mock clock. Our client caches until `exp` minus 30 s. */\n tokenTtlSeconds: number\n /** Only these logins authenticate; empty means any email/password pair does. */\n accounts: Account[]\n statusEnvelope: StatusEnvelope\n /** What the duplicate check reports for `isProviderSignatureNeeded`. */\n isProviderSignatureNeeded: boolean\n}\n\nexport const DEFAULT_SETTINGS: Settings = {\n tokenTtlSeconds: 3_600,\n accounts: [],\n statusEnvelope: \"vendor\",\n isProviderSignatureNeeded: true,\n}\n\n/** Replaceable seed data (defaults in `catalog.ts`). */\nexport type Seed = {\n products?: readonly Product[]\n providers?: readonly Provider[]\n clinicLocations?: readonly ClinicLocation[]\n patients?: readonly Patient[]\n}\n\nexport class VpiState {\n readonly products: Collection<Product>\n readonly providers: Collection<Provider>\n readonly locations: Collection<ClinicLocation>\n readonly patients: Collection<Patient>\n readonly prescriptions: Collection<PrescriptionRecord>\n readonly settings: Collection<Settings>\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n private readonly seed: { data: Seed; settings: Partial<Settings> },\n ) {\n this.products = new Collection(sqlite, namespace, \"products\")\n this.providers = new Collection(sqlite, namespace, \"providers\")\n this.locations = new Collection(sqlite, namespace, \"clinic_locations\")\n this.patients = new Collection(sqlite, namespace, \"patients\")\n this.prescriptions = new Collection(sqlite, namespace, \"prescriptions\")\n this.settings = new Collection(sqlite, namespace, \"settings\")\n this.ensureSeeded()\n }\n\n /** Re-apply the seed after a reset. */\n ensureSeeded(): void {\n const { data } = this.seed\n if (this.products.count() === 0) {\n for (const p of data.products ?? DEFAULT_PRODUCTS) this.products.insert(p.id, p)\n }\n if (this.providers.count() === 0) {\n for (const p of data.providers ?? DEFAULT_PROVIDERS) this.providers.insert(p.id, p)\n }\n if (this.locations.count() === 0) {\n for (const l of data.clinicLocations ?? [DEFAULT_CLINIC_LOCATION]) {\n this.locations.insert(l.id, l)\n }\n }\n if (this.patients.count() === 0) {\n for (const p of data.patients ?? DEFAULT_PATIENTS) this.patients.insert(p.id, p)\n }\n if (!this.settings.has(\"settings\")) {\n this.settings.insert(\"settings\", { ...DEFAULT_SETTINGS, ...this.seed.settings })\n }\n }\n\n current(): Settings {\n return this.settings.get(\"settings\") ?? DEFAULT_SETTINGS\n }\n\n update(patch: Partial<Settings>): Settings {\n const next = { ...this.current(), ...patch }\n this.settings.insert(\"settings\", next)\n return next\n }\n\n /** Clinic ids that exist (every location's clinic). */\n hasClinic(clinicId: string): boolean {\n return this.locations.list().some((row) => row.value.clinicId === clinicId)\n }\n\n /** A Mongo-looking prescription id, deterministic per namespace history. */\n nextPrescriptionId(): string {\n return `66b2${this.prescriptions.nextSequence().toString(16).padStart(20, \"0\")}`\n }\n\n /** A patient id for seeded patients that omit one. */\n nextPatientId(): string {\n return `66b4${this.patients.nextSequence().toString(16).padStart(20, \"0\")}`\n }\n\n /** A patient-address id for seeded addresses that omit one. */\n nextAddressId(): string {\n return `66b3${this.patients.nextSequence().toString(16).padStart(20, \"0\")}`\n }\n\n /**\n * A list's rows, newest first. The incomplete and submitted lists are per clinic location;\n * the archived list is per clinic (`getArchivedPrescriptionsInClinic`).\n */\n list(list: PrescriptionList, location: ClinicLocation): PrescriptionRecord[] {\n return this.prescriptions\n .list({\n where: (row) =>\n row.list === list &&\n (list === \"archived\"\n ? row.clinicId === location.clinicId\n : row.clinicLocationId === location.id),\n })\n .map((row) => row.value)\n }\n}\n", "/**\n * VPI prescription statuses and which of the three clinic lists shows a prescription in\n * each. `saveNewPrescription` creates a draft awaiting provider signature (the incomplete\n * list); the pharmacy then receives, processes, completes or cancels it.\n */\nexport type PrescriptionList = \"incomplete\" | \"submitted\" | \"archived\"\n\nexport const DRAFT_STATUS = \"Provider Signature Needed\"\n\nconst CANONICAL: Record<string, { status: string; list: PrescriptionList }> = {\n \"provider signature needed\": { status: \"Provider Signature Needed\", list: \"incomplete\" },\n \"signature needed\": { status: \"Signature Needed\", list: \"incomplete\" },\n \"new formula pending\": { status: \"New Formula Pending\", list: \"incomplete\" },\n received: { status: \"Received\", list: \"submitted\" },\n \"order received\": { status: \"Order Received\", list: \"submitted\" },\n \"in process\": { status: \"In Process\", list: \"submitted\" },\n \"order in process\": { status: \"Order In Process\", list: \"submitted\" },\n \"prescriptions in process\": { status: \"Prescriptions In Process\", list: \"submitted\" },\n \"on hold\": { status: \"On Hold\", list: \"submitted\" },\n \"order on hold\": { status: \"Order On Hold\", list: \"submitted\" },\n completed: { status: \"Completed\", list: \"submitted\" },\n \"order complete\": { status: \"Order Complete\", list: \"submitted\" },\n \"order completed\": { status: \"Order Completed\", list: \"submitted\" },\n cancelled: { status: \"Cancelled\", list: \"archived\" },\n \"order cancelled\": { status: \"Order Cancelled\", list: \"archived\" },\n archived: { status: \"Archived\", list: \"archived\" },\n}\n\n/** The canonical status and list for a transition target; unknown targets go verbatim to `submitted`. */\nexport const resolveStatus = (to: string): { status: string; list: PrescriptionList } =>\n CANONICAL[to.trim().toLowerCase()] ?? { status: to.trim(), list: \"submitted\" }\n\n/** Completed statuses carry a tracking number. */\nexport const isCompleted = (status: string): boolean => /complete/i.test(status)\n\n/** Still \"active\" for the duplicate check: not cancelled or archived. */\nexport const isActive = (list: PrescriptionList): boolean => list !== \"archived\"\n", "import {\n type AdminRoutes,\n type Clock,\n createRuntime as createServiceRuntime,\n type FaultPreset,\n type FaultRule,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { document, supportedOperationIds } from \"./generated/openapi.js\"\nimport { type PatientInput, tokenCredential, VPI_NAMESPACE, VpiAPI } from \"./index.js\"\nimport type { Account, Seed, Settings, StatusEnvelope } from \"./state.js\"\nimport type { PrescriptionList } from \"./statuses.js\"\n\nconst AUTHORIZED_OPERATIONS = supportedOperationIds.filter((id) => id !== \"Authenticate\")\n\n/** One canned rule per authorized operation, so a `count` applies to each call site separately. */\nconst everyAuthorized = (rule: Omit<FaultRule, \"id\" | \"operationId\">): Omit<FaultRule, \"id\">[] =>\n AUTHORIZED_OPERATIONS.map((operationId) => ({ operationId, ...rule }))\n\n/**\n * Every named VPI misbehaviour our consumer branches on, switched on with\n * `POST /__admin/faults {\"preset\": \"<name>\"}` (add `count` to limit it).\n */\nexport const VPI_PRESETS: Record<string, FaultPreset> = {\n token_expired: {\n description:\n 'Authorized calls answer 401 \"jwt expired\" before exp; with count 1 our client re-authenticates once and the retry succeeds',\n rules: everyAuthorized({ status: 401, body: { message: \"jwt expired\" } }),\n },\n unauthorized_twice: {\n description:\n \"Authorized calls answer 401 twice: the single re-auth retry fails too (VpiApiHttpError 401)\",\n rules: everyAuthorized({ status: 401, body: { message: \"Unauthorized\" }, count: 2 }),\n },\n auth_rejected: {\n description: \"POST /accounts/authenticate answers 401 (bad credentials)\",\n rules: [\n {\n operationId: \"Authenticate\",\n status: 401,\n body: { message: \"Email or password is incorrect\" },\n },\n ],\n },\n server_error: {\n description: \"Every call answers 500\",\n rules: [{ status: 500, body: { message: \"Internal Server Error\" } }],\n },\n duplicate_prescription: {\n description: \"checkProviderSignatureNeededDuplicate reports isDuplicate: true\",\n rules: [\n { operationId: \"CheckProviderSignatureNeededDuplicate\", effect: \"duplicate_prescription\" },\n ],\n },\n save_ambiguous_409: {\n description:\n \"saveNewPrescription saves the draft, then answers 409: the draft state is unknown (needs_review)\",\n rules: [{ operationId: \"SaveNewPrescription\", effect: \"save_ambiguous_409\" }],\n },\n save_rate_limited: {\n description: \"saveNewPrescription answers 429 without saving (ambiguous: needs_review)\",\n rules: [\n { operationId: \"SaveNewPrescription\", status: 429, body: { message: \"Too Many Requests\" } },\n ],\n },\n save_400: {\n description:\n \"saveNewPrescription answers 400 without saving (definitive: retry via the browser agent)\",\n rules: [{ operationId: \"SaveNewPrescription\", status: 400, body: { message: \"Bad Request\" } }],\n },\n response_drift: {\n description:\n \"Taxonomy answers categories as a string and product details unitPrice as a string: our zod parse fails closed\",\n rules: [\n { operationId: \"GetAllFamiliesAndCategories\", effect: \"response_drift\" },\n { operationId: \"GetProductDetailsByProductId\", effect: \"response_drift\" },\n ],\n },\n}\n\nexport type VpiRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: number | string\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n /** Replace the seeded clinic, providers, products or patients. */\n data?: Seed\n settings?: Partial<Settings>\n}\n\nexport type VpiRuntime = ServiceRuntime<VpiAPI>\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\nconst adminError = (status: number, message: string) =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\nconst isString = (value: unknown): value is string =>\n typeof value === \"string\" && value.trim().length > 0\n\nconst ENVELOPES: StatusEnvelope[] = [\n \"vendor\",\n \"array\",\n \"prescriptions\",\n \"message\",\n \"message.prescriptions\",\n]\nconst LISTS: PrescriptionList[] = [\"incomplete\", \"submitted\", \"archived\"]\n\nconst parsePatient = (body: unknown): PatientInput | string => {\n if (!isRecord(body)) return \"expected a JSON object\"\n for (const key of [\"firstName\", \"lastName\", \"dateOfBirth\"]) {\n if (!isString(body[key])) return `${key}: non-empty string`\n }\n const addresses = body.addresses ?? []\n if (!Array.isArray(addresses)) return \"addresses: [{addressLine1, city, state, zipcode}]\"\n for (const a of addresses) {\n if (!isRecord(a) || ![\"addressLine1\", \"city\", \"state\", \"zipcode\"].every((k) => isString(a[k])))\n return \"addresses: [{addressLine1, addressLine2?, city, state, zipcode}]\"\n }\n const optional = (key: string) =>\n typeof body[key] === \"string\" || body[key] === null ? { [key]: body[key] } : {}\n return {\n firstName: body.firstName as string,\n lastName: body.lastName as string,\n dateOfBirth: body.dateOfBirth as string,\n ...optional(\"id\"),\n ...optional(\"clinicId\"),\n ...optional(\"email\"),\n ...optional(\"phoneNumber\"),\n ...optional(\"cellPhone\"),\n addresses: (addresses as Record<string, unknown>[]).map((a) => ({\n addressLine1: a.addressLine1 as string,\n city: a.city as string,\n state: a.state as string,\n zipcode: a.zipcode as string,\n ...(typeof a.id === \"string\" ? { id: a.id } : {}),\n ...(typeof a.addressLine2 === \"string\" || a.addressLine2 === null\n ? { addressLine2: a.addressLine2 as string | null }\n : {}),\n })),\n } as PatientInput\n}\n\nconst adminRoutes = (runtime: ServiceRuntime<VpiAPI>): AdminRoutes => ({\n \"GET /prescriptions\": ({ namespace }) =>\n json(200, { prescriptions: runtime.instance(namespace).prescriptions() }),\n \"POST /prescriptions/:id/transition\": ({ params, body, namespace }) => {\n if (!isRecord(body) || !isString(body.to)) {\n return adminError(400, 'expected {\"to\": \"<VPI status>\", \"trackingNumber\"?, \"list\"?}')\n }\n if (body.list !== undefined && !LISTS.includes(body.list as PrescriptionList)) {\n return adminError(400, `list: one of ${LISTS.join(\", \")}`)\n }\n const updated = runtime.instance(namespace).transition(params.id as string, {\n to: body.to,\n ...(typeof body.trackingNumber === \"string\" ? { trackingNumber: body.trackingNumber } : {}),\n ...(body.list !== undefined ? { list: body.list as PrescriptionList } : {}),\n })\n return updated ? json(200, updated) : adminError(404, `no prescription ${params.id}`)\n },\n \"GET /patients\": ({ namespace }) =>\n json(200, {\n patients: runtime\n .instance(namespace)\n .state.patients.list({ order: \"oldest\" })\n .map((row) => row.value),\n }),\n \"POST /patients\": ({ body, namespace }) => {\n const parsed = parsePatient(body)\n if (typeof parsed === \"string\") return adminError(400, parsed)\n return json(201, runtime.instance(namespace).addPatient(parsed))\n },\n \"GET /catalog\": ({ namespace }) => {\n const state = runtime.instance(namespace).state\n return json(200, {\n products: state.products.list({ order: \"oldest\" }).map((row) => row.value),\n providers: state.providers.list({ order: \"oldest\" }).map((row) => row.value),\n clinicLocations: state.locations.list({ order: \"oldest\" }).map((row) => row.value),\n })\n },\n \"GET /settings\": ({ namespace }) => json(200, runtime.instance(namespace).state.current()),\n \"PUT /settings\": ({ body, namespace }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n const patch: Partial<Settings> = {}\n if (body.tokenTtlSeconds !== undefined) {\n if (typeof body.tokenTtlSeconds !== \"number\" || body.tokenTtlSeconds <= 0)\n return adminError(400, \"tokenTtlSeconds: positive number\")\n patch.tokenTtlSeconds = body.tokenTtlSeconds\n }\n if (body.accounts !== undefined) {\n if (!Array.isArray(body.accounts) || !body.accounts.every(isRecord))\n return adminError(400, \"accounts: [{email, password, id}]\")\n patch.accounts = body.accounts.map(\n (a): Account => ({\n email: String(a.email),\n password: String(a.password),\n id: String(a.id ?? \"\"),\n }),\n )\n }\n if (body.statusEnvelope !== undefined) {\n if (!ENVELOPES.includes(body.statusEnvelope as StatusEnvelope))\n return adminError(400, `statusEnvelope: one of ${ENVELOPES.join(\", \")}`)\n patch.statusEnvelope = body.statusEnvelope as StatusEnvelope\n }\n if (body.isProviderSignatureNeeded !== undefined) {\n if (typeof body.isProviderSignatureNeeded !== \"boolean\")\n return adminError(400, \"isProviderSignatureNeeded: boolean\")\n patch.isProviderSignatureNeeded = body.isProviderSignatureNeeded\n }\n return json(200, runtime.instance(namespace).state.update(patch))\n },\n})\n\n/**\n * The VPI mock with Mockingbird's full service contract: `/health`, `/__admin/*`, namespaces\n * by header, by `/ns/<name>` path prefix, or by login email\n * (`PUT /__admin/credentials {\"credentials\": {\"<VPI_API_EMAIL>\": \"<namespace>\"}}`), clock\n * control, fault presets and a request journal. VPI sends no webhooks: our client polls.\n */\nexport const createRuntime = (options: VpiRuntimeOptions = {}): VpiRuntime =>\n createServiceRuntime<VpiAPI>({\n name: VPI_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 credential: tokenCredential,\n presets: VPI_PRESETS,\n create: ({ sqlite, namespace, clock }) =>\n new VpiAPI({\n sqlite,\n namespace,\n now: clock.now,\n ...(options.data ? { seed: options.data } : {}),\n ...(options.settings ? { settings: options.settings } : {}),\n }),\n admin: adminRoutes,\n })\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n type BodyIssue,\n bearerToken,\n bodyIssues,\n bootSqlite,\n createService,\n defineOperations,\n faultEffect,\n fromBase64,\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n type Service,\n toBase64,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport {\n type ClinicLocation,\n DEFAULT_USER_ID,\n type Patient,\n type PatientAddress,\n type Product,\n SHIPPING_STATES,\n STATE_CODES,\n} from \"./catalog.js\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport { type PrescriptionRecord, type Seed, type Settings, VpiState } from \"./state.js\"\nimport {\n DRAFT_STATUS,\n isActive,\n isCompleted,\n type PrescriptionList,\n resolveStatus,\n} from \"./statuses.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type {\n ClinicLocation,\n Patient,\n PatientAddress,\n Product,\n Provider,\n} from \"./catalog.js\"\nexport {\n DEFAULT_CLINIC_ID,\n DEFAULT_CLINIC_LOCATION,\n DEFAULT_CLINIC_LOCATION_ID,\n DEFAULT_PATIENT_ID,\n DEFAULT_PATIENTS,\n DEFAULT_PRODUCTS,\n DEFAULT_PROVIDER_ID,\n DEFAULT_PROVIDERS,\n DEFAULT_USER_ID,\n SHIPPING_STATES,\n} from \"./catalog.js\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type { Account, PrescriptionRecord, Seed, Settings, StatusEnvelope } from \"./state.js\"\nexport type { PrescriptionList } from \"./statuses.js\"\n\nexport const VPI_NAMESPACE = \"vpi\"\n\nexport type VpiAPIOptions = APIOptions & {\n /** Replace the seeded clinic, providers, products or patients. */\n seed?: Seed\n /** Initial per-namespace settings (token TTL, accounts, status envelope). */\n settings?: Partial<Settings>\n}\n\nconst base64url = (value: string) =>\n toBase64(new TextEncoder().encode(value))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\")\nconst fromBase64url = (value: string) => {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n fromBase64(value.replace(/-/g, \"+\").replace(/_/g, \"/\")),\n )\n } catch {\n return undefined\n }\n}\n\nconst JWT_HEADER = base64url(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" }))\n\ntype JwtClaims = { sub: string; email: string; iat: number; exp: number }\n\nconst signJwt = (unsigned: string) => opaqueToken(`vpi-jwt:${unsigned}`, 43)\n\n/** A JWT whose payload carries `sub` (the user id), `email`, `iat` and `exp` (mock clock). */\nexport const issueJwt = (claims: JwtClaims): string => {\n const unsigned = `${JWT_HEADER}.${base64url(JSON.stringify(claims))}`\n return `${unsigned}.${signJwt(unsigned)}`\n}\n\nconst readClaims = (token: string): JwtClaims | undefined => {\n const [header, payload, signature] = token.split(\".\")\n if (!header || !payload || !signature) return undefined\n if (signature !== signJwt(`${header}.${payload}`)) return undefined\n const json = fromBase64url(payload)\n if (!json) return undefined\n try {\n const claims = JSON.parse(json) as JwtClaims\n return typeof claims.exp === \"number\" && typeof claims.email === \"string\" ? claims : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The login email a bearer JWT was issued to (how `PUT /__admin/credentials` maps\n * `VPI_API_EMAIL` to a namespace: the app's `fetch` cannot add a namespace header).\n */\nexport const tokenCredential = (request: Request): string | undefined => {\n const token = bearerToken(request)\n if (!token) return undefined\n const payload = token.split(\".\")[1]\n if (!payload) return undefined\n const json = fromBase64url(payload)\n if (!json) return undefined\n try {\n const email = (JSON.parse(json) as { email?: unknown }).email\n return typeof email === \"string\" ? email : undefined\n } catch {\n return undefined\n }\n}\n\nconst error = (status: number, message: string, errors?: BodyIssue[]) =>\n jsonRes(status, errors ? { message, errors } : { message })\n\nconst notFound = (what: string): never => {\n throw new HttpError(404, { message: `${what} not found` })\n}\n\nconst record = (context: OperationContext): Record<string, unknown> => {\n const issues = bodyIssues(context)\n if (issues.length > 0) {\n throw new HttpError(400, { message: \"Validation failed\", errors: issues })\n }\n return context.body.kind === \"json\" ? (context.body.value as Record<string, unknown>) : {}\n}\n\nconst round2 = (value: number) => Math.round(value * 100) / 100\n\nconst patientBody = (patient: Patient) => ({\n id: patient.id,\n firstName: patient.firstName,\n lastName: patient.lastName,\n dateOfBirth: patient.dateOfBirth,\n email: patient.email,\n phoneNumber: patient.phoneNumber,\n cellPhone: patient.cellPhone,\n})\n\nconst productSummary = (p: Product) => ({\n id: p.id,\n name: p.name,\n unitPrice: p.unitPrice,\n productId: p.productId,\n productSize: p.productSize,\n medicalAccessories: p.medicalAccessories,\n coldShipped: p.coldShipped,\n controlledSubstance: p.controlledSubstance,\n dispenseType: p.dispenseType,\n productType: p.productType,\n isReasonForCompoundedMedicationNeeded: p.isReasonForCompoundedMedicationNeeded,\n})\n\nconst productDetails = (p: Product) => ({\n id: p.id,\n productId: p.productId,\n name: p.name,\n unitPrice: p.unitPrice,\n family: p.family,\n subCategory1: p.subCategory1,\n subCategory2: p.subCategory2,\n commonName: p.commonName,\n sigOptions: p.sigOptions,\n productSize: p.productSize,\n medicalAccessories: p.medicalAccessories,\n coldShipped: p.coldShipped,\n controlledSubstance: p.controlledSubstance,\n dispenseType: p.dispenseType,\n reasonForCompoundedMedication: p.reasonForCompoundedMedication,\n isReasonForCompoundedMedicationNeeded: p.isReasonForCompoundedMedicationNeeded,\n productType: p.productType,\n patientPayAmount: p.patientPayAmount,\n ndc: p.ndc,\n isActive: true,\n isAvailable: true,\n})\n\nexport type TransitionInput = {\n /** A VPI status, e.g. `Order Received`, `In Process`, `Order Completed`, `Cancelled`. */\n to: string\n trackingNumber?: string\n /** Force the list the prescription shows in (default: by status). */\n list?: PrescriptionList\n}\n\nexport type PatientInput = {\n id?: string\n clinicId?: string\n firstName: string\n lastName: string\n dateOfBirth: string\n email?: string | null\n phoneNumber?: string | null\n cellPhone?: string | null\n addresses?: (Omit<PatientAddress, \"id\" | \"addressLine2\"> & {\n id?: string\n addressLine2?: string | null\n })[]\n}\n\n/**\n * Stateful mock of the VPI clinic API our backend drives as a draft-only rail.\n *\n * `saveNewPrescription` creates a draft awaiting provider signature; prescriptions move only\n * through admin transitions, between the incomplete, submitted and archived lists our status\n * poller reads (page 1, limit 5).\n */\nexport class VpiAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n readonly state: VpiState\n private readonly service: Service\n private readonly now: () => number\n\n constructor(options: VpiAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? VPI_NAMESPACE\n this.now = options.now ?? (() => Date.now())\n this.state = new VpiState(sqlite, namespace, {\n data: options.seed ?? {},\n settings: options.settings ?? {},\n })\n const handlers = defineOperations<SupportedOperationId>({\n Authenticate: (context) => this.authenticate(context),\n GetAllFamiliesAndCategories: (context) => this.taxonomy(context),\n GetProductsByCategory: (context) => this.productsByCategory(context),\n GetProductDetailsByProductId: (context) => this.productDetails(context),\n GetProductDiscountByProductIds: (context) => this.discounts(context),\n CalculateDaySupply: (context) => this.daySupply(context),\n GetShippingStates: () => jsonRes(200, { data: [{ states: SHIPPING_STATES }] }),\n GetShippingRate: (context) => this.shippingRate(context),\n CheckProviderSignatureNeededDuplicate: (context) => this.duplicateCheck(context),\n SaveNewPrescription: (context) => this.savePrescription(context),\n GetPatientByPatientId: (context) => {\n const body = record(context)\n const patient = this.patient(String(body.patientId))\n return annotateResponse(jsonRes(200, patientBody(patient)), {\n ids: { patientId: patient.id },\n })\n },\n GetPatientAddressesByPatientId: (context) => {\n const body = record(context)\n const patient = this.patient(String(body.patientId))\n return annotateResponse(jsonRes(200, { addresses: patient.addresses }), {\n ids: { patientId: patient.id },\n })\n },\n GetPatientsInClinic: (context) => this.roster(context),\n GetAllProvidersByClinicLocationId: (context) => {\n const body = record(context)\n const location = this.location(String(body.clinicLocationId))\n if (location.clinicId !== body.clinicId) notFound(\"Clinic location\")\n return jsonRes(\n 200,\n this.state.providers\n .list({ order: \"oldest\", where: (p) => p.clinicLocationId === location.id })\n .map(({ value: p }) => ({\n id: p.id,\n firstName: p.firstName,\n lastName: p.lastName,\n npi: p.npi,\n deaInfo: [],\n providerLicenses: [],\n allowExostar: false,\n isSuperUserSameAsProvider: false,\n })),\n )\n },\n GetClinicLocationByClinicLocationId: (context) => {\n const body = record(context)\n return jsonRes(200, this.location(String(body.clinicLocationId)))\n },\n GetIncompleteSavedPrescriptionsInClinicLocation: (context) =>\n this.prescriptionPage(context, \"incomplete\"),\n GetSubmittedPrescriptionsInClinicLocation: (context) =>\n this.prescriptionPage(context, \"submitted\"),\n GetArchivedPrescriptionsInClinic: (context) => this.prescriptionPage(context, \"archived\"),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: this.now,\n notFound: () => jsonRes(404, { message: \"Cannot find the requested route\" }),\n onError: (thrown) => {\n if (thrown instanceof HttpError) return thrown.toResponse()\n throw thrown\n },\n before: (context) => {\n if (context.operation.operationId === \"Authenticate\") return undefined\n const token = bearerToken(context.request)\n if (!token) return error(401, \"Unauthorized\")\n const claims = readClaims(token)\n if (!claims) return error(401, \"Unauthorized\")\n if (this.now() / 1000 >= claims.exp) return error(401, \"jwt expired\")\n return undefined\n },\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n }\n\n fetch(request: Request): Promise<Response> {\n return this.service.fetch(request)\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n this.state.ensureSeeded()\n }\n\n private iso(): string {\n return new Date(this.now()).toISOString()\n }\n\n private authenticate(context: OperationContext): Response {\n const body = record(context)\n const email = String(body.email).trim()\n const settings = this.state.current()\n let userId = DEFAULT_USER_ID\n if (settings.accounts.length > 0) {\n const account = settings.accounts.find(\n (a) => a.email.toLowerCase() === email.toLowerCase() && a.password === body.password,\n )\n if (!account) return error(401, \"Email or password is incorrect\")\n userId = account.id\n }\n if (body.isPatientLogin === true) return error(401, \"Email or password is incorrect\")\n const iat = Math.floor(this.now() / 1000)\n const jwtToken = issueJwt({ sub: userId, email, iat, exp: iat + settings.tokenTtlSeconds })\n return jsonRes(200, {\n id: userId,\n jwtToken,\n refreshToken: opaqueToken(`vpi-refresh:${jwtToken}`, 80),\n })\n }\n\n private product(id: string): Product {\n return this.state.products.get(id) ?? notFound(\"Product\")\n }\n\n private patient(id: string): Patient {\n return this.state.patients.get(id) ?? notFound(\"Patient\")\n }\n\n private location(id: string): ClinicLocation {\n return this.state.locations.get(id) ?? notFound(\"Clinic location\")\n }\n\n private clinic(id: string): void {\n if (!this.state.hasClinic(id)) notFound(\"Clinic\")\n }\n\n private taxonomy(context: OperationContext): Response {\n const families = new Map<string, string[]>()\n for (const { value: p } of this.state.products.list({ order: \"oldest\" })) {\n const categories = families.get(p.family) ?? []\n if (!categories.includes(p.subCategory1)) categories.push(p.subCategory1)\n families.set(p.family, categories)\n }\n const drift = faultEffect(context.request, \"response_drift\") !== undefined\n return jsonRes(\n 200,\n [...families].map(([family, categories]) => ({\n family,\n categories: drift ? categories.join(\",\") : categories,\n })),\n )\n }\n\n private productsByCategory(context: OperationContext): Response {\n const body = record(context)\n const groups = new Map<string, Map<string, Product[]>>()\n for (const { value: p } of this.state.products.list({ order: \"oldest\" })) {\n if (p.family !== body.category || p.subCategory1 !== body.subCategory1) continue\n const byName = groups.get(p.subCategory2) ?? new Map<string, Product[]>()\n byName.set(p.commonName, [...(byName.get(p.commonName) ?? []), p])\n groups.set(p.subCategory2, byName)\n }\n return jsonRes(\n 200,\n [...groups].map(([subCategory2, byName]) => ({\n subCategory2_item: subCategory2,\n commonNames: [...byName].map(([commonName, products]) => ({\n commonName,\n products: products.map(productSummary),\n })),\n })),\n )\n }\n\n private productDetails(context: OperationContext): Response {\n const product = this.product(context.params.productId ?? \"\")\n const body = productDetails(product)\n if (faultEffect(context.request, \"response_drift\") !== undefined) {\n return jsonRes(200, { ...body, unitPrice: String(body.unitPrice) })\n }\n return jsonRes(200, body)\n }\n\n private discounts(context: OperationContext): Response {\n const body = record(context)\n this.clinic(String(body.clinicId))\n const rows = (body.productIds as string[])\n .map((id) => this.state.products.get(id))\n .filter((p): p is Product => p !== undefined)\n .map((p) => ({\n id: p.id,\n productId: p.productId,\n discountedPrice: round2(p.unitPrice * (1 - p.discountedPercentage / 100)),\n unitPrice: p.unitPrice,\n discountedPercentage: p.discountedPercentage,\n controlledSubstance: p.controlledSubstance,\n }))\n return jsonRes(200, rows)\n }\n\n private daySupply(context: OperationContext): Response {\n const body = record(context)\n const product = this.product(String(body.productId))\n const quantity = Number(body.quantity)\n const perUnit = /ea$/i.test(product.productSize)\n const daySupply = perUnit ? Math.max(1, Math.round(quantity)) : 30\n return jsonRes(200, {\n daySupply,\n daySupplyReason: perUnit ? \"Calculated from quantity (1 per day)\" : \"Default 30-day supply\",\n })\n }\n\n private shippingRate(context: OperationContext): Response {\n const body = record(context)\n this.clinic(String(body.clinicId))\n this.location(String(body.clinicLocationId))\n this.patient(String(body.patientId))\n const products = (body.productIds as string[]).map((id) => this.product(id))\n const code = String(body.shippingState).toUpperCase()\n const state = SHIPPING_STATES.find((s) => STATE_CODES[s.name] === code)\n if (!state) return error(400, `VPI does not ship to ${code}`)\n if (products.some((p) => p.productType === \"S\") && !state.sterile) {\n return error(400, `VPI does not ship sterile products to ${state.name}`)\n }\n const cold = products.some((p) => p.coldShipped === \"1\")\n const rush = body.isRushOrder === true\n return jsonRes(200, {\n shippingMethod: cold ? \"FedEx Priority Overnight\" : \"UPS Ground\",\n rushOrderCost: rush ? 35 : 0,\n rushOrderMethod: rush ? \"FedEx Standard Overnight\" : \"\",\n isSignatureRequired: products.some((p) => p.productType === \"S\"),\n })\n }\n\n private duplicateCheck(context: OperationContext): Response {\n const body = record(context)\n const patients = body.patientIds as string[]\n const products = body.productIds as string[]\n const duplicate =\n faultEffect(context.request, \"duplicate_prescription\") !== undefined ||\n this.state.prescriptions\n .list()\n .some(\n ({ value: rx }) =>\n isActive(rx.list) &&\n patients.includes(rx.patientId) &&\n rx.productIds.some((id) => products.includes(id)),\n )\n return jsonRes(200, {\n isDuplicate: duplicate,\n isProviderSignatureNeeded: this.state.current().isProviderSignatureNeeded,\n })\n }\n\n private savePrescription(context: OperationContext): Response {\n const body = record(context)\n const location = this.location(String(body.clinicLocationId))\n if (location.clinicId !== body.clinicId) notFound(\"Clinic location\")\n const provider = this.state.providers.get(String(body.providerId))\n if (!provider || provider.clinicLocationId !== location.id) notFound(\"Provider\")\n const patientId = (body.patientIds as string[])[0] as string\n const patient = this.patient(patientId)\n if (patient.clinicId !== location.clinicId) notFound(\"Patient\")\n const lines = body.products as { id: string; productId: string }[]\n for (const line of lines) {\n const product = this.product(line.id)\n if (product.productId !== line.productId) {\n return error(400, `Product ${line.id} does not match product code ${line.productId}`)\n }\n if (product.controlledSubstance === \"1\") {\n return error(400, \"Controlled substances cannot be prescribed through this endpoint\")\n }\n }\n const now = this.iso()\n const created: PrescriptionRecord = {\n prescriptionId: this.state.nextPrescriptionId(),\n clinicId: location.clinicId,\n clinicLocationId: location.id,\n patientId,\n providerId: provider?.id ?? \"\",\n productIds: lines.map((line) => line.id),\n prescriptionStatus: DRAFT_STATUS,\n list: \"incomplete\",\n trackingNumber: null,\n createdAt: now,\n updatedAt: now,\n }\n this.state.prescriptions.insert(created.prescriptionId, created)\n const ids = { prescriptionId: created.prescriptionId, patientId }\n if (faultEffect(context.request, \"save_ambiguous_409\") !== undefined) {\n return annotateResponse(error(409, \"Request conflicted with a concurrent save\"), { ids })\n }\n return annotateResponse(\n jsonRes(200, {\n message: \"Prescription saved successfully\",\n prescriptionId: created.prescriptionId,\n isRefillRequest: false,\n refillFromPrescriptionId: null,\n }),\n { ids },\n )\n }\n\n private roster(context: OperationContext): Response {\n const body = record(context)\n this.clinic(String(body.clinicId))\n const limit = Number(body.limit)\n const page = Number(body.currentPage)\n const all = this.state.patients\n .list({ order: \"oldest\", where: (p) => p.clinicId === body.clinicId })\n .map((row) => row.value)\n const rows = all.slice((page - 1) * limit, page * limit)\n return jsonRes(200, {\n pagination: {\n hasNextPage: page * limit < all.length,\n currentPage: page,\n limit,\n totalCount: all.length,\n },\n patients: rows.map(patientBody),\n })\n }\n\n private prescriptionPage(context: OperationContext, list: PrescriptionList): Response {\n const body = record(context)\n const location = this.location(String(body.clinicLocationId))\n const limit = Number(body.limit)\n const page = Number(body.currentPage)\n const rows = this.state.list(list, location).slice((page - 1) * limit, page * limit)\n const envelope = this.state.current().statusEnvelope\n const useId = envelope === \"vendor\" && list === \"archived\"\n const shaped = rows.map((rx) => ({\n ...(useId ? { id: rx.prescriptionId } : { prescriptionId: rx.prescriptionId }),\n prescriptionStatus: rx.prescriptionStatus,\n trackingNumber: rx.trackingNumber,\n patientId: rx.patientId,\n createdAt: rx.createdAt,\n }))\n const kind =\n envelope !== \"vendor\"\n ? envelope\n : list === \"submitted\"\n ? \"message.prescriptions\"\n : list === \"archived\"\n ? \"message\"\n : \"array\"\n const payload =\n kind === \"array\"\n ? shaped\n : kind === \"prescriptions\"\n ? { prescriptions: shaped }\n : kind === \"message\"\n ? { message: shaped }\n : { message: { prescriptions: shaped } }\n return jsonRes(200, payload)\n }\n\n /** Move a prescription to a VPI status (and its list); completion adds a tracking number. */\n transition(id: string, input: TransitionInput): PrescriptionRecord | undefined {\n const rx = this.state.prescriptions.get(id)\n if (!rx) return undefined\n const resolved = resolveStatus(input.to)\n const next: PrescriptionRecord = {\n ...rx,\n prescriptionStatus: resolved.status,\n list: input.list ?? resolved.list,\n trackingNumber:\n input.trackingNumber ??\n rx.trackingNumber ??\n (isCompleted(resolved.status) ? `1Z${opaqueToken(id, 16).toUpperCase()}` : null),\n updatedAt: this.iso(),\n }\n this.state.prescriptions.update(id, next)\n return next\n }\n\n /** Seed a clinic patient (VPI patient creation is not part of our client's contract). */\n addPatient(input: PatientInput): Patient {\n const patient: Patient = {\n id: input.id ?? this.state.nextPatientId(),\n clinicId:\n input.clinicId ?? this.state.locations.list({ order: \"oldest\" })[0]?.value.clinicId ?? \"\",\n firstName: input.firstName,\n lastName: input.lastName,\n dateOfBirth: input.dateOfBirth,\n email: input.email ?? null,\n phoneNumber: input.phoneNumber ?? null,\n cellPhone: input.cellPhone ?? null,\n addresses: (input.addresses ?? []).map((a) => ({\n id: a.id ?? this.state.nextAddressId(),\n addressLine1: a.addressLine1,\n addressLine2: a.addressLine2 ?? null,\n city: a.city,\n state: a.state,\n zipcode: a.zipcode,\n })),\n }\n this.state.patients.insert(patient.id, patient)\n return patient\n }\n\n prescriptions(): PrescriptionRecord[] {\n return this.state.prescriptions.list({ order: \"oldest\" }).map((row) => row.value)\n }\n}\n\nexport type { VpiRuntime, VpiRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime, VPI_PRESETS } from \"./runtime.js\"\n"],
|
|
5
|
+
"mappings": ";AAgCO,IAAM,cAAc,CAAC,SAAuB,KAAK,QAAc;AACpE,MAAI,WAAW;AACf,MA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OAAO,QAAQ,IAAI,OAAO;AAC9C,WAAO;AAAA,EACT;AAAA,EAEA,gBAAsC;AACpC,WAAO,KAAK,MAAM,cAAc,KAAK,EAAE,OAAO,SAAS,CAAC,EAAE,IAAI,CAAC,QAAQ,IAAI,KAAK;AAAA,EAClF;AACF;",
|
|
6
|
+
"names": ["error", "next", "document", "document", "document", "document", "record", "matches", "error", "isRecord", "document", "error", "record", "json", "adminError", "isRecord", "BRANCH_PATTERN", "document", "snapshot", "branch", "url", "response", "error", "json", "adminError", "isRecord", "createRuntime", "json"]
|
|
7
|
+
}
|