@photonhealth/client 2.0.0-rc.1 → 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.
Files changed (152) hide show
  1. package/README.md +150 -5
  2. package/dist/analytics/lifecycleEvents.d.ts +29 -0
  3. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  4. package/dist/analytics/lifecycleEvents.js +72 -0
  5. package/dist/analytics/lifecycleEvents.js.map +1 -0
  6. package/dist/api/client.d.ts +6 -1
  7. package/dist/api/client.d.ts.map +1 -1
  8. package/dist/api/client.js +47 -33
  9. package/dist/api/client.js.map +1 -1
  10. package/dist/api/index.d.ts +2 -0
  11. package/dist/api/index.d.ts.map +1 -1
  12. package/dist/api/index.js +2 -0
  13. package/dist/api/index.js.map +1 -1
  14. package/dist/api/me.d.ts +37 -0
  15. package/dist/api/me.d.ts.map +1 -0
  16. package/dist/api/me.js +6 -0
  17. package/dist/api/me.js.map +1 -0
  18. package/dist/api/orders.d.ts +1047 -0
  19. package/dist/api/orders.d.ts.map +1 -0
  20. package/dist/api/orders.js +7 -0
  21. package/dist/api/orders.js.map +1 -0
  22. package/dist/api/patient.d.ts +5 -2
  23. package/dist/api/patient.d.ts.map +1 -1
  24. package/dist/api/patient.js +1 -1
  25. package/dist/api/patient.js.map +1 -1
  26. package/dist/api/prescription.d.ts +7 -1
  27. package/dist/api/prescription.d.ts.map +1 -1
  28. package/dist/api/prescription.js +10 -1
  29. package/dist/api/prescription.js.map +1 -1
  30. package/dist/gql/gql.d.ts +11 -3
  31. package/dist/gql/gql.d.ts.map +1 -1
  32. package/dist/gql/gql.js +5 -3
  33. package/dist/gql/gql.js.map +1 -1
  34. package/dist/gql/graphql.d.ts +10507 -1563
  35. package/dist/gql/graphql.d.ts.map +1 -1
  36. package/dist/gql/graphql.js +2984 -435
  37. package/dist/gql/graphql.js.map +1 -1
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/meta/version.d.ts +2 -0
  41. package/dist/meta/version.d.ts.map +1 -0
  42. package/dist/meta/version.js +2 -0
  43. package/dist/meta/version.js.map +1 -0
  44. package/dist/photon/analytics.d.ts +39 -0
  45. package/dist/photon/analytics.d.ts.map +1 -0
  46. package/dist/photon/analytics.js +91 -0
  47. package/dist/photon/analytics.js.map +1 -0
  48. package/dist/photon/auth.d.ts +9 -5
  49. package/dist/photon/auth.d.ts.map +1 -1
  50. package/dist/photon/auth.js +2 -6
  51. package/dist/photon/auth.js.map +1 -1
  52. package/dist/photon/choices.d.ts +1 -1
  53. package/dist/photon/choices.js +2 -2
  54. package/dist/photon/choices.js.map +1 -1
  55. package/dist/photon/environments.d.ts +2 -1
  56. package/dist/photon/environments.d.ts.map +1 -1
  57. package/dist/photon/environments.js +2 -1
  58. package/dist/photon/environments.js.map +1 -1
  59. package/dist/photon/index.d.ts +6 -3
  60. package/dist/photon/index.d.ts.map +1 -1
  61. package/dist/photon/index.js +2 -1
  62. package/dist/photon/index.js.map +1 -1
  63. package/dist/photon/machine.d.ts +28 -0
  64. package/dist/photon/machine.d.ts.map +1 -0
  65. package/dist/photon/machine.js +53 -0
  66. package/dist/photon/machine.js.map +1 -0
  67. package/dist/photon/map.d.ts +6 -2
  68. package/dist/photon/map.d.ts.map +1 -1
  69. package/dist/photon/map.js +133 -33
  70. package/dist/photon/map.js.map +1 -1
  71. package/dist/photon/order.d.ts +21 -1
  72. package/dist/photon/order.d.ts.map +1 -1
  73. package/dist/photon/order.js +79 -12
  74. package/dist/photon/order.js.map +1 -1
  75. package/dist/photon/orders.d.ts +5 -0
  76. package/dist/photon/orders.d.ts.map +1 -0
  77. package/dist/photon/orders.js +39 -0
  78. package/dist/photon/orders.js.map +1 -0
  79. package/dist/photon/patient.d.ts +8 -6
  80. package/dist/photon/patient.d.ts.map +1 -1
  81. package/dist/photon/patient.js +61 -30
  82. package/dist/photon/patient.js.map +1 -1
  83. package/dist/photon/photon.d.ts +39 -1
  84. package/dist/photon/photon.d.ts.map +1 -1
  85. package/dist/photon/photon.js +85 -5
  86. package/dist/photon/photon.js.map +1 -1
  87. package/dist/photon/prescription.d.ts +17 -4
  88. package/dist/photon/prescription.d.ts.map +1 -1
  89. package/dist/photon/prescription.js +48 -11
  90. package/dist/photon/prescription.js.map +1 -1
  91. package/dist/photon/session.d.ts +15 -10
  92. package/dist/photon/session.d.ts.map +1 -1
  93. package/dist/photon/session.js +5 -3
  94. package/dist/photon/session.js.map +1 -1
  95. package/dist/photon/types.d.ts +278 -46
  96. package/dist/photon/types.d.ts.map +1 -1
  97. package/dist/test-utils/msw.d.ts +2 -2
  98. package/dist/test-utils/msw.d.ts.map +1 -1
  99. package/dist/test-utils/msw.js +5 -5
  100. package/dist/test-utils/msw.js.map +1 -1
  101. package/dist/testing/{scriptedClient.d.ts → fakeNetworkApiClient.d.ts} +5 -4
  102. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  103. package/dist/testing/{scriptedClient.js → fakeNetworkApiClient.js} +8 -4
  104. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  105. package/dist/testing/fixtures.d.ts +1047 -0
  106. package/dist/testing/fixtures.d.ts.map +1 -1
  107. package/dist/testing/fixtures.js +47 -13
  108. package/dist/testing/fixtures.js.map +1 -1
  109. package/dist/testing.d.ts +4 -4
  110. package/dist/testing.d.ts.map +1 -1
  111. package/dist/testing.js +4 -4
  112. package/dist/testing.js.map +1 -1
  113. package/package.json +2 -2
  114. package/src/analytics/lifecycleEvents.test.ts +417 -0
  115. package/src/analytics/lifecycleEvents.ts +155 -0
  116. package/src/api/client.ts +71 -46
  117. package/src/api/index.ts +2 -0
  118. package/src/api/me.ts +7 -0
  119. package/src/api/orders.ts +8 -0
  120. package/src/api/patient.ts +11 -2
  121. package/src/api/prescription.ts +18 -0
  122. package/src/gql/gql.ts +21 -9
  123. package/src/gql/graphql.ts +4280 -597
  124. package/src/index.ts +1 -1
  125. package/src/meta/version.test.ts +10 -0
  126. package/src/meta/version.ts +1 -0
  127. package/src/operations/fragments.graphql +166 -20
  128. package/src/operations/me.graphql +38 -0
  129. package/src/operations/orders.graphql +35 -0
  130. package/src/operations/patient.graphql +29 -3
  131. package/src/operations/prescription.graphql +20 -0
  132. package/src/photon/analytics.ts +129 -0
  133. package/src/photon/auth.ts +9 -10
  134. package/src/photon/choices.ts +2 -2
  135. package/src/photon/environments.ts +3 -1
  136. package/src/photon/index.ts +16 -2
  137. package/src/photon/machine.ts +90 -0
  138. package/src/photon/map.ts +151 -35
  139. package/src/photon/order.test.ts +142 -0
  140. package/src/photon/order.ts +92 -12
  141. package/src/photon/orders.ts +42 -0
  142. package/src/photon/patient.ts +73 -33
  143. package/src/photon/photon.ts +139 -6
  144. package/src/photon/prescription.ts +71 -12
  145. package/src/photon/session.ts +18 -9
  146. package/src/photon/types.ts +280 -26
  147. package/src/test-utils/msw.ts +16 -5
  148. package/src/testing/{scriptedClient.ts → fakeNetworkApiClient.ts} +8 -4
  149. package/src/testing/fixtures.ts +55 -13
  150. package/src/testing.ts +6 -3
  151. package/dist/testing/scriptedClient.d.ts.map +0 -1
  152. package/dist/testing/scriptedClient.js.map +0 -1
@@ -1,19 +1,32 @@
1
- import { createNetworkClient, getOrder, getPatient, getPrescription, ping, type NetworkClient } from "../api/index.ts";
2
- import { linkAuthOf, refuseSecretInBrowser, signsIn, tokenSource, type LinkAuth, type PhotonAuth } from "./auth.ts";
1
+ import {
2
+ createNetworkClient,
3
+ getOrder,
4
+ getPatient,
5
+ getPrescription,
6
+ me,
7
+ ping,
8
+ type NetworkClient,
9
+ } from "../api/index.ts";
10
+ import { isMachine, linkAuthOf, refuseSecretInBrowser, signsIn, type LinkAuth, type PhotonAuth } from "./auth.ts";
11
+ import { machineCredentials, type MachineCredentials } from "./machine.ts";
3
12
  import { sessionFor, type Session } from "./session.ts";
4
13
  import type { Context } from "./context.ts";
14
+ import { analyticsFor, type Analytics, type AnalyticsTarget } from "./analytics.ts";
5
15
  import { environmentUrls, type EnvironmentUrls, type PhotonEnvironment } from "./environments.ts";
6
16
  import { linkPath, parseLinkPath, type FlowLink } from "./links.ts";
7
17
  import { guarded, PhotonError, refuse } from "./errors.ts";
8
18
  import { noChanges, toChanges, toPatient, toPrescription } from "./map.ts";
9
19
  import { adoptOrder, Order } from "./order.ts";
10
20
  import { Patient } from "./patient.ts";
21
+ import { readOrders } from "./orders.ts";
11
22
  import { Prescription } from "./prescription.ts";
12
23
  import type {
13
24
  Changes,
14
25
  OrderCandidate,
15
26
  OrderInput,
16
27
  OrderRecord,
28
+ OrdersInput,
29
+ OrdersResult,
17
30
  PatientCandidate,
18
31
  PatientInput,
19
32
  PatientRecord,
@@ -84,6 +97,11 @@ export interface PhotonOptions {
84
97
  * `organizationId`.
85
98
  */
86
99
  organization?: string;
100
+ /**
101
+ * Turns analytics off: `ph.analytics` is null and nothing is sent. Analytics is on by default — prescribing events
102
+ * go to Photon's analytics-api with the prescriber's token (never for M2M, never PHI).
103
+ */
104
+ disableAnalytics?: boolean;
87
105
  }
88
106
 
89
107
  /** Link to a flow: a live object (its record), or what a flow is given. `.parse(href)` reads a link back. */
@@ -124,6 +142,12 @@ export interface Photon {
124
142
  /** The environment's URLs, when created from one. */
125
143
  readonly environment: EnvironmentUrls | null;
126
144
 
145
+ /**
146
+ * Photon's analytics, as the signed-in prescriber: `ph.analytics.track(event, properties)`. Null for M2M, without
147
+ * an `environment`, or with `disableAnalytics`.
148
+ */
149
+ readonly analytics: Analytics | null;
150
+
127
151
  /**
128
152
  * Patients. `sync({ demographic })` finds the patient, lists candidates, says what's missing, or creates one
129
153
  * when nothing matches and it has enough. `ph.patient()`: a new patient to `sync` as the prescriber types.
@@ -142,6 +166,9 @@ export interface Photon {
142
166
  */
143
167
  readonly order: Calls<Order, OrderInput, Omit<OrderInput, "id" | "patient">, OrderResult>;
144
168
 
169
+ /** Read-only order snapshots and optional pharmacy choices. No live objects are opened or updated. */
170
+ orders(input?: OrdersInput): Promise<OrdersResult>;
171
+
145
172
  /**
146
173
  * network-api's health check: resolves once it's reachable and accepts this instance's token. Throws
147
174
  * `PhotonError` — `unauthorized` (a token it won't take), `network` (unreachable, or `getToken` threw),
@@ -149,6 +176,8 @@ export interface Photon {
149
176
  */
150
177
  ping(): Promise<void>;
151
178
 
179
+ me(): Promise<Caller>;
180
+
152
181
  /**
153
182
  * The prescriber's sign-in, when core runs it (`auth: { clientId }`): a live object — `status`, `user`,
154
183
  * `start()`, `signIn()`. Null when the host signs in (`auth: { getToken }`).
@@ -170,6 +199,32 @@ export interface Photon {
170
199
  readonly frame: LinkTo;
171
200
  }
172
201
 
202
+ export interface CallerName {
203
+ first: string | null;
204
+ last: string | null;
205
+ }
206
+
207
+ export interface CallerOrganization {
208
+ id: string;
209
+ name: string;
210
+ }
211
+
212
+ export type Caller =
213
+ | {
214
+ type: "user";
215
+ id: string;
216
+ name: CallerName;
217
+ organization: CallerOrganization | null;
218
+ permissions: string[];
219
+ }
220
+ | { type: "patient"; id: string; name: CallerName }
221
+ | { type: "machine"; organization: CallerOrganization | null; permissions: string[] };
222
+
223
+ const callerOrganization = (
224
+ organization: { __typename: "Organization"; id: string; name: string } | { __typename: "OperationError" },
225
+ ): CallerOrganization | null =>
226
+ organization.__typename === "Organization" ? { id: organization.id, name: organization.name } : null;
227
+
173
228
  /** The client a photon instance calls through — internal. */
174
229
  const clients = new WeakMap<Photon, NetworkClient>();
175
230
  export const clientOf = (ph: Photon): NetworkClient => {
@@ -194,18 +249,60 @@ export function photon(options: PhotonOptions): Photon {
194
249
  clientId: auth.clientId,
195
250
  });
196
251
  }
252
+ // A client secret: the backend's own token, by client credentials (machine.ts).
253
+ let machine: MachineCredentials | null = null;
254
+ if (isMachine(auth)) {
255
+ if (!environment)
256
+ throw new PhotonError("invalid", "Client credentials need an `environment`: it names the Auth0 tenant.");
257
+ if (!auth.organizationId)
258
+ throw new PhotonError("invalid", "Client credentials need the `organizationId` (org_…) they're for.");
259
+ machine = machineCredentials({
260
+ domain: environment.auth0Domain,
261
+ audience: environment.auth0Audience,
262
+ clientId: auth.clientId,
263
+ clientSecret: auth.clientSecret,
264
+ organizationId: auth.organizationId,
265
+ fetch: options.fetch,
266
+ });
267
+ }
197
268
  const signedIn = session;
269
+ const owned = machine;
270
+ const getToken = signedIn
271
+ ? () => signedIn.token()
272
+ : owned
273
+ ? () => owned.token()
274
+ : "getToken" in auth
275
+ ? auth.getToken
276
+ : null;
277
+ if (!getToken)
278
+ throw new PhotonError("invalid", "photon() needs `auth`: { clientId }, { getToken } or client credentials.");
198
279
  return photonOver(
199
280
  createNetworkClient({
200
281
  url,
201
- getToken: signedIn ? () => signedIn.token() : tokenSource(auth),
282
+ getToken,
283
+ // A refused machine token is dropped and the call tried once more with a new one.
284
+ onUnauthorized: owned ? () => owned.forget() : undefined,
202
285
  source: options.source,
203
286
  clientName: options.clientName,
204
287
  sourceVersion: options.sourceVersion,
205
288
  fetch: options.fetch,
206
289
  }),
207
290
  environment,
208
- { appUrl: options.appUrl ?? environment?.appUrl, session, linkAuth: linkAuthOf(auth, options.organization) },
291
+ {
292
+ appUrl: options.appUrl ?? environment?.appUrl,
293
+ session,
294
+ linkAuth: linkAuthOf(auth, options.organization),
295
+ analytics:
296
+ environment && !owned && !options.disableAnalytics
297
+ ? {
298
+ url: environment.analyticsApiUrl,
299
+ token: getToken,
300
+ clientName: options.clientName ?? null,
301
+ // The MCP's events say so on every one; React's cards set their own.
302
+ integration: options.source === "MCP_CONNECTOR" ? "mcp" : null,
303
+ }
304
+ : null,
305
+ },
209
306
  );
210
307
  }
211
308
 
@@ -213,7 +310,7 @@ export function photon(options: PhotonOptions): Photon {
213
310
  export function photonOver(
214
311
  client: NetworkClient,
215
312
  environment: EnvironmentUrls | null = null,
216
- options: { appUrl?: string; session?: Session | null; linkAuth?: LinkAuth } = {},
313
+ options: { appUrl?: string; session?: Session | null; linkAuth?: LinkAuth; analytics?: AnalyticsTarget | null } = {},
217
314
  ): Photon {
218
315
  const held = {
219
316
  patients: new Map<string, Patient>(),
@@ -402,7 +499,8 @@ export function photonOver(
402
499
  }
403
500
  if (input.clinical)
404
501
  throw new PhotonError("invalid", "Clinical changes need the patient's id: sync their demographics first.");
405
- if (!input.demographic) throw new PhotonError("invalid", "Send the patient's id, or what you know of them.");
502
+ if (!input.demographic && !input.contact)
503
+ throw new PhotonError("invalid", "Send the patient's id, or what you know of them.");
406
504
  const patient = new Patient(ctx, null);
407
505
  const { changes } = await patient.sync(fields);
408
506
  return { patient: theHeld(held.patients, patient), candidates: [...patient.snapshot.candidates], changes };
@@ -502,8 +600,43 @@ export function photonOver(
502
600
  updatePrescription,
503
601
  ),
504
602
  order: calls("order", () => new Order(ctx, null), openOrder, syncOrder, updateOrder),
603
+ orders: (input) => readOrders(client, input),
505
604
  ping: async () => void (await guarded(() => ping(client))),
605
+ me: async (): Promise<Caller> => {
606
+ const caller = await guarded(() => me(client));
607
+ switch (caller.__typename) {
608
+ case "User":
609
+ return {
610
+ type: "user",
611
+ id: caller.id,
612
+ name: { first: caller.name.first ?? null, last: caller.name.last ?? null },
613
+ organization: callerOrganization(caller.organization),
614
+ permissions: caller.permissions,
615
+ };
616
+ case "Patient":
617
+ return {
618
+ type: "patient",
619
+ id: caller.id,
620
+ name: { first: caller.name.first ?? null, last: caller.name.last ?? null },
621
+ };
622
+ case "Machine":
623
+ return {
624
+ type: "machine",
625
+ organization: callerOrganization(caller.organization),
626
+ permissions: caller.permissions,
627
+ };
628
+ }
629
+ },
506
630
  session: options.session ?? null,
631
+ analytics: options.analytics
632
+ ? analyticsFor(options.analytics, {
633
+ environment,
634
+ providerId: async () => {
635
+ const caller = await ph.me();
636
+ return caller.type === "user" ? caller.id : null;
637
+ },
638
+ })
639
+ : null,
507
640
  url,
508
641
  frame,
509
642
  };
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  getPrescription,
3
+ getPrescriptionTemplates,
3
4
  syncPrescription,
4
5
  updatePrescription,
5
6
  type ChangeSet,
@@ -12,14 +13,21 @@ import { classify, declaredChoice, optionKey, withChoice } from "./choices.ts";
12
13
  import { PhotonError, refuse } from "./errors.ts";
13
14
  import { filled } from "./inputs.ts";
14
15
  import { LiveRecord } from "./live.ts";
15
- import { noChanges, toChanges, toPrescription } from "./map.ts";
16
- import type { ChangeOption, Changes, PrescriptionEdits, PrescriptionRecord, Treatment } from "./types.ts";
16
+ import { noChanges, toChanges, toPrescription, toPrescriptionTemplate } from "./map.ts";
17
+ import type {
18
+ ChangeOption,
19
+ Changes,
20
+ PrescriptionEdits,
21
+ PrescriptionRecord,
22
+ PrescriptionTemplate,
23
+ Treatment,
24
+ } from "./types.ts";
17
25
 
18
26
  export interface PrescriptionExtra {
19
27
  /**
20
28
  * The drug for this line before its record exists — picked by the prescriber, or declared by the server
21
29
  * (an exact match) — and, once it does, the name the prescriber saw: network-api's treatment name can drop
22
- * the strength and form (docs/api-gaps.md). `treatment`: the picked option's drug, in parts (null when the
30
+ * the strength and form. `treatment`: the picked option's drug, in parts (null when the
23
31
  * server declared it, or it was given by id).
24
32
  */
25
33
  pick: { id: string; name: string; treatment: Treatment | null } | null;
@@ -28,6 +36,13 @@ export interface PrescriptionExtra {
28
36
  * Pick one with `continueDraft(id)`. null when not asked.
29
37
  */
30
38
  drafts: PrescriptionRecord[] | null;
39
+ /**
40
+ * This draft's templates, once `loadTemplates()` asked for them: kept current as its drug or patient changes.
41
+ * The caller's catalog templates come first, then recommended ones (sigs worded for the patient, then units).
42
+ * null until then, while loading, before the draft has a record, on a signed prescription, and when the lookup
43
+ * fails.
44
+ */
45
+ templates: PrescriptionTemplate[] | null;
31
46
  }
32
47
 
33
48
  /** The prescription mutation on a live object: its fields, and who it's for. */
@@ -97,7 +112,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
97
112
  #lookup: AbortController | null = null;
98
113
 
99
114
  constructor(ctx: Context, record: PrescriptionRecord | null, options: PrescriptionOptions = {}) {
100
- super(record, { pick: null, drafts: null }, options.changes);
115
+ super(record, { pick: null, drafts: null, templates: null }, options.changes);
101
116
  this.#ctx = ctx;
102
117
  this.#patientId = options.patientId ?? record?.patient?.id ?? null;
103
118
  this.#templateId = options.templateId ?? null;
@@ -119,6 +134,42 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
119
134
  this.#ctx.register(this);
120
135
  }
121
136
 
137
+ /** Whether anything asked for templates (`loadTemplates()`); until then, saves never trigger the lookup. */
138
+ #templatesWanted = false;
139
+ /** The record, drug and patient the current `templates` are for: a change to any of them fetches again. */
140
+ #templatesFor: string | null = null;
141
+
142
+ /**
143
+ * Fetch this draft's templates into `templates`, and refetch whenever its drug or patient changes. Separate from
144
+ * every other call so saves don't wait on the Medi-Span sig lookup. A failed lookup leaves `templates` null.
145
+ */
146
+ loadTemplates(): void {
147
+ this.#templatesWanted = true;
148
+ this.#refreshTemplates();
149
+ }
150
+
151
+ protected override patch(patch: Parameters<LiveRecord<PrescriptionRecord, PrescriptionExtra>["patch"]>[0]) {
152
+ super.patch(patch);
153
+ if (this.#templatesWanted) this.#refreshTemplates();
154
+ }
155
+
156
+ #refreshTemplates() {
157
+ const rx = this.state;
158
+ const templatesFor = rx?.patient && !this.signed ? `${rx.id}:${rx.treatment.id}:${rx.patient.id}` : null;
159
+ if (templatesFor === this.#templatesFor) return;
160
+ this.#templatesFor = templatesFor;
161
+ super.patch({ templates: null });
162
+ if (!rx || !templatesFor) return;
163
+ getPrescriptionTemplates(this.#ctx.client, rx.id).then(
164
+ (templates) => {
165
+ if (this.#templatesFor === templatesFor) {
166
+ super.patch({ templates: templates && templates.map(toPrescriptionTemplate) });
167
+ }
168
+ },
169
+ () => {},
170
+ );
171
+ }
172
+
122
173
  get signed(): boolean {
123
174
  return this.state?.signing.state === "SIGNED";
124
175
  }
@@ -126,7 +177,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
126
177
  /**
127
178
  * The drug's name as the prescriber saw it (the pick), while that pick is the record's drug; else the server's
128
179
  * product name (`prescribableName` — its `name` can be just the drug). Never an id: a drug given by id alone (e.g.
129
- * from a link) has no name until network-api gives one — once it's drafted for a patient (docs/api-gaps.md).
180
+ * from a link) has no name until network-api gives one — once it's drafted for a patient.
130
181
  */
131
182
  get name(): string | null {
132
183
  const pick = this.snapshot.pick;
@@ -255,14 +306,22 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
255
306
  /**
256
307
  * The prescriber's approval. Waits for updates already sent, then signs what was stored — bound to its
257
308
  * contentHash. Screening alerts don't stop it: signing is the prescriber's acknowledgement of
258
- * what screening showed (network-api has no way to acknowledge an alert yet — docs/api-gaps.md). Refused if
309
+ * what screening showed (network-api has no way to acknowledge an alert yet). Refused if
259
310
  * the server's last answer left something open (a choice to make, a rejected field), or if an update in
260
311
  * flight changed the screening result the prescriber saw (they review it first). A prescription marked changed-since-signing (INVALIDATED_SIGN) can be signed
261
312
  * again: that's the prescriber approving what it says now. Sends only the signing, never content.
262
313
  */
263
314
  sign(message?: string): Promise<{ changes: Changes }> {
264
315
  const seen = this.state;
265
- if (!seen) return Promise.reject(refuse("There's nothing to sign yet: pick the drug first."));
316
+ // Before its record, refused on the object (`error`), as a failed save is: a drug picked waits for its patient.
317
+ if (!seen)
318
+ return this.run("saving", async () => {
319
+ throw refuse(
320
+ this.snapshot.pick && !this.#patientId
321
+ ? "A patient is required for signing"
322
+ : "There's nothing to sign yet: pick the drug first.",
323
+ );
324
+ });
266
325
  return this.run("saving", async () => {
267
326
  const current = this.state!;
268
327
  if (current.signing.state === "SIGNED") return { changes: noChanges };
@@ -321,7 +380,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
321
380
  }
322
381
  if (!this.#patientId) {
323
382
  // A drug given by id, no patient yet: it's the line's drug — the pick, waiting for the patient. The lookup
324
- // checks the id; network-api doesn't name it until there's a draft (docs/api-gaps.md), so the name is the
383
+ // checks the id; network-api doesn't name it until there's a draft, so the name is the
325
384
  // one given with it, or the id.
326
385
  const given = this.#entered.treatment;
327
386
  if (!pick && given?.id) {
@@ -340,7 +399,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
340
399
  * SyncPrescription without a patient: a drug lookup — it can never create anything. network-api also rejects
341
400
  * the patient and every field it would have filled ("treatment.instructions", … — blocked by the missing
342
401
  * patient); only the drug's own change answers it: its choices, or why nothing matched. (A template isn't looked
343
- * up: network-api doesn't expand one without a patient — docs/api-gaps.md.) null when newer text aborted it.
402
+ * up: network-api doesn't expand one without a patient.) null when newer text aborted it.
344
403
  */
345
404
  async #lookUp(
346
405
  treatment: NonNullable<PrescriptionEdits["treatment"]>,
@@ -374,7 +433,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
374
433
  const changes = toChanges(outcome.changes);
375
434
  // A new line only takes a record once its drug is clear, and never a signed one or another line's:
376
435
  // while the drug is still ambiguous, network-api hands back the patient's latest prescription — an old
377
- // draft, one already signed and sent, or another line's (boson, 2026-09-29; docs/api-gaps.md).
436
+ // draft, one already signed and sent, or another line's (boson, 2026-09-29).
378
437
  const drugStillOpen = classify(changes).needsChoice.some((c) => c.key.startsWith("treatment"));
379
438
  const rx = outcome.prescription;
380
439
  if (!rx || drugStillOpen || !this.#canTake(rx)) {
@@ -392,7 +451,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
392
451
  /**
393
452
  * The patient already has several in-progress prescriptions and the server asks which this continues.
394
453
  * Candidates carry no drug or signing state, so read each; offer only unsigned drafts of the same drug that
395
- * no other line holds. network-api counts signed (even sent) ones as in progress (docs/api-gaps.md).
454
+ * no other line holds. network-api counts signed (even sent) ones as in progress.
396
455
  */
397
456
  async #offerDrafts(ids: string[]): Promise<{ changes: Changes }> {
398
457
  const read = await Promise.all(ids.map((id) => getPrescription(this.#ctx.client, id)));
@@ -408,7 +467,7 @@ export class Prescription extends LiveRecord<PrescriptionRecord, PrescriptionExt
408
467
  return { changes: this.changes };
409
468
  }
410
469
  const names = [...new Set(open.map((rx) => rx.treatment.name))].join(", ");
411
- // network-api won't start another prescription while ≥2 are open (docs/api-gaps.md).
470
+ // network-api won't start another prescription while ≥2 are open.
412
471
  throw refuse(
413
472
  open.every((rx) => rx.signing.state === "UNSIGNED")
414
473
  ? `This patient has ${open.length} unsent prescriptions (${names}). A new one can't be started until they're sent.`
@@ -20,9 +20,8 @@ import { PhotonError } from "./errors.ts";
20
20
  * uses a token the other already has. So the tabs of a site take turns (Web Locks) and each uses the newest one
21
21
  * stored. No refresh token from Auth0: nothing is kept, and the session lasts as long as the page.
22
22
  *
23
- * Known risks, each tracked: a script on the page can still read the refresh token (#36: the posture chosen,
24
- * Auth0's own for SPAs); a session ending mid-work swaps the cards for Sign in (#38); this file replaced Auth0's
25
- * SDK and awaits an auth review (#39).
23
+ * Known risks: a script on the page can still read the refresh token (the posture chosen, Auth0's own for SPAs);
24
+ * a session ending mid-work swaps the cards for Sign in.
26
25
  */
27
26
  export type SessionStatus = "starting" | "signed-out" | "signing-in" | "signed-in" | "error";
28
27
 
@@ -39,6 +38,14 @@ export interface SessionSnapshot {
39
38
  readonly error: PhotonError | null;
40
39
  }
41
40
 
41
+ /** Where `signIn` goes at Auth0. */
42
+ export interface SignInOptions {
43
+ /** The Photon organization to sign in to, past Auth0's picker. */
44
+ organization?: string;
45
+ /** An Auth0 connection (e.g. `"google-oauth2"`): straight to that identity provider, past Auth0's own page. */
46
+ connection?: string;
47
+ }
48
+
42
49
  export interface SessionConfig {
43
50
  /** The Auth0 tenant (`auth.<env>.health`). */
44
51
  domain: string;
@@ -120,9 +127,10 @@ export class Session {
120
127
 
121
128
  /**
122
129
  * Sign in — from a click. Leaves the page for Auth0 (its organization picker; `organization`, or the page's
123
- * `?organization=`, goes straight in) and comes back here. Inside an iframe: a popup, then signed in here.
130
+ * `?organization=`, goes straight in; `connection`, e.g. `"google-oauth2"`, goes straight to that identity provider,
131
+ * past Auth0's page) and comes back here. Inside an iframe: a popup, then signed in here.
124
132
  */
125
- async signIn(options: { organization?: string } = {}): Promise<void> {
133
+ async signIn(options: SignInOptions = {}): Promise<void> {
126
134
  this.#set({ status: "signing-in", error: null });
127
135
  if (window.top !== window) {
128
136
  const { params, state, pending } = await this.#authorize(options);
@@ -135,7 +143,7 @@ export class Session {
135
143
  * Auth0's sign-in page for this session — to link to, or go to yourself. It's ready to come back to: the next
136
144
  * `start()` on this page finishes the sign-in (PKCE: the verifier is kept for it, in this tab).
137
145
  */
138
- async signInUrl(options: { organization?: string } = {}): Promise<string> {
146
+ async signInUrl(options: SignInOptions = {}): Promise<string> {
139
147
  const { params, state, pending } = await this.#authorize(options);
140
148
  write(sessionStorage, pendingKey(state), pending);
141
149
  return this.#authorizeUrl(params);
@@ -165,7 +173,7 @@ export class Session {
165
173
  // ---- inside ----
166
174
 
167
175
  /** A sign-in request: Auth0's parameters (PKCE), and what coming back needs. */
168
- async #authorize(options: { organization?: string }) {
176
+ async #authorize(options: SignInOptions) {
169
177
  const state = randomString(16);
170
178
  const verifier = randomString(32);
171
179
  const redirectUri = window.location.origin;
@@ -180,6 +188,7 @@ export class Session {
180
188
  code_challenge: await challengeOf(verifier),
181
189
  code_challenge_method: "S256",
182
190
  ...(organization ? { organization } : {}),
191
+ ...(options.connection ? { connection: options.connection } : {}),
183
192
  });
184
193
  const pending: Pending = { verifier, returnTo: returnTo(), redirectUri };
185
194
  return { params, state, pending };
@@ -313,7 +322,7 @@ export class Session {
313
322
  }
314
323
 
315
324
  #keep(tokens: TokenResponse, previousRefresh: string | null) {
316
- const claims = { ...decode(tokens.id_token), ...decode(tokens.access_token) };
325
+ const claims = { ...claimsOf(tokens.id_token), ...claimsOf(tokens.access_token) };
317
326
  this.#access = { token: tokens.access_token, expiresAt: Date.now() + (tokens.expires_in ?? 3600) * 1000 };
318
327
  // The access token has the org; a refresh's id token may not come back, so the user carries over.
319
328
  this.#user = {
@@ -403,7 +412,7 @@ function base64Url(bytes: Uint8Array): string {
403
412
  }
404
413
 
405
414
  /** A JWT's claims (not verified — read only for display and the org; network-api checks the token). */
406
- function decode(jwt: string | undefined): Record<string, unknown> {
415
+ export function claimsOf(jwt: string | undefined): Record<string, unknown> {
407
416
  const payload = jwt?.split(".")[1];
408
417
  if (!payload) return {};
409
418
  try {