@genex-ai/embed-sdk 0.31.0 → 0.33.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,15 +1,575 @@
1
1
  import {
2
+ AUTHORIZE_ENTRY_REF_PARAM,
3
+ DASHBOARD_RESERVED_KEYS,
4
+ EMBED_REFERRER_PARAM,
5
+ ENTRY_HASH_KEY,
6
+ ENTRY_REFERRER_KEY,
7
+ MAX_ENTRY_QUERY_LENGTH,
8
+ MAX_RETURN_TO_LENGTH,
2
9
  NATIVE_CHANNEL,
3
10
  NATIVE_PROTOCOL_VERSION,
4
11
  NATIVE_RECEIVER,
12
+ PLATFORM_PROTOCOL_VERSION,
13
+ PLATFORM_REQUEST_TYPE,
14
+ RESERVED_QUERY_PREFIX,
15
+ SAVE_MAX_BYTES,
16
+ createBridgeId,
5
17
  encodeBridgeMessage,
6
18
  hasNativeMarker,
7
19
  isGenerationId,
8
20
  isGenerationTerminal,
21
+ isPlatformUrl,
22
+ isSaveName,
9
23
  parseGenerationStreamEvent,
24
+ parsePlatformRequest,
25
+ parsePlatformResult,
10
26
  readBridgeNativeCommand,
11
- readNativeEntry
12
- } from "./chunk-MJPLBT3T.js";
27
+ readNativeEntry,
28
+ readPlatformCaps,
29
+ sanitizeEntryHash,
30
+ sanitizeEntryReferrer,
31
+ sanitizePassthroughQuery,
32
+ savableMime,
33
+ stripNativeEntry,
34
+ stripReturnMarker
35
+ } from "./chunk-QBCWKMVQ.js";
36
+
37
+ // src/platform.ts
38
+ var ctx = null;
39
+ function _initPlatform(c) {
40
+ ctx = c;
41
+ }
42
+ var replyTimeoutMs = 3e3;
43
+ var confirmTimeoutMs = 18e4;
44
+ var SAVE_URL_LIFETIME_MS = 6e4;
45
+ var pending = /* @__PURE__ */ new Map();
46
+ var listening = null;
47
+ var wakeWanted = false;
48
+ var wakeSentinel = null;
49
+ var wakeRequest = null;
50
+ var wakeHook = null;
51
+ var shareParamsWarned = false;
52
+ function win() {
53
+ return globalThis.window;
54
+ }
55
+ function doc() {
56
+ return globalThis.document;
57
+ }
58
+ function shell() {
59
+ return ctx ? ctx.getShell() : "standalone";
60
+ }
61
+ function localTest() {
62
+ if (!ctx) return false;
63
+ return ctx.isLocalTest ? ctx.isLocalTest() : ctx.getShell() === "local";
64
+ }
65
+ function fail(error) {
66
+ return { ok: false, error };
67
+ }
68
+ async function settled(run, fallback) {
69
+ try {
70
+ return await run();
71
+ } catch {
72
+ return fallback;
73
+ }
74
+ }
75
+ function share(options) {
76
+ let url = "";
77
+ try {
78
+ url = shareUrl(options?.params);
79
+ } catch {
80
+ }
81
+ return settled(
82
+ async () => {
83
+ const nav = win()?.navigator;
84
+ if (url && nav && !localTest() && typeof nav.share === "function") {
85
+ const data = { url };
86
+ if (typeof options?.text === "string" && options.text) data.text = options.text;
87
+ if (canShare(nav, data)) {
88
+ try {
89
+ await nav.share(data);
90
+ return { status: "shared", url };
91
+ } catch (error) {
92
+ if (error?.name === "AbortError") {
93
+ return { status: "dismissed", url };
94
+ }
95
+ }
96
+ }
97
+ }
98
+ if (url && (await copyText(url)).ok) return { status: "copied", url };
99
+ return { status: "unavailable", url };
100
+ },
101
+ { status: "unavailable", url }
102
+ );
103
+ }
104
+ function canShare(nav, data) {
105
+ if (typeof nav.canShare !== "function") return true;
106
+ try {
107
+ return nav.canShare(data);
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ function shareUrl(params) {
113
+ const base = shareBase();
114
+ if (!base) return "";
115
+ const query = shareQuery(params);
116
+ return query ? `${base}?${query}` : base;
117
+ }
118
+ function shareBase() {
119
+ const w = win();
120
+ if (!w) return "";
121
+ const page = httpAddress(w.__GENEX__?.pageUrl);
122
+ if (page) return page;
123
+ const dashboard = trustedParent();
124
+ const config3 = ctx?.getConfig();
125
+ if (dashboard !== null && config3) {
126
+ const built = pageOnDashboard(dashboard, config3.slug);
127
+ if (built) return built;
128
+ }
129
+ try {
130
+ return httpAddress(w.location.origin + w.location.pathname);
131
+ } catch {
132
+ return "";
133
+ }
134
+ }
135
+ function pageOnDashboard(dashboard, slug) {
136
+ try {
137
+ return httpAddress(`${new URL(dashboard).origin}/${encodeURIComponent(slug)}`);
138
+ } catch {
139
+ return "";
140
+ }
141
+ }
142
+ function httpAddress(value) {
143
+ if (typeof value !== "string") return "";
144
+ try {
145
+ const url = new URL(value);
146
+ if (url.protocol !== "https:" && url.protocol !== "http:") return "";
147
+ if (url.username || url.password) return "";
148
+ return url.origin + url.pathname;
149
+ } catch {
150
+ return "";
151
+ }
152
+ }
153
+ function shareQuery(params) {
154
+ if (!params || typeof params !== "object") return "";
155
+ const pairs = [];
156
+ let leftOut = false;
157
+ for (const key of Object.keys(params)) {
158
+ const value = params[key];
159
+ const kind = typeof value;
160
+ if (!key || kind !== "string" && kind !== "number" && kind !== "boolean") {
161
+ leftOut = true;
162
+ continue;
163
+ }
164
+ try {
165
+ pairs.push(`${queryPart(key)}=${queryPart(String(value))}`);
166
+ } catch {
167
+ leftOut = true;
168
+ }
169
+ }
170
+ const asked = pairs.join("&");
171
+ const kept = asked.length <= MAX_ENTRY_QUERY_LENGTH ? sanitizePassthroughQuery(asked, DASHBOARD_RESERVED_KEYS) : "";
172
+ if ((leftOut || kept !== asked) && !shareParamsWarned) {
173
+ shareParamsWarned = true;
174
+ try {
175
+ console.warn(
176
+ "[genex] share(): some params were left out of the link. embed, ref, s, from, remix, slug and names starting genex_ are reserved, values are strings, numbers or booleans, and the whole query is capped at 1024 characters."
177
+ );
178
+ } catch {
179
+ }
180
+ }
181
+ return kept;
182
+ }
183
+ function queryPart(text) {
184
+ return encodeURIComponent(text).replace(/'/g, "%27");
185
+ }
186
+ function copyText(text) {
187
+ return settled(async () => {
188
+ if (typeof text !== "string" || text.length === 0) return fail("invalid_request");
189
+ const d = doc();
190
+ const clipboard = win()?.navigator?.clipboard;
191
+ let tried = false;
192
+ if (clipboard && typeof clipboard.writeText === "function") {
193
+ tried = true;
194
+ try {
195
+ await clipboard.writeText(text);
196
+ return { ok: true };
197
+ } catch {
198
+ }
199
+ }
200
+ if (d && typeof d.execCommand === "function") {
201
+ tried = true;
202
+ if (selectionCopy(d, text)) return { ok: true };
203
+ }
204
+ return fail(tried ? "needs_gesture" : "unsupported");
205
+ }, fail("unsupported"));
206
+ }
207
+ function selectionCopy(d, text) {
208
+ const host = d.body ?? d.documentElement;
209
+ if (!host) return false;
210
+ const focused = d.activeElement;
211
+ const field = d.createElement("textarea");
212
+ field.value = text;
213
+ field.setAttribute("readonly", "");
214
+ field.setAttribute("aria-hidden", "true");
215
+ field.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0;font-size:16px;";
216
+ host.appendChild(field);
217
+ let copied = false;
218
+ try {
219
+ field.focus({ preventScroll: true });
220
+ field.select();
221
+ field.setSelectionRange(0, text.length);
222
+ copied = d.execCommand("copy");
223
+ } catch {
224
+ copied = false;
225
+ }
226
+ field.remove();
227
+ try {
228
+ if (focused && typeof focused.focus === "function") focused.focus({ preventScroll: true });
229
+ } catch {
230
+ }
231
+ return copied;
232
+ }
233
+ function keepAwake(on2) {
234
+ return settled(() => {
235
+ if (shell() === "app") return { ok: true };
236
+ if (!on2) {
237
+ wakeWanted = false;
238
+ releaseWake();
239
+ return { ok: true };
240
+ }
241
+ const d = doc();
242
+ const lock = win()?.navigator?.wakeLock;
243
+ if (!d || !lock || typeof lock.request !== "function") return fail("unsupported");
244
+ wakeWanted = true;
245
+ hookWake(d);
246
+ return acquireWake(d, lock);
247
+ }, fail("unsupported"));
248
+ }
249
+ function acquireWake(d, lock) {
250
+ if (wakeRequest) return wakeRequest;
251
+ if (wakeSentinel && !wakeSentinel.released) return Promise.resolve({ ok: true });
252
+ if (d.visibilityState === "hidden") return Promise.resolve({ ok: true });
253
+ const request2 = (async () => {
254
+ try {
255
+ const sentinel = await lock.request("screen");
256
+ if (wakeWanted) holdSentinel(sentinel);
257
+ else dropSentinel(sentinel);
258
+ return { ok: true };
259
+ } catch {
260
+ if (d.visibilityState === "hidden") return { ok: true };
261
+ wakeWanted = false;
262
+ return fail("unsupported");
263
+ }
264
+ })();
265
+ wakeRequest = request2;
266
+ void request2.then(() => {
267
+ if (wakeRequest === request2) wakeRequest = null;
268
+ });
269
+ return request2;
270
+ }
271
+ function holdSentinel(sentinel) {
272
+ wakeSentinel = sentinel;
273
+ try {
274
+ sentinel.addEventListener?.("release", () => {
275
+ if (wakeSentinel === sentinel) wakeSentinel = null;
276
+ });
277
+ } catch {
278
+ }
279
+ }
280
+ function hookWake(d) {
281
+ if (wakeHook || typeof d.addEventListener !== "function") return;
282
+ const onVisibility = () => {
283
+ const lock = win()?.navigator?.wakeLock;
284
+ if (wakeWanted && lock && d.visibilityState === "visible") void acquireWake(d, lock);
285
+ };
286
+ d.addEventListener("visibilitychange", onVisibility);
287
+ wakeHook = { d, onVisibility };
288
+ }
289
+ function releaseWake() {
290
+ const sentinel = wakeSentinel;
291
+ wakeSentinel = null;
292
+ if (sentinel && !sentinel.released) dropSentinel(sentinel);
293
+ }
294
+ function dropSentinel(sentinel) {
295
+ try {
296
+ void sentinel.release().catch(() => {
297
+ });
298
+ } catch {
299
+ }
300
+ }
301
+ var HAPTIC_PATTERNS = {
302
+ selection: [8],
303
+ light: [12],
304
+ medium: [20],
305
+ heavy: [35],
306
+ success: [12, 60, 24],
307
+ warning: [24, 80, 24],
308
+ error: [35, 60, 35, 60, 35]
309
+ };
310
+ function haptic(kind) {
311
+ try {
312
+ if (shell() === "app") return;
313
+ const nav = win()?.navigator;
314
+ if (!nav || typeof nav.vibrate !== "function") return;
315
+ if (!Object.prototype.hasOwnProperty.call(HAPTIC_PATTERNS, kind)) return;
316
+ if (nav.userActivation && nav.userActivation.hasBeenActive === false) return;
317
+ nav.vibrate(HAPTIC_PATTERNS[kind]);
318
+ } catch {
319
+ }
320
+ }
321
+ function openExternal(url) {
322
+ return settled(() => {
323
+ const href = serialisedLink(url);
324
+ if (href === null) return fail("invalid_request");
325
+ const where = shell();
326
+ if (where === "app") return fail("unsupported");
327
+ if (where === "page") {
328
+ return askShell("open", (id) => ({ ...requestHead(id), cap: "open", url: href }));
329
+ }
330
+ const w = win();
331
+ if (!w || typeof w.open !== "function") return fail("unsupported");
332
+ const tab = w.open("", "_blank");
333
+ if (!tab) return fail("needs_gesture");
334
+ try {
335
+ tab.opener = null;
336
+ tab.location.replace(href);
337
+ } catch {
338
+ try {
339
+ tab.close();
340
+ } catch {
341
+ }
342
+ return fail("unsupported");
343
+ }
344
+ return { ok: true };
345
+ }, fail("unsupported"));
346
+ }
347
+ function serialisedLink(url) {
348
+ if (typeof url !== "string") return null;
349
+ let href;
350
+ try {
351
+ href = new URL(url).href;
352
+ } catch {
353
+ return null;
354
+ }
355
+ return isPlatformUrl(href) ? href : null;
356
+ }
357
+ function saveFile(file, name) {
358
+ return settled(() => {
359
+ if (!isSaveName(name) || !isBlob(file)) return fail("invalid_request");
360
+ if (file.size > SAVE_MAX_BYTES) return fail("too_large");
361
+ const mime = savableMime(file.type);
362
+ if (mime === null) return fail("invalid_request");
363
+ const where = shell();
364
+ if (where === "app") return fail("unsupported");
365
+ if (where === "page") {
366
+ return askShell("save", (id) => ({ ...requestHead(id), cap: "save", name, file }));
367
+ }
368
+ return downloadHere(file, withExtension(name, mime));
369
+ }, fail("unsupported"));
370
+ }
371
+ function isBlob(value) {
372
+ if (typeof value !== "object" || value === null) return false;
373
+ const tag = Object.prototype.toString.call(value);
374
+ return (tag === "[object Blob]" || tag === "[object File]") && typeof value.size === "number";
375
+ }
376
+ var SAVE_EXTENSIONS = {
377
+ "image/png": ["png"],
378
+ "image/jpeg": ["jpg", "jpeg"],
379
+ "image/webp": ["webp"],
380
+ "video/webm": ["webm"],
381
+ "video/mp4": ["mp4"],
382
+ "application/json": ["json"],
383
+ "text/plain": ["txt"]
384
+ };
385
+ function withExtension(name, mime) {
386
+ const extensions = SAVE_EXTENSIONS[mime];
387
+ const dot = name.lastIndexOf(".");
388
+ const current = dot === -1 ? "" : name.slice(dot + 1).toLowerCase();
389
+ return extensions.includes(current) ? name : `${name}.${extensions[0]}`;
390
+ }
391
+ function downloadHere(file, name) {
392
+ const w = win();
393
+ const d = doc();
394
+ const urls = w?.URL;
395
+ const host = d?.body ?? d?.documentElement;
396
+ if (!d || !host || !urls || typeof urls.createObjectURL !== "function") return fail("unsupported");
397
+ const href = urls.createObjectURL(file);
398
+ try {
399
+ const link = d.createElement("a");
400
+ link.href = href;
401
+ link.download = name;
402
+ link.style.display = "none";
403
+ host.appendChild(link);
404
+ link.click();
405
+ link.remove();
406
+ } finally {
407
+ const timer = setTimeout(() => {
408
+ try {
409
+ urls.revokeObjectURL(href);
410
+ } catch {
411
+ }
412
+ }, SAVE_URL_LIFETIME_MS);
413
+ timer.unref?.();
414
+ }
415
+ return { ok: true };
416
+ }
417
+ function setFullscreen(on2) {
418
+ return settled(() => {
419
+ if (typeof on2 !== "boolean") return fail("invalid_request");
420
+ const where = shell();
421
+ if (where === "app") return fail("unsupported");
422
+ if (where === "page" && shellOffers("fullscreen")) {
423
+ return askShell("fullscreen", (id) => ({ ...requestHead(id), cap: "fullscreen", on: on2 }));
424
+ }
425
+ return fullscreenHere(on2);
426
+ }, fail("unsupported"));
427
+ }
428
+ function fullscreenAllowed(d) {
429
+ const root = d.documentElement;
430
+ const request2 = root?.requestFullscreen ?? root?.webkitRequestFullscreen;
431
+ return typeof request2 === "function" && (d.fullscreenEnabled ?? d.webkitFullscreenEnabled) !== false;
432
+ }
433
+ async function fullscreenHere(on2) {
434
+ const d = doc();
435
+ if (!d) return fail("unsupported");
436
+ const current = d.fullscreenElement ?? d.webkitFullscreenElement ?? null;
437
+ if (!on2) {
438
+ if (!current) return { ok: true };
439
+ const exit = d.exitFullscreen ?? d.webkitExitFullscreen;
440
+ if (typeof exit !== "function") return fail("unsupported");
441
+ await exit.call(d);
442
+ return { ok: true };
443
+ }
444
+ if (!fullscreenAllowed(d)) return fail("unsupported");
445
+ if (current) return { ok: true };
446
+ const root = d.documentElement;
447
+ try {
448
+ await (root.requestFullscreen ?? root.webkitRequestFullscreen).call(root, { navigationUI: "hide" });
449
+ return { ok: true };
450
+ } catch {
451
+ return fail("needs_gesture");
452
+ }
453
+ }
454
+ function trustedParent() {
455
+ const origin = ctx?.getParentOrigin() ?? null;
456
+ const allowed = ctx?.getConfig()?.dashboardOrigins;
457
+ return origin !== null && allowed !== void 0 && allowed.includes(origin) ? origin : null;
458
+ }
459
+ function shellOffers(cap) {
460
+ return trustedParent() !== null && (ctx?.getShellCaps().includes(cap) ?? false);
461
+ }
462
+ function requestHead(id) {
463
+ return { type: PLATFORM_REQUEST_TYPE, v: PLATFORM_PROTOCOL_VERSION, id };
464
+ }
465
+ function askShell(cap, build) {
466
+ const w = win();
467
+ const origin = trustedParent();
468
+ if (!w || origin === null || !shellOffers(cap)) return fail("unsupported");
469
+ for (const waiting of pending.values()) {
470
+ if (waiting.cap === cap) return fail("busy");
471
+ }
472
+ const request2 = parsePlatformRequest(build(createBridgeId()));
473
+ if (!request2) return fail("invalid_request");
474
+ return new Promise((resolve) => {
475
+ const timer = setTimeout(
476
+ () => settle(request2.id, fail("timeout")),
477
+ cap === "fullscreen" ? replyTimeoutMs : confirmTimeoutMs
478
+ );
479
+ pending.set(request2.id, { cap, origin, resolve, timer });
480
+ if (!listening && typeof w.addEventListener === "function") {
481
+ w.addEventListener("message", onShellMessage);
482
+ listening = w;
483
+ }
484
+ if (cap !== "fullscreen") _releasePointer();
485
+ try {
486
+ w.parent.postMessage(request2, origin);
487
+ } catch {
488
+ settle(request2.id, fail("unsupported"));
489
+ }
490
+ });
491
+ }
492
+ function _releasePointer() {
493
+ try {
494
+ doc()?.exitPointerLock?.();
495
+ } catch {
496
+ }
497
+ }
498
+ function settle(id, outcome2) {
499
+ const waiting = pending.get(id);
500
+ if (!waiting) return;
501
+ pending.delete(id);
502
+ clearTimeout(waiting.timer);
503
+ waiting.resolve(outcome2);
504
+ }
505
+ function onShellMessage(event) {
506
+ const w = win();
507
+ if (!w || event.source !== w.parent) return;
508
+ const result = parsePlatformResult(event.data);
509
+ if (!result) return;
510
+ const waiting = pending.get(result.id);
511
+ if (!waiting || event.origin !== waiting.origin) return;
512
+ settle(result.id, result.ok ? { ok: true } : fail(result.code));
513
+ }
514
+ function supports(feature) {
515
+ try {
516
+ const w = win();
517
+ const d = doc();
518
+ if (!w || !d) return false;
519
+ const nav = w.navigator;
520
+ const where = shell();
521
+ const copy = typeof nav?.clipboard?.writeText === "function" || typeof d.execCommand === "function";
522
+ switch (feature) {
523
+ case "copy":
524
+ return copy;
525
+ case "share": {
526
+ const url = shareUrl(void 0);
527
+ if (!url) return false;
528
+ const sheet = !localTest() && !!nav && typeof nav.share === "function" && canShare(nav, { url });
529
+ return sheet || copy;
530
+ }
531
+ case "awake":
532
+ return where === "app" || typeof nav?.wakeLock?.request === "function";
533
+ case "haptic":
534
+ return where !== "app" && typeof nav?.vibrate === "function";
535
+ case "open":
536
+ return where === "page" ? shellOffers("open") : where !== "app" && typeof w.open === "function";
537
+ case "save":
538
+ return where === "page" ? shellOffers("save") : where !== "app" && typeof w.URL?.createObjectURL === "function";
539
+ case "fullscreen":
540
+ if (where === "app") return false;
541
+ return where === "page" && shellOffers("fullscreen") || fullscreenAllowed(d);
542
+ default:
543
+ return false;
544
+ }
545
+ } catch {
546
+ return false;
547
+ }
548
+ }
549
+ function _resetPlatform(overrides) {
550
+ for (const waiting of pending.values()) clearTimeout(waiting.timer);
551
+ pending.clear();
552
+ if (listening) {
553
+ try {
554
+ listening.removeEventListener("message", onShellMessage);
555
+ } catch {
556
+ }
557
+ }
558
+ listening = null;
559
+ if (wakeHook) {
560
+ try {
561
+ wakeHook.d.removeEventListener("visibilitychange", wakeHook.onVisibility);
562
+ } catch {
563
+ }
564
+ }
565
+ wakeHook = null;
566
+ wakeWanted = false;
567
+ wakeSentinel = null;
568
+ wakeRequest = null;
569
+ shareParamsWarned = false;
570
+ replyTimeoutMs = overrides?.replyTimeoutMs ?? 3e3;
571
+ confirmTimeoutMs = overrides?.confirmTimeoutMs ?? 18e4;
572
+ }
13
573
 
14
574
  // src/commerce.ts
15
575
  var cfg = null;
@@ -78,13 +638,14 @@ async function awaitOutcome(intentId, timeoutMs) {
78
638
  }
79
639
  return { status: "expired" };
80
640
  }
81
- function openConfirmSurface(view) {
641
+ function openConfirmSurface(view, parentOrigin2) {
82
642
  const c = must();
83
643
  const w = typeof window === "undefined" ? null : window;
84
644
  if (!w) return { ok: false, reason: "no_window" };
85
645
  if (c.isNative()) return { ok: false, reason: "native_unsupported" };
86
646
  if (c.isEmbedded() && w.parent) {
87
- for (const origin of c.dashboardOrigins) {
647
+ _releasePointer();
648
+ for (const origin of parentOrigin2 ? [parentOrigin2] : c.dashboardOrigins) {
88
649
  try {
89
650
  w.parent.postMessage({ type: "genex:commerce:confirm", v: 1, intentId: view.id }, origin);
90
651
  } catch {
@@ -117,6 +678,167 @@ async function buy(opts) {
117
678
  }
118
679
  return awaitOutcome(view.id, opts.timeoutMs ?? 18e4);
119
680
  }
681
+ async function getPayment(orderId) {
682
+ const c = must();
683
+ if (c.isLocalTest()) return null;
684
+ if (!validOrderId(orderId)) throw new Error("invalid_order_id");
685
+ return readPayment(orderId, 15e3);
686
+ }
687
+ async function getPayments(opts) {
688
+ const c = must();
689
+ if (c.isLocalTest()) return { payments: [], nextCursor: null };
690
+ const qs = new URLSearchParams();
691
+ if (opts?.cursor !== void 0) qs.set("cursor", opts.cursor);
692
+ if (opts?.limit !== void 0) qs.set("limit", String(opts.limit));
693
+ const query = qs.size ? `?${qs}` : "";
694
+ const res = await fetch(`${c.apiUrl}/api/coin/payments${query}`, {
695
+ headers: authHeaders(),
696
+ signal: AbortSignal.timeout(15e3)
697
+ });
698
+ if (!res.ok) throw new Error(`genex payments failed (${res.status})`);
699
+ return await res.json();
700
+ }
701
+ function validOrderId(orderId) {
702
+ return typeof orderId === "string" && orderId.length > 0 && orderId.length <= 128 && orderId !== "." && orderId !== "..";
703
+ }
704
+ async function readPayment(orderId, timeoutMs) {
705
+ const res = await fetch(`${must().apiUrl}/api/coin/payments/orders/${encodeURIComponent(orderId)}`, {
706
+ headers: authHeaders(),
707
+ signal: AbortSignal.timeout(Math.max(1, Math.ceil(timeoutMs)))
708
+ });
709
+ if (res.status === 404) {
710
+ const body = await res.json().catch(() => null);
711
+ if (body?.error === "payment_not_found") return null;
712
+ }
713
+ if (!res.ok) throw new Error(`genex payment failed (${res.status})`);
714
+ const payment = await res.json();
715
+ if (payment.orderId !== orderId) throw new Error("invalid_payment_response");
716
+ return payment;
717
+ }
718
+ function paymentOutcome(payment) {
719
+ switch (payment.status) {
720
+ case "succeeded":
721
+ case "canceled":
722
+ case "expired":
723
+ return { status: payment.status, payment };
724
+ case "failed":
725
+ return {
726
+ status: payment.failureCode === "insufficient_balance" ? "insufficient_balance" : "failed",
727
+ payment,
728
+ message: payment.failureCode ?? "payment_failed"
729
+ };
730
+ default:
731
+ return null;
732
+ }
733
+ }
734
+ async function awaitPaymentOutcome(payment, deadline) {
735
+ let delay = 400;
736
+ while (Date.now() < deadline) {
737
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay, deadline - Date.now())));
738
+ if (Date.now() >= deadline) break;
739
+ delay = Math.min(delay * 1.4, 2e3);
740
+ try {
741
+ const latest = await readPayment(payment.orderId, Math.min(15e3, deadline - Date.now()));
742
+ if (!latest || latest.id !== payment.id) continue;
743
+ payment = latest;
744
+ const result = paymentOutcome(payment);
745
+ if (result) return result;
746
+ } catch {
747
+ }
748
+ }
749
+ return { status: "pending", payment, message: "payment_timeout" };
750
+ }
751
+ async function requestPayment(opts) {
752
+ const c = must();
753
+ if (c.isLocalTest()) return { status: "failed", message: "payments are unavailable in local test mode" };
754
+ if (c.isNative()) return { status: "failed", message: "payments are not available in the app yet" };
755
+ if (typeof window === "undefined") return { status: "failed", message: "no_window" };
756
+ if (!c.getToken()) return { status: "failed", message: "no_player_session" };
757
+ const parentOrigin2 = c.getParentOrigin();
758
+ if (c.isEmbedded() && (!parentOrigin2 || !c.dashboardOrigins.includes(parentOrigin2))) {
759
+ return { status: "failed", message: "untrusted_parent" };
760
+ }
761
+ if (!validOrderId(opts.orderId)) return { status: "failed", message: "invalid_order_id" };
762
+ const title = typeof opts.title === "string" ? opts.title.trim() : "";
763
+ if (!title || title.length > 80) return { status: "failed", message: "invalid_title" };
764
+ if (opts.description !== void 0 && typeof opts.description !== "string") {
765
+ return { status: "failed", message: "invalid_description" };
766
+ }
767
+ const description = opts.description?.trim();
768
+ if (description && description.length > 1e3) return { status: "failed", message: "invalid_description" };
769
+ if (!Number.isSafeInteger(opts.amountCoins) || opts.amountCoins < 1 || opts.amountCoins > 1e5) {
770
+ return { status: "failed", message: "invalid_amount_coins" };
771
+ }
772
+ const timeoutMs = opts.timeoutMs ?? 18e4;
773
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
774
+ return { status: "failed", message: "invalid_timeout" };
775
+ }
776
+ const deadline = Date.now() + timeoutMs;
777
+ let popup = null;
778
+ if (!c.isEmbedded()) {
779
+ try {
780
+ popup = window.open("about:blank", "_blank", "popup,width=420,height=640");
781
+ if (popup) popup.opener = null;
782
+ } catch {
783
+ popup?.close();
784
+ return { status: "failed", message: "popup_blocked" };
785
+ }
786
+ if (!popup) return { status: "failed", message: "popup_blocked" };
787
+ }
788
+ let payment;
789
+ try {
790
+ const created = await fetch(`${c.apiUrl}/api/coin/payments`, {
791
+ method: "POST",
792
+ headers: { ...authHeaders(), "Content-Type": "application/json" },
793
+ body: JSON.stringify({
794
+ orderId: opts.orderId,
795
+ title,
796
+ amountCoins: opts.amountCoins,
797
+ ...description ? { description } : {}
798
+ }),
799
+ signal: AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(15e3, deadline - Date.now()))))
800
+ });
801
+ if (!created.ok) {
802
+ popup?.close();
803
+ const body = await created.json().catch(() => ({}));
804
+ return {
805
+ status: created.status >= 500 ? "pending" : "failed",
806
+ message: body.error ?? `payment_failed_${created.status}`
807
+ };
808
+ }
809
+ const view = await created.json();
810
+ if (view.orderId !== opts.orderId || view.title !== title || view.amountCoins !== opts.amountCoins || view.description !== (description || null) || typeof view.id !== "string") {
811
+ throw new Error("invalid_payment_response");
812
+ }
813
+ const { confirmUrl, ...receipt } = view;
814
+ payment = receipt;
815
+ const result = paymentOutcome(payment);
816
+ if (result) {
817
+ popup?.close();
818
+ return result;
819
+ }
820
+ if (payment.status === "requires_confirmation") {
821
+ const url = new URL(confirmUrl);
822
+ const trustedProtocol = url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
823
+ if (!trustedProtocol || !c.dashboardOrigins.includes(url.origin) || url.username || url.password || url.pathname !== `/confirm/${encodeURIComponent(payment.id)}` || url.search || url.hash) {
824
+ popup?.close();
825
+ return { status: "pending", payment, message: "invalid_confirm_url" };
826
+ }
827
+ if (popup) {
828
+ if (!popup.closed) popup.location.href = url.href;
829
+ } else {
830
+ const opened = openConfirmSurface({ id: payment.id, confirmUrl: url.href }, parentOrigin2);
831
+ if (!opened.ok) return { status: "pending", payment, message: opened.reason };
832
+ }
833
+ } else {
834
+ popup?.close();
835
+ }
836
+ } catch (error) {
837
+ popup?.close();
838
+ return { status: "pending", ...payment ? { payment } : {}, message: error instanceof Error ? error.message : "payment_unavailable" };
839
+ }
840
+ return awaitPaymentOutcome(payment, deadline);
841
+ }
120
842
 
121
843
  // src/stream.ts
122
844
  function createSseParser(onEvent) {
@@ -441,6 +1163,7 @@ async function startGeneration(path, body, timeoutMs, readOutcome, workflow, res
441
1163
  if (popup && dashboard) {
442
1164
  if (!popup.closed) popup.location.href = `${dashboard.origin}/play/generate/${encodeURIComponent(view.id)}`;
443
1165
  } else if (parentOrigin2) {
1166
+ _releasePointer();
444
1167
  window.parent.postMessage({ type: "genex:generation:confirm", v: 1, generationId: view.id }, parentOrigin2);
445
1168
  }
446
1169
  if (result) return result;
@@ -552,14 +1275,15 @@ async function requestSpendGrant(options) {
552
1275
  ...options.judge !== void 0 ? { judge: { enabled: options.judge.enabled, estimatedCallsPerPeriod: options.judge.estimatedCallsPerPeriod } } : {}
553
1276
  });
554
1277
  if (!isGrantId(view.id)) throw new Error("invalid_grant_response");
555
- const settled = grantOutcome(view);
556
- if (settled) {
1278
+ const settled2 = grantOutcome(view);
1279
+ if (settled2) {
557
1280
  popup?.close();
558
- return settled;
1281
+ return settled2;
559
1282
  }
560
1283
  if (popup && dashboard) {
561
1284
  if (!popup.closed) popup.location.href = `${dashboard.origin}/play/grant/${encodeURIComponent(view.id)}`;
562
1285
  } else if (parentOrigin2) {
1286
+ _releasePointer();
563
1287
  window.parent.postMessage({ type: "genex:grant:confirm", v: 1, grantId: view.id }, parentOrigin2);
564
1288
  }
565
1289
  return pollGrant(view.id, options.timeoutMs ?? 6e5, popup);
@@ -723,8 +1447,8 @@ async function judge(options) {
723
1447
  });
724
1448
  if (!isGenerationId(view.generationId) || view.grantId !== options.grantId) throw new Error("invalid_judgment_response");
725
1449
  if (view.status === "dispatching") {
726
- const settled = await poll(view.generationId, (options.timeoutMs ?? 2e4) + 1e4, judgeOutcome);
727
- return settled.status === "pending" ? { ...settled, billing: view.billing } : settled;
1450
+ const settled2 = await poll(view.generationId, (options.timeoutMs ?? 2e4) + 1e4, judgeOutcome);
1451
+ return settled2.status === "pending" ? { ...settled2, billing: view.billing } : settled2;
728
1452
  }
729
1453
  return {
730
1454
  status: view.status,
@@ -931,8 +1655,10 @@ var PROTOCOL_VERSION = 1;
931
1655
  var RETRY_FLAG = "genex:embed:retry";
932
1656
  var POPOVER_DISMISSED_FLAG = "genex:guest:popover-dismissed";
933
1657
  var LOCAL_AUTH_FLAG = "genex:embed:local-auth";
1658
+ var ENTRY_REFERRER_MEMO = "genex:embed:entry-referrer";
1659
+ var ENTRY_REFERRER_NONE = "none";
934
1660
  var PLAYER_ID_KEY = "genex:player";
935
- var SDK_VERSION = "0.31.0";
1661
+ var SDK_VERSION = "0.33.0";
936
1662
  var config2 = null;
937
1663
  var state = "pending";
938
1664
  var user = null;
@@ -945,6 +1671,7 @@ var nativeBootAt = 0;
945
1671
  var embedToken;
946
1672
  var colyseusUrls;
947
1673
  var parentOrigin = null;
1674
+ var shellCaps = [];
948
1675
  var initialized = false;
949
1676
  var redeeming = false;
950
1677
  var requestingGuest = false;
@@ -961,6 +1688,10 @@ var refreshTimer;
961
1688
  var unattendedWaiterTimer;
962
1689
  var earlyWaiterWarned = false;
963
1690
  var messageHandler;
1691
+ var entrySnapshot = null;
1692
+ var closingListeners = /* @__PURE__ */ new Set();
1693
+ var closingHooks = null;
1694
+ var closingFired = false;
964
1695
  var listeners = /* @__PURE__ */ new Map();
965
1696
  var authWaiters = [];
966
1697
  var playerWaiters = [];
@@ -970,10 +1701,10 @@ var popoverMinimizeTimer;
970
1701
  var pendingPlayerSave;
971
1702
  var hasPendingPlayerSave = false;
972
1703
  var pendingScores = /* @__PURE__ */ new Map();
973
- function win() {
1704
+ function win2() {
974
1705
  return globalThis.window;
975
1706
  }
976
- function doc() {
1707
+ function doc2() {
977
1708
  return globalThis.document;
978
1709
  }
979
1710
  function doFetch(input, init, timeoutMs) {
@@ -989,52 +1720,67 @@ function doFetch(input, init, timeoutMs) {
989
1720
  }
990
1721
  function readRetryFlag() {
991
1722
  try {
992
- return win()?.sessionStorage?.getItem(RETRY_FLAG) === "1";
1723
+ return win2()?.sessionStorage?.getItem(RETRY_FLAG) === "1";
993
1724
  } catch {
994
1725
  return false;
995
1726
  }
996
1727
  }
997
1728
  function writeRetryFlag() {
998
1729
  try {
999
- win()?.sessionStorage?.setItem(RETRY_FLAG, "1");
1730
+ win2()?.sessionStorage?.setItem(RETRY_FLAG, "1");
1000
1731
  } catch {
1001
1732
  }
1002
1733
  }
1003
1734
  function clearRetryFlag() {
1004
1735
  try {
1005
- win()?.sessionStorage?.removeItem(RETRY_FLAG);
1736
+ win2()?.sessionStorage?.removeItem(RETRY_FLAG);
1006
1737
  } catch {
1007
1738
  }
1008
1739
  }
1009
1740
  function readLocalAuthFlag() {
1010
1741
  try {
1011
- return win()?.sessionStorage?.getItem(LOCAL_AUTH_FLAG) === "1";
1742
+ return win2()?.sessionStorage?.getItem(LOCAL_AUTH_FLAG) === "1";
1012
1743
  } catch {
1013
1744
  return false;
1014
1745
  }
1015
1746
  }
1016
1747
  function writeLocalAuthFlag() {
1017
1748
  try {
1018
- win()?.sessionStorage?.setItem(LOCAL_AUTH_FLAG, "1");
1749
+ win2()?.sessionStorage?.setItem(LOCAL_AUTH_FLAG, "1");
1750
+ } catch {
1751
+ }
1752
+ }
1753
+ function readEntryReferrerMemo() {
1754
+ try {
1755
+ const stored = win2()?.sessionStorage?.getItem(ENTRY_REFERRER_MEMO);
1756
+ if (stored === null || stored === void 0) return void 0;
1757
+ return sanitizeEntryReferrer(stored);
1758
+ } catch {
1759
+ return void 0;
1760
+ }
1761
+ }
1762
+ function writeEntryReferrerMemo(referrer) {
1763
+ try {
1764
+ win2()?.sessionStorage?.setItem(ENTRY_REFERRER_MEMO, referrer ?? ENTRY_REFERRER_NONE);
1019
1765
  } catch {
1020
1766
  }
1021
1767
  }
1022
1768
  function readPopoverDismissed() {
1023
1769
  try {
1024
- return win()?.sessionStorage?.getItem(POPOVER_DISMISSED_FLAG) === "1";
1770
+ return win2()?.sessionStorage?.getItem(POPOVER_DISMISSED_FLAG) === "1";
1025
1771
  } catch {
1026
1772
  return false;
1027
1773
  }
1028
1774
  }
1029
1775
  function writePopoverDismissed() {
1030
1776
  try {
1031
- win()?.sessionStorage?.setItem(POPOVER_DISMISSED_FLAG, "1");
1777
+ win2()?.sessionStorage?.setItem(POPOVER_DISMISSED_FLAG, "1");
1032
1778
  } catch {
1033
1779
  }
1034
1780
  }
1035
1781
  function playerId() {
1036
1782
  try {
1037
- const store = win()?.localStorage;
1783
+ const store = win2()?.localStorage;
1038
1784
  if (!store) return "no-storage";
1039
1785
  let id = store.getItem(PLAYER_ID_KEY);
1040
1786
  if (!id) {
@@ -1047,7 +1793,7 @@ function playerId() {
1047
1793
  }
1048
1794
  }
1049
1795
  function initEmbed(cfg2) {
1050
- const w = win();
1796
+ const w = win2();
1051
1797
  if (!w) return;
1052
1798
  if (initialized) return;
1053
1799
  initialized = true;
@@ -1061,10 +1807,12 @@ function initEmbed(cfg2) {
1061
1807
  dashboardOrigins: [...cfg2.dashboardOrigins]
1062
1808
  };
1063
1809
  state = "pending";
1810
+ rememberEntry(w);
1064
1811
  _initCommerce({
1065
1812
  apiUrl: config2.apiUrl,
1066
1813
  dashboardOrigins: config2.dashboardOrigins,
1067
1814
  getToken: () => embedToken,
1815
+ getParentOrigin: () => parentOrigin,
1068
1816
  isEmbedded,
1069
1817
  isNative: inNativeMode,
1070
1818
  isLocalTest: () => localTestMode
@@ -1095,7 +1843,7 @@ function initEmbed(cfg2) {
1095
1843
  }
1096
1844
  }
1097
1845
  function isEmbedded() {
1098
- const w = win();
1846
+ const w = win2();
1099
1847
  if (!w) return false;
1100
1848
  try {
1101
1849
  return w.self !== w.top;
@@ -1103,6 +1851,31 @@ function isEmbedded() {
1103
1851
  return true;
1104
1852
  }
1105
1853
  }
1854
+ function getEntry() {
1855
+ const w = win2();
1856
+ const entry = w ? rememberEntry(w) : { search: "", hash: "", referrer: null };
1857
+ return {
1858
+ search: entry.search,
1859
+ params: new URLSearchParams(entry.search),
1860
+ hash: entry.hash,
1861
+ referrer: entry.referrer
1862
+ };
1863
+ }
1864
+ function getShell() {
1865
+ const w = win2();
1866
+ if (!w) return "standalone";
1867
+ if (isEmbedded()) return "page";
1868
+ if (inNativeMode() || nativeBridge(w)) return "app";
1869
+ if (initialized) return localTestMode ? "local" : "standalone";
1870
+ return wantsLocalTestMode(w, false) ? "local" : "standalone";
1871
+ }
1872
+ function onShellClosing(cb) {
1873
+ closingListeners.add(cb);
1874
+ hookShellClosing();
1875
+ return () => {
1876
+ closingListeners.delete(cb);
1877
+ };
1878
+ }
1106
1879
  function getAuthState() {
1107
1880
  return state;
1108
1881
  }
@@ -1437,12 +2210,90 @@ async function flushGuestQueue() {
1437
2210
  emit("error", { error });
1438
2211
  }
1439
2212
  }
1440
- function emit(event, ctx) {
2213
+ function emit(event, ctx2) {
1441
2214
  const set = listeners.get(event);
1442
2215
  if (!set) return;
1443
2216
  for (const cb of [...set]) {
1444
2217
  try {
1445
- cb(ctx);
2218
+ cb(ctx2);
2219
+ } catch {
2220
+ }
2221
+ }
2222
+ }
2223
+ var ENTRY_HIDDEN_KEYS = ["embed"];
2224
+ function readReturnFragment(hash, ownOrigin) {
2225
+ const empty = { ticket: null, guest: false, entryHash: "", entryReferrer: null };
2226
+ if (!hash || hash.length < 2) return empty;
2227
+ try {
2228
+ const params = new URLSearchParams(hash.slice(1));
2229
+ return {
2230
+ ticket: params.get("genex_ticket"),
2231
+ guest: params.get("genex_guest") === "1",
2232
+ entryHash: sanitizeEntryHash(params.get(ENTRY_HASH_KEY)),
2233
+ entryReferrer: sanitizeEntryReferrer(params.get(ENTRY_REFERRER_KEY), ownOrigin)
2234
+ };
2235
+ } catch {
2236
+ return empty;
2237
+ }
2238
+ }
2239
+ function queryValue(search, key) {
2240
+ try {
2241
+ return new URLSearchParams(search).get(key);
2242
+ } catch {
2243
+ return null;
2244
+ }
2245
+ }
2246
+ function rememberEntry(w) {
2247
+ if (entrySnapshot) return entrySnapshot;
2248
+ let search = "";
2249
+ let hash = "";
2250
+ let ownOrigin = null;
2251
+ try {
2252
+ search = w.location.search ?? "";
2253
+ hash = stashedTicketHash ?? w.location.hash ?? "";
2254
+ ownOrigin = w.location.origin ?? null;
2255
+ } catch {
2256
+ }
2257
+ const embedded = isEmbedded();
2258
+ const carried = readReturnFragment(hash, ownOrigin);
2259
+ const returnTrip = !embedded && (!!carried.ticket || carried.guest);
2260
+ const pairs = sanitizePassthroughQuery(search, ENTRY_HIDDEN_KEYS);
2261
+ entrySnapshot = {
2262
+ search: pairs ? `?${pairs}` : "",
2263
+ // Anywhere else the fragment is the game's as it stands, unless it names a
2264
+ // Genex key: that namespace is the platform's in a fragment too.
2265
+ hash: returnTrip ? carried.entryHash : hash.includes(RESERVED_QUERY_PREFIX) ? "" : hash,
2266
+ referrer: resolveEntryReferrer(search, embedded, returnTrip, carried.entryReferrer, ownOrigin)
2267
+ };
2268
+ return entrySnapshot;
2269
+ }
2270
+ function resolveEntryReferrer(search, embedded, returnTrip, carried, ownOrigin) {
2271
+ const known = readEntryReferrerMemo();
2272
+ if (known !== void 0) return known;
2273
+ let referrer;
2274
+ if (embedded) referrer = sanitizeEntryReferrer(queryValue(search, EMBED_REFERRER_PARAM), ownOrigin);
2275
+ else if (returnTrip) referrer = carried;
2276
+ else referrer = sanitizeEntryReferrer(doc2()?.referrer, ownOrigin);
2277
+ writeEntryReferrerMemo(referrer);
2278
+ return referrer;
2279
+ }
2280
+ function hookShellClosing() {
2281
+ const w = win2();
2282
+ if (!w || closingHooks || typeof w.addEventListener !== "function") return;
2283
+ const hide = () => fireShellClosing();
2284
+ const show = () => {
2285
+ closingFired = false;
2286
+ };
2287
+ w.addEventListener("pagehide", hide);
2288
+ w.addEventListener("pageshow", show);
2289
+ closingHooks = { w, hide, show };
2290
+ }
2291
+ function fireShellClosing() {
2292
+ if (closingFired || closingListeners.size === 0) return;
2293
+ closingFired = true;
2294
+ for (const cb of [...closingListeners]) {
2295
+ try {
2296
+ cb();
1446
2297
  } catch {
1447
2298
  }
1448
2299
  }
@@ -1477,6 +2328,7 @@ async function handleParentMessage(event) {
1477
2328
  }
1478
2329
  if (handshakeTimer !== void 0) clearTimeout(handshakeTimer);
1479
2330
  parentOrigin = event.origin;
2331
+ shellCaps = readPlatformCaps(data.caps);
1480
2332
  if (isGuest) {
1481
2333
  await requestGuestSession();
1482
2334
  return;
@@ -1505,7 +2357,7 @@ function inNativeMode() {
1505
2357
  return nativeEntry !== null;
1506
2358
  }
1507
2359
  function postToNative(message) {
1508
- const w = win();
2360
+ const w = win2();
1509
2361
  if (!w || !config2 || !nativeEntry) return;
1510
2362
  const bridge = nativeBridge(w);
1511
2363
  if (!bridge) return;
@@ -1557,6 +2409,7 @@ async function handleNativeCommand(payload) {
1557
2409
  return;
1558
2410
  case "cancel":
1559
2411
  stopNativeTimers();
2412
+ fireShellClosing();
1560
2413
  return;
1561
2414
  case "foreground":
1562
2415
  case "network":
@@ -1598,7 +2451,7 @@ function clearNativeReauth() {
1598
2451
  nativeReauthTimer = void 0;
1599
2452
  }
1600
2453
  function postToParent(message, targetOrigin) {
1601
- const w = win();
2454
+ const w = win2();
1602
2455
  if (!w || !isEmbedded()) return;
1603
2456
  try {
1604
2457
  w.parent.postMessage(message, targetOrigin);
@@ -1629,43 +2482,26 @@ function armStandaloneWatchdog() {
1629
2482
  }
1630
2483
  var stashedTicketHash = null;
1631
2484
  function _stashTicketFromUrl() {
1632
- const w = win();
2485
+ const w = win2();
1633
2486
  if (!w) return;
1634
2487
  const hash = w.location.hash;
1635
2488
  if (!hash || !hash.includes("genex_")) return;
1636
2489
  stashedTicketHash = hash;
1637
2490
  try {
1638
- w.history.replaceState(null, "", cleanUrl(w));
2491
+ w.history.replaceState(w.history.state ?? null, "", cleanUrl(w) + readReturnFragment(hash).entryHash);
1639
2492
  } catch {
1640
2493
  }
1641
2494
  }
1642
2495
  function cleanUrl(w) {
1643
- let search = w.location.search;
1644
- try {
1645
- const params = new URLSearchParams(search);
1646
- params.delete("genex_r");
1647
- const rest = params.toString();
1648
- search = rest ? `?${rest}` : "";
1649
- } catch {
1650
- }
1651
- return w.location.pathname + search;
2496
+ return w.location.pathname + stripReturnMarker(w.location.search);
1652
2497
  }
1653
2498
  function readFragment(w) {
1654
2499
  const hash = stashedTicketHash ?? w.location.hash;
1655
2500
  stashedTicketHash = null;
1656
- if (!hash || hash.length < 2) return { ticket: null, guest: false };
1657
- let ticket = null;
1658
- let guest = false;
1659
- try {
1660
- const params = new URLSearchParams(hash.slice(1));
1661
- ticket = params.get("genex_ticket");
1662
- guest = params.get("genex_guest") === "1";
1663
- } catch {
1664
- return { ticket: null, guest: false };
1665
- }
2501
+ const { ticket, guest, entryHash } = readReturnFragment(hash);
1666
2502
  if (ticket || guest) {
1667
2503
  try {
1668
- w.history.replaceState(null, "", cleanUrl(w));
2504
+ w.history.replaceState(w.history.state ?? null, "", cleanUrl(w) + entryHash);
1669
2505
  } catch {
1670
2506
  }
1671
2507
  }
@@ -1679,9 +2515,19 @@ async function redirectToAuthorize(w, opts) {
1679
2515
  enterBlocked();
1680
2516
  return;
1681
2517
  }
1682
- const returnTo = w.location.origin + w.location.pathname;
2518
+ let returnTo = w.location.origin + w.location.pathname;
2519
+ const query = stripNativeEntry(stripReturnMarker(w.location.search));
2520
+ if (
2521
+ // The cap is on the pairs; `query` is '' or starts with the one `?`.
2522
+ query.length - 1 <= MAX_ENTRY_QUERY_LENGTH && returnTo.length + query.length <= MAX_RETURN_TO_LENGTH && query.indexOf("#") === -1
2523
+ ) {
2524
+ returnTo += query;
2525
+ }
1683
2526
  const guestParam = opts?.guestOk ? "&guest=ok" : "";
1684
- const url = `${origin}/play/authorize?returnTo=${encodeURIComponent(returnTo)}&slug=${encodeURIComponent(config2.slug)}${guestParam}`;
2527
+ let url = `${origin}/play/authorize?returnTo=${encodeURIComponent(returnTo)}&slug=${encodeURIComponent(config2.slug)}${guestParam}`;
2528
+ const referrer = rememberEntry(w).referrer;
2529
+ if (referrer) url += `&${AUTHORIZE_ENTRY_REF_PARAM}=${encodeURIComponent(referrer)}`;
2530
+ url += sanitizeEntryHash(w.location.hash);
1685
2531
  w.location.replace(url);
1686
2532
  }
1687
2533
  async function fetchDashboardOrigins() {
@@ -1741,10 +2587,10 @@ async function redeemTicket(ticket) {
1741
2587
  startHeartbeat();
1742
2588
  }
1743
2589
  if (upgradingFromGuest) await flushGuestQueue();
1744
- const ctx = { user };
1745
- for (const waiter of authWaiters.splice(0)) waiter.resolve(ctx);
2590
+ const ctx2 = { user };
2591
+ for (const waiter of authWaiters.splice(0)) waiter.resolve(ctx2);
1746
2592
  for (const waiter of playerWaiters.splice(0)) waiter.resolve({ user, guest: false });
1747
- emit("authenticated", ctx);
2593
+ emit("authenticated", ctx2);
1748
2594
  } catch (error) {
1749
2595
  if (epoch !== identityEpoch) return;
1750
2596
  emit("error", { error });
@@ -1806,9 +2652,9 @@ function enterGuest() {
1806
2652
  showGuestPopover();
1807
2653
  }
1808
2654
  if (user) {
1809
- const ctx = { user };
2655
+ const ctx2 = { user };
1810
2656
  for (const waiter of playerWaiters.splice(0)) waiter.resolve({ user, guest: true });
1811
- emit("guest", ctx);
2657
+ emit("guest", ctx2);
1812
2658
  }
1813
2659
  }
1814
2660
  function isLoopbackLocation(w) {
@@ -1819,7 +2665,7 @@ function isLoopbackLocation(w) {
1819
2665
  return false;
1820
2666
  }
1821
2667
  }
1822
- function wantsLocalTestMode(w) {
2668
+ function wantsLocalTestMode(w, latch = true) {
1823
2669
  if (isEmbedded()) return false;
1824
2670
  if (detectNativeEntry(w)) return false;
1825
2671
  if (!isLoopbackLocation(w)) return false;
@@ -1830,7 +2676,7 @@ function wantsLocalTestMode(w) {
1830
2676
  }
1831
2677
  if (params?.get("genex_local_test") === "1") return true;
1832
2678
  if (params?.get("genex_auth") === "1") {
1833
- writeLocalAuthFlag();
2679
+ if (latch) writeLocalAuthFlag();
1834
2680
  return false;
1835
2681
  }
1836
2682
  if (readLocalAuthFlag()) return false;
@@ -1857,7 +2703,7 @@ function enterLocalTestMode(w) {
1857
2703
  emit("guest", { user: localUser });
1858
2704
  }
1859
2705
  async function handleRedeemFailure() {
1860
- const w = win();
2706
+ const w = win2();
1861
2707
  if (handshakeTimer !== void 0) clearTimeout(handshakeTimer);
1862
2708
  handshakeTimer = void 0;
1863
2709
  if (inNativeMode()) {
@@ -1983,7 +2829,7 @@ function scrambleNoise(length) {
1983
2829
  }
1984
2830
  function scrambleStatic() {
1985
2831
  try {
1986
- const w = win();
2832
+ const w = win2();
1987
2833
  if (!w || typeof w.matchMedia !== "function") return true;
1988
2834
  return w.matchMedia("(prefers-reduced-motion: reduce)").matches;
1989
2835
  } catch {
@@ -2040,7 +2886,7 @@ function ensureOverlayFont(d) {
2040
2886
  if (overlayFontRequested) return;
2041
2887
  overlayFontRequested = true;
2042
2888
  try {
2043
- const FF = win()?.FontFace;
2889
+ const FF = win2()?.FontFace;
2044
2890
  const fonts = d.fonts;
2045
2891
  if (!FF || !fonts?.add) return;
2046
2892
  const face = new FF("Geist Mono", `url(${OVERLAY_FONT_URL}) format('woff2')`, {
@@ -2053,7 +2899,7 @@ function ensureOverlayFont(d) {
2053
2899
  }
2054
2900
  }
2055
2901
  function showOverlay(kind) {
2056
- const d = doc();
2902
+ const d = doc2();
2057
2903
  if (!d?.createElement) return;
2058
2904
  try {
2059
2905
  if (!overlayEl) overlayEl = buildOverlay(d);
@@ -2101,7 +2947,7 @@ function buildOverlay(d) {
2101
2947
  button.style.background = "#4b60bf";
2102
2948
  });
2103
2949
  button.addEventListener("click", () => {
2104
- const w = win();
2950
+ const w = win2();
2105
2951
  if (!w) return;
2106
2952
  button.disabled = true;
2107
2953
  clearRetryFlag();
@@ -2154,7 +3000,7 @@ function buildOverlay(d) {
2154
3000
  };
2155
3001
  }
2156
3002
  function showGuestPopover() {
2157
- const d = doc();
3003
+ const d = doc2();
2158
3004
  if (!d?.createElement || popoverEl) return;
2159
3005
  try {
2160
3006
  popoverEl = buildGuestPopover(d);
@@ -2177,7 +3023,7 @@ function buildGuestPopover(d) {
2177
3023
  ensureOverlayFont(d);
2178
3024
  let mobile = false;
2179
3025
  try {
2180
- const w = win();
3026
+ const w = win2();
2181
3027
  const nav = w?.navigator;
2182
3028
  if (w && nav) {
2183
3029
  const coarse = w.matchMedia?.("(pointer: coarse)").matches ?? false;
@@ -2207,7 +3053,7 @@ function buildGuestPopover(d) {
2207
3053
  signIn.style.background = "#4b60bf";
2208
3054
  });
2209
3055
  signIn.addEventListener("click", () => {
2210
- const w = win();
3056
+ const w = win2();
2211
3057
  if (!w) return;
2212
3058
  signIn.disabled = true;
2213
3059
  clearRetryFlag();
@@ -2248,7 +3094,7 @@ function buildGuestPopover(d) {
2248
3094
  return { root };
2249
3095
  }
2250
3096
  function __resetForTests(overrides) {
2251
- const w = win();
3097
+ const w = win2();
2252
3098
  if (w && messageHandler) w.removeEventListener("message", messageHandler);
2253
3099
  messageHandler = void 0;
2254
3100
  if (handshakeTimer !== void 0) clearTimeout(handshakeTimer);
@@ -2273,6 +3119,7 @@ function __resetForTests(overrides) {
2273
3119
  embedToken = void 0;
2274
3120
  colyseusUrls = void 0;
2275
3121
  parentOrigin = null;
3122
+ shellCaps = [];
2276
3123
  initialized = false;
2277
3124
  redeeming = false;
2278
3125
  requestingGuest = false;
@@ -2281,6 +3128,17 @@ function __resetForTests(overrides) {
2281
3128
  authWaiters = [];
2282
3129
  playerWaiters = [];
2283
3130
  stashedTicketHash = null;
3131
+ entrySnapshot = null;
3132
+ if (closingHooks) {
3133
+ try {
3134
+ closingHooks.w.removeEventListener("pagehide", closingHooks.hide);
3135
+ closingHooks.w.removeEventListener("pageshow", closingHooks.show);
3136
+ } catch {
3137
+ }
3138
+ }
3139
+ closingHooks = null;
3140
+ closingListeners.clear();
3141
+ closingFired = false;
2284
3142
  pendingPlayerSave = void 0;
2285
3143
  hasPendingPlayerSave = false;
2286
3144
  pendingScores.clear();
@@ -2291,13 +3149,41 @@ function __resetForTests(overrides) {
2291
3149
  overlayTextDelayMs = overrides?.overlayTextDelayMs ?? 500;
2292
3150
  nativeReauthTimeoutMs = overrides?.nativeReauthTimeoutMs ?? 3e4;
2293
3151
  heartbeatIntervalMs = overrides?.heartbeatIntervalMs ?? 3e4;
3152
+ _resetPlatform({
3153
+ replyTimeoutMs: overrides?.platformReplyTimeoutMs,
3154
+ confirmTimeoutMs: overrides?.platformConfirmTimeoutMs
3155
+ });
2294
3156
  }
3157
+ _initPlatform({
3158
+ getShell,
3159
+ // getShell()'s own reading of local test mode, without its `app` answer
3160
+ // in front: a dev server inside a React Native WebView is both.
3161
+ isLocalTest: () => {
3162
+ const w = win2();
3163
+ if (!w || isEmbedded()) return false;
3164
+ return initialized ? localTestMode : wantsLocalTestMode(w, false);
3165
+ },
3166
+ getConfig: () => config2,
3167
+ getParentOrigin: () => parentOrigin,
3168
+ getShellCaps: () => shellCaps
3169
+ });
2295
3170
 
2296
3171
  export {
3172
+ share,
3173
+ copyText,
3174
+ keepAwake,
3175
+ haptic,
3176
+ openExternal,
3177
+ saveFile,
3178
+ setFullscreen,
3179
+ supports,
2297
3180
  getShop,
2298
3181
  getEntitlements,
2299
3182
  consumeEntitlement,
2300
3183
  buy,
3184
+ getPayment,
3185
+ getPayments,
3186
+ requestPayment,
2301
3187
  getGenerationModels,
2302
3188
  getWorkflowOfferings,
2303
3189
  getGeneration,
@@ -2314,6 +3200,9 @@ export {
2314
3200
  generationErrorMessage,
2315
3201
  initEmbed,
2316
3202
  isEmbedded,
3203
+ getEntry,
3204
+ getShell,
3205
+ onShellClosing,
2317
3206
  getAuthState,
2318
3207
  getUser,
2319
3208
  getEmbedToken,