@evopos/sdk
v0.5.0
Published
SDK for EvoPOS plugins: host handshake, host calls, events, windows, receipt interception; fake kassa for tests in @evopos/sdk/mock
Readme
@evopos/sdk
SDK for EvoPOS plugin authors. A plugin page runs inside a sandboxed iframe (sandbox="allow-scripts") that the
kassa or the back office embeds. The SDK performs the handshake with the host, then gives you typed calls, host
events, plugin windows and the receipt-close interception.
- No runtime dependencies in the main entry: it only needs
window,postMessageandMessageChannel. - A fake kassa for tests is a separate entry,
@evopos/sdk/mock. - Plugin docs: https://developers.evopos.az
Install
npm install @evopos/sdknpm install --save-dev @evopos/vite-plugin adds a fake kassa to your dev server (/__evopos/), manifest checks and
a multi-page build. It is optional.
Quick start
import { createPlugin } from '@evopos/sdk';
const plugin = createPlugin({ id: 'az.evopos.hello' }); // `id` from manifest.json
async function main(): Promise<void> {
// Handshake with the host. Resolves with the slot context: { slot, locale, receipt_uuid, ... }.
const context = await plugin.ready();
console.log(context.slot, context.locale);
// Host calls. The host checks the slot, the granted scopes and the arguments.
const receipt = await plugin.query.receipt();
await plugin.ui.toast(`Total: ${receipt.totals.total.amount}`, 'success');
// The same call without the wrapper:
await plugin.call('ui.toast', { message: 'Hello', kind: 'info' });
// Host events. on() subscribes on the first handler and unsubscribes when the last one is removed.
const off = plugin.on('receipt.changed', (payload) => {
console.log('receipt changed', payload);
});
off();
}
void main();A failed call rejects with PluginBridgeError; its code is one of the bridge codes (not_allowed,
scope_denied, invalid_args, timeout, host_error, window_limit, ...; the full list is ERROR_CODES).
Calls time out after 15 s, except those that wait for a person (ui.openModal, ui.confirm, ui.prompt,
ui.scanBarcode, ui.managerPin): they have no timeout.
on() does not throw when the subscription fails (no scope, the slot does not allow it): it prints one
console.warn('[evopos] ...').
Typed wrappers over call(): plugin.ui, plugin.query, plugin.receipt, plugin.device, plugin.http,
plugin.api, plugin.clients, plugin.command(name, payload). plugin.scopes() returns the granted scopes after
ready(); plugin.destroy() closes the channel.
Windows: ui.openModal and ui.close
import { createPlugin } from '@evopos/sdk';
const plugin = createPlugin({ id: 'az.evopos.tip' });
// On a slot page: open a window and wait until it is closed.
export async function askTip(): Promise<number | null> {
const r = await plugin.ui.openModal({
entry: 'modals/tip.html',
title: 'Tip',
size: 'sm', // 'sm' | 'md' | 'lg' | 'xl' | 'full'
height: 'auto', // 'auto' or a number of px
data: { total: 4499 },
actions: [{ id: 'apply', label: 'Apply', kind: 'primary' }],
});
// On older bridges (before 2026-11-21) the host answers at once with { opened: true }: check 'reason' in r.
if ('reason' in r && r.reason === 'done') {
return (r.result as { tip_percent: number }).tip_percent; // the value passed to ui.close({ result })
}
return null; // reason: 'dismissed' (cashier closed it) or 'host_closed'
}
// Inside modals/tip.html.
export async function windowSide(): Promise<void> {
await plugin.ready();
console.log(plugin.modal); // { id, data: { total: 4499 }, size: 'sm', height: 'auto' }; null on a slot page
plugin.ui.onAction(async (actionId) => {
if (actionId === 'apply') await plugin.ui.close({ result: { tip_percent: 10 } });
});
}ui.openModal resolves with { reason: 'done' | 'dismissed' | 'host_closed', result? }. ui.close({ result }),
ui.resize({ height }), ui.setActions(actions) and ui.onAction(cb) work only inside a window. With
height: 'auto' the SDK reports the page height itself (ui.resize, at most once per 50 ms). The kassa keeps at
most 4 windows open; one more is rejected with window_limit.
Closing a receipt: onBeforeClose
import { createPlugin } from '@evopos/sdk';
const plugin = createPlugin({ id: 'az.evopos.client-required' });
export async function guard(): Promise<() => void> {
// Blocking needs the receipts:write scope; without it the answer is ignored.
return plugin.onBeforeClose(async (receipt, { signal }) => {
if (receipt.client_id) return; // do not interfere
// A call that waits for a person holds the kassa automatically: 120 s instead of 3 s.
const r = await plugin.ui.openModal({ entry: 'modals/client.html', title: 'Client' });
if (signal.aborted) return; // the cashier chose "continue without the app"
if (!('reason' in r) || r.reason !== 'done') {
return { block: true, message: 'Choose a client first' };
}
});
}The handler receives the receipt and { hold, signal } and answers { block: true, message } or nothing. Without
hold the kassa waits 3 s and closes the receipt as usual; hold() extends this to 120 s and the SDK calls it
itself when a call that waits for a person is made while the interception is running. An error thrown in the
handler does not block the closing. signal aborts when the kassa cancels the interception; signal.reason is
skipped, timeout or superseded. On bridges older than 2026-11-21 hold() does nothing.
Testing with @evopos/sdk/mock
createMockHost is a fake kassa: the plugin is linked to it through a MessageChannel, so you need no iframe and
no DOM. It checks every call the way the kassa does (slot and host_calls of the manifest: not_allowed, scopes:
scope_denied, arguments: invalid_args) and, when you give no handler, answers with the example from
HOST_CALL_EXAMPLES. Pass manifest (your manifest.json, imported as it is): without it only the slot is checked,
and a call missing in host_calls passes the test but gets not_allowed in the real kassa.
import { expect, it } from 'vitest';
import { createMockHost } from '@evopos/sdk/mock';
import manifest from '../manifest.json';
it('asks for a client before the receipt is closed', async () => {
const host = createMockHost({
slot: 'receipt.actions',
manifest, // host_calls, scopes and slots of the plugin: checked as in the kassa
context: { receipt_uuid: '0198f1c2-7a3b-7c11-9d4e-2b1a6f0c5e01' },
handlers: { 'ui.confirm': () => ({ confirmed: true }) }, // your own answer to a host call
});
const plugin = host.connect(); // an SDK plugin wired to the fake kassa
await plugin.onBeforeClose(async () => {
const r = await plugin.ui.openModal({ entry: 'modals/client.html' });
if (!('reason' in r) || r.reason !== 'done') return { block: true, message: 'Choose a client' };
});
const verdict = host.beforeClose(); // run the interception
await new Promise((r) => setTimeout(r, 20));
expect(host.modals).toHaveLength(1); // the window is open and the kassa is held
await host.dismiss(host.modals[0]!.id); // the cashier closed the window
expect(await verdict).toMatchObject({ block: true, message: 'Choose a client', held: true });
await host.emit('receipt.closed'); // the payload defaults to HOST_EVENT_EXAMPLES
expect(host.calls.map((c) => c.call)).toContain('events.subscribe'); // journal of calls
host.destroy();
});createMockHost({ slot, manifest?, scopes?, context?, handlers?, bridgeVersion?, beforeClose? }).slotis a name from the slot catalog; an unknown one throws.manifestis{ host_calls?, scopes?, slots? }(a wholemanifest.jsonfits): a call outsidehost_callsgetsnot_allowed(a window's ownui.close,ui.resize,ui.set_actionsand subscriptions to its ownui.*events need no entry, as in the kassa);scopesdefault tomanifest.scopes, and an explicitscopesalways wins, so a test can revoke a right; aslotthat is not inmanifest.slotsthrows.beforeClose: { answerTimeoutMs?, holdMaxMs? }shortens the 3 s and 120 s limits so a test can check a timeout.host.connect({ id?, bridgeVersion?, callTimeoutMs? })returns an SDK plugin for the slot;host.connectWindow(modalId)returns a plugin inside an open window (plugin.modalis filled).host.emit(name, payload?)sends a host event to subscribers and resolves when it is delivered.host.beforeClose(receipt?)runs the interception and resolves with{ block, message?, held, timedOut, skipped }(the first block wins; no answer in time means the closing goes on). The promise also has.skip(): "continue without the app". It settles even if a plugin that held the kassa goes away (page reload,detach(),destroy()): the closing goes on andheldstaystrue.host.modalslists open windows ({ id, entry, title, size, height, data, dismissible, actions }).host.closeModal(id, { result })closes one asui.close({ result })would (reason: 'done'),host.dismiss(id)is the cashier closing it ('dismissed'),host.hostClose(id)is the kassa closing it ('host_closed'),host.pressAction(id, actionId)presses a footer button.host.callsis the journal of plugin calls:{ call, args, pending, ok, result | error }.- Your own answers to host calls go into the
handlersoption;host.handle(call, fn)adds or replaces one later. A handler returns the result or throws:PluginBridgeErroranswers with its code, any other error answershost_error. host.onChange(listener)notifies about windows,callsand resizes;host.destroy()closes everything.
A real iframe: host.attachFrame
attachFrame links the fake kassa to a real iframe (this is what @evopos/vite-plugin does on /__evopos/):
the same checks, but the channel opens on the evopos:hello of the iframe, and again after it reloads.
import { createMockHost } from '@evopos/sdk/mock';
import manifest from './manifest.json';
const host = createMockHost({ slot: 'receipt.actions', manifest });
const frame = document.createElement('iframe');
frame.setAttribute('sandbox', 'allow-scripts'); // as in the kassa
document.body.append(frame);
// Attach first, set src afterwards: the plugin says hello as soon as its script runs.
const detach = host.attachFrame(frame.contentWindow!);
frame.src = 'http://localhost:5173/index.html';
// later
detach();sandbox="allow-scripts"gives the page an opaque origin (null), so a browser loads its module scripts only if the server answers withAccess-Control-Allow-Origin: null.@evopos/vite-plugindoes this for you; with another server, set the header yourself.- Only messages whose
event.sourceis that iframe are accepted. A new hello from the same iframe closes the previous channel and opens a new one. - Options:
{ modalId?, expectId?, listenOn? }.modalIdbinds the iframe to an open window;expectIdaccepts hello only with thatplugin_id;listenOnis where to listen formessage(defaultglobalThis).
Receipt images
htmlToImage(html, { width, height, background }) renders HTML into a base64 PNG (without a prefix) through an SVG
foreignObject, an Image and a <canvas>. Only inline styles and data: images work; the height follows the
content (up to 1200 px). canvasToImage(canvas) converts a canvas, imageLine(base64, { align }) makes the
{ type: 'image', data, align } line for plugin.receipt.addExtension. Beyond 576x1200 px or 65 536 base64
characters it throws PluginImageError (code: 'too_large').
Links
- SDK reference: https://developers.evopos.az/plugins/sdk/
- Testing plugins: https://developers.evopos.az/guides/plugin-tests/
- Plugin windows: https://developers.evopos.az/guides/plugin-windows/
MIT
