@crvouga/mockingbird-service-pharmetika 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +175 -0
- package/dist/chunk-I6QERCU4.js +395 -0
- package/dist/chunk-I6QERCU4.js.map +7 -0
- package/dist/chunk-SQBTC6SN.js +3474 -0
- package/dist/chunk-SQBTC6SN.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1036 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1342 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
package/CHANGELOG.md
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# @crvouga/mockingbird-service-pharmetika
|
|
2
|
+
|
|
3
|
+
Stateful mock of the **Pharmetika** compounding-pharmacy provider portal for test suites:
|
|
4
|
+
clinic and patient lookup, patient create, medication-order validate / EPCS prepare / submit /
|
|
5
|
+
lookup, the v7 cancel, the medication-template catalog, and the status webhooks the pharmacy
|
|
6
|
+
posts back. Orders move only when a test says so (an admin transition or an auto-advance path on
|
|
7
|
+
the mock clock).
|
|
8
|
+
|
|
9
|
+
- Operation coverage: [SUPPORT.md](https://github.com/crvouga/mockingbird/blob/main/packages/service/pharmetika/SUPPORT.md)
|
|
10
|
+
- The vendor publishes no spec: the contract (`openapi.yaml`) is hand-authored from the wire
|
|
11
|
+
shapes our consumer reads and writes (`pharmetika-fulfillment.adapter.ts`,
|
|
12
|
+
`pharmetika-live.client.ts`, and the bodies recorded in the adapter's spec).
|
|
13
|
+
- **The success rule.** Every body carries Pharmetika's `success` flag. Only `true` or `1` is
|
|
14
|
+
success: the mock answers business failures (unknown patient, controlled substance on submit,
|
|
15
|
+
a reused order id, …) as **HTTP 200 with `success: 0`** and `messages: [{message, type}]`, the
|
|
16
|
+
case our adapter guards against.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install -D @crvouga/mockingbird-service-pharmetika
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
ESM only. Node >= 22 or Bun >= 1.2. No native dependencies. Serve it with
|
|
25
|
+
`npx mockingbird-pharmetika serve`, `createServer` from `./server` (Node), or `createRuntime` with
|
|
26
|
+
any Fetch server.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
Point `PHARMETIKA_API_URL` at the mock and give the app any `PHARMETIKA_API_TOKEN` (or pin one
|
|
31
|
+
with `--api-token`). Set `PHARMETIKA_WEBHOOK_SECRET` in the app and pass the same value as
|
|
32
|
+
`--webhook-secret`. `PHARMETIKA_PRACTITIONER_IDENTIFIER` can be any string;
|
|
33
|
+
`PHARMETIKA_CLINIC_NAME=Geviti` picks the seeded clinic.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npx mockingbird-pharmetika serve --port 8801 \
|
|
37
|
+
--webhook-url http://127.0.0.1:3000/prescriptions/webhooks/pharmetika \
|
|
38
|
+
--webhook-secret "$PHARMETIKA_WEBHOOK_SECRET" \
|
|
39
|
+
--auto-advance "2000:data_entry,shipped,completed"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { createRuntime } from "@crvouga/mockingbird-service-pharmetika"
|
|
44
|
+
|
|
45
|
+
const pmk = createRuntime({
|
|
46
|
+
webhooks: { url: "http://127.0.0.1:3000/prescriptions/webhooks/pharmetika", secret: "whsec" },
|
|
47
|
+
})
|
|
48
|
+
const admin = (path: string, body: unknown) =>
|
|
49
|
+
pmk.fetch(
|
|
50
|
+
new Request(`http://pharmetika.test/__admin${path}`, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: { "content-type": "application/json" },
|
|
53
|
+
body: JSON.stringify(body),
|
|
54
|
+
}),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
// …the app validates and submits PUT /api/v5/provider_portal/medication_order/id/<uuid>/submit…
|
|
58
|
+
|
|
59
|
+
// Move the order the way the pharmacy would; each step posts the status webhook.
|
|
60
|
+
await admin("/orders/<uuid>/transition", { to: "data_entry" })
|
|
61
|
+
await admin("/orders/<uuid>/transition", { to: "shipped", tracking_id: "1Z999" })
|
|
62
|
+
await admin("/orders/<uuid>/transition", { to: "completed" })
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Routes
|
|
66
|
+
|
|
67
|
+
All provider-portal routes need `x-pmk-authentication-token` (any non-empty token unless
|
|
68
|
+
`tokens` is set); a missing or rejected token is `401 {success: 0, messages}`.
|
|
69
|
+
|
|
70
|
+
| Route | Behaviour |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `GET /api/v5/provider_portal/clinic/clinic_list` | `{success: 1, data: [{identifier, data: {name}}]}`. Seeded with `Geviti` and `Geviti West`. |
|
|
73
|
+
| `GET /api/v5/provider_portal/provider/patient_list` | `{success: 1, data: [{patient_id, demographics: {first_name, last_name, DOB, email, phone_primary, line_1, postal_code}}]}`. Starts with one sandbox patient (id 1, "Sandbox Patient"). |
|
|
74
|
+
| `POST /api/v5/provider_portal/patient/create_new` | A FHIR `Patient` plus `clinic_identifier`. Created: `{success: true, patient_id, messages: [{message: "Added Patient!"}]}`. Same first/last name and DOB as an existing patient: `{success: 0, duplicate_entry_count, duplicate_entries: [...]}` (our adapter adopts the match). |
|
|
75
|
+
| `PUT …/medication_order/id/{uuid}/validate` | Dry run. Checks the clinic, the patient id, each `product_identifier` against the templates, and a non-empty `sig` ("Please provide instructions"). Answers `data: {controlled_substance_list_count, medication_list: [{…entry, medication_order_entry_identifier, controlled, control_level}]}`; a scheduled product (testosterone is C-III) sets `controlled`. |
|
|
76
|
+
| `PUT …/medication_order/id/{uuid}` | EPCS prepare (needs `prepared_by`). Parks the order at `pending_prescriber_approval`; it is **never submitted**. The prescriber "signs" with an admin transition to `signed`. |
|
|
77
|
+
| `PUT …/medication_order/id/{uuid}/submit` | Creates the order at `prescription_entered`. A controlled substance is refused (`success: 0`). **Idempotent by the UUIDv7**: a resubmit of the same clinic / patient / products / quantities / sigs (our adapter regenerates `date_issued` and entry ids on every attempt, so those are ignored) answers as the first did; different contents under a used id is `409 {success: 0}`; a concurrent submit of the same id is `409`. |
|
|
78
|
+
| `GET …/medication_order/id/{uuid}` | `{success: 1, data: {order_status, medication_order_identifier, electronic_prescription_order_number, data: {order_status, …, ancillary_order_data: {medication_order_status: {workflow_status, tracking_id}}}}}`; unknown ids 404. |
|
|
79
|
+
| `PUT /api/v7/provider_portal/medication_order/entry/cancel` | `{note, prescriber_order_number: <uuid>}` → `{success: 1, messages: []}` until the order ships; afterwards (or unknown) `success: 0`. Emits the webhook. |
|
|
80
|
+
| `GET /api/pharmetika/provider_access/profile/medication_templates` | `{success: 1, data: [{template_identifier, medication_display_name, description, map_dose_to_product: {dose: product_identifier}, qty_options, default_sigs, available_states, controlled}]}`. Accepts the token, Basic (`PHARMETIKA_USERNAME/PASSWORD`, any pair unless `basic` is set), or no credentials (unless `anonymousCatalog: false`) — our client's three fallbacks. |
|
|
81
|
+
|
|
82
|
+
### Webhooks
|
|
83
|
+
|
|
84
|
+
Every status change posts to `--webhook-url` with header `x-pharmetika-webhook-secret: <secret>`
|
|
85
|
+
(plain equality, as our receiver checks). The body shape follows the namespace's
|
|
86
|
+
`webhookVariant`, one per field fallback our receiver reads:
|
|
87
|
+
|
|
88
|
+
| Variant | Body |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `workflow_status` (default) | `{event_type, event_data: {electronic_prescription_order_number, medication_order_identifier, medication_order_status: {workflow_status, tracking_id}, tracking_id?, updated_at}}` |
|
|
91
|
+
| `status` | `{event_type, event_data: {medication_order_identifier, status, tracking_id?}}` |
|
|
92
|
+
| `flat` | `{medication_order_identifier, medication_order_workflow_status, tracking_id?}` |
|
|
93
|
+
|
|
94
|
+
Both id fields carry our UUIDv7 (the receiver looks payments up by it). Non-2xx answers are
|
|
95
|
+
retried (immediately, 5 s, 5 min, 30 min, 2 h). `GET /__admin/webhooks` lists deliveries,
|
|
96
|
+
`GET /__admin/webhooks/events` the payloads, `POST /__admin/webhooks/flush` runs pending retries,
|
|
97
|
+
`PUT /__admin/webhook-endpoints` sets per-namespace receivers.
|
|
98
|
+
|
|
99
|
+
### Status map
|
|
100
|
+
|
|
101
|
+
Transitions set `workflow_status` verbatim, so any string works. The ones our mapper knows:
|
|
102
|
+
|
|
103
|
+
| Workflow status | Our status |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| `completed`, `shipped-received`, `delivered` | delivered |
|
|
106
|
+
| `shipped`, `Completed Orders` | shipped |
|
|
107
|
+
| `cancelled` | cancelled |
|
|
108
|
+
| `data_entry*`, `lab_formulation`, `contacting_patient`, `compounding*`, `filled`, `dispensed`, `dispense_checked`, `dispense_verified`, `order_reconciliation`, `shipping`, `signed`, `verified`, `checked`, `ready`, `ready-ship`, `Complete Processing` | processing |
|
|
109
|
+
| anything else (`prescription_entered`, `pending_prescriber_approval`) | submitted |
|
|
110
|
+
|
|
111
|
+
Shipped-or-later statuses generate a `tracking_id` when none is given; a tracking id promotes
|
|
112
|
+
submitted/processing to shipped in our receiver.
|
|
113
|
+
|
|
114
|
+
### Admin (beyond the standard contract)
|
|
115
|
+
|
|
116
|
+
| Route | Effect |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `POST /__admin/orders/:uuid/transition` | `{to, tracking_id?}`: set the workflow status and emit the webhook. |
|
|
119
|
+
| `GET /__admin/orders` | The namespace's orders (ids and statuses only). |
|
|
120
|
+
| `GET /__admin/patients`, `POST /__admin/patients` | Read or seed the roster: `{patient_id?, clinic_identifier?, demographics: {first_name, last_name, DOB, …}}`. |
|
|
121
|
+
| `PUT /__admin/templates` | Replace the medication templates (`{templates: [...]}`). |
|
|
122
|
+
| `GET`/`PUT /__admin/settings` | `{tokens?, basic?, anonymousCatalog?, webhookVariant?, autoAdvance?: {afterMs, path} \| null}` for the calling namespace. |
|
|
123
|
+
| `POST /__admin/tick` | Apply due auto-advance steps (the served mock ticks every 100 ms). Orders awaiting prescriber approval never auto-advance. |
|
|
124
|
+
|
|
125
|
+
Fault presets (`POST /__admin/faults {"preset": "<name>", "count"?: n}`; `GET /__admin/faults/presets`):
|
|
126
|
+
|
|
127
|
+
| Preset | Effect |
|
|
128
|
+
| --- | --- |
|
|
129
|
+
| `validate_success_zero`, `submit_success_zero`, `prepare_success_zero`, `lookup_success_zero` | HTTP 200 with `success: 0` and a message |
|
|
130
|
+
| `validate_422` | 422 `{success: 0, messages: [{message: "Please provide instructions"}]}` |
|
|
131
|
+
| `success_boolean` | successes answer `success: true` instead of `1` |
|
|
132
|
+
| `success_string` | successes answer `success: "1"` (our client reads it as failure) |
|
|
133
|
+
| `cancel_success_true` | cancel answers `success: true` (our cancel accepts only `1`) |
|
|
134
|
+
| `submitted_but_500` | submit records the order, then answers 500; the retry replays success |
|
|
135
|
+
| `patient_create_duplicate`, `patient_create_500` | the create is refused as a duplicate (naming the patient), or fails |
|
|
136
|
+
| `clinic_list_keyed` | `clinic_list` answers `data` as an object keyed by identifier |
|
|
137
|
+
| `controlled_count_string`, `controlled_nested_requests` | validate's controlled-substance signal as a string count, or under `data.medication_requests` |
|
|
138
|
+
| `unauthorized`, `server_error` | 401 on every call; 500 on every provider-portal call |
|
|
139
|
+
| `webhook_duplicate`, `webhook_reorder`, `webhook_drop` | delivery faults on the next status webhooks |
|
|
140
|
+
|
|
141
|
+
### Namespaces
|
|
142
|
+
|
|
143
|
+
Our backend's `fetch` cannot add headers, so a namespace can be chosen three ways:
|
|
144
|
+
`x-mockingbird-namespace`, a `/ns/<name>` prefix on `PHARMETIKA_API_URL`, or by credential:
|
|
145
|
+
`PUT /__admin/credentials {"credentials": {"<PHARMETIKA_API_TOKEN>": "<namespace>"}}` (the Basic
|
|
146
|
+
username works the same way for the catalog client).
|
|
147
|
+
|
|
148
|
+
### Deliberately not modelled
|
|
149
|
+
|
|
150
|
+
- Real fulfilment timing and the pharmacy's internal queue: nothing moves on its own unless
|
|
151
|
+
`autoAdvance` is set.
|
|
152
|
+
- EPCS signing itself (two-factor, DEA checks): an admin transition to `signed` stands for it.
|
|
153
|
+
- Sigs, demographics on orders, documents and reason-for-compounding are validated, never stored
|
|
154
|
+
or echoed; only the roster keeps the demographics `patient_list` returns.
|
|
155
|
+
- The live catalog: the default templates are synthesised in the fields the live client parses
|
|
156
|
+
(no sandbox recording exists); pass `templates` or `PUT /__admin/templates` to load recorded rows.
|
|
157
|
+
- Refills, reauthorizations and multi-order shipments.
|
|
158
|
+
|
|
159
|
+
## API
|
|
160
|
+
|
|
161
|
+
| Export | Kind | Description |
|
|
162
|
+
| --- | --- | --- |
|
|
163
|
+
| `PharmetikaAPI` | class | The in-process mock: `fetch(request)`, `reset()`, `transition(uuid, {to, tracking_id?})`, `tick()`, `orders()`, `webhookBody(order)`. Options: `sqlite`, `now`, `namespace`, `templates`, `clinics`, `patients`, `settings`, `onWebhook`. |
|
|
164
|
+
| `createRuntime` | function | The mock with the full service contract (health, admin, namespaces, credentials, presets, webhooks). Options: `webhooks: {url, secret, retryDelaysMs?, fetch?}`, `settings`, `templates`, `clinics`, `patients`, `tickMs`, `clock`, `seed`, `adminKey`, `onLog`. |
|
|
165
|
+
| `PHARMETIKA_PRESETS` | object | Every named fault preset. |
|
|
166
|
+
| `PHARMETIKA_NAMESPACE` | string | The service name, `"pharmetika"`. |
|
|
167
|
+
| `TOKEN_HEADER` | string | `"x-pmk-authentication-token"`. |
|
|
168
|
+
| `WEBHOOK_SECRET_HEADER` | string | `"x-pharmetika-webhook-secret"`. |
|
|
169
|
+
| `tokenCredential` | function | The credential a request carries (portal token, else Basic username), for namespace mapping. |
|
|
170
|
+
| `DEFAULT_TEMPLATES`, `DEFAULT_CLINICS`, `SANDBOX_PATIENT` | values | The seed catalog, clinics and roster patient. |
|
|
171
|
+
| `KNOWN_STATUSES`, `SUBMITTED_STATUS`, `PENDING_APPROVAL_STATUS` | values | Documented workflow statuses. |
|
|
172
|
+
| `document`, `operationIds`, `supportedOperationIds` | values | The vendored OpenAPI contract and its operation ids. |
|
|
173
|
+
| `createServer`, `serveTarget`, `DEFAULT_PORT` (`./server`) | Node | Serve over `node:http` (auto-advance ticks every 100 ms); the `serve` CLI target; port 8801. |
|
|
174
|
+
|
|
175
|
+
Part of [mockingbird](https://github.com/crvouga/mockingbird).
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createRuntime
|
|
3
|
+
} from "./chunk-SQBTC6SN.js";
|
|
4
|
+
|
|
5
|
+
// ../../adapters/node/dist/cli.js
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
|
|
9
|
+
// ../../adapters/node/dist/serve.js
|
|
10
|
+
import { createServer } from "node:http";
|
|
11
|
+
var serve = async (api, options = {}) => {
|
|
12
|
+
const server = createServer(async (req, res) => {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
for await (const chunk of req) {
|
|
15
|
+
chunks.push(Buffer.from(chunk));
|
|
16
|
+
}
|
|
17
|
+
const body = Buffer.concat(chunks);
|
|
18
|
+
const address = server.address();
|
|
19
|
+
const port = typeof address === "object" && address !== null ? address.port : void 0;
|
|
20
|
+
const base = `http://${req.headers.host ?? `localhost:${port ?? 80}`}`;
|
|
21
|
+
const raw = req.url ?? "/";
|
|
22
|
+
const url = new URL(raw.replace(/^\/+/, "/"), base);
|
|
23
|
+
const method = req.method ?? "GET";
|
|
24
|
+
const init = { method, headers: req.headers };
|
|
25
|
+
if (method !== "GET" && method !== "HEAD" && body.length > 0) {
|
|
26
|
+
init.body = body;
|
|
27
|
+
}
|
|
28
|
+
const aborted = new AbortController();
|
|
29
|
+
res.once("close", () => {
|
|
30
|
+
if (!res.writableFinished)
|
|
31
|
+
aborted.abort();
|
|
32
|
+
});
|
|
33
|
+
init.signal = aborted.signal;
|
|
34
|
+
const request = new Request(url, init);
|
|
35
|
+
let response;
|
|
36
|
+
try {
|
|
37
|
+
response = await api.fetch(request);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (error.code === "MOCKINGBIRD_DROP") {
|
|
40
|
+
req.socket.destroy();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
44
|
+
res.end(JSON.stringify({
|
|
45
|
+
error: {
|
|
46
|
+
type: "mockingbird_internal",
|
|
47
|
+
message: error instanceof Error ? error.message : String(error)
|
|
48
|
+
}
|
|
49
|
+
}));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const headers = Object.fromEntries(response.headers);
|
|
53
|
+
const cookies = response.headers.getSetCookie();
|
|
54
|
+
if (cookies.length > 0)
|
|
55
|
+
headers["set-cookie"] = cookies;
|
|
56
|
+
if (!response.body) {
|
|
57
|
+
res.writeHead(response.status, headers);
|
|
58
|
+
res.end();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
res.writeHead(response.status, headers);
|
|
62
|
+
res.flushHeaders();
|
|
63
|
+
const reader = response.body.getReader();
|
|
64
|
+
try {
|
|
65
|
+
for (; ; ) {
|
|
66
|
+
const { done, value } = await reader.read();
|
|
67
|
+
if (done)
|
|
68
|
+
break;
|
|
69
|
+
if (!res.write(value))
|
|
70
|
+
await new Promise((resolve) => res.once("drain", resolve));
|
|
71
|
+
}
|
|
72
|
+
res.end();
|
|
73
|
+
} catch {
|
|
74
|
+
res.destroy();
|
|
75
|
+
} finally {
|
|
76
|
+
reader.releaseLock();
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
await new Promise((resolve, reject) => {
|
|
80
|
+
server.once("error", reject);
|
|
81
|
+
server.listen(options.port ?? 0, options.host, resolve);
|
|
82
|
+
});
|
|
83
|
+
return server;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// ../../adapters/node/dist/listen.js
|
|
87
|
+
var listen = async (api, options = {}) => {
|
|
88
|
+
const host = options.host ?? "127.0.0.1";
|
|
89
|
+
const server = await serve(api, { port: options.port ?? 0, host });
|
|
90
|
+
const address = server.address();
|
|
91
|
+
const port = typeof address === "object" && address !== null ? address.port : options.port ?? 0;
|
|
92
|
+
const shown = host.includes(":") ? `[${host}]` : host;
|
|
93
|
+
return {
|
|
94
|
+
url: `http://${shown}:${port}`,
|
|
95
|
+
port,
|
|
96
|
+
host,
|
|
97
|
+
server,
|
|
98
|
+
close: () => new Promise((resolve, reject) => {
|
|
99
|
+
server.close((error) => {
|
|
100
|
+
if (error && error.code !== "ERR_SERVER_NOT_RUNNING")
|
|
101
|
+
reject(error);
|
|
102
|
+
else
|
|
103
|
+
resolve();
|
|
104
|
+
});
|
|
105
|
+
server.closeAllConnections?.();
|
|
106
|
+
})
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// ../../adapters/node/dist/cli.js
|
|
111
|
+
var optionHelp = (options) => Object.entries(options).map(([name, option]) => {
|
|
112
|
+
const flag = `--${name}${option.type === "string" ? ` ${option.value ?? "<value>"}` : ""}`;
|
|
113
|
+
const fallback = option.default !== void 0 ? ` (default: ${String(option.default)})` : "";
|
|
114
|
+
return ` ${flag.padEnd(30)} ${option.description}${fallback}`;
|
|
115
|
+
});
|
|
116
|
+
var help = (spec) => [
|
|
117
|
+
`${spec.bin} \u2014 ${spec.description}`,
|
|
118
|
+
"",
|
|
119
|
+
"Usage:",
|
|
120
|
+
` ${spec.bin} <command> [options]`,
|
|
121
|
+
"",
|
|
122
|
+
"Commands:",
|
|
123
|
+
...Object.entries(spec.commands).map(([name, c]) => ` ${name.padEnd(30)} ${c.summary}`),
|
|
124
|
+
"",
|
|
125
|
+
`Run \`${spec.bin} <command> --help\` for a command's options.`
|
|
126
|
+
].join("\n");
|
|
127
|
+
var commandHelp = (spec, name, command) => [
|
|
128
|
+
`${spec.bin} ${name} \u2014 ${command.summary}`,
|
|
129
|
+
"",
|
|
130
|
+
"Usage:",
|
|
131
|
+
` ${command.usage ?? `${spec.bin} ${name} [options]`}`,
|
|
132
|
+
...command.options ? ["", "Options:", ...optionHelp(command.options)] : []
|
|
133
|
+
].join("\n");
|
|
134
|
+
var runCli = async (spec, argv) => {
|
|
135
|
+
const pair = argv.length >= 2 ? `${argv[0]} ${argv[1]}` : void 0;
|
|
136
|
+
const words = pair !== void 0 && spec.commands[pair] ? 2 : 1;
|
|
137
|
+
const name = words === 2 ? pair : argv[0];
|
|
138
|
+
const rest = argv.slice(words);
|
|
139
|
+
if (name === void 0 || name === "--help" || name === "-h" || name === "help") {
|
|
140
|
+
console.log(help(spec));
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
const command = spec.commands[name];
|
|
144
|
+
if (!command) {
|
|
145
|
+
console.error(`${spec.bin}: unknown command ${JSON.stringify(name)}
|
|
146
|
+
|
|
147
|
+
${help(spec)}`);
|
|
148
|
+
return 2;
|
|
149
|
+
}
|
|
150
|
+
if (rest.includes("--help") || rest.includes("-h")) {
|
|
151
|
+
console.log(commandHelp(spec, name, command));
|
|
152
|
+
return 0;
|
|
153
|
+
}
|
|
154
|
+
let parsed;
|
|
155
|
+
try {
|
|
156
|
+
parsed = parseArgs({
|
|
157
|
+
args: rest,
|
|
158
|
+
allowPositionals: true,
|
|
159
|
+
strict: true,
|
|
160
|
+
options: Object.fromEntries(Object.entries(command.options ?? {}).map(([key, option]) => [
|
|
161
|
+
key,
|
|
162
|
+
{
|
|
163
|
+
type: option.type,
|
|
164
|
+
...option.default !== void 0 ? { default: option.default } : {}
|
|
165
|
+
}
|
|
166
|
+
]))
|
|
167
|
+
});
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error(`${spec.bin} ${name}: ${error instanceof Error ? error.message : String(error)}
|
|
170
|
+
|
|
171
|
+
${commandHelp(spec, name, command)}`);
|
|
172
|
+
return 2;
|
|
173
|
+
}
|
|
174
|
+
return command.run(parsed.values, parsed.positionals);
|
|
175
|
+
};
|
|
176
|
+
var COMMON_SERVE_OPTIONS = {
|
|
177
|
+
port: { type: "string", value: "<port>", description: "Port to listen on" },
|
|
178
|
+
host: { type: "string", value: "<host>", description: "Interface to bind", default: "127.0.0.1" },
|
|
179
|
+
"admin-key": {
|
|
180
|
+
type: "string",
|
|
181
|
+
value: "<key>",
|
|
182
|
+
description: "Require x-mockingbird-admin-key on /__admin/* (env MOCKINGBIRD_ADMIN_KEY)"
|
|
183
|
+
},
|
|
184
|
+
seed: { type: "string", value: "<seed>", description: "Seed for every random choice" },
|
|
185
|
+
log: {
|
|
186
|
+
type: "string",
|
|
187
|
+
value: "<pretty|json|off>",
|
|
188
|
+
description: "Request log format",
|
|
189
|
+
default: "pretty"
|
|
190
|
+
},
|
|
191
|
+
"log-requests": {
|
|
192
|
+
type: "boolean",
|
|
193
|
+
description: "One JSON line per request: namespace, operationId, status, ids touched (never bodies). Same as --log json"
|
|
194
|
+
},
|
|
195
|
+
config: {
|
|
196
|
+
type: "string",
|
|
197
|
+
value: "<file>",
|
|
198
|
+
description: "Serve every service in a mockingbird.json config instead"
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
var formatLog = (format) => {
|
|
202
|
+
if (format === "off")
|
|
203
|
+
return void 0;
|
|
204
|
+
if (format === "json")
|
|
205
|
+
return (entry) => console.log(JSON.stringify(entry));
|
|
206
|
+
return (entry) => {
|
|
207
|
+
const op = entry.operationId ?? (entry.unmatched ? "UNMATCHED" : "-");
|
|
208
|
+
const ns = entry.namespace === "default" ? "" : ` [${entry.namespace}]`;
|
|
209
|
+
const fault = entry.faultId ? ` fault=${entry.faultId}` : "";
|
|
210
|
+
const adopted = entry.adopted ? " adopted" : "";
|
|
211
|
+
console.log(`${entry.service} ${entry.method} ${entry.path} ${entry.status} ${op} ${entry.durationMs}ms${ns}${fault}${adopted}`);
|
|
212
|
+
};
|
|
213
|
+
};
|
|
214
|
+
var asString = (value) => typeof value === "string" ? value : void 0;
|
|
215
|
+
var loadTarget = async (name, own) => {
|
|
216
|
+
if (name === own.name)
|
|
217
|
+
return own;
|
|
218
|
+
const specifier = `@crvouga/mockingbird-service-${name}/server`;
|
|
219
|
+
try {
|
|
220
|
+
const mod = await import(specifier);
|
|
221
|
+
if (!mod.serveTarget)
|
|
222
|
+
throw new Error(`${specifier} exports no serveTarget`);
|
|
223
|
+
return mod.serveTarget;
|
|
224
|
+
} catch (error) {
|
|
225
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
226
|
+
throw new Error(`cannot load service "${name}": ${reason}. Install @crvouga/mockingbird-service-${name}.`);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
var start = async (target, values, config) => {
|
|
230
|
+
const runtime = await target.create(values, {
|
|
231
|
+
adminKey: config.adminKey,
|
|
232
|
+
seed: config.seed,
|
|
233
|
+
onLog: formatLog(config.log)
|
|
234
|
+
});
|
|
235
|
+
const listening = await listen(runtime, { port: config.port, host: config.host });
|
|
236
|
+
console.log(`${target.name} mock listening on ${listening.url}`);
|
|
237
|
+
console.log(`${target.name} health: GET ${listening.url}/health`);
|
|
238
|
+
console.log(`${target.name} admin: ${listening.url}/__admin (${config.adminKey ? "x-mockingbird-admin-key required" : "open \u2014 pass --admin-key to lock"})`);
|
|
239
|
+
for (const line of target.banner?.(runtime) ?? [])
|
|
240
|
+
console.log(`${target.name} ${line}`);
|
|
241
|
+
return listening;
|
|
242
|
+
};
|
|
243
|
+
var untilSignal = async (servers) => new Promise((resolve) => {
|
|
244
|
+
const stop = async () => {
|
|
245
|
+
await Promise.allSettled(servers.map((s) => s.close()));
|
|
246
|
+
resolve(0);
|
|
247
|
+
};
|
|
248
|
+
process.once("SIGINT", stop);
|
|
249
|
+
process.once("SIGTERM", stop);
|
|
250
|
+
});
|
|
251
|
+
var serveCommand = (target) => ({
|
|
252
|
+
summary: `Serve the ${target.name} mock over HTTP`,
|
|
253
|
+
options: { ...COMMON_SERVE_OPTIONS, ...target.options },
|
|
254
|
+
async run(values) {
|
|
255
|
+
const log = values["log-requests"] === true ? "json" : asString(values.log) ?? "pretty";
|
|
256
|
+
if (!["pretty", "json", "off"].includes(log)) {
|
|
257
|
+
console.error(`--log must be pretty, json or off (got ${log})`);
|
|
258
|
+
return 2;
|
|
259
|
+
}
|
|
260
|
+
const configPath = asString(values.config);
|
|
261
|
+
if (configPath !== void 0) {
|
|
262
|
+
const config = JSON.parse(await readFile(configPath, "utf8"));
|
|
263
|
+
const servers = [];
|
|
264
|
+
try {
|
|
265
|
+
for (const [name, entry] of Object.entries(config.services ?? {})) {
|
|
266
|
+
const each = await loadTarget(name, target);
|
|
267
|
+
servers.push(await start(each, entry.options ?? {}, {
|
|
268
|
+
port: entry.port ?? each.defaultPort,
|
|
269
|
+
host: entry.host ?? "127.0.0.1",
|
|
270
|
+
...entry.adminKey !== void 0 ? { adminKey: entry.adminKey } : {},
|
|
271
|
+
...entry.seed !== void 0 ? { seed: entry.seed } : {},
|
|
272
|
+
log: config.log ?? log
|
|
273
|
+
}));
|
|
274
|
+
}
|
|
275
|
+
} catch (error) {
|
|
276
|
+
await Promise.allSettled(servers.map((s) => s.close()));
|
|
277
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
278
|
+
return 1;
|
|
279
|
+
}
|
|
280
|
+
return untilSignal(servers);
|
|
281
|
+
}
|
|
282
|
+
const port = asString(values.port);
|
|
283
|
+
const adminKey = asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
|
|
284
|
+
const seed = asString(values.seed);
|
|
285
|
+
let listening;
|
|
286
|
+
try {
|
|
287
|
+
listening = await start(target, values, {
|
|
288
|
+
port: port === void 0 ? target.defaultPort : Number.parseInt(port, 10),
|
|
289
|
+
host: asString(values.host) ?? "127.0.0.1",
|
|
290
|
+
...adminKey !== void 0 ? { adminKey } : {},
|
|
291
|
+
...seed !== void 0 ? { seed } : {},
|
|
292
|
+
log
|
|
293
|
+
});
|
|
294
|
+
} catch (error) {
|
|
295
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
296
|
+
return 1;
|
|
297
|
+
}
|
|
298
|
+
return untilSignal([listening]);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// src/server.ts
|
|
303
|
+
var DEFAULT_PORT = 8801;
|
|
304
|
+
var createServer2 = async (options = {}) => {
|
|
305
|
+
const { port, host, ...rest } = options;
|
|
306
|
+
const runtime = createRuntime({ tickMs: 100, ...rest });
|
|
307
|
+
const listening = await listen(runtime, {
|
|
308
|
+
port: port ?? 0,
|
|
309
|
+
...host !== void 0 ? { host } : {}
|
|
310
|
+
});
|
|
311
|
+
return {
|
|
312
|
+
...listening,
|
|
313
|
+
runtime,
|
|
314
|
+
close: async () => {
|
|
315
|
+
runtime.stop();
|
|
316
|
+
await listening.close();
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
};
|
|
320
|
+
var text = (value) => typeof value === "string" ? value : void 0;
|
|
321
|
+
var VARIANTS = ["workflow_status", "status", "flat"];
|
|
322
|
+
var serveTarget = {
|
|
323
|
+
name: "pharmetika",
|
|
324
|
+
defaultPort: DEFAULT_PORT,
|
|
325
|
+
options: {
|
|
326
|
+
"webhook-url": {
|
|
327
|
+
type: "string",
|
|
328
|
+
value: "<url>",
|
|
329
|
+
description: "Deliver status webhooks here (e.g. http://127.0.0.1:3000/prescriptions/webhooks/pharmetika)"
|
|
330
|
+
},
|
|
331
|
+
"webhook-secret": {
|
|
332
|
+
type: "string",
|
|
333
|
+
value: "<secret>",
|
|
334
|
+
description: "Sent as x-pharmetika-webhook-secret (the app's PHARMETIKA_WEBHOOK_SECRET)"
|
|
335
|
+
},
|
|
336
|
+
"api-token": {
|
|
337
|
+
type: "string",
|
|
338
|
+
value: "<token>",
|
|
339
|
+
description: "Accept only this x-pmk-authentication-token (the app's PHARMETIKA_API_TOKEN)"
|
|
340
|
+
},
|
|
341
|
+
"webhook-variant": {
|
|
342
|
+
type: "string",
|
|
343
|
+
value: "<workflow_status|status|flat>",
|
|
344
|
+
description: "Which receiver field fallback the webhook body uses (default workflow_status)"
|
|
345
|
+
},
|
|
346
|
+
"auto-advance": {
|
|
347
|
+
type: "string",
|
|
348
|
+
value: "<ms:status,status,\u2026>",
|
|
349
|
+
description: 'Walk every new order along a path, e.g. "2000:data_entry,shipped,completed"'
|
|
350
|
+
}
|
|
351
|
+
},
|
|
352
|
+
create: (values, common) => {
|
|
353
|
+
const url = text(values["webhook-url"]);
|
|
354
|
+
const secret = text(values["webhook-secret"]);
|
|
355
|
+
const token = text(values["api-token"]);
|
|
356
|
+
const variant = text(values["webhook-variant"]);
|
|
357
|
+
const auto = text(values["auto-advance"]);
|
|
358
|
+
const plan = auto ? /^(\d+):(.+)$/.exec(auto) : null;
|
|
359
|
+
if (auto && !plan)
|
|
360
|
+
throw new Error('--auto-advance must look like "2000:data_entry,shipped,completed"');
|
|
361
|
+
if (variant && !VARIANTS.includes(variant)) {
|
|
362
|
+
throw new Error(`--webhook-variant must be one of ${VARIANTS.join(", ")}`);
|
|
363
|
+
}
|
|
364
|
+
return createRuntime({
|
|
365
|
+
tickMs: 100,
|
|
366
|
+
...url ? { webhooks: { url, ...secret ? { secret } : {} } } : {},
|
|
367
|
+
settings: {
|
|
368
|
+
...token ? { tokens: [token] } : {},
|
|
369
|
+
...variant ? { webhookVariant: variant } : {},
|
|
370
|
+
...plan ? {
|
|
371
|
+
autoAdvance: {
|
|
372
|
+
afterMs: Number(plan[1]),
|
|
373
|
+
path: plan[2].split(",").map((s) => s.trim())
|
|
374
|
+
}
|
|
375
|
+
} : {}
|
|
376
|
+
},
|
|
377
|
+
...common.adminKey !== void 0 ? { adminKey: common.adminKey } : {},
|
|
378
|
+
...common.seed !== void 0 ? { seed: common.seed } : {},
|
|
379
|
+
...common.onLog ? { onLog: common.onLog } : {}
|
|
380
|
+
});
|
|
381
|
+
},
|
|
382
|
+
banner: () => [
|
|
383
|
+
"auth: x-pmk-authentication-token: <token> (catalog also takes Basic or nothing)",
|
|
384
|
+
"namespaces: x-mockingbird-namespace, /ns/<name>/\u2026, or PUT /__admin/credentials {<token>: <ns>}"
|
|
385
|
+
]
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
export {
|
|
389
|
+
runCli,
|
|
390
|
+
serveCommand,
|
|
391
|
+
DEFAULT_PORT,
|
|
392
|
+
createServer2 as createServer,
|
|
393
|
+
serveTarget
|
|
394
|
+
};
|
|
395
|
+
//# sourceMappingURL=chunk-I6QERCU4.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../adapters/node/src/cli.ts", "../../../adapters/node/src/serve.ts", "../../../adapters/node/src/listen.ts", "../src/server.ts"],
|
|
4
|
+
"sourcesContent": ["import { readFile } from \"node:fs/promises\"\nimport { type ParseArgsConfig, parseArgs } from \"node:util\"\nimport type { RequestLog, ServiceInstance, ServiceRuntime } from \"@crvouga/mockingbird-service\"\nimport { type Listening, listen } from \"./listen.js\"\n\nexport type CliOption = {\n type: \"string\" | \"boolean\"\n description: string\n /** Shown in help; the value placeholder, e.g. `<port>`. */\n value?: string\n default?: string | boolean\n}\n\nexport type CliValues = Record<string, string | boolean | undefined>\n\nexport type CliCommand = {\n summary: string\n usage?: string\n options?: Record<string, CliOption>\n /** Resolves to an exit code; a server command resolves only when it stops. */\n run(values: CliValues, positionals: string[]): Promise<number>\n}\n\nexport type CliSpec = {\n bin: string\n description: string\n commands: Record<string, CliCommand>\n}\n\nconst optionHelp = (options: Record<string, CliOption>): string[] =>\n Object.entries(options).map(([name, option]) => {\n const flag = `--${name}${option.type === \"string\" ? ` ${option.value ?? \"<value>\"}` : \"\"}`\n const fallback = option.default !== undefined ? ` (default: ${String(option.default)})` : \"\"\n return ` ${flag.padEnd(30)} ${option.description}${fallback}`\n })\n\nconst help = (spec: CliSpec): string =>\n [\n `${spec.bin} \u2014 ${spec.description}`,\n \"\",\n \"Usage:\",\n ` ${spec.bin} <command> [options]`,\n \"\",\n \"Commands:\",\n ...Object.entries(spec.commands).map(([name, c]) => ` ${name.padEnd(30)} ${c.summary}`),\n \"\",\n `Run \\`${spec.bin} <command> --help\\` for a command's options.`,\n ].join(\"\\n\")\n\nconst commandHelp = (spec: CliSpec, name: string, command: CliCommand): string =>\n [\n `${spec.bin} ${name} \u2014 ${command.summary}`,\n \"\",\n \"Usage:\",\n ` ${command.usage ?? `${spec.bin} ${name} [options]`}`,\n ...(command.options ? [\"\", \"Options:\", ...optionHelp(command.options)] : []),\n ].join(\"\\n\")\n\n/** Parse `argv` against `spec` and run the chosen command. Resolves to an exit code. */\nexport const runCli = async (spec: CliSpec, argv: string[]): Promise<number> => {\n // Two-word commands (`corpus pull`) win over one-word ones.\n const pair = argv.length >= 2 ? `${argv[0]} ${argv[1]}` : undefined\n const words = pair !== undefined && spec.commands[pair] ? 2 : 1\n const name = words === 2 ? pair : argv[0]\n const rest = argv.slice(words)\n if (name === undefined || name === \"--help\" || name === \"-h\" || name === \"help\") {\n console.log(help(spec))\n return 0\n }\n const command = spec.commands[name]\n if (!command) {\n console.error(`${spec.bin}: unknown command ${JSON.stringify(name)}\\n\\n${help(spec)}`)\n return 2\n }\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n console.log(commandHelp(spec, name, command))\n return 0\n }\n let parsed: { values: CliValues; positionals: string[] }\n try {\n parsed = parseArgs({\n args: rest,\n allowPositionals: true,\n strict: true,\n options: Object.fromEntries(\n Object.entries(command.options ?? {}).map(([key, option]) => [\n key,\n {\n type: option.type,\n ...(option.default !== undefined ? { default: option.default } : {}),\n },\n ]),\n ) as ParseArgsConfig[\"options\"],\n }) as { values: CliValues; positionals: string[] }\n } catch (error) {\n console.error(\n `${spec.bin} ${name}: ${error instanceof Error ? error.message : String(error)}\\n\\n${commandHelp(spec, name, command)}`,\n )\n return 2\n }\n return command.run(parsed.values, parsed.positionals)\n}\n\n// \u2500\u2500 serve \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type LogFormat = \"pretty\" | \"json\" | \"off\"\n\nexport type CommonServeOptions = {\n adminKey: string | undefined\n seed: string | undefined\n onLog: ((entry: RequestLog) => void) | undefined\n}\n\n/**\n * What a service contributes to `serve`: how to build its runtime from CLI flags,\n * and what to say at startup. Every service's `./server` entry exports one as\n * `serveTarget`, which is also how `serve --config` finds services by name.\n */\nexport type ServeTarget = {\n name: string\n defaultPort: number\n /** Serve flags beyond the common ones. */\n options?: Record<string, CliOption>\n create(\n values: CliValues,\n common: CommonServeOptions,\n ): Promise<ServiceRuntime<ServiceInstance>> | ServiceRuntime<ServiceInstance>\n /** Startup lines after the listen address, e.g. the loaded corpus version. */\n banner?(runtime: ServiceRuntime<ServiceInstance>): string[]\n}\n\nconst COMMON_SERVE_OPTIONS: Record<string, CliOption> = {\n port: { type: \"string\", value: \"<port>\", description: \"Port to listen on\" },\n host: { type: \"string\", value: \"<host>\", description: \"Interface to bind\", default: \"127.0.0.1\" },\n \"admin-key\": {\n type: \"string\",\n value: \"<key>\",\n description: \"Require x-mockingbird-admin-key on /__admin/* (env MOCKINGBIRD_ADMIN_KEY)\",\n },\n seed: { type: \"string\", value: \"<seed>\", description: \"Seed for every random choice\" },\n log: {\n type: \"string\",\n value: \"<pretty|json|off>\",\n description: \"Request log format\",\n default: \"pretty\",\n },\n \"log-requests\": {\n type: \"boolean\",\n description:\n \"One JSON line per request: namespace, operationId, status, ids touched (never bodies). Same as --log json\",\n },\n config: {\n type: \"string\",\n value: \"<file>\",\n description: \"Serve every service in a mockingbird.json config instead\",\n },\n}\n\nconst formatLog = (format: LogFormat) => {\n if (format === \"off\") return undefined\n if (format === \"json\") return (entry: RequestLog) => console.log(JSON.stringify(entry))\n return (entry: RequestLog) => {\n const op = entry.operationId ?? (entry.unmatched ? \"UNMATCHED\" : \"-\")\n const ns = entry.namespace === \"default\" ? \"\" : ` [${entry.namespace}]`\n const fault = entry.faultId ? ` fault=${entry.faultId}` : \"\"\n const adopted = entry.adopted ? \" adopted\" : \"\"\n console.log(\n `${entry.service} ${entry.method} ${entry.path} ${entry.status} ${op} ${entry.durationMs}ms${ns}${fault}${adopted}`,\n )\n }\n}\n\nconst asString = (value: string | boolean | undefined): string | undefined =>\n typeof value === \"string\" ? value : undefined\n\n/** A service entry in `mockingbird.json`. */\nexport type ConfigService = {\n port?: number\n host?: string\n adminKey?: string\n seed?: string\n /** Service-specific serve flags, by long name: `{ \"webhook-url\": \"\u2026\" }`. */\n options?: Record<string, string | boolean>\n}\n\nexport type MockingbirdConfig = {\n /** Keyed by service name: `junction` loads `@crvouga/mockingbird-service-junction`. */\n services: Record<string, ConfigService>\n log?: LogFormat\n}\n\nconst loadTarget = async (name: string, own: ServeTarget): Promise<ServeTarget> => {\n if (name === own.name) return own\n const specifier = `@crvouga/mockingbird-service-${name}/server`\n try {\n const mod = (await import(specifier)) as { serveTarget?: ServeTarget }\n if (!mod.serveTarget) throw new Error(`${specifier} exports no serveTarget`)\n return mod.serveTarget\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error)\n throw new Error(\n `cannot load service \"${name}\": ${reason}. Install @crvouga/mockingbird-service-${name}.`,\n )\n }\n}\n\nconst start = async (\n target: ServeTarget,\n values: CliValues,\n config: { port: number; host: string; adminKey?: string; seed?: string; log: LogFormat },\n): Promise<Listening> => {\n const runtime = await target.create(values, {\n adminKey: config.adminKey,\n seed: config.seed,\n onLog: formatLog(config.log),\n })\n const listening = await listen(runtime, { port: config.port, host: config.host })\n console.log(`${target.name} mock listening on ${listening.url}`)\n console.log(`${target.name} health: GET ${listening.url}/health`)\n console.log(\n `${target.name} admin: ${listening.url}/__admin (${config.adminKey ? \"x-mockingbird-admin-key required\" : \"open \u2014 pass --admin-key to lock\"})`,\n )\n for (const line of target.banner?.(runtime) ?? []) console.log(`${target.name} ${line}`)\n return listening\n}\n\nconst untilSignal = async (servers: Listening[]): Promise<number> =>\n new Promise((resolve) => {\n const stop = async () => {\n await Promise.allSettled(servers.map((s) => s.close()))\n resolve(0)\n }\n process.once(\"SIGINT\", stop)\n process.once(\"SIGTERM\", stop)\n })\n\n/** The standard `serve` command for a service, including multi-service `--config`. */\nexport const serveCommand = (target: ServeTarget): CliCommand => ({\n summary: `Serve the ${target.name} mock over HTTP`,\n options: { ...COMMON_SERVE_OPTIONS, ...target.options },\n async run(values) {\n const log = (\n values[\"log-requests\"] === true ? \"json\" : (asString(values.log) ?? \"pretty\")\n ) as LogFormat\n if (![\"pretty\", \"json\", \"off\"].includes(log)) {\n console.error(`--log must be pretty, json or off (got ${log})`)\n return 2\n }\n const configPath = asString(values.config)\n if (configPath !== undefined) {\n const config = JSON.parse(await readFile(configPath, \"utf8\")) as MockingbirdConfig\n const servers: Listening[] = []\n try {\n for (const [name, entry] of Object.entries(config.services ?? {})) {\n const each = await loadTarget(name, target)\n servers.push(\n await start(each, entry.options ?? {}, {\n port: entry.port ?? each.defaultPort,\n host: entry.host ?? \"127.0.0.1\",\n ...(entry.adminKey !== undefined ? { adminKey: entry.adminKey } : {}),\n ...(entry.seed !== undefined ? { seed: entry.seed } : {}),\n log: config.log ?? log,\n }),\n )\n }\n } catch (error) {\n await Promise.allSettled(servers.map((s) => s.close()))\n console.error(error instanceof Error ? error.message : String(error))\n return 1\n }\n return untilSignal(servers)\n }\n const port = asString(values.port)\n const adminKey = asString(values[\"admin-key\"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY\n const seed = asString(values.seed)\n let listening: Listening\n try {\n listening = await start(target, values, {\n port: port === undefined ? target.defaultPort : Number.parseInt(port, 10),\n host: asString(values.host) ?? \"127.0.0.1\",\n ...(adminKey !== undefined ? { adminKey } : {}),\n ...(seed !== undefined ? { seed } : {}),\n log,\n })\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 1\n }\n return untilSignal([listening])\n },\n})\n", "import { createServer } from \"node:http\"\nimport type { FetchAPI } from \"@crvouga/mockingbird-core\"\n\n/** Options for {@link serve}. */\nexport type NodeServeOptions = {\n port?: number\n host?: string\n}\n\n/**\n * Serve any Mockingbird {@link FetchAPI} over `node:http`.\n * Port defaults to `0`, so the OS assigns an ephemeral port (read from `server.address()`).\n */\nexport const serve = async (api: FetchAPI, options: NodeServeOptions = {}) => {\n const server = createServer(async (req, res) => {\n const chunks: Buffer[] = []\n for await (const chunk of req) {\n chunks.push(Buffer.from(chunk))\n }\n const body = Buffer.concat(chunks)\n const address = server.address()\n const port = typeof address === \"object\" && address !== null ? address.port : undefined\n const base = `http://${req.headers.host ?? `localhost:${port ?? 80}`}`\n const raw = req.url ?? \"/\"\n const url = new URL(raw.replace(/^\\/+/, \"/\"), base)\n const method = req.method ?? \"GET\"\n const init: RequestInit = { method, headers: req.headers as Record<string, string> }\n if (method !== \"GET\" && method !== \"HEAD\" && body.length > 0) {\n init.body = body\n }\n const aborted = new AbortController()\n res.once(\"close\", () => {\n if (!res.writableFinished) aborted.abort()\n })\n init.signal = aborted.signal\n const request = new Request(url, init)\n let response: Response\n try {\n response = await api.fetch(request)\n } catch (error) {\n // A `drop` fault: destroy the socket so the client sees the connection die.\n if ((error as { code?: string }).code === \"MOCKINGBIRD_DROP\") {\n req.socket.destroy()\n return\n }\n res.writeHead(500, { \"content-type\": \"application/json\" })\n res.end(\n JSON.stringify({\n error: {\n type: \"mockingbird_internal\",\n message: error instanceof Error ? error.message : String(error),\n },\n }),\n )\n return\n }\n // Headers#entries() joins repeated headers; Set-Cookie must stay one header per cookie.\n const headers: Record<string, string | string[]> = Object.fromEntries(response.headers)\n const cookies = response.headers.getSetCookie()\n if (cookies.length > 0) headers[\"set-cookie\"] = cookies\n if (!response.body) {\n res.writeHead(response.status, headers)\n res.end()\n return\n }\n // Stream the body chunk by chunk: event streams and long-polls must not be buffered.\n res.writeHead(response.status, headers)\n res.flushHeaders()\n const reader = response.body.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (!res.write(value)) await new Promise<void>((resolve) => res.once(\"drain\", resolve))\n }\n res.end()\n } catch {\n res.destroy()\n } finally {\n reader.releaseLock()\n }\n })\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject)\n server.listen(options.port ?? 0, options.host, resolve)\n })\n return server\n}\n", "import type { Server } from \"node:http\"\nimport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport { serve } from \"./serve.js\"\n\nexport type ListenOptions = {\n /** Default `0`: the OS picks a free port. */\n port?: number\n /** Default `127.0.0.1`: a mock should not be reachable off the machine by accident. */\n host?: string\n}\n\n/** A running server, with the address it actually bound. */\nexport type Listening = {\n url: string\n port: number\n host: string\n server: Server\n close(): Promise<void>\n}\n\nexport const listen = async (api: FetchAPI, options: ListenOptions = {}): Promise<Listening> => {\n const host = options.host ?? \"127.0.0.1\"\n const server = await serve(api, { port: options.port ?? 0, host })\n const address = server.address()\n const port = typeof address === \"object\" && address !== null ? address.port : (options.port ?? 0)\n const shown = host.includes(\":\") ? `[${host}]` : host\n return {\n url: `http://${shown}:${port}`,\n port,\n host,\n server,\n close: () =>\n new Promise<void>((resolve, reject) => {\n // Stop accepting first, then drop keep-alive sockets so close() can finish.\n server.close((error) => {\n if (error && (error as { code?: string }).code !== \"ERR_SERVER_NOT_RUNNING\") reject(error)\n else resolve()\n })\n server.closeAllConnections?.()\n }),\n }\n}\n", "/// <reference types=\"node\" />\nimport { type Listening, listen, type ServeTarget } from \"@crvouga/mockingbird-adapter-node\"\nimport { createRuntime, type PharmetikaRuntime, type PharmetikaRuntimeOptions } from \"./runtime.js\"\nimport type { WebhookVariant } from \"./state.js\"\n\n/** Port `mockingbird-pharmetika serve` listens on when none is given. */\nexport const DEFAULT_PORT = 8801\n\nexport type PharmetikaServerOptions = PharmetikaRuntimeOptions & {\n /** Default `0`: the OS picks a free port. */\n port?: number\n /** Default `127.0.0.1`. */\n host?: string\n}\n\nexport type PharmetikaServer = Listening & { runtime: PharmetikaRuntime }\n\n/** Serve the Pharmetika mock over `node:http`, with auto-advance ticking every 100 ms. */\nexport const createServer = async (\n options: PharmetikaServerOptions = {},\n): Promise<PharmetikaServer> => {\n const { port, host, ...rest } = options\n const runtime = createRuntime({ tickMs: 100, ...rest })\n const listening = await listen(runtime, {\n port: port ?? 0,\n ...(host !== undefined ? { host } : {}),\n })\n return {\n ...listening,\n runtime,\n close: async () => {\n runtime.stop()\n await listening.close()\n },\n }\n}\n\nconst text = (value: string | boolean | undefined) =>\n typeof value === \"string\" ? value : undefined\n\nconst VARIANTS = [\"workflow_status\", \"status\", \"flat\"]\n\n/** How `serve` (and `serve --config`) builds the Pharmetika mock from flags. */\nexport const serveTarget: ServeTarget = {\n name: \"pharmetika\",\n defaultPort: DEFAULT_PORT,\n options: {\n \"webhook-url\": {\n type: \"string\",\n value: \"<url>\",\n description:\n \"Deliver status webhooks here (e.g. http://127.0.0.1:3000/prescriptions/webhooks/pharmetika)\",\n },\n \"webhook-secret\": {\n type: \"string\",\n value: \"<secret>\",\n description: \"Sent as x-pharmetika-webhook-secret (the app's PHARMETIKA_WEBHOOK_SECRET)\",\n },\n \"api-token\": {\n type: \"string\",\n value: \"<token>\",\n description: \"Accept only this x-pmk-authentication-token (the app's PHARMETIKA_API_TOKEN)\",\n },\n \"webhook-variant\": {\n type: \"string\",\n value: \"<workflow_status|status|flat>\",\n description: \"Which receiver field fallback the webhook body uses (default workflow_status)\",\n },\n \"auto-advance\": {\n type: \"string\",\n value: \"<ms:status,status,\u2026>\",\n description: 'Walk every new order along a path, e.g. \"2000:data_entry,shipped,completed\"',\n },\n },\n create: (values, common) => {\n const url = text(values[\"webhook-url\"])\n const secret = text(values[\"webhook-secret\"])\n const token = text(values[\"api-token\"])\n const variant = text(values[\"webhook-variant\"])\n const auto = text(values[\"auto-advance\"])\n const plan = auto ? /^(\\d+):(.+)$/.exec(auto) : null\n if (auto && !plan)\n throw new Error('--auto-advance must look like \"2000:data_entry,shipped,completed\"')\n if (variant && !VARIANTS.includes(variant)) {\n throw new Error(`--webhook-variant must be one of ${VARIANTS.join(\", \")}`)\n }\n return createRuntime({\n tickMs: 100,\n ...(url ? { webhooks: { url, ...(secret ? { secret } : {}) } } : {}),\n settings: {\n ...(token ? { tokens: [token] } : {}),\n ...(variant ? { webhookVariant: variant as WebhookVariant } : {}),\n ...(plan\n ? {\n autoAdvance: {\n afterMs: Number(plan[1]),\n path: (plan[2] as string).split(\",\").map((s) => s.trim()),\n },\n }\n : {}),\n },\n ...(common.adminKey !== undefined ? { adminKey: common.adminKey } : {}),\n ...(common.seed !== undefined ? { seed: common.seed } : {}),\n ...(common.onLog ? { onLog: common.onLog } : {}),\n })\n },\n banner: () => [\n \"auth: x-pmk-authentication-token: <token> (catalog also takes Basic or nothing)\",\n \"namespaces: x-mockingbird-namespace, /ns/<name>/\u2026, or PUT /__admin/credentials {<token>: <ns>}\",\n ],\n}\n"],
|
|
5
|
+
"mappings": ";;;;;AAAA,SAAS,gBAAgB;AACzB,SAA+B,iBAAiB;;;ACDhD,SAAS,oBAAoB;AAatB,IAAM,QAAQ,OAAO,KAAe,UAA4B,CAAA,MAAM;AAC3E,QAAM,SAAS,aAAa,OAAO,KAAK,QAAO;AAC7C,UAAM,SAAmB,CAAA;AACzB,qBAAiB,SAAS,KAAK;AAC7B,aAAO,KAAK,OAAO,KAAK,KAAK,CAAC;IAChC;AACA,UAAM,OAAO,OAAO,OAAO,MAAM;AACjC,UAAM,UAAU,OAAO,QAAO;AAC9B,UAAM,OAAO,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,OAAO;AAC9E,UAAM,OAAO,UAAU,IAAI,QAAQ,QAAQ,aAAa,QAAQ,EAAE,EAAE;AACpE,UAAM,MAAM,IAAI,OAAO;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,QAAQ,GAAG,GAAG,IAAI;AAClD,UAAM,SAAS,IA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