Theme Contract

The theme contract is the host-owned definition of everything a theme can plug into: view ids, part areas, section types, the manifest, the table view models and intents, the DOM contract, the token names, the merge-tag dictionary, the SDK surface and the validator. It lives in the Poker Engine source and can be exported as a snapshot. This page covers the contract as code; the other Theme Development pages cover how to write a theme against it.

Vocabulary follows the Theme Development vocabulary: a theme fills a host-named part area with a part; screens are view ids; operators compose pages from sections; table renderers are layouts; the built-in layout is standard.

Where it lives

PathContents
packages/shared/src/themes/Type-only half, shared by server, client and the export: ids.ts (view, part, section, menu and token ids), manifest.ts (ThemeManifest), table.ts (TableView, ControlsView, ChatView, TournamentView, TableIntent, timing and cues), sections.ts (settings fields and section schemas), sdk.ts (ThemeSdk, ThemeDefinition), tags.ts, dom-contract.ts, validation.ts. contract.typecheck.ts is a compile-time test. Re-exported from @poker/shared as types only.
src/themes/Runtime half, compiled with the server: contract-version.ts (THEME_CONTRACT_VERSION, range matching), ids.ts (the lists, viewIdFallbackChain, tableViewId), manifest.schema.ts (zod schema, parseThemeManifest, manifestJsonSchema), sections.ts (host section schemas), tokens.ts, tags.ts (dictionary, parseMergeTags, checkMergeTags), merge-tag-fields.ts (the section settings that accept merge tags, sent to the client in the theme configuration), dom-contract.ts, sdk-surface.ts (SDK_EXPORTS, externals, host object keys), validator/.
src/themes/validator/validateThemePackage(files); package.ts (in-memory and directory packages, layout and size rules), css.ts, js-scanner.ts, data.ts (tokens and strings), rules.ts (the rule table and limits), gameplay-markers.ts, corpus.ts.
scripts/themes/export-contract.mjsnpm run themes:export-contract -- --out <dir> [--fixtures] writes the snapshot.

The server imports @poker/shared as types only; every list the validator needs at runtime is in src/themes/, and satisfies checks plus the tests beside the files keep the two halves in step. Bump THEME_CONTRACT_VERSION whenever a built theme could notice a change; theme.json pins the version it was built against in engines.contract (^x.y.z, ~x.y.z or exact). An additive change a theme built against the older version can ignore (a new field on a view model, a new optional DOM node) moves the patch, so ^0.1.0 themes keep installing: 0.1.1 added TableView.odds and win-odds; 0.1.2 added five plugin slots (below); 0.1.3 added extensible sign-in (below). 0.2.0 is a minor bump for a new capability set (plugin data, plugin page views, the table additions), but it only adds: the host still implements all of 0.1.3, so THEME_CONTRACT_COMPATIBLE_VERSIONS (['0.1.3']) lists it and a range is accepted when it matches the running version or one of those (contractRangeAccepted). A ^0.1.0 or ^0.1.3 theme keeps installing and loading on a 0.2.0 host; a theme that uses a 0.2.0 addition declares ^0.2.0. A breaking change empties the list. A certification record made at another contract version drops the verified badge, not the table: the layout stays mountable. The client loader checks a theme’s range against its own copy of the number and the list (HOST_CONTRACT_VERSION and HOST_CONTRACT_COMPATIBLE_VERSIONS in client/src/core/theme/runtime/contract.ts); tests/themes/contract-version-sync.test.ts keeps the two equal.

Contract changelog

VersionChangeWhat a theme must do
0.2.17A layout’s own notices kept clear of the seats: a node of a table layout marked data-pe-place="clear" (a refused action’s toast, a short notice) is left where the layout draws it when that spot covers no seat, and otherwise moved by the host (its position only: position: fixed, wrapped narrower where that helps) to the nearest spot clear of every seat, by the rule the host’s own passing overlays use (the rabbit-hunt reveal, the discard picker, the opened game information): never over the player’s own seat and cards, the board, the pot or the controls while any other spot exists, an open seat before another player’s. Additive: 0.2.16 is listed as compatible.Nothing. A layout may mark a passing notice data-pe-place="clear"; an older host ignores the attribute, so the layout may keep its declared range. Felthouse, Neo and Wildcard UI mark their refusal and keep declaring ^0.2.11.
0.2.16Refused actions: TableView.refusal (optional) is { id, message, intent } when the server refused something the viewer just did at the table (a betting action, the time bank, adding chips, a tournament rebuy, add-on or re-entry): message is already worded for the player (the server’s reason, such as the rate limit’s "Too many actions at once…" or a raise below the minimum, or the host’s words where the server gives none), intent the intent it answers, and id changes with every refusal so the same message twice shows twice. The host clears it after six seconds and when the next action is accepted; a spectator never has one. A refused sit-down or leave stays in notice. Post now or wait for the big blind: ControlsView.sitInChoice (optional) is { postsMissedSmallBlind } while the viewer sits out at a cash table, owes missed blinds and the table lets them post those now; null when sitting in asks nothing. sit-in takes an optional missedBlinds: 'post' | 'wait' with the answer (refused with unknown-intent for any other value; ignored when the question does not apply). Third board: TableView.thirdBoard (optional), like secondBoard: the third board of a hand run three times, as dealt so far; the host draws it over a layout with no data-pe="board-3" node. Additive: 0.2.15 is listed as compatible.A layout should show refusal.message (as an alert, role="alert") whenever its id changes; without it a refused raise or a rate-limited action leaves the player with no answer. A layout that draws its own sit-in button should, when sitInChoice is set, ask before it sits in, as the standard controls do: "You missed blinds" (game.missedBlinds.title), the explanation (game.missedBlinds.body), Post missed blinds (game.missedBlinds.post, sends missedBlinds: 'post'), Wait for big blind (game.missedBlinds.wait, sends 'wait') and Cancel. A layout that draws its own second board (data-pe="board-2") should draw the third one too (data-pe="board-3" from thirdBoard), so all boards sit together in its own style. The six bundled themes do, and keep declaring ^0.2.11 because the fields are optional.
0.2.15Waiting for the big blind: ControlsView.waitingForBigBlind (optional) is { canPost, postsMissedSmallBlind } while the viewer is seated at a cash table but waits for the big blind before being dealt in (new to a table already playing, or back from sitting out owing blinds), and null otherwise. canPost is true when the table lets them post now; postsMissedSmallBlind is true when posting also pays a missed small blind. The intent post-big-blind posts it (refused with illegal-action unless canPost), and the player is dealt in from the next hand. The data-pe-action value post-big-blind names the button. Additive: 0.2.14 is listed as compatible.A layout that draws its own action controls should say "Waiting for the big blind" (game.waitingForBigBlind.status) while waitingForBigBlind is set, and offer a post button when canPost is true, worded game.waitingForBigBlind.post ("Post big blind") or, with postsMissedSmallBlind, game.missedBlinds.post ("Post missed blinds"), as the standard controls do; without it a new player sits with no explanation and cannot choose to post. The six bundled themes do, and keep declaring ^0.2.11 because the field is optional.
0.2.14Two fixed-limit bet sizes: ControlsView.secondBetAmount (optional) is the larger bet or raise-to amount when a fixed-limit round offers two sizes: seven-card stud on fourth street with an open pair showing, where any player may bet or raise the small bet or the big bet. minBetAmount stays the small size; the field is null when the round has one size, when the viewer cannot bet or raise, and outside fixed limit. act({ type: controls.betOrRaise, amount: controls.secondBetAmount }) sends the big size. Private game amounts: useLobbyController().commands.validatePrivateGame also refuses a blind, buy-in or ante with more than two decimal places (the server refuses it too, with INVALID_AMOUNT_DECIMALS), and createPrivateGame answers that refusal with a translated message that names the field. No type changes. Additive: 0.2.13 is listed as compatible.A layout that draws its own fixed-limit bet button should draw a second one for secondBetAmount when it is a number, as the standard controls do; without it the player cannot choose the big bet. The six bundled themes do, and keep declaring ^0.2.11 because the field is optional. A private game form that shows validatePrivateGame‘s messages shows the new one without changes.
0.2.13Table replay and share link: useHandReplayController().view.tableReplayHref (optional) is the host’s page that replays the hand on a read-only table (play, pause, step, street jump, speed) and makes a share link that carries only what the table saw. Additive: 0.2.10 is listed as compatible; 0.2.11 and 0.2.12 are reserved for other additive packages and join the list when they land.Nothing. A hand page may link to view.tableReplayHref when it is present; the six bundled themes do, and keep declaring ^0.2.10 because the field is optional.
0.2.11Rabbit hunting: in the replay, HandReplayView.rabbitHunt ({ cards, boardSize }: the shared cards a rabbit hunt revealed after the hand, never dealt, and how many shared cards were out when it ended); absent when nobody asked. At the table the host draws the ask control and the revealed cards (dashed, labelled "Would have come (not dealt)", announced, placed clear of the play-critical nodes and marked data-host-critical) for every layout. Additive: 0.2.10 is listed as compatible (0.2.9 stays reserved).Nothing. A layout that draws its own replay board may draw rabbitHunt.cards apart from it, saying in words that they were not dealt (the six bundled themes do).
0.2.10Run it twice: TableView.secondBoard (the second board’s cards as dealt, or null), WinnerView.board and the win table-log line’s board (the board, 1 or 2, a share was won on), and in the replay HandReplayView.boards (every board with its cards) and HandReplayWinnerView.board. All absent for a hand with one board. The host draws the agree or decline prompt beside the action controls, the outcome line, each board’s shares and the second board for every layout; the second board is placed clear of the board, pot, seats, controls, top bar, chat and status text (full size, else smaller cards, else stacked) and marked data-host-critical so the game information keeps clear of it. Additive: 0.2.9 is listed as compatible.Nothing. A layout that wants to draw the second board itself renders a node with data-pe="board-2" from table.secondBoard; the host then does not draw its own. A layout that draws its own replay board may draw boards[1].cards beside it.
0.2.9Jackpot Sit and Go: the tournament detail view carries jackpot (the multiplier table in words: each multiplier with its probability, prize pool and prizes, the payout percentage and fee, then the drawn result) and each lobby tournament row jackpotLine. Additive: 0.2.8 is listed as compatible.Nothing; a theme that shows tournament details can print jackpot and jackpotLine. Declare ^0.2.9 to rely on them.
0.2.5The player’s records: useStatementController() (the gameplay statement of a chosen period: per-wallet opening and closing balance and totals, play chips apart, hands with funds, wagers, rake, void status and automatic actions; view.csvHref downloads it as CSV, commands.print() opens the print dialog to print or save as PDF), useTransactionsController({ pageSize }) (the transaction history of a period with the same per-wallet totals) and useSessionsController() (sign-in sessions and table sessions of a period, each table session’s net in the table’s currency, tournament chips and play chips apart). New view ids member.statement (/statement), member.transactions (/transactions) and member.sessions (/sessions). Additive: 0.2.4 is listed as compatible.Nothing to keep loading. To show these pages in the theme’s own member area, register the three view ids on the controllers and declare ^0.2.5. All six bundled themes do.
0.2.4Rake and fees before play. Each cash table row (useLobbyController().view.tables[]) carries rake (the effective percentage, heads-up percentage, cap per hand, caps by players dealt in and no flop no drop; null at a play-money table), rakeLabel ("Rake 5%" or "No rake") and rakeText (the whole rule in words, translated). Each tournament row and the tournament detail view carry entryFee (charged on top of buyIn, 0 for none) and priceText ("$10.00 + $1.00 fee", the buy-in alone without a fee). The lobby.table-row part gets rakeText and the lobby.tournament-row part priceText as props. At the table, nothing changes for themes: the host’s game information shows a Rake pill that opens the whole rule, and the host’s join dialog shows it before a player sits.Nothing to keep installing: 0.2.3 is listed in THEME_CONTRACT_COMPATIBLE_VERSIONS. The fields are optional, so a theme that reads them keeps working on an older host (it shows nothing there) and may keep declaring ^0.2.3. Show rakeText on every row that has one (or its detail): it is the rake rule at a real-money table and can also carry a rule of play at any table, such as a two-board table at play money; the host sends none for a play-money row without such a rule and priceText wherever the theme shows a tournament price; never work out a rake line yourself.
0.2.3Game information in the lobby view (useLobbyController().view): playMoney on every cash table, tournament and private game row, mixedRotation ({ games, handsPerVariant } or null) on a cash table and rulesHref (the game rules page) on the view. At the table, nothing changes for themes: the host draws the rules link (new tab), the play-money marker and the win-odds notice over every theme table layout, placed in the first corner or edge slot that covers none of the layout’s board, pot, seats, action buttons, controls, top bar, chat or win-odds meter, in the theme’s --th-* colours.Nothing to keep installing: 0.2.2 and 0.2.1 are listed in THEME_CONTRACT_COMPATIBLE_VERSIONS. A theme that reads the new fields declares ^0.2.3. The bundled themes show a Play money tag on play-money rows (Neo in every list, not only lists that mix both modes) and Neo and Felthouse link Game rules from their lobby; Play UI, Pokerfest and Riverhouse keep the host’s link above their rows. Keep the corner your layout leaves free in mind: the host draws the labelled cluster where it fits clear of those nodes and otherwise a single 28 px Game information button that opens the same items, and the certification harness fails a layout that leaves not even that button a clear spot.
0.2.2Private player notes: openPlayerMenu(target: PlayerMenuTarget, anchor?: { x, y }) opens the host’s opponent menu ("Add note" / "Edit note", "Report player") at a viewport point; editPlayerNote(target) opens the host’s note dialog directly (for a theme with its own player sheet); usePlayerNote(playerId): PlayerNoteView | null returns the viewer’s own note (body, color, swatch) so the seat can draw the colour tag. The host fetches the viewer’s notes for the players at the table in one request and caches them; only the author ever gets a note, and notes never travel over the table socket. Render body as text.Nothing to keep installing: 0.2.1 is listed in THEME_CONTRACT_COMPATIBLE_VERSIONS. A theme that uses any of the three declares ^0.2.2. The bundled neo, play-ui, pokerfest and riverhouse seats open openPlayerMenu from an opponent’s name (instead of reportPlayer) and draw the tag before the name; Felthouse adds Note and colour to its seat sheet (editPlayerNote) and draws the tag on opponent seats; Wildcard (wildcard-ui 1.0.2) opens openPlayerMenu from a button over an opponent’s plate (named "Player options for …") and draws the tag as a dot in the plate’s corner. The tag renders nothing without a colour, so seats look as before.
0.2.1The SDK command reportPlayer(target?: ReportPlayerTarget): opens the host’s "Report player" dialog (cheating, collusion, a bot, abuse). From a seat pass { playerId, username, tableId } (the host records the hand in progress when the viewer is dealt in); from hand history pass { gameId } and the dialog asks for the username; with nothing it asks for both. The host files the report and shows the player its reference.Nothing to keep installing: 0.2.0 is listed in THEME_CONTRACT_COMPATIBLE_VERSIONS. A theme that calls reportPlayer declares ^0.2.1. Every bundled theme offers it from an opponent’s seat and from its hand history.
0.2.0Plugin data in themes: the SDK hooks usePluginQuery, usePluginAction, usePluginEvent, usePluginAvailable and the types PluginQueryOptions, PluginQueryResult, PluginAction, PluginActionMethod, PluginEventHandler, PluginRequestError, PluginRequestErrorCode, backed by GET /api/v1/config/active-plugins; SlotProps.exclude (leave a plugin’s fills out of a slot whose feature the theme draws). Plugin page views: member.plugin.<providerType>.<segment>[.<segment>…] (one segment per page-path segment, most specific first), rendered only while the plugin is active, also where the plugin has no client page; templates get params.providerType and params.path. Table: ControlsView.preAction (PreActionView), sitOutNextHand, leaveAfterHand, topUp (TopUpView); the intents set-pre-action, clear-pre-action, sit-out-next-hand, cancel-sit-out-next-hand, leave-after-hand, cancel-leave-after-hand; add-chips refused over the maximum buy-in; WinnerView.bestCards; SeatTimer.startedAt, endsAt, usingTimeBank; the hooks useTableLog (TableLogEntry) and useTableHandHistory (TableHandSummary). VIRTUAL_CHIPS in the lobby and tournament currency unions. Lobby: LobbyControllerCommands.quickSeat(tableId, buyIn) (optional; join_table without a seat, plugin API 1.4) answering LobbyQuickSeatResult with the server’s errorCode (TABLE_FULL, PLAYER_NOT_ELIGIBLE, …), the plugin’s reason and details on a refusal; LobbyTournamentView.sngTemplateId (optional), LobbyTournamentView.lateRegistrationOpen and lateRegEndsAt (optional: a running tournament still taking late entries). Behaviour fixes in the same version (no new fields): TableView.sidePots is filled during the hand (the host reads the pots from table_state; before, it stayed empty until the result), TableView.connection reads disconnected as soon as the browser goes offline (before, only after the socket heartbeat timed out), usePluginQuery asks nothing a signed-out viewer may not read at the moment of signing out, SeatView.hiddenCardCount follows the server’s per-player count (TablePlayer.holeCardCount) when the server sends one and is 0 between a finished hand and the next (before, it was inferred from the street and the player’s flags, and every unfolded opponent showed card backs until the next hand started), and SeatView.isBot is true on bot seats while the operator’s bot badge game setting (showBotBadge, off by default) is on (before, always false); with it on the host also draws a BOT badge after the fills of every table.seat.badge slot, hidden behind a plugin badge that carries data-seat-disclosure.Nothing to keep installing: the host still accepts ^0.1.x ranges (THEME_CONTRACT_COMPATIBLE_VERSIONS). A theme that uses any addition declares ^0.2.0. A theme that renders tournament currencies handles VIRTUAL_CHIPS (play money).
0.1.3Extensible sign-in (plugin API 1.4): the view id site.auth.complete (/register/complete), the slot auth.register.fields ({ values, setValue, errors }), providers, providerError, linkNotice and linkConfirm on LoginView, the link-confirm login step with confirmLink() / cancelLink(), providers and providerError on RegisterView, the controllers useCompleteSignupController and useSignInMethodsController, and the SDK components ProviderButtons and ProviderIcon.Nothing to keep installing (^0.1.0 still matches; a theme that does not render the provider buttons shows none, and site.auth.complete falls back to the host page). A theme with its own site.auth.login and site.auth.register renders ProviderButtons, the link-confirm step and places auth.register.fields; one with its own member.settings view renders a Sign-in methods panel; declare ^0.1.3 once it does.
0.1.2Plugin slots profile.actions, settings.sections, notifications.item.actions, notifications.top, cashier.transfer.recipient (plugin API 1.3). The classic and pill table renderers place table.seat.badge.Nothing to keep installing (^0.1.0 still matches). A theme whose views replace the profile, settings, notifications or cashier pages places the new slots to keep plugin content there; declare ^0.1.2 once it does.
0.1.1TableView.odds and the optional win-odds DOM node.Nothing; a layout that shows odds declares ^0.1.1.
0.1.0First contract.

View ids, part areas, sections

View ids follow a hierarchy and fall back most specific first: table.tournament.stud → table.tournament → table.stud → table; site.page.sidebar-right → site.page; member.lobby.cash → member.lobby. member.plugin.<providerType> and agent.* are open-ended. Cashier and profile variants are tabs, not view ids, and maintenance is an overlay. Contract 0.2.0: a plugin page (/ext/<providerType>/<path>) resolves member.plugin.<providerType> plus one segment per path segment (up to MAX_PLUGIN_VIEW_SEGMENTS, four; pluginPageViewId in client/src/core/theme/runtime/view-ids.ts), so member.plugin.social.friends.requests → member.plugin.social.friends → member.plugin.social; see Plugin data and plugin pages.

Part areas carry a stability tier (stable, experimental, contract) and the prop names the host passes, so a theme part can render what the existing markup renders. Theme-owned parts, section types and view ids are namespaced theme.<slug>.<name>; the validator rejects another theme’s namespace.

Host section types ship with their settings schema in HOST_SECTION_SCHEMAS; a theme section type must bring its own schema, and a host type must not. Section and theme settings share one field vocabulary (text, textarea, number, toggle, select, color, image, range) so the admin renders every form from JSON.

Stored section lists (Page.sections, Page.sidebars, the site-wide sidebars in the appearance settings) are validated by src/themes/section-instances.ts: ids unique and well-formed, types known (host or theme.<slug>.<type>), placement matching the type’s schema, settings flat scalars, size-capped. The page service sanitises the HTML-bearing fields with sanitize-html on the way in; the client’s renderer (client/src/core/theme/sections/, loaded lazily so pages without sections pay nothing) sanitises again with DOMPurify, coerces every setting per field and renders each section inside the theme error boundary, so bad data never takes a page down. Menus come from navigation-settings.service.ts (getPublicMenus applies the visibility rules and resolves page items), are managed through src/api/routes/admin/menus.routes.ts and reach the client through GET /api/v1/config/menus and the SDK’s useMenu.

The table surface

TableView is what the adapter derives from the game store; a layout renders from it and sends TableIntents through act(). Fields the store cannot always fill are nullable. The DOM contract (DOM_CONTRACT) names every node the standard layout emits as data-pe="<node>" with data-pe-<property> attributes, the accessible name the certification wording expects, and the standard layout’s own .tbl-* selector (or test id) for the node. Nodes marked visible may never be hidden by theme CSS. Timing is split into gameplay steps a layout only reads and presentation steps it may declare within ranges.

TableView.odds (contract 0.1.1) carries the viewer’s win odds when the table style’s operator switch (TableStyle.showWinOdds, off by default) is on. The host computes them in the browser from the viewer’s own cards, the board, the live opponent count and hands shown publicly, never from hidden cards, and gives spectators none. The engine is client/src/core/theme/sdk/table/odds/; the optional win-odds DOM node lets certification check a layout’s meter against the adapter. See Win Odds.

Table additions (contract 0.2.0)

Everything below is host-owned, derived in client/src/core/theme/sdk/table/ and covered by the tests beside each file.

AdditionShapeSource
Pre-actionsControlsView.preAction: { selected, callAmount, available, facingAmount }; PreActionType = check-fold | fold | check | call | call-any; intents set-pre-action { preAction }, clear-pre-actionqueued-actions.ts
Sit out next handControlsView.sitOutNextHand; intents sit-out-next-hand, cancel-sit-out-next-handqueued-actions.ts
Leave after handControlsView.leaveAfterHand; intents leave-after-hand { keepWatching? }, cancel-leave-after-handqueued-actions.ts
Top-upControlsView.topUp: { available, min, max } for add-chips; add-chips is refused when the stack would pass the maximum buy-in. The range is the server’s add_chips rule: at least the table’s minimum buy-in, and the stack plus pending chips at most the maximum, so available is false once the stack is within a minimum buy-in of the maximumqueued-actions.ts, intents.ts
Winners’ cardsWinnerView.bestCards: Card[] (the five cards the server named; empty without a showdown)derive.ts
Turn clockSeatTimer.startedAt, endsAt (Date.now() milliseconds, anchored once per turn), usingTimeBankturn-clock.ts
Table loguseTableLog(): TableLogEntry[] (hand-start, blind, action, board, win, chat; oldest first; 200 lines; muted chat left out)table-log.ts
Session handsuseTableHandHistory(): TableHandSummary[] (newest first, 20 hands)table-log.ts
Report a player (0.2.1)reportPlayer({ playerId, username, tableId }) from a seat, reportPlayer({ gameId }) from a hand; opens the host’s dialogsdk/report-player.tsx
Player notes (0.2.2)openPlayerMenu({ playerId, username, tableId }, { x, y }) from an opponent’s name; editPlayerNote({ playerId, username }); usePlayerNote(playerId) for the colour tagsdk/player-menu.tsx

The host keeps the queue and sends a queued entry itself: a pre-action through act() the moment the turn arrives (once, after the render that shows the turn), sit-out and leave through the page’s own commands once the viewer is out of the hand. fold and check-fold never fold when checking is free; check is cancelled when a bet is faced and call when the amount faced changes; every pre-action is cleared on a new street or hand and when the viewer folds, goes all-in or leaves the hand. Nothing fires, and nothing is cleared, while the connection is down. The server has no "sit out next hand" or "leave after hand" of its own; the queue is the browser’s, so it is lost on a reload.

Already in the contract, so not duplicated: per-seat last action (SeatView.lastActionType, lastAction), pots (TableView.pot is the total, sidePots the pots after the main one with their eligible seats), winners’ hand names (WinnerView.handName), bestHands by seat, the time bank (SeatView.timeBankRemaining, ControlsView.canUseTimeBank, use-time-bank), rebuy after busting (ControlsView.busted with add-chips, tournament-rebuy, tournament-reentry), sit out and sit in at once (sit-out, sit-in), leaving at once (leave-table). The account’s hand history stays with useHandHistoryController (filter tableId).

Lobby quick seat (contract 0.2.0)

useLobbyController().commands.quickSeat?(tableId, buyIn) takes the first open seat at a cash table (join_table without seatIndex, plugin API 1.4), marks the table session seated and opens the table. It answers LobbyQuickSeatResult:

type LobbyQuickSeatResult =
  | { ok: true; value: { tableId: string; seatIndex: number } }
  | { ok: false; error: string; errorCode: string | null; reason: string | null;
      details: Record<string, string | number | boolean | null> | null };

errorCode is the server’s (TABLE_FULL: try the next table; PLAYER_NOT_ELIGIBLE: a plugin refused the seat, reason says why, e.g. LEVEL_REQUIRED or GUEST_ACCOUNT; REAL_EMAIL_REQUIRED: core keeps an account an anonymous login provider created, such as a guest, away from a real-money table until it has a confirmed real email, details.requirement is real_email or confirmed_email), or the host’s NOT_CONNECTED, TIMEOUT, UNAUTHORIZED, VALIDATION_ERROR. The host picks neither the table nor the amount; the server refuses a buy-in outside the table’s limits. Nothing is navigated on a refusal. LobbyTournamentView.sngTemplateId names the Sit & Go template of a sit-and-go instance (null otherwise). LobbyTournamentView.lateRegistrationOpen is true for a running scheduled tournament whose late-registration window is open now (a list can offer "Join late"; the detail controller’s register() still checks seats and balance), lateRegEndsAt the ISO time the window closes (null without one); both false / null from a host that does not say. Implementation: client/src/core/theme/sdk/controllers/lobby.ts (quickSeatAtTable), tests in lobby.test.tsx.

Plugin data and plugin pages (0.2.0)

A theme may not fetch, open a socket or use storage, and the scanner keeps refusing all three (and the string /api/). Contract 0.2.0 lets the host do it on the theme’s behalf, scoped to one plugin’s own namespace. Implementation: client/src/core/theme/sdk/plugin-data.ts; the active-plugin list, client/src/core/plugin-availability.ts; host event listeners, client/src/core/plugin-events.ts.

usePluginQuery<T = unknown>(providerType: string, path: string, options?: PluginQueryOptions): PluginQueryResult<T>;
usePluginAction(providerType: string): PluginAction;
usePluginEvent(providerType: string, event: string, handler: PluginEventHandler): void;
usePluginAvailable(providerType: string): boolean;

interface PluginQueryOptions {
  params?: Record<string, string | number | boolean | null | undefined>;
  enabled?: boolean;                    // default true
  refetchOnEvent?: readonly string[];   // the plugin's realtime event names
}
interface PluginQueryResult<T = unknown> {
  data: T | null;
  loading: boolean;
  error: PluginRequestError | null;
  available: boolean;
  refetch(): Promise<void>;             // never rejects
}
type PluginActionMethod = 'POST' | 'PUT' | 'PATCH' | 'DELETE';
type PluginAction = <T = unknown>(method: PluginActionMethod, path: string, body?: unknown) => Promise<T>;
interface PluginRequestError extends Error {
  name: 'PluginRequestError';
  code: 'unavailable' | 'invalid-request' | 'unauthorized' | 'forbidden' | 'not-found'
      | 'validation' | 'conflict' | 'rate-limited' | 'server' | 'network';
  status: number | null;
  providerType: string;
  details: Record<string, string[]> | null;
}
  • Namespace. Requests go to /api/v1/plugins/<providerType><path> through engine.http‘s client (client/src/core/plugin-http.ts): the same path rules (pluginEndpoint: no absolute URL, no //, no ./.. segments raw or encoded, no backslash, no control character, checked again after URL normalisation), cookies, CSRF on unsafe methods, the silent refresh, the { success, data } envelope, no retry for actions. A bad path, method or plugin id is invalid-request with no request.
  • Activation. GET /api/v1/config/active-plugins (public, no-store, rate limited; getClientPluginProviderTypes in src/core/plugins/plugin-scripts.ts) lists the active plugins a client can consume: a frontend bundle, a client-visible setting, or a public or authenticated route (backend-only plugins are left out); the plugin:activated, plugin:updated, plugin:deactivated and plugin:auto-disabled socket events keep it current (usePluginSync). Nothing is sent for a plugin outside it (available: false, actions reject with unavailable).
  • Cache. Identical queries (plugin, normalised path, sorted params) share one entry and one request. They refetch on mount when older than 30 seconds, on activation or update, when the signed-in viewer changes, after a successful action for the same plugin, and on refetchOnEvent. Deactivation drops the data. Idle entries are evicted beyond 64.
  • Events. usePluginEvent and refetchOnEvent subscribe to host listeners fed by the one plugin:event socket listener; they survive a plugin reload (unlike a bundle’s engine.socket channel) and drop events while the plugin is inactive. Event names follow PLUGIN_REALTIME_EVENT_PATTERN.
  • No throwing. The hooks report errors as data; they never throw during render (a theme that throws is deactivated).

Plugin page views. The /ext/:providerType/* route (and the public /plugins/:providerType/public/*) renders PluginViewTemplate: it resolves pluginPageViewId(providerType, path), and renders the theme’s template only when the active theme has one in the fallback chain and the plugin is active. The theme view may render where the plugin registered no client page; the URL namespace stays the active plugin’s, so a theme still cannot add URLs of its own. While the plugin list loads the route shows the loading fallback; with the plugin inactive, no template, or a declared page redirect, the plugin’s own page renders as before (PluginPageRenderer, "Plugin Not Available" for an inactive plugin). A provider type with _ is not a view-id segment and always renders the plugin’s page. Templates receive params.providerType and params.path. The validator already accepts member.plugin.* ids under the open prefix. Guide: Using Plugin Data in a Theme.

Plugin slots

ThemeSlotId (packages/shared/src/themes/ids.ts) lists the plugin slots a theme may place with the SDK Slot; THEME_SLOT_IDS in src/themes/ids.ts and client/src/core/slot-fill/theme-slots.ts mirror it, and tests/themes/theme-slots.test.ts keeps the three in step and checks each id is documented in client/src/core/slot-fill/SLOTS.md. Admin slots are never theme slots; Slot renders nothing for an id outside the list.

Plugin platform v2 (plugin API 1.1) added twelve Beta slots. A theme that replaces the markup holding one places it, with the same passProps, so plugin content survives the theme:

SlotWherepassProps
table.seat.badgeBeside each seated player’s name{ userId, seatIndex, isHero, tableId } (seat.playerId, seat.seatIndex, seat.isHero, table.tableId)
table.hud.panelA panel region of the table layout (the standard layout: a collapsible rail at the inline end, a sheet on phones){ tableId, heroUserId } (heroUserId: the hero seat’s playerId, else null)
table.sidebar.endBelow the layout’s chat or info column{ tableId }
table.hand-result.afterUnder the hand result while table.winners is not empty{ tableId, handNumber, winners } (table.winners)
lobby.sidebarThe lobby’s side columnnone
home.hero.afterUnder the front page heronone
profile.header.badgesBeside the username in the profile header{ userId, isOwnProfile }
profile.actionsUnder the profile header (plugin API 1.3){ userId, username, isOwnProfile }
profile.stats.afterBottom of the statistics tab{ userId, isOwnProfile }
profile.tabsAfter the profile tabs (tab slot){ userId, isOwnProfile }
leaderboard.tabsAfter the leaderboard (tab slot)none
cashier.topAbove the cashier tabsnone
layout.main.header.startHeader, before the navigation (headerStartSlot)none
notifications.top (API 1.3)Above the notification list{ searchParams }: new URLSearchParams(useLocation().search)
notifications.item.actions (API 1.3)Each notification’s actions (a master-detail inbox: the open message’s action bar){ notification: { id, source, subcategory, link, metadata, isRead } } from the NotificationView (missing fields as null)
cashier.transfer.recipient (API 1.3)Under the recipient field of the transfer form{ onSelect(username), balanceType: 'real' } (onSelect sets the recipient)

A notifications view also shows a plugin notification’s link (a relative path, or null) as an Open link.

Contract 0.1.2 (plugin API 1.3) adds the slots of the pages plugins now extend instead of shipping their own:

SlotWherepassProps
profile.actionsButtons on the public player profile (/players/:username, view member.player) and the own /profile{ userId, username, isOwnProfile }
settings.sectionsSections of /settings after the core ones (tab slot: one section per registration, /settings#<id>){ userId }
notifications.item.actionsEach notification row{ notification: { id, source, subcategory, link, metadata, isRead } }
notifications.topAbove the notification list{ searchParams }
cashier.transfer.recipientBeside the recipient field of the transfer form{ onSelect(username), balanceType }

The host’s navItems part prop also carries the plugin pages registered with nav (plugin API 1.3), after the product’s own links, as { id: 'plugin:<providerType>:<path>', to, label, section }: section is 'account' for pages that belong with the account links (a user menu) and 'main' for the main navigation. The host no longer fills layout.main.sidebar.end with those pages, so a theme that renders navItems lists them once. The bundled themes keep up to two plugin pages in the header and move the rest into the account menu (headerNavItems and accountMenuPluginItems in each theme’s src/parts/shared.ts); the default header does the same with a More menu.

| settings.sections | After the settings view’s own panels (section slot) | { userId } (useViewer().id) |

The table slots render inside the table theme boundary. The standard layout places them host-side (client/src/components/game/table/TablePluginSlots.tsx); a theme layout places them itself, from the view models it already receives.

Rules that keep pages unchanged without plugins:

  • An empty Slot renders no DOM. A theme that wraps a slot for layout gives the wrapper no box while it is empty (.my-slot:empty { display: none; }, the JSX holding only the Slot), as the bundled themes do.
  • Host containers around non-empty slots carry data-pe-slot="<slot id>"; a theme may restyle them through that attribute.
  • Contract 0.2.0: <Slot id="…" exclude={['progression', 'daily-wheel']} /> leaves out the fills of the named plugins (providerTypes) and keeps every other plugin’s. A theme that draws a plugin’s feature itself from plugin data (a level chip, a wheel tile) excludes that plugin where it would otherwise show the same thing twice. Plain slots only; tab and section slots ignore it.
  • Tab slots (profile.tabs, leaderboard.tabs): the theme cannot read the fill registry, so placing the slot renders the contributed tabs as a host strip ([data-pe-slot="profile.tabs"], role="tablist", one role="tab" button per contributed tab with data-pe-tab="<id>", the selected panel in role="tabpanel"), or nothing when no plugin contributes a tab. Place it after the theme’s own tabs.
  • Section slots (settings.sections): placing the slot renders each contributed section as section[data-pe-section="<id>"] with id="<id>" and an h2 heading, inside [data-pe-slot="settings.sections"] (class pe-plugin-sections, each section pe-plugin-section), or nothing. Place it after the settings view’s own panels and give the notifications panel the id notifications, so /settings#notifications and /settings#<id> land on them. useSettingsController().view.notifications carries the notifications grid (groups of categories with a value per channel) and commands.setNotificationPreference(source, category, channel, enabled) saves a switch.

Every fill renders inside the plugin’s own error boundary, so a fill that throws never takes the page, the table or the theme layout down.

Merge tags

The grammar is i18next interpolation: {{viewer.firstName}}, {{viewer.balance, money}}, {{viewer.firstName, fallback(there)}}. TAG_DICTIONARY lists the namespaces (site, viewer, viewer.stats, lobby, page, post, category, table, theme.settings), where each resolves (client, SEO head, email), and the formats. checkMergeTags warns on unknown tags, formats, kinds and missing options; plain placeholders such as {{count}} are not merge tags and pass untouched. Viewer tags are private and never resolve in cached public HTML.

The validator

validateThemePackage takes a ThemePackageFiles (an extracted directory via readPackageDirectory, or createMemoryPackage for tests and tooling) and returns a ValidationReport: ok, findings with rule id, severity, message, file, line and column, and size stats. The archive itself is extracted by the platform’s archive-safety.ts; the validator never reads a tar stream.

Rules, in VALIDATION_RULES:

  • Manifest: schema (strict, unknown fields rejected); engines.contract includes the running version; view, part and section ids are host-owned or theme.<slug>.*; files the manifest names exist; standard cannot be redeclared; fonts have licence files; strings files exist.
  • Package: extension allow-list (js css json woff2 svg png webp jpg mp3 ogg md txt plus licence files); no absolute paths, traversal or depth over 20; at most 5,000 files; 30 MB package, 500 KB CSS, 300 KiB gzip JavaScript, 120 KiB gzip per chunk; JavaScript only as dist/<entry>.js and dist/chunks/*.js; no fonts.googleapis.com anywhere.
  • CSS: no @import; url() relative to the package (resolved from the stylesheet’s directory, no climbing out, no absolute, protocol or data:); no expression(), behavior or -moz-binding; @layer blocks only pe-theme, a brace-less statement may restate the canonical order; on DOM-contract nodes no !important and nothing that hides them (display:none, visibility:hidden|collapse, content-visibility:hidden, opacity:0, filter:opacity(0), transform:scale(0), clip-path collapses, zero size or font size). Attribute selectors are parsed, not substring-matched: whitespace, quoting, case, the i flag, CSS escapes and every operator (=, ^=, $=, *=, |=, ~=) are resolved against the visible node names, so [ DATA-PE = 'controls' ] and [data-pe=\63 ontrols] are the same selector and [data-pe=seat-action] is not seat.
  • Tokens and strings: tokens.json values match the token kind (colour, length, number, font stack, shadow, duration, package-relative path) and never carry ;, {, }, <, url(http…) or expression(; strings are flat theme.<slug>.* keys and their merge tags are checked.
  • JavaScript: see below.

The JavaScript scanner

scanThemeScript parses each file with acorn as an ES module and walks it with scope tracking, so declared names are never mistaken for globals. The policy is an allow-list:

  • Imports only from react, react/jsx-runtime, react-dom (createPortal, flushSync), @pe/sdk (the names in SDK_EXPORTS) and the package’s own dist/chunks/*.js; import() only with a string literal naming an own chunk; no export * from, no import.meta.
  • Exactly one prologue per file may read the host object: const <alias> = window.__pokerEngine; at the top level, and the alias may only be read as .React, .jsxRuntime, .ReactDOM or .theme.register|sdk|externals. Any other mention of __pokerEngine, including as a string, is a finding.
  • Free identifiers must be in ALLOWED_GLOBALS (language built-ins, timers, observers, event and element classes, console, performance, crypto, URL, Intl, and the three roots). window, document and navigator may only appear as <root>.<member> with the member in the allow-list; aliasing, passing, computed access and assignment to them are findings. globalThis, self, top, parent, frames, Reflect, Proxy, Function, eval, with, .constructor, .__proto__, and string arguments to setTimeout or setInterval are findings.
  • fetch, WebSocket, EventSource, XMLHttpRequest, sendBeacon, workers, Image, Audio, cookies, Web Storage, IndexedDB, location, history, open, postMessage, the clipboard and notifications are findings with a pointed message. Because a window or document is reachable without naming one (el.ownerDocument, document.body.parentNode.parentNode, event.view, node.getRootNode(), an iframe’s contentWindow), the transport, storage, escape and defaultView/ownerDocument/getRootNode member names are findings on any object, and .write() calls are findings on any object too; names with a plausible meaning on theme objects (name, status, open, history, parent, view) are policed only on the three roots.
  • innerHTML and outerHTML assignment, insertAdjacentHTML, document.write, dangerouslySetInnerHTML, createElement of script, style, iframe, object, embed, link, meta, base, template or form (or with a non-literal tag), setAttribute of on*, style, srcdoc, href, src or a non-literal name, and javascript: URLs are findings.
  • Strings are checked after folding constant + chains and expression-free templates: socket.io, @poker/shared, gameStore, useGameSocket, every socket event name as a whole token, /api/, ws:// and wss:// are findings; http(s):// URLs are listed as warnings for review.
  • Obfuscation markers: identifiers written with escapes, string literals with eight or more hex or unicode escapes, atob, btoa, unescape, String.fromCharCode, and files that look minified (a line over 2,000 characters or a mean over 300). Bundled third-party libraries fail here by design.

What the scanner does not catch. It is a tripwire, not a proof. Strings assembled at runtime from parts that are individually innocent, values that arrive through SDK data, or an image whose src is built from viewer data and sent to a third-party host (the CSP leaves img-src https: and connect-src ws: wss: open) are beyond a static scan. React itself is reachable, so a theme can render any markup React can; the guarantees that matter are architectural: server authority, the SDK as the only data path, the socket never exposed, install permission, and the certification record. Treat an upload as code from the author.

The corpus

THEME_VALIDATOR_CORPUS holds in-memory packages with the findings they must produce: two valid packages (a child theme with parts, a table-only theme with a layout), and packages that reach for the socket, evade through computed access and aliases, fail the manifest schema or its cross-checks, break the CSS rules, carry bad files, bad tokens and strings, a minified library, bad imports and a parse error. validator.test.ts runs every case and checks the expected rule ids and file:line references; the sample-bad sample is the bad-socket case built into an archive.

The export

npm run themes:export-contract -- --out <dir> writes VERSION, types/ and types.d.ts (declarations emitted from the shared package), sdk.d.ts (one declaration per SDK export, generated from SDK_EXPORTS), manifest.schema.json (from the zod schema), validator.mjs (the validator bundled with acorn and zod for Node), ids.json, sections.json, tokens.json, dom-contract.json, tags.json, rules.json and corpus/. It writes nowhere else.

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.