# Palantir Foundry OSDK for TypeScript > Build applications on Palantir Foundry with type-safe TypeScript and React SDKs for the Ontology, Platform APIs, and AIP. This file contains every page of the documentation as Markdown. An index of the pages is at [llms.txt](https://palantir.github.io/osdk-ts/llms.txt). # Authentication Source: https://palantir.github.io/osdk-ts/authentication > Sign users in with @osdk/oauth, handle the OAuth redirect, authenticate servers with client credentials, and pass the token provider to createClient. Related Palantir Foundry documentation: - [Developer Console permissions](https://www.palantir.com/docs/foundry/developer-console/permissions) - [API authentication](https://www.palantir.com/docs/foundry/api/v2/general/overview/authentication) Every OSDK request needs a Foundry bearer token. `@osdk/oauth` creates token providers that sign users in, store and refresh tokens, and plug straight into `createClient`. ## Choose a token provider | Provider | Use it for | Grant | | --- | --- | --- | | `createPublicOauthClient` | Browser apps where each user signs in with their own Foundry account. | Authorization code with PKCE | | `createConfidentialOauthClient` | Servers, scheduled jobs, and backends that act as a service user. | Client credentials | | `createAuthlessClient` | Public apps that read Foundry data without a signed-in user, such as those from the **React (Public)** template of `@osdk/create-app`. | None | | Your own function | Scripts and tests that already have a token. | None | A token provider is any function that returns `Promise`. The OAuth clients are callable, so you pass them to `createClient` directly: ```ts title="src/client.ts" import { $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; export const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const client = createClient(foundryUrl, $ontologyRid, auth); ``` The client calls `auth()` before each request. You can call it yourself: `await auth()` resolves to the current access token and starts sign-in when there is none. ## Sign users in from a browser `createPublicOauthClient` runs the OAuth authorization code flow with PKCE against Foundry. Create it once, at module scope, next to your client. ```ts createPublicOauthClient(clientId, url, redirectUrl, options?) ``` | Argument | Type | Description | | --- | --- | --- | | `clientId` | `string` | The client ID from **OAuth & scopes** in Developer Console. | | `url` | `string` | The base URL of your Foundry stack, such as `https://example.palantirfoundry.com`. | | `redirectUrl` | `string` | The URL Foundry sends the user back to after sign-in. It must exactly match a redirect URL on **OAuth & scopes**. | | `options` | `PublicOauthClientOptions` | Optional settings, listed below. | | Option | Type | Default | Description | | --- | --- | --- | --- | | `scopes` | `string[]` | `["api:read-data", "api:write-data", "api:use-ontologies-read", "api:use-ontologies-write"]` | OAuth scopes to request. See [Scopes](#scopes). | | `tokenStorage` | `"localStorage" \| "sessionStorage" \| "none"` | `"localStorage"` | Where to keep the refresh token. See [Token storage](#token-storage). | | `postLoginPage` | `string` | The page URL when the client is created | Used with `loginPage`: the page to return to after sign-in. Without `loginPage`, the client returns to the page the user was on. | | `loginPage` | `string` | | A page in your app to show before redirecting to Foundry, such as `/login`. When set, the client navigates there instead of redirecting straight to Foundry. | | `useHistory` | `boolean` | `true` | Navigate within your app, to `loginPage` or back to the original page after sign-in, with `history.replaceState()` instead of `window.location.assign()`, so the page does not reload. | | `refreshTokenMarker` | `string` | | An extra value stored with the refresh token. Change it to invalidate stored refresh tokens and make every user sign in again. | | `fetchFn` | `typeof fetch` | `globalThis.fetch` | The `fetch` used for token requests. | | `ctxPath` | `string` | `"multipass"` | The path of Foundry's authorization server under `url`. | | `logger` | `OauthLogger` | | Receives warnings, such as a failed refresh. Without it, warnings are dropped. Compatible with the `Logger` from `@osdk/api`. | ```ts title="src/client.ts" export const auth = createPublicOauthClient(clientId, foundryUrl, redirectUrl, { scopes: ["api:read-data", "api:use-ontologies-read"], tokenStorage: "sessionStorage", }); ``` > [!NOTE] > The fourth argument can also be the older positional form, `useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath`. Pass either an options object or positional arguments, not both. `tokenStorage`, `refreshTokenMarker`, and `logger` are only available in the options object. ### How the flow works 1. The first time your app needs a token, the client looks for a stored refresh token and uses it if it is valid. 2. Without one, it saves a PKCE verifier and the current URL in `sessionStorage`, then redirects to Foundry's sign-in page. 3. Foundry redirects to `redirectUrl` with an authorization code. 4. On that page, your app asks for a token again. The client exchanges the code, stores the refresh token, and navigates back to the page the user started on. 5. The client refreshes the access token one minute before it expires. You do not schedule refreshes yourself. With `tokenStorage: "none"` there is no refresh token, so users sign in again when the access token expires. Concurrent token requests share one sign-in, so several components asking for data at once trigger a single redirect. ### Handle the redirect callback Render a route at your redirect URL's path that calls `auth.signIn()`. This completes step 4. The React template from `@osdk/create-app` uses this component, which then navigates to `/`; navigate elsewhere if your app needs to: ```tsx title="src/AuthCallback.tsx" import { auth } from "@/client"; import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; function AuthCallback(): React.ReactElement { const [error, setError] = useState(undefined); const navigate = useNavigate(); useEffect(() => { auth .signIn() .then(() => navigate("/", { replace: true })) .catch((e: unknown) => { setError(e instanceof Error ? e.message : String(e)); }); }, [navigate]); return
{error != null ? error : "Authenticating…"}
; } export default AuthCallback; ``` Register it at the same path as `redirectUrl`: ```tsx title="src/router.tsx" import AuthCallback from "@/AuthCallback"; import Home from "@/Home"; import { createBrowserRouter } from "react-router-dom"; export const router = createBrowserRouter( [ { path: "/", element: }, { path: "/auth/callback", element: }, ], { basename: import.meta.env.BASE_URL }, ); ``` If the redirect URL in your code, in `.env` files, and on **OAuth & scopes** differ in any character, including the port and a trailing slash, Foundry rejects the sign-in. ### Require sign-in before rendering The client starts sign-in on the first request, so pages that load OSDK data trigger it automatically. To keep a route from rendering until the user is signed in, check for a token first. `getTokenOrUndefined()` returns the current access token synchronously, or `undefined` if there is none or it has expired: ```tsx title="src/AuthenticatedRoute.tsx" import { auth } from "@/client"; import { useEffect, useState } from "react"; import { Outlet } from "react-router-dom"; export function AuthenticatedRoute() { const [token, setToken] = useState(auth.getTokenOrUndefined()); useEffect(() => { auth() .then(setToken) .catch((e: unknown) => { console.error("Sign-in failed", e); setToken(undefined); }); }, []); return token == null ? null : ; } ``` ### Scopes Scopes limit what the token can do. Both OAuth clients default to `api:read-data`, `api:write-data`, `api:use-ontologies-read`, and `api:use-ontologies-write`. Request only what your app needs, and make sure each scope is allowed for your application on **OAuth & scopes** in Developer Console. A read-only app can drop the two `write` scopes. The defaults only cover the Ontology. Add the scopes for anything else your app calls: each Platform SDK endpoint lists its required scopes (see [Platform SDK setup](https://palantir.github.io/osdk-ts/platform/setup.md)), and the AI packages need `api:use-language-models-execute` (see [AI](https://palantir.github.io/osdk-ts/ai.md)). The public client also requests `offline_access` so Foundry issues a refresh token, unless `tokenStorage` is `"none"`. A stored refresh token is only reused when it was issued for the same set of scopes, so changing `scopes` signs users in again. ### Token storage | `tokenStorage` | Refresh token kept | Trade-off | | --- | --- | --- | | `"localStorage"` | Across browser sessions | Fewest sign-ins. Anyone with access to the browser profile stays signed in. | | `"sessionStorage"` | Until the tab or browser closes | Recommended for shared devices. | | `"none"` | Never | Users sign in on every page load. No `offline_access` scope is requested. | The refresh token is stored under the key `@osdk/oauth : refresh : `. Access tokens stay in memory. ### Sign out `signOut()` revokes the access token with Foundry, deletes the stored refresh token, and emits a `signOut` event. It does not navigate, so redirect the user yourself: ```tsx title="src/SignOutButton.tsx" import { auth } from "@/client"; export function SignOutButton() { async function handleClick() { try { await auth.signOut(); } finally { window.location.assign("/"); } } return ( ); } ``` `signOut()` throws if nobody is signed in. If revocation fails, it still clears local state but throws instead of emitting `signOut`. The next token request after sign-out starts a new sign-in. ### Listen for auth events The public client emits `signIn`, `refresh`, and `signOut` events. `signIn` and `refresh` carry the new token in `event.detail`: ```ts import { auth } from "./client"; function handleSignOut() { console.info("Signed out"); } auth.addEventListener("signIn", (event) => { console.info("Signed in; token expires at", new Date(event.detail.expires_at)); }); auth.addEventListener("signOut", handleSignOut); auth.removeEventListener("signOut", handleSignOut); ``` | Member | Description | | --- | --- | | `auth()` | Resolves to a valid access token, refreshing or signing in when needed. | | `auth.signIn()` | Runs sign-in: refreshes from a stored token, completes a redirect callback, or redirects to Foundry. Resolves to the token object. | | `auth.refresh()` | Refreshes the access token with the stored refresh token. | | `auth.signOut()` | Revokes the token and clears stored state. | | `auth.getTokenOrUndefined()` | Returns the current access token, or `undefined` if there is none or it has expired. | | `auth.addEventListener(type, listener)` | Listens for `signIn`, `refresh`, or `signOut`. | | `auth.removeEventListener(type, listener)` | Removes a listener. | ## Authenticate a server or service `createConfidentialOauthClient` uses the client credentials grant with a client ID and secret from a confidential application in Developer Console. Requests run as that application's service user, not as a person. ```ts createConfidentialOauthClient(clientId, clientSecret, url, scopes?, fetchFn?, ctxPath?) ``` | Argument | Type | Default | Description | | --- | --- | --- | --- | | `clientId` | `string` | | The confidential application's client ID. | | `clientSecret` | `string` | | The client secret. | | `url` | `string` | | The base URL of your Foundry stack. | | `scopes` | `string[]` | `["api:read-data", "api:write-data", "api:use-ontologies-read", "api:use-ontologies-write"]` | Scopes to request. | | `fetchFn` | `typeof fetch` | `globalThis.fetch` | The `fetch` used for token requests. | | `ctxPath` | `string` | `"multipass"` | The path of Foundry's authorization server under `url`. | ```ts title="server/client.ts" import { $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createConfidentialOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const clientId = process.env.FOUNDRY_CLIENT_ID; const clientSecret = process.env.FOUNDRY_CLIENT_SECRET; if (clientId == null || clientSecret == null) { throw new Error("Set FOUNDRY_CLIENT_ID and FOUNDRY_CLIENT_SECRET"); } const auth = createConfidentialOauthClient(clientId, clientSecret, foundryUrl, [ "api:read-data", "api:use-ontologies-read", ]); export const client = createClient(foundryUrl, $ontologyRid, auth); ``` The client requests a new token when the current one expires. There is no refresh token or browser storage. It supports `signIn()`, `signOut()`, `getTokenOrUndefined()`, and `signIn` and `signOut` events, but not `refresh()`. > [!CAUTION] > Never use `createConfidentialOauthClient` in browser code. Anything you ship to a browser, including environment variables inlined by your bundler, is readable by users, and the client secret lets anyone act as your application. ## Public apps without sign-in `createAuthlessClient()` returns a token provider that sends a fixed public token, for apps that let anyone view data without a Foundry account: ```ts title="src/client.ts" import { createClient } from "@osdk/client"; import { createAuthlessClient } from "@osdk/oauth"; const foundryUrl = import.meta.env.VITE_FOUNDRY_API_URL; const ontologyRid = import.meta.env.VITE_FOUNDRY_ONTOLOGY_RID; export const client = createClient(foundryUrl, ontologyRid, createAuthlessClient()); ``` The **React (Public)** template of `@osdk/create-app` sets this up, including the request proxy it relies on. It reads the Foundry URL and Ontology RID from the `osdk-foundryUrl` and `osdk-ontologyRid` `` tags instead of environment variables, so a Marketplace installation uses its destination's Foundry URL and Ontology. ## Use an existing token For scripts, tests, and one-off tools, pass a function that returns a token you already have, such as one from an environment variable: ```ts title="scripts/countEngineers.ts" import { $ontologyRid, Employee } from "@my-app/sdk"; import { createClient } from "@osdk/client"; const token = process.env.FOUNDRY_TOKEN; if (token == null) { throw new Error("Set FOUNDRY_TOKEN"); } const client = createClient( "https://example.palantirfoundry.com", $ontologyRid, () => Promise.resolve(token), ); const result = await client(Employee) .where({ department: "Engineering" }) .aggregate({ $select: { $count: "unordered" } }); console.log(result.$count); ``` The client does not refresh a static token. When it expires, requests fail with `401` until you supply a new one. # Create a client Source: https://palantir.github.io/osdk-ts/client > Configure createClient with your Foundry URL, Ontology RID, and token provider, share it through OsdkProvider, and query without React. Related Palantir Foundry documentation: - [TypeScript OSDK](https://www.palantir.com/docs/foundry/ontology-sdk/typescript-osdk) The client from `@osdk/client` sends every OSDK request: it fetches objects, applies actions, and executes functions. Create it once per app, then hand it to `OsdkProvider` for React or call it directly. ## `createClient` ```ts createClient(baseUrl, ontologyRid, tokenProvider, options?, fetchFn?) ``` | Argument | Type | Description | | --- | --- | --- | | `baseUrl` | `string` | The base URL of your Foundry stack, such as `https://example.palantirfoundry.com`. In local development behind a CORS proxy, your dev server's origin. | | `ontologyRid` | `string \| Promise` | The Ontology to query, such as `ri.ontology.main.ontology.`. Usually `$ontologyRid` from your generated SDK. | | `tokenProvider` | `() => Promise` | Returns a bearer token for each request. Usually an OAuth client from `@osdk/oauth`. See [Authentication](https://palantir.github.io/osdk-ts/authentication.md). | | `options` | `object` | Optional settings, listed below. | | `fetchFn` | `typeof fetch` | The `fetch` used for every request. Defaults to the global `fetch`. | | Option | Type | Default | Description | | --- | --- | --- | --- | | `headers` | `Record` | | Extra headers added to every request. | | `logger` | `Logger` | A minimal built-in logger | A `Logger`, as defined in `@osdk/api`, that receives the client's log output. | | `UNSTABLE_DO_NOT_USE_BRANCH` | `string \| null` | Read from the page | Beta. The Foundry branch to read and write on. When omitted in a browser, the client uses the `foundryBranchRid` query parameter, then the branch meta tag injected by OSDK build tooling. `null` pins the default branch. | `createClient` throws `Invalid ontology RID` when `ontologyRid` is a string that does not start with `ri.`. ```ts title="src/client.ts" import { $ontologyRid } from "@my-app/sdk"; import { createClient, type Client } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; export const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const client: Client = createClient(foundryUrl, $ontologyRid, auth); ``` Some generated SDKs omit `$ontologyRid`, because they are built to run on more than one Foundry stack and an embedded RID would only be correct on one. Pass the RID from configuration instead. ## Keep one client per app Create the client at module scope in a single file, such as `src/client.ts`, and import it everywhere. `OsdkProvider` builds its cache from the client instance, so a new instance starts over with an empty cache. Read configuration from your environment instead of hard-coding it. With Vite, use `import.meta.env`: ```ts title="src/client.ts" import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = import.meta.env.VITE_FOUNDRY_API_URL; const clientId = import.meta.env.VITE_FOUNDRY_CLIENT_ID; const redirectUrl = import.meta.env.VITE_FOUNDRY_REDIRECT_URL; const ontologyRid = import.meta.env.VITE_FOUNDRY_ONTOLOGY_RID; export const auth = createPublicOauthClient(clientId, foundryUrl, redirectUrl); export const client = createClient(foundryUrl, ontologyRid, auth); ``` The React template from `@osdk/create-app` goes one step further: `index.html` renders the env values into `` tags, such as ``, and `src/client.ts` reads them at startup. Hosting can then change configuration by rewriting the HTML, without a new JavaScript build: ```ts title="src/client.ts" function getMetaTagContent(tagName: string): string { const elements = document.querySelectorAll(`meta[name="${tagName}"]`); const value = elements.item(elements.length - 1)?.getAttribute("content"); if (value == null || value === "") { throw new Error(`Meta tag ${tagName} not found or empty`); } return value; } const foundryUrl = getMetaTagContent("osdk-foundryUrl"); const ontologyRid = getMetaTagContent("osdk-ontologyRid"); ``` ### Platform API only clients `createPlatformClient(baseUrl, tokenProvider, options?, fetchFn?)` creates a client for Foundry Platform APIs, such as `@osdk/foundry.admin`, without an Ontology. Use it in apps that have no generated SDK. A client from `createClient` also works with the `@osdk/foundry.*` Platform SDK functions, so most apps need only one client. The exception is the AI helpers in `@osdk/aip-core`, such as `foundryModel`, which require a client from `createPlatformClient` (see [Chat and streaming](https://palantir.github.io/osdk-ts/ai/chat.md)): ```ts title="src/currentUser.ts" import { Users } from "@osdk/foundry.admin"; import { client } from "./client"; const me = await Users.getCurrent(client); console.log(me.username); ``` ## Provide the client to React Wrap your app's root in `OsdkProvider` from `@osdk/react`. Every `@osdk/react` hook reads the client and its cache from the provider. ```tsx title="src/main.tsx" import { OsdkProvider } from "@osdk/react"; import ReactDOM from "react-dom/client"; import { App } from "./App"; import { client } from "./client"; const rootElement = document.getElementById("root"); if (rootElement == null) { throw new Error("Root element not found"); } ReactDOM.createRoot(rootElement).render( , ); ``` | Prop | Type | Default | Description | | --- | --- | --- | --- | | `client` | `Client` | | The client from `createClient`. The provider creates its cache from this instance. | | `children` | `ReactNode` | | Your app. | | `enableDevTools` | `boolean` | `true` when `@osdk/react-devtools` is registered | Turns the [OSDK Devtools](https://palantir.github.io/osdk-ts/devtools.md) panel on or off. Has no effect in production builds. | | `devMode` | `object` | | Development-only cache behavior, ignored in production builds. See below. | | `devMode` field | Type | Default | Description | | --- | --- | --- | --- | | `actionDelayMs` | `number` | `1000` | Delays the result of a single (non-batched) action that has an optimistic update, so you can see the optimistic state. Set `0` to turn it off. | | `logLevel` | `"trace" \| "debug" \| "info" \| "warn" \| "error" \| "fatal"` | `"error"` | Log level of the cache layer. `"debug"` shows its tracing. | | `debug.refCounts` | `boolean` | `false` | Logs cache entry reference counts and cleanup, and shortens retention so cleanup happens sooner. | | `debug.cacheKeys` | `boolean` | `false` | Logs cache key lookups. | ```tsx ``` Put the provider above everything that uses OSDK data, including headers and navigation, and pass it a client created at module scope. `` inside a component creates a new client, and an empty cache, on every render. A hook rendered outside the provider throws: ```txt No OsdkProvider found. Did you forget to wrap your component tree with ? ``` To call the client inside a component, for example in an event handler, read it from the provider with `useOsdkClient`: ```tsx title="src/ExportButton.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkClient } from "@osdk/react"; export function ExportButton() { const client = useOsdkClient(); async function handleClick() { const names: string[] = []; for await (const employee of client(Employee).asyncIter({ $select: ["fullName"] })) { names.push(employee.fullName ?? ""); } await navigator.clipboard.writeText(names.join("\n")); } return ( ); } ``` For data you render, prefer the hooks, such as `useOsdkObjects` and `useOsdkAction`: they cache results and update when objects change. Direct client calls bypass the cache. ## Use the client without React Call `client` with a definition from your SDK. What it returns depends on the definition: | You pass | You get | Main methods | | --- | --- | --- | | Object type, such as `Employee` | An object set of all objects of that type | `where`, `fetchPage`, `fetchOne`, `asyncIter`, `aggregate`, `pivotTo` | | Interface | An object set over every type that implements it | Object set methods except `fetchOne`; see [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md) | | Action, such as `modifyEmployee` | An action invoker | `applyAction`, `batchApplyAction` | | Function (query) | A function invoker | `executeFunction` | ### Fetch objects `fetchPage` returns one page with `data`, `nextPageToken`, and `totalCount`. `where` narrows the set and returns a new object set, so you can chain it: ```ts title="src/employees.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ department: "Engineering" }) .fetchPage({ $select: ["fullName", "jobTitle"], $orderBy: { fullName: "asc" }, $pageSize: 50, }); for (const employee of page.data) { console.log(employee.$primaryKey, employee.fullName, employee.jobTitle); } if (page.nextPageToken != null) { const next = await client(Employee) .where({ department: "Engineering" }) .fetchPage({ $pageSize: 50, $nextPageToken: page.nextPageToken }); console.log(next.data.length); } ``` Without `$select`, the response includes the type's default properties. Select only what you read. `$pageSize` sizes each page; it does not cap the total. Fetch one object by primary key with `fetchOne`, and follow links from it through `$link`: ```ts const employee = await client(Employee).fetchOne(12345); const office = await employee.$link.office.fetchOne(); ``` To process every matching object, iterate with `asyncIter`. It fetches page after page from a consistent snapshot, so each object arrives once even if the data changes during the loop. Stream-backed object types have no snapshot guarantee, and iteration throws if the snapshot expires: ```ts for await (const employee of client(Employee).asyncIter({ $select: ["fullName"] })) { console.log(employee.fullName); } ``` For counts, sums, and group-bys, use `aggregate` instead of loading every object. ### Apply an action `applyAction` takes the action's parameters and an optional options object. Object parameters accept an object instance or its primary key: ```ts title="src/promote.ts" import { modifyEmployee } from "@my-app/sdk"; import { ActionValidationError } from "@osdk/client"; import { client } from "./client"; try { const edits = await client(modifyEmployee).applyAction( { employee: 12345, jobTitle: "Senior Engineer" }, { $returnEdits: true }, ); console.log(edits); } catch (e) { if (e instanceof ActionValidationError) { console.error("Invalid parameters", e.validation); } else { throw e; } } ``` | Option | Returns | | --- | --- | | none | `undefined` | | `{ $returnEdits: true }` | The edits the action made: objects added, modified, and deleted. | | `{ $validateOnly: true }` | The validation result, without applying the action. | `applyAction` throws `ActionValidationError` when the parameters fail validation, with the details in `error.validation`. `batchApplyAction` takes an array of parameter objects and applies them in one request. ### Execute a function ```ts const result = await client(getEmployeeCount).executeFunction({ department: "Engineering" }); ``` Replace `getEmployeeCount` with a function from your SDK. Its parameters and return type come from the function's definition. ### Read metadata `client.fetchMetadata(definition)` returns runtime metadata, such as display names and descriptions, for an object type, interface, action, or function: ```ts const metadata = await client.fetchMetadata(Employee); console.log(metadata.displayName, metadata.description); ``` # Caching and reactivity Source: https://palantir.github.io/osdk-ts/concepts/caching > How @osdk/react stores objects once, shares them across hooks, deduplicates requests, and updates every view after an action. {/* cspell:ignore refetched refetches */} `@osdk/react` keeps one normalized cache per `OsdkProvider`. This page explains what the cache stores, when hooks hit the network, and how data updates after actions, so you can predict what a component renders. ## One cache per provider `OsdkProvider` wraps your `Client` in an `ObservableClient` from `@osdk/client/observable`. Every hook below that provider reads from and writes to the same cache: ```tsx title="src/main.tsx" import { OsdkProvider } from "@osdk/react"; import ReactDOM from "react-dom/client"; import App from "./App"; import { client } from "./client"; ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` Create the client once, outside any component. A new client creates a new, empty cache. To share one cache with code outside React or across several providers, pass an `ObservableClient` to `OsdkProvider` instead; see [Share an observable client](https://palantir.github.io/osdk-ts/reference/react/osdk-provider.md#share-an-observable-client). ## Objects are stored once The cache stores each object under its object type and primary key, such as `Employee:12345`. Lists, links, and object sets do not copy objects. They store references to those entries. | Hook | What the cache stores | | --- | --- | | `useOsdkObject` | One entry per object type and primary key. | | `useOsdkObjects`, `useObjectSet` | The ordered list of references, plus `totalCount` and paging state. | | `useLinks` | References to the linked objects, keyed by source object, link name, and filters. | | `useOsdkAggregation` | The aggregation result, keyed by object type, filter, and aggregate definition. | | `useOsdkFunction` | The function result, keyed by function and parameters. | Because objects are shared, a change to `Employee:12345` reaches every list, link, and detail view that contains it in the same render: ```tsx title="src/EmployeeViews.tsx" import { Employee } from "@my-app/sdk"; import { useLinks, useOsdkObject, useOsdkObjects } from "@osdk/react"; function Directory() { const { data } = useOsdkObjects(Employee); return
    {data?.map(e =>
  • {e.fullName}
  • )}
; } function Profile({ id }: { id: number }) { const { object } = useOsdkObject(Employee, id); return

{object?.fullName}

; } function Team({ manager }: { manager: Employee.OsdkInstance }) { const { links } = useLinks(manager, "reports"); return
    {links?.map(e =>
  • {e.fullName}
  • )}
; } ``` All three render the same `Employee` instance for `12345`. ### Read an instance you already have `useOsdkObject(instance)` reads the object from the cache and does not send a request. Use it in a row component to get `isOptimistic` for an object a list already loaded: ```tsx title="src/EmployeeRow.tsx" import type { Employee } from "@my-app/sdk"; import { useOsdkObject } from "@osdk/react"; function EmployeeRow({ employee }: { employee: Employee.OsdkInstance }) { const { object, isOptimistic } = useOsdkObject(employee); return (
  • {object?.fullName ?? employee.fullName}
  • ); } ``` `useOsdkObject(Employee, id)` with a type and primary key does fetch. Calls for the same object type made within 25 ms are batched into one request of up to 100 objects. ## When two hooks share an entry Two hooks share a cache entry when they ask for the same data. The client canonicalizes options before building the key, so structurally equal options match even if you write them inline or list keys in a different order. | Part of the key | Not part of the key | | --- | --- | | Object type or interface | `pageSize` | | `where` | `enabled` | | `orderBy` | `dedupeIntervalMs` | | `withProperties` | `autoFetchMore` | | `$select`, `intersectWith`, `pivotTo`, `rids` | | For example, these share one entry, and each component sees its own page size: ```tsx useOsdkObjects(Employee, { where: { department: "Sales" }, pageSize: 10 }); useOsdkObjects(Employee, { where: { department: "Sales" }, pageSize: 50 }); ``` These are separate entries, because the filters differ: ```tsx useOsdkObjects(Employee, { where: { department: "Sales" } }); useOsdkObjects(Employee, { where: { department: "Support" } }); ``` Adding `withProperties` creates a separate variant of each object, so derived properties never leak into views that did not request them. ## When hooks fetch The cache serves data immediately and refreshes it in the background. When a hook subscribes, it does three things: 1. Returns any data already in the cache for its key. 2. Starts a request to revalidate the entry, unless a request for that entry is already in flight or one started within `dedupeIntervalMs`. 3. Updates when the response arrives. So a component that mounts onto cached data renders it at once, with `isLoading: true` while the refresh runs. See [Loading and errors](https://palantir.github.io/osdk-ts/concepts/loading-and-errors.md) for how to render that state. ### Deduplication `dedupeIntervalMs` defaults to `2000` on `useOsdkObjects`, `useObjectSet`, `useLinks`, `useOsdkAggregation`, and `useOsdkFunction`. If two components mount the same query within that window, the second one reuses the first request. ```tsx const { data } = useOsdkObjects(Employee, { where: { department: "Sales" }, dedupeIntervalMs: 30_000, }); ``` When several mounted hooks share an entry, the smallest non-zero `dedupeIntervalMs` among them applies. In-flight requests are always shared, whatever the interval. ### Retention An entry stays in the cache for about 60 seconds after its last hook unmounts. Navigating away and back within that window renders the cached data while it revalidates. After that, the entry is removed and the next mount starts empty. ## Updates after actions When you apply an action with `useOsdkAction`, the client requests the action's edits from the server and updates the cache from them. You do not need to invalidate anything. | Edit | What happens | | --- | --- | | Object modified | The object is refetched. Every list, link, and detail view that references it re-renders. | | Object added | The object is fetched. Lists of that type whose `where` clause it matches add it. | | Object deleted | The object is removed from the cache and from every list that contained it. | | Any edit to a type | Aggregations over that type refetch. Links to that type re-evaluate. Functions with `dependsOn` that include the type refetch. | The action's promise resolves after the edited objects are refetched. Aggregation and other type-wide refreshes continue in the background. When an action edits too many objects for the server to list them, the response names only the edited object types: every cached query for those types refetches in the background, and the promise resolves without waiting. ### How lists stay correct For a modified or added object, each list of that type checks the object against its `where` clause in the browser: - If the object matches, the list keeps it or inserts it. - If the object no longer matches, the list removes it. - If the clause uses a filter the browser cannot evaluate, such as full-text search, the list removes a modified object, does not insert an added one, and refetches from the server with `isLoading: true`. The rest of the list stays in place until the response arrives. Lists that follow a link (`pivotTo`) or return a different object type than they start from always refetch from the server when objects of their result type change. ### Functions Function results are not tied to objects, so the cache cannot know which edits affect them. Declare the dependency with `dependsOn` or `dependsOnObjects`: ```tsx import { type Employee, getEmployeeReport } from "@my-app/sdk"; import { useOsdkFunction } from "@osdk/react"; function EmployeeReport({ employee }: { employee: Employee.OsdkInstance }) { const { data } = useOsdkFunction(getEmployeeReport, { params: { employeeId: employee.$primaryKey }, dependsOnObjects: [employee], }); return
    {data}
    ; } ``` | Option | Refetches when | | --- | --- | | `dependsOn: [Employee]` | An action edits any `Employee`. | | `dependsOnObjects: [employee]` | An action edits that specific object. | | `dependsOnObjects: [objectSet]` | An action edits any object of the object set's type. | ## Optimistic updates Pass `$optimisticUpdate` in the arguments to `applyAction` from `useOsdkAction`. It writes your predicted change to a temporary layer above the server data. Every view shows the predicted change at once and reports `isOptimistic: true`. When the action finishes, the layer is removed and the server's data replaces it. If the action fails, the layer is removed and the views return to the previous data. In development, a single (non-batched) action with an optimistic update is delayed by 1000 ms so you can see the optimistic state. Set `devMode={{ actionDelayMs: 0 }}` on `OsdkProvider` to turn the delay off. The delay never applies in production builds. See [Optimistic updates](https://palantir.github.io/osdk-ts/react/optimistic-updates.md) for the API. ## Real-time updates Pass `streamUpdates: true` to `useOsdkObjects` to keep a list current over a WebSocket. Changes made outside your app, by other users or pipelines, arrive without polling. `streamUpdates` cannot be combined with `pivotTo`, because the server does not support subscriptions for link traversal. ## When you need to invalidate Automatic updates cover changes that go through `useOsdkAction` in this app. Invalidate manually when data changes another way: - Another system or pipeline edits the data. - Your code edits data with `@osdk/client` directly, a REST call, or a background job. - A function reads data the cache cannot track. See [Cache invalidation](https://palantir.github.io/osdk-ts/react/cache-invalidation.md) for `invalidateObjects`, `invalidateObjectType`, `invalidateFunction`, and the other methods. ## Practices - **Let actions drive updates.** Do not call `invalidate*` after `applyAction`. The cache already handles the edits. - **Keep one source of truth.** Do not copy OSDK data into Redux, TanStack Query, or component state. Copies miss optimistic updates and action edits. - **Declare function dependencies.** Prefer `dependsOn` and `dependsOnObjects` over invalidating functions by hand. - **Use the devtools.** The [Cache panel](https://palantir.github.io/osdk-ts/devtools/cache.md) shows entries, hits, and misses in a running app. # Loading and errors Source: https://palantir.github.io/osdk-ts/concepts/loading-and-errors > Render @osdk/react hooks correctly while data loads, refreshes, or fails, and narrow errors to PalantirApiError and ActionValidationError. {/* cspell:ignore refetched refetches */} `@osdk/react` hooks can return data and report loading at the same time. This page shows the loading pattern that avoids flashing UI, the error shape of each hook, and how to turn an error into a message the user can act on. ## Loading is not the same as empty `isLoading` means a request for the hook's data is in flight. It does not mean `data` is missing. The cache serves what it has and refreshes in the background, so `isLoading` is `true` with data present when: - The component mounts onto data that another component already cached. - An action edits an object and a list must refetch to decide whether the object still belongs in it. - You call `refetch`, or something invalidates the entry. - An optimistic update is applied to a list. The states you can see are: | `data` | `isLoading` | Meaning | Render | | --- | --- | --- | --- | | `undefined` | `true` | First load, nothing cached. | A placeholder or skeleton. | | Present | `true` | Refreshing cached data. | The data, with a small refreshing indicator. | | Present | `false` | Up to date. | The data. | | `undefined` | `false` | The hook is disabled with `enabled: false`. | An empty state. | | `undefined` | `true` or `false` | The first load failed and `error` is set. On `useOsdkObjects` and `useObjectSet`, `isLoading` stays `true`. | The error. | See [Caching and reactivity](https://palantir.github.io/osdk-ts/concepts/caching.md) for when hooks refetch. ## Keep rendering while loading Do not return early on `isLoading`. An early return replaces the content with a spinner every time the cache refreshes, which makes the page flash and resets scroll position and focus. The only early return that is safe is the initial state, when there is no data yet: ```tsx title="src/EmployeeList.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function EmployeeList() { const { data, isLoading, error, refetch, fetchMore } = useOsdkObjects( Employee, { where: { department: "Engineering" }, orderBy: { fullName: "asc" } }, ); if (data == null && isLoading && error == null) { return

    Loading employees…

    ; } return (

    Engineering

    {isLoading && Refreshing…}
    {error != null && (

    Could not load employees: {error.message}

    )}
      {data?.map(employee => (
    • {employee.fullName}
    • ))}
    {fetchMore != null && ( )}
    ); } ``` The component checks `error` separately from `data`. On `useOsdkObjects` and `useObjectSet`, a refresh can fail after earlier data loaded, so both can be set at once. `useOsdkFunction` and `useOsdkAggregation` clear `data` on failure, and `useLinks` returns an empty `links` array. > [!WARNING] > Do not write `if (isLoading) return `. Use `if (data == null && isLoading && error == null)` for the initial load, and render an inline indicator for refreshes. ## Loading and error fields by hook The hooks do not all use the same field names. Check this table before you destructure: | Hook | Data | Loading | Error | Retry | | --- | --- | --- | --- | --- | | `useOsdkObjects` | `data` | `isLoading` | `error: Error \| undefined` | `refetch()` | | `useObjectSet` | `data` | `isLoading` | `error: Error \| undefined` | `refetch()` | | `useOsdkObject` | `object` | `isLoading` | `error: Error \| undefined` | None | | `useLinks` | `links` | `isLoading` | `error: Error \| undefined` | None | | `useOsdkAggregation` | `data` | `isLoading` | `error: Error \| undefined` | `refetch()` | | `useOsdkFunction` | `data` | `isLoading` | `error: Error \| undefined` | `refetch()` | | `useOsdkAction` | `data` | `isPending`, `isValidating` | `error: { actionValidation?, unknown? } \| undefined` | Call `applyAction` again | | `useOsdkMetadata` | `metadata` | `loading` | `error: string \| undefined` | None | Details that differ between hooks: - **`refetch` scope.** On `useOsdkObjects`, `useObjectSet`, and `useOsdkAggregation`, `refetch` invalidates the whole object type, so every cached object, list, link, aggregation, and `dependsOn` function for that type refetches. On `useOsdkFunction`, it refetches only that function call with those parameters. To refetch more narrowly, use the methods in [Cache invalidation](https://palantir.github.io/osdk-ts/react/cache-invalidation.md). - **`useOsdkObject`.** `isLoading` is `false` as soon as `error` is set. - **`useObjectSet`.** When the object set changes, `data` keeps the last loaded result until the new set loads. - **`useOsdkFunction`.** `isLoading` is `true` only while a request is in flight, so the first render can report `isLoading: false` with no data. Treat `data === undefined && error == null` as the initial state, or check `lastUpdated === 0`. - **`useOsdkMetadata`.** It uses `loading`, not `isLoading`, and `error` is the error's message as a string, not an `Error`. It does not retry after a failure. - **Disabled hooks.** With `enabled: false` (or `false` as the last argument to `useOsdkObject`), `isLoading` is `false` and no request is sent. ## Narrow API errors Errors from Foundry are instances of `PalantirApiError`, which `@osdk/client` exports. `useOsdkObjects`, `useObjectSet`, `useOsdkObject`, and `useOsdkFunction` pass it through, and type `error` as `Error`, so narrow it with `instanceof`. `useOsdkAggregation` and `useLinks` replace it with a generic `Error`: ```tsx title="src/describeError.ts" import { PalantirApiError } from "@osdk/client"; export function describeError(error: Error): string { if (!(error instanceof PalantirApiError)) { return error.message; } if (error.statusCode === 401) { return "Your session has expired. Sign in again."; } if (error.errorCode === "PERMISSION_DENIED" || error.statusCode === 403) { return "You do not have access to this data."; } if (error.errorCode === "NOT_FOUND") { return "This item no longer exists, or you cannot see it."; } return error.message; } ``` | Field | Type | Description | | --- | --- | --- | | `message` | `string` | The server's message, or `Failed to fetch `. | | `errorCode` | `string \| undefined` | The error category, such as `PERMISSION_DENIED`, `NOT_FOUND`, `INVALID_ARGUMENT`, `CONFLICT`, or `TIMEOUT`. | | `errorName` | `string \| undefined` | The specific error, such as `ObjectNotFound`. | | `errorDescription` | `string \| undefined` | A longer description of the error. | | `statusCode` | `number \| undefined` | The HTTP status code. | | `errorInstanceId` | `string \| undefined` | An ID for this occurrence. Include it when you report a problem to your Foundry administrator. | | `parameters` | `unknown` | Error-specific details, such as the object type that was not found. | Some errors carry only a message: - When a request fails before reaching Foundry, or the response is not JSON, the error is a `PalantirApiError` with no `errorCode` or `errorName`, and the original error on `cause`. `statusCode` is set if a response arrived. - `useOsdkObject(Employee, id)` for an object that does not exist, or that you cannot see, reports a `PalantirApiError` with the message `Object not found: ` and no `errorCode` or `statusCode`. The client retries requests that fail with `429` or `503` up to three times, with exponential backoff, before the error reaches your hook. ## Handle action errors `useOsdkAction` splits errors into two kinds: | Field | Set when | Type | | --- | --- | --- | | `error.actionValidation` | The server ran the action's validation and it failed: a submission criterion or a parameter constraint was not met. | `ActionValidationError` | | `error.unknown` | Anything else, such as a network failure, a permission error, or a server error. | `unknown` | `applyAction` also rethrows the error, so always await it in `try`/`catch` or attach `.catch`. Otherwise a failed action becomes an unhandled promise rejection: ```tsx title="src/MoveEmployeeButton.tsx" import { type Employee, modifyEmployee } from "@my-app/sdk"; import { ActionValidationError } from "@osdk/client"; import { useOsdkAction } from "@osdk/react"; import { useState } from "react"; export function MoveEmployeeButton( { employee }: { employee: Employee.OsdkInstance }, ) { const { applyAction, isPending } = useOsdkAction(modifyEmployee); const [message, setMessage] = useState(); async function handleClick() { setMessage(undefined); try { await applyAction({ employee, primary_office_id: "nyc-1" }); } catch (e) { setMessage( e instanceof ActionValidationError ? validationMessage(e) : "Could not move the employee. Try again.", ); } } return (
    {message != null &&

    {message}

    }
    ); } function validationMessage(error: ActionValidationError): string { const criteria = error.validation.submissionCriteria .filter(c => c.result === "INVALID") .flatMap(c => c.configuredFailureMessage ?? []); const parameters = Object.entries(error.validation.parameters) .filter(([, p]) => p.result === "INVALID") .map(([id]) => id); if (criteria.length > 0) { return criteria.join(" "); } if (parameters.length > 0) { return `Check these fields: ${parameters.join(", ")}.`; } return "The action is not valid."; } ``` ### `.validation`, not `.message` `ActionValidationError.message` is `"Validation Error: "` followed by the validation response as JSON. It is useful in logs, not in UI. Read `.validation` instead: | Field | Type | Description | | --- | --- | --- | | `validation.result` | `"VALID" \| "INVALID"` | The overall result. | | `validation.submissionCriteria` | Array of `{ result, configuredFailureMessage? }` | One entry per submission criterion. `configuredFailureMessage` is the message the action's author wrote. | | `validation.parameters` | Record of parameter ID to `{ result, required, evaluatedConstraints }` | Per-parameter results. Use it to highlight form fields. | ### Validate before you apply `validateAction` runs the same validation without applying the action. An invalid result does not throw: it resolves to the validation response, which the hook also stores as `validationResult`. `validateAction` throws only for other failures, and resolves to `undefined` if a newer validation or an `applyAction` call supersedes it. ```tsx const { validateAction } = useOsdkAction(modifyEmployee); const result = await validateAction({ employee, primary_office_id: "nyc-1" }); const invalidFields = result?.result === "INVALID" ? Object.entries(result.parameters) .filter(([, p]) => p.result === "INVALID") .map(([id]) => id) : []; ``` The hook clears `error` when you call `applyAction` or `validateAction` again. ## Related - [Actions](https://palantir.github.io/osdk-ts/react/actions.md): apply, validate, and batch actions. - [Troubleshooting](https://palantir.github.io/osdk-ts/troubleshooting.md): fixes for setup, version, and auth errors. # The Ontology and your SDK Source: https://palantir.github.io/osdk-ts/concepts/ontology > How object types, links, actions, functions, interfaces, and object sets map to the generated SDK and to Osdk.Instance values in TypeScript. Related Palantir Foundry documentation: - [Ontology](https://www.palantir.com/docs/foundry/ontology/overview) - [Object types](https://www.palantir.com/docs/foundry/object-link-types/object-types-overview) Your generated SDK is a typed description of part of a Foundry Ontology. This page explains what each Ontology concept becomes in TypeScript, so you can read the SDK and the values it returns. ## Ontology concepts | Concept | What it is | In the generated SDK | How you use it | | --- | --- | --- | --- | | Object type | A schema for real-world entities, such as employees. | A definition, `Employee`, plus the namespace types `Employee.Props` and `Employee.OsdkInstance`. | `client(Employee)` returns an object set of every `Employee`. | | Property | A typed field on an object type. | A key in `Employee.Props`, typed from the property's base type. | Read it on an instance: `employee.fullName`. | | Primary key | The property that uniquely identifies an object. | `primaryKeyApiName` and `primaryKeyType` on the definition. | `client(Employee).fetchOne(12345)`, or `employee.$primaryKey`. | | Link type | A relationship between two object types. | Entries in `Employee.Links`. | `employee.$link.lead` for a single link, `employee.$link.reports` for many. | | Action type | A transaction that edits objects. | A definition, `modifyEmployee`. | `client(modifyEmployee).applyAction({ ... })`. | | Function (query) | Server-side logic that reads the Ontology and returns a value. | A definition, such as `getEmployeeMetrics`. | `client(getEmployeeMetrics).executeFunction({ ... })`. | | Interface | A shared shape that several object types implement. | A definition with its own properties. | `client(MyInterface).fetchPage()`, then `instance.$as(Employee)`. | | Object set | A lazy, composable query over objects. | `Employee.ObjectSet`. | `client(Employee).where({ ... }).pivotTo("lead")`. | The generated package does not contain a client. It exports definitions, which are plain metadata. You pass a definition to a client created with `createClient` from `@osdk/client`, and the client does the work: ```ts title="src/example.ts" import { Employee, getEmployeeMetrics, modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ department: "Engineering" }) .fetchPage({ $pageSize: 20 }); const employee = await client(Employee).fetchOne(12345); await client(modifyEmployee).applyAction({ employee, primary_office_id: "nyc-1", }); const metrics = await client(getEmployeeMetrics).executeFunction({ departmentId: "engineering", }); ``` See [Create a client](https://palantir.github.io/osdk-ts/client.md) to set up `client`. ## Why `client(Employee)` The SDK separates the code that knows your Ontology (the generated package) from the code that talks to Foundry (`@osdk/client`). That design has practical effects: - **Smaller bundles.** Each definition is a small named export. Bundlers drop the ones you do not import, so the SDK's cost scales with what you use, not with the size of the Ontology. - **One runtime.** Several generated SDKs share the same `@osdk/client` code instead of each shipping its own. - **Fixes without regenerating.** A bug fix in `@osdk/client` reaches you through a dependency update. You do not need to regenerate the SDK. If you want autocomplete across the whole Ontology, import the namespace exports. Tree-shaking still removes what you do not reference: ```ts import { $Objects } from "@my-app/sdk"; import { client } from "./client"; const page = await client($Objects.Employee).fetchPage(); ``` The generated package also exports `$Actions`, `$Queries`, and `$Interfaces`, and `$ontologyRid` when the SDK was generated for a single Foundry environment. ## Object instances Every object you fetch, from `@osdk/client` or from `@osdk/react` hooks, is an `Osdk.Instance`. The generated alias `Employee.OsdkInstance` is the same type: ```ts import type { Employee } from "@my-app/sdk"; import type { Osdk } from "@osdk/client"; type A = Employee.OsdkInstance; type B = Osdk.Instance; ``` ### Metadata fields Fields that start with `$` describe the object rather than hold Ontology data: | Field | Type | Description | | --- | --- | --- | | `$apiName` | `string` | API name of the type you queried. For an interface query, this is the interface's API name. | | `$objectType` | `string` | API name of the concrete object type, even when you queried an interface. | | `$primaryKey` | Primary key type | The object's primary key value. Use it as a React `key`. | | `$title` | `string \| undefined` | Value of the object type's title property. | | `$objectSpecifier` | `ObjectSpecifier` | A string that identifies the object by type and primary key. | | `$link` | Links object | Accessors for the object's links. | | `$as` | Function | Converts between an interface and an object type that implements it. | | `$clone` | Function | Returns a copy of the instance with updated properties. | | `$rid` | `string` | The object's RID. Present only when you request it with `$includeRid: true`. | ### Instances are immutable Instances are frozen, and their properties are `readonly`. To get a changed copy, call `$clone`: ```ts const renamed = employee.$clone({ fullName: "Ada Lovelace" }); ``` `$clone` throws if the update changes the primary key. It does not write anything to Foundry. Use it to build optimistic state for an action, as shown in [Optimistic updates](https://palantir.github.io/osdk-ts/react/optimistic-updates.md). To change data, apply an action. ### Links A single-valued link returns an accessor with `fetchOne`. A many-valued link returns an object set: ```ts const lead = await employee.$link.lead.fetchOne(); const reports = await employee.$link.reports.fetchPage({ $pageSize: 50 }); ``` In React, use [`useLinks`](https://palantir.github.io/osdk-ts/react/links.md) instead so linked objects share the cache. ## Property value types Most properties are optional on the instance (`T | undefined`). Only the primary key and properties the Ontology marks as required are always present. | Ontology type | TypeScript value | Notes | | --- | --- | --- | | `string` | `string` | | | `boolean` | `boolean` | | | `integer`, `short`, `byte`, `float`, `double` | `number` | | | `long` | `string` | Strings keep 64-bit precision that `number` cannot hold. | | `decimal` | `string` | Strings keep arbitrary precision. | | `date` | `string` | ISO 8601 date, such as `"2024-03-15"`. | | `timestamp` | `string` | ISO 8601 date and time, such as `"2024-03-15T09:30:00Z"`. | | `geopoint` | `GeoJSON.Point` | | | `geoshape` | `GeoJSON.GeoJSON` | | | `attachment` | `Attachment` | Has `rid`, `fetchMetadata()`, and `fetchContents()`, which resolves to a `Response`. | | `mediaReference` | `Media` | Has `fetchMetadata()`, `fetchContents()`, and `getMediaReference()`. | | `cipherText` | `CipherText` | Call `decrypt()` to get the plaintext. | | `marking` | `string` | | | `vector` | `number[]` | | | Numeric, string, and sensor time series | `TimeSeriesProperty` | Has `getFirstPoint()`, `getLastPoint()`, and `getAllPoints()`. | | `geotimeSeriesReference` | `GeotimeSeriesProperty` | | ### Dates and timestamps The SDK returns dates and timestamps as ISO 8601 strings instead of `Date` objects or a date library's types. This keeps a large date library out of your bundle, lets you use the date library you already have, and avoids parsing values you never read. Parse a value when you need date math: ```ts const startDate = employee.startDate != null ? new Date(employee.startDate) : undefined; ``` To send a date-only value, `@osdk/client` exports helpers that format a `Date` as `YYYY-MM-DD`: ```ts import { extractDateInLocalTime, extractDateInUTC } from "@osdk/client"; extractDateInLocalTime(new Date()); // "2024-03-15" in the user's time zone extractDateInUTC(new Date()); // "2024-03-15" in UTC ``` `extractDate` returns the date part of an ISO 8601 timestamp string. ## Object sets An object set describes which objects you want. Building one does not send a request; only fetching does: ```ts import { Employee } from "@my-app/sdk"; import { client } from "./client"; const engineers = client(Employee).where({ department: "Engineering" }); const theirLeads = engineers.pivotTo("lead"); const page = await theirLeads.fetchPage({ $pageSize: 20 }); ``` | Method | Returns | Description | | --- | --- | --- | | `where(clause)` | Object set | Filters the set. | | `union(...sets)`, `intersect(...sets)`, `subtract(...sets)` | Object set | Combines sets of the same type. | | `pivotTo(link)` | Object set | Follows a link to the linked type. | | `withProperties(...)` | Object set | Adds derived properties computed on the server. | | `fetchPage(options)` | `Promise` of a page | Fetches one page: `data`, `nextPageToken`, and `totalCount`. | | `fetchOne(primaryKey)` | `Promise` of an instance | Fetches one object. Object types only. | | `asyncIter()` | Async iterator | Iterates over every object across pages. | | `aggregate(options)` | `Promise` of results | Runs an aggregation on the server. | | `subscribe(listener)` | Subscription | Receives changes to the set over a WebSocket. | In React, pass the same filters to [`useOsdkObjects`](https://palantir.github.io/osdk-ts/react/objects.md) or build a set with [`useObjectSet`](https://palantir.github.io/osdk-ts/react/object-sets.md). ## Interfaces An interface lets you query several object types through one shape. Instances from an interface query expose the interface's properties. `$objectType` tells you the concrete type, and `$as` converts to it: ```ts import { Employee, Worker } from "@my-app/sdk"; import { client } from "./client"; const { data } = await client(Worker).fetchPage(); for (const worker of data) { if (worker.$objectType === "Employee") { const employee = worker.$as(Employee); console.log(employee.fullName); } } ``` ## Related - [Caching and reactivity](https://palantir.github.io/osdk-ts/concepts/caching.md): how `@osdk/react` stores these instances. - [Objects](https://palantir.github.io/osdk-ts/react/objects.md): query objects in React. - [Actions](https://palantir.github.io/osdk-ts/react/actions.md): edit objects. # Develop on Foundry branches Source: https://palantir.github.io/osdk-ts/deploy/branches > Point your OSDK app at a Foundry global branch with osdk branch sync, @osdk/vite-plugin-branch, and the beta UNSTABLE_DO_NOT_USE_BRANCH client option. Related Palantir Foundry documentation: - [Global Branching](https://www.palantir.com/docs/foundry/global-branching/overview) - [Branching applications](https://www.palantir.com/docs/foundry/developer-console/branching-integration) {/* cspell:ignore postinstall */} Develop against Ontology changes on a Foundry global branch before they merge, using the SDK versions generated for that branch and sending every request to it. Three pieces work together: `osdk branch sync` installs the branch's SDK, `@osdk/vite-plugin-branch` tells the client which branch you are on, and the client sends that branch with its requests. > [!WARNING] > Branch support is beta. The client option is named `UNSTABLE_DO_NOT_USE_BRANCH`, and `@osdk/create-app` only sets it up behind `--unstableFeatures`. Names and behavior can change in any release. ## How it works | Piece | What it does | | --- | --- | | Branched SDK versions | An SDK generated on a branch is published as a prerelease under the npm dist tag `-latest`. Its `package.json` records the branch RID in `osdk.branch`, and the SDK exports it as `$branch`. | | `osdk branch sync` | Reads your git branch and installs the matching SDK version: the branch's prerelease on a branch, the stable `latest` on `main`. | | `@osdk/vite-plugin-branch` | Injects the current branch into your app's HTML, and reloads the page when you switch git branches. | | `@osdk/client` | Reads the injected branch when you create the client, then reads and writes objects, actions, and queries on that branch. | Both the CLI and the plugin take the branch from `git branch --show-current`, so use the same name for your git branch and the Foundry branch you develop against. ## Set up a new app Pass `--unstableFeatures` to `@osdk/create-app`: ```npm npx @osdk/create-app@latest my-osdk-app --unstableFeatures ``` For an app with an SDK, this adds three things to the generated project: - `@osdk/cli` as a dev dependency. - A `postinstall` script that runs `./node_modules/.bin/osdk branch sync`, so every install picks the SDK for your branch. - `@osdk/vite-plugin-branch`, registered in `vite.config.ts` for the React and Vue 2.x templates. The Expo template instead passes `UNSTABLE_DO_NOT_USE_BRANCH: $branch` to `createClient`. ## Add to an existing app ### Install the packages Install `@osdk/vite-plugin-branch` at the same version as `@osdk/client`. It supports Vite 6, 7, and 8. ```npm npm install @osdk/vite-plugin-branch npm install --save-dev @osdk/cli ``` ### Sync the SDK on install ```json title="package.json" { "scripts": { "postinstall": "osdk branch sync" } } ``` ### Register the Vite plugin ```ts title="vite.config.ts" import { branchPlugin } from "@osdk/vite-plugin-branch"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig(({ mode }) => ({ plugins: [react(), branchPlugin()], define: { "process.env.NODE_ENV": JSON.stringify(mode), }, })); ``` `branchPlugin()` takes no options. ## Install the branch's SDK ```sh npx osdk branch sync ``` For each dependency in your root `package.json` whose installed `package.json` has an `osdk` block, the command reads the package's npm dist tags and picks a target: | You are on | Installed SDK | Target | | --- | --- | --- | | A branch | Any | The `-latest` dist tag, if one is published. Otherwise the SDK is left alone. | | `main`, `master`, or a detached `HEAD` | Generated on a branch | The `latest` dist tag. | | `main`, `master`, or a detached `HEAD` | Generated on main | Left alone. | It installs every SDK whose declared version differs from its target in one `npm install @ --save-exact`, so your `package.json` pins exact versions. It always runs `npm`, and only looks at `dependencies`, not `devDependencies`. | Option | Description | | --- | --- | | `--branchName ` | Sync to this branch instead of the current git branch. | | `--packageName ` | Sync only this SDK. | | `--dryRun` | Print `Would install @` lines without installing. | The command reads dist tags from your registry, so it needs the same `.npmrc` and `FOUNDRY_TOKEN` as a normal install. A `401` from the registry fails with `Not authorized to read `. See [Installation](https://palantir.github.io/osdk-ts/installation.md). ## Inject the branch with Vite `branchPlugin()` adds a meta tag to the `` of your HTML: ```html ``` It decides the value in this order: | Condition | Value | | --- | --- | | `FOUNDRY_BRANCH_RID` is set in the environment or a `.env` file | That value. | | The git branch is `main` or `master` | Empty, which means the default branch. | | Any other git branch | The branch name. | | No branch: detached `HEAD`, or not a git repository, during `vite dev` | `ri.branch..branch.unknown`. Requests fail instead of silently reading the default branch. | | No branch during `vite build` | Empty, which means the default branch. | `FOUNDRY_BRANCH_RID` has no `VITE_` prefix, so Vite does not expose it to your client code. Use it to pin a branch RID, or to build for a branch in CI where HEAD is detached: ```sh FOUNDRY_BRANCH_RID=ri.branch..branch. npm run build ``` The dev server logs the branch it uses, such as `Using Foundry branch "my-feature".` While it runs, it checks the git branch every second and reloads open pages when it changes, so you do not restart the server. Reloading needs HMR, which is on by default. A production build fixes the branch at build time. Rebuild to deploy for another branch. ## Choose the branch in the client `createClient` resolves the branch once, when you create the client: 1. The `UNSTABLE_DO_NOT_USE_BRANCH` option, when you pass it. `null` forces the default branch. 2. The `foundryBranchRid` query parameter in the page URL, such as `?foundryBranchRid=ri.branch..branch.`. This lets a page that embeds your app in an iframe choose the branch. 3. The `osdk-foundry-branch-rid` meta tag from the Vite plugin. A blank query parameter or meta tag is skipped, and a blank `UNSTABLE_DO_NOT_USE_BRANCH` acts like `null`. Outside a browser, only the option applies. | Option | Type | Default | Description | | --- | --- | --- | --- | | `UNSTABLE_DO_NOT_USE_BRANCH` | `string \| null` | `undefined` | Beta. The branch for every request. `undefined` reads the query parameter, then the meta tag. `null` ignores both and uses the default branch. | To pin a client to the branch your SDK was generated on, pass the SDK's `$branch` export. It is `undefined` for SDKs generated on main, which keeps the default lookup: ```ts title="src/client.ts" import { $branch, $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const client = createClient(foundryUrl, $ontologyRid, auth, { UNSTABLE_DO_NOT_USE_BRANCH: $branch, }); ``` In Node.js scripts there is no meta tag, so pass the branch explicitly: ```ts title="scripts/client.ts" import { $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; const token = process.env.FOUNDRY_TOKEN; if (token == null) { throw new Error("Set FOUNDRY_TOKEN"); } export const client = createClient( "https://example.palantirfoundry.com", $ontologyRid, () => Promise.resolve(token), { UNSTABLE_DO_NOT_USE_BRANCH: process.env.FOUNDRY_BRANCH_RID ?? null }, ); ``` ## Generate an SDK on a branch To generate SDK files locally from a branch's Ontology, pass the branch RID to `osdk unstable typescript generate --branch`. See [Generate an SDK](https://palantir.github.io/osdk-ts/deploy/generate-sdk.md#generate-locally). # CLI reference Source: https://palantir.github.io/osdk-ts/deploy/cli > Every @osdk/cli command and flag for deploying sites and widget sets, managing versions, syncing branched SDKs, and generating SDKs locally. Related Palantir Foundry documentation: - [Application hosting](https://www.palantir.com/docs/foundry/developer-console/deploy-custom-application-on-foundry) {/* cspell:ignore widgetset */} `@osdk/cli` deploys your app to Foundry website hosting, manages its versions, publishes widget sets, keeps branched SDKs in sync, and generates SDKs from an Ontology. This page lists every command and flag. ## Run the CLI Run it with `npx`, or install it as a dev dependency to get the `osdk` binary: ```sh npx @osdk/cli@latest site deploy ``` ```npm npm install --save-dev @osdk/cli ``` ```sh npx osdk site deploy ``` | Command | Description | | --- | --- | | [`osdk site deploy`](#osdk-site-deploy) | Upload a new version of your site and, by default, make it live. | | [`osdk site version`](#osdk-site-version) | List, get, set, unset, and delete site versions. | | [`osdk widgetset deploy`](#osdk-widgetset-deploy) | Publish a new widget set version. | | [`osdk widgetset version`](#osdk-widgetset-version) | List, inspect, and delete widget set versions. | | [`osdk branch sync`](#osdk-branch-sync) | Install the SDK versions published for your current branch. | | [`osdk unstable typescript generate`](#osdk-unstable-typescript-generate) | Generate SDK source files from an Ontology. Unstable. | | [`osdk unstable auth login`](#osdk-unstable-auth-login) | Test an OAuth sign-in from the terminal. Unstable. | `osdk experimental` is an alias for `osdk unstable`. Commands under it can change or be removed in any release. ## Global options | Option | Type | Description | | --- | --- | --- | | `--verbose`, `-v` | count | Debug logging. Pass `-vv` for trace logging, which includes every HTTP request. | | `--help` | boolean | Print the commands and options available at that level, such as `osdk site version --help`. | Each option also accepts its kebab-case form: `--foundryUrl` and `--foundry-url` are the same option. ## Configuration Options come from three places. The first one set wins: 1. The command-line flag. 2. An environment variable named `OSDK_` plus the option in upper snake case, such as `OSDK_FOUNDRY_URL`, `OSDK_APPLICATION`, or `OSDK_DIRECTORY`. 3. `foundry.config.json`, for the options it covers. The CLI looks for `foundry.config.json` in the current directory and then each parent, and uses the first one it finds. A file holds either a `site` block or a `widgetSet` block, not both. The full schema is in [Host on Foundry](https://palantir.github.io/osdk-ts/deploy/hosting.md#foundryconfigjson). ### Tokens Every `site` and `widgetset` command needs a Foundry token. The CLI uses the first of: 1. `--token ` 2. `--tokenFile `, a file whose contents are the token 3. The `FOUNDRY_TOKEN` environment variable 4. The `FOUNDRY_SDK_AUTH_TOKEN` environment variable, which is deprecated and logs a warning `--token` and `--tokenFile` cannot be used together. The token must be a JWT. Without one, the command exits with `No token found.` ```sh export FOUNDRY_TOKEN= npx @osdk/cli@latest site version list ``` ## `osdk site` Manages the website hosted for a Developer Console application. Run it with a subcommand: `deploy` or `version`. These options apply to every `site` subcommand: | Option | Type | Default | Description | | --- | --- | --- | --- | | `--application` | `string` | `site.application` | The application RID, such as `ri.third-party-applications.main.application.`. Required. | | `--foundryUrl` | `string` | `foundryUrl` | The Foundry stack URL. Must start with `https://`. Required. | | `--token` | `string` | | A Foundry token. Conflicts with `--tokenFile`. | | `--tokenFile` | `string` | | A path to a file containing a Foundry token. Conflicts with `--token`. | ### `osdk site deploy` Zips the contents of a directory, uploads it as a new site version, and makes that version live. ```sh npx @osdk/cli@latest site deploy --directory ./dist --version 1.2.0 ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `--directory` | `string` | `site.directory` | The directory to upload, usually your build output. Required. Everything in it is zipped, with the directory itself as the root. | | `--version` | `string` | | The version to create. Must be valid SemVer. Conflicts with `--autoVersion`; when `site.autoVersion` is set in the config file, `--version` overrides it. | | `--autoVersion` | `"git-describe" \| "package-json"` | `site.autoVersion.type` | Compute the version instead of passing `--version`. See [Automatic versions](https://palantir.github.io/osdk-ts/deploy/hosting.md#automatic-versions). | | `--gitTagPrefix` | `string` | `site.autoVersion.tagPrefix` | With `git-describe`, match only tags that start with this prefix, and strip it from the version. Without it, every tag matches and a leading `v` is stripped. Only valid with `git-describe`. | | `--uploadOnly` | `boolean` | `site.uploadOnly`, else `false` | Upload the version without making it live. The CLI prints a preview link instead. | | `--snapshot` | `boolean` | `false` | Upload a snapshot version with automatic retention. The CLI never makes a snapshot live. Cannot be combined with `--uploadOnly`. | | `--snapshotId` | `string` | | An alias to attach to the snapshot version. Requires `--snapshot`. | You must pass `--version` or `--autoVersion`, or set `site.autoVersion` in `foundry.config.json`. When the deploy succeeds, the CLI prints the live URL, `https://`. With `--uploadOnly`, it prints `https:///.system/preview?previewVersion=` instead. ### `osdk site version` Manages existing versions. Run it with a subcommand. | Command | Description | | --- | --- | | `osdk site version list` | Lists every version that is valid SemVer, newest first, and marks the live one `(deployed)`. | | `osdk site version get` | Prints the live version, or `No live site version set`. | | `osdk site version set ` | Makes `` live. Use it to roll back or to publish a version uploaded with `--uploadOnly`. | | `osdk site version unset` | Clears the live version after a confirmation prompt. The site is unreachable until you set a version again. | | `osdk site version delete ` | Deletes a version after a confirmation prompt. You cannot delete the live version, and deletion cannot be undone. | | Option | Applies to | Type | Description | | --- | --- | --- | --- | | `--yes`, `-y` | `unset`, `delete` | `boolean` | Skip the confirmation prompt. | ```sh npx @osdk/cli@latest site version set 1.1.0 npx @osdk/cli@latest site version delete 1.0.0 --yes ``` ### Site errors The CLI turns Foundry errors into these messages: | Message | Cause | What to do | | --- | --- | --- | | `The site version already exists` | A version with that number was uploaded before. | Use a new version. Versions are immutable. | | `The site version is invalid and must be a valid SemVer string` | The version is not SemVer. | Fix `--version`, or the tag or `package.json` version that `--autoVersion` reads. | | `The site contains too many versions` | The application reached its version limit, shown in the message. | Delete old versions with `osdk site version delete`. | | `The .zip file contains too many files` | The build output has more files than the limit. | Reduce the number of files in the build. | | `The .zip file contains a file ... that is too large` | One file exceeds the size limit. | Shrink or split that file. | | `The website version is being scanned for vulnerabilities and cannot be deployed yet` | Foundry is still scanning the upload. | Deploy with `--uploadOnly`, then make the version live after the scan, with `osdk site version set` or from **Website hosting** in Developer Console. | | `The site version to delete is live and cannot be deleted` | You tried to delete the live version. | Set another version live first. | | `The site version could not be found` | The version does not exist. | Check `osdk site version list`. | A `401` means the token is invalid or expired; a `403` means it lacks the permission or scopes for the request. ## `osdk widgetset` Publishes and manages widget sets for Workshop custom widgets. Run it with a subcommand: `deploy` or `version`. [Publish a widget set](https://palantir.github.io/osdk-ts/widgets/publish.md) covers the build and the manifest. These options apply to every `widgetset` subcommand: | Option | Type | Default | Description | | --- | --- | --- | --- | | `--widgetSet` | `string` | `widgetSet.rid` | The widget set RID. Required. | | `--foundryUrl` | `string` | `foundryUrl` | The Foundry stack URL. Must start with `https://`. Required. | | `--token` | `string` | | A Foundry token. Conflicts with `--tokenFile`. | | `--tokenFile` | `string` | | A path to a file containing a Foundry token. Conflicts with `--token`. | ### `osdk widgetset deploy` Zips a directory and publishes it as a new widget set version. The version comes from the manifest at `.palantir/widgets.config.json` inside the directory; there is no version flag. | Option | Type | Default | Description | | --- | --- | --- | --- | | `--directory` | `string` | `widgetSet.directory` | The directory to upload. Required. | | `--repository` | `string` | `widgetSet.repository` | A code repository RID to publish through. The repository must be authorized to publish the widget set. | | `--branchName` | `string` | The current git branch | The git branch to publish from. | ### `osdk widgetset version` | Command | Description | | --- | --- | | `osdk widgetset version list` | Lists published versions for the current git branch. Accepts `--branchName`. | | `osdk widgetset version info ` | Prints the details of one version. | | `osdk widgetset version delete ` | Deletes a version after a confirmation prompt. `--yes` or `-y` skips the prompt. | ## `osdk branch sync` Installs the version of each generated SDK that matches your current branch: the newest prerelease published for that branch, or, on `main`, the stable `latest` release for any SDK currently installed from a branch. [Develop on Foundry branches](https://palantir.github.io/osdk-ts/deploy/branches.md) explains the workflow. ```sh npx @osdk/cli@latest branch sync ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `--branchName` | `string` | The current git branch | The branch to sync to, used as given. Without it, the current git branch is used, and `main`, `master`, or a detached `HEAD` mean the default branch. | | `--packageName` | `string` | | Sync only this SDK instead of every SDK found. | | `--dryRun` | `boolean` | `false` | Print what would be installed without changing anything. | `osdk unstable branch sync` is the same command under its earlier name. ## `osdk unstable typescript generate` Generates SDK source files from an Ontology, either by signing in to Foundry or from a saved Ontology metadata file. [Generate an SDK](https://palantir.github.io/osdk-ts/deploy/generate-sdk.md#generate-locally) shows when to use it. ```sh npx @osdk/cli@latest unstable typescript generate \ --foundryUrl https://example.palantirfoundry.com \ --clientId \ --outDir src/generatedNoCheck \ --version dev ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `--outDir` | `string` | | Where to write the generated files. Required. | | `--version` | `string` | | The SDK version: `dev` or a SemVer string. Written into the generated SDK's user agent string, and used as the package version with `--asPackage`. Required. | | `--foundryUrl` | `string` | | Load the Ontology from this stack. Requires `--clientId`. Alias: `--stack`. | | `--clientId` | `string` | | The OAuth client ID to sign in with. Requires `--foundryUrl`. | | `--ontologyRid` | `string` | | With `--foundryUrl`, use this Ontology. Needed when the client can see more than one. | | `--branch` | `string` | | With `--foundryUrl`, the Foundry branch RID to load the Ontology from. | | `--ontologyWritePath` | `string` | | With `--foundryUrl`, also save the loaded Ontology metadata as JSON at this path. | | `--ontologyPath` | `string` | | Generate from an Ontology metadata JSON file instead of Foundry. Conflicts with `--foundryUrl` and `--clientId`. | | `--packageType` | `"commonjs" \| "module"` | `"commonjs"` | The module format of the project you generate into. | | `--clean` | `boolean` | | Delete `--outDir` before generating. | | `--skipPackageJsonUpdate` | `boolean` | `false` | Do not add `@osdk/api` and `@osdk/client` to the nearest `package.json`. | | `--externalObjects` | `string` | | Import these object types from another generated SDK instead of generating them, as `ApiName:@scope/package` pairs separated by commas. | | `--externalInterfaces` | `string` | | The same, for interfaces. | | `--experimentalOntologyMetadata` | `boolean` | `false` | Also write the raw Ontology metadata to `experimental/ontology-metadata.json` in `--outDir`. With `--asPackage`, it is also exported as `./experimental/ontology-metadata`. May change or be removed. | | `--asPackage` | `boolean` | | Generate a standalone package with its own `package.json`. Requires `--packageName` and `--beta`. | | `--packageName` | `string` | | The package name when using `--asPackage`. | | `--beta` | `boolean` | | Required with `--asPackage`. | | `--internal` | `boolean` | `false` | For the `osdk-ts` repository only. Writes `workspace:` dependency versions. | Pass either `--ontologyPath`, or `--foundryUrl` and `--clientId`. ## `osdk unstable auth login` Runs the OAuth authorization code flow in your browser, to check that a client ID and redirect URL work. It does not save or print the token. | Option | Type | Description | | --- | --- | --- | | `--foundryUrl` | `string` | The Foundry stack URL. Required. Alias: `--baseUrl`. | | `--clientId` | `string` | The OAuth client ID. Required. Alias: `--applicationId`. | The CLI listens on port 8080 and uses `http://localhost:8080/auth/callback` as the redirect URL, so that URL must be allowed on **OAuth & scopes** in Developer Console and port 8080 must be free. It requests the `offline_access`, `api:read-data`, and `api:use-ontologies-read` scopes. `osdk unstable typescript generate --foundryUrl` uses the same sign-in. # Generate an SDK Source: https://palantir.github.io/osdk-ts/deploy/generate-sdk > Generate your Ontology SDK in Developer Console or locally with osdk unstable typescript generate or @osdk/foundry-sdk-generator, and update it when the Ontology changes. Related Palantir Foundry documentation: - [Developer Console](https://www.palantir.com/docs/foundry/developer-console/overview) {/* cspell:ignore postinstall */} Your generated SDK holds typed definitions for the object types, links, actions, functions, and interfaces your app uses. Generate it in Developer Console and install it from your Foundry npm registry, or generate it yourself from the command line. ## Choose a method | Method | Output | Use it when | | --- | --- | --- | | Developer Console | A versioned npm package in your Foundry registry. | Almost always. Apps from `@osdk/create-app` expect it. | | `osdk unstable typescript generate` | TypeScript source files in a folder of your project. | You want the SDK in your repository, or you work offline from a saved Ontology file. | | `@osdk/foundry-sdk-generator` | A built npm package directory you can pack or publish. | You publish SDK packages from your own pipeline. | ## Generate in Developer Console ### Choose the resources In your application in Developer Console, add the object types, link types, actions, functions, and interfaces your app uses to the application's SDK. Only those resources are generated. ### Generate a version On **SDK versions**, generate a new version with the **npm** package type and the latest generator. The install instructions show the package name, such as `@my-app/sdk`, and your registry URL. ### Install it Point your SDK's npm scope at the Foundry registry in `.npmrc`, then install: ```npm npm install @my-app/sdk@latest ``` [Installation](https://palantir.github.io/osdk-ts/installation.md) covers the `.npmrc` lines, the token, and the other packages you need. ### What the package exports | Export | Description | | --- | --- | | Object types, such as `Employee` | Pass to `client(Employee)` to query. | | Actions, such as `modifyEmployee` | Pass to `client(modifyEmployee).applyAction(...)`. | | Functions and interfaces | Pass to `client(...)` the same way. | | `$ontologyRid` | The Ontology RID, for `createClient`. | | `$branch` | The Foundry branch RID the SDK was generated on, or `undefined` for main. See [Develop on Foundry branches](https://palantir.github.io/osdk-ts/deploy/branches.md). | ## Update the SDK when the Ontology changes The SDK is a snapshot of the Ontology when you generated it. When you add a resource to the SDK, or a property, parameter, or link you use changes: 1. Generate a new version in Developer Console. 2. Install it: ```npm npm install @my-app/sdk@latest ``` 3. Run your type checker. Renamed or removed properties and parameters show up as type errors where your code uses them. The SDK has a peer dependency on the `@osdk/client` version that generated it. If npm reports a peer conflict, align `@osdk/client`, `@osdk/api`, and `@osdk/react` as described in [Version compatibility](https://palantir.github.io/osdk-ts/installation.md#version-compatibility). On a Foundry branch, `osdk branch sync` picks the branch's SDK version instead of `latest`. ## Generate locally `osdk unstable typescript generate` from `@osdk/cli` writes the SDK as TypeScript source files into your project. It is unstable: flags and output can change in any release. **From Foundry** ```sh npx @osdk/cli@latest unstable typescript generate \ --foundryUrl https://example.palantirfoundry.com \ --clientId \ --outDir src/generatedNoCheck \ --version dev \ --packageType module \ --ontologyWritePath ontology.json ``` The CLI opens your browser to sign in, with `http://localhost:8080/auth/callback` as the redirect URL, so allow that URL on **OAuth & scopes** and keep port 8080 free. It generates every object type, action, function, and interface the client can see in the Ontology, except functions that return Ontology edits. If the client can see more than one Ontology, pass `--ontologyRid`. Pass `--branch ` to read a branch's Ontology. `--ontologyWritePath` saves the loaded metadata so you can regenerate later without signing in. **From a saved file** ```sh npx @osdk/cli@latest unstable typescript generate \ --ontologyPath ontology.json \ --outDir src/generatedNoCheck \ --version dev \ --packageType module \ --clean ``` `--ontologyPath` takes an Ontology metadata file written by `--ontologyWritePath`. Import from the generated folder instead of a package: ```ts title="src/client.ts" import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; import { $ontologyRid } from "./generatedNoCheck/index.js"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const client = createClient(foundryUrl, $ontologyRid, auth); ``` Unless you pass `--skipPackageJsonUpdate`, the command also edits the nearest `package.json` above `--outDir`: it adds `@osdk/api` and `@osdk/client` as peer dependencies and `@osdk/api` as a dev dependency, and sets any existing `@osdk/api` and `@osdk/client` entries to the versions the CLI was built with. Install `@osdk/client` as a regular dependency of your app yourself. All flags are in the [CLI reference](https://palantir.github.io/osdk-ts/deploy/cli.md#osdk-unstable-typescript-generate). ## Build a package with `@osdk/foundry-sdk-generator` `@osdk/foundry-sdk-generator` loads the resources you name from Foundry and writes a compiled npm package with ESM, CommonJS, and bundled type definitions. ```sh npx @osdk/foundry-sdk-generator generatePackage \ --authToken "$FOUNDRY_TOKEN" \ --foundryHostname example.palantirfoundry.com \ --ontology ri.ontology.main.ontology. \ --objectTypes Employee Office \ --linkTypes Employee.lead Employee.reports Employee.office Office.occupants \ --actionTypes modifyEmployee \ --interfaceTypes Worker \ --packageName @my-app/sdk \ --packageVersion 0.1.0 \ --outputDir ./out ``` The package is written to `/`, here `./out/@my-app/sdk`, with a `peerDependencies` entry for `@osdk/client`. Pack or publish it from there with npm. | Option | Type | Description | | --- | --- | --- | | `--authToken` | `string` | A Foundry token. Required. | | `--foundryHostname` | `string` | Your stack, such as `example.palantirfoundry.com`. A full `https://` URL also works. Required. | | `--ontology` | `string` | The Ontology RID or API name. | | `--packageName` | `string` | The npm package name. Required. | | `--packageVersion` | `string` | The package version. Must be SemVer. Required. | | `--outputDir` | `string` | The directory to write the package under. Required. | | `--objectTypes` | `string[]` | Object type API names. | | `--linkTypes` | `string[]` | Links to include, as `ObjectTypeApiName.linkApiName`. | | `--actionTypes` | `string[]` | Action type API names. | | `--queryTypes` | `string[]` | Function API names. Add `:` to pin a version, such as `countEmployees:1.2.0`. | | `--interfaceTypes` | `string[]` | Interface API names. | | `--agents` | `string[]` | AIP Agents, as `apiName:version`. | | `--experimentalOntologyMetadata` | `boolean` | Also export the raw metadata at `./experimental/ontology-metadata`. Experimental. | Each list flag takes space-separated values. The generator includes only what you list: an object type's links are left out unless you pass them in `--linkTypes`, and generation fails if a requested resource is missing. # Host on Foundry Source: https://palantir.github.io/osdk-ts/deploy/hosting > Build your OSDK app with Vite and deploy it to Foundry website hosting with osdk site deploy, foundry.config.json, versions, previews, and rollbacks. Related Palantir Foundry documentation: - [Application hosting](https://www.palantir.com/docs/foundry/developer-console/deploy-custom-application-on-foundry) Foundry website hosting serves your app's static build from a subdomain of your Foundry stack. You upload each build as a version with `@osdk/cli`, and one version at a time is live. This page covers configuring production, deploying, and managing versions; the [CLI reference](https://palantir.github.io/osdk-ts/deploy/cli.md#osdk-site) lists every flag. ## Before you start | You need | Where to get it | | --- | --- | | An application in Developer Console with website hosting set up | Developer Console. Note the subdomain, such as `https://myapp.example.palantirfoundry.com`. | | The application RID | The application's Developer Console URL, `/workspace/developer-console/app/`. | | A Foundry token | Set it as `FOUNDRY_TOKEN`. The CLI accepts only JWTs. | | A static build | Any framework works. Apps from `@osdk/create-app` build to `./dist` with Vite. | ## Deploy your app ### Add `foundry.config.json` Apps from `@osdk/create-app` already have this file. Otherwise, create it in your project root: ```json title="foundry.config.json" { "foundryUrl": "https://example.palantirfoundry.com", "site": { "application": "ri.third-party-applications.main.application.1c66b352-4e00-40d2-995d-061c9d533ace", "directory": "./dist", "autoVersion": { "type": "git-describe", "tagPrefix": "" } } } ``` The CLI reads it from the current directory or the nearest parent, so you do not repeat these values on every command. All fields are described in [`foundry.config.json`](#foundryconfigjson). ### Set the production redirect URL After sign-in, Foundry sends users back to your app's redirect URL, which must point at the hosted subdomain in production. In an app from `@osdk/create-app`, set it in `.env.production`: ```ini title=".env.production" VITE_FOUNDRY_REDIRECT_URL=https://myapp.example.palantirfoundry.com/auth/callback VITE_FOUNDRY_API_URL=https://example.palantirfoundry.com VITE_FOUNDRY_CLIENT_ID= ``` If you skipped the production URL when you created the app, the redirect line is commented out with a placeholder. Then add the same URL as a redirect URL on **OAuth & scopes** in Developer Console. The two must match exactly. See [Authentication](https://palantir.github.io/osdk-ts/authentication.md#handle-the-redirect-callback). The React template includes a test that fails while any of these variables is missing or still a placeholder: ```sh VERIFY_ENV_PRODUCTION=true npm test ``` ### Build ```sh npm run build ``` In the React templates from `@osdk/create-app` this runs `tsc && vite build` (`vue-tsc && vite build` for Vue, `expo export -p web` for Expo). Vite builds in `production` mode, reads `.env.production`, and writes to `./dist`. Your Vite config must define `process.env.NODE_ENV`; see [Use OSDK with Vite](https://palantir.github.io/osdk-ts/guides/vite.md). ### Deploy ```sh export FOUNDRY_TOKEN= npx @osdk/cli@latest site deploy ``` The CLI computes the version, zips `./dist`, uploads it, makes it live, and prints the site URL. To set the version yourself, pass `--version 1.2.0`. ## `foundry.config.json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `foundryUrl` | `string` | Yes | The Foundry stack URL. Must start with `https://`. | | `site.application` | `string` | Yes | The Developer Console application RID. | | `site.directory` | `string` | Yes | The directory to upload, relative to where you run the CLI. | | `site.autoVersion` | `object` | No | How to compute versions. `{ "type": "git-describe", "tagPrefix"?: string }` or `{ "type": "package-json" }`. | | `site.uploadOnly` | `boolean` | No | Upload new versions without making them live. Defaults to `false`. | The file must not contain other top-level fields. A `widgetSet` block, used by [widget sets](https://palantir.github.io/osdk-ts/widgets/publish.md), cannot share a file with `site`. Command-line flags and `OSDK_*` environment variables override the file; see [Configuration](https://palantir.github.io/osdk-ts/deploy/cli.md#configuration). ## Automatic versions Every version must be valid [SemVer](https://semver.org) and unique: Foundry rejects a version that already exists. Pass `--version`, or let the CLI compute it. | `autoVersion.type` | Version comes from | | --- | --- | | `git-describe` | `git describe --tags --first-parent --dirty`, limited to tags starting with `tagPrefix` when it is set. | | `package-json` | The `version` field of the nearest `package.json`. | With `git-describe`, the CLI strips `tagPrefix` from the result, or a leading `v` when there is no prefix. The result depends on where you are relative to the newest tag: | Repository state | Example tag | Version | | --- | --- | --- | | On the tagged commit | `v1.2.0` | `1.2.0` | | Three commits after the tag | `v1.2.0` | `1.2.0-3-g1a2b3c4` | | Uncommitted changes | `v1.2.0` | `1.2.0-dirty` | | Tag prefix `my-app@` | `my-app@1.2.0` | `1.2.0` | The deploy fails if git is missing, the directory is not a git repository, no tag matches, or the result is not SemVer. In CI, check out tags as well as commits, or `git describe` finds no tag. To use the version in `package.json`, bump it before each deploy: ```json title="foundry.config.json" { "foundryUrl": "https://example.palantirfoundry.com", "site": { "application": "ri.third-party-applications.main.application.1c66b352-4e00-40d2-995d-061c9d533ace", "directory": "./dist", "autoVersion": { "type": "package-json" } } } ``` ## Preview before going live Upload a version without making it live with `--uploadOnly`, or set `site.uploadOnly` to `true` to make that the default: ```sh npx @osdk/cli@latest site deploy --uploadOnly ``` The CLI prints a preview link, `https:///.system/preview?previewVersion=`. When it looks right, make it live: ```sh npx @osdk/cli@latest site version set 1.3.0 ``` Use the same flow when Foundry reports that a version is still being scanned for vulnerabilities: upload with `--uploadOnly`, wait for the scan, then set the version live with the CLI or from **Website hosting** in Developer Console. ## Roll back To roll back, set an earlier uploaded version live: ```sh npx @osdk/cli@latest site version list npx @osdk/cli@latest site version set 1.2.0 ``` `list` shows each version, newest first, and marks the live one. `osdk site version get` prints only the live version. ## Clean up old versions An application has a version limit. When you reach it, deploys fail with `The site contains too many versions`. Delete versions you no longer need: ```sh npx @osdk/cli@latest site version delete 1.0.0 --yes ``` You cannot delete the live version. To take the site offline, clear the live version with `osdk site version unset`; the site is unreachable until you set one again. ## Host somewhere else The build is static files, so any web server or CDN can host it. Foundry website hosting sets up cross-origin access to your stack for you; elsewhere you configure it yourself: | Requirement | Why | | --- | --- | | Your stack allows your origin for CORS | The browser calls Foundry APIs directly from your origin. Ask your Foundry administrator to allow it. | | The redirect URL is on **OAuth & scopes** | Foundry only redirects to listed URLs. Use your origin plus `/auth/callback`, and set the same value in `.env.production`. | | The server returns your app for `/auth/callback` | Sign-in lands on that path. A server that returns `404` for paths without a file breaks sign-in, so serve `index.html` for unknown paths. | # Integration testing Source: https://palantir.github.io/osdk-ts/deploy/integration-testing > Run OSDK code against a local Ontology server with @osdk/integration-testing, seed it with objects and links, and stub functions in Vitest. `@osdk/integration-testing` starts a local Ontology server from the Foundry CLI, fills it with seed objects and links, and gives you a real `Client` connected to it. Use it to test code that queries objects, filters, and follows links end to end, without a Foundry stack. To test React components with mocks instead, see [Testing](https://palantir.github.io/osdk-ts/react/testing.md). > [!WARNING] > `@osdk/integration-testing` is a `0.x` package and depends on the experimental `--experimentalOntologyMetadata` generator flag. Its API may change between releases. ## How it works | Piece | What it does | | --- | --- | | `createIntegrationServer` | Writes your Ontology metadata to a temporary `.test-run-*` directory and runs `foundry start ontology` from the Foundry CLI. | | Seed client | Writes objects and links to the local server. Each call replaces the server's data with the seed built so far. | | Integration client | A `Client` from `@osdk/client` pointed at the local server. Object and interface calls, such as `fetchPage`, `where`, and `pivotTo`, run against the seeded data. | | Function stubs | The local Ontology cannot run functions, so the integration client sends function calls to an in-memory mock from `@osdk/unit-testing`. Register results with `whenQuery`. | ## Requirements | Requirement | Details | | --- | --- | | Node.js | The package starts a subprocess and reads files, so tests run in Node, not a browser. | | Foundry CLI | The `foundry` binary, version `0.224.0` or later, on your `PATH`. Pass `foundryCliPath` to use a binary elsewhere. | | Ontology metadata | The full Ontology metadata your SDK was generated from, as JSON. See [Get the Ontology metadata](#get-the-ontology-metadata). | | `@osdk/seed-helpers` | A peer dependency, `>=0.25.0 <1.0.0`, that builds seed data. | ## Install ```npm npm install --save-dev @osdk/integration-testing @osdk/seed-helpers vitest ``` `@osdk/client` and `@osdk/api` are peer dependencies as well; install them as described in [Installation](https://palantir.github.io/osdk-ts/installation.md). ### Foundry CLI On install, a postinstall script checks for the Foundry CLI: - If `foundry` is installed and recent enough, it does nothing. - If it is too old, the install fails and asks you to run `foundry update self`. - If it is missing, it downloads the installer from your Foundry stack and runs it. If that fails, the install continues with a warning, and creating a client fails until the CLI is installed. To find your stack and authenticate the download, the script reads, in order: | Value | Sources | | --- | --- | | Foundry host | `FOUNDRY_EXTERNAL_HOST` or `FOUNDRY_HOSTNAME`, then the host of the git remote `origin`. | | Token | `FOUNDRY_TOKEN` when `FOUNDRY_HOSTNAME`, `FOUNDRY_TOKEN`, and `FOUNDRY_USERNAME` are all set, otherwise the credentials in the git remote URL. Foundry CI and Code Workspaces provide their own token automatically. | Set the three variables before installing on a machine whose git remote does not point at Foundry: ```sh export FOUNDRY_HOSTNAME=example.palantirfoundry.com export FOUNDRY_USERNAME= export FOUNDRY_TOKEN= npm install ``` ## Get the Ontology metadata `createIntegrationServer` needs the Ontology metadata as an `OntologyFullMetadata` object. The SDK generator writes it when you generate locally with the experimental `--experimentalOntologyMetadata` flag: ```sh npx @osdk/cli unstable typescript generate \ --foundryUrl https://example.palantirfoundry.com \ --clientId \ --outDir src/generatedNoCheck \ --version dev \ --packageType module \ --experimentalOntologyMetadata ``` The metadata lands in `experimental/ontology-metadata.json` inside `--outDir`. An SDK package generated with the flag, such as one built with `--asPackage` or published from Developer Console, also exports it as the `./experimental/ontology-metadata` subpath, which the examples below import. If you generate source files instead, import `../src/generatedNoCheck/experimental/ontology-metadata.json` with `resolveJsonModule` enabled. For the other generate options, see [Generate your SDK](https://palantir.github.io/osdk-ts/deploy/generate-sdk.md). ## Write a test This example uses Vitest. One server starts per Vitest worker, and every test resets the seed before it runs. ### Create a fixture `test.extend` creates the server, seed client, and integration client once per worker and passes them to each test. `stop()` runs in `finally`, so a server that fails to start does not leave its process or `.test-run-*` directory behind. ```ts title="test/fixture.ts" import metadata from "@my-app/sdk/experimental/ontology-metadata"; import { createIntegrationServer, type IntegrationClient, type IntegrationServer, type SeedClient, } from "@osdk/integration-testing"; import { test as baseTest } from "vitest"; export { metadata }; export interface IntegrationFixtures { server: IntegrationServer; client: IntegrationClient; seed: SeedClient; } export const test = baseTest.extend({ server: [ // eslint-disable-next-line no-empty-pattern async ({}, use) => { const server = await createIntegrationServer({ metadata }); try { await server.start(); await use(server); } finally { await server.stop(); } }, { scope: "worker" }, ], seed: [async ({ server }, use) => use(await server.getSeedClient()), { scope: "worker" }], client: [async ({ server }, use) => use(await server.getClient()), { scope: "worker" }], }); ``` ### Build the seed data `createSeedWithMetadata` from `@osdk/seed-helpers` builds seed data without a server, and returns it with whatever your function returns. `create` returns a reference with the object's properties, `$apiName`, and `$primaryKey`; `link` connects two references by link name. ```ts title="test/seed.ts" import { Employee, Office } from "@my-app/sdk"; import { createSeedWithMetadata } from "@osdk/seed-helpers"; import { metadata } from "./fixture.js"; export const baseSeed = createSeedWithMetadata(metadata, (seed) => { const london = seed.create(Office, { officeId: "lon", name: "London", city: "London" }); const ada = seed.create(Employee, { employeeId: 1, fullName: "Ada Lovelace", department: "Engineering", }); const grace = seed.create(Employee, { employeeId: 2, fullName: "Grace Hopper", department: "Engineering", }); seed.link(grace, "lead", ada); seed.link(ada, "office", london); return { london, ada, grace }; }); ``` `create` throws when an object of that type with the same primary key already exists, and when the properties do not match the metadata. A non-primary-key property set to `undefined` is allowed, even when the metadata marks it required, and is left empty. ### Test against the local server Reset the seed before each test so tests do not see each other's writes, and clear function stubs after each one. ```ts title="test/employees.test.ts" import { countEmployees, Employee } from "@my-app/sdk"; import { afterEach, beforeEach, expect } from "vitest"; import { test, type IntegrationFixtures } from "./fixture.js"; import { baseSeed } from "./seed.js"; beforeEach(async ({ seed }) => { await seed.set(baseSeed.output); }); afterEach(({ client }) => { client.clearStubs(); }); test("lists engineers", async ({ client }) => { const page = await client(Employee).where({ department: "Engineering" }).fetchPage(); expect(page.data.map((employee) => employee.fullName).sort()).toEqual([ "Ada Lovelace", "Grace Hopper", ]); }); test("follows the lead link", async ({ client }) => { const leads = await client(Employee) .where({ employeeId: baseSeed.context.grace.employeeId }) .pivotTo("lead") .fetchPage(); expect(leads.data.map((employee) => employee.$primaryKey)).toEqual([ baseSeed.context.ada.employeeId, ]); }); test("stubs a function", async ({ client }) => { client.whenQuery(countEmployees).thenReturn(2); await expect(client(countEmployees).executeFunction()).resolves.toBe(2); }); ``` Replace `countEmployees` with a function from your SDK. A stub matches only calls whose parameters deep-equal the second argument of `whenQuery`, or calls with no parameters when you omit it: `client.whenQuery(fn, params).thenReturn(result)`. Use `thenThrow(error)` to make the call fail. ### Run the tests ```sh npx vitest run ``` Starting the Ontology server can take a while on the first run. If the fixture times out, raise Vitest's `hookTimeout` and `testTimeout`. Each server's `.test-run-*` directory is removed when it stops; add `.test-run-*` to `.gitignore` in case a run is killed first. ## Change data inside a test Each seed client method updates the seed and writes it to the server before it resolves, so a test can set up extra data right before it queries: ```ts title="test/offices.test.ts" import { Employee, Office } from "@my-app/sdk"; import { expect } from "vitest"; import { test } from "./fixture.js"; test("lists an office's occupants", async ({ client, seed }) => { await seed.set(); const paris = await seed.create(Office, { officeId: "par", name: "Paris", city: "Paris" }); const alan = await seed.create(Employee, { employeeId: 3, fullName: "Alan Turing" }); await seed.link(paris, "occupants", [alan]); const occupants = await client(Office) .where({ officeId: paris.officeId }) .pivotTo("occupants") .fetchPage(); expect(occupants.data.map((employee) => employee.fullName)).toEqual(["Alan Turing"]); }); ``` ## API reference ### `createIntegrationServer(config)` Returns a `Promise`. Creating the server writes the metadata to disk; `start()` launches the CLI. | Option | Type | Default | Description | | --- | --- | --- | --- | | `metadata` | `OntologyFullMetadata` | | The Ontology metadata to serve. Required. Interfaces that object types implement but the metadata does not include are dropped, with a warning. | | `foundryCliPath` | `string` | `foundry` on `PATH` | Path to the Foundry CLI binary. | | `projectPath` | `string` | The working directory | An existing directory to create the server's `.test-run-*` directory in. Servers that share a `projectPath` stay isolated. | | `IntegrationServer` member | Description | | --- | --- | | `start()` | Starts the Ontology service and resolves once it reports ready. | | `stop()` | Stops the service and deletes the server's `.test-run-*` directory. | | `getOntologyUrl()` | The local server's URL, or `undefined` before it starts. | | `getClient()` | Resolves to the `IntegrationClient` for this server. Repeated calls return the same client. | | `getSeedClient()` | Resolves to the `SeedClient` for this server. Repeated calls return the same seed client. | `getClient()` and `getSeedClient()` throw an error containing `Ontology server is not ready` when called before `start()` resolves. ### `SeedClient` Every method applies the full seed to the server before it resolves. | Member | Description | | --- | --- | | `seed(fn)` | Calls `fn` with a `SeedBuilder`, applies the result, and resolves to what `fn` returns. | | `seed(output)` | Adds a `SeedOutput`, such as `baseSeed.output`, to the seed and applies it. | | `set(output?)` | Replaces the whole seed with `output` and applies it. With no argument, clears all data. | | `addAll(output)` | Merges a `SeedOutput` into the current seed. | | `create(type, props)` | Creates an object and resolves to its reference. Throws if the primary key already exists. | | `update(ref, props)` | Merges `props` into the object, leaving omitted properties unchanged. A property set to `undefined` is cleared. Creates the object if it does not exist. | | `delete(ref)` | Removes the object. Does nothing if it does not exist. | | `link(source, linkName, target)` | Links `source` to one reference, or an array for many-valued links. Re-adding a link does nothing. | | `unlink(source, linkName, target)` | Removes matching links. Does nothing if none exist. | | `ref(type, primaryKey)` | Returns the reference for an object already in the seed, or `undefined`. Does not write to the server. | ### `IntegrationClient` A `Client` from `@osdk/client` with two extra members: | Member | Description | | --- | --- | | `whenQuery(query, params?)` | Starts a function stub. Finish it with `.thenReturn(result)` or `.thenThrow(error)`. | | `clearStubs()` | Removes every function stub. | ### Other exports | Export | Description | | --- | --- | | `createIntegrationClient(config)` | Creates an `IntegrationClient` for a server that is already running, with `baseUrl` and `metadata`, and optionally `caCertPath` for the server's certificate. Without `caCertPath`, the client skips TLS certificate checks. Throws if the Foundry CLI is not installed. | | `checkFoundryCliVersion()` | Resolves to `{ type: "installed", version }`, `{ type: "version-incompatible", version }`, `{ type: "version-error" }`, or `{ type: "not-found" }`. Use it to skip integration tests on machines without the CLI, for example with `describe.runIf`. | ```ts title="test/employees.test.ts" import { Employee } from "@my-app/sdk"; import { checkFoundryCliVersion } from "@osdk/integration-testing"; import { describe, expect } from "vitest"; import { test } from "./fixture.js"; const foundryCli = await checkFoundryCliVersion(); describe.runIf(foundryCli.type === "installed")("employees", () => { test("loads an employee", async ({ client }) => { const employee = await client(Employee).fetchOne(1); expect(employee.fullName).toBe("Ada Lovelace"); }); }); ``` # FAQ Source: https://palantir.github.io/osdk-ts/faq > Short answers about @osdk/react versus React Query, using OSDK without React or on a server, package versions, dates, templates, and changelogs. Short answers to common questions about the OSDK TypeScript and React SDKs. Each answer links to the page that covers the topic in full. **How is @osdk/react different from React Query or SWR?** React Query and SWR cache responses by a key you choose. `@osdk/react` knows the Ontology, so it caches objects themselves: - Each object is stored once by type and primary key, and every list, link, and detail view that contains it updates together. - Actions report which objects they added, modified, or deleted, and the cache applies those edits without manual invalidation. - Optimistic updates roll back automatically if the action fails. - `streamUpdates: true` keeps lists live over a WebSocket. Use `@osdk/react` for Foundry data and keep React Query or SWR for other APIs. They work side by side, but do not copy OSDK data into another cache. See [Caching and reactivity](https://palantir.github.io/osdk-ts/concepts/caching.md). **Can I use OSDK without React?** Yes. `@osdk/client` has no UI dependency and works in any browser or JavaScript runtime with `fetch`. Create a client with `createClient` and call `client(Employee).fetchPage()`, `client(modifyEmployee).applyAction()`, and so on. See [Use the client without React](https://palantir.github.io/osdk-ts/client.md#use-the-client-without-react). For the normalized cache outside React, `createObservableClient` from `@osdk/client/observable` is the same engine `OsdkProvider` uses. **Which packages must share versions?** `@osdk/api`, `@osdk/client`, and `@osdk/react` are released together with one version number. Install the same version of all three, and keep prereleases together. Your generated SDK has a peer dependency on `@osdk/client`, so generate a new SDK version when you upgrade the client across many versions. `@osdk/react-components`, `@osdk/react-devtools`, and `@osdk/oauth` have their own version numbers. Upgrade them alongside the three core packages. See [Version compatibility](https://palantir.github.io/osdk-ts/installation.md#version-compatibility). **Why are dates and timestamps strings?** Date and timestamp properties are ISO 8601 strings, such as `"2024-03-15"` and `"2024-03-15T09:30:00Z"`. Bundling a date library would add weight to every app, often duplicating a library you already use, and parsing every value costs time even when you never read it. Parse values with `Date` or your date library when you need date math. See [Dates and timestamps](https://palantir.github.io/osdk-ts/concepts/ontology.md#dates-and-timestamps). **Can I use OSDK on a server or in Node.js?** Yes, with `@osdk/client` and a confidential OAuth client. `createConfidentialOauthClient` from `@osdk/oauth` uses the client credentials grant, so requests act as the application's service user, not a signed-in person: ```ts title="src/server/client.ts" import { createClient } from "@osdk/client"; import { createConfidentialOauthClient } from "@osdk/oauth"; const auth = createConfidentialOauthClient( process.env.FOUNDRY_CLIENT_ID!, process.env.FOUNDRY_CLIENT_SECRET!, process.env.FOUNDRY_URL!, ); export const client = createClient( process.env.FOUNDRY_URL!, process.env.FOUNDRY_ONTOLOGY_RID!, auth, ); ``` Keep the client secret on the server; never ship it to a browser. `@osdk/react` is for browser apps. See [Authenticate a server or service](https://palantir.github.io/osdk-ts/authentication.md#authenticate-a-server-or-service). **Is there a Vue template?** Yes. `@osdk/create-app` has React, Vue, and Expo templates, plus a React template for public apps without sign-in. Choose one at the prompt, or pass it directly: ```bash npx @osdk/create-app@latest my-app --template vue ``` The Vue template uses `@osdk/client` and `@osdk/oauth` directly. `@osdk/react` and its components are React-only. **Where do I find the Ontology RID and client ID?** Both come from your application in Developer Console: | Value | Where to find it | | --- | --- | | Client ID | The **OAuth & scopes** page. | | Ontology RID | The **Ontology SDK** page. Your generated SDK also exports it as `$ontologyRid` when it was generated for a single environment. | | Redirect URL | Also on **OAuth & scopes**. The value in your app must match one listed there exactly. | Apps created with `@osdk/create-app` store these in `.env.development` and `.env.production` as `VITE_FOUNDRY_CLIENT_ID`, `VITE_FOUNDRY_ONTOLOGY_RID`, and `VITE_FOUNDRY_REDIRECT_URL`. **Why do I call client(Employee) instead of client.objects.Employee?** The generated SDK exports definitions, and the client does the work. Importing definitions by name lets your bundler drop the parts of the Ontology you do not use, and lets several SDKs share one `@osdk/client`. See [Why `client(Employee)`](https://palantir.github.io/osdk-ts/concepts/ontology.md#why-clientemployee). **Where is the changelog?** Each package has a `CHANGELOG.md` on GitHub and in its npm package: - [`@osdk/react` changelog](https://github.com/palantir/osdk-ts/blob/main/packages/react/CHANGELOG.md) - [`@osdk/client` changelog](https://github.com/palantir/osdk-ts/blob/main/packages/client/CHANGELOG.md) - [`@osdk/react-components` changelog](https://github.com/palantir/osdk-ts/blob/main/packages/react-components/CHANGELOG.md) Locally, open `node_modules/@osdk/react/CHANGELOG.md` to read the notes for the version you have installed. # Expo and React Native Source: https://palantir.github.io/osdk-ts/frameworks/expo > Build an iOS, Android, and web app on OSDK with the create-app Expo template, sign in with expo-auth-session, and query objects from React Native screens. {/* cspell:ignore Metro metro PKCE inlines */} The `expo` template of `@osdk/create-app` gives you an Expo Router app that signs in to Foundry and calls `@osdk/client` on iOS, Android, and the web. Sign-in works differently from the browser templates, so read [Sign in](#sign-in) before you configure redirect URLs. ## Create an Expo app Run `@osdk/create-app` with the `expo` template: ```npm npx @osdk/create-app@latest my-expo-app --template expo --corsProxy false ``` The CLI asks for your Foundry URL, application RID, OAuth client ID, and SDK package. [Quickstart](https://palantir.github.io/osdk-ts/quickstart.md#run-the-cli) lists every prompt and its flag. The Expo template supports SDK version 2.x only. It ignores the scopes you enter: `app/(tabs)/login.tsx` hardcodes `api:read-data`, `api:write-data`, `api:use-ontologies-read`, and `api:use-ontologies-write`, so edit that list instead. > [!WARNING] > Answer **No** to the CORS proxy prompt, or pass `--corsProxy false`. The Expo template has no proxy server, but a **Yes** still sets `EXPO_PUBLIC_FOUNDRY_API_URL` to `http://localhost:8080` in `.env.development`, so every request goes to the Expo dev server instead of Foundry. Then install and start the app: ```sh cd my-expo-app export FOUNDRY_TOKEN= npm install npm run dev ``` `FOUNDRY_TOKEN` must be able to read your SDK's npm registry; see [Installation](https://palantir.github.io/osdk-ts/installation.md). | Script | Runs | Use it to | | --- | --- | --- | | `dev`, `start` | `expo start --port 8080` | Start the dev server, then press `i`, `a`, or `w` to open iOS, Android, or web. | | `ios` | `expo start --ios` | Start and open the iOS simulator. | | `android` | `expo start --android` | Start and open the Android emulator. | | `web` | `expo start --web --port 8080` | Start and open the web build. | | `build` | `expo export -p web` | Export the web build to `dist/` for [hosting](https://palantir.github.io/osdk-ts/deploy/hosting.md). | | `test` | `vitest run --passWithNoTests` | Run tests. | | `reset-project` | `node ./scripts/reset-project.js` | Move `app/`, `components/`, `hooks/`, `constants/`, and `scripts/`, including the Login screen, to `app-example/`, and create a minimal `app/`. | ## What the template generates ```text .env.development .env.production .npmrc app.json foundry.config.json metro.config.js package.json app/ _layout.tsx (tabs)/ _layout.tsx explore.tsx index.tsx login.tsx foundry/ Auth.ts client.ts osdkConst.ts ``` | File | Purpose | | --- | --- | | `.env.development`, `.env.production` | `EXPO_PUBLIC_FOUNDRY_API_URL`, `EXPO_PUBLIC_FOUNDRY_CLIENT_ID`, and `EXPO_PUBLIC_FOUNDRY_ONTOLOGY_RID`. Expo inlines `EXPO_PUBLIC_` variables into the bundle. | | `foundry/osdkConst.ts` | Reads those variables and throws `Missing environment variable` if one is unset. | | `foundry/Auth.ts` | Holds the access token in memory and exposes `getValidAuthToken` as the client's token provider. | | `foundry/client.ts` | Creates `client` with `createClient`. | | `app/(tabs)/login.tsx` | The **Login** tab, which runs the OAuth flow with `expo-auth-session`. | | `app/(tabs)/index.tsx` | The **Home** tab. On web it also completes the sign-in popup. | | `app/(tabs)/explore.tsx` | Lists the object types, actions, and functions in your SDK. | | `metro.config.js` | Lets Metro resolve the OSDK packages. See [Metro configuration](#metro-configuration). | | `app.json` | Expo config, including the URL `scheme` used for native sign-in redirects. | The generated `.env` files also contain `EXPO_PUBLIC_FOUNDRY_REDIRECT_URL`. The Expo template does not read it: the redirect URL comes from `makeRedirectUri`, described below. ## Sign in The browser templates use `createPublicOauthClient` from `@osdk/oauth`, which signs in by navigating the page to Foundry and back. A native app cannot do that, so the Expo template runs the same authorization code flow with PKCE through `expo-auth-session` instead, which opens Foundry's sign-in page in a system browser session and returns the code to the app. ### Store the token `foundry/Auth.ts` keeps the token response in a module variable. `getValidAuthToken` is the token provider you pass to `createClient`; it throws until the user has signed in: ```ts title="foundry/Auth.ts" import { TokenResponse } from "expo-auth-session"; let authToken: TokenResponse | undefined = undefined; export const setAuthToken = (authTokenResponse: TokenResponse): void => { authToken = authTokenResponse; }; export const getValidAuthToken = async (): Promise => { if (authToken != null) { return Promise.resolve(authToken.accessToken); } else { throw new Error("No valid auth token"); } }; ``` ```ts title="foundry/client.ts" import { createClient, type Client } from "@osdk/client"; import { getValidAuthToken } from "./Auth"; import { FOUNDRY_URL, ONTOLOGY_RID } from "./osdkConst"; export const client: Client = createClient( FOUNDRY_URL, ONTOLOGY_RID, getValidAuthToken, ); ``` The token lives only in memory. The template neither refreshes nor persists it, so the user signs in again when the app restarts or the access token expires. ### Run the authorization flow The **Login** tab points `useAuthRequest` at Foundry's authorize and token endpoints under `/multipass/api/oauth2`, then exchanges the returned code for a token. This version adds error handling to the generated screen: ```tsx title="app/(tabs)/login.tsx" import { setAuthToken } from "@/foundry/Auth"; import { CLIENT_ID, FOUNDRY_URL } from "@/foundry/osdkConst"; import { exchangeCodeAsync, makeRedirectUri, useAuthRequest, } from "expo-auth-session"; import { useRouter } from "expo-router"; import { useCallback, useMemo, useState } from "react"; import { Button, Text, View } from "react-native"; const discovery = { authorizationEndpoint: `${FOUNDRY_URL}/multipass/api/oauth2/authorize`, tokenEndpoint: `${FOUNDRY_URL}/multipass/api/oauth2/token`, }; export default function Login() { const router = useRouter(); const [error, setError] = useState(); const redirectUri = useMemo(() => makeRedirectUri({ path: "" }), []); const [request, , promptAsync] = useAuthRequest( { clientId: CLIENT_ID, scopes: [ "api:read-data", "api:write-data", "api:use-ontologies-read", "api:use-ontologies-write", ], redirectUri, usePKCE: true, }, discovery, ); const onLogin = useCallback(async () => { setError(undefined); try { const result = await promptAsync(); if (result.type !== "success") { return; } const tokenResponse = await exchangeCodeAsync( { clientId: CLIENT_ID, code: result.params.code, redirectUri, extraParams: request?.codeVerifier ? { code_verifier: request.codeVerifier } : undefined, }, discovery, ); setAuthToken(tokenResponse); router.navigate("/(tabs)/explore"); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } }, [promptAsync, redirectUri, request?.codeVerifier, router]); return (

    )} {isLoading && !data &&

    Loading employees…

    }
      {data?.map((employee) => (
    • {employee.fullName}, {employee.jobTitle}
    • ))}
    ); } ``` `data` is `undefined` until the first page arrives. After that, `isLoading` can be `true` while `data` still holds the previous result, for example while the hook revalidates after an action. Keep rendering `data` during those refreshes instead of replacing the list with a spinner. [Loading and errors](https://palantir.github.io/osdk-ts/concepts/loading-and-errors.md) covers the pattern in depth. `isOptimistic` is `true` when the order or membership of the list reflects an optimistic update that the server has not confirmed yet. It only describes the list of primary keys. To check whether one object's contents are optimistic, pass that object to [`useOsdkObject`](#load-one-object). ## Filter with `where` `where` takes the same clause as `ObjectSet.where` in `@osdk/client`. A bare value on a property means equality: ```tsx const { data } = useOsdkObjects(Employee, { where: { department: "Engineering" }, }); ``` For anything else, give the property an object with one operator: ```tsx const { data } = useOsdkObjects(Employee, { where: { department: { $in: ["Engineering", "Design"] }, salary: { $gte: 100000 }, jobTitle: { $isNull: false }, }, }); ``` Several properties in the same clause must all match. The operators each property accepts depend on its type: | Operator | Property types | Matches | | --- | --- | --- | | `$eq`, `$ne` | Strings, numbers, booleans, dates, timestamps | Equal to, or not equal to, the value. `{ department: "Sales" }` is shorthand for `$eq`. | | `$in` | Strings, numbers, booleans, dates, timestamps | Any of the listed values. | | `$isNull` | All | `true` for missing values, `false` for present ones. | | `$gt`, `$gte`, `$lt`, `$lte` | Numbers, dates, timestamps, strings | Greater or less than the value. Dates and timestamps take ISO 8601 strings. | | `$startsWith`, `$containsAnyTerm`, `$containsAllTerms`, `$containsAllTermsInOrder` | Strings | Text search. See [Search text](#search-text). | | `$matchesRegex` | Strings | A regular expression. Beta. | | `$contains` | Arrays | Arrays that contain the value. | | `$within`, `$intersects` | Geopoints, geoshapes | A distance, bounding box, or polygon. | You can also filter on `$primaryKey`, for example `{ $primaryKey: { $in: [101, 102] } }`, without knowing the name of the primary key property. > [!WARNING] > `$in` with an empty array matches every object. If the list comes from user input, set `enabled: false` (see [Fetch conditionally](#fetch-conditionally)) or leave the filter out when the list is empty. ### Combine conditions Each property takes exactly one operator, so a range on one property needs `$and`: ```tsx const { data } = useOsdkObjects(Employee, { where: { $and: [{ salary: { $gte: 80000 } }, { salary: { $lt: 120000 } }], }, }); ``` `$or` matches any of its clauses, and `$not` negates one clause. They nest: ```tsx const { data } = useOsdkObjects(Employee, { where: { $or: [ { department: "Sales" }, { $and: [{ department: "Engineering" }, { $not: { jobTitle: { $startsWith: "Intern" } } }] }, ], }, }); ``` To intersect several independent filters, you can also pass `intersectWith`, an array of `{ where }` clauses. The result contains only objects that match `where` and every entry. ```tsx const { data } = useOsdkObjects(Employee, { where: { department: "Engineering" }, intersectWith: [{ where: { salary: { $gte: 100000 } } }, { where: { startDate: { $lt: "2020-01-01" } } }], }); ``` ### Search text String properties support four search operators. `$containsAnyTerm` and `$containsAllTerms` also accept `{ term, fuzzySearch: true }` to tolerate small typos. All four accept `{ term, phoneticSearch: true }`, which matches similarly pronounced terms, such as `Jon` and `John`, on properties with phonetic search enabled. A filter cannot set both `fuzzySearch` and `phoneticSearch`; combine the two with `$or`. | Operator | Matches | Fuzzy | Phonetic | Example value | Matches `"Senior Software Engineer"` | | --- | --- | --- | --- | --- | --- | | `$startsWith` | Values that begin with the prefix | No | Yes | `"Senior"` | Yes | | `$containsAnyTerm` | Values that contain any of the space-separated terms | Yes | Yes | `"designer engineer"` | Yes | | `$containsAllTerms` | Values that contain every term, in any order | Yes | Yes | `"engineer senior"` | Yes | | `$containsAllTermsInOrder` | Values that contain every term, in this order | No | Yes | `"engineer senior"` | No | A search box that waits for two characters before it queries: ```tsx title="src/EmployeeSearch.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; import { useState } from "react"; export function EmployeeSearch() { const [query, setQuery] = useState(""); const { data, isLoading } = useOsdkObjects(Employee, { where: { fullName: { $containsAnyTerm: { term: query, fuzzySearch: true } } }, $select: ["fullName", "jobTitle"], pageSize: 20, enabled: query.length >= 2, }); return (
    setQuery(e.target.value)} /> {isLoading &&

    Searching…

    }
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    ); } ``` To send fewer requests while the user types, debounce the state update with `useDebouncedCallback` from `@osdk/react`. ### Load specific objects by RID `rids` starts from a fixed set of objects instead of every object of the type. `where` and `orderBy` then filter and sort that set. Objects loaded this way have `$rid` set. ```tsx const { data } = useOsdkObjects(Employee, { rids: ["ri.phonograph2-objects.main.object.1", "ri.phonograph2-objects.main.object.2"], where: { department: "Engineering" }, }); ``` ## Sort with `orderBy` `orderBy` maps property names to `"asc"` or `"desc"`. List several properties to break ties, in priority order: ```tsx const { data } = useOsdkObjects(Employee, { orderBy: { department: "asc", salary: "desc" }, }); ``` `orderBy` accepts the object type's own properties. To sort by a value computed from linked objects, see [derived properties](https://palantir.github.io/osdk-ts/react/object-sets.md#add-derived-properties). ## Select properties Without `$select`, the server returns its default property set for each object. Pass `$select` with only the properties the component reads; the primary key is always included. ```tsx const { data } = useOsdkObjects(Employee, { $select: ["fullName", "jobTitle"], }); ``` Loading unused properties costs bandwidth and slows down the query, and filtering them out after the fact does not get that cost back. Unlike `fetchPage` in `@osdk/client`, `useOsdkObjects` does not narrow the returned type to the selected properties. Reading a property you did not select still type-checks but is `undefined` at runtime, so keep `$select` in sync with what you render. ### Query an interface When you pass an interface instead of an object type, each object only exposes the interface's properties. Two options change that: | Option | Effect | | --- | --- | | `$includeAllBaseObjectProperties: true` | The server also returns every property of the implementing object type. | | `resolveToObjectType: true` | The hook returns instances of the implementing object type instead of interface views, so properties such as `$title` and properties that are not on the interface are available. Only allowed for interfaces. | ```tsx import { Worker } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function WorkerList() { const { data } = useOsdkObjects(Worker, { $includeAllBaseObjectProperties: true, resolveToObjectType: true, }); return (
      {data?.map((worker) => (
    • {worker.name} ({worker.$objectType})
    • ))}
    ); } ``` ## Paginate `pageSize` sets how many objects each request loads. It is not a limit on the total. Call `fetchMore` to load the next page; it is `undefined` once there are no more pages, and `hasMore` is `false`. ```tsx title="src/EmployeeDirectory.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function EmployeeDirectory() { const { data, isLoading, fetchMore, totalCount } = useOsdkObjects(Employee, { orderBy: { fullName: "asc" }, pageSize: 50, }); return (
    {totalCount != null &&

    {Number(totalCount).toLocaleString()} employees

    }
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    {fetchMore && ( )}
    ); } ``` `totalCount` is a string because the count can exceed `Number.MAX_SAFE_INTEGER`. It is `undefined` when the server does not report it. To load more pages without a button, set `autoFetchMore`: | Value | Behavior | | --- | --- | | `undefined` (default) | Load the first page only. | | A number, such as `200` | Keep loading pages until the list has at least that many objects or runs out. | | `true` | Load every page. | ```tsx const { data } = useOsdkObjects(Employee, { pageSize: 50, autoFetchMore: 200, }); ``` > [!WARNING] > `autoFetchMore: true` on a large object type can take a long time and hold every object in memory. Prefer a number, or `fetchMore` on demand. For counts, sums, and group-bys, use [`useOsdkAggregation`](https://palantir.github.io/osdk-ts/react/aggregations.md) instead of loading objects. > [!NOTE] > **Paging consistency** > > Pages load without a snapshot. If objects are added, removed, or edited between page requests, later pages can repeat or skip objects. When you need every object from one consistent view, call `asyncIter()` on the client from [`useOsdkClient`](https://palantir.github.io/osdk-ts/client.md) in an event handler or effect. ## Stream real-time updates Set `streamUpdates: true` to subscribe to changes over a WebSocket. The list then updates when matching objects are created, edited so that they start or stop matching `where`, or deleted, without waiting for a refetch. ```tsx title="src/LiveHiresList.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function LiveHiresList() { const { data } = useOsdkObjects(Employee, { where: { startDate: { $gte: "2026-01-01" } }, orderBy: { startDate: "desc" }, streamUpdates: true, }); return (
      {data?.map((employee) => (
    • {employee.fullName} started {employee.startDate}
    • ))}
    ); } ``` > [!WARNING] > **Streaming does not work with pivotTo or withProperties** > > The server has no WebSocket subscriptions for link traversals or derived properties. TypeScript rejects `streamUpdates` together with `pivotTo`. With `withProperties`, the code compiles, but the hook ignores `streamUpdates` and logs a warning in development. Both kinds of query still load data normally; they refresh when the cache is invalidated instead of in real time. The same applies to `useObjectSet`. ## Fetch conditionally Hooks cannot be called inside a condition, so use `enabled` instead. While `enabled` is `false`, the hook makes no request and returns `data: undefined` and `isLoading: false`. Setting it back to `true` starts the query. ```tsx title="src/DepartmentRoster.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function DepartmentRoster({ department }: { department: string | undefined }) { const { data, isLoading } = useOsdkObjects(Employee, { where: { department: department ?? "" }, enabled: department != null, }); if (department == null) { return

    Pick a department.

    ; } return (
      {isLoading && !data &&
    • Loading…
    • } {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    ); } ``` ## Load one object `useOsdkObject` takes an object type and a primary key, and returns `object`: ```tsx title="src/EmployeeCard.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObject } from "@osdk/react"; export function EmployeeCard({ employeeId }: { employeeId: number }) { const { object: employee, isLoading, error } = useOsdkObject(Employee, employeeId); return (
    {isLoading && !employee &&

    Loading…

    } {error &&

    {error.message}

    } {employee && ( <>

    {employee.fullName}

    {employee.jobTitle}, {employee.department}

    )}
    ); } ``` The third argument is either a boolean that enables or disables the query, or an options object: ```tsx const disabled = useOsdkObject(Employee, employeeId, false); const withOptions = useOsdkObject(Employee, employeeId, { $select: ["fullName", "jobTitle"], $loadPropertySecurityMetadata: true, enabled: employeeId > 0, }); ``` ### Track an instance you already have When a component receives an object from a list, pass the instance itself. The hook does not fetch; it subscribes to the cached copy, so the component re-renders when an action or optimistic update changes that object, and `isOptimistic` tells you whether the change is confirmed. ```tsx title="src/EmployeeRow.tsx" import type { Employee } from "@my-app/sdk"; import { useOsdkObject } from "@osdk/react"; export function EmployeeRow({ employee }: { employee: Employee.OsdkInstance }) { const { object, isOptimistic } = useOsdkObject(employee); const current = object ?? employee; return (
  • {current.fullName}, {current.jobTitle}
  • ); } ``` The instance form takes an optional boolean as its second argument to disable it. ## Refresh data `refetch` on the `useOsdkObjects` result invalidates the whole object type: every cached object, list, and link query of that type refetches, not only this list. Actions already invalidate the types they modify, so you only need `refetch` for changes made outside the app. To refresh one object, invalidate it with the observable client: ```tsx import type { Employee } from "@my-app/sdk"; import { useObservableClient } from "@osdk/react"; export function RefreshButton({ employee }: { employee: Employee.OsdkInstance }) { const observableClient = useObservableClient(); return ; } ``` `useOsdkObject` also returns a `forceUpdate` function, but it is not implemented and throws when called. [Cache invalidation](https://palantir.github.io/osdk-ts/react/cache-invalidation.md) covers the other invalidation methods. ## Reference ### `useOsdkObjects(type, options?)` | Option | Type | Default | Description | | --- | --- | --- | --- | | `where` | `WhereClause` | | Filter clause. Can reference properties defined in `withProperties`. | | `orderBy` | `{ [property]?: "asc" \| "desc" }` | | Sort order, in key order. | | `pageSize` | `number` | `100` | Objects per page. When several components observe the same query, requests use the largest `pageSize` among them. | | `autoFetchMore` | `boolean \| number` | | Load pages automatically: `true` for all, a number for at least that many. | | `$select` | `PropertyKeys[]` | Server default set | Properties to load. Does not narrow the returned type. | | `rids` | `readonly string[]` | | Start from these objects instead of the whole type. Adds `$rid` to results. | | `intersectWith` | `Array<{ where: WhereClause }>` | | Additional filters that every result must also match. | | `pivotTo` | Link name | | Return the objects linked from the matching objects instead. See [Follow links](https://palantir.github.io/osdk-ts/react/links.md#pivot-with-pivotto). | | `withProperties` | `DerivedProperty.Clause` | | Properties computed on the server. See [derived properties](https://palantir.github.io/osdk-ts/react/object-sets.md#add-derived-properties). | | `streamUpdates` | `boolean` | `false` | Subscribe to live changes. Not with `pivotTo` or `withProperties`. | | `enabled` | `boolean` | `true` | When `false`, no request is made and `data` is `undefined`. | | `dedupeIntervalMs` | `number` | `2000` | Two identical queries within this window share one request. | | `$loadPropertySecurityMetadata` | `boolean` | `false` | Populate `$propertySecurities` on each object with per-property marking requirements. | | `$includeAllBaseObjectProperties` | `boolean` | `false` | Interfaces only: also load the implementing type's properties. | | `resolveToObjectType` | `boolean` | `false` | Interfaces only: return implementing object type instances. | | Return | Type | Description | | --- | --- | --- | | `data` | `Osdk.Instance[] \| undefined` | Loaded objects. `undefined` before the first page and while disabled. | | `isLoading` | `boolean` | `true` while the first page or a `fetchMore` page is loading. During a background refetch it is `true` only if the list holds fewer than `pageSize` objects. | | `error` | `Error \| undefined` | The last error, if the query failed. | | `isOptimistic` | `boolean` | Whether the list order or membership includes unconfirmed optimistic changes. | | `fetchMore` | `(() => Promise) \| undefined` | Load the next page. `undefined` when there are no more pages. | | `hasMore` | `boolean` | Whether more pages exist. | | `totalCount` | `string \| undefined` | Total matching objects, when the server reports it. | | `objectSet` | `ObjectSet \| undefined` | The object set the hook queried, after `where`, `intersectWith`, and `pivotTo`. Pass it to [`useOsdkAggregation`](https://palantir.github.io/osdk-ts/react/aggregations.md#aggregate-an-object-set) or [`useObjectSet`](https://palantir.github.io/osdk-ts/react/object-sets.md). | | `refetch` | `() => Promise` | Invalidate the object type and refetch. | ### `useOsdkObject` | Signature | Description | | --- | --- | | `useOsdkObject(type, primaryKey, enabled?)` | Load by primary key. | | `useOsdkObject(type, primaryKey, options?)` | Load by primary key with options. | | `useOsdkObject(instance, enabled?)` | Subscribe to an instance you already have. Reads the cache without fetching. | | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | When `false`, no request is made. | | `$select` | `PropertyKeys[]` | Server default set | Properties to load. | | `$loadPropertySecurityMetadata` | `boolean` | `false` | Populate `$propertySecurities` with per-property marking requirements. | | `$includeAllBaseObjectProperties` | `boolean` | `false` | Interfaces only: also load the implementing type's properties. | | Return | Type | Description | | --- | --- | --- | | `object` | `Osdk.Instance \| undefined` | The object. `undefined` while loading, while disabled, or if it was not found. | | `isLoading` | `boolean` | `true` while a request is in flight. `false` once there is an error. | | `error` | `Error \| undefined` | The last error, if the load failed. | | `isOptimistic` | `boolean` | Whether the object includes unconfirmed optimistic changes. | | `forceUpdate` | `() => void` | Not implemented; throws. Use `invalidateObjects` instead. | # Optimistic updates Source: https://palantir.github.io/osdk-ts/react/optimistic-updates > Show an action's result before the server responds by layering optimistic edits on the cache, with automatic rollback when the action fails. {/* cspell:ignore refetched refetches */} An optimistic update shows the expected result of an action as soon as the user triggers it. You describe the edits, the cache shows them on top of the real data, and they are removed when the action finishes, whether it succeeds or fails. ## Add an optimistic update Add `$optimisticUpdate` to the parameters you pass to `applyAction` from `useOsdkAction`. The callback receives a builder for the edits you expect: ```tsx title="src/DepartmentPicker.tsx" import { Employee, modifyEmployee } from "@my-app/sdk"; import { useOsdkAction, useOsdkObject } from "@osdk/react"; export function DepartmentPicker({ employee }: { employee: Employee.OsdkInstance }) { const { object, isOptimistic } = useOsdkObject(employee); const { applyAction, error } = useOsdkAction(modifyEmployee); const current = object ?? employee; async function moveTo(department: string) { try { await applyAction({ employee, department, $optimisticUpdate: (update) => { update.updateObject(employee.$clone({ department })); }, }); } catch (e) { console.error("modifyEmployee failed", e); } } return (

    {current.fullName} works in {current.department} {isOptimistic && " (saving)"}

    {error &&

    The move failed and was undone.

    }
    ); } ``` `$optimisticUpdate` runs synchronously when you call `applyAction`, before the request is sent. The `$` prefix keeps it apart from the action's own parameters, and it is not sent to the server. ## Builder methods Each method returns the builder, so you can chain calls. | Method | Description | | --- | --- | | `updateObject(instance)` | Replaces a cached object with `instance`. Build it with `$clone`. | | `createObject(type, primaryKey, properties)` | Adds a new object of `type` to the cache. `properties` lists every property of the type; pass `undefined` for values you do not know yet. | | `deleteObject(instance)` | Removes the object from the cache and from every list that contains it. | OSDK objects are immutable. `$clone` returns a copy with the properties you pass changed: ```ts const moved = employee.$clone({ department: "Platform" }); ``` ### Create an object The server assigns the real primary key, so give the optimistic object a temporary one that cannot collide with a real object. This example uses `applyAction` from `useOsdkAction(createOffice)`, for an `Office` type whose properties are `officeId`, `name`, and `city`: ```ts await applyAction({ name, city, $optimisticUpdate: (update) => { const temporaryId = `tmp-${crypto.randomUUID()}`; update.createObject(Office, temporaryId, { officeId: temporaryId, name, city, }); }, }); ``` Lists of that type add the new object if it matches their `where` clause. When the action finishes, the temporary object goes away and the real one loads in its place. ### Edit several objects One callback can describe every edit the action makes. For an action that moves a lead and their reports to a new department: ```ts $optimisticUpdate: (update) => { update .updateObject(lead.$clone({ department })) .updateObject(report.$clone({ department })); }, ``` ## What happens when the action runs ### The optimistic layer is applied Your edits go into a separate layer on top of the cached server data. Every component that reads an edited object, or a list that contains one, re-renders with the edits. ### The action is sent The request goes to Foundry while the layer is shown. `isPending` from `useOsdkAction` is `true`. ### The layer is removed If the action succeeds, the cache first refetches every object the server reports as edited, then removes the layer, so the UI moves from your edits to the server's values without showing the old ones in between. If the action fails, the layer is removed straight away and the UI returns to the previous server values. `applyAction` rejects and `error` is set. You do not undo anything yourself. An optimistic edit can add an object to a list or remove a deleted one, but it does not remove an object that stops matching a list's `where` clause. That list catches up when the server responds. Because the layer is always removed, write the update you expect the server to make. If the server's result differs, for example a property computed on the server, the server's value replaces yours when the layer goes. ## Show that a change is pending Hooks that read from the cache report whether what they show includes optimistic edits: | Hook | Field | `true` when | | --- | --- | --- | | `useOsdkObject` | `isOptimistic` | The object comes from an optimistic layer. | | `useOsdkObjects`, `useObjectSet`, `useLinks` | `isOptimistic` | The membership or order of the list comes from an optimistic layer. An edit that only changes properties of an object already in the list does not set it; check those objects with `useOsdkObject`. | Use `isOptimistic` for a subtle "saving" cue, and `isPending` from `useOsdkAction` to disable controls. ## Simulate latency in development Against a fast backend, the optimistic state can disappear before you see it. In development builds, the cache waits 1000 ms after the server responds before removing the layer, so you can check that the optimistic state renders correctly. The first time it waits, it logs a message to the console. The delay applies only to single `applyAction` calls that pass `$optimisticUpdate`. Batches and actions without an optimistic update are not delayed, and production builds never delay. Change it with the `devMode` prop on `OsdkProvider`: ```tsx title="src/main.tsx" import { OsdkProvider } from "@osdk/react"; import { client } from "./client"; import { App } from "./App"; export function Root() { return ( ); } ``` Set `actionDelayMs: 0` to turn the delay off. `devMode` also accepts `logLevel` and `debug` for logging cache internals; see [Invalidate the cache](https://palantir.github.io/osdk-ts/react/cache-invalidation.md#debug-the-cache). # Users and markings Source: https://palantir.github.io/osdk-ts/react/platform-apis > Load Foundry users, markings, and CBAC classification banners in React with the hooks in @osdk/react/platform-apis. Related Palantir Foundry documentation: - [Foundry REST APIs](https://www.palantir.com/docs/foundry/api/v2/general/overview/introduction) {/* cspell:ignore CBAC cbac refetch refetches */} The hooks in `@osdk/react/platform-apis` call Foundry platform APIs for users and markings with the client from `OsdkProvider`. Use them to show who is signed in, look up other users, list markings, and render classification banners. ## Install the platform packages The hooks depend on two optional peer packages. Install them before importing from `@osdk/react/platform-apis`: ```npm npm install @osdk/foundry.admin @osdk/foundry.core ``` Without them, the bundler fails with `Rollup failed to resolve import "@osdk/foundry.admin"` or a similar error. The rest of `@osdk/react` works without these packages. Every hook needs an `OsdkProvider` above it. The signed-in user's token must allow the platform API you call; a missing permission comes back as an `error`. ## Show the signed-in user `useCurrentFoundryUser` loads the user the client's token belongs to: ```tsx title="src/CurrentUserBadge.tsx" import { useCurrentFoundryUser } from "@osdk/react/platform-apis"; export function CurrentUserBadge() { const { currentUser, isLoading, error } = useCurrentFoundryUser(); return ( {currentUser && `Signed in as ${currentUser.givenName ?? currentUser.username}`} {isLoading && !error && "Loading…"} {error && "Could not load your profile"} ); } ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | When `false`, no request is made. | | Field | Type | Description | | --- | --- | --- | | `currentUser` | `User \| undefined` | The user, with `id`, `username`, `givenName`, `familyName`, `email`, `realm`, `organization`, `status`, and `attributes`. | | `isLoading` | `boolean` | `true` while the request runs. | | `error` | `Error \| undefined` | Set when the request failed. | | `refetch` | `() => void` | Requests the user again. | ## Look up a user `useFoundryUser` takes the user ID as its first argument and options second: ```tsx title="src/UserName.tsx" import { useFoundryUser } from "@osdk/react/platform-apis"; export function UserName({ userId }: { userId: string }) { const { user, error } = useFoundryUser(userId); const fullName = [user?.givenName, user?.familyName].filter(Boolean).join(" "); return ( {error ? "Unknown user" : user ? fullName || user.username : "…"} ); } ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | When `false`, no request is made. | | `status` | `"ACTIVE" \| "DELETED"` | `"ACTIVE"` | Status of the user to look up. Pass `"DELETED"` to resolve users who have been removed. | The result has `user`, `isLoading`, `error`, and `refetch`. A new `userId` triggers a new request. ## List users `useFoundryUsersList` returns one page of users. Pass the previous page's `nextPageToken` as `pageToken` to load the next one: ```tsx title="src/UserDirectory.tsx" import { useFoundryUsersList } from "@osdk/react/platform-apis"; import { useState } from "react"; export function UserDirectory() { const [pageToken, setPageToken] = useState(); const { users, nextPageToken, isLoading, error } = useFoundryUsersList({ pageSize: 50, pageToken, }); return (
    {error &&

    Could not load users.

    } {isLoading && !error &&

    Loading…

    }
      {users?.map((user) => (
    • {user.username}
    • ))}
    ); } ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | When `false`, no request is made. | | `include` | `"ACTIVE" \| "DELETED"` | `"ACTIVE"` | Which users to list. | | `pageSize` | `number` | `1000` | Preferred page size. The server can return more or fewer. | | `pageToken` | `string` | `undefined` | Token for the page to load. Omit for the first page. | | Field | Type | Description | | --- | --- | --- | | `users` | `User[] \| undefined` | The users on this page. | | `nextPageToken` | `string \| undefined` | Token for the next page. `undefined` on the last page. | | `isLoading`, `error`, `refetch` | | As for `useCurrentFoundryUser`. | Each page replaces the previous one. To show every page loaded so far, keep the users you have received in state. ## List markings `useMarkings` lists the markings the user can see, and `useMarkingCategories` lists the categories they belong to. Join them on `marking.categoryId`: ```tsx title="src/MarkingList.tsx" import { useMarkingCategories, useMarkings } from "@osdk/react/platform-apis"; export function MarkingList() { const { markings, error: markingsError } = useMarkings({ includeDeleted: false }); const { categories, error: categoriesError } = useMarkingCategories({ includeDeleted: false, }); const categoryName = new Map(categories?.map((c) => [c.id, c.name] as const)); return (
    {(markingsError ?? categoriesError) &&

    Could not load markings.

    }
      {markings?.map((marking) => (
    • {categoryName.get(marking.categoryId) ?? "Other"}: {marking.name}
    • ))}
    ); } ``` | Hook | Option | Default | Returns | | --- | --- | --- | --- | | `useMarkings` | `includeDeleted` | `true` | `markings`: `Marking[]`, each with `id`, `categoryId`, `name`, `description`, and `deleted`. | | `useMarkingCategories` | `includeDeleted` | `true` | `categories`: `MarkingCategory[]`, each with `id`, `name`, `description`, `markings` (marking IDs), and `deleted`. | | Both | `markingType` | All types | Only markings or categories of this type, such as `"CBAC"`. | Both accept `enabled` and return `isLoading`, `error`, and `refetch`. Deleted entries are included unless you pass `includeDeleted: false`. ## Get a user's markings `useUserViewMarkings` returns the IDs of the markings a user can view. Without `userId`, it uses the signed-in user: ```tsx title="src/useCanView.ts" import { useUserViewMarkings } from "@osdk/react/platform-apis"; export function useCanView(requiredMarkingIds: string[]) { const { markingIds, isLoading, error } = useUserViewMarkings(); const viewable = new Set(markingIds); return { canView: markingIds != null && requiredMarkingIds.every((id) => viewable.has(id)), isLoading, error, }; } ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `userId` | `string` | Signed-in user | The user to look up. | | `enabled` | `boolean` | `true` | When `false`, no request is made. | The result has `markingIds` (`string[] | undefined`), `isLoading`, `error`, and `refetch`. ## Show a classification banner For classification-based access control (CBAC), `useCbacBanner` returns the banner text and colors for a set of marking IDs: ```tsx title="src/ClassificationBanner.tsx" import { useCbacBanner } from "@osdk/react/platform-apis"; export function ClassificationBanner({ markingIds }: { markingIds: string[] }) { const { banner, error } = useCbacBanner({ markingIds }); if (error != null || banner == null) { return null; } const [first, ...rest] = banner.backgroundColors; const background = rest.length > 0 ? `linear-gradient(90deg, ${banner.backgroundColors.join(", ")})` : first; return (
    {banner.classificationString}
    ); } ``` | Field | Type | Description | | --- | --- | --- | | `banner.classificationString` | `string` | The banner text. | | `banner.textColor` | `string` | Text color. | | `banner.backgroundColors` | `string[]` | One or more background colors. | | `banner.markingIds` | `string[]` | The markings the banner represents. | `useCbacMarkingRestrictions` checks a proposed set of marking IDs before you apply it, for example in a marking picker: | Field | Type | Description | | --- | --- | --- | | `restrictions.isValid` | `boolean` | Whether the markings form a valid classification: none are disallowed and every required constraint is met. | | `restrictions.userSatisfiesMarkings` | `boolean` | Whether the signed-in user satisfies the markings. | | `restrictions.impliedMarkings` | `string[]` | Markings that the selection implies. | | `restrictions.disallowedMarkings` | `string[]` | Markings that are disallowed with the selection. | | `restrictions.requiredMarkings` | `string[][]` | Required marking constraints, as groups of marking IDs. | Both hooks take `{ markingIds, enabled? }`, return `isLoading`, `error`, and `refetch`, and make no request while `markingIds` is empty. `useCbacMarkingRestrictions` calls a beta endpoint in preview mode, which must be enabled on your Foundry stack. For a ready-made picker, see the [CbacPicker component](https://palantir.github.io/osdk-ts/components/cbac-picker.md). ## How these hooks load data These hooks do not use the object cache that powers `useOsdkObjects` and the other ontology hooks: - Each mounted hook makes its own request. Two components that call `useCurrentFoundryUser` make two requests. Call the hook once and pass the result down when that matters. - A hook requests again when an option changes. `refetch` requests again on demand. - While a request runs, the previous result is cleared and the data field is `undefined`. - When a request fails, `isLoading` stays `true` next to `error`. Check `error` before `isLoading`, as the examples on this page do. ## Handle errors All hooks return failures as an `Error`. When the failure comes from a Foundry API, it is a `PalantirApiError`, exported from `@osdk/client`. Narrow with `instanceof` to read its fields, all of which are optional: | Field | Type | Description | | --- | --- | --- | | `errorName` | `string` | Stable identifier, such as `UserNotFound`. Switch on this. | | `errorCode` | `string` | Error category, such as `NOT_FOUND` or `PERMISSION_DENIED`. | | `errorDescription` | `string` | Human-readable description. | | `statusCode` | `number` | HTTP status. | | `errorInstanceId` | `string` | Server-side ID for this occurrence. Include it in bug reports. | | `parameters` | `object` | Extra context from the server, such as `{ userId }`. | ```tsx title="src/describePlatformError.ts" import { PalantirApiError } from "@osdk/client"; export function describePlatformError(error: Error): string { if (!(error instanceof PalantirApiError)) { return error.message; } if (error.errorName === "UserNotFound") { return "We couldn't find that user."; } if (error.errorCode === "PERMISSION_DENIED") { return "You don't have permission to see this."; } return `${error.errorDescription ?? error.message} (error ID: ${error.errorInstanceId ?? "unknown"})`; } ``` Use it with any hook on this page: ```tsx title="src/UserCard.tsx" import { useFoundryUser } from "@osdk/react/platform-apis"; import { describePlatformError } from "./describePlatformError"; export function UserCard({ userId }: { userId: string }) { const { user, error } = useFoundryUser(userId); return (
    {error &&

    {describePlatformError(error)}

    } {user &&

    {user.username}

    } {user?.email &&

    {user.email}

    }
    ); } ``` # Test your app Source: https://palantir.github.io/osdk-ts/react/testing > Unit test OSDK React components with Vitest and Testing Library, using @osdk/react/testing and the mocks in @osdk/unit-testing. Related Palantir Foundry documentation: - [Unit testing OSDK code](https://www.palantir.com/docs/foundry/ontology-sdk/typescript-osdk-testing) {/* cspell:ignore jsdom msw MSW stubbable */} Test components that use `@osdk/react` without a Foundry stack. Stub the hooks a component calls, give components that read the OSDK context a test provider, and use mock clients and objects from `@osdk/unit-testing` for code that calls the client directly. ## Choose an approach | What the code under test uses | Approach | Tools | | --- | --- | --- | | Ontology hooks: `useOsdkObjects`, `useOsdkObject`, `useOsdkAction`, `useOsdkFunction`, and the rest | Replace the hook with a stub that returns the state you want to test | `vi.mock`, `createMockOsdkObject` | | `useOsdkClient`, `useObservableClient`, or the hooks in `@osdk/react/platform-apis` | Render inside `TestOsdkProvider` | `@osdk/react/testing`, `createMockClient`, MSW | | The `Client` directly, in a helper or hook | Pass a mock client with stubbed responses | `createMockClient`, `createMockObjectSet` | Stubbing the ontology hooks keeps tests fast and lets you set loading, error, and optimistic states directly. The mock client from `@osdk/unit-testing` cannot power `OsdkProvider` or the ontology hooks, because they need the observable client that `OsdkProvider` builds from a real client. ## Set up Install Vitest, a DOM environment, Testing Library, and the OSDK test helpers. `@osdk/unit-testing` has `@osdk/functions` as a peer dependency, and MSW is only needed for the platform API example: ```npm npm install --save-dev vitest jsdom @testing-library/react @vitejs/plugin-react @osdk/unit-testing @osdk/functions msw ``` Run tests in a DOM environment: ```ts title="vitest.config.ts" import react from "@vitejs/plugin-react"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [react()], test: { environment: "jsdom", }, }); ``` `TestOsdkProvider` and `fakeObservableClient` ship in `@osdk/react` under `@osdk/react/testing`, so they need no extra install. ## Test a component that loads objects This component lists employees with `useOsdkObjects`: ```tsx title="src/EmployeeList.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function EmployeeList() { const { data, isLoading, error } = useOsdkObjects(Employee, { orderBy: { fullName: "asc" }, }); return (
    {isLoading &&

    Loading…

    } {error &&

    {error.message}

    }
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    ); } ``` Replace `useOsdkObjects` with a Vitest mock, keep the rest of `@osdk/react` real, and build objects with `createMockOsdkObject`: ```tsx title="src/EmployeeList.test.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; import { createMockOsdkObject } from "@osdk/unit-testing"; import { cleanup, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { EmployeeList } from "./EmployeeList"; vi.mock("@osdk/react", async (importOriginal) => ({ ...(await importOriginal()), useOsdkObjects: vi.fn(), })); type ListResult = ReturnType; function listResult( overrides: Omit, "data"> & { data?: unknown[] }, ): ListResult { return { data: undefined, isLoading: false, error: undefined, isOptimistic: false, hasMore: false, fetchMore: undefined, objectSet: undefined, refetch: vi.fn(), ...overrides, } as ListResult; } describe("EmployeeList", () => { afterEach(cleanup); it("renders employees", () => { const ada = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" }); const alan = createMockOsdkObject(Employee, { employeeId: 2, fullName: "Alan Turing" }); vi.mocked(useOsdkObjects).mockReturnValue( listResult({ data: [ada, alan] }), ); render(); expect(screen.getAllByRole("listitem").map((li) => li.textContent)).toEqual([ "Ada Lovelace", "Alan Turing", ]); }); it("keeps rendering data while it reloads", () => { const ada = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" }); vi.mocked(useOsdkObjects).mockReturnValue( listResult({ data: [ada], isLoading: true }), ); render(); expect(screen.getByText("Loading…")).toBeTruthy(); expect(screen.getByText("Ada Lovelace")).toBeTruthy(); }); it("shows errors", () => { vi.mocked(useOsdkObjects).mockReturnValue( listResult({ error: new Error("Permission denied") }), ); render(); expect(screen.getByRole("alert").textContent).toBe("Permission denied"); }); it("asks for employees sorted by name", () => { vi.mocked(useOsdkObjects).mockReturnValue(listResult({})); render(); expect(useOsdkObjects).toHaveBeenCalledWith(Employee, { orderBy: { fullName: "asc" }, }); }); }); ``` `createMockOsdkObject(type, properties, options?)` returns an object instance with `$apiName`, `$objectType`, `$primaryKey`, `$rid`, `$clone`, and `$link`. The primary key property must be in `properties`. Pass `options.links` to stub linked objects, and `options.titlePropertyApiName` to set `$title`. ## Test a component that applies an action Stub `useOsdkAction` and assert on the `applyAction` mock. This test drives the `PromoteButton` from [Apply actions](https://palantir.github.io/osdk-ts/react/actions.md): ```tsx title="src/PromoteButton.test.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkAction } from "@osdk/react"; import { createMockOsdkObject } from "@osdk/unit-testing"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { PromoteButton } from "./PromoteButton"; vi.mock("@osdk/react", async (importOriginal) => ({ ...(await importOriginal()), useOsdkAction: vi.fn(), })); const applyAction = vi.fn(); function actionResult(overrides: Partial> = {}) { return { applyAction, validateAction: vi.fn(), data: undefined, error: undefined, isPending: false, isValidating: false, validationResult: undefined, ...overrides, }; } describe("PromoteButton", () => { const employee = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" }); beforeEach(() => { applyAction.mockReset().mockResolvedValue(undefined); vi.mocked(useOsdkAction).mockReturnValue(actionResult()); }); afterEach(cleanup); it("applies modifyEmployee with the new title", async () => { render(); fireEvent.click(screen.getByRole("button", { name: "Make Staff Engineer" })); await waitFor(() => expect(applyAction).toHaveBeenCalledWith({ employee, jobTitle: "Staff Engineer" }), ); }); it("disables the button while the action runs", () => { vi.mocked(useOsdkAction).mockReturnValue(actionResult({ isPending: true })); render(); expect(screen.getByRole("button").hasAttribute("disabled")).toBe(true); }); it("shows the failure", () => { vi.mocked(useOsdkAction).mockReturnValue( actionResult({ error: { unknown: new Error("Network error") } }), ); render(); expect(screen.getByRole("alert").textContent).toContain("Could not update"); }); }); ``` The hook's state does not change by itself when the mock is called, so set `isPending`, `error`, or `validationResult` in each test rather than expecting `applyAction` to update them. To simulate a rejection, use `applyAction.mockRejectedValue(new Error("..."))`. ## Provide the OSDK context `TestOsdkProvider` from `@osdk/react/testing` puts a `client` and an `observableClient` of your choice into context, without the devtools and user-agent setup of `OsdkProvider`. Use it when the code under test calls `useOsdkClient`, `useObservableClient`, or a platform API hook. | Export | Description | | --- | --- | | `TestOsdkProvider` | Provider with `client` and `observableClient` props, both required. Use it only in tests. | | `fakeObservableClient` | An `ObservableClient` whose every method throws. Pass it when the code under test never uses the observable client, so an unexpected call fails loudly. | Platform API hooks call Foundry over HTTP with the context's `client`. A client from `createMockClient` sends those requests to `https://mock.invalid/`, so intercept them with MSW. This test renders the `CurrentUserBadge` from [Users and markings](https://palantir.github.io/osdk-ts/react/platform-apis.md): ```tsx title="src/CurrentUserBadge.test.tsx" import { fakeObservableClient, TestOsdkProvider } from "@osdk/react/testing"; import { createMockClient } from "@osdk/unit-testing"; import { cleanup, render, screen } from "@testing-library/react"; import { http, HttpResponse } from "msw"; import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, expect, it } from "vitest"; import { CurrentUserBadge } from "./CurrentUserBadge"; const server = setupServer(); beforeAll(() => server.listen({ onUnhandledRequest: "error" })); afterEach(() => { server.resetHandlers(); cleanup(); }); afterAll(() => server.close()); it("greets the signed-in user", async () => { server.use( http.get("https://mock.invalid/api/v2/admin/users/getCurrent", () => HttpResponse.json({ id: "user-1", username: "ada", givenName: "Ada", realm: "default", status: "ACTIVE", attributes: {}, }), ), ); render( , ); expect(await screen.findByText("Signed in as Ada")).toBeTruthy(); }); ``` ## Test code that calls the client For a helper or hook that calls the `Client` itself, pass a client from `createMockClient` and register the responses it should get. Stubs match on the exact chain of calls, including arguments: ```ts title="src/loadDepartmentRoster.ts" import { Employee } from "@my-app/sdk"; import type { Client } from "@osdk/client"; export async function loadDepartmentRoster(client: Client, department: string) { const page = await client(Employee) .where({ department: { $eq: department } }) .fetchPage(); return page.data.map((employee) => employee.fullName ?? "Unknown"); } ``` ```ts title="src/loadDepartmentRoster.test.ts" import { Employee, getEmployeeMetrics } from "@my-app/sdk"; import { createMockClient, createMockOsdkObject } from "@osdk/unit-testing"; import { expect, it } from "vitest"; import { loadDepartmentRoster } from "./loadDepartmentRoster"; it("lists the people in a department", async () => { const client = createMockClient(); client .when((stub) => stub(Employee) .where({ department: { $eq: "Platform" } }) .fetchPage(), ) .thenReturnObjects([ createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" }), ]); expect(await loadDepartmentRoster(client, "Platform")).toEqual(["Ada Lovelace"]); }); it("stubs function calls", async () => { const client = createMockClient(); client.whenQuery(getEmployeeMetrics, { department: "Sales" }).thenReturn({ headcount: 12 }); const result = await client(getEmployeeMetrics).executeFunction({ department: "Sales" }); expect(result).toEqual({ headcount: 12 }); }); ``` A call with no matching stub throws, with `No stub for request` for object set calls or `No stub for query ''` for functions. When several stubs match, the last one registered wins. ### `@osdk/unit-testing` reference | Export | Description | | --- | --- | | `createMockClient()` | A `Client` whose responses you stub. Use it with `TestOsdkProvider` or pass it to code that takes a `Client`. It does not stub actions. | | `client.when(callback)` | Stub an object set call chain that ends in `fetchPage`, `fetchOne`, `aggregate`, or similar. Complete it with `thenReturnObjects`, `thenReturnObject`, or `thenReturnAggregation`, depending on the call. | | `client.whenObjectSet(objectSet, callback)` | Stub calls on an object set created with `createMockObjectSet`, for code that takes an `ObjectSet` argument. | | `client.whenQuery(fn, params?)` | Stub a function call. Complete it with `thenReturn(value)` or `thenThrow(error)`. | | `client.clearStubs()` | Remove every stub. | | `createMockOsdkObject(type, properties, options?)` | An object instance. See [Test a component that loads objects](#test-a-component-that-loads-objects). | | `createMockObjectSet(type)` | A standalone object set to pass as an argument and stub with `whenObjectSet`. | | `createMockAttachment(rid, blob?, metadata?)` | An attachment whose `fetchContents` and `fetchMetadata` return the given values. | | `createMockWriteableClient()` | A mock client that records edits, for testing Foundry functions written with `@osdk/functions`. Read the edits with `getEdits()`. | # foundryModel Source: https://palantir.github.io/osdk-ts/reference/aip-core/foundry-model > Create a language model handle backed by the Foundry Language Model Service for generateText, streamText, and LmsChatTransport. ```ts import { foundryModel } from "@osdk/aip-core"; function foundryModel(options: FoundryModelOptions): LanguageModel; ``` Returns an opaque `LanguageModel` that the other `@osdk/aip-core` functions accept. It holds the client and model identifier; it does not send a request. ## Options ### FoundryModelOptions | Prop | Type | Description | | -------- | --------------------------- | ----------------------------------------------------------- | | `client` | `PlatformClient` | Foundry PlatformClient providing the auth token + base URL. | | `model` | `string \| ModelIdentifier` | LMS model API name or registered model RID. | `client` must be a `PlatformClient` from `createPlatformClient`. A string `model` is an LMS model API name, such as `"gpt-4o"`. To use a registered model, pass `{ type: "registeredModel", registeredModelRid }`. ## Returns `LanguageModel`: | Field | Type | Description | | --- | --- | --- | | `modelId` | `string` | `"foundry/"` followed by the API name or RID, for logging. | | `provider` | `string` | Always `"foundry-lms"`. | ## Example ```ts title="src/model.ts" import { foundryModel } from "@osdk/aip-core"; import { createPlatformClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const model = foundryModel({ client: createPlatformClient(foundryUrl, auth), model: "gpt-4o", }); ``` ## See also - [Chat and text generation](https://palantir.github.io/osdk-ts/ai/chat.md) # generateText Source: https://palantir.github.io/osdk-ts/reference/aip-core/generate-text > Generate a complete text response from a Foundry language model in one request. ```ts import { generateText } from "@osdk/aip-core"; function generateText( options: GenerateTextOptions, ): Promise>; ``` Sends one request to the Foundry Language Model Service and resolves when the model finishes. The call is single-step: when the model requests a tool, the result lists the call in `toolCalls`, and your code runs the tool and sends a follow-up request. ## Options ### GenerateTextOptions Options for generateText. | Prop | Type | Description | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `model` | `LanguageModel` | The language model to use. Build one via `foundryModel(...)`. | | `prompt?` | `string \| ModelMessage[]` | Plain text prompt. Mutually exclusive with `messages`. | | `messages?` | `ModelMessage[]` | Conversation history. Mutually exclusive with `prompt`. | | `system?` | `string \| SystemModelMessage[] \| SystemModelMessage` | System instructions, prepended to the conversation. | | `tools?` | `TOOLS` | | | `toolChoice?` | `ToolChoice` | | | `maxOutputTokens?` | `number` | | | `temperature?` | `number` | | | `topP?` | `number` | | | `presencePenalty?` | `number` | | | `frequencyPenalty?` | `number` | | | `stopSequences?` | `string[]` | | | `seed?` | `number` | | | `abortSignal?` | `AbortSignal` | | | `headers?` | `Record` | | | `onStepFinish?` | `((step: StepResult) => void \| Promise)` | | | `onFinish?` | `((event: StepResult & { steps: Array>; totalUsage: LanguageModelUsage; }) => void \| PromiseLike)` | | Pass either `prompt` or `messages`, not both; passing both throws. The call also throws when `system`, `prompt`, and `messages` are all empty. Tool `inputSchema` must be a plain JSON Schema object; any other value is sent as empty parameters and reported in `warnings`. ## Returns ### GenerateTextResult Result of generateText. | Prop | Type | Description | | ------------------ | ------------------------------------------------------ | ----------- | | `content` | `ContentPart[]` | | | `text` | `string` | | | `reasoning` | `ReasoningOutput[]` | | | `reasoningText` | `string \| undefined` | | | `toolCalls` | `ToolCall[]` | | | `toolResults` | `ToolResult[]` | | | `finishReason` | `FinishReason` | | | `rawFinishReason` | `string \| undefined` | | | `usage` | `LanguageModelUsage` | | | `warnings` | `Warning[] \| undefined` | | | `request?` | `RequestMetadata` | | | `response?` | `ResponseMetadata` | | | `providerMetadata` | `ProviderMetadata \| undefined` | | | `totalUsage` | `LanguageModelUsage` | | | `steps` | `StepResult[]` | | `steps` always holds one step, and `totalUsage` equals `usage`. ## Example ```ts title="src/summarize.ts" import { foundryModel, generateText } from "@osdk/aip-core"; import type { PlatformClient } from "@osdk/client"; export async function summarize(client: PlatformClient, notes: string) { const { text, usage } = await generateText({ model: foundryModel({ client, model: "gpt-4o" }), system: "Summarize in two sentences.", prompt: notes, maxOutputTokens: 200, }); console.log(usage); return text; } ``` ## See also - [Chat and text generation](https://palantir.github.io/osdk-ts/ai/chat.md) - [streamText](https://palantir.github.io/osdk-ts/reference/aip-core/stream-text.md) # LmsChatTransport Source: https://palantir.github.io/osdk-ts/reference/aip-core/lms-chat-transport > A ChatTransport that streams chat replies from the Foundry Language Model Service as UI message chunks. ```ts import { LmsChatTransport } from "@osdk/aip-core"; class LmsChatTransport implements ChatTransport { constructor(opts: LmsChatTransportOptions); sendMessages(args: ChatTransportSendMessagesArgs): Promise>; reconnectToStream(args: ChatTransportReconnectArgs): Promise | null>; } ``` Converts a `UIMessage[]` conversation to model messages, calls [`streamText`](https://palantir.github.io/osdk-ts/reference/aip-core/stream-text.md), and returns the reply as a stream of `UIMessageChunk`s in the AI SDK v5 UI format. Pass it to any chat UI that accepts a `ChatTransport`. ## Options ### LmsChatTransportOptions Options for LmsChatTransport. Configures the streamed chat completion against the Foundry Language Model Service. | Prop | Type | Description | | ------------------- | ------------------------------------- | ----------------------------------------------------------------- | | `model` | `LanguageModel` | Foundry-LMS-backed language model. Build via `foundryModel(...)`. | | `system?` | `string` | System prompt prepended to every request. | | `temperature?` | `number` | Sampling controls. | | `maxOutputTokens?` | `number` | | | `topP?` | `number` | | | `presencePenalty?` | `number` | | | `frequencyPenalty?` | `number` | | | `stopSequences?` | `string[]` | | | `seed?` | `number` | | | `headers?` | `Record` | Extra HTTP headers forwarded to LMS. | `headers` passed to `sendMessages` are merged over the constructor's `headers`. ## Methods | Method | Returns | Description | | --- | --- | --- | | `sendMessages(args)` | `Promise>` | Streams the assistant reply to `args.messages`, using `args.messageId` as its ID. Model errors arrive as an `{ type: "error", errorText }` chunk, after which the stream errors. | | `reconnectToStream(args)` | `Promise` | Always resolves to `null`; the transport cannot resume a stream. | ## Example ```ts title="src/askOnce.ts" import { foundryModel, generateMessageId, LmsChatTransport } from "@osdk/aip-core"; import type { PlatformClient } from "@osdk/client"; export async function askOnce(client: PlatformClient, question: string) { const transport = new LmsChatTransport({ model: foundryModel({ client, model: "gpt-4o" }), system: "Answer briefly.", }); const stream = await transport.sendMessages({ trigger: "submit-message", chatId: "chat-1", messageId: generateMessageId(), messages: [{ id: generateMessageId(), role: "user", parts: [{ type: "text", text: question }] }], abortSignal: undefined, }); let answer = ""; const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; if (value.type === "text-delta") answer += value.delta; } return answer; } ``` ## See also - [Chat and text generation](https://palantir.github.io/osdk-ts/ai/chat.md) - [Utilities](https://palantir.github.io/osdk-ts/reference/aip-core/utilities.md) # streamText Source: https://palantir.github.io/osdk-ts/reference/aip-core/stream-text > Stream a text response from a Foundry language model as it is generated. ```ts import { streamText } from "@osdk/aip-core"; function streamText( options: StreamTextOptions, ): StreamTextResult; ``` Starts the request immediately and returns streams and promises without awaiting. Read `textStream` for text only, or `fullStream` for every chunk, including reasoning, tool calls, and the finish event. Like `generateText`, the call is single-step. ## Options ### StreamTextOptions Options for streamText. | Prop | Type | Description | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `model` | `LanguageModel` | The language model to use. Build one via `foundryModel(...)`. | | `prompt?` | `string \| ModelMessage[]` | Plain text prompt. Mutually exclusive with `messages`. | | `messages?` | `ModelMessage[]` | Conversation history. Mutually exclusive with `prompt`. | | `system?` | `string \| SystemModelMessage[] \| SystemModelMessage` | System instructions, prepended to the conversation. | | `tools?` | `TOOLS` | | | `toolChoice?` | `ToolChoice` | | | `maxOutputTokens?` | `number` | | | `temperature?` | `number` | | | `topP?` | `number` | | | `presencePenalty?` | `number` | | | `frequencyPenalty?` | `number` | | | `stopSequences?` | `string[]` | | | `seed?` | `number` | | | `abortSignal?` | `AbortSignal` | | | `headers?` | `Record` | | | `onChunk?` | `((chunk: TextStreamChunk) => void \| PromiseLike)` | Fires for every chunk emitted on `fullStream`. | | `onError?` | `((error: Error) => void \| PromiseLike)` | Fires when the stream errors out. The same error is also emitted via the stream. | | `onFinish?` | `((event: { finishReason: FinishReason; text: string; reasoningText: string \| undefined; toolCalls: Array; usage: LanguageModelUsage; totalUsage: LanguageModelUsage; warnings: Array \| undefined; response: ResponseMetadata \| undefined; request: RequestMetadata \| undefined; }) => void \| PromiseLike` | Stream of all chunk events. | | `textStream` | `ReadableStream` | Stream of just text-delta strings (convenience). | | `text` | `Promise` | Resolves to the final accumulated assistant text. | | `reasoningText` | `Promise` | Resolves to the final accumulated reasoning text, if any. | | `usage` | `Promise` | Resolves to the final usage. | | `totalUsage` | `Promise` | Resolves to the same usage (single-step v0). | | `finishReason` | `Promise` | Resolves to the finish reason. | | `toolCalls` | `Promise[]>` | Resolves to the accumulated tool calls. | | `warnings` | `Promise` | Resolves to v0 warnings, if any. | | `response` | `Promise` | Resolves to response metadata once the stream finishes. | | `request` | `Promise` | Resolves to the request metadata. | On failure, `fullStream` emits `{ type: "error", error }` and then errors, and the promises reject, except `warnings`, which still resolves. ### `TextStreamChunk` | `type` | Fields | | --- | --- | | `"text-delta"` | `id`, `delta` | | `"reasoning-delta"` | `id`, `delta` | | `"tool-call"` | `toolCallId`, `toolName`, `input` | | `"finish"` | `finishReason`, `rawFinishReason`, `usage` | | `"error"` | `error` | ## Example ```ts title="src/streamAnswer.ts" import { foundryModel, streamText } from "@osdk/aip-core"; import type { PlatformClient } from "@osdk/client"; export async function streamAnswer( client: PlatformClient, question: string, onText: (delta: string) => void, ) { const result = streamText({ model: foundryModel({ client, model: "gpt-4o" }), prompt: question, }); const reader = result.textStream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; onText(value); } return result.finishReason; } ``` ## See also - [Chat and text generation](https://palantir.github.io/osdk-ts/ai/chat.md) - [generateText](https://palantir.github.io/osdk-ts/reference/aip-core/generate-text.md) - [LmsChatTransport](https://palantir.github.io/osdk-ts/reference/aip-core/lms-chat-transport.md) # Utilities Source: https://palantir.github.io/osdk-ts/reference/aip-core/utilities > generateMessageId and getUIMessageText, helpers for working with UIMessage conversations in @osdk/aip-core. ```ts import { generateMessageId, getUIMessageText } from "@osdk/aip-core"; function generateMessageId(): string; function getUIMessageText(message: UIMessage): string; ``` Helpers for building and reading the `UIMessage` objects that [`LmsChatTransport`](https://palantir.github.io/osdk-ts/reference/aip-core/lms-chat-transport.md) consumes. ## `generateMessageId` Returns `crypto.randomUUID()` when available, otherwise a random `msg-` prefixed ID. ## `getUIMessageText` Concatenates the `text` parts of `message` and ignores reasoning and file parts. | Parameter | Type | Description | | --- | --- | --- | | `message` | `UIMessage` | `{ id, role, parts, metadata? }`, where `role` is `"system"`, `"user"`, or `"assistant"`. | ## Example ```ts title="src/messages.ts" import { generateMessageId, getUIMessageText, type UIMessage } from "@osdk/aip-core"; export function userMessage(text: string): UIMessage { return { id: generateMessageId(), role: "user", parts: [{ type: "text", text }] }; } export function lastReply(messages: UIMessage[]): string { const reply = messages.findLast((m) => m.role === "assistant"); return reply ? getUIMessageText(reply) : ""; } ``` ## See also - [Chat and text generation](https://palantir.github.io/osdk-ts/ai/chat.md) # createClient Source: https://palantir.github.io/osdk-ts/reference/client/create-client > Create the OSDK Client that queries objects, applies actions, and executes functions against one Ontology. ```ts import { createClient } from "@osdk/client"; function createClient( baseUrl: string, ontologyRid: string | Promise, tokenProvider: () => Promise, options?: { logger?: Logger; UNSTABLE_DO_NOT_USE_BRANCH?: string | null; headers?: Record; }, fetchFn?: typeof fetch, ): Client; ``` Returns a `Client` bound to one Foundry stack and Ontology. Call the client with a definition from your generated SDK to get the matching operations, such as `client(Employee)` for an [`ObjectSet`](https://palantir.github.io/osdk-ts/reference/client/object-set.md). ## Parameters The options type is inline in the source, so these tables are written by hand. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `baseUrl` | `string` | | The base URL of your Foundry stack, such as `https://example.palantirfoundry.com`. | | `ontologyRid` | `string \| Promise` | | The Ontology RID, usually `$ontologyRid` from the generated SDK. A string that does not start with `ri.` throws `Invalid ontology RID`. | | `tokenProvider` | `() => Promise` | | Returns a bearer token for each request, such as a client from `@osdk/oauth`. | | `options` | `object` | | See below. | | `fetchFn` | `typeof fetch` | The global `fetch` | The `fetch` implementation for every request. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `logger` | `Logger` | A minimal built-in logger | Receives the client's log output. | | `headers` | `Record` | | Extra headers sent with every request. | | `UNSTABLE_DO_NOT_USE_BRANCH` | `string \| null` | Read from the page | Beta. The Foundry branch for every request. When omitted in a browser, the client reads the `foundryBranchRid` query parameter, then the branch meta tag injected by OSDK build tooling. `null` uses the default branch. | ## Returns `Client`, a function with one call signature per definition kind, plus `fetchMetadata`. | Call | Returns | | --- | --- | | `client(objectType)` or `client(interface)` | The `ObjectSet` declared by the generated SDK for that type. See [ObjectSet](https://palantir.github.io/osdk-ts/reference/client/object-set.md). Without a declared set, an interface gets a `MinimalObjectSet`, which has only `fetchPage`, `fetchPageWithErrors`, `asyncIter`, `where`, `subscribe`, and `experimental_asyncIterLinks`. | | `client(action)` | `{ applyAction, batchApplyAction }`. | | `client(query)` | `{ executeFunction }`. | | `client.fetchMetadata(definition)` | `Promise` of `ObjectMetadata`, `InterfaceMetadata`, `ActionMetadata`, or `QueryMetadata`, matching the definition. | ## Example ```ts title="src/client.ts" import { $ontologyRid, Employee } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); export const client = createClient(foundryUrl, $ontologyRid, auth); export async function firstEngineers() { const page = await client(Employee) .where({ department: "Engineering" }) .fetchPage({ $pageSize: 10, $select: ["fullName"] }); return page.data; } ``` ## See also - [Create a client](https://palantir.github.io/osdk-ts/client.md) - [Authentication](https://palantir.github.io/osdk-ts/authentication.md) # createPlatformClient Source: https://palantir.github.io/osdk-ts/reference/client/create-platform-client > Create a client for Foundry platform APIs only, without binding it to an Ontology. ```ts import { createPlatformClient } from "@osdk/client"; function createPlatformClient( baseUrl: string, tokenProvider: () => Promise, options?: undefined, fetchFn?: typeof globalThis.fetch, ): PlatformClient; ``` Returns a `PlatformClient` that you pass to functions from the `@osdk/foundry.*` packages, such as `Users.getCurrent(client)`. A `Client` from [`createClient`](https://palantir.github.io/osdk-ts/reference/client/create-client.md) works with platform APIs too, so you only need this when you have no Ontology to query. ## Parameters | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `baseUrl` | `string` | | The base URL of your Foundry stack. | | `tokenProvider` | `() => Promise` | | Returns a bearer token for each request. | | `options` | `undefined` | | Reserved. Pass `undefined`. | | `fetchFn` | `typeof fetch` | The global `fetch` | The `fetch` implementation for every request. | ## Returns `PlatformClient`: the base URL, token provider, and `fetch` that `@osdk/foundry.*` functions read. ## Example ```ts title="src/whoami.ts" import { createPlatformClient } from "@osdk/client"; import { Users } from "@osdk/foundry.admin"; import { createConfidentialOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createConfidentialOauthClient( process.env.FOUNDRY_CLIENT_ID!, process.env.FOUNDRY_CLIENT_SECRET!, foundryUrl, ); const platformClient = createPlatformClient(foundryUrl, auth); const me = await Users.getCurrent(platformClient); console.log(me.username); ``` ## See also - [Platform SDK](https://palantir.github.io/osdk-ts/platform.md) - [Platform SDK setup](https://palantir.github.io/osdk-ts/platform/setup.md) # Errors Source: https://palantir.github.io/osdk-ts/reference/client/errors > PalantirApiError and ActionValidationError, the error classes thrown by @osdk/client. ```ts import { ActionValidationError, PalantirApiError } from "@osdk/client"; class PalantirApiError extends Error { errorName?: string; errorCode?: string; errorDescription?: string; statusCode?: number; errorInstanceId?: string; parameters?: any; } class ActionValidationError extends Error { validation: ActionValidationResponse; } ``` Requests that Foundry rejects throw `PalantirApiError`. Network failures and responses that are not JSON also throw a `PalantirApiError`, with no `errorCode` and the underlying error on `cause`. If your token provider throws, the client rethrows a plain `Error`. `applyAction` throws `ActionValidationError` when the server reports the parameters as `INVALID`; with `$validateOnly: true` it returns the validation response instead. Check with `instanceof`. ## `PalantirApiError` The class has no JSDoc and inherits `Error` fields, so this table is written by hand. | Field | Type | Description | | --- | --- | --- | | `message` | `string` | A readable summary of the error. | | `errorName` | `string \| undefined` | The Foundry error name, such as `ObjectNotFound`. | | `errorCode` | `string \| undefined` | The error category, such as `NOT_FOUND` or `PERMISSION_DENIED`. | | `errorDescription` | `string \| undefined` | A longer description from the server. | | `statusCode` | `number \| undefined` | The HTTP status code. | | `errorInstanceId` | `string \| undefined` | An ID for this occurrence. Include it when you report an issue to Palantir support. | | `parameters` | `any` | Error-specific details, such as the primary key that was not found. | ## `ActionValidationError` | Field | Type | Description | | --- | --- | --- | | `message` | `string` | `"Validation Error: "` followed by the validation response as JSON. | | `validation.result` | `"VALID" \| "INVALID"` | The overall result. | | `validation.submissionCriteria` | `SubmissionCriteriaEvaluation[]` | Each submission criterion and whether it passed. | | `validation.parameters` | `Record` | The evaluation of each parameter, by parameter ID. | ## Example ```ts title="src/promote.ts" import { Employee, modifyEmployee } from "@my-app/sdk"; import { ActionValidationError, PalantirApiError, type Client } from "@osdk/client"; export async function promote(client: Client, employeeId: number) { try { const employee = await client(Employee).fetchOne(employeeId); await client(modifyEmployee).applyAction({ employee, jobTitle: "Lead" }); } catch (e) { if (e instanceof ActionValidationError) { return { ok: false, reason: e.validation.result }; } if (e instanceof PalantirApiError) { return { ok: false, reason: `${e.errorName ?? "Error"} (${e.statusCode})` }; } throw e; } return { ok: true }; } ``` ## See also - [Errors](https://palantir.github.io/osdk-ts/sdk/errors.md) - [useOsdkAction](https://palantir.github.io/osdk-ts/reference/react/use-osdk-action.md) # ObjectSet Source: https://palantir.github.io/osdk-ts/reference/client/object-set > Methods of an OSDK ObjectSet for filtering, set operations, pivots, aggregation, paging, and subscriptions. ```ts import type { ObjectSet } from "@osdk/client"; interface ObjectSet< Q extends ObjectOrInterfaceDefinition = any, UNUSED_OR_RDP extends BaseObjectSet | Record = never, > { /* methods below */ } ``` An `ObjectSet` describes a set of objects without loading them. `client(Employee)` returns the set of all employees; methods such as `where` and `pivotTo` return new sets, and methods such as `fetchPage` and `aggregate` send a request. `RDPs` holds the derived properties added with `withProperties`. ## Methods `ObjectSet` is composed of many generic signatures that a generated table cannot render, so this table is written by hand. ### Build a set These methods return a new set and do not send a request. | Method | Returns | Description | | --- | --- | --- | | `where(clause)` | `this` | Keeps objects that match a [`WhereClause`](https://palantir.github.io/osdk-ts/reference/client/where-clause.md). Chained calls combine with AND. | | `union(...sets)` | `this` | Objects in this set or any of `sets`. | | `intersect(...sets)` | `this` | Objects in this set and every one of `sets`. | | `subtract(...sets)` | `this` | Objects in this set and in none of `sets`. | | `pivotTo(linkName)` | `ObjectSet>` | The objects linked from this set through `linkName`. | | `withProperties(definitions)` | `ObjectSet` | Adds derived properties computed on the server. Each value is a function of a builder, such as `(base) => base.pivotTo("reports").aggregate("$count")`. | | `nearestNeighbors(query, numNeighbors, property)` | `this` | The `numNeighbors` objects (1 to 500) closest to `query`, a string or a vector, on a vector `property`. Order by `"relevance"` to get each object's `$score`. | | `narrowToType(type)` | `ObjectSet` | Casts to an interface this type implements, or to an object type that implements this interface. Objects that do not match are dropped. | ### Load objects | Method | Returns | Description | | --- | --- | --- | | `fetchPage(args?)` | `Promise>>` | One page of objects. Continue with `$nextPageToken`. | | `fetchPageWithErrors(args?)` | `Promise>>>` | Like `fetchPage`, but returns `{ value }` or `{ error }` instead of throwing. | | `asyncIter(args?)` | `AsyncIterableIterator>` | Every object, page by page, against a consistent snapshot. Takes the `fetchPage` arguments except `$pageSize`, `$nextPageToken`, `$snapshot`, and `$EXPERIMENTAL_defaultLoadLevel`. | | `fetchOne(primaryKey, options?)` | `Promise>` | One object by primary key. Throws if it does not exist. Object types only. Takes `$select`, `$includeRid`, and `$loadPropertySecurityMetadata`. | | `fetchOneWithErrors(primaryKey, options?)` | `Promise>>` | Like `fetchOne`, but returns `{ value }` or `{ error }`. Object types only. | | `aggregate(request)` | `Promise>` | Runs `$select` metrics, optionally grouped by `$groupBy`. | `PageResult` is `{ data: T[]; nextPageToken: string | undefined; totalCount: string }`. ### Watch for changes | Method | Returns | Description | | --- | --- | --- | | `subscribe(listener, options?)` | `{ unsubscribe: () => void }` | Opens a WebSocket subscription. `listener` takes `onChange`, `onSuccessfulSubscription`, `onOutOfDate`, and `onError`; `options` takes `properties` and `includeRid`. | | `experimental_asyncIterLinks(linkNames)` | `AsyncIterableIterator<{ source, target, linkType }>` | Beta. Yields every link of the given types from objects in this set. `source` and `target` hold `$apiName` and `$primaryKey`. | ## `fetchPage` arguments ### FetchPageArgs | Prop | Type | Description | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$nextPageToken?` | `string` | | | `$pageSize?` | `number` | The number of objects in one page. This does not limit the total number of objects: continue with `nextPageToken` to load further pages. | | `$applyModifiers?` | `({ [P in Exclude, PropsWithReducers>]?: "applyMainValue" \| undefined; } & { [P in Exclude, PropsWithMainValue<...>>]?: "applyReducers" \| undefined; } & ... & MODIFIERS & ...)` | Applies ontology-configured reducers or struct main values to properties by API name. Only properties with the corresponding configuration in the generated SDK accept a modifier: - `"applyReducers"`: reduces an array to a single element using its configured reducers. - `"applyMainValue"`: extracts a struct's configured main value. One main-value field returns that field's value; multiple fields return a struct containing only those fields. - `"applyReducersAndExtractMainValue"`: reduces a struct array, then extracts its main value. Requires both reducers and a main value. When passing `$select`, include every modified property using its plain API name, along with any other properties you need. Unlisted properties are not modified by this option. The returned property types reflect the modifiers, preserving property nullability. For an explicit `Osdk.Instance` type, use `"propertyApiName:modifier"` in its property keys. | | `$EXPERIMENTAL_defaultLoadLevel?` | `DEFAULT_LOAD_LEVEL` | Best-effort load level applied to every property without listing them: reducers and struct main values where defined, other properties unchanged. A per-property `$applyModifiers` entry wins. | | `$snapshot?` | `boolean` | Ensures paging consistency by freezing the view at the time of query to prevent duplicate or missing items. Setting $snapshot to false ensures that you will always get the latest results. Without a snapshot, if objects are added, removed, or edited between requests, later pages may repeat or skip objects. A snapshot configured for a function run still applies even when this is `false`. With a snapshot, pass `$snapshot: true` on every page request; paging fails if the snapshot expires or the backend detects a paging inconsistency (`PagingInconsistencyDetected`). Stream-backed object types do not provide this snapshot guarantee across pages. `asyncIter()` always requests a snapshot. Default: `false` | | `$orderBy?` | `(ORDER_BY_OPTIONS & (ORDER_BY_OPTIONS \| ObjectSetArgs.OrderByOptions>))` | | | `$select?` | `readonly K[]` | The properties to load for each object. If omitted, the API loads its default property set (vector properties, for example, are not included). The primary key is always returned, even when it is not selected. Select only the properties your code needs. Loading unused properties wastes bandwidth and compute and can slow down retrieval, and reading fewer properties afterwards does not avoid the cost of fetching them. Ontology-defined derived properties are not returned by default and must be included in `$select`. Include any other properties you need in the same selection. Runtime-defined derived properties added via `.withProperties(...)` are returned by default only when `$select` is omitted. If you pass `$select`, include them in the selection as well. | | `$includeRid?` | `R` | | | `$loadPropertySecurityMetadata?` | `PROPERTY_SECURITIES` | | | `$UNSTABLE_loadOntologyDefinedDerivedProperties?` | `boolean` | | | `$includeAllBaseObjectProperties?` | `(PropertyKeys extends K ? T : never)` | | `$orderBy` takes `{ [property]: "asc" | "desc" }`, or `"relevance"` after `nearestNeighbors`. `$includeRid: true` adds `$rid` to each object. `$includeAllBaseObjectProperties: true` loads every property of the underlying object type for interface sets. ## Example ```ts title="src/topEarners.ts" import { Employee } from "@my-app/sdk"; import type { Client } from "@osdk/client"; export async function topEarners(client: Client, city: string) { const inCity = client(Employee) .where({ salary: { $gt: 100_000 } }) .intersect(client(Employee).pivotTo("office").where({ city }).pivotTo("occupants")); const page = await inCity.fetchPage({ $select: ["fullName", "salary"], $orderBy: { salary: "desc" }, $pageSize: 20, }); return page.data.map((e) => `${e.fullName}: ${e.salary}`); } ``` ## See also - [Load objects](https://palantir.github.io/osdk-ts/sdk/objects.md) - [Filtering](https://palantir.github.io/osdk-ts/sdk/filtering.md) - [Links](https://palantir.github.io/osdk-ts/sdk/links.md) - [Aggregations](https://palantir.github.io/osdk-ts/sdk/aggregations.md) - [Derived properties](https://palantir.github.io/osdk-ts/sdk/derived-properties.md) - [Subscriptions](https://palantir.github.io/osdk-ts/sdk/subscriptions.md) # Osdk.Instance Source: https://palantir.github.io/osdk-ts/reference/client/osdk-instance > The type of a loaded object, with its properties plus $-prefixed fields for identity, links, and conversion. ```ts import type { Osdk } from "@osdk/client"; namespace Osdk { type Instance< Q extends ObjectOrInterfaceDefinition, OPTIONS extends never | "$rid" | "$allBaseProperties" | "$propertySecurities" = never, P extends PropertyKeys | ReducedValues = PropertyKeys, R extends Record = {}, >; } ``` Every object returned by `fetchPage`, `fetchOne`, `asyncIter`, and the `@osdk/react` hooks has this type. It holds the properties in `P`, the derived properties in `R`, and the fields below. Generated SDKs export a shorthand, such as `Employee.OsdkInstance`. | Type parameter | Description | | --- | --- | | `Q` | The object type or interface. | | `OPTIONS` | Extra fields: `"$rid"` adds `$rid`, `"$propertySecurities"` adds `$propertySecurities`, and `"$allBaseProperties"` marks an interface instance that carries every property of its object type. | | `P` | The loaded properties. Narrowed by `$select`. | | `R` | Derived properties added with `withProperties`. | ## Fields `Osdk.Instance` is an intersection of mapped and conditional types, so this table is written by hand. | Field | Type | Description | | --- | --- | --- | | `$apiName` | `Q["apiName"]` | The API name of `Q`. For an interface instance, the interface name. | | `$objectType` | `string` | The API name of the underlying object type, also for interface instances. | | `$primaryKey` | `PrimaryKeyType` | The primary key value. | | `$title` | `string \| undefined` | The value of the type's title property. | | `$objectSpecifier` | `ObjectSpecifier` | A string that identifies the object across object types. | | `$link` | `{ [link]: SingleLinkAccessor \| ObjectSet }` | Links of the object. A single link has `fetchOne` and `fetchOneWithErrors`; a many link is an [`ObjectSet`](https://palantir.github.io/osdk-ts/reference/client/object-set.md). | | `$as` | `(type) => Osdk.Instance` | Converts between an object type and an interface it implements, mapping property names. | | `$clone` | `(updates?) => Osdk.Instance` | Returns a copy with some properties replaced. Use it to build optimistic updates. | | `$rid` | `string` | The object's RID. Present only when loaded with `$includeRid: true`. | | `$propertySecurities` | `ObjectPropertySecurities` | Per-property marking requirements. Present only when loaded with `$loadPropertySecurityMetadata: true`. | | `$score` | `number` | Relevance score. Present only when ordered by `"relevance"`. | ## Example ```ts title="src/describeEmployee.ts" import { Employee, Worker } from "@my-app/sdk"; import type { Client, Osdk } from "@osdk/client"; export async function describeEmployee(client: Client, employeeId: number) { const employee: Osdk.Instance = await client(Employee).fetchOne(employeeId); const lead = await employee.$link.lead.fetchOne(); const reports = await employee.$link.reports.fetchPage({ $pageSize: 5 }); const asWorker = employee.$as(Worker); return { key: `${employee.$objectType}:${employee.$primaryKey}`, title: employee.$title, lead: lead.fullName, reports: reports.data.map((r) => r.fullName), workerName: asWorker.name, }; } ``` ## See also - [Load objects](https://palantir.github.io/osdk-ts/sdk/objects.md) - [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md) # WhereClause Source: https://palantir.github.io/osdk-ts/reference/client/where-clause > Filter operators accepted by ObjectSet.where and the where option of @osdk/react hooks, by property type. ```ts import type { WhereClause } from "@osdk/client"; type WhereClause< T extends ObjectOrInterfaceDefinition, RDPs extends Record = {}, > = | { $and: WhereClause[] } | { $or: WhereClause[] } | { $not: WhereClause } | { $title?: Filter; $primaryKey?: Filter } | { [property in PropertyKeys]?: FilterFor }; ``` A where clause maps property names to filters. Properties in one clause combine with AND. A bare value, such as `{ department: "Engineering" }`, is shorthand for `$eq`. Each filter object holds exactly one operator. The type is a union of mapped and conditional types, so these tables are written by hand. ## Logical operators | Operator | Value | Matches | | --- | --- | --- | | `$and` | `WhereClause[]` | Objects that match every clause. | | `$or` | `WhereClause[]` | Objects that match at least one clause. | | `$not` | `WhereClause` | Objects that do not match the clause. | ## Operators by property type | Operator | string | number | date and timestamp | boolean | Value | | --- | --- | --- | --- | --- | --- | | `$eq`, `$ne` | Yes | Yes | Yes | Yes | A value of the property's type. | | `$in` | Yes | Yes | Yes | Yes | An array of values. An empty array matches every object. | | `$isNull` | Yes | Yes | Yes | Yes | `true` or `false`. | | `$gt`, `$gte`, `$lt`, `$lte` | Yes | Yes | Yes | | A bound. Dates and timestamps take ISO 8601 strings. | | `$startsWith` | Yes | | | | A prefix, or `{ term, phoneticSearch? }`. | | `$containsAnyTerm` | Yes | | | | A string, `{ term, fuzzySearch? }`, or `{ term, phoneticSearch? }`. Matches any whitespace-separated term. | | `$containsAllTerms` | Yes | | | | A string, `{ term, fuzzySearch? }`, or `{ term, phoneticSearch? }`. Matches every term, in any order. | | `$containsAllTermsInOrder` | Yes | | | | A string, or `{ term, phoneticSearch? }`. Matches the terms in order. | | `$interval` | Yes | | | | An `IntervalRule`. | | `$matchesRegex` | Yes | | | | Beta. A regular expression in Foundry search syntax. | Number filters apply to `integer`, `long`, `double`, `float`, `decimal`, and `byte` properties. ### Array properties | Operator | Value | Matches | | --- | --- | --- | | `$contains` | An element value | Arrays that contain the value. | | `$isNull` | `boolean` | Arrays that are null, or not null. | ### Geo properties `geopoint` and `geoshape` properties take `$within`, `$intersects`, and `$isNull`. | Operator | Value | | --- | --- | | `$within` | `{ $distance: [number, unit], $of: [lon, lat] \| Point }`, `{ $bbox: BBox }`, a `BBox`, `{ $polygon: coordinates }`, or a GeoJSON `Polygon`. | | `$intersects` | `{ $bbox: BBox }`, a `BBox`, `{ $polygon: coordinates }`, or a GeoJSON `Polygon`. | The distance unit is one of `"cm"`, `"m"`, `"km"`, `"inches"`, `"feet"`, `"yards"`, `"miles"`, or `"nautical miles"`, or a singular or long form such as `"meter"` or `"kilometers"`. ### Struct properties Filter one field of a struct property by nesting it: `{ address: { city: { $eq: "Denver" } } }`. A struct filter holds exactly one field. ## Example ```ts title="src/seniorEngineers.ts" import { Employee } from "@my-app/sdk"; import type { Client, WhereClause } from "@osdk/client"; const seniorEngineers: WhereClause = { $and: [ { department: "Engineering" }, { startDate: { $lt: "2020-01-01" } }, { $or: [{ jobTitle: { $startsWith: "Senior" } }, { skills: { $contains: "Go" } }] }, { $not: { salary: { $isNull: true } } }, ], }; export function loadSeniorEngineers(client: Client) { return client(Employee).where(seniorEngineers).fetchPage({ $pageSize: 50 }); } ``` ## See also - [Filtering](https://palantir.github.io/osdk-ts/sdk/filtering.md) # API reference Source: https://palantir.github.io/osdk-ts/reference > Signatures, options, and return types for the public APIs of @osdk/react, @osdk/client, @osdk/oauth, and @osdk/aip-core. Look up the exact signature, options, and return type of each public API. Most option and return tables are generated from the TypeScript source and its JSDoc; a page says so when a table is written by hand. For walkthroughs, follow the "See also" links on each page. ## `@osdk/react` | API | Description | | --- | --- | | [`OsdkProvider`](https://palantir.github.io/osdk-ts/reference/react/osdk-provider.md) | Shares a client and its cache with the hooks below it. | | [`useOsdkObjects`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-objects.md) | Loads a list of objects of one type or interface. | | [`useOsdkObject`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-object.md) | Loads one object by primary key, or observes an instance. | | [`useLinks`](https://palantir.github.io/osdk-ts/reference/react/use-links.md) | Loads the objects linked from one or more objects. | | [`useObjectSet`](https://palantir.github.io/osdk-ts/reference/react/use-object-set.md) | Loads a list from an `ObjectSet`, with set operations and pivots. | | [`useStableObjectSet`](https://palantir.github.io/osdk-ts/reference/react/use-stable-object-set.md) | Keeps an `ObjectSet` referentially stable across renders. | | [`useOsdkAggregation`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-aggregation.md) | Runs a server-side aggregation. | | [`useOsdkFunction`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-function.md) | Executes a function and caches the result. | | [`useOsdkFunctions`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-functions.md) | Executes several functions from one hook. | | [`useOsdkAction`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-action.md) | Applies or validates an action. | | [`useDebouncedCallback`](https://palantir.github.io/osdk-ts/reference/react/use-debounced-callback.md) | Debounces a callback, with cancel and flush. | | [`useOsdkMetadata`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-metadata.md) | Fetches metadata for an object type, interface, or action. | | [`useOsdkClient`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-client.md) | Returns the `Client` from `OsdkProvider`. | | [`useObservableClient`](https://palantir.github.io/osdk-ts/reference/react/use-observable-client.md) | Returns the `ObservableClient` that backs the cache. | | [`@osdk/react/testing`](https://palantir.github.io/osdk-ts/reference/react/testing.md) | `TestOsdkProvider` and `fakeObservableClient` for unit tests. | ## `@osdk/react/platform-apis` | API | Description | | --- | --- | | [`useCurrentFoundryUser`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usecurrentfoundryuser) | Gets the signed-in user. | | [`useFoundryUser`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usefoundryuser) | Gets a user by ID. | | [`useFoundryUsersList`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usefoundryuserslist) | Lists users, one page at a time. | | [`useMarkings`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usemarkings) | Lists markings. | | [`useMarkingCategories`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usemarkingcategories) | Lists marking categories. | | [`useUserViewMarkings`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#useuserviewmarkings) | Gets the markings a user can view. | | [`useCbacBanner`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usecbacbanner) | Gets the classification banner for marking IDs. | | [`useCbacMarkingRestrictions`](https://palantir.github.io/osdk-ts/reference/react/platform-apis.md#usecbacmarkingrestrictions) | Gets implied, disallowed, and required markings. | ## `@osdk/client` | API | Description | | --- | --- | | [`createClient`](https://palantir.github.io/osdk-ts/reference/client/create-client.md) | Creates the client for one Ontology. | | [`createPlatformClient`](https://palantir.github.io/osdk-ts/reference/client/create-platform-client.md) | Creates a client for platform APIs only. | | [`ObjectSet`](https://palantir.github.io/osdk-ts/reference/client/object-set.md) | Filters, set operations, pivots, aggregation, paging, and subscriptions. | | [`Osdk.Instance`](https://palantir.github.io/osdk-ts/reference/client/osdk-instance.md) | The type of a loaded object and its `$` fields. | | [`WhereClause`](https://palantir.github.io/osdk-ts/reference/client/where-clause.md) | Filter operators by property type. | | [`PalantirApiError`, `ActionValidationError`](https://palantir.github.io/osdk-ts/reference/client/errors.md) | Errors thrown by the client. | ## `@osdk/oauth` | API | Description | | --- | --- | | [`createPublicOauthClient`](https://palantir.github.io/osdk-ts/reference/oauth/create-public-oauth-client.md) | Browser sign-in with the authorization code flow and PKCE. | | [`createConfidentialOauthClient`](https://palantir.github.io/osdk-ts/reference/oauth/create-confidential-oauth-client.md) | Server-side tokens from a client ID and secret. | | [`createAuthlessClient`](https://palantir.github.io/osdk-ts/reference/oauth/create-authless-client.md) | A token provider for public resources. | ## `@osdk/aip-core` | API | Description | | --- | --- | | [`foundryModel`](https://palantir.github.io/osdk-ts/reference/aip-core/foundry-model.md) | Creates a model handle for the Language Model Service. | | [`generateText`](https://palantir.github.io/osdk-ts/reference/aip-core/generate-text.md) | Generates a complete response. | | [`streamText`](https://palantir.github.io/osdk-ts/reference/aip-core/stream-text.md) | Streams a response as it is generated. | | [`LmsChatTransport`](https://palantir.github.io/osdk-ts/reference/aip-core/lms-chat-transport.md) | A `ChatTransport` for chat UIs. | | [`generateMessageId`, `getUIMessageText`](https://palantir.github.io/osdk-ts/reference/aip-core/utilities.md) | Helpers for `UIMessage` conversations. | # createAuthlessClient Source: https://palantir.github.io/osdk-ts/reference/oauth/create-authless-client > Create a token provider that always returns the public token, for Foundry resources that need no sign-in. ```ts import { createAuthlessClient } from "@osdk/oauth"; function createAuthlessClient(): () => Promise; ``` Returns a token provider that resolves to the string `"PUBLIC"` on every call. Pass it to `createClient` when your app reads resources that Foundry serves without authentication. ## Returns `() => Promise`: resolves to `"PUBLIC"`. ## Example ```ts title="src/client.ts" import { $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createAuthlessClient } from "@osdk/oauth"; export const client = createClient( "https://example.palantirfoundry.com", $ontologyRid, createAuthlessClient(), ); ``` ## See also - [Authentication](https://palantir.github.io/osdk-ts/authentication.md) # createConfidentialOauthClient Source: https://palantir.github.io/osdk-ts/reference/oauth/create-confidential-oauth-client > Create a server-side token provider that authenticates with a client ID and secret using the client credentials grant. ```ts import { createConfidentialOauthClient } from "@osdk/oauth"; function createConfidentialOauthClient( client_id: string, client_secret: string, url: string, scopes?: string[], fetchFn?: typeof globalThis.fetch, ctxPath?: string, ): ConfidentialOauthClient; ``` Returns a function you pass as the `tokenProvider` of `createClient` or `createPlatformClient`. It requests a token on the first call and requests a new one after the current token expires. Use it only on a server or in a script, where the secret stays private. ## Parameters The parameters are positional and have no options type, so this table is written by hand. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `client_id` | `string` | | The client ID of your Developer Console application. | | `client_secret` | `string` | | The client secret of the application. | | `url` | `string` | | The base URL of your Foundry stack. | | `scopes` | `string[]` | `["api:read-data", "api:write-data", "api:use-ontologies-read", "api:use-ontologies-write"]` | The OAuth scopes to request. | | `fetchFn` | `typeof fetch` | `globalThis.fetch` | The `fetch` implementation for token requests. | | `ctxPath` | `string` | `"multipass"` | The context path of the authorization server. | ## Returns `ConfidentialOauthClient`: | Member | Type | Description | | --- | --- | --- | | `()` | `() => Promise` | Returns a valid access token, requesting a new one if needed. | | `getTokenOrUndefined` | `() => string \| undefined` | The current access token, or `undefined` if there is none or it expired. | | `signIn` | `() => Promise` | Requests a new token. | | `signOut` | `() => Promise` | Revokes the access token. Throws when there is no token. | | `addEventListener` | `(type, listener, options?) => void` | Listens for `"signIn"` or `"signOut"`. | | `removeEventListener` | `(type, listener, options?) => void` | Removes a listener. | ## Example ```ts title="scripts/countEmployees.ts" import { $ontologyRid, Employee } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createConfidentialOauthClient } from "@osdk/oauth"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createConfidentialOauthClient( process.env.FOUNDRY_CLIENT_ID!, process.env.FOUNDRY_CLIENT_SECRET!, foundryUrl, ["api:use-ontologies-read", "api:read-data"], ); const client = createClient(foundryUrl, $ontologyRid, auth); const { $count } = await client(Employee).aggregate({ $select: { $count: "unordered" } }); console.log(`${$count} employees`); ``` ## See also - [Authentication](https://palantir.github.io/osdk-ts/authentication.md) - [Node.js](https://palantir.github.io/osdk-ts/frameworks/node.md) # createPublicOauthClient Source: https://palantir.github.io/osdk-ts/reference/oauth/create-public-oauth-client > Create a browser token provider that signs users in with the OAuth authorization code flow and PKCE. ```ts import { createPublicOauthClient } from "@osdk/oauth"; function createPublicOauthClient( clientId: string, url: string, redirectUrl: string, options?: PublicOauthClientOptions, ): PublicOauthClient; ``` Returns a function you pass as the `tokenProvider` of `createClient`. The first call without a stored token redirects the browser to Foundry to sign in. After the redirect back to `redirectUrl`, the client exchanges the code, stores the refresh token per `tokenStorage`, and refreshes the access token one minute before it expires. An older overload takes `useHistory`, `loginPage`, `postLoginPage`, `scopes`, `fetchFn`, and `ctxPath` as positional arguments. Prefer `options`, which also accepts `refreshTokenMarker`, `tokenStorage`, and `logger`. ## Parameters | Parameter | Type | Description | | --- | --- | --- | | `clientId` | `string` | The client ID of your Developer Console application. | | `url` | `string` | The base URL of your Foundry stack. | | `redirectUrl` | `string` | The redirect URL registered on the application. It must be a route of your app. | | `options` | `PublicOauthClientOptions` | See below. | ## Options ### PublicOauthClientOptions | Prop | Type | Description | | --------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `realmId?` | `string` | Realm of the authentication provider to use when the user needs to log in, sent as the `_realm` authorize parameter. Users who already have a Foundry session keep that session's identity. Takes precedence over the domain's default authentication provider. If it does not match an enabled provider, Foundry shows the provider picker. To ignore stored refresh tokens when `realmId` changes, also pass it as `refreshTokenMarker`. | | `useHistory?` | `boolean` | If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true) | | `loginPage?` | `string` | Custom landing page URL prior to logging in | | `postLoginPage?` | `string` | URL to return to after completed authentication cycle (defaults to `window.location.toString()`) | | `scopes?` | `string[]` | OAuth scopes to request. Defaults to `["api:read-data", "api:write-data", "api:use-ontologies-read", "api:use-ontologies-write"]`. | | `fetchFn?` | `((input: RequestInfo \| URL, init?: RequestInit) => Promise)` | Custom fetch function to use for requests (defaults to `globalThis.fetch`) | | `ctxPath?` | `string` | Context path for the authorization server (defaults to "multipass") | | `refreshTokenMarker?` | `string` | Value stored with the refresh token. A stored refresh token is only reused when its marker matches this value, so changing it (for example when the SDK version or `realmId` changes) forces a new authorization. | | `tokenStorage?` | `TokenStorageType` | Controls how refresh tokens are stored. Affects security vs. convenience tradeoff. - `'localStorage'` (default): Tokens persist across browser sessions. Best UX but vulnerable on shared devices. - `'sessionStorage'`: Tokens cleared when browser/tab closes. Recommended for shared devices. Users re-authenticate each browser session. - `'none'`: Tokens never stored. Users re-authenticate on every page load. Most secure but worst UX. Does not request `offline_access` scope. Default: `'localStorage'` | | `logger?` | `OauthLogger` | Optional logger for warning messages. If not provided, warnings are silently dropped. Structurally compatible with `@osdk/api`'s `Logger`. | When `scopes` is omitted, the client requests `api:read-data`, `api:write-data`, `api:use-ontologies-read`, and `api:use-ontologies-write`. Unless `tokenStorage` is `"none"`, it also requests `offline_access` to get a refresh token. ## Returns `PublicOauthClient`. The interface has no JSDoc, so this table is written by hand. | Member | Type | Description | | --- | --- | --- | | `()` | `() => Promise` | Returns a valid access token, signing in or refreshing first if needed. | | `getTokenOrUndefined` | `() => string \| undefined` | The current access token without signing in, or `undefined`. | | `signIn` | `() => Promise` | Signs in: uses the stored refresh token, completes a pending redirect, or redirects to Foundry. Concurrent calls share one attempt. | | `signOut` | `() => Promise` | Revokes the access token and removes the stored refresh token. Throws when not signed in. | | `refresh` | `() => Promise` | Refreshes the access token with the stored refresh token. Throws when none is stored or the refresh fails. | | `addEventListener` | `(type, listener, options?) => void` | Listens for `"signIn"`, `"signOut"`, or `"refresh"`. `signIn` and `refresh` events carry the `Token` in `detail`. | | `removeEventListener` | `(type, listener, options?) => void` | Removes a listener. | `Token` is `{ access_token: string; expires_in: number; refresh_token?: string; expires_at: number }`. ## Example ```ts title="src/auth.ts" import { createPublicOauthClient } from "@osdk/oauth"; export const auth = createPublicOauthClient( "", "https://example.palantirfoundry.com", "http://localhost:8080/auth/callback", { scopes: ["api:use-ontologies-read", "api:use-ontologies-write"], tokenStorage: "sessionStorage", }, ); auth.addEventListener("signOut", () => { window.location.assign("/"); }); ``` ## See also - [Authentication](https://palantir.github.io/osdk-ts/authentication.md) - [createClient](https://palantir.github.io/osdk-ts/reference/client/create-client.md) # OsdkProvider Source: https://palantir.github.io/osdk-ts/reference/react/osdk-provider > React context provider that shares an OSDK client and its normalized cache with every hook below it. ```ts import { OsdkProvider } from "@osdk/react"; function OsdkProvider( props: { children: React.ReactNode; enableDevTools?: boolean; } & ( | { client: Client; devMode?: ObservableClientOptions["devMode"] } | { client: ObservableClient; devMode?: never } ), ): React.JSX.Element; ``` Wraps your app so `@osdk/react` hooks can reach the client. Given a `Client`, the provider builds an `ObservableClient` from it, which holds the shared cache, and rebuilds it whenever `client` changes. Given an `ObservableClient`, the provider uses it and its cache as is. ## Props The props type is not exported, so this table is written by hand. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `client` | `Client \| ObservableClient` | | The client from `createClient` in `@osdk/client`, or an observable client from `createObservableClient` in `@osdk/client/observable`. Create it once at module scope; a new instance starts a new, empty cache. | | `children` | `React.ReactNode` | | The tree that uses OSDK hooks. | | `enableDevTools` | `boolean` | `true` when devtools are registered | Turns the devtools integration on or off. Ignored in production builds. | | `devMode` | `ObservableClientOptions["devMode"]` | | Development-only behavior of the observable client. Ignored in production builds. Only accepted with a plain `Client`; pass it to `createObservableClient` instead when you supply an observable client. See the fields below. | ### `devMode` fields | Field | Type | Description | | --- | --- | --- | | `actionDelayMs` | `number` | Delay, in milliseconds, applied to the result of an action that has an optimistic update, so the optimistic state stays visible. Defaults to `1000`; pass `0` to disable it. | | `logLevel` | `"trace" \| "debug" \| "info" \| "warn" \| "error" \| "fatal"` | Log level of the observable client. Defaults to `"error"`; pass `"debug"` to see its tracing. | | `debug.refCounts` | `boolean` | Logs the reference-count lifecycle of cache entries and shortens their retention window. | | `debug.cacheKeys` | `boolean` | Logs cache-key lookups. | ## Example ```tsx title="src/Root.tsx" import { $ontologyRid } from "@my-app/sdk"; import { createClient } from "@osdk/client"; import { createPublicOauthClient } from "@osdk/oauth"; import { OsdkProvider } from "@osdk/react"; const foundryUrl = "https://example.palantirfoundry.com"; const auth = createPublicOauthClient( "", foundryUrl, "http://localhost:8080/auth/callback", ); const client = createClient(foundryUrl, $ontologyRid, auth); function App() { return
    My app
    ; } export function Root() { return ( ); } ``` ## Share an observable client To share a cache with code outside React, create an observable client and pass it to `OsdkProvider`: ```tsx title="src/Root.tsx" import { createObservableClient } from "@osdk/client/observable"; import { OsdkProvider } from "@osdk/react"; import { client } from "./client"; const observableClient = createObservableClient(client, undefined, { devMode: { actionDelayMs: 0 }, }); export function Root() { return ( ); } ``` - `useOsdkClient()` returns the underlying client used by the observable client's store. - Keep the observable client stable across renders. Replace it when the ontology, branch, or authentication context changes. - The provider does not clear the shared cache when it unmounts. Each consumer must unsubscribe from its own observations. - Multiple providers can use the same observable client, and they share its user-agent registrations. Code outside React must use the observable client's APIs to share the cache; plain client fetches do not populate it. ## See also - [Create a client](https://palantir.github.io/osdk-ts/client.md) - [Devtools](https://palantir.github.io/osdk-ts/devtools.md) # @osdk/react/platform-apis Source: https://palantir.github.io/osdk-ts/reference/react/platform-apis > Hooks for Foundry users, markings, and CBAC banners and restrictions, built on @osdk/foundry.admin. These hooks call Foundry platform APIs with the client from `OsdkProvider`. Install the optional peer dependencies first: ```npm npm install @osdk/foundry.admin @osdk/foundry.core ``` All hooks share these behaviors: - Each hook instance fetches on mount and keeps its result in component state. Results are not shared through the OSDK cache, so two components that call the same hook make two requests. - `isLoading` is `true` while enabled and no successful response has arrived. If the request fails, `isLoading` stays `true` alongside `error`, so check `error` first. When `enabled` is `false`, the hook does not fetch and `isLoading` is `false`. - `refetch()` reruns the request. The data field is `undefined` until the new response arrives. - `error` holds the request error, if any. ## useCurrentFoundryUser ```ts function useCurrentFoundryUser( options?: UseCurrentFoundryUserOptions, ): UseCurrentFoundryUserResult; ``` Gets the signed-in user. ### UseCurrentFoundryUserOptions | Prop | Type | Description | | ---------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | Returns `{ currentUser, isLoading, error, refetch }`, where `currentUser` is a `User` from `@osdk/foundry.admin`. ## useFoundryUser ```ts function useFoundryUser( userId: string, options?: UseFoundryUserOptions, ): UseFoundryUserResult; ``` Gets one user by ID. ### UseFoundryUserOptions | Prop | Type | Description | | ---------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | | `status?` | `UserStatus` | The status filter applied when fetching the user. Default: `"ACTIVE"` | Returns `{ user, isLoading, error, refetch }`, where `user` is a `User`. ## useFoundryUsersList ```ts function useFoundryUsersList( options?: UseFoundryUsersListOptions, ): UseFoundryUsersListResult; ``` Lists users one page at a time. A page can hold more or fewer users than `pageSize`. ### UseFoundryUsersListOptions | Prop | Type | Description | | ------------ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | | `include?` | `UserStatus` | The default status of the users returned in the list. Default: `"ACTIVE"` | | `pageSize?` | `number` | The preferred page size for the list. Default: `1000` | | `pageToken?` | `string` | The page token indicates where to start paging. This should be omitted from the first page's request. To fetch the next page, clients should take the value from the nextPageToken field of the previous response and use it to populate the pageToken field of the next request. | Returns `{ users, nextPageToken, isLoading, error, refetch }`. Pass `nextPageToken` as `pageToken` to load the next page; it is `undefined` on the last page. ## useMarkings ```ts function useMarkings(options?: UseMarkingsOptions): UseMarkingsResult; ``` Lists markings. ### UseMarkingsOptions | Prop | Type | Description | | ----------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | | `includeDeleted?` | `boolean` | Whether to include deleted markings in the results. Default: `true` | | `markingType?` | `MarkingType` | Filter markings by type. When omitted, returns all marking types. Default: `undefined` | Returns `{ markings, isLoading, error, refetch }`, where `markings` is a `Marking[]`. ## useMarkingCategories ```ts function useMarkingCategories( options?: UseMarkingCategoriesOptions, ): UseMarkingCategoriesResult; ``` Lists marking categories. ### UseMarkingCategoriesOptions | Prop | Type | Description | | ----------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | | `includeDeleted?` | `boolean` | Whether to include deleted marking categories in the results. Default: `true` | | `markingType?` | `MarkingType` | Filter marking categories by type. When omitted, returns all marking types. Default: `undefined` | Returns `{ categories, isLoading, error, refetch }`, where `categories` is a `MarkingCategory[]`. ## useUserViewMarkings ```ts function useUserViewMarkings( options?: UseUserViewMarkingsOptions, ): UseUserViewMarkingsResult; ``` Gets the IDs of the markings a user can view. Without `userId`, the hook first looks up the current user, then fetches their markings. ### UseUserViewMarkingsOptions | Prop | Type | Description | | ---------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `userId?` | `string` | The user ID to fetch view markings for. When omitted, fetches markings for the current user. | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | Returns `{ markingIds, isLoading, error, refetch }`, where `markingIds` is a `string[]`. ## useCbacBanner ```ts function useCbacBanner(options: UseCbacBannerOptions): UseCbacBannerResult; ``` Gets the classification banner for a set of marking IDs. The hook does not fetch while `markingIds` is empty. ### UseCbacBannerOptions | Prop | Type | Description | | ------------ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `markingIds` | `string[]` | | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | Returns `{ banner, isLoading, error, refetch }`, where `banner` is: ### CbacBannerData | Prop | Type | Description | | ---------------------- | ---------- | ----------- | | `classificationString` | `string` | | | `textColor` | `string` | | | `backgroundColors` | `string[]` | | | `markingIds` | `string[]` | | ## useCbacMarkingRestrictions ```ts function useCbacMarkingRestrictions( options: UseCbacMarkingRestrictionsOptions, ): UseCbacMarkingRestrictionsResult; ``` Gets the markings that a set of marking IDs implies, disallows, and requires, and whether the current user satisfies them. The hook does not fetch while `markingIds` is empty. It calls a preview endpoint. ### UseCbacMarkingRestrictionsOptions | Prop | Type | Description | | ------------ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `markingIds` | `string[]` | | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query will not automatically execute. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | Returns `{ restrictions, isLoading, error, refetch }`, where `restrictions` is: ### CbacMarkingRestrictionsData | Prop | Type | Description | | ----------------------- | ------------ | ----------- | | `disallowedMarkings` | `string[]` | | | `impliedMarkings` | `string[]` | | | `requiredMarkings` | `string[][]` | | | `userSatisfiesMarkings` | `boolean` | | | `isValid` | `boolean` | | ## Example ```tsx title="src/CurrentUserBadge.tsx" import { useCurrentFoundryUser } from "@osdk/react/platform-apis"; export function CurrentUserBadge() { const { currentUser, isLoading, error } = useCurrentFoundryUser(); return ( {error ? "Unknown user" : (currentUser?.givenName ?? currentUser?.username)} ); } ``` ## See also - [Users and markings](https://palantir.github.io/osdk-ts/react/platform-apis.md) # @osdk/react/testing Source: https://palantir.github.io/osdk-ts/reference/react/testing > TestOsdkProvider and fakeObservableClient for rendering @osdk/react components in unit tests. ```ts import { fakeObservableClient, TestOsdkProvider } from "@osdk/react/testing"; function TestOsdkProvider(props: { children: React.ReactNode; client: Client; observableClient: ObservableClient; }): React.JSX.Element; const fakeObservableClient: ObservableClient; ``` `TestOsdkProvider` puts a `client` and an `observableClient` of your choice into context, skipping the devtools and user-agent setup of `OsdkProvider`. Use it only in tests; in production, `OsdkProvider` derives the observable client from `client` so the two cannot diverge. ## `TestOsdkProvider` props The props type is inline in the source, so this table is written by hand. | Prop | Type | Description | | --- | --- | --- | | `client` | `Client` | Returned by `useOsdkClient` and used by the platform API hooks. | | `observableClient` | `ObservableClient` | Used by the data hooks such as `useOsdkObjects` and returned by `useObservableClient`. | | `children` | `React.ReactNode` | The tree under test. | ## `fakeObservableClient` An `ObservableClient` whose every method throws. Pass it when the code under test never uses the observable client, so an unexpected call fails the test instead of returning `undefined`. ## Example ```tsx title="src/ClientStatus.test.tsx" import { createMockClient } from "@osdk/unit-testing"; import { useOsdkClient } from "@osdk/react"; import { fakeObservableClient, TestOsdkProvider } from "@osdk/react/testing"; import { render, screen } from "@testing-library/react"; import { expect, it } from "vitest"; const mockClient = createMockClient(); function ClientStatus() { const client = useOsdkClient(); return

    {client === mockClient ? "mock client" : "other client"}

    ; } it("reads the client from context", () => { render( , ); expect(screen.getByText("mock client")).toBeDefined(); }); ``` ## See also - [Testing](https://palantir.github.io/osdk-ts/react/testing.md) # useDebouncedCallback Source: https://palantir.github.io/osdk-ts/reference/react/use-debounced-callback > Debounce a callback, such as an action call from a text input, with cancel and flush controls. ```ts import { useDebouncedCallback } from "@osdk/react"; function useDebouncedCallback( callback: (...args: TArgs) => void | Promise, delay: number, ): DebouncedCallback; ``` Returns a function that calls `callback` once `delay` milliseconds pass without another call. The latest `callback` is always used, and a pending call is cancelled when the component unmounts. ## Parameters | Parameter | Type | Description | | --- | --- | --- | | `callback` | `(...args: TArgs) => void \| Promise` | The function to debounce. A returned promise is not awaited, so handle its errors inside `callback`. | | `delay` | `number` | Milliseconds to wait after the last call. | ## Returns `DebouncedCallback`, a function with the same arguments as `callback` and two methods: | Member | Type | Description | | --- | --- | --- | | `(...args)` | `(...args: TArgs) => void` | Schedules `callback` with these arguments and cancels any pending call. | | `cancel` | `() => void` | Drops the pending call. | | `flush` | `() => void` | Runs the pending call immediately. | ## Example ```tsx title="src/JobTitleInput.tsx" import { Employee, modifyEmployee } from "@my-app/sdk"; import { useDebouncedCallback, useOsdkAction } from "@osdk/react"; export function JobTitleInput({ employee }: { employee: Employee.OsdkInstance }) { const { applyAction, error } = useOsdkAction(modifyEmployee); const save = useDebouncedCallback(async (jobTitle: string) => { try { await applyAction({ employee, jobTitle }); } catch { // The hook result exposes the failure as error. } }, 500); return ( <> save(e.target.value)} /> {error &&

    Could not save.

    } ); } ``` ## See also - [Actions](https://palantir.github.io/osdk-ts/react/actions.md) # useLinks Source: https://palantir.github.io/osdk-ts/reference/react/use-links > Load the objects linked from one or more source objects through a named link. ```ts import { useLinks } from "@osdk/react"; function useLinks>( objects: Osdk.Instance | Array> | undefined, linkName: L, options?: UseLinksOptions>, ): UseLinksResult>; ``` Follows `linkName` from each source object and returns the linked objects as one list. Pass `undefined` while the source object is still loading; on the first render `links` is `undefined`, and once the hook subscribes it returns `links: []` with `isLoading: false` until the source arrives. ## Options ### UseLinksOptions | Prop | Type | Description | | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `where?` | `WhereClause` | Standard OSDK Where clause for filtering linked objects | | `pageSize?` | `number` | The preferred page size for the links list. | | `autoFetchMore?` | `number \| boolean` | Fetch all pages when true, or at least this many linked objects per source when a number is provided. Defaults to manual pagination. | | `orderBy?` | `{ [K in PropertyKeys]?: "asc" \| "desc" \| undefined; }` | Sorting options for the linked objects | | `$select?` | `readonly PropertyKeys[]` | Restrict which properties are returned for each linked object. When provided, only the specified properties will be fetched, reducing payload sizes for list views. | | `mode?` | `"force" \| "offline"` | The mode to use for fetching data. - undefined: Fetch data if not already in cache - "force": Always fetch fresh data - "offline": Only use cached data, don't make network requests | | `dedupeIntervalMs?` | `number` | The number of milliseconds to wait after the last observed link change. Two uses of `useLinks` with the same parameters will only trigger one network request if the second is within `dedupeIntervalMs`. | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query does not run and the hook returns no data, even if the cache already holds a result. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | | `$includeAllBaseObjectProperties?` | `boolean` | When true, includes all properties of the underlying concrete object type for interface link targets. Has no effect when the link target is a plain object type. | | `resolveToObjectType?` | `boolean` | | ## Returns ### UseLinksResult | Prop | Type | Description | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `links` | `Osdk.Instance, {}>[] \| undefined` | | | `linkedObjectsBySourcePrimaryKey` | `ReadonlyMap, {}>[]>` | Maps each source object's primary key to its linked object instances. Useful when observing links from multiple source objects to determine which source links to which targets. | | `isLoading` | `boolean` | | | `error` | `Error \| undefined` | | | `isOptimistic` | `boolean` | Refers to whether the links are optimistic or not. | | `fetchMore` | `(() => Promise) \| undefined` | Fetch more linked objects if pagination is supported | | `hasMore` | `boolean` | Indicates if there are more linked objects available to fetch | ## Example ```tsx title="src/DirectReports.tsx" import { Employee } from "@my-app/sdk"; import { useLinks, useOsdkObject } from "@osdk/react"; export function DirectReports({ employeeId }: { employeeId: number }) { const { object: employee } = useOsdkObject(Employee, employeeId); const { links: reports, isLoading, error } = useLinks(employee, "reports", { orderBy: { fullName: "asc" }, }); return (
    {error &&

    {error.message}

    }
      {reports?.map((report) => (
    • {report.fullName}
    • ))}
    ); } ``` ## See also - [Load linked objects](https://palantir.github.io/osdk-ts/react/links.md) # useObjectSet Source: https://palantir.github.io/osdk-ts/reference/react/use-object-set > Load a live, paged list from an ObjectSet, with filters, set operations, pivots, and derived properties applied on top. ```ts import { useObjectSet } from "@osdk/react"; function useObjectSet< Q extends ObjectOrInterfaceDefinition, BaseRDPs extends Record = never, RDPs extends Record = {}, >( baseObjectSet: ObjectSet | undefined, options?: UseObjectSetOptions, ): UseObjectSetResult; ``` Starts from an `ObjectSet` you build with the client and applies `options` before fetching. Pass `undefined` to wait; the hook does not fetch until it has a set. The hook keys the query on the set's wire definition, so a new `ObjectSet` instance with the same definition does not refetch. ## Options ### UseObjectSetOptions | Prop | Type | Description | | ------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `where?` | `WhereClause` | Where clause for filtering | | `withProperties?` | `{ [K in keyof RDPs]: DerivedProperty.Creator; }` | Derived properties to add to the object set | | `union?` | `ObjectSet[]` | Object sets to union with | | `intersect?` | `ObjectSet[]` | Object sets to intersect with | | `subtract?` | `ObjectSet[]` | Object sets to subtract from | | `pivotTo?` | `LinkNames` | Link to pivot to (changes the type). Cannot be combined with `streamUpdates`. The server does not support websocket subscriptions for link-traversal queries. | | `pageSize?` | `number` | The preferred page size for the list | | `orderBy?` | `{ [K in PropertyKeys]?: "asc" \| "desc" \| undefined; }` | Sort order for the results | | `dedupeIntervalMs?` | `number` | Minimum time between fetch requests in milliseconds (defaults to 2000ms) | | `autoFetchMore?` | `number \| boolean` | Automatically fetch additional pages on initial load. - `true`: Fetch all available pages automatically - `number`: Fetch pages until at least this many items are loaded - `undefined` (default): Only fetch the first page, user must call fetchMore() | | `streamUpdates?` | `boolean` | Enable streaming updates via websocket subscription. When true, the object set will automatically update when matching objects are added, updated, or removed. Cannot be combined with `pivotTo`. The server does not support websocket subscriptions for link-traversal queries. Default: `false` | | `$select?` | `readonly PropertyKeys[]` | Restrict which properties are returned for each object. When provided, only the specified properties will be fetched, reducing payload sizes for list views. | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query does not run and the hook returns no data, even if the cache already holds a result. This is useful for: - Lazy/on-demand queries that should wait for user interaction - Dependent queries that need data from another query first - Conditional queries based on component state Default: `true` | ## Returns ### UseObjectSetResult | Prop | Type | Description | | -------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------- | | `data` | `Osdk.Instance, RDPs>[] \| undefined` | The fetched data with derived properties | | `isLoading` | `boolean` | Whether data is currently being loaded | | `error` | `Error \| undefined` | Any error that occurred during fetching | | `isOptimistic` | `boolean` | | | `fetchMore` | `(() => Promise) \| undefined` | Function to fetch more pages (undefined if no more pages) | | `hasMore` | `boolean` | | | `objectSet` | `ObjectSet \| undefined` | The final ObjectSet after all transformations | | `totalCount?` | `string` | The total count of objects matching the query (if available from the API) | | `refetch` | `() => Promise` | | While a new query loads, `data` keeps the last completed result for the same object type, so the list does not flash empty between filters. ## Example ```tsx title="src/OfficeOccupants.tsx" import { Office } from "@my-app/sdk"; import { useObjectSet, useOsdkClient } from "@osdk/react"; import { useMemo } from "react"; export function OfficeOccupants({ city }: { city: string }) { const client = useOsdkClient(); const occupants = useMemo( () => client(Office).where({ city }).pivotTo("occupants"), [client, city], ); const { data, isLoading, error } = useObjectSet(occupants, { orderBy: { fullName: "asc" }, }); return (
    {error &&

    {error.message}

    }
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    ); } ``` ## See also - [Object sets](https://palantir.github.io/osdk-ts/react/object-sets.md) - [useStableObjectSet](https://palantir.github.io/osdk-ts/reference/react/use-stable-object-set.md) - [ObjectSet](https://palantir.github.io/osdk-ts/reference/client/object-set.md) # useObservableClient Source: https://palantir.github.io/osdk-ts/reference/react/use-observable-client > Return the ObservableClient that backs the shared cache of the nearest OsdkProvider. ```ts import { useObservableClient } from "@osdk/react"; function useObservableClient(): ObservableClient; ``` Returns the `ObservableClient` that `OsdkProvider` builds from its `client`. Use it to invalidate cached data after changes that do not go through an action, such as an update from an external system or a background job. ## Returns `ObservableClient` from `@osdk/client/observable`. The methods you are most likely to need: | Method | Description | | --- | --- | | `invalidateObjects(objects)` | Reloads one object instance or an array of them. Interface instances refetch their backing object. | | `invalidateObjectType(type)` | Reloads every cached query for an object type, by definition or API name. | | `invalidateFunction(queryDef, params?)` | Reloads a function's cached result for `params`, or every cached call when `params` is omitted. | | `invalidateAll()` | Reloads everything in the cache. | ## Example ```tsx title="src/RefreshButton.tsx" import { Employee } from "@my-app/sdk"; import { useObservableClient } from "@osdk/react"; export function RefreshButton({ employee }: { employee: Employee.OsdkInstance }) { const observableClient = useObservableClient(); return ( ); } ``` ## See also - [Cache invalidation](https://palantir.github.io/osdk-ts/react/cache-invalidation.md) # useOsdkAction Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-action > Apply or validate an action from a component, with pending state, errors, and optional optimistic updates. ```ts import { useOsdkAction } from "@osdk/react"; function useOsdkAction>( actionDef: Q, ): UseOsdkActionResult; ``` Returns functions that apply or validate `actionDef` through the shared cache. After an action succeeds, cached objects and lists that it changed are refreshed. ## Returns The result type has little JSDoc, so this table is written by hand. | Field | Type | Description | | --- | --- | --- | | `applyAction` | `(args: ApplyActionParams \| ApplyActionParams[]) => Promise` | Applies the action. Pass an array to apply a batch. Rethrows on failure after setting `error`. | | `validateAction` | `(args) => Promise` | Validates the parameters without applying the action. A new call cancels the previous one, and the cancelled call resolves to `undefined`. Resolves to `undefined` without validating while `applyAction` is pending. | | `data` | `ActionEditResponse \| undefined` | The response from the last successful `applyAction`. | | `error` | `{ actionValidation?: ActionValidationError; unknown?: unknown } \| undefined` | The last failure. `actionValidation` is set when the server rejected the parameters; `unknown` holds any other error. Cleared when the next call starts. | | `isPending` | `boolean` | `true` while `applyAction` is running. | | `isValidating` | `boolean` | `true` while `validateAction` is running. | | `validationResult` | `ActionValidationResponse \| undefined` | The response from the last completed `validateAction`. | ### `applyAction` arguments `ApplyActionParams` is the action's parameters plus: | Field | Type | Description | | --- | --- | --- | | `$optimisticUpdate` | `(ctx: OptimisticBuilder) => void` | Writes temporary changes to the cache that are rolled back when the action settles. In a batch, every entry's update runs. | ## Example ```tsx title="src/PromoteButton.tsx" import { Employee, modifyEmployee } from "@my-app/sdk"; import { useOsdkAction } from "@osdk/react"; export function PromoteButton({ employee }: { employee: Employee.OsdkInstance }) { const { applyAction, isPending, error } = useOsdkAction(modifyEmployee); async function promote() { try { await applyAction({ employee, jobTitle: "Senior Engineer", $optimisticUpdate: (ctx) => { ctx.updateObject(employee.$clone({ jobTitle: "Senior Engineer" })); }, }); } catch { // The hook result exposes the failure as error. } } return ( <> {error?.actionValidation &&

    Invalid parameters.

    } ); } ``` ## See also - [Actions](https://palantir.github.io/osdk-ts/react/actions.md) - [Optimistic updates](https://palantir.github.io/osdk-ts/react/optimistic-updates.md) - [Errors](https://palantir.github.io/osdk-ts/reference/client/errors.md) # useOsdkAggregation Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-aggregation > Run a server-side aggregation, such as counts or averages grouped by a property, and keep the result cached. ```ts import { useOsdkAggregation } from "@osdk/react"; function useOsdkAggregation< Q extends ObjectOrInterfaceDefinition, const A extends AggregateOpts, RDPs extends Record = {}, >( type: Q, options: UseOsdkAggregationOptions, ): UseOsdkAggregationResult; function useOsdkAggregation< Q extends ObjectTypeDefinition, const A extends AggregateOpts, RDPs extends Record = {}, >( type: Q, options: UseOsdkAggregationOptionsWithObjectSet, ): UseOsdkAggregationResult; ``` Aggregates the objects of `type`, or of `objectSet` when you pass one, after applying `where` and `intersectWith`. `aggregate` takes the same `$select` and `$groupBy` clauses as `ObjectSet.aggregate`. ## Options ### UseOsdkAggregationOptions | Prop | Type | Description | | ------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `where?` | `WhereClause` | Standard OSDK Where clause to filter objects before aggregation | | `withProperties?` | `{ [K in keyof RDPs]: DerivedProperty.Creator; }` | Define derived properties (RDPs) to be computed server-side. The derived properties can be used in the where clause and aggregation groupBy/select. | | `intersectWith?` | `{ where: WhereClause; }[]` | Intersect the main query with additional filtered object sets. Each entry creates a separate object set with its own where clause, and the final result is the intersection of all sets. | | `aggregate` | `A` | Aggregation options including `$groupBy` and `$select` | | `dedupeIntervalMs?` | `number` | The number of milliseconds to wait after the last observed aggregation change. Two uses of `useOsdkAggregation` with the same parameters will only trigger one network request if the second is within `dedupeIntervalMs`. | | `enabled?` | `boolean` | Enable or disable the aggregation. When `false`, the hook does not subscribe or fetch from the server and reports `data: undefined`, `isLoading: false`, and `error: undefined`. `refetch()` is also a no-op while disabled, so it will not invalidate the object type or trigger network requests. Setting it back to `true` re-subscribes and fetches. Default: `true` | The second overload (`UseOsdkAggregationOptionsWithObjectSet`) adds a required `objectSet: ObjectSet` to aggregate a pivoted, filtered, or composed set. It accepts object types only, not interfaces. ## Returns | Field | Type | Description | | --- | --- | --- | | `data` | `AggregationsResults \| undefined` | The aggregation result. An array of groups when `$groupBy` is set, otherwise one object of metrics. | | `isLoading` | `boolean` | `true` while enabled and the result has not loaded. | | `error` | `Error \| undefined` | The error from the last run, if any. | | `refetch` | `() => Promise` | Invalidates cached data for `type` and reruns the aggregation. No-op while disabled. | ## Example ```tsx title="src/HeadcountByDepartment.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkAggregation } from "@osdk/react"; export function HeadcountByDepartment() { const { data, isLoading, error } = useOsdkAggregation(Employee, { aggregate: { $select: { $count: "unordered", "salary:avg": "unordered" }, $groupBy: { department: "exact" }, }, }); return ( {error && ( )} {data?.map((group) => ( ))}
    {error.message}
    {group.$group.department} {group.$count} {group.salary.avg}
    ); } ``` ## See also - [Aggregations](https://palantir.github.io/osdk-ts/react/aggregations.md) - [Aggregations in `@osdk/client`](https://palantir.github.io/osdk-ts/sdk/aggregations.md) # useOsdkClient Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-client > Return the OSDK Client passed to the nearest OsdkProvider. ```ts import { useOsdkClient } from "@osdk/react"; function useOsdkClient(): Client; ``` Returns the `client` prop of the surrounding `OsdkProvider`. Use it to build object sets for `useObjectSet` or to call the client directly, for example in an event handler. Calls made directly on the client bypass the shared cache. ## Returns `Client`: the client from `createClient` in `@osdk/client`. ## Example ```tsx title="src/ExportButton.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkClient } from "@osdk/react"; export function ExportButton() { const client = useOsdkClient(); async function exportNames() { const names: string[] = []; for await (const employee of client(Employee).asyncIter({ $select: ["fullName"] })) { names.push(employee.fullName ?? ""); } console.log(names.join("\n")); } return ; } ``` ## See also - [Create a client](https://palantir.github.io/osdk-ts/client.md) - [createClient](https://palantir.github.io/osdk-ts/reference/client/create-client.md) # useOsdkFunction Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-function > Execute a Foundry function and cache its result, refetching when the objects it depends on change. ```ts import { useOsdkFunction } from "@osdk/react"; function useOsdkFunction>( queryDef: Q, options?: UseOsdkFunctionOptions, ): UseOsdkFunctionResult; ``` Runs the function when the component mounts and again when `params` change. Calls with the same function and `params` share one cached result. Use `dependsOn` or `dependsOnObjects` to refetch after actions change related objects. ## Options ### UseOsdkFunctionOptions | Prop | Type | Description | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params?` | `(CompileTimeMetadata["parameters"] extends Record ? undefined : QueryParameterType["parameters"]>)` | Parameters to pass to the function. Must include all required parameters; optional parameters can be omitted. | | `dependsOn?` | `(string \| ObjectTypeDefinition)[]` | Object types this function depends on. When actions modify objects of these types, the function will automatically refetch. | | `dependsOnObjects?` | `(ObjectSet \| Osdk.Instance)[]` | Specific object instances or ObjectSets this function depends on. When any of these specific objects change, the function will refetch. More fine-grained than dependsOn for precise invalidation control. For ObjectSets, the object type is extracted asynchronously and changes to any object of that type will trigger a refetch. | | `dedupeIntervalMs?` | `number` | The number of milliseconds to dedupe identical function calls. Two calls with the same function and params will share results if the second call is within this interval of the first. Default: `2000` | | `enabled?` | `boolean` | Whether to enable the query. When false, the query will not execute. Useful for: - Dependent queries that need to wait for other data - Conditional queries based on component state Default: `true` | ## Returns ### UseOsdkFunctionResult | Prop | Type | Description | | ------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `data` | `(CompileTimeMetadata["signature"] extends (...args: never[]) => infer R ? Awaited : never) \| undefined` | The function result, or undefined if not yet loaded or on error. | | `isLoading` | `boolean` | True while the function is executing. | | `error` | `Error \| undefined` | Error if the function execution failed. | | `lastUpdated` | `number` | Timestamp (ms since epoch) of when the result was last fetched. | | `refetch` | `() => Promise` | Manually refetch the function. Useful for "pull to refresh" or retry patterns. | `isLoading` is `true` only while a request is in flight. On the first render, before the hook subscribes, and while it is disabled, `isLoading` is `false` and `data` is `undefined`, so check both. ## Example ```tsx title="src/EmployeeReport.tsx" import { Employee, getEmployeeReport } from "@my-app/sdk"; import { useOsdkFunction } from "@osdk/react"; export function EmployeeReport({ employee }: { employee: Employee.OsdkInstance }) { const { data, isLoading, error, refetch } = useOsdkFunction(getEmployeeReport, { params: { employeeId: employee.$primaryKey }, dependsOnObjects: [employee], }); return (
    {error &&

    {error.message}

    }

    {data}

    ); } ``` ## See also - [Functions](https://palantir.github.io/osdk-ts/react/functions.md) - [useOsdkFunctions](https://palantir.github.io/osdk-ts/reference/react/use-osdk-functions.md) # useOsdkFunctions Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-functions > Execute several Foundry functions from one hook and get their results in input order. ```ts import { useOsdkFunctions } from "@osdk/react"; function useOsdkFunctions(props: UseOsdkFunctionsProps): UseOsdkFunctionsResult; type UseOsdkFunctionsResult = Array>>; ``` Use it when the number of function calls varies at runtime, which rules out calling `useOsdkFunction` in a loop. Each query shares the cache with `useOsdkFunction`, so identical calls elsewhere do not hit the network twice. ## Props ### UseOsdkFunctionsProps | Prop | Type | Description | | ---------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `queries` | `FunctionQueryParams>[]` | Array of query configurations to execute | | `enabled?` | `boolean` | Whether to enable all queries. When false, no queries will execute. Individual query enabled states are also respected. Default: `true` | | `maxConcurrent?` | `number` | Maximum number of queries to execute concurrently. When set, queries are subscribed in batches — the next query starts only after a running one completes (status "loaded" or "error"). Useful for large payloads that may exceed server time limits. Default: `undefined (all queries run in parallel)` | ### `FunctionQueryParams` | Field | Type | Description | | --- | --- | --- | | `queryDefinition` | `Q` | The function from your generated SDK. | | `options` | `UseOsdkFunctionOptions` | The same options as [`useOsdkFunction`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-function.md): `params`, `dependsOn`, `dependsOnObjects`, `dedupeIntervalMs`, and `enabled`. | ## Returns An array with one [`UseOsdkFunctionResult`](https://palantir.github.io/osdk-ts/reference/react/use-osdk-function.md#returns) per query, in the order of `queries`. `queries` is typed with `QueryDefinition`, so an entry with typed `params` does not type-check as written, and each result's `data` loses the function's return type. Cast each entry to `UseOsdkFunctionsProps["queries"][number]`, as the example does, and narrow `data` where you read it. ## Example ```tsx title="src/DepartmentHeadcounts.tsx" import { getEmployeeMetrics } from "@my-app/sdk"; import { useOsdkFunctions, type UseOsdkFunctionsProps } from "@osdk/react"; type FunctionCall = UseOsdkFunctionsProps["queries"][number]; export function DepartmentHeadcounts({ departments }: { departments: string[] }) { const results = useOsdkFunctions({ queries: departments.map( (department) => ({ queryDefinition: getEmployeeMetrics, options: { params: { department } }, }) as unknown as FunctionCall, ), maxConcurrent: 4, }); return (
      {departments.map((department, i) => (
    • {department}: {results[i].isLoading ? "…" : JSON.stringify(results[i].data)}
    • ))}
    ); } ``` ## See also - [Functions](https://palantir.github.io/osdk-ts/react/functions.md) # useOsdkMetadata Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-metadata > Fetch the runtime metadata of an object type, interface, or action, such as display names and property descriptions. ```ts import { useOsdkMetadata } from "@osdk/react"; function useOsdkMetadata>( type: T, ): UseOsdkMetadataResult; ``` Calls `client.fetchMetadata(type)` and returns the result. The metadata type follows the definition you pass: `ObjectMetadata` for an object type, `InterfaceMetadata` for an interface, and `ActionMetadata` for an action. The result is held in component state, not in the `ObservableClient` cache, and is not fetched again if `type` changes. The client caches Ontology metadata, so repeated calls for the same type do not repeat the network request. ## Returns | Field | Type | Description | | --- | --- | --- | | `loading` | `boolean` | `true` until the request settles. | | `metadata` | `ObjectMetadata \| InterfaceMetadata \| ActionMetadata \| undefined` | The metadata, once loaded. | | `error` | `string \| undefined` | The error message if the request failed. | ## Example ```tsx title="src/EmployeeHeading.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkMetadata } from "@osdk/react"; export function EmployeeHeading() { const { metadata, loading, error } = useOsdkMetadata(Employee); return (
    {error &&

    {error}

    }

    {metadata?.pluralDisplayName ?? "Employees"}

    {metadata?.description}

    ); } ``` ## See also - [Load objects](https://palantir.github.io/osdk-ts/react/objects.md) # useOsdkObject Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-object > Load one object by primary key, or observe an object instance you already have, from the shared cache. ```ts import { useOsdkObject } from "@osdk/react"; function useOsdkObject( type: Q, primaryKey: PrimaryKeyType, options?: UseOsdkObjectOptions, ): UseOsdkObjectResult; function useOsdkObject( type: Q, primaryKey: PrimaryKeyType, enabled?: boolean, ): UseOsdkObjectResult; function useOsdkObject( obj: Osdk.Instance, enabled?: boolean, ): UseOsdkObjectResult; ``` Pass a type and primary key to fetch the object, or pass an `Osdk.Instance` to observe it in the cache without a network request. The component re-renders when the cached object changes, for example after an action or an optimistic update. ## Parameters | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `type` | `Q` | | The object type or interface from your generated SDK. | | `primaryKey` | `PrimaryKeyType` | | The primary key of the object to load. | | `obj` | `Osdk.Instance` | | An object you already loaded. The hook reads it from the cache only and does not fetch. | | `enabled` | `boolean` | `true` | When `false`, the hook does not subscribe or fetch, and `object` is `undefined`. | | `options` | `UseOsdkObjectOptions` | | See below. | ## Options The options type has little JSDoc, so this table is written by hand. | Option | Type | Default | Description | | --- | --- | --- | --- | | `$select` | `readonly PropertyKeys[]` | All properties | Properties to load. | | `enabled` | `boolean` | `true` | When `false`, the hook does not subscribe or fetch, and `object` is `undefined`. | | `$loadPropertySecurityMetadata` | `boolean` | `false` | Loads per-property marking requirements into `$propertySecurities`. | | `$includeAllBaseObjectProperties` | `boolean` | `false` | For an interface, loads every property of the underlying object type. No effect for object types. | ## Returns | Field | Type | Description | | --- | --- | --- | | `object` | `Osdk.Instance \| undefined` | The object, or `undefined` before it loads, on error, or while disabled. | | `isLoading` | `boolean` | `true` while enabled and the object has not loaded. `false` once `error` is set. | | `error` | `Error \| undefined` | The error from the last load, if any. | | `isOptimistic` | `boolean` | `true` while the cached object reflects an optimistic update that the server has not confirmed. | | `forceUpdate` | `() => void` | Not implemented. Calling it throws. | ## Example ```tsx title="src/EmployeeCard.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObject } from "@osdk/react"; export function EmployeeCard({ employeeId }: { employeeId: number }) { const { object: employee, isLoading, error } = useOsdkObject( Employee, employeeId, { $select: ["fullName", "jobTitle"] }, ); return (
    {error &&

    {error.message}

    }

    {employee?.fullName}

    {employee?.jobTitle}

    ); } ``` ## See also - [Load objects](https://palantir.github.io/osdk-ts/react/objects.md) - [Osdk.Instance](https://palantir.github.io/osdk-ts/reference/client/osdk-instance.md) # useOsdkObjects Source: https://palantir.github.io/osdk-ts/reference/react/use-osdk-objects > Load a live, cached list of objects of one type or interface. ```ts import { useOsdkObjects } from "@osdk/react"; function useOsdkObjects( type: T, options?: UseOsdkObjectsOptions, ): UseOsdkListResult; ``` Subscribes the component to a list in the shared cache and re-renders when the list or any object in it changes. With `pivotTo`, the list holds the linked type instead of `T`; with `rids`, each object also carries `$rid`. ## Options ### UseOsdkObjectsOptions | Prop | Type | Description | | ---------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rids?` | `readonly string[]` | Fetch objects by their RIDs (Resource Identifiers). When provided, starts with a static objectset containing these RIDs. Can be combined with `where` to filter the RID set, and with `orderBy` to sort results. | | `where?` | `WhereClause` | Standard OSDK Where clause with RDP support. When used with `rids`, filters the RID set. When used alone, filters all objects of the type. | | `orderBy?` | `{ [K in PropertyKeys]?: "asc" \| "desc" \| undefined; }` | Sort results by one or more properties. | | `pageSize?` | `number` | The preferred page size for the list. | | `withProperties?` | `{ [K in keyof RDPs]: DerivedProperty.Creator; }` | Define derived properties (RDPs) to be computed server-side and attached to each object. These properties will be available on the returned objects alongside their regular properties. | | `dedupeIntervalMs?` | `number` | The number of milliseconds to wait after the last observed list change. Two uses of `useOsdkObjects` with the same parameters will only trigger one network request if the second is within `dedupeIntervalMs`. | | `enabled?` | `boolean` | Enable or disable the query. When `false`, the query does not run and the hook returns no data, even if the cache already holds a result. Default: `true` | | `intersectWith?` | `{ where: WhereClause; }[]` | Intersect the results with additional object sets. Each element defines a where clause for an object set to intersect with. The final result will only include objects that match ALL conditions. | | `pivotTo?` | `LinkNames` | Pivot to related objects through a link. This changes the return type from T to the linked object type. Cannot be combined with `streamUpdates`. The server does not support websocket subscriptions for link-traversal queries. | | `autoFetchMore?` | `number \| boolean` | Causes the list to automatically fetch more as soon as the previous page has been loaded. If a number is provided, it will continue to automatically fetch more until the list is at least that long. - `true`: Fetch all available pages automatically - `number`: Fetch pages until at least this many items are loaded - `undefined` (default): Only fetch the first page, user must call fetchMore() | | `streamUpdates?` | `boolean` | Enable streaming updates via websocket subscription. Cannot be combined with `pivotTo`. The server does not support websocket subscriptions for link-traversal queries. | | `$select?` | `readonly PropertyKeys[]` | Restrict which properties are returned for each object. When provided, only the specified properties will be fetched, reducing payload sizes for list views. | | `$loadPropertySecurityMetadata?` | `boolean` | When true, loads per-property security metadata (marking requirements) alongside each object. The returned objects will have `$propertySecurities` populated with conjunctive/disjunctive marking requirements per property. | | `$includeAllBaseObjectProperties?` | `boolean` | When true, includes all properties of the underlying concrete object type for interface queries. Has no effect for non-interface queries. | | `resolveToObjectType?` | `boolean` | | ## Returns ### UseOsdkListResult | Prop | Type | Description | | -------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `fetchMore` | `(() => Promise) \| undefined` | Function to fetch more pages (undefined if no more pages) | | `data` | `Osdk.Instance, RDPs>[] \| undefined` | The fetched data with derived properties | | `isLoading` | `boolean` | Whether data is currently being loaded | | `error` | `Error \| undefined` | Any error that occurred during fetching | | `isOptimistic` | `boolean` | Refers to whether the ordered list of objects (only considering the $primaryKey) is optimistic or not. If you need to know if the contents of the list are optimistic you can do that on a per object basis with useOsdkObject | | `totalCount?` | `string` | The total count of objects matching the query (if available from the API) | | `hasMore` | `boolean` | | | `objectSet` | `ObjectSet \| undefined` | | | `refetch` | `() => Promise` | | ## Example ```tsx title="src/EngineeringList.tsx" import { Employee } from "@my-app/sdk"; import { useOsdkObjects } from "@osdk/react"; export function EngineeringList() { const { data, isLoading, error, fetchMore } = useOsdkObjects(Employee, { where: { department: "Engineering" }, orderBy: { fullName: "asc" }, pageSize: 50, }); return (
    {error &&

    {error.message}

    }
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    {isLoading &&

    Loading…

    } {fetchMore && }
    ); } ``` ## See also - [Load objects](https://palantir.github.io/osdk-ts/react/objects.md) - [Filtering](https://palantir.github.io/osdk-ts/sdk/filtering.md) # useStableObjectSet Source: https://palantir.github.io/osdk-ts/reference/react/use-stable-object-set > Return a referentially stable ObjectSet that changes only when its definition changes. ```ts import { useStableObjectSet } from "@osdk/react"; function useStableObjectSet< Q extends ObjectOrInterfaceDefinition, RDPs extends Record = Record, >(objectSet: ObjectSet | undefined): ObjectSet | undefined; ``` Returns the same `ObjectSet` instance across renders until the serialized definition, including `where`, `union`, `intersect`, `subtract`, and pivots, changes. Use it instead of `useMemo` when you build an object set inline and pass it to a hook, an effect, or a memoized child. ## Parameters | Parameter | Type | Description | | --- | --- | --- | | `objectSet` | `ObjectSet \| undefined` | The object set to stabilize. `undefined` passes through. | ## Returns `ObjectSet | undefined`: the object set from the first render with the current definition. ## Example ```tsx title="src/TeamTable.tsx" import { Employee } from "@my-app/sdk"; import { useObjectSet, useOsdkClient, useStableObjectSet } from "@osdk/react"; export function TeamTable({ department }: { department: string }) { const client = useOsdkClient(); const team = useStableObjectSet(client(Employee).where({ department })); const { data } = useObjectSet(team); return (
      {data?.map((employee) => (
    • {employee.fullName}
    • ))}
    ); } ``` ## See also - [Object sets](https://palantir.github.io/osdk-ts/react/object-sets.md) - [useObjectSet](https://palantir.github.io/osdk-ts/reference/react/use-object-set.md) # Actions Source: https://palantir.github.io/osdk-ts/sdk/actions > Apply Ontology actions with applyAction and batchApplyAction, validate parameters first, read returned edits, and handle ActionValidationError. Related Palantir Foundry documentation: - [Action types](https://www.palantir.com/docs/foundry/action-types/overview) Actions are the way to change Ontology data: they create, modify, and delete objects and links according to rules defined in Foundry. `client(modifyEmployee)` returns an invoker with two methods, `applyAction` for one request and `batchApplyAction` for several. ```ts title="src/promote.ts" import { Employee, modifyEmployee } from "@my-app/sdk"; import { ActionValidationError } from "@osdk/client"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345); try { await client(modifyEmployee).applyAction({ employee, jobTitle: "Senior Engineer", }); } catch (e) { if (e instanceof ActionValidationError) { console.error("Rejected by validation", e.validation); } else { throw e; } } ``` `applyAction` rejects when the action fails, so always await it inside `try`/`catch` or attach `.catch`. The parameter names and types come from your generated SDK. In the example SDK, `modifyEmployee` takes `employee` (required), `jobTitle`, and `department`. ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `$returnEdits` | `boolean` | `false` | Resolve to the edits the action made. See [Read the edits](#read-the-edits). | | `$validateOnly` | `boolean` | `false` | Check the parameters without applying the action. See [Validate first](#validate-first). `applyAction` only. | You cannot set both on one call; the types reject it. | Options | `applyAction` resolves to | | --- | --- | | None | `undefined` | | `{ $returnEdits: true }` | `ActionEditResponse` | | `{ $validateOnly: true }` | `ActionValidationResponse` | When `applyAction` resolves, the action has run. Edits to objects in Object Storage V2 are visible to the next read. Edits in Object Storage V1 are eventually consistent and can take a moment to appear. ## Parameter values | Parameter type | Pass | | --- | --- | | Object | A loaded object, its primary key, or `{ $apiName, $primaryKey }`. | | Interface | A plain `{ $objectType, $primaryKey }` object, where `$objectType` is the concrete object type. Do not pass a loaded object: the client would send only its primary key. | | Object set | An object set, such as `client(Employee).where({ ... })`. | | Primitive | A value of the parameter's TypeScript type: `string`, `number`, `boolean`. Dates and timestamps are ISO 8601 strings. `long` and `decimal` accept a `number` or a `string`. | | List | An array of values of the element type. | | Struct | An object whose keys are the struct's fields. | | Attachment | An attachment RID, a `File`, or the result of `createAttachmentUpload`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md#upload-through-an-action). | | Media reference | A `MediaUpload`, a `Media` from an object, or a `MediaReference`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md#upload-through-an-action). | Omit an optional parameter to leave it out of the request. Pass `null` to send an empty value, which clears the property in a modify action: ```ts title="src/clearTitle.ts" import { modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; await client(modifyEmployee).applyAction({ employee: 12345, jobTitle: null }); ``` Parameter default values configured on the action type are not applied when you call the action from the client. Pass every value you need. ## Validate first `$validateOnly: true` runs the action's submission criteria and parameter constraints without applying it. It resolves to the validation result, valid or not, and does not throw on an invalid result: ```ts title="src/validate.ts" import { modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; const validation = await client(modifyEmployee).applyAction( { employee: 12345, department: "Research" }, { $validateOnly: true }, ); if (validation.result === "INVALID") { for (const [name, parameter] of Object.entries(validation.parameters)) { if (parameter.result === "INVALID") { console.warn(`${name} is invalid`, parameter.evaluatedConstraints); } } } ``` The validation result has this shape: | Field | Type | Description | | --- | --- | --- | | `result` | `"VALID" \| "INVALID"` | The overall result. | | `submissionCriteria` | `{ result, configuredFailureMessage? }[]` | One entry per submission criterion, with the failure message configured on the action type. | | `parameters` | `Record` | One entry per parameter. `evaluatedConstraints` lists the checks that ran, such as `range`, `stringLength`, `oneOf`, or `stringRegexMatch`. | ## Handle validation errors When you apply an action whose validation fails, `applyAction` throws an `ActionValidationError` from `@osdk/client`. Its `validation` field holds the same validation result: ```ts title="src/validationMessage.ts" import { modifyEmployee } from "@my-app/sdk"; import { ActionValidationError } from "@osdk/client"; import { client } from "./client"; function describeValidation(error: ActionValidationError): string { const criteria = error.validation.submissionCriteria .filter((criterion) => criterion.result === "INVALID") .flatMap((criterion) => criterion.configuredFailureMessage ?? []); const parameters = Object.entries(error.validation.parameters) .filter(([, parameter]) => parameter.result === "INVALID") .map(([name]) => `${name} is invalid`); return [...criteria, ...parameters].join("\n") || "The action was rejected."; } try { await client(modifyEmployee).applyAction({ employee: 12345, department: "Research" }); } catch (e) { console.error(e instanceof ActionValidationError ? describeValidation(e) : e); } ``` Every other failure, such as a missing permission or an invalid parameter type, rejects with a `PalantirApiError`. See [Errors](https://palantir.github.io/osdk-ts/sdk/errors.md). ## Read the edits `$returnEdits: true` resolves to the edits the action made: ```ts title="src/edits.ts" import { modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; const result = await client(modifyEmployee).applyAction( { employee: 12345, jobTitle: "Staff Engineer" }, { $returnEdits: true }, ); if (result.type === "edits") { for (const edited of result.modifiedObjects) { console.log(`Modified ${edited.objectType} ${edited.primaryKey}`); } } console.log("Edited types:", result.editedObjectTypes); ``` | Field | Type | Description | | --- | --- | --- | | `type` | `"edits" \| "largeScaleEdits"` | `"largeScaleEdits"` when the action made too many edits to list. Only `editedObjectTypes` is set then. | | `addedObjects`, `modifiedObjects`, `deletedObjects` | `{ objectType, primaryKey }[]` | The objects the action created, changed, and deleted. | | `addedLinks`, `deletedLinks` | `{ linkTypeApiNameAtoB, linkTypeApiNameBtoA, aSideObject, bSideObject }[]` | The links the action created and removed. | | `deletedObjectsCount`, `deletedLinksCount` | `number` | The number of deletions. | | `editedObjectTypes` | `string[]` | The API names of every object type the action touched. | The edits name objects by type and primary key. To read the new values, load the objects again. ## Apply in a batch `batchApplyAction` takes an array of parameter objects for the same action and applies them in one request: ```ts title="src/bulkRetitle.ts" import { modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; const ids = [101, 102, 103]; const result = await client(modifyEmployee).batchApplyAction( ids.map((employee) => ({ employee, jobTitle: "Engineer II" })), { $returnEdits: true }, ); ``` Differences from `applyAction`: - It accepts `$returnEdits` but not `$validateOnly`. - It does not throw `ActionValidationError`. If a request in the batch fails, the call rejects with a `PalantirApiError`. - A batch holds up to 20 requests. Actions that only modify objects in Object Storage V2 and call no functions may have a higher limit. For more, split the array and send several batches. - Action notifications are not sent for batched requests. ## In React `useOsdkAction` from `@osdk/react` wraps `applyAction`, tracks pending and validation state, and refreshes cached objects after the action. See [Actions in React](https://palantir.github.io/osdk-ts/react/actions.md). # Aggregations Source: https://palantir.github.io/osdk-ts/sdk/aggregations > Count, sum, average, and find the min, max, or distinct values of object sets on the server, grouped by exact values, ranges, fixed widths, or durations. `aggregate` computes counts and metrics over an object set on the server and returns only the numbers. It loads no objects, so it is the right tool for totals, averages, and breakdowns, however large the set. ```ts title="src/headcount.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const stats = await client(Employee) .where({ department: "Engineering" }) .aggregate({ $select: { $count: "unordered", "salary:avg": "unordered", "salary:max": "unordered" }, }); console.log(stats.$count, stats.salary.avg, stats.salary.max); ``` `aggregate` takes `$select`, the metrics to compute, and an optional `$groupBy`. Filter first with [`where`](https://palantir.github.io/osdk-ts/sdk/filtering.md); every object set method that returns an object set, such as `pivotTo` or `intersect`, can come before it. ## Metrics Each `$select` key is `$count` or `":"`. The value is a sort direction, described in [Sort groups](#sort-groups); use `"unordered"` when you do not need one. | Metric | Property types | Result type | | --- | --- | --- | | `$count` | Not applicable | `number` | | `sum`, `avg` | Numeric | `number \| undefined` | | `min`, `max` | Numeric, date, timestamp | The property's type, or `undefined` | | `approximateDistinct` | All | `number` | | `exactDistinct` | All | `number` | A metric that does not apply to the property's type, such as `"fullName:sum"`, does not typecheck. `approximateDistinct` is faster on large sets and can be off by a small amount; `exactDistinct` is exact. ## Read the result Without `$groupBy`, the result is one object. `$count` is a number, and each property is an object keyed by metric name: ```ts title="src/salaryRange.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const result = await client(Employee).aggregate({ $select: { $count: "unordered", "salary:min": "unordered", "salary:max": "unordered", "startDate:min": "unordered", "department:exactDistinct": "unordered", }, }); const { $count, salary, startDate, department } = result; console.log(`${$count} employees in ${department.exactDistinct} departments`); console.log(`Salaries ${salary.min} to ${salary.max}, earliest start ${startDate.min}`); ``` With `$groupBy`, the result is an array with one entry per group. Each entry has the group's values under `$group`, plus the same metric fields: ```ts title="src/byDepartment.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const groups = await client(Employee).aggregate({ $select: { $count: "desc", "salary:avg": "unordered" }, $groupBy: { department: "exact" }, }); for (const group of groups) { console.log(group.$group.department, group.$count, group.salary.avg); } ``` ## Group by `$groupBy` maps each property to a grouping. Several properties group by every combination of their values. | Grouping | Property types | `$group` value | Description | | --- | --- | --- | --- | | `"exact"` | String, boolean, numeric except `long`, date, timestamp | The property's value | One group per distinct value. | | `{ $exactWithLimit: n }` | String, boolean, numeric except `long`, date, timestamp | The property's value | At most `n` groups. | | `{ $exact: { $limit?, $includeNullValue: true } }` | String, boolean, numeric except `long`, date, timestamp | The value, or `null` | Adds a group for objects with no value. | | `{ $fixedWidth: n }` | Numeric | The bucket's lower bound | Buckets of width `n`. | | `{ $ranges: [[start, end], ...] }` | Numeric, date, timestamp | `{ startValue, endValue }` | One group per range. `start` is inclusive and `end` exclusive. | | `{ $duration: [n, unit] }` | Date, timestamp | The bucket's start | Buckets of `n` time units. | `$duration` units: | Property type | Units | | --- | --- | | Date | `"days"`, `"weeks"`, `"months"`, `"quarters"`, `"years"`, and singular or short forms such as `"day"`, `"wk"`, `"mos"`, `"yr"` | | Timestamp | The date units, plus `"seconds"`, `"minutes"`, and `"hours"` and their short forms such as `"sec"`, `"min"`, `"hr"` | For weeks, months, quarters, and years, `n` must be `1`. ```ts title="src/breakdowns.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const bySalaryBand = await client(Employee).aggregate({ $select: { $count: "unordered" }, $groupBy: { salary: { $ranges: [[0, 100_000], [100_000, 200_000], [200_000, 1_000_000]] }, }, }); for (const band of bySalaryBand) { console.log(`${band.$group.salary.startValue} to ${band.$group.salary.endValue}: ${band.$count}`); } const hiresPerYear = await client(Employee).aggregate({ $select: { $count: "unordered" }, $groupBy: { startDate: { $duration: [1, "years"] } }, }); const byDepartmentAndTitle = await client(Employee).aggregate({ $select: { $count: "unordered", "salary:avg": "unordered" }, $groupBy: { department: "exact", jobTitle: { $exactWithLimit: 20 } }, }); const withUnassigned = await client(Employee).aggregate({ $select: { $count: "unordered" }, $groupBy: { department: { $exact: { $includeNullValue: true } } }, }); for (const group of withUnassigned) { console.log(group.$group.department ?? "No department", group.$count); } ``` ## Sort groups Set a metric's value in `$select` to `"asc"` or `"desc"` to order the groups by that metric. `$count: "desc"` lists the largest groups first. Sorting has two limits, both enforced by the types: - With more than one `$groupBy` property, every `$select` value must be `"unordered"`. - With `$exact: { $includeNullValue: true }`, every `$select` value must be `"unordered"`. ## Aggregate over links and set operations Because `aggregate` runs on any object set, you can aggregate over linked objects or combined sets without loading them: ```ts title="src/officeStats.ts" import { Employee, Office } from "@my-app/sdk"; import { client } from "./client"; const newYorkSalaries = await client(Office) .where({ city: "New York" }) .pivotTo("occupants") .aggregate({ $select: { "salary:sum": "unordered", $count: "unordered" } }); const lead = await client(Employee).fetchOne(12345); const teamByTitle = await lead.$link.reports.aggregate({ $select: { $count: "desc" }, $groupBy: { jobTitle: "exact" }, }); ``` To attach a per-object aggregate, such as each employee's report count, as a property you can filter and sort on, use [derived properties](https://palantir.github.io/osdk-ts/sdk/derived-properties.md). ## In React `useOsdkAggregation` from `@osdk/react` runs the same request, caches the result, and loads it again when objects of the type change. See [Aggregations in React](https://palantir.github.io/osdk-ts/react/aggregations.md). # Derived properties Source: https://palantir.github.io/osdk-ts/sdk/derived-properties > Add computed properties to an object set with withProperties, from linked objects, link aggregations, and expressions, then filter and sort on them. Related Palantir Foundry documentation: - [Derived properties](https://www.palantir.com/docs/foundry/object-link-types/derived-properties) `withProperties` adds properties that the server computes at query time, such as an employee's number of reports or their lead's name. You can select, filter, sort, and aggregate on them like stored properties, and nothing is written to the Ontology. ```ts title="src/teamSizes.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .withProperties({ reportCount: (base) => base.pivotTo("reports").aggregate("$count"), leadName: (base) => base.pivotTo("lead").selectProperty("fullName"), }) .where({ reportCount: { $gt: 5 } }) .fetchPage({ $select: ["fullName", "reportCount", "leadName"], $orderBy: { reportCount: "desc" }, }); for (const employee of page.data) { console.log(employee.fullName, employee.reportCount, employee.leadName); } ``` `withProperties` takes an object that maps each new property name to a function. The function receives a builder for the object it computes on, and returns a definition. The result is a new object set with the new properties typed: `reportCount` is a `number` and `leadName` is `string | undefined`. ## Builder methods Start from the builder and chain: | Method | Available on | Returns | | --- | --- | --- | | `pivotTo(link)` | Every builder | A builder over the linked objects. After a many link, such as `reports`, the builder has `where`, `pivotTo`, and `aggregate`, but not `selectProperty`. | | `where(clause)` | Every builder | The builder, filtered. See [Filter objects](https://palantir.github.io/osdk-ts/sdk/filtering.md). | | `selectProperty(property)` | The base object, and builders reached through single links only | The property's value. | | `aggregate(metric, options?)` | Builders reached through any link | One value computed over the linked objects. | `selectProperty` after a many link does not typecheck: an employee has many reports, so there is no single report name to select. Aggregate instead, for example with `collectList`. ## Link aggregations `aggregate` takes `$count` or `":"`: | Metric | Property types | Options | Result type | | --- | --- | --- | --- | | `$count` | Not applicable | None | `number` | | `sum`, `avg` | Numeric | None | `number \| undefined` | | `min`, `max` | Numeric, date, timestamp | None | The property's type, or `undefined` | | `approximateDistinct`, `exactDistinct` | All | None | `number` | | `approximatePercentile` | Numeric | `{ percentile }` | `number \| undefined` | | `collectList` | All | `{ limit }`, up to 100. Default 100. | An array of the property's type | | `collectSet` | All | `{ limit }`, up to 100. Default 100. | An array of distinct values | ```ts title="src/teamStats.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .withProperties({ avgReportSalary: (base) => base.pivotTo("reports").aggregate("salary:avg"), reportNames: (base) => base.pivotTo("reports").aggregate("fullName:collectList", { limit: 20 }), engineeringReports: (base) => base.pivotTo("reports").where({ department: "Engineering" }).aggregate("$count"), skipLevelCount: (base) => base.pivotTo("reports").pivotTo("reports").aggregate("$count"), }) .fetchPage({ $pageSize: 20 }); ``` ## Values from single links On a single link, `selectProperty` reads one property of the linked object. Chain single links to go further: ```ts title="src/leadInfo.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .withProperties({ officeCity: (base) => base.pivotTo("office").selectProperty("city"), leadsLeadName: (base) => base.pivotTo("lead").pivotTo("lead").selectProperty("fullName"), }) .where({ officeCity: "London" }) .fetchPage({ $select: ["fullName", "officeCity", "leadsLeadName"] }); ``` ## Expressions A numeric definition, from `selectProperty` on an `integer`, `short`, `long`, `float`, or `double` property, or a numeric aggregation, has expression methods. Each binary method takes a number or another numeric definition: | Method | Result | | --- | --- | | `add(x)`, `subtract(x)`, `multiply(x)`, `divide(x)` | Arithmetic. | | `min(x)`, `max(x)` | The smaller or larger value. | | `abs()`, `negate()` | The absolute value, or the value times -1. | A date or timestamp definition has: | Method | Result | | --- | --- | | `min(other)`, `max(other)` | The earlier or later of two date or timestamp definitions. | | `extractPart(part)` | The `"DAYS"`, `"MONTHS"`, `"QUARTERS"`, or `"YEARS"` part, as a string. | ```ts title="src/expressions.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .withProperties({ salaryPerReport: (base) => base.selectProperty("salary").divide(base.pivotTo("reports").aggregate("$count")), proposedSalary: (base) => base.selectProperty("salary").multiply(1.05), startYear: (base) => base.selectProperty("startDate").extractPart("YEARS"), earlierStart: (base) => base.selectProperty("startDate").min(base.pivotTo("lead").selectProperty("startDate")), }) .fetchPage({ $pageSize: 20 }); ``` Arithmetic on two integers returns an integer. When either side is a `double`, a `float`, or a number literal, the result is a `double`. ## Use derived properties Once added, a derived property works everywhere a stored property does on that object set: | Use | Example | | --- | --- | | Filter | `.where({ reportCount: { $gte: 3 } })` | | Sort | `.fetchPage({ $orderBy: { reportCount: "desc" } })` | | Select | `.fetchPage({ $select: ["fullName", "reportCount"] })` | | Aggregate | `.aggregate({ $select: { "reportCount:avg": "unordered" } })` | | Load by key | `.fetchOne(12345, { $select: ["reportCount"] })` | Derived properties are returned when you omit `$select`. If you pass `$select`, list them in it, along with every stored property you need. ```ts title="src/avgTeamSize.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const byDepartment = await client(Employee) .withProperties({ reportCount: (base) => base.pivotTo("reports").aggregate("$count"), }) .where({ reportCount: { $gt: 0 } }) .aggregate({ $select: { "reportCount:avg": "unordered", $count: "unordered" }, $groupBy: { department: "exact" }, }); ``` Each call to `withProperties` returns a new object set, and the properties exist only on it and on the sets derived from it. To reuse a set of definitions, store the object set in a variable. # Errors Source: https://palantir.github.io/osdk-ts/sdk/errors > The errors @osdk/client throws, the fields of PalantirApiError and ActionValidationError, Result-returning methods, retries, and patterns for handling them. Every `@osdk/client` method that sends a request rejects on failure. This page lists what it rejects with, which fields to branch on, and the methods that return a result instead of throwing. ## Error types | Error | Import | Thrown when | | --- | --- | --- | | `PalantirApiError` | `@osdk/client` | Foundry returned an error response, the request never got a response (DNS, TLS, CORS, or connection failure), or the error body was not JSON. In the last two cases `errorCode` and `errorName` are `undefined`, and the original error is on `error.cause`. | | `ActionValidationError` | `@osdk/client` | `applyAction` ran the action's validation and it failed. | | `Error` | Built in | The client rejected your input before sending anything. See [Errors before a request](#errors-before-a-request). | An error thrown by your token provider reaches you as a plain `Error` whose message starts with `Captured stack trace for error:`. The original error is on `error.cause`. ## `PalantirApiError` | Field | Type | Description | | --- | --- | --- | | `message` | `string` | The server's message, or `Failed to fetch `. | | `errorCode` | `string \| undefined` | The category, such as `PERMISSION_DENIED`, `NOT_FOUND`, `INVALID_ARGUMENT`, `CONFLICT`, or `TIMEOUT`. | | `errorName` | `string \| undefined` | The specific error, such as `ObjectTypeNotFound` or `ActionNotFound`. | | `errorDescription` | `string \| undefined` | A longer description. | | `statusCode` | `number \| undefined` | The HTTP status. `undefined` when no response arrived. | | `errorInstanceId` | `string \| undefined` | An ID for this occurrence. Log it, and include it when you report a problem to your Foundry administrator. | | `parameters` | `unknown` | Error-specific details, such as the API name that was not found. | When the request never got a response, `statusCode` is `undefined`. The low-level error is on `error.cause`, and its `originalError` holds the `TypeError` from the failed `fetch`. When no object matches, `fetchOne` and `$link..fetchOne` reject with a `PalantirApiError` that carries only a message, `Expected a single result but got 0 instead`, and no `statusCode`, `errorCode`, or `errorName`. Branch on `statusCode` and `errorCode`, which are stable. Use `errorName` for a specific case. Do not parse `message`. ```ts title="src/describeError.ts" import { PalantirApiError } from "@osdk/client"; export function describeError(error: unknown): string { if (!(error instanceof PalantirApiError)) { return error instanceof Error ? error.message : String(error); } if (error.statusCode == null && error.errorCode == null) { return "Could not reach Foundry. Check the network and the Foundry URL."; } if (error.statusCode === 401) { return "The token is missing or expired."; } if (error.errorCode === "PERMISSION_DENIED" || error.statusCode === 403) { return "You do not have access to this data."; } if (error.errorCode === "NOT_FOUND") { return `Not found: ${error.errorName ?? error.message}`; } return `${error.message} (error instance ${error.errorInstanceId ?? "unknown"})`; } ``` A `NOT_FOUND` error can also mean that the user cannot see a resource that exists. ## `ActionValidationError` `applyAction` throws `ActionValidationError` when the server ran the action's submission criteria and parameter constraints and they failed. It is not a `PalantirApiError`. Its `validation` field has `result`, `submissionCriteria`, and `parameters`. See [Actions](https://palantir.github.io/osdk-ts/sdk/actions.md#handle-validation-errors) for the shape and a message helper. `batchApplyAction` does not throw it. A batch that fails validation rejects with a `PalantirApiError`. ## Methods that return a result Three methods resolve to a `Result` instead of rejecting: | Method | On | | --- | --- | | `fetchOneWithErrors(primaryKey, options?)` | Object type sets | | `fetchPageWithErrors(options?)` | Every object set | | `$link..fetchOneWithErrors(options?)` | Single links | A `Result` is `{ value }` on success or `{ error }` on failure, where `error` is an `Error`. Narrow it with `isOk` from `@osdk/client`: ```ts title="src/optionalLead.ts" import { Employee } from "@my-app/sdk"; import { isOk } from "@osdk/client"; import { client } from "./client"; const result = await client(Employee).fetchOneWithErrors(12345, { $select: ["fullName"] }); if (isOk(result)) { console.log(result.value.fullName); } else { console.warn("Employee not available:", result.error.message); } ``` `error` is the same error the throwing variant would have thrown, so the narrowing above still applies. ## Retries The client retries a request that fails with `429 Too Many Requests` or `503 Service Unavailable`, up to three times. The delays grow exponentially from about one second, with random jitter. Other errors, including network failures, are not retried. Your code sees the error only after the last attempt. ## Errors before a request These throw a plain `Error` before any request is sent: | Error | Cause | | --- | --- | | `Invalid ontology RID` | `createClient` got an Ontology RID string that does not start with `ri.`. If you pass a `Promise`, the check runs when it resolves and surfaces as an unhandled rejection instead. | | `baseUrl cannot be empty` | `createClient` got an empty base URL. A malformed URL throws a `TypeError` from `new URL`. | | `Cannot filter on property "" with an undefined or null value` | A `where` clause had a `null` or `undefined` value. See [Filter objects](https://palantir.github.io/osdk-ts/sdk/filtering.md#how-a-clause-combines). | | `A WhereClause Filter with multiple clauses/fields is not allowed` | One property in a `where` clause had more than one operator. | | `Object does not implement interface ''` | `$as` was called with an interface the object type does not implement. See [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md#convert-one-object-with-as). | Messages from `where` validation are prefixed `Invariant failed: `, and production builds (`NODE_ENV=production`) drop the detail and throw only `Invariant failed`. `executeFunction` on a function with a union return type runs the function, then throws `Union return types are not yet supported` while reading the result. See [Functions](https://palantir.github.io/osdk-ts/sdk/functions.md#return-values). ## Patterns - Await every call inside `try`/`catch`, or attach `.catch`. A rejected promise that nothing handles crashes a Node.js process and logs an unhandled rejection in the browser. - Catch `ActionValidationError` before `PalantirApiError`, and show the validation messages to the user. Other action errors usually need a retry or an administrator. - For loads where a missing object is expected, use the `WithErrors` variants instead of catching. - In long jobs, log `errorInstanceId` and `errorName` with each failure, and keep going instead of stopping at the first error. For errors in `@osdk/react` hooks, see [Loading and errors](https://palantir.github.io/osdk-ts/concepts/loading-and-errors.md). # Filter objects Source: https://palantir.github.io/osdk-ts/sdk/filtering > Reference for where clauses in @osdk/client, covering comparison, set, null, text, array, date, geospatial, and logical operators, with examples. {/* cspell:ignore geospatial enginer */} `where` narrows an object set on the server. It takes a clause object and returns a new object set, so you can chain it with other `where` calls, [links](https://palantir.github.io/osdk-ts/sdk/links.md), [aggregations](https://palantir.github.io/osdk-ts/sdk/aggregations.md), and any load method. ```ts title="src/seniorEngineers.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ department: "Engineering", salary: { $gte: 150_000 }, jobTitle: { $containsAnyTerm: "senior staff" }, }) .fetchPage({ $select: ["fullName", "jobTitle", "salary"] }); ``` `where` sends no request by itself. The filter runs when you call `fetchPage`, `asyncIter`, `aggregate`, or another method that loads data. ## How a clause combines - Each key of the clause is a property name, `$title`, `$primaryKey`, or one of `$and`, `$or`, `$not`. - Several keys in one clause must all match. `{ department: "Engineering", salary: { $gte: 150_000 } }` is an AND. - A bare value means equality. `{ department: "Engineering" }` is the same as `{ department: { $eq: "Engineering" } }`. - Each property takes one operator. `{ salary: { $gte: 100_000, $lt: 200_000 } }` does not typecheck, and throws at runtime. Use `$and` for a range. - Chained `where` calls also combine with AND. - The value must not be `null` or `undefined`. The client throws (in development, `Invariant failed: Cannot filter on property "" with an undefined or null value`). To match missing values, use `$isNull: true`. ## Operator reference | Operator | Property types | Value | Matches | | --- | --- | --- | --- | | `$eq` | Non-array, non-geo | A value of the property's type | Equal values. Also written as the bare value. | | `$ne` | Non-array, non-geo | A value of the property's type | Values that are not equal. | | `$in` | Non-array, non-geo | An array of values | Any value in the array. An empty array matches every object. | | `$isNull` | All | `boolean` | `true`: the property has no value. `false`: it has one. | | `$gt`, `$gte`, `$lt`, `$lte` | Numbers, strings, dates, timestamps | A value of the property's type | Greater than, greater or equal, less than, less or equal. Strings compare lexicographically. | | `$startsWith` | `string` | `string`, or `{ term, phoneticSearch? }` | Values that contain the terms adjacent and in order, with the last term matched as a prefix. The match can start anywhere in the value. | | `$containsAnyTerm` | `string` | `string`, `{ term, fuzzySearch? }`, or `{ term, phoneticSearch? }` | Values that contain any of the whitespace-separated terms. | | `$containsAllTerms` | `string` | `string`, `{ term, fuzzySearch? }`, or `{ term, phoneticSearch? }` | Values that contain all the terms, in any order. | | `$containsAllTermsInOrder` | `string` | `string`, or `{ term, phoneticSearch? }` | Values that contain all the terms, adjacent and in order. | | `$interval` | `string` | An interval rule | Term proximity, ordering, prefix, and fuzzy matches. See [Interval rules](#interval-rules). | | `$matchesRegex` | `string` | `string` | Beta. Values that match the regular expression, in the Foundry search syntax. | | `$contains` | Array properties | An element value, or a filter on elements | Arrays with at least one element that matches. | | `$within` | `geopoint`, `geoshape` | Distance, bounding box, or polygon | Shapes inside the area. See [Geospatial filters](#geospatial-filters). | | `$intersects` | `geopoint`, `geoshape` | Bounding box or polygon | Shapes that overlap the area. | | `$and` | Clause | An array of clauses | Objects that match every clause. | | `$or` | Clause | An array of clauses | Objects that match at least one clause. | | `$not` | Clause | One clause | Objects that do not match the clause. | Boolean properties accept `$eq`, `$ne`, `$in`, and `$isNull`. Array properties accept only `$contains` and `$isNull`. > [!WARNING] > `$in: []` matches every object, not none. When the array comes from user input, check for an empty array before you add the filter. ## Comparison and sets ```ts title="src/comparisons.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const notSales = client(Employee).where({ department: { $ne: "Sales" } }); const team = client(Employee).where({ employeeId: { $in: [101, 102, 103] } }); const noTitle = client(Employee).where({ jobTitle: { $isNull: true } }); const midBand = client(Employee).where({ $and: [{ salary: { $gte: 100_000 } }, { salary: { $lt: 200_000 } }], }); ``` ## Text The text operators match whole terms, the whitespace-separated words of the value, rather than raw substrings. `$startsWith` is a term match too: `{ fullName: { $startsWith: "ada lov" } }` matches `Ada Lovelace`, and also `Countess Ada Lovelace`. ```ts title="src/text.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const typeahead = client(Employee).where({ fullName: { $startsWith: "ada lov" } }); const anyTerm = client(Employee).where({ jobTitle: { $containsAnyTerm: "designer researcher" } }); const allTerms = client(Employee).where({ jobTitle: { $containsAllTerms: "senior engineer" } }); const phrase = client(Employee).where({ jobTitle: { $containsAllTermsInOrder: "staff engineer" } }); ``` ### Fuzzy matching `$containsAnyTerm` and `$containsAllTerms` also take `{ term, fuzzySearch: true }`, which matches terms within a small edit distance, such as a typo: ```ts title="src/fuzzy.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const engineers = client(Employee).where({ jobTitle: { $containsAnyTerm: { term: "enginer", fuzzySearch: true } }, }); ``` ### Phonetic matching `$startsWith`, `$containsAnyTerm`, `$containsAllTerms`, and `$containsAllTermsInOrder` also take `{ term, phoneticSearch: true }`, which matches similarly pronounced terms, such as `Jon` and `John`. The property must support phonetic search, set with `supportsPhonetic` in [Ontology as code](https://palantir.github.io/osdk-ts/ontology-as-code/object-types.md). `fuzzySearch` and `phoneticSearch` cannot both be `true`; use `$or` to combine them. ```ts title="src/phonetic.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const soundsLikeJon = client(Employee).where({ fullName: { $containsAnyTerm: { term: "Jon", phoneticSearch: true } }, }); ``` ### Interval rules `$interval` takes one rule. Rules nest through `$and` and `$or`: | Rule | Fields | Matches | | --- | --- | --- | | Match | `$match: string`, `$ordered: boolean`, `$maxGaps?: number` | The terms of `$match`. `$ordered: true` requires them in order. `$maxGaps` limits the number of words between them. | | Prefix | `$match: string`, `$prefixOnLastTerm: true` | The terms in order, with the last term matched as a prefix. | | Fuzzy | `$fuzzy: string`, `$fuzziness?: number` | A term within `$fuzziness` edits (0, 1, or 2; default 2). | | All | `$and: IntervalRule[]`, `$ordered: boolean`, `$maxGaps?: number` | Every sub-rule. | | Any | `$or: IntervalRule[]` | At least one sub-rule. | ```ts title="src/interval.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const typeahead = client(Employee).where({ jobTitle: { $interval: { $match: "staff eng", $prefixOnLastTerm: true } }, }); const nearby = client(Employee).where({ jobTitle: { $interval: { $match: "principal engineer", $ordered: true, $maxGaps: 1 } }, }); ``` ## Arrays On an array property, `$contains` matches objects where at least one element matches. Pass an element value, or a filter that each element is tested against. `$isNull` is the only other operator: ```ts title="src/skills.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const typescript = client(Employee).where({ skills: { $contains: "TypeScript" } }); const anyType = client(Employee).where({ skills: { $contains: { $startsWith: "Type" } } }); const noSkills = client(Employee).where({ skills: { $isNull: true } }); ``` To require several elements, combine `$contains` filters with `$and`. ## Dates and timestamps Date and timestamp properties take ISO 8601 strings: `"2024-01-31"` for dates and `"2024-01-31T09:00:00Z"` for timestamps. They accept `$eq`, `$ne`, `$in`, `$isNull`, and the range operators: ```ts title="src/recentHires.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const hired2024 = client(Employee).where({ $and: [{ startDate: { $gte: "2024-01-01" } }, { startDate: { $lt: "2025-01-01" } }], }); ``` ## Geospatial filters Coordinates are `[longitude, latitude]`, as in GeoJSON. The samples assume `Office` has a `geopoint` property named `location`. | Filter | Value | Matches | | --- | --- | --- | | `$within: { $distance, $of }` | `$distance: [number, unit]`, `$of: [lon, lat]` or a GeoJSON `Point` | Points within the distance of the center. | | `$within: { $bbox }` or `$within: bbox` | `[west, south, east, north]` | Shapes inside the bounding box. | | `$within: { $polygon }` | Polygon coordinates: an array of rings, each closed | Shapes inside the polygon. | | `$within: polygon` | A GeoJSON `Polygon` | Shapes inside the polygon. | | `$intersects: { $bbox }` or `$intersects: bbox` | `[west, south, east, north]` | Shapes that overlap the bounding box. | | `$intersects: { $polygon }` or `$intersects: polygon` | Polygon coordinates, or a GeoJSON `Polygon` | Shapes that overlap the polygon. | Distance units are `"m"`, `"meter"`, `"meters"`, `"km"`, `"kilometer"`, `"kilometers"`, `"cm"`, `"centimeter"`, `"centimeters"`, `"mile"`, `"miles"`, `"foot"`, `"feet"`, `"inch"`, `"inches"`, `"yard"`, `"yards"`, `"nautical_mile"`, `"nauticalMile"`, and `"nautical miles"`. ```ts title="src/nearbyOffices.ts" import { Office } from "@my-app/sdk"; import { client } from "./client"; const nearNewYork = client(Office).where({ location: { $within: { $distance: [25, "km"], $of: [-74.006, 40.7128] } }, }); const inManhattan = client(Office).where({ location: { $within: { $bbox: [-74.02, 40.7, -73.93, 40.88] } }, }); const inArea = client(Office).where({ location: { $intersects: { type: "Polygon", coordinates: [[[-74.02, 40.7], [-73.93, 40.7], [-73.93, 40.88], [-74.02, 40.7]]], }, }, }); ``` ## Combine clauses `$and`, `$or`, and `$not` take clauses and nest to any depth: ```ts title="src/combined.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const result = client(Employee).where({ $or: [ { department: "Engineering", salary: { $gte: 200_000 } }, { $not: { jobTitle: { $isNull: true } }, startDate: { $gte: "2025-01-01" } }, ], }); ``` ## Title and primary key `$title` filters on the object type's title property and `$primaryKey` on its primary key, without naming them. Both are useful in code that works across object types: ```ts title="src/special.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const byTitle = client(Employee).where({ $title: { $startsWith: "Ada" } }); const byKey = client(Employee).where({ $primaryKey: { $in: [101, 102] } }); ``` ## Struct properties A struct property filters on one field at a time: `{ address: { city: "Denver" } }` applies the field's own operators to `address.city`. To filter on two fields, combine two clauses with `$and`. On an array of structs, wrap the field filter in `$contains`: `{ addresses: { $contains: { city: "Denver" } } }`. ## Vector search `nearestNeighbors(query, numNeighbors, property)` returns an object set of the objects whose vector property is closest to the query. `query` is text, which the server embeds with the property's model, or a vector with the property's dimension. `numNeighbors` is between 1 and 500. To get the closest first, and a `$score` on each object, load the result with `$orderBy: "relevance"`. ## Type a clause Build a clause outside the call with the `WhereClause` type from `@osdk/client`: ```ts title="src/highEarners.ts" import { Employee } from "@my-app/sdk"; import type { WhereClause } from "@osdk/client"; import { client } from "./client"; function highEarnersIn(department: string, minSalary: number): WhereClause { return { department, salary: { $gte: minSalary } }; } const page = await client(Employee) .where(highEarnersIn("Engineering", 150_000)) .fetchPage({ $select: ["fullName", "department"] }); ``` # Functions Source: https://palantir.github.io/osdk-ts/sdk/functions > Execute Foundry functions (queries) with executeFunction, pass objects and object sets as parameters, and read struct, object, and object set results. Related Palantir Foundry documentation: - [Functions](https://www.palantir.com/docs/foundry/functions/overview) Functions published to the Ontology, called queries in the API, appear in your generated SDK next to object types and actions. `client(myFunction).executeFunction(params)` runs one on the server and resolves to its typed return value. The samples use these functions, which stand in for functions in your own SDK: | Function | Parameters | Returns | | --- | --- | --- | | `countEmployees` | None | `integer` | | `getEmployeeMetrics` | `department: string` | Struct `{ headcount: integer }` | | `summarizeTeam` | `team: ObjectSet` | `string` | | `getTopEarners` | `department: string`, `limit?: integer` | `ObjectSet` | | `getManager` | `employee: Employee` | `Employee` | ## Execute a function ```ts title="src/metrics.ts" import { countEmployees, getEmployeeMetrics } from "@my-app/sdk"; import { client } from "./client"; const total = await client(countEmployees).executeFunction(); const metrics = await client(getEmployeeMetrics).executeFunction({ department: "Engineering" }); console.log(`${metrics.headcount} of ${total} employees are engineers`); ``` `executeFunction` takes one object with a key per parameter, or no argument when the function has no parameters. Nullable parameters are optional. It rejects with a `PalantirApiError` when the function fails or times out on the server; see [Errors](https://palantir.github.io/osdk-ts/sdk/errors.md). If your SDK was generated with a pinned function version, the client calls that version. Otherwise it calls the latest published version. ## Parameter values | Parameter type | Pass | | --- | --- | | Primitive | A value of the parameter's TypeScript type. Dates and timestamps are ISO 8601 strings. `long` accepts a `number` or a `string`. | | Object | A loaded object, its primary key, or `{ $apiName, $primaryKey }`. | | Interface | An object loaded through the interface, or `{ $objectType, $primaryKey }`, where `$objectType` is the concrete object type. | | Object set | An object set, such as `client(Employee).where({ ... })`. The server receives its definition, not its objects. | | List, set | An array, or a `Set` for set parameters. | | Struct | An object whose keys are the struct's fields. | | Map | An object keyed by the map's keys. For object keys, use each object's `$objectSpecifier`. | | Attachment | An attachment RID, a `File`, or the result of `createAttachmentUpload`. The client uploads it first. | | Media reference | A `MediaUpload`, a `Media` from an object, or a `MediaReference`. | Pass an object set to let the function work on a filtered set without loading it in the client: ```ts title="src/summarize.ts" import { Employee, summarizeTeam } from "@my-app/sdk"; import { client } from "./client"; const summary = await client(summarizeTeam).executeFunction({ team: client(Employee).where({ department: "Sales", startDate: { $gte: "2025-01-01" } }), }); ``` ## Return values | Return type | You get | | --- | --- | | Primitive | The value. `long` is a string; dates and timestamps are ISO 8601 strings. | | List, set | An array. Set results are typed `Set` in the generated SDK but arrive as arrays; wrap them with `new Set(result)` before using `Set` methods. | | Struct | A plain object. | | Map | A plain object keyed by the map's keys. Object keys become object specifier strings. | | Object | An object reference with `$apiName`, `$objectType`, and `$primaryKey`. It has no properties. | | Object set | An object set. Load it with `fetchPage`, `asyncIter`, or `aggregate`. | | Attachment | An `Attachment`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md). | | Media reference | A `Media`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md). | | Two-dimensional aggregation | `{ key, value }[]` | | Three-dimensional aggregation | `{ key, groups: { key, value }[] }[]` | | Nullable, when the function returns nothing | `undefined` | Union return types are not supported: the client throws `Union return types are not yet supported`. ### Object results A returned object is a reference, not a loaded object. Load it by primary key to read its properties: ```ts title="src/manager.ts" import { Employee, getManager } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345); const managerRef = await client(getManager).executeFunction({ employee }); const manager = await client(Employee).fetchOne(managerRef.$primaryKey, { $select: ["fullName", "jobTitle"], }); ``` ### Object set results A returned object set is like any other. Filter, sort, page, and aggregate it before loading: ```ts title="src/topEarners.ts" import { getTopEarners } from "@my-app/sdk"; import { client } from "./client"; const topEarners = await client(getTopEarners).executeFunction({ department: "Sales", limit: 10 }); const page = await topEarners.fetchPage({ $select: ["fullName", "salary"], $orderBy: { salary: "desc" }, }); ``` ## In React `useOsdkFunction` from `@osdk/react` executes a function, caches the result by its parameters, and can refetch when objects it depends on change. See [Functions in React](https://palantir.github.io/osdk-ts/react/functions.md). # TypeScript SDK overview Source: https://palantir.github.io/osdk-ts/sdk > Query objects, apply actions, and run functions from any TypeScript runtime with @osdk/client, in Node.js scripts, servers, Vue, or any framework. Related Palantir Foundry documentation: - [TypeScript OSDK](https://www.palantir.com/docs/foundry/ontology-sdk/typescript-osdk) `@osdk/client` reads and edits your Ontology from any JavaScript runtime with `fetch`: Node.js scripts and servers, serverless functions, and browser apps in any framework. It has no UI dependency. Your generated SDK supplies typed definitions for your object types, interfaces, actions, and functions, and the client runs them. ## Install Your generated SDK comes from your Foundry npm registry. Set up `.npmrc` as described in [Installation](https://palantir.github.io/osdk-ts/installation.md), then: ```npm npm install @osdk/client @osdk/api @osdk/oauth @my-app/sdk@latest ``` Create one client for your app with `createClient`, as described in [Create a client](https://palantir.github.io/osdk-ts/client.md). [Authentication](https://palantir.github.io/osdk-ts/authentication.md) covers the token provider. The samples in this section import that client from `./client`. ## Example ```ts title="src/index.ts" import { Employee, modifyEmployee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ department: "Engineering", jobTitle: { $isNull: true } }) .fetchPage({ $select: ["fullName"], $pageSize: 20 }); for (const employee of page.data) { await client(modifyEmployee).applyAction({ employee, jobTitle: "Engineer" }); console.log(`Set title for ${employee.fullName}`); } ``` The query runs on the server and returns typed objects. Each `applyAction` call validates and applies one edit. In real code, wrap it in `try`/`catch`, as shown in [Actions](https://palantir.github.io/osdk-ts/sdk/actions.md). ## One entry point: `client(definition)` Call `client` with a definition from your SDK. What it returns depends on the definition: | You pass | You get | Main methods | | --- | --- | --- | | An object type, such as `Employee` | An object set of every object of that type | `fetchOne`, `fetchPage`, `asyncIter`, `where`, `aggregate`, `pivotTo`, `withProperties`, `subscribe` | | An interface, such as `Worker` | An object set over every type that implements it | The same, except `fetchOne` | | An action, such as `modifyEmployee` | An action invoker | `applyAction`, `batchApplyAction` | | A function (query) | A function invoker | `executeFunction` | Object sets are lazy descriptions. `where`, `pivotTo`, `union`, and `withProperties` return new object sets without sending a request. A request goes out when you call a method that loads data: `fetchOne`, `fetchPage`, `asyncIter`, `aggregate`, or `subscribe`. `client.fetchMetadata(definition)` loads the definition from Foundry at runtime, such as an object type's `displayName`, `description`, and `icon`, or an interface's `implementedBy`. ## Relation to `@osdk/react` `@osdk/react` is built on this client. Its hooks accept the same `where` clauses, derived property definitions, and action parameters, and add a shared cache that keeps components current after actions and live updates. In a React app, use the hooks for data you render and call the client directly for one-off work, such as exports. See [Objects in React](https://palantir.github.io/osdk-ts/react/objects.md). Outside React, framework guides show how to wire the client in [Node.js](https://palantir.github.io/osdk-ts/frameworks/node.md) and [Vue](https://palantir.github.io/osdk-ts/frameworks/vue.md). ## In this section - [Load objects](https://palantir.github.io/osdk-ts/sdk/objects.md): fetchOne, fetchPage, asyncIter, $select, sorting, and the object shape. - [Filter objects](https://palantir.github.io/osdk-ts/sdk/filtering.md): Every where operator, with examples. - [Links and object sets](https://palantir.github.io/osdk-ts/sdk/links.md): Follow links, pivot sets, and combine them. - [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md): Query across object types and convert between views. - [Aggregations](https://palantir.github.io/osdk-ts/sdk/aggregations.md): Counts, metrics, and group-bys on the server. - [Derived properties](https://palantir.github.io/osdk-ts/sdk/derived-properties.md): Compute properties at query time with withProperties. - [Actions](https://palantir.github.io/osdk-ts/sdk/actions.md): Apply, validate, and batch edits. - [Functions](https://palantir.github.io/osdk-ts/sdk/functions.md): Run Foundry functions and read their results. - [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md): Download and upload files. - [Subscriptions](https://palantir.github.io/osdk-ts/sdk/subscriptions.md): Receive live updates for an object set. - [Errors](https://palantir.github.io/osdk-ts/sdk/errors.md): Error types, retries, and handling patterns. # Interfaces Source: https://palantir.github.io/osdk-ts/sdk/interfaces > Query objects of every type that implements an interface, convert between interface and object views with $as, and narrow object sets with narrowToType. Related Palantir Foundry documentation: - [Interfaces](https://www.palantir.com/docs/foundry/interfaces/interface-overview) An interface describes properties that several object types share. Querying an interface returns objects of every type that implements it, viewed through the interface's properties. You can then convert each object to its concrete type. In the example SDK, the interface `Worker` has one property, `name`. `Employee` implements it, with `fullName` as `name`. ## Query an interface `client(Worker)` is an object set over every object that implements `Worker`. Filter, sort, and select by the interface's property names: ```ts title="src/workers.ts" import { Worker } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Worker) .where({ name: { $startsWith: "ada" } }) .fetchPage({ $select: ["name"], $orderBy: { name: "asc" }, $pageSize: 50 }); for (const worker of page.data) { console.log(worker.$objectType, worker.$primaryKey, worker.name); } ``` On an interface object, `$apiName` is the interface (`"Worker"`) and `$objectType` is the object's concrete type (`"Employee"`). `$primaryKey` is the concrete object's primary key. ## What an interface object set supports | Method | Supported | Notes | | --- | --- | --- | | `where` | Yes | On interface property names. | | `fetchPage`, `fetchPageWithErrors`, `asyncIter` | Yes | Accept `$includeAllBaseObjectProperties`. | | `aggregate` | Yes | On interface property names. | | `subscribe` | Yes | See [Subscriptions](https://palantir.github.io/osdk-ts/sdk/subscriptions.md). | | `narrowToType` | Yes | Converts to an object type set. See below. | | `pivotTo` | Yes | For links defined on the interface. | | `union`, `intersect`, `subtract` | With other sets of the same interface | Not with object type sets. Narrow first. | | `fetchOne`, `fetchOneWithErrors` | No | Typed `never`. A primary key is unique only within one object type, so load by key from the object type: `client(Employee).fetchOne(id)`. | ## Convert one object with `$as` `$as(Employee)` returns the concrete view of an interface object, with the object type's property names. `$as(Worker)` goes the other way: ```ts title="src/workerDetails.ts" import { Employee, Worker } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Worker).fetchPage({ $pageSize: 20 }); for (const worker of page.data) { if (worker.$objectType === "Employee") { const employee = worker.$as(Employee); console.log(employee.fullName); } } const employee = await client(Employee).fetchOne(12345); const asWorker = employee.$as(Worker); console.log(asWorker.name); ``` `$as` makes no request. It only exposes the properties that were loaded: - From an interface fetch, the concrete view has only the properties that the interface maps to, such as `fullName`. Reading `salary` is a type error. - To get every property of the object type, pass `$includeAllBaseObjectProperties: true` to `fetchPage` or `asyncIter`. Then `$as(Employee)` has all `Employee` properties. ```ts title="src/fullEmployees.ts" import { Employee, Worker } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Worker).fetchPage({ $includeAllBaseObjectProperties: true }); for (const worker of page.data) { if (worker.$objectType === "Employee") { const employee = worker.$as(Employee); console.log(employee.fullName, employee.salary, employee.department); } } ``` `$includeAllBaseObjectProperties` cannot be combined with `$select`. `$as` throws when: - The target is an object type other than the object's own. Check `$objectType` first, as above. - The target interface is not implemented by the object type. - Converting an interface object to its object type, when one of the interface's properties is implemented by something other than a plain property of the object type. The message tells you to load the object type directly. ## Convert an object set with `narrowToType` `narrowToType` converts a whole object set on the server, and keeps only objects of the given type: ```ts title="src/narrow.ts" import { Employee, Worker } from "@my-app/sdk"; import { client } from "./client"; const engineers = await client(Worker) .where({ name: { $startsWith: "a" } }) .narrowToType(Employee) .where({ department: "Engineering" }) .fetchPage({ $select: ["fullName", "jobTitle"] }); const workersInSales = client(Employee).where({ department: "Sales" }).narrowToType(Worker); ``` From an interface, pass a type that implements it. From an object type, pass an interface it implements. Other types do not typecheck. ## Read interface metadata `client.fetchMetadata(Worker)` loads the interface definition from Foundry, including `implementedBy`, the API names of the object types that implement it: ```ts title="src/workerMetadata.ts" import { Worker } from "@my-app/sdk"; import { client } from "./client"; const metadata = await client.fetchMetadata(Worker); console.log(metadata.displayName, metadata.implementedBy); ``` ## Pass interface objects to actions An action parameter of an interface type takes a plain object with the concrete type and primary key, such as `{ $objectType: worker.$objectType, $primaryKey: worker.$primaryKey }`. Pass that object, not the loaded `worker` itself. See [Actions](https://palantir.github.io/osdk-ts/sdk/actions.md#parameter-values). # Links and object sets Source: https://palantir.github.io/osdk-ts/sdk/links > Traverse links from an object with $link, pivot whole object sets with pivotTo, and combine object sets with union, intersect, and subtract. Related Palantir Foundry documentation: - [Link types](https://www.palantir.com/docs/foundry/object-link-types/link-types-overview) Links connect objects of one type to objects of another, such as an `Employee` to their `Office`. You can follow a link from one loaded object with `$link`, or from a whole object set with `pivotTo`. Object sets also combine with `union`, `intersect`, and `subtract`, all on the server. In the example SDK, `Employee` has three links: `lead` (one `Employee`), `reports` (many `Employee`), and `office` (one `Office`). `Office` has `occupants` (many `Employee`). ## Follow a link from an object Every object has a `$link` field with one entry per link type. What the entry is depends on the link's cardinality: | Link | `$link` entry | Methods | | --- | --- | --- | | One, such as `office` | A single-link accessor | `fetchOne(options?)`, `fetchOneWithErrors(options?)` | | Many, such as `reports` | An object set of the linked type | Everything an object set has: `where`, `fetchPage`, `asyncIter`, `aggregate`, `pivotTo`, and more | ### One-to-one and many-to-one links ```ts title="src/employeeOffice.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345); const office = await employee.$link.office.fetchOne({ $select: ["name", "city"] }); console.log(`${employee.fullName} works in ${office.name}, ${office.city}`); ``` `fetchOne` takes `$select` and `$includeRid`. It rejects when the object has no linked object, with a `PalantirApiError` whose message is `Expected a single result but got 0 instead`. If the link is optional, use `fetchOneWithErrors` and check the result: ```ts title="src/employeeLead.ts" import { Employee } from "@my-app/sdk"; import { isOk } from "@osdk/client"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345); const lead = await employee.$link.lead.fetchOneWithErrors({ $select: ["fullName"] }); console.log(isOk(lead) ? `Reports to ${lead.value.fullName}` : "No lead"); ``` ### One-to-many and many-to-many links A many link is an object set, so you can filter, sort, page, and aggregate it before loading anything: ```ts title="src/directReports.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const lead = await client(Employee).fetchOne(12345); const engineers = await lead.$link.reports .where({ department: "Engineering" }) .fetchPage({ $select: ["fullName", "jobTitle"], $orderBy: { fullName: "asc" } }); const { $count } = await lead.$link.reports.aggregate({ $select: { $count: "unordered" } }); console.log(`${engineers.data.length} engineers of ${$count} reports`); ``` `$link` sends no request until you call a load method. You do not need to `$select` anything for `$link` to work: the link resolves from the object's primary key. ## Pivot an object set `pivotTo(link)` returns the set of objects linked to any object in the source set. Use it to traverse links for many objects in one request instead of one request per object: ```ts title="src/engineeringOffices.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const offices = await client(Employee) .where({ department: "Engineering" }) .pivotTo("office") .fetchPage({ $select: ["name", "city"] }); ``` The result has no duplicates: an office with ten engineers appears once. Pivots chain, and the result is a full object set: ```ts title="src/skipLevel.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const skipLevelReports = client(Employee) .where({ employeeId: 12345 }) .pivotTo("reports") .pivotTo("reports"); const result = await skipLevelReports .where({ jobTitle: { $containsAnyTerm: "manager" } }) .aggregate({ $select: { $count: "unordered" } }); ``` The link name must exist on the source type. `pivotTo("occupants")` on an `Employee` set does not typecheck. ## Combine object sets `union`, `intersect`, and `subtract` take one or more object sets of the same type and return a new object set. Nothing loads until you call a load method: | Method | Returns | | --- | --- | | `a.union(b, c)` | Objects in any of the sets. | | `a.intersect(b, c)` | Objects in every set. | | `a.subtract(b, c)` | Objects in `a` that are in none of the other sets. | ```ts title="src/promotionCandidates.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const longTenure = client(Employee).where({ startDate: { $lt: "2020-01-01" } }); const highRated = client(Employee).where({ jobTitle: { $containsAnyTerm: "senior" } }); const leads = client(Employee).where({ employeeId: { $in: [101, 102] } }).pivotTo("lead"); const candidates = longTenure.intersect(highRated).subtract(leads); const page = await candidates.fetchPage({ $select: ["fullName", "jobTitle"] }); ``` The sets must be of the same object type. An `Employee` set and a `Worker` interface set do not combine; see [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md) to convert between them with `narrowToType`. ## Load links in bulk `experimental_asyncIterLinks(links)` iterates over the links of every object in a set and yields `{ source, target, linkType }`, where `source` and `target` carry `$apiName` and `$primaryKey`. It is experimental and may change. Use it to build an in-memory graph: ```ts title="src/orgChart.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const managerOf = new Map(); for await (const { source, target } of client(Employee).experimental_asyncIterLinks(["lead"])) { managerOf.set(source.$primaryKey, target.$primaryKey); } ``` Limits: - Links can be stale: a returned primary key may no longer exist. - The server loads source objects in pages. If one page has more than 100,000 links, the result for that page is cut off at 100,000. - Object Storage V1 links are not supported and throw. - Interface links are not supported. ## In React `@osdk/react` wraps these calls in hooks that cache and update: `useLinks` for `$link`, and `useObjectSet` for pivots and set operations. See [Links in React](https://palantir.github.io/osdk-ts/react/links.md) and [Object sets in React](https://palantir.github.io/osdk-ts/react/object-sets.md). # Attachments and media Source: https://palantir.github.io/osdk-ts/sdk/media > Read attachment and media reference properties with fetchContents and fetchMetadata, and upload files by passing them to action parameters. Related Palantir Foundry documentation: - [Media set API](https://www.palantir.com/docs/foundry/api/v2/media-sets-v2-resources/media-sets/media-set-basics) Objects store files in two property types. Attachment properties hold files uploaded through actions. Media reference properties point to items in a Foundry media set, such as images, documents, audio, and video. Both load lazily: the object holds a handle, and you download the content when you need it. The samples assume `Employee` has an attachment property `resume` and a media reference property `photo`, and that an action `updateEmployeeFiles` takes `employee`, `resume` (attachment), and `photo` (media reference). ## Read an attachment An attachment property is an `Attachment`: | Member | Type | Description | | --- | --- | --- | | `rid` | `string` | The attachment RID. | | `fetchMetadata()` | `Promise` | Loads `rid`, `filename`, `sizeBytes`, and `mediaType`. | | `fetchContents()` | `Promise` | Downloads the file. Read it with `blob()`, `arrayBuffer()`, or `text()`. | ```ts title="src/downloadResume.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345, { $select: ["resume"] }); if (employee.resume != null) { const metadata = await employee.resume.fetchMetadata(); console.log(metadata.filename, metadata.mediaType, metadata.sizeBytes); const response = await employee.resume.fetchContents(); const blob = await response.blob(); console.log(`Downloaded ${blob.size} bytes`); } ``` ## Read a media reference A media reference property is a `Media`: | Member | Type | Description | | --- | --- | --- | | `fetchMetadata()` | `Promise` | Loads `mediaType`, `sizeBytes`, and `path` when the item has one. | | `fetchFullMetadata?()` | `Promise` | Loads type-specific metadata, such as page count for documents and dimensions for images. Optional in the type, but every `Media` the client returns has it. | | `fetchContents()` | `Promise` | Downloads the item. | | `getMediaReference()` | `MediaReference` | The reference itself: the MIME type and the media set item it points to. Pass it to an action or function. | ```ts title="src/employeePhoto.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345, { $select: ["photo"] }); const metadata = await employee.photo?.fetchMetadata(); console.log(metadata?.mediaType, metadata?.sizeBytes); const full = await employee.photo?.fetchFullMetadata?.(); if (full?.itemMetadata.type === "imagery") { console.log(full.itemMetadata.dimensions); } const response = await employee.photo?.fetchContents(); if (response != null) { const image = await response.blob(); } ``` `itemMetadata.type` is one of `"document"`, `"imagery"`, `"audio"`, `"video"`, `"dicom"`, `"email"`, `"model3d"`, `"spreadsheet"`, or `"untyped"`. When the server returns a type this client version does not know, `type` is `"unknown"` and the payload is on `raw`. `fetchContents` resolves to a standard `Response` on success and rejects with a `PalantirApiError` on a non-2xx status, so wrap it in `try`/`catch`. ## Upload through an action The client does not write files to objects directly. Pass the file as an action parameter, and the client uploads it before it applies the action: | Parameter type | Pass | | --- | --- | | Attachment | `createAttachmentUpload(blob, fileName)`, a `File`, or the RID of an existing attachment. | | Media reference | A `MediaUpload` (`{ data: blob, fileName }`), a `Media` from another object, or a `MediaReference`. | **Node.js** ```ts title="src/uploadFiles.ts" import { updateEmployeeFiles } from "@my-app/sdk"; import { createAttachmentUpload, type MediaUpload } from "@osdk/client"; import { openAsBlob } from "node:fs"; import { client } from "./client"; const resume = await openAsBlob("./resume.pdf", { type: "application/pdf" }); const photo: MediaUpload = { data: await openAsBlob("./photo.png", { type: "image/png" }), fileName: "photo.png", }; await client(updateEmployeeFiles).applyAction({ employee: 12345, resume: createAttachmentUpload(resume, "resume.pdf"), photo, }); ``` `openAsBlob` needs Node.js 19.8 or later. **Browser** ```ts title="src/uploadFiles.ts" import { updateEmployeeFiles } from "@my-app/sdk"; import { client } from "./client"; export async function uploadResume(employeeId: number, input: HTMLInputElement) { const file = input.files?.[0]; if (file == null) { return; } await client(updateEmployeeFiles).applyAction({ employee: employeeId, resume: file }); } ``` A `File` from an `` already has a name, so you can pass it as is. To reuse a file that is already in Foundry, pass its handle instead of uploading again: ```ts title="src/copyPhoto.ts" import { Employee, updateEmployeeFiles } from "@my-app/sdk"; import { client } from "./client"; const source = await client(Employee).fetchOne(12345, { $select: ["resume", "photo"] }); await client(updateEmployeeFiles).applyAction({ employee: 67890, resume: source.resume?.rid, photo: source.photo, }); ``` Uploads are temporary until an action links them to an object. If the action fails, or you never apply one, Foundry deletes the uploaded file after one hour. Functions accept the same values for attachment and media reference parameters. See [Functions](https://palantir.github.io/osdk-ts/sdk/functions.md#parameter-values). # Load objects Source: https://palantir.github.io/osdk-ts/sdk/objects > Load one object by primary key, page through object sets, iterate over every object, select properties, sort, and read the Osdk.Instance shape. Related Palantir Foundry documentation: - [Object types](https://www.palantir.com/docs/foundry/object-link-types/object-types-overview) An object set from `client(Employee)` loads objects in three ways: one object by primary key, one page at a time, or every object with an async iterator. This page covers each method, its options, and the shape of the objects it returns. The samples import a client from `./client`. See [Create a client](https://palantir.github.io/osdk-ts/client.md) to set one up. ## Load one object `fetchOne` takes a primary key and resolves to the object: ```ts title="src/getEmployee.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345, { $select: ["fullName", "jobTitle", "department"], }); console.log(employee.$primaryKey, employee.fullName, employee.jobTitle); ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `$select` | `PropertyKeys[]` | The API's default property set | Properties to load. The primary key is always returned. | | `$includeRid` | `boolean` | `false` | Adds `$rid` to the returned object. | `fetchOne` rejects when no object has that primary key, or when you cannot see it. The error is a `PalantirApiError` with the message `Expected a single result but got 0 instead` and no `statusCode` or `errorName`. `fetchOne` exists only on object types. Interface object sets do not have it; see [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md). ### Without exceptions `fetchOneWithErrors` takes the same arguments and resolves to a `Result` instead of rejecting. Narrow it with `isOk`: ```ts title="src/getEmployee.ts" import { Employee } from "@my-app/sdk"; import { isOk } from "@osdk/client"; import { client } from "./client"; const result = await client(Employee).fetchOneWithErrors(12345, { $select: ["fullName"], }); if (isOk(result)) { console.log(result.value.fullName); } else { console.error("Could not load employee", result.error.message); } ``` A `Result` is either `{ value }` or `{ error }`, where `error` is an `Error`. See [Errors](https://palantir.github.io/osdk-ts/sdk/errors.md) for the error types. ## Load a page `fetchPage` resolves to one page of objects: ```ts title="src/listEngineers.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ department: "Engineering" }) .fetchPage({ $select: ["fullName", "jobTitle", "startDate"], $orderBy: { startDate: "desc" }, $pageSize: 50, }); for (const employee of page.data) { console.log(employee.fullName, employee.jobTitle); } ``` | Option | Type | Default | Description | | --- | --- | --- | --- | | `$select` | `PropertyKeys[]` | The API's default property set | Properties to load. See [Select properties](#select-properties). | | `$orderBy` | `{ [property]: "asc" \| "desc" } \| "relevance"` | Unordered | Sort order. See [Sort](#sort). | | `$pageSize` | `number` | Server default | Objects in this page. It does not limit the total; continue with `nextPageToken`. | | `$nextPageToken` | `string` | | The `nextPageToken` from the previous page. | | `$snapshot` | `boolean` | `false` | Pages through one consistent view of the data. See [Paging and consistency](#paging-and-consistency). | | `$includeRid` | `boolean` | `false` | Adds `$rid` to each object. | | `$includeAllBaseObjectProperties` | `boolean` | `false` | On interface sets, loads every property of the underlying object type. On object type sets, loads ontology-defined derived properties. See [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md). | The page has three fields: | Field | Type | Description | | --- | --- | --- | | `data` | `Osdk.Instance[]` | The objects in this page. | | `nextPageToken` | `string \| undefined` | Pass as `$nextPageToken` to load the next page. `undefined` on the last page. | | `totalCount` | `string` | The number of objects in the set, as a string. | `fetchPageWithErrors` takes the same options and resolves to a `Result` of the page instead of rejecting. ### Page through results Pass each page's `nextPageToken` into the next request until it is `undefined`: ```ts title="src/allEngineers.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const engineers = client(Employee).where({ department: "Engineering" }); let nextPageToken: string | undefined; do { const page = await engineers.fetchPage({ $select: ["fullName"], $pageSize: 100, $nextPageToken: nextPageToken, $snapshot: true, }); for (const employee of page.data) { console.log(employee.fullName); } nextPageToken = page.nextPageToken; } while (nextPageToken != null); ``` Keep the other options the same on every page. Only `$nextPageToken` changes. ## Load every object `asyncIter` loads page after page until it has every object in the set, and yields them one at a time: ```ts title="src/countSkills.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const skillCounts = new Map(); for await (const employee of client(Employee).asyncIter({ $select: ["skills"] })) { for (const skill of employee.skills ?? []) { skillCounts.set(skill, (skillCounts.get(skill) ?? 0) + 1); } } ``` `asyncIter` accepts `$select`, `$orderBy`, `$includeRid`, and `$includeAllBaseObjectProperties`. It requests pages of 10,000 objects and always requests a snapshot. Before you iterate over a large object type: - Pass `$select` with only the properties you read. Loading unused properties costs bandwidth and server time, and reading fewer properties afterwards does not undo it. - Handle each object as it arrives. Collecting every object into an array makes memory grow with the size of the set. - For counts, sums, and group-bys, use [`aggregate`](https://palantir.github.io/osdk-ts/sdk/aggregations.md). It runs on the server and loads no objects. - For a sample or the first N objects, use `fetchPage` with `$pageSize`. ## Paging and consistency | Method | Loads | Snapshot | | --- | --- | --- | | `fetchPage({ $pageSize })` | One page. Continue with `nextPageToken`. | Only with `$snapshot: true`, passed on every page. | | `asyncIter()` | Every matching object, page after page. | Always. | | `aggregate({ ... })` | Counts, sums, and groups only. | Not applicable. | Without a snapshot, later pages can repeat or skip objects if objects are added, removed, or edited between requests. A snapshot configured for a function run still applies, whatever you pass. With a snapshot, every page of a non-stream-backed object type reflects the same point in time, so a completed traversal returns each object exactly once. This does not hold with `$orderBy: "relevance"`: relevance-ordered pages can repeat or skip objects, so use a single `fetchPage` for relevance results. Paging fails if the snapshot expires or the server detects a paging inconsistency (`PagingInconsistencyDetected`). Stream-backed object types do not keep a snapshot across pages: changes during a traversal can make it fail, and exactly-once traversal is not guaranteed. If an `asyncIter` traversal of a frequently updated object type fails: 1. Aggregate instead, if you only need a summary. 2. Select fewer properties and filter the set so the traversal finishes sooner. 3. Loop over `fetchPage` without a snapshot and de-duplicate by `$primaryKey`. De-duplication removes repeated objects but cannot recover skipped ones. ## Select properties Without `$select`, the server returns its default property set for the object type. Vector properties, for example, are not in it. With `$select`, the result type narrows to the properties you asked for, so reading anything else is a type error: ```ts title="src/names.ts" import { Employee } from "@my-app/sdk"; import type { Osdk } from "@osdk/client"; import { client } from "./client"; const page = await client(Employee).fetchPage({ $select: ["fullName", "department"] }); const first: Osdk.Instance = page.data[0]; console.log(first.fullName, first.department); ``` Rules for `$select`: - The primary key is always returned, as a property and as `$primaryKey`. - Ontology-defined derived properties are not returned by default. Name them in `$select`. - Derived properties you add with [`withProperties`](https://palantir.github.io/osdk-ts/sdk/derived-properties.md) are returned when `$select` is omitted. If you pass `$select`, name them in it too. ## Sort `$orderBy` maps property names to `"asc"` or `"desc"`. With several keys, the first key sorts first and later keys break ties: ```ts title="src/directory.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee).fetchPage({ $select: ["department", "fullName"], $orderBy: { department: "asc", fullName: "asc" }, $pageSize: 100, }); ``` With `fetchPage`, include each `$orderBy` key in `$select`. An `$orderBy` that names no selected property does not typecheck. `$orderBy: "relevance"` sorts by how well each object matches the text filters in your `where` clause, and adds a numeric `$score` to each object: ```ts title="src/search.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const page = await client(Employee) .where({ jobTitle: { $containsAnyTerm: "staff engineer" } }) .fetchPage({ $orderBy: "relevance", $pageSize: 10 }); for (const employee of page.data) { console.log(employee.$score, employee.jobTitle); } ``` ## The object shape Each object is an `Osdk.Instance`: its properties plus a few `$` fields. Objects are frozen, so assigning to a property throws in strict mode. | Field | Type | Description | | --- | --- | --- | | `$primaryKey` | The primary key type | The object's primary key, such as `12345`. | | `$apiName` | `string` | The API name of the type you queried: the object type, or the interface for interface queries. | | `$objectType` | `string` | The API name of the object's concrete object type. Differs from `$apiName` on interface objects. | | `$title` | `string \| undefined` | The value of the object type's title property. | | `$rid` | `string` | The object's RID. Present only when you pass `$includeRid: true`. | | `$objectSpecifier` | `string` | A string that identifies the object across types. | | `$link` | `object` | Accessors for linked objects. See [Links](https://palantir.github.io/osdk-ts/sdk/links.md). | | `$as` | `(type) => Osdk.Instance` | Views the object as an interface it implements, or an interface object as its object type. See [Interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md). | | `$clone` | `(changes?) => Osdk.Instance` | Returns a copy, optionally with some property values replaced. | Nullable properties are typed `T | undefined`. Property values use these TypeScript types: | Property type | TypeScript type | | --- | --- | | `string` | `string` | | `integer`, `short`, `byte`, `float`, `double` | `number` | | `long`, `decimal` | `string` | | `boolean` | `boolean` | | `date`, `timestamp` | `string`, in ISO 8601 format | | Array properties | `T[]` | | `geopoint` | GeoJSON `Point` | | `geoshape` | GeoJSON geometry | | `attachment` | `Attachment`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md). | | `mediaReference` | `Media`. See [Attachments and media](https://palantir.github.io/osdk-ts/sdk/media.md). | ### Copy with changes `$clone` builds a new local object. It does not write to Foundry; use an [action](https://palantir.github.io/osdk-ts/sdk/actions.md) for that. It throws if the changes include a different primary key: ```ts title="src/preview.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const employee = await client(Employee).fetchOne(12345); const preview = employee.$clone({ jobTitle: "Senior Engineer" }); console.log(employee.jobTitle, "->", preview.jobTitle); ``` ### Type objects in your code Use `Osdk.Instance` from `@osdk/client`, or the generated alias `Employee.OsdkInstance`. Narrow the properties with the third type argument, and add `"$rid"` as the second to include the RID: ```ts title="src/types.ts" import type { Employee } from "@my-app/sdk"; import type { Osdk } from "@osdk/client"; type FullEmployee = Osdk.Instance; type EmployeeName = Osdk.Instance; type EmployeeWithRid = Osdk.Instance; function label(employee: EmployeeName): string { return employee.fullName ?? String(employee.$primaryKey); } ``` A function that takes `Osdk.Instance` accepts any `Employee` loaded with at least `fullName`. # Subscriptions Source: https://palantir.github.io/osdk-ts/sdk/subscriptions > Receive live updates when objects in an object set are added, changed, or removed, with subscribe, its four callbacks, and unsubscribe. Related Palantir Foundry documentation: - [Subscribe to Ontology changes](https://www.palantir.com/docs/foundry/ontology-sdk/typescript-subscriptions) `subscribe` opens a live connection to an object set. The server pushes each change to an object in the set, so you can keep a local copy current without polling. ```ts title="src/watchEngineers.ts" import { Employee } from "@my-app/sdk"; import { client } from "./client"; const subscription = client(Employee) .where({ department: "Engineering" }) .subscribe( { onChange(update) { console.log(update.state, update.object.$primaryKey, update.object.fullName); }, onSuccessfulSubscription() { console.log("Subscribed"); }, onOutOfDate() { console.log("Missed changes; reload the set"); }, onError({ subscriptionClosed, error }) { console.error("Subscription error", { subscriptionClosed, error }); }, }, { properties: ["fullName", "jobTitle"] }, ); subscription.unsubscribe(); ``` `subscribe` works on object type sets, filtered sets, set operations, and [interfaces](https://palantir.github.io/osdk-ts/sdk/interfaces.md). The server does not support subscriptions on link traversals (`pivotTo`, or a many-link `$link`) or on sets with `withProperties`. It returns immediately with `{ unsubscribe }`; the connection opens in the background. ## Callbacks All callbacks are optional. | Callback | Called when | | --- | --- | | `onSuccessfulSubscription()` | The server accepted the subscription. Changes from here on reach `onChange`. | | `onChange(update)` | An object in the set changed. See [Updates](#updates). | | `onOutOfDate()` | The client cannot account for every change, for example after the connection dropped and reconnected. Reload the whole set. | | `onError({ subscriptionClosed, error })` | Something failed. When `subscriptionClosed` is `true`, no more updates arrive. When it is `false`, the subscription continues. | An exception thrown inside `onChange` or another callback does not stop the subscription. The client reports it to `onError` with `subscriptionClosed: false`. If `onError` itself throws, the client closes the subscription. ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `properties` | `PropertyKeys[]` | Every property of the type | The properties to receive. `update.object` is typed to these. | | `includeRid` | `boolean` | `false` | Adds `$rid` to each updated object. Not available when `properties` includes a geotime series reference property. | Request only the properties you display. Without `properties`, each update can carry every property of the type. ## Updates `onChange` receives `{ object, state }`: | `state` | Meaning | | --- | --- | | `"ADDED_OR_UPDATED"` | The object was created, was edited, or now matches the set's filter. `object` has the latest values of the subscribed properties. | | `"REMOVED"` | The object was deleted, or no longer matches the filter. Drop it by `$primaryKey`. | Updates to a geotime series reference property arrive as separate updates that carry only the primary key and that property. Merge each update into your copy of the object rather than replacing it, so a property missing from an update keeps its last value. ## Keep a local copy current Load the set once the subscription is live, apply each change, and reload on `onOutOfDate`: ```ts title="src/liveRoster.ts" import { Employee } from "@my-app/sdk"; import type { Osdk } from "@osdk/client"; import { client } from "./client"; type Row = Osdk.Instance; const engineers = client(Employee).where({ department: "Engineering" }); const roster = new Map(); async function reload() { roster.clear(); for await (const employee of engineers.asyncIter({ $select: ["fullName", "jobTitle"] })) { roster.set(employee.$primaryKey, employee); } } const subscription = engineers.subscribe( { onSuccessfulSubscription() { void reload(); }, onOutOfDate() { void reload(); }, onChange({ object, state }) { if (state === "REMOVED") { roster.delete(object.$primaryKey); return; } const existing = roster.get(object.$primaryKey); roster.set(object.$primaryKey, existing == null ? object : existing.$clone(object)); }, onError({ subscriptionClosed, error }) { if (subscriptionClosed) { console.error("Roster is no longer live", error); } }, }, { properties: ["fullName", "jobTitle"] }, ); ``` Loading after `onSuccessfulSubscription`, not before, means a change made while the first load runs still reaches `onChange`. ## Connection All subscriptions from one client share a single WebSocket. When the connection drops, the client reconnects with exponential backoff, resubscribes, and calls `onOutOfDate` on each subscription it restored. In Node.js, the client uses the `ws` package, so no polyfill is needed. Call `unsubscribe` when you no longer need updates, such as when a component unmounts or a request handler finishes. An open subscription keeps the connection open. ## In React `useOsdkObjects` and `useObjectSet` accept `streamUpdates: true`, except together with `pivotTo` or `withProperties`, which subscribes for you and writes each change into the shared cache. See [Objects in React](https://palantir.github.io/osdk-ts/react/objects.md). # ActionForm Source: https://palantir.github.io/osdk-ts/components/action-form > ActionForm renders form fields from an OSDK action definition, validates input in the browser, and applies the action on submit. ## Import ```typescript import { ActionForm } from "@osdk/react-components/action-form"; import type { ActionFormContentItem, FormFieldDefinition, } from "@osdk/react-components/action-form"; ``` ## Basic Usage > [!NOTE] > `@my-app/sdk` is a placeholder for your generated SDK package. `./client` (used in scoped object-select examples below) is the file in your app where you exported the OSDK client returned by `createClient(...)`. Replace both with the actual paths in your project. ```tsx import { updateEmployee } from "@my-app/sdk"; import { ActionForm } from "@osdk/react-components/action-form"; function UpdateEmployeeForm() { return ; } ``` `ActionForm` fetches action metadata, renders fields for the action parameters, runs client-side validation, validates the action with Foundry, and calls the OSDK action when the user submits. The form title is hidden by default. Pass `showFormTitle={true}` to show it; the title uses `formTitle` when provided, otherwise the action display name, otherwise the action API name. ## Props Reference `ActionForm` is a discriminated union: provide both `formState` and `onFormStateChange` for controlled mode, or omit both for uncontrolled mode. Type parameters: `Q extends ActionDefinition` | Name | Type | Description | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `formTitle` | `string` | Title shown in the form header. Omit to hide the header. | | `isSubmitDisabled` | `boolean` | Whether the submit button is disabled. Default `false`. | | `actionDefinition` | `Q` | **Required.** The OSDK action definition. Its parameters drive the rendered fields and the submission. | | `showFormTitle` | `boolean` | Whether to show the form title. Defaults to `false`. | | `onSubmit` | `(formState: FormState, applyAction: (formState: FormState) => Promise) => Promise \| void` | If supplied, this will override the default submit action. By default, the action's applyAction will be called. | | `onValidationResponse` | `(results: ActionValidationResponse) => void` | Called with the validation response each time the form validates the action: 500 ms after a field change and before submit. Not called when `onSubmit` is provided. | | `onSuccess` | `(results: ActionEditResponse \| undefined) => void` | Called when the action is successfully executed from a non-validateOnly submission | | `onError` | `(error: FormError) => void` | Called when action metadata fails to load or form submission fails. | | `formFieldDefinitions` | `ReadonlyArray>` | Custom flat list of field definitions. | | `formContentDefinitions` | `ReadonlyArray>` | Ordered list of fields and sections that define the form layout. | | `formState` | `FormState` | The current form values. If provided, the form state is controlled. | | `onFormStateChange` | `(updater: (prevState: FormState) => FormState) => void` | Called when a field value changes, with a state updater. Required when the form state is controlled; also fires in uncontrolled mode so callers can observe changes. | ## Choosing ActionForm vs BaseForm | Use case | Use this API | | ------------------------------------------------------------------------ | ------------------------------------------ | | Render a form directly from an OSDK action and submit with `applyAction` | `ActionForm` | | Override generated fields for an OSDK action | `ActionForm` with `formFieldDefinitions` | | Build a form from manually-authored field definitions | `BaseForm` | | Group an OSDK action's fields into sections, or order standalone fields | `ActionForm` with `formContentDefinitions` | | Build a custom form layout without an OSDK action | `BaseForm` | ## Default Field Rendering When `formFieldDefinitions` is omitted, `ActionForm` derives one field per action parameter from action metadata. | Action parameter type | Default field component | Default behavior | | ---------------------------------------------- | ----------------------- | ---------------------------------------------- | | `string` | `TEXT_INPUT` | Single-line text input | | `boolean` | `RADIO_BUTTONS` | True/False radio options | | `integer`, `double`, `long` | `NUMBER_INPUT` | Numeric input | | `datetime`, `timestamp` | `DATETIME_PICKER` | Date picker | | `attachment`, `mediaReference` | `FILE_PICKER` | File picker | | `{ type: "object" }` | `OBJECT_SELECT` | Object selector for the referenced object type | | `{ type: "objectSet" }` | `OBJECT_SET` | Read-only object set summary | | `marking`, `geohash`, `geoshape`, `objectType` | `UNSUPPORTED` | Disabled field recommending a custom field | | `{ type: "interface" }`, `{ type: "struct" }` | `UNSUPPORTED` | Disabled field recommending a custom field | Required validation is inferred from the action parameter's nullability. Additional client-side validation comes from field-specific props such as `min`, `max`, `minLength`, `maxLength`, and `maxSize`. ## Unsupported Features `ActionForm` is a lightweight OSDK component and does not yet match the full ActionForm in Foundry. The table below lists the main gaps to account for when adopting it. | Feature | Current behavior | Workaround | | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Backend action validation | When `onSubmit` is omitted, the form validates the action with Foundry 500 ms after each field change and again before submit. If the result is `INVALID`, the action is not applied, and failed submission criteria and parameter errors are listed in the footer. Validation-derived displays, allowed values, defaults, and section results are not processed. With `onSubmit`, no backend validation runs. | Read the full response with `onValidationResponse`. Use `formFieldDefinitions` validation props, field-level `validate`, `onSubmit`, and `onError` for app-owned checks. | | Unsupported generated parameter types | `marking`, `geohash`, `geoshape`, `objectType`, `interface`, and `struct` render as disabled unsupported fields by default. | Override those parameters with `fieldComponent: "CUSTOM"` or another compatible component in `formFieldDefinitions`. | | Action-authored layout metadata | Action-defined sections, form content ordering, section validation, and layout toggles are not read from metadata. Fields render in metadata parameter order unless fully replaced by `formFieldDefinitions`. | Group fields with `formContentDefinitions` sections, or control field order with `formFieldDefinitions`. | | Conditional logic and dynamic display state | Backend-driven hidden, disabled, required, and allowed-value rules are not evaluated as the user edits the form. | Encode static display state in field definitions, or manage dynamic state in your app and pass updated `formFieldDefinitions` / controlled `formState`. | | Defaults and prefills | Backend prefills, type-class defaults, current timestamp defaults, and validation-derived default values are not applied automatically. | Provide `defaultValue` in field definitions, seed controlled `formState`, or compute defaults in app code before rendering. | ## Custom Field Definitions Use `formFieldDefinitions` when the default rendering for a parameter is not the UI you want. The list is a complete replacement: include every parameter that should appear in the form. ```tsx const fields = [ { fieldKey: "fullName", label: "Full name", fieldComponent: "TEXT_INPUT", fieldComponentProps: { placeholder: "Jane Doe", minLength: 2, }, }, { fieldKey: "yearsExperience", label: "Years of experience", fieldComponent: "NUMBER_INPUT", fieldComponentProps: { min: 0, max: 80, }, }, { fieldKey: "isRemote", label: "Remote employee", fieldComponent: "SWITCH", fieldComponentProps: {}, }, ] satisfies Array>; ; ``` ## Sections Use `formContentDefinitions` instead of `formFieldDefinitions` to group fields into sections. Each item is either `{ type: "field", definition }` or `{ type: "section", key, definition }`, and items render in array order. Like `formFieldDefinitions`, the list replaces the generated fields. ```tsx const content = [ { type: "field", definition: fields[0] }, { type: "section", key: "details", definition: { title: "Details", description: "Optional employment details", columnCount: 2, collapsedByDefault: true, fields: [fields[1], fields[2]], }, }, ] satisfies Array>; ; ``` | Section option | Default | Description | | -------------------- | ------- | -------------------------------------------------------------- | | `title` | | Section heading. | | `description` | | Text under the heading. | | `fields` | | The fields in the section. | | `collapsedByDefault` | `false` | Starts collapsed. | | `showTitleBar` | `true` | Shows the title bar. | | `columnCount` | `1` | `1` or `2` columns. | | `style` | `"box"` | `"box"` renders a bordered card, `"minimal"` only the heading. | ### Rich dropdown labels Use `itemToStringLabel` for the dropdown's text behavior: search matching, accessibility labels, fallback item keys, and default visual text. Add `renderItemLabel` when the visible label needs richer React content while preserving the same string behavior. ```tsx const fields = [ { fieldKey: "assigneeUserId", label: "Assignee", fieldComponent: "DROPDOWN", fieldComponentProps: { items: userIds, itemToStringLabel: (userId) => userNames[userId] ?? userId, renderItemLabel: (userId) => ( {userNames[userId] ?? userId} {userTeams[userId]} ), }, }, ] satisfies Array>; ``` ### Scoped object select fields `OBJECT_SELECT` can load options from either an object type or a pre-scoped object set. Pass `objectType` for an unfiltered selector, or pass `objectSet` to limit selectable options. The two are mutually exclusive. Search text is applied within the object set, and the current value is not automatically cleared when it is outside that set. ```tsx import { Employee, updateEmployee } from "@my-app/sdk"; import { useMemo } from "react"; import client from "./client"; function UpdateEmployeeForm() { const marketingEmployees = useMemo( () => client(Employee).where({ department: "Marketing" }), [], ); const fields = [ { fieldKey: "manager", label: "Marketing manager", fieldComponent: "OBJECT_SELECT", fieldComponentProps: { objectSet: marketingEmployees, placeholder: "Search Marketing employees…", }, }, ] satisfies Array>; return ( ); } ``` For a completely custom field, use `fieldComponent: "CUSTOM"` and provide `customRenderer`: ```tsx const fields = [ { fieldKey: "approvalReason", label: "Approval reason", fieldComponent: "CUSTOM", fieldComponentProps: { customRenderer: ({ value, onChange }) => (