// Type definitions for the Game Platform SDK v1 (https://PORTAL_DOMAIN/sdk/v1/gp-sdk.js) // Copy into a TypeScript project as gp-sdk.d.ts; the SDK itself is always loaded from the portal. export interface GPUser { signedIn: boolean; username: string | null; } /** * The game's own currency (gp-manifest.json "currency"). Players hold Sweet Credits (1 Credit = $0.01), * one balance shared by every Sweet game; your game shows that balance in its own units. * Games without a "currency" are priced in Credits (custom: false, credits_per_unit: 1). */ export interface GPCurrency { name: string; plural: string; /** Conversion rate: Credits per unit. display = floor(credits / credits_per_unit); debit = price x credits_per_unit */ credits_per_unit: number; icon?: string | null; custom: boolean; } /** The player's shared Sweet balance, shown in this game's currency */ export interface GPBalance { /** floor(credits / credits_per_unit): what to show the player */ units: number; /** the underlying Sweet Credits */ credits: number; /** the currency's plural name */ currency: string; } export interface GPItem { key: string; title: string; description: string; /** price in the game's currency (what the creator set in the manifest) */ price: number; /** Credits debited from the shared balance per item: price x credits_per_unit */ price_points: number; max_per_session: number; inventory_limit: number; icon_url?: string | null; } /** A monthly membership the game sells in its currency (gp-manifest.json "memberships") */ export interface GPMembershipPlan { key: string; title: string; description: string; /** price per month in the game's currency */ price: number; /** Credits charged per month: price x credits_per_unit */ price_points: number; perks: string[]; } export interface GPSession { sessionId: string; /** Consumables actually granted for this session (owned and within max_per_session) */ consumables: string[]; /** Membership plans the player is a member of for this session: apply their perks */ memberships: string[]; /** false for guests or when the game has no leaderboard */ leaderboardEligible: boolean; } export interface GPEndResult { recorded: boolean; score: number; /** false when the player is a guest, flagged, or the session failed verification (no reason is given) */ leaderboard_eligible: boolean; /** today's board (days start at midnight Pacific time) */ daily_rank: number | null; weekly_rank: number | null; all_time_rank: number | null; best_score: number | null; /** debug mode only */ debug_report?: GPDebugReport; } export interface GPDebugReport { ok: boolean; problems: string[]; notes: string[]; summary: { score: number; computed_score: number | null; duration_ms: number; events: number; inputs: number; primary_inputs: number; frames: number; }; } export interface GPLeaderboardEntry { rank: number; username: string; /** The player's avatar picture, or null: show their initial instead */ avatar_url?: string | null; score: number; } export interface GPMenu { corner: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; width: number; height: number; /** Set once the player has dragged the pill: its distance from the corner's edges, in CSS pixels */ x?: number; y?: number; moved?: boolean; } export interface GPLeaderboard { period: 'daily' | 'weekly' | 'all_time'; count: number; entries: GPLeaderboardEntry[]; me: { rank: number | null; username: string; score: number | null } | null; } // --- online play: gp.multiplayer ------------------------------------------------------------------------- // Rooms run on Sweet's relay; the game never opens a connection itself. See /docs/creators#multiplayer. /** A way to play online, from gp-manifest.json "multiplayer.modes" */ export interface GPMultiplayerMode { key: string; title: string; description: string; /** Skill-rated: quick match only, signed-in players only, every match ends with reportResult */ ranked: boolean; maxPlayers: number; } export interface GPPlayer { /** 0-15, stable for the player while they're in the room (also across reconnects) */ seat: number; /** The player's id in this game: a pseudonym, the same in every room of this game */ id: string; /** Sweet username, or "Guest 4821" */ name: string; guest: boolean; /** false while they're reconnecting (their seat is held) */ connected: boolean; host: boolean; me: boolean; } export interface GPRoom { /** 6 characters (no 0/O/1/I): what friends type into joinRoom */ code: string; mode: string; ranked: boolean; visibility: 'private' | 'public'; maxPlayers: number; /** A match is running (startMatch); nobody new joins unless the game allows joining in progress */ started: boolean; /** The room's match count: 1 for its first match */ match: number; hostSeat: number | null; mySeat: number; isHost: boolean; players: GPPlayer[]; } /** Whether this player can play ranked right now, and why not */ export interface GPRankedStatus { available: boolean; reason: 'sign_in' | 'update' | 'cooldown' | 'unavailable' | null; /** Ready to show the player, e.g. "Sign in to play ranked." */ message: string | null; /** cooldown: when ranked opens again (ISO 8601) */ until: string | null; } /** Best first. [[2], [0, 3], [1]]: seat 2 won, seats 0 and 3 tied for second (or were team-mates), seat 1 came last */ export type GPPlacements = number[][]; export interface GPMatchResult { placements: GPPlacements; scores?: Record; /** game data that came with the result (at most 1,000 characters) */ data?: string; /** players who reported this result, of those in the room */ agreed: number; of: number; /** every other player left a ranked match: the platform reported it */ forfeit?: boolean; } export interface GPRating { rating: number; games: number; wins: number; losses: number; /** null until the player has played enough rated matches to be ranked */ rank: number | null; placementGamesLeft: number; } export interface GPRatingBoard { mode: string; count: number; entries: { rank: number; username: string; rating: number; games: number; wins: number }[]; me: GPRating | null; } export interface GPMultiplayer { /** The game declares "multiplayer" in gp-manifest.json */ readonly enabled: boolean; readonly modes: GPMultiplayerMode[]; readonly ranked: GPRankedStatus; /** The room the player is in, or null */ readonly room: GPRoom | null; isHost(): boolean; /** * The room code of the invite link this player opened (inviteLink), or null. Once your menu is ready, call * joinRoom(mp.invite) (it's null again once they're in that room). Reading it tells the play page your game takes * invites; games that never read it get the play page's own "you're invited to room CODE" note instead. */ readonly invite: string | null; /** * The link that opens this game straight into a room, for an "Invite friends" / "Copy invite" button. code * defaults to the room the player is in; null without one, or for ranked rooms (quick match fills those). */ inviteLink(code?: string): string | null; /** Join the fullest open public room of this mode (ranked: nearest in skill), or open one. The only way into ranked. */ quickMatch(options?: { mode?: string }): Promise; /** Open a room you host; share room.code with friends (private) or let quick match fill it (public). Not for ranked modes. */ createRoom(options?: { mode?: string; visibility?: 'private' | 'public' }): Promise; joinRoom(code: string): Promise; /** Open public rooms of a mode near the player, fullest first */ listRooms(options?: { mode?: string }): Promise<{ code: string; players: number; maxPlayers: number }[]>; /** Leave on purpose. In a started match that's an abandon (ranked: placed last, and repeat leavers wait before ranked). */ leave(): Promise; /** * Send JSON-serialisable data. to: 'others' (default), 'host' (whoever hosts now), a seat or seats. * The platform stamps who sent it; size and rate are limited (oversize or flooding messages are dropped). */ send(data: unknown, options?: { to?: 'others' | 'host' | number | number[] }): void; /** Host: start the match. Closes the room to newcomers and, in ranked modes, starts each player's match session. */ startMatch(): void; /** Host: back to the lobby (a rematch starts with startMatch again) */ endMatch(): void; /** Host: the match's latest state (JSON, at most the checkpoint limit, at most every 400 ms); the next host receives it */ checkpoint(state: unknown): void; /** Host of a private room: remove a player (they can't come back to this room) */ kick(seat: number): void; /** Ask to remove a player; a majority of the other players removes them (not in a started ranked match: report them) */ voteKick(seat: number): void; /** * Every player reports the result they saw when a match ends; the result most players agree on counts (the host alone * can't decide it). Ranked modes are rated from it. Resolves with the agreed result. */ reportResult( result: { placements: GPPlacements } | { winners: number[] } | { ranking: number[] }, extra?: { scores?: Record; data?: string }, ): Promise; /** The platform's chat (filtered; signed-in players only; 1 line a second) */ chat(text: string): void; /** Open the platform's chat and player panel (players, report, vote-kick); the game gets 'pause' then 'resume' */ showPlayers(): Promise<{ shown: boolean }>; /** Report a player to Sweet's moderators, with the room's recent chat */ report(seat: number, reason: 'cheating' | 'abuse' | 'name' | 'other', note?: string): Promise; /** A ranked mode's board and the player's own rating */ getRatings(options?: { mode?: string; limit?: number }): Promise; on(event: 'message', callback: (data: unknown, fromSeat: number) => void): void; on(event: 'join', callback: (player: GPPlayer) => void): void; on(event: 'leave', callback: (info: { seat: number; reason: 'left' | 'expired' | 'kicked' }) => void): void; /** A player's connection dropped; their seat is held for `ms` */ on(event: 'away', callback: (info: { seat: number; ms: number }) => void): void; on(event: 'back', callback: (info: { seat: number }) => void): void; /** The host dropped; the host moves in `ms` unless they return */ on(event: 'hostwait', callback: (info: { seat: number; ms: number }) => void): void; /** Someone new hosts. When it's you (isMe), carry on from `checkpoint`, the last state the old host sent. */ on( event: 'host', callback: (info: { seat: number | null; previous: number | null; reason: 'host_left' | 'host_dropped' | 'host_kicked' | 'joined'; isMe: boolean; checkpoint?: unknown }) => void, ): void; on(event: 'start', callback: (info: { match: number }) => void): void; on(event: 'end', callback: () => void): void; on(event: 'result', callback: (result: GPMatchResult) => void): void; on(event: 'chat', callback: (line: { seat: number; name: string; text: string }) => void): void; /** Someone asked to remove a player: `votes` of the `needed` majority so far */ on(event: 'votekick', callback: (info: { seat: number; votes: number; needed: number }) => void): void; /** The room is gone: empty, idle (10 min), lifetime (4 h), disabled (Sweet switched online play off) */ on(event: 'closed', callback: (info: { reason: 'empty' | 'idle' | 'lifetime' | 'disabled' | 'kicked' | string }) => void): void; /** The platform reconnects by itself; show "reconnecting…" while state is 'reconnecting' */ on(event: 'connection', callback: (info: { state: 'connecting' | 'connected' | 'reconnecting' | 'lost' }) => void): void; on(event: 'ranked', callback: (status: GPRankedStatus) => void): void; /** Something was refused or dropped: { code, message } (see the creator guide's error codes) */ on(event: 'error', callback: (error: { code: string; message: string }) => void): void; off(event: string, callback: (...args: any[]) => void): void; } /** A save of the player's progress, as gp.progress.load() returns it */ export interface GPSavedProgress { /** What the game saved: any JSON (an object, array, string or number) */ data: any; /** When it was saved (ISO 8601) */ savedAt: string; } /** * The player's saved progress in this game (levels reached, unlocks earned, upgrades, a story's place), free on * every plan. Signed-in players keep it on their Sweet account and continue on any device; guests keep it on this * device until they sign in, when it moves to their account. Never put purchases, currency or anything of value in * it: the player's browser writes it (inventory, memberships and the balance stay with Sweet). See /docs/creators#progress */ export interface GPProgress { /** Load the saved progress once at start, before showing the menu: null when there's none (a new player) */ load(): Promise; /** * Save the player's progress, the whole state each time, as JSON of at most 64 KB. Call it at checkpoints (a * level finished, an upgrade bought, settings changed), not every frame: the SDK batches saves (at most one write * every 10 s, the latest wins) and sends what's pending when the player leaves. Resolves once it's stored. * Rejects with 'progress_too_large', 'invalid_progress', 'rate_limited' or 'progress_conflict' (another device * saved or reset since: the 'progress_conflict' event has that save). */ save(data: any): Promise<{ savedAt: string | null }>; /** Send a pending save now (before a big change of scene, say); saves are sent anyway as the player leaves */ flush(): Promise<{ savedAt: string | null }>; /** * Let the player start over: Sweet asks them first ("All your progress will be lost") in its own dialog. Resolves * { reset: true } once the progress is deleted (start the game fresh), or { reset: false } if they cancel. Give * players a "Reset progress" button (in settings or on the title screen) that calls it. */ reset(): Promise<{ reset: boolean }>; /** When the progress was last saved or loaded (ISO 8601), or null */ readonly savedAt: string | null; } export interface GamePlatformError extends Error { /** * e.g. not_signed_in, cancelled, insufficient_balance, insufficient_inventory, rate_limited, timeout; online play: * not_available, sign_in_required, room_not_found, room_full, room_started, version_mismatch, kicked, * multiplayer_disabled, ranked_quick_match, ranked_unavailable, not_entitled, already_in_room, match_session, network; * saved progress: progress_conflict, progress_too_large, invalid_progress, storage_unavailable */ code: string; /** progress_conflict: the save as it is now (null: it was reset on another device) */ current?: { data: any; version: number; saved_at: string } | null; } export interface GP { readonly version: string; readonly user: GPUser; readonly items: GPItem[]; /** The game's currency and its rate in Sweet Credits */ readonly currency: GPCurrency; /** The player's balance in this game's currency; null for guests. Display only: the platform charges. */ readonly balance: GPBalance | null; /** * Where the play page's Sweet menu (a small floating pill) sits over the game, in CSS pixels: in its corner, the * area to keep clear (at least 300 x 60, more when the pill reaches further). Keep it free of the game's own buttons, * or pick another corner with gp-manifest.json `menu_corner`. Players can drag the pill anywhere: then `moved` is * true, `x`/`y` are its distance from `corner`'s edges and width/height its own size. The 'menu' event fires on * every change. */ readonly menu: GPMenu; /** item key -> quantity owned */ readonly inventory: Record; readonly membershipPlans: GPMembershipPlan[]; /** keys of the plans the player is a member of now */ readonly memberships: string[]; readonly debug: boolean; /** Online play (gp-manifest.json "multiplayer"); `enabled` is false for games without it */ readonly multiplayer: GPMultiplayer; /** The player's saved progress in this game: load(), save(data), reset() */ readonly progress: GPProgress; /** Begin a play session. Recording starts when the promise resolves. */ startSession(options?: { consumables?: string[] }): Promise; /** Report a gameplay event declared in gp-manifest.json "events". Ignored outside a session. */ event(name: string, value?: number): void; /** Finish the session and submit the score. Call exactly once per startSession(). */ endSession(options: { score: number }): Promise; isSessionActive(): boolean; /** Ask the platform to sell an item; the platform shows its own confirmation. */ purchase(itemKey: string, quantity?: number): Promise<{ completed: boolean; inventory: Record }>; isMember(planKey: string): boolean; /** * Ask the player to join a monthly membership. The platform shows the price and perks and charges * their credits every month until they cancel. Rejects with 'cancelled', 'not_signed_in' or * 'insufficient_balance' (the platform offers to add credits). */ joinMembership(planKey: string): Promise<{ joined: boolean; memberships: string[] }>; /** True when the player is signed in to their Sweet account. */ isSignedIn(): boolean; /** * Send the player to Sweet's sign-in, the one account for every game on Sweet. With * { mode: 'signup' } it opens the create-account page. The platform leaves the game for its own * pages and reloads it signed in (then `user.signedIn` is true and the 'auth' event fires). * Resolves at once with the user when they're already signed in. * Without code: