@bounded-sh/client 0.0.61 → 0.0.64

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.
Files changed (58) hide show
  1. package/dist/auth/bounded-login-widget.d.ts +1 -1
  2. package/dist/auth/index.d.ts +4 -5
  3. package/dist/auth/providers/email-auth-provider.d.ts +4 -4
  4. package/dist/auth/turnkey-signer-bridge.d.ts +5 -0
  5. package/dist/{email-auth-provider-9BwSziWj.js → email-auth-provider-97CluDlZ.js} +27 -30
  6. package/dist/email-auth-provider-97CluDlZ.js.map +1 -0
  7. package/dist/{email-auth-provider-BttT2sZK.js → email-auth-provider-CKM4O5Z1.js} +27 -30
  8. package/dist/email-auth-provider-CKM4O5Z1.js.map +1 -0
  9. package/dist/{email-auth-provider-B3XaJw-G.mjs → email-auth-provider-h0fPnU76.mjs} +27 -30
  10. package/dist/email-auth-provider-h0fPnU76.mjs.map +1 -0
  11. package/dist/{email-auth-provider-Cb4VKA1E.mjs → email-auth-provider-v9xvY0Ky.mjs} +27 -30
  12. package/dist/email-auth-provider-v9xvY0Ky.mjs.map +1 -0
  13. package/dist/{guest-auth-provider-BBSFawAr.mjs → guest-auth-provider-BLRbjAv2.mjs} +2 -2
  14. package/dist/{guest-auth-provider-BBPpydtM.mjs.map → guest-auth-provider-BLRbjAv2.mjs.map} +1 -1
  15. package/dist/{guest-auth-provider-Di0TRg-z.js → guest-auth-provider-BvIf5W5c.js} +2 -2
  16. package/dist/{guest-auth-provider-Di0TRg-z.js.map → guest-auth-provider-BvIf5W5c.js.map} +1 -1
  17. package/dist/{guest-auth-provider-BcR-MQ0g.js → guest-auth-provider-CLnFuodt.js} +2 -2
  18. package/dist/{guest-auth-provider-BcR-MQ0g.js.map → guest-auth-provider-CLnFuodt.js.map} +1 -1
  19. package/dist/{guest-auth-provider-BBPpydtM.mjs → guest-auth-provider-Dmup2WIL.mjs} +2 -2
  20. package/dist/{guest-auth-provider-BBSFawAr.mjs.map → guest-auth-provider-Dmup2WIL.mjs.map} +1 -1
  21. package/dist/{index-L2R6C5Vl.mjs → index-7yz-Olrm.mjs} +1371 -1525
  22. package/dist/index-7yz-Olrm.mjs.map +1 -0
  23. package/dist/{index-C_L497w1.js → index-Bk0nEjB6.js} +1373 -1528
  24. package/dist/index-Bk0nEjB6.js.map +1 -0
  25. package/dist/index.js +1 -1
  26. package/dist/index.mjs +1 -1
  27. package/dist/{index.native-BIUs8t7F.mjs → index.native-CWcQMPZd.mjs} +518 -221
  28. package/dist/index.native-CWcQMPZd.mjs.map +1 -0
  29. package/dist/{index.native-BSheiGj2.js → index.native-Do-VhPUG.js} +520 -224
  30. package/dist/index.native-Do-VhPUG.js.map +1 -0
  31. package/dist/index.native.js +1 -1
  32. package/dist/index.native.mjs +1 -1
  33. package/dist/{injected-evm-wallet-provider-DgWUaVtt.js → injected-evm-wallet-provider-B5MA0w8I.js} +2 -2
  34. package/dist/{injected-evm-wallet-provider-DgWUaVtt.js.map → injected-evm-wallet-provider-B5MA0w8I.js.map} +1 -1
  35. package/dist/{injected-evm-wallet-provider-7XawIUdJ.js → injected-evm-wallet-provider-BMiT8I-4.js} +2 -2
  36. package/dist/{injected-evm-wallet-provider-7XawIUdJ.js.map → injected-evm-wallet-provider-BMiT8I-4.js.map} +1 -1
  37. package/dist/{injected-evm-wallet-provider-DSFDC8fh.mjs → injected-evm-wallet-provider-DlPsOmik.mjs} +2 -2
  38. package/dist/{injected-evm-wallet-provider-DSFDC8fh.mjs.map → injected-evm-wallet-provider-DlPsOmik.mjs.map} +1 -1
  39. package/dist/{injected-evm-wallet-provider-DnOrVMDX.mjs → injected-evm-wallet-provider-xvZq9Zli.mjs} +2 -2
  40. package/dist/{injected-evm-wallet-provider-DnOrVMDX.mjs.map → injected-evm-wallet-provider-xvZq9Zli.mjs.map} +1 -1
  41. package/dist/{injected-wallet-provider-oCRGuls5.js → injected-wallet-provider-CSj0lY9H.js} +2 -2
  42. package/dist/{injected-wallet-provider-oCRGuls5.js.map → injected-wallet-provider-CSj0lY9H.js.map} +1 -1
  43. package/dist/{injected-wallet-provider-BMDJntMD.js → injected-wallet-provider-CoE5XQQn.js} +2 -2
  44. package/dist/{injected-wallet-provider-BMDJntMD.js.map → injected-wallet-provider-CoE5XQQn.js.map} +1 -1
  45. package/dist/{injected-wallet-provider-ZkPzVj5W.mjs → injected-wallet-provider-Dd7ij6bc.mjs} +2 -2
  46. package/dist/{injected-wallet-provider-ZkPzVj5W.mjs.map → injected-wallet-provider-Dd7ij6bc.mjs.map} +1 -1
  47. package/dist/{injected-wallet-provider-DfJvN3sV.mjs → injected-wallet-provider-YHhhFzsj.mjs} +2 -2
  48. package/dist/{injected-wallet-provider-DfJvN3sV.mjs.map → injected-wallet-provider-YHhhFzsj.mjs.map} +1 -1
  49. package/package.json +2 -2
  50. package/dist/auth/crossmint-signer-bridge.d.ts +0 -45
  51. package/dist/email-auth-provider-9BwSziWj.js.map +0 -1
  52. package/dist/email-auth-provider-B3XaJw-G.mjs.map +0 -1
  53. package/dist/email-auth-provider-BttT2sZK.js.map +0 -1
  54. package/dist/email-auth-provider-Cb4VKA1E.mjs.map +0 -1
  55. package/dist/index-C_L497w1.js.map +0 -1
  56. package/dist/index-L2R6C5Vl.mjs.map +0 -1
  57. package/dist/index.native-BIUs8t7F.mjs.map +0 -1
  58. package/dist/index.native-BSheiGj2.js.map +0 -1
@@ -868,6 +868,8 @@ function getDefaultExportFromCjs (x) {
868
868
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
869
869
  }
870
870
 
871
+ var safeBuffer = {exports: {}};
872
+
871
873
  var buffer = {};
872
874
 
873
875
  var base64Js = {};
@@ -3237,10 +3239,6 @@ function requireBuffer () {
3237
3239
  return buffer;
3238
3240
  }
3239
3241
 
3240
- var bufferExports = requireBuffer();
3241
-
3242
- var safeBuffer = {exports: {}};
3243
-
3244
3242
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3245
3243
 
3246
3244
  var hasRequiredSafeBuffer;
@@ -3454,327 +3452,725 @@ var basex = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
3454
3452
  var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
3455
3453
  var bs58 = basex(ALPHABET);
3456
3454
 
3457
- // crossmint-signer-bridge.ts — routes embedded-wallet signing through the
3458
- // Bounded-owned signer popup (auth.bounded.sh/wallet/signer).
3455
+ var bufferExports = requireBuffer();
3456
+
3457
+ // bounded-widget-modal.ts - the shared in-app WIDGET shell for Bounded's login
3458
+ // and signing surfaces. One Shadow-DOM overlay + panel that matches the Bounded
3459
+ // widget (Seal) look and MOTION: a backdrop fade, a panel rise on desktop, a
3460
+ // bottom-sheet on mobile, a height tween as content swaps, and a clean close.
3459
3461
  //
3460
- // Slice-1 attached a non-custodial Crossmint smart wallet to email logins and
3461
- // populated `@user.address`. This bridge is the slice-2 counterpart: a user
3462
- // whose address came from `auth.wallets` can APPROVE transactions with that
3463
- // wallet from ANY app, non-custodially, by having the Crossmint client SDK run
3464
- // ONLY on the Bounded signer page (one whitelisted origin) and talking to it via
3465
- // postMessage.
3462
+ // It hosts EITHER:
3463
+ // - NATIVE content (the login card the SDK renders itself), or
3464
+ // - an IFRAME (the Bounded-owned signer page, which must run on the single
3465
+ // signer origin because a WebAuthn passkey is bound to one origin).
3466
3466
  //
3467
- // SEMANTICS (Crossmint Solana smart wallets): these wallets cannot produce raw
3468
- // detached signatures — there is no signMessage and no sign-without-submit. The
3469
- // only honest primitive is EXECUTION (sign + submit) via the wallet's email-OTP
3470
- // authorization. So this bridge implements `signAndSubmitTransaction` and a
3471
- // token-send; `signMessage` / `signTransaction` throw a clear unsupported error.
3472
- const EMBEDDED_WALLET_UNSUPPORTED = 'Unsupported for embedded smart wallets — Crossmint Solana smart wallets sign ' +
3473
- 'and submit atomically. Use signAndSubmitTransaction() (or bounded.sendWalletToken) ' +
3474
- 'instead of signMessage/signTransaction.';
3475
- const NO_EMBEDDED_WALLET = 'This login has no embedded wallet. Enable `"auth": { "wallets": true }` in ' +
3476
- 'the app policy so email logins get a non-custodial wallet (@user.address), ' +
3477
- 'then sign from a user gesture.';
3478
- function hasDOM$5() {
3479
- return typeof window !== 'undefined' && typeof document !== 'undefined';
3467
+ // The modal is a warm singleton: it stays mounted (hidden) between uses so a
3468
+ // second open - or a signature right after login - is instant and, when it is
3469
+ // already open, a clean in-place view swap rather than a reopen.
3470
+ function hasDOM$4() {
3471
+ return typeof window !== "undefined" && typeof document !== "undefined";
3480
3472
  }
3481
- function decodeJwt$1(token) {
3482
- try {
3483
- let b64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
3484
- const pad = b64.length % 4;
3485
- if (pad === 2)
3486
- b64 += '==';
3487
- else if (pad === 3)
3488
- b64 += '=';
3489
- return JSON.parse(bufferExports.Buffer.from(b64, 'base64').toString('utf8'));
3490
- }
3491
- catch (_a) {
3492
- return {};
3493
- }
3473
+ const OVERLAY_CSS = `
3474
+ :host{all:initial}
3475
+ *{box-sizing:border-box}
3476
+ .bw-ov{position:fixed;inset:0;z-index:2147483647;display:none;
3477
+ font-family:"Schibsted Grotesk","Helvetica Neue",Arial,sans-serif}
3478
+ .bw-ov.mounted{display:block}
3479
+ .bw-back{position:fixed;inset:0;background:rgba(4,4,5,.62);opacity:0;
3480
+ transition:opacity .24s ease;-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)}
3481
+ .bw-wrap{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:20px}
3482
+ .bw-panel{position:relative;width:420px;max-width:calc(100vw - 28px);height:280px;
3483
+ border-radius:14px;overflow:hidden;background:#0e0f11;border:1px solid rgba(232,230,222,.08);
3484
+ box-shadow:0 1px 0 rgba(232,230,222,.03) inset,0 40px 90px -45px rgba(0,0,0,.85);
3485
+ opacity:0;transform:translateY(14px) scale(.98);will-change:transform,opacity,height;
3486
+ transition:opacity .28s cubic-bezier(.2,.8,.2,1),transform .28s cubic-bezier(.2,.8,.2,1),
3487
+ height .3s cubic-bezier(.2,.8,.2,1)}
3488
+ .bw-ov.show .bw-back{opacity:1}
3489
+ .bw-ov.show .bw-panel{opacity:1;transform:none}
3490
+ .bw-ov.closing .bw-back{opacity:0}
3491
+ .bw-ov.closing .bw-panel{opacity:0;transform:translateY(12px) scale(.99)}
3492
+ .bw-content{position:absolute;inset:0;overflow:hidden}
3493
+ .bw-frame{display:block;width:100%;height:100%;border:0;background:transparent;color-scheme:dark}
3494
+ /* editorial corner crop-marks, matching the reference frame */
3495
+ .bw-mk{position:absolute;width:13px;height:13px;pointer-events:none;z-index:2;
3496
+ border-color:rgba(232,230,222,.22);border-style:solid;border-width:0}
3497
+ .bw-mk.tl{top:11px;left:11px;border-top-width:1px;border-left-width:1px}
3498
+ .bw-mk.tr{top:11px;right:11px;border-top-width:1px;border-right-width:1px}
3499
+ .bw-mk.bl{bottom:11px;left:11px;border-bottom-width:1px;border-left-width:1px}
3500
+ .bw-mk.br{bottom:11px;right:11px;border-bottom-width:1px;border-right-width:1px}
3501
+ @media(max-width:560px){
3502
+ .bw-wrap{align-items:flex-end;padding:0}
3503
+ .bw-panel{width:100%;max-width:100%;border-radius:18px 18px 0 0;border-bottom:0}
3504
+ .bw-content{overflow-y:auto}
3505
+ .bw-ov.show .bw-panel{transform:none}
3506
+ .bw-ov:not(.show) .bw-panel,.bw-ov.closing .bw-panel{transform:translateY(18%)}
3494
3507
  }
3495
- // Pull the embedded-wallet identity out of the active session's id token.
3496
- // Returns null when this session has no wallet (so callers can throw the
3497
- // informative NO_EMBEDDED_WALLET error).
3498
- function walletClaimsFromSession(chain = 'solana') {
3499
- let idToken = null;
3500
- try {
3501
- idToken = core.getActiveSessionManager().getIdToken();
3502
- }
3503
- catch (_a) {
3504
- idToken = null;
3508
+ @media(prefers-reduced-motion:reduce){.bw-back,.bw-panel{transition:opacity .12s linear!important}}
3509
+ `;
3510
+ let modal = null;
3511
+ function getModal() {
3512
+ if (modal)
3513
+ return modal;
3514
+ const root = document.createElement("div");
3515
+ root.setAttribute("data-bounded-widget", "");
3516
+ const shadow = root.attachShadow({ mode: "open" });
3517
+ const style = document.createElement("style");
3518
+ style.textContent = OVERLAY_CSS;
3519
+ shadow.appendChild(style);
3520
+ const overlay = document.createElement("div");
3521
+ overlay.className = "bw-ov";
3522
+ const back = document.createElement("div");
3523
+ back.className = "bw-back";
3524
+ const wrap = document.createElement("div");
3525
+ wrap.className = "bw-wrap";
3526
+ const panel = document.createElement("div");
3527
+ panel.className = "bw-panel";
3528
+ const content = document.createElement("div");
3529
+ content.className = "bw-content";
3530
+ panel.appendChild(content);
3531
+ for (const corner of ["tl", "tr", "bl", "br"]) {
3532
+ const mk = document.createElement("span");
3533
+ mk.className = "bw-mk " + corner;
3534
+ panel.appendChild(mk);
3505
3535
  }
3506
- if (!idToken)
3507
- return null;
3508
- const c = decodeJwt$1(idToken);
3509
- const address = c['custom:walletAddress'];
3510
- const evmAddress = c['custom:evmWalletAddress'];
3511
- const email = c['email'];
3512
- if (typeof email !== 'string' || !email)
3513
- return null;
3514
- if (chain === 'solana' && (typeof address !== 'string' || !address))
3515
- return null;
3516
- if (chain === 'evm' && (typeof evmAddress !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(evmAddress)))
3517
- return null;
3518
- const envClaim = c['custom:walletEnvironment'];
3519
- const environment = envClaim === 'staging' || envClaim === 'production' ? envClaim : undefined;
3520
- return Object.assign(Object.assign(Object.assign({ email }, (typeof address === 'string' && address ? { address } : {})), (typeof evmAddress === 'string' ? { evmAddress: evmAddress.toLowerCase() } : {})), { environment });
3521
- }
3522
- async function signerPageUrl() {
3523
- const cfg = await core.getConfig();
3524
- const base = (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
3525
- return { url: `${base}/wallet/signer`, origin: new URL(base).origin };
3526
- }
3527
- let requestSeq$1 = 0;
3528
- /**
3529
- * Open the Bounded signer popup, send `action` to it, and resolve with the
3530
- * submitted transaction result. Must be called from a USER GESTURE (click/tap) or
3531
- * the browser will block the popup — in which case this rejects with a clear
3532
- * "Popup blocked" error telling the app to call from a user gesture.
3533
- *
3534
- * Non-custodial: the popup gates signing behind an email OTP delivered to the
3535
- * wallet's owner, and validates that the wallet address matches the account.
3536
- */
3537
- async function signViaSignerPopup(action) {
3538
- if (!hasDOM$5()) {
3539
- throw new Error('Embedded-wallet signing is only available in the browser (popup-based).');
3540
- }
3541
- const isEvm = action.kind === 'evmTransaction';
3542
- const claims = walletClaimsFromSession(isEvm ? 'evm' : 'solana');
3543
- if (!claims)
3544
- throw new Error(NO_EMBEDDED_WALLET);
3545
- const { url, origin: signerOrigin } = await signerPageUrl();
3546
- const requestId = `bsign_${Date.now()}_${++requestSeq$1}`;
3547
- // Centered popup, sized for the OTP form (matches the OIDC login popup shape).
3548
- const w = 420, h = 600;
3549
- const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
3550
- const top = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
3551
- const popup = window.open(url, 'bounded-wallet-signer', `width=${w},height=${h},left=${left},top=${top}`);
3552
- if (!popup) {
3553
- throw new Error('Popup blocked — call signAndSubmitTransaction() from a user gesture (e.g. a click handler) so the wallet approval window can open.');
3554
- }
3555
- const request = {
3556
- type: 'bounded:sign',
3557
- requestId,
3558
- environment: claims.environment, // may be undefined → page auto-detects
3559
- email: claims.email,
3560
- address: isEvm ? claims.evmAddress : claims.address,
3561
- action,
3536
+ wrap.appendChild(panel);
3537
+ overlay.appendChild(back);
3538
+ overlay.appendChild(wrap);
3539
+ shadow.appendChild(overlay);
3540
+ (document.body || document.documentElement).appendChild(root);
3541
+ const m = {
3542
+ root,
3543
+ overlay,
3544
+ panel,
3545
+ content,
3546
+ iframe: null,
3547
+ iframeOrigin: "",
3548
+ iframeReady: false,
3549
+ onBackdrop: null,
3550
+ onIframeMessage: null,
3551
+ chain: Promise.resolve(),
3552
+ fitObserver: null,
3562
3553
  };
3563
- return await new Promise((resolve, reject) => {
3564
- let settled = false;
3565
- let closeTimer;
3566
- let sentRequest = false;
3567
- const cleanup = () => {
3568
- settled = true;
3569
- window.removeEventListener('message', onMsg);
3570
- if (closeTimer)
3571
- clearInterval(closeTimer);
3572
- };
3573
- const sendRequest = () => {
3574
- if (sentRequest)
3575
- return;
3576
- sentRequest = true;
3577
- try {
3578
- popup.postMessage(request, signerOrigin);
3579
- }
3580
- catch ( /* popup gone */_a) { /* popup gone */ }
3581
- };
3582
- const onMsg = (ev) => {
3583
- if (ev.origin !== signerOrigin)
3584
- return; // only trust the signer page origin
3585
- if (ev.source !== popup)
3586
- return; // only trust this signer popup window
3587
- const d = ev.data;
3588
- if (!d || typeof d !== 'object')
3589
- return;
3590
- if (d.type === 'bounded:signer:ready') {
3591
- sendRequest();
3592
- return;
3593
- }
3594
- if (d.type === 'bounded:signer:result' && d.requestId === requestId) {
3595
- cleanup();
3596
- try {
3597
- popup.close();
3598
- }
3599
- catch ( /* ignore */_a) { /* ignore */ }
3600
- if (d.ok)
3601
- resolve({ hash: d.hash, explorerLink: d.explorerLink, transactionId: d.transactionId });
3602
- else
3603
- reject(new Error(String(d.error || 'Wallet signing failed')));
3604
- }
3605
- };
3606
- window.addEventListener('message', onMsg);
3607
- // Fallback: if the ready ping was missed (fast load / focus race), push the
3608
- // request shortly after opening. The page ignores it until a bounded:sign
3609
- // arrives and only acts on the first one, so a duplicate is harmless.
3610
- setTimeout(sendRequest, 1200);
3611
- // If the user closes the popup before completing, reject (unless a result
3612
- // just arrived — give any in-flight message a beat to settle first).
3613
- closeTimer = setInterval(() => {
3614
- if (popup.closed) {
3615
- clearInterval(closeTimer);
3616
- setTimeout(() => { if (!settled) {
3617
- cleanup();
3618
- reject(new Error('Wallet approval window was closed before signing completed.'));
3619
- } }, 400);
3620
- }
3621
- }, 500);
3622
- // Overall safety timeout (OTP + signing). Generous — the user may take a
3623
- // while to fetch the code from their email.
3624
- setTimeout(() => { if (!settled) {
3625
- cleanup();
3626
- try {
3627
- popup.close();
3628
- }
3629
- catch ( /* ignore */_a) { /* ignore */ }
3630
- reject(new Error('Wallet approval timed out.'));
3631
- } }, 5 * 60 * 1000);
3554
+ // The dismiss handler lives on `.bw-wrap`: it is the full-viewport flex layer
3555
+ // that sits ABOVE `.bw-back`, so it (not the backdrop element) receives clicks
3556
+ // outside the panel. Fire only when the click lands on the wrap itself, never
3557
+ // when it bubbles up from the panel or its content.
3558
+ wrap.addEventListener("click", (event) => {
3559
+ if (event.target === wrap && m.onBackdrop)
3560
+ m.onBackdrop();
3561
+ });
3562
+ window.addEventListener("message", (event) => {
3563
+ if (!m.iframe)
3564
+ return;
3565
+ if (event.origin !== m.iframeOrigin)
3566
+ return;
3567
+ if (event.source !== m.iframe.contentWindow)
3568
+ return;
3569
+ const d = event.data;
3570
+ if (!d || typeof d !== "object")
3571
+ return;
3572
+ if (m.onIframeMessage)
3573
+ m.onIframeMessage(d);
3632
3574
  });
3575
+ modal = m;
3576
+ return m;
3633
3577
  }
3634
- // Serialize a legacy or versioned Solana transaction to BASE58 for the signer
3635
- // page. Crossmint's smart-wallet createTransaction endpoint requires the
3636
- // `serializedTransaction` string to be base58 — it rejects base64 with
3637
- // "Invalid base58 string" (verified against Crossmint staging 2026-07-07). The
3638
- // `wallets-sdk` object path bs58-encodes internally, so base58 is the contract.
3639
- //
3640
- // We do NOT require existing signatures (the smart wallet signs on the page);
3641
- // Crossmint extracts the instructions, overrides the fee payer to its sponsor,
3642
- // and re-wraps them for the smart wallet.
3643
- function serializeTransaction(transaction) {
3644
- const isLegacy = 'recentBlockhash' in transaction &&
3645
- !('message' in transaction && 'staticAccountKeys' in transaction.message);
3646
- const bytes = isLegacy
3647
- ? transaction.serialize({ requireAllSignatures: false, verifySignatures: false })
3648
- : transaction.serialize();
3649
- return bs58.encode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
3578
+ function showModal(m) {
3579
+ m.overlay.classList.remove("closing");
3580
+ m.overlay.classList.add("mounted");
3581
+ // Force a reflow so the .show transition runs from the hidden state every open.
3582
+ void m.panel.offsetWidth;
3583
+ m.overlay.classList.add("show");
3584
+ }
3585
+ function hideModal(m, after) {
3586
+ m.overlay.classList.remove("show");
3587
+ m.overlay.classList.add("closing");
3588
+ window.setTimeout(() => {
3589
+ m.overlay.classList.remove("mounted", "closing");
3590
+ }, 260);
3591
+ }
3592
+ function setPanelHeight(m, px) {
3593
+ const h = Math.max(140, Math.min(680, Math.round(px)));
3594
+ m.panel.style.height = h + "px";
3595
+ }
3596
+ // True outer height of the mounted card: the max of its padding-box scroll height
3597
+ // (catches overflowing descendants) and its border-box height plus own vertical
3598
+ // margins (catches border + margins, which scrollHeight omits). Ceiled so a
3599
+ // sub-pixel row is never clipped under `overflow:hidden`.
3600
+ function measureOuterHeight(target) {
3601
+ var _a;
3602
+ const cs = (_a = target.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.getComputedStyle(target);
3603
+ const marginY = cs ? parseFloat(cs.marginTop) + parseFloat(cs.marginBottom) : 0;
3604
+ const borderBox = target.offsetHeight + (Number.isFinite(marginY) ? marginY : 0);
3605
+ const rect = target.getBoundingClientRect().height;
3606
+ return Math.ceil(Math.max(target.scrollHeight, borderBox, rect));
3650
3607
  }
3651
3608
  /**
3652
- * Whether the active session carries an embedded wallet (so the provider should
3653
- * route signing through the popup rather than throw "no wallet").
3609
+ * Measure the currently mounted native content and tween the panel to fit it.
3610
+ * Re-fits automatically when the card's intrinsic height changes - notably after
3611
+ * the Newsreader/Schibsted web fonts swap in (which grows line boxes a few px
3612
+ * after first paint) and on inline view swaps (email -> OTP code -> success).
3654
3613
  */
3655
- function hasEmbeddedWallet() {
3656
- return walletClaimsFromSession() != null;
3657
- }
3658
- /** Whether the active email/social session carries an embedded Crossmint EVM wallet. */
3659
- function hasEmbeddedEvmWallet() {
3660
- return walletClaimsFromSession('evm') != null;
3661
- }
3662
- /** signAndSubmitTransaction for embedded wallets: serialize + route through the
3663
- * signer popup, resolve with the on-chain transaction signature/hash. */
3664
- async function embeddedSignAndSubmit(transaction) {
3665
- const serializedTransaction = serializeTransaction(transaction);
3666
- const result = await signViaSignerPopup({ kind: 'transaction', serializedTransaction });
3667
- const hash = result.hash || result.transactionId;
3668
- if (!hash)
3669
- throw new Error('Signer returned no transaction hash.');
3670
- return hash;
3671
- }
3672
- /** Submit a validated BoundedRuntime EVM write through the user's email signer. */
3673
- async function embeddedRunEvmTransaction(transaction) {
3614
+ function fitPanelToContent(m) {
3674
3615
  var _a, _b;
3675
- if (!transaction.to || !transaction.data || !transaction.chainId)
3676
- throw new Error('Incomplete embedded EVM transaction');
3677
- if (!/^0x[0-9a-fA-F]{40}$/.test(transaction.to))
3678
- throw new Error('Invalid embedded EVM runtime address');
3679
- core.assertCanonicalBoundedRuntimeWriteCalldata(transaction.data);
3680
- if (!Number.isSafeInteger(transaction.chainId) || transaction.chainId <= 0)
3681
- throw new Error('Invalid embedded EVM chain id');
3682
- if (transaction.nonce !== undefined)
3683
- throw new Error('Server-supplied EVM nonces are not accepted');
3684
- try {
3685
- if (BigInt((_a = transaction.value) !== null && _a !== void 0 ? _a : '0') !== BigInt(0))
3686
- throw new Error('Bounded EVM writes cannot transfer native value');
3687
- }
3688
- catch (error) {
3689
- if (error instanceof Error && error.message.includes('cannot transfer'))
3690
- throw error;
3691
- throw new Error('Invalid embedded EVM transaction value');
3616
+ const first = m.content.firstElementChild;
3617
+ const target = first || m.content;
3618
+ const apply = () => {
3619
+ // Only fit while this exact node is still the mounted card.
3620
+ if (m.content.firstElementChild !== first && first)
3621
+ return;
3622
+ const h = measureOuterHeight(target);
3623
+ if (h > 0)
3624
+ setPanelHeight(m, h);
3625
+ };
3626
+ apply();
3627
+ const view = target.ownerDocument.defaultView;
3628
+ // Re-fit after fonts load (one-shot) and once the ResizeObserver-less browsers
3629
+ // have painted, so the height never lags a late reflow.
3630
+ (_a = view === null || view === void 0 ? void 0 : view.requestAnimationFrame) === null || _a === void 0 ? void 0 : _a.call(view, apply);
3631
+ const fonts = target.ownerDocument.fonts;
3632
+ if (fonts === null || fonts === void 0 ? void 0 : fonts.ready)
3633
+ fonts.ready.then(apply).catch(() => { });
3634
+ (_b = m.fitObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
3635
+ m.fitObserver = null;
3636
+ if (first && typeof (view === null || view === void 0 ? void 0 : view.ResizeObserver) === "function") {
3637
+ const ro = new view.ResizeObserver(() => apply());
3638
+ ro.observe(first);
3639
+ m.fitObserver = ro;
3692
3640
  }
3693
- const result = await signViaSignerPopup({
3694
- kind: 'evmTransaction',
3695
- transaction: { to: transaction.to, data: transaction.data, value: (_b = transaction.value) !== null && _b !== void 0 ? _b : '0', chainId: transaction.chainId },
3696
- });
3697
- const hash = result.hash || result.transactionId;
3698
- if (!hash)
3699
- throw new Error('Signer returned no EVM transaction hash.');
3700
- return { transactionSignature: hash, blockNumber: 0, gasUsed: '0', data: result };
3641
+ }
3642
+ /** Switch the modal into NATIVE-content mode: detach any iframe, mount `node`. */
3643
+ function mountContent(m, node) {
3644
+ var _a;
3645
+ detachIframe(m);
3646
+ (_a = m.fitObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
3647
+ m.fitObserver = null;
3648
+ m.content.replaceChildren(node);
3649
+ m.content.style.display = "block";
3650
+ }
3651
+ /** Get (or lazily create) the warm iframe for signer/hosted-page mode. */
3652
+ function ensureIframe(m, url, origin) {
3653
+ var _a;
3654
+ if (m.iframe && m.iframeOrigin === origin && m.iframe.src === url)
3655
+ return m.iframe;
3656
+ detachIframe(m);
3657
+ (_a = m.fitObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
3658
+ m.fitObserver = null;
3659
+ m.content.style.display = "none";
3660
+ const iframe = document.createElement("iframe");
3661
+ iframe.className = "bw-frame";
3662
+ iframe.setAttribute("title", "Bounded");
3663
+ // Grant the framed origin WebAuthn get + create so passkey enroll/sign run
3664
+ // inside the frame from the user's click (transient activation stays in-frame).
3665
+ iframe.setAttribute("allow", "publickey-credentials-get; publickey-credentials-create; clipboard-write");
3666
+ iframe.src = url;
3667
+ m.iframeOrigin = origin;
3668
+ m.iframeReady = false;
3669
+ m.panel.appendChild(iframe);
3670
+ m.iframe = iframe;
3671
+ return iframe;
3672
+ }
3673
+ function detachIframe(m) {
3674
+ if (m.iframe) {
3675
+ try {
3676
+ m.iframe.remove();
3677
+ }
3678
+ catch (_a) {
3679
+ /* ignore */
3680
+ }
3681
+ }
3682
+ m.iframe = null;
3683
+ m.iframeReady = false;
3684
+ m.iframeOrigin = "";
3685
+ m.onIframeMessage = null;
3686
+ }
3687
+ // Load the Bounded editorial typefaces (Newsreader display + Schibsted Grotesk body +
3688
+ // JetBrains Mono) once at the document level so they apply inside the shadow root. A
3689
+ // no-op if already present or off-DOM. Fonts loaded here match the hosted auth page.
3690
+ const FONTS_HREF = "https://fonts.googleapis.com/css2?family=Newsreader:opsz,wght@6..72,400;6..72,500&family=Schibsted+Grotesk:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";
3691
+ function ensureFonts() {
3692
+ if (!hasDOM$4())
3693
+ return;
3694
+ if (document.querySelector('link[data-bounded-fonts="1"]'))
3695
+ return;
3696
+ const pre1 = document.createElement("link");
3697
+ pre1.rel = "preconnect";
3698
+ pre1.href = "https://fonts.googleapis.com";
3699
+ const pre2 = document.createElement("link");
3700
+ pre2.rel = "preconnect";
3701
+ pre2.href = "https://fonts.gstatic.com";
3702
+ pre2.crossOrigin = "anonymous";
3703
+ const link = document.createElement("link");
3704
+ link.rel = "stylesheet";
3705
+ link.href = FONTS_HREF;
3706
+ link.setAttribute("data-bounded-fonts", "1");
3707
+ document.head.append(pre1, pre2, link);
3701
3708
  }
3702
3709
 
3703
- // Same message the email provider uses when a hosted (OIDC) login has no
3704
- // embedded wallet — enable `auth.wallets` in policy to get one.
3705
- const OIDC_NO_WALLET = 'This login has no embedded wallet. Enable `"auth": { "wallets": true }` in ' +
3706
- 'the app policy so logins get a non-custodial Crossmint wallet (@user.address), ' +
3707
- 'then sign from a user gesture.';
3708
- const PKCE_STORE_KEY = 'bounded.oidc.pkce';
3709
- const STORED_AUTH_METHOD_KEY$1 = 'bounded_last_auth_method';
3710
- const ISSUER_SESSION_KIND_KEY$1 = 'bounded_issuer_session_kind';
3711
- // Active session store (Web on web, RN on React Native) — selected by config,
3712
- // not by `typeof window` (truthy on RN). OIDC redirect/popup is web-only, but the
3713
- // session it mints is read back through this same selector everywhere.
3714
- const sessionManager = core.getActiveSessionManager;
3715
- function hasDOM$4() {
3710
+ // turnkey-wallet-widget.ts - runs one Turnkey signer exchange inside the shared
3711
+ // in-app WIDGET (bounded-widget-modal.ts). The Bounded-owned signer page is loaded
3712
+ // in a warm iframe behind the modal so signing feels native: an in-app card plus
3713
+ // the OS Face ID / Touch ID sheet, never a jarring popup.
3714
+ //
3715
+ // WHY AN IFRAME: a WebAuthn passkey is bound to ONE origin, so passkey create/sign
3716
+ // MUST run on the single Bounded signer origin. The iframe carries the
3717
+ // publickey-credentials-{get,create} permission policy and the user's click lands
3718
+ // INSIDE it, giving WebAuthn the transient activation it needs.
3719
+ //
3720
+ // SAFARI / restricted embedders: cross-origin iframe passkey CREATE is unreliable
3721
+ // in Safari. The signer detects that and posts `fallbackPopup`; we then rerun the
3722
+ // SAME request through `popupFallback` (a real window). Callers pass a popup
3723
+ // implementation and never see the difference.
3724
+ /**
3725
+ * Run one signer exchange through the in-app widget. Resolves when `onResult`
3726
+ * accepts a result; falls back to `popupFallback` if the frame cannot run WebAuthn
3727
+ * (Safari cross-origin create) or cannot be mounted.
3728
+ */
3729
+ async function runWidget(url, signerOrigin, ex, popupFallback) {
3730
+ if (!hasDOM$4())
3731
+ return popupFallback();
3732
+ const m = getModal();
3733
+ const requestId = String(ex.request.requestId);
3734
+ // Serialize: WebAuthn is modal, and one warm frame handles one request at a time.
3735
+ const run = m.chain.then(() => new Promise((resolve, reject) => {
3736
+ let settled = false;
3737
+ let usedFallback = false;
3738
+ const iframe = ensureIframe(m, url, signerOrigin);
3739
+ const send = () => {
3740
+ if (!iframe.contentWindow)
3741
+ return;
3742
+ try {
3743
+ iframe.contentWindow.postMessage(ex.request, signerOrigin);
3744
+ }
3745
+ catch (_a) {
3746
+ /* frame gone */
3747
+ }
3748
+ };
3749
+ let loadTimer = 0;
3750
+ let ceilingTimer = 0;
3751
+ const finish = (fn) => {
3752
+ if (settled)
3753
+ return;
3754
+ settled = true;
3755
+ m.onIframeMessage = null;
3756
+ m.onBackdrop = null;
3757
+ window.clearTimeout(loadTimer);
3758
+ window.clearTimeout(ceilingTimer);
3759
+ fn();
3760
+ };
3761
+ const goFallback = () => {
3762
+ if (usedFallback || settled)
3763
+ return;
3764
+ usedFallback = true;
3765
+ hideModal(m);
3766
+ finish(() => popupFallback().then(resolve, reject));
3767
+ };
3768
+ m.onBackdrop = () => {
3769
+ hideModal(m);
3770
+ finish(() => reject(new Error("cancelled")));
3771
+ };
3772
+ m.onIframeMessage = (d) => {
3773
+ if (d.type === "bounded:turnkey:ready") {
3774
+ m.iframeReady = true;
3775
+ send();
3776
+ return;
3777
+ }
3778
+ if (d.type === "bounded:turnkey:resize" && typeof d.height === "number") {
3779
+ setPanelHeight(m, d.height);
3780
+ return;
3781
+ }
3782
+ if (d.type === "bounded:turnkey:fallbackPopup" && d.requestId === requestId) {
3783
+ goFallback();
3784
+ return;
3785
+ }
3786
+ if (d.type === "bounded:turnkey:result" && d.requestId === requestId) {
3787
+ const outcome = ex.onResult(d);
3788
+ if ("error" in outcome) {
3789
+ hideModal(m);
3790
+ finish(() => reject(new Error(outcome.error)));
3791
+ return;
3792
+ }
3793
+ if (outcome.done) {
3794
+ hideModal(m);
3795
+ finish(() => resolve(outcome.value));
3796
+ }
3797
+ }
3798
+ };
3799
+ showModal(m);
3800
+ if (m.iframeReady)
3801
+ send();
3802
+ // If the frame never loads, degrade to the popup (best-effort - a post-load
3803
+ // popup may be blocked without a gesture, in which case the fallback rejects).
3804
+ loadTimer = window.setTimeout(() => {
3805
+ if (!m.iframeReady && !settled)
3806
+ goFallback();
3807
+ }, 8000);
3808
+ // Absolute ceiling so a stuck flow cannot hang forever.
3809
+ ceilingTimer = window.setTimeout(() => {
3810
+ if (!settled) {
3811
+ hideModal(m);
3812
+ finish(() => reject(new Error("Wallet approval timed out.")));
3813
+ }
3814
+ }, 5 * 60 * 1000);
3815
+ }));
3816
+ m.chain = run.then(() => undefined, () => undefined);
3817
+ return run;
3818
+ }
3819
+
3820
+ // turnkey-signer-bridge.ts - routes NON-CUSTODIAL Turnkey embedded-wallet signing
3821
+ // through the Bounded-owned signer page (auth.bounded.sh/wallet/turnkey/signer).
3822
+ //
3823
+ // TRANSPORT: by default the signer runs inside the in-app WIDGET (turnkey-wallet-
3824
+ // widget.ts) - an iframe behind a Shadow-DOM modal that matches the Bounded widget
3825
+ // look + motion, so signing feels native. Safari (unreliable at iframe passkey
3826
+ // CREATE) and any environment where the frame cannot mount fall back to a real
3827
+ // popup window; both transports speak the same postMessage protocol.
3828
+ //
3829
+ // Turnkey wallets produce raw detached signatures. The signer runs the Turnkey
3830
+ // browser SDK on the single Bounded origin and stamps an ed25519 signRawPayload
3831
+ // with the user's passkey. The app retains the transaction itself.
3832
+ //
3833
+ // ONE ORIGIN, ONE PASSKEY: a WebAuthn passkey is bound to a single origin, so ALL
3834
+ // Bounded apps (any subdomain / custom domain) sign through this one origin - giving
3835
+ // every user one wallet + one passkey that roams across every app.
3836
+ function hasDOM$3() {
3716
3837
  return typeof window !== 'undefined' && typeof document !== 'undefined';
3717
3838
  }
3718
- function decodeJwt(token) {
3839
+ // Safari (incl. iOS WebViews) is unreliable at running a WebAuthn CREATE inside a
3840
+ // cross-origin iframe, so the widget's automatic in-iframe passkey enrollment can
3841
+ // fail - and a post-failure popup would no longer have a user gesture to open with.
3842
+ // There we pick the popup up front, from the original click, so enrollment is solid.
3843
+ // Everywhere else the inline widget is used (buttery in-app modal).
3844
+ function preferPopup() {
3845
+ if (!hasDOM$3() || typeof navigator === 'undefined')
3846
+ return true;
3847
+ const ua = navigator.userAgent || '';
3848
+ return /^((?!chrome|android|crios|fxios|edg|edga|opr).)*safari/i.test(ua);
3849
+ }
3850
+ // Dispatch one signer exchange through the in-app WIDGET, degrading to the POPUP
3851
+ // when we cannot embed (Safari enrollment, or the frame never loads).
3852
+ async function deliver(url, origin, ex) {
3853
+ const popup = () => runPopup(url, origin, ex);
3854
+ if (preferPopup())
3855
+ return popup();
3856
+ return runWidget(url, origin, { request: ex.request, onResult: ex.onResult }, popup);
3857
+ }
3858
+ async function turnkeySignerPage() {
3859
+ const cfg = await core.getConfig();
3860
+ const base = (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
3861
+ return { url: `${base}/wallet/turnkey/signer`, origin: new URL(base).origin };
3862
+ }
3863
+ function toHex(bytes) {
3864
+ let h = '';
3865
+ for (const b of bytes)
3866
+ h += b.toString(16).padStart(2, '0');
3867
+ return h;
3868
+ }
3869
+ function fromHex(hex) {
3870
+ const clean = hex.startsWith('0x') ? hex.slice(2) : hex;
3871
+ const out = new Uint8Array(clean.length / 2);
3872
+ for (let i = 0; i < out.length; i++)
3873
+ out[i] = parseInt(clean.substr(i * 2, 2), 16);
3874
+ return out;
3875
+ }
3876
+ function decodeJwt$1(token) {
3719
3877
  try {
3720
- let b64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
3721
- const pad = b64.length % 4;
3722
- if (pad === 2)
3723
- b64 += '==';
3724
- else if (pad === 3)
3725
- b64 += '=';
3726
- return JSON.parse(getPlatform().atob(b64));
3878
+ let value = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
3879
+ const padding = value.length % 4;
3880
+ if (padding === 2)
3881
+ value += '==';
3882
+ else if (padding === 3)
3883
+ value += '=';
3884
+ return JSON.parse(getPlatform().atob(value));
3727
3885
  }
3728
3886
  catch (_a) {
3729
3887
  return {};
3730
3888
  }
3731
3889
  }
3732
- // A minimal AuthProvider so getSession()/logout() work for OIDC sessions, mirroring email.
3733
- // Signing surface (slice 2): a hosted login on a wallets-enabled app carries an
3734
- // embedded Crossmint wallet (@user.address). signAndSubmitTransaction routes
3735
- // through the Bounded signer popup; signMessage/signTransaction are structurally
3736
- // unsupported for Crossmint smart wallets (sign+submit atomically, no raw sig).
3737
- const oidcProviderSingleton = {
3738
- async login() {
3739
- const idToken = sessionManager().getIdToken();
3740
- return idToken ? userFromIdToken(idToken) : null;
3741
- },
3742
- async getUser() {
3743
- const idToken = sessionManager().getIdToken();
3744
- return idToken ? userFromIdToken(idToken) : null;
3890
+ function activeTurnkeyAddress() {
3891
+ let token = null;
3892
+ try {
3893
+ token = core.getActiveSessionManager().getIdToken();
3894
+ }
3895
+ catch (_a) {
3896
+ token = null;
3897
+ }
3898
+ if (!token)
3899
+ return null;
3900
+ const claims = decodeJwt$1(token);
3901
+ const address = claims['custom:walletAddress'];
3902
+ const provider = claims['custom:walletProvider'];
3903
+ return provider === 'turnkey' && typeof address === 'string' && address
3904
+ ? address
3905
+ : null;
3906
+ }
3907
+ let requestSeq = 0;
3908
+ // Shared popup driver: open the signer page, do the ready/postMessage handshake, and
3909
+ // resolve when `onResult` accepts a result message. Origin + source are pinned.
3910
+ async function runPopup(url, signerOrigin, ex) {
3911
+ var _a, _b;
3912
+ const w = (_a = ex.width) !== null && _a !== void 0 ? _a : 420, h = (_b = ex.height) !== null && _b !== void 0 ? _b : 620;
3913
+ const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
3914
+ const top = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
3915
+ const popup = window.open(url, 'bounded-turnkey-signer', `width=${w},height=${h},left=${left},top=${top}`);
3916
+ if (!popup) {
3917
+ throw new Error('Popup blocked - call this from a user gesture (e.g. a click handler) so the passkey approval window can open.');
3918
+ }
3919
+ return await new Promise((resolve, reject) => {
3920
+ let settled = false;
3921
+ let sentRequest = false;
3922
+ let closeTimer;
3923
+ const cleanup = () => { settled = true; window.removeEventListener('message', onMsg); if (closeTimer)
3924
+ clearInterval(closeTimer); };
3925
+ const sendRequest = () => { if (sentRequest)
3926
+ return; sentRequest = true; try {
3927
+ popup.postMessage(ex.request, signerOrigin);
3928
+ }
3929
+ catch ( /* popup gone */_a) { /* popup gone */ } };
3930
+ const onMsg = (event) => {
3931
+ if (event.origin !== signerOrigin)
3932
+ return;
3933
+ if (event.source !== popup)
3934
+ return;
3935
+ const d = event.data;
3936
+ if (!d || typeof d !== 'object')
3937
+ return;
3938
+ if (d.type === 'bounded:turnkey:ready') {
3939
+ sendRequest();
3940
+ return;
3941
+ }
3942
+ if (d.type === 'bounded:turnkey:result' && d.requestId === ex.request.requestId) {
3943
+ const outcome = ex.onResult(d);
3944
+ if ('error' in outcome) {
3945
+ cleanup();
3946
+ try {
3947
+ popup.close();
3948
+ }
3949
+ catch ( /* ignore */_a) { /* ignore */ }
3950
+ reject(new Error(outcome.error));
3951
+ return;
3952
+ }
3953
+ if (outcome.done) {
3954
+ cleanup();
3955
+ try {
3956
+ popup.close();
3957
+ }
3958
+ catch ( /* ignore */_b) { /* ignore */ }
3959
+ resolve(outcome.value);
3960
+ }
3961
+ }
3962
+ };
3963
+ window.addEventListener('message', onMsg);
3964
+ setTimeout(sendRequest, 1200);
3965
+ closeTimer = setInterval(() => {
3966
+ if (popup.closed) {
3967
+ clearInterval(closeTimer);
3968
+ setTimeout(() => { if (!settled) {
3969
+ cleanup();
3970
+ reject(new Error('Wallet approval window was closed before it completed.'));
3971
+ } }, 400);
3972
+ }
3973
+ }, 500);
3974
+ setTimeout(() => { if (!settled) {
3975
+ cleanup();
3976
+ try {
3977
+ popup.close();
3978
+ }
3979
+ catch ( /* ignore */_a) { /* ignore */ }
3980
+ reject(new Error('Wallet approval timed out.'));
3981
+ } }, 5 * 60 * 1000);
3982
+ });
3983
+ }
3984
+ function hasTurnkeyWallet() {
3985
+ return activeTurnkeyAddress() !== null;
3986
+ }
3987
+ /**
3988
+ * Get-or-create the user's non-custodial Turnkey wallet, resolving with its stable
3989
+ * Solana address. On first use the popup enrolls a device passkey (Face ID / Touch ID)
3990
+ * and creates the wallet (lazy) with no email code; if the wallet already exists it
3991
+ * resolves immediately without a prompt. Call from a USER GESTURE.
3992
+ *
3993
+ * Use this to learn the fee-payer address BEFORE building a transaction to sign.
3994
+ */
3995
+ async function getOrCreateTurnkeyWallet() {
3996
+ if (!hasDOM$3())
3997
+ throw new Error('Turnkey embedded wallets are only available in the browser (popup-based).');
3998
+ const { url, origin } = await turnkeySignerPage();
3999
+ const requestId = `tkcreate_${Date.now()}_${++requestSeq}`;
4000
+ return await deliver(url, origin, {
4001
+ request: { type: 'bounded:turnkey:createWallet', requestId },
4002
+ onResult: (d) => {
4003
+ if (d.ok && typeof d.address === 'string')
4004
+ return { done: true, value: { address: d.address, subOrgId: String(d.subOrgId || '') } };
4005
+ return { error: String(d.error || 'Wallet setup failed') };
4006
+ },
4007
+ });
4008
+ }
4009
+ /**
4010
+ * Open the Bounded Turnkey signer popup and sign `message` (raw bytes) with the
4011
+ * user's non-custodial Turnkey wallet, resolving with the ed25519 signature +
4012
+ * the wallet address. MUST be called from a USER GESTURE (click/tap) or the
4013
+ * browser blocks the popup.
4014
+ *
4015
+ * On the user's FIRST signature the popup transparently enrolls a device passkey
4016
+ * (Face ID / Touch ID) and creates their wallet - no email code. Subsequent
4017
+ * signatures are just a passkey approval.
4018
+ */
4019
+ async function signSolanaMessageViaTurnkey(message) {
4020
+ if (!hasDOM$3()) {
4021
+ throw new Error('Turnkey embedded-wallet signing is only available in the browser (popup-based).');
4022
+ }
4023
+ const { url, origin } = await turnkeySignerPage();
4024
+ const requestId = `tksign_${Date.now()}_${++requestSeq}`;
4025
+ const messageHex = toHex(message);
4026
+ return await deliver(url, origin, {
4027
+ request: { type: 'bounded:turnkey:sign', requestId, messageHex },
4028
+ onResult: (d) => {
4029
+ if (d.ok && typeof d.signatureHex === 'string' && typeof d.address === 'string') {
4030
+ return { done: true, value: { signature: fromHex(d.signatureHex), address: d.address, subOrgId: String(d.subOrgId || '') } };
4031
+ }
4032
+ return { error: String(d.error || 'Turnkey signing failed') };
4033
+ },
4034
+ });
4035
+ }
4036
+ function requireMatchingAddress(result) {
4037
+ const expected = activeTurnkeyAddress();
4038
+ if (!expected)
4039
+ throw new Error('This session has no Turnkey wallet. Sign in again to provision one.');
4040
+ if (result.address !== expected)
4041
+ throw new Error('Turnkey signer returned a different wallet address than the active session.');
4042
+ return expected;
4043
+ }
4044
+ async function signMessageWithTurnkey(message) {
4045
+ const result = await signSolanaMessageViaTurnkey(getPlatform().textEncode(message));
4046
+ requireMatchingAddress(result);
4047
+ return bs58.encode(result.signature);
4048
+ }
4049
+ async function signTransactionWithTurnkey(transaction) {
4050
+ const isLegacy = 'serializeMessage' in transaction;
4051
+ const message = isLegacy
4052
+ ? transaction.serializeMessage()
4053
+ : transaction.message.serialize();
4054
+ const result = await signSolanaMessageViaTurnkey(new Uint8Array(message));
4055
+ const address = requireMatchingAddress(result);
4056
+ const { PublicKey } = await import('@solana/web3.js');
4057
+ if (isLegacy) {
4058
+ transaction.addSignature(new PublicKey(address), bufferExports.Buffer.from(result.signature));
4059
+ }
4060
+ else {
4061
+ transaction.addSignature(new PublicKey(address), result.signature);
4062
+ }
4063
+ return transaction;
4064
+ }
4065
+ async function signAndSubmitTransactionWithTurnkey(transaction, feePayer) {
4066
+ var _a;
4067
+ const config = await core.getConfig();
4068
+ const rpcUrl = (_a = config.rpcUrl) === null || _a === void 0 ? void 0 : _a.trim();
4069
+ if (!rpcUrl)
4070
+ throw new Error('Turnkey transaction submission requires init({ rpcUrl }).');
4071
+ const { Connection, PublicKey } = await import('@solana/web3.js');
4072
+ const connection = new Connection(rpcUrl, 'confirmed');
4073
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
4074
+ const isLegacy = 'serializeMessage' in transaction;
4075
+ if (isLegacy) {
4076
+ const legacy = transaction;
4077
+ legacy.recentBlockhash = blockhash;
4078
+ legacy.lastValidBlockHeight = lastValidBlockHeight;
4079
+ if (!legacy.feePayer) {
4080
+ const address = activeTurnkeyAddress();
4081
+ if (!address)
4082
+ throw new Error('This session has no Turnkey wallet. Sign in again to provision one.');
4083
+ legacy.feePayer = feePayer !== null && feePayer !== void 0 ? feePayer : new PublicKey(address);
4084
+ }
4085
+ }
4086
+ else {
4087
+ transaction.message.recentBlockhash = blockhash;
4088
+ }
4089
+ const signed = await signTransactionWithTurnkey(transaction);
4090
+ const signature = await connection.sendRawTransaction(signed.serialize(), {
4091
+ skipPreflight: false,
4092
+ maxRetries: 3,
4093
+ });
4094
+ const confirmation = await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
4095
+ if (confirmation.value.err) {
4096
+ throw new Error(`Turnkey transaction failed: ${JSON.stringify(confirmation.value.err)}`);
4097
+ }
4098
+ return signature;
4099
+ }
4100
+
4101
+ // Same message the email provider uses when a hosted (OIDC) login has no
4102
+ // embedded wallet — enable `auth.wallets` in policy to get one.
4103
+ const OIDC_NO_WALLET = 'This session has no Turnkey wallet. Sign in again to provision the default ' +
4104
+ 'embedded wallet, or check whether the app explicitly sets auth.wallets:false.';
4105
+ const PKCE_STORE_KEY = 'bounded.oidc.pkce';
4106
+ const STORED_AUTH_METHOD_KEY$1 = 'bounded_last_auth_method';
4107
+ const ISSUER_SESSION_KIND_KEY$1 = 'bounded_issuer_session_kind';
4108
+ // Active session store (Web on web, RN on React Native) — selected by config,
4109
+ // not by `typeof window` (truthy on RN). OIDC redirect/popup is web-only, but the
4110
+ // session it mints is read back through this same selector everywhere.
4111
+ const sessionManager = core.getActiveSessionManager;
4112
+ function hasDOM$2() {
4113
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
4114
+ }
4115
+ function decodeJwt(token) {
4116
+ try {
4117
+ let b64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
4118
+ const pad = b64.length % 4;
4119
+ if (pad === 2)
4120
+ b64 += '==';
4121
+ else if (pad === 3)
4122
+ b64 += '=';
4123
+ return JSON.parse(getPlatform().atob(b64));
4124
+ }
4125
+ catch (_a) {
4126
+ return {};
4127
+ }
4128
+ }
4129
+ // A minimal AuthProvider so getSession()/logout() work for OIDC sessions, mirroring email.
4130
+ // Turnkey supplies the default Solana wallet and supports raw message and transaction
4131
+ // signatures through the Bounded signer window.
4132
+ const oidcProviderSingleton = {
4133
+ async login() {
4134
+ const idToken = sessionManager().getIdToken();
4135
+ return idToken ? userFromIdToken(idToken) : null;
4136
+ },
4137
+ async getUser() {
4138
+ const idToken = sessionManager().getIdToken();
4139
+ return idToken ? userFromIdToken(idToken) : null;
3745
4140
  },
3746
4141
  async logout() { await sessionManager().clearSession(); },
3747
- async signMessage(_message) {
3748
- throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : OIDC_NO_WALLET);
4142
+ async signMessage(message) {
4143
+ if (!hasTurnkeyWallet())
4144
+ throw new Error(OIDC_NO_WALLET);
4145
+ return signMessageWithTurnkey(message);
3749
4146
  },
3750
- async signTransaction(_t) {
3751
- throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : OIDC_NO_WALLET);
4147
+ async signTransaction(transaction) {
4148
+ if (!hasTurnkeyWallet())
4149
+ throw new Error(OIDC_NO_WALLET);
4150
+ return signTransactionWithTurnkey(transaction);
3752
4151
  },
3753
- async runTransaction(evm, sol, options) {
4152
+ async runTransaction(evm, sol, _options) {
3754
4153
  if (evm && sol)
3755
4154
  throw new Error('A transaction cannot target EVM and Solana at the same time.');
3756
- if (!evm)
4155
+ if (!hasTurnkeyWallet())
3757
4156
  throw new Error(OIDC_NO_WALLET);
3758
- if ((options === null || options === void 0 ? void 0 : options.shouldSubmitTx) === false)
3759
- throw new Error('Embedded EVM wallets sign and submit atomically; shouldSubmitTx:false is unsupported.');
3760
- if (!hasEmbeddedEvmWallet())
3761
- throw new Error('This login has no embedded EVM wallet. Enable auth.wallets on an app with an EVM collection and sign in again.');
3762
- return embeddedRunEvmTransaction(evm);
4157
+ if (evm)
4158
+ throw new Error('Turnkey embedded wallets currently support Solana only. Connect an EVM wallet for EVM transactions.');
4159
+ throw new Error('This Solana transaction shape is not supported by the Turnkey provider. Use a pre-built transaction.');
3763
4160
  },
3764
- async signAndSubmitTransaction(transaction, _feePayer) {
3765
- if (!hasEmbeddedWallet())
4161
+ async signAndSubmitTransaction(transaction, feePayer) {
4162
+ if (!hasTurnkeyWallet())
3766
4163
  throw new Error(OIDC_NO_WALLET);
3767
- return embeddedSignAndSubmit(transaction);
4164
+ return signAndSubmitTransactionWithTurnkey(transaction, feePayer);
3768
4165
  },
3769
4166
  };
3770
4167
  function userFromIdToken(idToken) {
3771
4168
  const c = decodeJwt(idToken);
3772
4169
  const id = c['custom:userId'] || c.sub || c['custom:walletAddress'] || '';
3773
4170
  return {
3774
- id, address: (c['custom:walletAddress'] || null),
3775
- evmAddress: typeof c['custom:evmWalletAddress'] === 'string' && /^0x[0-9a-fA-F]{40}$/.test(c['custom:evmWalletAddress'])
3776
- ? c['custom:evmWalletAddress'].toLowerCase()
3777
- : null,
4171
+ id,
4172
+ address: (c['custom:walletProvider'] === 'turnkey' && c['custom:walletAddress'] || null),
4173
+ evmAddress: null,
3778
4174
  email: (c.email || null), provider: oidcProviderSingleton,
3779
4175
  };
3780
4176
  }
@@ -3852,7 +4248,7 @@ async function buildAuthorize(opts) {
3852
4248
  throw new Error('appId is not configured (init the SDK with your appId)');
3853
4249
  // Web: default to the current page so callers don't have to pass redirectUri. Native has no
3854
4250
  // window — it MUST pass an https universal link (the system auth session needs a real URL).
3855
- const redirectUri = opts.redirectUri || (hasDOM$4() ? window.location.origin + window.location.pathname : undefined);
4251
+ const redirectUri = opts.redirectUri || (hasDOM$2() ? window.location.origin + window.location.pathname : undefined);
3856
4252
  if (!redirectUri)
3857
4253
  throw new Error('redirectUri is required on React Native — pass the https universal link the app owner registered.');
3858
4254
  const { verifier, challenge } = await makePkce();
@@ -3960,7 +4356,7 @@ async function runNativeLogin(opts) {
3960
4356
  async function loginWithRedirect(opts) {
3961
4357
  if (isNative())
3962
4358
  return runNativeLogin(opts);
3963
- if (!hasDOM$4())
4359
+ if (!hasDOM$2())
3964
4360
  throw new Error('loginWithRedirect requires a browser or a configured React Native platform');
3965
4361
  const { url, pkce } = await buildAuthorize(opts);
3966
4362
  // Stash the verifier + state so the redirect_uri page can finish the exchange. sessionStorage
@@ -3976,7 +4372,7 @@ async function loginWithRedirect(opts) {
3976
4372
  * loginWithRedirect() (which resolves with the User), so there is no separate redirect
3977
4373
  * page to finish from. Calling it on RN is harmless. */
3978
4374
  async function completeLoginFromRedirect() {
3979
- if (!hasDOM$4())
4375
+ if (!hasDOM$2())
3980
4376
  return null;
3981
4377
  const url = new URL(window.location.href);
3982
4378
  const code = url.searchParams.get('code');
@@ -4022,7 +4418,7 @@ async function completeLoginFromRedirect() {
4022
4418
  * redirect_uri page posts the code back. The redirect_uri page just calls the usual
4023
4419
  * completeLoginFromRedirect() (which auto-detects the popup) — no separate call needed. */
4024
4420
  async function loginWithPopup(opts) {
4025
- if (!hasDOM$4())
4421
+ if (!hasDOM$2())
4026
4422
  throw new Error('loginWithPopup is web-only — on React Native use loginWithRedirect()');
4027
4423
  // Open synchronously, before PKCE/config awaits consume the click's user-
4028
4424
  // activation window. Opening only after buildAuthorize() intermittently
@@ -4162,7 +4558,7 @@ async function loginWithPopup(opts) {
4162
4558
  /** Call this on the redirect_uri page when login was opened via loginWithPopup(): posts the
4163
4559
  * code back to the opener and closes. (For the redirect variant use completeLoginFromRedirect.) */
4164
4560
  function completeLoginInPopup(openerOrigin) {
4165
- if (!hasDOM$4() || !window.opener)
4561
+ if (!hasDOM$2() || !window.opener)
4166
4562
  return;
4167
4563
  const url = new URL(window.location.href);
4168
4564
  const code = url.searchParams.get('code');
@@ -4498,14 +4894,13 @@ function getInitConfig() {
4498
4894
  return initConfig;
4499
4895
  }
4500
4896
  /**
4501
- * Which LOGIN mode the app runs (default "bounded"). "turnkey" opts the app into
4502
- * Turnkey-native email OTP: the unified widget runs the code entry INLINE (no OIDC
4503
- * popup) via startTurnkeyEmailLogin(), and Bounded mints the session from Turnkey's
4504
- * verification. The value comes from init() config (`authMode`); a `openBoundedWidget`
4505
- * option can override it per call. Anything other than "turnkey" is "bounded".
4897
+ * Which LOGIN mode the app runs (default "turnkey"). Turnkey-native email OTP keeps
4898
+ * code entry inline in the unified widget (no OIDC popup), and Bounded mints the
4899
+ * session from Turnkey's verification. Apps can explicitly select "bounded" for the
4900
+ * legacy Better Auth email flow. A per-call openBoundedWidget option can override it.
4506
4901
  */
4507
4902
  function resolveAuthMode(config) {
4508
- return config.authMode === 'turnkey' ? 'turnkey' : 'bounded';
4903
+ return config.authMode === 'bounded' ? 'bounded' : 'turnkey';
4509
4904
  }
4510
4905
  /**
4511
4906
  * Resolve the injected-wallet-config the provider should use, merging the
@@ -4566,7 +4961,7 @@ async function getAuthProvider(config) {
4566
4961
  // manager as legacy email sessions. Human login should be started
4567
4962
  // with loginWithRedirect(); this provider is kept as the restore and
4568
4963
  // logout surface for those sessions.
4569
- currentAuthProvider = new (await Promise.resolve().then(function () { return require('./email-auth-provider-9BwSziWj.js'); })).EmailAuthProvider();
4964
+ currentAuthProvider = new (await Promise.resolve().then(function () { return require('./email-auth-provider-97CluDlZ.js'); })).EmailAuthProvider();
4570
4965
  break;
4571
4966
  case "wallet":
4572
4967
  case "phantom": {
@@ -4585,7 +4980,7 @@ async function getAuthProvider(config) {
4585
4980
  if (!isWalletLoginEnabled(config)) {
4586
4981
  throw walletLoginNotEnabledError(authMethod);
4587
4982
  }
4588
- const { InjectedWalletProvider } = await Promise.resolve().then(function () { return require('./injected-wallet-provider-oCRGuls5.js'); });
4983
+ const { InjectedWalletProvider } = await Promise.resolve().then(function () { return require('./injected-wallet-provider-CSj0lY9H.js'); });
4589
4984
  currentAuthProvider = new InjectedWalletProvider(resolveInjectedWalletConfig(config), rpcUrl, configuredNetwork);
4590
4985
  break;
4591
4986
  }
@@ -4598,7 +4993,7 @@ async function getAuthProvider(config) {
4598
4993
  // Selecting authMethod:'evm-wallet' IS the opt-in — pass evmWalletConfig
4599
4994
  // to point at a specific wallet or set chainId/domain.
4600
4995
  const evmWalletConfig = ((_a = config.evmWalletConfig) !== null && _a !== void 0 ? _a : {});
4601
- const { InjectedEvmWalletProvider } = await Promise.resolve().then(function () { return require('./injected-evm-wallet-provider-DgWUaVtt.js'); });
4996
+ const { InjectedEvmWalletProvider } = await Promise.resolve().then(function () { return require('./injected-evm-wallet-provider-B5MA0w8I.js'); });
4602
4997
  currentAuthProvider = new InjectedEvmWalletProvider(evmWalletConfig);
4603
4998
  break;
4604
4999
  }
@@ -4626,7 +5021,7 @@ async function getAuthProvider(config) {
4626
5021
  break;
4627
5022
  case "guest":
4628
5023
  // Anonymous auth: a device-local ed25519 keypair signs the challenge.
4629
- currentAuthProvider = new (await Promise.resolve().then(function () { return require('./guest-auth-provider-Di0TRg-z.js'); })).GuestAuthProvider();
5024
+ currentAuthProvider = new (await Promise.resolve().then(function () { return require('./guest-auth-provider-BvIf5W5c.js'); })).GuestAuthProvider();
4630
5025
  break;
4631
5026
  }
4632
5027
  if (!currentAuthProvider) {
@@ -4682,7 +5077,7 @@ async function signInAnonymously() {
4682
5077
  // Lazy-load the guest provider so its ed25519/web3 dependencies stay out of
4683
5078
  // the main bundle for data-only apps. Specifier is a static string literal
4684
5079
  // so bundle-splitting can see it.
4685
- const provider = new (await Promise.resolve().then(function () { return require('./guest-auth-provider-Di0TRg-z.js'); })).GuestAuthProvider();
5080
+ const provider = new (await Promise.resolve().then(function () { return require('./guest-auth-provider-BvIf5W5c.js'); })).GuestAuthProvider();
4686
5081
  setAuthLoading(true); // reflect "signing in…" while the guest keypair session is minted
4687
5082
  const commit = (user) => {
4688
5083
  // No await/interleaving inside this block: provider/method/config/marker
@@ -4833,7 +5228,7 @@ async function loginWithWallet(options) {
4833
5228
  ? Object.assign(Object.assign({}, base), { getProvider: options.getProvider }) : base;
4834
5229
  const rpcUrl = normalizeSolanaRpcUrl(cfg.rpcUrl);
4835
5230
  const network = getConfiguredSolanaNetwork(cfg);
4836
- const { InjectedWalletProvider } = await Promise.resolve().then(function () { return require('./injected-wallet-provider-oCRGuls5.js'); });
5231
+ const { InjectedWalletProvider } = await Promise.resolve().then(function () { return require('./injected-wallet-provider-CSj0lY9H.js'); });
4837
5232
  let provider = new InjectedWalletProvider(injectedConfig, rpcUrl, network);
4838
5233
  if (coreConfig.chain === 'offchain')
4839
5234
  provider = new OffchainAuthProvider(provider);
@@ -5233,276 +5628,23 @@ function setAuthProviderInstance(provider) {
5233
5628
  authProviderInstance = provider;
5234
5629
  }
5235
5630
 
5236
- // bounded-widget-modal.ts - the shared in-app WIDGET shell for Bounded's login
5237
- // and signing surfaces. One Shadow-DOM overlay + panel that matches the Bounded
5238
- // widget (Seal) look and MOTION: a backdrop fade, a panel rise on desktop, a
5239
- // bottom-sheet on mobile, a height tween as content swaps, and a clean close.
5240
- //
5241
- // It hosts EITHER:
5242
- // - NATIVE content (the login card the SDK renders itself), or
5243
- // - an IFRAME (the Bounded-owned signer page, which must run on the single
5244
- // signer origin because a WebAuthn passkey is bound to one origin).
5245
- //
5246
- // The modal is a warm singleton: it stays mounted (hidden) between uses so a
5247
- // second open - or a signature right after login - is instant and, when it is
5248
- // already open, a clean in-place view swap rather than a reopen.
5249
- function hasDOM$3() {
5250
- return typeof window !== "undefined" && typeof document !== "undefined";
5251
- }
5252
- const OVERLAY_CSS = `
5253
- :host{all:initial}
5254
- *{box-sizing:border-box}
5255
- .bw-ov{position:fixed;inset:0;z-index:2147483647;display:none;
5256
- font-family:"Schibsted Grotesk","Helvetica Neue",Arial,sans-serif}
5257
- .bw-ov.mounted{display:block}
5258
- .bw-back{position:fixed;inset:0;background:rgba(4,4,5,.62);opacity:0;
5259
- transition:opacity .24s ease;-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)}
5260
- .bw-wrap{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:20px}
5261
- .bw-panel{position:relative;width:420px;max-width:calc(100vw - 28px);height:280px;
5262
- border-radius:14px;overflow:hidden;background:#0e0f11;border:1px solid rgba(232,230,222,.08);
5263
- box-shadow:0 1px 0 rgba(232,230,222,.03) inset,0 40px 90px -45px rgba(0,0,0,.85);
5264
- opacity:0;transform:translateY(14px) scale(.98);will-change:transform,opacity,height;
5265
- transition:opacity .28s cubic-bezier(.2,.8,.2,1),transform .28s cubic-bezier(.2,.8,.2,1),
5266
- height .3s cubic-bezier(.2,.8,.2,1)}
5267
- .bw-ov.show .bw-back{opacity:1}
5268
- .bw-ov.show .bw-panel{opacity:1;transform:none}
5269
- .bw-ov.closing .bw-back{opacity:0}
5270
- .bw-ov.closing .bw-panel{opacity:0;transform:translateY(12px) scale(.99)}
5271
- .bw-content{position:absolute;inset:0;overflow:hidden}
5272
- .bw-frame{display:block;width:100%;height:100%;border:0;background:transparent;color-scheme:dark}
5273
- /* editorial corner crop-marks, matching the reference frame */
5274
- .bw-mk{position:absolute;width:13px;height:13px;pointer-events:none;z-index:2;
5275
- border-color:rgba(232,230,222,.22);border-style:solid;border-width:0}
5276
- .bw-mk.tl{top:11px;left:11px;border-top-width:1px;border-left-width:1px}
5277
- .bw-mk.tr{top:11px;right:11px;border-top-width:1px;border-right-width:1px}
5278
- .bw-mk.bl{bottom:11px;left:11px;border-bottom-width:1px;border-left-width:1px}
5279
- .bw-mk.br{bottom:11px;right:11px;border-bottom-width:1px;border-right-width:1px}
5280
- @media(max-width:560px){
5281
- .bw-wrap{align-items:flex-end;padding:0}
5282
- .bw-panel{width:100%;max-width:100%;border-radius:18px 18px 0 0;border-bottom:0}
5283
- .bw-content{overflow-y:auto}
5284
- .bw-ov.show .bw-panel{transform:none}
5285
- .bw-ov:not(.show) .bw-panel,.bw-ov.closing .bw-panel{transform:translateY(18%)}
5286
- }
5287
- @media(prefers-reduced-motion:reduce){.bw-back,.bw-panel{transition:opacity .12s linear!important}}
5288
- `;
5289
- let modal = null;
5290
- function getModal() {
5291
- if (modal)
5292
- return modal;
5293
- const root = document.createElement("div");
5294
- root.setAttribute("data-bounded-widget", "");
5295
- const shadow = root.attachShadow({ mode: "open" });
5296
- const style = document.createElement("style");
5297
- style.textContent = OVERLAY_CSS;
5298
- shadow.appendChild(style);
5299
- const overlay = document.createElement("div");
5300
- overlay.className = "bw-ov";
5301
- const back = document.createElement("div");
5302
- back.className = "bw-back";
5303
- const wrap = document.createElement("div");
5304
- wrap.className = "bw-wrap";
5305
- const panel = document.createElement("div");
5306
- panel.className = "bw-panel";
5307
- const content = document.createElement("div");
5308
- content.className = "bw-content";
5309
- panel.appendChild(content);
5310
- for (const corner of ["tl", "tr", "bl", "br"]) {
5311
- const mk = document.createElement("span");
5312
- mk.className = "bw-mk " + corner;
5313
- panel.appendChild(mk);
5314
- }
5315
- wrap.appendChild(panel);
5316
- overlay.appendChild(back);
5317
- overlay.appendChild(wrap);
5318
- shadow.appendChild(overlay);
5319
- (document.body || document.documentElement).appendChild(root);
5320
- const m = {
5321
- root,
5322
- overlay,
5323
- panel,
5324
- content,
5325
- iframe: null,
5326
- iframeOrigin: "",
5327
- iframeReady: false,
5328
- onBackdrop: null,
5329
- onIframeMessage: null,
5330
- chain: Promise.resolve(),
5331
- fitObserver: null,
5332
- };
5333
- // The dismiss handler lives on `.bw-wrap`: it is the full-viewport flex layer
5334
- // that sits ABOVE `.bw-back`, so it (not the backdrop element) receives clicks
5335
- // outside the panel. Fire only when the click lands on the wrap itself, never
5336
- // when it bubbles up from the panel or its content.
5337
- wrap.addEventListener("click", (event) => {
5338
- if (event.target === wrap && m.onBackdrop)
5339
- m.onBackdrop();
5340
- });
5341
- window.addEventListener("message", (event) => {
5342
- if (!m.iframe)
5343
- return;
5344
- if (event.origin !== m.iframeOrigin)
5345
- return;
5346
- if (event.source !== m.iframe.contentWindow)
5347
- return;
5348
- const d = event.data;
5349
- if (!d || typeof d !== "object")
5350
- return;
5351
- if (m.onIframeMessage)
5352
- m.onIframeMessage(d);
5353
- });
5354
- modal = m;
5355
- return m;
5356
- }
5357
- function showModal(m) {
5358
- m.overlay.classList.remove("closing");
5359
- m.overlay.classList.add("mounted");
5360
- // Force a reflow so the .show transition runs from the hidden state every open.
5361
- void m.panel.offsetWidth;
5362
- m.overlay.classList.add("show");
5363
- }
5364
- function hideModal(m, after) {
5365
- m.overlay.classList.remove("show");
5366
- m.overlay.classList.add("closing");
5367
- window.setTimeout(() => {
5368
- m.overlay.classList.remove("mounted", "closing");
5369
- }, 260);
5370
- }
5371
- function setPanelHeight(m, px) {
5372
- const h = Math.max(140, Math.min(680, Math.round(px)));
5373
- m.panel.style.height = h + "px";
5374
- }
5375
- // True outer height of the mounted card: the max of its padding-box scroll height
5376
- // (catches overflowing descendants) and its border-box height plus own vertical
5377
- // margins (catches border + margins, which scrollHeight omits). Ceiled so a
5378
- // sub-pixel row is never clipped under `overflow:hidden`.
5379
- function measureOuterHeight(target) {
5380
- var _a;
5381
- const cs = (_a = target.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.getComputedStyle(target);
5382
- const marginY = cs ? parseFloat(cs.marginTop) + parseFloat(cs.marginBottom) : 0;
5383
- const borderBox = target.offsetHeight + (Number.isFinite(marginY) ? marginY : 0);
5384
- const rect = target.getBoundingClientRect().height;
5385
- return Math.ceil(Math.max(target.scrollHeight, borderBox, rect));
5386
- }
5387
- /**
5388
- * Measure the currently mounted native content and tween the panel to fit it.
5389
- * Re-fits automatically when the card's intrinsic height changes - notably after
5390
- * the Newsreader/Schibsted web fonts swap in (which grows line boxes a few px
5391
- * after first paint) and on inline view swaps (email -> OTP code -> success).
5392
- */
5393
- function fitPanelToContent(m) {
5394
- var _a, _b;
5395
- const first = m.content.firstElementChild;
5396
- const target = first || m.content;
5397
- const apply = () => {
5398
- // Only fit while this exact node is still the mounted card.
5399
- if (m.content.firstElementChild !== first && first)
5400
- return;
5401
- const h = measureOuterHeight(target);
5402
- if (h > 0)
5403
- setPanelHeight(m, h);
5404
- };
5405
- apply();
5406
- const view = target.ownerDocument.defaultView;
5407
- // Re-fit after fonts load (one-shot) and once the ResizeObserver-less browsers
5408
- // have painted, so the height never lags a late reflow.
5409
- (_a = view === null || view === void 0 ? void 0 : view.requestAnimationFrame) === null || _a === void 0 ? void 0 : _a.call(view, apply);
5410
- const fonts = target.ownerDocument.fonts;
5411
- if (fonts === null || fonts === void 0 ? void 0 : fonts.ready)
5412
- fonts.ready.then(apply).catch(() => { });
5413
- (_b = m.fitObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
5414
- m.fitObserver = null;
5415
- if (first && typeof (view === null || view === void 0 ? void 0 : view.ResizeObserver) === "function") {
5416
- const ro = new view.ResizeObserver(() => apply());
5417
- ro.observe(first);
5418
- m.fitObserver = ro;
5419
- }
5420
- }
5421
- /** Switch the modal into NATIVE-content mode: detach any iframe, mount `node`. */
5422
- function mountContent(m, node) {
5423
- var _a;
5424
- detachIframe(m);
5425
- (_a = m.fitObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
5426
- m.fitObserver = null;
5427
- m.content.replaceChildren(node);
5428
- m.content.style.display = "block";
5429
- }
5430
- /** Get (or lazily create) the warm iframe for signer/hosted-page mode. */
5431
- function ensureIframe(m, url, origin) {
5432
- var _a;
5433
- if (m.iframe && m.iframeOrigin === origin && m.iframe.src === url)
5434
- return m.iframe;
5435
- detachIframe(m);
5436
- (_a = m.fitObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
5437
- m.fitObserver = null;
5438
- m.content.style.display = "none";
5439
- const iframe = document.createElement("iframe");
5440
- iframe.className = "bw-frame";
5441
- iframe.setAttribute("title", "Bounded");
5442
- // Grant the framed origin WebAuthn get + create so passkey enroll/sign run
5443
- // inside the frame from the user's click (transient activation stays in-frame).
5444
- iframe.setAttribute("allow", "publickey-credentials-get; publickey-credentials-create; clipboard-write");
5445
- iframe.src = url;
5446
- m.iframeOrigin = origin;
5447
- m.iframeReady = false;
5448
- m.panel.appendChild(iframe);
5449
- m.iframe = iframe;
5450
- return iframe;
5451
- }
5452
- function detachIframe(m) {
5453
- if (m.iframe) {
5454
- try {
5455
- m.iframe.remove();
5456
- }
5457
- catch (_a) {
5458
- /* ignore */
5459
- }
5460
- }
5461
- m.iframe = null;
5462
- m.iframeReady = false;
5463
- m.iframeOrigin = "";
5464
- m.onIframeMessage = null;
5465
- }
5466
- // Load the Bounded editorial typefaces (Newsreader display + Schibsted Grotesk body +
5467
- // JetBrains Mono) once at the document level so they apply inside the shadow root. A
5468
- // no-op if already present or off-DOM. Fonts loaded here match the hosted auth page.
5469
- const FONTS_HREF = "https://fonts.googleapis.com/css2?family=Newsreader:opsz,wght@6..72,400;6..72,500&family=Schibsted+Grotesk:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";
5470
- function ensureFonts() {
5471
- if (!hasDOM$3())
5472
- return;
5473
- if (document.querySelector('link[data-bounded-fonts="1"]'))
5474
- return;
5475
- const pre1 = document.createElement("link");
5476
- pre1.rel = "preconnect";
5477
- pre1.href = "https://fonts.googleapis.com";
5478
- const pre2 = document.createElement("link");
5479
- pre2.rel = "preconnect";
5480
- pre2.href = "https://fonts.gstatic.com";
5481
- pre2.crossOrigin = "anonymous";
5482
- const link = document.createElement("link");
5483
- link.rel = "stylesheet";
5484
- link.href = FONTS_HREF;
5485
- link.setAttribute("data-bounded-fonts", "1");
5486
- document.head.append(pre1, pre2, link);
5487
- }
5488
-
5489
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5490
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5491
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5492
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5493
- };
5494
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5495
- if (kind === "m") throw new TypeError("Private method is not writable");
5496
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5497
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5498
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5499
- };
5500
- var _AppReadyEvent_detail;
5501
- let wallets = undefined;
5502
- const registeredWalletsSet = new Set();
5503
- function addRegisteredWallet(wallet) {
5504
- cachedWalletsArray = undefined;
5505
- registeredWalletsSet.add(wallet);
5631
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5632
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5633
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5634
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5635
+ };
5636
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5637
+ if (kind === "m") throw new TypeError("Private method is not writable");
5638
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5639
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5640
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5641
+ };
5642
+ var _AppReadyEvent_detail;
5643
+ let wallets = undefined;
5644
+ const registeredWalletsSet = new Set();
5645
+ function addRegisteredWallet(wallet) {
5646
+ cachedWalletsArray = undefined;
5647
+ registeredWalletsSet.add(wallet);
5506
5648
  }
5507
5649
  function removeRegisteredWallet(wallet) {
5508
5650
  cachedWalletsArray = undefined;
@@ -5774,7 +5916,7 @@ function discoverStandardWallets() {
5774
5916
  return out;
5775
5917
  }
5776
5918
 
5777
- function hasDOM$2() {
5919
+ function hasDOM$1() {
5778
5920
  return typeof window !== 'undefined' && typeof document !== 'undefined';
5779
5921
  }
5780
5922
  async function signerOrigin() {
@@ -5851,7 +5993,7 @@ function sealOtpInIframe(code, otpEncryptionTargetBundle) {
5851
5993
  * step needs the signer iframe); on React Native use loginWithRedirect() instead.
5852
5994
  */
5853
5995
  async function startTurnkeyEmailLogin(email) {
5854
- if (!hasDOM$2()) {
5996
+ if (!hasDOM$1()) {
5855
5997
  throw new Error('Turnkey-native email login is web-only - on React Native use loginWithRedirect()');
5856
5998
  }
5857
5999
  const trimmed = email.trim();
@@ -6040,7 +6182,7 @@ function el(tag, cls, text) {
6040
6182
  */
6041
6183
  async function openBoundedWidget(opts = {}) {
6042
6184
  var _a, _b, _c, _d, _e, _f, _g, _h;
6043
- if (!hasDOM$3()) {
6185
+ if (!hasDOM$4()) {
6044
6186
  throw new Error("openBoundedWidget is web-only - on React Native use loginWithRedirect()");
6045
6187
  }
6046
6188
  // Imported lazily to avoid a static cycle with the auth index barrel.
@@ -6413,1014 +6555,718 @@ function useAuth() {
6413
6555
  // Only log errors that aren't user-initiated cancellations
6414
6556
  if (error !== 'exited_auth_flow' && (error === null || error === void 0 ? void 0 : error.message) !== 'exited_auth_flow') {
6415
6557
  console.error('Error logging in:', error);
6416
- }
6417
- setUser(null);
6418
- }
6419
- finally {
6420
- setLoading(false);
6421
- }
6422
- };
6423
- const logout$1 = async () => {
6424
- try {
6425
- setLoading(true);
6426
- await logout();
6427
- setUser(null);
6428
- }
6429
- catch (error) {
6430
- console.error('Error logging out:', error);
6431
- }
6432
- finally {
6433
- setLoading(false);
6434
- }
6435
- };
6436
- return {
6437
- login: login$1,
6438
- logout: logout$1,
6439
- loading: loading || sdkLoading,
6440
- user,
6441
- };
6442
- }
6443
-
6444
- var _a$1;
6445
- // SSR guard (mirrors useAuth): no hooks/subscriptions during Node server render.
6446
- // React Native has no `window` but DOES support hooks, so detect Node SSR
6447
- // specifically via process.versions.node.
6448
- const isSSR$1 = typeof window === 'undefined'
6449
- && typeof process !== 'undefined'
6450
- && !!((_a$1 = process.versions) === null || _a$1 === void 0 ? void 0 : _a$1.node);
6451
- function useQuery(path, options) {
6452
- if (isSSR$1) {
6453
- return { data: undefined, loading: true, error: null };
6454
- }
6455
- const [data, setData] = React__namespace.useState(undefined);
6456
- const [loading, setLoading] = React__namespace.useState(true);
6457
- const [error, setError] = React__namespace.useState(null);
6458
- // Re-subscribe only when the query actually changes (not on every render).
6459
- const optionsKey = options ? JSON.stringify(options) : '';
6460
- React__namespace.useEffect(() => {
6461
- if (!path) {
6462
- setData(undefined);
6463
- setLoading(false);
6464
- setError(null);
6465
- return;
6466
- }
6467
- let active = true;
6468
- let unsubscribe;
6469
- setLoading(true);
6470
- setError(null);
6471
- core.subscribe(path, Object.assign(Object.assign({}, options), { onData: (d) => {
6472
- if (!active)
6473
- return;
6474
- // A reconnect can legitimately surface a transport error before the
6475
- // socket re-authenticates and sends a new authorized snapshot. That
6476
- // fresh snapshot is the recovery boundary: keep the error visible
6477
- // until data arrives, then clear it so React does not remain stuck on
6478
- // a failure page after realtime has recovered.
6479
- setError(null);
6480
- setData(d);
6481
- setLoading(false);
6482
- }, onError: (e) => {
6483
- if (!active)
6484
- return;
6485
- setError(e instanceof Error ? e : new Error(String(e)));
6486
- setLoading(false);
6487
- } }))
6488
- .then((unsub) => {
6489
- if (active)
6490
- unsubscribe = unsub;
6491
- else
6492
- void unsub(); // unmounted before subscribe resolved
6493
- })
6494
- .catch((e) => {
6495
- if (!active)
6496
- return;
6497
- setError(e instanceof Error ? e : new Error(String(e)));
6498
- setLoading(false);
6499
- });
6500
- return () => {
6501
- active = false;
6502
- void (unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
6503
- };
6504
- // optionsKey captures the option object's contents; path is the other input.
6505
- // eslint-disable-next-line react-hooks/exhaustive-deps
6506
- }, [path, optionsKey]);
6507
- return { data, loading, error };
6508
- }
6509
-
6510
- // Wrapper for getIdToken - passes isServer=false for client-side usage
6511
- async function getIdToken() {
6512
- return core.getIdToken(false);
6513
- }
6514
-
6515
- var __rest = (undefined && undefined.__rest) || function (s, e) {
6516
- var t = {};
6517
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6518
- t[p] = s[p];
6519
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
6520
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6521
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
6522
- t[p[i]] = s[p[i]];
6523
- }
6524
- return t;
6525
- };
6526
- /** A structured non-2xx response from the developer API. */
6527
- class BuildsApiError extends Error {
6528
- constructor(init) {
6529
- super(init.message);
6530
- this.name = 'BuildsApiError';
6531
- this.code = init.code;
6532
- this.retryable = init.retryable;
6533
- this.status = init.status;
6534
- this.details = init.details;
6535
- this.retryAfterMs = init.retryAfterMs;
6536
- }
6537
- }
6538
- const memoryIdempotencyKeys = new Map();
6539
- const IDEMPOTENCY_STORAGE_PREFIX = 'bounded:build:idempotency:';
6540
- function retryAfterMs(response) {
6541
- var _a, _b;
6542
- const value = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(_a, 'Retry-After');
6543
- if (!value)
6544
- return undefined;
6545
- const seconds = Number(value);
6546
- if (Number.isFinite(seconds) && seconds >= 0)
6547
- return Math.ceil(seconds * 1000);
6548
- const at = Date.parse(value);
6549
- if (!Number.isFinite(at))
6550
- return undefined;
6551
- return Math.max(0, at - Date.now());
6552
- }
6553
- async function responseBody(response) {
6554
- const text = await response.text();
6555
- if (!text)
6556
- return {};
6557
- try {
6558
- return JSON.parse(text);
6559
- }
6560
- catch (_a) {
6561
- return { raw: text };
6562
- }
6563
- }
6564
- function apiError(response, body) {
6565
- const envelope = body;
6566
- const nested = (envelope === null || envelope === void 0 ? void 0 : envelope.error) && typeof envelope.error === 'object'
6567
- ? envelope.error
6568
- : undefined;
6569
- const hasNestedDetails = !!nested && Object.prototype.hasOwnProperty.call(nested, 'details');
6570
- const hasTopLevelDetails = !!body
6571
- && typeof body === 'object'
6572
- && Object.prototype.hasOwnProperty.call(body, 'details');
6573
- const legacyCode = typeof (body === null || body === void 0 ? void 0 : body.error) === 'string' ? body.error : undefined;
6574
- const code = typeof (nested === null || nested === void 0 ? void 0 : nested.code) === 'string'
6575
- ? nested.code
6576
- : legacyCode !== null && legacyCode !== void 0 ? legacyCode : `http_${response.status}`;
6577
- const message = typeof (nested === null || nested === void 0 ? void 0 : nested.message) === 'string'
6578
- ? nested.message
6579
- : typeof (body === null || body === void 0 ? void 0 : body.message) === 'string'
6580
- ? body.message
6581
- : `Developer API request failed with HTTP ${response.status}`;
6582
- const retryable = typeof (nested === null || nested === void 0 ? void 0 : nested.retryable) === 'boolean'
6583
- ? nested.retryable
6584
- : response.status === 429 || response.status >= 500;
6585
- return new BuildsApiError(Object.assign(Object.assign({ code,
6586
- message,
6587
- retryable, status: response.status }, (hasNestedDetails
6588
- ? { details: nested === null || nested === void 0 ? void 0 : nested.details }
6589
- : hasTopLevelDetails
6590
- ? { details: body.details }
6591
- : {})), (response.status === 429 ? { retryAfterMs: retryAfterMs(response) } : {})));
6592
- }
6593
- /** @internal Shared authenticated developer-api transport for builds and apps. */
6594
- async function requestDevApi(path, request = {}) {
6595
- var _a, _b;
6596
- const config = await core.getConfig();
6597
- const base = (_a = config.devApiUrl) === null || _a === void 0 ? void 0 : _a.replace(/\/$/, '');
6598
- if (!base) {
6599
- throw new Error('Bounded developer API is not configured. Pass devApiUrl or a Bounded network to init().');
6600
- }
6601
- // Reuse the exact accessor exposed publicly as getIdToken().
6602
- const token = await getIdToken();
6603
- if (!token) {
6604
- throw new BuildsApiError({
6605
- code: 'auth_required',
6606
- message: 'Sign in before calling the Bounded developer API.',
6607
- retryable: false,
6608
- status: 401,
6609
- });
6610
- }
6611
- const hasBody = request.body !== undefined;
6612
- const response = await fetch(`${base}${path}`, Object.assign({ method: (_b = request.method) !== null && _b !== void 0 ? _b : 'GET', headers: Object.assign({ Authorization: `Bearer ${token}` }, (hasBody ? { 'Content-Type': 'application/json' } : {})) }, (hasBody ? { body: JSON.stringify(request.body) } : {})));
6613
- const body = await responseBody(response);
6614
- if (!response.ok)
6615
- throw apiError(response, body);
6616
- return body;
6617
- }
6618
- function intentStorageKey(intentKey) {
6619
- return `${IDEMPOTENCY_STORAGE_PREFIX}${intentKey}`;
6620
- }
6621
- function isValidIdempotencyKey(value) {
6622
- return typeof value === 'string' && value.length > 0 && value.length <= 256;
6623
- }
6624
- function readPersistedIdempotencyKey(intentKey) {
6625
- var _a;
6626
- const storageKey = intentStorageKey(intentKey);
6627
- try {
6628
- const stored = (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem(storageKey);
6629
- if (isValidIdempotencyKey(stored))
6630
- return stored;
6631
- }
6632
- catch (_b) {
6633
- // Storage can be disabled by browser privacy policy; use module memory.
6634
- }
6635
- const inMemory = memoryIdempotencyKeys.get(storageKey);
6636
- return isValidIdempotencyKey(inMemory) ? inMemory : undefined;
6637
- }
6638
- function persistIdempotencyKey(intentKey, idempotencyKey) {
6639
- var _a;
6640
- const storageKey = intentStorageKey(intentKey);
6641
- memoryIdempotencyKeys.set(storageKey, idempotencyKey);
6642
- try {
6643
- (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.setItem(storageKey, idempotencyKey);
6644
- }
6645
- catch (_b) {
6646
- // The in-memory write above is the React Native / disabled-storage fallback.
6647
- }
6648
- }
6649
- function randomHex(bytes) {
6650
- const cryptoObject = globalThis.crypto;
6651
- if (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.getRandomValues) {
6652
- const values = new Uint8Array(bytes);
6653
- cryptoObject.getRandomValues(values);
6654
- return Array.from(values, (value) => value.toString(16).padStart(2, '0')).join('');
6655
- }
6656
- let value = '';
6657
- for (let index = 0; index < bytes; index += 1) {
6658
- value += Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
6659
- }
6660
- return value;
6661
- }
6662
- function mintIdempotencyKey() {
6663
- const cryptoObject = globalThis.crypto;
6664
- if (typeof (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.randomUUID) === 'function') {
6665
- return `build_${cryptoObject.randomUUID()}`;
6666
- }
6667
- return `build_${Date.now().toString(36)}_${randomHex(16)}`;
6668
- }
6669
- function actionIdempotencyKey(options, action) {
6670
- const supplied = options.idempotencyKey;
6671
- if (supplied !== undefined) {
6672
- if (!isValidIdempotencyKey(supplied)) {
6673
- throw new TypeError('idempotencyKey must be between 1 and 256 characters.');
6674
- }
6675
- if (options.intentKey)
6676
- persistIdempotencyKey(options.intentKey, supplied);
6677
- return supplied;
6678
- }
6679
- if (!options.intentKey) {
6680
- throw new TypeError(`intentKey is required when ${action} auto-mints an idempotency key.`);
6681
- }
6682
- const existing = readPersistedIdempotencyKey(options.intentKey);
6683
- if (existing)
6684
- return existing;
6685
- const minted = mintIdempotencyKey();
6686
- // This is deliberately synchronous and happens before requestDevApi can fetch.
6687
- persistIdempotencyKey(options.intentKey, minted);
6688
- return minted;
6689
- }
6690
- function appPath(appId) {
6691
- return `/app/${encodeURIComponent(appId)}/builds`;
6692
- }
6693
- async function submit(appId, options) {
6694
- const idempotencyKey = actionIdempotencyKey(options, 'submit()');
6695
- const { intentKey: _intentKey, idempotencyKey: _suppliedKey } = options, submission = __rest(options, ["intentKey", "idempotencyKey"]);
6696
- return requestDevApi(appPath(appId), {
6697
- method: 'POST',
6698
- body: Object.assign(Object.assign({}, submission), { idempotencyKey }),
6699
- });
6700
- }
6701
- async function get(appId, runId) {
6702
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}`);
6703
- }
6704
- async function events(appId, runId, after = 0) {
6705
- const cursor = Number.isFinite(after) ? Math.max(0, Math.floor(after)) : 0;
6706
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/events?after=${cursor}`);
6707
- }
6708
- async function cancel(appId, runId) {
6709
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
6710
- }
6711
- async function decideGate(appId, runId, gateId, options) {
6712
- const idempotencyKey = actionIdempotencyKey(options, 'decideGate()');
6713
- const { intentKey: _intentKey, idempotencyKey: _suppliedKey } = options, decision = __rest(options, ["intentKey", "idempotencyKey"]);
6714
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/decision`, { method: 'POST', body: Object.assign(Object.assign({}, decision), { idempotencyKey }) });
6715
- }
6716
- async function refreshReviewCapability(appId, runId, gateId, options) {
6717
- const idempotencyKey = actionIdempotencyKey(options, 'refreshReviewCapability()');
6718
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/review-capability/refresh`, {
6719
- method: 'POST',
6720
- body: {
6721
- expectedGeneration: options.expectedGeneration,
6722
- expectedExpiresAtMs: options.expectedExpiresAtMs,
6723
- expectedRecoveryUntilMs: options.expectedRecoveryUntilMs,
6724
- expectedAudience: options.expectedAudience,
6725
- expectedReviewerBindingHash: options.expectedReviewerBindingHash,
6726
- idempotencyKey,
6727
- },
6728
- });
6729
- }
6730
- /**
6731
- * Read one exact delegated-review capability and its narrow lifecycle result.
6732
- * This does not refresh or extend the window and exposes no generic run-view
6733
- * authority.
6734
- */
6735
- async function getReviewCapability(appId, runId, gateId, options) {
6736
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/review-capability`, {
6737
- method: 'POST',
6738
- body: { expectedPreviewUrl: options.expectedPreviewUrl },
6739
- });
6740
- }
6741
- async function topup(appId, runId, options) {
6742
- return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/topup`, { method: 'POST', body: options });
6743
- }
6744
- async function list$1(appId, limit = 20) {
6745
- const requestedLimit = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 20;
6746
- return requestDevApi(`${appPath(appId)}?limit=${requestedLimit}`);
6747
- }
6748
-
6749
- // Source of truth for these strings:
6750
- // packages/cdk/cloudflare/bounded-build/src/types.ts. Keep them string-pinned;
6751
- // wire:1 remains additive and callers must tolerate unknown response strings.
6752
- const NON_TERMINAL_STATES = [
6753
- 'queued',
6754
- 'admitted',
6755
- 'executing',
6756
- 'preview_ready',
6757
- 'parked',
6758
- 'resuming',
6759
- 'promoting',
6760
- 'quarantined',
6761
- ];
6762
- const TERMINAL_STATES = [
6763
- 'promoted',
6764
- 'failed',
6765
- 'canceled',
6766
- 'rejected',
6767
- 'expired',
6768
- 'rebase_required',
6769
- 'reported',
6770
- ];
6771
- const RUN_STATES = [
6772
- ...NON_TERMINAL_STATES,
6773
- ...TERMINAL_STATES,
6774
- ];
6775
- const PARK_REASONS = ['gate', 'funding'];
6776
- const FAILURE_REASONS = [
6777
- 'admission_rejected',
6778
- 'dispatch_timeout',
6779
- 'auth_revoked',
6780
- 'owner_changed',
6781
- 'policy_changed',
6782
- 'quarantine_forced',
6783
- 'bind_failed',
6784
- 'internal_error',
6785
- ];
6786
- const BUILD_REVIEW_CAPABILITY_SCHEMA = 'bounded.build-review-capability.v1';
6787
- const BUILD_REVIEW_CAPABILITY_REFRESH_SCHEMA = 'bounded.build-review-capability-refresh.v1';
6788
- const BUILD_DELEGATED_REVIEW_CAPABILITY_SCHEMA = 'bounded.build-delegated-review-capability.v1';
6789
-
6790
- const FAST_POLL_MS = 1000;
6791
- const NORMAL_POLL_MS = 2000;
6792
- const PARKED_POLL_MS = 5000;
6793
- const LONG_RUNNING_POLL_MS = 10000;
6794
- const THIRTY_SECONDS_MS = 30000;
6795
- const TWO_MINUTES_MS = 2 * 60000;
6796
- const TEN_MINUTES_MS = 10 * 60000;
6797
- const terminalStates = new Set(TERMINAL_STATES);
6798
- function pollCadence(state, elapsedMs) {
6799
- if (elapsedMs >= TEN_MINUTES_MS)
6800
- return LONG_RUNNING_POLL_MS;
6801
- if ((state === null || state === void 0 ? void 0 : state.startsWith('parked')) || elapsedMs >= TWO_MINUTES_MS)
6802
- return PARKED_POLL_MS;
6803
- // The first 30s is where the user is staring at "waiting for a build slot" /
6804
- // "building" and every transition matters most; poll fast, then relax.
6805
- if (elapsedMs < THIRTY_SECONDS_MS)
6806
- return FAST_POLL_MS;
6807
- return NORMAL_POLL_MS;
6808
- }
6809
- function retryCadence(error, state, elapsedMs) {
6810
- const cadence = pollCadence(state, elapsedMs);
6811
- if (error instanceof BuildsApiError && error.status === 429 && error.retryAfterMs !== undefined) {
6812
- return Math.max(cadence, error.retryAfterMs);
6813
- }
6814
- return cadence;
6815
- }
6816
- function hasRetryAfter(error) {
6817
- return error instanceof BuildsApiError
6818
- && error.status === 429
6819
- && error.retryAfterMs !== undefined;
6820
- }
6821
- // A permanent API refusal (expired session, revoked access, unknown run) will
6822
- // never heal by re-polling; the loop must stop and surface it instead of
6823
- // retrying forever. 429 stays retryable regardless of the server envelope.
6824
- function isPermanentError(error) {
6825
- return error instanceof BuildsApiError
6826
- && error.status !== 429
6827
- && error.retryable === false;
6828
- }
6829
- function newEvents(rows, lastSeq, seen) {
6830
- const cursorBeforePoll = lastSeq;
6831
- const fresh = [];
6832
- let nextCursor = lastSeq;
6833
- for (const event of rows) {
6834
- if (!Number.isFinite(event === null || event === void 0 ? void 0 : event.seq))
6835
- continue;
6836
- nextCursor = Math.max(nextCursor, event.seq);
6837
- if (event.seq <= cursorBeforePoll || seen.has(event.seq))
6838
- continue;
6839
- seen.add(event.seq);
6840
- fresh.push(event);
6841
- }
6842
- return { events: fresh, lastSeq: nextCursor };
6843
- }
6844
- /**
6845
- * Poll a build view and its event cursor until stopped or the run reaches a
6846
- * known terminal state. Unknown state strings remain untouched and nonterminal.
6847
- */
6848
- function watch(appId, runId, onUpdate, options = {}) {
6849
- const startedAt = Date.now();
6850
- const seenSeqs = new Set();
6851
- let lastSeq = Number.isFinite(options.after)
6852
- ? Math.max(0, Math.floor(options.after))
6853
- : 0;
6854
- let timer;
6855
- let active = true;
6856
- let lastState;
6857
- const stop = () => {
6858
- active = false;
6859
- if (timer !== undefined) {
6860
- clearTimeout(timer);
6861
- timer = undefined;
6862
- }
6863
- };
6864
- const schedule = (delayMs) => {
6865
- if (!active)
6866
- return;
6867
- timer = setTimeout(() => {
6868
- timer = undefined;
6869
- void poll();
6870
- }, delayMs);
6871
- };
6872
- const reportError = (error) => {
6873
- var _a;
6874
- try {
6875
- (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error);
6876
- }
6877
- catch (_b) {
6878
- // A consumer error callback must not break the transport loop.
6879
- }
6880
- };
6881
- const publish = (run, events) => {
6882
- try {
6883
- onUpdate({ run, events });
6884
- }
6885
- catch (_a) {
6886
- // Polling is transport state; consumer render errors must not strand it.
6887
- }
6888
- };
6889
- const poll = async () => {
6890
- if (!active)
6891
- return;
6892
- // Fire the view and the events page concurrently: the events cursor (lastSeq)
6893
- // does not depend on the run view, so there is no reason to pay two serial
6894
- // round-trips per tick. Error semantics below are unchanged — the run result
6895
- // still gates, and a failed events page still publishes the run with no rows.
6896
- const runPromise = get(appId, runId);
6897
- const eventsPromise = events(appId, runId, lastSeq);
6898
- // Keep the in-flight events page from becoming an unhandled rejection if the
6899
- // run result makes us bail before awaiting it; the real await below still sees it.
6900
- eventsPromise.catch(() => { });
6901
- let run;
6902
- try {
6903
- const view = await runPromise;
6904
- if (!active)
6905
- return;
6906
- run = view.run;
6907
- lastState = run.state;
6908
- }
6909
- catch (error) {
6910
- if (!active)
6911
- return;
6912
- reportError(error);
6913
- if (isPermanentError(error)) {
6914
- stop();
6915
- return;
6916
- }
6917
- schedule(retryCadence(error, lastState, Date.now() - startedAt));
6918
- return;
6919
- }
6920
- try {
6921
- const response = await eventsPromise;
6922
- if (!active)
6923
- return;
6924
- const deduped = newEvents(Array.isArray(response.events) ? response.events : [], lastSeq, seenSeqs);
6925
- lastSeq = deduped.lastSeq;
6926
- publish(run, deduped.events);
6927
- }
6928
- catch (error) {
6929
- if (!active)
6930
- return;
6931
- // The view still advances UI state even when event replay is rate-limited.
6932
- publish(run, []);
6933
- reportError(error);
6934
- if (terminalStates.has(run.state)) {
6935
- // The run itself is done, but a rate-limited final event replay still
6936
- // owes the caller its unseen seq rows. Honor Retry-After, retry the
6937
- // piggyback once the limiter permits it, then stop after a successful
6938
- // replay. Other terminal replay failures stop normally.
6939
- if (hasRetryAfter(error)) {
6940
- schedule(retryCadence(error, run.state, Date.now() - startedAt));
6941
- return;
6942
- }
6943
- stop();
6944
- return;
6945
- }
6946
- if (isPermanentError(error)) {
6947
- stop();
6948
- return;
6949
- }
6950
- schedule(retryCadence(error, run.state, Date.now() - startedAt));
6951
- return;
6952
- }
6953
- if (!active)
6954
- return;
6955
- if (terminalStates.has(run.state)) {
6956
- // Drain the remaining event pages before stopping: a resumed terminal
6957
- // watch may owe the caller more rows than one page returns. Each page
6958
- // advances the cursor, so the loop terminates; the cap is a backstop.
6959
- for (let page = 0; page < 50 && active; page += 1) {
6960
- let drained;
6961
- try {
6962
- const response = await events(appId, runId, lastSeq);
6963
- if (!active)
6964
- return;
6965
- drained = newEvents(Array.isArray(response.events) ? response.events : [], lastSeq, seenSeqs);
6966
- }
6967
- catch (error) {
6968
- reportError(error);
6969
- break;
6970
- }
6971
- if (drained.events.length === 0)
6972
- break;
6973
- lastSeq = drained.lastSeq;
6974
- publish(run, drained.events);
6975
- }
6976
- stop();
6977
- return;
6558
+ }
6559
+ setUser(null);
6560
+ }
6561
+ finally {
6562
+ setLoading(false);
6978
6563
  }
6979
- schedule(pollCadence(run.state, Date.now() - startedAt));
6980
6564
  };
6981
- void poll();
6982
- return { stop };
6565
+ const logout$1 = async () => {
6566
+ try {
6567
+ setLoading(true);
6568
+ await logout();
6569
+ setUser(null);
6570
+ }
6571
+ catch (error) {
6572
+ console.error('Error logging out:', error);
6573
+ }
6574
+ finally {
6575
+ setLoading(false);
6576
+ }
6577
+ };
6578
+ return {
6579
+ login: login$1,
6580
+ logout: logout$1,
6581
+ loading: loading || sdkLoading,
6582
+ user,
6583
+ };
6983
6584
  }
6984
6585
 
6985
- var _a;
6586
+ var _a$1;
6986
6587
  // SSR guard (mirrors useAuth): no hooks/subscriptions during Node server render.
6987
6588
  // React Native has no `window` but DOES support hooks, so detect Node SSR
6988
6589
  // specifically via process.versions.node.
6989
- const isSSR = typeof window === 'undefined'
6590
+ const isSSR$1 = typeof window === 'undefined'
6990
6591
  && typeof process !== 'undefined'
6991
- && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
6992
- function useBuildRun(appId, runId, options) {
6993
- if (isSSR) {
6994
- return { run: null, events: [], loading: true, error: null };
6592
+ && !!((_a$1 = process.versions) === null || _a$1 === void 0 ? void 0 : _a$1.node);
6593
+ function useQuery(path, options) {
6594
+ if (isSSR$1) {
6595
+ return { data: undefined, loading: true, error: null };
6995
6596
  }
6996
- const [run, setRun] = React__namespace.useState(null);
6997
- const [events, setEvents] = React__namespace.useState([]);
6597
+ const [data, setData] = React__namespace.useState(undefined);
6998
6598
  const [loading, setLoading] = React__namespace.useState(true);
6999
6599
  const [error, setError] = React__namespace.useState(null);
6600
+ // Re-subscribe only when the query actually changes (not on every render).
7000
6601
  const optionsKey = options ? JSON.stringify(options) : '';
7001
6602
  React__namespace.useEffect(() => {
7002
- setRun(null);
7003
- setEvents([]);
7004
- setError(null);
7005
- if (!appId || !runId) {
6603
+ if (!path) {
6604
+ setData(undefined);
7006
6605
  setLoading(false);
6606
+ setError(null);
7007
6607
  return;
7008
6608
  }
7009
6609
  let active = true;
6610
+ let unsubscribe;
7010
6611
  setLoading(true);
7011
- const handle = watch(appId, runId, ({ run: nextRun, events: nextEvents }) => {
7012
- if (!active)
7013
- return;
7014
- setRun(nextRun);
7015
- if (nextEvents.length > 0) {
7016
- setEvents((current) => {
7017
- const seen = new Set(current.map((event) => event.seq));
7018
- return [...current, ...nextEvents.filter((event) => !seen.has(event.seq))];
7019
- });
7020
- }
7021
- setError(null);
7022
- setLoading(false);
7023
- }, Object.assign(Object.assign({}, options), { onError: (value) => {
6612
+ setError(null);
6613
+ core.subscribe(path, Object.assign(Object.assign({}, options), { onData: (d) => {
7024
6614
  if (!active)
7025
6615
  return;
7026
- setError(value instanceof Error ? value : new Error(String(value)));
6616
+ // A reconnect can legitimately surface a transport error before the
6617
+ // socket re-authenticates and sends a new authorized snapshot. That
6618
+ // fresh snapshot is the recovery boundary: keep the error visible
6619
+ // until data arrives, then clear it so React does not remain stuck on
6620
+ // a failure page after realtime has recovered.
6621
+ setError(null);
6622
+ setData(d);
7027
6623
  setLoading(false);
7028
- } }));
6624
+ }, onError: (e) => {
6625
+ if (!active)
6626
+ return;
6627
+ setError(e instanceof Error ? e : new Error(String(e)));
6628
+ setLoading(false);
6629
+ } }))
6630
+ .then((unsub) => {
6631
+ if (active)
6632
+ unsubscribe = unsub;
6633
+ else
6634
+ void unsub(); // unmounted before subscribe resolved
6635
+ })
6636
+ .catch((e) => {
6637
+ if (!active)
6638
+ return;
6639
+ setError(e instanceof Error ? e : new Error(String(e)));
6640
+ setLoading(false);
6641
+ });
7029
6642
  return () => {
7030
6643
  active = false;
7031
- handle.stop();
6644
+ void (unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
7032
6645
  };
7033
- // optionsKey captures the option object's contents; ids are the other inputs.
6646
+ // optionsKey captures the option object's contents; path is the other input.
7034
6647
  // eslint-disable-next-line react-hooks/exhaustive-deps
7035
- }, [appId, runId, optionsKey]);
7036
- return { run, events, loading, error };
6648
+ }, [path, optionsKey]);
6649
+ return { data, loading, error };
6650
+ }
6651
+
6652
+ // Wrapper for getIdToken - passes isServer=false for client-side usage
6653
+ async function getIdToken() {
6654
+ return core.getIdToken(false);
6655
+ }
6656
+
6657
+ var __rest = (undefined && undefined.__rest) || function (s, e) {
6658
+ var t = {};
6659
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6660
+ t[p] = s[p];
6661
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6662
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6663
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
6664
+ t[p[i]] = s[p[i]];
6665
+ }
6666
+ return t;
6667
+ };
6668
+ /** A structured non-2xx response from the developer API. */
6669
+ class BuildsApiError extends Error {
6670
+ constructor(init) {
6671
+ super(init.message);
6672
+ this.name = 'BuildsApiError';
6673
+ this.code = init.code;
6674
+ this.retryable = init.retryable;
6675
+ this.status = init.status;
6676
+ this.details = init.details;
6677
+ this.retryAfterMs = init.retryAfterMs;
6678
+ }
6679
+ }
6680
+ const memoryIdempotencyKeys = new Map();
6681
+ const IDEMPOTENCY_STORAGE_PREFIX = 'bounded:build:idempotency:';
6682
+ function retryAfterMs(response) {
6683
+ var _a, _b;
6684
+ const value = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(_a, 'Retry-After');
6685
+ if (!value)
6686
+ return undefined;
6687
+ const seconds = Number(value);
6688
+ if (Number.isFinite(seconds) && seconds >= 0)
6689
+ return Math.ceil(seconds * 1000);
6690
+ const at = Date.parse(value);
6691
+ if (!Number.isFinite(at))
6692
+ return undefined;
6693
+ return Math.max(0, at - Date.now());
6694
+ }
6695
+ async function responseBody(response) {
6696
+ const text = await response.text();
6697
+ if (!text)
6698
+ return {};
6699
+ try {
6700
+ return JSON.parse(text);
6701
+ }
6702
+ catch (_a) {
6703
+ return { raw: text };
6704
+ }
6705
+ }
6706
+ function apiError(response, body) {
6707
+ const envelope = body;
6708
+ const nested = (envelope === null || envelope === void 0 ? void 0 : envelope.error) && typeof envelope.error === 'object'
6709
+ ? envelope.error
6710
+ : undefined;
6711
+ const hasNestedDetails = !!nested && Object.prototype.hasOwnProperty.call(nested, 'details');
6712
+ const hasTopLevelDetails = !!body
6713
+ && typeof body === 'object'
6714
+ && Object.prototype.hasOwnProperty.call(body, 'details');
6715
+ const legacyCode = typeof (body === null || body === void 0 ? void 0 : body.error) === 'string' ? body.error : undefined;
6716
+ const code = typeof (nested === null || nested === void 0 ? void 0 : nested.code) === 'string'
6717
+ ? nested.code
6718
+ : legacyCode !== null && legacyCode !== void 0 ? legacyCode : `http_${response.status}`;
6719
+ const message = typeof (nested === null || nested === void 0 ? void 0 : nested.message) === 'string'
6720
+ ? nested.message
6721
+ : typeof (body === null || body === void 0 ? void 0 : body.message) === 'string'
6722
+ ? body.message
6723
+ : `Developer API request failed with HTTP ${response.status}`;
6724
+ const retryable = typeof (nested === null || nested === void 0 ? void 0 : nested.retryable) === 'boolean'
6725
+ ? nested.retryable
6726
+ : response.status === 429 || response.status >= 500;
6727
+ return new BuildsApiError(Object.assign(Object.assign({ code,
6728
+ message,
6729
+ retryable, status: response.status }, (hasNestedDetails
6730
+ ? { details: nested === null || nested === void 0 ? void 0 : nested.details }
6731
+ : hasTopLevelDetails
6732
+ ? { details: body.details }
6733
+ : {})), (response.status === 429 ? { retryAfterMs: retryAfterMs(response) } : {})));
6734
+ }
6735
+ /** @internal Shared authenticated developer-api transport for builds and apps. */
6736
+ async function requestDevApi(path, request = {}) {
6737
+ var _a, _b;
6738
+ const config = await core.getConfig();
6739
+ const base = (_a = config.devApiUrl) === null || _a === void 0 ? void 0 : _a.replace(/\/$/, '');
6740
+ if (!base) {
6741
+ throw new Error('Bounded developer API is not configured. Pass devApiUrl or a Bounded network to init().');
6742
+ }
6743
+ // Reuse the exact accessor exposed publicly as getIdToken().
6744
+ const token = await getIdToken();
6745
+ if (!token) {
6746
+ throw new BuildsApiError({
6747
+ code: 'auth_required',
6748
+ message: 'Sign in before calling the Bounded developer API.',
6749
+ retryable: false,
6750
+ status: 401,
6751
+ });
6752
+ }
6753
+ const hasBody = request.body !== undefined;
6754
+ const response = await fetch(`${base}${path}`, Object.assign({ method: (_b = request.method) !== null && _b !== void 0 ? _b : 'GET', headers: Object.assign({ Authorization: `Bearer ${token}` }, (hasBody ? { 'Content-Type': 'application/json' } : {})) }, (hasBody ? { body: JSON.stringify(request.body) } : {})));
6755
+ const body = await responseBody(response);
6756
+ if (!response.ok)
6757
+ throw apiError(response, body);
6758
+ return body;
6759
+ }
6760
+ function intentStorageKey(intentKey) {
6761
+ return `${IDEMPOTENCY_STORAGE_PREFIX}${intentKey}`;
6762
+ }
6763
+ function isValidIdempotencyKey(value) {
6764
+ return typeof value === 'string' && value.length > 0 && value.length <= 256;
6765
+ }
6766
+ function readPersistedIdempotencyKey(intentKey) {
6767
+ var _a;
6768
+ const storageKey = intentStorageKey(intentKey);
6769
+ try {
6770
+ const stored = (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem(storageKey);
6771
+ if (isValidIdempotencyKey(stored))
6772
+ return stored;
6773
+ }
6774
+ catch (_b) {
6775
+ // Storage can be disabled by browser privacy policy; use module memory.
6776
+ }
6777
+ const inMemory = memoryIdempotencyKeys.get(storageKey);
6778
+ return isValidIdempotencyKey(inMemory) ? inMemory : undefined;
6779
+ }
6780
+ function persistIdempotencyKey(intentKey, idempotencyKey) {
6781
+ var _a;
6782
+ const storageKey = intentStorageKey(intentKey);
6783
+ memoryIdempotencyKeys.set(storageKey, idempotencyKey);
6784
+ try {
6785
+ (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.setItem(storageKey, idempotencyKey);
6786
+ }
6787
+ catch (_b) {
6788
+ // The in-memory write above is the React Native / disabled-storage fallback.
6789
+ }
6790
+ }
6791
+ function randomHex(bytes) {
6792
+ const cryptoObject = globalThis.crypto;
6793
+ if (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.getRandomValues) {
6794
+ const values = new Uint8Array(bytes);
6795
+ cryptoObject.getRandomValues(values);
6796
+ return Array.from(values, (value) => value.toString(16).padStart(2, '0')).join('');
6797
+ }
6798
+ let value = '';
6799
+ for (let index = 0; index < bytes; index += 1) {
6800
+ value += Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
6801
+ }
6802
+ return value;
6803
+ }
6804
+ function mintIdempotencyKey() {
6805
+ const cryptoObject = globalThis.crypto;
6806
+ if (typeof (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.randomUUID) === 'function') {
6807
+ return `build_${cryptoObject.randomUUID()}`;
6808
+ }
6809
+ return `build_${Date.now().toString(36)}_${randomHex(16)}`;
7037
6810
  }
7038
-
7039
- /**
7040
- * Platform first-party surfaces only (bounded.sh, oapps.fun, localhost), with
7041
- * one exact Drafted exception for delegated review/decision routes. Other
7042
- * generated-app origins remain blocked; server-side callers are unaffected.
7043
- */
7044
- const builds = {
7045
- submit,
7046
- get,
7047
- getReviewCapability,
7048
- events,
7049
- cancel,
7050
- decideGate,
7051
- refreshReviewCapability,
7052
- topup,
7053
- list: list$1,
7054
- watch,
7055
- };
7056
-
7057
- async function create(options = {}) {
7058
- const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (options.name !== undefined ? { name: options.name } : {})), (options.prompt !== undefined ? { prompt: options.prompt } : {})), (options.idempotencyKey !== undefined ? { idempotencyKey: options.idempotencyKey } : {})), (options.intent !== undefined ? { intent: options.intent } : {})), (options.oapp === true ? { oapp: true } : {}));
7059
- const app = await requestDevApi('/apps/new', {
6811
+ function actionIdempotencyKey(options, action) {
6812
+ const supplied = options.idempotencyKey;
6813
+ if (supplied !== undefined) {
6814
+ if (!isValidIdempotencyKey(supplied)) {
6815
+ throw new TypeError('idempotencyKey must be between 1 and 256 characters.');
6816
+ }
6817
+ if (options.intentKey)
6818
+ persistIdempotencyKey(options.intentKey, supplied);
6819
+ return supplied;
6820
+ }
6821
+ if (!options.intentKey) {
6822
+ throw new TypeError(`intentKey is required when ${action} auto-mints an idempotency key.`);
6823
+ }
6824
+ const existing = readPersistedIdempotencyKey(options.intentKey);
6825
+ if (existing)
6826
+ return existing;
6827
+ const minted = mintIdempotencyKey();
6828
+ // This is deliberately synchronous and happens before requestDevApi can fetch.
6829
+ persistIdempotencyKey(options.intentKey, minted);
6830
+ return minted;
6831
+ }
6832
+ function appPath(appId) {
6833
+ return `/app/${encodeURIComponent(appId)}/builds`;
6834
+ }
6835
+ async function submit(appId, options) {
6836
+ const idempotencyKey = actionIdempotencyKey(options, 'submit()');
6837
+ const { intentKey: _intentKey, idempotencyKey: _suppliedKey } = options, submission = __rest(options, ["intentKey", "idempotencyKey"]);
6838
+ return requestDevApi(appPath(appId), {
7060
6839
  method: 'POST',
7061
- body,
6840
+ body: Object.assign(Object.assign({}, submission), { idempotencyKey }),
7062
6841
  });
7063
- return Object.assign(Object.assign(Object.assign(Object.assign({ appId: app.appId }, (typeof app.slug === 'string' && app.slug ? { slug: app.slug } : {})), { url: app.url }), (typeof app.prompt === 'string' && app.prompt ? { prompt: app.prompt } : {})), (typeof app.handoff === 'string' && app.handoff ? { handoff: app.handoff } : {}));
7064
6842
  }
7065
- /**
7066
- * F-1200: build the create-flow redirect the owner is sent to after `create()`, with the
7067
- * prompt and handoff carried in the URL FRAGMENT (never the query - fragments never reach
7068
- * servers, logs, or Referer). Encoding is byte-exact so the widget's `URLSearchParams`
7069
- * parse + `.trim()` reproduces the SAME prompt string dev-api hashed into the handoff;
7070
- * getting this wrong would make the widget reject a genuine token and degrade to prefill.
7071
- * Callers (bounded.sh, oapps.fun) should use this instead of hand-building the URL.
7072
- *
7073
- * Returns `${url}#bounded_prompt=<prompt>` with no `&bounded_handoff=` when the server
7074
- * minted no handoff (HANDOFF_SECRET unset) - the widget then prefills without auto-running.
7075
- */
7076
- function buildCreateRedirectUrl(app) {
7077
- const base = app.url;
7078
- const prompt = typeof app.prompt === 'string' ? app.prompt.trim() : '';
7079
- if (!prompt)
7080
- return base;
7081
- const params = `bounded_prompt=${encodeURIComponent(prompt)}`
7082
- + (app.handoff ? `&bounded_handoff=${encodeURIComponent(app.handoff)}` : '');
7083
- return `${base}#${params}`;
6843
+ async function get(appId, runId) {
6844
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}`);
7084
6845
  }
7085
- async function list() {
7086
- // This legacy-compatible action shape is also used by oapps.fun listMyApps.
7087
- const response = await requestDevApi('/', {
6846
+ async function events(appId, runId, after = 0) {
6847
+ const cursor = Number.isFinite(after) ? Math.max(0, Math.floor(after)) : 0;
6848
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/events?after=${cursor}`);
6849
+ }
6850
+ async function cancel(appId, runId) {
6851
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
6852
+ }
6853
+ async function decideGate(appId, runId, gateId, options) {
6854
+ const idempotencyKey = actionIdempotencyKey(options, 'decideGate()');
6855
+ const { intentKey: _intentKey, idempotencyKey: _suppliedKey } = options, decision = __rest(options, ["intentKey", "idempotencyKey"]);
6856
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/decision`, { method: 'POST', body: Object.assign(Object.assign({}, decision), { idempotencyKey }) });
6857
+ }
6858
+ async function refreshReviewCapability(appId, runId, gateId, options) {
6859
+ const idempotencyKey = actionIdempotencyKey(options, 'refreshReviewCapability()');
6860
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/review-capability/refresh`, {
7088
6861
  method: 'POST',
7089
- body: { action: 'listApps' },
6862
+ body: {
6863
+ expectedGeneration: options.expectedGeneration,
6864
+ expectedExpiresAtMs: options.expectedExpiresAtMs,
6865
+ expectedRecoveryUntilMs: options.expectedRecoveryUntilMs,
6866
+ expectedAudience: options.expectedAudience,
6867
+ expectedReviewerBindingHash: options.expectedReviewerBindingHash,
6868
+ idempotencyKey,
6869
+ },
7090
6870
  });
7091
- const rows = Array.isArray(response.apps) ? response.apps : [];
7092
- return rows
7093
- .map((value) => {
7094
- var _a, _b, _c, _d;
7095
- const row = value && typeof value === 'object'
7096
- ? value
7097
- : {};
7098
- const appId = String((_c = (_b = (_a = row._id) !== null && _a !== void 0 ? _a : row.id) !== null && _b !== void 0 ? _b : row.appId) !== null && _c !== void 0 ? _c : '');
7099
- if (!/^[a-f0-9]{24}$/i.test(appId))
7100
- return null;
7101
- const name = String((_d = row.name) !== null && _d !== void 0 ? _d : '').trim() || '(unnamed app)';
7102
- const slug = typeof row.slug === 'string' && row.slug ? row.slug : undefined;
7103
- const url = typeof row.url === 'string' && row.url.trim() ? row.url.trim() : undefined;
7104
- const buildStatus = row.buildStatus === 'building' || row.buildStatus === 'build_failed'
7105
- ? row.buildStatus
7106
- : undefined;
7107
- return Object.assign(Object.assign(Object.assign({ appId,
7108
- name }, (slug ? { slug } : {})), (url ? { url } : {})), (buildStatus ? { buildStatus } : {}));
7109
- })
7110
- .filter((app) => app !== null);
7111
- }
7112
- /**
7113
- * Platform first-party surfaces only (bounded.sh, oapps.fun, localhost) —
7114
- * dev-api CORS blocks calls from generated-app origins. Server-side callers unaffected.
7115
- */
7116
- const apps = { create, list, buildCreateRedirectUrl };
7117
-
7118
- async function deserializeTransaction(tx) {
7119
- // Literal specifier so bundlers can code-split the lazy chunk.
7120
- const { Transaction, VersionedTransaction } = await import('@solana/web3.js');
7121
- const buf = Buffer.isBuffer(tx) ? tx : Buffer.from(tx, 'base64');
7122
- if ((buf[0] & 0x80) !== 0) {
7123
- return VersionedTransaction.deserialize(buf);
7124
- }
7125
- else {
7126
- return Transaction.from(buf);
7127
- }
7128
6871
  }
7129
-
7130
- // turnkey-wallet-widget.ts - runs one Turnkey signer exchange inside the shared
7131
- // in-app WIDGET (bounded-widget-modal.ts). The Bounded-owned signer page is loaded
7132
- // in a warm iframe behind the modal so signing feels native: an in-app card plus
7133
- // the OS Face ID / Touch ID sheet, never a jarring popup.
7134
- //
7135
- // WHY AN IFRAME: a WebAuthn passkey is bound to ONE origin, so passkey create/sign
7136
- // MUST run on the single Bounded signer origin. The iframe carries the
7137
- // publickey-credentials-{get,create} permission policy and the user's click lands
7138
- // INSIDE it, giving WebAuthn the transient activation it needs.
7139
- //
7140
- // SAFARI / restricted embedders: cross-origin iframe passkey CREATE is unreliable
7141
- // in Safari. The signer detects that and posts `fallbackPopup`; we then rerun the
7142
- // SAME request through `popupFallback` (a real window). Callers pass a popup
7143
- // implementation and never see the difference.
7144
6872
  /**
7145
- * Run one signer exchange through the in-app widget. Resolves when `onResult`
7146
- * accepts a result; falls back to `popupFallback` if the frame cannot run WebAuthn
7147
- * (Safari cross-origin create) or cannot be mounted.
6873
+ * Read one exact delegated-review capability and its narrow lifecycle result.
6874
+ * This does not refresh or extend the window and exposes no generic run-view
6875
+ * authority.
7148
6876
  */
7149
- async function runWidget(url, signerOrigin, ex, popupFallback) {
7150
- if (!hasDOM$3())
7151
- return popupFallback();
7152
- const m = getModal();
7153
- const requestId = String(ex.request.requestId);
7154
- // Serialize: WebAuthn is modal, and one warm frame handles one request at a time.
7155
- const run = m.chain.then(() => new Promise((resolve, reject) => {
7156
- let settled = false;
7157
- let usedFallback = false;
7158
- const iframe = ensureIframe(m, url, signerOrigin);
7159
- const send = () => {
7160
- if (!iframe.contentWindow)
7161
- return;
7162
- try {
7163
- iframe.contentWindow.postMessage(ex.request, signerOrigin);
7164
- }
7165
- catch (_a) {
7166
- /* frame gone */
7167
- }
7168
- };
7169
- let loadTimer = 0;
7170
- let ceilingTimer = 0;
7171
- const finish = (fn) => {
7172
- if (settled)
7173
- return;
7174
- settled = true;
7175
- m.onIframeMessage = null;
7176
- m.onBackdrop = null;
7177
- window.clearTimeout(loadTimer);
7178
- window.clearTimeout(ceilingTimer);
7179
- fn();
7180
- };
7181
- const goFallback = () => {
7182
- if (usedFallback || settled)
7183
- return;
7184
- usedFallback = true;
7185
- hideModal(m);
7186
- finish(() => popupFallback().then(resolve, reject));
7187
- };
7188
- m.onBackdrop = () => {
7189
- hideModal(m);
7190
- finish(() => reject(new Error("cancelled")));
7191
- };
7192
- m.onIframeMessage = (d) => {
7193
- if (d.type === "bounded:turnkey:ready") {
7194
- m.iframeReady = true;
7195
- send();
7196
- return;
7197
- }
7198
- if (d.type === "bounded:turnkey:resize" && typeof d.height === "number") {
7199
- setPanelHeight(m, d.height);
7200
- return;
7201
- }
7202
- if (d.type === "bounded:turnkey:fallbackPopup" && d.requestId === requestId) {
7203
- goFallback();
7204
- return;
7205
- }
7206
- if (d.type === "bounded:turnkey:result" && d.requestId === requestId) {
7207
- const outcome = ex.onResult(d);
7208
- if ("error" in outcome) {
7209
- hideModal(m);
7210
- finish(() => reject(new Error(outcome.error)));
7211
- return;
7212
- }
7213
- if (outcome.done) {
7214
- hideModal(m);
7215
- finish(() => resolve(outcome.value));
7216
- }
7217
- }
7218
- };
7219
- showModal(m);
7220
- if (m.iframeReady)
7221
- send();
7222
- // If the frame never loads, degrade to the popup (best-effort - a post-load
7223
- // popup may be blocked without a gesture, in which case the fallback rejects).
7224
- loadTimer = window.setTimeout(() => {
7225
- if (!m.iframeReady && !settled)
7226
- goFallback();
7227
- }, 8000);
7228
- // Absolute ceiling so a stuck flow cannot hang forever.
7229
- ceilingTimer = window.setTimeout(() => {
7230
- if (!settled) {
7231
- hideModal(m);
7232
- finish(() => reject(new Error("Wallet approval timed out.")));
7233
- }
7234
- }, 5 * 60 * 1000);
7235
- }));
7236
- m.chain = run.then(() => undefined, () => undefined);
7237
- return run;
6877
+ async function getReviewCapability(appId, runId, gateId, options) {
6878
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/gates/${encodeURIComponent(gateId)}/review-capability`, {
6879
+ method: 'POST',
6880
+ body: { expectedPreviewUrl: options.expectedPreviewUrl },
6881
+ });
7238
6882
  }
7239
-
7240
- // turnkey-signer-bridge.ts - routes NON-CUSTODIAL Turnkey embedded-wallet signing
7241
- // through the Bounded-owned signer page (auth.bounded.sh/wallet/turnkey/signer).
7242
- //
7243
- // TRANSPORT: by default the signer runs inside the in-app WIDGET (turnkey-wallet-
7244
- // widget.ts) - an iframe behind a Shadow-DOM modal that matches the Bounded widget
7245
- // look + motion, so signing feels native. Safari (unreliable at iframe passkey
7246
- // CREATE) and any environment where the frame cannot mount fall back to a real
7247
- // popup window; both transports speak the same postMessage protocol.
7248
- //
7249
- // Unlike the Crossmint bridge (crossmint-signer-bridge.ts), Turnkey wallets DO
7250
- // produce raw detached signatures: the signer runs the Turnkey browser SDK on the
7251
- // single Bounded origin, enrolls the user's passkey on first use (lazy - the
7252
- // sub-org is created with the passkey + email attached at that moment), and stamps
7253
- // an ed25519 signRawPayload with that passkey. So this bridge exposes a
7254
- // `signSolanaMessage` primitive; the app builds + submits the transaction itself.
7255
- //
7256
- // ONE ORIGIN, ONE PASSKEY: a WebAuthn passkey is bound to a single origin, so ALL
7257
- // Bounded apps (any subdomain / custom domain) sign through this one origin - giving
7258
- // every user one wallet + one passkey that roams across every app.
7259
- function hasDOM$1() {
7260
- return typeof window !== 'undefined' && typeof document !== 'undefined';
6883
+ async function topup(appId, runId, options) {
6884
+ return requestDevApi(`${appPath(appId)}/${encodeURIComponent(runId)}/topup`, { method: 'POST', body: options });
7261
6885
  }
7262
- // Safari (incl. iOS WebViews) is unreliable at running a WebAuthn CREATE inside a
7263
- // cross-origin iframe, so the widget's automatic in-iframe passkey enrollment can
7264
- // fail - and a post-failure popup would no longer have a user gesture to open with.
7265
- // There we pick the popup up front, from the original click, so enrollment is solid.
7266
- // Everywhere else the inline widget is used (buttery in-app modal).
7267
- function preferPopup() {
7268
- if (!hasDOM$1() || typeof navigator === 'undefined')
7269
- return true;
7270
- const ua = navigator.userAgent || '';
7271
- return /^((?!chrome|android|crios|fxios|edg|edga|opr).)*safari/i.test(ua);
6886
+ async function list$1(appId, limit = 20) {
6887
+ const requestedLimit = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 20;
6888
+ return requestDevApi(`${appPath(appId)}?limit=${requestedLimit}`);
7272
6889
  }
7273
- // Dispatch one signer exchange through the in-app WIDGET, degrading to the POPUP
7274
- // when we cannot embed (Safari enrollment, or the frame never loads).
7275
- async function deliver(url, origin, ex) {
7276
- const popup = () => runPopup(url, origin, ex);
7277
- if (preferPopup())
7278
- return popup();
7279
- return runWidget(url, origin, { request: ex.request, onResult: ex.onResult }, popup);
6890
+
6891
+ // Source of truth for these strings:
6892
+ // packages/cdk/cloudflare/bounded-build/src/types.ts. Keep them string-pinned;
6893
+ // wire:1 remains additive and callers must tolerate unknown response strings.
6894
+ const NON_TERMINAL_STATES = [
6895
+ 'queued',
6896
+ 'admitted',
6897
+ 'executing',
6898
+ 'preview_ready',
6899
+ 'parked',
6900
+ 'resuming',
6901
+ 'promoting',
6902
+ 'quarantined',
6903
+ ];
6904
+ const TERMINAL_STATES = [
6905
+ 'promoted',
6906
+ 'failed',
6907
+ 'canceled',
6908
+ 'rejected',
6909
+ 'expired',
6910
+ 'rebase_required',
6911
+ 'reported',
6912
+ ];
6913
+ const RUN_STATES = [
6914
+ ...NON_TERMINAL_STATES,
6915
+ ...TERMINAL_STATES,
6916
+ ];
6917
+ const PARK_REASONS = ['gate', 'funding'];
6918
+ const FAILURE_REASONS = [
6919
+ 'admission_rejected',
6920
+ 'dispatch_timeout',
6921
+ 'auth_revoked',
6922
+ 'owner_changed',
6923
+ 'policy_changed',
6924
+ 'quarantine_forced',
6925
+ 'bind_failed',
6926
+ 'internal_error',
6927
+ ];
6928
+ const BUILD_REVIEW_CAPABILITY_SCHEMA = 'bounded.build-review-capability.v1';
6929
+ const BUILD_REVIEW_CAPABILITY_REFRESH_SCHEMA = 'bounded.build-review-capability-refresh.v1';
6930
+ const BUILD_DELEGATED_REVIEW_CAPABILITY_SCHEMA = 'bounded.build-delegated-review-capability.v1';
6931
+
6932
+ const FAST_POLL_MS = 1000;
6933
+ const NORMAL_POLL_MS = 2000;
6934
+ const PARKED_POLL_MS = 5000;
6935
+ const LONG_RUNNING_POLL_MS = 10000;
6936
+ const THIRTY_SECONDS_MS = 30000;
6937
+ const TWO_MINUTES_MS = 2 * 60000;
6938
+ const TEN_MINUTES_MS = 10 * 60000;
6939
+ const terminalStates = new Set(TERMINAL_STATES);
6940
+ function pollCadence(state, elapsedMs) {
6941
+ if (elapsedMs >= TEN_MINUTES_MS)
6942
+ return LONG_RUNNING_POLL_MS;
6943
+ if ((state === null || state === void 0 ? void 0 : state.startsWith('parked')) || elapsedMs >= TWO_MINUTES_MS)
6944
+ return PARKED_POLL_MS;
6945
+ // The first 30s is where the user is staring at "waiting for a build slot" /
6946
+ // "building" and every transition matters most; poll fast, then relax.
6947
+ if (elapsedMs < THIRTY_SECONDS_MS)
6948
+ return FAST_POLL_MS;
6949
+ return NORMAL_POLL_MS;
7280
6950
  }
7281
- async function turnkeySignerPage() {
7282
- const cfg = await core.getConfig();
7283
- const base = (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
7284
- return { url: `${base}/wallet/turnkey/signer`, origin: new URL(base).origin };
6951
+ function retryCadence(error, state, elapsedMs) {
6952
+ const cadence = pollCadence(state, elapsedMs);
6953
+ if (error instanceof BuildsApiError && error.status === 429 && error.retryAfterMs !== undefined) {
6954
+ return Math.max(cadence, error.retryAfterMs);
6955
+ }
6956
+ return cadence;
7285
6957
  }
7286
- function toHex(bytes) {
7287
- let h = '';
7288
- for (const b of bytes)
7289
- h += b.toString(16).padStart(2, '0');
7290
- return h;
6958
+ function hasRetryAfter(error) {
6959
+ return error instanceof BuildsApiError
6960
+ && error.status === 429
6961
+ && error.retryAfterMs !== undefined;
7291
6962
  }
7292
- function fromHex(hex) {
7293
- const clean = hex.startsWith('0x') ? hex.slice(2) : hex;
7294
- const out = new Uint8Array(clean.length / 2);
7295
- for (let i = 0; i < out.length; i++)
7296
- out[i] = parseInt(clean.substr(i * 2, 2), 16);
7297
- return out;
6963
+ // A permanent API refusal (expired session, revoked access, unknown run) will
6964
+ // never heal by re-polling; the loop must stop and surface it instead of
6965
+ // retrying forever. 429 stays retryable regardless of the server envelope.
6966
+ function isPermanentError(error) {
6967
+ return error instanceof BuildsApiError
6968
+ && error.status !== 429
6969
+ && error.retryable === false;
7298
6970
  }
7299
- let requestSeq = 0;
7300
- // Shared popup driver: open the signer page, do the ready/postMessage handshake, and
7301
- // resolve when `onResult` accepts a result message. Origin + source are pinned.
7302
- async function runPopup(url, signerOrigin, ex) {
7303
- var _a, _b;
7304
- const w = (_a = ex.width) !== null && _a !== void 0 ? _a : 420, h = (_b = ex.height) !== null && _b !== void 0 ? _b : 620;
7305
- const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
7306
- const top = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
7307
- const popup = window.open(url, 'bounded-turnkey-signer', `width=${w},height=${h},left=${left},top=${top}`);
7308
- if (!popup) {
7309
- throw new Error('Popup blocked - call this from a user gesture (e.g. a click handler) so the passkey approval window can open.');
6971
+ function newEvents(rows, lastSeq, seen) {
6972
+ const cursorBeforePoll = lastSeq;
6973
+ const fresh = [];
6974
+ let nextCursor = lastSeq;
6975
+ for (const event of rows) {
6976
+ if (!Number.isFinite(event === null || event === void 0 ? void 0 : event.seq))
6977
+ continue;
6978
+ nextCursor = Math.max(nextCursor, event.seq);
6979
+ if (event.seq <= cursorBeforePoll || seen.has(event.seq))
6980
+ continue;
6981
+ seen.add(event.seq);
6982
+ fresh.push(event);
7310
6983
  }
7311
- return await new Promise((resolve, reject) => {
7312
- let settled = false;
7313
- let sentRequest = false;
7314
- let closeTimer;
7315
- const cleanup = () => { settled = true; window.removeEventListener('message', onMsg); if (closeTimer)
7316
- clearInterval(closeTimer); };
7317
- const sendRequest = () => { if (sentRequest)
7318
- return; sentRequest = true; try {
7319
- popup.postMessage(ex.request, signerOrigin);
6984
+ return { events: fresh, lastSeq: nextCursor };
6985
+ }
6986
+ /**
6987
+ * Poll a build view and its event cursor until stopped or the run reaches a
6988
+ * known terminal state. Unknown state strings remain untouched and nonterminal.
6989
+ */
6990
+ function watch(appId, runId, onUpdate, options = {}) {
6991
+ const startedAt = Date.now();
6992
+ const seenSeqs = new Set();
6993
+ let lastSeq = Number.isFinite(options.after)
6994
+ ? Math.max(0, Math.floor(options.after))
6995
+ : 0;
6996
+ let timer;
6997
+ let active = true;
6998
+ let lastState;
6999
+ const stop = () => {
7000
+ active = false;
7001
+ if (timer !== undefined) {
7002
+ clearTimeout(timer);
7003
+ timer = undefined;
7320
7004
  }
7321
- catch ( /* popup gone */_a) { /* popup gone */ } };
7322
- const onMsg = (event) => {
7323
- if (event.origin !== signerOrigin)
7005
+ };
7006
+ const schedule = (delayMs) => {
7007
+ if (!active)
7008
+ return;
7009
+ timer = setTimeout(() => {
7010
+ timer = undefined;
7011
+ void poll();
7012
+ }, delayMs);
7013
+ };
7014
+ const reportError = (error) => {
7015
+ var _a;
7016
+ try {
7017
+ (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error);
7018
+ }
7019
+ catch (_b) {
7020
+ // A consumer error callback must not break the transport loop.
7021
+ }
7022
+ };
7023
+ const publish = (run, events) => {
7024
+ try {
7025
+ onUpdate({ run, events });
7026
+ }
7027
+ catch (_a) {
7028
+ // Polling is transport state; consumer render errors must not strand it.
7029
+ }
7030
+ };
7031
+ const poll = async () => {
7032
+ if (!active)
7033
+ return;
7034
+ // Fire the view and the events page concurrently: the events cursor (lastSeq)
7035
+ // does not depend on the run view, so there is no reason to pay two serial
7036
+ // round-trips per tick. Error semantics below are unchanged — the run result
7037
+ // still gates, and a failed events page still publishes the run with no rows.
7038
+ const runPromise = get(appId, runId);
7039
+ const eventsPromise = events(appId, runId, lastSeq);
7040
+ // Keep the in-flight events page from becoming an unhandled rejection if the
7041
+ // run result makes us bail before awaiting it; the real await below still sees it.
7042
+ eventsPromise.catch(() => { });
7043
+ let run;
7044
+ try {
7045
+ const view = await runPromise;
7046
+ if (!active)
7324
7047
  return;
7325
- if (event.source !== popup)
7048
+ run = view.run;
7049
+ lastState = run.state;
7050
+ }
7051
+ catch (error) {
7052
+ if (!active)
7326
7053
  return;
7327
- const d = event.data;
7328
- if (!d || typeof d !== 'object')
7054
+ reportError(error);
7055
+ if (isPermanentError(error)) {
7056
+ stop();
7057
+ return;
7058
+ }
7059
+ schedule(retryCadence(error, lastState, Date.now() - startedAt));
7060
+ return;
7061
+ }
7062
+ try {
7063
+ const response = await eventsPromise;
7064
+ if (!active)
7065
+ return;
7066
+ const deduped = newEvents(Array.isArray(response.events) ? response.events : [], lastSeq, seenSeqs);
7067
+ lastSeq = deduped.lastSeq;
7068
+ publish(run, deduped.events);
7069
+ }
7070
+ catch (error) {
7071
+ if (!active)
7072
+ return;
7073
+ // The view still advances UI state even when event replay is rate-limited.
7074
+ publish(run, []);
7075
+ reportError(error);
7076
+ if (terminalStates.has(run.state)) {
7077
+ // The run itself is done, but a rate-limited final event replay still
7078
+ // owes the caller its unseen seq rows. Honor Retry-After, retry the
7079
+ // piggyback once the limiter permits it, then stop after a successful
7080
+ // replay. Other terminal replay failures stop normally.
7081
+ if (hasRetryAfter(error)) {
7082
+ schedule(retryCadence(error, run.state, Date.now() - startedAt));
7083
+ return;
7084
+ }
7085
+ stop();
7329
7086
  return;
7330
- if (d.type === 'bounded:turnkey:ready') {
7331
- sendRequest();
7087
+ }
7088
+ if (isPermanentError(error)) {
7089
+ stop();
7332
7090
  return;
7333
7091
  }
7334
- if (d.type === 'bounded:turnkey:result' && d.requestId === ex.request.requestId) {
7335
- const outcome = ex.onResult(d);
7336
- if ('error' in outcome) {
7337
- cleanup();
7338
- try {
7339
- popup.close();
7340
- }
7341
- catch ( /* ignore */_a) { /* ignore */ }
7342
- reject(new Error(outcome.error));
7343
- return;
7092
+ schedule(retryCadence(error, run.state, Date.now() - startedAt));
7093
+ return;
7094
+ }
7095
+ if (!active)
7096
+ return;
7097
+ if (terminalStates.has(run.state)) {
7098
+ // Drain the remaining event pages before stopping: a resumed terminal
7099
+ // watch may owe the caller more rows than one page returns. Each page
7100
+ // advances the cursor, so the loop terminates; the cap is a backstop.
7101
+ for (let page = 0; page < 50 && active; page += 1) {
7102
+ let drained;
7103
+ try {
7104
+ const response = await events(appId, runId, lastSeq);
7105
+ if (!active)
7106
+ return;
7107
+ drained = newEvents(Array.isArray(response.events) ? response.events : [], lastSeq, seenSeqs);
7344
7108
  }
7345
- if (outcome.done) {
7346
- cleanup();
7347
- try {
7348
- popup.close();
7349
- }
7350
- catch ( /* ignore */_b) { /* ignore */ }
7351
- resolve(outcome.value);
7109
+ catch (error) {
7110
+ reportError(error);
7111
+ break;
7352
7112
  }
7113
+ if (drained.events.length === 0)
7114
+ break;
7115
+ lastSeq = drained.lastSeq;
7116
+ publish(run, drained.events);
7353
7117
  }
7354
- };
7355
- window.addEventListener('message', onMsg);
7356
- setTimeout(sendRequest, 1200);
7357
- closeTimer = setInterval(() => {
7358
- if (popup.closed) {
7359
- clearInterval(closeTimer);
7360
- setTimeout(() => { if (!settled) {
7361
- cleanup();
7362
- reject(new Error('Wallet approval window was closed before it completed.'));
7363
- } }, 400);
7364
- }
7365
- }, 500);
7366
- setTimeout(() => { if (!settled) {
7367
- cleanup();
7368
- try {
7369
- popup.close();
7118
+ stop();
7119
+ return;
7120
+ }
7121
+ schedule(pollCadence(run.state, Date.now() - startedAt));
7122
+ };
7123
+ void poll();
7124
+ return { stop };
7125
+ }
7126
+
7127
+ var _a;
7128
+ // SSR guard (mirrors useAuth): no hooks/subscriptions during Node server render.
7129
+ // React Native has no `window` but DOES support hooks, so detect Node SSR
7130
+ // specifically via process.versions.node.
7131
+ const isSSR = typeof window === 'undefined'
7132
+ && typeof process !== 'undefined'
7133
+ && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
7134
+ function useBuildRun(appId, runId, options) {
7135
+ if (isSSR) {
7136
+ return { run: null, events: [], loading: true, error: null };
7137
+ }
7138
+ const [run, setRun] = React__namespace.useState(null);
7139
+ const [events, setEvents] = React__namespace.useState([]);
7140
+ const [loading, setLoading] = React__namespace.useState(true);
7141
+ const [error, setError] = React__namespace.useState(null);
7142
+ const optionsKey = options ? JSON.stringify(options) : '';
7143
+ React__namespace.useEffect(() => {
7144
+ setRun(null);
7145
+ setEvents([]);
7146
+ setError(null);
7147
+ if (!appId || !runId) {
7148
+ setLoading(false);
7149
+ return;
7150
+ }
7151
+ let active = true;
7152
+ setLoading(true);
7153
+ const handle = watch(appId, runId, ({ run: nextRun, events: nextEvents }) => {
7154
+ if (!active)
7155
+ return;
7156
+ setRun(nextRun);
7157
+ if (nextEvents.length > 0) {
7158
+ setEvents((current) => {
7159
+ const seen = new Set(current.map((event) => event.seq));
7160
+ return [...current, ...nextEvents.filter((event) => !seen.has(event.seq))];
7161
+ });
7370
7162
  }
7371
- catch ( /* ignore */_a) { /* ignore */ }
7372
- reject(new Error('Wallet approval timed out.'));
7373
- } }, 5 * 60 * 1000);
7163
+ setError(null);
7164
+ setLoading(false);
7165
+ }, Object.assign(Object.assign({}, options), { onError: (value) => {
7166
+ if (!active)
7167
+ return;
7168
+ setError(value instanceof Error ? value : new Error(String(value)));
7169
+ setLoading(false);
7170
+ } }));
7171
+ return () => {
7172
+ active = false;
7173
+ handle.stop();
7174
+ };
7175
+ // optionsKey captures the option object's contents; ids are the other inputs.
7176
+ // eslint-disable-next-line react-hooks/exhaustive-deps
7177
+ }, [appId, runId, optionsKey]);
7178
+ return { run, events, loading, error };
7179
+ }
7180
+
7181
+ /**
7182
+ * Platform first-party surfaces only (bounded.sh, oapps.fun, localhost), with
7183
+ * one exact Drafted exception for delegated review/decision routes. Other
7184
+ * generated-app origins remain blocked; server-side callers are unaffected.
7185
+ */
7186
+ const builds = {
7187
+ submit,
7188
+ get,
7189
+ getReviewCapability,
7190
+ events,
7191
+ cancel,
7192
+ decideGate,
7193
+ refreshReviewCapability,
7194
+ topup,
7195
+ list: list$1,
7196
+ watch,
7197
+ };
7198
+
7199
+ async function create(options = {}) {
7200
+ const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (options.name !== undefined ? { name: options.name } : {})), (options.prompt !== undefined ? { prompt: options.prompt } : {})), (options.idempotencyKey !== undefined ? { idempotencyKey: options.idempotencyKey } : {})), (options.intent !== undefined ? { intent: options.intent } : {})), (options.oapp === true ? { oapp: true } : {}));
7201
+ const app = await requestDevApi('/apps/new', {
7202
+ method: 'POST',
7203
+ body,
7374
7204
  });
7205
+ return Object.assign(Object.assign(Object.assign(Object.assign({ appId: app.appId }, (typeof app.slug === 'string' && app.slug ? { slug: app.slug } : {})), { url: app.url }), (typeof app.prompt === 'string' && app.prompt ? { prompt: app.prompt } : {})), (typeof app.handoff === 'string' && app.handoff ? { handoff: app.handoff } : {}));
7375
7206
  }
7376
7207
  /**
7377
- * Get-or-create the user's non-custodial Turnkey wallet, resolving with its stable
7378
- * Solana address. On first use the popup enrolls a device passkey (Face ID / Touch ID)
7379
- * and creates the wallet (lazy) with no email code; if the wallet already exists it
7380
- * resolves immediately without a prompt. Call from a USER GESTURE.
7208
+ * F-1200: build the create-flow redirect the owner is sent to after `create()`, with the
7209
+ * prompt and handoff carried in the URL FRAGMENT (never the query - fragments never reach
7210
+ * servers, logs, or Referer). Encoding is byte-exact so the widget's `URLSearchParams`
7211
+ * parse + `.trim()` reproduces the SAME prompt string dev-api hashed into the handoff;
7212
+ * getting this wrong would make the widget reject a genuine token and degrade to prefill.
7213
+ * Callers (bounded.sh, oapps.fun) should use this instead of hand-building the URL.
7381
7214
  *
7382
- * Use this to learn the fee-payer address BEFORE building a transaction to sign.
7215
+ * Returns `${url}#bounded_prompt=<prompt>` with no `&bounded_handoff=` when the server
7216
+ * minted no handoff (HANDOFF_SECRET unset) - the widget then prefills without auto-running.
7383
7217
  */
7384
- async function getOrCreateTurnkeyWallet() {
7385
- if (!hasDOM$1())
7386
- throw new Error('Turnkey embedded wallets are only available in the browser (popup-based).');
7387
- const { url, origin } = await turnkeySignerPage();
7388
- const requestId = `tkcreate_${Date.now()}_${++requestSeq}`;
7389
- return await deliver(url, origin, {
7390
- request: { type: 'bounded:turnkey:createWallet', requestId },
7391
- onResult: (d) => {
7392
- if (d.ok && typeof d.address === 'string')
7393
- return { done: true, value: { address: d.address, subOrgId: String(d.subOrgId || '') } };
7394
- return { error: String(d.error || 'Wallet setup failed') };
7395
- },
7218
+ function buildCreateRedirectUrl(app) {
7219
+ const base = app.url;
7220
+ const prompt = typeof app.prompt === 'string' ? app.prompt.trim() : '';
7221
+ if (!prompt)
7222
+ return base;
7223
+ const params = `bounded_prompt=${encodeURIComponent(prompt)}`
7224
+ + (app.handoff ? `&bounded_handoff=${encodeURIComponent(app.handoff)}` : '');
7225
+ return `${base}#${params}`;
7226
+ }
7227
+ async function list() {
7228
+ // This legacy-compatible action shape is also used by oapps.fun listMyApps.
7229
+ const response = await requestDevApi('/', {
7230
+ method: 'POST',
7231
+ body: { action: 'listApps' },
7396
7232
  });
7233
+ const rows = Array.isArray(response.apps) ? response.apps : [];
7234
+ return rows
7235
+ .map((value) => {
7236
+ var _a, _b, _c, _d;
7237
+ const row = value && typeof value === 'object'
7238
+ ? value
7239
+ : {};
7240
+ const appId = String((_c = (_b = (_a = row._id) !== null && _a !== void 0 ? _a : row.id) !== null && _b !== void 0 ? _b : row.appId) !== null && _c !== void 0 ? _c : '');
7241
+ if (!/^[a-f0-9]{24}$/i.test(appId))
7242
+ return null;
7243
+ const name = String((_d = row.name) !== null && _d !== void 0 ? _d : '').trim() || '(unnamed app)';
7244
+ const slug = typeof row.slug === 'string' && row.slug ? row.slug : undefined;
7245
+ const url = typeof row.url === 'string' && row.url.trim() ? row.url.trim() : undefined;
7246
+ const buildStatus = row.buildStatus === 'building' || row.buildStatus === 'build_failed'
7247
+ ? row.buildStatus
7248
+ : undefined;
7249
+ return Object.assign(Object.assign(Object.assign({ appId,
7250
+ name }, (slug ? { slug } : {})), (url ? { url } : {})), (buildStatus ? { buildStatus } : {}));
7251
+ })
7252
+ .filter((app) => app !== null);
7397
7253
  }
7398
7254
  /**
7399
- * Open the Bounded Turnkey signer popup and sign `message` (raw bytes) with the
7400
- * user's non-custodial Turnkey wallet, resolving with the ed25519 signature +
7401
- * the wallet address. MUST be called from a USER GESTURE (click/tap) or the
7402
- * browser blocks the popup.
7403
- *
7404
- * On the user's FIRST signature the popup transparently enrolls a device passkey
7405
- * (Face ID / Touch ID) and creates their wallet - no email code. Subsequent
7406
- * signatures are just a passkey approval.
7255
+ * Platform first-party surfaces only (bounded.sh, oapps.fun, localhost) —
7256
+ * dev-api CORS blocks calls from generated-app origins. Server-side callers unaffected.
7407
7257
  */
7408
- async function signSolanaMessageViaTurnkey(message) {
7409
- if (!hasDOM$1()) {
7410
- throw new Error('Turnkey embedded-wallet signing is only available in the browser (popup-based).');
7258
+ const apps = { create, list, buildCreateRedirectUrl };
7259
+
7260
+ async function deserializeTransaction(tx) {
7261
+ // Literal specifier so bundlers can code-split the lazy chunk.
7262
+ const { Transaction, VersionedTransaction } = await import('@solana/web3.js');
7263
+ const buf = Buffer.isBuffer(tx) ? tx : Buffer.from(tx, 'base64');
7264
+ if ((buf[0] & 0x80) !== 0) {
7265
+ return VersionedTransaction.deserialize(buf);
7266
+ }
7267
+ else {
7268
+ return Transaction.from(buf);
7411
7269
  }
7412
- const { url, origin } = await turnkeySignerPage();
7413
- const requestId = `tksign_${Date.now()}_${++requestSeq}`;
7414
- const messageHex = toHex(message);
7415
- return await deliver(url, origin, {
7416
- request: { type: 'bounded:turnkey:sign', requestId, messageHex },
7417
- onResult: (d) => {
7418
- if (d.ok && typeof d.signatureHex === 'string' && typeof d.address === 'string') {
7419
- return { done: true, value: { signature: fromHex(d.signatureHex), address: d.address, subOrgId: String(d.subOrgId || '') } };
7420
- }
7421
- return { error: String(d.error || 'Turnkey signing failed') };
7422
- },
7423
- });
7424
7270
  }
7425
7271
 
7426
7272
  // bounded.onramp() - fund the signed-in user's wallet with Coinbase Onramp.
@@ -8088,7 +7934,6 @@ exports.BUILD_DELEGATED_REVIEW_CAPABILITY_SCHEMA = BUILD_DELEGATED_REVIEW_CAPABI
8088
7934
  exports.BUILD_REVIEW_CAPABILITY_REFRESH_SCHEMA = BUILD_REVIEW_CAPABILITY_REFRESH_SCHEMA;
8089
7935
  exports.BUILD_REVIEW_CAPABILITY_SCHEMA = BUILD_REVIEW_CAPABILITY_SCHEMA;
8090
7936
  exports.BuildsApiError = BuildsApiError;
8091
- exports.EMBEDDED_WALLET_UNSUPPORTED = EMBEDDED_WALLET_UNSUPPORTED;
8092
7937
  exports.FAILURE_REASONS = FAILURE_REASONS;
8093
7938
  exports.NON_TERMINAL_STATES = NON_TERMINAL_STATES;
8094
7939
  exports.OffchainAuthProvider = OffchainAuthProvider;
@@ -8106,16 +7951,13 @@ exports.confirmAndCheckTransaction = confirmAndCheckTransaction;
8106
7951
  exports.defaultInjectedEvmProvider = defaultInjectedEvmProvider;
8107
7952
  exports.defaultInjectedProvider = defaultInjectedProvider;
8108
7953
  exports.deserializeTransaction = deserializeTransaction;
8109
- exports.embeddedRunEvmTransaction = embeddedRunEvmTransaction;
8110
- exports.embeddedSignAndSubmit = embeddedSignAndSubmit;
8111
7954
  exports.getAuthLoading = getAuthLoading;
8112
7955
  exports.getAuthProvider = getAuthProvider;
8113
7956
  exports.getCurrentUser = getCurrentUser;
8114
7957
  exports.getIdToken = getIdToken;
8115
7958
  exports.getOrCreateTurnkeyWallet = getOrCreateTurnkeyWallet;
8116
7959
  exports.getPlatform = getPlatform;
8117
- exports.hasEmbeddedEvmWallet = hasEmbeddedEvmWallet;
8118
- exports.hasEmbeddedWallet = hasEmbeddedWallet;
7960
+ exports.hasTurnkeyWallet = hasTurnkeyWallet;
8119
7961
  exports.init = init;
8120
7962
  exports.login = login;
8121
7963
  exports.loginWithPopup = loginWithPopup;
@@ -8135,10 +7977,13 @@ exports.resolveSolanaRpcUrl = resolveSolanaRpcUrl;
8135
7977
  exports.setAuthLoading = setAuthLoading;
8136
7978
  exports.setCurrentUser = setCurrentUser;
8137
7979
  exports.setPlatform = setPlatform;
7980
+ exports.signAndSubmitTransactionWithTurnkey = signAndSubmitTransactionWithTurnkey;
8138
7981
  exports.signInAnonymously = signInAnonymously;
7982
+ exports.signMessageWithTurnkey = signMessageWithTurnkey;
8139
7983
  exports.signSolanaMessageViaTurnkey = signSolanaMessageViaTurnkey;
7984
+ exports.signTransactionWithTurnkey = signTransactionWithTurnkey;
8140
7985
  exports.startTurnkeyEmailLogin = startTurnkeyEmailLogin;
8141
7986
  exports.useAuth = useAuth;
8142
7987
  exports.useBuildRun = useBuildRun;
8143
7988
  exports.useQuery = useQuery;
8144
- //# sourceMappingURL=index-C_L497w1.js.map
7989
+ //# sourceMappingURL=index-Bk0nEjB6.js.map