@splattervault/server 0.0.0-stage → 0.1.0
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/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +364 -2
- package/dist/index.cjs +1584 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +13260 -0
- package/dist/index.d.ts +13260 -0
- package/dist/index.js +39 -0
- package/package.json +80 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/operations.ts","../src/core/errors.ts","../src/core/retry.ts","../src/core/validate.ts","../src/core/http.ts","../src/version.ts","../src/playerToken/jwks.ts","../src/playerToken/verify.ts","../src/resources/billing.ts","../src/resources/playerData.ts","../src/resources/players.ts","../src/resources/sessions.ts","../src/resources/store.ts","../src/client.ts","../src/sessionEnv.ts"],"names":["text","randomUUID","conditional","createPublicKey","KID_RE","p","verifySignature"],"mappings":";;;;;;;AAeA,IAAM,IAAA,GAAO,GAAA;AACb,IAAM,MAAA,GAAS,IAAA;AAMR,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,uBAAA,EAAyB,EAAE,MAAA,EAAQ,MAAA,EAAQ,MAAM,mBAAA,EAAqB,KAAA,EAAO,OAAA,EAAS,SAAA,EAAW,IAAA,EAAK;AAAA,EACtG,uBAAuB,EAAE,MAAA,EAAQ,OAAO,IAAA,EAAM,mBAAA,EAAqB,OAAO,MAAA,EAAO;AAAA,EACjF,qBAAA,EAAuB,EAAE,MAAA,EAAQ,MAAA,EAAQ,MAAM,oCAAA,EAAsC,KAAA,EAAO,OAAA,EAAS,SAAA,EAAW,IAAA,EAAK;AAAA,EACrH,yBAAyB,EAAE,MAAA,EAAQ,OAAO,IAAA,EAAM,6CAAA,EAA+C,OAAO,OAAA,EAAQ;AAAA,EAC9G,6BAA6B,EAAE,MAAA,EAAQ,OAAO,IAAA,EAAM,wCAAA,EAA0C,OAAO,OAAA,EAAQ;AAAA,EAC7G,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,CAAK,GAAA,EAAK,eAAe,CAAA;AAAA,IACvC,YAAA,EAAc,IAAA,CAAK,GAAA,EAAK,eAAe,CAAA;AAAA,IACvC,SAAA,EAAW,WAAA,CAAY,IAAA,CAAK,GAAA,EAAK,YAAY,CAAC;AAAA,GAChD;AACF","file":"index.cjs","sourcesContent":["import { type RetryMode } from \"./core/retry.js\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport interface OperationSpec {\n method: HttpMethod;\n /** The path below the base URL, with `{name}` placeholders, exactly as the API description writes it. */\n path: string;\n retry: RetryMode;\n /** Overrides the client's `timeoutMs` default for this operation (slow operations: imports, server creation). */\n timeoutMs?: number;\n /** A POST that only reads (it never changes anything, so its outcome is never unknown). GETs are reads anyway. */\n read?: true;\n}\n\nconst SLOW = 60_000;\nconst IMPORT = 120_000;\n\n/**\n * Every operation of the Studio API this SDK calls with an organization API key, by its `operationId`. The contract\n * test checks this table against `openapi/studio-api.json` in both directions.\n */\nexport const OPERATIONS = {\n // ── Game-server sessions ───────────────────────────────────────────────────────────────────────────────────────\n \"sessions.createCredit\": { method: \"POST\", path: \"/credits/sessions\", retry: \"never\", timeoutMs: SLOW },\n \"sessions.listCredit\": { method: \"GET\", path: \"/credits/sessions\", retry: \"safe\" },\n \"sessions.stopCredit\": { method: \"POST\", path: \"/credits/sessions/{sessionId}/stop\", retry: \"never\", timeoutMs: SLOW },\n \"sessions.renameCredit\": { method: \"PUT\", path: \"/credits/sessions/{sessionId}/friendly-name\", retry: \"never\" },\n \"sessions.rescheduleCredit\": { method: \"PUT\", path: \"/credits/sessions/{sessionId}/schedule\", retry: \"never\" },\n \"sessions.cancelScheduledCredit\": { method: \"POST\", path: \"/credits/sessions/{sessionId}/cancel-schedule\", retry: \"never\" },\n \"sessions.createSubscription\": { method: \"POST\", path: \"/subscriptions/sessions\", retry: \"never\", timeoutMs: SLOW },\n \"sessions.listSubscription\": { method: \"GET\", path: \"/subscriptions/sessions\", retry: \"safe\" },\n \"sessions.stopSubscription\": { method: \"POST\", path: \"/subscriptions/sessions/{sessionId}/stop\", retry: \"never\", timeoutMs: SLOW },\n \"sessions.renameSubscription\": { method: \"PUT\", path: \"/subscriptions/sessions/{sessionId}/friendly-name\", retry: \"never\" },\n \"sessions.rescheduleSubscription\": { method: \"PUT\", path: \"/subscriptions/sessions/{sessionId}/schedule\", retry: \"never\" },\n \"sessions.cancelScheduledSubscription\": {\n method: \"POST\",\n path: \"/subscriptions/sessions/{sessionId}/cancel-schedule\",\n retry: \"never\"\n },\n \"sessions.listMine\": { method: \"GET\", path: \"/game-sessions/my-sessions\", retry: \"safe\" },\n \"sessions.get\": { method: \"GET\", path: \"/game-sessions/{id}\", retry: \"safe\" },\n \"games.getConfigurableArgs\": { method: \"GET\", path: \"/game-types/{id}/configurable-args\", retry: \"safe\" },\n \"serverPools.claim\": { method: \"POST\", path: \"/server-pools/{id}/claim\", retry: \"never\", timeoutMs: SLOW },\n\n // ── Billing ────────────────────────────────────────────────────────────────────────────────────────────────────\n \"billing.getCredits\": { method: \"GET\", path: \"/credits\", retry: \"safe\" },\n \"billing.getCreditStats\": { method: \"GET\", path: \"/credits/stats\", retry: \"safe\" },\n \"billing.getKeyOrgCredits\": { method: \"GET\", path: \"/org/credits\", retry: \"safe\" },\n \"billing.getKeyOrgSubscriptions\": { method: \"GET\", path: \"/org/subscription\", retry: \"safe\" },\n \"billing.getOrgCredits\": { method: \"GET\", path: \"/organizations/{orgId}/credits\", retry: \"safe\" },\n \"billing.getOrgSubscription\": { method: \"GET\", path: \"/organizations/{orgId}/subscription\", retry: \"safe\" },\n \"billing.getSubscriptions\": { method: \"GET\", path: \"/subscriptions\", retry: \"safe\" },\n \"billing.getUsage\": { method: \"GET\", path: \"/subscriptions/usage\", retry: \"safe\" },\n\n // ── Player sign-in (studio backend) ────────────────────────────────────────────────────────────────────────────\n \"playerAuth.studio.signIn\": { method: \"POST\", path: \"/player-auth/studio\", retry: \"never\" },\n // \"running the same rows again changes nothing\"; 503 import_busy: \"send the same batch again\".\n \"playerAuth.studio.importPlayers\": { method: \"POST\", path: \"/player-auth/studio/import\", retry: \"safe\", timeoutMs: IMPORT },\n \"playerAuth.studio.erasePlayer\": { method: \"DELETE\", path: \"/player-auth/studio/players/{playerId}\", retry: \"never\" },\n\n // ── Player data (studio backend) ───────────────────────────────────────────────────────────────────────────────\n // \"A lookup only: nobody is created.\"\n \"studioData.resolvePlayers\": { method: \"POST\", path: \"/studio-data/games/{gameId}/players/resolve\", retry: \"safe\", read: true },\n \"studioData.getPlayerData\": { method: \"GET\", path: \"/studio-data/games/{gameId}/players/{playerId}/data\", retry: \"safe\" },\n \"studioData.updatePlayerData\": { method: \"PATCH\", path: \"/studio-data/games/{gameId}/players/{playerId}/data\", retry: \"if-version\" },\n // 204 \"Deleted (or there was nothing)\".\n \"studioData.clearPlayerData\": { method: \"DELETE\", path: \"/studio-data/games/{gameId}/players/{playerId}/data\", retry: \"safe\" },\n \"studioData.getPlayersData\": { method: \"POST\", path: \"/studio-data/games/{gameId}/data/get\", retry: \"safe\", read: true },\n \"studioData.writePlayersData\": { method: \"POST\", path: \"/studio-data/games/{gameId}/data/write\", retry: \"if-version\" },\n \"studioData.getGameData\": { method: \"GET\", path: \"/studio-data/games/{gameId}/game-data\", retry: \"safe\" },\n \"studioData.updateGameData\": { method: \"PATCH\", path: \"/studio-data/games/{gameId}/game-data\", retry: \"if-version\" },\n // \"Re-sending the same rows changes nothing.\"\n \"studioData.importData\": { method: \"POST\", path: \"/studio-data/games/{gameId}/import\", retry: \"safe\", timeoutMs: IMPORT },\n \"studioData.listErasedPlayers\": { method: \"GET\", path: \"/studio-data/erased-players\", retry: \"safe\" },\n\n // ── Store (studio backend) ─────────────────────────────────────────────────────────────────────────────────────\n \"store.studio.getCatalog\": { method: \"GET\", path: \"/store/studio/catalog\", retry: \"safe\" },\n \"store.studio.getPlayer\": { method: \"GET\", path: \"/store/studio/players/{player}\", retry: \"safe\" },\n \"store.studio.getPlayerHistory\": { method: \"GET\", path: \"/store/studio/players/{player}/history\", retry: \"safe\" },\n \"store.studio.grant\": { method: \"POST\", path: \"/store/studio/players/{player}/grants\", retry: \"idempotency-key\" },\n \"store.studio.consume\": { method: \"POST\", path: \"/store/studio/players/{player}/consume\", retry: \"idempotency-key\" },\n \"store.studio.purchase\": { method: \"POST\", path: \"/store/studio/players/{player}/purchases\", retry: \"idempotency-key\" },\n \"store.studio.updateItem\": { method: \"PATCH\", path: \"/store/studio/players/{player}/items/{instanceId}\", retry: \"idempotency-key\" },\n \"store.studio.reverse\": { method: \"POST\", path: \"/store/studio/players/{player}/reversals\", retry: \"idempotency-key\" },\n \"store.studio.syncMetaPurchases\": { method: \"POST\", path: \"/store/studio/players/{player}/platform-purchases/meta\", retry: \"never\" },\n // \"re-running a file changes nothing\" (catalog); holdings: \"the same row again is unchanged\" (once per source).\n \"store.studio.importCatalog\": { method: \"POST\", path: \"/store/studio/imports/catalog\", retry: \"safe\", timeoutMs: IMPORT },\n \"store.studio.importHoldings\": { method: \"POST\", path: \"/store/studio/imports/holdings\", retry: \"safe\", timeoutMs: IMPORT }\n} as const satisfies Record<string, OperationSpec>;\n\nexport type OperationId = keyof typeof OPERATIONS;\n\n/** The public keys that sign player tokens (no credential: never sent with your API key). */\nexport const PLAYER_TOKEN_KEYS_PATH = \"/player-auth/keys\";\n","/**\n * Codes the SDK itself sets on a {@link SplatterVaultError}. With `status` 0 (no HTTP answer): `network_error`,\n * `timeout`, `aborted`. With the answer's status: `invalid_response`, `redirect_not_followed`, `outcome_unknown`.\n */\nexport const SDK_ERROR_CODES = {\n /** No answer: no connection, a reset, a DNS or TLS failure. The request may or may not have arrived. */\n networkError: \"network_error\",\n /** No answer within `timeoutMs`. The request may or may not have arrived. */\n timeout: \"timeout\",\n /** Your `signal` aborted the call. */\n aborted: \"aborted\",\n /** The answer was not the JSON the SDK expected (the HTTP status is kept). */\n invalidResponse: \"invalid_response\",\n /**\n * The API answered a redirect (3xx). The SDK never follows one, so your API key never travels to another address;\n * `details.location` says where it pointed. Check `baseUrl` (it must be the https URL the API is served at).\n */\n redirectNotFollowed: \"redirect_not_followed\",\n /**\n * A player-data write with `ifVersion` was sent again after an answer that proved it was not applied, and the second\n * send met `version_conflict`: the first may have been applied after all (`outcomeUnknown` is true). Re-read.\n */\n outcomeUnknown: \"outcome_unknown\"\n} as const;\n\n/** One of the codes the SDK sets itself; see {@link SDK_ERROR_CODES}. */\nexport type SdkErrorCode = (typeof SDK_ERROR_CODES)[keyof typeof SDK_ERROR_CODES];\n\n/** HTTP statuses the SDK treats as \"try again later\" (with network errors and timeouts): 408, 429, 500, 502, 503, 504. */\nexport const TRANSIENT_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/** Transient answers that prove the request was not applied (refused before it ran): 408, 429, 503. */\nexport const NOT_APPLIED_STATUSES: ReadonlySet<number> = new Set([408, 429, 503]);\n\n/** Answers after which a write may or may not have been applied (with no answer at all): 500, 502, 504. */\nexport const OUTCOME_UNKNOWN_STATUSES: ReadonlySet<number> = new Set([500, 502, 504]);\n\nexport interface SplatterVaultErrorInit {\n status: number;\n code: string | null;\n message: string;\n operationId: string;\n method: string;\n path: string;\n details?: unknown;\n retryAfter?: number | null;\n requestId?: string | null;\n errorName?: string | null;\n errors?: unknown[] | null;\n body?: unknown;\n attempts?: number;\n outcomeUnknown?: boolean;\n idempotencyKey?: string | null;\n cause?: unknown;\n}\n\n/**\n * A refusal from the SplatterVault API, or a call that got no answer.\n *\n * Act on {@link SplatterVaultError.code | code} (the API's stable `error` code such as `insufficient_funds`,\n * `version_conflict` or `rate_limited`), never on `message`: the message is a sentence for people and may change.\n * The set of codes is open: handle an unknown code by its HTTP {@link SplatterVaultError.status | status}.\n *\n * Two answer shapes are read:\n * - the studio routes' `{ \"error\", \"message\", \"details\"? }` (player sign-in, player data, the store);\n * - the game-server session and billing routes' `{ \"name\", \"message\", \"status\", \"errors\" }`, which has no code:\n * `code` is null and {@link SplatterVaultError.errorName | errorName} holds `name` (such as `BAD_REQUEST`).\n * Their platform-ban answer `{ \"banned\": true, ... }` is read as code `banned`.\n *\n * `status` 0 means no HTTP answer: the code is then `network_error`, `timeout` or `aborted`.\n *\n * When a write failed without a clear answer, {@link SplatterVaultError.outcomeUnknown | outcomeUnknown} is true: it\n * may or may not have been applied. Store changes: send it again with the same\n * {@link SplatterVaultError.idempotencyKey | idempotencyKey} (and the same body), never without it. Player-data writes:\n * read the key again; if its version moved and the value is the one you wrote, your write was applied.\n */\nexport class SplatterVaultError extends Error {\n override readonly name = \"SplatterVaultError\";\n /** The HTTP status; 0 when no answer arrived (network error, timeout, abort). */\n readonly status: number;\n /** The API's `error` code, an SDK code ({@link SDK_ERROR_CODES}), or null when the answer had none. */\n readonly code: string | null;\n /** The answer's `details` (e.g. the current versions of a `version_conflict`), or undefined. */\n readonly details: unknown;\n /** The answer's `Retry-After`, in seconds: do not send this request again sooner. Null when absent. */\n readonly retryAfter: number | null;\n /** The answer's `x-request-id` (quote it when you contact SplatterVault support). Null when absent. */\n readonly requestId: string | null;\n /** The session and billing routes' `name` (e.g. `NOT_FOUND`), or null. */\n readonly errorName: string | null;\n /** The session and billing routes' validation `errors`, or null. */\n readonly errors: unknown[] | null;\n /** The parsed answer body, as received (never holds your API key). */\n readonly body: unknown;\n /** The API operation that failed, e.g. `store.studio.grant`. */\n readonly operationId: string;\n /** The HTTP method of the failed request. */\n readonly method: string;\n /** The request path (below the base URL, without the query). */\n readonly path: string;\n /** How many times the request was sent, retries included (0 when it never left). */\n readonly attempts: number;\n /**\n * True when this write may or may not have been applied: no answer, a 500, 502 or 504 (on any attempt), an abort\n * while a send was under way, or a resent player-data write that met `version_conflict` (code `outcome_unknown`).\n * Always false for reads.\n */\n readonly outcomeUnknown: boolean;\n /**\n * The `Idempotency-Key` the store change was sent with (yours or the one the SDK made), or null for other\n * operations. To resolve an unknown outcome, send the same change again with `{ idempotencyKey: err.idempotencyKey }`.\n */\n readonly idempotencyKey: string | null;\n\n constructor(init: SplatterVaultErrorInit) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.status = init.status;\n this.code = init.code;\n this.details = init.details;\n this.retryAfter = init.retryAfter ?? null;\n this.requestId = init.requestId ?? null;\n this.errorName = init.errorName ?? null;\n this.errors = init.errors ?? null;\n this.body = init.body;\n this.operationId = init.operationId;\n this.method = init.method;\n this.path = init.path;\n this.attempts = init.attempts ?? 0;\n this.outcomeUnknown = init.outcomeUnknown ?? false;\n this.idempotencyKey = init.idempotencyKey ?? null;\n }\n\n /** True when {@link SplatterVaultError.code | code} is `code`. */\n is(code: string): boolean {\n return this.code === code;\n }\n\n /** No answer arrived (a network error or a timeout): the request may or may not have been applied. */\n get isNetworkError(): boolean {\n return this.status === 0 && (this.code === SDK_ERROR_CODES.networkError || this.code === SDK_ERROR_CODES.timeout);\n }\n\n /**\n * The same request may succeed later: no answer arrived, or the API answered 408, 429, 500, 502, 503 or 504. Whether\n * the SDK sent it again by itself depends on the operation (see the README's retry rules).\n */\n get isTransient(): boolean {\n return this.isNetworkError || TRANSIENT_STATUSES.has(this.status);\n }\n\n /** @internal The same error with other fields (the SDK's final touches: attempts, outcome, key). */\n with(changes: Partial<SplatterVaultErrorInit>): SplatterVaultError {\n return new SplatterVaultError({\n status: this.status,\n code: this.code,\n message: this.message,\n operationId: this.operationId,\n method: this.method,\n path: this.path,\n details: this.details,\n retryAfter: this.retryAfter,\n requestId: this.requestId,\n errorName: this.errorName,\n errors: this.errors,\n body: this.body,\n attempts: this.attempts,\n outcomeUnknown: this.outcomeUnknown,\n idempotencyKey: this.idempotencyKey,\n cause: this.cause,\n ...changes\n });\n }\n}\n\n/** Reads `Retry-After` (whole seconds or an HTTP date) as seconds to wait; null when absent or unreadable. */\nexport function parseRetryAfter(header: string | null | undefined, nowMs: number = Date.now()): number | null {\n if (header == null) return null;\n const text = header.trim();\n if (text === \"\") return null;\n if (/^\\d+$/.test(text)) return Math.min(Number(text), 86_400);\n // An HTTP date (\"Sun, 15 Nov 2026 01:00:03 GMT\"): it names a weekday or month; \"-1\" or \"1.5\" is no date.\n if (!/[a-z]{3}/i.test(text)) return null;\n const at = Date.parse(text);\n if (Number.isNaN(at)) return null;\n return Math.max(0, (at - nowMs) / 1000);\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** What an error answer's body says, in either shape (see {@link SplatterVaultError}). */\nexport function readErrorBody(body: unknown): {\n code: string | null;\n message: string | null;\n details: unknown;\n errorName: string | null;\n errors: unknown[] | null;\n} {\n const out = { code: null as string | null, message: null as string | null, details: undefined as unknown, errorName: null as string | null, errors: null as unknown[] | null };\n if (!isRecord(body)) return out;\n if (typeof body.error === \"string\") out.code = body.error;\n if (typeof body.message === \"string\") out.message = body.message;\n if (body.details !== undefined && body.details !== null) out.details = body.details;\n if (out.code === null) {\n if (body.banned === true) {\n // The session and billing routes' platform ban: { banned, type, scopes, reason }.\n out.code = \"banned\";\n if (typeof body.reason === \"string\") out.message = body.reason;\n out.details = { type: body.type, scopes: body.scopes };\n } else {\n if (typeof body.name === \"string\") out.errorName = body.name;\n if (Array.isArray(body.errors)) out.errors = body.errors;\n }\n }\n return out;\n}\n","import { type SplatterVaultError } from \"./errors.js\";\n\n/**\n * When a request may be sent again by the SDK itself.\n *\n * - `\"safe\"`: reads, lookups and writes the API documents as safe to repeat (imports, clearing a player's data); after\n * any transient failure (no answer, 408, 429, 500, 502, 503, 504).\n * - `\"idempotency-key\"`: store changes; after any transient failure, with the same `Idempotency-Key` and the same body.\n * - `\"if-version\"`: player-data writes, only when every op carries `ifVersion`, and only after an answer that proves\n * nothing was applied (408, 429, 503). After no answer, a 500, 502 or 504 the outcome is unknown: the SDK does not\n * send it again (a resend could meet the first write's own new version) and the error says `outcomeUnknown`.\n * - `\"never\"`: creating, stopping or claiming servers, sign-ins, erasing a player, data writes without `ifVersion`,\n * the Meta purchase check: a repeat could act twice, so the SDK leaves it to you.\n */\nexport type RetryMode = \"safe\" | \"idempotency-key\" | \"if-version\" | \"never\";\n\nexport interface RetrySettings {\n /** Retries after the first attempt (0 turns retries off). */\n maxRetries: number;\n /** The wait before the first retry when the answer named none; it doubles each time. */\n baseDelayMs: number;\n /** The longest wait between retries when the answer named none. */\n maxDelayMs: number;\n /** The longest `Retry-After` the SDK waits out by itself; a longer one is thrown to you with `retryAfter` set. */\n maxRetryAfterMs: number;\n}\n\nexport const DEFAULT_RETRY: RetrySettings = {\n maxRetries: 2,\n baseDelayMs: 500,\n maxDelayMs: 8_000,\n maxRetryAfterMs: 10_000\n};\n\n/**\n * The wait before retry number `retry` (1 for the first) when the answer named no `Retry-After`: exponential, capped,\n * with jitter that spreads it between half and all of the wait.\n */\nexport function backoffMs(retry: number, settings: RetrySettings, random: () => number = Math.random): number {\n const exp = settings.baseDelayMs * 2 ** Math.max(0, retry - 1);\n const capped = Math.min(exp, settings.maxDelayMs);\n return capped / 2 + (capped / 2) * random();\n}\n\n/**\n * Whether a failed attempt should be sent again, and after how long (ms). `retry` is the number this retry would be\n * (1 for the first); `transient` says whether the failure may be retried at all (default: `error.isTransient`). A\n * `Retry-After` is never shortened, and one longer than `maxRetryAfterMs` is not waited out.\n */\nexport function retryDelay(\n error: SplatterVaultError,\n retry: number,\n settings: RetrySettings,\n random?: () => number,\n transient: boolean = error.isTransient\n): number | null {\n if (retry > settings.maxRetries || !transient) return null;\n if (error.retryAfter !== null) {\n const ms = error.retryAfter * 1000;\n return ms > settings.maxRetryAfterMs ? null : ms;\n }\n return backoffMs(retry, settings, random);\n}\n","/** The longest delay a Node.js timer holds (2^31 - 1 ms); a longer one fires after 1 ms. */\nexport const MAX_TIMER_MS = 2_147_483_647;\n\n/** `value` as a finite number in [min, max]; a RangeError naming `name` otherwise (NaN and Infinity included). */\nexport function numberInRange(value: unknown, name: string, min: number, max: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) {\n throw new RangeError(`${name} must be a finite number from ${min} to ${max} (got ${String(value)})`);\n }\n return value;\n}\n\n/** `value` as an integer in [min, max]; a RangeError naming `name` otherwise. */\nexport function intInRange(value: unknown, name: string, min: number, max: number): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < min || value > max) {\n throw new RangeError(`${name} must be a whole number from ${min} to ${max} (got ${String(value)})`);\n }\n return value;\n}\n\n/** True for a loopback host name: localhost, 127.x.x.x or [::1]. */\nexport function isLoopbackHost(hostname: string): boolean {\n const h = hostname.toLowerCase();\n return h === \"localhost\" || h === \"[::1]\" || /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h);\n}\n\n/**\n * Checks a URL the SDK sends requests to (the API base URL, the JWKS URL) and answers it without trailing slashes:\n * absolute, https (http only for a loopback host, or with `allowInsecureHttp`), no credentials, no query or fragment.\n */\nexport function checkServiceUrl(value: unknown, name: string, allowInsecureHttp: boolean): string {\n if (typeof value !== \"string\") throw new TypeError(`${name} must be a URL string`);\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new TypeError(`${name} must be an absolute https URL`);\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") throw new TypeError(`${name} must be an absolute https URL`);\n if (url.username || url.password) throw new TypeError(`${name} must not hold a user name or password`);\n if (url.search || url.hash) throw new TypeError(`${name} must not have a query or a fragment`);\n if (url.protocol === \"http:\" && !isLoopbackHost(url.hostname) && !allowInsecureHttp) {\n throw new TypeError(\n `${name} must use https: plain http is allowed only for loopback hosts (localhost, 127.0.0.1, [::1]), or with ` +\n \"{ dangerouslyAllowInsecureHttp: true } for a development server you trust\"\n );\n }\n return value.replace(/\\/+$/, \"\");\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { OPERATIONS, type OperationId } from \"../operations.js\";\nimport {\n NOT_APPLIED_STATUSES,\n OUTCOME_UNKNOWN_STATUSES,\n parseRetryAfter,\n readErrorBody,\n SDK_ERROR_CODES,\n SplatterVaultError\n} from \"./errors.js\";\nimport { retryDelay, type RetrySettings } from \"./retry.js\";\nimport { intInRange, MAX_TIMER_MS } from \"./validate.js\";\n\n/** The most retries a client or a call may ask for. */\nexport const MAX_RETRIES = 20;\n\n/** The `fetch` the SDK calls: the global one by default, or any function with its signature. */\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/** Options every call accepts as its last argument. */\nexport interface RequestOptions {\n /** Aborts the call (and any wait between retries). The call then rejects with code `aborted`. */\n signal?: AbortSignal;\n /** How long one attempt may take in ms, answer body included: 1 to 2147483647 (default: the client's `timeoutMs`). */\n timeoutMs?: number;\n /**\n * Retries after the first attempt for this call, 0 to 20 (default: the client's `maxRetries`). Only operations that\n * are safe to repeat are ever retried; this cannot make another operation retry.\n */\n maxRetries?: number;\n /**\n * Extra request headers. They never replace `X-API-Key`, `Idempotency-Key`, `Content-Type` or `Accept`. The SDK\n * sends no `If-None-Match` itself (no server operation declares ETags); if you send one, it adds\n * `Cache-Control: max-age=0` (Node's fetch would otherwise add `no-cache`, and no 304 would come), and a 304 answer\n * rejects with a {@link SplatterVaultError} of `status` 304.\n */\n headers?: Record<string, string>;\n}\n\n/** Options of a store change (grant, consume, purchase, item update, reversal). */\nexport interface IdempotentRequestOptions extends RequestOptions {\n /**\n * The change's `Idempotency-Key` (1-128 visible ASCII characters). By default the SDK makes one per call\n * (`crypto.randomUUID()`) and sends it with every retry of that call; a failed call's error carries it\n * (`err.idempotencyKey`). Pass your own, derived from your own record (e.g. `reward:${matchId}:${playerId}`), to\n * stay exactly-once across process restarts and your own retries: the same key and request again answers the first\n * result with `replayed: true`. Never send the same change again WITHOUT its key after an unknown outcome.\n * `null` (or leaving it out) makes a new one, so `{ idempotencyKey: err.idempotencyKey }` works for any error.\n */\n idempotencyKey?: string | null;\n}\n\nexport interface HttpConfig {\n apiKey: string;\n baseUrl: string;\n fetch: FetchLike;\n timeoutMs: number;\n retry: RetrySettings;\n userAgent: string;\n}\n\ntype Scalar = string | number | boolean;\nexport type QueryValue = Scalar | readonly Scalar[] | null | undefined;\n\nexport interface CallInput {\n path?: Record<string, string | number | undefined | null>;\n query?: Record<string, QueryValue>;\n body?: unknown;\n options?: IdempotentRequestOptions | undefined;\n /** For `\"if-version\"` operations: true when every op carries `ifVersion` (the call may then be retried). */\n conditional?: boolean;\n}\n\n/** The header an `Idempotency-Key` must match: 1-128 visible ASCII characters. */\nexport const IDEMPOTENCY_KEY_RE = /^[\\x21-\\x7e]{1,128}$/;\n\n/** A new `Idempotency-Key` (a random uuid). */\nexport function newIdempotencyKey(): string {\n return randomUUID();\n}\n\nconst MANAGED_HEADERS = new Set([\"x-api-key\", \"idempotency-key\", \"content-type\", \"accept\"]);\n\n/**\n * Fills `{name}` placeholders, each value URL-encoded. Throws a TypeError for a missing one, and for `.` or `..`\n * (URL-encoding leaves dots alone, and a dot segment would turn the request into another route).\n */\nexport function fillPath(template: string, params: CallInput[\"path\"] = {}): string {\n return template.replace(/\\{([^}]+)\\}/g, (_m, name: string) => {\n const value = params[name];\n if (value === undefined || value === null || value === \"\") throw new TypeError(`${name} is required`);\n if (typeof value === \"number\" && !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number`);\n const text = String(value);\n if (text === \".\" || text === \"..\") throw new TypeError(`${name} must not be \"${text}\"`);\n return encodeURIComponent(text);\n });\n}\n\n/** The query string (with `?`) of the defined values: arrays comma-separated, booleans as `true`/`false`. */\nexport function queryString(query: CallInput[\"query\"] = {}): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n params.append(key, Array.isArray(value) ? value.map(String).join(\",\") : String(value));\n }\n const text = params.toString();\n return text ? `?${text}` : \"\";\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason;\n}\n\n/** Resolves after `ms`, or rejects as soon as `signal` aborts (with the signal's reason). */\nexport function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortReason(signal as AbortSignal));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nclass AttemptTimeout extends Error {\n constructor() {\n super(\"timeout\");\n }\n}\n\ninterface Answer {\n status: number;\n headers: Headers;\n text: string;\n}\n\n/** The request pipeline: URL, headers, Idempotency-Key, per-attempt timeout, retries, error mapping. */\nexport class HttpClient {\n // An ES private field: the API key never shows in console.log, util.inspect or JSON.stringify of a client.\n readonly #config: HttpConfig;\n\n constructor(config: HttpConfig) {\n this.#config = config;\n }\n\n get baseUrl(): string {\n return this.#config.baseUrl;\n }\n\n get fetchFn(): FetchLike {\n return this.#config.fetch;\n }\n\n get defaultTimeoutMs(): number {\n return this.#config.timeoutMs;\n }\n\n async call<T>(operationId: OperationId, input: CallInput = {}): Promise<T> {\n const op = OPERATIONS[operationId];\n const options = input.options ?? {};\n const path = fillPath(op.path, input.path);\n const url = `${this.#config.baseUrl}${path}${queryString(input.query)}`;\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n if (!MANAGED_HEADERS.has(name.toLowerCase())) headers[name] = value;\n }\n // Node's fetch adds \"Cache-Control: no-cache\" to a request that carries If-None-Match, and the API (Express) then\n // never answers 304: a caller's own If-None-Match goes with max-age=0 instead (unless they chose a Cache-Control).\n const names = Object.keys(headers).map((n) => n.toLowerCase());\n if (names.includes(\"if-none-match\") && !names.includes(\"cache-control\")) headers[\"Cache-Control\"] = \"max-age=0\";\n headers[\"Accept\"] = \"application/json\";\n headers[\"User-Agent\"] = this.#config.userAgent;\n headers[\"X-API-Key\"] = this.#config.apiKey;\n let body: string | undefined;\n if (input.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(input.body);\n }\n if (op.retry === \"idempotency-key\") {\n const key = options.idempotencyKey ?? newIdempotencyKey();\n if (typeof key !== \"string\" || !IDEMPOTENCY_KEY_RE.test(key)) {\n throw new TypeError(\"idempotencyKey must be 1-128 visible ASCII characters\");\n }\n headers[\"Idempotency-Key\"] = key;\n } else if (options.idempotencyKey != null) {\n throw new TypeError(`${operationId} takes no idempotencyKey`);\n }\n\n const conditional = op.retry === \"if-version\" && input.conditional === true;\n const retryable = op.retry === \"safe\" || op.retry === \"idempotency-key\" || conditional;\n const maxRetries = options.maxRetries === undefined ? this.#config.retry.maxRetries : intInRange(options.maxRetries, \"maxRetries\", 0, MAX_RETRIES);\n const settings: RetrySettings = { ...this.#config.retry, maxRetries: retryable ? maxRetries : 0 };\n const timeoutMs =\n options.timeoutMs !== undefined\n ? intInRange(options.timeoutMs, \"timeoutMs\", 1, MAX_TIMER_MS)\n : \"timeoutMs\" in op\n ? Math.max(op.timeoutMs, this.#config.timeoutMs)\n : this.#config.timeoutMs;\n const signal = options.signal;\n const write = op.method !== \"GET\" && !(\"read\" in op);\n const meta = { operationId, method: op.method, path, idempotencyKey: headers[\"Idempotency-Key\"] ?? null };\n // Set once an attempt of a write ended without telling whether it was applied (no answer, 500, 502, 504).\n let unknownSoFar = false;\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) throw this.abortedError(meta, attempt - 1, abortReason(signal), write && unknownSoFar);\n let error: SplatterVaultError;\n try {\n const answer = await this.send(url, { method: op.method, headers, body, redirect: \"manual\" }, timeoutMs, signal);\n if (answer.status >= 200 && answer.status < 300) return this.parseSuccess<T>(answer, meta, attempt);\n if (answer.status >= 300 && answer.status < 400 && answer.status !== 304) {\n // Never followed: a redirect would carry X-API-Key to wherever it points (fetch drops only Authorization),\n // and a 301/302 turns a POST into a GET of another route. Not retried.\n throw this.redirectError(answer, meta, attempt, write && unknownSoFar);\n }\n error = this.errorFromAnswer(answer, meta, attempt);\n } catch (err) {\n if (err instanceof SplatterVaultError) throw err;\n // An abort while the request was out: it may have arrived.\n if (signal?.aborted) throw this.abortedError(meta, attempt, abortReason(signal), write);\n error =\n err instanceof AttemptTimeout\n ? new SplatterVaultError({\n ...meta,\n status: 0,\n code: SDK_ERROR_CODES.timeout,\n message: `timeout: no answer from SplatterVault within ${timeoutMs} ms`,\n attempts: attempt\n })\n : new SplatterVaultError({\n ...meta,\n status: 0,\n code: SDK_ERROR_CODES.networkError,\n message: `network_error: no answer from SplatterVault (${err instanceof Error ? err.message : String(err)})`,\n attempts: attempt,\n cause: err\n });\n }\n if (write && (error.isNetworkError || OUTCOME_UNKNOWN_STATUSES.has(error.status))) unknownSoFar = true;\n\n // A resent change that meets a conflict with its own earlier send.\n const resentConflict = attempt > 1 && error.status === 409;\n if (conditional && resentConflict && error.code === \"version_conflict\") {\n // The second send of an ifVersion write: the first may have been applied after all (its own new version).\n throw error.with({\n code: SDK_ERROR_CODES.outcomeUnknown,\n message: `outcome_unknown (HTTP 409): this write was sent again and met version_conflict; the first send may have been applied. Read the data again.`,\n outcomeUnknown: true\n });\n }\n // The same key with a byte-identical body can only conflict with its own send still in progress.\n const inProgress = op.retry === \"idempotency-key\" && resentConflict && error.code === \"idempotency_conflict\";\n\n let transient = error.isTransient || inProgress;\n // ifVersion writes: only an answer that proves nothing was applied may be sent again (unknown-outcome rule).\n if (conditional && !NOT_APPLIED_STATUSES.has(error.status)) transient = false;\n const delay = retryDelay(error, attempt, settings, undefined, transient);\n if (delay === null) throw error.with({ outcomeUnknown: write && (unknownSoFar || inProgress) });\n try {\n await sleep(delay, signal);\n } catch (reason) {\n throw this.abortedError(meta, attempt, reason, write && unknownSoFar);\n }\n }\n }\n\n /** One attempt: the answer with its whole body, within `timeoutMs`. Throws AttemptTimeout or the fetch error. */\n private async send(url: string, init: RequestInit, timeoutMs: number, signal: AbortSignal | undefined): Promise<Answer> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new AttemptTimeout());\n }, timeoutMs);\n const onAbort = () => controller.abort(abortReason(signal as AbortSignal));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const res = await this.#config.fetch(url, { ...init, signal: controller.signal });\n const text = await res.text();\n return { status: res.status, headers: res.headers, text };\n } catch (err) {\n if (timedOut) throw new AttemptTimeout();\n throw err;\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n\n private parseSuccess<T>(answer: Answer, meta: { operationId: string; method: string; path: string; idempotencyKey: string | null }, attempt: number): T {\n if (answer.status === 204 || answer.text.trim() === \"\") return undefined as T;\n try {\n return JSON.parse(answer.text) as T;\n } catch (err) {\n throw new SplatterVaultError({\n ...meta,\n status: answer.status,\n code: SDK_ERROR_CODES.invalidResponse,\n message: `invalid_response: the answer (HTTP ${answer.status}) is not JSON`,\n requestId: answer.headers.get(\"x-request-id\"),\n attempts: attempt,\n cause: err\n });\n }\n }\n\n private errorFromAnswer(\n answer: Answer,\n meta: { operationId: string; method: string; path: string; idempotencyKey: string | null },\n attempt: number\n ): SplatterVaultError {\n let parsed: unknown;\n if (answer.text.trim() !== \"\") {\n try {\n parsed = JSON.parse(answer.text);\n } catch {\n parsed = undefined; // an HTML page from a proxy, for example: never quoted into the message\n }\n }\n const read = readErrorBody(parsed);\n const label = read.code ?? read.errorName ?? `HTTP ${answer.status}`;\n const sentence = read.message ?? `SplatterVault answered HTTP ${answer.status}`;\n return new SplatterVaultError({\n ...meta,\n status: answer.status,\n code: read.code,\n message: `${label} (HTTP ${answer.status}): ${sentence}`,\n details: read.details,\n retryAfter: parseRetryAfter(answer.headers.get(\"retry-after\")),\n requestId: answer.headers.get(\"x-request-id\"),\n errorName: read.errorName,\n errors: read.errors,\n body: parsed,\n attempts: attempt\n });\n }\n\n private abortedError(\n meta: { operationId: string; method: string; path: string; idempotencyKey: string | null },\n attempts: number,\n reason: unknown,\n outcomeUnknown: boolean\n ): SplatterVaultError {\n return new SplatterVaultError({\n ...meta,\n status: 0,\n code: SDK_ERROR_CODES.aborted,\n message: \"aborted: the call was aborted by its signal\",\n attempts,\n outcomeUnknown,\n cause: reason\n });\n }\n\n private redirectError(\n answer: Answer,\n meta: { operationId: string; method: string; path: string; idempotencyKey: string | null },\n attempt: number,\n outcomeUnknown: boolean\n ): SplatterVaultError {\n const location = answer.headers.get(\"location\");\n return new SplatterVaultError({\n ...meta,\n status: answer.status,\n code: SDK_ERROR_CODES.redirectNotFollowed,\n message: `redirect_not_followed (HTTP ${answer.status}): SplatterVault answered a redirect, which the SDK never follows (check baseUrl)`,\n details: { location },\n requestId: answer.headers.get(\"x-request-id\"),\n attempts: attempt,\n outcomeUnknown\n });\n }\n}\n\n","/** This package's version (kept equal to package.json's by a test). */\nexport const SDK_VERSION = \"0.1.0\";\n","import { createPublicKey, type KeyObject } from \"node:crypto\";\n\nimport { type FetchLike } from \"../core/http.js\";\n\n/** One public key of the player-token JWKS (`GET /player-auth/keys`). */\nexport interface PlayerTokenJwk {\n kty: \"OKP\";\n crv: \"Ed25519\";\n /** base64url of the raw 32-byte Ed25519 public key. */\n x: string;\n /** 16 hex characters; a token's header names it. */\n kid: string;\n alg?: \"EdDSA\";\n use?: \"sig\";\n}\n\n/** The JWKS `GET /player-auth/keys` answers: the current key and, during a rotation, the next and previous ones. */\nexport interface PlayerTokenJwks {\n keys: PlayerTokenJwk[];\n}\n\nconst KID_RE = /^[0-9a-f]{16}$/;\n/** The shortest time a fetched key set is kept (whatever its Cache-Control says). */\nexport const MIN_KEYS_LIFETIME_MS = 60_000;\n/** The longest time a fetched key set is kept (whatever its Cache-Control says). */\nexport const MAX_KEYS_LIFETIME_MS = 3_600_000;\nconst X_RE = /^[A-Za-z0-9_-]{43}$/;\n\n/** The usable Ed25519 keys of a JWKS, by kid. Keys of another kind (or malformed ones) are skipped, never fatal. */\nexport function importJwks(jwks: unknown): Map<string, KeyObject> {\n const keys = new Map<string, KeyObject>();\n const list = (jwks as { keys?: unknown } | null)?.keys;\n if (!Array.isArray(list)) throw new Error(\"not a JWKS: no keys array\");\n for (const jwk of list as unknown[]) {\n if (!jwk || typeof jwk !== \"object\") continue;\n const k = jwk as Record<string, unknown>;\n if (k.kty !== \"OKP\" || k.crv !== \"Ed25519\") continue;\n if (k.alg !== undefined && k.alg !== \"EdDSA\") continue;\n if (k.use !== undefined && k.use !== \"sig\") continue;\n if (typeof k.kid !== \"string\" || !KID_RE.test(k.kid)) continue;\n if (typeof k.x !== \"string\" || !X_RE.test(k.x)) continue;\n const raw = Buffer.from(k.x, \"base64url\");\n if (raw.length !== 32 || raw.toString(\"base64url\") !== k.x) continue;\n try {\n keys.set(k.kid, createPublicKey({ key: { kty: \"OKP\", crv: \"Ed25519\", x: k.x }, format: \"jwk\" }));\n } catch {\n /* not a usable Ed25519 key: skipped */\n }\n }\n return keys;\n}\n\n/**\n * How long an answer may be used without fetching again, in ms, from its `Cache-Control` and `Age`: `max-age` minus\n * `Age`; 0 for `no-store` / `no-cache`; `fallbackMs` when the answer names no lifetime.\n */\nexport function freshnessMs(cacheControl: string | null, age: string | null, fallbackMs: number): number {\n if (cacheControl === null || cacheControl.trim() === \"\") return fallbackMs;\n const directives = cacheControl.toLowerCase().split(\",\").map((d) => d.trim());\n if (directives.some((d) => d === \"no-store\" || d === \"no-cache\" || d.startsWith(\"no-cache=\"))) return 0;\n const maxAge = directives.find((d) => d.startsWith(\"max-age=\"));\n if (!maxAge) return fallbackMs;\n const seconds = Number(maxAge.slice(\"max-age=\".length).replace(/^\"|\"$/g, \"\"));\n if (!Number.isFinite(seconds) || seconds < 0) return 0;\n const ageSeconds = age !== null && /^\\d+$/.test(age.trim()) ? Number(age.trim()) : 0;\n return Math.max(0, seconds - ageSeconds) * 1000;\n}\n\nexport interface JwksCacheOptions {\n url: string;\n fetch: FetchLike;\n userAgent: string;\n timeoutMs: number;\n /** The shortest time between two fetches caused by an unknown kid. */\n minRefetchIntervalMs: number;\n /** How long past its lifetime a key set may still be used while fetching a new one fails. */\n staleIfErrorMs: number;\n /** The lifetime of an answer that names none in Cache-Control. */\n fallbackMaxAgeMs: number;\n now: () => number;\n}\n\n/** Why the key set could not be fetched; the cause carries the details. */\nexport class JwksFetchError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"JwksFetchError\";\n }\n}\n\ninterface CachedSet {\n keys: Map<string, KeyObject>;\n freshUntil: number;\n staleUntil: number;\n}\n\n/**\n * The player-token keys, fetched on demand and kept as long as the answer's `Cache-Control` allows (at least\n * max(minRefetchIntervalMs, 60 s), at most an hour); fetched again (single-flight, at most once per\n * `minRefetchIntervalMs`) when a token names a kid the set does not hold. After a failed fetch, no new fetch for\n * `minRefetchIntervalMs`.\n */\nexport class JwksCache {\n private cached: CachedSet | null = null;\n private inflight: Promise<CachedSet> | null = null;\n private lastFetchStart = Number.NEGATIVE_INFINITY;\n private lastFailure = Number.NEGATIVE_INFINITY;\n\n constructor(private readonly options: JwksCacheOptions) {}\n\n /** The key of `kid`, or null when the (refreshed) set has none. Throws JwksFetchError when no usable set exists. */\n async keyFor(kid: string): Promise<KeyObject | null> {\n const now = this.options.now();\n const cached = this.cached;\n if (cached && now < cached.freshUntil) {\n const key = cached.keys.get(kid);\n if (key) return key;\n if (now - this.lastFetchStart < this.options.minRefetchIntervalMs) return null;\n return (await this.refresh()).keys.get(kid) ?? null;\n }\n // Past its lifetime (or never fetched): fetch again, unless a fetch failed a moment ago. Then the old set serves\n // while it may, else the failure stands without another fetch (no fetch per verification while the API is down).\n if (now - this.lastFailure < this.options.minRefetchIntervalMs) {\n if (cached && now < cached.staleUntil) return cached.keys.get(kid) ?? null;\n throw new JwksFetchError(\"the player token keys could not be fetched a moment ago; not trying again yet\");\n }\n try {\n return (await this.refresh()).keys.get(kid) ?? null;\n } catch (err) {\n this.lastFailure = this.options.now();\n const stale = this.cached;\n if (stale && this.lastFailure < stale.staleUntil) return stale.keys.get(kid) ?? null;\n throw err;\n }\n }\n\n /** Fetches the set now (joining a fetch already under way). */\n refresh(): Promise<CachedSet> {\n if (this.inflight) return this.inflight;\n this.lastFetchStart = this.options.now();\n const p = this.fetchSet().finally(() => {\n if (this.inflight === p) this.inflight = null;\n });\n this.inflight = p;\n return p;\n }\n\n private async fetchSet(): Promise<CachedSet> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);\n let res: Response;\n let text: string;\n try {\n res = await this.options.fetch(this.options.url, {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"Cache-Control\": \"no-cache\", \"User-Agent\": this.options.userAgent },\n // Never followed: keys from wherever a redirect points would be trusted to sign player tokens.\n redirect: \"manual\",\n signal: controller.signal\n });\n text = await res.text();\n } catch (err) {\n throw new JwksFetchError(`could not fetch the player token keys: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n } finally {\n clearTimeout(timer);\n }\n if (res.status !== 200) {\n let code = \"\";\n try {\n const body = JSON.parse(text) as { error?: unknown };\n if (typeof body?.error === \"string\") code = ` ${body.error}`;\n } catch {\n /* not JSON */\n }\n const redirect = res.status >= 300 && res.status < 400 ? \" (a redirect, which is never followed)\" : \"\";\n throw new JwksFetchError(`the player token keys answered HTTP ${res.status}${code}${redirect}`);\n }\n let keys: Map<string, KeyObject>;\n try {\n keys = importJwks(JSON.parse(text));\n } catch (err) {\n throw new JwksFetchError(\"the player token keys answer is not a JWKS\", { cause: err });\n }\n const fetchedAt = this.options.now();\n // Kept at least max(minRefetchIntervalMs, 60 s), even for no-store (else every verification would fetch), and at\n // most an hour (a key SplatterVault stops publishing is not trusted much longer, whatever the answer said).\n const floor = Math.max(this.options.minRefetchIntervalMs, MIN_KEYS_LIFETIME_MS);\n const named = freshnessMs(res.headers.get(\"cache-control\"), res.headers.get(\"age\"), this.options.fallbackMaxAgeMs);\n const lifetime = Math.min(Math.max(named, floor), MAX_KEYS_LIFETIME_MS);\n const set: CachedSet = { keys, freshUntil: fetchedAt + lifetime, staleUntil: fetchedAt + lifetime + this.options.staleIfErrorMs };\n this.cached = set;\n return set;\n }\n}\n","import { type KeyObject, verify as verifySignature } from \"node:crypto\";\n\nimport { type FetchLike } from \"../core/http.js\";\nimport { checkServiceUrl, intInRange, MAX_TIMER_MS, numberInRange } from \"../core/validate.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport { importJwks, JwksCache, JwksFetchError, type PlayerTokenJwks } from \"./jwks.js\";\n\n/** The default API base URL. */\nexport const DEFAULT_BASE_URL = \"https://splattervault.com/rest\";\n\n/** Every player token's issuer. */\nexport const PLAYER_TOKEN_ISSUER = \"splattervault\";\n/** Every player token's audience is this prefix and the game id: `sv-player:42`. */\nexport const PLAYER_TOKEN_AUDIENCE_PREFIX = \"sv-player:\";\n/** The longest lifetime (exp - iat) of a player token the API issues. */\nexport const PLAYER_TOKEN_MAX_LIFETIME_SECONDS = 3600;\n/** The clock skew the API allows when it checks a player token, and this verifier's default. */\nexport const PLAYER_TOKEN_CLOCK_SKEW_SECONDS = 30;\nconst PLAYER_TOKEN_MAX_BYTES = 2048;\n/** How long an expired key set may still serve while fetching a new one fails (the API's 5-minute guidance). */\nexport const DEFAULT_STALE_IF_ERROR_SECONDS = 300;\n\nconst KID_RE = /^[0-9a-f]{16}$/;\nconst B64URL_RE = /^[A-Za-z0-9_-]+$/;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;\nconst SCOPE_RE = /^(org|game):([1-9][0-9]{0,9})$/;\nconst APP_ID_RE = /^[\\x21-\\x7e]{1,64}$/;\nconst PROVIDER_RE = /^[a-z][a-z0-9_-]{0,31}$/;\nconst MAX_INT32 = 2147483647;\nconst MAX_GAME_KEY = 255;\n\n/** The sign-in methods the API issues tokens for today (new ones may be added; the verifier accepts any). */\nexport type PlayerSignInMethod = \"xsolla\" | \"meta\" | \"steam\" | \"studio\" | \"playfab\" | \"supabase\" | \"email\" | \"device\";\n\n/** What a verified player token says. Only SplatterVault can have signed it. */\nexport interface PlayerTokenClaims {\n /** Always `splattervault`. */\n iss: typeof PLAYER_TOKEN_ISSUER;\n /** `sv-player:<game id>`: the game the token is for. */\n aud: `${typeof PLAYER_TOKEN_AUDIENCE_PREFIX}${number}`;\n /** The player's SplatterVault id (uuid): the same player in every game of your organization. */\n sub: string;\n /** Whose players: `org:<organization id>`, or `game:<game id>` for a personal game. */\n scope: `org:${number}` | `game:${number}`;\n /** The game id the token was issued for. */\n game: number;\n /** The game's key when issued (\"\" when it had none). */\n gk: string;\n /** The game's organization, null for a personal game. */\n org: number | null;\n /** How the player signed in: one method. */\n amr: [PlayerSignInMethod | (string & {})];\n /** The platform app the sign-in proof was checked against (Xsolla project, Meta or Steam app); absent for studio. */\n app?: string;\n /** Issued at (seconds since the epoch). */\n iat: number;\n /** Expires at (seconds since the epoch): about an hour after `iat`. */\n exp: number;\n /** The token's unique id. */\n jti: string;\n}\n\n/** Why a player token was refused. */\nexport type PlayerTokenErrorCode =\n /** Not a genuine, well-formed token for this game. */\n | \"token_invalid\"\n /** A genuine token past its `exp` (plus the clock tolerance): the player signs in or refreshes again. */\n | \"token_expired\"\n /** The public keys could not be fetched, so the token could not be checked: try again shortly. */\n | \"keys_unavailable\";\n\n/**\n * Which check refused the token (for your logs; never shown to players): `malformed`, `header`, `unknown_kid`,\n * `signature`, `issuer`, `claims`, `lifetime`, `not_yet_valid`, `audience` (another game's token), `expired`, `keys`.\n */\nexport type PlayerTokenFailure =\n | \"malformed\"\n | \"header\"\n | \"unknown_kid\"\n | \"signature\"\n | \"issuer\"\n | \"claims\"\n | \"lifetime\"\n | \"not_yet_valid\"\n | \"audience\"\n | \"expired\"\n | \"keys\";\n\n/** A player token that was not accepted. */\nexport class PlayerTokenError extends Error {\n override readonly name = \"PlayerTokenError\";\n constructor(\n /** `token_invalid`, `token_expired` or `keys_unavailable`. */\n readonly code: PlayerTokenErrorCode,\n /** Which check failed. */\n readonly reason: PlayerTokenFailure,\n message: string,\n options?: { cause?: unknown }\n ) {\n super(message, options);\n }\n}\n\nexport interface PlayerTokenVerifierOptions {\n /** The games whose tokens to accept (the `aud` must be `sv-player:<one of them>`). Can be given per verify too. */\n gameId?: number | readonly number[];\n /**\n * API base URL (default `https://splattervault.com/rest`); the keys are at `<baseUrl>/player-auth/keys`. https only\n * (http for loopback hosts); redirects are never followed.\n */\n baseUrl?: string;\n /** The JWKS URL, if not under `baseUrl` (same rules as `baseUrl`). */\n jwksUrl?: string;\n /** A fixed key set (a saved `GET /player-auth/keys` answer): nothing is ever fetched. */\n keys?: PlayerTokenJwks;\n /** The `fetch` to use (default: the global one). */\n fetch?: FetchLike;\n /** How long fetching the keys may take, 1 to 2147483647 ms (default 10,000). */\n timeoutMs?: number;\n /** Clock tolerance for `iat` and `exp`, 0 to 300 s (default 30, as the API). */\n clockToleranceSeconds?: number;\n /** The longest `exp - iat` accepted, 1 to 3600 s (default 3600, as the API issues them). */\n maxLifetimeSeconds?: number;\n /** The shortest time between two key fetches caused by an unknown kid or a failed fetch, 0 to 3,600,000 ms (default 10,000). */\n minRefetchIntervalMs?: number;\n /**\n * How long past its lifetime the last key set may still be used while fetching a new one fails, 0 to 3600 s\n * (default 300: the API's own five-minute key-cache guidance). 0 refuses every token (`keys_unavailable`) as soon as\n * a fetch fails after the set expired.\n */\n staleIfErrorSeconds?: number;\n /** Your clock, in ms since the epoch (default `Date.now`). */\n now?: () => number;\n /** Sent as User-Agent when fetching the keys. */\n userAgent?: string;\n /**\n * Allows a plain-http `baseUrl` / `jwksUrl` on a host other than localhost / 127.0.0.1 / [::1]. Keys fetched over\n * plain http can be replaced on the way (anyone in between could then mint player tokens your server accepts):\n * for a development server you trust only.\n */\n dangerouslyAllowInsecureHttp?: boolean;\n}\n\nexport interface VerifyOptions {\n /** The games whose tokens to accept; overrides the verifier's `gameId`. */\n gameId?: number | readonly number[];\n}\n\nfunction decodeJsonPart(part: string): Record<string, unknown> | null {\n try {\n const value: unknown = JSON.parse(Buffer.from(part, \"base64url\").toString(\"utf8\"));\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\nconst positiveInt32 = (v: unknown): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v > 0 && v <= MAX_INT32;\n\n/** Null when the claims hang together as the API issues them, else the first problem. */\nfunction claimsProblem(c: Record<string, unknown>): string | null {\n if (typeof c.sub !== \"string\" || !UUID_RE.test(c.sub)) return \"sub\";\n if (typeof c.scope !== \"string\" || !SCOPE_RE.test(c.scope) || Number(c.scope.split(\":\")[1]) > MAX_INT32) return \"scope\";\n if (!positiveInt32(c.game)) return \"game\";\n if (typeof c.gk !== \"string\" || c.gk.length > MAX_GAME_KEY) return \"gk\";\n if (c.org !== null && !positiveInt32(c.org)) return \"org\";\n const [kind, id] = c.scope.split(\":\");\n if (kind === \"org\" ? c.org !== Number(id) : c.org !== null || c.game !== Number(id)) return \"scope/org/game\";\n // One sign-in method. Its value is not limited to today's list: a method SplatterVault adds later must not make\n // genuine tokens fail in a server that has not updated this SDK.\n if (!Array.isArray(c.amr) || c.amr.length !== 1 || typeof c.amr[0] !== \"string\" || !PROVIDER_RE.test(c.amr[0])) return \"amr\";\n if (c.app !== undefined && (c.amr[0] === \"studio\" || typeof c.app !== \"string\" || !APP_ID_RE.test(c.app))) return \"app\";\n return null;\n}\n\nfunction gameList(gameId: number | readonly number[] | undefined): readonly number[] {\n const list = gameId === undefined ? [] : typeof gameId === \"number\" ? [gameId] : gameId;\n if (list.length === 0) throw new TypeError(\"gameId is required: the game (or games) whose player tokens to accept\");\n for (const g of list) if (!positiveInt32(g)) throw new TypeError(\"gameId must be a positive integer game id\");\n return list;\n}\n\nconst invalid = (reason: PlayerTokenFailure, message: string) => new PlayerTokenError(\"token_invalid\", reason, message);\n\n/**\n * Verifies SplatterVault player tokens offline, against the public keys from `GET /player-auth/keys` (Ed25519,\n * fetched when needed and kept as long as the answer's Cache-Control allows; fetched again when a token names an\n * unknown key). Use one verifier for the life of your server.\n *\n * It checks what the API itself checks (the signature, `iss`, the claims' shapes, `aud` = `sv-player:<game>`, `iat`\n * and `exp` with a 30-second tolerance, no `nbf`) and that the token is for one of your games. Two differences:\n * - a sign-in method (`amr`) the API adds later is accepted (the signature still proves SplatterVault issued it);\n * - offline, it cannot know what happened after the token was issued: a player erased since, or a game moved to\n * another owner, still verifies here until the token expires (within the hour), although the API refuses such a\n * token (`player_deleted`, `token_invalid`). Where that matters, ask the API (e.g. `sv.store.getPlayer(claims.sub)`\n * answers `player_not_found` for an erased player).\n */\nexport class PlayerTokenVerifier {\n private readonly cache: JwksCache | null;\n private readonly fixedKeys: Map<string, KeyObject> | null;\n private readonly gameId: number | readonly number[] | undefined;\n private readonly skew: number;\n private readonly maxLifetime: number;\n private readonly now: () => number;\n\n constructor(options: PlayerTokenVerifierOptions = {}) {\n this.gameId = options.gameId;\n if (options.gameId !== undefined) gameList(options.gameId);\n // Validated here: a NaN tolerance or lifetime would switch the expiry and lifetime checks off.\n this.skew = numberInRange(options.clockToleranceSeconds ?? PLAYER_TOKEN_CLOCK_SKEW_SECONDS, \"clockToleranceSeconds\", 0, 300);\n this.maxLifetime = intInRange(options.maxLifetimeSeconds ?? PLAYER_TOKEN_MAX_LIFETIME_SECONDS, \"maxLifetimeSeconds\", 1, 3600);\n if (options.now !== undefined && typeof options.now !== \"function\") throw new TypeError(\"now must be a function\");\n this.now = options.now ?? Date.now;\n const timeoutMs = intInRange(options.timeoutMs ?? 10_000, \"timeoutMs\", 1, MAX_TIMER_MS);\n const minRefetchIntervalMs = intInRange(options.minRefetchIntervalMs ?? 10_000, \"minRefetchIntervalMs\", 0, 3_600_000);\n const staleIfErrorSeconds = numberInRange(options.staleIfErrorSeconds ?? DEFAULT_STALE_IF_ERROR_SECONDS, \"staleIfErrorSeconds\", 0, 3600);\n if (options.keys) {\n this.fixedKeys = importJwks(options.keys);\n this.cache = null;\n return;\n }\n const fetchFn = options.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (typeof fetchFn !== \"function\") throw new TypeError(\"no fetch: use Node.js 18 or later, or pass { fetch }\");\n const insecure = options.dangerouslyAllowInsecureHttp === true;\n const url =\n options.jwksUrl !== undefined\n ? checkServiceUrl(options.jwksUrl, \"jwksUrl\", insecure)\n : `${checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, \"baseUrl\", insecure)}/player-auth/keys`;\n this.fixedKeys = null;\n this.cache = new JwksCache({\n url,\n fetch: fetchFn,\n userAgent: options.userAgent ?? `@splattervault/server/${SDK_VERSION}`,\n timeoutMs,\n minRefetchIntervalMs,\n staleIfErrorMs: staleIfErrorSeconds * 1000,\n fallbackMaxAgeMs: 60_000,\n now: this.now\n });\n }\n\n /**\n * The claims of a valid player token for one of your games; rejects with a {@link PlayerTokenError} otherwise.\n * `claims.sub` is the player's id.\n */\n async verify(token: string, options: VerifyOptions = {}): Promise<PlayerTokenClaims> {\n const games = gameList(options.gameId ?? this.gameId);\n if (typeof token !== \"string\" || token.length === 0 || token.length > PLAYER_TOKEN_MAX_BYTES) {\n throw invalid(\"malformed\", \"not a player token\");\n }\n const parts = token.split(\".\");\n if (parts.length !== 3 || !parts.every((p) => B64URL_RE.test(p))) throw invalid(\"malformed\", \"not a player token\");\n const [h, p, s] = parts as [string, string, string];\n\n const header = decodeJsonPart(h);\n if (!header || header.alg !== \"EdDSA\") throw invalid(\"header\", \"the token is not signed with EdDSA\");\n if (header.typ !== undefined && header.typ !== \"JWT\") throw invalid(\"header\", \"the token's typ is not JWT\");\n if (header.crit !== undefined || header.jku !== undefined || header.jwk !== undefined || header.x5u !== undefined) {\n throw invalid(\"header\", \"the token's header names keys or extensions it may not\");\n }\n if (typeof header.kid !== \"string\" || !KID_RE.test(header.kid)) throw invalid(\"header\", \"the token names no valid kid\");\n\n const key = await this.keyFor(header.kid);\n if (!key) throw invalid(\"unknown_kid\", \"the token names a key SplatterVault does not publish\");\n\n const signature = Buffer.from(s, \"base64url\");\n if (signature.length !== 64 || signature.toString(\"base64url\") !== s) throw invalid(\"signature\", \"the signature is malformed\");\n let ok: boolean;\n try {\n ok = verifySignature(null, Buffer.from(`${h}.${p}`, \"ascii\"), key, signature);\n } catch {\n ok = false;\n }\n if (!ok) throw invalid(\"signature\", \"the signature does not verify\");\n\n const claims = decodeJsonPart(p);\n if (!claims) throw invalid(\"claims\", \"the claims are not a JSON object\");\n if (claims.iss !== PLAYER_TOKEN_ISSUER || typeof claims.aud !== \"string\") throw invalid(\"issuer\", \"not a SplatterVault player token\");\n if (claims.nbf !== undefined) throw invalid(\"claims\", \"player tokens carry no nbf\");\n if (!Number.isSafeInteger(claims.iat) || !Number.isSafeInteger(claims.exp)) throw invalid(\"claims\", \"iat and exp must be integers\");\n const iat = claims.iat as number;\n const exp = claims.exp as number;\n if (exp <= iat || exp - iat > this.maxLifetime) throw invalid(\"lifetime\", \"the token's lifetime is not one the API issues\");\n const nowSeconds = Math.floor(this.now() / 1000);\n if (iat > nowSeconds + this.skew) throw invalid(\"not_yet_valid\", \"the token was issued in the future (check the server clock)\");\n if (typeof claims.jti !== \"string\" || !JTI_RE.test(claims.jti)) throw invalid(\"claims\", \"the token has no valid jti\");\n const problem = claimsProblem(claims);\n if (problem) throw invalid(\"claims\", `the token's ${problem} claim is not valid`);\n if (claims.aud !== `${PLAYER_TOKEN_AUDIENCE_PREFIX}${claims.game as number}`) throw invalid(\"claims\", \"aud does not name the token's game\");\n if (!games.includes(claims.game as number)) throw invalid(\"audience\", \"the token is for another game\");\n if (nowSeconds > exp + this.skew) throw new PlayerTokenError(\"token_expired\", \"expired\", \"Token expired\");\n return claims as unknown as PlayerTokenClaims;\n }\n\n private async keyFor(kid: string): Promise<KeyObject | null> {\n if (this.fixedKeys) return this.fixedKeys.get(kid) ?? null;\n try {\n return await (this.cache as JwksCache).keyFor(kid);\n } catch (err) {\n if (err instanceof JwksFetchError) {\n throw new PlayerTokenError(\"keys_unavailable\", \"keys\", `${err.message}; the token could not be checked`, { cause: err });\n }\n throw err;\n }\n }\n}\n\n/** A {@link PlayerTokenVerifier}: keep one for the life of your server. */\nexport function createPlayerTokenVerifier(options: PlayerTokenVerifierOptions = {}): PlayerTokenVerifier {\n return new PlayerTokenVerifier(options);\n}\n\nconst shared = new Map<string, PlayerTokenVerifier>();\nconst sharedByFetch = new WeakMap<FetchLike, Map<string, PlayerTokenVerifier>>();\n\n/**\n * Verifies a player token offline and answers its claims (`claims.sub` is the player's id); rejects with a\n * {@link PlayerTokenError} otherwise. The keys are cached per JWKS URL (and `fetch`) across calls; for other settings\n * than `gameId`, `baseUrl`, `jwksUrl`, `fetch` or `keys`, keep a verifier from {@link createPlayerTokenVerifier}.\n *\n * ```ts\n * const claims = await verifyPlayerToken(token, { gameId: 42 });\n * console.log(`player ${claims.sub} joined`);\n * ```\n */\nexport function verifyPlayerToken(\n token: string,\n options: { gameId: number | readonly number[] } & Pick<\n PlayerTokenVerifierOptions,\n \"baseUrl\" | \"jwksUrl\" | \"fetch\" | \"keys\" | \"dangerouslyAllowInsecureHttp\"\n >\n): Promise<PlayerTokenClaims> {\n if (options.keys) return new PlayerTokenVerifier({ keys: options.keys }).verify(token, { gameId: options.gameId });\n const insecure = options.dangerouslyAllowInsecureHttp === true;\n const url =\n options.jwksUrl !== undefined\n ? checkServiceUrl(options.jwksUrl, \"jwksUrl\", insecure)\n : `${checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, \"baseUrl\", insecure)}/player-auth/keys`;\n let byUrl = shared;\n if (options.fetch) {\n byUrl = sharedByFetch.get(options.fetch) ?? new Map();\n sharedByFetch.set(options.fetch, byUrl);\n }\n let verifier = byUrl.get(url);\n if (!verifier) {\n verifier = new PlayerTokenVerifier({ jwksUrl: url, dangerouslyAllowInsecureHttp: insecure, ...(options.fetch ? { fetch: options.fetch } : {}) });\n byUrl.set(url, verifier);\n }\n return verifier.verify(token, { gameId: options.gameId });\n}\n","import { type HttpClient, type RequestOptions } from \"../core/http.js\";\nimport type {\n CreditBalance,\n CreditStats,\n CreditStatsQuery,\n KeyOrgQuery,\n OrgCreditStats,\n PlanSubscription,\n SubscriptionOverview,\n SubscriptionsQuery,\n UsageStats\n} from \"../types.js\";\n\n/**\n * Credits and subscriptions. With an organization API key these are the key's organization's (the key needs a\n * permission to read them, e.g. org:view).\n */\nexport class Billing {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * The credit balance: the organization's for an organization API key (split into subscription and purchased\n * credits).\n * @see GET /credits (`billing.getCredits`)\n */\n getCredits(options?: RequestOptions): Promise<CreditBalance> {\n return this.http.call(\"billing.getCredits\", { options });\n }\n\n /**\n * Credit usage statistics; `organizationId` for an organization's.\n * @see GET /credits/stats (`billing.getCreditStats`)\n */\n getCreditStats(query?: CreditStatsQuery, options?: RequestOptions): Promise<CreditStats> {\n return this.http.call(\"billing.getCreditStats\", { query, options });\n }\n\n /**\n * The credits of the organization the API key belongs to (balance, available balance, auto-buy settings).\n * @see GET /org/credits (`billing.getKeyOrgCredits`)\n */\n getOrgCredits(query?: KeyOrgQuery, options?: RequestOptions): Promise<OrgCreditStats> {\n return this.http.call(\"billing.getKeyOrgCredits\", { query, options });\n }\n\n /**\n * Every subscription of the organization the API key belongs to.\n * @see GET /org/subscription (`billing.getKeyOrgSubscriptions`)\n */\n getOrgSubscriptions(query?: KeyOrgQuery, options?: RequestOptions): Promise<PlanSubscription[]> {\n return this.http.call(\"billing.getKeyOrgSubscriptions\", { query, options });\n }\n\n /**\n * The credits of organization `orgId` (the key's own organization).\n * @see GET /organizations/{orgId}/credits (`billing.getOrgCredits`)\n */\n getOrgCreditsById(orgId: number | string, options?: RequestOptions): Promise<OrgCreditStats> {\n return this.http.call(\"billing.getOrgCredits\", { path: { orgId }, options });\n }\n\n /**\n * The current and past subscriptions of organization `orgId` (the key's own organization).\n * @see GET /organizations/{orgId}/subscription (`billing.getOrgSubscription`)\n */\n getOrgSubscriptionById(orgId: number | string, options?: RequestOptions): Promise<SubscriptionOverview> {\n return this.http.call(\"billing.getOrgSubscription\", { path: { orgId }, options });\n }\n\n /**\n * The current subscription and the others (`includeStripeHistory: true` adds invoices).\n * @see GET /subscriptions (`billing.getSubscriptions`)\n */\n getSubscriptions(query?: SubscriptionsQuery, options?: RequestOptions): Promise<SubscriptionOverview> {\n return this.http.call(\"billing.getSubscriptions\", { query, options });\n }\n\n /**\n * Usage in the current billing period: instances, credit hours, sessions.\n * @see GET /subscriptions/usage (`billing.getUsage`)\n */\n getUsage(options?: RequestOptions): Promise<UsageStats> {\n return this.http.call(\"billing.getUsage\", { options });\n }\n}\n","import { type HttpClient, type RequestOptions } from \"../core/http.js\";\nimport type {\n DataImportReport,\n DataImportRequest,\n DataOp,\n DataOpResults,\n ErasedPlayersPage,\n GameDataOp,\n GameDataStore,\n PlayerDataStore,\n PlayerRef,\n PlayersDataAnswer,\n PlayersDataRequest,\n PlayersWriteAnswer,\n PlayersWriteRequest,\n ResolvePlayersAnswer,\n StudioGameDataAnswer,\n StudioPlayerDataAnswer\n} from \"../types.js\";\n\n/** A game id: one of your organization's games. */\nexport type GameId = number | string;\n\n/** What to read of a player's or a game's data. */\nexport interface DataReadQuery<Store extends string> {\n /** Which stores (default: all). */\n stores?: readonly Store[];\n /** Which keys, at most 100 (default: every key). */\n keys?: readonly string[];\n /** true: versions and times without the values. */\n keysOnly?: boolean;\n}\n\n/** Where to start reading erased players. */\nexport interface ErasedPlayersQuery {\n /** The `next` of the previous page (store it after each page). Takes precedence over `since`. */\n cursor?: string;\n /** For the very first call only: erases after this time (ISO 8601 or a Date). */\n since?: string | Date;\n}\n\nconst conditional = (ops: readonly { ifVersion?: number | null }[]): boolean =>\n ops.length > 0 && ops.every((op) => typeof op.ifVersion === \"number\");\n\n/** An empty list would read EVERYTHING (the API reads every store and key when none is named): refused. */\nfunction nonEmpty(list: readonly unknown[] | undefined, name: string): void {\n if (list !== undefined && list.length === 0) {\n throw new TypeError(`${name} must not be empty: leave it out to read every one, or name at least one`);\n }\n}\n\nconst readQuery = (q: DataReadQuery<string> | undefined) => {\n if (q === undefined) return undefined;\n nonEmpty(q.stores, \"stores\");\n nonEmpty(q.keys, \"keys\");\n return { stores: q.stores, keys: q.keys, keysOnly: q.keysOnly === undefined ? undefined : String(q.keysOnly) };\n};\n\n/**\n * Player data from your backend: each player's stores (`player`, `readonly`, `internal`) and the game's own data\n * (`public`, `internal`), with versions for safe concurrent changes (`ifVersion`).\n *\n * Writes are all or nothing. The SDK sends a write again only when every op carries `ifVersion`, and only after an\n * answer that proves nothing was applied (408, 429, 503). After no answer, a timeout, a 500, 502 or 504, the write\n * may or may not have been applied: the error has `outcomeUnknown: true` and is not sent again (a second send could\n * meet the first one's own new version). Then read the key again: if its version moved and the value is the one you\n * wrote, your write was applied; do not simply apply your change again on top of it.\n */\nexport class PlayerData {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * SplatterVault player ids for the ids other systems know your players by (at most 100 refs:\n * `{ provider, providerId, providerApp? }` or an SV player id). `id` is null for refs nobody holds. A lookup only.\n * @see POST /studio-data/games/{gameId}/players/resolve (`studioData.resolvePlayers`)\n */\n resolve(gameId: GameId, body: { refs: ReadonlyArray<PlayerRef | string> }, options?: RequestOptions): Promise<ResolvePlayersAnswer> {\n return this.http.call(\"studioData.resolvePlayers\", { path: { gameId }, body, options });\n }\n\n /**\n * One player's data in a game, by store and key: `{ data: { player: { <key>: { value, version, ... } }, ... } }`.\n * @see GET /studio-data/games/{gameId}/players/{playerId}/data (`studioData.getPlayerData`)\n */\n async get(gameId: GameId, playerId: string, query?: DataReadQuery<PlayerDataStore>, options?: RequestOptions): Promise<StudioPlayerDataAnswer> {\n return this.http.call(\"studioData.getPlayerData\", { path: { gameId, playerId }, query: readQuery(query), options });\n }\n\n /**\n * Changes one player's data (at most 100 ops: `set`, `delete`, `inc`), all or nothing. A failed `ifVersion` is\n * `version_conflict` with the current versions in `details`. On `outcomeUnknown` (see {@link PlayerData}), read\n * before writing again; a resent write that meets `version_conflict` is reported as code `outcome_unknown`.\n * @see PATCH /studio-data/games/{gameId}/players/{playerId}/data (`studioData.updatePlayerData`)\n */\n update(gameId: GameId, playerId: string, body: { ops: readonly DataOp[] }, options?: RequestOptions): Promise<DataOpResults> {\n return this.http.call(\"studioData.updatePlayerData\", {\n path: { gameId, playerId },\n body,\n options,\n conditional: conditional(body.ops)\n });\n }\n\n /**\n * Deletes all of one player's data in a game (the player stays). Resolves when done, also when there was nothing.\n * @see DELETE /studio-data/games/{gameId}/players/{playerId}/data (`studioData.clearPlayerData`)\n */\n clear(gameId: GameId, playerId: string, options?: RequestOptions): Promise<void> {\n return this.http.call(\"studioData.clearPlayerData\", { path: { gameId, playerId }, options });\n }\n\n /**\n * Several players' data (at most 100 players and 50 keys); `notFound` lists ids of no live player.\n * @see POST /studio-data/games/{gameId}/data/get (`studioData.getPlayersData`)\n */\n async getMany(gameId: GameId, body: PlayersDataRequest, options?: RequestOptions): Promise<PlayersDataAnswer> {\n nonEmpty(body.stores, \"stores\");\n nonEmpty(body.keys, \"keys\");\n return this.http.call(\"studioData.getPlayersData\", { path: { gameId }, body, options });\n }\n\n /**\n * Changes several players' data atomically (at most 100 players, 1,000 ops in all): all or nothing across every\n * player. Sent again by the SDK only as {@link PlayerData} says (every op with `ifVersion`, after 408/429/503).\n * @see POST /studio-data/games/{gameId}/data/write (`studioData.writePlayersData`)\n */\n writeMany(gameId: GameId, body: PlayersWriteRequest, options?: RequestOptions): Promise<PlayersWriteAnswer> {\n return this.http.call(\"studioData.writePlayersData\", {\n path: { gameId },\n body,\n options,\n conditional: body.writes.length > 0 && body.writes.every((w) => conditional(w.ops))\n });\n }\n\n /**\n * The game's own data (`public`: players can read it; `internal`: only your backend).\n * @see GET /studio-data/games/{gameId}/game-data (`studioData.getGameData`)\n */\n async getGameData(gameId: GameId, query?: DataReadQuery<GameDataStore>, options?: RequestOptions): Promise<StudioGameDataAnswer> {\n return this.http.call(\"studioData.getGameData\", { path: { gameId }, query: readQuery(query), options });\n }\n\n /**\n * Changes the game's data (`set` and `delete`, at most 100 ops, values at most 256 KiB). Players read `public`\n * within 30 seconds. Sent again by the SDK only as {@link PlayerData} says.\n * @see PATCH /studio-data/games/{gameId}/game-data (`studioData.updateGameData`)\n */\n updateGameData(gameId: GameId, body: { ops: readonly GameDataOp[] }, options?: RequestOptions): Promise<DataOpResults> {\n return this.http.call(\"studioData.updateGameData\", { path: { gameId }, body, options, conditional: conditional(body.ops) });\n }\n\n /**\n * Imports player and game data (at most 1,000 rows, 8 MiB). `dryRun: true` writes nothing; the same rows again\n * change nothing, so the SDK retries this call.\n * @see POST /studio-data/games/{gameId}/import (`studioData.importData`)\n */\n import(gameId: GameId, body: DataImportRequest, options?: RequestOptions): Promise<DataImportReport> {\n return this.http.call(\"studioData.importData\", { path: { gameId }, body, options });\n }\n\n /**\n * One page (oldest first, 500 at most) of your organization's erased players, for deleting what you keep about\n * them. Store the answer's `next` and pass it back as `cursor`; `more: true` means call again now.\n * @see GET /studio-data/erased-players (`studioData.listErasedPlayers`)\n */\n listErasedPlayers(query?: ErasedPlayersQuery, options?: RequestOptions): Promise<ErasedPlayersPage> {\n const cursor = query?.cursor;\n const since = cursor === undefined ? query?.since : undefined;\n return this.http.call(\"studioData.listErasedPlayers\", {\n query: { cursor, since: since instanceof Date ? since.toISOString() : since },\n options\n });\n }\n\n /**\n * Every page of erased players from `cursor` (or `since`), until a page says `more: false`. Save each page's `next`\n * once you have handled it, and start there next time (poll every few minutes).\n *\n * ```ts\n * for await (const page of sv.playerData.erasedPlayerPages({ cursor: saved })) {\n * await deleteMyRows(page.players.map((p) => p.id));\n * saved = page.next;\n * }\n * ```\n */\n async *erasedPlayerPages(query?: ErasedPlayersQuery, options?: RequestOptions): AsyncGenerator<ErasedPlayersPage, void, undefined> {\n let next: ErasedPlayersQuery = { ...query };\n for (;;) {\n const page = await this.listErasedPlayers(next, options);\n yield page;\n if (!page.more) return;\n next = { cursor: page.next };\n }\n }\n}\n","import { type HttpClient, type RequestOptions } from \"../core/http.js\";\nimport type { PlayerImportReport, PlayerImportRequest, PlayerSignIn, StudioSignInRequest } from \"../types.js\";\n\n/** Studio player sign-in from your backend: sign players in with your own ids, import players, erase players. */\nexport class Players {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Signs a player in with your own id for them (`externalId`, 1-128 visible ASCII characters) and answers a player\n * token (about an hour) to hand to that player's game client. The same `externalId` is always the same player.\n * The key needs org:issue_player_tokens; the game's \"studio\" sign-in must be on. Not retried by the SDK.\n * @see POST /player-auth/studio (`playerAuth.studio.signIn`)\n */\n signIn(body: StudioSignInRequest, options?: RequestOptions): Promise<PlayerSignIn> {\n return this.http.call(\"playerAuth.studio.signIn\", { body, options });\n }\n\n /**\n * Imports players from other systems (at most 1,000 rows, 1 MB): their identities, emails, bcrypt password hashes\n * and names. `dryRun: true` writes nothing; the same rows again change nothing, so the SDK retries this call. The\n * key needs org:import_players.\n * @see POST /player-auth/studio/import (`playerAuth.studio.importPlayers`)\n */\n import(body: PlayerImportRequest, options?: RequestOptions): Promise<PlayerImportReport> {\n return this.http.call(\"playerAuth.studio.importPlayers\", { body, options });\n }\n\n /**\n * Erases a player and everything every studio service keeps about them (identities, data in every game, store\n * holdings). It cannot be undone; their tokens stop working. Resolves when erased (204). Not retried by the SDK.\n * The key needs org:issue_player_tokens.\n * @see DELETE /player-auth/studio/players/{playerId} (`playerAuth.studio.erasePlayer`)\n */\n erase(playerId: string, options?: RequestOptions): Promise<void> {\n return this.http.call(\"playerAuth.studio.erasePlayer\", { path: { playerId }, options });\n }\n}\n","import { SplatterVaultError } from \"../core/errors.js\";\nimport { type HttpClient, type RequestOptions, sleep } from \"../core/http.js\";\nimport { intInRange, MAX_TIMER_MS } from \"../core/validate.js\";\nimport type {\n CancelScheduleAnswer,\n CreateCreditSessionRequest,\n GetSessionQuery,\n LaunchArgument,\n ListMySessionsQuery,\n ListSessionsQuery,\n PoolClaimAnswer,\n PoolClaimRequest,\n RescheduleSessionRequest,\n ServerSession,\n StopCreditSessionAnswer\n} from \"../types.js\";\n\n/** A session id (the `id` of a {@link ServerSession}). */\nexport type SessionId = number | string;\n\n/**\n * A session as {@link Sessions.waitUntilReady} answers it: the same as {@link ServerSession}, whose `ready`, `readyAt`\n * and `readyDeadlineAt` say whether (and since when) its game has said it is ready for players.\n */\nexport type ReadySession = ServerSession;\n\n/** Options of {@link Sessions.waitUntilReady}. */\nexport interface WaitUntilReadyOptions {\n /** How long to wait in all, 1 to 2147483647 ms (default 300,000: five minutes). */\n timeoutMs?: number;\n /**\n * The first wait between two reads, 250 to 60,000 ms (default 2,000); it grows by half each time, up to 10 s (or\n * up to `intervalMs` when that is longer).\n */\n intervalMs?: number;\n /**\n * true (default): wait until the GAME says it is ready (`ready`), not just until the server is up (status Active).\n * A game that sends no ready signal is returned once its `readyDeadlineAt` has passed, with `ready: false`.\n * false: return as soon as the session is Active (the Unity SDK's `WaitForServerReady` default).\n */\n waitForGameReady?: boolean;\n /** Stops waiting (and any read under way): rejects with code `aborted`. */\n signal?: AbortSignal;\n /** Called with each session read, e.g. to show progress. */\n onPoll?: (session: ReadySession) => void;\n}\n\n/** Why {@link Sessions.waitUntilReady} gave up. */\nexport type SessionWaitErrorCode =\n /** The session ended (status `Not Active`) before it was ready: see `stopReason` (e.g. `GAME_CRASH`). */\n | \"session_ended\"\n /** It was not ready within `timeoutMs`; `session` holds the last state read. */\n | \"wait_timeout\";\n\n/** {@link Sessions.waitUntilReady} gave up: the session ended, or it was not ready in time. */\nexport class SessionWaitError extends Error {\n override readonly name = \"SessionWaitError\";\n /** The session's id. */\n readonly sessionId: number | string;\n /** The session's last status read (`Pending`, `Active`, `Not Active`, `Scheduled`, …), or null if none was read. */\n readonly sessionStatus: string | null;\n /** The session's stop reason when it ended (e.g. `GAME_CRASH`, `IDLE_TIMEOUT`), else null. */\n readonly stopReason: string | null;\n /** The last session read, or null. */\n readonly session: ReadySession | null;\n\n constructor(\n /** `session_ended` or `wait_timeout`. */\n readonly code: SessionWaitErrorCode,\n sessionId: number | string,\n session: ReadySession | null,\n message: string,\n options?: { cause?: unknown }\n ) {\n super(message, options);\n this.sessionId = sessionId;\n this.session = session;\n this.sessionStatus = session?.status ?? null;\n this.stopReason = session?.stopReason ?? null;\n }\n}\n\nconst MAX_POLL_INTERVAL_MS = 10_000;\nconst MAX_CONSECUTIVE_POLL_FAILURES = 3;\n\n/** Ready to hand to players: Active, and (when asked) the game said ready, or has no readiness fields, or its deadline passed. */\nfunction isReady(session: ReadySession, waitForGameReady: boolean, nowMs: number): boolean {\n if (session.status !== \"Active\") return false;\n if (!waitForGameReady || session.ready === true || session.ready === undefined) return true;\n const deadline = session.readyDeadlineAt ? Date.parse(session.readyDeadlineAt) : Number.NaN;\n return Number.isFinite(deadline) && nowMs >= deadline;\n}\n\n/**\n * Subscription-billed game-server sessions (`/subscriptions/sessions`): the same calls as {@link Sessions}, for\n * accounts with a server subscription. Most studios use credit sessions ({@link Sessions}).\n */\nexport class SubscriptionSessions {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Starts a dedicated server for a match, billed to the subscription. Never retried by the SDK (a repeat would start\n * a second server).\n * @see POST /subscriptions/sessions (`sessions.createSubscription`)\n */\n create(body: CreateCreditSessionRequest, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.createSubscription\", { body, options });\n }\n\n /**\n * The subscription sessions, optionally of one organization and of some statuses (`\"Active,Pending\"`).\n * @see GET /subscriptions/sessions (`sessions.listSubscription`)\n */\n list(query?: ListSessionsQuery, options?: RequestOptions): Promise<ServerSession[]> {\n return this.http.call(\"sessions.listSubscription\", { query, options });\n }\n\n /**\n * Stops a subscription session.\n * @see POST /subscriptions/sessions/{sessionId}/stop (`sessions.stopSubscription`)\n */\n stop(sessionId: SessionId, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.stopSubscription\", { path: { sessionId }, options });\n }\n\n /**\n * Sets a session's friendly name (at most 255 characters).\n * @see PUT /subscriptions/sessions/{sessionId}/friendly-name (`sessions.renameSubscription`)\n */\n rename(sessionId: SessionId, friendlyName: string, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.renameSubscription\", { path: { sessionId }, body: { friendlyName }, options });\n }\n\n /**\n * Moves a scheduled session's start and end, or sets an active session's end.\n * @see PUT /subscriptions/sessions/{sessionId}/schedule (`sessions.rescheduleSubscription`)\n */\n reschedule(sessionId: SessionId, body: RescheduleSessionRequest, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.rescheduleSubscription\", { path: { sessionId }, body, options });\n }\n\n /**\n * Cancels a scheduled session (it becomes Not Active).\n * @see POST /subscriptions/sessions/{sessionId}/cancel-schedule (`sessions.cancelScheduledSubscription`)\n */\n cancelSchedule(sessionId: SessionId, options?: RequestOptions): Promise<CancelScheduleAnswer> {\n return this.http.call(\"sessions.cancelScheduledSubscription\", { path: { sessionId }, options });\n }\n}\n\n/**\n * Game-server sessions: dedicated servers SplatterVault starts for your matches, billed in credits (your\n * organization's credits with an organization API key, which also fills in `organizationId`).\n */\nexport class Sessions {\n /** Subscription-billed sessions. */\n readonly subscription: SubscriptionSessions;\n\n /** @internal */\n constructor(private readonly http: HttpClient) {\n this.subscription = new SubscriptionSessions(http);\n }\n\n /**\n * Starts a dedicated server for a match (status `Pending` until it is up; poll {@link Sessions.get} for\n * `connection`). Credits are billed per minute while it runs. Never retried by the SDK: a repeat would start a second\n * server, so on a network error look for it with {@link Sessions.list} before trying again.\n * @see POST /credits/sessions (`sessions.createCredit`)\n */\n create(body: CreateCreditSessionRequest, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.createCredit\", { body, options });\n }\n\n /**\n * The credit sessions, optionally of one organization (0: personal only) and of some statuses (`\"Active,Pending\"`).\n * @see GET /credits/sessions (`sessions.listCredit`)\n */\n list(query?: ListSessionsQuery, options?: RequestOptions): Promise<ServerSession[]> {\n return this.http.call(\"sessions.listCredit\", { query, options });\n }\n\n /**\n * One session with its connection details. `{ slim: true }` leaves out its matches.\n * @see GET /game-sessions/{id} (`sessions.get`)\n */\n get(sessionId: SessionId, query?: GetSessionQuery, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.get\", { path: { id: sessionId }, query, options });\n }\n\n /**\n * Waits until a session is ready for players and answers it: polls {@link Sessions.get} (slim) with a growing\n * interval, from `intervalMs` up to 10 s. \"Ready\" is status `Active` and, by default, the game's own ready signal\n * (`ready: true`); a game with no ready signal is returned once its `readyDeadlineAt` (server up + 300 s) passes,\n * with `ready: false`. The counterpart of the Unity SDK's `WaitForServerReady`.\n *\n * Rejects with a {@link SessionWaitError}: `session_ended` as soon as the session is `Not Active` (see its\n * `stopReason`), or `wait_timeout` after `timeoutMs` (default five minutes). A read that fails transiently is\n * tolerated twice in a row; any other refusal (e.g. 404) rejects at once. An aborted `signal` rejects with a\n * `SplatterVaultError` of code `aborted`.\n *\n * ```ts\n * const session = await sv.sessions.create({ gameTypeConfigKey: \"my-game\", region: \"NYC3\" });\n * const ready = await sv.sessions.waitUntilReady(session.id);\n * console.log(ready.connection?.host, ready.connection?.primaryPort);\n * ```\n */\n async waitUntilReady(sessionId: SessionId, options: WaitUntilReadyOptions = {}): Promise<ReadySession> {\n const timeoutMs = intInRange(options.timeoutMs ?? 300_000, \"timeoutMs\", 1, MAX_TIMER_MS);\n let interval = intInRange(options.intervalMs ?? 2_000, \"intervalMs\", 250, 60_000);\n const maxInterval = Math.max(MAX_POLL_INTERVAL_MS, interval);\n const waitForGameReady = options.waitForGameReady !== false;\n const signal = options.signal;\n const giveUpAt = Date.now() + timeoutMs;\n let last: ReadySession | null = null;\n let failures = 0;\n for (;;) {\n const remaining = giveUpAt - Date.now();\n try {\n const session = await this.get(sessionId, { slim: true }, {\n ...(signal ? { signal } : {}),\n timeoutMs: Math.max(1, Math.min(this.http.defaultTimeoutMs, remaining))\n });\n failures = 0;\n last = session;\n options.onPoll?.(session);\n if (session.status === \"Not Active\") {\n const reason = session.stopReason ? ` (stop reason: ${session.stopReason})` : \"\";\n throw new SessionWaitError(\"session_ended\", sessionId, session, `session ${sessionId} ended before it was ready${reason}`);\n }\n if (isReady(session, waitForGameReady, Date.now())) return session;\n } catch (err) {\n if (!(err instanceof SplatterVaultError) || err.code === \"aborted\") throw err;\n // A transient failure (after the SDK's own retries) is tolerated a couple of times; anything else is real.\n if (!err.isTransient || ++failures >= MAX_CONSECUTIVE_POLL_FAILURES || Date.now() >= giveUpAt) throw err;\n }\n const left = giveUpAt - Date.now();\n if (left <= 0) {\n const state = last ? ` (last status: ${last.status}${last.status === \"Active\" && waitForGameReady ? \", game not ready yet\" : \"\"})` : \"\";\n throw new SessionWaitError(\"wait_timeout\", sessionId, last, `session ${sessionId} was not ready within ${timeoutMs} ms${state}`);\n }\n try {\n await sleep(Math.min(interval, left), signal);\n } catch (reason) {\n throw new SplatterVaultError({\n status: 0,\n code: \"aborted\",\n message: \"aborted: the call was aborted by its signal\",\n operationId: \"sessions.get\",\n method: \"GET\",\n path: `/game-sessions/${encodeURIComponent(String(sessionId))}`,\n cause: reason\n });\n }\n interval = Math.min(Math.round(interval * 1.5), maxInterval);\n }\n }\n\n /**\n * The sessions this key (or account) created, optionally of one game type and status.\n * @see GET /game-sessions/my-sessions (`sessions.listMine`)\n */\n listMine(query?: ListMySessionsQuery, options?: RequestOptions): Promise<ServerSession[]> {\n return this.http.call(\"sessions.listMine\", { query, options });\n }\n\n /**\n * Stops a credit session and bills it: answers the session, its hours and its cost.\n * @see POST /credits/sessions/{sessionId}/stop (`sessions.stopCredit`)\n */\n stop(sessionId: SessionId, options?: RequestOptions): Promise<StopCreditSessionAnswer> {\n return this.http.call(\"sessions.stopCredit\", { path: { sessionId }, options });\n }\n\n /**\n * Sets a session's friendly name (at most 255 characters).\n * @see PUT /credits/sessions/{sessionId}/friendly-name (`sessions.renameCredit`)\n */\n rename(sessionId: SessionId, friendlyName: string, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.renameCredit\", { path: { sessionId }, body: { friendlyName }, options });\n }\n\n /**\n * Moves a scheduled session's start and end, or sets an active session's end.\n * @see PUT /credits/sessions/{sessionId}/schedule (`sessions.rescheduleCredit`)\n */\n reschedule(sessionId: SessionId, body: RescheduleSessionRequest, options?: RequestOptions): Promise<ServerSession> {\n return this.http.call(\"sessions.rescheduleCredit\", { path: { sessionId }, body, options });\n }\n\n /**\n * Cancels a scheduled credit session (it becomes Not Active).\n * @see POST /credits/sessions/{sessionId}/cancel-schedule (`sessions.cancelScheduledCredit`)\n */\n cancelSchedule(sessionId: SessionId, options?: RequestOptions): Promise<CancelScheduleAnswer> {\n return this.http.call(\"sessions.cancelScheduledCredit\", { path: { sessionId }, options });\n }\n}\n\n/** Warm server pools: servers already running, claimed for a match in seconds. */\nexport class ServerPools {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Claims a warm server from pool `poolId` for a match: answers the new session's id, the pool instance and its\n * `connection` (null until reachable). Needs a key holding org:manage_pools. Never retried by the SDK: a repeat\n * would claim a second server.\n * @see POST /server-pools/{id}/claim (`serverPools.claim`)\n */\n claim(poolId: number | string, body?: PoolClaimRequest, options?: RequestOptions): Promise<PoolClaimAnswer> {\n return this.http.call(\"serverPools.claim\", { path: { id: poolId }, body: body ?? {}, options });\n }\n}\n\n/** Game types (the games SplatterVault hosts servers for). */\nexport class Games {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * The launch arguments a session of this game may set (`userConfigurable`), by the game's key (or its id).\n * @see GET /game-types/{id}/configurable-args (`games.getConfigurableArgs`)\n */\n getConfigurableArgs(game: string | number, options?: RequestOptions): Promise<LaunchArgument[]> {\n return this.http.call(\"games.getConfigurableArgs\", { path: { id: game }, options });\n }\n}\n","import { type HttpClient, type IdempotentRequestOptions, type RequestOptions } from \"../core/http.js\";\nimport type {\n MetaPurchaseSyncAnswer,\n StoreCatalogImportRequest,\n StoreGrantRequest,\n StoreHistoryPage,\n StoreHoldings,\n StoreHoldingsImportRequest,\n StoreImportReport,\n StoreItemUpdateRequest,\n StoreReversalRequest,\n StoreStudioConsumeRequest,\n StoreStudioPurchaseRequest,\n StoreTxnResult,\n StudioMetaPurchaseSyncRequest,\n StudioStoreCatalog\n} from \"../types.js\";\n\n/**\n * A player, for the store: their SplatterVault id (uuid), or another system's id for them: `steam:<SteamID>`,\n * `meta:<org-scoped id>`, `studio:<your id>`, `xsolla:<Login project id>:<user id>`,\n * `playfab:<title id>:<PlayFabId>`, `supabase:<project ref>:<user id>`. The SDK URL-encodes it.\n */\nexport type StorePlayer = string;\n\n/**\n * Your organization's store from your backend: virtual currencies and items, players' holdings, and server-side\n * changes (grant, consume, purchase, reverse), each applied exactly once per `Idempotency-Key`.\n *\n * Every change sends an `Idempotency-Key`: the SDK makes one per call and reuses it on its own retries; pass\n * `{ idempotencyKey }` to choose it (see {@link IdempotentRequestOptions}). A repeat answers the first result with\n * `replayed: true`.\n */\nexport class Store {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * The whole catalog (archived entries too) and the store's settings. The key needs org:view_economy or\n * org:grant_economy.\n * @see GET /store/studio/catalog (`store.studio.getCatalog`)\n */\n getCatalog(options?: RequestOptions): Promise<StudioStoreCatalog> {\n return this.http.call(\"store.studio.getCatalog\", { options });\n }\n\n /**\n * A player's balances and items.\n * @see GET /store/studio/players/{player} (`store.studio.getPlayer`)\n */\n getPlayer(player: StorePlayer, options?: RequestOptions): Promise<StoreHoldings> {\n return this.http.call(\"store.studio.getPlayer\", { path: { player }, options });\n }\n\n /**\n * One page (50) of a player's store history, newest first; pass the answer's `next` as `before` for older ones\n * (`next` is null on the last page). See {@link Store.historyPages} to walk every page.\n * @see GET /store/studio/players/{player}/history (`store.studio.getPlayerHistory`)\n */\n getHistory(player: StorePlayer, query?: { before?: string }, options?: RequestOptions): Promise<StoreHistoryPage> {\n return this.http.call(\"store.studio.getPlayerHistory\", { path: { player }, query: { before: query?.before }, options });\n }\n\n /**\n * Every page of a player's store history, newest first, from `before` (default: the newest).\n *\n * ```ts\n * for await (const page of sv.store.historyPages(playerId)) {\n * for (const txn of page.txns) console.log(txn.kind, txn.createdAt);\n * }\n * ```\n */\n async *historyPages(player: StorePlayer, query?: { before?: string }, options?: RequestOptions): AsyncGenerator<StoreHistoryPage, void, undefined> {\n let before = query?.before;\n for (;;) {\n const page = await this.getHistory(player, { before }, options);\n yield page;\n if (!page.next) return;\n before = page.next;\n }\n }\n\n /**\n * Gives a player items and currency (1-50 lines: `{ sku, quantity, custom? }` or `{ currency, amount }`). Bundles\n * give their contents; currency caps and `maxOwned` apply. The key needs org:grant_economy.\n * @see POST /store/studio/players/{player}/grants (`store.studio.grant`)\n */\n grant(player: StorePlayer, body: StoreGrantRequest, options?: IdempotentRequestOptions): Promise<StoreTxnResult> {\n return this.http.call(\"store.studio.grant\", { path: { player }, body, options });\n }\n\n /**\n * Uses up or takes a player's items and currency (by SKU oldest first, by `instanceId`, or `{ currency, amount }`),\n * never below zero: `insufficient_items` / `insufficient_funds` otherwise.\n * @see POST /store/studio/players/{player}/consume (`store.studio.consume`)\n */\n consume(player: StorePlayer, body: StoreStudioConsumeRequest, options?: IdempotentRequestOptions): Promise<StoreTxnResult> {\n return this.http.call(\"store.studio.consume\", { path: { player }, body, options });\n }\n\n /**\n * Buys an item with the player's virtual currency, from the server (the item's player-purchase switch does not\n * apply). Send `expectedPrice` to refuse a changed price (`price_changed`).\n * @see POST /store/studio/players/{player}/purchases (`store.studio.purchase`)\n */\n purchase(player: StorePlayer, body: StoreStudioPurchaseRequest, options?: IdempotentRequestOptions): Promise<StoreTxnResult> {\n return this.http.call(\"store.studio.purchase\", { path: { player }, body, options });\n }\n\n /**\n * Sets the custom data of one of a player's items (a JSON object of at most 1 KB, or null).\n * @see PATCH /store/studio/players/{player}/items/{instanceId} (`store.studio.updateItem`)\n */\n updateItem(\n player: StorePlayer,\n instanceId: string,\n body: StoreItemUpdateRequest,\n options?: IdempotentRequestOptions\n ): Promise<StoreTxnResult> {\n return this.http.call(\"store.studio.updateItem\", { path: { player, instanceId }, body, options });\n }\n\n /**\n * Reverses an earlier change, named by its `txn` id or by the `originalKey` (the Idempotency-Key it was sent with):\n * takes back what the player still holds and gives back what it took; what was spent already is in `shortfall`.\n * Once per change (`already_reversed`).\n * @see POST /store/studio/players/{player}/reversals (`store.studio.reverse`)\n */\n reverse(player: StorePlayer, body: StoreReversalRequest, options?: IdempotentRequestOptions): Promise<StoreTxnResult> {\n return this.http.call(\"store.studio.reverse\", { path: { player }, body, options });\n }\n\n /**\n * Checks the player's Meta Quest purchases and grants what is new (the player must have Meta linked). Not retried\n * by the SDK.\n * @see POST /store/studio/players/{player}/platform-purchases/meta (`store.studio.syncMetaPurchases`)\n */\n syncMetaPurchases(player: StorePlayer, body: StudioMetaPurchaseSyncRequest, options?: RequestOptions): Promise<MetaPurchaseSyncAnswer> {\n return this.http.call(\"store.studio.syncMetaPurchases\", { path: { player }, body, options });\n }\n\n /**\n * Imports a catalog (`format`: `playfab`, `xsolla` or `sv`; 1-1,000 rows). Re-running a file changes nothing, so\n * the SDK retries this call. The key needs org:manage_economy.\n * @see POST /store/studio/imports/catalog (`store.studio.importCatalog`)\n */\n importCatalog(body: StoreCatalogImportRequest, options?: RequestOptions): Promise<StoreImportReport> {\n return this.http.call(\"store.studio.importCatalog\", { body, options });\n }\n\n /**\n * Imports players' balances and items (1-1,000 rows; each player once per `source`, so the same rows again change\n * nothing and the SDK retries this call). The key needs org:manage_economy.\n * @see POST /store/studio/imports/holdings (`store.studio.importHoldings`)\n */\n importHoldings(body: StoreHoldingsImportRequest, options?: RequestOptions): Promise<StoreImportReport> {\n return this.http.call(\"store.studio.importHoldings\", { body, options });\n }\n}\n","import { type FetchLike, HttpClient, MAX_RETRIES } from \"./core/http.js\";\nimport { DEFAULT_RETRY, type RetrySettings } from \"./core/retry.js\";\nimport { checkServiceUrl, intInRange, MAX_TIMER_MS } from \"./core/validate.js\";\nimport { PlayerTokenVerifier, DEFAULT_BASE_URL, type PlayerTokenClaims, type VerifyOptions } from \"./playerToken/verify.js\";\nimport { Billing } from \"./resources/billing.js\";\nimport { PlayerData } from \"./resources/playerData.js\";\nimport { Players } from \"./resources/players.js\";\nimport { Games, ServerPools, Sessions } from \"./resources/sessions.js\";\nimport { Store } from \"./resources/store.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\nexport interface SplatterVaultOptions {\n /**\n * Your organization API key (`sv_org_...`), holding the permissions of the calls you make. Default:\n * `process.env.SV_API_KEY`. Keep it on your servers: never in a game build or a web page.\n */\n apiKey?: string;\n /**\n * The API base URL. Default `https://splattervault.com/rest`. https only (plain http only for localhost, 127.0.0.1\n * or [::1], e.g. a local mock); no credentials, query or fragment. The SDK never follows redirects.\n */\n baseUrl?: string;\n /** The `fetch` to call (default: the global one, Node.js 18+). Tests and proxies can pass their own. */\n fetch?: FetchLike;\n /** Retries after the first attempt, for calls that are safe to repeat: 0 to 20 (default 2). 0 turns retries off. */\n maxRetries?: number;\n /**\n * How long one attempt may take in ms, answer included: 1 to 2147483647 (default 30,000). Slow operations (creating\n * or claiming servers: 60 s; imports: 120 s) get at least their own default.\n */\n timeoutMs?: number;\n /** Prefixed to the SDK's User-Agent, e.g. `my-matchmaker/2.1`. */\n userAgent?: string;\n /** Waits between retries, each 0 to 2147483647 ms. */\n retry?: Partial<Pick<RetrySettings, \"baseDelayMs\" | \"maxDelayMs\" | \"maxRetryAfterMs\">>;\n /**\n * The SDK refuses to start in a browser, a web worker, React Native, Electron or NW.js: an organization API key in\n * anything you ship to players is readable by them. Set this only for a trusted environment that merely looks like\n * one (e.g. a test runner with a DOM, an internal Electron tool). Game clients use a game-client SDK and player\n * tokens instead.\n */\n dangerouslyAllowBrowser?: boolean;\n /**\n * Allows a plain-http `baseUrl` on a host other than localhost / 127.0.0.1 / [::1]. Your API key would travel\n * unencrypted: for a development server on a network you trust only.\n */\n dangerouslyAllowInsecureHttp?: boolean;\n}\n\n/**\n * True in a browser, a web worker, React Native, or an app shell that ships to players: Electron (main process and\n * renderer) and NW.js.\n */\nexport function isBrowserLike(): boolean {\n const g = globalThis as Record<string, unknown> & { navigator?: { product?: string } };\n const versions = (typeof process !== \"undefined\" ? process.versions : undefined) as Record<string, string | undefined> | undefined;\n if (versions?.electron !== undefined || versions?.nw !== undefined) return true;\n const win = g.window as { document?: unknown } | undefined;\n if (win !== undefined && win !== null && typeof win === \"object\" && win.document !== undefined) return true;\n if (typeof g.importScripts === \"function\") return true;\n const workerScope = g.WorkerGlobalScope as (abstract new () => unknown) | undefined;\n if (typeof workerScope === \"function\" && globalThis instanceof workerScope) return true;\n if (g.navigator?.product === \"ReactNative\") return true;\n return false;\n}\n\nconst API_KEY_RE = /^[\\x21-\\x7e]+$/;\n\n/**\n * The SplatterVault server client: one per process, for your game backend and game servers.\n *\n * ```ts\n * import { SplatterVault } from \"@splattervault/server\";\n *\n * const sv = new SplatterVault({ apiKey: process.env.SV_API_KEY });\n * const session = await sv.sessions.create({ gameTypeConfigKey: \"my-game\", region: \"NYC3\" });\n * ```\n */\nexport class SplatterVault {\n /** Game-server sessions billed in credits (and `sessions.subscription` for subscription-billed ones). */\n readonly sessions: Sessions;\n /** Warm server pools: claim a running server for a match. */\n readonly serverPools: ServerPools;\n /** Game types: the launch arguments a session may set. */\n readonly games: Games;\n /** Credits, subscriptions and usage. */\n readonly billing: Billing;\n /** Studio player sign-in from your backend: sign in with your own ids, import, erase. */\n readonly players: Players;\n /** Each player's data and the game's data. */\n readonly playerData: PlayerData;\n /** The store: catalog, holdings, grants, consumes, purchases, reversals, imports. */\n readonly store: Store;\n\n readonly #http: HttpClient;\n readonly #insecureHttp: boolean;\n #verifier: PlayerTokenVerifier | null = null;\n\n constructor(options: SplatterVaultOptions = {}) {\n if (isBrowserLike() && options.dangerouslyAllowBrowser !== true) {\n throw new Error(\n \"@splattervault/server refuses to run in a browser-like environment (a browser, a web worker, React Native, \" +\n \"Electron or NW.js): an organization API key there is readable by anyone who has the page or the app. Call \" +\n \"SplatterVault from your server; game clients sign players in and use player tokens. If this environment is \" +\n \"trusted and only looks like one, pass { dangerouslyAllowBrowser: true }.\"\n );\n }\n const apiKey = options.apiKey ?? (typeof process !== \"undefined\" ? process.env?.SV_API_KEY : undefined);\n if (typeof apiKey !== \"string\" || apiKey === \"\") {\n throw new TypeError(\"apiKey is required: pass { apiKey } or set SV_API_KEY (an organization API key, sv_org_...)\");\n }\n if (!API_KEY_RE.test(apiKey)) throw new TypeError(\"apiKey must be visible ASCII characters only (check for spaces or line breaks)\");\n const fetchFn = options.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (typeof fetchFn !== \"function\") throw new TypeError(\"no fetch: use Node.js 18 or later, or pass { fetch }\");\n this.#insecureHttp = options.dangerouslyAllowInsecureHttp === true;\n const baseUrl = checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, \"baseUrl\", this.#insecureHttp);\n // Numbers are checked here: NaN retries would never stop, and a timer past 2^31-1 ms fires after 1 ms.\n const timeoutMs = intInRange(options.timeoutMs ?? 30_000, \"timeoutMs\", 1, MAX_TIMER_MS);\n const maxRetries = intInRange(options.maxRetries ?? DEFAULT_RETRY.maxRetries, \"maxRetries\", 0, MAX_RETRIES);\n const retry: RetrySettings = { ...DEFAULT_RETRY, maxRetries };\n for (const name of [\"baseDelayMs\", \"maxDelayMs\", \"maxRetryAfterMs\"] as const) {\n const value = options.retry?.[name];\n if (value !== undefined) retry[name] = intInRange(value, `retry.${name}`, 0, MAX_TIMER_MS);\n }\n const sdkAgent = `splattervault-server-node/${SDK_VERSION} node/${typeof process !== \"undefined\" ? process.version : \"unknown\"}`;\n\n this.#http = new HttpClient({\n apiKey,\n baseUrl,\n fetch: fetchFn,\n timeoutMs,\n retry,\n userAgent: options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent\n });\n this.sessions = new Sessions(this.#http);\n this.serverPools = new ServerPools(this.#http);\n this.games = new Games(this.#http);\n this.billing = new Billing(this.#http);\n this.players = new Players(this.#http);\n this.playerData = new PlayerData(this.#http);\n this.store = new Store(this.#http);\n }\n\n /** The API base URL this client calls. */\n get baseUrl(): string {\n return this.#http.baseUrl;\n }\n\n /**\n * Verifies a player's token offline (Ed25519, against `GET /player-auth/keys` of this client's base URL, cached as\n * the answer's Cache-Control allows) and answers its claims: `claims.sub` is the player's id. Rejects with a\n * `PlayerTokenError` (`token_invalid`, `token_expired` or `keys_unavailable`). The API key is not sent.\n *\n * ```ts\n * const { sub: playerId } = await sv.verifyPlayerToken(tokenFromClient, { gameId: 42 });\n * ```\n */\n verifyPlayerToken(token: string, options: VerifyOptions & { gameId: number | readonly number[] }): Promise<PlayerTokenClaims> {\n this.#verifier ??= new PlayerTokenVerifier({\n baseUrl: this.#http.baseUrl,\n fetch: this.#http.fetchFn,\n dangerouslyAllowInsecureHttp: this.#insecureHttp\n });\n return this.#verifier.verify(token, options);\n }\n\n /** Never shows the API key. */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `SplatterVault { baseUrl: '${this.#http.baseUrl}' }`;\n }\n\n /** Never shows the API key. */\n toJSON(): { baseUrl: string } {\n return { baseUrl: this.#http.baseUrl };\n }\n}\n","/**\n * What a game server running ON SplatterVault learns from its environment.\n *\n * The SplatterVault wrapper starts your game process with an allowlisted environment (it never passes its own\n * credentials). These are the session variables in that list:\n *\n * | Variable | Cold session (its own server) | Pool server (claimed for a match) |\n * |-----------------|------------------------------------------|-------------------------------------------------------|\n * | `SESSION_ID` | the session's id | empty: the claim does not set it |\n * | `CODE` | the session's join code | the claiming session's fresh code |\n * | `MODE` | the session's mode | set when the pool server booted, not by the claim |\n * | `SERVER_NAME` | the session's server name | set when the pool server booted |\n * | `FRIENDLY_NAME` | the session's friendly name | set when the pool server booted |\n * | `GAME_TYPE` | the game type | the game type |\n * | `BUILD_CHANNEL` | the build channel name, when there is one | the build channel name, when there is one |\n * | `SLAVE_PORT` | the base game port, when set | the base game port, when set |\n *\n * Your game's own variables (`GAME_TYPE_ENV_*` as configured in the console, and channel overrides) are passed\n * too, under the names you gave them.\n */\nexport interface SessionEnvironment {\n /** True when the variables look like a SplatterVault game server's (`GAME_TYPE` and `CODE` are set). */\n onSplatterVault: boolean;\n /** The session's id on a cold session server; null on a pool server (use the id `serverPools.claim()` answered). */\n sessionId: number | null;\n /** The session's join code (on a pool server: the claiming session's). */\n code: string | null;\n /** The game type, e.g. `PPG`. */\n gameType: string | null;\n /** The session's mode (on a pool server: the pool's, from its boot). */\n mode: string | null;\n /** The server name (on a pool server: from its boot). */\n serverName: string | null;\n /** The friendly name (on a pool server: from its boot). */\n friendlyName: string | null;\n /** The build channel name, or null. */\n buildChannel: string | null;\n /** The base game port, or null when the wrapper did not set one. */\n slavePort: number | null;\n}\n\ntype Env = Record<string, string | undefined>;\n\nconst text = (env: Env, name: string): string | null => {\n const value = env[name];\n return value === undefined || value.trim() === \"\" ? null : value;\n};\n\nconst positiveInt = (value: string | null): number | null => {\n if (value === null || !/^\\d+$/.test(value.trim())) return null;\n const n = Number(value.trim());\n return Number.isSafeInteger(n) && n > 0 ? n : null;\n};\n\n/**\n * Reads the session variables the SplatterVault wrapper gives a game process (see {@link SessionEnvironment}).\n * Pass another object than `process.env` to read a saved environment.\n */\nexport function readSessionEnvironment(env: Env = process.env): SessionEnvironment {\n const code = text(env, \"CODE\");\n const gameType = text(env, \"GAME_TYPE\");\n return {\n onSplatterVault: code !== null && gameType !== null,\n sessionId: positiveInt(text(env, \"SESSION_ID\")),\n code,\n gameType,\n mode: text(env, \"MODE\"),\n serverName: text(env, \"SERVER_NAME\"),\n friendlyName: text(env, \"FRIENDLY_NAME\"),\n buildChannel: text(env, \"BUILD_CHANNEL\"),\n slavePort: positiveInt(text(env, \"SLAVE_PORT\"))\n };\n}\n"]}
|