# Runtime API (pos)

> Applies to `api_version: "2026-01"`.

Every extension gets a `pos` object to read context, call the Open API and send commands to the POS UI.

- **Extensions in the worker** (blocks, actions, hooks, Worker UI pages): `pos` is a global preloaded by the POS runtime before the module runs.
- **Iframe pages**: `<PosProvider>` from `@pancake-pos/ui` (or `connect()` from the SDK) gives the page its `pos` (see [Iframe pages](#iframe-pages)).

Full types ship in `@pancake-pos/ui-extensions` (see [SDK & CLI](/developers/apps/en/sdk)).

## Overview

```ts
interface Pos {
  apiVersion: string;                 // for example "2026-01"
  target: string;                     // the running extension's target
  extensionId: string;                // the id declared in the manifest
  app: { id: string; handle: string; version: string };
  shop: { id: number; name: string; currency: string; country: string; timezone: string };
  user: { id: string; name: string; locale: string };
  data: unknown;                      // context data, schema depends on the target

  api: PosApi;                        // Open API calls
  format: PosFormat;                  // numbers, money and dates formatted like POS screens
  session: { getToken(): Promise<{ token: string; expiresAt: string }> };

  toast: { show(message: string, options?: ToastOptions): void };
  ui: {
    confirm(options: ConfirmOptions): Promise<boolean>;
    modal<T>(options: OverlayOptions): Promise<T | null>;    // an iframe page of the app in a POS modal
    drawer<T>(options: OverlayOptions): Promise<T | null>;
  };
  download(file: DownloadFile): Promise<void>;
  clipboard: { copy(text: string): Promise<void> };
  navigate(to: NavigateTarget): void;
  refresh(): void;
  close(result?: unknown): void;

  on(event: PosEvent, handler: (payload: any) => void): () => void;
}
```

### Availability

| API | Block | Headless action | Modal/fullscreen action | Hook, should_render | Page |
|---|---|---|---|---|---|
| `shop`, `user`, `app`, `data` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `api`, `session`, `format` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `toast`, `ui.confirm`, `download`, `clipboard` | ✓ | ✓ | ✓ | | ✓ |
| `ui.modal`, `ui.drawer` | ✓ | ✓ | ✓ | | ✓ ¹ |
| `navigate` | ✓ | ✓ | ✓ | | ✓ |
| `refresh` | ✓ | ✓ | ✓ | | |
| `close` | | | ✓ | | ² |
| `on('data-change')` | ✓ | | ✓ | | ✓ |
| `page.setTitle`, `page.setPrimaryAction`, `on('primary-action')` | | | | | ✓ ¹ |
| `page.setHeader`, `page.setFrame`, `page.setBackdrop`, `on('header-action')`, `on('backdrop-dismiss')` | | | | | iframe ¹ |

¹ Except a page shown in a `pos.ui.modal`/`drawer` (one level, no POS title row).
² Only an iframe page shown in a `pos.ui.modal`/`drawer`.

Calling an API outside its availability throws `PosRuntimeError` with `code: 'unavailable'`.

## pos.data

The context data of the current target, also passed to the `export default` function. See each target's schema in [Extension points](/developers/apps/en/targets).

- Targets on POS records share one shape: `pos.data.resource` names the resource (`order`, `purchase`…), `pos.data.record` is the saved record (`records` in the bulk action bar) and `pos.data.draft` is the detail form content.
- Fields hidden by `access.hidden_order_fields` are not present in `pos.data`.
- For blocks, `pos.data` updates as the user edits the form; listen to `data-change` to re-render.

## pos.api

Calls the Open API with the app token. The SDK attaches the token, renews it and retries once when it expires.

```ts
interface PosApi {
  baseUrl: string;   // Open API root, for example "https://pos.pages.fm/api/v1"
  request<T = any>(options: {
    method: 'GET' | 'POST' | 'PUT' | 'DELETE';
    path: string;                          // relative to baseUrl: /shops/{shop_id}/... or /geo/...
    query?: Record<string, unknown>;
    body?: unknown;                        // sent as JSON
    signal?: AbortSignal;
  }): Promise<T>;
  get<T = any>(path: string, options?: { query?: Record<string, unknown>; signal?: AbortSignal; cache?: number }): Promise<T>;
  paginate<T = any>(path: string, options?: PaginateOptions): Promise<{ items: T[]; total: number | null; truncated: boolean }>;
  post<T = any>(path: string, body?: unknown, options?: { query?: Record<string, unknown>; signal?: AbortSignal }): Promise<T>;
  put<T = any>(path: string, body?: unknown, options?: { query?: Record<string, unknown>; signal?: AbortSignal }): Promise<T>;
  delete<T = any>(path: string, options?: { query?: Record<string, unknown>; signal?: AbortSignal }): Promise<T>;
}
```

- `path` must belong to the current shop (`/shops/${pos.shop.id}/...`). Calls to other shops are rejected. The only exception is the address catalog: `/geo/provinces`, `/geo/districts`, `/geo/communes`.
- The result is the raw Open API JSON (usually `{ success, data, ... }`).
- The method must be listed in the app's `access.methods`; otherwise an error is thrown before the request is sent.

### Caching catalogs

`get(path, { cache: seconds })` keeps the result in the extension's memory (up to 3600 seconds), for catalogs that rarely change: carriers (`/partners`), warehouses, tags, provinces (`/geo/provinces`). Later calls with the same `path` and `query` send no request; each call gets its own copy, so changing a result does not affect the next one. A successful write (`POST`, `PUT`, `DELETE`) clears the whole cache.

```ts
const { data: partners } = await pos.api.get(`/shops/${pos.shop.id}/partners`, { cache: 600 });
```

### Loading many pages

`paginate` loads an Open API list over several pages, a few at a time, within the [rate limit](/developers/apps/en/data-access#rate-limits). On `429` it waits and retries (up to 3 times).

```ts
type PaginateOptions = {
  query?: Record<string, unknown>;     // the endpoint's filters; add fields[] to fetch only what you need
  pageSize?: number;                   // 100 by default, at most 200
  maxItems?: number;                   // 2,000 by default, at most 20,000
  concurrency?: number;                // pages loaded at once, 3 by default, at most 5
  pageParam?: 'page_number' | 'page';  // both are sent by default (Open API endpoints use one or the other)
  signal?: AbortSignal;                // cancel when the user changes the filters
  onProgress?: (progress: { loaded: number; total: number | null }) => void;
};

const controller = new AbortController();
const { items, total, truncated } = await pos.api.paginate(`/shops/${pos.shop.id}/orders`, {
  query: { startDateTime, endDateTime },
  maxItems: 5000,
  signal: controller.signal,
  onProgress: ({ loaded, total }) => setProgress(total ? (loaded / total) * 100 : 0),
});
```

- The endpoint must return `{ data: [...] }`. With `total_entries` or `total_pages` the remaining pages load in parallel; without them pages load one by one until a short page.
- `truncated: true` means records remain after `maxItems`: ask the user to narrow the filters.
- Reports over long periods stay slow because every record is downloaded; default to a short period (7 days) and show progress with `pos-progress`.

### Errors

```ts
class PosApiError extends Error {
  status: number;            // HTTP status
  code?: number | string;    // Open API error_code when present
  body?: unknown;            // response body
}
```

The SDK throws `PosApiError` when the HTTP status is ≥ 400 **or** the body has `success: false`. See the error codes in [Data access › Error codes](/developers/apps/en/data-access#error-codes).

```ts
try {
  const { record } = pos.data;   // order.details.action: record is an OrderRef
  const res = await pos.api.get(`/shops/${pos.shop.id}/orders/${record.system_id}`);
  render(<OrderInfo order={res.data} />, document.body);
} catch (error) {
  if (error.status === 403) pos.toast.show('You do not have permission to view this order', { tone: 'error' });
  else throw error;
}
```

## pos.session.getToken

Gets the current app token to call the Open API with another library.

```ts
const { token, expiresAt } = await pos.session.getToken();
await fetch(`${pos.api.baseUrl}/shops/${pos.shop.id}/orders`, {
  headers: { Authorization: `Bearer ${token}` },
});
```

Do not store the token long term or send it to external systems, except to the backend of a [self-hosted page](#self-hosted-pages). Tokens expire after 15 minutes; call `getToken()` again for a new one.

## pos.toast.show

```ts
type ToastOptions = {
  tone?: 'success' | 'error' | 'info' | 'warning';   // default 'success'
  duration?: number;                                  // seconds, default 3, from 1 to 10
};
```

At most 3 toasts per 10 seconds per extension; extra toasts are dropped.

## pos.ui.confirm

A confirmation dialog drawn by POS over the whole screen.

```ts
type ConfirmOptions = {
  title: string;
  content?: string;
  okText?: string;       // defaults to the POS "OK" label
  cancelText?: string;   // defaults to the POS "Cancel" label
  danger?: boolean;      // red confirm button
};

if (await pos.ui.confirm({ title: 'Push this order to the ERP?' })) {
  // ...
}
```

## pos.ui.modal, pos.ui.drawer

Opens an iframe page of the app (an `app.page` with `render: "iframe"`) in a POS modal or drawer over the whole POS screen. Use it for complex screens opened from a block, an action or a page: picking products, editing delivery details, viewing a record.

```ts
type OverlayOptions = {
  page?: string;                    // id of an app.page with render "iframe"; defaults to the first iframe page
  path?: string;                    // path inside the page, "/" by default
  query?: Record<string, string>;
  title?: string;                   // modal title; POS adds the app name
  width?: 'small' | 'medium' | 'large';   // modal 520/720/1000 px (small by default), drawer 400/560/800 px (medium by default)
};

const picked = await pos.ui.drawer<{ id: number }>({ path: '/pick-product', title: 'Pick a product', width: 'large' });
if (picked) addProduct(picked.id);
```

- The page inside knows it is in a modal through `pos.data.presentation` (`'modal'` or `'drawer'`) and closes with a result through `pos.close(result)` (up to 256 KB). When the user clicks ×, the result is `null`.
- A modal is as tall as the page content (`PosProvider` reports the height), up to the screen height; the rest scrolls inside the iframe. A drawer is full height.
- One level: a page in a modal/drawer cannot open another one and has no `pos.page.*`. Moving to another POS page closes the modal.
- Not available in hooks and `should_render`. Bad arguments (a path not starting with `/`, an unknown `width`) throw `invalid_argument`; an app without any iframe page gets `failed`; an app that already has a modal/drawer open gets `busy` (one modal per app at a time).
- A headless action waiting on a modal does not count toward its 30-second run limit.

## pos.download

Downloads a file to the user's computer. Code in the worker cannot create download links, so POS downloads it for the app; iframe pages can call it the same way. Two ways:

- **Table (`sheet`)**: the app passes columns and rows, POS builds an `.xlsx` or `.csv` file. Numbers, money, percentages and dates are formatted like POS screens, and the header row follows POS Excel exports. No Excel library needed.
- **Content (`content`)**: the app builds the file itself (text or bytes).

```ts
type SheetColumn = {
  key: string;            // field of the row, may be a path such as customer.name
  title: string;
  format?: 'text' | 'number' | 'money' | 'percent' | 'date' | 'datetime' | 'badge' | 'link';  // badge and link export as text
};

type DownloadFile =
  | { filename: string; sheet: { name?: string; columns: SheetColumn[]; rows: object[] } }   // .xlsx, .csv
  | { filename: string; content: string | ArrayBuffer | ArrayBufferView; type?: string };   // .csv, .xlsx, .json, .txt, .pdf

// Reuse the pos-table columns and the Open API records as shown.
await pos.download({ filename: 'orders.xlsx', sheet: { name: 'Orders', columns, rows: orders } });

const csv = ['Order,Customer,Total', ...rows.map((r) => [r.id, r.name, r.total].join(','))].join('\n');
await pos.download({ filename: 'orders.csv', content: csv });
```

- `sheet`: up to 50 columns and 20,000 rows. Object or array values leave the cell empty; text starting with `=`, `+`, `-` or `@` is written as text, never as a formula.
- Up to 10 MB per file. Other types, larger files or a malformed `content` or `sheet` throw `PosRuntimeError` with `code: 'invalid_download'`.
- CSV files get a UTF-8 BOM so Excel reads Vietnamese correctly.
- Not available in hooks and `should_render`.

## pos.clipboard.copy

Copies text (tracking codes, order codes, links) to the user's clipboard. The worker cannot reach the clipboard, so POS copies it and shows "Copied."; the app does not need its own message.

```ts
await pos.clipboard.copy(order.partner.extend_code);
```

- Up to 10,000 characters. Throws when the browser refuses (for example when the page is not focused).
- To copy a table cell, set `copyable: true` on the [`pos-table`](/developers/apps/en/components#pos-table) column instead.

## pos.navigate

Navigates to one of the app's pages, or opens a POS record.

```ts
type NavigateTarget =
  | { page: string; path?: string; query?: Record<string, string> }   // page: id of an app.page extension
  | { resource: 'order'; id: number | string };                       // id: the order's system_id

pos.navigate({ page: 'home', path: '/returns', query: { order_id: String(pos.data.record.system_id) } });
pos.navigate({ resource: 'order', id: order.system_id });
```

- `resource` opens the record in POS in a **new tab**, so the app's report or list page keeps its filters and position. Orders (`order`) are supported; `id` is the id used in the Open API path (`system_id`).

When called from a modal, the modal closes before navigating. If that page is already open, POS only updates the URL and emits `data-change` with the new `path` and `query`; the page is not reloaded.

## pos.format

Formats values like POS screens for text the app builds itself (headings, descriptions, printouts). Table columns, `pos-stat` and `pos-money` are already formatted by POS from their `format`.

```ts
interface PosFormat {
  number(value: number, digits?: number): string;      // user's language, up to 2 decimals: 1,234.5
  percent(value: number, digits?: number): string;     // 12.5 → "12.5%"
  money(value: number): string;                        // shop currency: "916.460 ₫", "$ 12,345.67"
  date(value: string | number | Date): string;         // "01/10/2026"
  datetime(value: string | number | Date): string;     // "01/10/2026 08:05", user's local time
}

pos.toast.show(`Reconciled ${pos.format.number(count)} orders, ${pos.format.money(diff)} off`);
```

- `money` takes the value as the Open API returns it and follows POS currency rules (symbol, decimal mark; currencies with cents such as USD and the `VND100`, `PHP100` codes are stored in hundredths).
- `pos.shop.currency` can be `VND100` or `PHP100`: POS-internal codes for dong and peso kept to 2 decimals, not ISO 4217. When you need the ISO code (external services), drop the `100` suffix and divide amounts by 100.
- `date` takes `YYYY-MM-DD` (a calendar day, no time zone shift), an ISO string, milliseconds or a `Date`. Invalid values return `''`.

## pos.refresh

Asks POS to reload the data of the current screen (for example the open order or purchase) after the app updated it through the Open API.

- POS reloads the list on screen and the open record. Unsaved changes in that record's form are replaced by the new data.
- Repeated calls are merged: each resource reloads at most once every 3 seconds.

## pos.close

Closes the open modal/fullscreen action. An iframe page shown in a [`pos.ui.modal`](#pos-ui-modal-pos-ui-drawer) modal or drawer passes a result back to its opener: `pos.close({ id: 5 })`.

## Events

```ts
const off = pos.on('data-change', (data) => {
  // data has the same schema as pos.data
});
off(); // unsubscribe
```

| Event | Fires when | Payload |
|---|---|---|
| `data-change` | Context data changes, for example the user edits a detail form (batched over 300 ms) or a page's path changes | the new `pos.data` |
| `primary-action` | The user clicks the page's primary button (iframe or Worker UI) | none |
| `header-action` | The user clicks a button an iframe page set with `pos.page.setHeader` | `{ id, item? }` (`item`: the chosen entry of a menu button) |
| `backdrop-dismiss` | The user clicks the dimmed POS area or presses Esc while an iframe page has `pos.page.setBackdrop` on | `{ via: 'click' \| 'escape' }` |

## Worker UI pages

A `render: "worker"` page runs in a worker like a block: it uses the global `pos` and `pos-*` elements (see [Components › Worker UI pages](/developers/apps/en/components#worker-ui-pages)). `pos.page` is available on Worker UI pages as on iframe pages:

```ts
pos.page.setTitle('Reconciliation 12/05');
pos.page.setPrimaryAction({ label: 'Export Excel', loading: false });
pos.on('primary-action', exportExcel);
```

A `pos-page` `heading`, when set, replaces the `setTitle` title on the title row; `setTitle` still sets the browser tab title.

In TypeScript `pos.page` is optional because only pages have it; in a page module use `pos.page!` or `(pos as PosPage).page`.

## Iframe pages

A `render: "iframe"` page is a regular web app served from the root of the app's sandbox domain. Every path that is not a static file returns `index.html`, so routers use `/` as their `basename`. Paths starting with `/_pos/` are reserved for POS: do not use them as routes or file paths.

The recommended way is [`@pancake-pos/ui`](/developers/apps/en/page-ui): `<PosProvider>` connects to POS and applies the theme, font and frame, then `usePos()` returns `pos`. Without React, call `connect()`:

```ts
import { connect } from '@pancake-pos/ui-extensions/page';

const pos = await connect();   // waits for POS to send context and token
// pos.data: { path, query, presentation? }
```

On top of the APIs above, iframe pages get:

```ts
interface PosPage {
  setTitle(title: string): void;
  setPrimaryAction(action: { label: string; disabled?: boolean; loading?: boolean } | null): void;
  setHeader(header: { heading?: string; description?: string; actions?: HeaderAction[] } | null): Promise<boolean>;
  setFrame(frame: { background: 'none' | 'card' }): Promise<boolean>;   // false: POS does not support it yet
  setBackdrop(on: boolean): Promise<boolean>;
}

type HeaderAction = {
  id: string;
  label?: string;                 // up to 40 characters; a button needs a label or an icon
  icon?: string;                  // same icons as pos-button
  variant?: 'primary' | 'secondary' | 'tertiary' | 'danger';
  tooltip?: string;
  disabled?: boolean;
  loading?: boolean;
  items?: { id: string; label: string; danger?: boolean; disabled?: boolean }[];   // with items: a menu button
};

pos.page.setHeader({ heading: 'Debts', description: 'By customer', actions: [{ id: 'export', label: 'Export', icon: 'download' }] });
pos.on('header-action', ({ id, item }) => id === 'export' && exportExcel());
pos.page.setFrame({ background: 'none' });
```

- **Title row:** `setHeader` sets the heading, description and up to 5 buttons on the POS title row (next to the `setPrimaryAction` button), drawn like `pos-page` buttons. Clicking a button fires `header-action`. `heading` wins over `setTitle`; `null` restores the default title. Buttons with neither `label` nor `icon`, or with a duplicate `id`, are dropped. It returns `false` when the POS version does not support it yet: the page then draws its own title (`PosProvider` does this for you). `PosPage` from `@pancake-pos/ui` calls `setHeader` for you with `heading`, `description` and the buttons in `actions`.
- **Frame:** by default the page sits in a white rounded card. `setFrame({ background: 'none' })` removes the card so the page draws on the gray POS background like a Worker UI page (`PosProvider` calls it; `<PosProvider frame="card">` keeps the card).
- **Backdrop:** a modal or drawer drawn in the page only covers the iframe. Call `setBackdrop(true)` when it opens and `setBackdrop(false)` when it closes: POS dims everything around the iframe (title row, menu, top bar), and clicking the dimmed area or pressing Esc fires `backdrop-dismiss` so the page closes the top-most one. If the page keeps the backdrop on after the first click, the second click makes POS remove it. `PosModal`, `PosDrawer` and `usePosBackdrop` from `@pancake-pos/ui` call it for you. It returns `false` when the POS version does not support it yet.
- **URL sync:** the SDK watches `history.pushState`, `replaceState` and `popstate` inside the iframe and updates the POS URL. When a shared link is opened, the iframe loads the matching path.
- **Height:** the iframe fills the POS content area; the page scrolls internally. In a `pos.ui.modal` modal, the modal follows the page height.
- **Modals and drawers:** a page opened with [`pos.ui.modal`/`drawer`](#pos-ui-modal-pos-ui-drawer) gets `pos.data.presentation` and closes with `pos.close(result)`.
- **Look and feel:** use [`@pancake-pos/ui`](/developers/apps/en/page-ui): components with the names and properties of the `pos-*` elements, plus the POS theme, font and tokens. `pos-app check` warns about other UI libraries, colors outside the POS palette and hand-formatted money.
- **Storage:** the iframe page's `localStorage` belongs to the app's sandbox domain only and is not shared with POS or other apps.

### Self-hosted pages

Declare `url` instead of `entry` when the page already runs on your own server, such as an existing ERP web app. POS embeds `url` directly in the iframe; the bundle does not need a `page/` folder.

```json
{ "target": "app.page", "id": "home", "title": "ERP", "render": "iframe", "url": "https://erp.example.com/pos" }
```

- **Connecting:** install `@pancake-pos/ui` (`<PosProvider>`) or `@pancake-pos/ui-extensions` (`connect()`) as a bundled page does; `pos.page`, `pos.api`, `pos.toast` and the rest work the same way.
- **Opening it outside POS:** `<PosProvider standalone>` still renders the page when it is opened directly in a browser (no POS) and `usePosOptional()` returns `null`; without React, `connect({ optional: true })` returns `null` instead of failing and `isEmbedded()` tells whether the page sits inside another window.
- **Paths:** the path part of `url` is the app root. `/shop/<id>/apps/<handle>/orders/5` in POS maps to `https://erp.example.com/pos/orders/5`. When the page leaves that root (for example `/login`), the POS URL stays as it is. `pos.data.path` is the page's real path.
- **Allowing POS to embed it:** send `Content-Security-Policy: frame-ancestors https://pos.pancake.vn https://pos.pages.fm` so only POS can embed the page. Do not rely on the page's own sign-in cookies: browsers may block cookies in cross-site iframes (Safari does by default).
- **Calling the API from your server:** send the app token (`pos.session.getToken()`) with requests to your backend, and have the backend call the Open API with it (`Authorization: Bearer`). The token lasts 15 minutes and carries only the app's access; do not store it long term.
- **Review and changes:** admins see `url` when they activate a version. Your server decides what the page shows and can change it at any time without a new version, so only use servers you control.
- **Trying it out:** `pos-app dev --page-url http://localhost:3000/pos` replaces `url` with a server on your machine; Vite or Next hot reload keeps working inside the iframe.

## Worker environment

Extensions in the worker can only rely on:

- Standard JavaScript syntax and built-ins (ES2020).
- `fetch`, `Headers`, `Request`, `Response`, `AbortController`, `URL`, `URLSearchParams`.
- `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`.
- `console` (only visible in development mode).
- The minimal DOM provided by the POS runtime so Preact or plain JS can build `pos-*` elements: `document.createElement`, `document.createTextNode`, `append`, `appendChild`, `insertBefore`, `removeChild`, `remove`, `setAttribute`, `removeAttribute`, `textContent`, `addEventListener`, `removeEventListener`, `parentNode`, `childNodes`, `firstChild`, `nextSibling`, `CustomEvent`. `document.body` is the root of the extension's UI.

**Do not** use `window`, `document.querySelector`, `localStorage`, `sessionStorage`, `canvas`, DOM measurement (`getBoundingClientRect`…), `alert`/`confirm`/`prompt`, or load scripts from CDNs. These may not exist or may be locked down at any time.

## Error log

- Development mode: errors and `console.*` show up in the browser DevTools; POS errors and warnings are available through the `get_errors` tool of the [MCP](/developers/apps/en/ai-guide#mcp). POS also checks the running screen against [Standard screens](/developers/apps/en/components#standard-screens) and records `standard_screen` warnings (emoji in labels, sections holding only a number, tables with too many columns…), including dynamic data that `pos-app check` cannot see.
- A property with the wrong type or an element in the wrong place **does not stop the extension**: POS drops that property (the default applies) or does not draw that element, and records an `invalid_prop`, `invalid_child` or `invalid_slot` warning. Numbers are turned into strings where a string is expected (for example `selected` of `pos-tabs`); `null` or `''` count as not set.
- Active version: uncaught errors, render errors and timeouts are recorded in the app's error log, visible in the [error log](/developers/apps/en/manage-apps#error-log) on the custom apps page.
