@puzzmo/sdk 1.0.89 → 1.0.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/bootstrapPayload.ts","../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts"],"sourcesContent":["import type { BootstrapGame, BootstrapGameData, BootstrapSession } from \"./types\"\n\n/**\n * READY_DATA as hosts from before the payload split send it: the gameplay with the puzzle nested\n * inside it, and a flattened game inside that. Deliberately not part of the SDK's public types.\n */\ntype LegacyReadyData = Omit<BootstrapGameData, \"game\" | \"session\"> & {\n game?: BootstrapGame\n session?: BootstrapSession\n startOrFindGameplay?: {\n gamePlayed?: BootstrapSession[\"gameplay\"] & { puzzle: BootstrapSession[\"puzzle\"] & { game?: any; viewerMetadata?: unknown } }\n }\n}\n\n/**\n * Fills in `game` and `session` when READY_DATA comes from a host which only sends the older\n * `startOrFindGameplay` nesting, so the SDK and games only ever see the new shape. A copy of\n * upgradeBootstrapGameData in @puzzmo-com/shared, which the SDK can't depend on.\n */\nexport const normalizeReadyData = (received: unknown): BootstrapGameData => {\n const { startOrFindGameplay, ...data } = received as LegacyReadyData\n if (data.game) return data as BootstrapGameData\n\n const gamePlayed = startOrFindGameplay?.gamePlayed\n const game = gameFromLegacy(gamePlayed?.puzzle?.game ?? {})\n if (!gamePlayed) return { ...data, game }\n\n const { puzzle, ...gameplay } = gamePlayed\n const { game: _game, viewerMetadata, ...puzzleFields } = puzzle\n return { ...data, game, session: { gameplay, puzzle: puzzleFields }, viewerMetadata: data.viewerMetadata ?? viewerMetadata }\n}\n\n/** Builds the game from the flattened fields older hosts put on `puzzle.game`, with no version IDs */\nconst gameFromLegacy = (game: any): BootstrapGame => {\n const flags = game.flagsArr\n return {\n id: game.id ?? \"\",\n slug: game.slug ?? \"\",\n stableSlug: game.stableSlug ?? game.slug ?? \"\",\n displayName: game.displayName ?? \"\",\n version: {\n id: \"\",\n label: null,\n featuresArr: game.featuresArr ?? [0],\n flagsArr: Array.isArray(flags) ? flags : typeof flags === \"number\" ? [flags] : [0],\n runtime: {\n id: \"\",\n version:\n game.assetsSha || game.assetsBaseURL\n ? { id: \"\", assetsSha: game.assetsSha ?? \"\", assetsBaseURL: game.assetsBaseURL ?? \"\" }\n : null,\n },\n },\n }\n}\n","import type { DeviceType, GameAnalyticsContext, LinkClickedInfo } from \"./analytics\"\n\n/**\n * Game analytics event-firing logic for the SDK.\n *\n * This mirrors the runtime's tracker (and the canonical copy in @puzzmo-com/clickhouse/gameTracker\n * used server-side): which host messages map to which events, the engagement thresholds, the\n * payload shape, and the /events endpoint. It is kept here, dependency-free, so the published SDK\n * pulls in none of the clickhouse package's server deps (kysely / @clickhouse/client) and so the\n * public OSS mirror can build it without the private workspace packages present.\n */\n\nexport type GameAnalyticsEventType = \"page_view\" | \"gameplay_active\" | \"active_30s\" | \"completed\" | \"link_click\"\n\ntype GameAnalyticsState = {\n context: GameAnalyticsContext\n updateCount: number\n startTime: Date\n tracked: {\n pageView: boolean\n gameplayActive: boolean\n active30s: boolean\n completed: boolean\n }\n}\n\ntype MessagesSent =\n | \"READY_GAME_LOADED\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"UPDATE_GAME_STATE\"\n | string\n\nconst sendGameAnalyticsEvent = async (\n context: GameAnalyticsContext,\n eventType: GameAnalyticsEventType,\n metadata?: Record<string, string | number | boolean>,\n elapsedTimeOnComplete?: number,\n) => {\n try {\n const body = {\n ...context,\n eventType,\n elapsedTimeOnComplete,\n metadata,\n }\n\n const response = await fetch(`${context.apiRoot}events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n // Ensures the event still fires if the user navigates away (e.g. clicking a _blank link)\n keepalive: true,\n })\n\n if (!response.ok) {\n console.warn(`Analytics event failed: ${eventType} - ${response.status} ${response.statusText}`)\n }\n } catch (error) {\n console.warn(`Analytics event error: ${eventType}`, error)\n }\n}\n\nexport const createGameAnalyticsTracker = (context: GameAnalyticsContext) => {\n const state: GameAnalyticsState = {\n context: { ...context, deviceType: context.deviceType ?? detectDeviceType() },\n updateCount: 0,\n startTime: new Date(),\n tracked: {\n pageView: false,\n gameplayActive: false,\n active30s: false,\n completed: false,\n },\n }\n\n const trackEvent = (type: MessagesSent, json?: any) => {\n const now = new Date()\n const timeDiff = now.getTime() - state.startTime.getTime()\n const seconds = timeDiff / 1000\n\n switch (type) {\n case \"READY_GAME_LOADED\": {\n if (!state.tracked.pageView) {\n sendGameAnalyticsEvent(state.context, \"page_view\")\n state.tracked.pageView = true\n }\n break\n }\n\n case \"UPLOAD_NEW_GAME_STATE\": {\n state.updateCount++\n\n // Fire gameplay_active early (after 2 state changes) to indicate user engagement\n if (state.updateCount > 2 && !state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n\n // Fire active_30s for sustained engagement\n if (seconds > 30) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\n }\n break\n }\n\n case \"GAME_COMPLETED\": {\n if (!state.tracked.completed && json?.input) {\n sendGameAnalyticsEvent(state.context, \"completed\", {}, json.input.elapsedTimeSecs)\n state.tracked.completed = true\n }\n break\n }\n }\n }\n\n const trackLinkClick = (info: LinkClickedInfo) => {\n sendGameAnalyticsEvent(state.context, \"link_click\", info)\n }\n\n return {\n trackEvent,\n trackLinkClick,\n }\n}\n\n/**\n * The kind of device the game runs on, judged by the whole device rather than the game's frame. A copy of\n * detectDeviceType in @puzzmo-com/clickhouse/deviceType, kept dependency-free for the published SDK.\n */\nconst detectDeviceType = (): DeviceType => {\n if (typeof navigator === \"undefined\" || typeof window === \"undefined\") return \"unknown\"\n const userAgent = navigator.userAgent\n\n // iPadOS Safari reports itself as a Mac, so only a touchscreen gives it away\n if (/iPad/.test(userAgent) || (/Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1)) return \"tablet\"\n const mobileHint = (navigator as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData?.mobile\n if (/iPhone|iPod/.test(userAgent) || mobileHint) return \"mobile\"\n // Android phones carry \"Mobile\", Android tablets leave it out\n if (/Android/.test(userAgent)) return /Mobile/.test(userAgent) ? \"mobile\" : \"tablet\"\n if (/Mobile|Windows Phone/.test(userAgent)) return \"mobile\"\n\n // Anything else whose main input is touch, sized by the screen's short side\n if (window.matchMedia?.(\"(pointer: coarse)\").matches) return Math.min(screen.width, screen.height) < 600 ? \"mobile\" : \"tablet\"\n return \"desktop\"\n}\n","import { createGameAnalyticsTracker } from \"./gameTracker\"\n\nimport type { BootstrapGameData } from \"./types\"\n\n/**\n * Game analytics for the SDK.\n *\n * The event-firing logic — which host messages map to which ClickHouse events, the\n * engagement thresholds, the payload, and the /events endpoint — lives in ./gameTracker,\n * a self-contained mirror of the runtime's tracker. It is kept local (rather than imported\n * from @puzzmo-com/clickhouse) so the published SDK pulls in none of the clickhouse package's\n * server deps, and so the public OSS mirror can build the SDK without the private workspace\n * packages present.\n *\n * This file only adds the SDK-specific glue: deciding whether analytics should run,\n * building the context from bootstrap data, and watching for link clicks. Events are\n * never sent from localhost (dev + the SDK simulator).\n */\n\nexport type LinkClickedInfo = {\n href: string\n text: string\n target: string\n}\n\ntype UserType = \"anon\" | \"user\" | \"paid\"\ntype RuntimeType = \"puzzmo_com\" | \"iframe\" | \"simple_embed\" | \"app_embed\" | \"ios_native\" | \"msn\"\n\n/** Everything the events endpoint needs to attribute an event, mirrors the runtime's context. */\nexport type GameAnalyticsContext = {\n gameSlug: string\n puzzleID: string\n gameplayOwnerID: string\n apiRoot: string\n userType: UserType\n runtimeType: RuntimeType\n userID?: string\n teamSlug?: string\n partnerSlug?: string\n dailyDateKey?: string\n embedID?: string\n /** Defaults to the device the game is running on, see detectDeviceType in ./gameTracker */\n deviceType?: DeviceType\n}\n\n/** Matches the device_type column in ClickHouse, the API classifies events which leave it out */\nexport type DeviceType = \"unknown\" | \"mobile\" | \"tablet\" | \"desktop\"\n\nexport type GameAnalyticsTracker = {\n /** Map an outgoing host message to its analytics event(s), if any. */\n trackEvent: (type: string, json?: any) => void\n /** Report an anchor click inside the game. */\n trackLinkClick: (info: LinkClickedInfo) => void\n}\n\n/**\n * Build the analytics tracker for a game, or null when analytics shouldn't run\n * (the game doesn't bring its own runtime, no browser, running on localhost, or\n * missing bootstrap data).\n */\nexport const createGameAnalytics = (readyData: BootstrapGameData | null): GameAnalyticsTracker | null => {\n // Only games that bring their own runtime track via the SDK — see gameBringsOwnRuntime.\n if (!gameBringsOwnRuntime(readyData)) return null\n\n const endpoint = resolveAnalyticsEndpoint()\n if (!endpoint.enabled) return null\n\n const context = buildAnalyticsContext(readyData, endpoint.apiRoot)\n if (!context) return null\n\n return createGameAnalyticsTracker(context)\n}\n\n/** Delegates document clicks to report anchor navigations. Returns a cleanup function. */\nexport const setupLinkTracking = (onLinkClicked: (info: LinkClickedInfo) => void): (() => void) => {\n if (typeof document === \"undefined\") return () => {}\n\n const handler = (event: MouseEvent) => {\n const node = event.target\n if (!(node instanceof Element)) return\n const anchor = node.closest(\"a[href]\")\n if (!(anchor instanceof HTMLAnchorElement)) return\n\n onLinkClicked({\n href: anchor.href,\n text: anchor.textContent?.trim() ?? \"\",\n target: anchor.target,\n })\n }\n\n document.addEventListener(\"click\", handler)\n return () => document.removeEventListener(\"click\", handler)\n}\n\n/** Picks the events endpoint, and disables analytics entirely on localhost (dev + simulator). */\nconst resolveAnalyticsEndpoint = (): { apiRoot: string; enabled: boolean } => {\n if (typeof window === \"undefined\" || !window.location) return { apiRoot: \"\", enabled: false }\n\n const hostname = window.location.hostname\n const isLocalhost =\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"[::1]\" ||\n hostname.endsWith(\".localhost\")\n\n if (isLocalhost) return { apiRoot: \"\", enabled: false }\n\n const isStaging = hostname.includes(\"staging\")\n return { apiRoot: isStaging ? \"https://api-staging.puzzmo.com/\" : \"https://api.puzzmo.com/\", enabled: true }\n}\n\n/** Derive the analytics context from the host's bootstrap data, or null if a game isn't present. */\nexport const buildAnalyticsContext = (readyData: BootstrapGameData | null, apiRoot: string): GameAnalyticsContext | null => {\n const session = readyData?.session\n if (!session) return null\n\n const gameplay = session.gameplay\n const puzzle: any = session.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n const embedContext = hostContext.find((hc) => hc?.type === \"embed\")\n\n return {\n gameSlug: readyData?.game?.slug || \"unknown\",\n puzzleID: puzzle.id,\n gameplayOwnerID: gameplay.ownerID || readyData?.userState?.id || \"unknown\",\n apiRoot,\n userType: mapUserType(readyData?.currentUser?.type),\n runtimeType: getRuntimeType(hostContext),\n userID: readyData?.currentUser?.id,\n teamSlug: puzzle.team?.slug || undefined,\n // Embeds carry their partner in the embed context; partner pages on puzzmo.com send it top-level\n partnerSlug: embedContext?.partner?.slug || readyData?.partnerSlug || undefined,\n dailyDateKey: puzzle.mostRecentDaily?.daily?.dateKey,\n embedID: embedContext?.embedID || undefined,\n }\n}\n\n/** Map the user's subscription tier to the analytics user bucket. */\nconst mapUserType = (type: string | null | undefined): UserType => {\n if (!type || type === \"Unverified\") return \"anon\"\n if (type === \"Paid\") return \"paid\"\n return \"user\"\n}\n\n// GameFlags1.bringsOwnRuntime — see packages/shared/flags/gameFlags.ts. Inlined to keep the SDK\n// free of the @puzzmo-com/shared workspace dep (the OSS mirror doesn't have that package).\nconst bringsOwnRuntimeFlag = 1 << 9\n\n/**\n * Whether the bootstrapped game has the \"brings own runtime\" flag set. SDK analytics only\n * run for these games; the standard Puzzmo runtime tracks the same events itself, so gating\n * here avoids double-counting for games that don't bring their own runtime.\n */\nconst gameBringsOwnRuntime = (readyData: BootstrapGameData | null): boolean => {\n const flagValue = readyData?.game?.version.flagsArr[0] ?? 0\n return (flagValue & bringsOwnRuntimeFlag) === bringsOwnRuntimeFlag\n}\n\n/** Derive the runtime bucket from host context, mirroring the runtime's getRuntimeType. */\nconst getRuntimeType = (hostContext: any[]): RuntimeType => {\n const embed = hostContext.find((hc) => hc?.type === \"embed\")\n if (embed) return embed.host === \"msn\" ? \"msn\" : \"iframe\"\n\n const app = hostContext.find((hc) => hc?.type === \"app\")\n if (app?.host === \"__embed\") return \"simple_embed\"\n if (app?.host === \"app-embed\") return \"app_embed\"\n if (app?.host === \"ios-app\") return \"ios_native\"\n\n return \"puzzmo_com\"\n}\n","import { normalizeReadyData } from \"./bootstrapPayload\"\nimport { createGameAnalytics, setupLinkTracking, type GameAnalyticsTracker } from \"./analytics\"\nimport type { PluginAPIs, SDKPlugin, SDKPluginContext } from \"./plugins\"\nimport type {\n MessagesSentFromEmbed,\n MessagesReceived,\n GamePlay,\n GameCompletedPlay,\n AugmentationConfig,\n CheckpointConfig,\n Theme,\n Deed,\n GameOverMessageUIComponent,\n KeyboardConfig,\n GameSettingsUIComponents,\n SettingsUIOverride,\n AvailableHaptics,\n} from \"./types\"\n\nexport type SDK = PuzzmoSDK\n\nexport interface PuzzmoSDKOptions<Plugins extends readonly SDKPlugin[] = []> {\n /** Optional timeout in ms to wait for READY_DATA (default: 5000) */\n timeout?: number\n /** Plugins to extend the SDK with; each contributes a namespaced API at `sdk.plugins[name]`. */\n plugins?: Plugins\n}\n\n/** The bootstrap info a game needs to set up its board, returned by `sdk.gameReady()`. */\nexport type GameReadyResult = {\n /**\n * \"puzzle\" when the host booted a puzzle session, \"repeatable\" when it booted the game alone for repeat\n * play. A repeatable game either makes its own boards or is handed one from its pool, and keeps its\n * state in `storage`.\n */\n mode: \"puzzle\" | \"repeatable\"\n /**\n * The serialized puzzle, in the game's own format. Null when the host sent none: a repeatable game\n * that makes its own boards, or another mode with no puzzle. In repeatable mode it is the first\n * puzzle from the game's pool.\n */\n puzzleString: string | null\n /** The pool key of a repeatable game's puzzle, to pass back with `completeRepeatableRun`. Null otherwise. */\n puzzleKey: string | null\n /** The player's saved in-progress board state from a previous session, or null when starting fresh. */\n inputString: string | null\n /** The host's current display theme, so the game can match the surrounding page. */\n theme: Theme | null\n /** True when the player has already finished this puzzle (e.g. re-opening a completed daily). False without a session. */\n completed: boolean\n /** The raw bootstrap payload from the host: user state, the gameplay record, host context, etc. */\n readyData: MessagesReceived[\"READY_DATA\"] | null\n}\n\n/** The question `sdk.confirm()` asks. */\nexport type SDKConfirmOptions = {\n title: string\n /** The explanation under the title. */\n text?: string\n /** The confirming button's text. Defaults to the host's \"OK\". */\n confirmLabel?: string\n /** The cancelling button's text. Defaults to the host's \"Cancel\". */\n cancelLabel?: string\n}\n\n/** Another puzzle from the game's pool, as `sdk.requestPuzzle()` resolves it. */\nexport type SDKPoolPuzzle = { puzzleKey: string; puzzleString: string }\n\n/** What `sdk.storage.get()` hands back: the payload as the game last wrote it, with the version it wrote it under. */\nexport type SDKStoredState = { state: string; stateVersion: number }\n\n/**\n * The game's own per-player store: unlocks, meta progression, an in-flight repeatable run. Opaque to\n * the host, whole-document, last write wins, 64 KB serialised. Not tied to a puzzle or a gameplay, so\n * it is there for play that has neither. Settings stay in `settings`; this is for durable game state.\n * Only kept in repeatable mode for now: a puzzle session's host does not save it, so writes there last\n * only until the page reloads.\n */\nexport interface SDKStorage {\n /** The payload the host handed over at boot, or null when this player has never written one. */\n get: () => SDKStoredState | null\n /**\n * Replace the stored payload. The host throttles the write and flushes on page hide, so calling\n * this on every move is fine; what the player loses in a crash is a couple of seconds. The\n * `stateVersion` is the game's own schema number, for migrating old payloads on read. Throws for a\n * state over 64 KB or a `stateVersion` below 1, which the host would refuse.\n */\n set: (state: string, stateVersion?: number) => void\n}\n\n/** A value a round event carries after its time */\nexport type SDKRoundEventValue = number | boolean | string | null\n\n/**\n * One entry in a round's log: its time in ms since the round started, then up to 7 values for the server bundle's\n * replay to read. Strings hold at most 64 characters: a pile name or an op, not a payload. The host drops an event\n * that breaks these rules, which leaves the round's log short of what happened, so its replay won't verify.\n */\nexport type SDKRoundEvent = readonly [number, ...SDKRoundEventValue[]]\n\n/**\n * Repeat-play rounds, which the server replays through the game's achievements parser to decide what the\n * player unlocked. A round runs from `start()` to `completeRepeatableRun()`; one the player walks away\n * from closes as abandoned when the next starts, or after a quiet day. While the page is open Puzzmo keeps the round\n * open, and if it closes anyway (a device asleep for over a day) Puzzmo boots the game again from the server.\n */\nexport interface SDKRounds {\n /**\n * A round begins: a fresh deal (`new`) or the same deal again from the top (`reset`). A pool game passes\n * the key of the puzzle the host drew for it; the server only verifies a round on a key it handed out.\n */\n start: (opts: { reason: \"new\" | \"reset\"; puzzleKey?: string }) => void\n /** Adds events to the round's log, in the order they happened. The host sends them on in batches. */\n log: (...events: SDKRoundEvent[]) => void\n /**\n * Picks the round back up for a deal resumed after a reload, instead of `start()`: `events` is the round's whole log\n * (`inProgress().events`), and later `log()` calls carry on from it. When the round closed after the\n * boot, the SDK emits `roundLost`: drop the deal and `start()` a new one, as nothing played on it can unlock anything.\n */\n resume: (opts: { puzzleKey?: string; events: readonly SDKRoundEvent[] }) => void\n /**\n * The deal the player left mid-way, as the server holds it: the round it has open, with its pool key and puzzle (null\n * for a game that makes its own), its log so far and the resets before it. The round is the only copy of a deal in\n * progress, so don't save one: rebuild the board by replaying `events` on the puzzle, then `resume()` with them. Null\n * when no round is open, or the open one has gone quiet for a day, and then the deal `gameReady()` handed over plays.\n */\n inProgress: () => SDKRoundInProgress | null\n}\n\n/** A deal left mid-way, as `rounds.inProgress()` hands it back */\nexport type SDKRoundInProgress = {\n puzzleKey: string | null\n puzzleString: string | null\n events: readonly SDKRoundEvent[]\n /** Resets of this deal before the round began */\n resets: number\n}\n\n/**\n * The table: other players playing alone together see this player's game beside theirs, drawn by the host from the\n * game's own thumbnail renderer, as anywhere else Puzzmo shows a thumbnail.\n */\nexport interface SDKTable {\n /**\n * What other players at the table see of this game: the same strings your thumbnail renderer takes, the input as\n * `updateGameState()` takes it. Nothing is stored, so keep saving as you do. Call it once the board is built, before\n * `gameLoaded()`, then on every change: neighbours only see a player once it has been called, so a game that waits\n * for the first move hides its player until then. Pass `puzzleString` on the first call and whenever the puzzle\n * changes (a new deal), and leave it out otherwise; the host sends the latest at most once a second.\n *\n * Others see a status line under the player's name: the round's clock, which the SDK adds itself, and `stat`, one\n * number the game chooses to share with its label ready to show, e.g. `{ value: 34, label: \"moves\" }`. Send it with\n * every call; a label is at most 16 characters.\n */\n updateGameState: (inputString: string, opts?: { puzzleString?: string; stat?: SDKTableStat }) => void\n}\n\n/** The one number a game shares at the table beside the round's clock, its label ready to show */\nexport type SDKTableStat = { value: number; label: string }\n\n/** An achievement the server decided a round unlocked, as the `achievementsUnlocked` event hands it over */\nexport type SDKUnlockedAchievement = {\n stableID: string\n name: string\n description: string\n icon: string\n /** How hard it is to earn */\n tier: \"Basic\" | \"Fancy\" | \"Rare\" | \"Mythic\"\n /** A Puzzmo achievement any game can offer, rather than one of this game's own */\n isSiteAchievement: boolean\n}\n\n/** Player-facing game settings, rendered by the host's settings panel and persisted per-user, per-game. */\nexport interface SDKSettings {\n /**\n * Register the game's settings UI with the host. Component `defaultValue`s are merged\n * underneath the player's saved values, the host shows the components in its settings panel,\n * and the resolved settings object is returned. Listen for the `settingsUpdate` event to\n * react to the player changing values. Call after `gameReady()`.\n *\n * In an embed, the partner's `settingsUIOverrides` for this game are applied first: an override\n * replaces fields of the component with its `id` (a new `defaultValue`, say), and `omit` hides\n * the component and locks the setting to its default, over anything the player saved.\n */\n initialize: (components: GameSettingsUIComponents[]) => any\n /** Get the current resolved settings object. */\n get: () => any\n /** Merge changes into the current settings and persist them to the host. Returns the updated settings. */\n update: (changes: any) => any\n /**\n * The components from `initialize()` with the embed's overrides applied, omitted ones marked\n * `hidden`. Draw an in-game settings UI from these rather than from your own list.\n */\n components: () => GameSettingsUIComponents[]\n}\n\n/** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\nexport interface SDKKeyboard {\n /** Show the on-screen keyboard with the given config. Call again to update state (e.g. to change disabled keys). */\n show: (config: KeyboardConfig) => void\n /** Hide the on-screen keyboard. */\n hide: () => void\n}\n\n/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => void\n}\n\n/**\n * The SDK instance returned by `createPuzzmoSDK` — a game's API surface for talking to whichever\n * host is embedding it (puzzmo.com, a partner embed, or the native apps): bootstrapping the\n * puzzle, syncing progress, reporting completion, and driving host UI like settings and the\n * on-screen keyboard.\n *\n * The expected lifecycle is: `gameReady()` → build your board from the result → `gameLoaded()` →\n * play, persisting via `updateGameState()` → `gameCompleted()` → `showCompletionScreen()`.\n */\nexport interface PuzzmoSDK<Plugins extends readonly SDKPlugin[] = []> {\n /**\n * The play clock. The SDK manages it for you: it starts when the host starts the game, pauses\n * and resumes with the host UI, and its display is mirrored into the host chrome twice a\n * second. Most games only need `addPenalty()` for hint or mistake costs.\n */\n timer: SDKTimer\n\n /** APIs contributed by the plugins passed to `createPuzzmoSDK`, keyed by plugin name. */\n plugins: PluginAPIs<Plugins>\n\n /**\n * Announce that the game is ready to receive data. Sends `READY` to the host and resolves with\n * the bootstrap info once the host replies: the puzzle to load, any saved in-progress state,\n * and the host theme. Call this first — every other API assumes it has resolved. Rejects when\n * the host doesn't reply within `PuzzmoSDKOptions.timeout` (default 5s).\n */\n gameReady: () => Promise<GameReadyResult>\n\n /**\n * Tell the host the game has parsed the puzzle, rendered, and is ready to be revealed. The\n * host dismisses its loading UI and replies with a start signal — listen via `on(\"start\")` to\n * begin play; the timer starts then too.\n */\n gameLoaded: (state?: any) => void\n\n /**\n * Subscribe to a host lifecycle event: `start`, `pause`, `resume`, `retry`, `settingsUpdate`,\n * or the on-screen `keyboard*` events. Returns an unsubscribe function.\n */\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => () => void\n\n /** Remove an event listener previously registered with `on`. */\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => void\n\n /**\n * Save the player's in-progress state to the server so play can resume later, on any\n * device. `inputString` is the game's own serialized format — it comes back as `inputString`\n * from `gameReady()`. Call whenever the player makes a meaningful move; elapsed time is filled\n * in from the SDK timer unless provided in `play`. Ignored, with a console warning, when there is\n * no gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => void\n\n /**\n * Report the game as finished. Concludes the timer, fills in elapsed/penalty time when not\n * provided, and uploads the final play plus its deeds — the host uses these for scoring,\n * leaderboards, stats, and other augmentations. Pass progress as `inputString` (the same\n * string `updateGameState()` takes). Follow with `showCompletionScreen()`. Without a play session\n * the result is still reported, with no gameplay ID, when the host negotiated contract \"1.1\" —\n * older hosts can't record one, so the message is dropped with a console warning.\n */\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => void\n\n /**\n * Ask the host to show its post-game completion UI. `results` render in the completion\n * sidebar: markdown congratulations, the player's streak stats, and custom stat rows. Call\n * after `gameCompleted()`, typically once your own victory animation has finished.\n */\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => void\n\n /**\n * Record a named mid-game checkpoint. Uploads the current board state and play time, and can\n * run parts of the completion pipeline early (e.g. posting to leaderboards) via\n * `checkpointConfig.process`. A checkpoint is also the host's opportunity to show an ad when\n * `checkpointConfig.interruptible` is true. Ignored, with a console warning, when there is no\n * gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => void\n\n /** Player-facing game settings, rendered in the host's settings panel and persisted per-user, per-game. */\n settings: SDKSettings\n\n /** The game's own durable per-player state, opaque to the host. See `SDKStorage`. */\n storage: SDKStorage\n\n /**\n * Report a finished run of a repeatable (Anytime) mode. Unlike `gameCompleted()` there is no gameplay behind it: the host records the run\n * against the player's counters for this game and nothing more. One page hosts many runs, so the SDK timer is not concluded; pass\n * `elapsedTimeSecs` for the run, else the timer's time since the previous run (or since it started, for the first) is used.\n * `config.deeds` ride along as they do on completion.\n */\n completeRepeatableRun: (play?: { elapsedTimeSecs?: number; puzzleKey?: string }, config?: AugmentationConfig) => void\n\n /** The rounds of repeat play, logged for the server to replay. See `SDKRounds`. */\n rounds: SDKRounds\n\n /** What other players at the table see of this game. See `SDKTable`. */\n table: SDKTable\n\n /**\n * Whether the host draws `confirm()`'s question over its whole page. Where it doesn't, ask with the game's own\n * dialog instead. Call after `gameReady()`.\n */\n canConfirm: () => boolean\n\n /**\n * Ask a yes/no question in a dialog the host draws over its whole page, so it dims what the host draws around the\n * game too (the table's neighbours, say). Resolves true when the player confirms. Only where `canConfirm()`;\n * elsewhere it warns and resolves false. A second call while one is showing answers the first with false.\n *\n * @example\n * const ok = sdk.canConfirm() ? await sdk.confirm({ title: \"Reset this deal?\", confirmLabel: \"Reset\" }) : await myOwnDialog()\n */\n confirm: (opts: SDKConfirmOptions) => Promise<boolean>\n\n /**\n * Ask the host for another puzzle from the game's pool, for a repeatable game whose puzzles come from\n * the host (the first arrives with `gameReady()`). Leave `buckets` out to draw from the whole pool, and\n * set it only when the game wants a particular kind of puzzle, such as difficulties chosen by the player:\n * the draw is uniform across whichever buckets it covers. `exclude` is the game's own recent keys, newest\n * last, which the host avoids while it can. Rejects when the game has no pool, a bucket does not exist,\n * or the host does not answer in time. A game that sends READY again is handed the last puzzle drawn, so\n * one that draws ahead should keep the puzzle in play in its storage rather than rely on the boot's.\n */\n requestPuzzle: (opts?: { buckets?: readonly string[]; exclude?: readonly string[] }) => Promise<SDKPoolPuzzle>\n\n /** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\n keyboard: SDKKeyboard\n\n /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\n\n /**\n * The raw postMessage transport to the host — an escape hatch for protocol messages the SDK\n * doesn't wrap.\n *\n * @internal\n */\n _hostAPI: {\n sendMessage: <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => void\n onMessage: <T extends keyof SupportedIncomingMessages>(type: T, handler: (data: SupportedIncomingMessages[T]) => void) => () => void\n }\n}\n\nexport type SupportedOutgoingMessages = Pick<\n MessagesSentFromEmbed,\n | \"READY\"\n | \"READY_GAME_LOADED\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"TIMER_TICK\"\n | \"TIMER_SYNC\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"UPDATE_GAME_USER_STATE\"\n | \"COMPLETE_REPEATABLE_RUN\"\n | \"START_REPEATABLE_ROUND\"\n | \"RESUME_REPEATABLE_ROUND\"\n | \"UPDATE_TABLE_GAME_STATE\"\n | \"APPEND_REPEATABLE_ROUND_LOG\"\n | \"REQUEST_PUZZLE\"\n | \"REQUEST_CONFIRM\"\n | \"HIT_CHECKPOINT\"\n | \"KEYBOARD_UPDATE_CONFIG\"\n | \"INITIALIZE_SETTINGS\"\n | \"UPDATE_SETTINGS_FROM_EMBED\"\n | \"SENSORY_EVENT\"\n>\n\nexport type SupportedIncomingMessages = Pick<\n MessagesReceived,\n | \"READY_DATA\"\n | \"START_GAME\"\n | \"PAUSE_GAME\"\n | \"RESUME_GAME\"\n | \"SETTINGS_UPDATE\"\n | \"RETRY_PUZZLE\"\n | \"KEYBOARD_KEY_PRESS\"\n | \"KEYBOARD_CURSOR_CHANGE\"\n | \"KEYBOARD_CURSOR_END\"\n | \"PUZZLE_DATA\"\n | \"ACHIEVEMENTS_UNLOCKED\"\n | \"REPEATABLE_ROUND_LOST\"\n | \"CONFIRM_ANSWER\"\n>\n\ntype MessageHandler<T extends keyof SupportedIncomingMessages> = (data: SupportedIncomingMessages[T]) => void\n\nexport type SDKEventMap = {\n start: void\n pause: void\n resume: void\n retry: void\n /** The player changed a setting in the host UI. The payload is the full resolved settings object. */\n settingsUpdate: any\n /** A key on the on-screen keyboard was tapped. */\n keyboardKeyPress: { key: string }\n /** The drag cursor moved across the keyboard. Only fires when `supportsDragCursor` is true. */\n keyboardCursorChange: { position: [number, number] }\n /** The drag cursor was released. Only fires when `supportsDragCursor` is true. */\n keyboardCursorEnd: void\n /** The repeat-play round in progress or just finished unlocked these. The host shows them over the game; a game need not. */\n achievementsUnlocked: { achievements: SDKUnlockedAchievement[] }\n /**\n * The deal passed to `rounds.resume()` has no round on the server, so nothing played on it can unlock an achievement.\n * Drop the deal and start a new one with `rounds.start({ reason: \"new\" })`. Not sent once the game has started a round.\n */\n roundLost: void\n}\n\nexport type SDKEventType = keyof SDKEventMap\n\nexport interface SDKTimer {\n /** Get elapsed time in milliseconds */\n timeMs: () => number\n /** Get elapsed time in seconds */\n timeSecs: () => number\n /** Get added/penalty time in milliseconds */\n addedTimeMs: () => number\n /** Get added/penalty time in seconds */\n addedTimeSecs: () => number\n /** Get elapsed time without penalties in seconds */\n timeWithoutPenaltySecs: () => number\n /** Get formatted display strings [elapsed, added] */\n display: () => [string, string]\n /** Add penalty time in milliseconds */\n addPenalty: (ms: number) => void\n /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (ms: number) => void\n /** Check if timer is paused */\n isPaused: () => boolean\n /** Check if timer has been started */\n isRunning: () => boolean\n /** Pause the timer (same as a host-sent PAUSE_GAME); emits \"pause\" on an actual transition. */\n pause: () => void\n /** Resume the timer (same as a host-sent RESUME_GAME); emits \"resume\" on an actual transition. */\n resume: () => void\n}\n\nfunction formatTime(timeMs: number): string {\n const isAnHourOrMore = timeMs >= 60 * 60 * 1000\n return new Date(timeMs)\n .toISOString()\n .slice(isAnHourOrMore ? 11 : 14, -1)\n .split(\".\")[0]\n}\n\nfunction createTimer(\n initialTimeMs = 0,\n initialAddedTimeMs = 0,\n): Omit<SDKTimer, \"pause\" | \"resume\"> & {\n _init: () => void\n _pause: () => void\n _resume: () => void\n _reset: (initialTimeMs?: number, initialAddedTimeMs?: number) => void\n _conclude: () => void\n} {\n let baseTime = initialTimeMs\n let addedTime = initialAddedTimeMs\n let pausedTime = 0\n let concludeTime: number | undefined\n\n let startDate: number | undefined = undefined\n let pausedDate: number | undefined = undefined\n\n const getTime = (): number => {\n if (startDate === undefined) return baseTime + addedTime\n if (concludeTime !== undefined) return concludeTime\n const now = pausedDate ?? performance.now()\n const elapsed = now - startDate - pausedTime\n return baseTime + addedTime + elapsed\n }\n\n return {\n _init: () => {\n if (startDate === undefined) {\n startDate = performance.now()\n pausedDate = undefined\n }\n },\n _pause: () => {\n if (pausedDate !== undefined || startDate === undefined) return\n pausedDate = performance.now()\n },\n _resume: () => {\n if (pausedDate === undefined) return\n pausedTime += performance.now() - pausedDate\n pausedDate = undefined\n },\n _reset: (newInitialTimeMs = 0, newInitialAddedTimeMs = 0) => {\n baseTime = newInitialTimeMs\n addedTime = newInitialAddedTimeMs\n pausedTime = 0\n concludeTime = undefined\n startDate = undefined\n pausedDate = undefined\n },\n _conclude: () => {\n if (pausedDate !== undefined) {\n concludeTime = getTime()\n return\n }\n if (startDate === undefined) {\n concludeTime = baseTime + addedTime\n return\n }\n concludeTime = getTime()\n },\n timeMs: () => getTime(),\n timeSecs: () => getTime() / 1000,\n addedTimeMs: () => addedTime,\n addedTimeSecs: () => addedTime / 1000,\n timeWithoutPenaltySecs: () => (getTime() - addedTime) / 1000,\n addPenalty: (ms: number) => {\n addedTime += ms\n },\n setPenalty: (ms: number) => {\n addedTime = ms\n },\n isPaused: () => pausedDate !== undefined || startDate === undefined,\n isRunning: () => startDate !== undefined && pausedDate === undefined,\n display: () => {\n const elapsed = getTime() - addedTime\n const elapsedStr = formatTime(Math.max(0, elapsed))\n const addedStr = addedTime === 0 ? \"\" : formatTime(addedTime)\n return [elapsedStr, addedStr]\n },\n }\n}\n\nfunction createHostAPI() {\n const messageHandlers = new Map<string, Set<(data: any) => void>>()\n const sendWatchers = new Map<string, Set<(json: any) => void>>()\n\n const sendMessage = <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => {\n const message = { type, json, _: \"p\", __: \"mp\", private: true }\n\n if (\"parent\" in window && window.parent !== window) window.parent.postMessage(message, \"*\")\n\n window.postMessage(message, \"*\")\n\n if (\"webkit\" in window && (window as any).webkit?.messageHandlers?.app) (window as any).webkit.messageHandlers.app.postMessage(message)\n\n if (\"puzzmoMessageString\" in window) (window as any).puzzmoMessageString(JSON.stringify(message))\n\n if (\"ReactNativeWebView\" in window && (window as any).ReactNativeWebView?.postMessage)\n (window as any).ReactNativeWebView.postMessage(JSON.stringify(message))\n\n if (type !== \"TIMER_TICK\" && type !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] sent:\", type, json)\n\n // A watcher runs inside the game's own call, so one that throws must not break it.\n sendWatchers.get(type)?.forEach((watcher) => {\n try {\n watcher(json)\n } catch (error) {\n console.error(`[Puzzmo SDK] a watcher of ${type} threw:`, error)\n }\n })\n }\n\n const onMessage = <T extends keyof SupportedIncomingMessages>(type: T, handler: MessageHandler<T>) => {\n if (!messageHandlers.has(type)) messageHandlers.set(type, new Set())\n messageHandlers.get(type)!.add(handler)\n\n return () => {\n messageHandlers.get(type)?.delete(handler)\n }\n }\n\n /** Runs `watcher` synchronously each time a message of `type` is sent. Returns an unsubscribe function. */\n const onSend = (type: string, watcher: (json: any) => void) => {\n if (!sendWatchers.has(type)) sendWatchers.set(type, new Set())\n sendWatchers.get(type)!.add(watcher)\n\n return () => {\n sendWatchers.get(type)?.delete(watcher)\n }\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", (event) => {\n if (!event?.data?.type) return\n const msgType = event.data.type as string\n const handlers = messageHandlers.get(msgType)\n if (handlers) {\n const msgData = event.data.data ?? event.data.json ?? {}\n if (msgType !== \"TIMER_TICK\" && msgType !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] received:\", msgType, msgData)\n handlers.forEach((handler) => handler(msgData))\n }\n })\n }\n\n return { sendMessage, onMessage, onSend }\n}\n\n/**\n * The host<->game contract this SDK speaks, declared in READY and READY_GAME_LOADED: games read\n * `game` and `session`, and handle `session` being absent. Hosts on \"1.0\" always send a session.\n */\nconst sdkRuntimeContract = \"1.1\"\n\nconst hostAPI = createHostAPI()\n\n/** A puzzle request covers a round trip to the API and a blob read, so it gets longer than READY_DATA */\nconst puzzleRequestTimeoutMs = 10_000\n\n/** Creates a Puzzmo SDK instance for communicating with the Puzzmo host */\nexport const createPuzzmoSDK = <const Plugins extends readonly SDKPlugin[] = []>(\n options: PuzzmoSDKOptions<Plugins> = {},\n): PuzzmoSDK<Plugins> => {\n let readyData: MessagesReceived[\"READY_DATA\"] | null = null\n let readyDataResolve: ((data: MessagesReceived[\"READY_DATA\"]) => void) | null = null\n\n const getGameplay = () => readyData?.session?.gameplay\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => readyData?.session?.puzzle.puzzle ?? readyData?.repeatablePuzzle?.puzzle ?? null\n const getBoardState = () => getGameplay()?.boardState ?? null\n const getTheme = () => readyData?.theme ?? null\n // Mirrors what the host holds, so get() reflects the game's own writes within a session\n let storedState: SDKStoredState | null = null\n let lastRunEndedAtSecs = 0\n // Where the open round began on the timer, for the table's clock; null when the game logs no rounds\n let roundStartedAtSecs: number | null = null\n // What the game last showed the table, sent again with a new clock when the timer pauses or resumes\n let lastTableState: { inputString: string; stat?: SDKTableStat } | null = null\n // Events logged in the round in progress, so each batch says where it starts and a resend is harmless\n let roundLogLength = 0\n // A resumed deal waiting on the host to find its round, so only it can be told the round is lost\n let awaitingResume = false\n let warnedStorageUnsaved = false\n const getCompleted = () => getGameplay()?.completed ?? false\n\n let warnedNoSession = false\n /** Warns once that a call was dropped: before READY_DATA arrived, or the host sent no play session */\n const warnNoSession = (method: string) => {\n if (warnedNoSession) return\n warnedNoSession = true\n const reason = readyData\n ? \"the host sent no play session, so there is no gameplay to save to\"\n : \"it was called before gameReady() resolved\"\n console.warn(`[Puzzmo SDK] ${method}() was ignored: ${reason}`)\n }\n\n const eventListeners = new Map<SDKEventType, Set<(data?: any) => void>>()\n\n // The resolved settings object — seeded from READY_DATA's saved values, then component\n // defaults are merged underneath when the game calls settings.initialize\n let currentSettings: any | null = null\n // What settings.initialize registered, after an embed's overrides\n let settingsComponents: GameSettingsUIComponents[] = []\n // Settings an embed has hidden, held at these values whatever the player saved\n let lockedSettings: Record<string, unknown> = {}\n const resolvedSettings = () => ({ ...currentSettings, ...lockedSettings })\n\n // ClickHouse game analytics — sends the same lifecycle events the runtime tracks\n // (page_view, gameplay_active, active_30s, completed, link_click). Disabled on localhost.\n let analytics: GameAnalyticsTracker | null = null\n let analyticsCompletedAtStart = false\n\n const trackAnalyticsEvent = (type: string, json?: any) => {\n // Don't re-send progression events for a game that was already completed when loaded\n if (analyticsCompletedAtStart) return\n analytics?.trackEvent(type, json)\n }\n\n const internalTimer = createTimer()\n let timerTickInterval: ReturnType<typeof setInterval> | null = null\n let timerSyncInterval: ReturnType<typeof setInterval> | null = null\n\n const startTimerIntervals = () => {\n if (timerTickInterval) return\n\n timerTickInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n const [elapsed, added] = internalTimer.display()\n hostAPI.sendMessage(\"TIMER_TICK\", { display: [elapsed, added] })\n }, 500)\n\n timerSyncInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n hostAPI.sendMessage(\"TIMER_SYNC\", Math.floor(internalTimer.timeWithoutPenaltySecs()))\n }, 10000)\n }\n\n const stopTimerIntervals = () => {\n if (timerTickInterval) {\n clearInterval(timerTickInterval)\n timerTickInterval = null\n }\n if (timerSyncInterval) {\n clearInterval(timerSyncInterval)\n timerSyncInterval = null\n }\n }\n\n const emit = <T extends SDKEventType>(event: T, data?: SDKEventMap[T]) => {\n const listeners = eventListeners.get(event)\n if (listeners) listeners.forEach((listener) => listener(data))\n }\n\n hostAPI.onMessage(\"START_GAME\", () => {\n internalTimer._init()\n startTimerIntervals()\n emit(\"start\")\n // A game shows the table its board before it starts, so its clock only starts here\n resendTableStatus()\n })\n\n // Shared by the host-sent PAUSE_GAME/RESUME_GAME messages and the game-initiated\n // sdk.timer.pause()/resume() below, so both paths stop/start the same timer identically.\n const pauseTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._pause()\n if (internalTimer.isPaused() !== wasPaused) emit(\"pause\")\n }\n const resumeTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._resume()\n if (internalTimer.isPaused() !== wasPaused) emit(\"resume\")\n }\n\n // The table's clock for the round on screen, from its start, or from the last run's end for a game logging no rounds\n const tableStatus = (stat?: SDKTableStat) => {\n const timerSecs = internalTimer.timeWithoutPenaltySecs()\n const from = roundStartedAtSecs ?? lastRunEndedAtSecs\n // A timer reset since (a retry restarts it) leaves it short of the start, so the clock reads from the reset\n const secs = Math.max(0, Math.floor(timerSecs >= from ? timerSecs - from : timerSecs))\n return { secs, running: !internalTimer.isPaused(), ...(stat ? { stat: { value: stat.value, label: stat.label } } : {}) }\n }\n // Neighbours' pages count the clock on themselves, so they hear when it stops and starts\n const resendTableStatus = () => {\n if (!lastTableState) return\n hostAPI.sendMessage(\"UPDATE_TABLE_GAME_STATE\", { inputString: lastTableState.inputString, status: tableStatus(lastTableState.stat) })\n }\n const pauseThenTell = () => {\n pauseTimer()\n resendTableStatus()\n }\n const resumeThenTell = () => {\n resumeTimer()\n resendTableStatus()\n }\n\n hostAPI.onMessage(\"PAUSE_GAME\", pauseThenTell)\n hostAPI.onMessage(\"RESUME_GAME\", resumeThenTell)\n\n hostAPI.onMessage(\"SETTINGS_UPDATE\", (data) => {\n currentSettings = { ...currentSettings, ...data }\n emit(\"settingsUpdate\", resolvedSettings())\n })\n\n hostAPI.onMessage(\"KEYBOARD_KEY_PRESS\", (data) => emit(\"keyboardKeyPress\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_CHANGE\", (data) => emit(\"keyboardCursorChange\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_END\", () => emit(\"keyboardCursorEnd\"))\n hostAPI.onMessage(\"ACHIEVEMENTS_UNLOCKED\", (data) => emit(\"achievementsUnlocked\", data))\n hostAPI.onMessage(\"REPEATABLE_ROUND_LOST\", () => {\n // The game may have started a new deal while the host was asking, and that one has a round of its own\n if (!awaitingResume) return\n awaitingResume = false\n emit(\"roundLost\")\n })\n\n // Puzzle requests in flight, by nonce, each settled by its PUZZLE_DATA or a timeout\n const puzzleRequests = new Map<string, { resolve: (puzzle: SDKPoolPuzzle) => void; reject: (error: Error) => void }>()\n let puzzleRequestCount = 0\n\n hostAPI.onMessage(\"PUZZLE_DATA\", (data) => {\n const request = puzzleRequests.get(data.nonce)\n if (!request) return\n puzzleRequests.delete(data.nonce)\n if (\"failed\" in data) request.reject(new Error(data.error))\n else request.resolve({ puzzleKey: data.puzzle.key, puzzleString: data.puzzle.puzzle })\n })\n\n // The question the host is showing, settled by its CONFIRM_ANSWER\n let pendingConfirm: { nonce: string; resolve: (confirmed: boolean) => void } | null = null\n let confirmCount = 0\n hostAPI.onMessage(\"CONFIRM_ANSWER\", (data) => {\n if (!pendingConfirm || pendingConfirm.nonce !== data.nonce) return\n const { resolve } = pendingConfirm\n pendingConfirm = null\n resolve(data.confirmed === true)\n })\n\n hostAPI.onMessage(\"RETRY_PUZZLE\", () => {\n internalTimer._reset()\n stopTimerIntervals()\n emit(\"retry\")\n })\n\n hostAPI.onMessage(\"READY_DATA\", (data) => {\n const bootstrapData = normalizeReadyData(data as MessagesReceived[\"READY_DATA\"])\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.session?.gameplay\n\n // userState.gameSettings is a map keyed by game slug; older records can hold the\n // value as a JSON string rather than an object\n if (currentSettings === null) {\n const gameSlug = bootstrapData.game.slug\n let saved = gameSlug ? bootstrapData.userState?.gameSettings?.[gameSlug] : null\n if (typeof saved === \"string\") {\n try {\n saved = JSON.parse(saved)\n } catch {\n saved = null\n }\n }\n currentSettings = saved ?? {}\n }\n if (gamePlayed) {\n const existingTime = (gamePlayed.elapsedTimeSecs ?? 0) * 1000\n const existingAddedTime = (gamePlayed.additionalTimeAddedSecs ?? 0) * 1000\n internalTimer._reset(existingTime, existingAddedTime)\n }\n\n // Wire up analytics once, from the first bootstrap payload\n if (!analytics) {\n analytics = createGameAnalytics(bootstrapData)\n analyticsCompletedAtStart = gamePlayed?.completed ?? false\n // Link clicks are tracked even for already-completed games, matching the runtime\n if (analytics) setupLinkTracking((info) => analytics!.trackLinkClick(info))\n }\n\n if (readyDataResolve) {\n readyDataResolve(bootstrapData)\n readyDataResolve = null\n }\n })\n\n const timer: SDKTimer = {\n timeMs: () => internalTimer.timeMs(),\n timeSecs: () => internalTimer.timeSecs(),\n addedTimeMs: () => internalTimer.addedTimeMs(),\n addedTimeSecs: () => internalTimer.addedTimeSecs(),\n timeWithoutPenaltySecs: () => internalTimer.timeWithoutPenaltySecs(),\n display: () => internalTimer.display(),\n addPenalty: (ms: number) => internalTimer.addPenalty(ms),\n setPenalty: (ms: number) => internalTimer.setPenalty(ms),\n isPaused: () => internalTimer.isPaused(),\n isRunning: () => internalTimer.isRunning(),\n pause: pauseThenTell,\n resume: resumeThenTell,\n }\n\n // Wire up plugins. Each gets the host transport (open to the full protocol), the timer, and\n // the bootstrap payload, and contributes a namespaced API onto `sdk.plugins[name]`.\n const pluginContext: SDKPluginContext = {\n send: (type, json) => hostAPI.sendMessage(type as keyof SupportedOutgoingMessages, json as never),\n on: (type, handler) => hostAPI.onMessage(type as keyof SupportedIncomingMessages, handler),\n onSend: hostAPI.onSend,\n timer,\n bootstrap: () => readyData,\n }\n const pluginAPIs: Record<string, unknown> = {}\n for (const plugin of options.plugins ?? []) pluginAPIs[plugin.name] = plugin.setup(pluginContext)\n\n return {\n timer,\n\n plugins: pluginAPIs as PluginAPIs<Plugins>,\n\n gameReady: async () => {\n hostAPI.sendMessage(\"READY\", { runtimeContract: sdkRuntimeContract })\n\n // READY_DATA may already be here, answering an earlier READY\n if (!readyData) {\n const timeout = options.timeout ?? 5000\n await new Promise<MessagesReceived[\"READY_DATA\"]>((resolve, reject) => {\n readyDataResolve = resolve\n setTimeout(() => {\n if (readyDataResolve) {\n readyDataResolve = null\n reject(new Error(`Timeout waiting for READY_DATA after ${timeout}ms`))\n }\n }, timeout)\n })\n }\n\n const inputString = getBoardState()\n const result: GameReadyResult = {\n mode: readyData?.repeatable ? \"repeatable\" : \"puzzle\",\n puzzleString: getPuzzleString(),\n puzzleKey: readyData?.repeatable ? (readyData.repeatablePuzzle?.key ?? null) : null,\n inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n // boardState is the pre-rename spelling of inputString, kept for untyped callers\n return { ...result, boardState: inputString } as GameReadyResult\n },\n\n gameLoaded: (state: any = {}) => {\n hostAPI.sendMessage(\"READY_GAME_LOADED\", {\n state,\n gameRuntimeContract: sdkRuntimeContract,\n embedRuntimeContract: \"1.0\",\n })\n trackAnalyticsEvent(\"READY_GAME_LOADED\")\n },\n\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void): (() => void) => {\n if (!eventListeners.has(event)) eventListeners.set(event, new Set())\n eventListeners.get(event)!.add(listener)\n return () => {\n eventListeners.get(event)?.delete(listener)\n }\n },\n\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => {\n eventListeners.get(event)?.delete(listener)\n },\n\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"updateGameState\")\n\n hostAPI.sendMessage(\"UPLOAD_NEW_GAME_STATE\", {\n id: gameplayID,\n input: {\n boardState: inputString,\n elapsedTimeSecs: play?.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play?.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n collabUserReferences: [],\n },\n })\n trackAnalyticsEvent(\"UPLOAD_NEW_GAME_STATE\")\n },\n\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => {\n internalTimer._conclude()\n stopTimerIntervals()\n\n // Games say inputString; the wire and database say boardState. Untyped callers\n // may still send the old boardState spelling, so keep accepting it at runtime.\n const { inputString, ...rest } = play\n const finalPlay: Partial<GamePlay> = {\n ...rest,\n boardState: inputString ?? (play as { boardState?: string }).boardState,\n elapsedTimeSecs: play.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n }\n\n const deeds: Deed[] = (config?.deeds as any) ?? []\n deeds.push({ id: \"points\", value: play.pointsAwarded })\n deeds.push({\n id: \"time\",\n value: Math.round(finalPlay.elapsedTimeSecs ?? 0) + Math.round(finalPlay.additionalTimeAddedSecs ?? 0),\n })\n\n const gameplayID = getGameplayID()\n // Without a session there's no gameplay ID; only hosts which negotiated \"1.1\" know to record\n // an id-less completion. A pre-1.1 host sending no gameplay is a host bug, not sessionless play.\n const sessionlessHost = readyData && !readyData.session && readyData.appRuntimeContract === \"1.1\"\n if (gameplayID || sessionlessHost) {\n hostAPI.sendMessage(\"GAME_COMPLETED\", {\n id: gameplayID ?? undefined,\n input: finalPlay,\n config,\n })\n trackAnalyticsEvent(\"GAME_COMPLETED\", { input: finalPlay })\n } else {\n warnNoSession(\"gameCompleted\")\n }\n },\n\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => {\n // showRetry stays in the message contract for a future host play-again button; no host renders one yet\n hostAPI.sendMessage(\"SHOW_GAME_COMPLETE_SCREEN\", { results, showRetry: true })\n },\n\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"hitCheckpoint\")\n\n const inputStr = getBoardState() ?? \"\"\n const play: Partial<GamePlay> = {\n elapsedTimeSecs: internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: internalTimer.addedTimeSecs(),\n }\n\n hostAPI.sendMessage(\"HIT_CHECKPOINT\", {\n checkpointName,\n gameplay: { inputStr, play },\n checkpointConfig,\n augConfig: config ?? {},\n })\n },\n\n completeRepeatableRun: (play?: { elapsedTimeSecs?: number; puzzleKey?: string }, config?: AugmentationConfig) => {\n // The timer runs on across runs, so a run's default time is measured from where the last one ended\n const timerSecs = internalTimer.timeWithoutPenaltySecs()\n const sinceLastRun = timerSecs >= lastRunEndedAtSecs ? timerSecs - lastRunEndedAtSecs : timerSecs\n lastRunEndedAtSecs = timerSecs\n const elapsedTimeSecs = Math.round(play?.elapsedTimeSecs ?? sinceLastRun)\n // The run's own time is the time deed; one the game passed would be a second, conflicting value\n const gameDeeds = ((config?.deeds as Deed[] | undefined) ?? []).filter((deed) => deed.id !== \"time\")\n const deedValues = [...gameDeeds, { id: \"time\", value: elapsedTimeSecs }]\n const puzzleKey = play?.puzzleKey\n hostAPI.sendMessage(\"COMPLETE_REPEATABLE_RUN\", { input: { deedValues, elapsedTimeSecs, ...(puzzleKey ? { puzzleKey } : {}) } })\n trackAnalyticsEvent(\"COMPLETE_REPEATABLE_RUN\", { elapsedTimeSecs })\n },\n\n rounds: {\n start: (opts) => {\n roundLogLength = 0\n roundStartedAtSecs = internalTimer.timeWithoutPenaltySecs()\n awaitingResume = false\n hostAPI.sendMessage(\"START_REPEATABLE_ROUND\", { reason: opts.reason, ...(opts.puzzleKey ? { puzzleKey: opts.puzzleKey } : {}) })\n },\n resume: (opts) => {\n roundLogLength = opts.events.length\n // The round has run as long as its last event, in ms from its start, so the clock carries on from there\n const lastEventMs = Number(opts.events[opts.events.length - 1]?.[0]) || 0\n roundStartedAtSecs = internalTimer.timeWithoutPenaltySecs() - lastEventMs / 1000\n awaitingResume = true\n hostAPI.sendMessage(\"RESUME_REPEATABLE_ROUND\", {\n events: opts.events.map((ev) => [...ev]),\n ...(opts.puzzleKey ? { puzzleKey: opts.puzzleKey } : {}),\n })\n },\n inProgress: () => {\n const open = readyData?.repeatableOpenRound\n if (!open || !Array.isArray(open.events)) return null\n return { puzzleKey: open.puzzleKey, puzzleString: open.puzzle, events: open.events, resets: open.resets }\n },\n log: (...events) => {\n if (!events.length) return\n hostAPI.sendMessage(\"APPEND_REPEATABLE_ROUND_LOG\", { from: roundLogLength, events: events.map((ev) => [...ev]) })\n roundLogLength += events.length\n },\n },\n\n table: {\n updateGameState: (inputString, opts) => {\n lastTableState = { inputString, ...(opts?.stat ? { stat: opts.stat } : {}) }\n hostAPI.sendMessage(\"UPDATE_TABLE_GAME_STATE\", {\n inputString,\n ...(opts?.puzzleString !== undefined ? { puzzleString: opts.puzzleString } : {}),\n status: tableStatus(opts?.stat),\n })\n },\n },\n\n requestPuzzle: (opts?: { buckets?: readonly string[]; exclude?: readonly string[] }) =>\n new Promise<SDKPoolPuzzle>((resolve, reject) => {\n const nonce = `puzzle-${++puzzleRequestCount}`\n const timer = setTimeout(() => {\n if (!puzzleRequests.delete(nonce)) return\n reject(new Error(`Timeout waiting for PUZZLE_DATA after ${puzzleRequestTimeoutMs}ms`))\n }, puzzleRequestTimeoutMs)\n const settle =\n <T>(fn: (value: T) => void) =>\n (value: T) => {\n clearTimeout(timer)\n fn(value)\n }\n puzzleRequests.set(nonce, { resolve: settle(resolve), reject: settle(reject) })\n hostAPI.sendMessage(\"REQUEST_PUZZLE\", {\n nonce,\n buckets: opts?.buckets ? [...opts.buckets] : undefined,\n exclude: opts?.exclude ? [...opts.exclude] : undefined,\n })\n }),\n\n canConfirm: () => readyData?.hostDialogs?.confirm === true,\n\n confirm: (opts: SDKConfirmOptions) =>\n new Promise<boolean>((resolve) => {\n if (readyData?.hostDialogs?.confirm !== true) {\n console.warn(\"[Puzzmo SDK] confirm() was answered no: this host draws no confirm dialog, check canConfirm() first\")\n resolve(false)\n return\n }\n // The host replaces a showing question with the new one, so the old one's answer is no\n pendingConfirm?.resolve(false)\n const nonce = `confirm-${++confirmCount}`\n pendingConfirm = { nonce, resolve }\n const { title, text, confirmLabel, cancelLabel } = opts\n hostAPI.sendMessage(\"REQUEST_CONFIRM\", { nonce, title, text, confirmLabel, cancelLabel })\n }),\n\n storage: {\n get: () => {\n if (storedState) return storedState\n const fromHost = readyData?.viewerStorage\n return fromHost && fromHost.state != null ? { state: fromHost.state, stateVersion: fromHost.stateVersion } : null\n },\n set: (state: string, stateVersion = 1) => {\n // The host's limits, checked here so a write it would refuse fails at the call instead of looking saved\n const sizeBytes = new TextEncoder().encode(state).length\n if (sizeBytes > storageMaxBytes) throw new Error(`[sdk.storage] State is ${sizeBytes} bytes, over the ${storageMaxBytes} byte cap`)\n if (!Number.isInteger(stateVersion) || stateVersion < 1) throw new Error(\"[sdk.storage] stateVersion must be a positive integer\")\n if (readyData && !readyData.repeatable && !warnedStorageUnsaved) {\n warnedStorageUnsaved = true\n console.warn(\"[sdk.storage] Only repeat play saves storage for now; this write lasts until the page reloads\")\n }\n storedState = { state, stateVersion }\n hostAPI.sendMessage(\"UPDATE_GAME_USER_STATE\", { state, stateVersion })\n },\n },\n\n settings: {\n initialize: (components: GameSettingsUIComponents[]) => {\n const overridden = applySettingsOverrides(components, embedSettingsOverrides(readyData))\n settingsComponents = overridden.components\n lockedSettings = overridden.locked\n currentSettings = { ...settingsDefaultsFromComponents(settingsComponents), ...currentSettings }\n const settings = resolvedSettings()\n hostAPI.sendMessage(\"INITIALIZE_SETTINGS\", { components: settingsComponents, settings })\n return settings\n },\n get: resolvedSettings,\n update: (changes: any) => {\n // Locked values stay out of what is saved, so the player's own choice outlives the embed's\n const unlocked = Object.entries(changes ?? {}).filter(([name]) => !(name in lockedSettings))\n currentSettings = { ...currentSettings, ...Object.fromEntries(unlocked) }\n hostAPI.sendMessage(\"UPDATE_SETTINGS_FROM_EMBED\", { settings: currentSettings })\n return resolvedSettings()\n },\n components: () => settingsComponents,\n },\n\n keyboard: {\n show: (config: KeyboardConfig) => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", config)\n },\n hide: () => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", {\n layout: [],\n symbols: {},\n highlight: [],\n disabled: [],\n xl: [],\n l: [],\n supportsDragCursor: false,\n })\n },\n },\n\n haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\n },\n },\n\n _hostAPI: hostAPI,\n }\n}\n\n/** Walks settings UI components (recursing into split groups) collecting name → defaultValue pairs */\nfunction settingsDefaultsFromComponents(components: GameSettingsUIComponents[]): Record<string, unknown> {\n const defaults: Record<string, unknown> = {}\n for (const component of components) {\n if (component.type === \"split\") Object.assign(defaults, settingsDefaultsFromComponents(component.content))\n else if (\"name\" in component) defaults[component.name] = component.defaultValue\n }\n return defaults\n}\n\n/** The settings overrides an embed's host context holds for this game, under the game's slug */\nfunction embedSettingsOverrides(data: MessagesReceived[\"READY_DATA\"] | null): SettingsUIOverride[] {\n const embed = data?.hostContext?.find((context) => context.type === \"embed\")\n const gameSlug = data?.game?.slug\n if (!embed || !gameSlug) return []\n\n const forGame = (embed as Record<string, unknown>)[gameSlug] as { settingsUIOverrides?: unknown } | undefined\n return Array.isArray(forGame?.settingsUIOverrides) ? forGame.settingsUIOverrides : []\n}\n\n/**\n * Applies an embed's overrides to the components they match by `id`, recursing into split groups.\n * `omit` marks the component `hidden`, and `locked` holds the value each omitted setting is kept at.\n */\nfunction applySettingsOverrides(components: GameSettingsUIComponents[], overrides: SettingsUIOverride[]) {\n const locked: Record<string, unknown> = {}\n if (!overrides.length) return { components, locked }\n\n const apply = (component: GameSettingsUIComponents, parentOmitted: boolean): GameSettingsUIComponents => {\n const { omit, ...patch } = overrides.find((override) => override.id === component.id) ?? { id: component.id }\n const omitted = parentOmitted || Boolean(omit)\n // The cast is for the spread, which widens the discriminated union\n const patched = { ...component, ...patch, ...(omitted ? { hidden: true } : {}) } as GameSettingsUIComponents\n\n if (patched.type === \"split\") return { ...patched, content: patched.content.map((inner) => apply(inner, omitted)) }\n if (omitted && \"name\" in patched) locked[patched.name] = patched.defaultValue\n return patched\n }\n\n return { components: components.map((component) => apply(component, false)), locked }\n}\n\n/** The largest state `sdk.storage.set()` takes, matching the API's cap */\nconst storageMaxBytes = 64 * 1024\n","import type { KeyboardConfig, KeyStyleRule, KeyStyles } from \"./types\"\n\n/**\n * A standard QWERTY layout with Enter and Backspace — a reasonable default for\n * any game that needs text input. Customize from here by spreading and overriding.\n *\n * @example\n * // Use as-is\n * sdk.keyboard.show(defaultKeyboardConfig)\n *\n * @example\n * // Extend with dynamic disabled letters\n * sdk.keyboard.show({ ...defaultKeyboardConfig, disabled: usedLetters })\n */\nexport const defaultKeyboardConfig: KeyboardConfig = {\n layout: [\"qwertyuiop\", \"asdfghjkl\", \"↵zxcvbnm⌫\", undefined],\n symbols: { \"↵\": \"enter\", \"⌫\": \"bsp\" },\n highlight: [\"↵\", \"⌫\"],\n disabled: [],\n xl: [],\n l: [\"↵\", \"⌫\"],\n supportsDragCursor: false,\n}\n\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\n}\n","// For now, we will keep these types in here but not mark them as something which should appear in the public SDK docs\n\nimport type { Theme } from \"./types\"\n\n/**\n * The theme passed to an editor bundle. The host sends its full {@link Theme} so editors derive\n * their colors from it rather than making their own theme decisions. Use `theme.type` for\n * light/dark bucketing.\n *\n * The bare `\"light\" | \"dark\"` string form is deprecated and will be removed in a future SDK\n * release — editors should handle the full `Theme` object.\n */\nexport type EditorTheme = Theme | \"light\" | \"dark\"\n\n/** Severity level for validation issues */\nexport type ValidationLevel = \"error\" | \"warning\" | \"info\"\n\n/** Represents a single validation issue found during puzzle validation */\nexport interface ValidationIssue {\n level: ValidationLevel\n message: string\n line?: number\n col?: number\n length?: number\n}\n\n/** Complete validation report for a puzzle */\nexport interface ValidationReport {\n success: boolean\n issues: ValidationIssue[]\n}\n\nexport type ImportErrorType = \"invalid_format\" | \"parsing_error\" | \"unknown\"\n\n/** Custom error class for workshop import failures */\nexport class EditorImportError extends Error {\n constructor(\n public type: ImportErrorType,\n message: string,\n public originalError?: unknown,\n ) {\n super(message)\n this.name = \"EditorImportError\"\n }\n}\n\n/** Result of a successful puzzle import operation */\nexport interface ImportResult {\n data: string\n warnings?: ValidationIssue[]\n title?: string\n authors?: string[]\n editors?: string[]\n}\n\n/** Settings UI descriptor returned by an editor bundle */\nexport interface EditorBundleSettings<TComponent = unknown> {\n components: TComponent[]\n defaults: Record<string, unknown>\n}\n\n/** A preceding/following phrase for a word, returned by the getRelatedWords editor callback */\nexport interface RelatedWord {\n word: string\n frequency: number\n position: \"preceding\" | \"following\"\n}\n\n/** One redirect followed while fetching a URL from within the editor */\nexport interface EditorFetchURLRedirect {\n /** The redirect's status code (301, 302, 307, ...) */\n status: number\n /** The URL which answered with the redirect */\n url: string\n}\n\n/**\n * Result of fetching a URL from within the editor. It resolves for any HTTP status, so check\n * `status` before trusting `body`; it only rejects when no response arrived at all.\n */\nexport interface EditorFetchURLResult {\n status: number\n body: string\n /** The reason phrase sent with the status, often empty over HTTP/2 */\n statusText?: string\n /** Response headers, with lower-cased names */\n headers?: Record<string, string>\n /** The URL which answered, after any redirects */\n url?: string\n /** Each redirect followed on the way to `url`, in order */\n redirects?: EditorFetchURLRedirect[]\n /** Milliseconds from the first request to the end of the body */\n durationMs?: number\n /** Size of the response body in bytes */\n bodyBytes?: number\n}\n\n/** Config passed to an editor bundle's mount() */\nexport interface EditorMountConfig {\n puzzleString: string\n onChange: (puzzleString: string) => void\n theme: EditorTheme\n width: number\n height: number\n /**\n * Optional function for making chat completions from the editor (e.g. for AI-assisted puzzle\n * editing). This needs to be enabled for a team explicitly.\n */\n chatCompletion?: (prompt: string) => Promise<string>\n /**\n * Optional function for fetching URLs from the editor (e.g. for fetching article content).\n * This needs to be enabled for a team explicitly.\n */\n fetchURL?: (url: string) => Promise<EditorFetchURLResult>\n /** Optional function for looking up a word's preceding/following phrases from wordvault. */\n getRelatedWords?: (word: string, limit?: number) => Promise<RelatedWord[]>\n /** Pre-configured editor settings values from the queue's editorSettings. */\n settings?: Record<string, unknown>\n}\n\n/** Handle returned by an editor bundle's mount() */\nexport interface EditorMountHandle {\n unmount: () => void\n /**\n * Called whenever the puzzle string is updated in the editor from the outside, or when the theme\n * or dimensions update. Workshop will rely on the validator to reject / accept updates.\n */\n update: (config: { puzzleString?: string; theme?: EditorTheme; width?: number; height?: number }) => void\n}\n\n/** Main interface for a Workshop editor bundle */\nexport interface EditorBundle<TSettingsComponent = unknown> {\n /** Required validator for puzzle data validation */\n validator: {\n validate(data: string): Promise<ValidationReport> | ValidationReport\n }\n /** Optional importer for converting external puzzle file formats */\n importer?: {\n onImport(filename: string, contents: string | ArrayBuffer): Promise<ImportResult> | ImportResult\n }\n /** Embed-level settings UI, populated from the bundle's declared settings */\n settings?: EditorBundleSettings<TSettingsComponent>\n /** Editor-level settings UI, populated from the bundle's declared editor settings */\n editorSettings?: EditorBundleSettings<TSettingsComponent>\n /** Custom puzzle editor, if provided by the bundle */\n editor?: {\n /** Called when first visiting a puzzle page. */\n mount(element: HTMLElement, config: EditorMountConfig): Promise<EditorMountHandle>\n }\n}\n"],"mappings":";;;SAoBU,sBAAA,EAAA,IAAA,CAOA,SAAA,EAAA,IAAA,CACA,QAAa,iBAAA;;;;;;AATvB,MAAa,KAAsB,MAAyC;;CAC1E,IAAM,EAAE,2BAAA,GAAwB,IAAA,EAAS,GAAA,EAAA;AACzC,KAAI,EAAK,KAAM,QAAO;CAEtB,IAAM,IAAA,KAAA,OAAA,KAAA,IAAa,EAAqB,YAClC,IAAO,GAAA,IAAA,KAAA,SAAA,IAAe,EAAY,WAAA,OAAA,KAAA,IAAA,EAAQ,SAAA,OAAQ,EAAE,GAAV,EAAW;AAC3D,KAAI,CAAC,EAAY,QAAA,EAAA,EAAA,EAAA,EAAY,EAAA,EAAA,EAAA,EAAA,EAAM,SAAA,CAAM;CAEzC,IAAM,EAAE,cAAA,GAAW,IAAA,EAAa,GAAA,EAAA,EAC1B,EAAE,MAAM,GAAO,sBAAA,GAAmB,IAAA,EAAiB,GAAA,EAAA;AACzD,QAAA,EAAA,EAAA,EAAA,EAAY,EAAA,EAAA,EAAA,EAAA;EAAM;EAAM,SAAS;GAAE;GAAU,QAAQ;GAAc;EAAE,iBAAA,IAAgB,EAAK,mBAAA,OAAkB,IAAlB;GAAkC;;;AAI9H,IAA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AAK,MAAc,EAAM,GAAW,GAAM,CAAC;EAAE;EAAQ;;;AAIvF,IAAM,IAAkB,KAAK;;;;;;;;;;;;;ACvrC7B,MAAa,IAAwC;CACnD,QAAQ;EAAC;EAAc;EAAa;EAAa,KAAA;EAAU;CAC3D,SAAS;EAAE,KAAK;EAAS,KAAK;EAAO;CACrC,WAAW,CAAC,KAAK,IAAI;CACrB,UAAU,EAAE;CACZ,IAAI,EAAE;CACN,GAAG,CAAC,KAAK,IAAI;CACb,oBAAoB;CACrB,EAYY,KAAsB,MAAqD;CACtF,IAAM,IAAoC,EAAE;AAC5C,MAAK,IAAM,KAAQ,EACjB,MAAK,IAAM,KAAO,EAAK,MAAM;;EAC3B,IAAM,IAAoB,EAAE,EACtB,IAAA,EAAA,EAAA,EAAA,GAAA,IAAY,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,KAAA,EAAS,EAAK,KAAM,EAC7C,IAAA,EAAA,EAAA,EAAA,GAAA,IAAkB,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,WAAA,EAAe,EAAK,WAAY;AAKrE,EAFI,OAAO,KAAK,EAAK,CAAC,WAAQ,EAAO,OAAO,IACxC,OAAO,KAAK,EAAW,CAAC,WAAQ,EAAO,aAAa,IACxD,EAAO,KAAO;;AAGlB,QAAO;;;ACbT,IAAa,IAAb,cAAuC,MAAM;CAC3C,YACE,GACA,GACA,GACA;AAEA,EADA,MAAM,EAAQ,EAJP,KAAA,OAAA,GAEA,KAAA,gBAAA,GAGP,KAAK,OAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/bootstrapPayload.ts","../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts"],"sourcesContent":["import type { BootstrapGame, BootstrapGameData, BootstrapSession } from \"./types\"\n\n/**\n * READY_DATA as hosts from before the payload split send it: the gameplay with the puzzle nested\n * inside it, and a flattened game inside that. Deliberately not part of the SDK's public types.\n */\ntype LegacyReadyData = Omit<BootstrapGameData, \"game\" | \"session\"> & {\n game?: BootstrapGame\n session?: BootstrapSession\n startOrFindGameplay?: {\n gamePlayed?: BootstrapSession[\"gameplay\"] & { puzzle: BootstrapSession[\"puzzle\"] & { game?: any; viewerMetadata?: unknown } }\n }\n}\n\n/**\n * Fills in `game` and `session` when READY_DATA comes from a host which only sends the older\n * `startOrFindGameplay` nesting, so the SDK and games only ever see the new shape. A copy of\n * upgradeBootstrapGameData in @puzzmo-com/shared, which the SDK can't depend on.\n */\nexport const normalizeReadyData = (received: unknown): BootstrapGameData => {\n const { startOrFindGameplay, ...data } = received as LegacyReadyData\n if (data.game) return data as BootstrapGameData\n\n const gamePlayed = startOrFindGameplay?.gamePlayed\n const game = gameFromLegacy(gamePlayed?.puzzle?.game ?? {})\n if (!gamePlayed) return { ...data, game }\n\n const { puzzle, ...gameplay } = gamePlayed\n const { game: _game, viewerMetadata, ...puzzleFields } = puzzle\n return { ...data, game, session: { gameplay, puzzle: puzzleFields }, viewerMetadata: data.viewerMetadata ?? viewerMetadata }\n}\n\n/** Builds the game from the flattened fields older hosts put on `puzzle.game`, with no version IDs */\nconst gameFromLegacy = (game: any): BootstrapGame => {\n const flags = game.flagsArr\n return {\n id: game.id ?? \"\",\n slug: game.slug ?? \"\",\n stableSlug: game.stableSlug ?? game.slug ?? \"\",\n displayName: game.displayName ?? \"\",\n version: {\n id: \"\",\n label: null,\n featuresArr: game.featuresArr ?? [0],\n flagsArr: Array.isArray(flags) ? flags : typeof flags === \"number\" ? [flags] : [0],\n runtime: {\n id: \"\",\n version:\n game.assetsSha || game.assetsBaseURL\n ? { id: \"\", assetsSha: game.assetsSha ?? \"\", assetsBaseURL: game.assetsBaseURL ?? \"\" }\n : null,\n },\n },\n }\n}\n","import type { DeviceType, GameAnalyticsContext, LinkClickedInfo } from \"./analytics\"\n\n/**\n * Game analytics event-firing logic for the SDK.\n *\n * This mirrors the runtime's tracker (and the canonical copy in @puzzmo-com/clickhouse/gameTracker\n * used server-side): which host messages map to which events, the engagement thresholds, the\n * payload shape, and the /events endpoint. It is kept here, dependency-free, so the published SDK\n * pulls in none of the clickhouse package's server deps (kysely / @clickhouse/client) and so the\n * public OSS mirror can build it without the private workspace packages present.\n */\n\nexport type GameAnalyticsEventType = \"page_view\" | \"gameplay_active\" | \"active_30s\" | \"completed\" | \"link_click\"\n\ntype GameAnalyticsState = {\n context: GameAnalyticsContext\n updateCount: number\n startTime: Date\n tracked: {\n pageView: boolean\n gameplayActive: boolean\n active30s: boolean\n completed: boolean\n }\n}\n\ntype MessagesSent =\n | \"READY_GAME_LOADED\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"UPDATE_GAME_STATE\"\n | string\n\nconst sendGameAnalyticsEvent = async (\n context: GameAnalyticsContext,\n eventType: GameAnalyticsEventType,\n metadata?: Record<string, string | number | boolean>,\n elapsedTimeOnComplete?: number,\n) => {\n try {\n const body = {\n ...context,\n eventType,\n elapsedTimeOnComplete,\n metadata,\n }\n\n const response = await fetch(`${context.apiRoot}events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n // Ensures the event still fires if the user navigates away (e.g. clicking a _blank link)\n keepalive: true,\n })\n\n if (!response.ok) {\n console.warn(`Analytics event failed: ${eventType} - ${response.status} ${response.statusText}`)\n }\n } catch (error) {\n console.warn(`Analytics event error: ${eventType}`, error)\n }\n}\n\nexport const createGameAnalyticsTracker = (context: GameAnalyticsContext) => {\n const state: GameAnalyticsState = {\n context: { ...context, deviceType: context.deviceType ?? detectDeviceType() },\n updateCount: 0,\n startTime: new Date(),\n tracked: {\n pageView: false,\n gameplayActive: false,\n active30s: false,\n completed: false,\n },\n }\n\n const trackEvent = (type: MessagesSent, json?: any) => {\n const now = new Date()\n const timeDiff = now.getTime() - state.startTime.getTime()\n const seconds = timeDiff / 1000\n\n switch (type) {\n case \"READY_GAME_LOADED\": {\n if (!state.tracked.pageView) {\n sendGameAnalyticsEvent(state.context, \"page_view\")\n state.tracked.pageView = true\n }\n break\n }\n\n case \"UPLOAD_NEW_GAME_STATE\": {\n state.updateCount++\n\n // Fire gameplay_active early (after 2 state changes) to indicate user engagement\n if (state.updateCount > 2 && !state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n\n // Fire active_30s for sustained engagement\n if (seconds > 30) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\n }\n break\n }\n\n case \"GAME_COMPLETED\": {\n if (!state.tracked.completed && json?.input) {\n sendGameAnalyticsEvent(state.context, \"completed\", {}, json.input.elapsedTimeSecs)\n state.tracked.completed = true\n }\n break\n }\n }\n }\n\n const trackLinkClick = (info: LinkClickedInfo) => {\n sendGameAnalyticsEvent(state.context, \"link_click\", info)\n }\n\n return {\n trackEvent,\n trackLinkClick,\n }\n}\n\n/**\n * The kind of device the game runs on, judged by the whole device rather than the game's frame. A copy of\n * detectDeviceType in @puzzmo-com/clickhouse/deviceType, kept dependency-free for the published SDK.\n */\nconst detectDeviceType = (): DeviceType => {\n if (typeof navigator === \"undefined\" || typeof window === \"undefined\") return \"unknown\"\n const userAgent = navigator.userAgent\n\n // iPadOS Safari reports itself as a Mac, so only a touchscreen gives it away\n if (/iPad/.test(userAgent) || (/Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1)) return \"tablet\"\n const mobileHint = (navigator as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData?.mobile\n if (/iPhone|iPod/.test(userAgent) || mobileHint) return \"mobile\"\n // Android phones carry \"Mobile\", Android tablets leave it out\n if (/Android/.test(userAgent)) return /Mobile/.test(userAgent) ? \"mobile\" : \"tablet\"\n if (/Mobile|Windows Phone/.test(userAgent)) return \"mobile\"\n\n // Anything else whose main input is touch, sized by the screen's short side\n if (window.matchMedia?.(\"(pointer: coarse)\").matches) return Math.min(screen.width, screen.height) < 600 ? \"mobile\" : \"tablet\"\n return \"desktop\"\n}\n","import { createGameAnalyticsTracker } from \"./gameTracker\"\n\nimport type { BootstrapGameData } from \"./types\"\n\n/**\n * Game analytics for the SDK.\n *\n * The event-firing logic — which host messages map to which ClickHouse events, the\n * engagement thresholds, the payload, and the /events endpoint — lives in ./gameTracker,\n * a self-contained mirror of the runtime's tracker. It is kept local (rather than imported\n * from @puzzmo-com/clickhouse) so the published SDK pulls in none of the clickhouse package's\n * server deps, and so the public OSS mirror can build the SDK without the private workspace\n * packages present.\n *\n * This file only adds the SDK-specific glue: deciding whether analytics should run,\n * building the context from bootstrap data, and watching for link clicks. Events are\n * never sent from localhost (dev + the SDK simulator).\n */\n\nexport type LinkClickedInfo = {\n href: string\n text: string\n target: string\n}\n\ntype UserType = \"anon\" | \"user\" | \"paid\"\ntype RuntimeType = \"puzzmo_com\" | \"iframe\" | \"simple_embed\" | \"app_embed\" | \"ios_native\" | \"msn\"\n\n/** Everything the events endpoint needs to attribute an event, mirrors the runtime's context. */\nexport type GameAnalyticsContext = {\n gameSlug: string\n puzzleID: string\n gameplayOwnerID: string\n apiRoot: string\n userType: UserType\n runtimeType: RuntimeType\n userID?: string\n teamSlug?: string\n partnerSlug?: string\n dailyDateKey?: string\n embedID?: string\n /** Defaults to the device the game is running on, see detectDeviceType in ./gameTracker */\n deviceType?: DeviceType\n}\n\n/** Matches the device_type column in ClickHouse, the API classifies events which leave it out */\nexport type DeviceType = \"unknown\" | \"mobile\" | \"tablet\" | \"desktop\"\n\nexport type GameAnalyticsTracker = {\n /** Map an outgoing host message to its analytics event(s), if any. */\n trackEvent: (type: string, json?: any) => void\n /** Report an anchor click inside the game. */\n trackLinkClick: (info: LinkClickedInfo) => void\n}\n\n/**\n * Build the analytics tracker for a game, or null when analytics shouldn't run\n * (the game doesn't bring its own runtime, no browser, running on localhost, or\n * missing bootstrap data).\n */\nexport const createGameAnalytics = (readyData: BootstrapGameData | null): GameAnalyticsTracker | null => {\n // Only games that bring their own runtime track via the SDK — see gameBringsOwnRuntime.\n if (!gameBringsOwnRuntime(readyData)) return null\n\n const endpoint = resolveAnalyticsEndpoint()\n if (!endpoint.enabled) return null\n\n const context = buildAnalyticsContext(readyData, endpoint.apiRoot)\n if (!context) return null\n\n return createGameAnalyticsTracker(context)\n}\n\n/** Delegates document clicks to report anchor navigations. Returns a cleanup function. */\nexport const setupLinkTracking = (onLinkClicked: (info: LinkClickedInfo) => void): (() => void) => {\n if (typeof document === \"undefined\") return () => {}\n\n const handler = (event: MouseEvent) => {\n const node = event.target\n if (!(node instanceof Element)) return\n const anchor = node.closest(\"a[href]\")\n if (!(anchor instanceof HTMLAnchorElement)) return\n\n onLinkClicked({\n href: anchor.href,\n text: anchor.textContent?.trim() ?? \"\",\n target: anchor.target,\n })\n }\n\n document.addEventListener(\"click\", handler)\n return () => document.removeEventListener(\"click\", handler)\n}\n\n/** Picks the events endpoint, and disables analytics entirely on localhost (dev + simulator). */\nconst resolveAnalyticsEndpoint = (): { apiRoot: string; enabled: boolean } => {\n if (typeof window === \"undefined\" || !window.location) return { apiRoot: \"\", enabled: false }\n\n const hostname = window.location.hostname\n const isLocalhost =\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"[::1]\" ||\n hostname.endsWith(\".localhost\")\n\n if (isLocalhost) return { apiRoot: \"\", enabled: false }\n\n const isStaging = hostname.includes(\"staging\")\n return { apiRoot: isStaging ? \"https://api-staging.puzzmo.com/\" : \"https://api.puzzmo.com/\", enabled: true }\n}\n\n/** Derive the analytics context from the host's bootstrap data, or null if a game isn't present. */\nexport const buildAnalyticsContext = (readyData: BootstrapGameData | null, apiRoot: string): GameAnalyticsContext | null => {\n const session = readyData?.session\n if (!session) return null\n\n const gameplay = session.gameplay\n const puzzle: any = session.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n const embedContext = hostContext.find((hc) => hc?.type === \"embed\")\n\n return {\n gameSlug: readyData?.game?.slug || \"unknown\",\n puzzleID: puzzle.id,\n gameplayOwnerID: gameplay.ownerID || readyData?.userState?.id || \"unknown\",\n apiRoot,\n userType: mapUserType(readyData?.currentUser?.type),\n runtimeType: getRuntimeType(hostContext),\n userID: readyData?.currentUser?.id,\n teamSlug: puzzle.team?.slug || undefined,\n // Embeds carry their partner in the embed context; partner pages on puzzmo.com send it top-level\n partnerSlug: embedContext?.partner?.slug || readyData?.partnerSlug || undefined,\n dailyDateKey: puzzle.mostRecentDaily?.daily?.dateKey,\n embedID: embedContext?.embedID || undefined,\n }\n}\n\n/** Map the user's subscription tier to the analytics user bucket. */\nconst mapUserType = (type: string | null | undefined): UserType => {\n if (!type || type === \"Unverified\") return \"anon\"\n if (type === \"Paid\") return \"paid\"\n return \"user\"\n}\n\n// GameFlags1.bringsOwnRuntime — see packages/shared/flags/gameFlags.ts. Inlined to keep the SDK\n// free of the @puzzmo-com/shared workspace dep (the OSS mirror doesn't have that package).\nconst bringsOwnRuntimeFlag = 1 << 9\n\n/**\n * Whether the bootstrapped game has the \"brings own runtime\" flag set. SDK analytics only\n * run for these games; the standard Puzzmo runtime tracks the same events itself, so gating\n * here avoids double-counting for games that don't bring their own runtime.\n */\nconst gameBringsOwnRuntime = (readyData: BootstrapGameData | null): boolean => {\n const flagValue = readyData?.game?.version.flagsArr[0] ?? 0\n return (flagValue & bringsOwnRuntimeFlag) === bringsOwnRuntimeFlag\n}\n\n/** Derive the runtime bucket from host context, mirroring the runtime's getRuntimeType. */\nconst getRuntimeType = (hostContext: any[]): RuntimeType => {\n const embed = hostContext.find((hc) => hc?.type === \"embed\")\n if (embed) return embed.host === \"msn\" ? \"msn\" : \"iframe\"\n\n const app = hostContext.find((hc) => hc?.type === \"app\")\n if (app?.host === \"__embed\") return \"simple_embed\"\n if (app?.host === \"app-embed\") return \"app_embed\"\n if (app?.host === \"ios-app\") return \"ios_native\"\n\n return \"puzzmo_com\"\n}\n","import { normalizeReadyData } from \"./bootstrapPayload\"\nimport { createGameAnalytics, setupLinkTracking, type GameAnalyticsTracker } from \"./analytics\"\nimport type { PluginAPIs, SDKPlugin, SDKPluginContext } from \"./plugins\"\nimport type {\n MessagesSentFromEmbed,\n MessagesReceived,\n GamePlay,\n GameCompletedPlay,\n AugmentationConfig,\n CheckpointConfig,\n Theme,\n Deed,\n GameOverMessageUIComponent,\n KeyboardConfig,\n GameSettingsUIComponents,\n SettingsUIOverride,\n AvailableHaptics,\n} from \"./types\"\n\nexport type SDK = PuzzmoSDK\n\nexport interface PuzzmoSDKOptions<Plugins extends readonly SDKPlugin[] = []> {\n /** Optional timeout in ms to wait for READY_DATA (default: 5000) */\n timeout?: number\n /** Plugins to extend the SDK with; each contributes a namespaced API at `sdk.plugins[name]`. */\n plugins?: Plugins\n}\n\n/** The bootstrap info a game needs to set up its board, returned by `sdk.gameReady()`. */\nexport type GameReadyResult = {\n /**\n * \"puzzle\" when the host booted a puzzle session, \"repeatable\" when it booted the game alone for repeat\n * play. A repeatable game either makes its own boards or is handed one from its pool, and keeps its\n * state in `storage`.\n */\n mode: \"puzzle\" | \"repeatable\"\n /**\n * The serialized puzzle, in the game's own format. Null when the host sent none: a repeatable game\n * that makes its own boards, or another mode with no puzzle. In repeatable mode it is the first\n * puzzle from the game's pool.\n */\n puzzleString: string | null\n /** The pool key of a repeatable game's puzzle, to pass back with `completeRepeatableRun`. Null otherwise. */\n puzzleKey: string | null\n /** The player's saved in-progress board state from a previous session, or null when starting fresh. */\n inputString: string | null\n /** The host's current display theme, so the game can match the surrounding page. */\n theme: Theme | null\n /** True when the player has already finished this puzzle (e.g. re-opening a completed daily). False without a session. */\n completed: boolean\n /** The raw bootstrap payload from the host: user state, the gameplay record, host context, etc. */\n readyData: MessagesReceived[\"READY_DATA\"] | null\n}\n\n/** The question `sdk.confirm()` asks. */\nexport type SDKConfirmOptions = {\n title: string\n /** The explanation under the title. */\n text?: string\n /** The confirming button's text. Defaults to the host's \"OK\". */\n confirmLabel?: string\n /** The cancelling button's text. Defaults to the host's \"Cancel\". */\n cancelLabel?: string\n}\n\n/** Another puzzle from the game's pool, as `sdk.requestPuzzle()` resolves it. */\nexport type SDKPoolPuzzle = { puzzleKey: string; puzzleString: string }\n\n/** What `sdk.storage.get()` hands back: the payload as the game last wrote it, with the version it wrote it under. */\nexport type SDKStoredState = { state: string; stateVersion: number }\n\n/**\n * The game's own per-player store: unlocks, meta progression, an in-flight repeatable run. Opaque to\n * the host, whole-document, last write wins, 64 KB serialised. Not tied to a puzzle or a gameplay, so\n * it is there for play that has neither. Settings stay in `settings`; this is for durable game state.\n * Only kept in repeatable mode for now: a puzzle session's host does not save it, so writes there last\n * only until the page reloads.\n */\nexport interface SDKStorage {\n /** The payload the host handed over at boot, or null when this player has never written one. */\n get: () => SDKStoredState | null\n /**\n * Replace the stored payload. The host throttles the write and flushes on page hide, so calling\n * this on every move is fine; what the player loses in a crash is a couple of seconds. The\n * `stateVersion` is the game's own schema number, for migrating old payloads on read. Throws for a\n * state over 64 KB or a `stateVersion` below 1, which the host would refuse.\n */\n set: (state: string, stateVersion?: number) => void\n}\n\n/** A value a round event carries after its time */\nexport type SDKRoundEventValue = number | boolean | string | null\n\n/**\n * One entry in a round's log: its time in ms since the round started, then up to 7 values for the server bundle's\n * replay to read. Strings hold at most 64 characters: a pile name or an op, not a payload. The host drops an event\n * that breaks these rules, which leaves the round's log short of what happened, so its replay won't verify.\n */\nexport type SDKRoundEvent = readonly [number, ...SDKRoundEventValue[]]\n\n/**\n * Repeat-play rounds, which the server replays through the game's achievements parser to decide what the\n * player unlocked. A round runs from `start()` to `completeRepeatableRun()`; one the player walks away\n * from closes as abandoned when the next starts, or after a quiet day. While the page is open Puzzmo keeps the round\n * open, and if it closes anyway (a device asleep for over a day) Puzzmo boots the game again from the server.\n */\nexport interface SDKRounds {\n /**\n * A round begins: a fresh deal (`new`) or the same deal again from the top (`reset`). A pool game passes\n * the key of the puzzle the host drew for it; the server only verifies a round on a key it handed out.\n */\n start: (opts: { reason: \"new\" | \"reset\"; puzzleKey?: string }) => void\n /** Adds events to the round's log, in the order they happened. The host sends them on in batches. */\n log: (...events: SDKRoundEvent[]) => void\n /**\n * Picks the round back up for a deal resumed after a reload, instead of `start()`: `events` is the round's whole log\n * (`inProgress().events`, not a copy the game saved), and later `log()` calls carry on from it. When the round closed\n * after the boot, or `events` is shorter than the server's log, the SDK emits `roundLost`: drop the deal and `start()`\n * a new one, as nothing played on it can unlock anything.\n */\n resume: (opts: { puzzleKey?: string; events: readonly SDKRoundEvent[] }) => void\n /**\n * The deal the player left mid-way, as the server holds it: the round it has open, with its pool key and puzzle (null\n * for a game that makes its own), its log so far and the resets before it. The round is the only copy of a deal in\n * progress, so don't save one: rebuild the board by replaying `events` on the puzzle, then `resume()` with them. Null\n * when no round is open, or the open one has gone quiet for a day, and then the deal `gameReady()` handed over plays.\n */\n inProgress: () => SDKRoundInProgress | null\n}\n\n/** A deal left mid-way, as `rounds.inProgress()` hands it back */\nexport type SDKRoundInProgress = {\n puzzleKey: string | null\n puzzleString: string | null\n events: readonly SDKRoundEvent[]\n /** Resets of this deal before the round began */\n resets: number\n}\n\n/**\n * The table: other players playing alone together see this player's game beside theirs, drawn by the host from the\n * game's own thumbnail renderer, as anywhere else Puzzmo shows a thumbnail.\n */\nexport interface SDKTable {\n /**\n * What other players at the table see of this game: the same strings your thumbnail renderer takes, the input as\n * `updateGameState()` takes it. Nothing is stored, so keep saving as you do. Call it once the board is built, before\n * `gameLoaded()`, then on every change: neighbours only see a player once it has been called, so a game that waits\n * for the first move hides its player until then. Pass `puzzleString` on the first call and whenever the puzzle\n * changes (a new deal), and leave it out otherwise; the host sends the latest at most once a second.\n *\n * Others see a status line under the player's name: the round's clock, which the SDK adds itself, and `stat`, one\n * number the game chooses to share with its label ready to show, e.g. `{ value: 34, label: \"moves\" }`. Send it with\n * every call; a label is at most 16 characters.\n */\n updateGameState: (inputString: string, opts?: { puzzleString?: string; stat?: SDKTableStat }) => void\n}\n\n/** The one number a game shares at the table beside the round's clock, its label ready to show */\nexport type SDKTableStat = { value: number; label: string }\n\n/** An achievement the server decided a round unlocked, as the `achievementsUnlocked` event hands it over */\nexport type SDKUnlockedAchievement = {\n stableID: string\n name: string\n description: string\n icon: string\n /** How hard it is to earn */\n tier: \"Basic\" | \"Fancy\" | \"Rare\" | \"Mythic\"\n /** A Puzzmo achievement any game can offer, rather than one of this game's own */\n isSiteAchievement: boolean\n}\n\n/** Player-facing game settings, rendered by the host's settings panel and persisted per-user, per-game. */\nexport interface SDKSettings {\n /**\n * Register the game's settings UI with the host. Component `defaultValue`s are merged\n * underneath the player's saved values, the host shows the components in its settings panel,\n * and the resolved settings object is returned. Listen for the `settingsUpdate` event to\n * react to the player changing values. Call after `gameReady()`.\n *\n * In an embed, the partner's `settingsUIOverrides` for this game are applied first: an override\n * replaces fields of the component with its `id` (a new `defaultValue`, say), and `omit` hides\n * the component and locks the setting to its default, over anything the player saved.\n */\n initialize: (components: GameSettingsUIComponents[]) => any\n /** Get the current resolved settings object. */\n get: () => any\n /** Merge changes into the current settings and persist them to the host. Returns the updated settings. */\n update: (changes: any) => any\n /**\n * The components from `initialize()` with the embed's overrides applied, omitted ones marked\n * `hidden`. Draw an in-game settings UI from these rather than from your own list.\n */\n components: () => GameSettingsUIComponents[]\n}\n\n/** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\nexport interface SDKKeyboard {\n /** Show the on-screen keyboard with the given config. Call again to update state (e.g. to change disabled keys). */\n show: (config: KeyboardConfig) => void\n /** Hide the on-screen keyboard. */\n hide: () => void\n}\n\n/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => void\n}\n\n/**\n * The SDK instance returned by `createPuzzmoSDK` — a game's API surface for talking to whichever\n * host is embedding it (puzzmo.com, a partner embed, or the native apps): bootstrapping the\n * puzzle, syncing progress, reporting completion, and driving host UI like settings and the\n * on-screen keyboard.\n *\n * The expected lifecycle is: `gameReady()` → build your board from the result → `gameLoaded()` →\n * play, persisting via `updateGameState()` → `gameCompleted()` → `showCompletionScreen()`.\n */\nexport interface PuzzmoSDK<Plugins extends readonly SDKPlugin[] = []> {\n /**\n * The play clock. The SDK manages it for you: it starts when the host starts the game, pauses\n * and resumes with the host UI, and its display is mirrored into the host chrome twice a\n * second. Most games only need `addPenalty()` for hint or mistake costs.\n */\n timer: SDKTimer\n\n /** APIs contributed by the plugins passed to `createPuzzmoSDK`, keyed by plugin name. */\n plugins: PluginAPIs<Plugins>\n\n /**\n * Announce that the game is ready to receive data. Sends `READY` to the host and resolves with\n * the bootstrap info once the host replies: the puzzle to load, any saved in-progress state,\n * and the host theme. Call this first — every other API assumes it has resolved. Rejects when\n * the host doesn't reply within `PuzzmoSDKOptions.timeout` (default 5s).\n */\n gameReady: () => Promise<GameReadyResult>\n\n /**\n * Tell the host the game has parsed the puzzle, rendered, and is ready to be revealed. The\n * host dismisses its loading UI and replies with a start signal — listen via `on(\"start\")` to\n * begin play; the timer starts then too.\n */\n gameLoaded: (state?: any) => void\n\n /**\n * Subscribe to a host lifecycle event: `start`, `pause`, `resume`, `retry`, `settingsUpdate`,\n * or the on-screen `keyboard*` events. Returns an unsubscribe function.\n */\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => () => void\n\n /** Remove an event listener previously registered with `on`. */\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => void\n\n /**\n * Save the player's in-progress state to the server so play can resume later, on any\n * device. `inputString` is the game's own serialized format — it comes back as `inputString`\n * from `gameReady()`. Call whenever the player makes a meaningful move; elapsed time is filled\n * in from the SDK timer unless provided in `play`. Ignored, with a console warning, when there is\n * no gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => void\n\n /**\n * Report the game as finished. Concludes the timer, fills in elapsed/penalty time when not\n * provided, and uploads the final play plus its deeds — the host uses these for scoring,\n * leaderboards, stats, and other augmentations. Pass progress as `inputString` (the same\n * string `updateGameState()` takes). Follow with `showCompletionScreen()`. Without a play session\n * the result is still reported, with no gameplay ID, when the host negotiated contract \"1.1\" —\n * older hosts can't record one, so the message is dropped with a console warning.\n */\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => void\n\n /**\n * Ask the host to show its post-game completion UI. `results` render in the completion\n * sidebar: markdown congratulations, the player's streak stats, and custom stat rows. Call\n * after `gameCompleted()`, typically once your own victory animation has finished.\n */\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => void\n\n /**\n * Record a named mid-game checkpoint. Uploads the current board state and play time, and can\n * run parts of the completion pipeline early (e.g. posting to leaderboards) via\n * `checkpointConfig.process`. A checkpoint is also the host's opportunity to show an ad when\n * `checkpointConfig.interruptible` is true. Ignored, with a console warning, when there is no\n * gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => void\n\n /** Player-facing game settings, rendered in the host's settings panel and persisted per-user, per-game. */\n settings: SDKSettings\n\n /** The game's own durable per-player state, opaque to the host. See `SDKStorage`. */\n storage: SDKStorage\n\n /**\n * Report a finished run of a repeatable (Anytime) mode. Unlike `gameCompleted()` there is no gameplay behind it: the host records the run\n * against the player's counters for this game and nothing more. One page hosts many runs, so the SDK timer is not concluded; pass\n * `elapsedTimeSecs` for the run, else the timer's time since the previous run (or since it started, for the first) is used.\n * `config.deeds` ride along as they do on completion.\n */\n completeRepeatableRun: (play?: { elapsedTimeSecs?: number; puzzleKey?: string }, config?: AugmentationConfig) => void\n\n /** The rounds of repeat play, logged for the server to replay. See `SDKRounds`. */\n rounds: SDKRounds\n\n /** What other players at the table see of this game. See `SDKTable`. */\n table: SDKTable\n\n /**\n * Whether the host draws `confirm()`'s question over its whole page. Where it doesn't, ask with the game's own\n * dialog instead. Call after `gameReady()`.\n */\n canConfirm: () => boolean\n\n /**\n * Ask a yes/no question in a dialog the host draws over its whole page, so it dims what the host draws around the\n * game too (the table's neighbours, say). Resolves true when the player confirms. Only where `canConfirm()`;\n * elsewhere it warns and resolves false. A second call while one is showing answers the first with false.\n *\n * @example\n * const ok = sdk.canConfirm() ? await sdk.confirm({ title: \"Reset this deal?\", confirmLabel: \"Reset\" }) : await myOwnDialog()\n */\n confirm: (opts: SDKConfirmOptions) => Promise<boolean>\n\n /**\n * Ask the host for another puzzle from the game's pool, for a repeatable game whose puzzles come from\n * the host (the first arrives with `gameReady()`). Leave `buckets` out to draw from the whole pool, and\n * set it only when the game wants a particular kind of puzzle, such as difficulties chosen by the player:\n * the draw is uniform across whichever buckets it covers. `exclude` is the game's own recent keys, newest\n * last, which the host avoids while it can. Rejects when the game has no pool, a bucket does not exist,\n * or the host does not answer in time. A game that sends READY again is handed the last puzzle drawn, so\n * one that draws ahead should keep the puzzle in play in its storage rather than rely on the boot's.\n */\n requestPuzzle: (opts?: { buckets?: readonly string[]; exclude?: readonly string[] }) => Promise<SDKPoolPuzzle>\n\n /** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\n keyboard: SDKKeyboard\n\n /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\n\n /**\n * The raw postMessage transport to the host — an escape hatch for protocol messages the SDK\n * doesn't wrap.\n *\n * @internal\n */\n _hostAPI: {\n sendMessage: <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => void\n onMessage: <T extends keyof SupportedIncomingMessages>(type: T, handler: (data: SupportedIncomingMessages[T]) => void) => () => void\n }\n}\n\nexport type SupportedOutgoingMessages = Pick<\n MessagesSentFromEmbed,\n | \"READY\"\n | \"READY_GAME_LOADED\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"TIMER_TICK\"\n | \"TIMER_SYNC\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"UPDATE_GAME_USER_STATE\"\n | \"COMPLETE_REPEATABLE_RUN\"\n | \"START_REPEATABLE_ROUND\"\n | \"RESUME_REPEATABLE_ROUND\"\n | \"UPDATE_TABLE_GAME_STATE\"\n | \"APPEND_REPEATABLE_ROUND_LOG\"\n | \"REQUEST_PUZZLE\"\n | \"REQUEST_CONFIRM\"\n | \"HIT_CHECKPOINT\"\n | \"KEYBOARD_UPDATE_CONFIG\"\n | \"INITIALIZE_SETTINGS\"\n | \"UPDATE_SETTINGS_FROM_EMBED\"\n | \"SENSORY_EVENT\"\n>\n\nexport type SupportedIncomingMessages = Pick<\n MessagesReceived,\n | \"READY_DATA\"\n | \"START_GAME\"\n | \"PAUSE_GAME\"\n | \"RESUME_GAME\"\n | \"SETTINGS_UPDATE\"\n | \"RETRY_PUZZLE\"\n | \"KEYBOARD_KEY_PRESS\"\n | \"KEYBOARD_CURSOR_CHANGE\"\n | \"KEYBOARD_CURSOR_END\"\n | \"PUZZLE_DATA\"\n | \"ACHIEVEMENTS_UNLOCKED\"\n | \"REPEATABLE_ROUND_LOST\"\n | \"CONFIRM_ANSWER\"\n>\n\ntype MessageHandler<T extends keyof SupportedIncomingMessages> = (data: SupportedIncomingMessages[T]) => void\n\nexport type SDKEventMap = {\n start: void\n pause: void\n resume: void\n retry: void\n /** The player changed a setting in the host UI. The payload is the full resolved settings object. */\n settingsUpdate: any\n /** A key on the on-screen keyboard was tapped. */\n keyboardKeyPress: { key: string }\n /** The drag cursor moved across the keyboard. Only fires when `supportsDragCursor` is true. */\n keyboardCursorChange: { position: [number, number] }\n /** The drag cursor was released. Only fires when `supportsDragCursor` is true. */\n keyboardCursorEnd: void\n /** The repeat-play round in progress or just finished unlocked these. The host shows them over the game; a game need not. */\n achievementsUnlocked: { achievements: SDKUnlockedAchievement[] }\n /**\n * The deal passed to `rounds.resume()` has no round on the server, so nothing played on it can unlock an achievement.\n * Drop the deal and start a new one with `rounds.start({ reason: \"new\" })`. Not sent once the game has started a round.\n */\n roundLost: void\n}\n\nexport type SDKEventType = keyof SDKEventMap\n\nexport interface SDKTimer {\n /** Get elapsed time in milliseconds */\n timeMs: () => number\n /** Get elapsed time in seconds */\n timeSecs: () => number\n /** Get added/penalty time in milliseconds */\n addedTimeMs: () => number\n /** Get added/penalty time in seconds */\n addedTimeSecs: () => number\n /** Get elapsed time without penalties in seconds */\n timeWithoutPenaltySecs: () => number\n /** Get formatted display strings [elapsed, added] */\n display: () => [string, string]\n /** Add penalty time in milliseconds */\n addPenalty: (ms: number) => void\n /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (ms: number) => void\n /** Check if timer is paused */\n isPaused: () => boolean\n /** Check if timer has been started */\n isRunning: () => boolean\n /** Pause the timer (same as a host-sent PAUSE_GAME); emits \"pause\" on an actual transition. */\n pause: () => void\n /** Resume the timer (same as a host-sent RESUME_GAME); emits \"resume\" on an actual transition. */\n resume: () => void\n}\n\nfunction formatTime(timeMs: number): string {\n const isAnHourOrMore = timeMs >= 60 * 60 * 1000\n return new Date(timeMs)\n .toISOString()\n .slice(isAnHourOrMore ? 11 : 14, -1)\n .split(\".\")[0]\n}\n\nfunction createTimer(\n initialTimeMs = 0,\n initialAddedTimeMs = 0,\n): Omit<SDKTimer, \"pause\" | \"resume\"> & {\n _init: () => void\n _pause: () => void\n _resume: () => void\n _reset: (initialTimeMs?: number, initialAddedTimeMs?: number) => void\n _conclude: () => void\n} {\n let baseTime = initialTimeMs\n let addedTime = initialAddedTimeMs\n let pausedTime = 0\n let concludeTime: number | undefined\n\n let startDate: number | undefined = undefined\n let pausedDate: number | undefined = undefined\n\n const getTime = (): number => {\n if (startDate === undefined) return baseTime + addedTime\n if (concludeTime !== undefined) return concludeTime\n const now = pausedDate ?? performance.now()\n const elapsed = now - startDate - pausedTime\n return baseTime + addedTime + elapsed\n }\n\n return {\n _init: () => {\n if (startDate === undefined) {\n startDate = performance.now()\n pausedDate = undefined\n }\n },\n _pause: () => {\n if (pausedDate !== undefined || startDate === undefined) return\n pausedDate = performance.now()\n },\n _resume: () => {\n if (pausedDate === undefined) return\n pausedTime += performance.now() - pausedDate\n pausedDate = undefined\n },\n _reset: (newInitialTimeMs = 0, newInitialAddedTimeMs = 0) => {\n baseTime = newInitialTimeMs\n addedTime = newInitialAddedTimeMs\n pausedTime = 0\n concludeTime = undefined\n startDate = undefined\n pausedDate = undefined\n },\n _conclude: () => {\n if (pausedDate !== undefined) {\n concludeTime = getTime()\n return\n }\n if (startDate === undefined) {\n concludeTime = baseTime + addedTime\n return\n }\n concludeTime = getTime()\n },\n timeMs: () => getTime(),\n timeSecs: () => getTime() / 1000,\n addedTimeMs: () => addedTime,\n addedTimeSecs: () => addedTime / 1000,\n timeWithoutPenaltySecs: () => (getTime() - addedTime) / 1000,\n addPenalty: (ms: number) => {\n addedTime += ms\n },\n setPenalty: (ms: number) => {\n addedTime = ms\n },\n isPaused: () => pausedDate !== undefined || startDate === undefined,\n isRunning: () => startDate !== undefined && pausedDate === undefined,\n display: () => {\n const elapsed = getTime() - addedTime\n const elapsedStr = formatTime(Math.max(0, elapsed))\n const addedStr = addedTime === 0 ? \"\" : formatTime(addedTime)\n return [elapsedStr, addedStr]\n },\n }\n}\n\nfunction createHostAPI() {\n const messageHandlers = new Map<string, Set<(data: any) => void>>()\n const sendWatchers = new Map<string, Set<(json: any) => void>>()\n\n const sendMessage = <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => {\n const message = { type, json, _: \"p\", __: \"mp\", private: true }\n\n if (\"parent\" in window && window.parent !== window) window.parent.postMessage(message, \"*\")\n\n window.postMessage(message, \"*\")\n\n if (\"webkit\" in window && (window as any).webkit?.messageHandlers?.app) (window as any).webkit.messageHandlers.app.postMessage(message)\n\n if (\"puzzmoMessageString\" in window) (window as any).puzzmoMessageString(JSON.stringify(message))\n\n if (\"ReactNativeWebView\" in window && (window as any).ReactNativeWebView?.postMessage)\n (window as any).ReactNativeWebView.postMessage(JSON.stringify(message))\n\n if (type !== \"TIMER_TICK\" && type !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] sent:\", type, json)\n\n // A watcher runs inside the game's own call, so one that throws must not break it.\n sendWatchers.get(type)?.forEach((watcher) => {\n try {\n watcher(json)\n } catch (error) {\n console.error(`[Puzzmo SDK] a watcher of ${type} threw:`, error)\n }\n })\n }\n\n const onMessage = <T extends keyof SupportedIncomingMessages>(type: T, handler: MessageHandler<T>) => {\n if (!messageHandlers.has(type)) messageHandlers.set(type, new Set())\n messageHandlers.get(type)!.add(handler)\n\n return () => {\n messageHandlers.get(type)?.delete(handler)\n }\n }\n\n /** Runs `watcher` synchronously each time a message of `type` is sent. Returns an unsubscribe function. */\n const onSend = (type: string, watcher: (json: any) => void) => {\n if (!sendWatchers.has(type)) sendWatchers.set(type, new Set())\n sendWatchers.get(type)!.add(watcher)\n\n return () => {\n sendWatchers.get(type)?.delete(watcher)\n }\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", (event) => {\n if (!event?.data?.type) return\n const msgType = event.data.type as string\n const handlers = messageHandlers.get(msgType)\n if (handlers) {\n const msgData = event.data.data ?? event.data.json ?? {}\n if (msgType !== \"TIMER_TICK\" && msgType !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] received:\", msgType, msgData)\n handlers.forEach((handler) => handler(msgData))\n }\n })\n }\n\n return { sendMessage, onMessage, onSend }\n}\n\n/**\n * The host<->game contract this SDK speaks, declared in READY and READY_GAME_LOADED: games read\n * `game` and `session`, and handle `session` being absent. Hosts on \"1.0\" always send a session.\n */\nconst sdkRuntimeContract = \"1.1\"\n\nconst hostAPI = createHostAPI()\n\n/** A puzzle request covers a round trip to the API and a blob read, so it gets longer than READY_DATA */\nconst puzzleRequestTimeoutMs = 10_000\n\n/** Creates a Puzzmo SDK instance for communicating with the Puzzmo host */\nexport const createPuzzmoSDK = <const Plugins extends readonly SDKPlugin[] = []>(\n options: PuzzmoSDKOptions<Plugins> = {},\n): PuzzmoSDK<Plugins> => {\n let readyData: MessagesReceived[\"READY_DATA\"] | null = null\n let readyDataResolve: ((data: MessagesReceived[\"READY_DATA\"]) => void) | null = null\n\n const getGameplay = () => readyData?.session?.gameplay\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => readyData?.session?.puzzle.puzzle ?? readyData?.repeatablePuzzle?.puzzle ?? null\n const getBoardState = () => getGameplay()?.boardState ?? null\n const getTheme = () => readyData?.theme ?? null\n // Mirrors what the host holds, so get() reflects the game's own writes within a session\n let storedState: SDKStoredState | null = null\n let lastRunEndedAtSecs = 0\n // Where the open round began on the timer, for the table's clock; null when the game logs no rounds\n let roundStartedAtSecs: number | null = null\n // What the game last showed the table, sent again with a new clock when the timer pauses or resumes\n let lastTableState: { inputString: string; stat?: SDKTableStat } | null = null\n // Events logged in the round in progress, so each batch says where it starts and a resend is harmless\n let roundLogLength = 0\n // A resumed deal waiting on the host to find its round, so only it can be told the round is lost\n let awaitingResume = false\n let warnedStorageUnsaved = false\n const getCompleted = () => getGameplay()?.completed ?? false\n\n let warnedNoSession = false\n /** Warns once that a call was dropped: before READY_DATA arrived, or the host sent no play session */\n const warnNoSession = (method: string) => {\n if (warnedNoSession) return\n warnedNoSession = true\n const reason = readyData\n ? \"the host sent no play session, so there is no gameplay to save to\"\n : \"it was called before gameReady() resolved\"\n console.warn(`[Puzzmo SDK] ${method}() was ignored: ${reason}`)\n }\n\n const eventListeners = new Map<SDKEventType, Set<(data?: any) => void>>()\n\n // The resolved settings object — seeded from READY_DATA's saved values, then component\n // defaults are merged underneath when the game calls settings.initialize\n let currentSettings: any | null = null\n // What settings.initialize registered, after an embed's overrides\n let settingsComponents: GameSettingsUIComponents[] = []\n // Settings an embed has hidden, held at these values whatever the player saved\n let lockedSettings: Record<string, unknown> = {}\n const resolvedSettings = () => ({ ...currentSettings, ...lockedSettings })\n\n // ClickHouse game analytics — sends the same lifecycle events the runtime tracks\n // (page_view, gameplay_active, active_30s, completed, link_click). Disabled on localhost.\n let analytics: GameAnalyticsTracker | null = null\n let analyticsCompletedAtStart = false\n\n const trackAnalyticsEvent = (type: string, json?: any) => {\n // Don't re-send progression events for a game that was already completed when loaded\n if (analyticsCompletedAtStart) return\n analytics?.trackEvent(type, json)\n }\n\n const internalTimer = createTimer()\n let timerTickInterval: ReturnType<typeof setInterval> | null = null\n let timerSyncInterval: ReturnType<typeof setInterval> | null = null\n\n const startTimerIntervals = () => {\n if (timerTickInterval) return\n\n timerTickInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n const [elapsed, added] = internalTimer.display()\n hostAPI.sendMessage(\"TIMER_TICK\", { display: [elapsed, added] })\n }, 500)\n\n timerSyncInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n hostAPI.sendMessage(\"TIMER_SYNC\", Math.floor(internalTimer.timeWithoutPenaltySecs()))\n }, 10000)\n }\n\n const stopTimerIntervals = () => {\n if (timerTickInterval) {\n clearInterval(timerTickInterval)\n timerTickInterval = null\n }\n if (timerSyncInterval) {\n clearInterval(timerSyncInterval)\n timerSyncInterval = null\n }\n }\n\n const emit = <T extends SDKEventType>(event: T, data?: SDKEventMap[T]) => {\n const listeners = eventListeners.get(event)\n if (listeners) listeners.forEach((listener) => listener(data))\n }\n\n hostAPI.onMessage(\"START_GAME\", () => {\n internalTimer._init()\n startTimerIntervals()\n emit(\"start\")\n // A game shows the table its board before it starts, so its clock only starts here\n resendTableStatus()\n })\n\n // Shared by the host-sent PAUSE_GAME/RESUME_GAME messages and the game-initiated\n // sdk.timer.pause()/resume() below, so both paths stop/start the same timer identically.\n const pauseTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._pause()\n if (internalTimer.isPaused() !== wasPaused) emit(\"pause\")\n }\n const resumeTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._resume()\n if (internalTimer.isPaused() !== wasPaused) emit(\"resume\")\n }\n\n // The table's clock for the round on screen, from its start, or from the last run's end for a game logging no rounds\n const tableStatus = (stat?: SDKTableStat) => {\n const timerSecs = internalTimer.timeWithoutPenaltySecs()\n const from = roundStartedAtSecs ?? lastRunEndedAtSecs\n // A timer reset since (a retry restarts it) leaves it short of the start, so the clock reads from the reset\n const secs = Math.max(0, Math.floor(timerSecs >= from ? timerSecs - from : timerSecs))\n return { secs, running: !internalTimer.isPaused(), ...(stat ? { stat: { value: stat.value, label: stat.label } } : {}) }\n }\n // Neighbours' pages count the clock on themselves, so they hear when it stops and starts\n const resendTableStatus = () => {\n if (!lastTableState) return\n hostAPI.sendMessage(\"UPDATE_TABLE_GAME_STATE\", { inputString: lastTableState.inputString, status: tableStatus(lastTableState.stat) })\n }\n const pauseThenTell = () => {\n pauseTimer()\n resendTableStatus()\n }\n const resumeThenTell = () => {\n resumeTimer()\n resendTableStatus()\n }\n\n hostAPI.onMessage(\"PAUSE_GAME\", pauseThenTell)\n hostAPI.onMessage(\"RESUME_GAME\", resumeThenTell)\n\n hostAPI.onMessage(\"SETTINGS_UPDATE\", (data) => {\n currentSettings = { ...currentSettings, ...data }\n emit(\"settingsUpdate\", resolvedSettings())\n })\n\n hostAPI.onMessage(\"KEYBOARD_KEY_PRESS\", (data) => emit(\"keyboardKeyPress\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_CHANGE\", (data) => emit(\"keyboardCursorChange\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_END\", () => emit(\"keyboardCursorEnd\"))\n hostAPI.onMessage(\"ACHIEVEMENTS_UNLOCKED\", (data) => emit(\"achievementsUnlocked\", data))\n hostAPI.onMessage(\"REPEATABLE_ROUND_LOST\", () => {\n // The game may have started a new deal while the host was asking, and that one has a round of its own\n if (!awaitingResume) return\n awaitingResume = false\n emit(\"roundLost\")\n })\n\n // Puzzle requests in flight, by nonce, each settled by its PUZZLE_DATA or a timeout\n const puzzleRequests = new Map<string, { resolve: (puzzle: SDKPoolPuzzle) => void; reject: (error: Error) => void }>()\n let puzzleRequestCount = 0\n\n hostAPI.onMessage(\"PUZZLE_DATA\", (data) => {\n const request = puzzleRequests.get(data.nonce)\n if (!request) return\n puzzleRequests.delete(data.nonce)\n if (\"failed\" in data) request.reject(new Error(data.error))\n else request.resolve({ puzzleKey: data.puzzle.key, puzzleString: data.puzzle.puzzle })\n })\n\n // The question the host is showing, settled by its CONFIRM_ANSWER\n let pendingConfirm: { nonce: string; resolve: (confirmed: boolean) => void } | null = null\n let confirmCount = 0\n hostAPI.onMessage(\"CONFIRM_ANSWER\", (data) => {\n if (!pendingConfirm || pendingConfirm.nonce !== data.nonce) return\n const { resolve } = pendingConfirm\n pendingConfirm = null\n resolve(data.confirmed === true)\n })\n\n hostAPI.onMessage(\"RETRY_PUZZLE\", () => {\n internalTimer._reset()\n stopTimerIntervals()\n emit(\"retry\")\n })\n\n hostAPI.onMessage(\"READY_DATA\", (data) => {\n const bootstrapData = normalizeReadyData(data as MessagesReceived[\"READY_DATA\"])\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.session?.gameplay\n\n // userState.gameSettings is a map keyed by game slug; older records can hold the\n // value as a JSON string rather than an object\n if (currentSettings === null) {\n const gameSlug = bootstrapData.game.slug\n let saved = gameSlug ? bootstrapData.userState?.gameSettings?.[gameSlug] : null\n if (typeof saved === \"string\") {\n try {\n saved = JSON.parse(saved)\n } catch {\n saved = null\n }\n }\n currentSettings = saved ?? {}\n }\n if (gamePlayed) {\n const existingTime = (gamePlayed.elapsedTimeSecs ?? 0) * 1000\n const existingAddedTime = (gamePlayed.additionalTimeAddedSecs ?? 0) * 1000\n internalTimer._reset(existingTime, existingAddedTime)\n }\n\n // Wire up analytics once, from the first bootstrap payload\n if (!analytics) {\n analytics = createGameAnalytics(bootstrapData)\n analyticsCompletedAtStart = gamePlayed?.completed ?? false\n // Link clicks are tracked even for already-completed games, matching the runtime\n if (analytics) setupLinkTracking((info) => analytics!.trackLinkClick(info))\n }\n\n if (readyDataResolve) {\n readyDataResolve(bootstrapData)\n readyDataResolve = null\n }\n })\n\n const timer: SDKTimer = {\n timeMs: () => internalTimer.timeMs(),\n timeSecs: () => internalTimer.timeSecs(),\n addedTimeMs: () => internalTimer.addedTimeMs(),\n addedTimeSecs: () => internalTimer.addedTimeSecs(),\n timeWithoutPenaltySecs: () => internalTimer.timeWithoutPenaltySecs(),\n display: () => internalTimer.display(),\n addPenalty: (ms: number) => internalTimer.addPenalty(ms),\n setPenalty: (ms: number) => internalTimer.setPenalty(ms),\n isPaused: () => internalTimer.isPaused(),\n isRunning: () => internalTimer.isRunning(),\n pause: pauseThenTell,\n resume: resumeThenTell,\n }\n\n // Wire up plugins. Each gets the host transport (open to the full protocol), the timer, and\n // the bootstrap payload, and contributes a namespaced API onto `sdk.plugins[name]`.\n const pluginContext: SDKPluginContext = {\n send: (type, json) => hostAPI.sendMessage(type as keyof SupportedOutgoingMessages, json as never),\n on: (type, handler) => hostAPI.onMessage(type as keyof SupportedIncomingMessages, handler),\n onSend: hostAPI.onSend,\n timer,\n bootstrap: () => readyData,\n }\n const pluginAPIs: Record<string, unknown> = {}\n for (const plugin of options.plugins ?? []) pluginAPIs[plugin.name] = plugin.setup(pluginContext)\n\n return {\n timer,\n\n plugins: pluginAPIs as PluginAPIs<Plugins>,\n\n gameReady: async () => {\n hostAPI.sendMessage(\"READY\", { runtimeContract: sdkRuntimeContract })\n\n // READY_DATA may already be here, answering an earlier READY\n if (!readyData) {\n const timeout = options.timeout ?? 5000\n await new Promise<MessagesReceived[\"READY_DATA\"]>((resolve, reject) => {\n readyDataResolve = resolve\n setTimeout(() => {\n if (readyDataResolve) {\n readyDataResolve = null\n reject(new Error(`Timeout waiting for READY_DATA after ${timeout}ms`))\n }\n }, timeout)\n })\n }\n\n const inputString = getBoardState()\n const result: GameReadyResult = {\n mode: readyData?.repeatable ? \"repeatable\" : \"puzzle\",\n puzzleString: getPuzzleString(),\n puzzleKey: readyData?.repeatable ? (readyData.repeatablePuzzle?.key ?? null) : null,\n inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n // boardState is the pre-rename spelling of inputString, kept for untyped callers\n return { ...result, boardState: inputString } as GameReadyResult\n },\n\n gameLoaded: (state: any = {}) => {\n hostAPI.sendMessage(\"READY_GAME_LOADED\", {\n state,\n gameRuntimeContract: sdkRuntimeContract,\n embedRuntimeContract: \"1.0\",\n })\n trackAnalyticsEvent(\"READY_GAME_LOADED\")\n },\n\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void): (() => void) => {\n if (!eventListeners.has(event)) eventListeners.set(event, new Set())\n eventListeners.get(event)!.add(listener)\n return () => {\n eventListeners.get(event)?.delete(listener)\n }\n },\n\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => {\n eventListeners.get(event)?.delete(listener)\n },\n\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"updateGameState\")\n\n hostAPI.sendMessage(\"UPLOAD_NEW_GAME_STATE\", {\n id: gameplayID,\n input: {\n boardState: inputString,\n elapsedTimeSecs: play?.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play?.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n collabUserReferences: [],\n },\n })\n trackAnalyticsEvent(\"UPLOAD_NEW_GAME_STATE\")\n },\n\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => {\n internalTimer._conclude()\n stopTimerIntervals()\n\n // Games say inputString; the wire and database say boardState. Untyped callers\n // may still send the old boardState spelling, so keep accepting it at runtime.\n const { inputString, ...rest } = play\n const finalPlay: Partial<GamePlay> = {\n ...rest,\n boardState: inputString ?? (play as { boardState?: string }).boardState,\n elapsedTimeSecs: play.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n }\n\n const deeds: Deed[] = (config?.deeds as any) ?? []\n deeds.push({ id: \"points\", value: play.pointsAwarded })\n deeds.push({\n id: \"time\",\n value: Math.round(finalPlay.elapsedTimeSecs ?? 0) + Math.round(finalPlay.additionalTimeAddedSecs ?? 0),\n })\n\n const gameplayID = getGameplayID()\n // Without a session there's no gameplay ID; only hosts which negotiated \"1.1\" know to record\n // an id-less completion. A pre-1.1 host sending no gameplay is a host bug, not sessionless play.\n const sessionlessHost = readyData && !readyData.session && readyData.appRuntimeContract === \"1.1\"\n if (gameplayID || sessionlessHost) {\n hostAPI.sendMessage(\"GAME_COMPLETED\", {\n id: gameplayID ?? undefined,\n input: finalPlay,\n config,\n })\n trackAnalyticsEvent(\"GAME_COMPLETED\", { input: finalPlay })\n } else {\n warnNoSession(\"gameCompleted\")\n }\n },\n\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => {\n // showRetry stays in the message contract for a future host play-again button; no host renders one yet\n hostAPI.sendMessage(\"SHOW_GAME_COMPLETE_SCREEN\", { results, showRetry: true })\n },\n\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"hitCheckpoint\")\n\n const inputStr = getBoardState() ?? \"\"\n const play: Partial<GamePlay> = {\n elapsedTimeSecs: internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: internalTimer.addedTimeSecs(),\n }\n\n hostAPI.sendMessage(\"HIT_CHECKPOINT\", {\n checkpointName,\n gameplay: { inputStr, play },\n checkpointConfig,\n augConfig: config ?? {},\n })\n },\n\n completeRepeatableRun: (play?: { elapsedTimeSecs?: number; puzzleKey?: string }, config?: AugmentationConfig) => {\n // The timer runs on across runs, so a run's default time is measured from where the last one ended\n const timerSecs = internalTimer.timeWithoutPenaltySecs()\n const sinceLastRun = timerSecs >= lastRunEndedAtSecs ? timerSecs - lastRunEndedAtSecs : timerSecs\n lastRunEndedAtSecs = timerSecs\n const elapsedTimeSecs = Math.round(play?.elapsedTimeSecs ?? sinceLastRun)\n // The run's own time is the time deed; one the game passed would be a second, conflicting value\n const gameDeeds = ((config?.deeds as Deed[] | undefined) ?? []).filter((deed) => deed.id !== \"time\")\n const deedValues = [...gameDeeds, { id: \"time\", value: elapsedTimeSecs }]\n const puzzleKey = play?.puzzleKey\n hostAPI.sendMessage(\"COMPLETE_REPEATABLE_RUN\", { input: { deedValues, elapsedTimeSecs, ...(puzzleKey ? { puzzleKey } : {}) } })\n trackAnalyticsEvent(\"COMPLETE_REPEATABLE_RUN\", { elapsedTimeSecs })\n },\n\n rounds: {\n start: (opts) => {\n roundLogLength = 0\n roundStartedAtSecs = internalTimer.timeWithoutPenaltySecs()\n awaitingResume = false\n hostAPI.sendMessage(\"START_REPEATABLE_ROUND\", { reason: opts.reason, ...(opts.puzzleKey ? { puzzleKey: opts.puzzleKey } : {}) })\n },\n resume: (opts) => {\n roundLogLength = opts.events.length\n // The round has run as long as its last event, in ms from its start, so the clock carries on from there\n const lastEventMs = Number(opts.events[opts.events.length - 1]?.[0]) || 0\n roundStartedAtSecs = internalTimer.timeWithoutPenaltySecs() - lastEventMs / 1000\n awaitingResume = true\n hostAPI.sendMessage(\"RESUME_REPEATABLE_ROUND\", {\n events: opts.events.map((ev) => [...ev]),\n ...(opts.puzzleKey ? { puzzleKey: opts.puzzleKey } : {}),\n })\n },\n inProgress: () => {\n const open = readyData?.repeatableOpenRound\n if (!open || !Array.isArray(open.events)) return null\n return { puzzleKey: open.puzzleKey, puzzleString: open.puzzle, events: open.events, resets: open.resets }\n },\n log: (...events) => {\n if (!events.length) return\n hostAPI.sendMessage(\"APPEND_REPEATABLE_ROUND_LOG\", { from: roundLogLength, events: events.map((ev) => [...ev]) })\n roundLogLength += events.length\n },\n },\n\n table: {\n updateGameState: (inputString, opts) => {\n lastTableState = { inputString, ...(opts?.stat ? { stat: opts.stat } : {}) }\n hostAPI.sendMessage(\"UPDATE_TABLE_GAME_STATE\", {\n inputString,\n ...(opts?.puzzleString !== undefined ? { puzzleString: opts.puzzleString } : {}),\n status: tableStatus(opts?.stat),\n })\n },\n },\n\n requestPuzzle: (opts?: { buckets?: readonly string[]; exclude?: readonly string[] }) =>\n new Promise<SDKPoolPuzzle>((resolve, reject) => {\n const nonce = `puzzle-${++puzzleRequestCount}`\n const timer = setTimeout(() => {\n if (!puzzleRequests.delete(nonce)) return\n reject(new Error(`Timeout waiting for PUZZLE_DATA after ${puzzleRequestTimeoutMs}ms`))\n }, puzzleRequestTimeoutMs)\n const settle =\n <T>(fn: (value: T) => void) =>\n (value: T) => {\n clearTimeout(timer)\n fn(value)\n }\n puzzleRequests.set(nonce, { resolve: settle(resolve), reject: settle(reject) })\n hostAPI.sendMessage(\"REQUEST_PUZZLE\", {\n nonce,\n buckets: opts?.buckets ? [...opts.buckets] : undefined,\n exclude: opts?.exclude ? [...opts.exclude] : undefined,\n })\n }),\n\n canConfirm: () => readyData?.hostDialogs?.confirm === true,\n\n confirm: (opts: SDKConfirmOptions) =>\n new Promise<boolean>((resolve) => {\n if (readyData?.hostDialogs?.confirm !== true) {\n console.warn(\"[Puzzmo SDK] confirm() was answered no: this host draws no confirm dialog, check canConfirm() first\")\n resolve(false)\n return\n }\n // The host replaces a showing question with the new one, so the old one's answer is no\n pendingConfirm?.resolve(false)\n const nonce = `confirm-${++confirmCount}`\n pendingConfirm = { nonce, resolve }\n const { title, text, confirmLabel, cancelLabel } = opts\n hostAPI.sendMessage(\"REQUEST_CONFIRM\", { nonce, title, text, confirmLabel, cancelLabel })\n }),\n\n storage: {\n get: () => {\n if (storedState) return storedState\n const fromHost = readyData?.viewerStorage\n return fromHost && fromHost.state != null ? { state: fromHost.state, stateVersion: fromHost.stateVersion } : null\n },\n set: (state: string, stateVersion = 1) => {\n // The host's limits, checked here so a write it would refuse fails at the call instead of looking saved\n const sizeBytes = new TextEncoder().encode(state).length\n if (sizeBytes > storageMaxBytes) throw new Error(`[sdk.storage] State is ${sizeBytes} bytes, over the ${storageMaxBytes} byte cap`)\n if (!Number.isInteger(stateVersion) || stateVersion < 1) throw new Error(\"[sdk.storage] stateVersion must be a positive integer\")\n if (readyData && !readyData.repeatable && !warnedStorageUnsaved) {\n warnedStorageUnsaved = true\n console.warn(\"[sdk.storage] Only repeat play saves storage for now; this write lasts until the page reloads\")\n }\n storedState = { state, stateVersion }\n hostAPI.sendMessage(\"UPDATE_GAME_USER_STATE\", { state, stateVersion })\n },\n },\n\n settings: {\n initialize: (components: GameSettingsUIComponents[]) => {\n const overridden = applySettingsOverrides(components, embedSettingsOverrides(readyData))\n settingsComponents = overridden.components\n lockedSettings = overridden.locked\n currentSettings = { ...settingsDefaultsFromComponents(settingsComponents), ...currentSettings }\n const settings = resolvedSettings()\n hostAPI.sendMessage(\"INITIALIZE_SETTINGS\", { components: settingsComponents, settings })\n return settings\n },\n get: resolvedSettings,\n update: (changes: any) => {\n // Locked values stay out of what is saved, so the player's own choice outlives the embed's\n const unlocked = Object.entries(changes ?? {}).filter(([name]) => !(name in lockedSettings))\n currentSettings = { ...currentSettings, ...Object.fromEntries(unlocked) }\n hostAPI.sendMessage(\"UPDATE_SETTINGS_FROM_EMBED\", { settings: currentSettings })\n return resolvedSettings()\n },\n components: () => settingsComponents,\n },\n\n keyboard: {\n show: (config: KeyboardConfig) => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", config)\n },\n hide: () => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", {\n layout: [],\n symbols: {},\n highlight: [],\n disabled: [],\n xl: [],\n l: [],\n supportsDragCursor: false,\n })\n },\n },\n\n haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\n },\n },\n\n _hostAPI: hostAPI,\n }\n}\n\n/** Walks settings UI components (recursing into split groups) collecting name → defaultValue pairs */\nfunction settingsDefaultsFromComponents(components: GameSettingsUIComponents[]): Record<string, unknown> {\n const defaults: Record<string, unknown> = {}\n for (const component of components) {\n if (component.type === \"split\") Object.assign(defaults, settingsDefaultsFromComponents(component.content))\n else if (\"name\" in component) defaults[component.name] = component.defaultValue\n }\n return defaults\n}\n\n/** The settings overrides an embed's host context holds for this game, under the game's slug */\nfunction embedSettingsOverrides(data: MessagesReceived[\"READY_DATA\"] | null): SettingsUIOverride[] {\n const embed = data?.hostContext?.find((context) => context.type === \"embed\")\n const gameSlug = data?.game?.slug\n if (!embed || !gameSlug) return []\n\n const forGame = (embed as Record<string, unknown>)[gameSlug] as { settingsUIOverrides?: unknown } | undefined\n return Array.isArray(forGame?.settingsUIOverrides) ? forGame.settingsUIOverrides : []\n}\n\n/**\n * Applies an embed's overrides to the components they match by `id`, recursing into split groups.\n * `omit` marks the component `hidden`, and `locked` holds the value each omitted setting is kept at.\n */\nfunction applySettingsOverrides(components: GameSettingsUIComponents[], overrides: SettingsUIOverride[]) {\n const locked: Record<string, unknown> = {}\n if (!overrides.length) return { components, locked }\n\n const apply = (component: GameSettingsUIComponents, parentOmitted: boolean): GameSettingsUIComponents => {\n const { omit, ...patch } = overrides.find((override) => override.id === component.id) ?? { id: component.id }\n const omitted = parentOmitted || Boolean(omit)\n // The cast is for the spread, which widens the discriminated union\n const patched = { ...component, ...patch, ...(omitted ? { hidden: true } : {}) } as GameSettingsUIComponents\n\n if (patched.type === \"split\") return { ...patched, content: patched.content.map((inner) => apply(inner, omitted)) }\n if (omitted && \"name\" in patched) locked[patched.name] = patched.defaultValue\n return patched\n }\n\n return { components: components.map((component) => apply(component, false)), locked }\n}\n\n/** The largest state `sdk.storage.set()` takes, matching the API's cap */\nconst storageMaxBytes = 64 * 1024\n","import type { KeyboardConfig, KeyStyleRule, KeyStyles } from \"./types\"\n\n/**\n * A standard QWERTY layout with Enter and Backspace — a reasonable default for\n * any game that needs text input. Customize from here by spreading and overriding.\n *\n * @example\n * // Use as-is\n * sdk.keyboard.show(defaultKeyboardConfig)\n *\n * @example\n * // Extend with dynamic disabled letters\n * sdk.keyboard.show({ ...defaultKeyboardConfig, disabled: usedLetters })\n */\nexport const defaultKeyboardConfig: KeyboardConfig = {\n layout: [\"qwertyuiop\", \"asdfghjkl\", \"↵zxcvbnm⌫\", undefined],\n symbols: { \"↵\": \"enter\", \"⌫\": \"bsp\" },\n highlight: [\"↵\", \"⌫\"],\n disabled: [],\n xl: [],\n l: [\"↵\", \"⌫\"],\n supportsDragCursor: false,\n}\n\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\n}\n","// For now, we will keep these types in here but not mark them as something which should appear in the public SDK docs\n\nimport type { Theme } from \"./types\"\n\n/**\n * The theme passed to an editor bundle. The host sends its full {@link Theme} so editors derive\n * their colors from it rather than making their own theme decisions. Use `theme.type` for\n * light/dark bucketing.\n *\n * The bare `\"light\" | \"dark\"` string form is deprecated and will be removed in a future SDK\n * release — editors should handle the full `Theme` object.\n */\nexport type EditorTheme = Theme | \"light\" | \"dark\"\n\n/** Severity level for validation issues */\nexport type ValidationLevel = \"error\" | \"warning\" | \"info\"\n\n/** Represents a single validation issue found during puzzle validation */\nexport interface ValidationIssue {\n level: ValidationLevel\n message: string\n line?: number\n col?: number\n length?: number\n}\n\n/** Complete validation report for a puzzle */\nexport interface ValidationReport {\n success: boolean\n issues: ValidationIssue[]\n}\n\nexport type ImportErrorType = \"invalid_format\" | \"parsing_error\" | \"unknown\"\n\n/** Custom error class for workshop import failures */\nexport class EditorImportError extends Error {\n constructor(\n public type: ImportErrorType,\n message: string,\n public originalError?: unknown,\n ) {\n super(message)\n this.name = \"EditorImportError\"\n }\n}\n\n/** Result of a successful puzzle import operation */\nexport interface ImportResult {\n data: string\n warnings?: ValidationIssue[]\n title?: string\n authors?: string[]\n editors?: string[]\n}\n\n/** Settings UI descriptor returned by an editor bundle */\nexport interface EditorBundleSettings<TComponent = unknown> {\n components: TComponent[]\n defaults: Record<string, unknown>\n}\n\n/** A preceding/following phrase for a word, returned by the getRelatedWords editor callback */\nexport interface RelatedWord {\n word: string\n frequency: number\n position: \"preceding\" | \"following\"\n}\n\n/** One redirect followed while fetching a URL from within the editor */\nexport interface EditorFetchURLRedirect {\n /** The redirect's status code (301, 302, 307, ...) */\n status: number\n /** The URL which answered with the redirect */\n url: string\n}\n\n/**\n * Result of fetching a URL from within the editor. It resolves for any HTTP status, so check\n * `status` before trusting `body`; it only rejects when no response arrived at all.\n */\nexport interface EditorFetchURLResult {\n status: number\n body: string\n /** The reason phrase sent with the status, often empty over HTTP/2 */\n statusText?: string\n /** Response headers, with lower-cased names */\n headers?: Record<string, string>\n /** The URL which answered, after any redirects */\n url?: string\n /** Each redirect followed on the way to `url`, in order */\n redirects?: EditorFetchURLRedirect[]\n /** Milliseconds from the first request to the end of the body */\n durationMs?: number\n /** Size of the response body in bytes */\n bodyBytes?: number\n}\n\n/** Config passed to an editor bundle's mount() */\nexport interface EditorMountConfig {\n puzzleString: string\n onChange: (puzzleString: string) => void\n theme: EditorTheme\n width: number\n height: number\n /**\n * Optional function for making chat completions from the editor (e.g. for AI-assisted puzzle\n * editing). This needs to be enabled for a team explicitly.\n */\n chatCompletion?: (prompt: string) => Promise<string>\n /**\n * Optional function for fetching URLs from the editor (e.g. for fetching article content).\n * This needs to be enabled for a team explicitly.\n */\n fetchURL?: (url: string) => Promise<EditorFetchURLResult>\n /** Optional function for looking up a word's preceding/following phrases from wordvault. */\n getRelatedWords?: (word: string, limit?: number) => Promise<RelatedWord[]>\n /** Pre-configured editor settings values from the queue's editorSettings. */\n settings?: Record<string, unknown>\n}\n\n/** Handle returned by an editor bundle's mount() */\nexport interface EditorMountHandle {\n unmount: () => void\n /**\n * Called whenever the puzzle string is updated in the editor from the outside, or when the theme\n * or dimensions update. Workshop will rely on the validator to reject / accept updates.\n */\n update: (config: { puzzleString?: string; theme?: EditorTheme; width?: number; height?: number }) => void\n}\n\n/** Main interface for a Workshop editor bundle */\nexport interface EditorBundle<TSettingsComponent = unknown> {\n /** Required validator for puzzle data validation */\n validator: {\n validate(data: string): Promise<ValidationReport> | ValidationReport\n }\n /** Optional importer for converting external puzzle file formats */\n importer?: {\n onImport(filename: string, contents: string | ArrayBuffer): Promise<ImportResult> | ImportResult\n }\n /** Embed-level settings UI, populated from the bundle's declared settings */\n settings?: EditorBundleSettings<TSettingsComponent>\n /** Editor-level settings UI, populated from the bundle's declared editor settings */\n editorSettings?: EditorBundleSettings<TSettingsComponent>\n /** Custom puzzle editor, if provided by the bundle */\n editor?: {\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AK,IAAM,KAAO,EAAK,MAAM;;EAC3B,IAAM,IAAoB,EAAE,EACtB,IAAA,EAAA,EAAA,EAAA,GAAA,IAAY,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,KAAA,EAAS,EAAK,KAAM,EAC7C,IAAA,EAAA,EAAA,EAAA,GAAA,IAAkB,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,WAAA,EAAe,EAAK,WAAY;AAKrE,EAFI,OAAO,KAAK,EAAK,CAAC,WAAQ,EAAO,OAAO,IACxC,OAAO,KAAK,EAAW,CAAC,WAAQ,EAAO,aAAa,IACxD,EAAO,KAAO;;AAGlB,QAAO;;;ACbT,IAAa,IAAb,cAAuC,MAAM;CAC3C,YACE,GACA,GACA,GACA;AAEA,EADA,MAAM,EAAQ,EAJP,KAAA,OAAA,GAEA,KAAA,gBAAA,GAGP,KAAK,OAAO"}
package/dist/sdk.d.ts CHANGED
@@ -97,8 +97,9 @@ export interface SDKRounds {
97
97
  log: (...events: SDKRoundEvent[]) => void;
98
98
  /**
99
99
  * Picks the round back up for a deal resumed after a reload, instead of `start()`: `events` is the round's whole log
100
- * (`inProgress().events`), and later `log()` calls carry on from it. When the round closed after the
101
- * boot, the SDK emits `roundLost`: drop the deal and `start()` a new one, as nothing played on it can unlock anything.
100
+ * (`inProgress().events`, not a copy the game saved), and later `log()` calls carry on from it. When the round closed
101
+ * after the boot, or `events` is shorter than the server's log, the SDK emits `roundLost`: drop the deal and `start()`
102
+ * a new one, as nothing played on it can unlock anything.
102
103
  */
103
104
  resume: (opts: {
104
105
  puzzleKey?: string;
package/dist/sdk.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sources":["../src/sdk.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACxE,OAAO,KAAK,EACV,qBAAqB,EACrB,gBAAgB,EAChB,QAAQ,EACR,iBAAiB,EACjB,kBAAkB,E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MAAM,MAAM,CAAA;IACpC,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,uCAAuC;IACvC,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAA;IAChC,6FAA6F;IAC7F,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAA;IAChC,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,OAAO,CAAA;IACvB,sCAAsC;IACtC,SAAS,EAAE,MAAM,OAAO,CAAA;IACxB,+FAA+F;IAC/F,KAAK,EAAE,MAAM,IAAI,CAAA;IACjB,kGAAkG;IAClG,MAAM,EAAE,MAAM,IAAI,CAAA;CACnB;AAyKD,2EAA2E;AAC3E,eAAO,MAAM,eAAe,GAAI,KAAK,CAAC,OAAO,SAAS,SAAS,SAAS,EAAE,GAAG,EAAE,YACpE,gBAAgB,CAAC,OAAO,CAAC,KACjC,SAAS,CAAC,OAAO,CA4hBnB,CAAA"}
package/dist/types.d.ts CHANGED
@@ -1032,10 +1032,10 @@ export type MessagesSentFromEmbed = {
1032
1032
  };
1033
1033
  };
1034
1034
  /**
1035
- * A deal resumed after a reload picks its round back up. `events` is the whole log the game saved for the deal; the
1036
- * host asks the server for the open round on `puzzleKey` and sends only what the server lacks. With no such round,
1037
- * or a server holding more than the game saved, the host answers `REPEATABLE_ROUND_LOST` and the game deals afresh.
1038
- * Send via `sdk.rounds.resume()`.
1035
+ * A deal resumed after a reload picks its round back up. `events` is the round's whole log as `sdk.rounds.inProgress()`
1036
+ * handed it back, not a copy the game saved; the host asks the server for the open round on `puzzleKey` and sends only
1037
+ * what the server lacks. With no such round, or a server holding more events than these, the host answers
1038
+ * `REPEATABLE_ROUND_LOST` and the game deals afresh. Send via `sdk.rounds.resume()`.
1039
1039
  */
1040
1040
  RESUME_REPEATABLE_ROUND: {
1041
1041
  puzzleKey?: string;
@@ -1195,8 +1195,9 @@ export type MessagesReceived = {
1195
1195
  };
1196
1196
  /**
1197
1197
  * The deal the game resumed with `RESUME_REPEATABLE_ROUND` has no round the server can carry on: it closed after a
1198
- * quiet day, another deal started since, or the server holds more of its log than the game saved. Nothing played on
1199
- * it could unlock an achievement, so the game drops the deal and starts a new one. `sdk.on("roundLost")` hears it.
1198
+ * quiet day, another deal started since, or the game resumed with fewer events than the server holds. Nothing
1199
+ * played on it could unlock an achievement, so the game drops the deal and starts a new one. `sdk.on("roundLost")`
1200
+ * hears it.
1200
1201
  */
1201
1202
  REPEATABLE_ROUND_LOST: object;
1202
1203
  /** The host's answer to `REQUEST_CONFIRM`: whether the player confirmed. */