@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,90 @@
|
|
|
1
|
+
# Prescription: Get / Sync / Update — all on the one `prescription` upsert.
|
|
2
|
+
# Get id only: read it, draft or signed; nothing changes.
|
|
3
|
+
# Sync whatever's known. Without a patient it can only look the drug up: the server lists the
|
|
4
|
+
# matching treatments (a DISAMBIGUATION change with options) and rejects the missing patient.
|
|
5
|
+
# With a patient it continues their in-progress draft or starts one (2+ in progress:
|
|
6
|
+
# AmbiguousPrescriptionMatch). ⚠ Send a treatment or template — without one the server
|
|
7
|
+
# copies the patient's last Rx (seen on boson, 2026-09).
|
|
8
|
+
# Update that one prescription (by id): only the fields sent change — or sign it: `signing.signedHash`
|
|
9
|
+
# = the contentHash the prescriber reviewed. Signing can't be combined with content edits.
|
|
10
|
+
# Screening runs on every call; every response carries signing.contentHash.
|
|
11
|
+
# Templates: like Get (id only, nothing changes), but selects only its treatment's templates — their Medi-Span
|
|
12
|
+
# sig lookup runs only when asked for, not on every save.
|
|
13
|
+
|
|
14
|
+
mutation GetPrescription($id: ID!, $metadata: RequestMetadata!) {
|
|
15
|
+
prescription(prescription: { id: $id }, metadata: $metadata) {
|
|
16
|
+
...PrescriptionResultFields
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
mutation GetPrescriptionTemplates($id: ID!, $metadata: RequestMetadata!) {
|
|
21
|
+
prescription(prescription: { id: $id }, metadata: $metadata) {
|
|
22
|
+
__typename
|
|
23
|
+
... on PrescriptionPayload {
|
|
24
|
+
prescription {
|
|
25
|
+
treatment {
|
|
26
|
+
templates {
|
|
27
|
+
...PrescriptionTemplateFields
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
... on OperationError {
|
|
33
|
+
...OperationErrorFields
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
mutation SyncPrescription(
|
|
39
|
+
$id: ID
|
|
40
|
+
$externalId: String
|
|
41
|
+
$patient: PatientReferenceInput
|
|
42
|
+
$treatment: TreatmentReferenceInput
|
|
43
|
+
$templateId: ID
|
|
44
|
+
$instructions: String
|
|
45
|
+
$dispense: DispenseInput
|
|
46
|
+
$clinical: PrescriptionClinicalInput
|
|
47
|
+
$metadata: RequestMetadata!
|
|
48
|
+
) {
|
|
49
|
+
prescription(
|
|
50
|
+
prescription: {
|
|
51
|
+
id: $id
|
|
52
|
+
externalId: $externalId
|
|
53
|
+
patient: $patient
|
|
54
|
+
treatment: $treatment
|
|
55
|
+
templateId: $templateId
|
|
56
|
+
instructions: $instructions
|
|
57
|
+
dispense: $dispense
|
|
58
|
+
clinical: $clinical
|
|
59
|
+
}
|
|
60
|
+
metadata: $metadata
|
|
61
|
+
) {
|
|
62
|
+
...PrescriptionResultFields
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
mutation UpdatePrescription(
|
|
67
|
+
$id: ID!
|
|
68
|
+
$externalId: String
|
|
69
|
+
$treatment: TreatmentReferenceInput
|
|
70
|
+
$instructions: String
|
|
71
|
+
$dispense: DispenseInput
|
|
72
|
+
$clinical: PrescriptionClinicalInput
|
|
73
|
+
$signing: PrescriptionSigningDetailsInput
|
|
74
|
+
$metadata: RequestMetadata!
|
|
75
|
+
) {
|
|
76
|
+
prescription(
|
|
77
|
+
prescription: {
|
|
78
|
+
id: $id
|
|
79
|
+
externalId: $externalId
|
|
80
|
+
treatment: $treatment
|
|
81
|
+
instructions: $instructions
|
|
82
|
+
dispense: $dispense
|
|
83
|
+
clinical: $clinical
|
|
84
|
+
signing: $signing
|
|
85
|
+
}
|
|
86
|
+
metadata: $metadata
|
|
87
|
+
) {
|
|
88
|
+
...PrescriptionResultFields
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { clientVersion } from "../meta/version.ts";
|
|
2
|
+
import type { EnvironmentUrls } from "./environments.ts";
|
|
3
|
+
import { lifecycleAnalyticsSentWith, type LifecycleAnalytics } from "../analytics/lifecycleEvents.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* An event's properties: ids, enums, booleans, counts, durations, timestamps, and lists of ids (an order's
|
|
7
|
+
* prescriptions). Never PHI, never a value typed.
|
|
8
|
+
*/
|
|
9
|
+
export type AnalyticsProperties = Record<string, string | number | boolean | null | string[]>;
|
|
10
|
+
|
|
11
|
+
/** Where an instance's events go: analytics-api and the token to send them with. */
|
|
12
|
+
export interface AnalyticsTarget {
|
|
13
|
+
readonly url: string;
|
|
14
|
+
token(): Promise<string>;
|
|
15
|
+
readonly clientName: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* Which Photon surface the events come from (`"mcp"`), when the instance knows: every event carries it as
|
|
18
|
+
* `integration`, unless the event's properties set their own (React's cards send `"react"`).
|
|
19
|
+
*/
|
|
20
|
+
readonly integration?: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `ph.analytics`: send prescribing events to Photon's analytics, as the signed-in prescriber. */
|
|
24
|
+
export interface Analytics extends AnalyticsTarget, LifecycleAnalytics {
|
|
25
|
+
/**
|
|
26
|
+
* Sends one event as the signed-in prescriber, with `providerId`, `orgId`, `environment`, `clientName`,
|
|
27
|
+
* `clientVersion`, `timestamp` and, when the instance knows it, `integration` added. Never rejects, and never throws: it resolves once the event is sent, or
|
|
28
|
+
* once it's dropped — no prescriber behind the token, network-api can't say who it is, analytics-api fails, or the
|
|
29
|
+
* event breaks the guards (a Title Case name; string, number, boolean or null values, or lists of at most
|
|
30
|
+
* {@link MAX_LIST_LENGTH} strings; strings of at most {@link MAX_PROPERTY_LENGTH} characters). The guards catch mistakes, not abuse: analytics-api checks only the token.
|
|
31
|
+
*/
|
|
32
|
+
track(event: string, properties?: AnalyticsProperties): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const MAX_PROPERTY_LENGTH = 128;
|
|
36
|
+
export const MAX_LIST_LENGTH = 50;
|
|
37
|
+
const TITLE_CASE = /^[A-Z][A-Za-z]*( [A-Z][A-Za-z]*)*$/;
|
|
38
|
+
|
|
39
|
+
interface Instance {
|
|
40
|
+
environment: EnvironmentUrls | null;
|
|
41
|
+
/** The instance's caller's `usr_` id, or null when it isn't a prescriber. Throws when network-api can't say. */
|
|
42
|
+
providerId(): Promise<string | null>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function analyticsFor(target: AnalyticsTarget, instance: Instance): Analytics {
|
|
46
|
+
const providerIdsBySub = new Map<string, Promise<string | null>>();
|
|
47
|
+
const providerIdFor = (sub: string) => {
|
|
48
|
+
let providerId = providerIdsBySub.get(sub);
|
|
49
|
+
if (!providerId) {
|
|
50
|
+
providerId = instance.providerId();
|
|
51
|
+
providerId.catch(() => providerIdsBySub.delete(sub)); // ask again next time
|
|
52
|
+
providerIdsBySub.set(sub, providerId);
|
|
53
|
+
}
|
|
54
|
+
return providerId;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const track: Analytics["track"] = async (event, properties = {}) => {
|
|
58
|
+
try {
|
|
59
|
+
if (!wellFormed(event, properties)) return;
|
|
60
|
+
const timestamp = new Date().toISOString();
|
|
61
|
+
const token = await target.token();
|
|
62
|
+
const claims = unverifiedJwtClaims(token);
|
|
63
|
+
if (typeof claims.sub !== "string") return;
|
|
64
|
+
const providerId = await providerIdFor(claims.sub);
|
|
65
|
+
if (!providerId) return;
|
|
66
|
+
const orgId = typeof claims.org_id === "string" ? claims.org_id : null;
|
|
67
|
+
await fetch(`${target.url}/event`, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: {
|
|
70
|
+
"content-type": "application/json",
|
|
71
|
+
"x-photon-auth-token": token,
|
|
72
|
+
"x-photon-auth-token-type": "auth0", // analytics-api returns 400 without it
|
|
73
|
+
},
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
event,
|
|
76
|
+
userId: providerId,
|
|
77
|
+
properties: {
|
|
78
|
+
clientName: target.clientName,
|
|
79
|
+
clientVersion,
|
|
80
|
+
timestamp,
|
|
81
|
+
...(target.integration ? { integration: target.integration } : {}),
|
|
82
|
+
...properties,
|
|
83
|
+
// Who and where come from the instance, never the caller.
|
|
84
|
+
providerId,
|
|
85
|
+
orgId,
|
|
86
|
+
environment: instance.environment?.name ?? null,
|
|
87
|
+
},
|
|
88
|
+
}),
|
|
89
|
+
keepalive: true,
|
|
90
|
+
});
|
|
91
|
+
} catch {
|
|
92
|
+
// never block the prescriber
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
url: target.url,
|
|
98
|
+
token: () => target.token(),
|
|
99
|
+
clientName: target.clientName,
|
|
100
|
+
integration: target.integration ?? null,
|
|
101
|
+
track,
|
|
102
|
+
...lifecycleAnalyticsSentWith(track),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function wellFormed(event: string, properties: AnalyticsProperties): boolean {
|
|
107
|
+
if (typeof event !== "string" || !TITLE_CASE.test(event)) return false;
|
|
108
|
+
if (!properties || typeof properties !== "object") return false;
|
|
109
|
+
const shortString = (value: unknown) => typeof value === "string" && value.length <= MAX_PROPERTY_LENGTH;
|
|
110
|
+
return Object.values(properties).every(
|
|
111
|
+
(value) =>
|
|
112
|
+
value === null ||
|
|
113
|
+
value === undefined ||
|
|
114
|
+
typeof value === "number" ||
|
|
115
|
+
typeof value === "boolean" ||
|
|
116
|
+
shortString(value) ||
|
|
117
|
+
(Array.isArray(value) && value.length <= MAX_LIST_LENGTH && value.every(shortString)),
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function unverifiedJwtClaims(jwt: string): Record<string, unknown> {
|
|
122
|
+
try {
|
|
123
|
+
const payload = jwt.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/");
|
|
124
|
+
const bytes = Uint8Array.from(atob(payload), (c) => c.charCodeAt(0));
|
|
125
|
+
return JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;
|
|
126
|
+
} catch {
|
|
127
|
+
return {};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { PhotonError } from "./errors.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How a photon instance gets its token.
|
|
5
|
+
*
|
|
6
|
+
* SPA `{ clientId }` — core signs the prescriber in itself, in the browser (session.ts): `ph.session`.
|
|
7
|
+
* SPA `{ getToken }` — the host signs in (e.g. its own Auth0 SDK) and supplies the org-scoped token.
|
|
8
|
+
* M2M `{ clientId, clientSecret, organizationId }` — a backend's own credentials (machine.ts): core runs the
|
|
9
|
+
* client-credentials grant, keeps the token until shortly before it expires, shares one request between
|
|
10
|
+
* concurrent calls and retries once on a 401. Servers only: `photon()` refuses a secret in a browser.
|
|
11
|
+
*/
|
|
12
|
+
export type PhotonAuth =
|
|
13
|
+
| { getToken: () => Promise<string> }
|
|
14
|
+
| { clientId: string }
|
|
15
|
+
| { clientId: string; clientSecret: string; organizationId: string };
|
|
16
|
+
|
|
17
|
+
/** Core's own browser sign-in: a client id alone. */
|
|
18
|
+
export const signsIn = (auth: PhotonAuth): auth is { clientId: string } => "clientId" in auth && !hasSecret(auth);
|
|
19
|
+
|
|
20
|
+
/** A backend's own credentials (M2M). */
|
|
21
|
+
export const isMachine = (
|
|
22
|
+
auth: PhotonAuth,
|
|
23
|
+
): auth is { clientId: string; clientSecret: string; organizationId: string } =>
|
|
24
|
+
"clientId" in auth && "clientSecret" in auth;
|
|
25
|
+
|
|
26
|
+
/** A client secret, in any shape it's given (M2M). */
|
|
27
|
+
export const hasSecret = (auth: object): boolean => "clientSecret" in auth || "client_secret" in auth;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Whether this code runs in a browser — a page, or a worker one started — where everything in it, a secret too,
|
|
31
|
+
* is readable by whoever opens the page.
|
|
32
|
+
*/
|
|
33
|
+
export const inBrowser = (): boolean =>
|
|
34
|
+
typeof document !== "undefined" || typeof (globalThis as { importScripts?: unknown }).importScripts === "function";
|
|
35
|
+
|
|
36
|
+
/** A client secret in a browser is a published secret: refused before anything else, and loudly. */
|
|
37
|
+
export function refuseSecretInBrowser(auth: object): void {
|
|
38
|
+
if (!hasSecret(auth) || !inBrowser()) return;
|
|
39
|
+
throw new PhotonError(
|
|
40
|
+
"invalid",
|
|
41
|
+
"SECURITY: a client secret was passed to photon() in a browser. Anyone who opens this page can read it and " +
|
|
42
|
+
"act as your backend — treat it as leaked and rotate it now. Client credentials (M2M) are for servers only; " +
|
|
43
|
+
"in a browser use { clientId } (core signs the prescriber in) or { getToken }.",
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* How links from an instance sign in (`FlowLink.auth`): an embed signs the prescriber in with the host's own
|
|
49
|
+
* client — `{ clientId }`'s — and any link opens in the instance's organization, when it has one. An M2M client
|
|
50
|
+
* makes webapp links only: its credentials are a server's, so its client id and secret never go in a link.
|
|
51
|
+
*/
|
|
52
|
+
export interface LinkAuth {
|
|
53
|
+
/** The client an embed signs in with: the instance's `{ clientId }`. Never an M2M client's. */
|
|
54
|
+
clientId: string | null;
|
|
55
|
+
/** The organization links open in: `photon({ organization })`, or M2M's `organizationId`. */
|
|
56
|
+
organization: string | null;
|
|
57
|
+
/** M2M: `frame()` is refused. */
|
|
58
|
+
machine: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function linkAuthOf(auth: PhotonAuth, organization?: string): LinkAuth {
|
|
62
|
+
const machine = hasSecret(auth);
|
|
63
|
+
const orgOfMachine = machine ? (auth as { organizationId?: string }).organizationId : undefined;
|
|
64
|
+
return {
|
|
65
|
+
clientId: signsIn(auth) ? auth.clientId : null,
|
|
66
|
+
organization: organization || orgOfMachine || null,
|
|
67
|
+
machine,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { applyAt } from "../api/index.ts";
|
|
2
|
+
import type { Change, ChangeOption, Changes } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Acting on what the server said (a ChangeSet), without parsing its prose.
|
|
6
|
+
*
|
|
7
|
+
* needsChoice AMBIGUOUS — nothing was written; the caller picks an option and sends again
|
|
8
|
+
* blocking REJECTED, or applied but BLOCKING — can't proceed until fixed
|
|
9
|
+
* advisories applied, but worth showing (COST_SAVINGS, PRODUCT_PREFERENCE, …)
|
|
10
|
+
* applied everything else that took effect
|
|
11
|
+
*/
|
|
12
|
+
export interface ClassifiedChanges {
|
|
13
|
+
needsChoice: Change[];
|
|
14
|
+
blocking: Change[];
|
|
15
|
+
advisories: Change[];
|
|
16
|
+
applied: Change[];
|
|
17
|
+
/** Nothing left open: no choice to make, nothing blocking. */
|
|
18
|
+
settled: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function classify(changes: Changes): ClassifiedChanges {
|
|
22
|
+
const result: ClassifiedChanges = { needsChoice: [], blocking: [], advisories: [], applied: [], settled: true };
|
|
23
|
+
for (const c of changes.unapplied) (c.status === "AMBIGUOUS" ? result.needsChoice : result.blocking).push(c);
|
|
24
|
+
for (const c of changes.applied) {
|
|
25
|
+
if (c.severity === "BLOCKING") result.blocking.push(c);
|
|
26
|
+
else if (c.severity === "ADVISORY") result.advisories.push(c);
|
|
27
|
+
else result.applied.push(c);
|
|
28
|
+
}
|
|
29
|
+
result.settled = result.needsChoice.length === 0 && result.blocking.length === 0;
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The changes waiting for a pick (e.g. which lisinopril), each with its options. Nothing was written for them. */
|
|
34
|
+
export const choicesIn = (changes: Changes): Change[] => changes.unapplied.filter((c) => c.status === "AMBIGUOUS");
|
|
35
|
+
|
|
36
|
+
const DECLARED = ["EXACT_NAME_MATCH", "RXNORM_CODE_MATCH"];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The one option the server has *declared* the match: a choice with a single option marked an exact name
|
|
40
|
+
* or RxNorm match. Taken without asking; anything else — fuzzy, several options, no match type — is the
|
|
41
|
+
* caller's (the prescriber's) pick.
|
|
42
|
+
*/
|
|
43
|
+
export function declaredChoice(changes: Changes): ChangeOption | null {
|
|
44
|
+
for (const change of choicesIn(changes)) {
|
|
45
|
+
const [only, ...rest] = change.options;
|
|
46
|
+
if (only && !rest.length && only.matchReasons.some((r) => DECLARED.includes(r.type))) return only;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The input to send again with a pick applied — the option says where it goes (`path`) and what (`value`).
|
|
53
|
+
* Never parse an option's prose. (On a live object, `obj.choose(option)` does this for you.)
|
|
54
|
+
*
|
|
55
|
+
* const { changes } = await ph.prescription({ treatment: { name: "lisinopril" } });
|
|
56
|
+
* const option = choicesIn(changes)[0]!.options[1]!;
|
|
57
|
+
* await ph.prescription(withChoice({ patient: { id }, treatment: { name: "lisinopril" } }, option));
|
|
58
|
+
*/
|
|
59
|
+
export function withChoice<T>(input: T, option: ChangeOption): T {
|
|
60
|
+
if (!option.path) throw new Error(`"${option.displayName}" calls ${option.operation}; it doesn't go in this input.`);
|
|
61
|
+
return applyAt(input, option.path, option.value);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A key for an option — the same pick gives the same key. */
|
|
65
|
+
export const optionKey = (option: ChangeOption) => `${option.path}=${JSON.stringify(option.value)}`;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Does the server want a mailing address for this patient? network-api says so either as an unapplied
|
|
69
|
+
* change under contact.address (patient upserts) or in an error ("patient … has no address", at
|
|
70
|
+
* submit). Ask for one only when it does — a phone is often enough.
|
|
71
|
+
*/
|
|
72
|
+
export function asksForAddress(changes?: Changes | null, message?: string | null): boolean {
|
|
73
|
+
const fromChanges = (changes?.unapplied ?? []).some(
|
|
74
|
+
(c) =>
|
|
75
|
+
c.key.startsWith("contact.address") ||
|
|
76
|
+
(c.category === "MISSING_INPUT" && /address/i.test(`${c.label} ${c.reason ?? ""}`)),
|
|
77
|
+
);
|
|
78
|
+
return fromChanges || /\baddress\b/i.test(message ?? "");
|
|
79
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { NetworkClient } from "../api/index.ts";
|
|
2
|
+
import type { Order } from "./order.ts";
|
|
3
|
+
import type { Patient } from "./patient.ts";
|
|
4
|
+
import type { Prescription } from "./prescription.ts";
|
|
5
|
+
import type { Changes, OrderRecord, PatientRecord, PrescriptionRecord } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What a photon instance's objects share: the client, and one object per record. `patient(record)` gives
|
|
9
|
+
* the object for that record — the one already held (which takes this copy, if it's idle) or a new one.
|
|
10
|
+
*/
|
|
11
|
+
export interface Context {
|
|
12
|
+
client: NetworkClient;
|
|
13
|
+
patient(record: PatientRecord, changes?: Changes): Patient;
|
|
14
|
+
prescription(record: PrescriptionRecord, changes?: Changes): Prescription;
|
|
15
|
+
order(record: OrderRecord, changes?: Changes): Order;
|
|
16
|
+
/** The object for a record by id: the one held, or read (null when there's no such record). */
|
|
17
|
+
openPatient(id: string): Promise<Patient | null>;
|
|
18
|
+
openPrescription(id: string): Promise<Prescription | null>;
|
|
19
|
+
/** The app's link to an object's flow, and the embeddable one (ph.url / ph.frame). */
|
|
20
|
+
url(obj: Patient | Prescription | Order): string;
|
|
21
|
+
frame(obj: Patient | Prescription | Order): string;
|
|
22
|
+
/** An object made before its record just got one: hold it as that record's object (unless one is held). */
|
|
23
|
+
|
|
24
|
+
register(obj: Patient | Prescription | Order): void;
|
|
25
|
+
held: {
|
|
26
|
+
patients: Map<string, Patient>;
|
|
27
|
+
prescriptions: Map<string, Prescription>;
|
|
28
|
+
orders: Map<string, Order>;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
* 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
|
+
analyticsApiUrl: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Environments without their own Auth0 tenant. Local services (tau) sign in through boson's. */
|
|
28
|
+
const AUTH_ENVIRONMENT: Partial<Record<PhotonEnvironment, PhotonEnvironment>> = { tau: "boson" };
|
|
29
|
+
|
|
30
|
+
/** The app's own domain, where it isn't `rx.<env>.health`. */
|
|
31
|
+
const APP_URL: Partial<Record<PhotonEnvironment, string>> = { photon: "https://rx.new", tau: "http://localhost:3000" };
|
|
32
|
+
|
|
33
|
+
/** Local services are plain http (fine from http://localhost); every hosted environment is https. */
|
|
34
|
+
const scheme = (name: PhotonEnvironment) => (name === "tau" ? "http" : "https");
|
|
35
|
+
|
|
36
|
+
/** The environment whose Auth0 tenant `name` signs in through (itself, except tau → boson). */
|
|
37
|
+
export const authEnvironmentOf = (name: PhotonEnvironment): PhotonEnvironment => AUTH_ENVIRONMENT[name] ?? name;
|
|
38
|
+
|
|
39
|
+
export function environmentUrls(name: PhotonEnvironment): EnvironmentUrls {
|
|
40
|
+
const authEnv = authEnvironmentOf(name);
|
|
41
|
+
return {
|
|
42
|
+
name,
|
|
43
|
+
networkApiUrl: `${scheme(name)}://network.${name}.health/graphql`,
|
|
44
|
+
auth0Domain: `auth.${authEnv}.health`,
|
|
45
|
+
auth0Audience: `https://api.${authEnv}.health`,
|
|
46
|
+
appUrl: APP_URL[name] ?? `https://rx.${name}.health`,
|
|
47
|
+
analyticsApiUrl: `${scheme(name)}://analytics-api.${name}.health`,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -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,49 @@
|
|
|
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
|
+
* the package README.
|
|
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
|
+
Caller,
|
|
21
|
+
CallerName,
|
|
22
|
+
CallerOrganization,
|
|
23
|
+
} from "./photon.ts";
|
|
24
|
+
export { clientVersion } from "../meta/version.ts";
|
|
25
|
+
export type { Analytics, AnalyticsTarget, AnalyticsProperties } from "./analytics.ts";
|
|
26
|
+
export type {
|
|
27
|
+
DraftPrescriptionForLifecycleAnalytics,
|
|
28
|
+
DraftPrescriptionSource,
|
|
29
|
+
LifecycleAnalytics,
|
|
30
|
+
LifecycleEventName,
|
|
31
|
+
OrderForLifecycleAnalytics,
|
|
32
|
+
PatientForLifecycleAnalytics,
|
|
33
|
+
PrescriptionForLifecycleAnalytics,
|
|
34
|
+
} from "../analytics/lifecycleEvents.ts";
|
|
35
|
+
export type { PatientExtra } from "./patient.ts";
|
|
36
|
+
export type { PrescriptionExtra, PrescriptionUpdate } from "./prescription.ts";
|
|
37
|
+
export type { OrderExtra, OrderUpdate } from "./order.ts";
|
|
38
|
+
export type { LiveStatus, LiveSnapshot, LiveBase } from "./live.ts";
|
|
39
|
+
export type { PhotonAuth } from "./auth.ts";
|
|
40
|
+
export { Session } from "./session.ts";
|
|
41
|
+
export type { SessionStatus, SessionSnapshot, SessionUser, SessionConfig, SignInOptions } from "./session.ts";
|
|
42
|
+
export { PhotonError } from "./errors.ts";
|
|
43
|
+
export type { Flow, FlowLink } from "./links.ts";
|
|
44
|
+
export type { PhotonErrorKind } from "./errors.ts";
|
|
45
|
+
export { PHOTON_ENVIRONMENTS, environmentUrls, authEnvironmentOf } from "./environments.ts";
|
|
46
|
+
export type { PhotonEnvironment, EnvironmentUrls } from "./environments.ts";
|
|
47
|
+
export { classify, choicesIn, declaredChoice, withChoice, asksForAddress } from "./choices.ts";
|
|
48
|
+
export type { ClassifiedChanges } from "./choices.ts";
|
|
49
|
+
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
|
+
}
|