@invonetwork/web-sdk 3.27.0 → 3.28.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.
@@ -0,0 +1,6 @@
1
+ // src/version.ts
2
+ var SDK_VERSION = "3.28.0";
3
+
4
+ export { SDK_VERSION };
5
+ //# sourceMappingURL=chunk-3DRWLDDF.js.map
6
+ //# sourceMappingURL=chunk-3DRWLDDF.js.map
@@ -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-3DRWLDDF.js';
3
3
  import { InvoError, buildGameEventBody, toReportGameEventResult } from './chunk-VP3OK4J4.js';
4
4
  import { createHmac, timingSafeEqual } from 'crypto';
5
5
 
@@ -363,6 +363,60 @@ async function hmacHexSubtle(secret, message) {
363
363
  return hex;
364
364
  }
365
365
 
366
+ // src/environment.ts
367
+ var PRODUCTION_BASE_URL = "https://invo.network";
368
+ var SANDBOX_BASE_URL = "https://sandbox.invo.network/sandbox";
369
+ var DEMO_KEY_PREFIX = "ivsdk_demo_";
370
+ var KEY_ENVIRONMENT_PATH = "/api/sdk/key-environment";
371
+ var EnvironmentUnknownError = class extends Error {
372
+ constructor(message) {
373
+ super(message);
374
+ this.name = "EnvironmentUnknownError";
375
+ }
376
+ };
377
+ function isDemoKey(gameSecret) {
378
+ return typeof gameSecret === "string" && gameSecret.startsWith(DEMO_KEY_PREFIX);
379
+ }
380
+ var cache = /* @__PURE__ */ new Map();
381
+ async function ask(baseUrl, gameSecret, fetchImpl) {
382
+ let res;
383
+ try {
384
+ res = await fetchImpl(baseUrl + KEY_ENVIRONMENT_PATH, {
385
+ method: "GET",
386
+ headers: { "X-Game-Secret-Key": gameSecret, Accept: "application/json" },
387
+ redirect: "error"
388
+ });
389
+ } catch {
390
+ throw new EnvironmentUnknownError("Could not reach INVO to check the key.");
391
+ }
392
+ if (res.status === 401 || res.status === 403 || res.status === 404) return null;
393
+ if (!res.ok) throw new EnvironmentUnknownError(`INVO answered ${res.status} while checking the key.`);
394
+ const body = await res.json().catch(() => ({}));
395
+ return body.environment === "production" || body.environment === "sandbox" ? body.environment : null;
396
+ }
397
+ function resolveEnvironment(gameSecret, opts = {}) {
398
+ if (!gameSecret) return Promise.reject(new Error("A game secret is required."));
399
+ if (isDemoKey(gameSecret)) return Promise.resolve("sandbox");
400
+ const hit = cache.get(gameSecret);
401
+ if (hit) return hit;
402
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
403
+ const p = (async () => {
404
+ const env = await ask(PRODUCTION_BASE_URL, gameSecret, fetchImpl) ?? await ask(SANDBOX_BASE_URL, gameSecret, fetchImpl);
405
+ if (!env) {
406
+ throw new EnvironmentUnknownError(
407
+ "Neither INVO production nor the INVO sandbox recognises this key. Check INVO_GAME_SECRET in your secrets."
408
+ );
409
+ }
410
+ return env;
411
+ })();
412
+ cache.set(gameSecret, p);
413
+ p.catch(() => cache.delete(gameSecret));
414
+ return p;
415
+ }
416
+ async function baseUrlForKey(gameSecret, opts = {}) {
417
+ return await resolveEnvironment(gameSecret, opts) === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL;
418
+ }
419
+
366
420
  // src/server.ts
367
421
  var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
368
422
  var MAX_USD_AMOUNT = 999999.99;
@@ -3676,6 +3730,6 @@ var InvoServer = class {
3676
3730
  }
3677
3731
  };
3678
3732
 
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
3733
+ export { CardsServer, DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, PayoutsServer, PlatformCommerceServer, SANDBOX_BASE_URL, SandboxServer, SandboxSubscriptionsServer, SubscriptionsServer, baseUrlForKey, createWebhookHandler, isDemoKey, isRefundPendingApproval, resolveEnvironment, verifyWebhook, verifyWebhookAsync };
3734
+ //# sourceMappingURL=chunk-4YKTKXC5.js.map
3735
+ //# sourceMappingURL=chunk-4YKTKXC5.js.map
@@ -26,6 +26,60 @@ 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
+ const env = await ask(PRODUCTION_BASE_URL, gameSecret, fetchImpl) ?? await ask(SANDBOX_BASE_URL, gameSecret, fetchImpl);
68
+ if (!env) {
69
+ throw new EnvironmentUnknownError(
70
+ "Neither INVO production nor the INVO sandbox recognises this key. Check INVO_GAME_SECRET in your secrets."
71
+ );
72
+ }
73
+ return env;
74
+ })();
75
+ cache.set(gameSecret, p);
76
+ p.catch(() => cache.delete(gameSecret));
77
+ return p;
78
+ }
79
+ async function baseUrlForKey(gameSecret, opts = {}) {
80
+ return await resolveEnvironment(gameSecret, opts) === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL;
81
+ }
82
+
29
83
  // src/shared/errors.ts
30
84
  var LEGACY_NOT_PENDING_RE = /^transaction not pending\b|\bcannot be confirmed\b/i;
31
85
  var LEGACY_CURRENT_STATUS_RE = /\((?:current )?status:\s*([^)]+)\)/i;
@@ -1617,7 +1671,7 @@ function toPhoneChangeRequest(raw) {
1617
1671
  }
1618
1672
 
1619
1673
  // src/version.ts
1620
- var SDK_VERSION = "3.27.0";
1674
+ var SDK_VERSION = "3.28.0";
1621
1675
 
1622
1676
  // src/payouts.ts
1623
1677
  var AMOUNT = /^\d+(\.\d{1,2})?$/;
@@ -5754,31 +5808,61 @@ function createInvoGameServer(options) {
5754
5808
  function invoGameServerFromEnv(options) {
5755
5809
  validateEconomy(options.economy);
5756
5810
  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");
5811
+ const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
5812
+ const forced = env["INVO_ENV"]?.trim().toLowerCase();
5813
+ const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
5814
+ const state = { environment: known };
5815
+ const sandboxNow = () => state.environment !== "production";
5759
5816
  const missing = ["INVO_GAME_SECRET", "INVO_WEBHOOK_SECRET"].filter((k) => !env[k]?.trim());
5760
5817
  if (missing.length) {
5761
- return { server: setupRequiredServer(options.economy, missing, sandbox, options.basePath), missing, sandbox };
5818
+ return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow() };
5762
5819
  }
5763
5820
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
5764
- const projectId = sandbox ? options.projectId?.trim() : void 0;
5765
- const invoFetch = projectId ? (input, init) => {
5821
+ const projectId = (options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0;
5822
+ const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
5823
+ const resolved = explicitBase || known ? null : resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
5824
+ state.environment = e;
5825
+ return e;
5826
+ });
5827
+ resolved?.catch(() => void 0);
5828
+ const invoFetch = async (input, init) => {
5829
+ let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
5830
+ if (!explicitBase) {
5831
+ const e = known ?? await resolved;
5832
+ if (e === "sandbox" && url.startsWith(PRODUCTION_BASE_URL + "/")) url = SANDBOX_BASE_URL + url.slice(PRODUCTION_BASE_URL.length);
5833
+ }
5766
5834
  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({
5835
+ if (projectId) headers.set("X-Invo-Project-Id", projectId);
5836
+ return baseFetch(url, { ...init, headers });
5837
+ };
5838
+ const invo = new InvoServer({ gameSecret: secret, baseUrl: explicitBase || PRODUCTION_BASE_URL, fetch: invoFetch });
5839
+ const serverOptions = {
5772
5840
  invo,
5773
5841
  webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
5774
5842
  economy: options.economy,
5775
5843
  store: options.store,
5776
- sandbox,
5844
+ get sandbox() {
5845
+ return sandboxNow();
5846
+ },
5777
5847
  basePath: options.basePath,
5778
5848
  publicUrl: env["PUBLIC_URL"] || void 0,
5779
5849
  log: options.log
5780
- });
5781
- return { server, missing, sandbox };
5850
+ };
5851
+ const server = createInvoGameServer(serverOptions);
5852
+ return { server, missing, sandbox: sandboxNow() };
5853
+ }
5854
+ function newProjectId(now = Date.now()) {
5855
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5856
+ let t = now;
5857
+ let time = "";
5858
+ for (let i = 0; i < 10; i++) {
5859
+ time = A[t % 32] + time;
5860
+ t = Math.floor(t / 32);
5861
+ }
5862
+ const bytes = crypto.randomBytes(16);
5863
+ let rand = "";
5864
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
5865
+ return "proj_" + time + rand;
5782
5866
  }
5783
5867
  function setupRequiredServer(economy, missing, sandbox, basePathOpt) {
5784
5868
  const basePath = (basePathOpt ?? "/api/invo").replace(/\/+$/, "");
@@ -5886,18 +5970,18 @@ function createMemoryGameStore(initial) {
5886
5970
  function createFileGameStore(options) {
5887
5971
  const file = path__namespace.resolve(options.file);
5888
5972
  const queue = serial();
5889
- let cache;
5973
+ let cache2;
5890
5974
  async function load() {
5891
- if (cache) return cache;
5975
+ if (cache2) return cache2;
5892
5976
  try {
5893
5977
  const text = await fs.promises.readFile(file, "utf8");
5894
5978
  const parsed = JSON.parse(text);
5895
- cache = { ...emptyGameState(), ...parsed, version: 1 };
5979
+ cache2 = { ...emptyGameState(), ...parsed, version: 1 };
5896
5980
  } catch (err) {
5897
5981
  if (err.code !== "ENOENT") throw err;
5898
- cache = emptyGameState();
5982
+ cache2 = emptyGameState();
5899
5983
  }
5900
- return cache;
5984
+ return cache2;
5901
5985
  }
5902
5986
  async function save(state) {
5903
5987
  await fs.promises.mkdir(path__namespace.dirname(file), { recursive: true });
@@ -5911,22 +5995,30 @@ function createFileGameStore(options) {
5911
5995
  const draft = clone(await load());
5912
5996
  const out = fn(draft);
5913
5997
  await save(draft);
5914
- cache = draft;
5998
+ cache2 = draft;
5915
5999
  return out;
5916
6000
  })
5917
6001
  };
5918
6002
  }
5919
6003
 
6004
+ exports.DEMO_KEY_PREFIX = DEMO_KEY_PREFIX;
6005
+ exports.EnvironmentUnknownError = EnvironmentUnknownError;
5920
6006
  exports.GameServerError = GameServerError;
5921
6007
  exports.InvoError = InvoError;
5922
6008
  exports.InvoServer = InvoServer;
6009
+ exports.PRODUCTION_BASE_URL = PRODUCTION_BASE_URL;
6010
+ exports.SANDBOX_BASE_URL = SANDBOX_BASE_URL;
5923
6011
  exports.SDK_VERSION = SDK_VERSION;
6012
+ exports.baseUrlForKey = baseUrlForKey;
5924
6013
  exports.createFileGameStore = createFileGameStore;
5925
6014
  exports.createInvoGameServer = createInvoGameServer;
5926
6015
  exports.createMemoryGameStore = createMemoryGameStore;
5927
6016
  exports.emptyGameState = emptyGameState;
5928
6017
  exports.invoGameServerFromEnv = invoGameServerFromEnv;
6018
+ exports.isDemoKey = isDemoKey;
6019
+ exports.newProjectId = newProjectId;
5929
6020
  exports.playerIdFor = playerIdFor;
6021
+ exports.resolveEnvironment = resolveEnvironment;
5930
6022
  exports.toNodeListener = toNodeListener;
5931
6023
  exports.validateEconomy = validateEconomy;
5932
6024
  //# sourceMappingURL=game-server.cjs.map
@@ -1,8 +1,9 @@
1
1
  import { InvoServer } from './server.cjs';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoEnvironment, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment } from './server.cjs';
2
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-CoW9LopI.cjs';
3
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameWallet } from './types-CoW9LopI.cjs';
4
5
  export { I as InvoError } from './types-_lIm74kd.cjs';
5
- export { S as SDK_VERSION } from './version-BXFwI0-s.cjs';
6
+ export { S as SDK_VERSION } from './version-iWmcxjYu.cjs';
6
7
 
7
8
  interface StoredPlayer {
8
9
  id: string;
@@ -135,9 +136,11 @@ interface InvoGameServerFromEnvOptions {
135
136
  basePath?: string;
136
137
  log?: InvoGameServerOptions["log"];
137
138
  /**
138
- * A stable id for this copy of the game (e.g. one per Replit fork), sent to INVO's sandbox
139
- * as the `X-Invo-Project-Id` header so sandbox activity can be told apart per project and
140
- * carried over when the project goes live. Not sent in production. Not a secret.
139
+ * A stable id for this copy of the game (e.g. one per Replit fork): `proj_` + a 26-character
140
+ * uppercase ULID (see {@link newProjectId}). Sent to INVO as the `X-Invo-Project-Id` header on
141
+ * every call, so sandbox activity is told apart per project, and so the first live call after
142
+ * go-live links the project to your INVO account. Required with the public demo key. Not a
143
+ * secret. `INVO_PROJECT_ID` in `env` is used when this is not given.
141
144
  */
142
145
  projectId?: string;
143
146
  /** Override `fetch` for the calls to INVO (tests, proxies). */
@@ -156,13 +159,18 @@ interface InvoGameServerSetup {
156
159
  * `503 INVO_SETUP_REQUIRED` naming what to add, `/health` and `/catalog` keep working, and the
157
160
  * game itself stays playable.
158
161
  *
159
- * - `INVO_GAME_SECRET` (required): the game secret for this environment, from the INVO console
162
+ * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
163
+ * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
164
+ * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
160
165
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
161
- * - `INVO_ENV`: `sandbox` (default) or `production`
166
+ * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
167
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
162
168
  * - `INVO_BASE_URL`: override the API base (rarely needed)
163
169
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
164
170
  */
165
171
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
172
+ /** A new template project id: `proj_` + a 26-character uppercase Crockford ULID. */
173
+ declare function newProjectId(now?: number): string;
166
174
  /** The parts of Node's `IncomingMessage` the adapter reads. */
167
175
  interface NodeRequestLike {
168
176
  method?: string;
@@ -182,4 +190,4 @@ interface NodeResponseLike {
182
190
  */
183
191
  declare function toNodeListener(server: InvoGameServer, fallback?: (req: NodeRequestLike, res: NodeResponseLike) => unknown): (req: NodeRequestLike, res: NodeResponseLike) => Promise<void>;
184
192
 
185
- export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
193
+ export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, newProjectId, playerIdFor, toNodeListener, validateEconomy };
@@ -1,8 +1,9 @@
1
1
  import { InvoServer } from './server.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoEnvironment, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment } from './server.js';
2
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-CoW9LopI.js';
3
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameWallet } from './types-CoW9LopI.js';
4
5
  export { I as InvoError } from './types-_lIm74kd.js';
5
- export { S as SDK_VERSION } from './version-BXFwI0-s.js';
6
+ export { S as SDK_VERSION } from './version-iWmcxjYu.js';
6
7
 
7
8
  interface StoredPlayer {
8
9
  id: string;
@@ -135,9 +136,11 @@ interface InvoGameServerFromEnvOptions {
135
136
  basePath?: string;
136
137
  log?: InvoGameServerOptions["log"];
137
138
  /**
138
- * A stable id for this copy of the game (e.g. one per Replit fork), sent to INVO's sandbox
139
- * as the `X-Invo-Project-Id` header so sandbox activity can be told apart per project and
140
- * carried over when the project goes live. Not sent in production. Not a secret.
139
+ * A stable id for this copy of the game (e.g. one per Replit fork): `proj_` + a 26-character
140
+ * uppercase ULID (see {@link newProjectId}). Sent to INVO as the `X-Invo-Project-Id` header on
141
+ * every call, so sandbox activity is told apart per project, and so the first live call after
142
+ * go-live links the project to your INVO account. Required with the public demo key. Not a
143
+ * secret. `INVO_PROJECT_ID` in `env` is used when this is not given.
141
144
  */
142
145
  projectId?: string;
143
146
  /** Override `fetch` for the calls to INVO (tests, proxies). */
@@ -156,13 +159,18 @@ interface InvoGameServerSetup {
156
159
  * `503 INVO_SETUP_REQUIRED` naming what to add, `/health` and `/catalog` keep working, and the
157
160
  * game itself stays playable.
158
161
  *
159
- * - `INVO_GAME_SECRET` (required): the game secret for this environment, from the INVO console
162
+ * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
163
+ * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
164
+ * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
160
165
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
161
- * - `INVO_ENV`: `sandbox` (default) or `production`
166
+ * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
167
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
162
168
  * - `INVO_BASE_URL`: override the API base (rarely needed)
163
169
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
164
170
  */
165
171
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
172
+ /** A new template project id: `proj_` + a 26-character uppercase Crockford ULID. */
173
+ declare function newProjectId(now?: number): string;
166
174
  /** The parts of Node's `IncomingMessage` the adapter reads. */
167
175
  interface NodeRequestLike {
168
176
  method?: string;
@@ -182,4 +190,4 @@ interface NodeResponseLike {
182
190
  */
183
191
  declare function toNodeListener(server: InvoGameServer, fallback?: (req: NodeRequestLike, res: NodeResponseLike) => unknown): (req: NodeRequestLike, res: NodeResponseLike) => Promise<void>;
184
192
 
185
- export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
193
+ export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, newProjectId, playerIdFor, toNodeListener, validateEconomy };
@@ -1,7 +1,7 @@
1
- import { InvoServer, verifyWebhook } from './chunk-2DYTV74W.js';
2
- export { InvoServer } from './chunk-2DYTV74W.js';
1
+ import { isDemoKey, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, resolveEnvironment, InvoServer, verifyWebhook } from './chunk-4YKTKXC5.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment } from './chunk-4YKTKXC5.js';
3
3
  import './chunk-6CN236QH.js';
4
- export { SDK_VERSION } from './chunk-3YDO7GSH.js';
4
+ export { SDK_VERSION } from './chunk-3DRWLDDF.js';
5
5
  import { InvoError } from './chunk-VP3OK4J4.js';
6
6
  export { InvoError } from './chunk-VP3OK4J4.js';
7
7
  import { createHash, randomBytes } from 'crypto';
@@ -548,31 +548,61 @@ function createInvoGameServer(options) {
548
548
  function invoGameServerFromEnv(options) {
549
549
  validateEconomy(options.economy);
550
550
  const env = options.env;
551
- const sandbox = (env["INVO_ENV"] ?? "sandbox").toLowerCase() !== "production";
552
- const baseUrl = env["INVO_BASE_URL"] || (sandbox ? "https://sandbox.invo.network/sandbox" : "https://invo.network");
551
+ const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
552
+ const forced = env["INVO_ENV"]?.trim().toLowerCase();
553
+ const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
554
+ const state = { environment: known };
555
+ const sandboxNow = () => state.environment !== "production";
553
556
  const missing = ["INVO_GAME_SECRET", "INVO_WEBHOOK_SECRET"].filter((k) => !env[k]?.trim());
554
557
  if (missing.length) {
555
- return { server: setupRequiredServer(options.economy, missing, sandbox, options.basePath), missing, sandbox };
558
+ return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow() };
556
559
  }
557
560
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
558
- const projectId = sandbox ? options.projectId?.trim() : void 0;
559
- const invoFetch = projectId ? (input, init) => {
561
+ const projectId = (options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0;
562
+ const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
563
+ const resolved = explicitBase || known ? null : resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
564
+ state.environment = e;
565
+ return e;
566
+ });
567
+ resolved?.catch(() => void 0);
568
+ const invoFetch = async (input, init) => {
569
+ let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
570
+ if (!explicitBase) {
571
+ const e = known ?? await resolved;
572
+ if (e === "sandbox" && url.startsWith(PRODUCTION_BASE_URL + "/")) url = SANDBOX_BASE_URL + url.slice(PRODUCTION_BASE_URL.length);
573
+ }
560
574
  const headers = new Headers(init?.headers);
561
- headers.set("X-Invo-Project-Id", projectId);
562
- return baseFetch(input, { ...init, headers });
563
- } : baseFetch;
564
- const invo = new InvoServer({ gameSecret: env["INVO_GAME_SECRET"].trim(), baseUrl, fetch: invoFetch });
565
- const server = createInvoGameServer({
575
+ if (projectId) headers.set("X-Invo-Project-Id", projectId);
576
+ return baseFetch(url, { ...init, headers });
577
+ };
578
+ const invo = new InvoServer({ gameSecret: secret, baseUrl: explicitBase || PRODUCTION_BASE_URL, fetch: invoFetch });
579
+ const serverOptions = {
566
580
  invo,
567
581
  webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
568
582
  economy: options.economy,
569
583
  store: options.store,
570
- sandbox,
584
+ get sandbox() {
585
+ return sandboxNow();
586
+ },
571
587
  basePath: options.basePath,
572
588
  publicUrl: env["PUBLIC_URL"] || void 0,
573
589
  log: options.log
574
- });
575
- return { server, missing, sandbox };
590
+ };
591
+ const server = createInvoGameServer(serverOptions);
592
+ return { server, missing, sandbox: sandboxNow() };
593
+ }
594
+ function newProjectId(now = Date.now()) {
595
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
596
+ let t = now;
597
+ let time = "";
598
+ for (let i = 0; i < 10; i++) {
599
+ time = A[t % 32] + time;
600
+ t = Math.floor(t / 32);
601
+ }
602
+ const bytes = randomBytes(16);
603
+ let rand = "";
604
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
605
+ return "proj_" + time + rand;
576
606
  }
577
607
  function setupRequiredServer(economy, missing, sandbox, basePathOpt) {
578
608
  const basePath = (basePathOpt ?? "/api/invo").replace(/\/+$/, "");
@@ -711,6 +741,6 @@ function createFileGameStore(options) {
711
741
  };
712
742
  }
713
743
 
714
- export { GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
744
+ export { GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, newProjectId, playerIdFor, toNodeListener, validateEconomy };
715
745
  //# sourceMappingURL=game-server.js.map
716
746
  //# sourceMappingURL=game-server.js.map
package/dist/game.cjs CHANGED
@@ -2162,7 +2162,7 @@ function mountInvoUI(container, economy, options = {}) {
2162
2162
  }
2163
2163
 
2164
2164
  // src/version.ts
2165
- var SDK_VERSION = "3.27.0";
2165
+ var SDK_VERSION = "3.28.0";
2166
2166
 
2167
2167
  exports.InvoGameEconomy = InvoGameEconomy;
2168
2168
  exports.InvoGameError = InvoGameError;
package/dist/game.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as GamePlayer, m as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, d as GameCatalogItem, f as GameCurrencyBalance } from './types-CoW9LopI.cjs';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-CoW9LopI.cjs';
3
- export { S as SDK_VERSION } from './version-BXFwI0-s.cjs';
3
+ export { S as SDK_VERSION } from './version-iWmcxjYu.cjs';
4
4
 
5
5
  /**
6
6
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as GamePlayer, m as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, d as GameCatalogItem, f as GameCurrencyBalance } from './types-CoW9LopI.js';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-CoW9LopI.js';
3
- export { S as SDK_VERSION } from './version-BXFwI0-s.js';
3
+ export { S as SDK_VERSION } from './version-iWmcxjYu.js';
4
4
 
5
5
  /**
6
6
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.js CHANGED
@@ -1,4 +1,4 @@
1
- export { SDK_VERSION } from './chunk-3YDO7GSH.js';
1
+ export { SDK_VERSION } from './chunk-3DRWLDDF.js';
2
2
  import { newEventId } from './chunk-VP3OK4J4.js';
3
3
 
4
4
  // src/game/client.ts
package/dist/server.cjs CHANGED
@@ -1593,7 +1593,7 @@ function toPhoneChangeRequest(raw) {
1593
1593
  }
1594
1594
 
1595
1595
  // src/version.ts
1596
- var SDK_VERSION = "3.27.0";
1596
+ var SDK_VERSION = "3.28.0";
1597
1597
 
1598
1598
  // src/payouts.ts
1599
1599
  var AMOUNT = /^\d+(\.\d{1,2})?$/;
@@ -1955,6 +1955,60 @@ async function hmacHexSubtle(secret, message) {
1955
1955
  return hex;
1956
1956
  }
1957
1957
 
1958
+ // src/environment.ts
1959
+ var PRODUCTION_BASE_URL = "https://invo.network";
1960
+ var SANDBOX_BASE_URL = "https://sandbox.invo.network/sandbox";
1961
+ var DEMO_KEY_PREFIX = "ivsdk_demo_";
1962
+ var KEY_ENVIRONMENT_PATH = "/api/sdk/key-environment";
1963
+ var EnvironmentUnknownError = class extends Error {
1964
+ constructor(message) {
1965
+ super(message);
1966
+ this.name = "EnvironmentUnknownError";
1967
+ }
1968
+ };
1969
+ function isDemoKey(gameSecret) {
1970
+ return typeof gameSecret === "string" && gameSecret.startsWith(DEMO_KEY_PREFIX);
1971
+ }
1972
+ var cache = /* @__PURE__ */ new Map();
1973
+ async function ask(baseUrl, gameSecret, fetchImpl) {
1974
+ let res;
1975
+ try {
1976
+ res = await fetchImpl(baseUrl + KEY_ENVIRONMENT_PATH, {
1977
+ method: "GET",
1978
+ headers: { "X-Game-Secret-Key": gameSecret, Accept: "application/json" },
1979
+ redirect: "error"
1980
+ });
1981
+ } catch {
1982
+ throw new EnvironmentUnknownError("Could not reach INVO to check the key.");
1983
+ }
1984
+ if (res.status === 401 || res.status === 403 || res.status === 404) return null;
1985
+ if (!res.ok) throw new EnvironmentUnknownError(`INVO answered ${res.status} while checking the key.`);
1986
+ const body = await res.json().catch(() => ({}));
1987
+ return body.environment === "production" || body.environment === "sandbox" ? body.environment : null;
1988
+ }
1989
+ function resolveEnvironment(gameSecret, opts = {}) {
1990
+ if (!gameSecret) return Promise.reject(new Error("A game secret is required."));
1991
+ if (isDemoKey(gameSecret)) return Promise.resolve("sandbox");
1992
+ const hit = cache.get(gameSecret);
1993
+ if (hit) return hit;
1994
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
1995
+ const p = (async () => {
1996
+ const env = await ask(PRODUCTION_BASE_URL, gameSecret, fetchImpl) ?? await ask(SANDBOX_BASE_URL, gameSecret, fetchImpl);
1997
+ if (!env) {
1998
+ throw new EnvironmentUnknownError(
1999
+ "Neither INVO production nor the INVO sandbox recognises this key. Check INVO_GAME_SECRET in your secrets."
2000
+ );
2001
+ }
2002
+ return env;
2003
+ })();
2004
+ cache.set(gameSecret, p);
2005
+ p.catch(() => cache.delete(gameSecret));
2006
+ return p;
2007
+ }
2008
+ async function baseUrlForKey(gameSecret, opts = {}) {
2009
+ return await resolveEnvironment(gameSecret, opts) === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL;
2010
+ }
2011
+
1958
2012
  // src/server.ts
1959
2013
  var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
1960
2014
  var MAX_USD_AMOUNT = 999999.99;
@@ -5269,16 +5323,23 @@ var InvoServer = class {
5269
5323
  };
5270
5324
 
5271
5325
  exports.CardsServer = CardsServer;
5326
+ exports.DEMO_KEY_PREFIX = DEMO_KEY_PREFIX;
5327
+ exports.EnvironmentUnknownError = EnvironmentUnknownError;
5272
5328
  exports.InvoError = InvoError;
5273
5329
  exports.InvoServer = InvoServer;
5330
+ exports.PRODUCTION_BASE_URL = PRODUCTION_BASE_URL;
5274
5331
  exports.PayoutsServer = PayoutsServer;
5275
5332
  exports.PlatformCommerceServer = PlatformCommerceServer;
5333
+ exports.SANDBOX_BASE_URL = SANDBOX_BASE_URL;
5276
5334
  exports.SDK_VERSION = SDK_VERSION;
5277
5335
  exports.SandboxServer = SandboxServer;
5278
5336
  exports.SandboxSubscriptionsServer = SandboxSubscriptionsServer;
5279
5337
  exports.SubscriptionsServer = SubscriptionsServer;
5338
+ exports.baseUrlForKey = baseUrlForKey;
5280
5339
  exports.createWebhookHandler = createWebhookHandler;
5340
+ exports.isDemoKey = isDemoKey;
5281
5341
  exports.isRefundPendingApproval = isRefundPendingApproval;
5342
+ exports.resolveEnvironment = resolveEnvironment;
5282
5343
  exports.verifyWebhook = verifyWebhook;
5283
5344
  exports.verifyWebhookAsync = verifyWebhookAsync;
5284
5345
  //# sourceMappingURL=server.cjs.map