@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 ADDED
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@splattervault/server` are listed here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package uses [semantic versioning](https://semver.org/);
5
+ while it is 0.x, a minor version may change the API.
6
+
7
+ ## [0.1.0] - Unreleased (preview)
8
+
9
+ The first release: the Studio API's server operations (organization API key) for Node.js 18 and later.
10
+
11
+ ### Added
12
+
13
+ - `SplatterVault` client with the API key from `apiKey` or `SV_API_KEY`; refuses to start in a browser, a web
14
+ worker or React Native unless `dangerouslyAllowBrowser`; never shows the key in logs, `util.inspect`, JSON or errors.
15
+ - Game-server sessions: `sessions.create/list/get/listMine/stop/rename/reschedule/cancelSchedule`, the same for
16
+ subscription-billed sessions under `sessions.subscription`, `serverPools.claim`, `games.getConfigurableArgs`, and
17
+ `sessions.waitUntilReady` (polls until the game is ready; `SessionWaitError` with `session_ended` / `wait_timeout`).
18
+ - Billing: `billing.getCredits/getCreditStats/getOrgCredits/getOrgSubscriptions/getOrgCreditsById/getOrgSubscriptionById/getSubscriptions/getUsage`.
19
+ - Player sign-in from your backend: `players.signIn/import/erase`.
20
+ - Player data: `playerData.resolve/get/update/clear/getMany/writeMany/getGameData/updateGameData/import/listErasedPlayers`
21
+ and the `playerData.erasedPlayerPages` page iterator.
22
+ - Store: `store.getCatalog/getPlayer/getHistory/grant/consume/purchase/updateItem/reverse/syncMetaPurchases/importCatalog/importHoldings`
23
+ and the `store.historyPages` page iterator. Store changes send an `Idempotency-Key` (made per call, reused on
24
+ retries, or yours with `{ idempotencyKey }`; `null` makes one, so `err.idempotencyKey` can be passed straight back).
25
+ - Offline player-token verification: `verifyPlayerToken`, `createPlayerTokenVerifier`, `sv.verifyPlayerToken`
26
+ (Ed25519 with `node:crypto`; the JWKS from `GET /player-auth/keys` cached per its Cache-Control, at least 60 s and
27
+ at most an hour, fetched again on an unknown key id, stale keys usable 300 s while the API is unreachable; the API's
28
+ own checks plus your game id; sign-in methods added later are accepted).
29
+ - `readSessionEnvironment()` for game processes started by SplatterVault.
30
+ - `SplatterVaultError` with `status`, `code`, `message`, `details`, `retryAfter`, `requestId` (both API error shapes),
31
+ `outcomeUnknown` (a write that may or may not have been applied) and `idempotencyKey` (the key a store change was
32
+ sent with, to resend it exactly once).
33
+ - Retries for safe calls only, on network errors, timeouts, 408, 429, 500, 502, 503 and 504, honouring `Retry-After`,
34
+ with jittered exponential backoff: reads, lookups, imports and `clear`; store changes with the same Idempotency-Key
35
+ and body (also after a resend meets its own in-progress `idempotency_conflict`); player-data writes whose every op
36
+ has `ifVersion` only after 408, 429 or 503 (never after an unknown outcome; a resend that meets `version_conflict` is
37
+ `outcome_unknown`). Per-attempt timeouts; `AbortSignal` support.
38
+ - Safety: redirects are never followed (`redirect_not_followed`), so the API key never goes to another address; plain
39
+ http only for loopback hosts (or `dangerouslyAllowInsecureHttp`), for the API and the player-token keys alike;
40
+ numeric options validated (NaN, Infinity and out-of-range values throw); `.` and `..` path parameters and empty
41
+ `stores` / `keys` lists refused; the SDK refuses to start in Electron and NW.js as in browsers.
42
+ - One copy for `import` and `require` (the ES module entry re-exports the CommonJS build): `instanceof` holds across
43
+ both, and the key cache is shared.
44
+ - Request and answer types generated from the Studio API's OpenAPI description (`npm run generate`).
45
+ - ESM and CommonJS builds with type declarations; no runtime dependencies.
46
+
47
+ ### API description
48
+
49
+ - `openapi/studio-api.json` is the corrected Studio API description: `StoreHoldingsImportRequest.rows[].balances` is
50
+ `{ [currency code]: amount }` (an integer of at least 0 per code), not a list of `{ currency, amount }`. The
51
+ generated type changed accordingly (`balances?: { [key: string]: number }`).
52
+ - `ServerSession` now lists `ready`, `readyAt` and `readyDeadlineAt` (optional; the times nullable), so `ReadySession`
53
+ is an alias of `ServerSession`.
54
+ - Its code samples now name the key variable `SV_API_KEY`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SplatterVault
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,365 @@
1
- # Temporary Holding Version
1
+ # @splattervault/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The SplatterVault SDK for your **game backend and game servers** (Node.js 18+, TypeScript types included, no
4
+ runtime dependencies).
5
+
6
+ - **Game servers**: start a dedicated server for a match, or claim a warm one from a pool in seconds; stop, rename,
7
+ reschedule; credits and subscriptions.
8
+ - **Players**: sign players in with your own ids, import players from other systems, erase a player and everything
9
+ kept about them.
10
+ - **Player data**: read and write each player's data and your game's data, with versions for safe concurrent changes.
11
+ - **Store**: grant, consume, buy with virtual currency and reverse, each applied exactly once; catalog and holdings
12
+ imports.
13
+ - **Player tokens**: verify, offline, that a player connecting to your game server really signed in to SplatterVault.
14
+
15
+ > **Preview (0.x).** The API surface may still change between minor versions; see the [CHANGELOG](CHANGELOG.md).
16
+
17
+ ## Your API key stays on your servers
18
+
19
+ This SDK calls the Studio API with an **organization API key** (`sv_org_...`). Anyone who holds that key can act as
20
+ your studio: grant items, read and erase players, start servers billed to you. So:
21
+
22
+ - Put the key only on your backend and game servers (an environment variable or your secret manager). **Never in a
23
+ game build, a web page or a mobile app**, never in a repository.
24
+ - The SDK refuses to start in a browser, a web worker, React Native, Electron or NW.js (anything you ship to players),
25
+ and it never logs or prints the key (not even in `console.log(sv)` or in errors).
26
+ - The key only travels over https to the URL you configured: the SDK refuses a plain-http `baseUrl` except for
27
+ localhost / 127.0.0.1 / [::1] (a local mock), and it **never follows a redirect** (a 3xx is an error with code
28
+ `redirect_not_followed`), so the key is never sent to another address.
29
+ - Give each key only the permissions it needs (console → your organization → API keys), and rotate it if it leaks.
30
+
31
+ Game clients do not use this SDK. They sign their player in (Steam, Meta, email, a guest, your own backend…) and call
32
+ the player routes with a short-lived **player token**, using the SDK of their engine:
33
+ [Unity](https://github.com/splattervault/unity-sdk), [Unreal](https://github.com/splattervault/unreal-sdk) or
34
+ [Godot](https://github.com/splattervault/godot-sdk).
35
+
36
+ ## Install
37
+
38
+ ```sh
39
+ npm install @splattervault/server
40
+ ```
41
+
42
+ Works from ESM (`import`) and CommonJS (`require`), on Node.js 18, 20, 22 and later. Both load the same single copy of
43
+ the SDK (the ES module entry re-exports the CommonJS build), so `instanceof SplatterVaultError` holds whichever way an
44
+ error was created.
45
+
46
+ ## Quick start
47
+
48
+ ```ts
49
+ import { SplatterVault } from "@splattervault/server";
50
+
51
+ const sv = new SplatterVault({ apiKey: process.env.SV_API_KEY });
52
+ // With no apiKey option, the SDK reads SV_API_KEY itself.
53
+ ```
54
+
55
+ One client per process is enough; it is safe to share.
56
+
57
+ ### Give a match a dedicated server
58
+
59
+ Claim a warm server from one of your pools (it is already running: seconds), or start a new session (about a
60
+ minute):
61
+
62
+ ```ts
63
+ import { SplatterVault, SplatterVaultError } from "@splattervault/server";
64
+
65
+ const sv = new SplatterVault();
66
+
67
+ async function serverForMatch(matchId: string) {
68
+ try {
69
+ const claim = await sv.serverPools.claim(12, { friendlyName: `Match ${matchId}`, mode: "Ranked" });
70
+ return claim; // { sessionId, serverInstanceId, connection: { host, primaryPort, code, ... } | null }
71
+ } catch (err) {
72
+ // 409: no warm server free right now: start a new one instead.
73
+ if (!(err instanceof SplatterVaultError) || err.status !== 409) throw err;
74
+ }
75
+ const session = await sv.sessions.create({
76
+ gameTypeConfigKey: "my-game",
77
+ region: "NYC3",
78
+ friendlyName: `Match ${matchId}`,
79
+ idleTimeoutMinutes: 15 // stops itself 15 minutes after the last player leaves
80
+ });
81
+ // "Pending" until the server is up: wait until the game says it is ready (up to 5 minutes by default).
82
+ const ready = await sv.sessions.waitUntilReady(session.id);
83
+ return { sessionId: ready.id, connection: ready.connection ?? null };
84
+ }
85
+
86
+ // When the match is over:
87
+ const { totalCost } = await sv.sessions.stop(sessionId); // credits billed for this session
88
+ ```
89
+
90
+ `waitUntilReady` polls the session with a growing interval (2 s, then up to 10 s) until it is Active and its game
91
+ says it is ready (`ready: true`; a game with no ready signal is returned once its `readyDeadlineAt` passes, with
92
+ `ready: false`; `{ waitForGameReady: false }` returns as soon as it is Active). It rejects with a `SessionWaitError`:
93
+ `session_ended` (with `sessionStatus` and `stopReason`, e.g. `GAME_CRASH`) or `wait_timeout` (`timeoutMs`, default
94
+ 5 minutes), and honours `signal`.
95
+
96
+ Creating a session, stopping one and claiming a pool server are **never retried by the SDK** (a repeat could start or
97
+ claim a second server). After a network error, look for the session with `sv.sessions.list()` before trying again.
98
+
99
+ ### Verify a player's token on your game server
100
+
101
+ The game client sends its player token when it connects; your server checks it **offline** against SplatterVault's
102
+ public keys (Ed25519; fetched once, then cached as long as the API's `Cache-Control` allows, and fetched again when a
103
+ token names a new key):
104
+
105
+ ```ts
106
+ import { createPlayerTokenVerifier, PlayerTokenError } from "@splattervault/server";
107
+
108
+ const verifier = createPlayerTokenVerifier({ gameId: 42 }); // one for the life of the server
109
+
110
+ async function onConnect(token: string) {
111
+ try {
112
+ const claims = await verifier.verify(token);
113
+ return claims.sub; // the player's SplatterVault id
114
+ } catch (err) {
115
+ if (err instanceof PlayerTokenError) {
116
+ // token_expired: the client refreshes its token and connects again
117
+ // keys_unavailable: SplatterVault could not be reached to fetch the keys: try again shortly
118
+ // token_invalid: refuse (err.reason says which check failed, for your logs)
119
+ }
120
+ throw err;
121
+ }
122
+ }
123
+ ```
124
+
125
+ It checks what the API itself checks: the signature, `iss` = `splattervault`, `aud` = `sv-player:<your game id>`
126
+ (a token for another of your games is refused), `iat` and `exp` with 30 seconds of clock tolerance, no `nbf`, and the
127
+ shape of every claim. Verifying needs no API key (the keys are public), so it also works in a game server that holds
128
+ none. With a client at hand: `await sv.verifyPlayerToken(token, { gameId: 42 })`; or the one-off
129
+ `verifyPlayerToken(token, { gameId: 42 })`.
130
+
131
+ What offline verification cannot know:
132
+
133
+ - **Erased players and changed owners.** The API refuses a token whose player was erased since it was issued
134
+ (`player_deleted`), or whose game moved to another owner (`token_invalid`). Offline, such a token still verifies
135
+ until it expires (at most an hour). Where it matters, ask the API: `sv.store.getPlayer(claims.sub)` answers
136
+ `player_not_found` for an erased player.
137
+ - **New sign-in methods.** `claims.amr` holds one sign-in method; a method SplatterVault adds after this SDK version is
138
+ accepted too (the signature still proves SplatterVault issued the token), where the API's own list is closed.
139
+
140
+ The keys are cached as the answer's `Cache-Control` says, but at least 60 seconds and at most an hour; while
141
+ SplatterVault cannot be reached, the last keys keep working for `staleIfErrorSeconds` (default 300) after they
142
+ expired, and a failed fetch is not tried again for 10 seconds.
143
+
144
+ ### Grant a store item
145
+
146
+ ```ts
147
+ const result = await sv.store.grant(
148
+ playerId, // a SplatterVault player id, or "steam:7656...", "studio:<your id>", ...
149
+ { lines: [{ sku: "trophy_s3", quantity: 1 }, { currency: "GOLD", amount: 100 }], reason: "Season 3 reward" },
150
+ { idempotencyKey: `season3:${playerId}` } // optional: see "Exactly once" below
151
+ );
152
+ console.log(result.replayed, result.balances);
153
+ ```
154
+
155
+ `consume`, `purchase` (with `expectedPrice`), `updateItem` and `reverse` work the same way.
156
+
157
+ **Exactly once.** Every store change carries an `Idempotency-Key`. By default the SDK makes one per call and sends
158
+ the same one, with the same body, on its own retries, so a lost answer never applies a change twice. To stay
159
+ exactly-once across your own retries and process restarts too, pass a key derived from your own record
160
+ (`reward:${matchId}:${playerId}`): the same key and request again answers the first result with `replayed: true`; the
161
+ same key with a different request is `409 idempotency_conflict`.
162
+
163
+ When a change fails with `err.outcomeUnknown` (no answer, or a 500/502/504, even after the SDK's own retries), it may
164
+ have been applied. Send it again **with the same key** (`{ idempotencyKey: err.idempotencyKey }`, the same body), at
165
+ once or from a "Retry" button: never call `grant` or `purchase` again without the key, which could apply it twice.
166
+
167
+ ### Write player data
168
+
169
+ ```ts
170
+ // Read, then change only what you read (ifVersion): a concurrent change makes it fail with version_conflict.
171
+ const { data } = await sv.playerData.get(42, playerId, { stores: ["readonly"], keys: ["settings"] });
172
+ const settings = data.readonly?.settings;
173
+ await sv.playerData.update(42, playerId, {
174
+ ops: [{ op: "set", store: "readonly", key: "settings", value: { music: false }, ifVersion: settings?.version ?? 0 }]
175
+ });
176
+
177
+ // A counter: no read needed (never sent twice by the SDK; after an unknown outcome you cannot tell if it counted).
178
+ await sv.playerData.update(42, playerId, { ops: [{ op: "inc", store: "readonly", key: "xp", by: 50 }] });
179
+
180
+ // Your game's own data; players read "public" within 30 seconds.
181
+ await sv.playerData.updateGameData(42, { ops: [{ op: "set", store: "public", key: "motd", value: "Season 3 is live" }] });
182
+ ```
183
+
184
+ Stores: a player's `player` (the game client may write it), `readonly` (only your backend writes it) and `internal`
185
+ (players never see it); a game's `public` and `internal`. Writes are all or nothing. `stores` and `keys` may be left
186
+ out (everything) but not empty.
187
+
188
+ **When the answer is lost.** A write that got no answer, a timeout, a 500, 502 or 504 may or may not have been
189
+ applied: the error has `outcomeUnknown: true`, and the SDK does not send it again (even with `ifVersion`: the second
190
+ send could meet the first one's own new version). The same goes for a write the SDK did resend (only ever after a 408,
191
+ 429 or 503, which prove nothing was applied) that then meets `version_conflict`: it is reported as code
192
+ `outcome_unknown`, never as a plain conflict. To recover, read the key again: if its version moved and the value is
193
+ the one you wrote, your write was applied. Never just apply your change again on top. A value that carries its own
194
+ mark makes this easy (see `recordWin` in [examples/rewards.ts](examples/rewards.ts), which keeps the ids of the
195
+ matches it counted).
196
+
197
+ ### Sign players in from your backend
198
+
199
+ Use your own accounts and still give players SplatterVault tokens (store, player data):
200
+
201
+ ```ts
202
+ const { token, expiresAt, player } = await sv.players.signIn({ gameId: 42, externalId: "user-981", displayName: "Nova" });
203
+ // Send token to the game client. The same externalId is always the same player (player.id).
204
+ ```
205
+
206
+ ## Errors
207
+
208
+ Every refusal is a `SplatterVaultError`:
209
+
210
+ ```ts
211
+ import { SplatterVaultError } from "@splattervault/server";
212
+
213
+ try {
214
+ await sv.store.purchase(playerId, { sku: "sword", currency: "GOLD", expectedPrice: 250 });
215
+ } catch (err) {
216
+ if (err instanceof SplatterVaultError) {
217
+ switch (err.code) {
218
+ case "insufficient_funds": /* tell the player */ break;
219
+ case "price_changed": /* show the new price */ break;
220
+ default: throw err;
221
+ }
222
+ }
223
+ }
224
+ ```
225
+
226
+ | Field | What it is |
227
+ |---|---|
228
+ | `code` | The API's stable `error` code (`insufficient_funds`, `version_conflict`, `rate_limited`, `player_not_found`…). **Key your handling on it.** The set is open: handle an unknown code by `status`. Null for the session and billing routes' refusals, which have no code (see `errorName`). SDK codes: `network_error`, `timeout`, `aborted` (status 0); `invalid_response`, `redirect_not_followed`, `outcome_unknown` (with the answer's status). |
229
+ | `status` | The HTTP status; 0 when no answer arrived. |
230
+ | `message` | `"<code> (HTTP <status>): <the API's sentence>"`: for logs, not for parsing. |
231
+ | `details` | More about some refusals, e.g. `version_conflict`: `[{ store, key, version }]`; `limit_exceeded`: `{ limit, max }`; `banned`: `{ type, scopes }`. |
232
+ | `retryAfter` | The answer's `Retry-After`, in seconds, or null. |
233
+ | `requestId` | The answer's `x-request-id`: quote it when you contact support. |
234
+ | `errorName`, `errors` | The session and billing routes' `{ name, errors }` (e.g. `BAD_REQUEST`). |
235
+ | `outcomeUnknown` | True when a write may or may not have been applied (no answer, 500/502/504, an abort mid-send, a resent `ifVersion` write that met a conflict). Always false for reads. |
236
+ | `idempotencyKey` | The `Idempotency-Key` a store change was sent with (yours or the SDK's): send the change again with it to settle an unknown outcome. |
237
+ | `operationId`, `method`, `path`, `attempts`, `body` | What failed, and how many times it was sent. |
238
+
239
+ `err.is("rate_limited")`, `err.isTransient` (408, 429, 500, 502, 503, 504 or no answer) and `err.isNetworkError` help too. Each
240
+ operation's codes are listed in the [Studio API reference](https://splattervault.com/docs/studio).
241
+
242
+ ## Retries, timeouts and cancellation
243
+
244
+ The SDK sends a request again by itself only when that is **safe**, and only after a transient failure: no answer
245
+ (network error or timeout), or HTTP 408, 429, 500, 502, 503 or 504. Never after another 4xx or a redirect.
246
+
247
+ | Retried after any transient failure | Retried only after 408, 429, 503 | Not retried (a repeat could act twice) |
248
+ |---|---|---|
249
+ | Every read (GET) | Player-data writes whose every op has `ifVersion` (see "When the answer is lost") | Creating, stopping, renaming, rescheduling or cancelling a session |
250
+ | Store changes (same `Idempotency-Key` and body each time) | | Claiming a pool server |
251
+ | Lookups (`playerData.resolve`, `playerData.getMany`) and `playerData.clear` | | Player-data writes without `ifVersion` (e.g. `inc`) |
252
+ | Imports (the same rows again change nothing) | | Studio sign-in, erasing a player, the Meta purchase check |
253
+
254
+ A resent store change that meets `409 idempotency_conflict` can only be meeting its own first send still in progress
255
+ (same key, same body), so it is retried too.
256
+
257
+ - Up to `maxRetries` retries (default 2, at most 20), with exponential backoff and jitter (0.5 s, 1 s, … up to 8 s).
258
+ - A `Retry-After` is always honoured, never shortened. One longer than `retry.maxRetryAfterMs` (default 10 s) is not
259
+ waited out: the error is thrown with `retryAfter` set, for you to schedule.
260
+ - `timeoutMs` (default 30 s, 1 ms to 2147483647 ms) bounds each attempt, answer included. Creating or claiming servers
261
+ gets at least 60 s, imports at least 120 s.
262
+ - Numeric options are checked when you set them: NaN, Infinity or out-of-range values throw a `RangeError`.
263
+ - Every method takes options last: `{ signal, timeoutMs, maxRetries, headers }` (and `idempotencyKey` for store
264
+ changes). An aborted `signal` ends the call at once, also during a wait, with code `aborted`.
265
+
266
+ ```ts
267
+ const sv = new SplatterVault({ maxRetries: 3, timeoutMs: 10_000, retry: { maxRetryAfterMs: 30_000 } });
268
+ await sv.billing.getOrgCredits({}, { signal: AbortSignal.timeout(5000) });
269
+ ```
270
+
271
+ ## Pages
272
+
273
+ ```ts
274
+ // A player's store history, newest first, 50 a page.
275
+ for await (const page of sv.store.historyPages(playerId)) {
276
+ for (const txn of page.txns) console.log(txn.kind, txn.createdAt);
277
+ }
278
+
279
+ // Erased players, for deleting what YOUR database keeps about them. Save `next` after each page; poll every few minutes.
280
+ for await (const page of sv.playerData.erasedPlayerPages(savedCursor ? { cursor: savedCursor } : { since: "2026-11-01T00:00:00Z" })) {
281
+ await deleteFromMyDatabase(page.players.map((p) => p.id));
282
+ savedCursor = page.next;
283
+ }
284
+ ```
285
+
286
+ ## On a SplatterVault game server
287
+
288
+ A game process that SplatterVault starts gets a few session variables (never the server's own credentials):
289
+
290
+ ```ts
291
+ import { readSessionEnvironment } from "@splattervault/server";
292
+
293
+ const env = readSessionEnvironment(); // reads process.env
294
+ // { onSplatterVault, sessionId, code, gameType, mode, serverName, friendlyName, buildChannel, slavePort }
295
+ ```
296
+
297
+ On a server of its own (a session you created), `sessionId` is the session's id. On a **pool** server `sessionId` is
298
+ null (the claim does not set it: use the `sessionId` that `serverPools.claim()` answered) and only `code` is the
299
+ claiming match's; `mode`, `serverName` and `friendlyName` are from when the pool server booted.
300
+
301
+ ## API
302
+
303
+ | Namespace | Methods |
304
+ |---|---|
305
+ | `sv.sessions` | `create`, `list`, `get`, `waitUntilReady`, `listMine`, `stop`, `rename`, `reschedule`, `cancelSchedule` |
306
+ | `sv.sessions.subscription` | `create`, `list`, `stop`, `rename`, `reschedule`, `cancelSchedule` (subscription-billed) |
307
+ | `sv.serverPools` | `claim` |
308
+ | `sv.games` | `getConfigurableArgs` |
309
+ | `sv.billing` | `getCredits`, `getCreditStats`, `getOrgCredits`, `getOrgSubscriptions`, `getOrgCreditsById`, `getOrgSubscriptionById`, `getSubscriptions`, `getUsage` |
310
+ | `sv.players` | `signIn`, `import`, `erase` |
311
+ | `sv.playerData` | `resolve`, `get`, `update`, `clear`, `getMany`, `writeMany`, `getGameData`, `updateGameData`, `import`, `listErasedPlayers`, `erasedPlayerPages` |
312
+ | `sv.store` | `getCatalog`, `getPlayer`, `getHistory`, `historyPages`, `grant`, `consume`, `purchase`, `updateItem`, `reverse`, `syncMetaPurchases`, `importCatalog`, `importHoldings` |
313
+ | `sv` | `verifyPlayerToken` |
314
+ | functions | `verifyPlayerToken`, `createPlayerTokenVerifier`, `readSessionEnvironment`, `newIdempotencyKey` |
315
+
316
+ Each method's documentation names its API operation (`@see POST /store/studio/players/{player}/grants`). Request and
317
+ answer types (`ServerSession`, `StoreTxnResult`, `DataOp`, …) are exported, generated from the API's OpenAPI
318
+ description; `Schemas`, `components`, `operations` and `paths` hold all of them.
319
+
320
+ Options of `new SplatterVault(options)`:
321
+
322
+ | Option | Default | |
323
+ |---|---|---|
324
+ | `apiKey` | `process.env.SV_API_KEY` | Your organization API key. |
325
+ | `baseUrl` | `https://splattervault.com/rest` | https only; http for localhost / 127.0.0.1 / [::1]. |
326
+ | `fetch` | `globalThis.fetch` | Any `fetch`-compatible function (proxies, tests). |
327
+ | `maxRetries` | `2` | Retries after the first attempt (safe calls only). |
328
+ | `timeoutMs` | `30000` | Per attempt. |
329
+ | `retry` | `{ baseDelayMs: 500, maxDelayMs: 8000, maxRetryAfterMs: 10000 }` | |
330
+ | `userAgent` | | Prefixed to the SDK's User-Agent. |
331
+ | `dangerouslyAllowBrowser` | `false` | See "Your API key stays on your servers". |
332
+ | `dangerouslyAllowInsecureHttp` | `false` | Allows a plain-http `baseUrl` on another host (the key travels unencrypted). |
333
+
334
+ ### Testing your code
335
+
336
+ Pass a `fetch` to answer requests yourself, and a `baseUrl` to point the SDK at a local server:
337
+
338
+ ```ts
339
+ const sv = new SplatterVault({
340
+ apiKey: "sv_org_test",
341
+ fetch: async (url, init) => new Response(JSON.stringify({ balance: 100 }), { status: 200 })
342
+ });
343
+ ```
344
+
345
+ ## Developing this SDK
346
+
347
+ ```sh
348
+ npm install
349
+ npm run generate # src/generated/studio-api.ts from openapi/studio-api.json (or: npm run generate -- <file or URL>)
350
+ npm run check # typecheck, lint, tests, build, then the packed package from ESM and CJS
351
+ npm run docs # API documentation (HTML) into docs/
352
+ ```
353
+
354
+ Integration tests run against the local API mock in [`tools/sdk-mock`](tools/sdk-mock/README.md) (Node 18+, no
355
+ dependencies, fake test credentials; it never calls SplatterVault) when `SV_MOCK_URL` is set:
356
+
357
+ ```sh
358
+ node tools/sdk-mock/server.mjs --port 8787 & # or, in its own terminal: npm run mock
359
+ SV_MOCK_URL=http://127.0.0.1:8787/rest npm test # every test, including the integration suite
360
+ npm run mock:selftest # the mock's own check against openapi/studio-api.json
361
+ ```
362
+
363
+ ## License
364
+
365
+ [MIT](LICENSE)