@invonetwork/web-sdk 3.28.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.
@@ -1,13 +1,129 @@
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';
1
+ import { isDemoKey, SANDBOX_BASE_URL, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-FJR44FKW.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-FJR44FKW.js';
3
3
  import './chunk-6CN236QH.js';
4
- export { SDK_VERSION } from './chunk-3DRWLDDF.js';
4
+ export { SDK_VERSION } from './chunk-KZJABBVT.js';
5
5
  import { InvoError } from './chunk-VP3OK4J4.js';
6
6
  export { InvoError } from './chunk-VP3OK4J4.js';
7
7
  import { createHash, randomBytes } from 'crypto';
8
- import { promises } from 'fs';
8
+ import { promises, readFileSync, mkdirSync, writeFileSync } from 'fs';
9
9
  import * as path from 'path';
10
+ import { dirname } from 'path';
10
11
 
12
+ var DEMO_EMAIL_DOMAIN = "demo.invo.network";
13
+ var DEFAULT_PROJECT_FILE = ".invo/project.json";
14
+ var PROJECT_ID = /^proj_[0-9A-HJKMNP-TV-Z]{26}$/;
15
+ function newDemoProjectId(now = Date.now()) {
16
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
17
+ let t = now;
18
+ let time = "";
19
+ for (let i = 0; i < 10; i++) {
20
+ time = A[t % 32] + time;
21
+ t = Math.floor(t / 32);
22
+ }
23
+ const bytes = randomBytes(16);
24
+ let rand = "";
25
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
26
+ return "proj_" + time + rand;
27
+ }
28
+ function isValidProjectId(value) {
29
+ return typeof value === "string" && PROJECT_ID.test(value);
30
+ }
31
+ function toDemoEmail(email, projectId) {
32
+ if (!isValidProjectId(projectId)) throw new Error("A valid template project id is required.");
33
+ const lower = email.trim().toLowerCase();
34
+ if (lower.endsWith("@" + DEMO_EMAIL_DOMAIN)) return lower;
35
+ const local = (lower.split("@")[0] ?? "player").replace(/[^a-z0-9._-]/g, "").slice(0, 24) || "player";
36
+ const tag = createHash("sha256").update(lower).digest("hex").slice(0, 8);
37
+ return `${local}-${tag}+${projectId.slice(5).toLowerCase()}@${DEMO_EMAIL_DOMAIN}`;
38
+ }
39
+ function demoPhoneFor(email) {
40
+ const n = BigInt("0x" + createHash("sha256").update(email.trim().toLowerCase()).digest("hex")) % BigInt(100);
41
+ return "+120255501" + n.toString().padStart(2, "0");
42
+ }
43
+ function hostOf(url) {
44
+ if (!url) return void 0;
45
+ try {
46
+ return new URL(url).host.toLowerCase();
47
+ } catch {
48
+ return void 0;
49
+ }
50
+ }
51
+ function readFile(file) {
52
+ try {
53
+ const data = JSON.parse(readFileSync(file, "utf8"));
54
+ return isValidProjectId(data.projectId) ? data : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ function writeFile(file, data) {
60
+ mkdirSync(dirname(file), { recursive: true });
61
+ writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode: 384 });
62
+ }
63
+ function loadProject(opts = {}) {
64
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
65
+ if (opts.projectId) {
66
+ if (!isValidProjectId(opts.projectId)) throw new Error('INVO_PROJECT_ID must be "proj_" + a 26-character ULID.');
67
+ const saved2 = readFile(file);
68
+ return saved2 && saved2.projectId === opts.projectId ? saved2 : { projectId: opts.projectId };
69
+ }
70
+ const host = hostOf(opts.publicUrl);
71
+ const saved = readFile(file);
72
+ if (saved && (!host || !saved.host || saved.host === host)) return saved;
73
+ const fresh = { projectId: newDemoProjectId(), host };
74
+ try {
75
+ writeFile(file, fresh);
76
+ } catch {
77
+ }
78
+ return fresh;
79
+ }
80
+ async function registerProject(opts) {
81
+ if (!isDemoKey(opts.gameSecret)) throw new Error("registerProject is for the public demo key only.");
82
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
83
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
84
+ const base = (opts.baseUrl ?? SANDBOX_BASE_URL).replace(/\/+$/, "");
85
+ let project = loadProject({ file, publicUrl: opts.webhookUrl, projectId: opts.projectId });
86
+ for (let attempt = 0; attempt < 2; attempt++) {
87
+ const res = await fetchImpl(base + "/api/demo/projects/register", {
88
+ method: "POST",
89
+ redirect: "error",
90
+ headers: {
91
+ "Content-Type": "application/json",
92
+ Accept: "application/json",
93
+ "X-Game-Secret-Key": opts.gameSecret,
94
+ "X-Invo-Project-Id": project.projectId,
95
+ "X-Invo-Project-Host": hostOf(opts.webhookUrl) ?? ""
96
+ },
97
+ body: JSON.stringify({ webhook_url: opts.webhookUrl, registration_token: project.registrationToken })
98
+ });
99
+ const body = await res.json().catch(() => ({}));
100
+ if (res.status === 409 && body.error_code === "PROJECT_REGISTERED" && attempt === 0 && !opts.projectId) {
101
+ project = { projectId: newDemoProjectId(), host: hostOf(opts.webhookUrl) };
102
+ continue;
103
+ }
104
+ if (!res.ok) throw new Error(`INVO demo registration failed (${res.status} ${body.error_code ?? ""}): ${body.error ?? ""}`.trim());
105
+ const created = res.status === 201;
106
+ if (created) {
107
+ project = {
108
+ projectId: project.projectId,
109
+ host: hostOf(opts.webhookUrl),
110
+ webhookUrl: opts.webhookUrl,
111
+ webhookSecret: body.webhook?.signing_secret ?? project.webhookSecret,
112
+ registrationToken: body.registration_token ?? project.registrationToken
113
+ };
114
+ } else {
115
+ project = { ...project, host: project.host ?? hostOf(opts.webhookUrl), webhookUrl: opts.webhookUrl };
116
+ }
117
+ try {
118
+ writeFile(file, project);
119
+ } catch {
120
+ }
121
+ return { projectId: project.projectId, webhookSecret: project.webhookSecret ?? null, created };
122
+ }
123
+ throw new Error("INVO demo registration failed.");
124
+ }
125
+
126
+ // src/game/server.ts
11
127
  var MAX_BODY_BYTES = 1e6;
12
128
  var EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,63}$/;
13
129
  var E164 = /^\+[1-9]\d{6,14}$/;
@@ -199,9 +315,12 @@ function createInvoGameServer(options) {
199
315
  const name = (rawName || email.split("@")[0] || "Player").slice(0, 64);
200
316
  const id = playerIdFor(email);
201
317
  const known = await store.read((s) => s.players[id] ?? null);
202
- const phoneForInvo = phone ?? known?.phone ?? void 0;
318
+ const demoPid = options.demoProjectId;
319
+ const invoEmail = demoPid ? toDemoEmail(email, demoPid) : email;
320
+ const phoneForInvo = demoPid ? demoPhoneFor(invoEmail) : phone ?? known?.phone ?? void 0;
321
+ const storedPhone = demoPid ? null : phone;
203
322
  try {
204
- await invo.mintPlayerToken({ playerEmail: email, playerPhone: phoneForInvo, playerName: name });
323
+ await invo.mintPlayerToken({ playerEmail: invoEmail, playerPhone: phoneForInvo, playerName: name });
205
324
  } catch (err) {
206
325
  if (err instanceof InvoError && err.status === 404) {
207
326
  throw new GameServerError(400, "PHONE_REQUIRED", "First sign-in needs a phone number so INVO can create your account.");
@@ -213,7 +332,7 @@ function createInvoGameServer(options) {
213
332
  const expiresAt = new Date(now().getTime() + sessionTtlMs).toISOString();
214
333
  const player = await store.transact((s) => {
215
334
  const existing = s.players[id];
216
- const record = existing ? { ...existing, name, phone: phone ?? existing.phone } : { id, email, phone, name, createdAt: iso() };
335
+ const record = existing ? { ...existing, email: invoEmail, name, phone: storedPhone ?? existing.phone } : { id, email: invoEmail, phone: storedPhone, name, createdAt: iso() };
217
336
  s.players[id] = record;
218
337
  if (soft.starting > 0) {
219
338
  addLedger(s, { playerId: id, currency: "soft", amount: soft.starting, reason: "starting balance", ref: `start:${id}`, at: iso() });
@@ -552,23 +671,33 @@ function invoGameServerFromEnv(options) {
552
671
  const forced = env["INVO_ENV"]?.trim().toLowerCase();
553
672
  const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
554
673
  const state = { environment: known };
555
- const sandboxNow = () => state.environment !== "production";
556
- const missing = ["INVO_GAME_SECRET", "INVO_WEBHOOK_SECRET"].filter((k) => !env[k]?.trim());
674
+ const sandboxNow = () => state.environment === "sandbox";
675
+ const envNow = () => state.environment ?? "resolving";
676
+ const demo = isDemoKey(secret);
677
+ 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;
678
+ const webhookSecrets = (() => {
679
+ const raw = options.webhookSecret ?? env["INVO_WEBHOOK_SECRET"] ?? demoProject?.webhookSecret ?? "";
680
+ return (Array.isArray(raw) ? raw : raw.split(",")).map((s) => s.trim()).filter(Boolean);
681
+ })();
682
+ const missing = [
683
+ ...secret ? [] : ["INVO_GAME_SECRET"],
684
+ ...webhookSecrets.length ? [] : ["INVO_WEBHOOK_SECRET"]
685
+ ];
557
686
  if (missing.length) {
558
- return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow() };
687
+ return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow(), environment: envNow() };
559
688
  }
560
689
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
561
- const projectId = (options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0;
690
+ const projectId = demoProject?.projectId ?? ((options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0);
562
691
  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) => {
692
+ const resolveNow = () => resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
564
693
  state.environment = e;
565
694
  return e;
566
695
  });
567
- resolved?.catch(() => void 0);
696
+ if (!explicitBase && !known) resolveNow().catch(() => void 0);
568
697
  const invoFetch = async (input, init) => {
569
698
  let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
570
699
  if (!explicitBase) {
571
- const e = known ?? await resolved;
700
+ const e = known ?? state.environment ?? await resolveNow();
572
701
  if (e === "sandbox" && url.startsWith(PRODUCTION_BASE_URL + "/")) url = SANDBOX_BASE_URL + url.slice(PRODUCTION_BASE_URL.length);
573
702
  }
574
703
  const headers = new Headers(init?.headers);
@@ -578,7 +707,8 @@ function invoGameServerFromEnv(options) {
578
707
  const invo = new InvoServer({ gameSecret: secret, baseUrl: explicitBase || PRODUCTION_BASE_URL, fetch: invoFetch });
579
708
  const serverOptions = {
580
709
  invo,
581
- webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
710
+ webhookSecret: webhookSecrets,
711
+ demoProjectId: demo ? projectId : void 0,
582
712
  economy: options.economy,
583
713
  store: options.store,
584
714
  get sandbox() {
@@ -589,7 +719,7 @@ function invoGameServerFromEnv(options) {
589
719
  log: options.log
590
720
  };
591
721
  const server = createInvoGameServer(serverOptions);
592
- return { server, missing, sandbox: sandboxNow() };
722
+ return { server, missing, sandbox: sandboxNow(), environment: envNow() };
593
723
  }
594
724
  function newProjectId(now = Date.now()) {
595
725
  const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -741,6 +871,6 @@ function createFileGameStore(options) {
741
871
  };
742
872
  }
743
873
 
744
- export { GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, newProjectId, playerIdFor, toNodeListener, validateEconomy };
874
+ export { DEFAULT_PROJECT_FILE, DEMO_EMAIL_DOMAIN, GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, demoPhoneFor, emptyGameState, invoGameServerFromEnv, isValidProjectId, loadProject, newProjectId, playerIdFor, registerProject, toDemoEmail, toNodeListener, validateEconomy };
745
875
  //# sourceMappingURL=game-server.js.map
746
876
  //# 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.28.0";
2165
+ var SDK_VERSION = "3.29.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-iWmcxjYu.cjs';
3
+ export { S as SDK_VERSION } from './version-xyYQO5hp.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-iWmcxjYu.js';
3
+ export { S as SDK_VERSION } from './version-xyYQO5hp.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-3DRWLDDF.js';
1
+ export { SDK_VERSION } from './chunk-KZJABBVT.js';
2
2
  import { newEventId } from './chunk-VP3OK4J4.js';
3
3
 
4
4
  // src/game/client.ts