### Setup Aidbox TS SDK Project Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/CONTRIBUTING.md Clone the repository, install dependencies, and set up pre-commit hooks and initial build. ```bash git clone https://github.com/HealthSamurai/aidbox-ts-sdk.git cd aidbox-ts-sdk pnpm install pnpm hooks # install pre-commit hooks (lint + typecheck) pnpm -r run build # initial build (required for cross-package types) ``` -------------------------------- ### Install all dependencies Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/AGENTS.md Installs all project dependencies using pnpm. Run this from the root of the monorepo. ```bash pnpm install ``` -------------------------------- ### Install and Build All Packages Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/README.md Installs all project dependencies and builds all packages in the monorepo. Requires pnpm version 10 or higher. ```bash pnpm install pnpm -r run build ``` -------------------------------- ### Initialize SmartBackendServicesAuthProvider Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Example of initializing the auth provider with a private key imported from JWK format. This setup is used to create an AidboxClient instance for backend services. ```typescript import { SmartBackendServicesAuthProvider } from "@health-samurai/aidbox-client"; // Import or generate private key (Web Crypto API) const privateKeyJwk = JSON.parse(process.env.PRIVATE_KEY_JWK!); const privateKey = await crypto.subtle.importKey( "jwk", privateKeyJwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"] ); const authProvider = new SmartBackendServicesAuthProvider({ baseUrl: "https://fhir.example.com", clientId: "my-backend-service", privateKey, keyId: "my-key-id", scope: "system/Patient.read system/Observation.read", }); const client = new AidboxClient(baseUrl, authProvider); ``` -------------------------------- ### Install Aidbox FHIRPath LSP Package Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/06-fhirpath-lsp.md Install the FHIRPath LSP package using npm. This is the first step in setting up the language server. ```bash npm install @health-samurai/aidbox-fhirpath-lsp ``` -------------------------------- ### Preview UI with Storybook Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/CONTRIBUTING.md Start the Storybook development server to preview UI changes for React components. ```bash cd packages/react-components pnpm storybook # opens on http://localhost:6006 ``` -------------------------------- ### BasicAuthProvider Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Example of creating a BasicAuthProvider and initializing an AidboxClient. Credentials are UTF-8 encoded and Base64-encoded in the Authorization header. ```typescript const authProvider = new BasicAuthProvider( "https://fhir.example.com", "myuser", "mypassword" ); const client = new AidboxClient("https://fhir.example.com", authProvider); ``` -------------------------------- ### Install Git Hooks Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/README.md Installs git pre-commit hooks to ensure code quality before committing. ```bash pnpm hooks ``` -------------------------------- ### Install React Components Package Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/react-components/README.md Install the @health-samurai/react-components package using pnpm. Ensure you have React 19+ installed. ```bash pnpm add @health-samurai/react-components ``` -------------------------------- ### Install Aidbox FHIRPath LSP Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-fhirpath-lsp/README.md Install the package using pnpm. Ensure peer dependencies like react, react-dom, and @codemirror/lsp-client are met. ```bash pnpm add @health-samurai/aidbox-fhirpath-lsp ``` -------------------------------- ### Initialize Aidbox Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of initializing the Aidbox client with the instance URL. This client is similar to the Supabase client. ```typescript import { createClient } from '@health-samurai/aidbox-client' // Create a single supabase client for interacting with your database const client = new createClient('https://your-aidbox-instance.com'); ``` -------------------------------- ### AidboxClient Customization Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/01-aidbox-client-overview.md Shows how to instantiate the AidboxClient with custom types for Bundle, OperationOutcome, and User. ```typescript const client = new AidboxClient( baseUrl, authProvider ); ``` -------------------------------- ### Install Aidbox TS SDK Packages Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/08-integration-guide.md Install the necessary Aidbox TS SDK packages using npm. This includes the client, React components, and FHIRPath language server. ```bash npm install @health-samurai/aidbox-client \ @health-samurai/react-components \ @health-samurai/aidbox-fhirpath-lsp ``` -------------------------------- ### BasicAuthProvider Setup Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Instantiate AidboxClient with BasicAuthProvider for server-side applications requiring HTTP Basic Authentication. ```typescript import { AidboxClient, BasicAuthProvider } from "@health-samurai/aidbox-client"; const baseUrl = "https://fhir-server.address"; const client = new AidboxClient( baseUrl, new BasicAuthProvider(baseUrl, "username", "password"), ); ``` -------------------------------- ### Start the FHIRPath LSP Server Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/06-fhirpath-lsp.md Initialize and start the FHIRPath language server once at your application's startup. This enables all LSP features. ```typescript import { startServer } from "@health-samurai/aidbox-fhirpath-lsp"; // Initialize once at app startup startServer(); ``` -------------------------------- ### startServer() Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/06-fhirpath-lsp.md Starts the FHIRPath language server in a Web Worker. It initializes the server on the first call and subsequent calls are ignored if the server is already running. ```APIDOC ## startServer() ### Description Starts a FHIRPath language server in a Web Worker. This function initializes the server on its first invocation and subsequent calls will have no effect if the server is already active. ### Parameters #### Options - `options` (StartServerOptions) - Optional - Server configuration object. ### Options Interface ```typescript interface StartServerOptions { onError?: (error: Error) => void; onWarning?: (warning: string) => void; } ``` ### Example ```typescript import { startServer } from "@health-samurai/aidbox-fhirpath-lsp"; startServer({ onError: (error) => console.error("LSP error:", error), onWarning: (warning) => console.warn("LSP warning:", warning), }); ``` ``` -------------------------------- ### Create a Request Object Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Example of constructing a RequestParams object for a GET request. Ensure the URL is an absolute path and provide query parameters and headers as needed. ```typescript const request: RequestParams = { method: "GET", url: "/fhir/Patient", params: [["name", "Smith"], ["_count", "10"]], headers: { "Accept": "application/fhir+json" }, }; ``` -------------------------------- ### Server-Side SMART App Launch Example (Express) Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Demonstrates a full server-side SMART app launch flow using Express. It covers authorization, callback handling for code exchange, and using the AidboxClient for FHIR requests. ```typescript import { authorize, exchangeCode, AidboxClient, SmartAppLaunchAuthProvider, type PendingAuthorization, type SmartSession, } from "@health-samurai/aidbox-client"; // 1. Launch route — both standalone and EHR launches arrive here. // For EHR launch the EHR appends `?iss=...&launch=...` to this URL. app.get("/launch", async (req, res) => { const { redirectUrl, pending } = await authorize({ iss: "https://fhir.example.com", // fallback for standalone; query iss wins for EHR clientId: process.env.SMART_CLIENT_ID, clientSecret: process.env.SMART_CLIENT_SECRET, // sets usesClientSecret without persisting the secret scope: "launch openid fhirUser patient/*.read offline_access", redirectUri: `${process.env.BASE_URL}/callback`, launchUrl: req.url, // lets the helper extract iss/launch from query params issMatch: /^https:\/\/(fhir|aidbox)\.example\.com$/, }); req.session.pending = { [pending.stateNonce]: pending }; res.redirect(redirectUrl); }); // 2. Callback route — exchange the code for a session. app.get("/callback", async (req, res) => { const stateNonce = new URL(req.url, process.env.BASE_URL).searchParams.get("state"); const pending: PendingAuthorization = req.session.pending?.[stateNonce!]; if (!pending) return res.status(400).send("Unknown state"); const session = await exchangeCode({ url: req.url, pending, clientSecret: process.env.SMART_CLIENT_SECRET, }); req.session.smart = session; delete req.session.pending; res.redirect("/app"); }); // 3. Application route — use the provider for FHIR requests. app.get("/app", async (req, res) => { const session: SmartSession | undefined = req.session.smart; if (!session) return res.redirect("/launch"); const auth = new SmartAppLaunchAuthProvider({ baseUrl: session.serverUrl, getSession: () => req.session.smart, setSession: (s) => { req.session.smart = s; }, getClientSecret: () => process.env.SMART_CLIENT_SECRET, }); const client = new AidboxClient(session.serverUrl, auth); const result = await client.read({ type: "Patient", id: session.patient! }); res.json(result.value.resource); }); ``` -------------------------------- ### Aidbox Client request Method Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Use the `request` method to send a GET request and receive a parsed result. It returns a `Result` which can be checked for success or error. ```typescript const result: Result = client.request({ method: "GET", url: "/fhir/Patient/patient-id", headers: {Accept: "application/json"}, params: [["some" "parameters"], ["if", "needed"]], }); if (result.isOk()) { const patient: Patient = result.value.resource; // work with patient } if (result.isErr()) { const outcome: OperationOutcome = result.value.resource; // process OperationOutcome } ``` -------------------------------- ### CodeEditor SQL Configuration Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/05-react-components.md Configuration snippet for the CodeEditor component when used for SQL, demonstrating how to provide metadata fetching. ```typescript const sqlConfig: SqlConfig = { fetchMetadata: async (tableName?: string) => { // Fetch table schema from your server }, }; ``` -------------------------------- ### Browser SPA SMART App Launch Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Illustrates how to implement SMART app launch flows in a browser-based Single Page Application. It uses `sessionStorage` for persistence and highlights the use of public SMART clients. ```typescript import { authorize, exchangeCode, AidboxClient, SmartAppLaunchAuthProvider, type SmartSession, } from "@health-samurai/aidbox-client"; // On the launch page (e.g. /launch.html) const { redirectUrl, pending } = await authorize({ iss: new URL(location.href).searchParams.get("iss") ?? "https://fhir.example.com", launchUrl: location.href, clientId: "my-spa", scope: "launch openid fhirUser patient/*.read", redirectUri: `${location.origin}/callback.html`, }); sessionStorage.setItem(`smart:pending:${pending.stateNonce}`, JSON.stringify(pending)); location.href = redirectUrl; // On the callback page (e.g. /callback.html) const stateNonce = new URL(location.href).searchParams.get("state")!; const pending = JSON.parse(sessionStorage.getItem(`smart:pending:${stateNonce}`)!); const session = await exchangeCode({ url: location.href, pending }); sessionStorage.setItem("smart:session", JSON.stringify(session)); sessionStorage.removeItem(`smart:pending:${stateNonce}`); location.href = "/app.html"; // On any application page const auth = new SmartAppLaunchAuthProvider({ baseUrl: JSON.parse(sessionStorage.getItem("smart:session")!).serverUrl, getSession: () => JSON.parse(sessionStorage.getItem("smart:session")!) as SmartSession, setSession: (s) => sessionStorage.setItem("smart:session", JSON.stringify(s)), }); const client = new AidboxClient(auth.baseUrl, auth); ``` -------------------------------- ### BrowserAuthProvider Setup Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Instantiate AidboxClient with BrowserAuthProvider for browser applications using cookie-based sessions. ```typescript import { AidboxClient, BrowserAuthProvider } from "@health-samurai/aidbox-client"; const baseUrl = "https://fhir-server.address"; const client = new AidboxClient(baseUrl, new BrowserAuthProvider(baseUrl)); ``` -------------------------------- ### Ok Constructor Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Demonstrates creating a successful Result using the Ok constructor. This is used when an operation completes without errors. ```typescript const result = Ok(42); console.log(result.isOk()); // true console.log(result.value); // 42 ``` -------------------------------- ### Per-package Storybook dev server Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/AGENTS.md Starts the Storybook development server on port 6006 for the react-components package. ```bash pnpm storybook ``` -------------------------------- ### SmartBackendServicesAuthProvider Setup Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Configure SmartBackendServicesAuthProvider for server-to-server OAuth 2.0 client_credentials flow. Requires a private key generated via Web Crypto API. ```typescript import { AidboxClient, SmartBackendServicesAuthProvider } from "@health-samurai/aidbox-client"; // Generate or import your private key using Web Crypto API const privateKey = await crypto.subtle.generateKey( { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-384" }, true, ["sign", "verify"] ).then(kp => kp.privateKey); const auth = new SmartBackendServicesAuthProvider({ baseUrl: "https://fhir-server.address", clientId: "my-service", privateKey: privateKey, // CryptoKey from Web Crypto API keyId: "key-001", // Must match kid in JWKS scope: "system/*.read", // tokenExpirationBuffer: 30, // Optional: seconds before expiry to refresh (default: 30) }); const client = new AidboxClient("https://fhir-server.address", auth); ``` -------------------------------- ### Import FHIRPath LSP Server and Hooks Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/00-index.md Import functions to start the FHIRPath language server and hooks for integrating it with CodeMirror editors from the @health-samurai/aidbox-fhirpath-lsp package. ```typescript import { startServer, useCodeMirrorLsp } from "@health-samurai/aidbox-fhirpath-lsp"; ``` -------------------------------- ### Instance Read using Box Client Instance Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of performing an instance read operation directly via 'box.Instance'. ```typescript const patient = await box.Instance.Read('Patient', 'my-patient-id'); ``` -------------------------------- ### Example IconButton Usage Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/05-react-components.md Demonstrates how to use the IconButton component with a ghost variant and an icon from lucide-react. This is useful for actions that require a compact visual representation. ```typescript import { IconButton } from "@health-samurai/react-components"; import { Trash2 } from "lucide-react"; ``` -------------------------------- ### Testing Patient Fetch Operation with Vitest Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/08-integration-guide.md This example demonstrates how to mock Aidbox client interactions and assert successful patient data retrieval using Vitest. ```typescript import { describe, it, expect, vi } from "vitest"; describe("Patient operations", () => { it("should fetch a patient", async () => { const mockResult = { isOk: () => true, value: { resource: { id: "123", name: [{ family: "Doe" }] }, }, }; const mockClient = { read: vi.fn().mockResolvedValue(mockResult), }; const result = await mockClient.read({ type: "Patient", id: "123", }); expect(result.isOk()).toBe(true); expect(mockClient.read).toHaveBeenCalledWith( expect.objectContaining({ id: "123" }) ); }); }); ``` -------------------------------- ### Initialize Aidbox Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Create an instance of the AidboxClient with a base URL and an authentication provider. This is the primary step to start interacting with the FHIR server. ```typescript const baseUrl = "https://fhir-server.address"; const client = new AidboxClient( baseUrl, new BrowserAuthProvider(baseUrl), ); ``` -------------------------------- ### Instantiate SmartAppLaunchAuthProvider Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Use this to create an instance of SmartAppLaunchAuthProvider. Provide configuration including the FHIR server base URL, functions to get and set the session, and optionally a client secret resolver and token expiration buffer. ```typescript const authProvider = new SmartAppLaunchAuthProvider({ baseUrl: "https://fhir.example.com", getSession: () => sessionStore.get(sessionId), setSession: (session) => sessionStore.set(sessionId, session), getClientSecret: () => process.env.AIDBOX_CLIENT_SECRET, tokenExpirationBuffer: 60, // Refresh 1 minute before expiry }); const client = new AidboxClient(baseUrl, authProvider); ``` -------------------------------- ### Resource Creation Patterns Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Illustrates how to construct FHIR Patient resources, showing both a minimal representation and a more complete example with various fields. ```APIDOC ## Resource Creation Patterns ### Description Examples for creating FHIR Patient resources. ### Minimal Patient Example ```typescript const patient: Patient = { resourceType: "Patient", name: [{ family: "Doe" }], }; ``` ### Full Patient Example ```typescript const patient: Patient = { resourceType: "Patient", active: true, identifier: [ { system: "http://example.com/mrn", value: "12345" }, ], name: [ { use: "official", family: "Doe", given: ["Jane"] }, ], telecom: [ { system: "email", value: "jane@example.com" }, ], gender: "female", birthDate: "1985-03-15", address: [ { use: "home", type: "physical", line: ["123 Main St"], city: "Boston", state: "MA", postalCode: "02101", country: "USA", }, ], }; ``` ``` -------------------------------- ### SMART App Launch Flow Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/00-index.md Initiate a SMART app launch by calling `authorize` to get a redirect URL. On the callback, use `exchangeCode` to obtain a session, then configure the `SmartAppLaunchAuthProvider`. ```typescript // 1. Initiate const { redirectUrl, pending } = await authorize({ iss: "https://fhir.example.com", clientId: "my-app", scope: "patient/*.read", redirectUri: "https://myapp.example.com/callback", }); // 2. Exchange code on callback const session = await exchangeCode({ url: callbackUrl, pending, clientSecret: process.env.SECRET, }); // 3. Use in client const authProvider = new SmartAppLaunchAuthProvider({ baseUrl, getSession, setSession, }); ``` -------------------------------- ### Access Response Details Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Example of making a raw request and accessing details from the ResponseWithMeta object. Log the HTTP status, content type, and request duration. ```typescript const response = await client.rawRequest({ method: "GET", url: "/fhir/Patient/123", }); console.log(response.response.status); console.log(response.responseHeaders["content-type"]); console.log(response.duration); // ms ``` -------------------------------- ### Start FHIRPath Language Server Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/06-fhirpath-lsp.md Initiates the FHIRPath language server in a Web Worker. Configure error and warning callbacks. The server initializes on the first call; subsequent calls are ignored. ```typescript import { startServer } from "@health-samurai/aidbox-fhirpath-lsp"; startServer({ onError: (error) => console.error("LSP error:", error), onWarning: (warning) => console.warn("LSP warning:", warning), }); ``` -------------------------------- ### Search Resources with Chained Search Parameters and Pagination Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of performing a search operation with multiple chained search parameters and pagination controls (_count, _page). ```typescript const { result: , error: } = await client .search({type: 'Patient'}) .sp_family('John Doe') .sp_address-city_exact('Belgrade') .sp_address-city_contains('Nove Sad') .sp_birthdate('gt:2020') ._count(10) ._page(3); ``` -------------------------------- ### Common Search Queries for Aidbox Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Examples of constructing search queries for Aidbox, including by identifier, name, date range, pagination, multiple values, and composite searches. ```typescript // By identifier [['identifier', 'http://example.com/mrn|12345']] // By name [['name', 'Smith']] // By date range [['date', 'ge2020-01-01'], ['date', 'le2020-12-31']] // With pagination [['_count', '50'], ['_offset', '100']] // Multiple values [['status', 'draft,pending']] // Composite search [['subject', 'Patient/123'], ['status', 'final']] ``` -------------------------------- ### isOk() Method Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Shows how to check if a Result is a success case using the isOk() method. This is typically used in conditional logic to safely access the success value. ```typescript const result = await client.read({ type: "Patient", id: "123" }); if (result.isOk()) { console.log(result.value.resource.name); } ``` -------------------------------- ### Aidbox Client rawRequest Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/README.md Use `rawRequest` to send a GET request to the FHIR server and handle the raw JavaScript Response. This method throws an error for non-successful status codes. ```typescript const result = await client.rawRequest({ method: "GET", url: "/fhir/Patient/patient-id", headers: {Accept: "application/json"}, params: [["some" "parameters"], ["if", "needed"]], }).then((result) => { const patient: Patient = await result.response.json(); // ... }).catch((error) => { if (error instanceof ErrorResponse) { const outcome = await error.responseWithMeta.response.json // ... } }); ``` -------------------------------- ### FHIRPath Editor Integration Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Provides examples for integrating the FHIRPath editor, including starting the server and using the editor hook in a React component or the standalone CodeEditor component. Requires the CodeMirrorLSP and EditorView to be available. ```typescript // 1. Start server once startServer(); ``` ```typescript // 2. Use hook in React const containerRef = useRef(null); const editorViewRef = useRef(null); const { isReady, diagnostics } = useCodeMirrorLsp( editorViewRef.current, { resourceType: "Patient" } ); ``` ```typescript // 3. Or use CodeEditor component ``` -------------------------------- ### Initialize Aidbox Client with Client Credentials Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Shows how to set up the Aidbox client for server-to-server communication using client ID and secret for authentication. ```typescript import {Auth, makeClient} from "@health-samurai/aidbox-client"; const auth = Auth.ClientCredentials({ client_id: "client_id", client_secret: "client_secret", }); // by default just inject to query HTTP only cookies // TODO: think about namings const baseUrl = "https://fhir-server.address"; const auth_provider = Auth.Browser({ baseUrl }); const client = makeClient({ baseUrl, auth_provider }); ``` -------------------------------- ### Development and Build Commands Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/create-react-app/template/CLAUDE.md Common commands for running the development server, building for production, type checking, and linting the project. ```bash pnpm dev # Start dev server pnpm build # Production build pnpm typecheck # Type-check pnpm lint:check # Lint with Biome pnpm lint:fix # Auto-fix lint issues ``` -------------------------------- ### Instantiate AidboxClient Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/02-aidbox-client-class.md Demonstrates how to create an instance of the AidboxClient with a base URL and an authentication provider. Ensure you have the necessary authentication provider implementation. ```typescript import { AidboxClient, BrowserAuthProvider } from "@health-samurai/aidbox-client"; const baseUrl = "https://fhir-server.example.com"; const authProvider = new BrowserAuthProvider(baseUrl); const client = new AidboxClient(baseUrl, authProvider); ``` -------------------------------- ### SmartAppLaunchAuthProvider Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Initializes the SmartAppLaunchAuthProvider with configuration details for managing smart app authentication. ```APIDOC ## Constructor SmartAppLaunchAuthProvider ### Description Initializes the `SmartAppLaunchAuthProvider` with configuration parameters. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Field | Type | Required | Description | |---|---|---|---| | `baseUrl` | `string` | Yes | FHIR server base URL | | `getSession` | `() => SmartSession | Promise>` | Yes | Called on every request to retrieve current session | | `setSession` | `(session: SmartSession) => void | Promise` | Yes | Called when token is refreshed; host must persist new session | | `getClientSecret` | `(session: SmartSession) => string | undefined | Promise` | No | Server-side callback to resolve client secret | | `tokenExpirationBuffer` | `number` | No | Seconds before token expiry to refresh (default: 30) | ### Example ```typescript const authProvider = new SmartAppLaunchAuthProvider({ baseUrl: "https://fhir.example.com", getSession: () => sessionStore.get(sessionId), setSession: (session) => sessionStore.set(sessionId, session), getClientSecret: () => process.env.AIDBOX_CLIENT_SECRET, tokenExpirationBuffer: 60, // Refresh 1 minute before expiry }); const client = new AidboxClient(baseUrl, authProvider); ``` ``` -------------------------------- ### FHIR Period Type Definition Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/07-fhir-types.md Defines a time period with a start and end date/time. ```typescript type Period = { id?: string; extension?: Extension[]; start?: string; end?: string; } ``` -------------------------------- ### Initialize Aidbox Client for Browser Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Demonstrates how to initialize the Aidbox client for browser-based authentication using a provided base URL. ```typescript const baseUrl = "https://fhir-server.address"; const auth_provider = Auth.Browser({ baseUrl }); const client = makeClient({ baseUrl, auth_provider }); const orgId = 'asdf-1212-asdfasfdasdf-12312'; // TODO: tenant fn namign const client = client.tenant('asdf-1212-asdfasfdasdf-12312'); const resp = await orgClient.read({type: 'Patient', id: 'PatientId'}); async function read(opts: ReadOptions) { const req = fetch(`${baseUrl}/${opts.type}/${opts.id}`) const req = auth_provider.authenticate(req) return await req } ``` -------------------------------- ### Aidbox Get Base URL Method Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/01-aidbox-client-overview.md Retrieve the base URL of the Aidbox server. ```typescript getBaseUrl(): string ``` -------------------------------- ### Read Operation Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/01-aidbox-client-overview.md Retrieves a specific resource by its type and ID using a GET request. ```APIDOC ## GET [base]/[type]/[id] ### Description Retrieves a specific resource by its type and ID. ### Method GET ### Endpoint `[base]/[type]/[id]` ### Parameters #### Path Parameters - **type** (string) - Required - The resource type. - **id** (string) - Required - The resource ID. #### Query Parameters None explicitly documented for this basic read operation. ### Request Example (No request body for GET) ### Response #### Success Response (200) - **ResourceResponse** - Contains the requested FHIR resource of type T. #### Response Example (FHIR Resource JSON) #### Error Response - **OperationOutcome** - If the operation fails. ``` -------------------------------- ### Logout using Box Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of performing a logout operation using the 'box.Logout' method. ```typescript const patient = await box.Logout('Patient', 'name=foo'); ``` -------------------------------- ### Create Feature Branch Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/CONTRIBUTING.md Create a new branch for your feature development, starting from the 'development' branch. ```bash git checkout -b my-feature development ``` -------------------------------- ### Run Aidbox Client Tests Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/CONTRIBUTING.md Execute the test suite for the 'aidbox-client' package. ```bash cd packages/aidbox-client pnpm test ``` -------------------------------- ### Perform Operation using Box Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of performing a FHIR operation using the 'box.Operation' method. ```typescript const patient = await box.Operation('Patient', 'name=foo'); ``` -------------------------------- ### Read Patient Resource by ID Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of reading a Patient resource using a generated client method. ```typescript const patient = await client.Patient.read('my-patient-id'); ``` -------------------------------- ### BrowserAuthProvider Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Initializes the BrowserAuthProvider with the server's base URL. ```APIDOC ## BrowserAuthProvider Constructor ### Description Initializes the BrowserAuthProvider with the server's base URL. ### Signature ```typescript constructor(baseUrl: string) ``` ### Parameters #### Path Parameters - **baseUrl** (string) - Required - Server base URL ### Example ```typescript import { AidboxClient, BrowserAuthProvider } from "@health-samurai/aidbox-client"; const authProvider = new BrowserAuthProvider("https://fhir.example.com"); const client = new AidboxClient("https://fhir.example.com", authProvider); ``` ``` -------------------------------- ### SMART App Launch Authentication Flow Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/08-integration-guide.md This integration demonstrates how to implement the SMART App Launch flow using the Aidbox client. It covers handling the OAuth callback to exchange a code for a session and creating an authentication provider backed by session storage. ```typescript import { authorize, exchangeCode, SmartAppLaunchAuthProvider } from "@health-samurai/aidbox-client"; import { AidboxClient } from "@health-samurai/aidbox-client"; // In OAuth callback handler async function handleSmartCallback(req: Request, sessionStore: any) { const url = new URL(req.url); const state = url.searchParams.get("state"); if (!state) { throw new Error("Missing state parameter"); } // Look up pending authorization from session store const pending = sessionStore.get(state); if (!pending) { throw new Error("Invalid state"); } // Exchange code for session const session = await exchangeCode({ url: url.toString(), pending, clientSecret: process.env.AIDBOX_CLIENT_SECRET, }); // Store session sessionStore.set(req.sessionId, session); // Return session for use in client return { ok: true, sessionId: req.sessionId }; } // In client, create auth provider backed by session function createAuthProvider(sessionId: string, sessionStore: any) { return new SmartAppLaunchAuthProvider({ baseUrl: "https://fhir.example.com", getSession: () => sessionStore.get(sessionId), setSession: (session) => sessionStore.set(sessionId, session), getClientSecret: () => process.env.NEXT_PUBLIC_CLIENT_SECRET, }); } const authProvider = createAuthProvider(sessionId, sessionStore); const client = new AidboxClient("https://fhir.example.com", authProvider); ``` -------------------------------- ### CreateOptions Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Options for creating a new resource. ```APIDOC ## CreateOptions ### Description Options for creating a new resource. ### Type Definition ```typescript type CreateOptions = { type: string; resource: T; } ``` ### Fields - `type` (string): Required. Resource type. - `resource` (T): Required. The resource to create. ``` -------------------------------- ### Instance Delete using Box Client Instance Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of deleting a specific resource instance using 'box.Instance.Delete'. ```typescript const patient = await box.Instance.Delete('Patient', 'my-patient-id'); ``` -------------------------------- ### Develop and Build Packages Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/CONTRIBUTING.md Navigate to a specific package directory, compile the code, perform type checking, and auto-fix formatting. ```bash cd packages/ pnpm build # compile pnpm tsc:check # type-check pnpm lint:fix # auto-fix formatting ``` -------------------------------- ### FhirStructureView Component Usage Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/05-react-components.md Example of rendering a FHIR resource with the FhirStructureView component, optionally showing meta fields. ```typescript import { FhirStructureView } from "@health-samurai/react-components"; export function PatientDetail({ patient }) { return ; } ``` -------------------------------- ### Development Build and Check Commands Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-fhirpath-lsp/README.md Commands for building the library and worker, and for type-checking during development. ```bash pnpm build # Build library + worker pnpm tsc:check # Type-check pnpm lint:fix # Lint and format with Biome ``` -------------------------------- ### SmartBackendServicesAuthProvider Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Initializes the SmartBackendServicesAuthProvider with the provided configuration. This sets up the authentication mechanism for backend services. ```APIDOC ## SmartBackendServicesAuthProvider Constructor Initializes the SmartBackendServicesAuthProvider with the provided configuration. ### Constructor ```typescript constructor(config: SmartBackendServicesConfig) ``` ### Parameters #### Request Body - **config** (SmartBackendServicesConfig) - Required - Configuration object for the authentication provider. ### Example ```typescript import { SmartBackendServicesAuthProvider } from "@health-samurai/aidbox-client"; // Import or generate private key (Web Crypto API) const privateKeyJwk = JSON.parse(process.env.PRIVATE_KEY_JWK!); const privateKey = await crypto.subtle.importKey( "jwk", privateKeyJwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"] ); const authProvider = new SmartBackendServicesAuthProvider({ baseUrl: "https://fhir.example.com", clientId: "my-backend-service", privateKey, keyId: "my-key-id", scope: "system/Patient.read system/Observation.read", }); const client = new AidboxClient(baseUrl, authProvider); ``` ``` -------------------------------- ### Err Constructor Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Demonstrates creating a failed Result using the Err constructor. This is used when an operation encounters an error. ```typescript const result = Err("Something went wrong"); console.log(result.isErr()); // true console.log(result.value); // "Something went wrong" ``` -------------------------------- ### Conditional Update using Box Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of performing a conditional update on a FHIR resource based on a search query. ```typescript const patient = await box.conditionalUpdate( 'Patient', 'name=John%20Doe&gender=male', { name: 'John Doe', }); ``` -------------------------------- ### BasicAuthProvider Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Initializes the BasicAuthProvider with server URL, username, and password for HTTP Basic Authentication. ```APIDOC ## BasicAuthProvider Constructor ### Description Initializes the BasicAuthProvider with server URL, username, and password for HTTP Basic Authentication. ### Constructor Signature ```typescript constructor(baseUrl: string, username: string, password: string) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Details - Credentials are UTF-8 encoded (per RFC 7617) - Base64-encoded as `Authorization: Basic ` - Credentials are stored in memory; never persisted ### Example ```typescript const authProvider = new BasicAuthProvider( "https://fhir.example.com", "myuser", "mypassword" ); const client = new AidboxClient("https://fhir.example.com", authProvider); ``` ``` -------------------------------- ### Initialize Aidbox Client with SMART App Launch Authentication Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Initialize the Aidbox client for SMART App Launch authorization flows. ```typescript // SMART App Launch const authProvider = new SmartAppLaunchAuthProvider({ baseUrl, getSession, setSession, getClientSecret, }); const client = new AidboxClient(baseUrl, authProvider); ``` -------------------------------- ### Delete Resource using Box Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Example of deleting a FHIR resource by its type and ID using the 'box' client. ```typescript const patient = await box.delete('Patient', 'my-patient-id'); ``` -------------------------------- ### Initialize Aidbox Client with Basic Authentication Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Initialize the Aidbox client for server-to-server communication using basic authentication. ```typescript // Basic Auth (server-to-server) const client = new AidboxClient( baseUrl, new BasicAuthProvider(baseUrl, username, password) ); ``` -------------------------------- ### DataTable Component Usage Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/05-react-components.md Example of using the DataTable component with custom patient data and columns. Supports sticky headers. ```typescript import { DataTable, type ColumnDef } from "@health-samurai/react-components"; interface Patient { id: string; name: string; birthDate: string; } const columns: ColumnDef[] = [ { accessorKey: "id", header: "ID", }, { accessorKey: "name", header: "Name", }, { accessorKey: "birthDate", header: "Birth Date", }, ]; export function PatientsTable({ patients }: { patients: Patient[] }) { return ( ); } ``` -------------------------------- ### Add Required Peer Dependencies Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/06-fhirpath-lsp.md Install the necessary peer dependencies for the FHIRPath LSP package, including React and CodeMirror components. ```bash npm install react react-dom @codemirror/state @codemirror/lsp-client ``` -------------------------------- ### fetch Method Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Adds the Authorization header with Basic credentials and sends the request. ```APIDOC ## fetch Method ### Description Adds Authorization header and sends request. ### Method Signature ```typescript public async fetch(input: RequestInfo | URL, init?: RequestInit): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const response = await authProvider.fetch("https://fhir.example.com/Patient/123"); ``` ### Behavior 1. Validates URL matches baseUrl 2. Merges headers from request and init 3. Sets `Authorization: Basic ` 4. Sends request and returns response **Note**: Does not retry on 401 (credentials are always the same) ``` -------------------------------- ### mapErr() Method Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Illustrates transforming the error value of a Result using the mapErr() method. If the Result is a success, mapErr() has no effect. ```typescript const result: Result = await client.read({ type: "Patient", id: "123", }); const readable = result.mapErr(outcome => ({ errors: outcome.issue?.map(i => i.diagnostics).join(", "), })); ``` -------------------------------- ### Initialize Aidbox Client with SMART Backend Services Authentication Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Initialize the Aidbox client for server-to-server communication using SMART Backend Services authentication. ```typescript // SMART Backend Services const authProvider = new SmartBackendServicesAuthProvider({ baseUrl, clientId, privateKey, keyId, scope, }); const client = new AidboxClient(baseUrl, authProvider); ``` -------------------------------- ### map() Method Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Demonstrates transforming the success value of a Result using the map() method. If the Result is an error, map() has no effect. ```typescript const result = Ok(42); const doubled = result.map(x => x * 2); console.log(doubled.value); // 84 ``` -------------------------------- ### SMART App Launch Authentication Flow Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Initiates the SMART App Launch authorization, handles the callback, and sets up an authentication provider for client-side usage. Requires storing pending authorization state and session information. ```typescript const { redirectUrl, pending } = await authorize({ iss: "https://fhir.example.com", clientId: "my-app", scope: "patient/*.read launch", redirectUri: "https://myapp.example.com/callback", issMatch: "https://fhir.example.com", }); // Store pending, redirect user sessionStore.set(stateNonce, pending); window.location.href = redirectUrl; ``` ```typescript const session = await exchangeCode({ url: callbackUrl, pending, clientSecret: process.env.SECRET, }); // Store session, return to client sessionStore.set(sessionId, session); ``` ```typescript const authProvider = new SmartAppLaunchAuthProvider({ baseUrl, getSession: () => sessionStore.get(sessionId), setSession: (s) => sessionStore.set(sessionId, s), }); ``` -------------------------------- ### fetchSmartConfiguration Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Fetches the SMART configuration document from the issuer's /.well-known/smart-configuration endpoint. This is crucial for understanding the authorization server's capabilities. ```APIDOC ## fetchSmartConfiguration() ### Description Fetch the SMART configuration document from `{iss}/.well-known/smart-configuration`. ### Method Signature ```typescript export async function fetchSmartConfiguration(iss: string, requestInit?: RequestInit): Promise ``` ### Parameters #### Path Parameters - **iss** (string) - Required - FHIR server URL (issuer) - **requestInit** (RequestInit) - Optional - Fetch options ### Throws - If the endpoint is unreachable or returns non-2xx - If response lacks required fields (`authorization_endpoint`, `token_endpoint`) ### Example ```typescript const config = await fetchSmartConfiguration("https://fhir.example.com"); console.log(config.authorization_endpoint); ``` ``` -------------------------------- ### isErr() Method Example Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Illustrates checking if a Result is an error case using the isErr() method. This is useful for handling potential errors gracefully. ```typescript if (result.isErr()) { console.error(result.value.resource.issue); } ``` -------------------------------- ### Read Resource using Box Client Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Basic example of reading a FHIR resource using the 'box' client instance with explicit type. ```typescript const patient = await box.read('Patient', 'my-patient-id'}); ``` -------------------------------- ### Ok() Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/04-result-and-types.md Creates a successful Result with a given value. ```APIDOC ## Ok() ### Description Create a successful `Result`. ### Signature ```typescript function Ok(value: T): Result ``` ### Parameters #### Path Parameters - **value** (T) - Required - Success value ### Request Example ```typescript const result = Ok(42); console.log(result.isOk()); // true console.log(result.value); // 42 ``` ``` -------------------------------- ### Run all tests Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/AGENTS.md Executes all tests for all packages using pnpm. Run this from the root. ```bash pnpm -r run test ``` -------------------------------- ### System History using Box Client Instance Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/packages/aidbox-client/DESIGN.md Shows retrieving the history of all resources across the system using 'box.System.History'. ```typescript const patient = await box.System.History('name=foo'); ``` -------------------------------- ### Constructor Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/02-aidbox-client-class.md Initializes a new instance of the AidboxClient class. It requires the base URL of the FHIR server and an authentication provider. ```APIDOC ## Constructor ### Description Initializes a new instance of the AidboxClient class. It requires the base URL of the FHIR server and an authentication provider. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { AidboxClient, BrowserAuthProvider } from "@health-samurai/aidbox-client"; const baseUrl = "https://fhir-server.example.com"; const authProvider = new BrowserAuthProvider(baseUrl); const client = new AidboxClient(baseUrl, authProvider); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Resolve Patient Reference ID Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/07-fhir-types.md Parses a FHIR Reference object to extract the ID of a Patient resource. It checks if the reference string starts with 'Patient/'. ```typescript import type { Patient, Reference } from "@health-samurai/aidbox-client"; function resolvePatientReference(ref: Reference): string | undefined { // Extract patient ID from reference if (ref.reference?.startsWith("Patient/")) { return ref.reference.split("/")[1]; } return undefined; } const gp: Reference | undefined = patient.generalPractitioner?.[0]; if (gp?.reference?.startsWith("Patient/")) { console.log("Primary care physician ID:", gp.reference.split("/")[1]); } ``` -------------------------------- ### Utility Functions with React Components Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/09-quick-reference.md Demonstrates merging class names using `cn` and performing mobile detection with `useMobile`. Includes examples of toast notifications. ```typescript import { cn } from "@health-samurai/react-components"; // Merge class names const buttonClass = cn( "px-4 py-2 rounded", "bg-blue-500", isActive && "bg-blue-700", disabled && "opacity-50" ); // Mobile detection const isMobile = useMobile(); if (isMobile) { // Show mobile layout } // Toast notifications import { toast } from "@health-samurai/react-components"; tost.success("Saved successfully"); tost.error("Failed to save"); ``` -------------------------------- ### authorize Source: https://github.com/healthsamurai/aidbox-ts-sdk/blob/master/_autodocs/03-auth-providers.md Builds an authorization redirect URL and prepares the pending authorization state. It handles discovering the SMART configuration, determining PKCE support, and generating necessary security nonces. ```APIDOC ## authorize() ### Description Build an authorization redirect URL and prepare pending authorization. ### Method Signature ```typescript export async function authorize(config: AuthorizeConfig): Promise ``` ### Behavior 1. Resolves `iss` from config or `launchUrl` query 2. Validates `iss` against `issMatch` (CSRF protection) 3. Fetches SMART configuration 4. Determines PKCE support 5. Generates random state nonce and PKCE code verifier 6. Builds authorization URL with all FHIR SMART parameters 7. Returns redirect URL and pending authorization state ### Throws - If `iss` is missing - If `issMatch` rejects the resolved `iss` - If SMART config discovery fails - If `pkceMode="required"` but server doesn't advertise S256 ### Example ```typescript const result = await authorize({ iss: "https://fhir.example.com", clientId: "my-app", scope: "patient/*.read patient/Patient.write launch", redirectUri: "https://myapp.example.com/callback", issMatch: "https://fhir.example.com", // CSRF guard }); // In server code: session.pending = result.pending; // Store keyed by result.pending.stateNonce res.redirect(result.redirectUrl); ``` ```