@invonetwork/web-sdk 3.27.0 → 3.29.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/README.md CHANGED
@@ -2398,7 +2398,7 @@ const economy = {
2398
2398
  ],
2399
2399
  };
2400
2400
 
2401
- // INVO_GAME_SECRET, INVO_WEBHOOK_SECRET, INVO_ENV (sandbox | production), PUBLIC_URL
2401
+ // INVO_GAME_SECRET, INVO_WEBHOOK_SECRET, PUBLIC_URL (the environment follows the key)
2402
2402
  const { server, missing } = invoGameServerFromEnv({
2403
2403
  economy,
2404
2404
  env: process.env,
@@ -2409,6 +2409,29 @@ http.createServer(toNodeListener(server, serveYourStaticFiles)).listen(3000);
2409
2409
 
2410
2410
  Point your INVO webhook at `https://<your-host>/api/invo/webhook`.
2411
2411
 
2412
+ **On the public demo key (INVO's game templates).** A fresh fork runs on the public demo key
2413
+ (`ivsdk_demo_...`, sandbox only, no signup). Register the fork on every start; the first time,
2414
+ the webhook signing secret and a registration token are stored in `.invo/project.json` (add it to
2415
+ `.gitignore`; a remix that copied it gets a fresh project id automatically):
2416
+
2417
+ ```ts
2418
+ import { registerProject, invoGameServerFromEnv } from "@invonetwork/web-sdk/game-server";
2419
+
2420
+ if (process.env.INVO_GAME_SECRET?.startsWith("ivsdk_demo_")) {
2421
+ await registerProject({
2422
+ gameSecret: process.env.INVO_GAME_SECRET,
2423
+ webhookUrl: `${process.env.PUBLIC_URL}/api/invo/webhook`,
2424
+ });
2425
+ }
2426
+ const { server } = invoGameServerFromEnv({ economy, env: process.env, store });
2427
+ ```
2428
+
2429
+ On the demo key every sign-in is mapped to a demo-sandbox player email for this project and a
2430
+ fictional 555-01XX phone, so no real address or number reaches INVO. Going live is replacing
2431
+ `INVO_GAME_SECRET` with your own key (and `INVO_WEBHOOK_SECRET` with the secret from your INVO
2432
+ console): no code changes. `verifyInvoSignature(rawBody, header, secrets)` checks an INVO webhook
2433
+ signature anywhere else you need it.
2434
+
2412
2435
  **Browser.**
2413
2436
 
2414
2437
  ```ts
@@ -1,5 +1,5 @@
1
1
  import { assertSecureBaseUrl, Http, toRequestPhoneChangeResult, toPhoneChangeRequest, receiptFields, creditFields, toLoyaltyCardsResult, toDestinationsResult } from './chunk-6CN236QH.js';
2
- import { SDK_VERSION } from './chunk-3YDO7GSH.js';
2
+ import { SDK_VERSION } from './chunk-KZJABBVT.js';
3
3
  import { InvoError, buildGameEventBody, toReportGameEventResult } from './chunk-VP3OK4J4.js';
4
4
  import { createHmac, timingSafeEqual } from 'crypto';
5
5
 
@@ -294,6 +294,9 @@ function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
294
294
  }
295
295
  return finalizeEvent(bodyBytes);
296
296
  }
297
+ function verifyInvoSignature(rawBody, signatureHeader, secrets, opts = {}) {
298
+ return verifyWebhook(rawBody, signatureHeader, secrets, opts);
299
+ }
297
300
  async function verifyWebhookAsync(rawBody, signatureHeader, secret, opts = {}) {
298
301
  const { secrets, sigs, message, bodyBytes } = prepareVerification(
299
302
  rawBody,
@@ -363,6 +366,74 @@ async function hmacHexSubtle(secret, message) {
363
366
  return hex;
364
367
  }
365
368
 
369
+ // src/environment.ts
370
+ var PRODUCTION_BASE_URL = "https://invo.network";
371
+ var SANDBOX_BASE_URL = "https://sandbox.invo.network/sandbox";
372
+ var DEMO_KEY_PREFIX = "ivsdk_demo_";
373
+ var KEY_ENVIRONMENT_PATH = "/api/sdk/key-environment";
374
+ var EnvironmentUnknownError = class extends Error {
375
+ constructor(message) {
376
+ super(message);
377
+ this.name = "EnvironmentUnknownError";
378
+ }
379
+ };
380
+ function isDemoKey(gameSecret) {
381
+ return typeof gameSecret === "string" && gameSecret.startsWith(DEMO_KEY_PREFIX);
382
+ }
383
+ var cache = /* @__PURE__ */ new Map();
384
+ async function ask(baseUrl, gameSecret, fetchImpl) {
385
+ let res;
386
+ try {
387
+ res = await fetchImpl(baseUrl + KEY_ENVIRONMENT_PATH, {
388
+ method: "GET",
389
+ headers: { "X-Game-Secret-Key": gameSecret, Accept: "application/json" },
390
+ redirect: "error"
391
+ });
392
+ } catch {
393
+ throw new EnvironmentUnknownError("Could not reach INVO to check the key.");
394
+ }
395
+ if (res.status === 401 || res.status === 403 || res.status === 404) return null;
396
+ if (!res.ok) throw new EnvironmentUnknownError(`INVO answered ${res.status} while checking the key.`);
397
+ const body = await res.json().catch(() => ({}));
398
+ return body.environment === "production" || body.environment === "sandbox" ? body.environment : null;
399
+ }
400
+ function resolveEnvironment(gameSecret, opts = {}) {
401
+ if (!gameSecret) return Promise.reject(new Error("A game secret is required."));
402
+ if (isDemoKey(gameSecret)) return Promise.resolve("sandbox");
403
+ const hit = cache.get(gameSecret);
404
+ if (hit) return hit;
405
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
406
+ const p = (async () => {
407
+ let prodError = null;
408
+ let env = null;
409
+ try {
410
+ env = await ask(PRODUCTION_BASE_URL, gameSecret, fetchImpl);
411
+ } catch (err) {
412
+ prodError = err;
413
+ }
414
+ if (!env) {
415
+ try {
416
+ env = await ask(SANDBOX_BASE_URL, gameSecret, fetchImpl);
417
+ } catch (err) {
418
+ throw prodError ?? err;
419
+ }
420
+ }
421
+ if (!env && prodError) throw prodError;
422
+ if (!env) {
423
+ throw new EnvironmentUnknownError(
424
+ "Neither INVO production nor the INVO sandbox recognises this key. Check INVO_GAME_SECRET in your secrets."
425
+ );
426
+ }
427
+ return env;
428
+ })();
429
+ cache.set(gameSecret, p);
430
+ p.catch(() => cache.delete(gameSecret));
431
+ return p;
432
+ }
433
+ async function baseUrlForKey(gameSecret, opts = {}) {
434
+ return await resolveEnvironment(gameSecret, opts) === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL;
435
+ }
436
+
366
437
  // src/server.ts
367
438
  var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
368
439
  var MAX_USD_AMOUNT = 999999.99;
@@ -3676,6 +3747,6 @@ var InvoServer = class {
3676
3747
  }
3677
3748
  };
3678
3749
 
3679
- export { CardsServer, InvoServer, PayoutsServer, PlatformCommerceServer, SandboxServer, SandboxSubscriptionsServer, SubscriptionsServer, createWebhookHandler, isRefundPendingApproval, verifyWebhook, verifyWebhookAsync };
3680
- //# sourceMappingURL=chunk-2DYTV74W.js.map
3681
- //# sourceMappingURL=chunk-2DYTV74W.js.map
3750
+ export { CardsServer, DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, PayoutsServer, PlatformCommerceServer, SANDBOX_BASE_URL, SandboxServer, SandboxSubscriptionsServer, SubscriptionsServer, baseUrlForKey, createWebhookHandler, isDemoKey, isRefundPendingApproval, resolveEnvironment, verifyInvoSignature, verifyWebhook, verifyWebhookAsync };
3751
+ //# sourceMappingURL=chunk-FJR44FKW.js.map
3752
+ //# sourceMappingURL=chunk-FJR44FKW.js.map
@@ -0,0 +1,6 @@
1
+ // src/version.ts
2
+ var SDK_VERSION = "3.29.0";
3
+
4
+ export { SDK_VERSION };
5
+ //# sourceMappingURL=chunk-KZJABBVT.js.map
6
+ //# sourceMappingURL=chunk-KZJABBVT.js.map
@@ -26,6 +26,74 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
26
26
 
27
27
  // src/game/server.ts
28
28
 
29
+ // src/environment.ts
30
+ var PRODUCTION_BASE_URL = "https://invo.network";
31
+ var SANDBOX_BASE_URL = "https://sandbox.invo.network/sandbox";
32
+ var DEMO_KEY_PREFIX = "ivsdk_demo_";
33
+ var KEY_ENVIRONMENT_PATH = "/api/sdk/key-environment";
34
+ var EnvironmentUnknownError = class extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "EnvironmentUnknownError";
38
+ }
39
+ };
40
+ function isDemoKey(gameSecret) {
41
+ return typeof gameSecret === "string" && gameSecret.startsWith(DEMO_KEY_PREFIX);
42
+ }
43
+ var cache = /* @__PURE__ */ new Map();
44
+ async function ask(baseUrl, gameSecret, fetchImpl) {
45
+ let res;
46
+ try {
47
+ res = await fetchImpl(baseUrl + KEY_ENVIRONMENT_PATH, {
48
+ method: "GET",
49
+ headers: { "X-Game-Secret-Key": gameSecret, Accept: "application/json" },
50
+ redirect: "error"
51
+ });
52
+ } catch {
53
+ throw new EnvironmentUnknownError("Could not reach INVO to check the key.");
54
+ }
55
+ if (res.status === 401 || res.status === 403 || res.status === 404) return null;
56
+ if (!res.ok) throw new EnvironmentUnknownError(`INVO answered ${res.status} while checking the key.`);
57
+ const body = await res.json().catch(() => ({}));
58
+ return body.environment === "production" || body.environment === "sandbox" ? body.environment : null;
59
+ }
60
+ function resolveEnvironment(gameSecret, opts = {}) {
61
+ if (!gameSecret) return Promise.reject(new Error("A game secret is required."));
62
+ if (isDemoKey(gameSecret)) return Promise.resolve("sandbox");
63
+ const hit = cache.get(gameSecret);
64
+ if (hit) return hit;
65
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
66
+ const p = (async () => {
67
+ let prodError = null;
68
+ let env = null;
69
+ try {
70
+ env = await ask(PRODUCTION_BASE_URL, gameSecret, fetchImpl);
71
+ } catch (err) {
72
+ prodError = err;
73
+ }
74
+ if (!env) {
75
+ try {
76
+ env = await ask(SANDBOX_BASE_URL, gameSecret, fetchImpl);
77
+ } catch (err) {
78
+ throw prodError ?? err;
79
+ }
80
+ }
81
+ if (!env && prodError) throw prodError;
82
+ if (!env) {
83
+ throw new EnvironmentUnknownError(
84
+ "Neither INVO production nor the INVO sandbox recognises this key. Check INVO_GAME_SECRET in your secrets."
85
+ );
86
+ }
87
+ return env;
88
+ })();
89
+ cache.set(gameSecret, p);
90
+ p.catch(() => cache.delete(gameSecret));
91
+ return p;
92
+ }
93
+ async function baseUrlForKey(gameSecret, opts = {}) {
94
+ return await resolveEnvironment(gameSecret, opts) === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL;
95
+ }
96
+
29
97
  // src/shared/errors.ts
30
98
  var LEGACY_NOT_PENDING_RE = /^transaction not pending\b|\bcannot be confirmed\b/i;
31
99
  var LEGACY_CURRENT_STATUS_RE = /\((?:current )?status:\s*([^)]+)\)/i;
@@ -1617,7 +1685,7 @@ function toPhoneChangeRequest(raw) {
1617
1685
  }
1618
1686
 
1619
1687
  // src/version.ts
1620
- var SDK_VERSION = "3.27.0";
1688
+ var SDK_VERSION = "3.29.0";
1621
1689
 
1622
1690
  // src/payouts.ts
1623
1691
  var AMOUNT = /^\d+(\.\d{1,2})?$/;
@@ -1899,6 +1967,9 @@ function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
1899
1967
  }
1900
1968
  return finalizeEvent(bodyBytes);
1901
1969
  }
1970
+ function verifyInvoSignature(rawBody, signatureHeader, secrets, opts = {}) {
1971
+ return verifyWebhook(rawBody, signatureHeader, secrets, opts);
1972
+ }
1902
1973
 
1903
1974
  // src/server.ts
1904
1975
  var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
@@ -5212,6 +5283,119 @@ var InvoServer = class {
5212
5283
  };
5213
5284
  }
5214
5285
  };
5286
+ var DEMO_EMAIL_DOMAIN = "demo.invo.network";
5287
+ var DEFAULT_PROJECT_FILE = ".invo/project.json";
5288
+ var PROJECT_ID = /^proj_[0-9A-HJKMNP-TV-Z]{26}$/;
5289
+ function newDemoProjectId(now = Date.now()) {
5290
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5291
+ let t = now;
5292
+ let time = "";
5293
+ for (let i = 0; i < 10; i++) {
5294
+ time = A[t % 32] + time;
5295
+ t = Math.floor(t / 32);
5296
+ }
5297
+ const bytes = crypto.randomBytes(16);
5298
+ let rand = "";
5299
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
5300
+ return "proj_" + time + rand;
5301
+ }
5302
+ function isValidProjectId(value) {
5303
+ return typeof value === "string" && PROJECT_ID.test(value);
5304
+ }
5305
+ function toDemoEmail(email, projectId) {
5306
+ if (!isValidProjectId(projectId)) throw new Error("A valid template project id is required.");
5307
+ const lower = email.trim().toLowerCase();
5308
+ if (lower.endsWith("@" + DEMO_EMAIL_DOMAIN)) return lower;
5309
+ const local = (lower.split("@")[0] ?? "player").replace(/[^a-z0-9._-]/g, "").slice(0, 24) || "player";
5310
+ const tag = crypto.createHash("sha256").update(lower).digest("hex").slice(0, 8);
5311
+ return `${local}-${tag}+${projectId.slice(5).toLowerCase()}@${DEMO_EMAIL_DOMAIN}`;
5312
+ }
5313
+ function demoPhoneFor(email) {
5314
+ const n = BigInt("0x" + crypto.createHash("sha256").update(email.trim().toLowerCase()).digest("hex")) % BigInt(100);
5315
+ return "+120255501" + n.toString().padStart(2, "0");
5316
+ }
5317
+ function hostOf(url) {
5318
+ if (!url) return void 0;
5319
+ try {
5320
+ return new URL(url).host.toLowerCase();
5321
+ } catch {
5322
+ return void 0;
5323
+ }
5324
+ }
5325
+ function readFile(file) {
5326
+ try {
5327
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
5328
+ return isValidProjectId(data.projectId) ? data : null;
5329
+ } catch {
5330
+ return null;
5331
+ }
5332
+ }
5333
+ function writeFile(file, data) {
5334
+ fs.mkdirSync(path.dirname(file), { recursive: true });
5335
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode: 384 });
5336
+ }
5337
+ function loadProject(opts = {}) {
5338
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
5339
+ if (opts.projectId) {
5340
+ if (!isValidProjectId(opts.projectId)) throw new Error('INVO_PROJECT_ID must be "proj_" + a 26-character ULID.');
5341
+ const saved2 = readFile(file);
5342
+ return saved2 && saved2.projectId === opts.projectId ? saved2 : { projectId: opts.projectId };
5343
+ }
5344
+ const host = hostOf(opts.publicUrl);
5345
+ const saved = readFile(file);
5346
+ if (saved && (!host || !saved.host || saved.host === host)) return saved;
5347
+ const fresh = { projectId: newDemoProjectId(), host };
5348
+ try {
5349
+ writeFile(file, fresh);
5350
+ } catch {
5351
+ }
5352
+ return fresh;
5353
+ }
5354
+ async function registerProject(opts) {
5355
+ if (!isDemoKey(opts.gameSecret)) throw new Error("registerProject is for the public demo key only.");
5356
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
5357
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
5358
+ const base = (opts.baseUrl ?? SANDBOX_BASE_URL).replace(/\/+$/, "");
5359
+ let project = loadProject({ file, publicUrl: opts.webhookUrl, projectId: opts.projectId });
5360
+ for (let attempt = 0; attempt < 2; attempt++) {
5361
+ const res = await fetchImpl(base + "/api/demo/projects/register", {
5362
+ method: "POST",
5363
+ redirect: "error",
5364
+ headers: {
5365
+ "Content-Type": "application/json",
5366
+ Accept: "application/json",
5367
+ "X-Game-Secret-Key": opts.gameSecret,
5368
+ "X-Invo-Project-Id": project.projectId,
5369
+ "X-Invo-Project-Host": hostOf(opts.webhookUrl) ?? ""
5370
+ },
5371
+ body: JSON.stringify({ webhook_url: opts.webhookUrl, registration_token: project.registrationToken })
5372
+ });
5373
+ const body = await res.json().catch(() => ({}));
5374
+ if (res.status === 409 && body.error_code === "PROJECT_REGISTERED" && attempt === 0 && !opts.projectId) {
5375
+ project = { projectId: newDemoProjectId(), host: hostOf(opts.webhookUrl) };
5376
+ continue;
5377
+ }
5378
+ if (!res.ok) throw new Error(`INVO demo registration failed (${res.status} ${body.error_code ?? ""}): ${body.error ?? ""}`.trim());
5379
+ const created = res.status === 201;
5380
+ if (created) {
5381
+ project = {
5382
+ projectId: project.projectId,
5383
+ host: hostOf(opts.webhookUrl),
5384
+ webhookUrl: opts.webhookUrl,
5385
+ webhookSecret: body.webhook?.signing_secret ?? project.webhookSecret,
5386
+ registrationToken: body.registration_token ?? project.registrationToken
5387
+ };
5388
+ } else {
5389
+ project = { ...project, host: project.host ?? hostOf(opts.webhookUrl), webhookUrl: opts.webhookUrl };
5390
+ }
5391
+ try {
5392
+ writeFile(file, project);
5393
+ } catch {
5394
+ }
5395
+ return { projectId: project.projectId, webhookSecret: project.webhookSecret ?? null, created };
5396
+ }
5397
+ throw new Error("INVO demo registration failed.");
5398
+ }
5215
5399
 
5216
5400
  // src/game/server.ts
5217
5401
  var MAX_BODY_BYTES = 1e6;
@@ -5405,9 +5589,12 @@ function createInvoGameServer(options) {
5405
5589
  const name = (rawName || email.split("@")[0] || "Player").slice(0, 64);
5406
5590
  const id = playerIdFor(email);
5407
5591
  const known = await store.read((s) => s.players[id] ?? null);
5408
- const phoneForInvo = phone ?? known?.phone ?? void 0;
5592
+ const demoPid = options.demoProjectId;
5593
+ const invoEmail = demoPid ? toDemoEmail(email, demoPid) : email;
5594
+ const phoneForInvo = demoPid ? demoPhoneFor(invoEmail) : phone ?? known?.phone ?? void 0;
5595
+ const storedPhone = demoPid ? null : phone;
5409
5596
  try {
5410
- await invo.mintPlayerToken({ playerEmail: email, playerPhone: phoneForInvo, playerName: name });
5597
+ await invo.mintPlayerToken({ playerEmail: invoEmail, playerPhone: phoneForInvo, playerName: name });
5411
5598
  } catch (err) {
5412
5599
  if (err instanceof InvoError && err.status === 404) {
5413
5600
  throw new GameServerError(400, "PHONE_REQUIRED", "First sign-in needs a phone number so INVO can create your account.");
@@ -5419,7 +5606,7 @@ function createInvoGameServer(options) {
5419
5606
  const expiresAt = new Date(now().getTime() + sessionTtlMs).toISOString();
5420
5607
  const player = await store.transact((s) => {
5421
5608
  const existing = s.players[id];
5422
- const record = existing ? { ...existing, name, phone: phone ?? existing.phone } : { id, email, phone, name, createdAt: iso() };
5609
+ const record = existing ? { ...existing, email: invoEmail, name, phone: storedPhone ?? existing.phone } : { id, email: invoEmail, phone: storedPhone, name, createdAt: iso() };
5423
5610
  s.players[id] = record;
5424
5611
  if (soft.starting > 0) {
5425
5612
  addLedger(s, { playerId: id, currency: "soft", amount: soft.starting, reason: "starting balance", ref: `start:${id}`, at: iso() });
@@ -5754,31 +5941,72 @@ function createInvoGameServer(options) {
5754
5941
  function invoGameServerFromEnv(options) {
5755
5942
  validateEconomy(options.economy);
5756
5943
  const env = options.env;
5757
- const sandbox = (env["INVO_ENV"] ?? "sandbox").toLowerCase() !== "production";
5758
- const baseUrl = env["INVO_BASE_URL"] || (sandbox ? "https://sandbox.invo.network/sandbox" : "https://invo.network");
5759
- const missing = ["INVO_GAME_SECRET", "INVO_WEBHOOK_SECRET"].filter((k) => !env[k]?.trim());
5944
+ const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
5945
+ const forced = env["INVO_ENV"]?.trim().toLowerCase();
5946
+ const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
5947
+ const state = { environment: known };
5948
+ const sandboxNow = () => state.environment === "sandbox";
5949
+ const envNow = () => state.environment ?? "resolving";
5950
+ const demo = isDemoKey(secret);
5951
+ const demoProject = demo ? loadProject({ file: options.projectFile ?? DEFAULT_PROJECT_FILE, publicUrl: env["PUBLIC_URL"], projectId: (options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0 }) : null;
5952
+ const webhookSecrets = (() => {
5953
+ const raw = options.webhookSecret ?? env["INVO_WEBHOOK_SECRET"] ?? demoProject?.webhookSecret ?? "";
5954
+ return (Array.isArray(raw) ? raw : raw.split(",")).map((s) => s.trim()).filter(Boolean);
5955
+ })();
5956
+ const missing = [
5957
+ ...secret ? [] : ["INVO_GAME_SECRET"],
5958
+ ...webhookSecrets.length ? [] : ["INVO_WEBHOOK_SECRET"]
5959
+ ];
5760
5960
  if (missing.length) {
5761
- return { server: setupRequiredServer(options.economy, missing, sandbox, options.basePath), missing, sandbox };
5961
+ return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow(), environment: envNow() };
5762
5962
  }
5763
5963
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
5764
- const projectId = sandbox ? options.projectId?.trim() : void 0;
5765
- const invoFetch = projectId ? (input, init) => {
5964
+ const projectId = demoProject?.projectId ?? ((options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0);
5965
+ const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
5966
+ const resolveNow = () => resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
5967
+ state.environment = e;
5968
+ return e;
5969
+ });
5970
+ if (!explicitBase && !known) resolveNow().catch(() => void 0);
5971
+ const invoFetch = async (input, init) => {
5972
+ let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
5973
+ if (!explicitBase) {
5974
+ const e = known ?? state.environment ?? await resolveNow();
5975
+ if (e === "sandbox" && url.startsWith(PRODUCTION_BASE_URL + "/")) url = SANDBOX_BASE_URL + url.slice(PRODUCTION_BASE_URL.length);
5976
+ }
5766
5977
  const headers = new Headers(init?.headers);
5767
- headers.set("X-Invo-Project-Id", projectId);
5768
- return baseFetch(input, { ...init, headers });
5769
- } : baseFetch;
5770
- const invo = new InvoServer({ gameSecret: env["INVO_GAME_SECRET"].trim(), baseUrl, fetch: invoFetch });
5771
- const server = createInvoGameServer({
5978
+ if (projectId) headers.set("X-Invo-Project-Id", projectId);
5979
+ return baseFetch(url, { ...init, headers });
5980
+ };
5981
+ const invo = new InvoServer({ gameSecret: secret, baseUrl: explicitBase || PRODUCTION_BASE_URL, fetch: invoFetch });
5982
+ const serverOptions = {
5772
5983
  invo,
5773
- webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
5984
+ webhookSecret: webhookSecrets,
5985
+ demoProjectId: demo ? projectId : void 0,
5774
5986
  economy: options.economy,
5775
5987
  store: options.store,
5776
- sandbox,
5988
+ get sandbox() {
5989
+ return sandboxNow();
5990
+ },
5777
5991
  basePath: options.basePath,
5778
5992
  publicUrl: env["PUBLIC_URL"] || void 0,
5779
5993
  log: options.log
5780
- });
5781
- return { server, missing, sandbox };
5994
+ };
5995
+ const server = createInvoGameServer(serverOptions);
5996
+ return { server, missing, sandbox: sandboxNow(), environment: envNow() };
5997
+ }
5998
+ function newProjectId(now = Date.now()) {
5999
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
6000
+ let t = now;
6001
+ let time = "";
6002
+ for (let i = 0; i < 10; i++) {
6003
+ time = A[t % 32] + time;
6004
+ t = Math.floor(t / 32);
6005
+ }
6006
+ const bytes = crypto.randomBytes(16);
6007
+ let rand = "";
6008
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
6009
+ return "proj_" + time + rand;
5782
6010
  }
5783
6011
  function setupRequiredServer(economy, missing, sandbox, basePathOpt) {
5784
6012
  const basePath = (basePathOpt ?? "/api/invo").replace(/\/+$/, "");
@@ -5886,18 +6114,18 @@ function createMemoryGameStore(initial) {
5886
6114
  function createFileGameStore(options) {
5887
6115
  const file = path__namespace.resolve(options.file);
5888
6116
  const queue = serial();
5889
- let cache;
6117
+ let cache2;
5890
6118
  async function load() {
5891
- if (cache) return cache;
6119
+ if (cache2) return cache2;
5892
6120
  try {
5893
6121
  const text = await fs.promises.readFile(file, "utf8");
5894
6122
  const parsed = JSON.parse(text);
5895
- cache = { ...emptyGameState(), ...parsed, version: 1 };
6123
+ cache2 = { ...emptyGameState(), ...parsed, version: 1 };
5896
6124
  } catch (err) {
5897
6125
  if (err.code !== "ENOENT") throw err;
5898
- cache = emptyGameState();
6126
+ cache2 = emptyGameState();
5899
6127
  }
5900
- return cache;
6128
+ return cache2;
5901
6129
  }
5902
6130
  async function save(state) {
5903
6131
  await fs.promises.mkdir(path__namespace.dirname(file), { recursive: true });
@@ -5911,23 +6139,39 @@ function createFileGameStore(options) {
5911
6139
  const draft = clone(await load());
5912
6140
  const out = fn(draft);
5913
6141
  await save(draft);
5914
- cache = draft;
6142
+ cache2 = draft;
5915
6143
  return out;
5916
6144
  })
5917
6145
  };
5918
6146
  }
5919
6147
 
6148
+ exports.DEFAULT_PROJECT_FILE = DEFAULT_PROJECT_FILE;
6149
+ exports.DEMO_EMAIL_DOMAIN = DEMO_EMAIL_DOMAIN;
6150
+ exports.DEMO_KEY_PREFIX = DEMO_KEY_PREFIX;
6151
+ exports.EnvironmentUnknownError = EnvironmentUnknownError;
5920
6152
  exports.GameServerError = GameServerError;
5921
6153
  exports.InvoError = InvoError;
5922
6154
  exports.InvoServer = InvoServer;
6155
+ exports.PRODUCTION_BASE_URL = PRODUCTION_BASE_URL;
6156
+ exports.SANDBOX_BASE_URL = SANDBOX_BASE_URL;
5923
6157
  exports.SDK_VERSION = SDK_VERSION;
6158
+ exports.baseUrlForKey = baseUrlForKey;
5924
6159
  exports.createFileGameStore = createFileGameStore;
5925
6160
  exports.createInvoGameServer = createInvoGameServer;
5926
6161
  exports.createMemoryGameStore = createMemoryGameStore;
6162
+ exports.demoPhoneFor = demoPhoneFor;
5927
6163
  exports.emptyGameState = emptyGameState;
5928
6164
  exports.invoGameServerFromEnv = invoGameServerFromEnv;
6165
+ exports.isDemoKey = isDemoKey;
6166
+ exports.isValidProjectId = isValidProjectId;
6167
+ exports.loadProject = loadProject;
6168
+ exports.newProjectId = newProjectId;
5929
6169
  exports.playerIdFor = playerIdFor;
6170
+ exports.registerProject = registerProject;
6171
+ exports.resolveEnvironment = resolveEnvironment;
6172
+ exports.toDemoEmail = toDemoEmail;
5930
6173
  exports.toNodeListener = toNodeListener;
5931
6174
  exports.validateEconomy = validateEconomy;
6175
+ exports.verifyInvoSignature = verifyInvoSignature;
5932
6176
  //# sourceMappingURL=game-server.cjs.map
5933
6177
  //# sourceMappingURL=game-server.cjs.map