@esushealth/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ export type OperationOutcome = Readonly<{
2
+ resourceType: "OperationOutcome";
3
+ issue: readonly {
4
+ severity: string;
5
+ code: string;
6
+ diagnostics?: string;
7
+ expression?: readonly string[];
8
+ }[];
9
+ }>;
10
+ export declare class EsusError extends Error {
11
+ readonly status: number;
12
+ readonly requestId: string | null;
13
+ readonly outcome: OperationOutcome | null;
14
+ readonly retryAfter: string | null;
15
+ readonly oauthCode: string | null;
16
+ constructor(message: string, status: number, requestId?: string | null, outcome?: OperationOutcome | null, retryAfter?: string | null, options?: ErrorOptions, oauthCode?: string | null);
17
+ }
18
+ export declare function record(value: unknown): Record<string, unknown> | null;
19
+ export declare function integrationOrigin(url: string): string;
20
+ export type RequestOptions = Readonly<{
21
+ signal?: AbortSignal;
22
+ }>;
23
+ export type TransportOptions = Readonly<{
24
+ url: string;
25
+ organizationId: string;
26
+ fetch?: typeof globalThis.fetch;
27
+ timeoutMs?: number;
28
+ }>;
29
+ export declare function createTransport(options: Omit<TransportOptions, "organizationId"> & {
30
+ organizationId?: string;
31
+ }, credential: HeadersInit): (path: string, { responseMode, acceptStatus, ...init }?: RequestInit & {
32
+ responseMode?: "json" | "empty" | "stream" | "binary";
33
+ acceptStatus?: number;
34
+ }) => Promise<{
35
+ body: unknown;
36
+ response: Response;
37
+ }>;
38
+ export type Transport = ReturnType<typeof createTransport>;
@@ -0,0 +1,108 @@
1
+ export class EsusError extends Error {
2
+ status;
3
+ requestId;
4
+ outcome;
5
+ retryAfter;
6
+ oauthCode;
7
+ constructor(message, status, requestId = null, outcome = null, retryAfter = null, options, oauthCode = null) {
8
+ super(message, options);
9
+ this.status = status;
10
+ this.requestId = requestId;
11
+ this.outcome = outcome;
12
+ this.retryAfter = retryAfter;
13
+ this.oauthCode = oauthCode;
14
+ this.name = "EsusError";
15
+ }
16
+ }
17
+ export function record(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value)
19
+ ? value
20
+ : null;
21
+ }
22
+ function readOutcome(value) {
23
+ const body = record(value);
24
+ if (body?.resourceType !== "OperationOutcome" || !Array.isArray(body.issue))
25
+ return null;
26
+ const issue = body.issue.map((entry) => {
27
+ const item = record(entry);
28
+ if (typeof item?.severity !== "string" || typeof item?.code !== "string")
29
+ return null;
30
+ const expression = item.expression;
31
+ return {
32
+ severity: item.severity,
33
+ code: item.code,
34
+ diagnostics: typeof item.diagnostics === "string" ? item.diagnostics : undefined,
35
+ expression: Array.isArray(expression) && expression.every((value) => typeof value === "string")
36
+ ? expression
37
+ : undefined,
38
+ };
39
+ });
40
+ return issue.every((entry) => entry !== null) ? { resourceType: "OperationOutcome", issue } : null;
41
+ }
42
+ export function integrationOrigin(url) {
43
+ const origin = new URL(url);
44
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname);
45
+ if ((origin.protocol !== "https:" && !(local && origin.protocol === "http:")) ||
46
+ origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) {
47
+ throw new TypeError("Esus URL must be an HTTPS origin or an HTTP loopback origin");
48
+ }
49
+ return origin.origin;
50
+ }
51
+ export function createTransport(options, credential) {
52
+ const origin = integrationOrigin(options.url);
53
+ const fetch = options.fetch ?? globalThis.fetch;
54
+ const timeoutMs = options.timeoutMs ?? 15_000;
55
+ const organizationId = options.organizationId;
56
+ return async (path, { responseMode = "json", acceptStatus, ...init } = {}) => {
57
+ const url = new URL(path, origin);
58
+ if (url.origin !== origin)
59
+ throw new TypeError("Esus requests must stay on the configured origin");
60
+ const headers = new Headers(init.headers);
61
+ for (const [name, value] of new Headers(credential))
62
+ headers.set(name, value);
63
+ const accept = responseMode === "stream" ? "application/fhir+ndjson"
64
+ : responseMode === "binary" ? "*/*" : "application/json, application/fhir+json";
65
+ headers.set("accept", accept);
66
+ if (organizationId !== undefined)
67
+ headers.set("x-esus-expected-organization", organizationId);
68
+ const timeout = AbortSignal.timeout(timeoutMs);
69
+ let response;
70
+ try {
71
+ response = await fetch(url, {
72
+ ...init,
73
+ headers,
74
+ cache: "no-store",
75
+ redirect: "error",
76
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
77
+ });
78
+ }
79
+ catch (cause) {
80
+ throw new EsusError("Esus request could not be completed", 0, null, null, null, { cause });
81
+ }
82
+ const requestId = response.headers.get("x-request-id");
83
+ const retryAfter = response.headers.get("retry-after");
84
+ if (!response.ok && response.status !== acceptStatus) {
85
+ const body = await response.json().catch(() => null);
86
+ const outcome = readOutcome(body);
87
+ const error = record(body)?.error;
88
+ throw new EsusError(`Esus returned HTTP ${response.status}`, response.status, requestId, outcome, retryAfter, undefined, typeof error === "string" ? error : null);
89
+ }
90
+ if (response.status === 204 || responseMode === "empty")
91
+ return { body: undefined, response };
92
+ if (responseMode === "binary")
93
+ return { body: response.body, response };
94
+ if (responseMode === "stream") {
95
+ if (response.headers.get("content-type")?.split(";")[0]?.trim() !== "application/fhir+ndjson" || !response.body) {
96
+ throw new EsusError("Esus did not return an NDJSON stream", response.status, requestId);
97
+ }
98
+ return { body: response.body, response };
99
+ }
100
+ try {
101
+ const body = await response.json();
102
+ return { body, response };
103
+ }
104
+ catch (cause) {
105
+ throw new EsusError("Esus returned an invalid JSON response", response.status, requestId, null, null, { cause });
106
+ }
107
+ };
108
+ }
@@ -0,0 +1,53 @@
1
+ import type { IntegrationInputs, IntegrationResults } from "./integration-contract.js";
2
+ import { type RequestOptions, type Transport } from "./transport.js";
3
+ type ResultBody<Route extends keyof IntegrationResults> = IntegrationResults[Route]["body"];
4
+ export type WebhookSubscription = Omit<ResultBody<"GET /tenant-apps/:id/webhooks/:webhookId">, "secret">;
5
+ export type WebhookDelivery = ResultBody<"GET /tenant-apps/:id/webhooks/:webhookId/deliveries">["deliveries"][number];
6
+ type CreateWebhook = IntegrationInputs["POST /tenant-apps/:id/webhooks"];
7
+ type UpdateWebhook = IntegrationInputs["PATCH /tenant-apps/:id/webhooks/:webhookId"];
8
+ export declare function webhookManagement(request: Transport, applicationId: string, boundAppId?: string): {
9
+ list(options?: RequestOptions): Promise<WebhookSubscription[]>;
10
+ get(webhookId: string, options?: RequestOptions): Promise<WebhookSubscription>;
11
+ create(input: CreateWebhook, options?: RequestOptions): Promise<{
12
+ readonly id: string;
13
+ readonly appId: string;
14
+ readonly url: string;
15
+ readonly events: ReadonlyArray<string>;
16
+ readonly description: string | null;
17
+ readonly active: boolean;
18
+ readonly secret?: string;
19
+ readonly createdAt: string;
20
+ readonly updatedAt: string;
21
+ }>;
22
+ update(webhookId: string, input: UpdateWebhook, options?: RequestOptions): Promise<{
23
+ readonly id: string;
24
+ readonly appId: string;
25
+ readonly url: string;
26
+ readonly events: ReadonlyArray<string>;
27
+ readonly description: string | null;
28
+ readonly active: boolean;
29
+ readonly secret?: string;
30
+ readonly createdAt: string;
31
+ readonly updatedAt: string;
32
+ }>;
33
+ delete(webhookId: string, options?: RequestOptions): Promise<void>;
34
+ ping(webhookId: string, options?: RequestOptions): Promise<{
35
+ deliveryId: string;
36
+ }>;
37
+ deliveries(webhookId: string, options?: RequestOptions & {
38
+ limit?: number;
39
+ }): Promise<{
40
+ readonly id: string;
41
+ readonly webhookId: string;
42
+ readonly eventId: string;
43
+ readonly eventType: string;
44
+ readonly status: "pending" | "delivered" | "failed" | "dead";
45
+ readonly attempts: number;
46
+ readonly lastStatusCode: number | null;
47
+ readonly lastError: string | null;
48
+ readonly lastAttemptAt: string | null;
49
+ readonly deliveredAt: string | null;
50
+ readonly createdAt: string;
51
+ }[]>;
52
+ };
53
+ export {};
@@ -0,0 +1,83 @@
1
+ import { EsusError, record } from "./transport.js";
2
+ function id(value, name) {
3
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) {
4
+ throw new TypeError(`Invalid webhook ${name}`);
5
+ }
6
+ return value.toLowerCase();
7
+ }
8
+ function unexpected(response) {
9
+ throw new EsusError("Esus returned an invalid webhook response", response.status, response.headers.get("x-request-id"));
10
+ }
11
+ export function webhookManagement(request, applicationId, boundAppId) {
12
+ const appId = id(applicationId, "app ID");
13
+ if (boundAppId !== undefined && boundAppId.toLowerCase() !== appId) {
14
+ throw new TypeError("Configure the service client with the internal UUID of this tenant app");
15
+ }
16
+ const base = `/tenant-apps/${appId}/webhooks`;
17
+ const pathFor = (webhookId) => `${base}/${id(webhookId, "subscription ID")}`;
18
+ async function call(path, method, status, { signal }, input) {
19
+ const reply = await request(path, {
20
+ method, signal,
21
+ ...(input === undefined ? {} : {
22
+ headers: { "content-type": "application/json" }, body: JSON.stringify(input),
23
+ }),
24
+ });
25
+ if (reply.response.status !== status)
26
+ unexpected(reply.response);
27
+ return reply;
28
+ }
29
+ function subscription(body, response) {
30
+ const webhook = record(body);
31
+ if (webhook?.appId !== appId || typeof webhook.id !== "string" || typeof webhook.active !== "boolean") {
32
+ return unexpected(response);
33
+ }
34
+ return webhook;
35
+ }
36
+ function publicSubscription(body, response) {
37
+ const { secret: _secret, ...webhook } = subscription(body, response);
38
+ return webhook;
39
+ }
40
+ return {
41
+ async list(options = {}) {
42
+ const { body, response } = await call(base, "GET", 200, options);
43
+ const rows = record(body)?.webhooks;
44
+ if (!Array.isArray(rows))
45
+ return unexpected(response);
46
+ return rows.map((row) => publicSubscription(row, response));
47
+ },
48
+ async get(webhookId, options = {}) {
49
+ const { body, response } = await call(pathFor(webhookId), "GET", 200, options);
50
+ return publicSubscription(body, response);
51
+ },
52
+ async create(input, options = {}) {
53
+ const { body, response } = await call(base, "POST", 201, options, input);
54
+ return subscription(body, response);
55
+ },
56
+ async update(webhookId, input, options = {}) {
57
+ const { body, response } = await call(pathFor(webhookId), "PATCH", 200, options, input);
58
+ return subscription(body, response);
59
+ },
60
+ async delete(webhookId, options = {}) {
61
+ await call(pathFor(webhookId), "DELETE", 204, options);
62
+ },
63
+ async ping(webhookId, options = {}) {
64
+ const { body, response } = await call(pathFor(webhookId) + "/ping", "POST", 200, options);
65
+ const deliveryId = record(body)?.deliveryId;
66
+ if (typeof deliveryId !== "string")
67
+ return unexpected(response);
68
+ return { deliveryId };
69
+ },
70
+ async deliveries(webhookId, options = {}) {
71
+ const { limit } = options;
72
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
73
+ throw new TypeError("Webhook delivery limit must be an integer from 1 to 200");
74
+ }
75
+ const query = limit === undefined ? "" : `?limit=${limit}`;
76
+ const { body, response } = await call(pathFor(webhookId) + "/deliveries" + query, "GET", 200, options);
77
+ const rows = record(body)?.deliveries;
78
+ if (!Array.isArray(rows))
79
+ return unexpected(response);
80
+ return rows;
81
+ },
82
+ };
83
+ }
@@ -0,0 +1,24 @@
1
+ export type WebhookEvent = Readonly<{
2
+ id: string;
3
+ type: string;
4
+ appId: string;
5
+ createdAt: string;
6
+ data: Readonly<Record<string, unknown>>;
7
+ }>;
8
+ type VerificationOptions = {
9
+ appId: string;
10
+ secret: string;
11
+ maxAgeMs?: number;
12
+ };
13
+ /** Verify the original request bytes before reading the event. Persist deliveryId to deduplicate retries. */
14
+ export declare function verifyWebhook(headers: Headers, body: Uint8Array, { appId, secret, maxAgeMs, }: VerificationOptions): Promise<{
15
+ deliveryId: string;
16
+ event: Readonly<{
17
+ id: string;
18
+ type: string;
19
+ appId: string;
20
+ createdAt: string;
21
+ data: Readonly<Record<string, unknown>>;
22
+ }>;
23
+ } | null>;
24
+ export {};
@@ -0,0 +1,41 @@
1
+ import { record } from "./transport.js";
2
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3
+ const signatureFormat = /^sha256=([0-9a-f]{64})$/;
4
+ const encoder = new TextEncoder();
5
+ const decoder = new TextDecoder("utf-8", { fatal: true });
6
+ function webhookEvent(body, appId) {
7
+ try {
8
+ const event = record(JSON.parse(decoder.decode(body)));
9
+ if (!event || event.appId !== appId ||
10
+ typeof event.id !== "string" || typeof event.type !== "string" ||
11
+ typeof event.createdAt !== "string" || !record(event.data))
12
+ return null;
13
+ return event;
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ /** Verify the original request bytes before reading the event. Persist deliveryId to deduplicate retries. */
20
+ export async function verifyWebhook(headers, body, { appId, secret, maxAgeMs = 5 * 60_000, }) {
21
+ if (!uuid.test(appId) || !secret || !Number.isSafeInteger(maxAgeMs) || maxAgeMs < 0) {
22
+ throw new TypeError("An Esus webhook requires its app ID, signing secret, and a valid freshness window");
23
+ }
24
+ const timestamp = headers.get("x-esus-timestamp");
25
+ const deliveryId = headers.get("x-esus-delivery-id");
26
+ const signature = signatureFormat.exec(headers.get("x-esus-signature") ?? "")?.[1];
27
+ if (!timestamp || !/^\d{1,15}$/.test(timestamp) || !deliveryId || !uuid.test(deliveryId) || !signature)
28
+ return null;
29
+ if (Math.abs(Date.now() - Number(timestamp)) > maxAgeMs)
30
+ return null;
31
+ const prefix = encoder.encode(`${timestamp}.${deliveryId}.`);
32
+ const input = new Uint8Array(prefix.length + body.length);
33
+ input.set(prefix);
34
+ input.set(body, prefix.length);
35
+ const mac = Uint8Array.from({ length: 32 }, (_, index) => Number.parseInt(signature.slice(index * 2, index * 2 + 2), 16));
36
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
37
+ if (!await crypto.subtle.verify("HMAC", key, mac, input))
38
+ return null;
39
+ const event = webhookEvent(body, appId);
40
+ return event && { deliveryId, event };
41
+ }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "@esushealth/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "TypeScript server SDK for Esus Health integrations and app sessions.",
5
+ "license": "MIT",
6
+ "homepage": "https://esus.health",
7
+ "type": "module",
8
+ "engines": { "node": ">=22" },
9
+ "scripts": { "prepack": "tsc -b --force" },
10
+ "files": ["dist/*.js", "dist/*.d.ts"],
11
+ "publishConfig": { "access": "public", "tag": "beta", "registry": "https://registry.npmjs.org/" },
12
+ "typesVersions": { "*": { "server": ["dist/server.d.ts"] } },
13
+ "exports": {
14
+ "./server": {
15
+ "types": "./dist/server.d.ts",
16
+ "import": "./dist/server.js"
17
+ }
18
+ }
19
+ }