@photonhealth/client 0.0.0-stage → 2.0.0-rc.2
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/LICENSE +15 -0
- package/README.md +234 -2
- package/dist/analytics/lifecycleEvents.d.ts +29 -0
- package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
- package/dist/analytics/lifecycleEvents.js +72 -0
- package/dist/analytics/lifecycleEvents.js.map +1 -0
- package/dist/api/changes/applyOption.d.ts +41 -0
- package/dist/api/changes/applyOption.d.ts.map +1 -0
- package/dist/api/changes/applyOption.js +76 -0
- package/dist/api/changes/applyOption.js.map +1 -0
- package/dist/api/changes/classifyChanges.d.ts +9 -0
- package/dist/api/changes/classifyChanges.d.ts.map +1 -0
- package/dist/api/changes/classifyChanges.js +2 -0
- package/dist/api/changes/classifyChanges.js.map +1 -0
- package/dist/api/changes/index.d.ts +3 -0
- package/dist/api/changes/index.d.ts.map +1 -0
- package/dist/api/changes/index.js +3 -0
- package/dist/api/changes/index.js.map +1 -0
- package/dist/api/client.d.ts +48 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +91 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/health.d.ts +4 -0
- package/dist/api/health.d.ts.map +1 -0
- package/dist/api/health.js +6 -0
- package/dist/api/health.js.map +1 -0
- package/dist/api/index.d.ts +24 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +23 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/me.d.ts +37 -0
- package/dist/api/me.d.ts.map +1 -0
- package/dist/api/me.js +6 -0
- package/dist/api/me.js.map +1 -0
- package/dist/api/order.d.ts +33 -0
- package/dist/api/order.d.ts.map +1 -0
- package/dist/api/order.js +33 -0
- package/dist/api/order.js.map +1 -0
- package/dist/api/orders.d.ts +1047 -0
- package/dist/api/orders.d.ts.map +1 -0
- package/dist/api/orders.js +7 -0
- package/dist/api/orders.js.map +1 -0
- package/dist/api/patient.d.ts +36 -0
- package/dist/api/patient.d.ts.map +1 -0
- package/dist/api/patient.js +33 -0
- package/dist/api/patient.js.map +1 -0
- package/dist/api/prescription.d.ts +37 -0
- package/dist/api/prescription.d.ts.map +1 -0
- package/dist/api/prescription.js +39 -0
- package/dist/api/prescription.js.map +1 -0
- package/dist/api/results.d.ts +30 -0
- package/dist/api/results.d.ts.map +1 -0
- package/dist/api/results.js +26 -0
- package/dist/api/results.js.map +1 -0
- package/dist/gql/gql.d.ts +29 -0
- package/dist/gql/gql.d.ts.map +1 -0
- package/dist/gql/gql.js +15 -0
- package/dist/gql/gql.js.map +1 -0
- package/dist/gql/graphql.d.ts +18618 -0
- package/dist/gql/graphql.d.ts.map +1 -0
- package/dist/gql/graphql.js +6579 -0
- package/dist/gql/graphql.js.map +1 -0
- package/dist/gql/index.d.ts +2 -0
- package/dist/gql/index.d.ts.map +1 -0
- package/dist/gql/index.js +3 -0
- package/dist/gql/index.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/meta/version.d.ts +2 -0
- package/dist/meta/version.d.ts.map +1 -0
- package/dist/meta/version.js +2 -0
- package/dist/meta/version.js.map +1 -0
- package/dist/photon/analytics.d.ts +39 -0
- package/dist/photon/analytics.d.ts.map +1 -0
- package/dist/photon/analytics.js +91 -0
- package/dist/photon/analytics.js.map +1 -0
- package/dist/photon/auth.d.ts +52 -0
- package/dist/photon/auth.d.ts.map +1 -0
- package/dist/photon/auth.js +30 -0
- package/dist/photon/auth.js.map +1 -0
- package/dist/photon/choices.d.ts +44 -0
- package/dist/photon/choices.d.ts.map +1 -0
- package/dist/photon/choices.js +58 -0
- package/dist/photon/choices.js.map +1 -0
- package/dist/photon/context.d.ts +29 -0
- package/dist/photon/context.d.ts.map +1 -0
- package/dist/photon/context.js +2 -0
- package/dist/photon/context.js.map +1 -0
- package/dist/photon/environments.d.ts +27 -0
- package/dist/photon/environments.d.ts.map +1 -0
- package/dist/photon/environments.js +27 -0
- package/dist/photon/environments.js.map +1 -0
- package/dist/photon/errors.d.ts +26 -0
- package/dist/photon/errors.d.ts.map +1 -0
- package/dist/photon/errors.js +42 -0
- package/dist/photon/errors.js.map +1 -0
- package/dist/photon/index.d.ts +26 -0
- package/dist/photon/index.d.ts.map +1 -0
- package/dist/photon/index.js +12 -0
- package/dist/photon/index.js.map +1 -0
- package/dist/photon/inputs.d.ts +7 -0
- package/dist/photon/inputs.d.ts.map +1 -0
- package/dist/photon/inputs.js +25 -0
- package/dist/photon/inputs.js.map +1 -0
- package/dist/photon/links.d.ts +68 -0
- package/dist/photon/links.d.ts.map +1 -0
- package/dist/photon/links.js +187 -0
- package/dist/photon/links.js.map +1 -0
- package/dist/photon/live.d.ts +62 -0
- package/dist/photon/live.d.ts.map +1 -0
- package/dist/photon/live.js +107 -0
- package/dist/photon/live.js.map +1 -0
- package/dist/photon/machine.d.ts +28 -0
- package/dist/photon/machine.d.ts.map +1 -0
- package/dist/photon/machine.js +53 -0
- package/dist/photon/machine.js.map +1 -0
- package/dist/photon/map.d.ts +14 -0
- package/dist/photon/map.d.ts.map +1 -0
- package/dist/photon/map.js +311 -0
- package/dist/photon/map.js.map +1 -0
- package/dist/photon/order.d.ts +168 -0
- package/dist/photon/order.d.ts.map +1 -0
- package/dist/photon/order.js +558 -0
- package/dist/photon/order.js.map +1 -0
- package/dist/photon/orders.d.ts +5 -0
- package/dist/photon/orders.d.ts.map +1 -0
- package/dist/photon/orders.js +39 -0
- package/dist/photon/orders.js.map +1 -0
- package/dist/photon/patient.d.ts +80 -0
- package/dist/photon/patient.d.ts.map +1 -0
- package/dist/photon/patient.js +347 -0
- package/dist/photon/patient.js.map +1 -0
- package/dist/photon/photon.d.ts +188 -0
- package/dist/photon/photon.d.ts.map +1 -0
- package/dist/photon/photon.js +395 -0
- package/dist/photon/photon.js.map +1 -0
- package/dist/photon/prescription.d.ts +145 -0
- package/dist/photon/prescription.d.ts.map +1 -0
- package/dist/photon/prescription.js +418 -0
- package/dist/photon/prescription.js.map +1 -0
- package/dist/photon/session.d.ts +89 -0
- package/dist/photon/session.d.ts.map +1 -0
- package/dist/photon/session.js +352 -0
- package/dist/photon/session.js.map +1 -0
- package/dist/photon/types.d.ts +643 -0
- package/dist/photon/types.d.ts.map +1 -0
- package/dist/photon/types.js +7 -0
- package/dist/photon/types.js.map +1 -0
- package/dist/test-utils/msw.d.ts +23 -0
- package/dist/test-utils/msw.d.ts.map +1 -0
- package/dist/test-utils/msw.js +51 -0
- package/dist/test-utils/msw.js.map +1 -0
- package/dist/testing/fakeNetworkApiClient.d.ts +39 -0
- package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
- package/dist/testing/fakeNetworkApiClient.js +56 -0
- package/dist/testing/fakeNetworkApiClient.js.map +1 -0
- package/dist/testing/fixtures.d.ts +1098 -0
- package/dist/testing/fixtures.d.ts.map +1 -0
- package/dist/testing/fixtures.js +200 -0
- package/dist/testing/fixtures.js.map +1 -0
- package/dist/testing.d.ts +11 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +10 -0
- package/dist/testing.js.map +1 -0
- package/package.json +67 -4
- package/src/analytics/lifecycleEvents.test.ts +417 -0
- package/src/analytics/lifecycleEvents.ts +155 -0
- package/src/api/changes/applyOption.ts +103 -0
- package/src/api/changes/classifyChanges.ts +10 -0
- package/src/api/changes/index.ts +2 -0
- package/src/api/client.ts +149 -0
- package/src/api/health.ts +7 -0
- package/src/api/index.ts +24 -0
- package/src/api/me.ts +7 -0
- package/src/api/order.ts +64 -0
- package/src/api/orders.ts +8 -0
- package/src/api/patient.ts +67 -0
- package/src/api/prescription.ts +86 -0
- package/src/api/results.ts +45 -0
- package/src/gql/gql.ts +68 -0
- package/src/gql/graphql.ts +9027 -0
- package/src/gql/index.ts +2 -0
- package/src/index.ts +14 -0
- package/src/meta/version.test.ts +10 -0
- package/src/meta/version.ts +1 -0
- package/src/operations/fragments.graphql +497 -0
- package/src/operations/health.graphql +4 -0
- package/src/operations/me.graphql +38 -0
- package/src/operations/order.graphql +42 -0
- package/src/operations/orders.graphql +35 -0
- package/src/operations/patient.graphql +62 -0
- package/src/operations/prescription.graphql +90 -0
- package/src/photon/analytics.ts +129 -0
- package/src/photon/auth.ts +69 -0
- package/src/photon/choices.ts +79 -0
- package/src/photon/context.ts +30 -0
- package/src/photon/environments.ts +49 -0
- package/src/photon/errors.ts +56 -0
- package/src/photon/index.ts +49 -0
- package/src/photon/inputs.ts +24 -0
- package/src/photon/links.ts +197 -0
- package/src/photon/live.ts +135 -0
- package/src/photon/machine.ts +90 -0
- package/src/photon/map.ts +371 -0
- package/src/photon/order.test.ts +142 -0
- package/src/photon/order.ts +661 -0
- package/src/photon/orders.ts +42 -0
- package/src/photon/patient.ts +386 -0
- package/src/photon/photon.ts +646 -0
- package/src/photon/prescription.ts +506 -0
- package/src/photon/session.ts +454 -0
- package/src/photon/types.ts +583 -0
- package/src/test-utils/msw.ts +72 -0
- package/src/testing/fakeNetworkApiClient.ts +56 -0
- package/src/testing/fixtures.ts +233 -0
- package/src/testing.ts +25 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Links to a flow in the Photon Rx app: ids only, in the clear — never PHI or free text. A link names what to open
|
|
3
|
+
* by Photon's own ids; anything else (a patient's details, a drug's name, a sig) is synced first, and then linked by
|
|
4
|
+
* the id the server gave it.
|
|
5
|
+
* /<flow>/<id> an existing record, the flow's own (`/order/ord_…`)
|
|
6
|
+
* /patient someone to find or add
|
|
7
|
+
* /prescription?patient=pat_…&template=tmp_… a new prescription, from a template — or a drug (`med=med_…`):
|
|
8
|
+
* one of `rx`, `template`, `med`; reading, the first wins
|
|
9
|
+
* /order?patient=pat_…&rx=rx_…&template=tmp_…&med=med_… a new order: a card per prescription, template
|
|
10
|
+
* and drug (each repeats)
|
|
11
|
+
* The record's own id may come in the path or the query (`?patient=`, `?rx=`, `?order=`); the query's other ids count
|
|
12
|
+
* beside it unless they'd conflict — the highest-level id first: the order, then the patient, then the rest.
|
|
13
|
+
* and on any of them `org=org_…` (sign straight in to that organization) and, on an embed, `client=…` (the host's
|
|
14
|
+
* Auth0 client). `/<flow>/embed/…` is the same, for an iframe.
|
|
15
|
+
*/
|
|
16
|
+
import { PhotonError } from "./errors.ts";
|
|
17
|
+
|
|
18
|
+
export const FLOWS = ["order", "patient", "prescription"] as const;
|
|
19
|
+
export type Flow = (typeof FLOWS)[number];
|
|
20
|
+
export const isFlow = (value: unknown): value is Flow => FLOWS.includes(value as Flow);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* What a link opens: a flow, and the ids it's given — each record as a card takes it (`{ id }` is read; a new
|
|
24
|
+
* prescription for its drug and patient; a new order from its patient and lines).
|
|
25
|
+
*/
|
|
26
|
+
export interface FlowLink {
|
|
27
|
+
flow: Flow;
|
|
28
|
+
/** Who it's for: an existing patient. */
|
|
29
|
+
patient?: { id: string };
|
|
30
|
+
/** An existing prescription, or a new one — from a template, or for a drug: one of the three. */
|
|
31
|
+
prescription?: { id: string } | { templateId: string } | { treatment: { id: string } };
|
|
32
|
+
/**
|
|
33
|
+
* An existing order, a new one's lines — existing prescriptions, new lines from templates or drugs — or (read from
|
|
34
|
+
* a query naming the order) both.
|
|
35
|
+
*/
|
|
36
|
+
order?: {
|
|
37
|
+
id?: string;
|
|
38
|
+
prescriptions?: { add?: ({ id: string } | { templateId: string } | { treatment: { id: string } })[] };
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* How the page it opens signs in: the host's Auth0 client — an embed's only (`ph.frame()` puts the instance's in;
|
|
42
|
+
* `ph.url()` leaves it out: the app signs in with its own) — and the organization to go straight in to.
|
|
43
|
+
*/
|
|
44
|
+
auth?: { clientId?: string; organization?: string };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Photon's ids, by what they name. */
|
|
48
|
+
const PREFIX = { patient: "pat_", prescription: "rx_", order: "ord_", med: "med_", template: "tmp_", org: "org_" };
|
|
49
|
+
type Kind = keyof typeof PREFIX;
|
|
50
|
+
const isId = (kind: Kind, value: unknown): value is string =>
|
|
51
|
+
typeof value === "string" && value.startsWith(PREFIX[kind]) && /^[A-Za-z0-9_]+$/.test(value);
|
|
52
|
+
/** An Auth0 client id: public, not one of ours, but never free text. */
|
|
53
|
+
const isClientId = (value: unknown): value is string =>
|
|
54
|
+
typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The link's ids, checked: each in its place, with its prefix, and nothing else — so no patient details, drug names
|
|
58
|
+
* or sigs ever reach a URL. Refused otherwise, naming the fields (never their values).
|
|
59
|
+
*/
|
|
60
|
+
function idsOf(link: FlowLink) {
|
|
61
|
+
const wrong: string[] = [];
|
|
62
|
+
const take = (kind: Kind, value: unknown, path: string) => {
|
|
63
|
+
if (value === undefined) return undefined;
|
|
64
|
+
if (isId(kind, value)) return value;
|
|
65
|
+
wrong.push(path);
|
|
66
|
+
return undefined;
|
|
67
|
+
};
|
|
68
|
+
/** An object of only these keys: the rest are wrong. */
|
|
69
|
+
const only = (value: unknown, path: string, keys: string[]): Record<string, unknown> => {
|
|
70
|
+
if (value === undefined) return {};
|
|
71
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
72
|
+
wrong.push(path);
|
|
73
|
+
return {};
|
|
74
|
+
}
|
|
75
|
+
for (const key of Object.keys(value)) if (!keys.includes(key)) wrong.push(`${path}.${key}`);
|
|
76
|
+
return value as Record<string, unknown>;
|
|
77
|
+
};
|
|
78
|
+
const { flow } = link;
|
|
79
|
+
const rx = only(link.prescription, "prescription", ["id", "templateId", "treatment", "patient"]);
|
|
80
|
+
// One prescription: by its id, from a template, or for a drug — never two of them.
|
|
81
|
+
if ([rx.id, rx.templateId, rx.treatment].filter((v) => v !== undefined).length > 1)
|
|
82
|
+
wrong.push("prescription (one of id, templateId, treatment)");
|
|
83
|
+
const order = only(link.order, "order", ["id", "prescriptions", "patient"]);
|
|
84
|
+
// A new prescription's or order's patient may be given in its own input (`ph.order.url({ patient: { id } })`).
|
|
85
|
+
const patient = only(link.patient ?? rx.patient ?? order.patient, "patient", ["id"]);
|
|
86
|
+
const lines = only(order.prescriptions, "order.prescriptions", ["add"]).add ?? [];
|
|
87
|
+
if (!Array.isArray(lines)) wrong.push("order.prescriptions.add");
|
|
88
|
+
const ids = {
|
|
89
|
+
patient: take("patient", patient.id, "patient.id"),
|
|
90
|
+
prescription: take("prescription", rx.id, "prescription.id"),
|
|
91
|
+
template: take("template", rx.templateId, "prescription.templateId"),
|
|
92
|
+
med: take("med", only(rx.treatment, "prescription.treatment", ["id"]).id, "prescription.treatment.id"),
|
|
93
|
+
order: take("order", order.id, "order.id"),
|
|
94
|
+
rx: [] as string[],
|
|
95
|
+
templates: [] as string[],
|
|
96
|
+
meds: [] as string[],
|
|
97
|
+
org: take("org", link.auth?.organization || undefined, "auth.organization"),
|
|
98
|
+
client: undefined as string | undefined,
|
|
99
|
+
};
|
|
100
|
+
for (const [i, line] of (Array.isArray(lines) ? lines : []).entries()) {
|
|
101
|
+
const at = `order.prescriptions.add.${i}`;
|
|
102
|
+
const { id, templateId, treatment } = only(line, at, ["id", "templateId", "treatment"]);
|
|
103
|
+
if (id !== undefined) ids.rx.push(take("prescription", id, `${at}.id`) ?? "");
|
|
104
|
+
else if (templateId !== undefined) ids.templates.push(take("template", templateId, `${at}.templateId`) ?? "");
|
|
105
|
+
else if (treatment !== undefined)
|
|
106
|
+
ids.meds.push(take("med", only(treatment, `${at}.treatment`, ["id"]).id, `${at}.treatment.id`) ?? "");
|
|
107
|
+
}
|
|
108
|
+
const clientId = link.auth?.clientId || undefined;
|
|
109
|
+
if (clientId !== undefined && !isClientId(clientId)) wrong.push("auth.clientId");
|
|
110
|
+
else ids.client = clientId;
|
|
111
|
+
if (wrong.length)
|
|
112
|
+
throw new PhotonError(
|
|
113
|
+
"invalid",
|
|
114
|
+
`A link carries Photon ids only (pat_, rx_, ord_, med_, tmp_, org_) — sync first, then link by id. Not: ${wrong.join(", ")}.`,
|
|
115
|
+
);
|
|
116
|
+
return { ...ids, own: flow === "patient" ? ids.patient : flow === "prescription" ? ids.prescription : ids.order };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The app's path for a link (`/<flow>/embed/…` for an iframe): an existing record by its id in the path, a new one's
|
|
121
|
+
* ids in the query — and beside an order's id, its new lines (`/order/ord_…?rx=…&template=…`). Throws for anything
|
|
122
|
+
* that isn't an id.
|
|
123
|
+
*/
|
|
124
|
+
export function linkPath(link: FlowLink, { embed = false } = {}): string {
|
|
125
|
+
const ids = idsOf(link);
|
|
126
|
+
const params = new URLSearchParams();
|
|
127
|
+
// The highest-level id first — the order, then the patient, then the rest: a record given by id keeps its own
|
|
128
|
+
// patient (and a prescription by id is the one prescription), so nothing that would conflict goes beside it.
|
|
129
|
+
if (link.flow !== "patient" && ids.patient && !ids.own) params.set("patient", ids.patient);
|
|
130
|
+
if (link.flow === "prescription" && !ids.own) {
|
|
131
|
+
if (ids.template) params.set("template", ids.template);
|
|
132
|
+
if (ids.med) params.set("med", ids.med);
|
|
133
|
+
}
|
|
134
|
+
if (link.flow === "order") {
|
|
135
|
+
for (const rx of ids.rx) params.append("rx", rx);
|
|
136
|
+
for (const template of ids.templates) params.append("template", template);
|
|
137
|
+
for (const med of ids.meds) params.append("med", med);
|
|
138
|
+
}
|
|
139
|
+
if (ids.org) params.set("org", ids.org);
|
|
140
|
+
if (ids.client) params.set("client", ids.client);
|
|
141
|
+
const path = `/${link.flow}${embed ? "/embed" : ""}${ids.own ? `/${ids.own}` : ""}`;
|
|
142
|
+
return params.size ? `${path}?${params}` : path;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The link an app URL or path holds, or null if it isn't one: `/<flow>[/embed][/<id>]`, and the query's ids (any
|
|
147
|
+
* other parameter, such as sign-in's own, is left alone). What an id names is the server's to say: one it doesn't
|
|
148
|
+
* know opens as not found.
|
|
149
|
+
*/
|
|
150
|
+
export function parseLinkPath(href: string): { link: FlowLink; embed: boolean } | null {
|
|
151
|
+
let url: URL;
|
|
152
|
+
try {
|
|
153
|
+
url = new URL(href, "http://x");
|
|
154
|
+
} catch {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
const [flow, ...rest] = url.pathname.split("/").filter(Boolean);
|
|
158
|
+
if (!isFlow(flow)) return null;
|
|
159
|
+
const embed = rest[0] === "embed";
|
|
160
|
+
const parts = embed ? rest.slice(1) : rest;
|
|
161
|
+
if (parts.length > 1) return null;
|
|
162
|
+
const own = parts[0] ? decodeURIComponent(parts[0]) : null;
|
|
163
|
+
const q = url.searchParams;
|
|
164
|
+
const link: FlowLink = { flow };
|
|
165
|
+
// The highest-level id first — the order, then the patient, then the rest. The record's own id comes in the path
|
|
166
|
+
// or the query (`?patient=`, `?rx=`, `?order=`), and the query's other ids count beside it unless they'd conflict:
|
|
167
|
+
// a record given by id keeps its own patient, and a prescription given by id is the one prescription.
|
|
168
|
+
const ownId = own ?? q.get({ patient: "patient", prescription: "rx", order: "order" }[flow]);
|
|
169
|
+
const patient = q.get("patient");
|
|
170
|
+
if (flow === "patient" && ownId) link.patient = { id: ownId };
|
|
171
|
+
if (flow !== "patient" && patient && !ownId) link.patient = { id: patient };
|
|
172
|
+
if (flow === "prescription") {
|
|
173
|
+
// One prescription: its id, else the first of `rx`, `template` and `med` the query names.
|
|
174
|
+
const [key, value] = own
|
|
175
|
+
? ["rx", own]
|
|
176
|
+
: ([...q].find(([k, v]) => ["rx", "template", "med"].includes(k) && v) ?? []);
|
|
177
|
+
if (key === "rx") link.prescription = { id: value! };
|
|
178
|
+
if (key === "template") link.prescription = { templateId: value! };
|
|
179
|
+
if (key === "med") link.prescription = { treatment: { id: value! } };
|
|
180
|
+
}
|
|
181
|
+
if (flow === "order") {
|
|
182
|
+
// A card per id (only an order takes several): existing prescriptions, then template lines, then drugs — onto
|
|
183
|
+
// the order given by id too.
|
|
184
|
+
const add = [
|
|
185
|
+
...q.getAll("rx").map((id) => ({ id })),
|
|
186
|
+
...q.getAll("template").map((templateId) => ({ templateId })),
|
|
187
|
+
...q.getAll("med").map((id) => ({ treatment: { id } })),
|
|
188
|
+
];
|
|
189
|
+
if (ownId || add.length)
|
|
190
|
+
link.order = { ...(ownId ? { id: ownId } : {}), ...(add.length ? { prescriptions: { add } } : {}) };
|
|
191
|
+
}
|
|
192
|
+
const organization = q.get("org");
|
|
193
|
+
const clientId = q.get("client");
|
|
194
|
+
if (organization || clientId)
|
|
195
|
+
link.auth = { ...(clientId ? { clientId } : {}), ...(organization ? { organization } : {}) };
|
|
196
|
+
return { link, embed };
|
|
197
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { noChanges } from "./map.ts";
|
|
2
|
+
import { guarded, type PhotonError, toPhotonError } from "./errors.ts";
|
|
3
|
+
import type { Changes } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
/** idle · loading (a read is in flight) · saving (a write is; wins over loading) · error (the last call failed). */
|
|
6
|
+
export type LiveStatus = "idle" | "loading" | "saving" | "error";
|
|
7
|
+
|
|
8
|
+
/** What every live object's snapshot has; each kind adds its own fields (candidates, a held pick, lines, …). */
|
|
9
|
+
export interface LiveBase<S> {
|
|
10
|
+
/** The record as the server has it — null until the server has one (an object can exist before its record). */
|
|
11
|
+
readonly state: S | null;
|
|
12
|
+
readonly status: LiveStatus;
|
|
13
|
+
readonly error: PhotonError | null;
|
|
14
|
+
/**
|
|
15
|
+
* What the server said about this object on its latest call — pending choices, rejected fields,
|
|
16
|
+
* advisories — whoever made the call. Every holder of the object sees it.
|
|
17
|
+
*/
|
|
18
|
+
readonly changes: Changes;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type LiveSnapshot<S, X extends object = object> = LiveBase<S> & Readonly<X>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A record that stays current — and can exist before it does. `id` and `state` are null until the server
|
|
25
|
+
* has the record; `sync()` sends what's known and the object decides what that means (look up, find,
|
|
26
|
+
* create) from what it holds; `update()` changes the record by its id.
|
|
27
|
+
*
|
|
28
|
+
* Calls go out one at a time, in the order they were made, so a slow early response can never land on top
|
|
29
|
+
* of a newer one.
|
|
30
|
+
*
|
|
31
|
+
* obj.id / obj.state / obj.status / obj.error / obj.changes read any time
|
|
32
|
+
* obj.subscribe(fn) → unsubscribe; fn runs after every change
|
|
33
|
+
* obj.snapshot all of it — stable until something changes
|
|
34
|
+
*/
|
|
35
|
+
export abstract class LiveRecord<S extends { id: string }, X extends object = object> {
|
|
36
|
+
#snapshot: LiveSnapshot<S, X>;
|
|
37
|
+
#listeners = new Set<() => void>();
|
|
38
|
+
#queue: Promise<unknown> = Promise.resolve();
|
|
39
|
+
#pending = { loading: 0, saving: 0 };
|
|
40
|
+
|
|
41
|
+
constructor(state: S | null, extra: X, changes: Changes = noChanges) {
|
|
42
|
+
this.#snapshot = { state, status: "idle", error: null, changes, ...extra };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
get id(): string | null {
|
|
46
|
+
return this.#snapshot.state?.id ?? null;
|
|
47
|
+
}
|
|
48
|
+
get state(): S | null {
|
|
49
|
+
return this.#snapshot.state;
|
|
50
|
+
}
|
|
51
|
+
get status(): LiveStatus {
|
|
52
|
+
return this.#snapshot.status;
|
|
53
|
+
}
|
|
54
|
+
get error(): PhotonError | null {
|
|
55
|
+
return this.#snapshot.error;
|
|
56
|
+
}
|
|
57
|
+
get changes(): Changes {
|
|
58
|
+
return this.#snapshot.changes;
|
|
59
|
+
}
|
|
60
|
+
get snapshot(): LiveSnapshot<S, X> {
|
|
61
|
+
return this.#snapshot;
|
|
62
|
+
}
|
|
63
|
+
/** The record's state, for `JSON.stringify` and logs. */
|
|
64
|
+
toJSON(): S | null {
|
|
65
|
+
return this.#snapshot.state;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
69
|
+
this.#listeners.add(listener);
|
|
70
|
+
return () => this.#listeners.delete(listener);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Something this object is made of changed (e.g. an order's patient or prescription): a new snapshot. */
|
|
74
|
+
protected touch() {
|
|
75
|
+
this.#snapshot = { ...this.#snapshot };
|
|
76
|
+
for (const listener of this.#listeners) listener();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Set snapshot fields; listeners hear it only if something actually changed. */
|
|
80
|
+
protected patch(patch: Partial<LiveSnapshot<S, X>>) {
|
|
81
|
+
const current = this.#snapshot as Record<string, unknown>;
|
|
82
|
+
if (Object.entries(patch).every(([k, v]) => current[k] === v)) return;
|
|
83
|
+
const hadId = this.id;
|
|
84
|
+
this.#snapshot = { ...this.#snapshot, ...patch };
|
|
85
|
+
if (!hadId && this.id) this.onRecord();
|
|
86
|
+
for (const listener of this.#listeners) listener();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** This object's own call came back: the server's copy (if it sent one) and what it said. */
|
|
90
|
+
protected settle(state: S | null, changes: Changes) {
|
|
91
|
+
this.patch((state ? { state, changes } : { changes }) as Partial<LiveSnapshot<S, X>>);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The record just came to exist (its first id). The instance registers it here. */
|
|
95
|
+
protected onRecord(): void {}
|
|
96
|
+
|
|
97
|
+
get busy(): boolean {
|
|
98
|
+
return this.#pending.loading + this.#pending.saving > 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A copy that arrived some other way — inside an order's response, or from the call that found this
|
|
103
|
+
* record. Taken only while this object has nothing in flight (its own pending call's answer is newer),
|
|
104
|
+
* and only for its own record. Internal: photon() calls it; hosts don't need to.
|
|
105
|
+
*/
|
|
106
|
+
adopt(state: S, changes?: Changes) {
|
|
107
|
+
if (this.busy || state.id !== this.id) return;
|
|
108
|
+
this.patch((changes ? { state, changes } : { state }) as Partial<LiveSnapshot<S, X>>);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#busy(): LiveStatus {
|
|
112
|
+
return this.#pending.saving ? "saving" : this.#pending.loading ? "loading" : "idle";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Queue a call behind this object's others; status follows it; failures become PhotonErrors. */
|
|
116
|
+
protected run<T>(kind: "loading" | "saving", work: () => Promise<T>): Promise<T> {
|
|
117
|
+
this.#pending[kind]++;
|
|
118
|
+
this.patch({ status: this.#busy(), error: null } as Partial<LiveSnapshot<S, X>>);
|
|
119
|
+
const result = this.#queue.then(() => guarded(work));
|
|
120
|
+
this.#queue = result.catch(() => {});
|
|
121
|
+
return result.then(
|
|
122
|
+
(value) => {
|
|
123
|
+
this.#pending[kind]--;
|
|
124
|
+
this.patch({ status: this.#busy(), error: null } as Partial<LiveSnapshot<S, X>>); // a newer call worked
|
|
125
|
+
return value;
|
|
126
|
+
},
|
|
127
|
+
(e: unknown) => {
|
|
128
|
+
const error = toPhotonError(e);
|
|
129
|
+
this.#pending[kind]--;
|
|
130
|
+
this.patch({ status: "error", error } as Partial<LiveSnapshot<S, X>>);
|
|
131
|
+
throw error;
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { PhotonError } from "./errors.ts";
|
|
2
|
+
import { claimsOf } from "./session.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A backend's own sign-in: OAuth 2 client credentials against the environment's Auth0 tenant, with the M2M client
|
|
6
|
+
* Photon made for the organization (`client_metadata.org_id`, which Auth0 puts on the token as its org claim).
|
|
7
|
+
* Servers only — `photon()` refuses a secret in a browser before it gets here.
|
|
8
|
+
*
|
|
9
|
+
* token() the access token: one from Auth0, kept until shortly before it expires; concurrent calls share one
|
|
10
|
+
* request.
|
|
11
|
+
* forget() drop it, so the next call gets a new one (network-api refused it: a 401).
|
|
12
|
+
*
|
|
13
|
+
* The token's organization must be `organizationId`: links name that organization, so calls made in another would
|
|
14
|
+
* go somewhere the links don't.
|
|
15
|
+
*/
|
|
16
|
+
export interface MachineConfig {
|
|
17
|
+
/** The Auth0 tenant (`auth.<env>.health`). */
|
|
18
|
+
domain: string;
|
|
19
|
+
/** The token audience network-api accepts. */
|
|
20
|
+
audience: string;
|
|
21
|
+
clientId: string;
|
|
22
|
+
clientSecret: string;
|
|
23
|
+
organizationId: string;
|
|
24
|
+
fetch?: typeof fetch;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface MachineCredentials {
|
|
28
|
+
token(): Promise<string>;
|
|
29
|
+
forget(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Renew this long before the token expires. */
|
|
33
|
+
const EARLY_MS = 60_000;
|
|
34
|
+
/** Where Photon's Auth0 action puts the organization on a machine token. */
|
|
35
|
+
const ORG_CLAIM = "http://photon.health/org_id";
|
|
36
|
+
|
|
37
|
+
export function machineCredentials(config: MachineConfig): MachineCredentials {
|
|
38
|
+
let held: { token: string; expiresAt: number } | null = null;
|
|
39
|
+
let pending: Promise<string> | null = null;
|
|
40
|
+
|
|
41
|
+
const request = async (): Promise<string> => {
|
|
42
|
+
const response = await (config.fetch ?? fetch)(`https://${config.domain}/oauth/token`, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/json" },
|
|
45
|
+
body: JSON.stringify({
|
|
46
|
+
grant_type: "client_credentials",
|
|
47
|
+
client_id: config.clientId,
|
|
48
|
+
client_secret: config.clientSecret,
|
|
49
|
+
audience: config.audience,
|
|
50
|
+
}),
|
|
51
|
+
}).catch((e: unknown) => {
|
|
52
|
+
throw new PhotonError("network", "Couldn't reach Photon's sign-in for a machine token.", true, { cause: e });
|
|
53
|
+
});
|
|
54
|
+
const json = (await response.json().catch(() => ({}))) as {
|
|
55
|
+
access_token?: string;
|
|
56
|
+
expires_in?: number;
|
|
57
|
+
error?: string;
|
|
58
|
+
error_description?: string;
|
|
59
|
+
};
|
|
60
|
+
if (!response.ok || !json.access_token) {
|
|
61
|
+
const reason = json.error_description ?? json.error ?? `Auth0 responded ${response.status}`;
|
|
62
|
+
if (response.status >= 500) throw new PhotonError("network", reason, true);
|
|
63
|
+
throw new PhotonError("unauthorized", `The client credentials were refused: ${reason}`);
|
|
64
|
+
}
|
|
65
|
+
const claims = claimsOf(json.access_token);
|
|
66
|
+
const organization = claims[ORG_CLAIM] ?? claims.org_id;
|
|
67
|
+
if (organization !== config.organizationId) {
|
|
68
|
+
throw new PhotonError(
|
|
69
|
+
"unauthorized",
|
|
70
|
+
`This client's tokens are for ${typeof organization === "string" ? organization : "no organization"}, ` +
|
|
71
|
+
`not ${config.organizationId}: use the client Photon made for that organization.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
held = { token: json.access_token, expiresAt: Date.now() + (json.expires_in ?? 0) * 1000 };
|
|
75
|
+
return json.access_token;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
token() {
|
|
80
|
+
if (held && held.expiresAt - EARLY_MS > Date.now()) return Promise.resolve(held.token);
|
|
81
|
+
pending ??= request().finally(() => {
|
|
82
|
+
pending = null;
|
|
83
|
+
});
|
|
84
|
+
return pending;
|
|
85
|
+
},
|
|
86
|
+
forget() {
|
|
87
|
+
held = null;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|