@splattervault/server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1594 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+
5
+ // src/core/http.ts
6
+
7
+ // src/operations.ts
8
+ var SLOW = 6e4;
9
+ var IMPORT = 12e4;
10
+ var OPERATIONS = {
11
+ // ── Game-server sessions ───────────────────────────────────────────────────────────────────────────────────────
12
+ "sessions.createCredit": { method: "POST", path: "/credits/sessions", retry: "never", timeoutMs: SLOW },
13
+ "sessions.listCredit": { method: "GET", path: "/credits/sessions", retry: "safe" },
14
+ "sessions.stopCredit": { method: "POST", path: "/credits/sessions/{sessionId}/stop", retry: "never", timeoutMs: SLOW },
15
+ "sessions.renameCredit": { method: "PUT", path: "/credits/sessions/{sessionId}/friendly-name", retry: "never" },
16
+ "sessions.rescheduleCredit": { method: "PUT", path: "/credits/sessions/{sessionId}/schedule", retry: "never" },
17
+ "sessions.cancelScheduledCredit": { method: "POST", path: "/credits/sessions/{sessionId}/cancel-schedule", retry: "never" },
18
+ "sessions.createSubscription": { method: "POST", path: "/subscriptions/sessions", retry: "never", timeoutMs: SLOW },
19
+ "sessions.listSubscription": { method: "GET", path: "/subscriptions/sessions", retry: "safe" },
20
+ "sessions.stopSubscription": { method: "POST", path: "/subscriptions/sessions/{sessionId}/stop", retry: "never", timeoutMs: SLOW },
21
+ "sessions.renameSubscription": { method: "PUT", path: "/subscriptions/sessions/{sessionId}/friendly-name", retry: "never" },
22
+ "sessions.rescheduleSubscription": { method: "PUT", path: "/subscriptions/sessions/{sessionId}/schedule", retry: "never" },
23
+ "sessions.cancelScheduledSubscription": {
24
+ method: "POST",
25
+ path: "/subscriptions/sessions/{sessionId}/cancel-schedule",
26
+ retry: "never"
27
+ },
28
+ "sessions.listMine": { method: "GET", path: "/game-sessions/my-sessions", retry: "safe" },
29
+ "sessions.get": { method: "GET", path: "/game-sessions/{id}", retry: "safe" },
30
+ "games.getConfigurableArgs": { method: "GET", path: "/game-types/{id}/configurable-args", retry: "safe" },
31
+ "serverPools.claim": { method: "POST", path: "/server-pools/{id}/claim", retry: "never", timeoutMs: SLOW },
32
+ // ── Billing ────────────────────────────────────────────────────────────────────────────────────────────────────
33
+ "billing.getCredits": { method: "GET", path: "/credits", retry: "safe" },
34
+ "billing.getCreditStats": { method: "GET", path: "/credits/stats", retry: "safe" },
35
+ "billing.getKeyOrgCredits": { method: "GET", path: "/org/credits", retry: "safe" },
36
+ "billing.getKeyOrgSubscriptions": { method: "GET", path: "/org/subscription", retry: "safe" },
37
+ "billing.getOrgCredits": { method: "GET", path: "/organizations/{orgId}/credits", retry: "safe" },
38
+ "billing.getOrgSubscription": { method: "GET", path: "/organizations/{orgId}/subscription", retry: "safe" },
39
+ "billing.getSubscriptions": { method: "GET", path: "/subscriptions", retry: "safe" },
40
+ "billing.getUsage": { method: "GET", path: "/subscriptions/usage", retry: "safe" },
41
+ // ── Player sign-in (studio backend) ────────────────────────────────────────────────────────────────────────────
42
+ "playerAuth.studio.signIn": { method: "POST", path: "/player-auth/studio", retry: "never" },
43
+ // "running the same rows again changes nothing"; 503 import_busy: "send the same batch again".
44
+ "playerAuth.studio.importPlayers": { method: "POST", path: "/player-auth/studio/import", retry: "safe", timeoutMs: IMPORT },
45
+ "playerAuth.studio.erasePlayer": { method: "DELETE", path: "/player-auth/studio/players/{playerId}", retry: "never" },
46
+ // ── Player data (studio backend) ───────────────────────────────────────────────────────────────────────────────
47
+ // "A lookup only: nobody is created."
48
+ "studioData.resolvePlayers": { method: "POST", path: "/studio-data/games/{gameId}/players/resolve", retry: "safe", read: true },
49
+ "studioData.getPlayerData": { method: "GET", path: "/studio-data/games/{gameId}/players/{playerId}/data", retry: "safe" },
50
+ "studioData.updatePlayerData": { method: "PATCH", path: "/studio-data/games/{gameId}/players/{playerId}/data", retry: "if-version" },
51
+ // 204 "Deleted (or there was nothing)".
52
+ "studioData.clearPlayerData": { method: "DELETE", path: "/studio-data/games/{gameId}/players/{playerId}/data", retry: "safe" },
53
+ "studioData.getPlayersData": { method: "POST", path: "/studio-data/games/{gameId}/data/get", retry: "safe", read: true },
54
+ "studioData.writePlayersData": { method: "POST", path: "/studio-data/games/{gameId}/data/write", retry: "if-version" },
55
+ "studioData.getGameData": { method: "GET", path: "/studio-data/games/{gameId}/game-data", retry: "safe" },
56
+ "studioData.updateGameData": { method: "PATCH", path: "/studio-data/games/{gameId}/game-data", retry: "if-version" },
57
+ // "Re-sending the same rows changes nothing."
58
+ "studioData.importData": { method: "POST", path: "/studio-data/games/{gameId}/import", retry: "safe", timeoutMs: IMPORT },
59
+ "studioData.listErasedPlayers": { method: "GET", path: "/studio-data/erased-players", retry: "safe" },
60
+ // ── Store (studio backend) ─────────────────────────────────────────────────────────────────────────────────────
61
+ "store.studio.getCatalog": { method: "GET", path: "/store/studio/catalog", retry: "safe" },
62
+ "store.studio.getPlayer": { method: "GET", path: "/store/studio/players/{player}", retry: "safe" },
63
+ "store.studio.getPlayerHistory": { method: "GET", path: "/store/studio/players/{player}/history", retry: "safe" },
64
+ "store.studio.grant": { method: "POST", path: "/store/studio/players/{player}/grants", retry: "idempotency-key" },
65
+ "store.studio.consume": { method: "POST", path: "/store/studio/players/{player}/consume", retry: "idempotency-key" },
66
+ "store.studio.purchase": { method: "POST", path: "/store/studio/players/{player}/purchases", retry: "idempotency-key" },
67
+ "store.studio.updateItem": { method: "PATCH", path: "/store/studio/players/{player}/items/{instanceId}", retry: "idempotency-key" },
68
+ "store.studio.reverse": { method: "POST", path: "/store/studio/players/{player}/reversals", retry: "idempotency-key" },
69
+ "store.studio.syncMetaPurchases": { method: "POST", path: "/store/studio/players/{player}/platform-purchases/meta", retry: "never" },
70
+ // "re-running a file changes nothing" (catalog); holdings: "the same row again is unchanged" (once per source).
71
+ "store.studio.importCatalog": { method: "POST", path: "/store/studio/imports/catalog", retry: "safe", timeoutMs: IMPORT },
72
+ "store.studio.importHoldings": { method: "POST", path: "/store/studio/imports/holdings", retry: "safe", timeoutMs: IMPORT }
73
+ };
74
+
75
+ // src/core/errors.ts
76
+ var SDK_ERROR_CODES = {
77
+ /** No answer: no connection, a reset, a DNS or TLS failure. The request may or may not have arrived. */
78
+ networkError: "network_error",
79
+ /** No answer within `timeoutMs`. The request may or may not have arrived. */
80
+ timeout: "timeout",
81
+ /** Your `signal` aborted the call. */
82
+ aborted: "aborted",
83
+ /** The answer was not the JSON the SDK expected (the HTTP status is kept). */
84
+ invalidResponse: "invalid_response",
85
+ /**
86
+ * The API answered a redirect (3xx). The SDK never follows one, so your API key never travels to another address;
87
+ * `details.location` says where it pointed. Check `baseUrl` (it must be the https URL the API is served at).
88
+ */
89
+ redirectNotFollowed: "redirect_not_followed",
90
+ /**
91
+ * A player-data write with `ifVersion` was sent again after an answer that proved it was not applied, and the second
92
+ * send met `version_conflict`: the first may have been applied after all (`outcomeUnknown` is true). Re-read.
93
+ */
94
+ outcomeUnknown: "outcome_unknown"
95
+ };
96
+ var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
97
+ var NOT_APPLIED_STATUSES = /* @__PURE__ */ new Set([408, 429, 503]);
98
+ var OUTCOME_UNKNOWN_STATUSES = /* @__PURE__ */ new Set([500, 502, 504]);
99
+ var SplatterVaultError = class _SplatterVaultError extends Error {
100
+ name = "SplatterVaultError";
101
+ /** The HTTP status; 0 when no answer arrived (network error, timeout, abort). */
102
+ status;
103
+ /** The API's `error` code, an SDK code ({@link SDK_ERROR_CODES}), or null when the answer had none. */
104
+ code;
105
+ /** The answer's `details` (e.g. the current versions of a `version_conflict`), or undefined. */
106
+ details;
107
+ /** The answer's `Retry-After`, in seconds: do not send this request again sooner. Null when absent. */
108
+ retryAfter;
109
+ /** The answer's `x-request-id` (quote it when you contact SplatterVault support). Null when absent. */
110
+ requestId;
111
+ /** The session and billing routes' `name` (e.g. `NOT_FOUND`), or null. */
112
+ errorName;
113
+ /** The session and billing routes' validation `errors`, or null. */
114
+ errors;
115
+ /** The parsed answer body, as received (never holds your API key). */
116
+ body;
117
+ /** The API operation that failed, e.g. `store.studio.grant`. */
118
+ operationId;
119
+ /** The HTTP method of the failed request. */
120
+ method;
121
+ /** The request path (below the base URL, without the query). */
122
+ path;
123
+ /** How many times the request was sent, retries included (0 when it never left). */
124
+ attempts;
125
+ /**
126
+ * True when this write may or may not have been applied: no answer, a 500, 502 or 504 (on any attempt), an abort
127
+ * while a send was under way, or a resent player-data write that met `version_conflict` (code `outcome_unknown`).
128
+ * Always false for reads.
129
+ */
130
+ outcomeUnknown;
131
+ /**
132
+ * The `Idempotency-Key` the store change was sent with (yours or the one the SDK made), or null for other
133
+ * operations. To resolve an unknown outcome, send the same change again with `{ idempotencyKey: err.idempotencyKey }`.
134
+ */
135
+ idempotencyKey;
136
+ constructor(init) {
137
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
138
+ this.status = init.status;
139
+ this.code = init.code;
140
+ this.details = init.details;
141
+ this.retryAfter = init.retryAfter ?? null;
142
+ this.requestId = init.requestId ?? null;
143
+ this.errorName = init.errorName ?? null;
144
+ this.errors = init.errors ?? null;
145
+ this.body = init.body;
146
+ this.operationId = init.operationId;
147
+ this.method = init.method;
148
+ this.path = init.path;
149
+ this.attempts = init.attempts ?? 0;
150
+ this.outcomeUnknown = init.outcomeUnknown ?? false;
151
+ this.idempotencyKey = init.idempotencyKey ?? null;
152
+ }
153
+ /** True when {@link SplatterVaultError.code | code} is `code`. */
154
+ is(code) {
155
+ return this.code === code;
156
+ }
157
+ /** No answer arrived (a network error or a timeout): the request may or may not have been applied. */
158
+ get isNetworkError() {
159
+ return this.status === 0 && (this.code === SDK_ERROR_CODES.networkError || this.code === SDK_ERROR_CODES.timeout);
160
+ }
161
+ /**
162
+ * The same request may succeed later: no answer arrived, or the API answered 408, 429, 500, 502, 503 or 504. Whether
163
+ * the SDK sent it again by itself depends on the operation (see the README's retry rules).
164
+ */
165
+ get isTransient() {
166
+ return this.isNetworkError || TRANSIENT_STATUSES.has(this.status);
167
+ }
168
+ /** @internal The same error with other fields (the SDK's final touches: attempts, outcome, key). */
169
+ with(changes) {
170
+ return new _SplatterVaultError({
171
+ status: this.status,
172
+ code: this.code,
173
+ message: this.message,
174
+ operationId: this.operationId,
175
+ method: this.method,
176
+ path: this.path,
177
+ details: this.details,
178
+ retryAfter: this.retryAfter,
179
+ requestId: this.requestId,
180
+ errorName: this.errorName,
181
+ errors: this.errors,
182
+ body: this.body,
183
+ attempts: this.attempts,
184
+ outcomeUnknown: this.outcomeUnknown,
185
+ idempotencyKey: this.idempotencyKey,
186
+ cause: this.cause,
187
+ ...changes
188
+ });
189
+ }
190
+ };
191
+ function parseRetryAfter(header, nowMs = Date.now()) {
192
+ if (header == null) return null;
193
+ const text2 = header.trim();
194
+ if (text2 === "") return null;
195
+ if (/^\d+$/.test(text2)) return Math.min(Number(text2), 86400);
196
+ if (!/[a-z]{3}/i.test(text2)) return null;
197
+ const at = Date.parse(text2);
198
+ if (Number.isNaN(at)) return null;
199
+ return Math.max(0, (at - nowMs) / 1e3);
200
+ }
201
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
202
+ function readErrorBody(body) {
203
+ const out = { code: null, message: null, details: void 0, errorName: null, errors: null };
204
+ if (!isRecord(body)) return out;
205
+ if (typeof body.error === "string") out.code = body.error;
206
+ if (typeof body.message === "string") out.message = body.message;
207
+ if (body.details !== void 0 && body.details !== null) out.details = body.details;
208
+ if (out.code === null) {
209
+ if (body.banned === true) {
210
+ out.code = "banned";
211
+ if (typeof body.reason === "string") out.message = body.reason;
212
+ out.details = { type: body.type, scopes: body.scopes };
213
+ } else {
214
+ if (typeof body.name === "string") out.errorName = body.name;
215
+ if (Array.isArray(body.errors)) out.errors = body.errors;
216
+ }
217
+ }
218
+ return out;
219
+ }
220
+
221
+ // src/core/retry.ts
222
+ var DEFAULT_RETRY = {
223
+ maxRetries: 2,
224
+ baseDelayMs: 500,
225
+ maxDelayMs: 8e3,
226
+ maxRetryAfterMs: 1e4
227
+ };
228
+ function backoffMs(retry, settings, random = Math.random) {
229
+ const exp = settings.baseDelayMs * 2 ** Math.max(0, retry - 1);
230
+ const capped = Math.min(exp, settings.maxDelayMs);
231
+ return capped / 2 + capped / 2 * random();
232
+ }
233
+ function retryDelay(error, retry, settings, random, transient = error.isTransient) {
234
+ if (retry > settings.maxRetries || !transient) return null;
235
+ if (error.retryAfter !== null) {
236
+ const ms = error.retryAfter * 1e3;
237
+ return ms > settings.maxRetryAfterMs ? null : ms;
238
+ }
239
+ return backoffMs(retry, settings, random);
240
+ }
241
+
242
+ // src/core/validate.ts
243
+ var MAX_TIMER_MS = 2147483647;
244
+ function numberInRange(value, name, min, max) {
245
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
246
+ throw new RangeError(`${name} must be a finite number from ${min} to ${max} (got ${String(value)})`);
247
+ }
248
+ return value;
249
+ }
250
+ function intInRange(value, name, min, max) {
251
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) {
252
+ throw new RangeError(`${name} must be a whole number from ${min} to ${max} (got ${String(value)})`);
253
+ }
254
+ return value;
255
+ }
256
+ function isLoopbackHost(hostname) {
257
+ const h = hostname.toLowerCase();
258
+ return h === "localhost" || h === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
259
+ }
260
+ function checkServiceUrl(value, name, allowInsecureHttp) {
261
+ if (typeof value !== "string") throw new TypeError(`${name} must be a URL string`);
262
+ let url;
263
+ try {
264
+ url = new URL(value);
265
+ } catch {
266
+ throw new TypeError(`${name} must be an absolute https URL`);
267
+ }
268
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new TypeError(`${name} must be an absolute https URL`);
269
+ if (url.username || url.password) throw new TypeError(`${name} must not hold a user name or password`);
270
+ if (url.search || url.hash) throw new TypeError(`${name} must not have a query or a fragment`);
271
+ if (url.protocol === "http:" && !isLoopbackHost(url.hostname) && !allowInsecureHttp) {
272
+ throw new TypeError(
273
+ `${name} must use https: plain http is allowed only for loopback hosts (localhost, 127.0.0.1, [::1]), or with { dangerouslyAllowInsecureHttp: true } for a development server you trust`
274
+ );
275
+ }
276
+ return value.replace(/\/+$/, "");
277
+ }
278
+
279
+ // src/core/http.ts
280
+ var MAX_RETRIES = 20;
281
+ var IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{1,128}$/;
282
+ function newIdempotencyKey() {
283
+ return crypto.randomUUID();
284
+ }
285
+ var MANAGED_HEADERS = /* @__PURE__ */ new Set(["x-api-key", "idempotency-key", "content-type", "accept"]);
286
+ function fillPath(template, params = {}) {
287
+ return template.replace(/\{([^}]+)\}/g, (_m, name) => {
288
+ const value = params[name];
289
+ if (value === void 0 || value === null || value === "") throw new TypeError(`${name} is required`);
290
+ if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number`);
291
+ const text2 = String(value);
292
+ if (text2 === "." || text2 === "..") throw new TypeError(`${name} must not be "${text2}"`);
293
+ return encodeURIComponent(text2);
294
+ });
295
+ }
296
+ function queryString(query = {}) {
297
+ const params = new URLSearchParams();
298
+ for (const [key, value] of Object.entries(query)) {
299
+ if (value === void 0 || value === null) continue;
300
+ params.append(key, Array.isArray(value) ? value.map(String).join(",") : String(value));
301
+ }
302
+ const text2 = params.toString();
303
+ return text2 ? `?${text2}` : "";
304
+ }
305
+ function abortReason(signal) {
306
+ return signal.reason;
307
+ }
308
+ function sleep(ms, signal) {
309
+ return new Promise((resolve, reject) => {
310
+ if (signal?.aborted) {
311
+ reject(abortReason(signal));
312
+ return;
313
+ }
314
+ const onAbort = () => {
315
+ clearTimeout(timer);
316
+ reject(abortReason(signal));
317
+ };
318
+ const timer = setTimeout(() => {
319
+ signal?.removeEventListener("abort", onAbort);
320
+ resolve();
321
+ }, ms);
322
+ signal?.addEventListener("abort", onAbort, { once: true });
323
+ });
324
+ }
325
+ var AttemptTimeout = class extends Error {
326
+ constructor() {
327
+ super("timeout");
328
+ }
329
+ };
330
+ var HttpClient = class {
331
+ // An ES private field: the API key never shows in console.log, util.inspect or JSON.stringify of a client.
332
+ #config;
333
+ constructor(config) {
334
+ this.#config = config;
335
+ }
336
+ get baseUrl() {
337
+ return this.#config.baseUrl;
338
+ }
339
+ get fetchFn() {
340
+ return this.#config.fetch;
341
+ }
342
+ get defaultTimeoutMs() {
343
+ return this.#config.timeoutMs;
344
+ }
345
+ async call(operationId, input = {}) {
346
+ const op = OPERATIONS[operationId];
347
+ const options = input.options ?? {};
348
+ const path = fillPath(op.path, input.path);
349
+ const url = `${this.#config.baseUrl}${path}${queryString(input.query)}`;
350
+ const headers = {};
351
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
352
+ if (!MANAGED_HEADERS.has(name.toLowerCase())) headers[name] = value;
353
+ }
354
+ const names = Object.keys(headers).map((n) => n.toLowerCase());
355
+ if (names.includes("if-none-match") && !names.includes("cache-control")) headers["Cache-Control"] = "max-age=0";
356
+ headers["Accept"] = "application/json";
357
+ headers["User-Agent"] = this.#config.userAgent;
358
+ headers["X-API-Key"] = this.#config.apiKey;
359
+ let body;
360
+ if (input.body !== void 0) {
361
+ headers["Content-Type"] = "application/json";
362
+ body = JSON.stringify(input.body);
363
+ }
364
+ if (op.retry === "idempotency-key") {
365
+ const key = options.idempotencyKey ?? newIdempotencyKey();
366
+ if (typeof key !== "string" || !IDEMPOTENCY_KEY_RE.test(key)) {
367
+ throw new TypeError("idempotencyKey must be 1-128 visible ASCII characters");
368
+ }
369
+ headers["Idempotency-Key"] = key;
370
+ } else if (options.idempotencyKey != null) {
371
+ throw new TypeError(`${operationId} takes no idempotencyKey`);
372
+ }
373
+ const conditional2 = op.retry === "if-version" && input.conditional === true;
374
+ const retryable = op.retry === "safe" || op.retry === "idempotency-key" || conditional2;
375
+ const maxRetries = options.maxRetries === void 0 ? this.#config.retry.maxRetries : intInRange(options.maxRetries, "maxRetries", 0, MAX_RETRIES);
376
+ const settings = { ...this.#config.retry, maxRetries: retryable ? maxRetries : 0 };
377
+ const timeoutMs = options.timeoutMs !== void 0 ? intInRange(options.timeoutMs, "timeoutMs", 1, MAX_TIMER_MS) : "timeoutMs" in op ? Math.max(op.timeoutMs, this.#config.timeoutMs) : this.#config.timeoutMs;
378
+ const signal = options.signal;
379
+ const write = op.method !== "GET" && !("read" in op);
380
+ const meta = { operationId, method: op.method, path, idempotencyKey: headers["Idempotency-Key"] ?? null };
381
+ let unknownSoFar = false;
382
+ for (let attempt = 1; ; attempt++) {
383
+ if (signal?.aborted) throw this.abortedError(meta, attempt - 1, abortReason(signal), write && unknownSoFar);
384
+ let error;
385
+ try {
386
+ const answer = await this.send(url, { method: op.method, headers, body, redirect: "manual" }, timeoutMs, signal);
387
+ if (answer.status >= 200 && answer.status < 300) return this.parseSuccess(answer, meta, attempt);
388
+ if (answer.status >= 300 && answer.status < 400 && answer.status !== 304) {
389
+ throw this.redirectError(answer, meta, attempt, write && unknownSoFar);
390
+ }
391
+ error = this.errorFromAnswer(answer, meta, attempt);
392
+ } catch (err) {
393
+ if (err instanceof SplatterVaultError) throw err;
394
+ if (signal?.aborted) throw this.abortedError(meta, attempt, abortReason(signal), write);
395
+ error = err instanceof AttemptTimeout ? new SplatterVaultError({
396
+ ...meta,
397
+ status: 0,
398
+ code: SDK_ERROR_CODES.timeout,
399
+ message: `timeout: no answer from SplatterVault within ${timeoutMs} ms`,
400
+ attempts: attempt
401
+ }) : new SplatterVaultError({
402
+ ...meta,
403
+ status: 0,
404
+ code: SDK_ERROR_CODES.networkError,
405
+ message: `network_error: no answer from SplatterVault (${err instanceof Error ? err.message : String(err)})`,
406
+ attempts: attempt,
407
+ cause: err
408
+ });
409
+ }
410
+ if (write && (error.isNetworkError || OUTCOME_UNKNOWN_STATUSES.has(error.status))) unknownSoFar = true;
411
+ const resentConflict = attempt > 1 && error.status === 409;
412
+ if (conditional2 && resentConflict && error.code === "version_conflict") {
413
+ throw error.with({
414
+ code: SDK_ERROR_CODES.outcomeUnknown,
415
+ 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.`,
416
+ outcomeUnknown: true
417
+ });
418
+ }
419
+ const inProgress = op.retry === "idempotency-key" && resentConflict && error.code === "idempotency_conflict";
420
+ let transient = error.isTransient || inProgress;
421
+ if (conditional2 && !NOT_APPLIED_STATUSES.has(error.status)) transient = false;
422
+ const delay = retryDelay(error, attempt, settings, void 0, transient);
423
+ if (delay === null) throw error.with({ outcomeUnknown: write && (unknownSoFar || inProgress) });
424
+ try {
425
+ await sleep(delay, signal);
426
+ } catch (reason) {
427
+ throw this.abortedError(meta, attempt, reason, write && unknownSoFar);
428
+ }
429
+ }
430
+ }
431
+ /** One attempt: the answer with its whole body, within `timeoutMs`. Throws AttemptTimeout or the fetch error. */
432
+ async send(url, init, timeoutMs, signal) {
433
+ const controller = new AbortController();
434
+ let timedOut = false;
435
+ const timer = setTimeout(() => {
436
+ timedOut = true;
437
+ controller.abort(new AttemptTimeout());
438
+ }, timeoutMs);
439
+ const onAbort = () => controller.abort(abortReason(signal));
440
+ signal?.addEventListener("abort", onAbort, { once: true });
441
+ try {
442
+ const res = await this.#config.fetch(url, { ...init, signal: controller.signal });
443
+ const text2 = await res.text();
444
+ return { status: res.status, headers: res.headers, text: text2 };
445
+ } catch (err) {
446
+ if (timedOut) throw new AttemptTimeout();
447
+ throw err;
448
+ } finally {
449
+ clearTimeout(timer);
450
+ signal?.removeEventListener("abort", onAbort);
451
+ }
452
+ }
453
+ parseSuccess(answer, meta, attempt) {
454
+ if (answer.status === 204 || answer.text.trim() === "") return void 0;
455
+ try {
456
+ return JSON.parse(answer.text);
457
+ } catch (err) {
458
+ throw new SplatterVaultError({
459
+ ...meta,
460
+ status: answer.status,
461
+ code: SDK_ERROR_CODES.invalidResponse,
462
+ message: `invalid_response: the answer (HTTP ${answer.status}) is not JSON`,
463
+ requestId: answer.headers.get("x-request-id"),
464
+ attempts: attempt,
465
+ cause: err
466
+ });
467
+ }
468
+ }
469
+ errorFromAnswer(answer, meta, attempt) {
470
+ let parsed;
471
+ if (answer.text.trim() !== "") {
472
+ try {
473
+ parsed = JSON.parse(answer.text);
474
+ } catch {
475
+ parsed = void 0;
476
+ }
477
+ }
478
+ const read = readErrorBody(parsed);
479
+ const label = read.code ?? read.errorName ?? `HTTP ${answer.status}`;
480
+ const sentence = read.message ?? `SplatterVault answered HTTP ${answer.status}`;
481
+ return new SplatterVaultError({
482
+ ...meta,
483
+ status: answer.status,
484
+ code: read.code,
485
+ message: `${label} (HTTP ${answer.status}): ${sentence}`,
486
+ details: read.details,
487
+ retryAfter: parseRetryAfter(answer.headers.get("retry-after")),
488
+ requestId: answer.headers.get("x-request-id"),
489
+ errorName: read.errorName,
490
+ errors: read.errors,
491
+ body: parsed,
492
+ attempts: attempt
493
+ });
494
+ }
495
+ abortedError(meta, attempts, reason, outcomeUnknown) {
496
+ return new SplatterVaultError({
497
+ ...meta,
498
+ status: 0,
499
+ code: SDK_ERROR_CODES.aborted,
500
+ message: "aborted: the call was aborted by its signal",
501
+ attempts,
502
+ outcomeUnknown,
503
+ cause: reason
504
+ });
505
+ }
506
+ redirectError(answer, meta, attempt, outcomeUnknown) {
507
+ const location = answer.headers.get("location");
508
+ return new SplatterVaultError({
509
+ ...meta,
510
+ status: answer.status,
511
+ code: SDK_ERROR_CODES.redirectNotFollowed,
512
+ message: `redirect_not_followed (HTTP ${answer.status}): SplatterVault answered a redirect, which the SDK never follows (check baseUrl)`,
513
+ details: { location },
514
+ requestId: answer.headers.get("x-request-id"),
515
+ attempts: attempt,
516
+ outcomeUnknown
517
+ });
518
+ }
519
+ };
520
+
521
+ // src/version.ts
522
+ var SDK_VERSION = "0.1.1";
523
+ var KID_RE = /^[0-9a-f]{16}$/;
524
+ var MIN_KEYS_LIFETIME_MS = 6e4;
525
+ var MAX_KEYS_LIFETIME_MS = 36e5;
526
+ var X_RE = /^[A-Za-z0-9_-]{43}$/;
527
+ function importJwks(jwks) {
528
+ const keys = /* @__PURE__ */ new Map();
529
+ const list = jwks?.keys;
530
+ if (!Array.isArray(list)) throw new Error("not a JWKS: no keys array");
531
+ for (const jwk of list) {
532
+ if (!jwk || typeof jwk !== "object") continue;
533
+ const k = jwk;
534
+ if (k.kty !== "OKP" || k.crv !== "Ed25519") continue;
535
+ if (k.alg !== void 0 && k.alg !== "EdDSA") continue;
536
+ if (k.use !== void 0 && k.use !== "sig") continue;
537
+ if (typeof k.kid !== "string" || !KID_RE.test(k.kid)) continue;
538
+ if (typeof k.x !== "string" || !X_RE.test(k.x)) continue;
539
+ const raw = Buffer.from(k.x, "base64url");
540
+ if (raw.length !== 32 || raw.toString("base64url") !== k.x) continue;
541
+ try {
542
+ keys.set(k.kid, crypto.createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: k.x }, format: "jwk" }));
543
+ } catch {
544
+ }
545
+ }
546
+ return keys;
547
+ }
548
+ function freshnessMs(cacheControl, age, fallbackMs) {
549
+ if (cacheControl === null || cacheControl.trim() === "") return fallbackMs;
550
+ const directives = cacheControl.toLowerCase().split(",").map((d) => d.trim());
551
+ if (directives.some((d) => d === "no-store" || d === "no-cache" || d.startsWith("no-cache="))) return 0;
552
+ const maxAge = directives.find((d) => d.startsWith("max-age="));
553
+ if (!maxAge) return fallbackMs;
554
+ const seconds = Number(maxAge.slice("max-age=".length).replace(/^"|"$/g, ""));
555
+ if (!Number.isFinite(seconds) || seconds < 0) return 0;
556
+ const ageSeconds = age !== null && /^\d+$/.test(age.trim()) ? Number(age.trim()) : 0;
557
+ return Math.max(0, seconds - ageSeconds) * 1e3;
558
+ }
559
+ var JwksFetchError = class extends Error {
560
+ constructor(message, options) {
561
+ super(message, options);
562
+ this.name = "JwksFetchError";
563
+ }
564
+ };
565
+ var JwksCache = class {
566
+ constructor(options) {
567
+ this.options = options;
568
+ }
569
+ options;
570
+ cached = null;
571
+ inflight = null;
572
+ lastFetchStart = Number.NEGATIVE_INFINITY;
573
+ lastFailure = Number.NEGATIVE_INFINITY;
574
+ /** The key of `kid`, or null when the (refreshed) set has none. Throws JwksFetchError when no usable set exists. */
575
+ async keyFor(kid) {
576
+ const now = this.options.now();
577
+ const cached = this.cached;
578
+ if (cached && now < cached.freshUntil) {
579
+ const key = cached.keys.get(kid);
580
+ if (key) return key;
581
+ if (now - this.lastFetchStart < this.options.minRefetchIntervalMs) return null;
582
+ return (await this.refresh()).keys.get(kid) ?? null;
583
+ }
584
+ if (now - this.lastFailure < this.options.minRefetchIntervalMs) {
585
+ if (cached && now < cached.staleUntil) return cached.keys.get(kid) ?? null;
586
+ throw new JwksFetchError("the player token keys could not be fetched a moment ago; not trying again yet");
587
+ }
588
+ try {
589
+ return (await this.refresh()).keys.get(kid) ?? null;
590
+ } catch (err) {
591
+ this.lastFailure = this.options.now();
592
+ const stale = this.cached;
593
+ if (stale && this.lastFailure < stale.staleUntil) return stale.keys.get(kid) ?? null;
594
+ throw err;
595
+ }
596
+ }
597
+ /** Fetches the set now (joining a fetch already under way). */
598
+ refresh() {
599
+ if (this.inflight) return this.inflight;
600
+ this.lastFetchStart = this.options.now();
601
+ const p = this.fetchSet().finally(() => {
602
+ if (this.inflight === p) this.inflight = null;
603
+ });
604
+ this.inflight = p;
605
+ return p;
606
+ }
607
+ async fetchSet() {
608
+ const controller = new AbortController();
609
+ const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);
610
+ let res;
611
+ let text2;
612
+ try {
613
+ res = await this.options.fetch(this.options.url, {
614
+ method: "GET",
615
+ headers: { Accept: "application/json", "Cache-Control": "no-cache", "User-Agent": this.options.userAgent },
616
+ // Never followed: keys from wherever a redirect points would be trusted to sign player tokens.
617
+ redirect: "manual",
618
+ signal: controller.signal
619
+ });
620
+ text2 = await res.text();
621
+ } catch (err) {
622
+ throw new JwksFetchError(`could not fetch the player token keys: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
623
+ } finally {
624
+ clearTimeout(timer);
625
+ }
626
+ if (res.status !== 200) {
627
+ let code = "";
628
+ try {
629
+ const body = JSON.parse(text2);
630
+ if (typeof body?.error === "string") code = ` ${body.error}`;
631
+ } catch {
632
+ }
633
+ const redirect = res.status >= 300 && res.status < 400 ? " (a redirect, which is never followed)" : "";
634
+ throw new JwksFetchError(`the player token keys answered HTTP ${res.status}${code}${redirect}`);
635
+ }
636
+ let keys;
637
+ try {
638
+ keys = importJwks(JSON.parse(text2));
639
+ } catch (err) {
640
+ throw new JwksFetchError("the player token keys answer is not a JWKS", { cause: err });
641
+ }
642
+ const fetchedAt = this.options.now();
643
+ const floor = Math.max(this.options.minRefetchIntervalMs, MIN_KEYS_LIFETIME_MS);
644
+ const named = freshnessMs(res.headers.get("cache-control"), res.headers.get("age"), this.options.fallbackMaxAgeMs);
645
+ const lifetime = Math.min(Math.max(named, floor), MAX_KEYS_LIFETIME_MS);
646
+ const set = { keys, freshUntil: fetchedAt + lifetime, staleUntil: fetchedAt + lifetime + this.options.staleIfErrorMs };
647
+ this.cached = set;
648
+ return set;
649
+ }
650
+ };
651
+
652
+ // src/playerToken/verify.ts
653
+ var DEFAULT_BASE_URL = "https://splattervault.com/rest";
654
+ var PLAYER_TOKEN_ISSUER = "splattervault";
655
+ var PLAYER_TOKEN_AUDIENCE_PREFIX = "sv-player:";
656
+ var PLAYER_TOKEN_MAX_LIFETIME_SECONDS = 3600;
657
+ var PLAYER_TOKEN_CLOCK_SKEW_SECONDS = 30;
658
+ var PLAYER_TOKEN_MAX_BYTES = 2048;
659
+ var DEFAULT_STALE_IF_ERROR_SECONDS = 300;
660
+ var KID_RE2 = /^[0-9a-f]{16}$/;
661
+ var B64URL_RE = /^[A-Za-z0-9_-]+$/;
662
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
663
+ var JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;
664
+ var SCOPE_RE = /^(org|game):([1-9][0-9]{0,9})$/;
665
+ var APP_ID_RE = /^[\x21-\x7e]{1,64}$/;
666
+ var PROVIDER_RE = /^[a-z][a-z0-9_-]{0,31}$/;
667
+ var MAX_INT32 = 2147483647;
668
+ var MAX_GAME_KEY = 255;
669
+ var PlayerTokenError = class extends Error {
670
+ constructor(code, reason, message, options) {
671
+ super(message, options);
672
+ this.code = code;
673
+ this.reason = reason;
674
+ }
675
+ code;
676
+ reason;
677
+ name = "PlayerTokenError";
678
+ };
679
+ function decodeJsonPart(part) {
680
+ try {
681
+ const value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
682
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
683
+ } catch {
684
+ return null;
685
+ }
686
+ }
687
+ var positiveInt32 = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0 && v <= MAX_INT32;
688
+ function claimsProblem(c) {
689
+ if (typeof c.sub !== "string" || !UUID_RE.test(c.sub)) return "sub";
690
+ if (typeof c.scope !== "string" || !SCOPE_RE.test(c.scope) || Number(c.scope.split(":")[1]) > MAX_INT32) return "scope";
691
+ if (!positiveInt32(c.game)) return "game";
692
+ if (typeof c.gk !== "string" || c.gk.length > MAX_GAME_KEY) return "gk";
693
+ if (c.org !== null && !positiveInt32(c.org)) return "org";
694
+ const [kind, id] = c.scope.split(":");
695
+ if (kind === "org" ? c.org !== Number(id) : c.org !== null || c.game !== Number(id)) return "scope/org/game";
696
+ if (!Array.isArray(c.amr) || c.amr.length !== 1 || typeof c.amr[0] !== "string" || !PROVIDER_RE.test(c.amr[0])) return "amr";
697
+ if (c.app !== void 0 && (c.amr[0] === "studio" || typeof c.app !== "string" || !APP_ID_RE.test(c.app))) return "app";
698
+ return null;
699
+ }
700
+ function gameList(gameId) {
701
+ const list = gameId === void 0 ? [] : typeof gameId === "number" ? [gameId] : gameId;
702
+ if (list.length === 0) throw new TypeError("gameId is required: the game (or games) whose player tokens to accept");
703
+ for (const g of list) if (!positiveInt32(g)) throw new TypeError("gameId must be a positive integer game id");
704
+ return list;
705
+ }
706
+ var invalid = (reason, message) => new PlayerTokenError("token_invalid", reason, message);
707
+ var PlayerTokenVerifier = class {
708
+ cache;
709
+ fixedKeys;
710
+ gameId;
711
+ skew;
712
+ maxLifetime;
713
+ now;
714
+ constructor(options = {}) {
715
+ this.gameId = options.gameId;
716
+ if (options.gameId !== void 0) gameList(options.gameId);
717
+ this.skew = numberInRange(options.clockToleranceSeconds ?? PLAYER_TOKEN_CLOCK_SKEW_SECONDS, "clockToleranceSeconds", 0, 300);
718
+ this.maxLifetime = intInRange(options.maxLifetimeSeconds ?? PLAYER_TOKEN_MAX_LIFETIME_SECONDS, "maxLifetimeSeconds", 1, 3600);
719
+ if (options.now !== void 0 && typeof options.now !== "function") throw new TypeError("now must be a function");
720
+ this.now = options.now ?? Date.now;
721
+ const timeoutMs = intInRange(options.timeoutMs ?? 1e4, "timeoutMs", 1, MAX_TIMER_MS);
722
+ const minRefetchIntervalMs = intInRange(options.minRefetchIntervalMs ?? 1e4, "minRefetchIntervalMs", 0, 36e5);
723
+ const staleIfErrorSeconds = numberInRange(options.staleIfErrorSeconds ?? DEFAULT_STALE_IF_ERROR_SECONDS, "staleIfErrorSeconds", 0, 3600);
724
+ if (options.keys) {
725
+ this.fixedKeys = importJwks(options.keys);
726
+ this.cache = null;
727
+ return;
728
+ }
729
+ const fetchFn = options.fetch ?? globalThis.fetch;
730
+ if (typeof fetchFn !== "function") throw new TypeError("no fetch: use Node.js 18 or later, or pass { fetch }");
731
+ const insecure = options.dangerouslyAllowInsecureHttp === true;
732
+ const url = options.jwksUrl !== void 0 ? checkServiceUrl(options.jwksUrl, "jwksUrl", insecure) : `${checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, "baseUrl", insecure)}/player-auth/keys`;
733
+ this.fixedKeys = null;
734
+ this.cache = new JwksCache({
735
+ url,
736
+ fetch: fetchFn,
737
+ userAgent: options.userAgent ?? `@splattervault/server/${SDK_VERSION}`,
738
+ timeoutMs,
739
+ minRefetchIntervalMs,
740
+ staleIfErrorMs: staleIfErrorSeconds * 1e3,
741
+ fallbackMaxAgeMs: 6e4,
742
+ now: this.now
743
+ });
744
+ }
745
+ /**
746
+ * The claims of a valid player token for one of your games; rejects with a {@link PlayerTokenError} otherwise.
747
+ * `claims.sub` is the player's id.
748
+ */
749
+ async verify(token, options = {}) {
750
+ const games = gameList(options.gameId ?? this.gameId);
751
+ if (typeof token !== "string" || token.length === 0 || token.length > PLAYER_TOKEN_MAX_BYTES) {
752
+ throw invalid("malformed", "not a player token");
753
+ }
754
+ const parts = token.split(".");
755
+ if (parts.length !== 3 || !parts.every((p2) => B64URL_RE.test(p2))) throw invalid("malformed", "not a player token");
756
+ const [h, p, s] = parts;
757
+ const header = decodeJsonPart(h);
758
+ if (!header || header.alg !== "EdDSA") throw invalid("header", "the token is not signed with EdDSA");
759
+ if (header.typ !== void 0 && header.typ !== "JWT") throw invalid("header", "the token's typ is not JWT");
760
+ if (header.crit !== void 0 || header.jku !== void 0 || header.jwk !== void 0 || header.x5u !== void 0) {
761
+ throw invalid("header", "the token's header names keys or extensions it may not");
762
+ }
763
+ if (typeof header.kid !== "string" || !KID_RE2.test(header.kid)) throw invalid("header", "the token names no valid kid");
764
+ const key = await this.keyFor(header.kid);
765
+ if (!key) throw invalid("unknown_kid", "the token names a key SplatterVault does not publish");
766
+ const signature = Buffer.from(s, "base64url");
767
+ if (signature.length !== 64 || signature.toString("base64url") !== s) throw invalid("signature", "the signature is malformed");
768
+ let ok;
769
+ try {
770
+ ok = crypto.verify(null, Buffer.from(`${h}.${p}`, "ascii"), key, signature);
771
+ } catch {
772
+ ok = false;
773
+ }
774
+ if (!ok) throw invalid("signature", "the signature does not verify");
775
+ const claims = decodeJsonPart(p);
776
+ if (!claims) throw invalid("claims", "the claims are not a JSON object");
777
+ if (claims.iss !== PLAYER_TOKEN_ISSUER || typeof claims.aud !== "string") throw invalid("issuer", "not a SplatterVault player token");
778
+ if (claims.nbf !== void 0) throw invalid("claims", "player tokens carry no nbf");
779
+ if (!Number.isSafeInteger(claims.iat) || !Number.isSafeInteger(claims.exp)) throw invalid("claims", "iat and exp must be integers");
780
+ const iat = claims.iat;
781
+ const exp = claims.exp;
782
+ if (exp <= iat || exp - iat > this.maxLifetime) throw invalid("lifetime", "the token's lifetime is not one the API issues");
783
+ const nowSeconds = Math.floor(this.now() / 1e3);
784
+ if (iat > nowSeconds + this.skew) throw invalid("not_yet_valid", "the token was issued in the future (check the server clock)");
785
+ if (typeof claims.jti !== "string" || !JTI_RE.test(claims.jti)) throw invalid("claims", "the token has no valid jti");
786
+ const problem = claimsProblem(claims);
787
+ if (problem) throw invalid("claims", `the token's ${problem} claim is not valid`);
788
+ if (claims.aud !== `${PLAYER_TOKEN_AUDIENCE_PREFIX}${claims.game}`) throw invalid("claims", "aud does not name the token's game");
789
+ if (!games.includes(claims.game)) throw invalid("audience", "the token is for another game");
790
+ if (nowSeconds > exp + this.skew) throw new PlayerTokenError("token_expired", "expired", "Token expired");
791
+ return claims;
792
+ }
793
+ async keyFor(kid) {
794
+ if (this.fixedKeys) return this.fixedKeys.get(kid) ?? null;
795
+ try {
796
+ return await this.cache.keyFor(kid);
797
+ } catch (err) {
798
+ if (err instanceof JwksFetchError) {
799
+ throw new PlayerTokenError("keys_unavailable", "keys", `${err.message}; the token could not be checked`, { cause: err });
800
+ }
801
+ throw err;
802
+ }
803
+ }
804
+ };
805
+ function createPlayerTokenVerifier(options = {}) {
806
+ return new PlayerTokenVerifier(options);
807
+ }
808
+ var shared = /* @__PURE__ */ new Map();
809
+ var sharedByFetch = /* @__PURE__ */ new WeakMap();
810
+ function verifyPlayerToken(token, options) {
811
+ if (options.keys) return new PlayerTokenVerifier({ keys: options.keys }).verify(token, { gameId: options.gameId });
812
+ const insecure = options.dangerouslyAllowInsecureHttp === true;
813
+ const url = options.jwksUrl !== void 0 ? checkServiceUrl(options.jwksUrl, "jwksUrl", insecure) : `${checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, "baseUrl", insecure)}/player-auth/keys`;
814
+ let byUrl = shared;
815
+ if (options.fetch) {
816
+ byUrl = sharedByFetch.get(options.fetch) ?? /* @__PURE__ */ new Map();
817
+ sharedByFetch.set(options.fetch, byUrl);
818
+ }
819
+ let verifier = byUrl.get(url);
820
+ if (!verifier) {
821
+ verifier = new PlayerTokenVerifier({ jwksUrl: url, dangerouslyAllowInsecureHttp: insecure, ...options.fetch ? { fetch: options.fetch } : {} });
822
+ byUrl.set(url, verifier);
823
+ }
824
+ return verifier.verify(token, { gameId: options.gameId });
825
+ }
826
+
827
+ // src/resources/billing.ts
828
+ var Billing = class {
829
+ /** @internal */
830
+ constructor(http) {
831
+ this.http = http;
832
+ }
833
+ http;
834
+ /**
835
+ * The credit balance: the organization's for an organization API key (split into subscription and purchased
836
+ * credits). For an organization key `id` is 0 and `createdAt`, `updatedAt` and `user` are null.
837
+ * @see GET /credits (`billing.getCredits`)
838
+ */
839
+ getCredits(options) {
840
+ return this.http.call("billing.getCredits", { options });
841
+ }
842
+ /**
843
+ * Credit usage statistics; `organizationId` for an organization's.
844
+ * @see GET /credits/stats (`billing.getCreditStats`)
845
+ */
846
+ getCreditStats(query, options) {
847
+ return this.http.call("billing.getCreditStats", { query, options });
848
+ }
849
+ /**
850
+ * The credits of the organization the API key belongs to (balance, available balance, auto-buy settings).
851
+ * @see GET /org/credits (`billing.getKeyOrgCredits`)
852
+ */
853
+ getOrgCredits(query, options) {
854
+ return this.http.call("billing.getKeyOrgCredits", { query, options });
855
+ }
856
+ /**
857
+ * Every subscription of the organization the API key belongs to.
858
+ * @see GET /org/subscription (`billing.getKeyOrgSubscriptions`)
859
+ */
860
+ getOrgSubscriptions(query, options) {
861
+ return this.http.call("billing.getKeyOrgSubscriptions", { query, options });
862
+ }
863
+ /**
864
+ * The credits of organization `orgId` (the key's own organization).
865
+ * @see GET /organizations/{orgId}/credits (`billing.getOrgCredits`)
866
+ */
867
+ getOrgCreditsById(orgId, options) {
868
+ return this.http.call("billing.getOrgCredits", { path: { orgId }, options });
869
+ }
870
+ /**
871
+ * The current and past subscriptions of organization `orgId` (the key's own organization).
872
+ * @see GET /organizations/{orgId}/subscription (`billing.getOrgSubscription`)
873
+ */
874
+ getOrgSubscriptionById(orgId, options) {
875
+ return this.http.call("billing.getOrgSubscription", { path: { orgId }, options });
876
+ }
877
+ /**
878
+ * The current subscription and the others (`includeStripeHistory: true` adds invoices).
879
+ * @see GET /subscriptions (`billing.getSubscriptions`)
880
+ */
881
+ getSubscriptions(query, options) {
882
+ return this.http.call("billing.getSubscriptions", { query, options });
883
+ }
884
+ /**
885
+ * Usage in the current billing period: instances, credit hours, sessions.
886
+ * @see GET /subscriptions/usage (`billing.getUsage`)
887
+ */
888
+ getUsage(options) {
889
+ return this.http.call("billing.getUsage", { options });
890
+ }
891
+ };
892
+
893
+ // src/resources/playerData.ts
894
+ var conditional = (ops) => ops.length > 0 && ops.every((op) => typeof op.ifVersion === "number");
895
+ function nonEmpty(list, name) {
896
+ if (list !== void 0 && list.length === 0) {
897
+ throw new TypeError(`${name} must not be empty: leave it out to read every one, or name at least one`);
898
+ }
899
+ }
900
+ var readQuery = (q) => {
901
+ if (q === void 0) return void 0;
902
+ nonEmpty(q.stores, "stores");
903
+ nonEmpty(q.keys, "keys");
904
+ return { stores: q.stores, keys: q.keys, keysOnly: q.keysOnly === void 0 ? void 0 : String(q.keysOnly) };
905
+ };
906
+ var PlayerData = class {
907
+ /** @internal */
908
+ constructor(http) {
909
+ this.http = http;
910
+ }
911
+ http;
912
+ /**
913
+ * SplatterVault player ids for the ids other systems know your players by (at most 100 refs:
914
+ * `{ provider, providerId, providerApp? }` or an SV player id). `id` is null for refs nobody holds. A lookup only.
915
+ * @see POST /studio-data/games/{gameId}/players/resolve (`studioData.resolvePlayers`)
916
+ */
917
+ resolve(gameId, body, options) {
918
+ return this.http.call("studioData.resolvePlayers", { path: { gameId }, body, options });
919
+ }
920
+ /**
921
+ * One player's data in a game, by store and key: `{ data: { player: { <key>: { value, version, ... } }, ... } }`.
922
+ * @see GET /studio-data/games/{gameId}/players/{playerId}/data (`studioData.getPlayerData`)
923
+ */
924
+ async get(gameId, playerId, query, options) {
925
+ return this.http.call("studioData.getPlayerData", { path: { gameId, playerId }, query: readQuery(query), options });
926
+ }
927
+ /**
928
+ * Changes one player's data (at most 100 ops: `set`, `delete`, `inc`), all or nothing. A failed `ifVersion` is
929
+ * `version_conflict` with the current versions in `details`. On `outcomeUnknown` (see {@link PlayerData}), read
930
+ * before writing again; a resent write that meets `version_conflict` is reported as code `outcome_unknown`.
931
+ * @see PATCH /studio-data/games/{gameId}/players/{playerId}/data (`studioData.updatePlayerData`)
932
+ */
933
+ update(gameId, playerId, body, options) {
934
+ return this.http.call("studioData.updatePlayerData", {
935
+ path: { gameId, playerId },
936
+ body,
937
+ options,
938
+ conditional: conditional(body.ops)
939
+ });
940
+ }
941
+ /**
942
+ * Deletes all of one player's data in a game (the player stays). Resolves when done, also when there was nothing.
943
+ * @see DELETE /studio-data/games/{gameId}/players/{playerId}/data (`studioData.clearPlayerData`)
944
+ */
945
+ clear(gameId, playerId, options) {
946
+ return this.http.call("studioData.clearPlayerData", { path: { gameId, playerId }, options });
947
+ }
948
+ /**
949
+ * Several players' data (at most 100 players and 50 keys); `notFound` lists ids of no live player.
950
+ * @see POST /studio-data/games/{gameId}/data/get (`studioData.getPlayersData`)
951
+ */
952
+ async getMany(gameId, body, options) {
953
+ nonEmpty(body.stores, "stores");
954
+ nonEmpty(body.keys, "keys");
955
+ return this.http.call("studioData.getPlayersData", { path: { gameId }, body, options });
956
+ }
957
+ /**
958
+ * Changes several players' data atomically (at most 100 players, 1,000 ops in all): all or nothing across every
959
+ * player. Sent again by the SDK only as {@link PlayerData} says (every op with `ifVersion`, after 408/429/503).
960
+ * @see POST /studio-data/games/{gameId}/data/write (`studioData.writePlayersData`)
961
+ */
962
+ writeMany(gameId, body, options) {
963
+ return this.http.call("studioData.writePlayersData", {
964
+ path: { gameId },
965
+ body,
966
+ options,
967
+ conditional: body.writes.length > 0 && body.writes.every((w) => conditional(w.ops))
968
+ });
969
+ }
970
+ /**
971
+ * The game's own data (`public`: players can read it; `internal`: only your backend).
972
+ * @see GET /studio-data/games/{gameId}/game-data (`studioData.getGameData`)
973
+ */
974
+ async getGameData(gameId, query, options) {
975
+ return this.http.call("studioData.getGameData", { path: { gameId }, query: readQuery(query), options });
976
+ }
977
+ /**
978
+ * Changes the game's data (`set` and `delete`, at most 100 ops, values at most 256 KiB). Players read `public`
979
+ * within 30 seconds. Sent again by the SDK only as {@link PlayerData} says.
980
+ * @see PATCH /studio-data/games/{gameId}/game-data (`studioData.updateGameData`)
981
+ */
982
+ updateGameData(gameId, body, options) {
983
+ return this.http.call("studioData.updateGameData", { path: { gameId }, body, options, conditional: conditional(body.ops) });
984
+ }
985
+ /**
986
+ * Imports player and game data (at most 1,000 rows, 8 MiB). `dryRun: true` writes nothing; the same rows again
987
+ * change nothing, so the SDK retries this call.
988
+ * @see POST /studio-data/games/{gameId}/import (`studioData.importData`)
989
+ */
990
+ import(gameId, body, options) {
991
+ return this.http.call("studioData.importData", { path: { gameId }, body, options });
992
+ }
993
+ /**
994
+ * One page (oldest first, 500 at most) of your organization's erased players, for deleting what you keep about
995
+ * them. Store the answer's `next` and pass it back as `cursor`; `more: true` means call again now.
996
+ * @see GET /studio-data/erased-players (`studioData.listErasedPlayers`)
997
+ */
998
+ listErasedPlayers(query, options) {
999
+ const cursor = query?.cursor;
1000
+ const since = cursor === void 0 ? query?.since : void 0;
1001
+ return this.http.call("studioData.listErasedPlayers", {
1002
+ query: { cursor, since: since instanceof Date ? since.toISOString() : since },
1003
+ options
1004
+ });
1005
+ }
1006
+ /**
1007
+ * Every page of erased players from `cursor` (or `since`), until a page says `more: false`. Save each page's `next`
1008
+ * once you have handled it, and start there next time (poll every few minutes).
1009
+ *
1010
+ * ```ts
1011
+ * for await (const page of sv.playerData.erasedPlayerPages({ cursor: saved })) {
1012
+ * await deleteMyRows(page.players.map((p) => p.id));
1013
+ * saved = page.next;
1014
+ * }
1015
+ * ```
1016
+ */
1017
+ async *erasedPlayerPages(query, options) {
1018
+ let next = { ...query };
1019
+ for (; ; ) {
1020
+ const page = await this.listErasedPlayers(next, options);
1021
+ yield page;
1022
+ if (!page.more) return;
1023
+ next = { cursor: page.next };
1024
+ }
1025
+ }
1026
+ };
1027
+
1028
+ // src/resources/players.ts
1029
+ var Players = class {
1030
+ /** @internal */
1031
+ constructor(http) {
1032
+ this.http = http;
1033
+ }
1034
+ http;
1035
+ /**
1036
+ * Signs a player in with your own id for them (`externalId`, 1-128 visible ASCII characters) and answers a player
1037
+ * token (about an hour) to hand to that player's game client. The same `externalId` is always the same player.
1038
+ * The key needs org:issue_player_tokens; the game's "studio" sign-in must be on. Not retried by the SDK.
1039
+ * @see POST /player-auth/studio (`playerAuth.studio.signIn`)
1040
+ */
1041
+ signIn(body, options) {
1042
+ return this.http.call("playerAuth.studio.signIn", { body, options });
1043
+ }
1044
+ /**
1045
+ * Imports players from other systems (at most 1,000 rows, 1 MB): their identities, emails, bcrypt password hashes
1046
+ * and names. `dryRun: true` writes nothing; the same rows again change nothing, so the SDK retries this call. The
1047
+ * key needs org:import_players.
1048
+ * @see POST /player-auth/studio/import (`playerAuth.studio.importPlayers`)
1049
+ */
1050
+ import(body, options) {
1051
+ return this.http.call("playerAuth.studio.importPlayers", { body, options });
1052
+ }
1053
+ /**
1054
+ * Erases a player and everything every studio service keeps about them (identities, data in every game, store
1055
+ * holdings). It cannot be undone; their tokens stop working. Resolves when erased (204). Not retried by the SDK.
1056
+ * The key needs org:issue_player_tokens.
1057
+ * @see DELETE /player-auth/studio/players/{playerId} (`playerAuth.studio.erasePlayer`)
1058
+ */
1059
+ erase(playerId, options) {
1060
+ return this.http.call("playerAuth.studio.erasePlayer", { path: { playerId }, options });
1061
+ }
1062
+ };
1063
+
1064
+ // src/resources/sessions.ts
1065
+ var SessionWaitError = class extends Error {
1066
+ constructor(code, sessionId, session, message, options) {
1067
+ super(message, options);
1068
+ this.code = code;
1069
+ this.sessionId = sessionId;
1070
+ this.session = session;
1071
+ this.sessionStatus = session?.status ?? null;
1072
+ this.stopReason = session?.stopReason ?? null;
1073
+ }
1074
+ code;
1075
+ name = "SessionWaitError";
1076
+ /** The session's id. */
1077
+ sessionId;
1078
+ /** The session's last status read (`Pending`, `Active`, `Not Active`, `Scheduled`, …), or null if none was read. */
1079
+ sessionStatus;
1080
+ /** The session's stop reason when it ended (e.g. `GAME_CRASH`, `IDLE_TIMEOUT`), else null. */
1081
+ stopReason;
1082
+ /** The last session read, or null. */
1083
+ session;
1084
+ };
1085
+ var MAX_POLL_INTERVAL_MS = 1e4;
1086
+ var MAX_CONSECUTIVE_POLL_FAILURES = 3;
1087
+ function isReady(session, waitForGameReady, nowMs) {
1088
+ if (session.status !== "Active") return false;
1089
+ if (!waitForGameReady || session.ready === true || session.ready === void 0) return true;
1090
+ const deadline = session.readyDeadlineAt ? Date.parse(session.readyDeadlineAt) : Number.NaN;
1091
+ return Number.isFinite(deadline) && nowMs >= deadline;
1092
+ }
1093
+ var SubscriptionSessions = class {
1094
+ /** @internal */
1095
+ constructor(http) {
1096
+ this.http = http;
1097
+ }
1098
+ http;
1099
+ /**
1100
+ * Starts a dedicated server for a match, billed to the subscription. Never retried by the SDK (a repeat would start
1101
+ * a second server).
1102
+ * @see POST /subscriptions/sessions (`sessions.createSubscription`)
1103
+ */
1104
+ create(body, options) {
1105
+ return this.http.call("sessions.createSubscription", { body, options });
1106
+ }
1107
+ /**
1108
+ * The subscription sessions, optionally of one organization and of some statuses (`"Active,Pending"`).
1109
+ * @see GET /subscriptions/sessions (`sessions.listSubscription`)
1110
+ */
1111
+ list(query, options) {
1112
+ return this.http.call("sessions.listSubscription", { query, options });
1113
+ }
1114
+ /**
1115
+ * Stops a subscription session.
1116
+ * @see POST /subscriptions/sessions/{sessionId}/stop (`sessions.stopSubscription`)
1117
+ */
1118
+ stop(sessionId, options) {
1119
+ return this.http.call("sessions.stopSubscription", { path: { sessionId }, options });
1120
+ }
1121
+ /**
1122
+ * Sets a session's friendly name (at most 255 characters).
1123
+ * @see PUT /subscriptions/sessions/{sessionId}/friendly-name (`sessions.renameSubscription`)
1124
+ */
1125
+ rename(sessionId, friendlyName, options) {
1126
+ return this.http.call("sessions.renameSubscription", { path: { sessionId }, body: { friendlyName }, options });
1127
+ }
1128
+ /**
1129
+ * Moves a scheduled session's start and end, or sets an active session's end.
1130
+ * @see PUT /subscriptions/sessions/{sessionId}/schedule (`sessions.rescheduleSubscription`)
1131
+ */
1132
+ reschedule(sessionId, body, options) {
1133
+ return this.http.call("sessions.rescheduleSubscription", { path: { sessionId }, body, options });
1134
+ }
1135
+ /**
1136
+ * Cancels a scheduled session (it becomes Not Active).
1137
+ * @see POST /subscriptions/sessions/{sessionId}/cancel-schedule (`sessions.cancelScheduledSubscription`)
1138
+ */
1139
+ cancelSchedule(sessionId, options) {
1140
+ return this.http.call("sessions.cancelScheduledSubscription", { path: { sessionId }, options });
1141
+ }
1142
+ };
1143
+ var Sessions = class {
1144
+ /** @internal */
1145
+ constructor(http) {
1146
+ this.http = http;
1147
+ this.subscription = new SubscriptionSessions(http);
1148
+ }
1149
+ http;
1150
+ /** Subscription-billed sessions. */
1151
+ subscription;
1152
+ /**
1153
+ * Starts a dedicated server for a match (status `Pending` until it is up; poll {@link Sessions.get} for
1154
+ * `connection`). Credits are billed per minute while it runs. Never retried by the SDK: a repeat would start a second
1155
+ * server, so on a network error look for it with {@link Sessions.list} before trying again.
1156
+ * @see POST /credits/sessions (`sessions.createCredit`)
1157
+ */
1158
+ create(body, options) {
1159
+ return this.http.call("sessions.createCredit", { body, options });
1160
+ }
1161
+ /**
1162
+ * The credit sessions, optionally of one organization (0: personal only) and of some statuses (`"Active,Pending"`).
1163
+ * @see GET /credits/sessions (`sessions.listCredit`)
1164
+ */
1165
+ list(query, options) {
1166
+ return this.http.call("sessions.listCredit", { query, options });
1167
+ }
1168
+ /**
1169
+ * One session with its connection details. `{ slim: true }` leaves out its matches.
1170
+ * @see GET /game-sessions/{id} (`sessions.get`)
1171
+ */
1172
+ get(sessionId, query, options) {
1173
+ return this.http.call("sessions.get", { path: { id: sessionId }, query, options });
1174
+ }
1175
+ /**
1176
+ * Waits until a session is ready for players and answers it: polls {@link Sessions.get} (slim) with a growing
1177
+ * interval, from `intervalMs` up to 10 s. "Ready" is status `Active` and, by default, the game's own ready signal
1178
+ * (`ready: true`); a game with no ready signal is returned once its `readyDeadlineAt` (server up + 300 s) passes,
1179
+ * with `ready: false`. The counterpart of the Unity SDK's `WaitForServerReady`.
1180
+ *
1181
+ * Rejects with a {@link SessionWaitError}: `session_ended` as soon as the session is `Not Active` (see its
1182
+ * `stopReason`), or `wait_timeout` after `timeoutMs` (default five minutes). A read that fails transiently is
1183
+ * tolerated twice in a row; any other refusal (e.g. 404) rejects at once. An aborted `signal` rejects with a
1184
+ * `SplatterVaultError` of code `aborted`.
1185
+ *
1186
+ * ```ts
1187
+ * const session = await sv.sessions.create({ gameTypeConfigKey: "my-game", region: "NYC3" });
1188
+ * const ready = await sv.sessions.waitUntilReady(session.id);
1189
+ * console.log(ready.connection?.host, ready.connection?.primaryPort);
1190
+ * ```
1191
+ */
1192
+ async waitUntilReady(sessionId, options = {}) {
1193
+ const timeoutMs = intInRange(options.timeoutMs ?? 3e5, "timeoutMs", 1, MAX_TIMER_MS);
1194
+ let interval = intInRange(options.intervalMs ?? 2e3, "intervalMs", 250, 6e4);
1195
+ const maxInterval = Math.max(MAX_POLL_INTERVAL_MS, interval);
1196
+ const waitForGameReady = options.waitForGameReady !== false;
1197
+ const signal = options.signal;
1198
+ const giveUpAt = Date.now() + timeoutMs;
1199
+ let last = null;
1200
+ let failures = 0;
1201
+ for (; ; ) {
1202
+ const remaining = giveUpAt - Date.now();
1203
+ try {
1204
+ const session = await this.get(sessionId, { slim: true }, {
1205
+ ...signal ? { signal } : {},
1206
+ timeoutMs: Math.max(1, Math.min(this.http.defaultTimeoutMs, remaining))
1207
+ });
1208
+ failures = 0;
1209
+ last = session;
1210
+ options.onPoll?.(session);
1211
+ if (session.status === "Not Active") {
1212
+ const reason = session.stopReason ? ` (stop reason: ${session.stopReason})` : "";
1213
+ throw new SessionWaitError("session_ended", sessionId, session, `session ${sessionId} ended before it was ready${reason}`);
1214
+ }
1215
+ if (isReady(session, waitForGameReady, Date.now())) return session;
1216
+ } catch (err) {
1217
+ if (!(err instanceof SplatterVaultError) || err.code === "aborted") throw err;
1218
+ if (!err.isTransient || ++failures >= MAX_CONSECUTIVE_POLL_FAILURES || Date.now() >= giveUpAt) throw err;
1219
+ }
1220
+ const left = giveUpAt - Date.now();
1221
+ if (left <= 0) {
1222
+ const state = last ? ` (last status: ${last.status}${last.status === "Active" && waitForGameReady ? ", game not ready yet" : ""})` : "";
1223
+ throw new SessionWaitError("wait_timeout", sessionId, last, `session ${sessionId} was not ready within ${timeoutMs} ms${state}`);
1224
+ }
1225
+ try {
1226
+ await sleep(Math.min(interval, left), signal);
1227
+ } catch (reason) {
1228
+ throw new SplatterVaultError({
1229
+ status: 0,
1230
+ code: "aborted",
1231
+ message: "aborted: the call was aborted by its signal",
1232
+ operationId: "sessions.get",
1233
+ method: "GET",
1234
+ path: `/game-sessions/${encodeURIComponent(String(sessionId))}`,
1235
+ cause: reason
1236
+ });
1237
+ }
1238
+ interval = Math.min(Math.round(interval * 1.5), maxInterval);
1239
+ }
1240
+ }
1241
+ /**
1242
+ * The sessions this key (or account) created, optionally of one game type and status.
1243
+ * @see GET /game-sessions/my-sessions (`sessions.listMine`)
1244
+ */
1245
+ listMine(query, options) {
1246
+ return this.http.call("sessions.listMine", { query, options });
1247
+ }
1248
+ /**
1249
+ * Stops a credit session and bills it: answers the session, its hours and its cost.
1250
+ * @see POST /credits/sessions/{sessionId}/stop (`sessions.stopCredit`)
1251
+ */
1252
+ stop(sessionId, options) {
1253
+ return this.http.call("sessions.stopCredit", { path: { sessionId }, options });
1254
+ }
1255
+ /**
1256
+ * Sets a session's friendly name (at most 255 characters).
1257
+ * @see PUT /credits/sessions/{sessionId}/friendly-name (`sessions.renameCredit`)
1258
+ */
1259
+ rename(sessionId, friendlyName, options) {
1260
+ return this.http.call("sessions.renameCredit", { path: { sessionId }, body: { friendlyName }, options });
1261
+ }
1262
+ /**
1263
+ * Moves a scheduled session's start and end, or sets an active session's end.
1264
+ * @see PUT /credits/sessions/{sessionId}/schedule (`sessions.rescheduleCredit`)
1265
+ */
1266
+ reschedule(sessionId, body, options) {
1267
+ return this.http.call("sessions.rescheduleCredit", { path: { sessionId }, body, options });
1268
+ }
1269
+ /**
1270
+ * Cancels a scheduled credit session (it becomes Not Active).
1271
+ * @see POST /credits/sessions/{sessionId}/cancel-schedule (`sessions.cancelScheduledCredit`)
1272
+ */
1273
+ cancelSchedule(sessionId, options) {
1274
+ return this.http.call("sessions.cancelScheduledCredit", { path: { sessionId }, options });
1275
+ }
1276
+ };
1277
+ function poolClaimConflict(err) {
1278
+ if (!(err instanceof SplatterVaultError) || err.status !== 409 || err.operationId !== "serverPools.claim") return null;
1279
+ const body = err.body;
1280
+ const message = typeof body?.message === "string" ? body.message : "";
1281
+ return /\bretry\s*[.!]?\s*$/i.test(message) ? "busy" : "no_warm_server";
1282
+ }
1283
+ var ServerPools = class {
1284
+ /** @internal */
1285
+ constructor(http) {
1286
+ this.http = http;
1287
+ }
1288
+ http;
1289
+ /**
1290
+ * Claims a warm server from pool `poolId` for a match: answers the new session's id, the pool instance and its
1291
+ * `connection` (null until reachable). Needs a key holding org:manage_pools (with an organization API key).
1292
+ *
1293
+ * Never retried by the SDK: a repeat after a lost answer could claim a second server. A `409` claimed nothing:
1294
+ * {@link poolClaimConflict} says whether no server is idle (`"no_warm_server"`: start a session instead) or the
1295
+ * claim met contention (`"busy"`: you may try again shortly). Like every session route it never answers 429.
1296
+ * @see POST /server-pools/{id}/claim (`serverPools.claim`)
1297
+ */
1298
+ claim(poolId, body, options) {
1299
+ return this.http.call("serverPools.claim", { path: { id: poolId }, body: body ?? {}, options });
1300
+ }
1301
+ };
1302
+ var Games = class {
1303
+ /** @internal */
1304
+ constructor(http) {
1305
+ this.http = http;
1306
+ }
1307
+ http;
1308
+ /**
1309
+ * The launch arguments a session of this game may set (`userConfigurable`), by the game's key (or its id).
1310
+ * @see GET /game-types/{id}/configurable-args (`games.getConfigurableArgs`)
1311
+ */
1312
+ getConfigurableArgs(game, options) {
1313
+ return this.http.call("games.getConfigurableArgs", { path: { id: game }, options });
1314
+ }
1315
+ };
1316
+
1317
+ // src/resources/store.ts
1318
+ var Store = class {
1319
+ /** @internal */
1320
+ constructor(http) {
1321
+ this.http = http;
1322
+ }
1323
+ http;
1324
+ /**
1325
+ * The whole catalog (archived entries too) and the store's settings. The key needs org:view_economy or
1326
+ * org:grant_economy.
1327
+ * @see GET /store/studio/catalog (`store.studio.getCatalog`)
1328
+ */
1329
+ getCatalog(options) {
1330
+ return this.http.call("store.studio.getCatalog", { options });
1331
+ }
1332
+ /**
1333
+ * A player's balances and items.
1334
+ * @see GET /store/studio/players/{player} (`store.studio.getPlayer`)
1335
+ */
1336
+ getPlayer(player, options) {
1337
+ return this.http.call("store.studio.getPlayer", { path: { player }, options });
1338
+ }
1339
+ /**
1340
+ * One page (50) of a player's store history, newest first; pass the answer's `next` as `before` for older ones
1341
+ * (`next` is null on the last page). See {@link Store.historyPages} to walk every page.
1342
+ * @see GET /store/studio/players/{player}/history (`store.studio.getPlayerHistory`)
1343
+ */
1344
+ getHistory(player, query, options) {
1345
+ return this.http.call("store.studio.getPlayerHistory", { path: { player }, query: { before: query?.before }, options });
1346
+ }
1347
+ /**
1348
+ * Every page of a player's store history, newest first, from `before` (default: the newest).
1349
+ *
1350
+ * ```ts
1351
+ * for await (const page of sv.store.historyPages(playerId)) {
1352
+ * for (const txn of page.txns) console.log(txn.kind, txn.createdAt);
1353
+ * }
1354
+ * ```
1355
+ */
1356
+ async *historyPages(player, query, options) {
1357
+ let before = query?.before;
1358
+ for (; ; ) {
1359
+ const page = await this.getHistory(player, { before }, options);
1360
+ yield page;
1361
+ if (!page.next) return;
1362
+ before = page.next;
1363
+ }
1364
+ }
1365
+ /**
1366
+ * Gives a player items and currency (1-50 lines: `{ sku, quantity, custom? }` or `{ currency, amount }`). Bundles
1367
+ * give their contents; currency caps and `maxOwned` apply. The key needs org:grant_economy.
1368
+ * @see POST /store/studio/players/{player}/grants (`store.studio.grant`)
1369
+ */
1370
+ grant(player, body, options) {
1371
+ return this.http.call("store.studio.grant", { path: { player }, body, options });
1372
+ }
1373
+ /**
1374
+ * Uses up or takes a player's items and currency (by SKU oldest first, by `instanceId`, or `{ currency, amount }`),
1375
+ * never below zero: `insufficient_items` / `insufficient_funds` otherwise.
1376
+ * @see POST /store/studio/players/{player}/consume (`store.studio.consume`)
1377
+ */
1378
+ consume(player, body, options) {
1379
+ return this.http.call("store.studio.consume", { path: { player }, body, options });
1380
+ }
1381
+ /**
1382
+ * Buys an item with the player's virtual currency, from the server (the item's player-purchase switch does not
1383
+ * apply). Send `expectedPrice` to refuse a changed price (`price_changed`).
1384
+ * @see POST /store/studio/players/{player}/purchases (`store.studio.purchase`)
1385
+ */
1386
+ purchase(player, body, options) {
1387
+ return this.http.call("store.studio.purchase", { path: { player }, body, options });
1388
+ }
1389
+ /**
1390
+ * Sets the custom data of one of a player's items (a JSON object of at most 1 KB, or null).
1391
+ * @see PATCH /store/studio/players/{player}/items/{instanceId} (`store.studio.updateItem`)
1392
+ */
1393
+ updateItem(player, instanceId, body, options) {
1394
+ return this.http.call("store.studio.updateItem", { path: { player, instanceId }, body, options });
1395
+ }
1396
+ /**
1397
+ * Reverses an earlier change, named by its `txn` id or by the `originalKey` (the Idempotency-Key it was sent with):
1398
+ * takes back what the player still holds and gives back what it took; what was spent already is in `shortfall`.
1399
+ * Once per change (`already_reversed`).
1400
+ * @see POST /store/studio/players/{player}/reversals (`store.studio.reverse`)
1401
+ */
1402
+ reverse(player, body, options) {
1403
+ return this.http.call("store.studio.reverse", { path: { player }, body, options });
1404
+ }
1405
+ /**
1406
+ * Checks the player's Meta Quest purchases and grants what is new (the player must have Meta linked). Not retried
1407
+ * by the SDK.
1408
+ * @see POST /store/studio/players/{player}/platform-purchases/meta (`store.studio.syncMetaPurchases`)
1409
+ */
1410
+ syncMetaPurchases(player, body, options) {
1411
+ return this.http.call("store.studio.syncMetaPurchases", { path: { player }, body, options });
1412
+ }
1413
+ /**
1414
+ * Imports a catalog (`format`: `playfab`, `xsolla` or `sv`; 1-1,000 rows). Re-running a file changes nothing, so
1415
+ * the SDK retries this call. The key needs org:manage_economy.
1416
+ * @see POST /store/studio/imports/catalog (`store.studio.importCatalog`)
1417
+ */
1418
+ importCatalog(body, options) {
1419
+ return this.http.call("store.studio.importCatalog", { body, options });
1420
+ }
1421
+ /**
1422
+ * Imports players' balances and items (1-1,000 rows; each player once per `source`, so the same rows again change
1423
+ * nothing and the SDK retries this call). The key needs org:manage_economy.
1424
+ * @see POST /store/studio/imports/holdings (`store.studio.importHoldings`)
1425
+ */
1426
+ importHoldings(body, options) {
1427
+ return this.http.call("store.studio.importHoldings", { body, options });
1428
+ }
1429
+ };
1430
+
1431
+ // src/client.ts
1432
+ function isBrowserLike() {
1433
+ const g = globalThis;
1434
+ const versions = typeof process !== "undefined" ? process.versions : void 0;
1435
+ if (versions?.electron !== void 0 || versions?.nw !== void 0) return true;
1436
+ const win = g.window;
1437
+ if (win !== void 0 && win !== null && typeof win === "object" && win.document !== void 0) return true;
1438
+ if (typeof g.importScripts === "function") return true;
1439
+ const workerScope = g.WorkerGlobalScope;
1440
+ if (typeof workerScope === "function" && globalThis instanceof workerScope) return true;
1441
+ if (g.navigator?.product === "ReactNative") return true;
1442
+ return false;
1443
+ }
1444
+ var API_KEY_RE = /^[\x21-\x7e]+$/;
1445
+ var SplatterVault = class {
1446
+ /** Game-server sessions billed in credits (and `sessions.subscription` for subscription-billed ones). */
1447
+ sessions;
1448
+ /** Warm server pools: claim a running server for a match. */
1449
+ serverPools;
1450
+ /** Game types: the launch arguments a session may set. */
1451
+ games;
1452
+ /** Credits, subscriptions and usage. */
1453
+ billing;
1454
+ /** Studio player sign-in from your backend: sign in with your own ids, import, erase. */
1455
+ players;
1456
+ /** Each player's data and the game's data. */
1457
+ playerData;
1458
+ /** The store: catalog, holdings, grants, consumes, purchases, reversals, imports. */
1459
+ store;
1460
+ #http;
1461
+ #insecureHttp;
1462
+ #verifier = null;
1463
+ constructor(options = {}) {
1464
+ if (isBrowserLike() && options.dangerouslyAllowBrowser !== true) {
1465
+ throw new Error(
1466
+ "@splattervault/server refuses to run in a browser-like environment (a browser, a web worker, React Native, Electron or NW.js): an organization API key there is readable by anyone who has the page or the app. Call SplatterVault from your server; game clients sign players in and use player tokens. If this environment is trusted and only looks like one, pass { dangerouslyAllowBrowser: true }."
1467
+ );
1468
+ }
1469
+ const apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env?.SV_API_KEY : void 0);
1470
+ if (typeof apiKey !== "string" || apiKey === "") {
1471
+ throw new TypeError("apiKey is required: pass { apiKey } or set SV_API_KEY (an organization API key, sv_org_...)");
1472
+ }
1473
+ if (!API_KEY_RE.test(apiKey)) throw new TypeError("apiKey must be visible ASCII characters only (check for spaces or line breaks)");
1474
+ const fetchFn = options.fetch ?? globalThis.fetch;
1475
+ if (typeof fetchFn !== "function") throw new TypeError("no fetch: use Node.js 18 or later, or pass { fetch }");
1476
+ this.#insecureHttp = options.dangerouslyAllowInsecureHttp === true;
1477
+ const baseUrl = checkServiceUrl(options.baseUrl ?? DEFAULT_BASE_URL, "baseUrl", this.#insecureHttp);
1478
+ const timeoutMs = intInRange(options.timeoutMs ?? 3e4, "timeoutMs", 1, MAX_TIMER_MS);
1479
+ const maxRetries = intInRange(options.maxRetries ?? DEFAULT_RETRY.maxRetries, "maxRetries", 0, MAX_RETRIES);
1480
+ const retry = { ...DEFAULT_RETRY, maxRetries };
1481
+ for (const name of ["baseDelayMs", "maxDelayMs", "maxRetryAfterMs"]) {
1482
+ const value = options.retry?.[name];
1483
+ if (value !== void 0) retry[name] = intInRange(value, `retry.${name}`, 0, MAX_TIMER_MS);
1484
+ }
1485
+ const sdkAgent = `splattervault-server-node/${SDK_VERSION} node/${typeof process !== "undefined" ? process.version : "unknown"}`;
1486
+ this.#http = new HttpClient({
1487
+ apiKey,
1488
+ baseUrl,
1489
+ fetch: fetchFn,
1490
+ timeoutMs,
1491
+ retry,
1492
+ userAgent: options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent
1493
+ });
1494
+ this.sessions = new Sessions(this.#http);
1495
+ this.serverPools = new ServerPools(this.#http);
1496
+ this.games = new Games(this.#http);
1497
+ this.billing = new Billing(this.#http);
1498
+ this.players = new Players(this.#http);
1499
+ this.playerData = new PlayerData(this.#http);
1500
+ this.store = new Store(this.#http);
1501
+ }
1502
+ /** The API base URL this client calls. */
1503
+ get baseUrl() {
1504
+ return this.#http.baseUrl;
1505
+ }
1506
+ /**
1507
+ * Verifies a player's token offline (Ed25519, against `GET /player-auth/keys` of this client's base URL, cached as
1508
+ * the answer's Cache-Control allows) and answers its claims: `claims.sub` is the player's id. Rejects with a
1509
+ * `PlayerTokenError` (`token_invalid`, `token_expired` or `keys_unavailable`). The API key is not sent.
1510
+ *
1511
+ * ```ts
1512
+ * const { sub: playerId } = await sv.verifyPlayerToken(tokenFromClient, { gameId: 42 });
1513
+ * ```
1514
+ */
1515
+ verifyPlayerToken(token, options) {
1516
+ this.#verifier ??= new PlayerTokenVerifier({
1517
+ baseUrl: this.#http.baseUrl,
1518
+ fetch: this.#http.fetchFn,
1519
+ dangerouslyAllowInsecureHttp: this.#insecureHttp
1520
+ });
1521
+ return this.#verifier.verify(token, options);
1522
+ }
1523
+ /** Never shows the API key. */
1524
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1525
+ return `SplatterVault { baseUrl: '${this.#http.baseUrl}' }`;
1526
+ }
1527
+ /** Never shows the API key. */
1528
+ toJSON() {
1529
+ return { baseUrl: this.#http.baseUrl };
1530
+ }
1531
+ };
1532
+
1533
+ // src/sessionEnv.ts
1534
+ var text = (env, name) => {
1535
+ const value = env[name];
1536
+ return value === void 0 || value.trim() === "" ? null : value;
1537
+ };
1538
+ var positiveInt = (value) => {
1539
+ if (value === null || !/^\d+$/.test(value.trim())) return null;
1540
+ const n = Number(value.trim());
1541
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
1542
+ };
1543
+ function readSessionEnvironment(env = process.env) {
1544
+ const code = text(env, "CODE");
1545
+ const gameType = text(env, "GAME_TYPE");
1546
+ return {
1547
+ onSplatterVault: code !== null && gameType !== null,
1548
+ sessionId: positiveInt(text(env, "SESSION_ID")),
1549
+ code,
1550
+ gameType,
1551
+ mode: text(env, "MODE"),
1552
+ serverName: text(env, "SERVER_NAME"),
1553
+ friendlyName: text(env, "FRIENDLY_NAME"),
1554
+ buildChannel: text(env, "BUILD_CHANNEL"),
1555
+ slavePort: positiveInt(text(env, "SLAVE_PORT"))
1556
+ };
1557
+ }
1558
+
1559
+ exports.Billing = Billing;
1560
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1561
+ exports.DEFAULT_RETRY = DEFAULT_RETRY;
1562
+ exports.DEFAULT_STALE_IF_ERROR_SECONDS = DEFAULT_STALE_IF_ERROR_SECONDS;
1563
+ exports.Games = Games;
1564
+ exports.IDEMPOTENCY_KEY_RE = IDEMPOTENCY_KEY_RE;
1565
+ exports.MAX_RETRIES = MAX_RETRIES;
1566
+ exports.NOT_APPLIED_STATUSES = NOT_APPLIED_STATUSES;
1567
+ exports.OPERATIONS = OPERATIONS;
1568
+ exports.OUTCOME_UNKNOWN_STATUSES = OUTCOME_UNKNOWN_STATUSES;
1569
+ exports.PLAYER_TOKEN_AUDIENCE_PREFIX = PLAYER_TOKEN_AUDIENCE_PREFIX;
1570
+ exports.PLAYER_TOKEN_CLOCK_SKEW_SECONDS = PLAYER_TOKEN_CLOCK_SKEW_SECONDS;
1571
+ exports.PLAYER_TOKEN_ISSUER = PLAYER_TOKEN_ISSUER;
1572
+ exports.PLAYER_TOKEN_MAX_LIFETIME_SECONDS = PLAYER_TOKEN_MAX_LIFETIME_SECONDS;
1573
+ exports.PlayerData = PlayerData;
1574
+ exports.PlayerTokenError = PlayerTokenError;
1575
+ exports.PlayerTokenVerifier = PlayerTokenVerifier;
1576
+ exports.Players = Players;
1577
+ exports.SDK_ERROR_CODES = SDK_ERROR_CODES;
1578
+ exports.SDK_VERSION = SDK_VERSION;
1579
+ exports.ServerPools = ServerPools;
1580
+ exports.SessionWaitError = SessionWaitError;
1581
+ exports.Sessions = Sessions;
1582
+ exports.SplatterVault = SplatterVault;
1583
+ exports.SplatterVaultError = SplatterVaultError;
1584
+ exports.Store = Store;
1585
+ exports.SubscriptionSessions = SubscriptionSessions;
1586
+ exports.TRANSIENT_STATUSES = TRANSIENT_STATUSES;
1587
+ exports.createPlayerTokenVerifier = createPlayerTokenVerifier;
1588
+ exports.isBrowserLike = isBrowserLike;
1589
+ exports.newIdempotencyKey = newIdempotencyKey;
1590
+ exports.poolClaimConflict = poolClaimConflict;
1591
+ exports.readSessionEnvironment = readSessionEnvironment;
1592
+ exports.verifyPlayerToken = verifyPlayerToken;
1593
+ //# sourceMappingURL=index.cjs.map
1594
+ //# sourceMappingURL=index.cjs.map