@photonhealth/client 0.0.0-stage → 2.0.0-rc.1

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.
Files changed (178) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +89 -2
  3. package/dist/api/changes/applyOption.d.ts +41 -0
  4. package/dist/api/changes/applyOption.d.ts.map +1 -0
  5. package/dist/api/changes/applyOption.js +76 -0
  6. package/dist/api/changes/applyOption.js.map +1 -0
  7. package/dist/api/changes/classifyChanges.d.ts +9 -0
  8. package/dist/api/changes/classifyChanges.d.ts.map +1 -0
  9. package/dist/api/changes/classifyChanges.js +2 -0
  10. package/dist/api/changes/classifyChanges.js.map +1 -0
  11. package/dist/api/changes/index.d.ts +3 -0
  12. package/dist/api/changes/index.d.ts.map +1 -0
  13. package/dist/api/changes/index.js +3 -0
  14. package/dist/api/changes/index.js.map +1 -0
  15. package/dist/api/client.d.ts +43 -0
  16. package/dist/api/client.d.ts.map +1 -0
  17. package/dist/api/client.js +77 -0
  18. package/dist/api/client.js.map +1 -0
  19. package/dist/api/health.d.ts +4 -0
  20. package/dist/api/health.d.ts.map +1 -0
  21. package/dist/api/health.js +6 -0
  22. package/dist/api/health.js.map +1 -0
  23. package/dist/api/index.d.ts +22 -0
  24. package/dist/api/index.d.ts.map +1 -0
  25. package/dist/api/index.js +21 -0
  26. package/dist/api/index.js.map +1 -0
  27. package/dist/api/order.d.ts +33 -0
  28. package/dist/api/order.d.ts.map +1 -0
  29. package/dist/api/order.js +33 -0
  30. package/dist/api/order.js.map +1 -0
  31. package/dist/api/patient.d.ts +33 -0
  32. package/dist/api/patient.d.ts.map +1 -0
  33. package/dist/api/patient.js +33 -0
  34. package/dist/api/patient.js.map +1 -0
  35. package/dist/api/prescription.d.ts +31 -0
  36. package/dist/api/prescription.d.ts.map +1 -0
  37. package/dist/api/prescription.js +30 -0
  38. package/dist/api/prescription.js.map +1 -0
  39. package/dist/api/results.d.ts +30 -0
  40. package/dist/api/results.d.ts.map +1 -0
  41. package/dist/api/results.js +26 -0
  42. package/dist/api/results.js.map +1 -0
  43. package/dist/gql/gql.d.ts +21 -0
  44. package/dist/gql/gql.d.ts.map +1 -0
  45. package/dist/gql/gql.js +13 -0
  46. package/dist/gql/gql.js.map +1 -0
  47. package/dist/gql/graphql.d.ts +9674 -0
  48. package/dist/gql/graphql.d.ts.map +1 -0
  49. package/dist/gql/graphql.js +4030 -0
  50. package/dist/gql/graphql.js.map +1 -0
  51. package/dist/gql/index.d.ts +2 -0
  52. package/dist/gql/index.d.ts.map +1 -0
  53. package/dist/gql/index.js +3 -0
  54. package/dist/gql/index.js.map +1 -0
  55. package/dist/index.d.ts +15 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +15 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/photon/auth.d.ts +48 -0
  60. package/dist/photon/auth.d.ts.map +1 -0
  61. package/dist/photon/auth.js +34 -0
  62. package/dist/photon/auth.js.map +1 -0
  63. package/dist/photon/choices.d.ts +44 -0
  64. package/dist/photon/choices.d.ts.map +1 -0
  65. package/dist/photon/choices.js +58 -0
  66. package/dist/photon/choices.js.map +1 -0
  67. package/dist/photon/context.d.ts +29 -0
  68. package/dist/photon/context.d.ts.map +1 -0
  69. package/dist/photon/context.js +2 -0
  70. package/dist/photon/context.js.map +1 -0
  71. package/dist/photon/environments.d.ts +26 -0
  72. package/dist/photon/environments.d.ts.map +1 -0
  73. package/dist/photon/environments.js +26 -0
  74. package/dist/photon/environments.js.map +1 -0
  75. package/dist/photon/errors.d.ts +26 -0
  76. package/dist/photon/errors.d.ts.map +1 -0
  77. package/dist/photon/errors.js +42 -0
  78. package/dist/photon/errors.js.map +1 -0
  79. package/dist/photon/index.d.ts +23 -0
  80. package/dist/photon/index.d.ts.map +1 -0
  81. package/dist/photon/index.js +11 -0
  82. package/dist/photon/index.js.map +1 -0
  83. package/dist/photon/inputs.d.ts +7 -0
  84. package/dist/photon/inputs.d.ts.map +1 -0
  85. package/dist/photon/inputs.js +25 -0
  86. package/dist/photon/inputs.js.map +1 -0
  87. package/dist/photon/links.d.ts +68 -0
  88. package/dist/photon/links.d.ts.map +1 -0
  89. package/dist/photon/links.js +187 -0
  90. package/dist/photon/links.js.map +1 -0
  91. package/dist/photon/live.d.ts +62 -0
  92. package/dist/photon/live.d.ts.map +1 -0
  93. package/dist/photon/live.js +107 -0
  94. package/dist/photon/live.js.map +1 -0
  95. package/dist/photon/map.d.ts +10 -0
  96. package/dist/photon/map.d.ts.map +1 -0
  97. package/dist/photon/map.js +211 -0
  98. package/dist/photon/map.js.map +1 -0
  99. package/dist/photon/order.d.ts +148 -0
  100. package/dist/photon/order.d.ts.map +1 -0
  101. package/dist/photon/order.js +491 -0
  102. package/dist/photon/order.js.map +1 -0
  103. package/dist/photon/patient.d.ts +78 -0
  104. package/dist/photon/patient.d.ts.map +1 -0
  105. package/dist/photon/patient.js +316 -0
  106. package/dist/photon/patient.js.map +1 -0
  107. package/dist/photon/photon.d.ts +150 -0
  108. package/dist/photon/photon.d.ts.map +1 -0
  109. package/dist/photon/photon.js +315 -0
  110. package/dist/photon/photon.js.map +1 -0
  111. package/dist/photon/prescription.d.ts +132 -0
  112. package/dist/photon/prescription.d.ts.map +1 -0
  113. package/dist/photon/prescription.js +381 -0
  114. package/dist/photon/prescription.js.map +1 -0
  115. package/dist/photon/session.d.ts +84 -0
  116. package/dist/photon/session.d.ts.map +1 -0
  117. package/dist/photon/session.js +350 -0
  118. package/dist/photon/session.js.map +1 -0
  119. package/dist/photon/types.d.ts +411 -0
  120. package/dist/photon/types.d.ts.map +1 -0
  121. package/dist/photon/types.js +7 -0
  122. package/dist/photon/types.js.map +1 -0
  123. package/dist/test-utils/msw.d.ts +23 -0
  124. package/dist/test-utils/msw.d.ts.map +1 -0
  125. package/dist/test-utils/msw.js +51 -0
  126. package/dist/test-utils/msw.js.map +1 -0
  127. package/dist/testing/fixtures.d.ts +51 -0
  128. package/dist/testing/fixtures.d.ts.map +1 -0
  129. package/dist/testing/fixtures.js +166 -0
  130. package/dist/testing/fixtures.js.map +1 -0
  131. package/dist/testing/scriptedClient.d.ts +38 -0
  132. package/dist/testing/scriptedClient.d.ts.map +1 -0
  133. package/dist/testing/scriptedClient.js +52 -0
  134. package/dist/testing/scriptedClient.js.map +1 -0
  135. package/dist/testing.d.ts +11 -0
  136. package/dist/testing.d.ts.map +1 -0
  137. package/dist/testing.js +10 -0
  138. package/dist/testing.js.map +1 -0
  139. package/package.json +67 -4
  140. package/src/api/changes/applyOption.ts +103 -0
  141. package/src/api/changes/classifyChanges.ts +10 -0
  142. package/src/api/changes/index.ts +2 -0
  143. package/src/api/client.ts +124 -0
  144. package/src/api/health.ts +7 -0
  145. package/src/api/index.ts +22 -0
  146. package/src/api/order.ts +64 -0
  147. package/src/api/patient.ts +58 -0
  148. package/src/api/prescription.ts +68 -0
  149. package/src/api/results.ts +45 -0
  150. package/src/gql/gql.ts +56 -0
  151. package/src/gql/graphql.ts +5344 -0
  152. package/src/gql/index.ts +2 -0
  153. package/src/index.ts +14 -0
  154. package/src/operations/fragments.graphql +351 -0
  155. package/src/operations/health.graphql +4 -0
  156. package/src/operations/order.graphql +42 -0
  157. package/src/operations/patient.graphql +36 -0
  158. package/src/operations/prescription.graphql +70 -0
  159. package/src/photon/auth.ts +70 -0
  160. package/src/photon/choices.ts +79 -0
  161. package/src/photon/context.ts +30 -0
  162. package/src/photon/environments.ts +47 -0
  163. package/src/photon/errors.ts +56 -0
  164. package/src/photon/index.ts +35 -0
  165. package/src/photon/inputs.ts +24 -0
  166. package/src/photon/links.ts +197 -0
  167. package/src/photon/live.ts +135 -0
  168. package/src/photon/map.ts +255 -0
  169. package/src/photon/order.ts +581 -0
  170. package/src/photon/patient.ts +346 -0
  171. package/src/photon/photon.ts +513 -0
  172. package/src/photon/prescription.ts +447 -0
  173. package/src/photon/session.ts +445 -0
  174. package/src/photon/types.ts +329 -0
  175. package/src/test-utils/msw.ts +61 -0
  176. package/src/testing/fixtures.ts +191 -0
  177. package/src/testing/scriptedClient.ts +52 -0
  178. package/src/testing.ts +22 -0
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Photon environments, in code. Every URL is inferred from the environment name —
3
+ * `<service>.<env>.health` — so there's nothing to configure per deploy, in a browser or on a server.
4
+ * Mirrors Photon-Health/mcp src/config.ts. tau is locally running services; it signs in through
5
+ * boson's Auth0 tenant.
6
+ */
7
+
8
+ export const PHOTON_ENVIRONMENTS = ["boson", "tau", "neutron", "photon"] as const;
9
+ export type PhotonEnvironment = (typeof PHOTON_ENVIRONMENTS)[number];
10
+
11
+ export interface EnvironmentUrls {
12
+ name: PhotonEnvironment;
13
+ /** network-api's GraphQL endpoint (it allows cross-origin calls from browsers). */
14
+ networkApiUrl: string;
15
+ /** The Auth0 tenant that issues tokens for it. */
16
+ auth0Domain: string;
17
+ /** The token audience network-api accepts. */
18
+ auth0Audience: string;
19
+ /**
20
+ * The Photon Rx app: where `ph.url()` / `ph.frame()` links go unless the instance says (`photon({ appUrl })`) —
21
+ * `rx.new` in production, `rx.<env>.health` otherwise; tau's is the local dev server (`npm run dev:tau`).
22
+ */
23
+ appUrl: string;
24
+ }
25
+
26
+ /** Environments without their own Auth0 tenant. Local services (tau) sign in through boson's. */
27
+ const AUTH_ENVIRONMENT: Partial<Record<PhotonEnvironment, PhotonEnvironment>> = { tau: "boson" };
28
+
29
+ /** The app's own domain, where it isn't `rx.<env>.health`. */
30
+ const APP_URL: Partial<Record<PhotonEnvironment, string>> = { photon: "https://rx.new", tau: "http://localhost:3000" };
31
+
32
+ /** Local services are plain http (fine from http://localhost); every hosted environment is https. */
33
+ const scheme = (name: PhotonEnvironment) => (name === "tau" ? "http" : "https");
34
+
35
+ /** The environment whose Auth0 tenant `name` signs in through (itself, except tau → boson). */
36
+ export const authEnvironmentOf = (name: PhotonEnvironment): PhotonEnvironment => AUTH_ENVIRONMENT[name] ?? name;
37
+
38
+ export function environmentUrls(name: PhotonEnvironment): EnvironmentUrls {
39
+ const authEnv = authEnvironmentOf(name);
40
+ return {
41
+ name,
42
+ networkApiUrl: `${scheme(name)}://network.${name}.health/graphql`,
43
+ auth0Domain: `auth.${authEnv}.health`,
44
+ auth0Audience: `https://api.${authEnv}.health`,
45
+ appUrl: APP_URL[name] ?? `https://rx.${name}.health`,
46
+ };
47
+ }
@@ -0,0 +1,56 @@
1
+ import { NetworkTransportError, OperationFailure } from "../api/index.ts";
2
+
3
+ /**
4
+ * The one thing core throws. Anything the server *answers* about the data is a result (a null record,
5
+ * candidates, unapplied changes); a PhotonError is a failure that sending different data can't fix.
6
+ *
7
+ * network fetch failed or timed out — retryable
8
+ * unauthorized bad or expired token, or a permission the caller lacks
9
+ * upstream a network-api dependency failed — `retryable` says whether to try again
10
+ * invalid the server rejected the request's shape (a bug in the caller or in core)
11
+ * refused a live object's rule said no (sign a changed prescription, submit with an unsigned one,
12
+ * update a signed one) — not retryable as is
13
+ */
14
+ export type PhotonErrorKind = "network" | "unauthorized" | "upstream" | "invalid" | "refused";
15
+
16
+ export class PhotonError extends Error {
17
+ override name = "PhotonError";
18
+ constructor(
19
+ readonly kind: PhotonErrorKind,
20
+ message: string,
21
+ readonly retryable = false,
22
+ options?: { cause?: unknown },
23
+ ) {
24
+ super(message, options);
25
+ }
26
+ }
27
+
28
+ /** Any failure from the transport or network-api, as a PhotonError. */
29
+ export function toPhotonError(e: unknown): PhotonError {
30
+ if (e instanceof PhotonError) return e;
31
+ if (e instanceof OperationFailure) {
32
+ return e.type === "UNAUTHORIZED"
33
+ ? new PhotonError("unauthorized", e.message, false, { cause: e })
34
+ : new PhotonError("upstream", e.message, e.retryable, { cause: e });
35
+ }
36
+ if (e instanceof NetworkTransportError) {
37
+ if (e.status === 401 || e.status === 403 || e.code === "UNAUTHENTICATED" || e.code === "FORBIDDEN")
38
+ return new PhotonError("unauthorized", e.message, false, { cause: e });
39
+ if (e.status !== undefined && e.status >= 500) return new PhotonError("network", e.message, true, { cause: e });
40
+ return new PhotonError("invalid", e.message, false, { cause: e });
41
+ }
42
+ // fetch() itself failed (offline, DNS, CORS, aborted) — or the token source threw.
43
+ const message = e instanceof Error ? e.message : String(e);
44
+ return new PhotonError("network", message, true, { cause: e });
45
+ }
46
+
47
+ /** Run a call, turning any failure into a PhotonError. */
48
+ export async function guarded<T>(work: () => Promise<T>): Promise<T> {
49
+ try {
50
+ return await work();
51
+ } catch (e) {
52
+ throw toPhotonError(e);
53
+ }
54
+ }
55
+
56
+ export const refuse = (message: string) => new PhotonError("refused", message);
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The public API: `photon()` and what it returns. network-api's three upsert mutations, one call each,
3
+ * returning live objects with the workflow rules inside — objects that can exist before their record. See
4
+ * docs/CORE.md.
5
+ */
6
+ export { photon, Patient, Prescription, Order } from "./photon.ts";
7
+ export type {
8
+ Photon,
9
+ PhotonOptions,
10
+ Calls,
11
+ LinkTo,
12
+ PatientResult,
13
+ PrescriptionResult,
14
+ OrderResult,
15
+ LiveObject,
16
+ AnySnapshot,
17
+ PatientSnapshot,
18
+ PrescriptionSnapshot,
19
+ OrderSnapshot,
20
+ } from "./photon.ts";
21
+ export type { PatientExtra } from "./patient.ts";
22
+ export type { PrescriptionExtra, PrescriptionUpdate } from "./prescription.ts";
23
+ export type { OrderExtra, OrderUpdate } from "./order.ts";
24
+ export type { LiveStatus, LiveSnapshot, LiveBase } from "./live.ts";
25
+ export type { PhotonAuth } from "./auth.ts";
26
+ export { Session } from "./session.ts";
27
+ export type { SessionStatus, SessionSnapshot, SessionUser, SessionConfig } from "./session.ts";
28
+ export { PhotonError } from "./errors.ts";
29
+ export type { Flow, FlowLink } from "./links.ts";
30
+ export type { PhotonErrorKind } from "./errors.ts";
31
+ export { PHOTON_ENVIRONMENTS, environmentUrls, authEnvironmentOf } from "./environments.ts";
32
+ export type { PhotonEnvironment, EnvironmentUrls } from "./environments.ts";
33
+ export { classify, choicesIn, declaredChoice, withChoice, asksForAddress } from "./choices.ts";
34
+ export type { ClassifiedChanges } from "./choices.ts";
35
+ export type * from "./types.ts";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * An input without its empty values — "" (and whitespace), null, undefined, {} and [] — so an empty field
3
+ * reads as "not known" rather than as a value to send. For syncs before a record exists (lookups, finding);
4
+ * once it does, "" can mean "clear this", so updates send what they're given.
5
+ */
6
+ export function filled<T>(value: T): T {
7
+ return (prune(value) ?? {}) as T;
8
+ }
9
+
10
+ function prune(value: unknown): unknown {
11
+ if (Array.isArray(value)) {
12
+ const items = value.map(prune).filter((v) => v !== undefined);
13
+ return items.length ? items : undefined;
14
+ }
15
+ if (value && typeof value === "object") {
16
+ const entries = Object.entries(value).flatMap(([k, v]) => {
17
+ const kept = prune(v);
18
+ return kept === undefined ? [] : [[k, kept] as const];
19
+ });
20
+ return entries.length ? Object.fromEntries(entries) : undefined;
21
+ }
22
+ if (typeof value === "string" && !value.trim()) return undefined;
23
+ return value ?? undefined;
24
+ }
@@ -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
+ }