@lastshotlabs/slingshot-game-engine
npm install @lastshotlabs/slingshot-game-engine
Functions
Section titled “Functions”authorizeDisplayToken
Section titled “authorizeDisplayToken”Authorize verified claims against the live session record.
Fails closed on every axis: wrong session, revoked epoch, or a session that is already over.
function authorizeDisplayToken(claims: DisplayTokenClaims, session: DisplaySessionFacts | null,): DisplayTokenVerificationSource: packages/slingshot-game-engine/src/lib/displayToken.ts
buildContentValidationGuard
Section titled “buildContentValidationGuard”Build the content validation guard middleware.
Registered under 'contentValidationGuard' in the named middleware map.
function buildContentValidationGuard({ getSessionAdapter, getRegistry, }: ContentValidationGuardDeps): voidSource: packages/slingshot-game-engine/src/middleware/contentValidationGuard.ts
buildLobbyOnlyGuard
Section titled “buildLobbyOnlyGuard”Build the lobby-only guard middleware.
Registered under 'lobbyOnlyGuard' in the named middleware map.
function buildLobbyOnlyGuard({ getSessionAdapter }: LobbyOnlyGuardDeps): voidSource: packages/slingshot-game-engine/src/middleware/lobbyOnlyGuard.ts
buildRulesValidationGuard
Section titled “buildRulesValidationGuard”Build the rules validation guard middleware.
Registered under 'rulesValidationGuard' in the named middleware map.
function buildRulesValidationGuard({ getSessionAdapter, getRegistry, }: RulesValidationGuardDeps): voidSource: packages/slingshot-game-engine/src/middleware/rulesValidationGuard.ts
createGameEnginePackage
Section titled “createGameEnginePackage”Create the game engine package.
function createGameEnginePackage(rawConfig: Partial<GameEnginePluginConfig> & { games?: GameDefinition[] } = {},): SlingshotPackageDefinitionSource: packages/slingshot-game-engine/src/plugin.ts
createGameSessionPolicy
Section titled “createGameSessionPolicy”Create the default session access policy.
Dispatches on gameType field. Default fallback allows access to
lobbies and denies access to in-progress sessions unless overridden
by a game-type-specific handler.
function createGameSessionPolicy(): voidSource: packages/slingshot-game-engine/src/policy/index.ts
DEFAULT_DISPLAY_TOKEN_TTL_MS
Section titled “DEFAULT_DISPLAY_TOKEN_TTL_MS”Default lifetime. Long enough to outlast a party, short enough that a photo of the TV rots.
Source: packages/slingshot-game-engine/src/lib/displayToken.ts
GAME_ENGINE_PLUGIN_STATE_KEY
Section titled “GAME_ENGINE_PLUGIN_STATE_KEY”Stable key used for reading or publishing the game-engine plugin state.
Source: packages/slingshot-game-engine/src/types/state.ts
GAME_SESSION_POLICY_KEY
Section titled “GAME_SESSION_POLICY_KEY”Stable policy key — referenced in entity route configs.
Source: packages/slingshot-game-engine/src/policy/index.ts
gameSessionOperations
Section titled “gameSessionOperations”Declarative operations for the GameSession entity.
Includes lookups (findByJoinCode, findByGameType) and status
transitions (startGame, pauseGame, resumeGame, completeGame,
abandonSession).
Source: packages/slingshot-game-engine/src/operations/session.ts
getDisplaySessionId
Section titled “getDisplaySessionId”The session this request is a display for, or null.
This is the ONLY sanctioned way an app authorizes a TV. Use it to widen a route that would otherwise require a user:
const userId = getActorId(c); // null for a TVconst display = getDisplaySessionId(c); // the session, for a TVif (!userId && display !== match.gameSessionId) return c.json(…, 401);Note what this does NOT do: it never returns a user id, so a display can never be mistaken for a player by any code that reads identity the normal way.
function getDisplaySessionId(c: Context<AppEnv>): string | nullSource: packages/slingshot-game-engine/src/lib/displayRuntime.ts
hostRoom
Section titled “hostRoom”Build a host-only room key.
function hostRoom(sessionId: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
isDisplayFor
Section titled “isDisplayFor”True when this request is a display bound to sessionId.
function isDisplayFor(c: Context<AppEnv>, sessionId: string): booleanSource: packages/slingshot-game-engine/src/lib/displayRuntime.ts
mintDisplayToken
Section titled “mintDisplayToken”Mint a display token for one session. Host-authorized — the caller enforces that.
function mintDisplayToken(input: { readonly sessionId: string; readonly epoch: number; readonly secret: string | readonly string[]; readonly ttlMs?: number; readonly now?: number; readonly tokenId?: string; }): voidSource: packages/slingshot-game-engine/src/lib/displayToken.ts
playerRoom
Section titled “playerRoom”Build a per-player private room key.
function playerRoom(sessionId: string, userId: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
registerGameSessionPolicies
Section titled “registerGameSessionPolicies”Register the game session policy on an app instance.
Called during setupMiddleware in the plugin lifecycle.
function registerGameSessionPolicies(app: Hono<AppEnv>): voidSource: packages/slingshot-game-engine/src/policy/index.ts
roleRoom
Section titled “roleRoom”Build a per-role room key.
function roleRoom(sessionId: string, roleName: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
sessionRoom
Section titled “sessionRoom”Build a session broadcast room key.
function sessionRoom(sessionId: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
spectatorRoom
Section titled “spectatorRoom”Build a spectator room key.
function spectatorRoom(sessionId: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
streamRoom
Section titled “streamRoom”Build a stream relay room key.
function streamRoom(sessionId: string, channelName: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
teamRoom
Section titled “teamRoom”Build a per-team room key.
function teamRoom(sessionId: string, teamName: string): stringSource: packages/slingshot-game-engine/src/lib/display.ts
verifyDisplayToken
Section titled “verifyDisplayToken”Verify a display token’s SIGNATURE and EXPIRY only.
Deliberately does not touch the database. Session existence, status and epoch
are authorization questions and are answered by authorizeDisplayToken,
which has the session record. Splitting them keeps this half pure and lets the
WS path verify cheaply before doing any I/O.
function verifyDisplayToken(token: string, opts: { readonly secret: string | readonly string[]; readonly now?: number },): DisplayTokenVerificationSource: packages/slingshot-game-engine/src/lib/displayToken.ts
Constants
Section titled “Constants”GameEngine
Section titled “GameEngine”Provider-owned package contract for slingshot-game-engine.
Source: packages/slingshot-game-engine/src/public.ts
gameEnginePluginConfigSchema
Section titled “gameEnginePluginConfigSchema”Canonically cased schema export.
Source: packages/slingshot-game-engine/src/validation/config.ts
GameEnginePluginConfigSchema
Section titled “GameEnginePluginConfigSchema”Zod schema validating the game engine package config: mount path, WS endpoint, replay, cleanup, disconnect, rate-limit, heartbeat, recovery, and disabled routes.
Config Fields
Section titled “Config Fields”| Field | Description |
|---|---|
cleanup | Cleanup configuration for completed/abandoned sessions. |
disableRoutes | Routes to disable. Keys are entityName.operationOrAction strings. |
disconnect | Default disconnect configuration. |
heartbeat | WS heartbeat configuration. |
mountPath | Mount path for game engine REST routes. Default: /game. |
recovery | WS message persistence and recovery configuration. |
replay | Replay log storage and retention. |
wsEndpoint | WS endpoint name. Default: ‘game’. |
wsRateLimit | WS rate-limiting configuration (per-socket, rolling window). |
Source: packages/slingshot-game-engine/src/validation/config.ts
GameEngineRuntimeCap
Section titled “GameEngineRuntimeCap”Capability handle for the game-engine runtime state.
Cross-package consumers resolve it via
ctx.capabilities.require(GameEngineRuntimeCap). The legacy
GAME_ENGINE_PLUGIN_STATE_KEY plugin-state slot is still published in
parallel during the bridge period; new consumers should prefer the cap.
Source: packages/slingshot-game-engine/src/public.ts
GameErrorCode
Section titled “GameErrorCode”All game engine error codes.
Source: packages/slingshot-game-engine/src/errors.ts
GamePlayer
Section titled “GamePlayer”GamePlayer entity definition.
Persisted player record linking a user to a session with role,
team, score, connection status, and join order. Unique on
(sessionId, userId).
Source: packages/slingshot-game-engine/src/entities/gamePlayer.ts
gamePlayerFactories
Section titled “gamePlayerFactories”Repository factories for the GamePlayer entity, dispatched by StoreType.
Source: packages/slingshot-game-engine/src/entities/factories.ts
gamePlayerOperations
Section titled “gamePlayerOperations”Declarative operations for the GamePlayer entity.
Includes lookups (findBySession, findBySessionAndUser),
mutations (incrementScore, updateConnection), and aggregates
(countBySession).
Source: packages/slingshot-game-engine/src/operations/player.ts
GameSession
Section titled “GameSession”GameSession entity definition.
Persisted session record with status, phase, round, RNG state, win result, and all timing fields. Indexed by game type, status, join code, host, and parent session.
Source: packages/slingshot-game-engine/src/entities/gameSession.ts
gameSessionFactories
Section titled “gameSessionFactories”Repository factories for the GameSession entity, dispatched by StoreType.
Source: packages/slingshot-game-engine/src/entities/factories.ts
Classes
Section titled “Classes”GameError
Section titled “GameError”Structured game engine error.
Carries a machine-readable code from GameErrorCode, an HTTP status
(for REST responses), and optional structured details (e.g., Zod
validation errors, handler rejection reasons).
Source: packages/slingshot-game-engine/src/errors.ts
Interfaces
Section titled “Interfaces”BufferedInput
Section titled “BufferedInput”Buffered input from a stream channel (consumed in tick handler).
Source: packages/slingshot-game-engine/src/types/models.ts
ChannelDefinition
Section titled “ChannelDefinition”Base channel definition shared by all modes.
Source: packages/slingshot-game-engine/src/types/models.ts
ChannelRuntimeState
Section titled “ChannelRuntimeState”Runtime state of an active channel.
Source: packages/slingshot-game-engine/src/types/models.ts
ContentDefinition
Section titled “ContentDefinition”Content definition for a game type.
Source: packages/slingshot-game-engine/src/types/models.ts
ContentProvider
Section titled “ContentProvider”Content provider contract.
Game definitions declare content providers by name. Each provider loads content from an external source (API, database, user upload) and validates it against the game’s content schema.
Source: packages/slingshot-game-engine/src/types/adapters.ts
ContentProviderDefinition
Section titled “ContentProviderDefinition”A named content provider.
Source: packages/slingshot-game-engine/src/types/models.ts
DisplaySessionFacts
Section titled “DisplaySessionFacts”Session facts the authorization step needs.
Source: packages/slingshot-game-engine/src/lib/displayToken.ts
DisplayTokenClaims
Section titled “DisplayTokenClaims”The claims carried inside a display token. Signed, not secret.
Source: packages/slingshot-game-engine/src/lib/displayToken.ts
GameDefinition
Section titled “GameDefinition”Validated, frozen output of defineGame().
Source: packages/slingshot-game-engine/src/types/models.ts
GameDefinitionInput
Section titled “GameDefinitionInput”Input shape passed to defineGame(). Accepts partial/optional fields
that are resolved to full GameDefinition with defaults.
Source: packages/slingshot-game-engine/src/types/models.ts
GameDisconnectConfig
Section titled “GameDisconnectConfig”Per-game disconnect configuration (overrides plugin-level defaults).
Source: packages/slingshot-game-engine/src/types/models.ts
GameEngineActiveSessionSnapshot
Section titled “GameEngineActiveSessionSnapshot”Read-only snapshot of one active game session runtime.
The snapshot is safe for app-layer inspection and persistence projection.
It intentionally does not expose the mutable SessionRuntime internals.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEngineAdvancePhaseInput
Section titled “GameEngineAdvancePhaseInput”Optional override input when advancing an active session phase.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEnginePluginConfig
Section titled “GameEnginePluginConfig”Configuration options for createGameEnginePackage().
Source: packages/slingshot-game-engine/src/types/config.ts
GameEnginePluginState
Section titled “GameEnginePluginState”Runtime state stored in getContext(app).pluginState.
Shallow-frozen at registration time. The config and public control surface
are independently frozen, while adapter references remain opaque mutable
runtime resources and are never traversed by deepFreeze().
Adapters are captured via closure during buildAdapter callbacks.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEngineSessionControls
Section titled “GameEngineSessionControls”Narrow app-facing control surface for active session runtimes.
Apps should use this surface instead of reading mutable SessionRuntime
internals from plugin state.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEngineSessionMutationContext
Section titled “GameEngineSessionMutationContext”Mutation callback surface for a live active session.
This intentionally exposes the engine’s sanctioned handler context rather
than the underlying mutable SessionRuntime object.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEngineSessionMutationResult
Section titled “GameEngineSessionMutationResult”Result of a session mutation callback.
Source: packages/slingshot-game-engine/src/types/state.ts
GameEngineSubmitInput
Section titled “GameEngineSubmitInput”Input payload for server-side submission into an active session channel.
Source: packages/slingshot-game-engine/src/types/state.ts
GameLifecycleHooks
Section titled “GameLifecycleHooks”Lifecycle hooks for a game definition.
Source: packages/slingshot-game-engine/src/types/models.ts
GameLoopDefinition
Section titled “GameLoopDefinition”Game loop configuration from a game definition.
Source: packages/slingshot-game-engine/src/types/models.ts
GamePlayerState
Section titled “GamePlayerState”Runtime player state visible to clients.
Source: packages/slingshot-game-engine/src/types/models.ts
GameSessionState
Section titled “GameSessionState”Runtime session state visible to clients.
Source: packages/slingshot-game-engine/src/types/models.ts
GameTimer
Section titled “GameTimer”Server-authoritative game timer.
Source: packages/slingshot-game-engine/src/types/models.ts
HandlerResult
Section titled “HandlerResult”Result returned by a handler.
Source: packages/slingshot-game-engine/src/types/models.ts
InputAck
Section titled “InputAck”Acknowledgment sent to a client after input processing.
Source: packages/slingshot-game-engine/src/types/models.ts
Leaderboard
Section titled “Leaderboard”Computed leaderboard.
Source: packages/slingshot-game-engine/src/types/models.ts
LifecycleHooks
Section titled “LifecycleHooks”Lifecycle hooks for a game definition.
Source: packages/slingshot-game-engine/src/types/models.ts
PhaseDefinition
Section titled “PhaseDefinition”Phase definition within a game’s phase graph.
Source: packages/slingshot-game-engine/src/types/models.ts
PlayerInfo
Section titled “PlayerInfo”Minimal player info passed to relay filters and hooks.
Source: packages/slingshot-game-engine/src/types/models.ts
ProcessHandlerContext
Section titled “ProcessHandlerContext”Full mutation API available to all game handlers.
Process handlers, onEnter, onExit, onTick, lifecycle hooks, and win condition checks all receive this context (or the read-only subset).
Source: packages/slingshot-game-engine/src/types/models.ts
RateLimitBackend
Section titled “RateLimitBackend”Rate limit backend interface.
Matches the pattern from slingshot-polls. The game engine uses this
for per-player per-channel rate limiting — the only rate limiter
the engine implements itself.
Source: packages/slingshot-game-engine/src/types/adapters.ts
ReadonlyHandlerContext
Section titled “ReadonlyHandlerContext”Read-only subset of ProcessHandlerContext.
Used for enabled conditions, checkWinCondition, dynamic config
resolution (timeout: (ctx) => ...), and next function resolution.
Source: packages/slingshot-game-engine/src/types/models.ts
ReplayEntry
Section titled “ReplayEntry”Single entry in the replay log.
Source: packages/slingshot-game-engine/src/types/models.ts
ReplayStore
Section titled “ReplayStore”Replay log storage adapter.
The default implementation stores entries in-memory per session. Alternative implementations can persist to a durable store (e.g., MongoDB collection, S3 objects).
Source: packages/slingshot-game-engine/src/types/adapters.ts
RoleAssignmentContext
Section titled “RoleAssignmentContext”Context available during role assignment.
Source: packages/slingshot-game-engine/src/types/models.ts
RoleDefinition
Section titled “RoleDefinition”Role definition within a game type.
Source: packages/slingshot-game-engine/src/types/models.ts
ScheduledEvent
Section titled “ScheduledEvent”Scheduled event for the game loop.
Source: packages/slingshot-game-engine/src/types/models.ts
ScoreEntry
Section titled “ScoreEntry”Single score entry.
Source: packages/slingshot-game-engine/src/types/models.ts
ScoringDefinition
Section titled “ScoringDefinition”Scoring configuration.
Source: packages/slingshot-game-engine/src/types/models.ts
SeededRng
Section titled “SeededRng”Seeded PRNG interface exposed to handlers via ctx.random.
Source: packages/slingshot-game-engine/src/types/models.ts
SessionLeaseAdapter
Section titled “SessionLeaseAdapter”Session lease adapter for multi-instance mode (§32).
Uses Redis-backed atomic leases to ensure a session is only active on one instance at a time. The owning instance renews the lease periodically. If the lease expires, another instance can claim it.
Source: packages/slingshot-game-engine/src/types/adapters.ts
SessionMutex
Section titled “SessionMutex”Session-level async mutex for serializing state mutations.
Source: packages/slingshot-game-engine/src/types/models.ts
SubPhaseDefinition
Section titled “SubPhaseDefinition”Sub-phase definition within a parent phase.
Source: packages/slingshot-game-engine/src/types/models.ts
SyncDefinition
Section titled “SyncDefinition”State sync configuration.
Source: packages/slingshot-game-engine/src/types/models.ts
TeamDefinition
Section titled “TeamDefinition”Team configuration for a game type.
Source: packages/slingshot-game-engine/src/types/models.ts
TeamScoreEntry
Section titled “TeamScoreEntry”Team score entry.
Source: packages/slingshot-game-engine/src/types/models.ts
TurnState
Section titled “TurnState”Runtime turn order state.
Source: packages/slingshot-game-engine/src/types/models.ts
VoteTally
Section titled “VoteTally”Vote tally result for a vote channel.
Source: packages/slingshot-game-engine/src/types/models.ts
WinResult
Section titled “WinResult”Result of a completed game.
Source: packages/slingshot-game-engine/src/types/models.ts
ChannelFromConfig
Section titled “ChannelFromConfig”Who can submit input to a channel.
String literals cover common patterns. Object forms filter by role, state, team, or dynamic player subsets. Function form is fully custom.
Source: packages/slingshot-game-engine/src/types/models.ts
ChannelMode
Section titled “ChannelMode”Channel interaction mode.
Source: packages/slingshot-game-engine/src/types/models.ts
ChannelRelayConfig
Section titled “ChannelRelayConfig”Where processed inputs or channel events are relayed.
Source: packages/slingshot-game-engine/src/types/models.ts
ClientToServerMessage
Section titled “ClientToServerMessage”Client → Server WS message types.
Source: packages/slingshot-game-engine/src/types/models.ts
DisplayTokenFailure
Section titled “DisplayTokenFailure”Why a token was rejected. Returned rather than thrown so callers can log precisely.
Source: packages/slingshot-game-engine/src/lib/displayToken.ts
DisplayTokenVerification
Section titled “DisplayTokenVerification”Successful display-token claims or a precise non-throwing verification failure.
Source: packages/slingshot-game-engine/src/lib/displayToken.ts
GameErrorCodeValue
Section titled “GameErrorCodeValue”Union type of all game engine error code values.
Source: packages/slingshot-game-engine/src/errors.ts
HandlerFunction
Section titled “HandlerFunction”Handler function signature. All handlers receive ProcessHandlerContext.
Source: packages/slingshot-game-engine/src/types/models.ts
PhaseAdvanceTrigger
Section titled “PhaseAdvanceTrigger”Phase advance trigger strategy.
Source: packages/slingshot-game-engine/src/types/models.ts
RelayFilterFunction
Section titled “RelayFilterFunction”Relay filter function for custom channel relay.
Source: packages/slingshot-game-engine/src/types/models.ts
ReplayEventType
Section titled “ReplayEventType”All replay event types.
Source: packages/slingshot-game-engine/src/types/models.ts
RoleVisibilityRule
Section titled “RoleVisibilityRule”Rule controlling which other roles a given role can see.
Source: packages/slingshot-game-engine/src/types/models.ts
ServerToClientMessage
Section titled “ServerToClientMessage”Server → Client WS message types.
Source: packages/slingshot-game-engine/src/types/models.ts
SessionStatus
Section titled “SessionStatus”Session status state machine states.
Source: packages/slingshot-game-engine/src/types/models.ts
Exports
Section titled “Exports”defineGame
Section titled “defineGame”Define a game type.
Takes a GameDefinitionInput with optional fields, resolves defaults,
and returns a frozen GameDefinition ready for registration.
Source: packages/slingshot-game-engine/src/defineGame.ts