@capxul/sdk 1.2.2 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -20
- package/dist/{create-capxul-client-DVzm78RU.mjs → create-capxul-client-BTnlLLag.mjs} +462 -66
- package/dist/create-capxul-client-BTnlLLag.mjs.map +1 -0
- package/dist/{create-capxul-client-C7H5b68l.d.mts → create-capxul-client-BxTtXho7.d.mts} +287 -285
- package/dist/create-capxul-client-BxTtXho7.d.mts.map +1 -0
- package/dist/index.d.mts +29 -78
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +131 -405
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +1 -1
- package/dist/{signer-CJT0pPiO.d.mts → signer-DgWAmtmi.d.mts} +2 -3
- package/dist/{signer-CJT0pPiO.d.mts.map → signer-DgWAmtmi.d.mts.map} +1 -1
- package/dist/testing/index.d.mts +1 -1
- package/dist/testing/index.mjs +1 -1
- package/package.json +4 -4
- package/dist/create-capxul-client-C7H5b68l.d.mts.map +0 -1
- package/dist/create-capxul-client-DVzm78RU.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["EVM_ADDRESS_HEX","ECDSA_SIGNATURE_HEX","SAFE_OP_DIGEST_HEX","recoverRawDigestSigner","withSignal","DEFAULT_JWT_LIFETIME_S","decodeJwtExp","authSessionFromBetterAuth","safeJson","isAbortError","mapFetchError","#client","#tokenProvider","#applicationId","#observation","#observedArgs","#convex","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#chainId","#runMutation","#runQuery","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#readTreasuryWire","#convex","#signer","#chainId","#fns","#lifecycleAction","#capture","#identify","#group","#reset","#run","SDK_VERSION","sdkPackageJson.version","sdkPackageJson.version","createCapxulClient","createCapxulClientFromProductionAdapters"],"sources":["../src/surface/account-providers.ts","../src/signer.ts","../src/dev-signer.ts","../src/ports/embedded-wallet.ts","../src/openfort-embedded-signer.ts","../package.json","../../observability/src/engineering.ts","../src/adapters/auth-client/resolve-auth-url.ts","../src/internal/observation-http.ts","../src/adapters/auth-client/BetterAuthBrowserAdapter.ts","../src/adapters/auth-client/cookie-jar.ts","../src/adapters/auth-client/BetterAuthNodeAdapter.ts","../src/adapters/bootstrap/HttpBootstrapAdapter.ts","../src/adapters/clock/SystemClockAdapter.ts","../src/adapters/convex-call/ConvexCallAdapter.ts","../src/adapters/identity/ConvexIdentityAdapter.ts","../src/adapters/account-read/ConvexAccountAdapter.ts","../src/adapters/sub-account/ConvexSubAccountAdapter.ts","../src/adapters/smart-account/ConvexSmartAccountAdapter.ts","../src/ports/org.ts","../src/adapters/org/parse.ts","../src/adapters/org/ConvexOrganizationAdapter.ts","../src/adapters/org/ConvexOrganizationSetupAdapter.ts","../src/adapters/telemetry/PostHogTelemetryAdapter.ts","../src/adapters/diagnostic/ConsoleDiagnosticAdapter.ts","../src/openfort/create-openfort-browser-signer.ts","../src/observation.ts","../src/production.ts","../src/surface/create-capxul-client-from-production.ts","../src/telemetry/from-posthog.ts"],"sourcesContent":["import { Errors } from \"@capxul/config\";\nimport { toAddress, type Address } from \"@capxul/types\";\nimport type { Account as ViemAccount, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport type AccountProviderSource = \"local-private-key\" | \"openfort-embedded\" | \"injected-eip1193\";\n\nexport type AccountRequirement = \"none\" | \"counterfactual\" | \"deployed\";\n\nexport interface AccountProvider {\n readonly source: AccountProviderSource;\n /**\n * Resolve the signer's EVM address.\n *\n * @determinism MUST return the same `Address` across calls for the\n * lifetime of a single provider instance — the SDK-level deploy mutex\n * keys on `(authUserId, safeAddress)` where `safeAddress` is computed\n * from `getAddress()`'s result before the port's `prepare()` round-trip.\n * If two successive calls returned different addresses, concurrent\n * `deploySafe` invocations would compute different mutex keys and\n * bypass dedup, defeating the mutex.\n *\n * The two sanctioned providers both satisfy this invariant:\n * - `localPrivateKeyAccountProvider` — derives once from the key\n * - `eip1193AccountProvider` — reads `eth_accounts` (idempotent once\n * the wallet is connected; consumer is responsible for connection)\n *\n * The Openfort embedded path no longer needs a provider: the\n * `openfortEmbeddedSigner` `CapxulSigner` caches its own address and the\n * deploy is backend-orchestrated (backend-orchestrated-deploy.md).\n *\n * Custom providers MUST honor this contract.\n */\n getAddress(): Promise<CapxulResult<Address>>;\n getDeployAccount(): Promise<CapxulResult<ViemAccount>>;\n}\n\nexport interface Eip1193Provider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\nexport function localPrivateKeyAccountProvider(input: {\n readonly privateKey: Hex;\n}): AccountProvider {\n const account = privateKeyToAccount(input.privateKey);\n const address = toAddress(account.address);\n return {\n source: \"local-private-key\",\n async getAddress() {\n return { ok: true, value: address };\n },\n async getDeployAccount() {\n return { ok: true, value: account };\n },\n };\n}\n\nexport function eip1193AccountProvider(input: {\n readonly provider: Eip1193Provider;\n}): AccountProvider {\n // Cache the first successful address to honor the determinism contract on\n // `AccountProvider.getAddress` (see JSDoc above). Without this cache, a user\n // switching accounts in their browser wallet mid-flow would produce a\n // different `Address` on successive calls, defeating the deploy mutex.\n // Errors are intentionally NOT cached — transient wallet-not-connected or\n // RPC failures must remain retryable.\n //\n // `inFlight` memoizes the in-progress request so that concurrent first\n // callers (e.g. two `await provider.getAddress()` issued in parallel before\n // either resolves) share the same `eth_accounts` round-trip and the same\n // resolved Address. Without it, both calls would race, both would hit the\n // wallet, and the second resolver could overwrite `cachedAddress` with a\n // stale-vs-fresh wallet read — defeating determinism even with the resolved\n // cache. Cleared in `finally` so the lane stays retryable after errors.\n let cachedAddress: Address | null = null;\n let inFlight: Promise<CapxulResult<Address>> | null = null;\n\n const getAddress = async (): Promise<CapxulResult<Address>> => {\n if (cachedAddress !== null) {\n return { ok: true, value: cachedAddress };\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const accounts = await input.provider.request({ method: \"eth_accounts\" });\n const first = firstAccount(accounts);\n if (first === null) {\n return { ok: false, error: Errors.smartAccountMissing(\"eip1193-account\") };\n }\n const address = toAddress(first);\n cachedAddress = address;\n return { ok: true, value: address };\n } catch (err) {\n return {\n ok: false,\n error: Errors.providerError(\"eip1193\", \"eth_accounts\", err),\n };\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n return {\n source: \"injected-eip1193\",\n getAddress,\n async getDeployAccount() {\n return {\n ok: false,\n error: Errors.notImplemented(\"Eip1193AccountProvider\", \"getDeployAccount\"),\n };\n },\n };\n}\n\nfunction firstAccount(value: unknown): string | null {\n if (!Array.isArray(value)) return null;\n const first = value[0];\n return typeof first === \"string\" ? first : null;\n}\n","// CapxulSigner — the consumer-held key boundary (backend-orchestrated-deploy.md).\n//\n// The backend orchestrates the Safe deployment (build + gas + paymaster + submit)\n// but never holds the user's key. The consumer supplies a `CapxulSigner` that\n// signs exactly one thing: the EIP-712 `SafeOp` digest the backend returns for\n// the prepared deployment UserOperation. `safe4337SafeOpDigest` (@capxul/config)\n// computes that digest; this signer produces the owner signature; the backend\n// packs + submits. Verified equivalent to permissionless's inline signing in\n// `src/__tests__/safe4337-split-sign.test.ts`.\n//\n// Security note: the browser signer uses `eth_sign`, which can sign arbitrary\n// bytes. In the backend-orchestrated flow, `CapxulSigner` signs only the\n// backend-provided SafeOp digest, so consumers must trust the backend that\n// constructs the UserOperation and computes that digest. A malicious backend\n// could ask the wallet to sign a harmful digest; prefer typed structured\n// signing when that flow exists, and only enable raw-hash signing for trusted\n// Capxul deployments.\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport type { AccountProviderSource } from \"./surface/account-providers\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface CapxulDigestSigner {\n /**\n * Sign the EIP-712 `SafeOp` digest the backend returns for the prepared\n * deployment UserOperation. Returns the raw 65-byte ECDSA signature; the\n * backend packs `validAfter|validUntil|signature`.\n */\n signUserOpHash(hash: Hex): Promise<Hex>;\n}\n\nexport interface CapxulSigner extends CapxulDigestSigner {\n /**\n * Signer kind — surfaced on the `accountProviderReady` status so the\n * readiness ladder reports which signer the consumer wired.\n */\n readonly source: AccountProviderSource;\n /** Owner EOA address — the Safe's single owner. */\n getAddress(): Promise<Address>;\n}\n\n/** Minimal EIP-1193 surface an injected browser wallet exposes. */\nexport interface Eip1193RequestProvider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\n/**\n * Browser `CapxulSigner` backed by an injected EIP-1193 wallet (MetaMask, etc.).\n * Signs the SafeOp digest via `eth_sign`, then verifies the returned signature\n * recovers the selected account against that raw digest. Wallets that prefix\n * `eth_sign` payloads are rejected before the backend submits an invalid SafeOp.\n * The node key signer lives in `@capxul/sdk/node` (`localPrivateKeySigner`).\n */\nexport function injectedWalletSigner(provider: Eip1193RequestProvider): CapxulSigner {\n const resolveAddress = async (): Promise<Address> => {\n const accounts = await provider.request({ method: \"eth_requestAccounts\" });\n const first = Array.isArray(accounts) ? accounts[0] : undefined;\n if (typeof first !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned no accounts\");\n }\n if (!EVM_ADDRESS_HEX.test(first)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid address format\");\n }\n return toAddress(first);\n };\n return {\n source: \"injected-eip1193\",\n getAddress: resolveAddress,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"injectedWalletSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: unknown;\n try {\n signature = await provider.request({ method: \"eth_sign\", params: [address, hash] });\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: eth_sign failed; enable raw-hash signing for deployment (${detail})`,\n { cause },\n );\n }\n if (typeof signature !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned a non-string signature\");\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid signature format\");\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"injectedWalletSigner: wallet signature did not recover the selected account for the raw SafeOp digest; use a raw-hash-capable wallet or @capxul/sdk/node localPrivateKeySigner for deployed flows\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","// devPrivateKeySigner — browser-safe dev-mode `CapxulSigner` (dogfood only).\n//\n// Derives a deterministic throwaway EOA per email: privateKey =\n// keccak256(utf8(seed + normalizedEmail)). Re-login with the same email\n// reproduces the same signer, so binding resolution (signerAddress-hint\n// path) and the account lane stay coherent without Openfort. The seed is a\n// dev-only secret for unfunded keys; never fund these accounts.\n//\n// The signer is constructed before login, so the email is resolved lazily:\n// at first use it reads the cached `AuthSession` the SDK wrote to browser\n// localStorage (`capxul.session`, BrowserAuthCacheAdapter) — or uses the\n// explicit `email` override (tests / non-browser harnesses).\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { keccak256, stringToHex, type Hex } from \"viem\";\nimport { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\n\nimport { BASE_SEPOLIA_CHAIN_ID, Errors, normalizeBindingEmail } from \"@capxul/config\";\n\nimport type { BrowserStorageShape } from \"./adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport type { CapxulResult } from \"./surface/types\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst SESSION_KEY = \"capxul.session\";\n\n/**\n * Chains a `local-private-key` signer may sign on. Base Sepolia only, and this\n * list does not grow without an ADR: the keys are deterministic throwaways\n * derived from a shared seed (see `deriveDevPrivateKey`), so anyone holding\n * the seed holds every account. A dev key on a value-bearing chain is a\n * custody incident, not a config mistake.\n */\nconst DEV_KEY_ALLOWED_CHAIN_IDS: readonly number[] = [BASE_SEPOLIA_CHAIN_ID];\n\n/**\n * Testnet fence for the dev-key signing lane (#1149, folds #1065; ADR-0018 P9\n * human/Openfort vs agent/dev-key split). Call it wherever a signer first\n * meets a resolved chain; it refuses before the signer can be used.\n *\n * Only `local-private-key` signers are fenced — Openfort-embedded and injected\n * wallets carry their own custody and are the sanctioned human paths.\n */\nexport function assertDevKeySignerIsTestnetOnly(\n signer: { readonly source?: string } | undefined,\n chainId: number,\n): CapxulResult<void> {\n if (signer?.source !== \"local-private-key\") return { ok: true, value: undefined };\n if (DEV_KEY_ALLOWED_CHAIN_IDS.includes(chainId)) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.invalidInput(\n \"signer\",\n `dev-key signer is testnet-only: chain ${chainId} is not allowed (expected ${DEV_KEY_ALLOWED_CHAIN_IDS.join(\", \")})`,\n ),\n };\n}\n\nexport interface DevPrivateKeySignerInput {\n /** Dev-only derivation seed (e.g. `VITE_CAPXUL_DEV_SIGNER_SEED`). Throwaway keys only. */\n readonly seed: string;\n /** Explicit email — skips the auth-cache lookup (tests, node harnesses). */\n readonly email?: string;\n /** Storage holding the cached session. Defaults to browser `localStorage`. */\n readonly storage?: BrowserStorageShape;\n}\n\n/** Deterministic dev private key for an email under a seed. Exported for probes. */\nexport function deriveDevPrivateKey(seed: string, email: string): Hex {\n return keccak256(stringToHex(seed + normalizeBindingEmail(email)));\n}\n\nfunction readSessionEmail(storage: BrowserStorageShape | undefined): string {\n const resolved =\n storage ??\n (globalThis as unknown as { window?: { localStorage?: BrowserStorageShape } }).window\n ?.localStorage;\n if (resolved === undefined) {\n throw new Error(\n \"devPrivateKeySigner: no browser localStorage available and no explicit email supplied\",\n );\n }\n const raw = resolved.getItem(SESSION_KEY);\n if (raw === null) {\n throw new Error(\n \"devPrivateKeySigner: no cached session yet — sign in before the account lane uses the signer\",\n );\n }\n let email: unknown;\n try {\n email = (JSON.parse(raw) as { email?: unknown }).email;\n } catch {\n throw new Error(\"devPrivateKeySigner: cached session is not valid JSON\");\n }\n if (typeof email !== \"string\" || email.length === 0) {\n throw new Error(\"devPrivateKeySigner: cached session has no email\");\n }\n return email;\n}\n\n/**\n * Browser-safe dev signer. Lazy: the email (and so the key) is resolved at\n * each `getAddress()` / `signUserOpHash()` from the cached session, so the\n * same signer instance follows whichever user is signed in.\n */\nexport function devPrivateKeySigner(input: DevPrivateKeySignerInput): CapxulSigner {\n if (input.seed.trim().length === 0) {\n throw new Error(\"devPrivateKeySigner: seed must be non-empty\");\n }\n const accounts = new Map<string, PrivateKeyAccount>();\n const resolveAccount = (): PrivateKeyAccount => {\n const email = normalizeBindingEmail(input.email ?? readSessionEmail(input.storage));\n const cached = accounts.get(email);\n if (cached !== undefined) return cached;\n const account = privateKeyToAccount(deriveDevPrivateKey(input.seed, email));\n accounts.set(email, account);\n return account;\n };\n return {\n source: \"local-private-key\",\n async getAddress(): Promise<Address> {\n return toAddress(resolveAccount().address);\n },\n async signUserOpHash(hash: Hex): Promise<Hex> {\n // Raw digest signing — same semantics as `localPrivateKeySigner` in\n // `@capxul/sdk/node`: no EIP-191 prefix on the SafeOp digest.\n return resolveAccount().sign({ hash });\n },\n };\n}\n","import type { Hex } from \"viem\";\n\n/**\n * Minimal Openfort embedded-wallet surface for hermetic tests and\n * `openfortEmbeddedSigner`. Keeps Convex / Shield secrets out of the SDK.\n */\nexport interface OpenfortEmbeddedWalletPort {\n /** Owner EOA address — must stay stable for the lifetime of this port. */\n getAddress(): Promise<string>;\n /**\n * Sign a 32-byte SafeOp digest without EIP-191 prefixing (backend-orchestrated\n * deploy contract).\n */\n signRawDigest(hash: Hex): Promise<Hex>;\n}\n\n/** Openfort `embeddedWallet` subset used by `openfortEmbeddedWalletPort`. */\nexport interface OpenfortEmbeddedWalletApi {\n get(): Promise<{ readonly address: string }>;\n signMessage(\n message: string | Uint8Array,\n options?: { readonly hashMessage?: boolean; readonly arrayifyMessage?: boolean },\n ): Promise<string>;\n}\n\nexport function openfortEmbeddedWalletPort(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureReady?: () => Promise<void>;\n}): OpenfortEmbeddedWalletPort {\n return {\n async getAddress() {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n const account = await input.embeddedWallet.get();\n return account.address;\n },\n async signRawDigest(hash) {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n // The digest must cross the Openfort iframe RPC as the 0x-hex STRING\n // with BOTH flags off — openfort-js's own raw-hash path\n // (walletHelpers: `signer.sign(hash, false, false)`) is the canon.\n // A Uint8Array mangles to UTF-8 across the RPC, and arrayifyMessage\n // triggers a double-arrayify inside the iframe; either way signing\n // dies with \"invalid arrayify value\" (first live signing proof,\n // mcp-stretch S4). hashMessage stays off: raw SafeOp digest, no\n // EIP-191 prefix.\n return (await input.embeddedWallet.signMessage(hash, {\n hashMessage: false,\n arrayifyMessage: false,\n })) as Hex;\n },\n };\n}\n","import { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport {\n openfortEmbeddedWalletPort,\n type OpenfortEmbeddedWalletApi,\n type OpenfortEmbeddedWalletPort,\n} from \"./ports/embedded-wallet\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface OpenfortEmbeddedSignerInput {\n readonly wallet: OpenfortEmbeddedWalletPort;\n}\n\n/** Browser helper: wrap an initialized Openfort `embeddedWallet` API. */\nexport function openfortEmbeddedSignerFromWallet(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureWalletReady?: () => Promise<void>;\n}): OpenfortEmbeddedSigner {\n return openfortEmbeddedSigner({\n wallet: openfortEmbeddedWalletPort({\n embeddedWallet: input.embeddedWallet,\n ...(input.ensureWalletReady === undefined ? {} : { ensureReady: input.ensureWalletReady }),\n }),\n });\n}\n\n/**\n * Browser `CapxulSigner` backed by an Openfort embedded wallet (#335).\n * Signs the backend's SafeOp digest via raw `signMessage` (no EIP-191 prefix)\n * and verifies recovery before the backend submits.\n */\nexport type OpenfortEmbeddedSigner = CapxulSigner & {\n /** Drop cached `getAddress()` so the next read hits the embedded wallet again. */\n readonly resetAddressCache: () => void;\n};\n\nexport function openfortEmbeddedSigner(input: OpenfortEmbeddedSignerInput): OpenfortEmbeddedSigner {\n let cachedAddress: Address | null = null;\n let addressInFlight: Promise<Address> | null = null;\n // Bumped on every reset so a resolve that started before the reset cannot\n // win the race and repopulate the cache with the now-stale session address.\n let cacheEpoch = 0;\n\n const resetAddressCache = (): void => {\n cacheEpoch += 1;\n cachedAddress = null;\n addressInFlight = null;\n };\n\n const resolveAddress = async (): Promise<Address> => {\n if (cachedAddress !== null) {\n return cachedAddress;\n }\n if (addressInFlight !== null) {\n return addressInFlight;\n }\n const epoch = cacheEpoch;\n addressInFlight = (async () => {\n try {\n const raw = await input.wallet.getAddress();\n if (!EVM_ADDRESS_HEX.test(raw)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid address format\",\n );\n }\n const address = toAddress(raw);\n // A reset during this resolve invalidates the result — don't cache it.\n if (epoch === cacheEpoch) {\n cachedAddress = address;\n }\n return address;\n } finally {\n if (epoch === cacheEpoch) {\n addressInFlight = null;\n }\n }\n })();\n return addressInFlight;\n };\n\n return {\n source: \"openfort-embedded\",\n getAddress: resolveAddress,\n resetAddressCache,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"openfortEmbeddedSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: string;\n try {\n signature = await input.wallet.signRawDigest(hash);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: raw digest signing failed; ensure the embedded wallet is configured (${detail})`,\n { cause },\n );\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid signature format\",\n );\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"openfortEmbeddedSigner: signature did not recover the embedded wallet address for the raw SafeOp digest\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\n/**\n * Canonical name for the embedded-wallet `CapxulSigner` constructor\n * (backend-orchestrated-deploy.md). The embedded-wallet (passkey / Openfort)\n * member of the named constructor trio `localPrivateKeySigner` /\n * `injectedWalletSigner` / `embeddedSigner`. Takes the provider-agnostic\n * `OpenfortEmbeddedWalletPort` (getAddress + signRawDigest); the Openfort-API\n * convenience wrapper is `openfortEmbeddedSignerFromWallet`.\n */\nexport const embeddedSigner = openfortEmbeddedSigner;\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","","import { Cause, Effect, Exit, Layer, Tracer } from \"effect\";\nimport { FetchHttpClient, Headers, HttpClient } from \"effect/unstable/http\";\n// Effect v4 deliberately marks the OTLP exporters unstable. This module is the\n// one quarantine seam: no producer imports these modules directly.\nimport {\n OtlpExporter,\n OtlpLogger,\n OtlpSerialization,\n OtlpTracer,\n} from \"effect/unstable/observability\";\n\nexport type EngineeringProducer = \"browser\" | \"server\";\nexport type EngineeringCapxulEnv = \"development\" | \"e2e\" | \"staging\" | \"production\";\n\nexport interface EngineeringTelemetryConfig {\n readonly host: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly capxulEnv: EngineeringCapxulEnv;\n readonly producer: EngineeringProducer;\n readonly sdkVersion: string;\n readonly serviceName?: string;\n}\n\nconst SAFE_TRACED_HEADER_NAMES = [\n \"content-length\",\n \"content-type\",\n \"traceparent\",\n \"tracestate\",\n \"x-request-id\",\n] as const;\n\nconst ENGINEERING_REDACTED_HEADER_NAMES: ReadonlyArray<string | RegExp> = Object.freeze([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n /auth|email|key|otp|secret|session|token|wallet/i,\n]);\n\nexport const traceHeaderFilter = (name: string): boolean =>\n SAFE_TRACED_HEADER_NAMES.includes(\n name.toLowerCase() as (typeof SAFE_TRACED_HEADER_NAMES)[number],\n );\n\nexport const postHogOtlpEndpoints = (host: string) => {\n const base = host.replace(/\\/+$/, \"\");\n return {\n logs: `${base}/i/v1/logs`,\n traces: `${base}/i/v1/traces`,\n } as const;\n};\n\nconst ENGINEERING_CAPXUL_ENVS = new Set<EngineeringCapxulEnv>([\n \"development\",\n \"e2e\",\n \"staging\",\n \"production\",\n]);\nconst ENGINEERING_PRODUCERS = new Set<EngineeringProducer>([\"browser\", \"server\"]);\nconst PUBLIC_POSTHOG_AUTHORIZATION = /^Bearer phc_[A-Za-z0-9_-]{1,191}$/u;\nconst SAFE_RESOURCE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._+@/-]{0,127}$/u;\n\nconst validateEngineeringTelemetryConfig = (\n config: EngineeringTelemetryConfig,\n): EngineeringTelemetryConfig => {\n let url: URL;\n try {\n url = new URL(config.host);\n } catch {\n throw new TypeError(\"engineering telemetry host must be an absolute HTTPS URL\");\n }\n if (\n url.protocol !== \"https:\" ||\n url.username.length > 0 ||\n url.password.length > 0 ||\n url.pathname !== \"/\" ||\n url.search.length > 0 ||\n url.hash.length > 0\n ) {\n throw new TypeError(\"engineering telemetry host must be a credential-free HTTPS origin\");\n }\n if (!ENGINEERING_CAPXUL_ENVS.has(config.capxulEnv)) {\n throw new TypeError(\"engineering telemetry capxulEnv is not canonical\");\n }\n if (!ENGINEERING_PRODUCERS.has(config.producer)) {\n throw new TypeError(\"engineering telemetry producer is not canonical\");\n }\n if (!SAFE_RESOURCE_VALUE.test(config.sdkVersion)) {\n throw new TypeError(\"engineering telemetry sdkVersion must be a bounded safe value\");\n }\n if (config.serviceName !== undefined && !SAFE_RESOURCE_VALUE.test(config.serviceName)) {\n throw new TypeError(\"engineering telemetry serviceName must be a bounded safe value\");\n }\n const headerEntries = Object.entries(config.headers);\n if (\n headerEntries.length !== 1 ||\n headerEntries[0]?.[0].toLowerCase() !== \"authorization\" ||\n !PUBLIC_POSTHOG_AUTHORIZATION.test(headerEntries[0]?.[1] ?? \"\")\n ) {\n throw new TypeError(\n \"engineering telemetry headers must contain exactly one public PostHog authorization token\",\n );\n }\n return {\n ...config,\n host: url.origin,\n headers: Object.freeze({ authorization: headerEntries[0][1] }),\n };\n};\n\nclass RedactedEngineeringSpanFailure extends Error {\n constructor() {\n super(\"Engineering operation failed\");\n this.name = \"RedactedEngineeringSpanFailure\";\n delete this.stack;\n }\n}\n\nconst REDACTED_SPAN_FAILURE = Exit.fail(new RedactedEngineeringSpanFailure());\n\n/** Preserve domain exits while preventing the OTLP serializer from seeing raw causes. */\nexport const makeLeakSafeEngineeringTracer = (delegate: Tracer.Tracer): Tracer.Tracer =>\n Tracer.make({\n span(options) {\n const span = delegate.span(options);\n const wrapped = Object.create(span) as Tracer.Span;\n Object.defineProperty(wrapped, \"end\", {\n configurable: false,\n enumerable: false,\n value: (endTime: bigint, exit: Exit.Exit<unknown, unknown>) =>\n span.end(\n endTime,\n Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)\n ? REDACTED_SPAN_FAILURE\n : exit,\n ),\n writable: false,\n });\n return wrapped;\n },\n ...(delegate.context === undefined ? {} : { context: delegate.context.bind(delegate) }),\n });\n\n/** Shared browser/server OTLP layer. OtlpLogger merges with incumbent loggers once. */\nexport const makeEngineeringTelemetryLayer = (config: EngineeringTelemetryConfig) => {\n const validated = validateEngineeringTelemetryConfig(config);\n const endpoints = postHogOtlpEndpoints(validated.host);\n const resource = {\n serviceName: validated.serviceName ?? \"capxul-sdk\",\n serviceVersion: validated.sdkVersion,\n attributes: {\n capxul_env: validated.capxulEnv,\n producer: validated.producer,\n sdk_version: validated.sdkVersion,\n },\n } as const;\n const tracing = Layer.effect(\n Tracer.Tracer,\n OtlpTracer.make({\n url: endpoints.traces,\n headers: validated.headers,\n resource,\n }).pipe(Effect.map(makeLeakSafeEngineeringTracer)),\n ).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));\n const logging = OtlpLogger.layer({\n url: endpoints.logs,\n headers: validated.headers,\n resource,\n mergeWithExisting: true,\n });\n const headerPolicy = Layer.merge(\n Layer.succeed(HttpClient.TracerHeaderFilter, traceHeaderFilter),\n Layer.succeed(Headers.CurrentRedactedNames, ENGINEERING_REDACTED_HEADER_NAMES),\n );\n return Layer.mergeAll(tracing, logging, headerPolicy).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n};\n","/** Join bootstrap `authBaseUrl` with a BetterAuth route without duplicating `/api/auth`. */\nexport function resolveAuthClientUrl(authBaseUrl: string, path: string): string {\n const base = authBaseUrl.replace(/\\/$/, \"\");\n if (base.endsWith(\"/api/auth\") && path.startsWith(\"/api/auth\")) {\n return `${base}${path.slice(\"/api/auth\".length)}`;\n }\n return `${base}${path}`;\n}\n","import {\n encodeObservationContextHeader,\n OBSERVATION_CONTEXT_HEADER,\n} from \"@capxul/wire/observation-context\";\n\nimport type { ObservationAdapter } from \"../observation\";\n\n/** Resolve one bounded pre-auth snapshot for an outbound SDK HTTP request. */\nexport function observationRequestHeaders(\n adapter: ObservationAdapter | undefined,\n): Readonly<Record<string, string>> {\n if (adapter === undefined) return {};\n try {\n const encoded = encodeObservationContextHeader(adapter.resolveContext?.());\n return encoded === undefined ? {} : { [OBSERVATION_CONTEXT_HEADER]: encoded };\n } catch {\n return {};\n }\n}\n","// BetterAuthBrowserAdapter — TA3 production adapter for browser runtimes.\n// Aligned with W1/W2/W3/W6/W7 wire reality verified against\n// incredible-possum-990 (2026-05-19) using @convex-dev/better-auth@0.10.13.\n//\n// - W1 sendOtp POST /api/auth/email-otp/send-verification-otp\n// body `{email, type: \"sign-in\"}`\n// 200 `{success: true}` | 400 `{code, message}`\n// - W2 verifyOtp POST /api/auth/sign-in/email-otp\n// 200 `{token, user}` + Set-Cookie headers |\n// 400 `{code, message}` (OTP_EXPIRED, INVALID_OTP)\n// - W3 getSession GET /api/auth/get-session\n// 200 literal `null` body OR `{session, user}`\n// - W6 signOut POST /api/auth/sign-out body `\"{}\"`\n// (without body the server returns 500 — F11)\n// - W7 getConvexJwt GET /api/auth/convex/token\n// 200 `{token: <JWT>}`; decode `exp` for cache\n// eviction (Probe A: fresh JWT per call)\n//\n// Browser-runtime semantics: the browser fetch automatically attaches +\n// stores cookies for the same-origin domain. We send `credentials: \"include\"`\n// on requests that need cookies, but never read/write Set-Cookie ourselves —\n// that's the browser's job. The Node adapter takes a different path via\n// CookieJar (see BetterAuthNodeAdapter).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthBrowserAdapterDeps {\n readonly authBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n readonly emailVerified?: boolean;\n readonly name?: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface GetSessionBody {\n readonly session: { readonly id?: string; readonly token?: string; readonly expiresAt?: string };\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\n// Sentinel — a 15-min JWT lifetime per Probe A. Used when we can't decode\n// the `exp` claim from a malformed/opaque token (fixtures, defensive depth).\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n // Strip whitespace defensively (real JWTs don't have it; the fixture\n // builder's line-wrap can introduce some).\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = atob(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad);\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction mapBetterAuthError(\n operation: string,\n body: unknown,\n): ReturnType<typeof Errors.invalidInput | typeof Errors.providerError | typeof Errors.otpExpired> {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n const code = typeof errBody.code === \"string\" ? errBody.code : \"\";\n if (code === \"OTP_EXPIRED\") {\n return Errors.otpExpired();\n }\n if (code === \"INVALID_OTP\") {\n return Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\");\n }\n if (code === \"VALIDATION_ERROR\" || code === \"INVALID_EMAIL\") {\n return Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\");\n }\n }\n return Errors.providerError(\"better-auth\", operation, new Error(String(body)));\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthBrowserAdapter {\n private readonly authBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthBrowserAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...observationRequestHeaders(this.observation),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n if (res.status === 429) {\n return { ok: false, error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }) };\n }\n const body = await safeJson(res);\n // W1 errors: 400 with { code, message } shape — OTP_EXPIRED can't\n // appear on send; INVALID_EMAIL / VALIDATION_ERROR can.\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n const body = await safeJson(res);\n if (res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(\"unexpected 200 body\")),\n };\n }\n // W2 errors: structured 400 with `{ code, message }`.\n return { ok: false, error: mapBetterAuthError(\"verifyOtp\", body) };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n // W3 body is literal `null` OR a `{session, user}` object.\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<GetSessionBody>;\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n // Build a session synthetically — get-session doesn't return a\n // bearer token in the body (cookies carry it). For ports that\n // want a non-null AuthSession on success, we set token to the\n // session id if available.\n const token = okBody.session?.token ?? okBody.session?.id ?? \"session\";\n return { ok: true, value: authSessionFromBetterAuth(token, okBody.user) };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n // F11: BetterAuth REQUIRES a non-empty body + Content-Type:\n // application/json. Without it the route returns HTTP 500.\n headers: { \"Content-Type\": \"application/json\" },\n body: \"{}\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n // forceRefresh is observed by the caller (ConvexCallAdapter); the\n // bridge mints fresh on every call regardless (Probe A).\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthBrowserLayer(\n deps: BetterAuthBrowserAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthBrowserAdapter(deps)),\n );\n}\n","// Minimal in-tree cookie jar for the Node auth-client adapter (tactical\n// placeholder 4 resolution). Scope is tiny: set + replay via `Cookie`\n// header on subsequent requests, expiry tracking, scope-by-host.\n//\n// No `tough-cookie` dependency.\n\nexport interface ParsedCookie {\n readonly name: string;\n readonly value: string;\n readonly maxAgeSeconds: number | null;\n readonly expiresEpochMs: number | null;\n readonly path: string | null;\n readonly httpOnly: boolean;\n readonly secure: boolean;\n readonly sameSite: \"strict\" | \"lax\" | \"none\" | null;\n}\n\ninterface StoredCookie extends ParsedCookie {\n readonly storedAtEpochMs: number;\n}\n\nfunction parseSetCookie(raw: string): ParsedCookie | null {\n // Set-Cookie header format: `name=value; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax`\n const parts = raw.split(\";\").map((p) => p.trim());\n if (parts.length === 0 || parts[0] === undefined) return null;\n const nameValue = parts[0];\n const eq = nameValue.indexOf(\"=\");\n if (eq < 0) return null;\n const name = nameValue.slice(0, eq).trim();\n const value = nameValue.slice(eq + 1).trim();\n if (name.length === 0) return null;\n\n let maxAgeSeconds: number | null = null;\n let expiresEpochMs: number | null = null;\n let path: string | null = null;\n let httpOnly = false;\n let secure = false;\n let sameSite: \"strict\" | \"lax\" | \"none\" | null = null;\n\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (part === undefined) continue;\n const partEq = part.indexOf(\"=\");\n const key = (partEq < 0 ? part : part.slice(0, partEq)).trim().toLowerCase();\n const val = partEq < 0 ? \"\" : part.slice(partEq + 1).trim();\n if (key === \"max-age\") {\n const n = Number(val);\n if (Number.isFinite(n)) maxAgeSeconds = n;\n } else if (key === \"expires\") {\n const t = Date.parse(val);\n if (Number.isFinite(t)) expiresEpochMs = t;\n } else if (key === \"path\") {\n path = val;\n } else if (key === \"httponly\") {\n httpOnly = true;\n } else if (key === \"secure\") {\n secure = true;\n } else if (key === \"samesite\") {\n const lc = val.toLowerCase();\n if (lc === \"strict\" || lc === \"lax\" || lc === \"none\") sameSite = lc;\n }\n }\n\n return { name, value, maxAgeSeconds, expiresEpochMs, path, httpOnly, secure, sameSite };\n}\n\nfunction isExpired(cookie: StoredCookie, nowEpochMs: number): boolean {\n if (cookie.maxAgeSeconds !== null) {\n if (cookie.maxAgeSeconds <= 0) return true;\n return nowEpochMs >= cookie.storedAtEpochMs + cookie.maxAgeSeconds * 1000;\n }\n if (cookie.expiresEpochMs !== null) {\n return nowEpochMs >= cookie.expiresEpochMs;\n }\n // Session cookie — never expires in this process. The Node adapter does\n // not preserve the jar across processes; this is fine.\n return false;\n}\n\nexport class CookieJar {\n // host → name → cookie. Map preserves insertion order, which keeps the\n // serialized Cookie header deterministic for tests.\n private readonly store = new Map<string, Map<string, StoredCookie>>();\n\n set(host: string, setCookieHeaders: readonly string[]): void {\n let perHost = this.store.get(host);\n const now = Date.now();\n for (const raw of setCookieHeaders) {\n const parsed = parseSetCookie(raw);\n if (parsed === null) continue;\n if (perHost === undefined) {\n perHost = new Map();\n this.store.set(host, perHost);\n }\n // Max-Age=0 (or negative) immediately deletes; treat as a clear.\n if (parsed.maxAgeSeconds !== null && parsed.maxAgeSeconds <= 0) {\n perHost.delete(parsed.name);\n continue;\n }\n perHost.set(parsed.name, { ...parsed, storedAtEpochMs: now });\n }\n if (perHost !== undefined && perHost.size === 0) {\n this.store.delete(host);\n }\n }\n\n getCookieHeader(host: string): string | null {\n const perHost = this.store.get(host);\n if (perHost === undefined || perHost.size === 0) return null;\n const now = Date.now();\n const live: string[] = [];\n for (const [name, cookie] of perHost.entries()) {\n if (isExpired(cookie, now)) {\n perHost.delete(name);\n continue;\n }\n live.push(`${name}=${cookie.value}`);\n }\n if (live.length === 0) {\n this.store.delete(host);\n return null;\n }\n return live.join(\"; \");\n }\n}\n","// BetterAuthNodeAdapter — TA3 production adapter for Node + Ink runtimes.\n// Same surface as the browser adapter; cookies round-trip via the in-tree\n// CookieJar instead of being managed by the browser.\n//\n// Wire shapes are identical to BetterAuthBrowserAdapter (W1/W2/W3/W6/W7).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\n\nimport { CookieJar } from \"./cookie-jar\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthNodeAdapterDeps {\n readonly authBaseUrl: string;\n /**\n * Some BetterAuth routes (notably sign-out) enforce an Origin check and will\n * return 403 if absent. For Node clients, pass the same origin a browser\n * would send (e.g. SITE_URL).\n */\n readonly origin?: string;\n readonly cookieJar?: CookieJar;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = Buffer.from(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\").toString(\n \"utf-8\",\n );\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n try {\n return new URL(baseUrl).host;\n } catch {\n return baseUrl;\n }\n}\n\nfunction originFromBaseUrl(baseUrl: string): string | undefined {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction setCookiesFromResponse(jar: CookieJar, host: string, res: Response): void {\n // Headers.getSetCookie() is the Node 19.7+ way; falls back to single header\n // splitting if unavailable.\n type HeadersExt = Headers & { getSetCookie?: () => string[] };\n const ext = res.headers as HeadersExt;\n let setCookies: string[] = [];\n if (typeof ext.getSetCookie === \"function\") {\n setCookies = ext.getSetCookie();\n } else {\n res.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\") setCookies.push(value);\n });\n }\n if (setCookies.length > 0) jar.set(host, setCookies);\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthNodeAdapter {\n private readonly authBaseUrl: string;\n private readonly host: string;\n private readonly origin: string | undefined;\n private readonly cookieJar: CookieJar;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthNodeAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.host = hostFromBaseUrl(this.authBaseUrl);\n this.origin = deps.origin?.replace(/\\/$/, \"\");\n this.cookieJar = deps.cookieJar ?? new CookieJar();\n this.fetchImpl = deps.fetch ?? fetch;\n this.observation = deps.observation;\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n private headersWithCookie(extra: Record<string, string> = {}): Record<string, string> {\n const cookie = this.cookieJar.getCookieHeader(this.host);\n return cookie !== null ? { ...extra, cookie } : { ...extra };\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n ...observationRequestHeaders(this.observation),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) return { ok: true, value: undefined };\n if (res.status === 429) {\n return {\n ok: false,\n error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n setCookiesFromResponse(this.cookieJar, this.host, res);\n const body = await safeJson(res);\n if (res.ok && typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n if (!res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"OTP_EXPIRED\") {\n return { ok: false, error: Errors.otpExpired() };\n }\n if (errBody.code === \"INVALID_OTP\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\"),\n };\n }\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as {\n readonly session?: { readonly id?: string; readonly token?: string };\n readonly user?: BetterAuthUser;\n };\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n return {\n ok: true,\n value: authSessionFromBetterAuth(\n okBody.session?.token ?? okBody.session?.id ?? \"session\",\n okBody.user,\n ),\n };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const signOutOrigin = originFromBaseUrl(this.authBaseUrl) ?? this.origin;\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n headers: this.headersWithCookie({\n \"content-type\": \"application/json\",\n ...(signOutOrigin ? { origin: signOutOrigin } : {}),\n }),\n body: \"{}\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // The sign-out response sets Max-Age=0 cookies — the jar treats those\n // as immediate deletions.\n setCookiesFromResponse(this.cookieJar, this.host, res);\n if (res.ok) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthNodeLayer(\n deps: BetterAuthNodeAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthNodeAdapter(deps)),\n );\n}\n","// HttpBootstrapAdapter — TA3 production adapter. Calls\n// POST `/v1/client/bootstrap` on the backend. Per W4 + issue #119\n// (audit row B3), the 200 body is a versioned `BootstrapEnvelope`\n// shared with the producer via `@capxul/wire` — backend encodes,\n// SDK decodes, same schema both sides.\n//\n// Error mapping:\n// HTTP 401 and explicit NOT_AUTHENTICATED bodies map to NOT_AUTHENTICATED.\n// Schema-decode failures on a 200 body map to INVALID_INPUT per #119 AC1.\n// Provider 500s stay PROVIDER_ERROR so infrastructure faults are not collapsed\n// into auth failures.\n\nimport { Effect, Result, Layer } from \"effect\";\nimport { SchemaIssue, SchemaParser } from \"effect\";\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { BootstrapEnvelope } from \"@capxul/wire\";\n\nimport type { BootstrapInput, BootstrapPort, BootstrapResolution } from \"../../ports/bootstrap\";\nimport { BootstrapError, BootstrapPortTag, bootstrapErrorFromCapxul } from \"../../ports/bootstrap\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface HttpBootstrapAdapterDeps {\n readonly bootstrapBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text();\n } catch {\n return \"\";\n }\n}\n\nexport class HttpBootstrapAdapter implements BootstrapPort {\n private readonly bootstrapBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: HttpBootstrapAdapterDeps) {\n this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n // Bind through an arrow — assigning `fetch` to `this.fetchImpl` and calling it\n // as a method throws \"Illegal invocation\" in browsers.\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n resolve(input: BootstrapInput): Effect.Effect<BootstrapResolution, BootstrapError> {\n return Effect.tryPromise({\n try: () => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...observationRequestHeaders(this.observation),\n };\n return this.fetchImpl(`${this.bootstrapBaseUrl}/v1/client/bootstrap`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ publishableKey: input.publishableKey }),\n });\n },\n catch: (cause) =>\n bootstrapErrorFromCapxul(\"network\", Errors.networkError(\"bootstrap\", cause)),\n }).pipe(Effect.flatMap((res) => this.mapResponse(res)));\n }\n\n private mapResponse(res: Response): Effect.Effect<BootstrapResolution, BootstrapError> {\n if (res.ok) {\n return Effect.tryPromise({\n try: async () => {\n const body: unknown = await res.json();\n // `BootstrapEnvelope` lives in `@capxul/wire` so the producer\n // (`packages/backend/convex/credentials/http.ts`) and this\n // consumer share one schema. Branded fields (`applicationId`,\n // `chainId`, `sessionToken`, `issuedAt`, `expiresIn`) come out\n // of decode already branded — no `to*` chain afterwards.\n const decoded = SchemaParser.decodeUnknownResult(BootstrapEnvelope)(body);\n if (Result.isFailure(decoded)) {\n // Schema validation failure → INVALID_INPUT per #119 AC1.\n // Unknown `version` literals, missing fields, and brand-rule\n // failures (e.g. `applicationId` not matching `APP_ID_RE`)\n // all land here.\n throw Errors.invalidInput(\n \"bootstrapEnvelope\",\n SchemaIssue.makeFormatterDefault()(decoded.failure),\n );\n }\n const { state } = decoded.success;\n return {\n applicationId: state.applicationId,\n chainId: state.chainId,\n sessionToken: state.sessionToken,\n issuedAt: state.issuedAt,\n expiresIn: state.expiresIn,\n authBaseUrl: normalizeRuntimeUrl(\"authBaseUrl\", state.authBaseUrl),\n convexUrl: normalizeRuntimeUrl(\"convexUrl\", state.convexUrl),\n siteBaseUrl: normalizeRuntimeUrl(\"siteBaseUrl\", state.siteBaseUrl),\n openfortPublishableKey: state.openfortPublishableKey,\n shieldPublishableKey: state.shieldPublishableKey,\n };\n },\n catch: (cause) => {\n if (cause instanceof CapxulError && cause.code === \"INVALID_INPUT\") {\n return bootstrapErrorFromCapxul(\"invalidInput\", cause);\n }\n return bootstrapErrorFromCapxul(\n \"malformedBody\",\n Errors.providerError(\n \"convex\",\n \"bootstrap\",\n cause instanceof Error ? cause : new Error(String(cause)),\n ),\n );\n },\n });\n }\n\n return Effect.promise(() => safeText(res)).pipe(\n Effect.flatMap((body) => {\n if (res.status === 401 || body.startsWith(\"NOT_AUTHENTICATED\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\"notAuthenticated\", Errors.notAuthenticated()),\n );\n }\n if (res.status === 400 || body.startsWith(\"INVALID_INPUT\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"invalidInput\",\n Errors.invalidInput(\"publishableKey\", \"rejected by bootstrap\"),\n ),\n );\n }\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"provider\",\n Errors.providerError(\"convex\", \"bootstrap\", new Error(`HTTP ${res.status}`)),\n ),\n );\n }),\n );\n }\n}\n\nexport function HttpBootstrapLayer(deps: HttpBootstrapAdapterDeps): Layer.Layer<BootstrapPortTag> {\n return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));\n}\n\nfunction normalizeRuntimeUrl(\n field: \"authBaseUrl\" | \"convexUrl\" | \"siteBaseUrl\",\n raw: string,\n): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n","import type { DurationMs, EpochMs } from \"@capxul/types\";\nimport { toEpochMs } from \"@capxul/types\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ClockError, ClockPortTag, type ClockPort } from \"../../ports/clock\";\n\nexport class SystemClockAdapter implements ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError, never> = Effect.try({\n try: () => toEpochMs(Date.now()),\n catch: (cause) => new ClockError({ operation: \"now\", cause }),\n });\n\n sleep(duration: DurationMs): Effect.Effect<void, ClockError, never> {\n return Effect.callback<void, ClockError>((resume) => {\n const timeout = setTimeout(() => resume(Effect.void), duration as number);\n return Effect.sync(() => clearTimeout(timeout));\n });\n }\n}\n\nexport function SystemClockLayer(): Layer.Layer<ClockPortTag, ClockError, never> {\n return Layer.succeed(ClockPortTag, new SystemClockAdapter());\n}\n","import { CapxulError, Errors, decodeConvexError } from \"@capxul/config\";\nimport { ConvexClient } from \"convex/browser\";\nimport { getFunctionName, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer, Tracer } from \"effect\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport {\n ConvexCallPortTag,\n convexCallErrorFromCapxul,\n type ConvexCallError,\n type ConvexCallPort,\n type Snapshot,\n type Unsubscribe,\n} from \"../../ports/convex-call\";\nimport { readInvocationObservation } from \"../../internal/invocation-observation\";\nimport { formatTraceparent } from \"../../domain/machine/telemetry.ts\";\nimport type { ObservationAdapter } from \"../../observation\";\n\nexport type ConvexCallAuthFetcher = (args: {\n readonly forceRefreshToken: boolean;\n}) => Promise<string | null>;\n\nexport interface ConvexClientShape {\n setAuth(fetchToken: ConvexCallAuthFetcher): void;\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n onUpdate<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n onValue: (value: TOutput) => void,\n onError: (err: Error) => void,\n ): () => void;\n close(): Promise<void>;\n}\n\nexport type ConvexCallLayerDeps = {\n readonly convexUrl: string;\n readonly tokenProvider?: ConvexCallAuthFetcher;\n readonly client?: ConvexClientShape;\n readonly applicationId?: string;\n readonly observation?: Pick<ObservationAdapter, \"resolveContext\">;\n};\n\n/** Exact floor-first allowlist; every additional handler must migrate its validator first. */\nconst OBSERVED_CONVEX_ACTIONS: ReadonlySet<string> = new Set([\n \"subAccount/actions:transfer\",\n \"smartAccount/actions:claim\",\n \"org/actions:prepareFounderAccount\",\n \"org/actions:prepareBootstrap\",\n \"org/actions:submitBootstrap\",\n \"org/actions:resumeBootstrapSubmission\",\n \"org/actions:confirmBootstrap\",\n]);\nconst OBSERVED_CONVEX_QUERIES: ReadonlySet<string> = new Set([\n \"identity/queries:loadByAuthUserId\",\n \"smartAccount/queries:loadByAuthUserId\",\n \"org/lifecycle:load\",\n]);\nconst OBSERVED_CONVEX_MUTATIONS: ReadonlySet<string> = new Set([\n \"identity/mutations:create\",\n \"identity/mutations:update\",\n \"identity/mutations:completeOnboarding\",\n \"smartAccount/mutations:provision\",\n \"org/lifecycle:startOrResume\",\n \"org/lifecycle:recordFailure\",\n \"org/lifecycle:retry\",\n]);\n\nexport class ConvexCallAdapter implements ConvexCallPort {\n readonly #client: ConvexClientShape;\n readonly #tokenProvider: ConvexCallAuthFetcher | undefined;\n readonly #applicationId: string | undefined;\n readonly #observation: Pick<ObservationAdapter, \"resolveContext\"> | undefined;\n\n constructor(deps: ConvexCallLayerDeps) {\n this.#client = deps.client ?? (new ConvexClient(deps.convexUrl) as ConvexClientShape);\n this.#tokenProvider = deps.tokenProvider;\n this.#applicationId = deps.applicationId;\n this.#observation = deps.observation;\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n refreshAuth(): void {\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.query(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_QUERIES, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.mutation(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_MUTATIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.action(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n #observedArgs<TArgs extends Record<string, unknown>>(\n allowlist: ReadonlySet<string>,\n path: string,\n args: TArgs,\n traceparent: string | undefined,\n ): TArgs {\n if (!allowlist.has(path)) return args;\n\n const carriedContext = sanitizeObservationContext(\n (args as { readonly observationContext?: unknown }).observationContext,\n );\n let hostContext: WireObservationContext | undefined;\n const invocationSnapshot = readInvocationObservation(args);\n if (invocationSnapshot !== undefined) {\n hostContext = invocationSnapshot.context;\n } else {\n const resolveContext = this.#observation?.resolveContext;\n if (resolveContext !== undefined) {\n try {\n hostContext = resolveContext();\n } catch {\n hostContext = undefined;\n }\n }\n }\n if (hostContext === undefined && carriedContext === undefined && traceparent === undefined) {\n return args;\n }\n hostContext = sanitizeObservationContext({\n ...hostContext,\n ...carriedContext,\n ...(this.#applicationId === undefined ? {} : { applicationId: this.#applicationId }),\n ...(traceparent === undefined ? {} : { traceparent }),\n });\n if (hostContext === undefined) return args;\n\n // Never mutate caller-owned args. This cast is localized to the one handler\n // whose backend validator explicitly accepts the reserved context field.\n return { ...args, observationContext: hostContext } as TArgs;\n }\n\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError> {\n return Effect.try({\n try: () => {\n const path = getFunctionName(fn);\n const unsubscribe = this.#client.onUpdate(\n fn,\n args,\n (value) => callback({ status: \"ok\", value }),\n (err) => callback({ status: \"error\", error: mapToCapxulError(path, err) }),\n );\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n unsubscribe();\n };\n },\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n }).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n callback({ status: \"loading\" });\n }),\n ),\n );\n }\n\n async close(): Promise<void> {\n await this.#client.close();\n }\n}\n\nexport function ConvexCallLayer(deps: ConvexCallLayerDeps): Layer.Layer<ConvexCallPortTag> {\n return Layer.effect(\n ConvexCallPortTag,\n Effect.acquireRelease(\n Effect.sync(() => new ConvexCallAdapter(deps)),\n (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie),\n ),\n );\n}\n\nfunction mapToCapxulError(operation: string, err: unknown): CapxulError {\n const decoded = decodeConvexError(err);\n if (decoded !== null) return decoded;\n if (err instanceof CapxulError) return err;\n if (err instanceof Error) {\n if (isTransportError(err)) return Errors.networkError(operation, err);\n return Errors.providerError(\"convex\", operation, err);\n }\n return Errors.providerError(\"convex\", operation, new Error(String(err)));\n}\n\nfunction mapToConvexCallError(operation: string, err: unknown): ConvexCallError {\n return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err));\n}\n\nfunction isTransportError(err: Error): boolean {\n const message = err.message.toLowerCase();\n return (\n message.includes(\"failed to fetch\") ||\n message.includes(\"network\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"enotfound\") ||\n message.includes(\"etimedout\") ||\n message.includes(\"socket\")\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, Profile } from \"@capxul/types\";\nimport {\n toAddress,\n toAuthUserId,\n toCountryCode,\n toEmail,\n toEpochMs,\n toKycTier,\n} from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CompleteOnboardingIdentityInput,\n CreateIdentityInput,\n IdentityError,\n IdentityPort,\n UpdateIdentityInput,\n} from \"../../ports/identity\";\nimport { identityErrorFromCapxul, IdentityPortTag } from \"../../ports/identity\";\n\ntype RawProfile = {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly country: string | null;\n readonly onboarded?: boolean;\n readonly withdrawalAddress?: string | null;\n readonly username?: string | null;\n readonly imageUrl?: string | null;\n readonly kycTier: 0 | 1 | 2 | 3;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nconst identityLoadByAuthUserIdQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: AuthUserId },\n RawProfile | null\n> = makeFunctionReference<\"query\", { readonly authUserId: AuthUserId }, RawProfile | null>(\n CAPXUL_FUNCTIONS[\"identity/queries\"].loadByAuthUserId,\n);\n\nconst identityCreateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CreateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CreateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].create,\n);\n\nconst identityUpdateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n UpdateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", UpdateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].update,\n);\n\nconst identityCompleteOnboardingMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CompleteOnboardingIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CompleteOnboardingIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].completeOnboarding,\n);\n\nexport class ConvexIdentityAdapter implements IdentityPort {\n readonly #convex: ConvexCallPort;\n\n constructor(deps: { readonly convex: ConvexCallPort }) {\n this.#convex = deps.convex;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError> {\n return this.#convex.query(identityLoadByAuthUserIdQuery, { authUserId }).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => (row === null ? null : brandProfile(row)),\n catch: (cause) => identityErrorFromUnknown(\"loadByAuthUserId\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCreateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"create\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"create\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"create\", cause))),\n );\n }\n\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityUpdateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"update\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"update\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"update\", cause))),\n );\n }\n\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"completeOnboarding\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"completeOnboarding\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"completeOnboarding\", cause)),\n ),\n );\n }\n}\n\nexport function ConvexIdentityLayer(): Layer.Layer<\n IdentityPortTag,\n IdentityError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n IdentityPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })),\n );\n}\n\nfunction brandProfile(raw: RawProfile): Profile {\n return {\n authUserId: toAuthUserId(raw.authUserId),\n email: toEmail(raw.email),\n displayName: raw.displayName,\n country: raw.country === null ? null : toCountryCode(raw.country),\n onboarded: raw.onboarded ?? false,\n withdrawalAddress:\n raw.withdrawalAddress === null || raw.withdrawalAddress === undefined\n ? null\n : toAddress(raw.withdrawalAddress),\n // #1062 / #1061: plain strings on the wire and the surface — no brand.\n username: raw.username ?? null,\n imageUrl: raw.imageUrl ?? null,\n kycTier: toKycTier(raw.kycTier),\n createdAt: toEpochMs(raw.createdAt),\n updatedAt: toEpochMs(raw.updatedAt),\n };\n}\n\nfunction identityErrorFromUnknown(operation: string, cause: unknown): IdentityError {\n if (cause instanceof CapxulError) return identityErrorFromCapxul(operation, cause);\n return identityErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Account } from \"@capxul/types\";\nimport { toAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n AccountReadError,\n AccountReadPort,\n FundFromFaucetInput,\n FundFromFaucetResult,\n ReadAccountBalanceInput,\n} from \"../../ports/account-read\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { accountReadErrorFromCapxul, AccountReadPortTag } from \"../../ports/account-read\";\nimport { fromWei } from \"../../domain/money/from-wei\";\n\nexport type WireAccountBalance = {\n readonly accountId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\nexport type WireFaucetMintResult = {\n readonly txHash: string;\n};\n\nexport type ConvexAccountFunctions = {\n readonly readBalance: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number },\n WireAccountBalance\n >;\n readonly faucetMint: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number; readonly rawAmount: string },\n WireFaucetMintResult\n >;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexAccountFunctions = {\n readBalance: makeFunctionReference<\"action\", { chainId: number }, WireAccountBalance>(\n CAPXUL_FUNCTIONS[\"account/actions\"].readBalance,\n ),\n faucetMint: makeFunctionReference<\n \"action\",\n { chainId: number; rawAmount: string },\n WireFaucetMintResult\n >(CAPXUL_FUNCTIONS[\"account/actions\"].faucetMint),\n};\n\nexport class ConvexAccountAdapter implements AccountReadPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError> {\n return this.#convex.action(this.#fns.readBalance, { chainId: wireChainId(input.chainId) }).pipe(\n Effect.mapError((error) =>\n accountReadErrorFromCapxul(\"readBalance\", error.publicError, error),\n ),\n Effect.flatMap((wire) => brandAccountEffect(\"readBalance\", wire)),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(\"readBalance\", cause))),\n );\n }\n\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError> {\n const operation = \"fundFromFaucet\";\n // `toWei`/`parseUnits` throws on a malformed money string; suspend so the\n // throw surfaces as a defect below and maps to an AccountReadError, never an\n // escaped throw out of `fundFromFaucet` (mirrors ConvexSubAccountAdapter.transfer).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(this.#fns.faucetMint, {\n chainId: wireChainId(input.chainId),\n rawAmount,\n });\n }).pipe(\n Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => ({ txHash: wire.txHash })),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexAccountLayer(): Layer.Layer<\n AccountReadPortTag,\n AccountReadError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n AccountReadPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })),\n );\n}\n\nfunction brandAccountEffect(\n operation: string,\n wire: WireAccountBalance,\n): Effect.Effect<Account, AccountReadError> {\n return Effect.try({\n try: () => brandAccount(wire),\n catch: (cause) => accountReadErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandAccount(wire: WireAccountBalance): Account {\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(\n wire.rawAvailableBalance ?? wire.rawBalance,\n wire.decimals,\n wire.currency,\n );\n return {\n id: toAccountId(wire.accountId),\n balance,\n available,\n };\n}\n\nfunction accountReadErrorFromUnknown(operation: string, cause: unknown): AccountReadError {\n if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);\n return accountReadErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount } from \"@capxul/types\";\nimport { toAccountId, toEpochMs, toSubAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateSubAccountInput,\n RenameSubAccountInput,\n SubAccountError,\n SubAccountIdInput,\n SubAccountPort,\n TransferInput,\n TransferResult,\n} from \"../../ports/sub-account\";\nimport { subAccountErrorFromCapxul, SubAccountPortTag } from \"../../ports/sub-account\";\n\nexport type WireSubAccount = {\n readonly subAccountId: string;\n readonly accountId: string;\n readonly name: string;\n readonly rawBalance: string;\n readonly decimals: number;\n readonly currency: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\n/**\n * Wire result of `subAccount/actions:transfer`. `availableRaw` is the\n * recomputed `balanceOf − Σ` on-chain integer; the SDK lifts it to `Money`\n * via `fromWei`. `from`/`to` are the updated sub-account rows, or `null` when\n * that endpoint is the Account's MAIN balance (never a stored row).\n */\nexport type WireTransferResult = {\n readonly availableRaw: string;\n readonly decimals: number;\n readonly currency: string;\n readonly from: WireSubAccount | null;\n readonly to: WireSubAccount | null;\n};\n\nexport type WireTransferArgs = {\n readonly chainId: number;\n readonly from: string;\n readonly to: string;\n readonly rawAmount: string;\n};\n\nexport type ConvexSubAccountFunctions = {\n readonly create: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly accountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly get: FunctionReference<\n \"query\",\n \"public\",\n { readonly subAccountId: string },\n WireSubAccount | null\n >;\n readonly list: FunctionReference<\n \"query\",\n \"public\",\n { readonly accountId: string },\n readonly WireSubAccount[]\n >;\n readonly rename: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly remove: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string },\n { readonly ok: true }\n >;\n readonly transfer: FunctionReference<\"action\", \"public\", WireTransferArgs, WireTransferResult>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSubAccountFunctions = {\n create: makeFunctionReference<\"mutation\", { accountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].create,\n ),\n get: makeFunctionReference<\"query\", { subAccountId: string }, WireSubAccount | null>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].get,\n ),\n list: makeFunctionReference<\"query\", { accountId: string }, readonly WireSubAccount[]>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].list,\n ),\n rename: makeFunctionReference<\"mutation\", { subAccountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].rename,\n ),\n remove: makeFunctionReference<\"mutation\", { subAccountId: string }, { ok: true }>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].remove,\n ),\n transfer: makeFunctionReference<\"action\", WireTransferArgs, WireTransferResult>(\n CAPXUL_FUNCTIONS[\"subAccount/actions\"].transfer,\n ),\n};\n\nexport class ConvexSubAccountAdapter implements SubAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSubAccountFunctions;\n readonly #chainId: number;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly chainId: number;\n readonly functions?: ConvexSubAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#chainId = deps.chainId;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"create\", this.#fns.create, {\n accountId: input.accountId as string,\n name: input.name,\n });\n }\n\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError> {\n return this.#runQuery(\n \"get\",\n this.#fns.get,\n { subAccountId: input.subAccountId as string },\n (wire) => (wire === null ? null : brandSubAccount(wire)),\n );\n }\n\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError> {\n return this.#runQuery(\n \"list\",\n this.#fns.list,\n { accountId: input.accountId as string },\n (wires) => wires.map((wire) => brandSubAccount(wire)),\n );\n }\n\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"rename\", this.#fns.rename, {\n subAccountId: input.subAccountId as string,\n name: input.name,\n });\n }\n\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError> {\n const operation = \"delete\";\n return this.#convex\n .mutation(this.#fns.remove, { subAccountId: input.subAccountId as string })\n .pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.asVoid,\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError> {\n const operation = \"transfer\";\n // `toWei`/`parseUnits` throws on a malformed money string; that surfaces as\n // a defect below and is mapped to a SubAccountError (INVALID_INPUT-ish).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(\n this.#fns.transfer,\n copyInvocationObservation(input, {\n chainId: this.#chainId,\n from: input.from as string,\n to: input.to as string,\n rawAmount,\n }),\n );\n }).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n // Branding (`fromWei` / `brandSubAccount`) runs INSIDE the guarded pipe so\n // a throw surfaces as a SubAccountError defect, never an escaped defect.\n Effect.map((wire) => brandTransferResult(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runMutation(\n operation: string,\n ref: FunctionReference<\"mutation\", \"public\", Record<string, string>, WireSubAccount>,\n args: Record<string, string>,\n ): Effect.Effect<SubAccount, SubAccountError> {\n return this.#convex.mutation(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => brandSubAccount(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runQuery<TWire, TOut>(\n operation: string,\n ref: FunctionReference<\"query\", \"public\", Record<string, string>, TWire>,\n args: Record<string, string>,\n map: (wire: TWire) => TOut,\n ): Effect.Effect<TOut, SubAccountError> {\n // Branding (`map`) runs INSIDE the guarded pipe so a throw from\n // toAccountId/toSubAccountId/fromWei surfaces as a SubAccountError defect,\n // never an unhandled defect that escapes the typed channel.\n return this.#convex.query(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map(map),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexSubAccountLayer(\n chainId: number,\n): Layer.Layer<SubAccountPortTag, SubAccountError, ConvexCallPortTag> {\n return Layer.effect(\n SubAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSubAccountAdapter({ convex, chainId })),\n );\n}\n\nfunction brandTransferResult(wire: WireTransferResult): TransferResult {\n return {\n available: fromWei(wire.availableRaw, wire.decimals, wire.currency),\n from: wire.from === null ? null : brandSubAccount(wire.from),\n to: wire.to === null ? null : brandSubAccount(wire.to),\n };\n}\n\nfunction brandSubAccount(wire: WireSubAccount): SubAccount {\n return {\n id: toSubAccountId(wire.subAccountId),\n accountId: toAccountId(wire.accountId),\n name: wire.name,\n balance: fromWei(wire.rawBalance, wire.decimals, wire.currency),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction subAccountErrorFromUnknown(operation: string, cause: unknown): SubAccountError {\n if (cause instanceof CapxulError) return subAccountErrorFromCapxul(operation, cause);\n return subAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Address, AuthUserId, SmartAccount } from \"@capxul/types\";\nimport { toAddress, toAuthUserId, toChainId, toEpochMs } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n ClaimInput,\n ConfirmDeploymentInput,\n ProvisionInput,\n SmartAccountError,\n SmartAccountPort,\n} from \"../../ports/smart-account\";\nimport { smartAccountErrorFromCapxul, SmartAccountPortTag } from \"../../ports/smart-account\";\n\nexport type WireSmartAccount = {\n readonly authUserId: string;\n readonly signerAddress: string | null;\n readonly smartAccountAddress: string;\n readonly chainId: number;\n readonly deployedAt: number | null;\n readonly claimedAt: number | null;\n readonly createdAt: number;\n};\n\nexport type WireConfirmDeploymentArgs = {\n readonly chainId: number;\n readonly safeAddress: string;\n readonly telemetryRunId?: string;\n readonly evidence: {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly safeAddress: string;\n readonly userOpHash?: string;\n readonly txHash?: string;\n readonly blockNumber?: number;\n };\n};\n\nexport type WireClaimArgs = {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly telemetryRunId?: string;\n readonly observationContext?: WireObservationContext;\n};\n\nexport type ConvexSmartAccountFunctions = {\n readonly loadByAuthUserId: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: string },\n WireSmartAccount | null\n >;\n readonly loadBySmartAccountAddress: FunctionReference<\n \"query\",\n \"public\",\n { readonly address: string },\n WireSmartAccount | null\n >;\n readonly provision: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly chainId: number;\n },\n WireSmartAccount\n >;\n // `confirmDeployment` is an ACTION, not a mutation, because the\n // backend handler must perform outbound `fetch` calls to Alchemy\n // (eth_getCode / eth_getUserOperationReceipt / eth_getLogs /\n // eth_getBlockByNumber) — Convex mutations are transactional and\n // cannot do fetch. See `packages/backend/convex/smartAccount/actions.ts`.\n readonly confirmDeployment: FunctionReference<\n \"action\",\n \"public\",\n WireConfirmDeploymentArgs,\n WireSmartAccount\n >;\n // `claim` is an ACTION: the backend builds, bootstrap-signs, and submits\n // the claim userOp (deploy + swapOwner) via outbound bundler RPC (PRD #462).\n readonly claim: FunctionReference<\"action\", \"public\", WireClaimArgs, WireSmartAccount>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSmartAccountFunctions = {\n loadByAuthUserId: makeFunctionReference<\"query\", { authUserId: string }, WireSmartAccount | null>(\n CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadByAuthUserId,\n ),\n loadBySmartAccountAddress: makeFunctionReference<\n \"query\",\n { address: string },\n WireSmartAccount | null\n >(CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadBySmartAccountAddress),\n provision: makeFunctionReference<\"mutation\", { chainId: number }, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/mutations\"].provision,\n ),\n confirmDeployment: makeFunctionReference<\"action\", WireConfirmDeploymentArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].confirmDeployment,\n ),\n claim: makeFunctionReference<\"action\", WireClaimArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].claim,\n ),\n};\n\nexport class ConvexSmartAccountAdapter implements SmartAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSmartAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexSmartAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadByAuthUserId\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadBySmartAccountAddress\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadBySmartAccountAddress\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadBySmartAccountAddress\", cause)),\n ),\n );\n }\n\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .mutation(this.#fns.provision, {\n chainId: wireChainId(input.chainId),\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"provision\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"provision\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"provision\", cause)),\n ),\n );\n }\n\n confirmDeployment(input: ConfirmDeploymentInput): Effect.Effect<SmartAccount, SmartAccountError> {\n const evidence: WireConfirmDeploymentArgs[\"evidence\"] = {\n chainId: wireChainId(input.evidence.chainId),\n signerAddress: input.evidence.signerAddress,\n safeAddress: input.evidence.safeAddress,\n ...(input.evidence.userOpHash === undefined ? {} : { userOpHash: input.evidence.userOpHash }),\n ...(input.evidence.txHash === undefined ? {} : { txHash: input.evidence.txHash }),\n ...(input.evidence.blockNumber === undefined\n ? {}\n : { blockNumber: input.evidence.blockNumber }),\n };\n return this.#convex\n .action(this.#fns.confirmDeployment, {\n chainId: wireChainId(input.chainId),\n safeAddress: input.safeAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n evidence,\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"confirmDeployment\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"confirmDeployment\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"confirmDeployment\", cause)),\n ),\n );\n }\n\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .action(\n this.#fns.claim,\n copyInvocationObservation(input, {\n chainId: wireChainId(input.chainId),\n signerAddress: input.signerAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n }),\n )\n .pipe(\n Effect.mapError((error) => smartAccountErrorFromCapxul(\"claim\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"claim\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown(\"claim\", cause))),\n );\n }\n}\n\nexport function ConvexSmartAccountLayer(): Layer.Layer<\n SmartAccountPortTag,\n SmartAccountError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n SmartAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })),\n );\n}\n\nfunction brandSmartAccountEffect(\n operation: string,\n wire: WireSmartAccount | null,\n): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return Effect.try({\n try: () => (wire === null ? null : brandNonNullSmartAccount(wire)),\n catch: (cause) => smartAccountErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandNonNullSmartAccount(wire: WireSmartAccount): SmartAccount {\n return {\n authUserId: toAuthUserId(wire.authUserId),\n signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),\n smartAccountAddress: toAddress(wire.smartAccountAddress),\n chainId: toChainId(wire.chainId),\n deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),\n claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction brandProvisionedSmartAccount(\n requestedAuthUserId: AuthUserId,\n wire: WireSmartAccount,\n): SmartAccount {\n if (wire.authUserId !== String(requestedAuthUserId)) {\n throw Errors.notAuthenticated();\n }\n return brandNonNullSmartAccount(wire);\n}\n\nfunction smartAccountErrorFromUnknown(operation: string, cause: unknown): SmartAccountError {\n if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);\n return smartAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","// Organization domain port (owned by `packages/sdk/docs/architecture.md`).\n// The SEAM between the Effect org programs and the outside\n// world: the live adapter (added by the CLI/live-proof slice) performs the\n// SDK-orchestrated Org Safe deploy (D10 — permissionless + zodiac-roles-sdk,\n// no custom Solidity) and the RPC `balanceOf` treasury read (D3); the hermetic\n// L1 path runs with NO port and the org programs fall back to a deterministic\n// `$0` treasury (a fresh Org has no on-chain funds).\n//\n// The port returns plain records branded at this boundary (brand-at-source).\n// `OrgError` carries the public `CapxulError` so the program can surface a\n// typed failure channel exactly like `AccountReadPort`.\n\nimport { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/errors\";\nimport type { Account, OrgId } from \"@capxul/types\";\n\nimport type {\n AssignRoleInput,\n CreateOrgInput,\n InviteMemberInput,\n MemberView,\n OrgView,\n RemoveMemberInput,\n RoleView,\n OrgSpendViaPaymentsInput,\n OrgPayrollRun,\n} from \"../surface/org\";\nimport type { Address, Money, SubAccountId } from \"@capxul/types\";\n\n/**\n * The minimal `{from, to, amount}` spend shape the authority read keys off\n * (D3 #565). The legacy address-keyed `OrgSpendInput`/`org.spend` lane was\n * hard-removed when `orgSpends` folded into the one `payments` ledger; the\n * leak-safe ref-based lane (`spendViaPayments`/`batchPayroll`) constructs this\n * internally and enforces the real validated recipient on the gate.\n */\nexport type OrgSpendShape = {\n readonly from: SubAccountId;\n readonly to: Address;\n readonly amount: Money;\n};\nimport type { Payment } from \"../surface/money\";\nimport type { SpendGateRecipients, SpendGateSubAccountScope } from \"../domain/org/spend-gate\";\n\nexport type CreateOrgPortInput = {\n readonly input: CreateOrgInput;\n};\n\nexport type ReadOrgTreasuryInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgsInput = Record<never, never>;\n\nexport type ListOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgMembersInput = {\n readonly orgId: OrgId;\n};\n\nexport type InviteOrgMemberInput = {\n readonly orgId: OrgId;\n readonly input: InviteMemberInput;\n};\n\nexport type ResendOrgInviteTokenInput = {\n readonly orgId: OrgId;\n readonly email: string;\n};\n\nexport type DetectPendingOrgInvitationsInput = Record<never, never>;\n\nexport type DetectPendingOrgInvitationsResult = {\n readonly matched: readonly OrgId[];\n};\n\nexport type DeployOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type OrgRolesDeploymentResult = {\n readonly orgId: OrgId;\n readonly roles: readonly RoleView[];\n};\n\nexport type GrantOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: AssignRoleInput;\n};\n\nexport type RevokeOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: RemoveMemberInput;\n};\n\nexport type OrgSpendAuthority = {\n readonly activeMember: boolean;\n readonly subAccountBalanceRaw: string;\n readonly recipients: SpendGateRecipients;\n readonly subAccounts: SpendGateSubAccountScope;\n readonly perTxCapRaw?: string | null;\n readonly perDayCapRaw?: string | null;\n readonly spentTodayRaw?: string | null;\n readonly role?: string;\n};\n\nexport type ReadOrgSpendAuthorityInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendShape;\n readonly amountRaw: string;\n};\n\nexport class OrgError extends Data.TaggedError(\"OrgError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function orgErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): OrgError {\n return new OrgError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n/**\n * Live org seam. `createOrg` runs the SDK-orchestrated deploy (D10) and returns\n * the created `OrgView` (its treasury is the real M2 `Account` over the Org\n * Safe — $0 at creation, D3). `readTreasury` pulls the org's Account via RPC\n * `balanceOf` (D3). `listOrgs` lists the orgs the authenticated user belongs to.\n */\nexport interface OrgPort {\n createOrg(input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError, never>;\n readTreasury(input: ReadOrgTreasuryInput): Effect.Effect<Account, OrgError, never>;\n listOrgs(input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError, never>;\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError, never>;\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError, never>;\n pendingMembers?(\n input: ListOrgMembersInput,\n ): Effect.Effect<readonly MemberView[], OrgError, never>;\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError, never>;\n resendInviteToken?(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError, never>;\n detectAndAcceptPendingInvitations(\n input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError, never>;\n}\n\nexport class OrgPortTag extends Context.Service<OrgPortTag, OrgPort>()(\n \"@capxul/sdk/ports/OrgPort\",\n) {}\n\nexport interface OrgRolesDeploymentPort {\n deployRoles(input: DeployOrgRolesInput): Effect.Effect<OrgRolesDeploymentResult, OrgError, never>;\n grantRole(input: GrantOrgRoleInput): Effect.Effect<MemberView, OrgError, never>;\n revokeRole(input: RevokeOrgRoleInput): Effect.Effect<void, OrgError, never>;\n}\n\nexport class OrgRolesDeploymentPortTag extends Context.Service<\n OrgRolesDeploymentPortTag,\n OrgRolesDeploymentPort\n>()(\"@capxul/sdk/ports/OrgRolesDeploymentPort\") {}\n\nexport type SubmitOrgSpendViaPaymentsInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendViaPaymentsInput;\n readonly amountRaw: string;\n readonly authority: OrgSpendAuthority;\n};\n\nexport type SubmitOrgBatchPayrollInput = {\n readonly orgId: OrgId;\n readonly from: OrgSpendViaPaymentsInput[\"from\"];\n readonly runs: readonly { readonly run: OrgPayrollRun; readonly amountRaw: string }[];\n readonly authorities: readonly OrgSpendAuthority[];\n};\n\nexport interface OrgSpendPort {\n readSpendAuthority(\n input: ReadOrgSpendAuthorityInput,\n ): Effect.Effect<OrgSpendAuthority, OrgError, never>;\n /**\n * Leak-safe org spend (G4 · #547; D3 #565 — the one ledger of record): execute\n * the spend through the payments engine (Roles modifier → CapxulPayments),\n * write a real `payments` row (`source:\"org\"`) and read it back as a `Payment`\n * — the wire carries no `txHash` / Safe / userOp internals. Optional so a\n * hermetic adapter without a payments-submit lane still compiles; absent ⇒ the\n * program falls back to a deterministic hermetic `Payment`.\n */\n submitSpendViaPayments?(\n input: SubmitOrgSpendViaPaymentsInput,\n ): Effect.Effect<Payment, OrgError, never>;\n /** Leak-safe org payroll batch (G4 · #547): one MultiSend, one Payment per run. */\n submitBatchPayroll?(\n input: SubmitOrgBatchPayrollInput,\n ): Effect.Effect<readonly Payment[], OrgError, never>;\n}\n\nexport class OrgSpendPortTag extends Context.Service<OrgSpendPortTag, OrgSpendPort>()(\n \"@capxul/sdk/ports/OrgSpendPort\",\n) {}\n","/**\n * Pure brand-at-read-edge parser for the Org domain wire shape (canon D9/D10a;\n * `.claude/rules/typescript-style.md` \"Brand at DB read boundaries\" +\n * `.claude/rules/wire-fixture-discipline.md`). Maps the raw Convex `WireOrg`\n * row into the branded `OrgView`. No I/O, no viem — so the hermetic L2 fixture\n * test can load `__fixtures__/createOrg-actual.json` verbatim and assert this\n * parser narrows it.\n */\nimport type { Account, Address, Money } from \"@capxul/types\";\nimport {\n toAccountId,\n toAddress,\n toCurrencyCode,\n toEmail,\n toOrgId,\n toRoleKey,\n toSubAccountId,\n} from \"@capxul/types\";\n\nimport type { MemberView, OrgView, RoleDefinition, RoleView } from \"../../surface/org\";\n\n/** Raw Org row as returned by the backend `org/queries` + `org/mutations`. */\nexport type WireOrg = {\n readonly orgId: string;\n readonly name: string;\n readonly slug: string;\n readonly safeAddress: string;\n readonly chainId: number;\n readonly ownerPersonalSafeAddress: string;\n readonly founderEmail: string;\n readonly status?: \"safe_placeholder\" | \"safe_deployed\" | \"active\";\n readonly template?: string;\n readonly metadata: string | null;\n readonly country: string | null;\n // #1064 bio/size + #1061 logoUrl. Optional so pre-rollout recorded fixtures\n // stay verbatim-loadable; the parser maps absence to null.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly logoUrl?: string | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nexport type WireOrgRole = {\n readonly orgId: string;\n readonly roleKey: string;\n readonly label: string;\n readonly definitionJson: string;\n readonly permissions: readonly string[];\n readonly allowanceJson: string | null;\n readonly status: \"active\" | \"revoked\";\n readonly createdAt: number;\n readonly revokedAt: number | null;\n};\n\nexport type WireOrgMember = {\n readonly orgId: string;\n readonly email: string;\n readonly name: string | null;\n readonly authUserId: string | null;\n readonly personalSafeAddress: string | null;\n readonly role: string;\n readonly roleKey: string | null;\n readonly status: \"pending\" | \"pending_safe\" | \"pending_grant\" | \"active\" | \"revoked\" | \"expired\";\n readonly grantTxHash: string | null;\n readonly revokeTxHash: string | null;\n readonly invitedAt: number;\n readonly acceptedAt: number | null;\n readonly grantedAt: number | null;\n readonly revokedAt: number | null;\n readonly expiresAt: number;\n readonly updatedAt: number;\n};\n\ntype RawRoleDefinition = {\n readonly label?: unknown;\n readonly spend?: {\n readonly perTx?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly perDay?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly toRecipients?: unknown;\n };\n readonly subAccounts?: { readonly scope?: unknown };\n readonly canManageMembers?: unknown;\n readonly canManageRoles?: unknown;\n};\n\n/**\n * Map a `WireOrg` + its (separately read) treasury `Account` into the branded\n * `OrgView`. The viewer role is projected by the authenticated backend read;\n * it must never be inferred from Organization ownership. Brands at the read\n * edge: `orgId`, `safeAddress`.\n */\nexport function brandOrgView(wire: WireOrg, treasury: Account, viewerRole: string): OrgView {\n return {\n id: toOrgId(wire.orgId),\n name: wire.name,\n handle: wire.slug,\n safeAddress: toAddress(wire.safeAddress.toLowerCase()),\n role: viewerRole,\n treasury,\n bio: wire.bio ?? null,\n size: wire.size ?? null,\n logoUrl: wire.logoUrl ?? null,\n };\n}\n\n/**\n * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer\n * (the D3 RPC read). `available === balance` for a treasury with no envelope\n * partition yet (a fresh Org reads back $0).\n */\nexport function brandOrgTreasury(input: {\n readonly orgId: string;\n readonly money: Money;\n}): Account {\n return {\n id: toAccountId(`account_${orgIdBody(input.orgId)}`),\n balance: input.money,\n available: input.money,\n };\n}\n\nexport function brandOrgRole(wire: WireOrgRole): RoleView {\n return {\n orgId: toOrgId(wire.orgId),\n label: wire.label,\n roleKey: toRoleKey(wire.roleKey),\n definition: parseRoleDefinition(wire.definitionJson),\n };\n}\n\nexport function brandOrgMember(wire: WireOrgMember): MemberView {\n return {\n orgId: toOrgId(wire.orgId),\n email: toEmail(wire.email),\n name: wire.name,\n personalSafeAddress:\n wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),\n role: wire.role,\n roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),\n status: wire.status,\n grantTxHash: wire.grantTxHash,\n revokeTxHash: wire.revokeTxHash,\n };\n}\n\nfunction parseRoleDefinition(json: string): RoleDefinition {\n let raw: RawRoleDefinition;\n try {\n const parsed = JSON.parse(json) as unknown;\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"expected object\");\n }\n raw = parsed as RawRoleDefinition;\n } catch (err) {\n throw new Error(\n `Invalid role definition: malformed JSON - ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n if (typeof raw.label !== \"string\" || raw.label.trim().length === 0) {\n throw new Error(\"Invalid role definition: missing label\");\n }\n return {\n label: raw.label,\n ...(raw.spend === undefined\n ? {}\n : {\n spend: {\n ...(raw.spend.perTx === undefined\n ? {}\n : { perTx: parseRoleMoney(raw.spend.perTx, \"perTx\") }),\n ...(raw.spend.perDay === undefined\n ? {}\n : { perDay: parseRoleMoney(raw.spend.perDay, \"perDay\") }),\n ...(raw.spend.toRecipients === undefined\n ? {}\n : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }),\n },\n }),\n ...(raw.subAccounts === undefined\n ? {}\n : { subAccounts: parseRoleSubAccounts(raw.subAccounts) }),\n ...(typeof raw.canManageMembers === \"boolean\"\n ? { canManageMembers: raw.canManageMembers }\n : {}),\n ...(typeof raw.canManageRoles === \"boolean\" ? { canManageRoles: raw.canManageRoles } : {}),\n };\n}\n\nfunction parseRoleMoney(\n raw: { readonly currency: unknown; readonly value: unknown; readonly decimals: unknown },\n field: string,\n) {\n if (\n typeof raw.currency !== \"string\" ||\n typeof raw.value !== \"string\" ||\n !/^\\d+$/.test(raw.value) ||\n raw.decimals !== 6\n ) {\n throw new Error(`Invalid role money: ${field}`);\n }\n return {\n currency: toCurrencyCode(raw.currency),\n value: raw.value,\n decimals: raw.decimals,\n };\n}\n\nfunction parseRoleRecipients(raw: unknown): \"anyone\" | readonly Address[] {\n if (raw === \"anyone\") return \"anyone\";\n if (!Array.isArray(raw)) {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return raw.map((recipient) => {\n if (typeof recipient !== \"string\") {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return toAddress(recipient);\n });\n}\n\nfunction parseRoleSubAccounts(raw: { readonly scope?: unknown }) {\n if (raw.scope === \"all\") return { scope: \"all\" as const };\n if (!Array.isArray(raw.scope)) {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return {\n scope: raw.scope.map((subAccountId) => {\n if (typeof subAccountId !== \"string\") {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return toSubAccountId(subAccountId);\n }),\n };\n}\n\n/** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */\nfunction orgIdBody(orgId: string): string {\n const underscore = orgId.indexOf(\"_\");\n const tail = underscore < 0 ? orgId : orgId.slice(underscore + 1);\n const cleaned = tail.replace(/[^0-9A-Za-z]/g, \"\");\n return cleaned.length > 0 ? cleaned : \"0\";\n}\n","import { CapxulError, Errors } from \"@capxul/errors\";\nimport { toOrgId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect } from \"effect\";\n\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateOrgPortInput,\n DetectPendingOrgInvitationsInput,\n DetectPendingOrgInvitationsResult,\n InviteOrgMemberInput,\n ListOrgMembersInput,\n ListOrgRolesInput,\n ListOrgsInput,\n OrgError,\n OrgPort,\n ReadOrgTreasuryInput,\n ResendOrgInviteTokenInput,\n} from \"../../ports/org\";\nimport { orgErrorFromCapxul } from \"../../ports/org\";\nimport type { MemberView, OrgView, RoleView } from \"../../surface/org\";\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport {\n brandOrgMember,\n brandOrgRole,\n brandOrgTreasury,\n brandOrgView,\n type WireOrg,\n type WireOrgMember,\n type WireOrgRole,\n} from \"./parse\";\n\ntype WireTreasury = {\n readonly orgId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\ntype WireOrgListItem = WireOrg & { readonly viewerRole: string };\n\ntype DetectInvitationsWire = {\n readonly matched: readonly string[];\n readonly members: readonly WireOrgMember[];\n};\n\ntype OrganizationFunctions = {\n readonly listAll: FunctionReference<\n \"query\",\n \"public\",\n Record<never, never>,\n readonly WireOrgListItem[]\n >;\n readonly listRoles: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgRole[]\n >;\n readonly listMembers: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgMember[]\n >;\n readonly readTreasury: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string },\n WireTreasury\n >;\n readonly inviteMember: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly email: string; readonly role: string },\n WireOrgMember\n >;\n readonly resendInvite: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly email: string },\n WireOrgMember\n >;\n readonly detectInvitations: FunctionReference<\n \"action\",\n \"public\",\n Record<never, never>,\n DetectInvitationsWire\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationFunctions = {\n listAll: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listAll),\n listRoles: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listRolesByOrgId),\n listMembers: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listMembersByOrgId),\n readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].readTreasury),\n inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].inviteMember),\n resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/mutations\"].resendInviteToken),\n detectInvitations: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].detectAndAcceptPendingInvitations,\n ),\n};\n\n/**\n * Standard production Organization read adapter. It intentionally has no\n * deployer/RPC/test configuration: authenticated Convex actions own live chain\n * reads, while the lifecycle adapter owns the single sponsored bootstrap.\n */\nexport class ConvexOrganizationAdapter implements OrgPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: OrganizationFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly functions?: OrganizationFunctions;\n }) {\n this.#convex = input.convex;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n createOrg(_input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError> {\n return Effect.fail(\n orgErrorFromCapxul(\n \"createOrg\",\n Errors.notImplemented(\"organizationSetup\", \"use onboarding.completeOrganization\"),\n ),\n );\n }\n\n listOrgs(_input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError> {\n return this.#convex.query(this.#fns.listAll, {}).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listOrgs\", error.publicError, error)),\n Effect.flatMap((wires) =>\n Effect.forEach(wires, (wire) =>\n this.#readTreasuryWire(wire.orgId).pipe(\n Effect.map((treasury) => {\n const viewerRole = wire.viewerRole.trim();\n if (viewerRole.length === 0) {\n throw Errors.wrongState({\n method: \"listOrgs\",\n currentState: \"viewerRoleMissing\",\n validStates: [\"activeViewerRole\"],\n });\n }\n return brandOrgView(wire, treasury, viewerRole);\n }),\n ),\n ),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listOrgs\", cause))),\n );\n }\n\n readTreasury(input: ReadOrgTreasuryInput) {\n return this.#readTreasuryWire(String(input.orgId)).pipe(\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"readTreasury\", cause))),\n );\n }\n\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError> {\n return this.#convex.query(this.#fns.listRoles, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listRoles\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listRoles\", \"activeRoleMissing\"))\n : Effect.succeed(rows.map(brandOrgRole)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listRoles\", cause))),\n );\n }\n\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.#convex.query(this.#fns.listMembers, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listMembers\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listMembers\", \"activeMemberMissing\"))\n : Effect.succeed(rows.map(brandOrgMember)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listMembers\", cause))),\n );\n }\n\n pendingMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.listMembers(input).pipe(\n Effect.map((members) =>\n members.filter(\n (member) =>\n member.status === \"pending\" ||\n member.status === \"pending_safe\" ||\n member.status === \"pending_grant\",\n ),\n ),\n );\n }\n\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .action(this.#fns.inviteMember, {\n orgId: input.orgId,\n email: input.input.email,\n role: input.input.role,\n })\n .pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"inviteMember\", error.publicError, error)),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"inviteMember\", cause))),\n );\n }\n\n resendInviteToken(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .mutation(this.#fns.resendInvite, { orgId: input.orgId, email: input.email })\n .pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"resendInviteToken\", error.publicError, error),\n ),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"resendInviteToken\", cause))),\n );\n }\n\n detectAndAcceptPendingInvitations(\n _input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError> {\n return this.#convex.action(this.#fns.detectInvitations, {}).pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"detectAndAcceptPendingInvitations\", error.publicError, error),\n ),\n Effect.map((result) => ({ matched: result.matched.map(toOrgId) })),\n Effect.catchDefect((cause) =>\n Effect.fail(toOrgError(\"detectAndAcceptPendingInvitations\", cause)),\n ),\n );\n }\n\n #readTreasuryWire(orgId: string) {\n return this.#convex.action(this.#fns.readTreasury, { orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"readTreasury\", error.publicError, error)),\n Effect.map((wire) => {\n if (wire.orgId !== orgId) {\n throw Errors.invalidInput(\"orgId\", \"Organization treasury scope does not match\");\n }\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);\n const account = brandOrgTreasury({ orgId: wire.orgId, money: balance });\n return { ...account, available };\n }),\n );\n }\n}\n\nfunction toOrgError(operation: string, cause: unknown): OrgError {\n if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);\n return orgErrorFromCapxul(operation, Errors.providerError(\"convex\", operation, cause), cause);\n}\n\nfunction partialOrgTruth(operation: string, currentState: string): OrgError {\n return orgErrorFromCapxul(\n operation,\n Errors.wrongState({\n method: operation,\n currentState,\n validStates: [\"completeProductionOrganizationTruth\"],\n }),\n );\n}\n","import { CapxulError, Errors, type CapxulErrorCode } from \"@capxul/errors\";\nimport { toOrgId, type OrgId } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Result } from \"effect\";\nimport type { Hex } from \"viem\";\n\nimport type {\n OrganizationSetupOps,\n OrganizationSetupStepInput,\n OrgLifecycle,\n RecordOrganizationSetupFailureInput,\n StartOrResumeOrganizationInput,\n} from \"../../surface/org-lifecycle\";\nimport type { CapxulResult } from \"../../surface/types\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type { CapxulSigner } from \"../../signer\";\n\ntype WireLifecycle =\n | { readonly status: \"loading\"; readonly orgId: string }\n | {\n readonly status: \"settingUp\";\n readonly orgId: string;\n readonly step: OrgLifecycle extends infer _ ? string : never;\n }\n | { readonly status: \"ready\"; readonly orgId: string; readonly canTransact: true }\n | {\n readonly status: \"failed\";\n readonly orgId: string;\n readonly at: string;\n readonly error: { readonly code: CapxulErrorCode; readonly message: string };\n readonly retryable: boolean;\n };\n\nexport type OrganizationBootstrapUserOp = {\n readonly sender: string;\n readonly nonce: string;\n readonly factory?: string;\n readonly factoryData?: string;\n readonly callData: string;\n readonly callGasLimit: string;\n readonly verificationGasLimit: string;\n readonly preVerificationGas: string;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n readonly paymaster: string;\n readonly paymasterVerificationGasLimit?: string;\n readonly paymasterPostOpGasLimit?: string;\n readonly paymasterData: string;\n};\n\ntype PreparedBootstrap = {\n readonly digest: string;\n readonly signerAddress: string;\n readonly founderPersonalAccount: string;\n readonly organizationAccountAddress: string;\n readonly userOp: OrganizationBootstrapUserOp;\n};\n\ntype OrganizationSetupFunctions = {\n readonly startOrResume: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly name: string;\n readonly handle: string;\n readonly country: string;\n // #1064: onboarding-collected description + size bucket, pass-through.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly chainId: number;\n readonly observationContext?: WireObservationContext;\n },\n { readonly orgId: string; readonly lifecycle: WireLifecycle }\n >;\n readonly prepareFounderAccount: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly prepareBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly observationContext?: WireObservationContext;\n },\n PreparedBootstrap\n >;\n readonly submitBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly signature: string;\n readonly userOp: OrganizationBootstrapUserOp;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly resumeBootstrapSubmission: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly confirmBootstrap: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly recordFailure: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly orgId: string;\n readonly errorCode: string;\n readonly errorProvider?: string;\n readonly errorOperation?: string;\n readonly retryable: boolean;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly load: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle | null\n >;\n readonly retry: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationSetupFunctions = {\n startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].startOrResume),\n prepareFounderAccount: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].prepareFounderAccount,\n ),\n prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].prepareBootstrap),\n submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].submitBootstrap),\n resumeBootstrapSubmission: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].resumeBootstrapSubmission,\n ),\n confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].confirmBootstrap),\n recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].recordFailure),\n load: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].load),\n retry: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].retry),\n};\n\n/** Durable Organization setup capability composed by the standard client. */\nexport class ConvexOrganizationSetupAdapter implements OrganizationSetupOps {\n readonly #convex: ConvexCallPort;\n readonly #signer: CapxulSigner;\n readonly #chainId: number;\n readonly #fns: OrganizationSetupFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly signer: CapxulSigner;\n readonly chainId: number;\n readonly functions?: OrganizationSetupFunctions;\n }) {\n this.#convex = input.convex;\n this.#signer = input.signer;\n this.#chainId = input.chainId;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n async startOrResume(\n input: StartOrResumeOrganizationInput,\n ): Promise<CapxulResult<{ readonly orgId: OrgId; readonly lifecycle: OrgLifecycle }>> {\n const result = await runCall<{\n readonly orgId: string;\n readonly lifecycle: WireLifecycle;\n }>(\n \"startOrResume\",\n this.#convex.mutation(\n this.#fns.startOrResume,\n copyInvocationObservation(input, { ...input, chainId: this.#chainId }),\n ),\n );\n if (!result.ok) return result;\n const lifecycle = parseLifecycle(\"startOrResume\", result.value.lifecycle);\n if (!lifecycle.ok) return lifecycle;\n const orgId = parseOrgId(\"startOrResume\", result.value.orgId);\n if (!orgId.ok) return orgId;\n if (String(orgId.value) !== String(lifecycle.value.orgId)) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle scope does not match\"));\n }\n return { ok: true, value: { orgId: orgId.value, lifecycle: lifecycle.value } } as const;\n }\n\n prepareFounderAccount(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"prepareFounderAccount\", input, () =>\n this.#convex.action(\n this.#fns.prepareFounderAccount,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async authorizeAndSubmitBootstrap(\n input: OrganizationSetupStepInput,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n\n const signerAddress = await signerResult(\"getAddress\", () => this.#signer.getAddress());\n if (!signerAddress.ok) return signerAddress;\n const prepared = await runCall(\n \"prepareBootstrap\",\n this.#convex.action(\n this.#fns.prepareBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!prepared.ok) return prepared;\n const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);\n if (!authority.ok) return authority;\n const cancelledAfterPrepare = cancellation(input.signal);\n if (cancelledAfterPrepare !== undefined) return cancelledAfterPrepare;\n\n const signature = await signerResult(\"signUserOpHash\", () =>\n this.#signer.signUserOpHash(prepared.value.digest as Hex),\n );\n if (!signature.ok) return signature;\n const cancelledAfterSign = cancellation(input.signal);\n if (cancelledAfterSign !== undefined) return cancelledAfterSign;\n\n const submitted = await runCall(\n \"submitBootstrap\",\n this.#convex.action(\n this.#fns.submitBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n signature: signature.value,\n userOp: prepared.value.userOp,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!submitted.ok) return submitted;\n return parseLifecycle(\"submitBootstrap\", submitted.value);\n }\n\n resumeSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"resumeBootstrapSubmission\", input, () =>\n this.#convex.action(\n this.#fns.resumeBootstrapSubmission,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n confirmSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"confirmBootstrap\", input, () =>\n this.#convex.action(\n this.#fns.confirmBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async recordFailure(input: RecordOrganizationSetupFailureInput) {\n const errorProvider = input.error.details?.provider;\n const errorOperation = input.error.details?.operation;\n const result = await runCall(\n \"recordFailure\",\n this.#convex.mutation(\n this.#fns.recordFailure,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n errorCode: input.error.code,\n ...(typeof errorProvider === \"string\" && typeof errorOperation === \"string\"\n ? { errorProvider, errorOperation }\n : {}),\n retryable: input.retryable,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n return result.ok ? parseLifecycle(\"recordFailure\", result.value) : result;\n }\n\n async loadLifecycle(input: {\n readonly orgId: OrgId;\n readonly observationContext?: WireObservationContext;\n }): Promise<CapxulResult<OrgLifecycle>> {\n const result = await runCall<WireLifecycle | null>(\n \"loadLifecycle\",\n this.#convex.query(this.#fns.load, input),\n );\n if (!result.ok) return result;\n if (result.value === null) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle was not found\"));\n }\n return parseLifecycle(\"loadLifecycle\", result.value);\n }\n\n async retry(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const current = await this.loadLifecycle({\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n });\n if (!current.ok) return current;\n if (\n current.value.status === \"failed\" &&\n current.value.retryable &&\n (current.value.at === \"awaitingFounderAuthorization\" ||\n current.value.at === \"submittingBootstrap\")\n ) {\n const reset = resetSignerSession(this.#signer);\n if (!reset.ok) return reset;\n }\n const result = await runCall(\n \"retry\",\n this.#convex.mutation(\n this.#fns.retry,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!result.ok) return result;\n return parseLifecycle(\"retry\", result.value);\n }\n\n async #lifecycleAction(\n operation: string,\n input: OrganizationSetupStepInput,\n call: () => Effect.Effect<WireLifecycle, unknown>,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const result = await runCall(operation, call());\n if (!result.ok) return result;\n const cancelledAfter = cancellation(input.signal);\n if (cancelledAfter !== undefined) return cancelledAfter;\n return parseLifecycle(operation, result.value);\n }\n}\n\nfunction resetSignerSession(signer: CapxulSigner): CapxulResult<void> {\n const resetSession = (signer as CapxulSigner & { readonly resetSession?: unknown }).resetSession;\n if (typeof resetSession !== \"function\") return { ok: true, value: undefined };\n try {\n resetSession.call(signer);\n return { ok: true, value: undefined };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", \"resetSession\", cause, {\n failure_mode: \"unknown\",\n }),\n );\n }\n}\n\nasync function runCall<T>(\n operation: string,\n effect: Effect.Effect<T, unknown>,\n): Promise<CapxulResult<T>> {\n try {\n const result = await Effect.runPromise(Effect.result(effect));\n return Result.isSuccess(result)\n ? { ok: true, value: result.success }\n : fail(publicError(operation, result.failure));\n } catch (cause) {\n return fail(publicError(operation, cause));\n }\n}\n\nfunction publicError(operation: string, cause: unknown): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const carried = (cause as { readonly publicError?: unknown }).publicError;\n if (carried instanceof CapxulError) return carried;\n }\n return Errors.providerError(\"convex-organization\", operation, cause);\n}\n\nasync function signerResult<T>(operation: string, run: () => Promise<T>): Promise<CapxulResult<T>> {\n try {\n return { ok: true, value: await run() };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"organization-signer\", operation, cause),\n );\n }\n}\n\nfunction validatePreparedAuthorities(\n prepared: PreparedBootstrap,\n signerAddress: string,\n): CapxulResult<void> {\n const signer = signerAddress.toLowerCase();\n const preparedSigner = prepared.signerAddress.toLowerCase();\n const founder = prepared.founderPersonalAccount.toLowerCase();\n const organization = prepared.organizationAccountAddress.toLowerCase();\n const sender = prepared.userOp.sender.toLowerCase();\n if (preparedSigner !== signer) {\n return fail(\n Errors.invalidInput(\"signerAddress\", \"Prepared signer does not match configured signer\"),\n );\n }\n if (founder === signer || organization === signer || organization === founder) {\n return fail(\n Errors.invalidInput(\n \"organizationAuthority\",\n \"Signer EOA, founder Account, and Organization Account must be distinct\",\n ),\n );\n }\n if (sender !== founder) {\n return fail(\n Errors.invalidInput(\"userOp.sender\", \"Bootstrap sender must be the founder Account\"),\n );\n }\n if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) {\n return fail(Errors.invalidInput(\"digest\", \"Prepared bootstrap digest must be 32-byte hex\"));\n }\n return { ok: true, value: undefined };\n}\n\nfunction parseLifecycle(operation: string, wire: WireLifecycle): CapxulResult<OrgLifecycle> {\n const orgId = parseOrgId(operation, wire.orgId);\n if (!orgId.ok) return orgId;\n if (wire.status === \"loading\")\n return { ok: true, value: { status: \"loading\", orgId: orgId.value } };\n if (wire.status === \"ready\") {\n return { ok: true, value: { status: \"ready\", orgId: orgId.value, canTransact: true } };\n }\n if (wire.status === \"failed\") {\n if (!isSetupStep(wire.at))\n return fail(Errors.invalidInput(\"lifecycle.at\", \"Unknown setup step\"));\n return {\n ok: true,\n value: {\n status: \"failed\",\n orgId: orgId.value,\n at: wire.at,\n error: new CapxulError(wire.error.code, wire.error.message),\n retryable: wire.retryable,\n },\n };\n }\n if (!isSetupStep(wire.step)) {\n return fail(Errors.invalidInput(\"lifecycle.step\", `Unknown setup step from ${operation}`));\n }\n return { ok: true, value: { status: \"settingUp\", orgId: orgId.value, step: wire.step } };\n}\n\nfunction parseOrgId(operation: string, value: string): CapxulResult<OrgId> {\n try {\n return { ok: true, value: toOrgId(value) };\n } catch (cause) {\n return fail(Errors.providerError(\"convex-organization\", operation, cause));\n }\n}\n\nfunction isSetupStep(\n value: string,\n): value is Extract<OrgLifecycle, { status: \"settingUp\" }>[\"step\"] {\n return (\n value === \"preparingFounderAccount\" ||\n value === \"awaitingFounderAuthorization\" ||\n value === \"submittingBootstrap\" ||\n value === \"confirmingBootstrap\"\n );\n}\n\nfunction cancellation(signal: AbortSignal | undefined): CapxulResult<never> | undefined {\n return signal?.aborted ? fail(Errors.cancelled({ operation: \"organization.setup\" })) : undefined;\n}\n\nfunction fail<T>(error: CapxulError): CapxulResult<T> {\n return { ok: false, error };\n}\n","import { Effect, Layer } from \"effect\";\n\nimport {\n redactTelemetryProps,\n TelemetryPortTag,\n type TelemetryEvent,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEventName,\n type TelemetryPort,\n type TelemetryProps,\n} from \"../../ports/telemetry\";\n\nexport type PostHogCapture = (\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n) => void | Promise<void>;\nexport type PostHogIdentify = (input: TelemetryIdentifyInput) => void | Promise<void>;\nexport type PostHogGroup = (input: TelemetryGroupInput) => void | Promise<void>;\nexport type PostHogReset = () => void | Promise<void>;\n\nexport type PostHogTelemetryLayerDeps = {\n readonly capture: PostHogCapture;\n readonly identify?: PostHogIdentify;\n readonly group?: PostHogGroup;\n readonly reset?: PostHogReset;\n};\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: PostHogCapture;\n readonly #identify: PostHogIdentify;\n readonly #group: PostHogGroup;\n readonly #reset: PostHogReset;\n\n constructor(deps: PostHogTelemetryLayerDeps) {\n this.#capture = deps.capture;\n this.#identify = deps.identify ?? (() => undefined);\n this.#group = deps.group ?? (() => undefined);\n this.#reset = deps.reset ?? (() => undefined);\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never, never> {\n return this.#run(\n () => this.#capture(event.name, redactTelemetryProps(event.name, cloneProps(event.props))),\n \"emit\",\n event.name,\n );\n }\n\n identify(input: TelemetryIdentifyInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#identify(cloneIdentifyInput(input)), \"identify\");\n }\n\n group(input: TelemetryGroupInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#group(cloneGroupInput(input)), \"group\");\n }\n\n reset(): Effect.Effect<void, never, never> {\n return this.#run(() => this.#reset(), \"reset\");\n }\n\n #run(\n operation: () => void | Promise<void>,\n operationName: \"emit\" | \"identify\" | \"group\" | \"reset\",\n eventName?: TelemetryEventName,\n ): Effect.Effect<void, never> {\n const diagnose = Effect.logWarning(\"product.telemetry.transport.dropped\").pipe(\n Effect.annotateLogs({\n operation: operationName,\n ...(eventName === undefined ? {} : { product_event: eventName }),\n }),\n Effect.catchCause(() => Effect.void),\n );\n return Effect.suspend(() => {\n let pending: void | Promise<void>;\n try {\n pending = operation();\n } catch {\n return diagnose;\n }\n if (pending === undefined) return Effect.void;\n const transport = Effect.tryPromise({\n try: () => pending,\n catch: () => undefined,\n }).pipe(Effect.catch(() => diagnose));\n return Effect.forkDetach(transport, { startImmediately: true }).pipe(Effect.asVoid);\n });\n }\n}\n\nexport function PostHogTelemetryLayer(\n deps: PostHogTelemetryLayerDeps,\n): Layer.Layer<TelemetryPortTag, never, never> {\n return Layer.succeed(TelemetryPortTag, new PostHogTelemetryAdapter(deps));\n}\n\nfunction cloneIdentifyInput(input: TelemetryIdentifyInput): TelemetryIdentifyInput {\n const traits = input.traits === undefined ? undefined : cloneProps(input.traits);\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return {\n distinctId: input.distinctId,\n ...(input.anonDistinctId === undefined ? {} : { anonDistinctId: input.anonDistinctId }),\n ...(traits === undefined ? {} : { traits }),\n ...(properties === undefined ? {} : { properties }),\n };\n}\n\nfunction cloneGroupInput(input: TelemetryGroupInput): TelemetryGroupInput {\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return properties === undefined\n ? { groupType: input.groupType, groupKey: input.groupKey }\n : {\n groupType: input.groupType,\n groupKey: input.groupKey,\n properties,\n };\n}\n\nfunction cloneProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n const cloned: TelemetryProps = {};\n for (const [key, value] of Object.entries(props)) {\n cloned[key] = cloneTelemetryValue(value);\n }\n return cloned;\n}\n\nfunction cloneTelemetryValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(cloneTelemetryValue);\n if (value === null || typeof value !== \"object\") return value;\n if (Object.getPrototypeOf(value) !== Object.prototype) return value;\n const cloned: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n cloned[key] = cloneTelemetryValue(nested);\n }\n return cloned;\n}\n","import type { DiagnosticDetail, DiagnosticPort } from \"../../ports/diagnostic\";\n\nconst DEFAULT_ACCOUNT_SETUP_LOG_PREFIX = \"[capxul:account-setup]\";\n\nexport class ConsoleDiagnosticAdapter implements DiagnosticPort {\n private readonly prefix: string;\n\n constructor(prefix: string = DEFAULT_ACCOUNT_SETUP_LOG_PREFIX) {\n this.prefix = prefix;\n }\n\n trace(scope: string, detail: DiagnosticDetail): void {\n globalThis.console?.debug?.(`${this.prefix} ${scope}`, detail);\n }\n}\n\nexport function ConsoleDiagnosticLayer(prefix?: string): DiagnosticPort {\n return new ConsoleDiagnosticAdapter(prefix);\n}\n","import {\n AccountTypeEnum,\n ChainTypeEnum,\n EmbeddedState,\n Openfort,\n RecoveryMethod,\n ThirdPartyOAuthProvider,\n} from \"@openfort/openfort-js\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\n\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { DiagnosticPort } from \"../ports/diagnostic\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport type { CapxulSigner } from \"../signer\";\nimport { openfortEmbeddedSignerFromWallet } from \"../openfort-embedded-signer\";\n\nexport interface OpenfortBrowserSigner extends CapxulSigner {\n readonly resetSession: () => void;\n}\n\nfunction openfortProviderError(operation: string, cause: unknown): CapxulError {\n return cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", operation, cause, { failure_mode: \"unknown\" });\n}\n\nexport interface OpenfortBrowserSignerOptions {\n readonly diagnostic?: DiagnosticPort;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * True when the browser cannot perform Web Crypto — sandboxed iframes, headless\n * agent browsers, or non-HTTPS origins. OpenFort's embedded-wallet `configure`\n * silently produces no address in this state, so we detect it up front and name\n * it `no-secure-context` instead of letting it decay into `unknown`.\n */\nfunction isInsecureBrowserContext(): boolean {\n return globalThis.isSecureContext === false || globalThis.crypto?.subtle === undefined;\n}\n\n/** Openfort SDK storage keys (`@openfort/openfort-js` StorageKeys). */\nconst OPENFORT_BROWSER_STORAGE_KEYS = [\n \"openfort.authentication\",\n \"openfort.account\",\n \"openfort.session\",\n \"openfort.configuration\",\n] as const;\n\n/**\n * Matches `@openfort/openfort-js` ScopedStorage.createScope — chars 8–15 of the\n * publishable key, prefixed onto each StorageKeys entry in localStorage.\n */\nexport function openfortBrowserStorageScope(publishableKey: string): string | undefined {\n const trimmed = publishableKey.trim();\n if (trimmed.length < 16) {\n return undefined;\n }\n return trimmed.substring(8, 16);\n}\n\n/**\n * Drop cached Openfort auth/account state so third-party login re-runs for the\n * current Better Auth session. The SDK skips `authenticateThirdParty` when a\n * stale `userId` is already in storage, which yields 401 on `v2/accounts`.\n */\nfunction clearStaleOpenfortBrowserStorage(publishableKey: string): void {\n if (typeof localStorage === \"undefined\") {\n return;\n }\n const scope = openfortBrowserStorageScope(publishableKey);\n if (scope === undefined) {\n return;\n }\n for (const key of OPENFORT_BROWSER_STORAGE_KEYS) {\n localStorage.removeItem(`${scope}.${key}`);\n }\n}\n\nexport function createOpenfortBrowserSignerFromBootstrap(\n bootstrap: BootstrapResolution,\n options: OpenfortBrowserSignerOptions = {},\n): OpenfortBrowserSigner {\n const diagnostic = options.diagnostic;\n const telemetry = options.telemetry;\n const authBaseUrl = normalizeBetterAuthBaseUrl(bootstrap.authBaseUrl);\n\n /**\n * Closes the black hole: when the browser has no Web Crypto, OpenFort's\n * `configure` would resolve to no address and the failure would be reported\n * as `unknown`. Detect it before any network/wallet work, tag it\n * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`, breadcrumb\n * it via DiagnosticPort, and self-report via TelemetryPort.\n */\n function failNoSecureContext(): never {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"no-secure-context\",\n });\n const error = Errors.providerError(\n \"openfort\",\n \"configure\",\n new Error(\"Web Crypto unavailable: browser is not a secure context\"),\n { failure_mode: \"no-secure-context\" },\n );\n if (telemetry) {\n captureExceptionSync(telemetry, error, {\n layer: \"openfort\",\n operation: \"configure\",\n provider: \"openfort\",\n failure_mode: \"no-secure-context\",\n });\n }\n throw error;\n }\n\n function betterAuthSessionUrl(): string {\n return `${authBaseUrl}/get-session`;\n }\n\n function encryptionSessionUrl(): string {\n return `${authBaseUrl}/encryption-session`;\n }\n\n async function fetchBetterAuthAccessToken(): Promise<string | null> {\n try {\n const response = await fetch(betterAuthSessionUrl(), { credentials: \"include\" });\n if (!response.ok) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n httpStatus: response.status,\n failure_mode: \"unknown\",\n });\n return null;\n }\n const body = (await response.json()) as { session?: { token?: string } };\n const token = body.session?.token?.trim();\n if (token === undefined || token.length === 0) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n return null;\n }\n diagnostic?.trace(\"openfort.token\", { ok: true, tokenPresent: true });\n return token;\n } catch (cause) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"token\", cause);\n }\n }\n\n const openfort = new Openfort({\n baseConfiguration: {\n publishableKey: bootstrap.openfortPublishableKey,\n },\n shieldConfiguration: {\n shieldPublishableKey: bootstrap.shieldPublishableKey,\n },\n thirdPartyAuth: {\n provider: ThirdPartyOAuthProvider.BETTER_AUTH,\n getAccessToken: fetchBetterAuthAccessToken,\n },\n });\n\n let walletReadyPromise: Promise<void> | null = null;\n\n function startWalletReady(): Promise<void> {\n return (async () => {\n if (isInsecureBrowserContext()) {\n failNoSecureContext();\n }\n await openfort.waitForInitialization();\n\n const accessToken = await fetchBetterAuthAccessToken();\n if (accessToken === null) {\n throw openfortProviderError(\n \"token\",\n new Error(\"Better Auth access token unavailable for Openfort\"),\n );\n }\n\n let encryptionResponse: Response;\n try {\n encryptionResponse = await fetch(encryptionSessionUrl(), {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n });\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n if (!encryptionResponse.ok) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw Errors.providerError(\n \"openfort\",\n \"encryptionSession\",\n new Error(`Openfort encryption session failed (${encryptionResponse.status})`),\n { failure_mode: \"unknown\" },\n );\n }\n let encryptionBody: { sessionId?: string };\n try {\n encryptionBody = (await encryptionResponse.json()) as { sessionId?: string };\n if (typeof encryptionBody.sessionId !== \"string\" || encryptionBody.sessionId.length === 0) {\n throw new Error(\"Openfort encryption session response missing sessionId\");\n }\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: true,\n httpStatus: encryptionResponse.status,\n });\n\n let embeddedState: EmbeddedState;\n try {\n embeddedState = await openfort.embeddedWallet.getEmbeddedState();\n diagnostic?.trace(\"openfort.embeddedState\", { state: embeddedState });\n } catch (cause) {\n diagnostic?.trace(\"openfort.embeddedState\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"embeddedState\", cause);\n }\n if (embeddedState !== EmbeddedState.READY) {\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n diagnostic?.trace(\"openfort.storageCleared\", { beforeConfigure: true });\n try {\n await openfort.embeddedWallet.configure({\n accountType: AccountTypeEnum.EOA,\n chainType: ChainTypeEnum.EVM,\n recoveryParams: {\n recoveryMethod: RecoveryMethod.AUTOMATIC,\n encryptionSession: encryptionBody.sessionId,\n },\n });\n diagnostic?.trace(\"openfort.configure\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"configure\", cause);\n }\n }\n\n try {\n await openfort.embeddedWallet.get();\n diagnostic?.trace(\"openfort.get\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.get\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"get\", cause);\n }\n })();\n }\n\n async function ensureOpenfortWalletReady(): Promise<void> {\n walletReadyPromise ??= startWalletReady();\n try {\n await walletReadyPromise;\n } catch (cause) {\n walletReadyPromise = null;\n throw cause;\n }\n }\n\n const signer = openfortEmbeddedSignerFromWallet({\n embeddedWallet: openfort.embeddedWallet,\n ensureWalletReady: ensureOpenfortWalletReady,\n });\n\n return {\n ...signer,\n getAddress: async () => {\n try {\n const address = await signer.getAddress();\n diagnostic?.trace(\"openfort.address\", { ok: true });\n return address;\n } catch (cause) {\n diagnostic?.trace(\"openfort.address\", { ok: false, failure_mode: \"unknown\" });\n throw openfortProviderError(\"getAddress\", cause);\n }\n },\n resetSession: () => {\n walletReadyPromise = null;\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n signer.resetAddressCache();\n },\n };\n}\n\nfunction normalizeBetterAuthBaseUrl(raw: string): string {\n const trimmed = raw.replace(/\\/$/, \"\");\n return trimmed.endsWith(\"/api/auth\") ? trimmed : `${trimmed}/api/auth`;\n}\n","import { EXPECTED_OPERATION_OUTCOMES, isCapxulError, type CapxulErrorCode } from \"@capxul/errors\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport {\n hasFailureInvocationSnapshot,\n markFailureInvocationSnapshot,\n} from \"./internal/invocation-observation\";\nimport { EXCEPTION_MESSAGE } from \"./telemetry/capture-exception\";\n\n/** Host-owned correlation fields that are safe to attach to an SDK failure. */\nexport interface ObservationContext extends Omit<WireObservationContext, \"applicationId\"> {}\n\n/**\n * The small, SDK-owned failure envelope delivered to observation adapters.\n * Method arguments, response bodies, wallet payloads, and arbitrary error\n * details are deliberately absent.\n */\nexport interface SdkFailureObservation {\n readonly exception: Error;\n readonly sdkVersion: string;\n readonly operation: string;\n readonly errorKind: string;\n /** Invocation snapshot; failure correlation wins over later host state. */\n readonly context?: ObservationContext;\n}\n\nexport type ObservationDelivery = void | PromiseLike<void>;\n\n/**\n * High-level host observation boundary. The SDK owns when each method is\n * called; the host owns the destination client, consent, and delivery policy.\n */\nexport interface ObservationAdapter {\n /**\n * Optional read-only invocation context. Transport adapters snapshot it once\n * at call start; implementations must not mutate global SDK state.\n */\n readonly resolveContext?: () => ObservationContext | undefined;\n /** A method returned the SDK's typed `{ ok: false, error }` result. */\n captureOperationFailure(failure: SdkFailureObservation): ObservationDelivery;\n /** A method unexpectedly threw or rejected instead of returning a typed result. */\n captureException(exception: SdkFailureObservation): ObservationDelivery;\n}\n\n/** The host-owned PostHog capabilities consumed by the supported adapter. */\nexport interface PostHogObservationClient {\n capture(event: string, properties?: Readonly<Record<string, unknown>>): unknown;\n /** Optional host capability; the supported adapter uses ordinary capture for slim clients. */\n captureException?(exception: Error, properties?: Readonly<Record<string, unknown>>): unknown;\n}\n\nexport interface PostHogObservationOptions {\n /** Consent / kill-switch seam. Defaults to enabled. */\n readonly enabled?: boolean | (() => boolean);\n /** Snapshotted at invocation start and resolved again for direct adapter capture. */\n readonly context?: ObservationContext | (() => ObservationContext | undefined);\n}\n\nconst SDK_VERSION = sdkPackageJson.version;\n\n/** Stable PostHog event used for typed failures that are expected product outcomes. */\nexport const CAPXUL_SDK_EXPECTED_OUTCOME_EVENT = \"capxul_sdk_expected_outcome\";\n\n/**\n * Adapt the host's already-initialized PostHog-like client. This function does\n * not import, initialize, configure, or own PostHog.\n */\nexport function fromPostHog(\n client: PostHogObservationClient | null | undefined,\n options: PostHogObservationOptions = {},\n): ObservationAdapter {\n const prepare = (\n failure: SdkFailureObservation,\n ): readonly [SdkFailureObservation, Readonly<Record<string, unknown>>] | undefined => {\n if (!isEnabled(options.enabled)) return;\n if (client === null || client === undefined) return;\n\n const safeFailure = sanitizeFailureObservation(failure);\n const directContext = hasFailureInvocationSnapshot(failure)\n ? undefined\n : resolveContext(options.context);\n const properties = postHogProperties(safeFailure, directContext);\n return [safeFailure, properties];\n };\n\n const captureOperationFailure = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || client === null || client === undefined) return;\n const [safeFailure, properties] = prepared;\n\n if (classifyOperationOutcome(safeFailure.errorKind) === \"expected\") {\n if (typeof client.capture !== \"function\") return;\n deliver(() =>\n client.capture(CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, {\n ...properties,\n outcome_class: \"expected\",\n }),\n );\n return;\n }\n\n deliver(() =>\n client.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n const captureException = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || client === null || client === undefined) return;\n const [safeFailure, properties] = prepared;\n deliver(() =>\n client.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n return {\n resolveContext: () => {\n if (!isEnabled(options.enabled) || client === null || client === undefined) return undefined;\n // Raw call-start snapshot: each consumer sanitizes at its own emission\n // boundary, so the pure sanitize is kept off the SDK success path.\n return resolveRawContext(options.context) ?? {};\n },\n captureOperationFailure,\n captureException,\n };\n}\n\nfunction classifyOperationOutcome(kind: string): \"expected\" | \"unexpected\" {\n return EXPECTED_OPERATION_OUTCOMES.has(kind as CapxulErrorCode) ? \"expected\" : \"unexpected\";\n}\n\nfunction deliver(capture: () => unknown): void {\n try {\n const delivery = capture();\n ignoreDeliveryFailure(delivery);\n } catch {\n // Observation is best effort and can never become an SDK failure.\n }\n}\n\n/**\n * Fan one SDK failure out to several adapters (issue #877). The SDK's own\n * first-party relay and an optional host-provided adapter both observe the same\n * failure. Order matters for `resolveContext`: the FIRST adapter that returns a\n * context wins, so pass the host adapter first to keep its call-start snapshot.\n * Each capture is isolated — a throwing adapter never blocks its peers or the\n * SDK. Returns `undefined` when no adapters are present (zero observation work).\n */\nexport function composeObservationAdapters(\n ...adapters: readonly (ObservationAdapter | undefined)[]\n): ObservationAdapter | undefined {\n const present = adapters.filter(\n (adapter): adapter is ObservationAdapter => adapter !== undefined,\n );\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n\n const fanOut = (select: (adapter: ObservationAdapter) => ObservationDelivery): void => {\n for (const adapter of present) {\n try {\n ignoreDeliveryFailure(select(adapter));\n } catch {\n // One adapter's defect is isolated from its peers and the SDK.\n }\n }\n };\n\n return {\n resolveContext: () => {\n for (const adapter of present) {\n try {\n const context = adapter.resolveContext?.();\n if (context !== undefined) return context;\n } catch {\n // Fall through to the next adapter's snapshot.\n }\n }\n return undefined;\n },\n captureOperationFailure: (failure) =>\n fanOut((adapter) => adapter.captureOperationFailure(failure)),\n captureException: (failure) => fanOut((adapter) => adapter.captureException(failure)),\n };\n}\n\n/** @internal Reports a factory-level typed failure without changing its identity. */\nexport function observeFailedResult<T extends { readonly ok: boolean }>(\n result: T,\n adapter: ObservationAdapter | undefined,\n operation: string,\n): T {\n if (adapter !== undefined && isFailedResult(result)) {\n report(adapter, \"operation\", operation, result.error, resolveAdapterContext(adapter));\n }\n return result;\n}\n\nfunction report(\n adapter: ObservationAdapter,\n kind: \"operation\" | \"exception\",\n operation: string,\n cause: unknown,\n invocationContext?: ObservationContext,\n): void {\n const operationName = normalizeOperation(operation);\n const kindName = normalizeErrorKind(errorKind(cause));\n const context = sanitizeObservationContext({\n ...invocationContext,\n ...(isCapxulError(cause) && cause.correlationId !== undefined\n ? { correlationId: cause.correlationId }\n : {}),\n }) as ObservationContext | undefined;\n const failure = markFailureInvocationSnapshot<SdkFailureObservation>({\n exception: syntheticException(operationName, kindName),\n sdkVersion: SDK_VERSION,\n operation: operationName,\n errorKind: kindName,\n ...(context === undefined ? {} : { context }),\n });\n\n try {\n const delivery =\n kind === \"operation\"\n ? adapter.captureOperationFailure(failure)\n : adapter.captureException(failure);\n ignoreDeliveryFailure(delivery);\n } catch {\n // Adapter failures are isolated from SDK return values and control flow.\n }\n}\n\nfunction resolveAdapterContext(adapter: ObservationAdapter): ObservationContext | undefined {\n // The adapter snapshot is the raw call-start context. Sanitize is deferred to\n // failure time in `report` and to each transport's own emission boundary, so\n // a successful call pays no per-call sanitize cost.\n try {\n return adapter.resolveContext?.();\n } catch {\n return undefined;\n }\n}\n\nfunction ignoreDeliveryFailure(delivery: unknown): void {\n if (!isPromiseLike(delivery)) return;\n try {\n void Promise.resolve(delivery).catch(() => undefined);\n } catch {\n // A malformed thenable is an adapter defect, not an SDK failure.\n }\n}\n\n/**\n * Map an ALREADY-sanitized observation context to the snake_case PostHog\n * property keys. Shared by the failure boundary here and the host\n * success-telemetry seam (`telemetry/from-posthog.ts`) so both attach identical\n * correlation fields from one definition.\n */\nexport function observationContextProps(\n context: WireObservationContext | undefined,\n): Record<string, string> {\n const props: Record<string, string> = {};\n if (context?.application !== undefined) props.application = context.application;\n if (context?.release !== undefined) props.release = context.release;\n if (context?.sessionId !== undefined) props.session_id = context.sessionId;\n if (context?.organizationId !== undefined) props.organization_id = context.organizationId;\n if (context?.journeyId !== undefined) props.journey_id = context.journeyId;\n if (context?.correlationId !== undefined) props.correlation_id = context.correlationId;\n if (context?.anonymousId !== undefined) props.anonymous_id = context.anonymousId;\n return props;\n}\n\nfunction postHogProperties(\n failure: SdkFailureObservation,\n context: ObservationContext | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = sanitizeObservationContext({ ...context, ...failure.context });\n return {\n sdk_version: failure.sdkVersion,\n operation: failure.operation,\n error_kind: failure.errorKind,\n handled: true,\n ...observationContextProps(merged),\n };\n}\n\nfunction postHogExceptionProperties(\n failure: SdkFailureObservation,\n properties: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> {\n const filename = `capxul-sdk-observation://boundary/${failure.operation}`;\n return {\n ...properties,\n $exception_type: failure.errorKind,\n $exception_message: EXCEPTION_MESSAGE,\n $exception_level: \"error\",\n $exception_list: [\n {\n type: failure.errorKind,\n value: EXCEPTION_MESSAGE,\n mechanism: { type: \"capxul_sdk_boundary\", handled: true, synthetic: true },\n stacktrace: {\n type: \"raw\",\n frames: [\n {\n platform: \"javascript\",\n filename,\n function: `CapxulSdkBoundary.${failure.operation}`,\n lineno: 1,\n colno: 1,\n in_app: true,\n },\n ],\n },\n },\n ],\n };\n}\n\nfunction resolveContext(\n context: PostHogObservationOptions[\"context\"],\n): ObservationContext | undefined {\n return sanitizeObservationContext(resolveRawContext(context)) as ObservationContext | undefined;\n}\n\n/** Resolve the host context closure without sanitizing — the call-start snapshot. */\nfunction resolveRawContext(\n context: PostHogObservationOptions[\"context\"],\n): ObservationContext | undefined {\n try {\n return (typeof context === \"function\" ? context() : context) as ObservationContext | undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isEnabled(enabled: PostHogObservationOptions[\"enabled\"]): boolean {\n try {\n return typeof enabled === \"function\" ? enabled() : (enabled ?? true);\n } catch {\n return false;\n }\n}\n\nfunction errorKind(cause: unknown): string {\n try {\n if (isCapxulError(cause)) return normalizeErrorKind(cause.code);\n if (cause instanceof Error) return normalizeErrorKind(cause.name);\n return \"UnknownFailure\";\n } catch {\n return \"Error\";\n }\n}\n\nfunction sanitizeFailureObservation(failure: SdkFailureObservation): SdkFailureObservation {\n const operation = normalizeOperation(failure.operation);\n const kind = normalizeErrorKind(failure.errorKind);\n const context = sanitizeObservationContext(failure.context) as ObservationContext | undefined;\n return {\n exception: syntheticException(operation, kind),\n sdkVersion: normalizeSdkVersion(failure.sdkVersion),\n operation,\n errorKind: kind,\n ...(context === undefined ? {} : { context }),\n };\n}\n\nfunction normalizeSdkVersion(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeOperation(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,255}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeErrorKind(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(value)\n ? value\n : \"Error\";\n}\n\nfunction syntheticException(operation: string, kind: string): Error {\n const error = new Error(EXCEPTION_MESSAGE);\n error.name = kind;\n error.stack =\n `${kind}: ${error.message}\\n` +\n ` at CapxulSdkBoundary.${operation} ` +\n `(capxul-sdk-observation://boundary/${operation}:1:1)`;\n return error;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === \"function\"\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isCapxulResult(\n value: unknown,\n): value is\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; error: unknown } {\n return isPlainObject(value) && typeof value.ok === \"boolean\";\n}\n\nfunction isFailedResult(value: unknown): value is { readonly ok: false; readonly error: unknown } {\n return isCapxulResult(value) && value.ok === false && \"error\" in value;\n}\n","import { Context, Effect, Result, Exit, Layer, Scope } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toAllowedOrigin, toPublishableKey, type ChainId } from \"@capxul/types\";\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport {\n makeEngineeringTelemetryLayer,\n type EngineeringTelemetryConfig,\n} from \"@capxul/observability/engineering\";\n\nimport { BetterAuthBrowserLayer, BetterAuthNodeLayer } from \"./adapters/auth-client\";\nimport { HttpBootstrapLayer } from \"./adapters/bootstrap\";\nimport { SystemClockLayer } from \"./adapters/clock\";\nimport { ConvexCallLayer, type ConvexClientShape } from \"./adapters/convex-call\";\nimport { ConvexIdentityLayer } from \"./adapters/identity\";\nimport { ConvexAccountLayer } from \"./adapters/account-read\";\nimport { ConvexSubAccountLayer } from \"./adapters/sub-account/ConvexSubAccountAdapter\";\nimport { ConvexSmartAccountLayer } from \"./adapters/smart-account\";\nimport { ConvexOrganizationAdapter } from \"./adapters/org/ConvexOrganizationAdapter\";\nimport { ConvexOrganizationSetupAdapter } from \"./adapters/org/ConvexOrganizationSetupAdapter\";\nimport { PostHogTelemetryLayer } from \"./adapters/telemetry\";\nimport { ConsoleDiagnosticAdapter } from \"./adapters/diagnostic/ConsoleDiagnosticAdapter\";\nimport { assertDevKeySignerIsTestnetOnly } from \"./dev-signer\";\nimport type { AccountRequirement } from \"./surface/account-providers\";\nimport {\n createOpenfortBrowserSignerFromBootstrap,\n type OpenfortBrowserSigner,\n} from \"./openfort/create-openfort-browser-signer\";\nimport type { CapxulSigner } from \"./signer\";\nimport { assembleCapxulClient, type CapxulClient } from \"./surface/create-capxul-client\";\nimport { detectAuthCacheAdapter } from \"./surface/factory\";\nimport type { CapxulResult } from \"./surface/types\";\nimport { observeFailedResult, type ObservationAdapter } from \"./observation\";\nimport type { FlowPorts } from \"./flows/types\";\nimport { AuthClientPortTag, type AuthClientPort } from \"./ports/auth-client\";\nimport { AuthCachePortTag, type AuthCachePort } from \"./ports/auth-cache\";\nimport { BootstrapPortTag, type BootstrapPort, type BootstrapResolution } from \"./ports/bootstrap\";\nimport { ClockPortTag } from \"./ports/clock\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"./ports/convex-call\";\nimport { IdentityPortTag } from \"./ports/identity\";\nimport { OrgPortTag, type OrgPort } from \"./ports/org\";\nimport { AccountReadPortTag } from \"./ports/account-read\";\nimport { SubAccountPortTag } from \"./ports/sub-account\";\nimport { SmartAccountPortTag } from \"./ports/smart-account\";\nimport type { TelemetryEvent, TelemetryPort } from \"./ports/telemetry\";\nimport { TelemetryPortTag } from \"./ports/telemetry\";\n\nexport type ProductionRuntime = \"browser\" | \"node\";\nexport type ProductionAdapterClose = () => Promise<void>;\n\n/**\n * Interim default Capxul bootstrap host (SDK publish readiness · I3). Node\n * consumers pass neither `origin` nor `bootstrapBaseUrl`; both default here so\n * `createCapxulClient({ publishableKey })` reaches the Capxul backend with no\n * extra wiring. Superseded by the key-encoded host (`cap_pk_live_…`, out of\n * scope this milestone). See `packages/sdk/CONTEXT.md`.\n */\nexport const DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL = \"https://api.capxul.com\";\n\n/** Default per-request auth invocation timeout (ms) when the consumer omits it. */\nexport const DEFAULT_INVOKE_TIMEOUT_MS = 30_000;\n\n/**\n * Consumer-facing `createCapxulClient` input (SDK DX public surface · #326).\n * The publishable key is the primary input; bootstrap host, invoke timeout,\n * runtime detection, and auth-cache selection are SDK-owned defaults.\n */\nexport interface CapxulClientInput {\n readonly publishableKey: string;\n /**\n * Optional high-level observation adapter. The host supplies an adapter\n * around its existing analytics client; Capxul never initializes or bundles\n * another vendor SDK. Omit this property for zero observation work.\n */\n readonly observation?: ObservationAdapter;\n /**\n * Optional host success-telemetry sink. Build it from your posthog-js client\n * with `telemetryFromPostHog(posthog, …)`; events from SDK producers wired to\n * this port then reach the host's PostHog person after the host calls\n * `identify()`. Capxul never initializes or bundles a vendor SDK. Omit for no\n * host telemetry.\n */\n readonly telemetry?: TelemetryPort;\n /**\n * Optional engineering OTLP sink. The SDK supplies producer and version;\n * the host supplies its environment, PostHog host, and receipt-safe headers.\n */\n readonly engineeringTelemetry?: Omit<EngineeringTelemetryConfig, \"producer\" | \"sdkVersion\">;\n /**\n * Init-time account readiness target (issue #159 · AC4). Threaded into\n * `assembleCapxulClient` so `client.account.{getStatus,ensureReady}` reflect\n * the consumer's chosen requirement. Optional — defaults to `\"none\"` (SDK\n * publish readiness · I3) so `createCapxulClient({ publishableKey })` works\n * with no account lane.\n */\n readonly requirement?: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n}\n\n/**\n * Internal production adapter input for `@capxul/sdk/production` and hermetic\n * tests. Extends the consumer contract with bootstrap/fetch/runtime/auth-cache/\n * signal/timeout seams that must not appear on the bare `@capxul/sdk` barrel.\n * Org deployment port factories and deploy config live on\n * `@capxul/sdk/testing/org-deployment-client` (#327).\n */\nexport interface ProductionAdapterInput extends CapxulClientInput {\n readonly origin?: string;\n readonly bootstrapBaseUrl?: string;\n /** Optional BetterAuth host override (dogfood Vite proxy → same-origin `/api/auth`). */\n readonly authBaseUrl?: string;\n readonly runtime?: ProductionRuntime;\n readonly authCache?: AuthCachePort;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n}\n\n/**\n * @internal Test-injection seam. `convexClientFactory` is intentionally NOT a\n * member of the public `ProductionAdapterInput` (production-surface-policy.md):\n * consumers must not inject a Convex client. Hermetic tests pass a fake through\n * the fixture; it is read back here.\n */\ninterface ProductionConvexClientFactorySeam {\n readonly convexClientFactory?: (convexUrl: string) => ConvexClientShape;\n}\n\nexport interface ProductionAdapters {\n /**\n * THE RUNTIME (A2-Q1A, blueprint §2: \"the graph is the runtime, never\n * flattened to a record\"). This is the built Layer graph, alive in the same\n * `Scope` as `close`. Anything that needs a port resolves it from here.\n *\n * `ports` below is a PROJECTION of this context for the method bundles,\n * which still take ports as plain values — that is the shape L1 replaces\n * when it rebuilds the flows. Until then the projection is a convenience\n * VIEW of the graph, not a replacement for it: before the re-cut the graph\n * was discarded the moment the record was made, so nothing downstream could\n * resolve a tag, run an Effect against the real wiring, or add a port\n * without widening a hand-written record.\n */\n readonly context: Context.Context<ProductionFlowPortTags>;\n readonly ports: FlowPorts;\n readonly bootstrap: BootstrapResolution;\n readonly close: ProductionAdapterClose;\n}\n\nexport type ProductionAdapterLayerName =\n | \"bootstrap\"\n | \"authClient\"\n | \"authCache\"\n | \"identity\"\n | \"smartAccount\"\n | \"accountRead\"\n | \"subAccount\"\n | \"clock\"\n | \"telemetry\"\n | \"convexCall\"\n | \"org\";\n\nexport type ProductionFlowPortTags =\n | AuthClientPortTag\n | AuthCachePortTag\n | BootstrapPortTag\n | ClockPortTag\n | ConvexCallPortTag\n | IdentityPortTag\n | SmartAccountPortTag\n | AccountReadPortTag\n | SubAccountPortTag\n | TelemetryPortTag\n | OrgPortTag;\n\ntype RefreshConvexAuthRef = {\n current: (() => void) | null;\n pending: boolean;\n};\n\n/**\n * The embedded signer's session-reset callback, resolved after the graph is\n * built (the browser signer is derived from the bootstrap the graph itself\n * needs). Same late-binding idiom as `RefreshConvexAuthRef` above — the auth\n * layer closes over the ref and reads `current` at call time.\n */\ntype ResetSignerSessionRef = {\n current: (() => void) | null;\n};\n\nconst SDK_VERSION = sdkPackageJson.version;\n\ntype ProductionAdapterLayerOutput<N extends ProductionAdapterLayerName> = {\n readonly bootstrap: BootstrapPortTag;\n readonly authClient: AuthClientPortTag;\n readonly authCache: AuthCachePortTag;\n readonly identity: IdentityPortTag;\n readonly smartAccount: SmartAccountPortTag;\n readonly accountRead: AccountReadPortTag;\n readonly subAccount: SubAccountPortTag;\n readonly clock: ClockPortTag;\n readonly telemetry: TelemetryPortTag;\n readonly convexCall: ConvexCallPortTag;\n readonly org: OrgPortTag;\n}[N];\n\nexport interface ProductionRuntimeUrls {\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n}\n\nexport interface ProductionAdapterLayerInput {\n readonly bootstrap: BootstrapPort;\n readonly runtime: ProductionRuntime;\n readonly origin?: string;\n readonly runtimeUrls: ProductionRuntimeUrls;\n /**\n * Bootstrap-resolved chain. The `ConvexSubAccountAdapter`'s `transfer`\n * action reads the Safe's live `balanceOf` on this chain (canon §2/§5);\n * the consumer-facing `transfer({ from, to, amount })` carries no chainId\n * (public-surface no-consumer-chainId rule), so the adapter closes over it.\n */\n readonly chainId: ChainId;\n readonly authCache?: AuthCachePort;\n readonly telemetry?: TelemetryPort;\n readonly convexClient?: ConvexClientShape;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n /** Bootstrap-verified hint; the backend independently verifies it again. */\n readonly applicationId?: string;\n readonly observation?: ObservationAdapter;\n /**\n * Late-bound signer session reset (see `ResetSignerSessionRef`). Present when\n * the composition root intends to attach an embedded signer; the auth layer\n * wraps `signOut` with it whether or not `current` is ever filled in.\n */\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\nexport type ProductionAdapterLayerEntry<\n N extends ProductionAdapterLayerName = ProductionAdapterLayerName,\n> = {\n readonly [K in N]: {\n readonly name: K;\n readonly layer: Layer.Layer<ProductionAdapterLayerOutput<K>, unknown, unknown>;\n };\n}[N];\n\n/**\n * Project the built graph into the flat `FlowPorts` record the method bundles\n * still take. It is a VIEW of `ProductionAdapters.context`, taken from the\n * graph and never instead of it — the graph stays alive in the scope and is\n * handed to every caller.\n */\nexport const collectProductionFlowPorts: Effect.Effect<FlowPorts, never, ProductionFlowPortTags> =\n Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const authCache = yield* AuthCachePortTag;\n const bootstrap = yield* BootstrapPortTag;\n const clock = yield* ClockPortTag;\n const convexCall = yield* ConvexCallPortTag;\n const identity = yield* IdentityPortTag;\n const smartAccount = yield* SmartAccountPortTag;\n const accountRead = yield* AccountReadPortTag;\n const subAccount = yield* SubAccountPortTag;\n const telemetry = yield* TelemetryPortTag;\n return {\n authClient,\n authCache,\n identity,\n smartAccount,\n accountRead,\n subAccount,\n bootstrap,\n clock,\n telemetry,\n convexCall,\n };\n });\n\nexport function makeProductionAdapterLayerEntries(\n input: ProductionAdapterLayerInput,\n): readonly ProductionAdapterLayerEntry[] {\n const refreshConvexAuthRef: RefreshConvexAuthRef = { current: null, pending: false };\n return [\n {\n name: \"bootstrap\",\n layer: productionBootstrapPortLayer(input.bootstrap),\n },\n {\n name: \"authClient\",\n layer: productionAuthClientLayer(input, refreshConvexAuthRef, input.resetSignerSession),\n },\n {\n name: \"authCache\",\n layer: productionAuthCacheLayer(input),\n },\n {\n name: \"identity\",\n layer: ConvexIdentityLayer(),\n },\n {\n name: \"smartAccount\",\n layer: ConvexSmartAccountLayer(),\n },\n {\n name: \"accountRead\",\n layer: ConvexAccountLayer(),\n },\n {\n name: \"subAccount\",\n layer: ConvexSubAccountLayer(input.chainId),\n },\n {\n name: \"clock\",\n layer: SystemClockLayer(),\n },\n {\n name: \"telemetry\",\n layer:\n input.telemetry === undefined\n ? PostHogTelemetryLayer({ capture: () => undefined })\n : Layer.succeed(TelemetryPortTag, input.telemetry),\n },\n {\n name: \"convexCall\",\n layer: productionConvexCallLayer(input, refreshConvexAuthRef),\n },\n {\n // The org port used to be constructed by hand at the composition root\n // (`new ConvexOrganizationAdapter({ convex: ports.convexCall })`), which\n // is why `OrgPortTag` sat in `.fallowrc.json`'s ignore-list with zero\n // resolvers. It is a Convex-backed port like the four below it, so it\n // belongs IN the graph.\n name: \"org\",\n layer: Layer.effect(\n OrgPortTag,\n Effect.map(\n ConvexCallPortTag,\n (convex) => new ConvexOrganizationAdapter({ convex }) as OrgPort,\n ),\n ),\n },\n ];\n}\n\nexport function mergeProductionAdapterLayers(\n entries: readonly ProductionAdapterLayerEntry[],\n): Layer.Layer<ProductionFlowPortTags, unknown, never> {\n const byName = new Map<ProductionAdapterLayerName, Layer.Layer<never, unknown, unknown>>();\n for (const entry of entries) {\n byName.set(entry.name, entry.layer as Layer.Layer<never, unknown, unknown>);\n }\n const authClientLayer = byName.get(\"authClient\");\n const convexCallLayer = byName.get(\"convexCall\");\n // Phase 1: authClient -> convexCall. The auth wrapper reads\n // RefreshConvexAuthRef at call time, after this convex layer registers\n // the concrete refreshAuth callback during construction.\n const convexCallReadyLayer =\n convexCallLayer === undefined || authClientLayer === undefined\n ? convexCallLayer\n : convexCallLayer.pipe(Layer.provide(authClientLayer));\n\n const readyLayers = entries.map((entry) => {\n const layer = byName.get(entry.name) ?? (entry.layer as Layer.Layer<never, unknown, unknown>);\n if (entry.name === \"convexCall\") return convexCallReadyLayer ?? layer;\n if (isConvexDependentLayer(entry.name)) {\n // Phase 2: convexCallReady -> Convex-backed domain ports.\n return convexCallReadyLayer === undefined\n ? layer\n : layer.pipe(Layer.provide(convexCallReadyLayer));\n }\n return layer;\n });\n\n const merged = readyLayers.reduce((current, layer) => Layer.merge(current, layer), Layer.empty);\n // Entries are heterogeneous Layers stored behind one contract; the cast is\n // localized here, while production-layers.test.ts proves omissions fail\n // startup instead of silently assembling a partial FlowPorts graph.\n return merged as Layer.Layer<ProductionFlowPortTags, unknown, never>;\n}\n\nfunction isConvexDependentLayer(name: ProductionAdapterLayerName): boolean {\n return (\n name === \"identity\" ||\n name === \"smartAccount\" ||\n name === \"accountRead\" ||\n name === \"subAccount\" ||\n name === \"org\"\n );\n}\n\nfunction productionBootstrapPortLayer(\n bootstrap: BootstrapPort,\n): Layer.Layer<BootstrapPortTag, never, never> {\n return Layer.succeed(BootstrapPortTag, bootstrap);\n}\n\nfunction productionAuthClientLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n resetSignerSessionRef: ResetSignerSessionRef | undefined,\n): Layer.Layer<AuthClientPortTag, never, never> {\n const baseLayer =\n input.runtime === \"browser\"\n ? BetterAuthBrowserLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n })\n : BetterAuthNodeLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n });\n\n return baseLayer.pipe(\n Layer.flatMap((context) => {\n const authClient = Context.get(context, AuthClientPortTag);\n const refreshed = refreshConvexAuthOnSession(authClient, () => {\n const refresh = refreshConvexAuthRef.current;\n if (refresh === null) {\n refreshConvexAuthRef.pending = true;\n return;\n }\n refresh();\n });\n return Layer.succeedContext(\n Context.make(\n AuthClientPortTag,\n resetSignerSessionRef === undefined\n ? refreshed\n : resetSignerSessionOnSignOut(refreshed, resetSignerSessionRef),\n ),\n );\n }),\n );\n}\n\nfunction productionAuthCacheLayer(\n input: ProductionAdapterLayerInput,\n): Layer.Layer<AuthCachePortTag, never, never> {\n return Layer.succeed(AuthCachePortTag, input.authCache ?? detectAuthCacheAdapter());\n}\n\nfunction productionConvexCallLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n): Layer.Layer<ConvexCallPortTag, never, AuthClientPortTag> {\n return Layer.unwrap(\n Effect.map(AuthClientPortTag, (authClient) =>\n ConvexCallLayer({\n convexUrl: input.runtimeUrls.convexUrl,\n ...(input.applicationId === undefined ? {} : { applicationId: input.applicationId }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n ...(input.convexClient === undefined ? {} : { client: input.convexClient }),\n tokenProvider: async ({ forceRefreshToken }) => {\n const tokenResult = await Effect.runPromise(\n Effect.result(\n authClient.getConvexJwt({\n forceRefresh: forceRefreshToken,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n }),\n ),\n );\n if (Result.isFailure(tokenResult)) return null;\n return String(tokenResult.success.token);\n },\n }).pipe(\n Layer.flatMap((context) => {\n const convexCall = Context.get(context, ConvexCallPortTag);\n if (isRefreshableConvexCallPort(convexCall)) {\n refreshConvexAuthRef.current = () => convexCall.refreshAuth();\n if (refreshConvexAuthRef.pending) {\n refreshConvexAuthRef.pending = false;\n refreshConvexAuthRef.current();\n }\n }\n return Layer.succeedContext(context);\n }),\n ),\n ),\n );\n}\n\nfunction isRefreshableConvexCallPort(\n convexCall: ConvexCallPort,\n): convexCall is ConvexCallPort & { readonly refreshAuth: () => void } {\n return \"refreshAuth\" in convexCall && typeof convexCall.refreshAuth === \"function\";\n}\n\n/**\n * @internal Seam for the composition root only: `createCapxulClient` derives\n * the browser signer from the bootstrap this function resolves, so it hands in\n * a ref the auth layer closes over and fills the callback in afterwards. Not on\n * `ProductionAdapterInput` — a consumer must never reach the auth seam.\n */\ninterface ProductionResetSignerSeam {\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\nexport async function createProductionAdapters(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<ProductionAdapters>> {\n const resolvedInput = resolveInput(input);\n if (!resolvedInput.ok) return resolvedInput;\n\n const scope = await Effect.runPromise(Scope.make());\n const closeScope = idempotentClose(() => Effect.runPromise(Scope.close(scope, Exit.void)));\n\n const bootstrapLayer = HttpBootstrapLayer({\n bootstrapBaseUrl: resolvedInput.value.bootstrapBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n });\n\n try {\n const bootstrapContext = await Effect.runPromise(Layer.buildWithScope(bootstrapLayer, scope));\n const bootstrap = Context.get(bootstrapContext, BootstrapPortTag);\n const bootstrapResult = await runBootstrap(\n bootstrap.resolve({\n publishableKey: resolvedInput.value.publishableKey,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n }),\n );\n if (!bootstrapResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n reason: bootstrapResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return bootstrapResult;\n }\n\n // Testnet fence for the dev-key lane (#1149, folds #1065; ADR-0018 P9).\n // A `local-private-key` signer is a disposable, deterministically derived\n // dev key — it is the AGENT signing path, never the human one. This is the\n // one place where such a signer meets a resolved chain, so the refusal\n // lives here: every consumer (MCP proof lane, exemplar, approve, reference)\n // constructs through `createProductionAdapters`. It fails BEFORE any\n // adapter, Convex client, or signer call exists.\n const chainFence = assertDevKeySignerIsTestnetOnly(input.signer, bootstrapResult.value.chainId);\n if (!chainFence.ok) {\n await closeScope().catch(() => undefined);\n return chainFence;\n }\n\n const runtimeUrlsResult = resolveRuntimeUrls(\n bootstrapResult.value,\n resolvedInput.value.runtime,\n input.authBaseUrl,\n );\n if (!runtimeUrlsResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n reason: runtimeUrlsResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return runtimeUrlsResult;\n }\n const runtimeUrls = runtimeUrlsResult;\n\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_resolved\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n },\n });\n\n let injectedClient: ConvexClientShape | undefined;\n const convexClientFactory = (input as ProductionConvexClientFactorySeam).convexClientFactory;\n if (convexClientFactory !== undefined) {\n try {\n injectedClient = convexClientFactory(runtimeUrls.value.convexUrl);\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n }\n\n const portsLayer = mergeProductionAdapterLayers(\n makeProductionAdapterLayerEntries({\n bootstrap,\n runtime: resolvedInput.value.runtime,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n runtimeUrls: runtimeUrls.value,\n chainId: bootstrapResult.value.chainId,\n applicationId: bootstrapResult.value.applicationId,\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n ...(input.authCache === undefined ? {} : { authCache: input.authCache }),\n ...(input.telemetry === undefined ? {} : { telemetry: input.telemetry }),\n ...(injectedClient === undefined ? {} : { convexClient: injectedClient }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...((input as ProductionResetSignerSeam).resetSignerSession === undefined\n ? {}\n : {\n resetSignerSession: (input as ProductionResetSignerSeam)\n .resetSignerSession as ResetSignerSessionRef,\n }),\n }),\n );\n const applicationLayer =\n input.engineeringTelemetry === undefined\n ? portsLayer\n : Layer.merge(\n portsLayer,\n makeEngineeringTelemetryLayer({\n ...input.engineeringTelemetry,\n producer: resolvedInput.value.runtime === \"browser\" ? \"browser\" : \"server\",\n sdkVersion: SDK_VERSION,\n }),\n );\n // The graph, built into the same scope as `close`. It is the runtime; the\n // `FlowPorts` record below is a projection taken FROM it (A2-Q1A).\n const context = await Effect.runPromise(Layer.buildWithScope(applicationLayer, scope));\n const ports = await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context)));\n\n return {\n ok: true,\n value: { context, ports, bootstrap: bootstrapResult.value, close: closeScope },\n };\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nfunction refreshConvexAuthOnSession(\n authClient: AuthClientPort,\n refresh: () => void,\n): AuthClientPort {\n return {\n ...authClient,\n verifyOtp: (input, options) =>\n authClient.verifyOtp(input, options).pipe(Effect.tap(() => Effect.sync(refresh))),\n signOut: (options) => authClient.signOut(options).pipe(Effect.tap(() => Effect.sync(refresh))),\n };\n}\n\n/**\n * Signer-session reset, as a port wrapper INSIDE the Layer graph (blueprint §2:\n * \"wrappers become Layers, not post-hoc spreads/Proxies\").\n *\n * This was a spread over the assembled client — `{...client, auth: {...,\n * signOut}}` — applied after composition finished, so the reset lived on one\n * particular object rather than on the auth seam itself. Here it wraps\n * `AuthClientPort.signOut`, so it holds for every route to a sign-out.\n *\n * `Effect.ensuring` (not `Effect.tap`) is deliberate: the old wrapper used\n * `try/finally`, so the session was reset even when sign-out failed. Dropping\n * to `tap` would silently strand an Openfort session on the error path.\n */\nfunction resetSignerSessionOnSignOut(\n authClient: AuthClientPort,\n resetRef: ResetSignerSessionRef,\n): AuthClientPort {\n return {\n ...authClient,\n signOut: (options) =>\n authClient.signOut(options).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n resetRef.current?.();\n }),\n ),\n ),\n };\n}\n\nexport async function createCapxulClient(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<CapxulClient>> {\n const validation = validateCreateCapxulClientInput(input);\n if (!validation.ok) {\n return observeFailedResult(validation, input.observation, \"createCapxulClient\");\n }\n\n // The auth layer closes over this ref while the graph is built; the signer\n // that fills it in is derived from the bootstrap the graph itself resolves,\n // so the callback lands one step later. The WRAPPER is part of the graph\n // either way — that is the point of moving it off the assembled object.\n const resetSignerSession: ResetSignerSessionRef = { current: null };\n const adapters = await createProductionAdapters({\n ...input,\n resetSignerSession,\n } as ProductionAdapterInput);\n if (!adapters.ok) {\n return observeFailedResult(adapters, input.observation, \"createCapxulClient\");\n }\n try {\n const runtime = input.runtime ?? detectRuntime();\n const resolvedAuthBaseUrl = resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: adapters.value.bootstrap.authBaseUrl,\n runtime,\n ...(input.authBaseUrl === undefined ? {} : { override: input.authBaseUrl }),\n });\n let signer: CapxulSigner | OpenfortBrowserSigner | undefined = input.signer;\n if (signer === undefined && runtime === \"browser\") {\n // Thread the diagnostic + telemetry options so the signer's breadcrumbs\n // (token, encryptionSession, embeddedState, configure, getAddress) and its\n // no-secure-context self-report actually fire on the real browser path —\n // building it with the bootstrap alone dropped #870's native cause (#1032).\n signer = createOpenfortBrowserSignerFromBootstrap(\n {\n ...adapters.value.bootstrap,\n authBaseUrl: resolvedAuthBaseUrl,\n },\n {\n diagnostic: new ConsoleDiagnosticAdapter(),\n telemetry: adapters.value.ports.telemetry,\n },\n );\n }\n if (signer !== undefined && \"resetSession\" in signer) {\n const { resetSession } = signer;\n resetSignerSession.current = () => {\n resetSession();\n };\n }\n const client = assembleCapxulClient({\n ports: adapters.value.ports,\n bootstrap: adapters.value.bootstrap,\n authCache: adapters.value.ports.authCache,\n requirement: input.requirement ?? \"none\",\n ...(signer === undefined ? {} : { signer }),\n // Resolved FROM the graph rather than constructed beside it — the org\n // adapter is a Convex-backed port and now has a layer entry like its\n // siblings (`OrgPortTag` had zero resolvers before the re-cut).\n orgPort: Context.get(adapters.value.context, OrgPortTag),\n ...(signer === undefined\n ? {}\n : {\n // Still hand-built: this adapter closes over the SIGNER, which is\n // derived from the bootstrap the graph resolves, so it cannot be a\n // layer entry until the signer moves ahead of composition. ADR-0019\n // P3 / L1 owns that; noted rather than faked.\n organizationSetup: new ConvexOrganizationSetupAdapter({\n convex: adapters.value.ports.convexCall,\n signer,\n chainId: adapters.value.bootstrap.chainId,\n }),\n }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n invokeTimeoutMs: input.invokeTimeoutMs ?? DEFAULT_INVOKE_TIMEOUT_MS,\n effectRunner: {\n runSync: Effect.runSyncWith(adapters.value.context as Context.Context<never>),\n runPromise: Effect.runPromiseWith(adapters.value.context as Context.Context<never>),\n },\n });\n const upstreamClose = adapters.value.close;\n const close = idempotentClose(async () => {\n try {\n if (\"resetSession\" in (signer ?? {})) {\n (signer as OpenfortBrowserSigner).resetSession();\n }\n } finally {\n await Promise.all([client._internal.close?.(), upstreamClose()]);\n }\n });\n const value = {\n ...client,\n _internal: {\n ...client._internal,\n close,\n },\n };\n return { ok: true, value };\n } catch (cause) {\n await adapters.value.close().catch(() => undefined);\n return observeFailedResult(\n { ok: false, error: toPublicError(cause, \"createCapxulClient\") } as const,\n input.observation,\n \"createCapxulClient\",\n );\n }\n}\n\nfunction validateCreateCapxulClientInput(input: ProductionAdapterInput): CapxulResult<void> {\n const runtime = input.runtime ?? detectRuntime();\n if (\n (input.requirement ?? \"none\") === \"deployed\" &&\n input.signer === undefined &&\n runtime !== \"browser\"\n ) {\n return {\n ok: false,\n error: Errors.invalidInput(\"signer\", 'required when requirement is \"deployed\"'),\n };\n }\n return { ok: true, value: undefined };\n}\n\ntype ResolvedInput = {\n readonly publishableKey: ReturnType<typeof toPublishableKey>;\n readonly origin?: ReturnType<typeof toAllowedOrigin>;\n readonly bootstrapBaseUrl: string;\n readonly runtime: ProductionRuntime;\n};\n\nfunction resolveInput(input: ProductionAdapterInput): CapxulResult<ResolvedInput> {\n try {\n const runtime = input.runtime ?? detectRuntime();\n const publishableKey = toPublishableKey(input.publishableKey);\n const origin =\n input.origin === undefined\n ? runtime === \"browser\"\n ? toAllowedOrigin(derivedBrowserOrigin(runtime))\n : undefined\n : toAllowedOrigin(input.origin);\n return {\n ok: true,\n value: {\n publishableKey,\n ...(origin === undefined ? {} : { origin }),\n bootstrapBaseUrl: normalizeHttpUrl(\n \"bootstrapBaseUrl\",\n input.bootstrapBaseUrl ??\n (runtime === \"browser\"\n ? derivedBrowserOrigin(runtime)\n : DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL),\n ),\n runtime,\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\n/**\n * Address of the Capxul client-relay ingest endpoint (Pipe 1, issue #877). The\n * HTTP router that serves `/v1/client/observe` lives on the deployment's\n * `.convex.site` host, while the bootstrap-resolved `convexUrl` is the sibling\n * `.convex.cloud` (WebSocket/query) host — the same deterministic pairing\n * `mintQuickstartKey` inverts. For any standard Convex deployment (including\n * production) rewriting the suffix targets the router directly with no host\n * proxy, so it is the primary rule.\n *\n * `siteBaseUrl` is deliberately NOT the primary source: it is an app-configured\n * field that defaults to a placeholder (`https://capxul.local`, see\n * `credentials/applications.ts`) for registered applications, so trusting it\n * outright would POST to a dead host for the common case. It is only consulted\n * as a fallback for a custom-domain `convexUrl` (no deterministic `.convex.site`\n * sibling) when it carries a real, non-placeholder origin.\n */\nexport function deriveObserveIngestUrl(bootstrap: BootstrapResolution): string {\n const convexUrl = bootstrap.convexUrl.replace(/\\/+$/, \"\");\n if (convexUrl.endsWith(\".convex.cloud\")) {\n return `${convexUrl.replace(/\\.convex\\.cloud$/, \".convex.site\")}/v1/client/observe`;\n }\n const site = usableSiteOrigin(bootstrap.siteBaseUrl) ?? convexUrl;\n return `${site.replace(/\\/+$/, \"\")}/v1/client/observe`;\n}\n\n/** A configured `siteBaseUrl` usable as a router host, or `undefined` if it is the placeholder. */\nfunction usableSiteOrigin(siteBaseUrl: string): string | undefined {\n try {\n const url = new URL(siteBaseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n if (url.hostname === \"capxul.local\") return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n\nfunction detectRuntime(): ProductionRuntime {\n const globalAny = globalThis as {\n readonly window?: unknown;\n readonly document?: unknown;\n };\n return globalAny.window !== undefined || globalAny.document !== undefined ? \"browser\" : \"node\";\n}\n\nfunction derivedBrowserOrigin(runtime: ProductionRuntime): string {\n if (runtime !== \"browser\") {\n throw Errors.invalidInput(\"origin\", \"required outside browser runtime\");\n }\n const globalAny = globalThis as { readonly location?: { readonly origin?: string } };\n if (typeof globalAny.location?.origin === \"string\" && globalAny.location.origin.length > 0) {\n return globalAny.location.origin;\n }\n throw Errors.invalidInput(\"origin\", \"required when browser location is unavailable\");\n}\n\n/**\n * Browser local dev serves `/api/auth` via the Vite proxy on `window.location.origin`\n * while bootstrap returns the remote Convex site host. Openfort wallet setup reads\n * Better Auth cookies from `get-session` — those only attach on the same origin the\n * OTP flow used, so rewrite when hosts differ.\n */\nexport function resolveBrowserAuthBaseUrl(input: {\n readonly bootstrapAuthBaseUrl: string;\n readonly runtime: ProductionRuntime;\n readonly override?: string;\n}): string {\n if (input.override !== undefined) {\n return normalizeHttpUrl(\"authBaseUrl\", input.override);\n }\n const bootstrapUrl = normalizeHttpUrl(\"authBaseUrl\", input.bootstrapAuthBaseUrl);\n if (input.runtime !== \"browser\") {\n return bootstrapUrl;\n }\n try {\n const origin = derivedBrowserOrigin(input.runtime);\n const localAuthBase = normalizeHttpUrl(\"authBaseUrl\", `${origin}/api/auth`);\n const remoteAuthBase = bootstrapUrl.endsWith(\"/api/auth\")\n ? bootstrapUrl\n : `${bootstrapUrl}/api/auth`;\n if (new URL(remoteAuthBase).host !== new URL(localAuthBase).host) {\n return localAuthBase;\n }\n return bootstrapUrl;\n } catch {\n return bootstrapUrl;\n }\n}\n\nfunction resolveRuntimeUrls(\n bootstrap: BootstrapResolution,\n runtime: ProductionRuntime,\n authBaseUrlOverride?: string,\n): CapxulResult<{ readonly authBaseUrl: string; readonly convexUrl: string }> {\n try {\n return {\n ok: true,\n value: {\n authBaseUrl: resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: bootstrap.authBaseUrl,\n runtime,\n ...(authBaseUrlOverride === undefined ? {} : { override: authBaseUrlOverride }),\n }),\n convexUrl: normalizeHttpUrl(\"convexUrl\", bootstrap.convexUrl),\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nasync function runBootstrap(\n effect: ReturnType<BootstrapPort[\"resolve\"]>,\n): Promise<CapxulResult<BootstrapResolution>> {\n const result = await Effect.runPromise(Effect.result(effect));\n if (Result.isSuccess(result)) return { ok: true, value: result.success };\n return { ok: false, error: toPublicError(result.failure, \"bootstrap.resolve\") };\n}\n\n/**\n * Bootstrap-event props. `runtime` used to be called `capxulEnv`, which was a\n * name collision, not a value: it carried \"browser\"/\"node\", never an\n * environment. ADR-0020 A1 makes `capxul_env` the environment discriminator\n * every synced artifact filters on, so this field was renamed to what it\n * actually is. `sdk_version` follows the canon envelope spelling.\n */\nfunction bootstrapTelemetryEnvelope(\n input: ProductionAdapterInput,\n resolvedInput: ResolvedInput,\n): {\n readonly runtime: ProductionRuntime;\n readonly env: AccountRequirement;\n readonly origin?: string;\n readonly sdk_version: string;\n} {\n return {\n runtime: resolvedInput.runtime,\n env: input.requirement ?? \"none\",\n ...(resolvedInput.origin === undefined ? {} : { origin: resolvedInput.origin }),\n sdk_version: SDK_VERSION,\n };\n}\n\nasync function emitBootstrapTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(telemetry.emit(event).pipe(Effect.catchDefect(() => Effect.void)));\n}\n\nfunction normalizeHttpUrl(field: string, raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nfunction toPublicError(cause: unknown, operation: string): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const publicError = (cause as { readonly publicError?: unknown }).publicError;\n if (publicError instanceof CapxulError) return publicError;\n const nestedCause = (cause as { readonly cause?: unknown }).cause;\n if (nestedCause instanceof CapxulError) return nestedCause;\n }\n return Errors.providerError(\"sdk-production-adapters\", operation, cause);\n}\n\nfunction idempotentClose(close: () => Promise<void>): ProductionAdapterClose {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n}\n","import {\n createCapxulClient as createCapxulClientFromProductionAdapters,\n type CapxulClientInput,\n} from \"../production\";\nimport type { CapxulClient } from \"./create-capxul-client\";\nimport type { CapxulResult } from \"./types\";\n\n/** Consumer-facing factory — accepts only production-meaningful inputs (#326). */\nexport async function createCapxulClient(\n input: CapxulClientInput,\n): Promise<CapxulResult<CapxulClient>> {\n return createCapxulClientFromProductionAdapters(input);\n}\n","// Host-facing SUCCESS-telemetry seam — the twin of `fromPostHog` in\n// `observation.ts` (which covers failures). The host passes its own\n// already-initialized posthog-js client; the SDK's rich success events\n// (`org_created`, `faucet_requested`, `transfer_requested`, …) are delivered to\n// it and, because it is the same client the consumer called `identify()` on,\n// they attach to the browser person and light up the journey funnel.\n//\n// The SDK never imports, initializes, configures, or owns posthog. Event props\n// are PII-redacted by the shared `PostHogTelemetryAdapter`; the host-owned\n// context is sanitized with the SAME `sanitizeObservationContext` the failure\n// path uses; and the `$exception` `details` blob (amounts / org names / account\n// IDs — the one field the shared redactor has no rule for) is dropped at this\n// host boundary — so no addresses, names, or amounts reach the host sink\n// (infra#1037).\n\nimport { sanitizeObservationContext } from \"@capxul/wire/observation-context\";\nimport { stampTelemetryEnvelope, type CapxulEnv } from \"@capxul/observability\";\n\nimport { PostHogTelemetryAdapter } from \"../adapters/telemetry/PostHogTelemetryAdapter\";\nimport { observationContextProps, type ObservationContext } from \"../observation\";\nimport type { TelemetryPort, TelemetryProps } from \"../ports/telemetry\";\n\n/**\n * Drop props that must never cross to a host-owned external sink. Today that is\n * the `$exception` `details` blob: `captureException` serializes\n * `CapxulError.details` (e.g. `{ asset, available, required }`, `{ name }`,\n * `{ accountId }` — errors.ts) into it, and the shared redactor has no\n * `$exception` rule, so it is stripped here at the boundary (infra#1037). The\n * safe fields (error code, operation, failure_mode, the fixed leak-safe message,\n * stack frames) are preserved.\n */\nfunction stripHostUnsafeProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n const { details: _details, ...safe } = props;\n return safe;\n}\n\n/**\n * The subset of a posthog-js client the seam calls. `identify` / `group` /\n * `reset` are optional — a host that only wants event capture can omit them.\n */\nexport interface PostHogTelemetryClient {\n capture(event: string, properties?: Record<string, unknown>): unknown;\n identify?(distinctId: string, properties?: Record<string, unknown>): unknown;\n group?(groupType: string, groupKey: string, properties?: Record<string, unknown>): unknown;\n reset?(): unknown;\n}\n\nexport interface PostHogTelemetryOptions {\n /** Consent / kill-switch seam. Defaults to enabled. */\n readonly enabled?: boolean | (() => boolean);\n /** Host environment stamped on every SDK-owned product event. */\n readonly capxulEnv?: CapxulEnv;\n /** Host-owned correlation context, merged (sanitized) onto every captured event. */\n readonly context?: ObservationContext | (() => ObservationContext | undefined);\n}\n\n/**\n * Adapt the host's already-initialized posthog-like client into a\n * `TelemetryPort` for the `telemetry` prop / input. This port SUPPLANTS the\n * SDK's no-op default telemetry sink (`production.ts` binds it via\n * `Layer.succeed`, not `compose` — there is no client-side success relay to\n * compose with); it is additive to Capxul's backend first-party record and\n * never owns the client.\n */\nexport function telemetryFromPostHog(\n client: PostHogTelemetryClient | null | undefined,\n options: PostHogTelemetryOptions = {},\n): TelemetryPort {\n const active = (): boolean => {\n if (client === null || client === undefined) return false;\n try {\n return typeof options.enabled === \"function\" ? options.enabled() : (options.enabled ?? true);\n } catch {\n return false;\n }\n };\n\n const contextProps = (): Record<string, string> => {\n let raw: ObservationContext | undefined;\n try {\n raw = typeof options.context === \"function\" ? options.context() : options.context;\n } catch {\n return {};\n }\n // Same sanitizer + snake_case mapping as the failure path, so success and\n // failure events carry identical correlation fields.\n return observationContextProps(sanitizeObservationContext(raw));\n };\n\n // Reuse the existing adapter for per-event PII redaction, prop cloning, and\n // fire-and-forget isolation; the deps here add consent gating + context merge.\n return new PostHogTelemetryAdapter({\n capture: (name, props) => {\n if (!active() || client === null || client === undefined) return;\n const event = stampTelemetryEnvelope(\n { name, props },\n { capxul_env: options.capxulEnv ?? \"unknown\", producer: \"sdk\" },\n );\n client.capture(name, { ...stripHostUnsafeProps(event.props), ...contextProps() });\n },\n // NOTE: identify traits / group properties are forwarded structurally and are\n // NOT run through the per-event redactor the capture arm relies on. Callers\n // MUST pre-minimize them (send `email_domain`, never a raw email). Do not\n // pass raw PII here — it would reach the host un-redacted.\n identify: (input) => {\n if (!active() || client?.identify === undefined) return;\n client.identify(input.distinctId, { ...input.traits, ...input.properties });\n },\n group: (input) => {\n if (!active() || client?.group === undefined) return;\n client.group(\n input.groupType,\n input.groupKey,\n input.properties === undefined ? undefined : { ...input.properties },\n );\n },\n reset: () => {\n if (!active() || client?.reset === undefined) return;\n client.reset();\n },\n });\n}\n"],"mappings":";;;;;;;;;;;AA8CA,SAAgB,+BAA+B,OAE3B;CAClB,MAAM,UAAU,oBAAoB,MAAM,UAAU;CACpD,MAAM,UAAU,UAAU,QAAQ,OAAO;CACzC,OAAO;EACL,QAAQ;EACR,MAAM,aAAa;GACjB,OAAO;IAAE,IAAI;IAAM,OAAO;GAAQ;EACpC;EACA,MAAM,mBAAmB;GACvB,OAAO;IAAE,IAAI;IAAM,OAAO;GAAQ;EACpC;CACF;AACF;AAEA,SAAgB,uBAAuB,OAEnB;CAelB,IAAI,gBAAgC;CACpC,IAAI,WAAkD;CAEtD,MAAM,aAAa,YAA4C;EAC7D,IAAI,kBAAkB,MACpB,OAAO;GAAE,IAAI;GAAM,OAAO;EAAc;EAE1C,IAAI,aAAa,MACf,OAAO;EAET,YAAY,YAAY;GACtB,IAAI;IAEF,MAAM,QAAQ,aAAa,MADJ,MAAM,SAAS,QAAQ,EAAE,QAAQ,eAAe,CAAC,CACrC;IACnC,IAAI,UAAU,MACZ,OAAO;KAAE,IAAI;KAAO,OAAO,OAAO,oBAAoB,iBAAiB;IAAE;IAE3E,MAAM,UAAU,UAAU,KAAK;IAC/B,gBAAgB;IAChB,OAAO;KAAE,IAAI;KAAM,OAAO;IAAQ;GACpC,SAAS,KAAK;IACZ,OAAO;KACL,IAAI;KACJ,OAAO,OAAO,cAAc,WAAW,gBAAgB,GAAG;IAC5D;GACF,UAAU;IACR,WAAW;GACb;EACF,GAAG;EACH,OAAO;CACT;CACA,OAAO;EACL,QAAQ;EACR;EACA,MAAM,mBAAmB;GACvB,OAAO;IACL,IAAI;IACJ,OAAO,OAAO,eAAe,0BAA0B,kBAAkB;GAC3E;EACF;CACF;AACF;AAEA,SAAS,aAAa,OAA+B;CACnD,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO;CAClC,MAAM,QAAQ,MAAM;CACpB,O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f;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["EVM_ADDRESS_HEX","ECDSA_SIGNATURE_HEX","SAFE_OP_DIGEST_HEX","recoverRawDigestSigner","withSignal","DEFAULT_JWT_LIFETIME_S","decodeJwtExp","authSessionFromBetterAuth","safeJson","isAbortError","mapFetchError","#client","#tokenProvider","#applicationId","#observation","#observedArgs","#convex","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#chainId","#runMutation","#runQuery","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#readTreasuryWire","#convex","#signer","#chainId","#fns","#lifecycleAction","sdkPackageJson.version","createCapxulClient","createCapxulClientFromProductionAdapters"],"sources":["../src/surface/account-providers.ts","../src/signer.ts","../src/dev-signer.ts","../src/ports/embedded-wallet.ts","../src/openfort-embedded-signer.ts","../../observability/src/engineering.ts","../src/adapters/auth-client/resolve-auth-url.ts","../src/internal/observation-http.ts","../src/adapters/auth-client/BetterAuthBrowserAdapter.ts","../src/adapters/auth-client/cookie-jar.ts","../src/adapters/auth-client/BetterAuthNodeAdapter.ts","../src/adapters/bootstrap/HttpBootstrapAdapter.ts","../src/adapters/clock/SystemClockAdapter.ts","../src/adapters/convex-call/ConvexCallAdapter.ts","../src/adapters/identity/ConvexIdentityAdapter.ts","../src/adapters/account-read/ConvexAccountAdapter.ts","../src/adapters/sub-account/ConvexSubAccountAdapter.ts","../src/adapters/smart-account/ConvexSmartAccountAdapter.ts","../src/ports/org.ts","../src/adapters/org/parse.ts","../src/adapters/org/ConvexOrganizationAdapter.ts","../src/adapters/org/ConvexOrganizationSetupAdapter.ts","../src/adapters/diagnostic/ConsoleDiagnosticAdapter.ts","../src/openfort/create-openfort-browser-signer.ts","../src/host-observability.ts","../src/production.ts","../src/surface/create-capxul-client-from-production.ts"],"sourcesContent":["import { Errors } from \"@capxul/config\";\nimport { toAddress, type Address } from \"@capxul/types\";\nimport type { Account as ViemAccount, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport type AccountProviderSource = \"local-private-key\" | \"openfort-embedded\" | \"injected-eip1193\";\n\nexport type AccountRequirement = \"none\" | \"counterfactual\" | \"deployed\";\n\nexport interface AccountProvider {\n readonly source: AccountProviderSource;\n /**\n * Resolve the signer's EVM address.\n *\n * @determinism MUST return the same `Address` across calls for the\n * lifetime of a single provider instance — the SDK-level deploy mutex\n * keys on `(authUserId, safeAddress)` where `safeAddress` is computed\n * from `getAddress()`'s result before the port's `prepare()` round-trip.\n * If two successive calls returned different addresses, concurrent\n * `deploySafe` invocations would compute different mutex keys and\n * bypass dedup, defeating the mutex.\n *\n * The two sanctioned providers both satisfy this invariant:\n * - `localPrivateKeyAccountProvider` — derives once from the key\n * - `eip1193AccountProvider` — reads `eth_accounts` (idempotent once\n * the wallet is connected; consumer is responsible for connection)\n *\n * The Openfort embedded path no longer needs a provider: the\n * `openfortEmbeddedSigner` `CapxulSigner` caches its own address and the\n * deploy is backend-orchestrated (backend-orchestrated-deploy.md).\n *\n * Custom providers MUST honor this contract.\n */\n getAddress(): Promise<CapxulResult<Address>>;\n getDeployAccount(): Promise<CapxulResult<ViemAccount>>;\n}\n\nexport interface Eip1193Provider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\nexport function localPrivateKeyAccountProvider(input: {\n readonly privateKey: Hex;\n}): AccountProvider {\n const account = privateKeyToAccount(input.privateKey);\n const address = toAddress(account.address);\n return {\n source: \"local-private-key\",\n async getAddress() {\n return { ok: true, value: address };\n },\n async getDeployAccount() {\n return { ok: true, value: account };\n },\n };\n}\n\nexport function eip1193AccountProvider(input: {\n readonly provider: Eip1193Provider;\n}): AccountProvider {\n // Cache the first successful address to honor the determinism contract on\n // `AccountProvider.getAddress` (see JSDoc above). Without this cache, a user\n // switching accounts in their browser wallet mid-flow would produce a\n // different `Address` on successive calls, defeating the deploy mutex.\n // Errors are intentionally NOT cached — transient wallet-not-connected or\n // RPC failures must remain retryable.\n //\n // `inFlight` memoizes the in-progress request so that concurrent first\n // callers (e.g. two `await provider.getAddress()` issued in parallel before\n // either resolves) share the same `eth_accounts` round-trip and the same\n // resolved Address. Without it, both calls would race, both would hit the\n // wallet, and the second resolver could overwrite `cachedAddress` with a\n // stale-vs-fresh wallet read — defeating determinism even with the resolved\n // cache. Cleared in `finally` so the lane stays retryable after errors.\n let cachedAddress: Address | null = null;\n let inFlight: Promise<CapxulResult<Address>> | null = null;\n\n const getAddress = async (): Promise<CapxulResult<Address>> => {\n if (cachedAddress !== null) {\n return { ok: true, value: cachedAddress };\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const accounts = await input.provider.request({ method: \"eth_accounts\" });\n const first = firstAccount(accounts);\n if (first === null) {\n return { ok: false, error: Errors.smartAccountMissing(\"eip1193-account\") };\n }\n const address = toAddress(first);\n cachedAddress = address;\n return { ok: true, value: address };\n } catch (err) {\n return {\n ok: false,\n error: Errors.providerError(\"eip1193\", \"eth_accounts\", err),\n };\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n return {\n source: \"injected-eip1193\",\n getAddress,\n async getDeployAccount() {\n return {\n ok: false,\n error: Errors.notImplemented(\"Eip1193AccountProvider\", \"getDeployAccount\"),\n };\n },\n };\n}\n\nfunction firstAccount(value: unknown): string | null {\n if (!Array.isArray(value)) return null;\n const first = value[0];\n return typeof first === \"string\" ? first : null;\n}\n","// CapxulSigner — the consumer-held key boundary (backend-orchestrated-deploy.md).\n//\n// The backend orchestrates the Safe deployment (build + gas + paymaster + submit)\n// but never holds the user's key. The consumer supplies a `CapxulSigner` that\n// signs exactly one thing: the EIP-712 `SafeOp` digest the backend returns for\n// the prepared deployment UserOperation. `safe4337SafeOpDigest` (@capxul/config)\n// computes that digest; this signer produces the owner signature; the backend\n// packs + submits. Verified equivalent to permissionless's inline signing in\n// `src/__tests__/safe4337-split-sign.test.ts`.\n//\n// Security note: the browser signer uses `eth_sign`, which can sign arbitrary\n// bytes. In the backend-orchestrated flow, `CapxulSigner` signs only the\n// backend-provided SafeOp digest, so consumers must trust the backend that\n// constructs the UserOperation and computes that digest. A malicious backend\n// could ask the wallet to sign a harmful digest; prefer typed structured\n// signing when that flow exists, and only enable raw-hash signing for trusted\n// Capxul deployments.\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport type { AccountProviderSource } from \"./surface/account-providers\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface CapxulDigestSigner {\n /**\n * Sign the EIP-712 `SafeOp` digest the backend returns for the prepared\n * deployment UserOperation. Returns the raw 65-byte ECDSA signature; the\n * backend packs `validAfter|validUntil|signature`.\n */\n signUserOpHash(hash: Hex): Promise<Hex>;\n}\n\nexport interface CapxulSigner extends CapxulDigestSigner {\n /**\n * Signer kind — surfaced on the `accountProviderReady` status so the\n * readiness ladder reports which signer the consumer wired.\n */\n readonly source: AccountProviderSource;\n /** Owner EOA address — the Safe's single owner. */\n getAddress(): Promise<Address>;\n}\n\n/** Minimal EIP-1193 surface an injected browser wallet exposes. */\nexport interface Eip1193RequestProvider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\n/**\n * Browser `CapxulSigner` backed by an injected EIP-1193 wallet (MetaMask, etc.).\n * Signs the SafeOp digest via `eth_sign`, then verifies the returned signature\n * recovers the selected account against that raw digest. Wallets that prefix\n * `eth_sign` payloads are rejected before the backend submits an invalid SafeOp.\n * The node key signer lives in `@capxul/sdk/node` (`localPrivateKeySigner`).\n */\nexport function injectedWalletSigner(provider: Eip1193RequestProvider): CapxulSigner {\n const resolveAddress = async (): Promise<Address> => {\n const accounts = await provider.request({ method: \"eth_requestAccounts\" });\n const first = Array.isArray(accounts) ? accounts[0] : undefined;\n if (typeof first !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned no accounts\");\n }\n if (!EVM_ADDRESS_HEX.test(first)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid address format\");\n }\n return toAddress(first);\n };\n return {\n source: \"injected-eip1193\",\n getAddress: resolveAddress,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"injectedWalletSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: unknown;\n try {\n signature = await provider.request({ method: \"eth_sign\", params: [address, hash] });\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: eth_sign failed; enable raw-hash signing for deployment (${detail})`,\n { cause },\n );\n }\n if (typeof signature !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned a non-string signature\");\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid signature format\");\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"injectedWalletSigner: wallet signature did not recover the selected account for the raw SafeOp digest; use a raw-hash-capable wallet or @capxul/sdk/node localPrivateKeySigner for deployed flows\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","// devPrivateKeySigner — browser-safe dev-mode `CapxulSigner` (dogfood only).\n//\n// Derives a deterministic throwaway EOA per email: privateKey =\n// keccak256(utf8(seed + normalizedEmail)). Re-login with the same email\n// reproduces the same signer, so binding resolution (signerAddress-hint\n// path) and the account lane stay coherent without Openfort. The seed is a\n// dev-only secret for unfunded keys; never fund these accounts.\n//\n// The signer is constructed before login, so the email is resolved lazily:\n// at first use it reads the cached `AuthSession` the SDK wrote to browser\n// localStorage (`capxul.session`, BrowserAuthCacheAdapter) — or uses the\n// explicit `email` override (tests / non-browser harnesses).\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { keccak256, stringToHex, type Hex } from \"viem\";\nimport { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\n\nimport { BASE_SEPOLIA_CHAIN_ID, Errors, normalizeBindingEmail } from \"@capxul/config\";\n\nimport type { BrowserStorageShape } from \"./adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport type { CapxulResult } from \"./surface/types\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst SESSION_KEY = \"capxul.session\";\n\n/**\n * Chains a `local-private-key` signer may sign on. Base Sepolia only, and this\n * list does not grow without an ADR: the keys are deterministic throwaways\n * derived from a shared seed (see `deriveDevPrivateKey`), so anyone holding\n * the seed holds every account. A dev key on a value-bearing chain is a\n * custody incident, not a config mistake.\n */\nconst DEV_KEY_ALLOWED_CHAIN_IDS: readonly number[] = [BASE_SEPOLIA_CHAIN_ID];\n\n/**\n * Testnet fence for the dev-key signing lane (#1149, folds #1065; ADR-0018 P9\n * human/Openfort vs agent/dev-key split). Call it wherever a signer first\n * meets a resolved chain; it refuses before the signer can be used.\n *\n * Only `local-private-key` signers are fenced — Openfort-embedded and injected\n * wallets carry their own custody and are the sanctioned human paths.\n */\nexport function assertDevKeySignerIsTestnetOnly(\n signer: { readonly source?: string } | undefined,\n chainId: number,\n): CapxulResult<void> {\n if (signer?.source !== \"local-private-key\") return { ok: true, value: undefined };\n if (DEV_KEY_ALLOWED_CHAIN_IDS.includes(chainId)) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.invalidInput(\n \"signer\",\n `dev-key signer is testnet-only: chain ${chainId} is not allowed (expected ${DEV_KEY_ALLOWED_CHAIN_IDS.join(\", \")})`,\n ),\n };\n}\n\nexport interface DevPrivateKeySignerInput {\n /** Dev-only derivation seed (e.g. `VITE_CAPXUL_DEV_SIGNER_SEED`). Throwaway keys only. */\n readonly seed: string;\n /** Explicit email — skips the auth-cache lookup (tests, node harnesses). */\n readonly email?: string;\n /** Storage holding the cached session. Defaults to browser `localStorage`. */\n readonly storage?: BrowserStorageShape;\n}\n\n/** Deterministic dev private key for an email under a seed. Exported for probes. */\nexport function deriveDevPrivateKey(seed: string, email: string): Hex {\n return keccak256(stringToHex(seed + normalizeBindingEmail(email)));\n}\n\nfunction readSessionEmail(storage: BrowserStorageShape | undefined): string {\n const resolved =\n storage ??\n (globalThis as unknown as { window?: { localStorage?: BrowserStorageShape } }).window\n ?.localStorage;\n if (resolved === undefined) {\n throw new Error(\n \"devPrivateKeySigner: no browser localStorage available and no explicit email supplied\",\n );\n }\n const raw = resolved.getItem(SESSION_KEY);\n if (raw === null) {\n throw new Error(\n \"devPrivateKeySigner: no cached session yet — sign in before the account lane uses the signer\",\n );\n }\n let email: unknown;\n try {\n email = (JSON.parse(raw) as { email?: unknown }).email;\n } catch {\n throw new Error(\"devPrivateKeySigner: cached session is not valid JSON\");\n }\n if (typeof email !== \"string\" || email.length === 0) {\n throw new Error(\"devPrivateKeySigner: cached session has no email\");\n }\n return email;\n}\n\n/**\n * Browser-safe dev signer. Lazy: the email (and so the key) is resolved at\n * each `getAddress()` / `signUserOpHash()` from the cached session, so the\n * same signer instance follows whichever user is signed in.\n */\nexport function devPrivateKeySigner(input: DevPrivateKeySignerInput): CapxulSigner {\n if (input.seed.trim().length === 0) {\n throw new Error(\"devPrivateKeySigner: seed must be non-empty\");\n }\n const accounts = new Map<string, PrivateKeyAccount>();\n const resolveAccount = (): PrivateKeyAccount => {\n const email = normalizeBindingEmail(input.email ?? readSessionEmail(input.storage));\n const cached = accounts.get(email);\n if (cached !== undefined) return cached;\n const account = privateKeyToAccount(deriveDevPrivateKey(input.seed, email));\n accounts.set(email, account);\n return account;\n };\n return {\n source: \"local-private-key\",\n async getAddress(): Promise<Address> {\n return toAddress(resolveAccount().address);\n },\n async signUserOpHash(hash: Hex): Promise<Hex> {\n // Raw digest signing — same semantics as `localPrivateKeySigner` in\n // `@capxul/sdk/node`: no EIP-191 prefix on the SafeOp digest.\n return resolveAccount().sign({ hash });\n },\n };\n}\n","import type { Hex } from \"viem\";\n\n/**\n * Minimal Openfort embedded-wallet surface for hermetic tests and\n * `openfortEmbeddedSigner`. Keeps Convex / Shield secrets out of the SDK.\n */\nexport interface OpenfortEmbeddedWalletPort {\n /** Owner EOA address — must stay stable for the lifetime of this port. */\n getAddress(): Promise<string>;\n /**\n * Sign a 32-byte SafeOp digest without EIP-191 prefixing (backend-orchestrated\n * deploy contract).\n */\n signRawDigest(hash: Hex): Promise<Hex>;\n}\n\n/** Openfort `embeddedWallet` subset used by `openfortEmbeddedWalletPort`. */\nexport interface OpenfortEmbeddedWalletApi {\n get(): Promise<{ readonly address: string }>;\n signMessage(\n message: string | Uint8Array,\n options?: { readonly hashMessage?: boolean; readonly arrayifyMessage?: boolean },\n ): Promise<string>;\n}\n\nexport function openfortEmbeddedWalletPort(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureReady?: () => Promise<void>;\n}): OpenfortEmbeddedWalletPort {\n return {\n async getAddress() {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n const account = await input.embeddedWallet.get();\n return account.address;\n },\n async signRawDigest(hash) {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n // The digest must cross the Openfort iframe RPC as the 0x-hex STRING\n // with BOTH flags off — openfort-js's own raw-hash path\n // (walletHelpers: `signer.sign(hash, false, false)`) is the canon.\n // A Uint8Array mangles to UTF-8 across the RPC, and arrayifyMessage\n // triggers a double-arrayify inside the iframe; either way signing\n // dies with \"invalid arrayify value\" (first live signing proof,\n // mcp-stretch S4). hashMessage stays off: raw SafeOp digest, no\n // EIP-191 prefix.\n return (await input.embeddedWallet.signMessage(hash, {\n hashMessage: false,\n arrayifyMessage: false,\n })) as Hex;\n },\n };\n}\n","import { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport {\n openfortEmbeddedWalletPort,\n type OpenfortEmbeddedWalletApi,\n type OpenfortEmbeddedWalletPort,\n} from \"./ports/embedded-wallet\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface OpenfortEmbeddedSignerInput {\n readonly wallet: OpenfortEmbeddedWalletPort;\n}\n\n/** Browser helper: wrap an initialized Openfort `embeddedWallet` API. */\nexport function openfortEmbeddedSignerFromWallet(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureWalletReady?: () => Promise<void>;\n}): OpenfortEmbeddedSigner {\n return openfortEmbeddedSigner({\n wallet: openfortEmbeddedWalletPort({\n embeddedWallet: input.embeddedWallet,\n ...(input.ensureWalletReady === undefined ? {} : { ensureReady: input.ensureWalletReady }),\n }),\n });\n}\n\n/**\n * Browser `CapxulSigner` backed by an Openfort embedded wallet (#335).\n * Signs the backend's SafeOp digest via raw `signMessage` (no EIP-191 prefix)\n * and verifies recovery before the backend submits.\n */\nexport type OpenfortEmbeddedSigner = CapxulSigner & {\n /** Drop cached `getAddress()` so the next read hits the embedded wallet again. */\n readonly resetAddressCache: () => void;\n};\n\nexport function openfortEmbeddedSigner(input: OpenfortEmbeddedSignerInput): OpenfortEmbeddedSigner {\n let cachedAddress: Address | null = null;\n let addressInFlight: Promise<Address> | null = null;\n // Bumped on every reset so a resolve that started before the reset cannot\n // win the race and repopulate the cache with the now-stale session address.\n let cacheEpoch = 0;\n\n const resetAddressCache = (): void => {\n cacheEpoch += 1;\n cachedAddress = null;\n addressInFlight = null;\n };\n\n const resolveAddress = async (): Promise<Address> => {\n if (cachedAddress !== null) {\n return cachedAddress;\n }\n if (addressInFlight !== null) {\n return addressInFlight;\n }\n const epoch = cacheEpoch;\n addressInFlight = (async () => {\n try {\n const raw = await input.wallet.getAddress();\n if (!EVM_ADDRESS_HEX.test(raw)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid address format\",\n );\n }\n const address = toAddress(raw);\n // A reset during this resolve invalidates the result — don't cache it.\n if (epoch === cacheEpoch) {\n cachedAddress = address;\n }\n return address;\n } finally {\n if (epoch === cacheEpoch) {\n addressInFlight = null;\n }\n }\n })();\n return addressInFlight;\n };\n\n return {\n source: \"openfort-embedded\",\n getAddress: resolveAddress,\n resetAddressCache,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"openfortEmbeddedSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: string;\n try {\n signature = await input.wallet.signRawDigest(hash);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: raw digest signing failed; ensure the embedded wallet is configured (${detail})`,\n { cause },\n );\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid signature format\",\n );\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"openfortEmbeddedSigner: signature did not recover the embedded wallet address for the raw SafeOp digest\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\n/**\n * Canonical name for the embedded-wallet `CapxulSigner` constructor\n * (backend-orchestrated-deploy.md). The embedded-wallet (passkey / Openfort)\n * member of the named constructor trio `localPrivateKeySigner` /\n * `injectedWalletSigner` / `embeddedSigner`. Takes the provider-agnostic\n * `OpenfortEmbeddedWalletPort` (getAddress + signRawDigest); the Openfort-API\n * convenience wrapper is `openfortEmbeddedSignerFromWallet`.\n */\nexport const embeddedSigner = openfortEmbeddedSigner;\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","import { Cause, Effect, Exit, Layer, Tracer } from \"effect\";\nimport { FetchHttpClient, Headers, HttpClient } from \"effect/unstable/http\";\n// Effect v4 deliberately marks the OTLP exporters unstable. This module is the\n// one quarantine seam: no producer imports these modules directly.\nimport {\n OtlpExporter,\n OtlpLogger,\n OtlpSerialization,\n OtlpTracer,\n} from \"effect/unstable/observability\";\n\nexport type EngineeringProducer = \"browser\" | \"server\";\nexport type EngineeringCapxulEnv = \"development\" | \"e2e\" | \"staging\" | \"production\";\n\nexport interface EngineeringTelemetryConfig {\n readonly host: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly capxulEnv: EngineeringCapxulEnv;\n readonly producer: EngineeringProducer;\n readonly sdkVersion: string;\n readonly serviceName?: string;\n}\n\nconst SAFE_TRACED_HEADER_NAMES = [\n \"content-length\",\n \"content-type\",\n \"traceparent\",\n \"tracestate\",\n \"x-request-id\",\n] as const;\n\nconst ENGINEERING_REDACTED_HEADER_NAMES: ReadonlyArray<string | RegExp> = Object.freeze([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n /auth|email|key|otp|secret|session|token|wallet/i,\n]);\n\nexport const traceHeaderFilter = (name: string): boolean =>\n SAFE_TRACED_HEADER_NAMES.includes(\n name.toLowerCase() as (typeof SAFE_TRACED_HEADER_NAMES)[number],\n );\n\nexport const postHogOtlpEndpoints = (host: string) => {\n const base = host.replace(/\\/+$/, \"\");\n return {\n logs: `${base}/i/v1/logs`,\n traces: `${base}/i/v1/traces`,\n } as const;\n};\n\nconst ENGINEERING_CAPXUL_ENVS = new Set<EngineeringCapxulEnv>([\n \"development\",\n \"e2e\",\n \"staging\",\n \"production\",\n]);\nconst ENGINEERING_PRODUCERS = new Set<EngineeringProducer>([\"browser\", \"server\"]);\nconst PUBLIC_POSTHOG_AUTHORIZATION = /^Bearer phc_[A-Za-z0-9_-]{1,191}$/u;\nconst SAFE_RESOURCE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._+@/-]{0,127}$/u;\n\nconst validateEngineeringTelemetryConfig = (\n config: EngineeringTelemetryConfig,\n): EngineeringTelemetryConfig => {\n let url: URL;\n try {\n url = new URL(config.host);\n } catch {\n throw new TypeError(\"engineering telemetry host must be an absolute HTTPS URL\");\n }\n if (\n url.protocol !== \"https:\" ||\n url.username.length > 0 ||\n url.password.length > 0 ||\n url.pathname !== \"/\" ||\n url.search.length > 0 ||\n url.hash.length > 0 ||\n !(url.hostname === \"posthog.com\" || url.hostname.endsWith(\".posthog.com\"))\n ) {\n throw new TypeError(\"engineering telemetry host must be a credential-free HTTPS origin\");\n }\n if (!ENGINEERING_CAPXUL_ENVS.has(config.capxulEnv)) {\n throw new TypeError(\"engineering telemetry capxulEnv is not canonical\");\n }\n if (!ENGINEERING_PRODUCERS.has(config.producer)) {\n throw new TypeError(\"engineering telemetry producer is not canonical\");\n }\n if (!SAFE_RESOURCE_VALUE.test(config.sdkVersion)) {\n throw new TypeError(\"engineering telemetry sdkVersion must be a bounded safe value\");\n }\n if (config.serviceName !== undefined && !SAFE_RESOURCE_VALUE.test(config.serviceName)) {\n throw new TypeError(\"engineering telemetry serviceName must be a bounded safe value\");\n }\n const headerEntries = Object.entries(config.headers);\n if (\n headerEntries.length !== 1 ||\n headerEntries[0]?.[0].toLowerCase() !== \"authorization\" ||\n !PUBLIC_POSTHOG_AUTHORIZATION.test(headerEntries[0]?.[1] ?? \"\")\n ) {\n throw new TypeError(\n \"engineering telemetry headers must contain exactly one public PostHog authorization token\",\n );\n }\n return {\n ...config,\n host: url.origin,\n headers: Object.freeze({ authorization: headerEntries[0][1] }),\n };\n};\n\nclass RedactedEngineeringSpanFailure extends Error {\n constructor() {\n super(\"Engineering operation failed\");\n this.name = \"RedactedEngineeringSpanFailure\";\n delete this.stack;\n }\n}\n\nconst REDACTED_SPAN_FAILURE = Exit.fail(new RedactedEngineeringSpanFailure());\n\n/** Preserve domain exits while preventing the OTLP serializer from seeing raw causes. */\nexport const makeLeakSafeEngineeringTracer = (delegate: Tracer.Tracer): Tracer.Tracer =>\n Tracer.make({\n span(options) {\n const span = delegate.span(options);\n const wrapped = Object.create(span) as Tracer.Span;\n Object.defineProperty(wrapped, \"end\", {\n configurable: false,\n enumerable: false,\n value: (endTime: bigint, exit: Exit.Exit<unknown, unknown>) =>\n span.end(\n endTime,\n Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)\n ? REDACTED_SPAN_FAILURE\n : exit,\n ),\n writable: false,\n });\n return wrapped;\n },\n ...(delegate.context === undefined ? {} : { context: delegate.context.bind(delegate) }),\n });\n\n/** Shared browser/server OTLP layer. OtlpLogger merges with incumbent loggers once. */\nexport const makeEngineeringTelemetryLayer = (config: EngineeringTelemetryConfig) => {\n const validated = validateEngineeringTelemetryConfig(config);\n const endpoints = postHogOtlpEndpoints(validated.host);\n const resource = {\n serviceName: validated.serviceName ?? \"capxul-sdk\",\n serviceVersion: validated.sdkVersion,\n attributes: {\n capxul_env: validated.capxulEnv,\n producer: validated.producer,\n sdk_version: validated.sdkVersion,\n },\n } as const;\n const tracing = Layer.effect(\n Tracer.Tracer,\n OtlpTracer.make({\n url: endpoints.traces,\n headers: validated.headers,\n resource,\n }).pipe(Effect.map(makeLeakSafeEngineeringTracer)),\n ).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));\n const logging = OtlpLogger.layer({\n url: endpoints.logs,\n headers: validated.headers,\n resource,\n mergeWithExisting: true,\n });\n const headerPolicy = Layer.merge(\n Layer.succeed(HttpClient.TracerHeaderFilter, traceHeaderFilter),\n Layer.succeed(Headers.CurrentRedactedNames, ENGINEERING_REDACTED_HEADER_NAMES),\n );\n return Layer.mergeAll(tracing, logging, headerPolicy).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n};\n","/** Join bootstrap `authBaseUrl` with a BetterAuth route without duplicating `/api/auth`. */\nexport function resolveAuthClientUrl(authBaseUrl: string, path: string): string {\n const base = authBaseUrl.replace(/\\/$/, \"\");\n if (base.endsWith(\"/api/auth\") && path.startsWith(\"/api/auth\")) {\n return `${base}${path.slice(\"/api/auth\".length)}`;\n }\n return `${base}${path}`;\n}\n","import {\n encodeObservationContextHeader,\n OBSERVATION_CONTEXT_HEADER,\n} from \"@capxul/wire/observation-context\";\n\nimport type { ObservationAdapter } from \"../observation\";\nimport { readInvocationObservation } from \"./invocation-observation\";\n\n/** Resolve one bounded pre-auth snapshot for an outbound SDK HTTP request. */\nexport function observationRequestHeaders(\n adapter: ObservationAdapter | undefined,\n source?: unknown,\n): Readonly<Record<string, string>> {\n if (adapter === undefined) return {};\n try {\n const invocation = readInvocationObservation(source);\n if (invocation !== undefined && !invocation.active) return {};\n const encoded = encodeObservationContextHeader(\n invocation === undefined ? adapter.resolveContext?.() : invocation.context,\n );\n return encoded === undefined ? {} : { [OBSERVATION_CONTEXT_HEADER]: encoded };\n } catch {\n return {};\n }\n}\n","// BetterAuthBrowserAdapter — TA3 production adapter for browser runtimes.\n// Aligned with W1/W2/W3/W6/W7 wire reality verified against\n// incredible-possum-990 (2026-05-19) using @convex-dev/better-auth@0.10.13.\n//\n// - W1 sendOtp POST /api/auth/email-otp/send-verification-otp\n// body `{email, type: \"sign-in\"}`\n// 200 `{success: true}` | 400 `{code, message}`\n// - W2 verifyOtp POST /api/auth/sign-in/email-otp\n// 200 `{token, user}` + Set-Cookie headers |\n// 400 `{code, message}` (OTP_EXPIRED, INVALID_OTP)\n// - W3 getSession GET /api/auth/get-session\n// 200 literal `null` body OR `{session, user}`\n// - W6 signOut POST /api/auth/sign-out body `\"{}\"`\n// (without body the server returns 500 — F11)\n// - W7 getConvexJwt GET /api/auth/convex/token\n// 200 `{token: <JWT>}`; decode `exp` for cache\n// eviction (Probe A: fresh JWT per call)\n//\n// Browser-runtime semantics: the browser fetch automatically attaches +\n// stores cookies for the same-origin domain. We send `credentials: \"include\"`\n// on requests that need cookies, but never read/write Set-Cookie ourselves —\n// that's the browser's job. The Node adapter takes a different path via\n// CookieJar (see BetterAuthNodeAdapter).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthBrowserAdapterDeps {\n readonly authBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n readonly emailVerified?: boolean;\n readonly name?: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface GetSessionBody {\n readonly session: { readonly id?: string; readonly token?: string; readonly expiresAt?: string };\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\n// Sentinel — a 15-min JWT lifetime per Probe A. Used when we can't decode\n// the `exp` claim from a malformed/opaque token (fixtures, defensive depth).\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n // Strip whitespace defensively (real JWTs don't have it; the fixture\n // builder's line-wrap can introduce some).\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = atob(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad);\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction mapBetterAuthError(\n operation: string,\n body: unknown,\n): ReturnType<typeof Errors.invalidInput | typeof Errors.providerError | typeof Errors.otpExpired> {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n const code = typeof errBody.code === \"string\" ? errBody.code : \"\";\n if (code === \"OTP_EXPIRED\") {\n return Errors.otpExpired();\n }\n if (code === \"INVALID_OTP\") {\n return Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\");\n }\n if (code === \"VALIDATION_ERROR\" || code === \"INVALID_EMAIL\") {\n return Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\");\n }\n }\n return Errors.providerError(\"better-auth\", operation, new Error(String(body)));\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthBrowserAdapter {\n private readonly authBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthBrowserAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...observationRequestHeaders(this.observation, input),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n if (res.status === 429) {\n return { ok: false, error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }) };\n }\n const body = await safeJson(res);\n // W1 errors: 400 with { code, message } shape — OTP_EXPIRED can't\n // appear on send; INVALID_EMAIL / VALIDATION_ERROR can.\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n const body = await safeJson(res);\n if (res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(\"unexpected 200 body\")),\n };\n }\n // W2 errors: structured 400 with `{ code, message }`.\n return { ok: false, error: mapBetterAuthError(\"verifyOtp\", body) };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n // W3 body is literal `null` OR a `{session, user}` object.\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<GetSessionBody>;\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n // Build a session synthetically — get-session doesn't return a\n // bearer token in the body (cookies carry it). For ports that\n // want a non-null AuthSession on success, we set token to the\n // session id if available.\n const token = okBody.session?.token ?? okBody.session?.id ?? \"session\";\n return { ok: true, value: authSessionFromBetterAuth(token, okBody.user) };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n // F11: BetterAuth REQUIRES a non-empty body + Content-Type:\n // application/json. Without it the route returns HTTP 500.\n headers: { \"Content-Type\": \"application/json\" },\n body: \"{}\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n // forceRefresh is observed by the caller (ConvexCallAdapter); the\n // bridge mints fresh on every call regardless (Probe A).\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthBrowserLayer(\n deps: BetterAuthBrowserAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthBrowserAdapter(deps)),\n );\n}\n","// Minimal in-tree cookie jar for the Node auth-client adapter (tactical\n// placeholder 4 resolution). Scope is tiny: set + replay via `Cookie`\n// header on subsequent requests, expiry tracking, scope-by-host.\n//\n// No `tough-cookie` dependency.\n\nexport interface ParsedCookie {\n readonly name: string;\n readonly value: string;\n readonly maxAgeSeconds: number | null;\n readonly expiresEpochMs: number | null;\n readonly path: string | null;\n readonly httpOnly: boolean;\n readonly secure: boolean;\n readonly sameSite: \"strict\" | \"lax\" | \"none\" | null;\n}\n\ninterface StoredCookie extends ParsedCookie {\n readonly storedAtEpochMs: number;\n}\n\nfunction parseSetCookie(raw: string): ParsedCookie | null {\n // Set-Cookie header format: `name=value; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax`\n const parts = raw.split(\";\").map((p) => p.trim());\n if (parts.length === 0 || parts[0] === undefined) return null;\n const nameValue = parts[0];\n const eq = nameValue.indexOf(\"=\");\n if (eq < 0) return null;\n const name = nameValue.slice(0, eq).trim();\n const value = nameValue.slice(eq + 1).trim();\n if (name.length === 0) return null;\n\n let maxAgeSeconds: number | null = null;\n let expiresEpochMs: number | null = null;\n let path: string | null = null;\n let httpOnly = false;\n let secure = false;\n let sameSite: \"strict\" | \"lax\" | \"none\" | null = null;\n\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (part === undefined) continue;\n const partEq = part.indexOf(\"=\");\n const key = (partEq < 0 ? part : part.slice(0, partEq)).trim().toLowerCase();\n const val = partEq < 0 ? \"\" : part.slice(partEq + 1).trim();\n if (key === \"max-age\") {\n const n = Number(val);\n if (Number.isFinite(n)) maxAgeSeconds = n;\n } else if (key === \"expires\") {\n const t = Date.parse(val);\n if (Number.isFinite(t)) expiresEpochMs = t;\n } else if (key === \"path\") {\n path = val;\n } else if (key === \"httponly\") {\n httpOnly = true;\n } else if (key === \"secure\") {\n secure = true;\n } else if (key === \"samesite\") {\n const lc = val.toLowerCase();\n if (lc === \"strict\" || lc === \"lax\" || lc === \"none\") sameSite = lc;\n }\n }\n\n return { name, value, maxAgeSeconds, expiresEpochMs, path, httpOnly, secure, sameSite };\n}\n\nfunction isExpired(cookie: StoredCookie, nowEpochMs: number): boolean {\n if (cookie.maxAgeSeconds !== null) {\n if (cookie.maxAgeSeconds <= 0) return true;\n return nowEpochMs >= cookie.storedAtEpochMs + cookie.maxAgeSeconds * 1000;\n }\n if (cookie.expiresEpochMs !== null) {\n return nowEpochMs >= cookie.expiresEpochMs;\n }\n // Session cookie — never expires in this process. The Node adapter does\n // not preserve the jar across processes; this is fine.\n return false;\n}\n\nexport class CookieJar {\n // host → name → cookie. Map preserves insertion order, which keeps the\n // serialized Cookie header deterministic for tests.\n private readonly store = new Map<string, Map<string, StoredCookie>>();\n\n set(host: string, setCookieHeaders: readonly string[]): void {\n let perHost = this.store.get(host);\n const now = Date.now();\n for (const raw of setCookieHeaders) {\n const parsed = parseSetCookie(raw);\n if (parsed === null) continue;\n if (perHost === undefined) {\n perHost = new Map();\n this.store.set(host, perHost);\n }\n // Max-Age=0 (or negative) immediately deletes; treat as a clear.\n if (parsed.maxAgeSeconds !== null && parsed.maxAgeSeconds <= 0) {\n perHost.delete(parsed.name);\n continue;\n }\n perHost.set(parsed.name, { ...parsed, storedAtEpochMs: now });\n }\n if (perHost !== undefined && perHost.size === 0) {\n this.store.delete(host);\n }\n }\n\n getCookieHeader(host: string): string | null {\n const perHost = this.store.get(host);\n if (perHost === undefined || perHost.size === 0) return null;\n const now = Date.now();\n const live: string[] = [];\n for (const [name, cookie] of perHost.entries()) {\n if (isExpired(cookie, now)) {\n perHost.delete(name);\n continue;\n }\n live.push(`${name}=${cookie.value}`);\n }\n if (live.length === 0) {\n this.store.delete(host);\n return null;\n }\n return live.join(\"; \");\n }\n}\n","// BetterAuthNodeAdapter — TA3 production adapter for Node + Ink runtimes.\n// Same surface as the browser adapter; cookies round-trip via the in-tree\n// CookieJar instead of being managed by the browser.\n//\n// Wire shapes are identical to BetterAuthBrowserAdapter (W1/W2/W3/W6/W7).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\n\nimport { CookieJar } from \"./cookie-jar\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthNodeAdapterDeps {\n readonly authBaseUrl: string;\n /**\n * Some BetterAuth routes (notably sign-out) enforce an Origin check and will\n * return 403 if absent. For Node clients, pass the same origin a browser\n * would send (e.g. SITE_URL).\n */\n readonly origin?: string;\n readonly cookieJar?: CookieJar;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = Buffer.from(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\").toString(\n \"utf-8\",\n );\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n try {\n return new URL(baseUrl).host;\n } catch {\n return baseUrl;\n }\n}\n\nfunction originFromBaseUrl(baseUrl: string): string | undefined {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction setCookiesFromResponse(jar: CookieJar, host: string, res: Response): void {\n // Headers.getSetCookie() is the Node 19.7+ way; falls back to single header\n // splitting if unavailable.\n type HeadersExt = Headers & { getSetCookie?: () => string[] };\n const ext = res.headers as HeadersExt;\n let setCookies: string[] = [];\n if (typeof ext.getSetCookie === \"function\") {\n setCookies = ext.getSetCookie();\n } else {\n res.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\") setCookies.push(value);\n });\n }\n if (setCookies.length > 0) jar.set(host, setCookies);\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthNodeAdapter {\n private readonly authBaseUrl: string;\n private readonly host: string;\n private readonly origin: string | undefined;\n private readonly cookieJar: CookieJar;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthNodeAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.host = hostFromBaseUrl(this.authBaseUrl);\n this.origin = deps.origin?.replace(/\\/$/, \"\");\n this.cookieJar = deps.cookieJar ?? new CookieJar();\n this.fetchImpl = deps.fetch ?? fetch;\n this.observation = deps.observation;\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n private headersWithCookie(extra: Record<string, string> = {}): Record<string, string> {\n const cookie = this.cookieJar.getCookieHeader(this.host);\n return cookie !== null ? { ...extra, cookie } : { ...extra };\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n ...observationRequestHeaders(this.observation, input),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) return { ok: true, value: undefined };\n if (res.status === 429) {\n return {\n ok: false,\n error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n setCookiesFromResponse(this.cookieJar, this.host, res);\n const body = await safeJson(res);\n if (res.ok && typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n if (!res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"OTP_EXPIRED\") {\n return { ok: false, error: Errors.otpExpired() };\n }\n if (errBody.code === \"INVALID_OTP\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\"),\n };\n }\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as {\n readonly session?: { readonly id?: string; readonly token?: string };\n readonly user?: BetterAuthUser;\n };\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n return {\n ok: true,\n value: authSessionFromBetterAuth(\n okBody.session?.token ?? okBody.session?.id ?? \"session\",\n okBody.user,\n ),\n };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const signOutOrigin = originFromBaseUrl(this.authBaseUrl) ?? this.origin;\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n headers: this.headersWithCookie({\n \"content-type\": \"application/json\",\n ...(signOutOrigin ? { origin: signOutOrigin } : {}),\n }),\n body: \"{}\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // The sign-out response sets Max-Age=0 cookies — the jar treats those\n // as immediate deletions.\n setCookiesFromResponse(this.cookieJar, this.host, res);\n if (res.ok) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthNodeLayer(\n deps: BetterAuthNodeAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthNodeAdapter(deps)),\n );\n}\n","// HttpBootstrapAdapter — TA3 production adapter. Calls\n// POST `/v1/client/bootstrap` on the backend. Per W4 + issue #119\n// (audit row B3), the 200 body is a versioned `BootstrapEnvelope`\n// shared with the producer via `@capxul/wire` — backend encodes,\n// SDK decodes, same schema both sides.\n//\n// Error mapping:\n// HTTP 401 and explicit NOT_AUTHENTICATED bodies map to NOT_AUTHENTICATED.\n// Schema-decode failures on a 200 body map to INVALID_INPUT per #119 AC1.\n// Provider 500s stay PROVIDER_ERROR so infrastructure faults are not collapsed\n// into auth failures.\n\nimport { Effect, Result, Layer } from \"effect\";\nimport { SchemaIssue, SchemaParser } from \"effect\";\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { BootstrapEnvelope, EngineeringTelemetryBootstrapPolicy } from \"@capxul/wire\";\n\nimport type { BootstrapInput, BootstrapPort, BootstrapResolution } from \"../../ports/bootstrap\";\nimport { BootstrapError, BootstrapPortTag, bootstrapErrorFromCapxul } from \"../../ports/bootstrap\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface HttpBootstrapAdapterDeps {\n readonly bootstrapBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text();\n } catch {\n return \"\";\n }\n}\n\nexport class HttpBootstrapAdapter implements BootstrapPort {\n private readonly bootstrapBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: HttpBootstrapAdapterDeps) {\n this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n // Bind through an arrow — assigning `fetch` to `this.fetchImpl` and calling it\n // as a method throws \"Illegal invocation\" in browsers.\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n resolve(input: BootstrapInput): Effect.Effect<BootstrapResolution, BootstrapError> {\n return Effect.tryPromise({\n try: () => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...observationRequestHeaders(this.observation),\n };\n return this.fetchImpl(`${this.bootstrapBaseUrl}/v1/client/bootstrap`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ publishableKey: input.publishableKey }),\n });\n },\n catch: (cause) =>\n bootstrapErrorFromCapxul(\"network\", Errors.networkError(\"bootstrap\", cause)),\n }).pipe(Effect.flatMap((res) => this.mapResponse(res)));\n }\n\n private mapResponse(res: Response): Effect.Effect<BootstrapResolution, BootstrapError> {\n if (res.ok) {\n return Effect.tryPromise({\n try: async () => {\n const body: unknown = await res.json();\n const state =\n typeof body === \"object\" &&\n body !== null &&\n \"state\" in body &&\n typeof body.state === \"object\" &&\n body.state !== null\n ? (body.state as Record<string, unknown>)\n : undefined;\n const rawEngineeringTelemetry = state?.engineeringTelemetry;\n const baseBody =\n state === undefined || rawEngineeringTelemetry === undefined\n ? body\n : {\n ...(body as Record<string, unknown>),\n state: Object.fromEntries(\n Object.entries(state).filter(([key]) => key !== \"engineeringTelemetry\"),\n ),\n };\n // `BootstrapEnvelope` lives in `@capxul/wire` so the producer\n // (`packages/backend/convex/credentials/http.ts`) and this\n // consumer share one schema. Branded fields (`applicationId`,\n // `chainId`, `sessionToken`, `issuedAt`, `expiresIn`) come out\n // of decode already branded — no `to*` chain afterwards.\n const decoded = SchemaParser.decodeUnknownResult(BootstrapEnvelope)(baseBody);\n if (Result.isFailure(decoded)) {\n // Schema validation failure → INVALID_INPUT per #119 AC1.\n // Unknown `version` literals, missing fields, and brand-rule\n // failures (e.g. `applicationId` not matching `APP_ID_RE`)\n // all land here.\n throw Errors.invalidInput(\n \"bootstrapEnvelope\",\n SchemaIssue.makeFormatterDefault()(decoded.failure),\n );\n }\n const { state: decodedState } = decoded.success;\n const decodedEngineeringTelemetry =\n rawEngineeringTelemetry === undefined\n ? undefined\n : SchemaParser.decodeUnknownResult(EngineeringTelemetryBootstrapPolicy)(\n rawEngineeringTelemetry,\n { onExcessProperty: \"error\" },\n );\n return {\n applicationId: decodedState.applicationId,\n chainId: decodedState.chainId,\n sessionToken: decodedState.sessionToken,\n issuedAt: decodedState.issuedAt,\n expiresIn: decodedState.expiresIn,\n authBaseUrl: normalizeRuntimeUrl(\"authBaseUrl\", decodedState.authBaseUrl),\n convexUrl: normalizeRuntimeUrl(\"convexUrl\", decodedState.convexUrl),\n siteBaseUrl: normalizeRuntimeUrl(\"siteBaseUrl\", decodedState.siteBaseUrl),\n openfortPublishableKey: decodedState.openfortPublishableKey,\n shieldPublishableKey: decodedState.shieldPublishableKey,\n ...(decodedEngineeringTelemetry !== undefined &&\n Result.isSuccess(decodedEngineeringTelemetry)\n ? { engineeringTelemetry: decodedEngineeringTelemetry.success }\n : {}),\n };\n },\n catch: (cause) => {\n if (cause instanceof CapxulError && cause.code === \"INVALID_INPUT\") {\n return bootstrapErrorFromCapxul(\"invalidInput\", cause);\n }\n return bootstrapErrorFromCapxul(\n \"malformedBody\",\n Errors.providerError(\n \"convex\",\n \"bootstrap\",\n cause instanceof Error ? cause : new Error(String(cause)),\n ),\n );\n },\n });\n }\n\n return Effect.promise(() => safeText(res)).pipe(\n Effect.flatMap((body) => {\n if (res.status === 401 || body.startsWith(\"NOT_AUTHENTICATED\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\"notAuthenticated\", Errors.notAuthenticated()),\n );\n }\n if (res.status === 400 || body.startsWith(\"INVALID_INPUT\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"invalidInput\",\n Errors.invalidInput(\"publishableKey\", \"rejected by bootstrap\"),\n ),\n );\n }\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"provider\",\n Errors.providerError(\"convex\", \"bootstrap\", new Error(`HTTP ${res.status}`)),\n ),\n );\n }),\n );\n }\n}\n\nexport function HttpBootstrapLayer(deps: HttpBootstrapAdapterDeps): Layer.Layer<BootstrapPortTag> {\n return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));\n}\n\nfunction normalizeRuntimeUrl(\n field: \"authBaseUrl\" | \"convexUrl\" | \"siteBaseUrl\",\n raw: string,\n): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n","import type { DurationMs, EpochMs } from \"@capxul/types\";\nimport { toEpochMs } from \"@capxul/types\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ClockError, ClockPortTag, type ClockPort } from \"../../ports/clock\";\n\nexport class SystemClockAdapter implements ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError, never> = Effect.try({\n try: () => toEpochMs(Date.now()),\n catch: (cause) => new ClockError({ operation: \"now\", cause }),\n });\n\n sleep(duration: DurationMs): Effect.Effect<void, ClockError, never> {\n return Effect.callback<void, ClockError>((resume) => {\n const timeout = setTimeout(() => resume(Effect.void), duration as number);\n return Effect.sync(() => clearTimeout(timeout));\n });\n }\n}\n\nexport function SystemClockLayer(): Layer.Layer<ClockPortTag, ClockError, never> {\n return Layer.succeed(ClockPortTag, new SystemClockAdapter());\n}\n","import { CapxulError, Errors, decodeConvexError } from \"@capxul/config\";\nimport { ConvexClient } from \"convex/browser\";\nimport { getFunctionName, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer, Tracer } from \"effect\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport {\n ConvexCallPortTag,\n convexCallErrorFromCapxul,\n type ConvexCallError,\n type ConvexCallPort,\n type Snapshot,\n type Unsubscribe,\n} from \"../../ports/convex-call\";\nimport { readInvocationObservation } from \"../../internal/invocation-observation\";\nimport { formatTraceparent } from \"../../domain/machine/telemetry.ts\";\nimport type { ObservationAdapter } from \"../../observation\";\n\nexport type ConvexCallAuthFetcher = (args: {\n readonly forceRefreshToken: boolean;\n}) => Promise<string | null>;\n\nexport interface ConvexClientShape {\n setAuth(fetchToken: ConvexCallAuthFetcher): void;\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n onUpdate<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n onValue: (value: TOutput) => void,\n onError: (err: Error) => void,\n ): () => void;\n close(): Promise<void>;\n}\n\nexport type ConvexCallLayerDeps = {\n readonly convexUrl: string;\n readonly tokenProvider?: ConvexCallAuthFetcher;\n readonly client?: ConvexClientShape;\n readonly applicationId?: string;\n readonly observation?: Pick<ObservationAdapter, \"resolveContext\">;\n};\n\n/** Exact floor-first allowlist; every additional handler must migrate its validator first. */\nconst OBSERVED_CONVEX_ACTIONS: ReadonlySet<string> = new Set([\n \"subAccount/actions:transfer\",\n \"smartAccount/actions:claim\",\n \"org/actions:prepareFounderAccount\",\n \"org/actions:prepareBootstrap\",\n \"org/actions:submitBootstrap\",\n \"org/actions:resumeBootstrapSubmission\",\n \"org/actions:confirmBootstrap\",\n]);\nconst OBSERVED_CONVEX_QUERIES: ReadonlySet<string> = new Set([\n \"identity/queries:loadByAuthUserId\",\n \"smartAccount/queries:loadByAuthUserId\",\n \"org/lifecycle:load\",\n]);\nconst OBSERVED_CONVEX_MUTATIONS: ReadonlySet<string> = new Set([\n \"identity/mutations:create\",\n \"identity/mutations:update\",\n \"identity/mutations:completeOnboarding\",\n \"smartAccount/mutations:provision\",\n \"org/lifecycle:startOrResume\",\n \"org/lifecycle:recordFailure\",\n \"org/lifecycle:retry\",\n]);\n\nexport class ConvexCallAdapter implements ConvexCallPort {\n readonly #client: ConvexClientShape;\n readonly #tokenProvider: ConvexCallAuthFetcher | undefined;\n readonly #applicationId: string | undefined;\n readonly #observation: Pick<ObservationAdapter, \"resolveContext\"> | undefined;\n\n constructor(deps: ConvexCallLayerDeps) {\n this.#client = deps.client ?? (new ConvexClient(deps.convexUrl) as ConvexClientShape);\n this.#tokenProvider = deps.tokenProvider;\n this.#applicationId = deps.applicationId;\n this.#observation = deps.observation;\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n refreshAuth(): void {\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.query(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_QUERIES, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.mutation(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_MUTATIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.action(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n #observedArgs<TArgs extends Record<string, unknown>>(\n allowlist: ReadonlySet<string>,\n path: string,\n args: TArgs,\n traceparent: string | undefined,\n ): TArgs {\n if (!allowlist.has(path)) return args;\n\n const carriedContext = sanitizeObservationContext(\n (args as { readonly observationContext?: unknown }).observationContext,\n );\n let hostContext: WireObservationContext | undefined;\n const invocationSnapshot = readInvocationObservation(args);\n if (invocationSnapshot !== undefined) {\n hostContext = invocationSnapshot.context;\n } else {\n const resolveContext = this.#observation?.resolveContext;\n if (resolveContext !== undefined) {\n try {\n hostContext = resolveContext();\n } catch {\n hostContext = undefined;\n }\n }\n }\n if (hostContext === undefined && carriedContext === undefined && traceparent === undefined) {\n return args;\n }\n hostContext = sanitizeObservationContext({\n ...hostContext,\n ...carriedContext,\n ...(this.#applicationId === undefined ? {} : { applicationId: this.#applicationId }),\n ...(traceparent === undefined ? {} : { traceparent }),\n });\n if (hostContext === undefined) return args;\n\n // Never mutate caller-owned args. This cast is localized to the one handler\n // whose backend validator explicitly accepts the reserved context field.\n return { ...args, observationContext: hostContext } as TArgs;\n }\n\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError> {\n return Effect.try({\n try: () => {\n const path = getFunctionName(fn);\n const unsubscribe = this.#client.onUpdate(\n fn,\n args,\n (value) => callback({ status: \"ok\", value }),\n (err) => callback({ status: \"error\", error: mapToCapxulError(path, err) }),\n );\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n unsubscribe();\n };\n },\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n }).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n callback({ status: \"loading\" });\n }),\n ),\n );\n }\n\n async close(): Promise<void> {\n await this.#client.close();\n }\n}\n\nexport function ConvexCallLayer(deps: ConvexCallLayerDeps): Layer.Layer<ConvexCallPortTag> {\n return Layer.effect(\n ConvexCallPortTag,\n Effect.acquireRelease(\n Effect.sync(() => new ConvexCallAdapter(deps)),\n (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie),\n ),\n );\n}\n\nfunction mapToCapxulError(operation: string, err: unknown): CapxulError {\n const decoded = decodeConvexError(err);\n if (decoded !== null) return decoded;\n if (err instanceof CapxulError) return err;\n if (err instanceof Error) {\n if (isTransportError(err)) return Errors.networkError(operation, err);\n return Errors.providerError(\"convex\", operation, err);\n }\n return Errors.providerError(\"convex\", operation, new Error(String(err)));\n}\n\nfunction mapToConvexCallError(operation: string, err: unknown): ConvexCallError {\n return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err));\n}\n\nfunction isTransportError(err: Error): boolean {\n const message = err.message.toLowerCase();\n return (\n message.includes(\"failed to fetch\") ||\n message.includes(\"network\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"enotfound\") ||\n message.includes(\"etimedout\") ||\n message.includes(\"socket\")\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, Profile } from \"@capxul/types\";\nimport {\n toAddress,\n toAuthUserId,\n toCountryCode,\n toEmail,\n toEpochMs,\n toKycTier,\n} from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CompleteOnboardingIdentityInput,\n CreateIdentityInput,\n IdentityError,\n IdentityPort,\n UpdateIdentityInput,\n} from \"../../ports/identity\";\nimport { identityErrorFromCapxul, IdentityPortTag } from \"../../ports/identity\";\n\ntype RawProfile = {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly country: string | null;\n readonly onboarded?: boolean;\n readonly withdrawalAddress?: string | null;\n readonly username?: string | null;\n readonly imageUrl?: string | null;\n readonly kycTier: 0 | 1 | 2 | 3;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nconst identityLoadByAuthUserIdQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: AuthUserId },\n RawProfile | null\n> = makeFunctionReference<\"query\", { readonly authUserId: AuthUserId }, RawProfile | null>(\n CAPXUL_FUNCTIONS[\"identity/queries\"].loadByAuthUserId,\n);\n\nconst identityCreateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CreateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CreateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].create,\n);\n\nconst identityUpdateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n UpdateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", UpdateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].update,\n);\n\nconst identityCompleteOnboardingMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CompleteOnboardingIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CompleteOnboardingIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].completeOnboarding,\n);\n\nexport class ConvexIdentityAdapter implements IdentityPort {\n readonly #convex: ConvexCallPort;\n\n constructor(deps: { readonly convex: ConvexCallPort }) {\n this.#convex = deps.convex;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError> {\n return this.#convex.query(identityLoadByAuthUserIdQuery, { authUserId }).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => (row === null ? null : brandProfile(row)),\n catch: (cause) => identityErrorFromUnknown(\"loadByAuthUserId\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCreateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"create\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"create\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"create\", cause))),\n );\n }\n\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityUpdateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"update\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"update\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"update\", cause))),\n );\n }\n\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"completeOnboarding\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"completeOnboarding\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"completeOnboarding\", cause)),\n ),\n );\n }\n}\n\nexport function ConvexIdentityLayer(): Layer.Layer<\n IdentityPortTag,\n IdentityError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n IdentityPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })),\n );\n}\n\nfunction brandProfile(raw: RawProfile): Profile {\n return {\n authUserId: toAuthUserId(raw.authUserId),\n email: toEmail(raw.email),\n displayName: raw.displayName,\n country: raw.country === null ? null : toCountryCode(raw.country),\n onboarded: raw.onboarded ?? false,\n withdrawalAddress:\n raw.withdrawalAddress === null || raw.withdrawalAddress === undefined\n ? null\n : toAddress(raw.withdrawalAddress),\n // #1062 / #1061: plain strings on the wire and the surface — no brand.\n username: raw.username ?? null,\n imageUrl: raw.imageUrl ?? null,\n kycTier: toKycTier(raw.kycTier),\n createdAt: toEpochMs(raw.createdAt),\n updatedAt: toEpochMs(raw.updatedAt),\n };\n}\n\nfunction identityErrorFromUnknown(operation: string, cause: unknown): IdentityError {\n if (cause instanceof CapxulError) return identityErrorFromCapxul(operation, cause);\n return identityErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Account } from \"@capxul/types\";\nimport { toAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n AccountReadError,\n AccountReadPort,\n FundFromFaucetInput,\n FundFromFaucetResult,\n ReadAccountBalanceInput,\n} from \"../../ports/account-read\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { accountReadErrorFromCapxul, AccountReadPortTag } from \"../../ports/account-read\";\nimport { fromWei } from \"../../domain/money/from-wei\";\n\nexport type WireAccountBalance = {\n readonly accountId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\nexport type WireFaucetMintResult = {\n readonly txHash: string;\n};\n\nexport type ConvexAccountFunctions = {\n readonly readBalance: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number },\n WireAccountBalance\n >;\n readonly faucetMint: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number; readonly rawAmount: string },\n WireFaucetMintResult\n >;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexAccountFunctions = {\n readBalance: makeFunctionReference<\"action\", { chainId: number }, WireAccountBalance>(\n CAPXUL_FUNCTIONS[\"account/actions\"].readBalance,\n ),\n faucetMint: makeFunctionReference<\n \"action\",\n { chainId: number; rawAmount: string },\n WireFaucetMintResult\n >(CAPXUL_FUNCTIONS[\"account/actions\"].faucetMint),\n};\n\nexport class ConvexAccountAdapter implements AccountReadPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError> {\n return this.#convex.action(this.#fns.readBalance, { chainId: wireChainId(input.chainId) }).pipe(\n Effect.mapError((error) =>\n accountReadErrorFromCapxul(\"readBalance\", error.publicError, error),\n ),\n Effect.flatMap((wire) => brandAccountEffect(\"readBalance\", wire)),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(\"readBalance\", cause))),\n );\n }\n\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError> {\n const operation = \"fundFromFaucet\";\n // `toWei`/`parseUnits` throws on a malformed money string; suspend so the\n // throw surfaces as a defect below and maps to an AccountReadError, never an\n // escaped throw out of `fundFromFaucet` (mirrors ConvexSubAccountAdapter.transfer).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(this.#fns.faucetMint, {\n chainId: wireChainId(input.chainId),\n rawAmount,\n });\n }).pipe(\n Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => ({ txHash: wire.txHash })),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexAccountLayer(): Layer.Layer<\n AccountReadPortTag,\n AccountReadError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n AccountReadPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })),\n );\n}\n\nfunction brandAccountEffect(\n operation: string,\n wire: WireAccountBalance,\n): Effect.Effect<Account, AccountReadError> {\n return Effect.try({\n try: () => brandAccount(wire),\n catch: (cause) => accountReadErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandAccount(wire: WireAccountBalance): Account {\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(\n wire.rawAvailableBalance ?? wire.rawBalance,\n wire.decimals,\n wire.currency,\n );\n return {\n id: toAccountId(wire.accountId),\n balance,\n available,\n };\n}\n\nfunction accountReadErrorFromUnknown(operation: string, cause: unknown): AccountReadError {\n if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);\n return accountReadErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount } from \"@capxul/types\";\nimport { toAccountId, toEpochMs, toSubAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateSubAccountInput,\n RenameSubAccountInput,\n SubAccountError,\n SubAccountIdInput,\n SubAccountPort,\n TransferInput,\n TransferResult,\n} from \"../../ports/sub-account\";\nimport { subAccountErrorFromCapxul, SubAccountPortTag } from \"../../ports/sub-account\";\n\nexport type WireSubAccount = {\n readonly subAccountId: string;\n readonly accountId: string;\n readonly name: string;\n readonly rawBalance: string;\n readonly decimals: number;\n readonly currency: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\n/**\n * Wire result of `subAccount/actions:transfer`. `availableRaw` is the\n * recomputed `balanceOf − Σ` on-chain integer; the SDK lifts it to `Money`\n * via `fromWei`. `from`/`to` are the updated sub-account rows, or `null` when\n * that endpoint is the Account's MAIN balance (never a stored row).\n */\nexport type WireTransferResult = {\n readonly availableRaw: string;\n readonly decimals: number;\n readonly currency: string;\n readonly from: WireSubAccount | null;\n readonly to: WireSubAccount | null;\n};\n\nexport type WireTransferArgs = {\n readonly chainId: number;\n readonly from: string;\n readonly to: string;\n readonly rawAmount: string;\n};\n\nexport type ConvexSubAccountFunctions = {\n readonly create: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly accountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly get: FunctionReference<\n \"query\",\n \"public\",\n { readonly subAccountId: string },\n WireSubAccount | null\n >;\n readonly list: FunctionReference<\n \"query\",\n \"public\",\n { readonly accountId: string },\n readonly WireSubAccount[]\n >;\n readonly rename: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly remove: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string },\n { readonly ok: true }\n >;\n readonly transfer: FunctionReference<\"action\", \"public\", WireTransferArgs, WireTransferResult>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSubAccountFunctions = {\n create: makeFunctionReference<\"mutation\", { accountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].create,\n ),\n get: makeFunctionReference<\"query\", { subAccountId: string }, WireSubAccount | null>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].get,\n ),\n list: makeFunctionReference<\"query\", { accountId: string }, readonly WireSubAccount[]>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].list,\n ),\n rename: makeFunctionReference<\"mutation\", { subAccountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].rename,\n ),\n remove: makeFunctionReference<\"mutation\", { subAccountId: string }, { ok: true }>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].remove,\n ),\n transfer: makeFunctionReference<\"action\", WireTransferArgs, WireTransferResult>(\n CAPXUL_FUNCTIONS[\"subAccount/actions\"].transfer,\n ),\n};\n\nexport class ConvexSubAccountAdapter implements SubAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSubAccountFunctions;\n readonly #chainId: number;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly chainId: number;\n readonly functions?: ConvexSubAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#chainId = deps.chainId;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"create\", this.#fns.create, {\n accountId: input.accountId as string,\n name: input.name,\n });\n }\n\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError> {\n return this.#runQuery(\n \"get\",\n this.#fns.get,\n { subAccountId: input.subAccountId as string },\n (wire) => (wire === null ? null : brandSubAccount(wire)),\n );\n }\n\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError> {\n return this.#runQuery(\n \"list\",\n this.#fns.list,\n { accountId: input.accountId as string },\n (wires) => wires.map((wire) => brandSubAccount(wire)),\n );\n }\n\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"rename\", this.#fns.rename, {\n subAccountId: input.subAccountId as string,\n name: input.name,\n });\n }\n\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError> {\n const operation = \"delete\";\n return this.#convex\n .mutation(this.#fns.remove, { subAccountId: input.subAccountId as string })\n .pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.asVoid,\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError> {\n const operation = \"transfer\";\n // `toWei`/`parseUnits` throws on a malformed money string; that surfaces as\n // a defect below and is mapped to a SubAccountError (INVALID_INPUT-ish).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(\n this.#fns.transfer,\n copyInvocationObservation(input, {\n chainId: this.#chainId,\n from: input.from as string,\n to: input.to as string,\n rawAmount,\n }),\n );\n }).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n // Branding (`fromWei` / `brandSubAccount`) runs INSIDE the guarded pipe so\n // a throw surfaces as a SubAccountError defect, never an escaped defect.\n Effect.map((wire) => brandTransferResult(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runMutation(\n operation: string,\n ref: FunctionReference<\"mutation\", \"public\", Record<string, string>, WireSubAccount>,\n args: Record<string, string>,\n ): Effect.Effect<SubAccount, SubAccountError> {\n return this.#convex.mutation(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => brandSubAccount(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runQuery<TWire, TOut>(\n operation: string,\n ref: FunctionReference<\"query\", \"public\", Record<string, string>, TWire>,\n args: Record<string, string>,\n map: (wire: TWire) => TOut,\n ): Effect.Effect<TOut, SubAccountError> {\n // Branding (`map`) runs INSIDE the guarded pipe so a throw from\n // toAccountId/toSubAccountId/fromWei surfaces as a SubAccountError defect,\n // never an unhandled defect that escapes the typed channel.\n return this.#convex.query(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map(map),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexSubAccountLayer(\n chainId: number,\n): Layer.Layer<SubAccountPortTag, SubAccountError, ConvexCallPortTag> {\n return Layer.effect(\n SubAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSubAccountAdapter({ convex, chainId })),\n );\n}\n\nfunction brandTransferResult(wire: WireTransferResult): TransferResult {\n return {\n available: fromWei(wire.availableRaw, wire.decimals, wire.currency),\n from: wire.from === null ? null : brandSubAccount(wire.from),\n to: wire.to === null ? null : brandSubAccount(wire.to),\n };\n}\n\nfunction brandSubAccount(wire: WireSubAccount): SubAccount {\n return {\n id: toSubAccountId(wire.subAccountId),\n accountId: toAccountId(wire.accountId),\n name: wire.name,\n balance: fromWei(wire.rawBalance, wire.decimals, wire.currency),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction subAccountErrorFromUnknown(operation: string, cause: unknown): SubAccountError {\n if (cause instanceof CapxulError) return subAccountErrorFromCapxul(operation, cause);\n return subAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Address, AuthUserId, SmartAccount } from \"@capxul/types\";\nimport { toAddress, toAuthUserId, toChainId, toEpochMs } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n ClaimInput,\n ConfirmDeploymentInput,\n ProvisionInput,\n SmartAccountError,\n SmartAccountPort,\n} from \"../../ports/smart-account\";\nimport { smartAccountErrorFromCapxul, SmartAccountPortTag } from \"../../ports/smart-account\";\n\nexport type WireSmartAccount = {\n readonly authUserId: string;\n readonly signerAddress: string | null;\n readonly smartAccountAddress: string;\n readonly chainId: number;\n readonly deployedAt: number | null;\n readonly claimedAt: number | null;\n readonly createdAt: number;\n};\n\nexport type WireConfirmDeploymentArgs = {\n readonly chainId: number;\n readonly safeAddress: string;\n readonly evidence: {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly safeAddress: string;\n readonly userOpHash?: string;\n readonly txHash?: string;\n readonly blockNumber?: number;\n };\n};\n\nexport type WireClaimArgs = {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly observationContext?: WireObservationContext;\n};\n\nexport type ConvexSmartAccountFunctions = {\n readonly loadByAuthUserId: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: string },\n WireSmartAccount | null\n >;\n readonly loadBySmartAccountAddress: FunctionReference<\n \"query\",\n \"public\",\n { readonly address: string },\n WireSmartAccount | null\n >;\n readonly provision: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly chainId: number;\n },\n WireSmartAccount\n >;\n // `confirmDeployment` is an ACTION, not a mutation, because the\n // backend handler must perform outbound `fetch` calls to Alchemy\n // (eth_getCode / eth_getUserOperationReceipt / eth_getLogs /\n // eth_getBlockByNumber) — Convex mutations are transactional and\n // cannot do fetch. See `packages/backend/convex/smartAccount/actions.ts`.\n readonly confirmDeployment: FunctionReference<\n \"action\",\n \"public\",\n WireConfirmDeploymentArgs,\n WireSmartAccount\n >;\n // `claim` is an ACTION: the backend builds, bootstrap-signs, and submits\n // the claim userOp (deploy + swapOwner) via outbound bundler RPC (PRD #462).\n readonly claim: FunctionReference<\"action\", \"public\", WireClaimArgs, WireSmartAccount>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSmartAccountFunctions = {\n loadByAuthUserId: makeFunctionReference<\"query\", { authUserId: string }, WireSmartAccount | null>(\n CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadByAuthUserId,\n ),\n loadBySmartAccountAddress: makeFunctionReference<\n \"query\",\n { address: string },\n WireSmartAccount | null\n >(CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadBySmartAccountAddress),\n provision: makeFunctionReference<\"mutation\", { chainId: number }, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/mutations\"].provision,\n ),\n confirmDeployment: makeFunctionReference<\"action\", WireConfirmDeploymentArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].confirmDeployment,\n ),\n claim: makeFunctionReference<\"action\", WireClaimArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].claim,\n ),\n};\n\nexport class ConvexSmartAccountAdapter implements SmartAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSmartAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexSmartAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadByAuthUserId\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadBySmartAccountAddress\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadBySmartAccountAddress\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadBySmartAccountAddress\", cause)),\n ),\n );\n }\n\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .mutation(this.#fns.provision, {\n chainId: wireChainId(input.chainId),\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"provision\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"provision\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"provision\", cause)),\n ),\n );\n }\n\n confirmDeployment(input: ConfirmDeploymentInput): Effect.Effect<SmartAccount, SmartAccountError> {\n const evidence: WireConfirmDeploymentArgs[\"evidence\"] = {\n chainId: wireChainId(input.evidence.chainId),\n signerAddress: input.evidence.signerAddress,\n safeAddress: input.evidence.safeAddress,\n ...(input.evidence.userOpHash === undefined ? {} : { userOpHash: input.evidence.userOpHash }),\n ...(input.evidence.txHash === undefined ? {} : { txHash: input.evidence.txHash }),\n ...(input.evidence.blockNumber === undefined\n ? {}\n : { blockNumber: input.evidence.blockNumber }),\n };\n return this.#convex\n .action(this.#fns.confirmDeployment, {\n chainId: wireChainId(input.chainId),\n safeAddress: input.safeAddress,\n evidence,\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"confirmDeployment\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"confirmDeployment\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"confirmDeployment\", cause)),\n ),\n );\n }\n\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .action(\n this.#fns.claim,\n copyInvocationObservation(input, {\n chainId: wireChainId(input.chainId),\n signerAddress: input.signerAddress,\n }),\n )\n .pipe(\n Effect.mapError((error) => smartAccountErrorFromCapxul(\"claim\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"claim\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown(\"claim\", cause))),\n );\n }\n}\n\nexport function ConvexSmartAccountLayer(): Layer.Layer<\n SmartAccountPortTag,\n SmartAccountError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n SmartAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })),\n );\n}\n\nfunction brandSmartAccountEffect(\n operation: string,\n wire: WireSmartAccount | null,\n): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return Effect.try({\n try: () => (wire === null ? null : brandNonNullSmartAccount(wire)),\n catch: (cause) => smartAccountErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandNonNullSmartAccount(wire: WireSmartAccount): SmartAccount {\n return {\n authUserId: toAuthUserId(wire.authUserId),\n signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),\n smartAccountAddress: toAddress(wire.smartAccountAddress),\n chainId: toChainId(wire.chainId),\n deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),\n claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction brandProvisionedSmartAccount(\n requestedAuthUserId: AuthUserId,\n wire: WireSmartAccount,\n): SmartAccount {\n if (wire.authUserId !== String(requestedAuthUserId)) {\n throw Errors.notAuthenticated();\n }\n return brandNonNullSmartAccount(wire);\n}\n\nfunction smartAccountErrorFromUnknown(operation: string, cause: unknown): SmartAccountError {\n if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);\n return smartAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","// Organization domain port (owned by `packages/sdk/docs/architecture.md`).\n// The SEAM between the Effect org programs and the outside\n// world: the live adapter (added by the CLI/live-proof slice) performs the\n// SDK-orchestrated Org Safe deploy (D10 — permissionless + zodiac-roles-sdk,\n// no custom Solidity) and the RPC `balanceOf` treasury read (D3); the hermetic\n// L1 path runs with NO port and the org programs fall back to a deterministic\n// `$0` treasury (a fresh Org has no on-chain funds).\n//\n// The port returns plain records branded at this boundary (brand-at-source).\n// `OrgError` carries the public `CapxulError` so the program can surface a\n// typed failure channel exactly like `AccountReadPort`.\n\nimport { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/errors\";\nimport type { Account, OrgId } from \"@capxul/types\";\n\nimport type {\n AssignRoleInput,\n CreateOrgInput,\n InviteMemberInput,\n MemberView,\n OrgView,\n RemoveMemberInput,\n RoleView,\n OrgSpendViaPaymentsInput,\n OrgPayrollRun,\n} from \"../surface/org\";\nimport type { Address, Money, SubAccountId } from \"@capxul/types\";\n\n/**\n * The minimal `{from, to, amount}` spend shape the authority read keys off\n * (D3 #565). The legacy address-keyed `OrgSpendInput`/`org.spend` lane was\n * hard-removed when `orgSpends` folded into the one `payments` ledger; the\n * leak-safe ref-based lane (`spendViaPayments`/`batchPayroll`) constructs this\n * internally and enforces the real validated recipient on the gate.\n */\nexport type OrgSpendShape = {\n readonly from: SubAccountId;\n readonly to: Address;\n readonly amount: Money;\n};\nimport type { Payment } from \"../surface/money\";\nimport type { SpendGateRecipients, SpendGateSubAccountScope } from \"../domain/org/spend-gate\";\n\nexport type CreateOrgPortInput = {\n readonly input: CreateOrgInput;\n};\n\nexport type ReadOrgTreasuryInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgsInput = Record<never, never>;\n\nexport type ListOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgMembersInput = {\n readonly orgId: OrgId;\n};\n\nexport type InviteOrgMemberInput = {\n readonly orgId: OrgId;\n readonly input: InviteMemberInput;\n};\n\nexport type ResendOrgInviteTokenInput = {\n readonly orgId: OrgId;\n readonly email: string;\n};\n\nexport type DetectPendingOrgInvitationsInput = Record<never, never>;\n\nexport type DetectPendingOrgInvitationsResult = {\n readonly matched: readonly OrgId[];\n};\n\nexport type DeployOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type OrgRolesDeploymentResult = {\n readonly orgId: OrgId;\n readonly roles: readonly RoleView[];\n};\n\nexport type GrantOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: AssignRoleInput;\n};\n\nexport type RevokeOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: RemoveMemberInput;\n};\n\nexport type OrgSpendAuthority = {\n readonly activeMember: boolean;\n readonly subAccountBalanceRaw: string;\n readonly recipients: SpendGateRecipients;\n readonly subAccounts: SpendGateSubAccountScope;\n readonly perTxCapRaw?: string | null;\n readonly perDayCapRaw?: string | null;\n readonly spentTodayRaw?: string | null;\n readonly role?: string;\n};\n\nexport type ReadOrgSpendAuthorityInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendShape;\n readonly amountRaw: string;\n};\n\nexport class OrgError extends Data.TaggedError(\"OrgError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function orgErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): OrgError {\n return new OrgError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n/**\n * Live org seam. `createOrg` runs the SDK-orchestrated deploy (D10) and returns\n * the created `OrgView` (its treasury is the real M2 `Account` over the Org\n * Safe — $0 at creation, D3). `readTreasury` pulls the org's Account via RPC\n * `balanceOf` (D3). `listOrgs` lists the orgs the authenticated user belongs to.\n */\nexport interface OrgPort {\n createOrg(input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError, never>;\n readTreasury(input: ReadOrgTreasuryInput): Effect.Effect<Account, OrgError, never>;\n listOrgs(input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError, never>;\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError, never>;\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError, never>;\n pendingMembers?(\n input: ListOrgMembersInput,\n ): Effect.Effect<readonly MemberView[], OrgError, never>;\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError, never>;\n resendInviteToken?(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError, never>;\n detectAndAcceptPendingInvitations(\n input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError, never>;\n}\n\nexport class OrgPortTag extends Context.Service<OrgPortTag, OrgPort>()(\n \"@capxul/sdk/ports/OrgPort\",\n) {}\n\nexport interface OrgRolesDeploymentPort {\n deployRoles(input: DeployOrgRolesInput): Effect.Effect<OrgRolesDeploymentResult, OrgError, never>;\n grantRole(input: GrantOrgRoleInput): Effect.Effect<MemberView, OrgError, never>;\n revokeRole(input: RevokeOrgRoleInput): Effect.Effect<void, OrgError, never>;\n}\n\nexport class OrgRolesDeploymentPortTag extends Context.Service<\n OrgRolesDeploymentPortTag,\n OrgRolesDeploymentPort\n>()(\"@capxul/sdk/ports/OrgRolesDeploymentPort\") {}\n\nexport type SubmitOrgSpendViaPaymentsInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendViaPaymentsInput;\n readonly amountRaw: string;\n readonly authority: OrgSpendAuthority;\n};\n\nexport type SubmitOrgBatchPayrollInput = {\n readonly orgId: OrgId;\n readonly from: OrgSpendViaPaymentsInput[\"from\"];\n readonly runs: readonly { readonly run: OrgPayrollRun; readonly amountRaw: string }[];\n readonly authorities: readonly OrgSpendAuthority[];\n};\n\nexport interface OrgSpendPort {\n readSpendAuthority(\n input: ReadOrgSpendAuthorityInput,\n ): Effect.Effect<OrgSpendAuthority, OrgError, never>;\n /**\n * Leak-safe org spend (G4 · #547; D3 #565 — the one ledger of record): execute\n * the spend through the payments engine (Roles modifier → CapxulPayments),\n * write a real `payments` row (`source:\"org\"`) and read it back as a `Payment`\n * — the wire carries no `txHash` / Safe / userOp internals. Optional so a\n * hermetic adapter without a payments-submit lane still compiles; absent ⇒ the\n * program falls back to a deterministic hermetic `Payment`.\n */\n submitSpendViaPayments?(\n input: SubmitOrgSpendViaPaymentsInput,\n ): Effect.Effect<Payment, OrgError, never>;\n /** Leak-safe org payroll batch (G4 · #547): one MultiSend, one Payment per run. */\n submitBatchPayroll?(\n input: SubmitOrgBatchPayrollInput,\n ): Effect.Effect<readonly Payment[], OrgError, never>;\n}\n\nexport class OrgSpendPortTag extends Context.Service<OrgSpendPortTag, OrgSpendPort>()(\n \"@capxul/sdk/ports/OrgSpendPort\",\n) {}\n","/**\n * Pure brand-at-read-edge parser for the Org domain wire shape (canon D9/D10a;\n * `.claude/rules/typescript-style.md` \"Brand at DB read boundaries\" +\n * `.claude/rules/wire-fixture-discipline.md`). Maps the raw Convex `WireOrg`\n * row into the branded `OrgView`. No I/O, no viem — so the hermetic L2 fixture\n * test can load `__fixtures__/createOrg-actual.json` verbatim and assert this\n * parser narrows it.\n */\nimport type { Account, Address, Money } from \"@capxul/types\";\nimport {\n toAccountId,\n toAddress,\n toCurrencyCode,\n toEmail,\n toOrgId,\n toRoleKey,\n toSubAccountId,\n} from \"@capxul/types\";\n\nimport type { MemberView, OrgView, RoleDefinition, RoleView } from \"../../surface/org\";\n\n/** Raw Org row as returned by the backend `org/queries` + `org/mutations`. */\nexport type WireOrg = {\n readonly orgId: string;\n readonly name: string;\n readonly slug: string;\n readonly safeAddress: string;\n readonly chainId: number;\n readonly ownerPersonalSafeAddress: string;\n readonly founderEmail: string;\n readonly status?: \"safe_placeholder\" | \"safe_deployed\" | \"active\";\n readonly template?: string;\n readonly metadata: string | null;\n readonly country: string | null;\n // #1064 bio/size + #1061 logoUrl. Optional so pre-rollout recorded fixtures\n // stay verbatim-loadable; the parser maps absence to null.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly logoUrl?: string | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nexport type WireOrgRole = {\n readonly orgId: string;\n readonly roleKey: string;\n readonly label: string;\n readonly definitionJson: string;\n readonly permissions: readonly string[];\n readonly allowanceJson: string | null;\n readonly status: \"active\" | \"revoked\";\n readonly createdAt: number;\n readonly revokedAt: number | null;\n};\n\nexport type WireOrgMember = {\n readonly orgId: string;\n readonly email: string;\n readonly name: string | null;\n readonly authUserId: string | null;\n readonly personalSafeAddress: string | null;\n readonly role: string;\n readonly roleKey: string | null;\n readonly status: \"pending\" | \"pending_safe\" | \"pending_grant\" | \"active\" | \"revoked\" | \"expired\";\n readonly grantTxHash: string | null;\n readonly revokeTxHash: string | null;\n readonly invitedAt: number;\n readonly acceptedAt: number | null;\n readonly grantedAt: number | null;\n readonly revokedAt: number | null;\n readonly expiresAt: number;\n readonly updatedAt: number;\n};\n\ntype RawRoleDefinition = {\n readonly label?: unknown;\n readonly spend?: {\n readonly perTx?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly perDay?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly toRecipients?: unknown;\n };\n readonly subAccounts?: { readonly scope?: unknown };\n readonly canManageMembers?: unknown;\n readonly canManageRoles?: unknown;\n};\n\n/**\n * Map a `WireOrg` + its (separately read) treasury `Account` into the branded\n * `OrgView`. The viewer role is projected by the authenticated backend read;\n * it must never be inferred from Organization ownership. Brands at the read\n * edge: `orgId`, `safeAddress`.\n */\nexport function brandOrgView(wire: WireOrg, treasury: Account, viewerRole: string): OrgView {\n return {\n id: toOrgId(wire.orgId),\n name: wire.name,\n handle: wire.slug,\n safeAddress: toAddress(wire.safeAddress.toLowerCase()),\n role: viewerRole,\n treasury,\n bio: wire.bio ?? null,\n size: wire.size ?? null,\n logoUrl: wire.logoUrl ?? null,\n };\n}\n\n/**\n * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer\n * (the D3 RPC read). `available === balance` for a treasury with no envelope\n * partition yet (a fresh Org reads back $0).\n */\nexport function brandOrgTreasury(input: {\n readonly orgId: string;\n readonly money: Money;\n}): Account {\n return {\n id: toAccountId(`account_${orgIdBody(input.orgId)}`),\n balance: input.money,\n available: input.money,\n };\n}\n\nexport function brandOrgRole(wire: WireOrgRole): RoleView {\n return {\n orgId: toOrgId(wire.orgId),\n label: wire.label,\n roleKey: toRoleKey(wire.roleKey),\n definition: parseRoleDefinition(wire.definitionJson),\n };\n}\n\nexport function brandOrgMember(wire: WireOrgMember): MemberView {\n return {\n orgId: toOrgId(wire.orgId),\n email: toEmail(wire.email),\n name: wire.name,\n personalSafeAddress:\n wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),\n role: wire.role,\n roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),\n status: wire.status,\n grantTxHash: wire.grantTxHash,\n revokeTxHash: wire.revokeTxHash,\n };\n}\n\nfunction parseRoleDefinition(json: string): RoleDefinition {\n let raw: RawRoleDefinition;\n try {\n const parsed = JSON.parse(json) as unknown;\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"expected object\");\n }\n raw = parsed as RawRoleDefinition;\n } catch (err) {\n throw new Error(\n `Invalid role definition: malformed JSON - ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n if (typeof raw.label !== \"string\" || raw.label.trim().length === 0) {\n throw new Error(\"Invalid role definition: missing label\");\n }\n return {\n label: raw.label,\n ...(raw.spend === undefined\n ? {}\n : {\n spend: {\n ...(raw.spend.perTx === undefined\n ? {}\n : { perTx: parseRoleMoney(raw.spend.perTx, \"perTx\") }),\n ...(raw.spend.perDay === undefined\n ? {}\n : { perDay: parseRoleMoney(raw.spend.perDay, \"perDay\") }),\n ...(raw.spend.toRecipients === undefined\n ? {}\n : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }),\n },\n }),\n ...(raw.subAccounts === undefined\n ? {}\n : { subAccounts: parseRoleSubAccounts(raw.subAccounts) }),\n ...(typeof raw.canManageMembers === \"boolean\"\n ? { canManageMembers: raw.canManageMembers }\n : {}),\n ...(typeof raw.canManageRoles === \"boolean\" ? { canManageRoles: raw.canManageRoles } : {}),\n };\n}\n\nfunction parseRoleMoney(\n raw: { readonly currency: unknown; readonly value: unknown; readonly decimals: unknown },\n field: string,\n) {\n if (\n typeof raw.currency !== \"string\" ||\n typeof raw.value !== \"string\" ||\n !/^\\d+$/.test(raw.value) ||\n raw.decimals !== 6\n ) {\n throw new Error(`Invalid role money: ${field}`);\n }\n return {\n currency: toCurrencyCode(raw.currency),\n value: raw.value,\n decimals: raw.decimals,\n };\n}\n\nfunction parseRoleRecipients(raw: unknown): \"anyone\" | readonly Address[] {\n if (raw === \"anyone\") return \"anyone\";\n if (!Array.isArray(raw)) {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return raw.map((recipient) => {\n if (typeof recipient !== \"string\") {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return toAddress(recipient);\n });\n}\n\nfunction parseRoleSubAccounts(raw: { readonly scope?: unknown }) {\n if (raw.scope === \"all\") return { scope: \"all\" as const };\n if (!Array.isArray(raw.scope)) {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return {\n scope: raw.scope.map((subAccountId) => {\n if (typeof subAccountId !== \"string\") {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return toSubAccountId(subAccountId);\n }),\n };\n}\n\n/** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */\nfunction orgIdBody(orgId: string): string {\n const underscore = orgId.indexOf(\"_\");\n const tail = underscore < 0 ? orgId : orgId.slice(underscore + 1);\n const cleaned = tail.replace(/[^0-9A-Za-z]/g, \"\");\n return cleaned.length > 0 ? cleaned : \"0\";\n}\n","import { CapxulError, Errors } from \"@capxul/errors\";\nimport { toOrgId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect } from \"effect\";\n\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateOrgPortInput,\n DetectPendingOrgInvitationsInput,\n DetectPendingOrgInvitationsResult,\n InviteOrgMemberInput,\n ListOrgMembersInput,\n ListOrgRolesInput,\n ListOrgsInput,\n OrgError,\n OrgPort,\n ReadOrgTreasuryInput,\n ResendOrgInviteTokenInput,\n} from \"../../ports/org\";\nimport { orgErrorFromCapxul } from \"../../ports/org\";\nimport type { MemberView, OrgView, RoleView } from \"../../surface/org\";\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport {\n brandOrgMember,\n brandOrgRole,\n brandOrgTreasury,\n brandOrgView,\n type WireOrg,\n type WireOrgMember,\n type WireOrgRole,\n} from \"./parse\";\n\ntype WireTreasury = {\n readonly orgId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\ntype WireOrgListItem = WireOrg & { readonly viewerRole: string };\n\ntype DetectInvitationsWire = {\n readonly matched: readonly string[];\n readonly members: readonly WireOrgMember[];\n};\n\ntype OrganizationFunctions = {\n readonly listAll: FunctionReference<\n \"query\",\n \"public\",\n Record<never, never>,\n readonly WireOrgListItem[]\n >;\n readonly listRoles: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgRole[]\n >;\n readonly listMembers: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgMember[]\n >;\n readonly readTreasury: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string },\n WireTreasury\n >;\n readonly inviteMember: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly email: string; readonly role: string },\n WireOrgMember\n >;\n readonly resendInvite: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly email: string },\n WireOrgMember\n >;\n readonly detectInvitations: FunctionReference<\n \"action\",\n \"public\",\n Record<never, never>,\n DetectInvitationsWire\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationFunctions = {\n listAll: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listAll),\n listRoles: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listRolesByOrgId),\n listMembers: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listMembersByOrgId),\n readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].readTreasury),\n inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].inviteMember),\n resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/mutations\"].resendInviteToken),\n detectInvitations: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].detectAndAcceptPendingInvitations,\n ),\n};\n\n/**\n * Standard production Organization read adapter. It intentionally has no\n * deployer/RPC/test configuration: authenticated Convex actions own live chain\n * reads, while the lifecycle adapter owns the single sponsored bootstrap.\n */\nexport class ConvexOrganizationAdapter implements OrgPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: OrganizationFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly functions?: OrganizationFunctions;\n }) {\n this.#convex = input.convex;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n createOrg(_input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError> {\n return Effect.fail(\n orgErrorFromCapxul(\n \"createOrg\",\n Errors.notImplemented(\"organizationSetup\", \"use onboarding.completeOrganization\"),\n ),\n );\n }\n\n listOrgs(_input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError> {\n return this.#convex.query(this.#fns.listAll, {}).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listOrgs\", error.publicError, error)),\n Effect.flatMap((wires) =>\n Effect.forEach(wires, (wire) =>\n this.#readTreasuryWire(wire.orgId).pipe(\n Effect.map((treasury) => {\n const viewerRole = wire.viewerRole.trim();\n if (viewerRole.length === 0) {\n throw Errors.wrongState({\n method: \"listOrgs\",\n currentState: \"viewerRoleMissing\",\n validStates: [\"activeViewerRole\"],\n });\n }\n return brandOrgView(wire, treasury, viewerRole);\n }),\n ),\n ),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listOrgs\", cause))),\n );\n }\n\n readTreasury(input: ReadOrgTreasuryInput) {\n return this.#readTreasuryWire(String(input.orgId)).pipe(\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"readTreasury\", cause))),\n );\n }\n\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError> {\n return this.#convex.query(this.#fns.listRoles, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listRoles\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listRoles\", \"activeRoleMissing\"))\n : Effect.succeed(rows.map(brandOrgRole)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listRoles\", cause))),\n );\n }\n\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.#convex.query(this.#fns.listMembers, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listMembers\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listMembers\", \"activeMemberMissing\"))\n : Effect.succeed(rows.map(brandOrgMember)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listMembers\", cause))),\n );\n }\n\n pendingMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.listMembers(input).pipe(\n Effect.map((members) =>\n members.filter(\n (member) =>\n member.status === \"pending\" ||\n member.status === \"pending_safe\" ||\n member.status === \"pending_grant\",\n ),\n ),\n );\n }\n\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .action(this.#fns.inviteMember, {\n orgId: input.orgId,\n email: input.input.email,\n role: input.input.role,\n })\n .pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"inviteMember\", error.publicError, error)),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"inviteMember\", cause))),\n );\n }\n\n resendInviteToken(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .mutation(this.#fns.resendInvite, { orgId: input.orgId, email: input.email })\n .pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"resendInviteToken\", error.publicError, error),\n ),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"resendInviteToken\", cause))),\n );\n }\n\n detectAndAcceptPendingInvitations(\n _input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError> {\n return this.#convex.action(this.#fns.detectInvitations, {}).pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"detectAndAcceptPendingInvitations\", error.publicError, error),\n ),\n Effect.map((result) => ({ matched: result.matched.map(toOrgId) })),\n Effect.catchDefect((cause) =>\n Effect.fail(toOrgError(\"detectAndAcceptPendingInvitations\", cause)),\n ),\n );\n }\n\n #readTreasuryWire(orgId: string) {\n return this.#convex.action(this.#fns.readTreasury, { orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"readTreasury\", error.publicError, error)),\n Effect.map((wire) => {\n if (wire.orgId !== orgId) {\n throw Errors.invalidInput(\"orgId\", \"Organization treasury scope does not match\");\n }\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);\n const account = brandOrgTreasury({ orgId: wire.orgId, money: balance });\n return { ...account, available };\n }),\n );\n }\n}\n\nfunction toOrgError(operation: string, cause: unknown): OrgError {\n if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);\n return orgErrorFromCapxul(operation, Errors.providerError(\"convex\", operation, cause), cause);\n}\n\nfunction partialOrgTruth(operation: string, currentState: string): OrgError {\n return orgErrorFromCapxul(\n operation,\n Errors.wrongState({\n method: operation,\n currentState,\n validStates: [\"completeProductionOrganizationTruth\"],\n }),\n );\n}\n","import { CapxulError, Errors, type CapxulErrorCode } from \"@capxul/errors\";\nimport { toOrgId, type OrgId } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Result } from \"effect\";\nimport type { Hex } from \"viem\";\n\nimport type {\n OrganizationSetupOps,\n OrganizationSetupStepInput,\n OrgLifecycle,\n RecordOrganizationSetupFailureInput,\n StartOrResumeOrganizationInput,\n} from \"../../surface/org-lifecycle\";\nimport type { CapxulResult } from \"../../surface/types\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type { CapxulSigner } from \"../../signer\";\n\ntype WireLifecycle =\n | { readonly status: \"loading\"; readonly orgId: string }\n | {\n readonly status: \"settingUp\";\n readonly orgId: string;\n readonly step: OrgLifecycle extends infer _ ? string : never;\n }\n | { readonly status: \"ready\"; readonly orgId: string; readonly canTransact: true }\n | {\n readonly status: \"failed\";\n readonly orgId: string;\n readonly at: string;\n readonly error: { readonly code: CapxulErrorCode; readonly message: string };\n readonly retryable: boolean;\n };\n\nexport type OrganizationBootstrapUserOp = {\n readonly sender: string;\n readonly nonce: string;\n readonly factory?: string;\n readonly factoryData?: string;\n readonly callData: string;\n readonly callGasLimit: string;\n readonly verificationGasLimit: string;\n readonly preVerificationGas: string;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n readonly paymaster: string;\n readonly paymasterVerificationGasLimit?: string;\n readonly paymasterPostOpGasLimit?: string;\n readonly paymasterData: string;\n};\n\ntype PreparedBootstrap = {\n readonly digest: string;\n readonly signerAddress: string;\n readonly founderPersonalAccount: string;\n readonly organizationAccountAddress: string;\n readonly userOp: OrganizationBootstrapUserOp;\n};\n\ntype OrganizationSetupFunctions = {\n readonly startOrResume: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly name: string;\n readonly handle: string;\n readonly country: string;\n // #1064: onboarding-collected description + size bucket, pass-through.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly chainId: number;\n readonly observationContext?: WireObservationContext;\n },\n { readonly orgId: string; readonly lifecycle: WireLifecycle }\n >;\n readonly prepareFounderAccount: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly prepareBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly observationContext?: WireObservationContext;\n },\n PreparedBootstrap\n >;\n readonly submitBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly signature: string;\n readonly userOp: OrganizationBootstrapUserOp;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly resumeBootstrapSubmission: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly confirmBootstrap: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly recordFailure: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly orgId: string;\n readonly errorCode: string;\n readonly errorProvider?: string;\n readonly errorOperation?: string;\n readonly retryable: boolean;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly load: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle | null\n >;\n readonly retry: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationSetupFunctions = {\n startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].startOrResume),\n prepareFounderAccount: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].prepareFounderAccount,\n ),\n prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].prepareBootstrap),\n submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].submitBootstrap),\n resumeBootstrapSubmission: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].resumeBootstrapSubmission,\n ),\n confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].confirmBootstrap),\n recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].recordFailure),\n load: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].load),\n retry: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].retry),\n};\n\n/** Durable Organization setup capability composed by the standard client. */\nexport class ConvexOrganizationSetupAdapter implements OrganizationSetupOps {\n readonly #convex: ConvexCallPort;\n readonly #signer: CapxulSigner;\n readonly #chainId: number;\n readonly #fns: OrganizationSetupFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly signer: CapxulSigner;\n readonly chainId: number;\n readonly functions?: OrganizationSetupFunctions;\n }) {\n this.#convex = input.convex;\n this.#signer = input.signer;\n this.#chainId = input.chainId;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n async startOrResume(\n input: StartOrResumeOrganizationInput,\n ): Promise<CapxulResult<{ readonly orgId: OrgId; readonly lifecycle: OrgLifecycle }>> {\n const result = await runCall<{\n readonly orgId: string;\n readonly lifecycle: WireLifecycle;\n }>(\n \"startOrResume\",\n this.#convex.mutation(\n this.#fns.startOrResume,\n copyInvocationObservation(input, { ...input, chainId: this.#chainId }),\n ),\n );\n if (!result.ok) return result;\n const lifecycle = parseLifecycle(\"startOrResume\", result.value.lifecycle);\n if (!lifecycle.ok) return lifecycle;\n const orgId = parseOrgId(\"startOrResume\", result.value.orgId);\n if (!orgId.ok) return orgId;\n if (String(orgId.value) !== String(lifecycle.value.orgId)) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle scope does not match\"));\n }\n return { ok: true, value: { orgId: orgId.value, lifecycle: lifecycle.value } } as const;\n }\n\n prepareFounderAccount(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"prepareFounderAccount\", input, () =>\n this.#convex.action(\n this.#fns.prepareFounderAccount,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async authorizeAndSubmitBootstrap(\n input: OrganizationSetupStepInput,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n\n const signerAddress = await signerResult(\"getAddress\", () => this.#signer.getAddress());\n if (!signerAddress.ok) return signerAddress;\n const prepared = await runCall(\n \"prepareBootstrap\",\n this.#convex.action(\n this.#fns.prepareBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!prepared.ok) return prepared;\n const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);\n if (!authority.ok) return authority;\n const cancelledAfterPrepare = cancellation(input.signal);\n if (cancelledAfterPrepare !== undefined) return cancelledAfterPrepare;\n\n const signature = await signerResult(\"signUserOpHash\", () =>\n this.#signer.signUserOpHash(prepared.value.digest as Hex),\n );\n if (!signature.ok) return signature;\n const cancelledAfterSign = cancellation(input.signal);\n if (cancelledAfterSign !== undefined) return cancelledAfterSign;\n\n const submitted = await runCall(\n \"submitBootstrap\",\n this.#convex.action(\n this.#fns.submitBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n signature: signature.value,\n userOp: prepared.value.userOp,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!submitted.ok) return submitted;\n return parseLifecycle(\"submitBootstrap\", submitted.value);\n }\n\n resumeSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"resumeBootstrapSubmission\", input, () =>\n this.#convex.action(\n this.#fns.resumeBootstrapSubmission,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n confirmSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"confirmBootstrap\", input, () =>\n this.#convex.action(\n this.#fns.confirmBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async recordFailure(input: RecordOrganizationSetupFailureInput) {\n const errorProvider = input.error.details?.provider;\n const errorOperation = input.error.details?.operation;\n const result = await runCall(\n \"recordFailure\",\n this.#convex.mutation(\n this.#fns.recordFailure,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n errorCode: input.error.code,\n ...(typeof errorProvider === \"string\" && typeof errorOperation === \"string\"\n ? { errorProvider, errorOperation }\n : {}),\n retryable: input.retryable,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n return result.ok ? parseLifecycle(\"recordFailure\", result.value) : result;\n }\n\n async loadLifecycle(input: {\n readonly orgId: OrgId;\n readonly observationContext?: WireObservationContext;\n }): Promise<CapxulResult<OrgLifecycle>> {\n const result = await runCall<WireLifecycle | null>(\n \"loadLifecycle\",\n this.#convex.query(this.#fns.load, input),\n );\n if (!result.ok) return result;\n if (result.value === null) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle was not found\"));\n }\n return parseLifecycle(\"loadLifecycle\", result.value);\n }\n\n async retry(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const current = await this.loadLifecycle({\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n });\n if (!current.ok) return current;\n if (\n current.value.status === \"failed\" &&\n current.value.retryable &&\n (current.value.at === \"awaitingFounderAuthorization\" ||\n current.value.at === \"submittingBootstrap\")\n ) {\n const reset = resetSignerSession(this.#signer);\n if (!reset.ok) return reset;\n }\n const result = await runCall(\n \"retry\",\n this.#convex.mutation(\n this.#fns.retry,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!result.ok) return result;\n return parseLifecycle(\"retry\", result.value);\n }\n\n async #lifecycleAction(\n operation: string,\n input: OrganizationSetupStepInput,\n call: () => Effect.Effect<WireLifecycle, unknown>,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const result = await runCall(operation, call());\n if (!result.ok) return result;\n const cancelledAfter = cancellation(input.signal);\n if (cancelledAfter !== undefined) return cancelledAfter;\n return parseLifecycle(operation, result.value);\n }\n}\n\nfunction resetSignerSession(signer: CapxulSigner): CapxulResult<void> {\n const resetSession = (signer as CapxulSigner & { readonly resetSession?: unknown }).resetSession;\n if (typeof resetSession !== \"function\") return { ok: true, value: undefined };\n try {\n resetSession.call(signer);\n return { ok: true, value: undefined };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", \"resetSession\", cause, {\n failure_mode: \"unknown\",\n }),\n );\n }\n}\n\nasync function runCall<T>(\n operation: string,\n effect: Effect.Effect<T, unknown>,\n): Promise<CapxulResult<T>> {\n try {\n const result = await Effect.runPromise(Effect.result(effect));\n return Result.isSuccess(result)\n ? { ok: true, value: result.success }\n : fail(publicError(operation, result.failure));\n } catch (cause) {\n return fail(publicError(operation, cause));\n }\n}\n\nfunction publicError(operation: string, cause: unknown): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const carried = (cause as { readonly publicError?: unknown }).publicError;\n if (carried instanceof CapxulError) return carried;\n }\n return Errors.providerError(\"convex-organization\", operation, cause);\n}\n\nasync function signerResult<T>(operation: string, run: () => Promise<T>): Promise<CapxulResult<T>> {\n try {\n return { ok: true, value: await run() };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"organization-signer\", operation, cause),\n );\n }\n}\n\nfunction validatePreparedAuthorities(\n prepared: PreparedBootstrap,\n signerAddress: string,\n): CapxulResult<void> {\n const signer = signerAddress.toLowerCase();\n const preparedSigner = prepared.signerAddress.toLowerCase();\n const founder = prepared.founderPersonalAccount.toLowerCase();\n const organization = prepared.organizationAccountAddress.toLowerCase();\n const sender = prepared.userOp.sender.toLowerCase();\n if (preparedSigner !== signer) {\n return fail(\n Errors.invalidInput(\"signerAddress\", \"Prepared signer does not match configured signer\"),\n );\n }\n if (founder === signer || organization === signer || organization === founder) {\n return fail(\n Errors.invalidInput(\n \"organizationAuthority\",\n \"Signer EOA, founder Account, and Organization Account must be distinct\",\n ),\n );\n }\n if (sender !== founder) {\n return fail(\n Errors.invalidInput(\"userOp.sender\", \"Bootstrap sender must be the founder Account\"),\n );\n }\n if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) {\n return fail(Errors.invalidInput(\"digest\", \"Prepared bootstrap digest must be 32-byte hex\"));\n }\n return { ok: true, value: undefined };\n}\n\nfunction parseLifecycle(operation: string, wire: WireLifecycle): CapxulResult<OrgLifecycle> {\n const orgId = parseOrgId(operation, wire.orgId);\n if (!orgId.ok) return orgId;\n if (wire.status === \"loading\")\n return { ok: true, value: { status: \"loading\", orgId: orgId.value } };\n if (wire.status === \"ready\") {\n return { ok: true, value: { status: \"ready\", orgId: orgId.value, canTransact: true } };\n }\n if (wire.status === \"failed\") {\n if (!isSetupStep(wire.at))\n return fail(Errors.invalidInput(\"lifecycle.at\", \"Unknown setup step\"));\n return {\n ok: true,\n value: {\n status: \"failed\",\n orgId: orgId.value,\n at: wire.at,\n error: new CapxulError(wire.error.code, wire.error.message),\n retryable: wire.retryable,\n },\n };\n }\n if (!isSetupStep(wire.step)) {\n return fail(Errors.invalidInput(\"lifecycle.step\", `Unknown setup step from ${operation}`));\n }\n return { ok: true, value: { status: \"settingUp\", orgId: orgId.value, step: wire.step } };\n}\n\nfunction parseOrgId(operation: string, value: string): CapxulResult<OrgId> {\n try {\n return { ok: true, value: toOrgId(value) };\n } catch (cause) {\n return fail(Errors.providerError(\"convex-organization\", operation, cause));\n }\n}\n\nfunction isSetupStep(\n value: string,\n): value is Extract<OrgLifecycle, { status: \"settingUp\" }>[\"step\"] {\n return (\n value === \"preparingFounderAccount\" ||\n value === \"awaitingFounderAuthorization\" ||\n value === \"submittingBootstrap\" ||\n value === \"confirmingBootstrap\"\n );\n}\n\nfunction cancellation(signal: AbortSignal | undefined): CapxulResult<never> | undefined {\n return signal?.aborted ? fail(Errors.cancelled({ operation: \"organization.setup\" })) : undefined;\n}\n\nfunction fail<T>(error: CapxulError): CapxulResult<T> {\n return { ok: false, error };\n}\n","import type { DiagnosticDetail, DiagnosticPort } from \"../../ports/diagnostic\";\n\nconst DEFAULT_ACCOUNT_SETUP_LOG_PREFIX = \"[capxul:account-setup]\";\n\nexport class ConsoleDiagnosticAdapter implements DiagnosticPort {\n private readonly prefix: string;\n\n constructor(prefix: string = DEFAULT_ACCOUNT_SETUP_LOG_PREFIX) {\n this.prefix = prefix;\n }\n\n trace(scope: string, detail: DiagnosticDetail): void {\n globalThis.console?.debug?.(`${this.prefix} ${scope}`, detail);\n }\n}\n\nexport function ConsoleDiagnosticLayer(prefix?: string): DiagnosticPort {\n return new ConsoleDiagnosticAdapter(prefix);\n}\n","import {\n AccountTypeEnum,\n ChainTypeEnum,\n EmbeddedState,\n Openfort,\n RecoveryMethod,\n ThirdPartyOAuthProvider,\n} from \"@openfort/openfort-js\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\n\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { DiagnosticPort } from \"../ports/diagnostic\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport type { CapxulSigner } from \"../signer\";\nimport { openfortEmbeddedSignerFromWallet } from \"../openfort-embedded-signer\";\n\nexport interface OpenfortBrowserSigner extends CapxulSigner {\n readonly resetSession: () => void;\n}\n\nfunction openfortProviderError(operation: string, cause: unknown): CapxulError {\n return cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", operation, cause, { failure_mode: \"unknown\" });\n}\n\nexport interface OpenfortBrowserSignerOptions {\n readonly diagnostic?: DiagnosticPort;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * True when the browser cannot perform Web Crypto — sandboxed iframes, headless\n * agent browsers, or non-HTTPS origins. OpenFort's embedded-wallet `configure`\n * silently produces no address in this state, so we detect it up front and name\n * it `no-secure-context` instead of letting it decay into `unknown`.\n */\nfunction isInsecureBrowserContext(): boolean {\n return globalThis.isSecureContext === false || globalThis.crypto?.subtle === undefined;\n}\n\n/** Openfort SDK storage keys (`@openfort/openfort-js` StorageKeys). */\nconst OPENFORT_BROWSER_STORAGE_KEYS = [\n \"openfort.authentication\",\n \"openfort.account\",\n \"openfort.session\",\n \"openfort.configuration\",\n] as const;\n\n/**\n * Matches `@openfort/openfort-js` ScopedStorage.createScope — chars 8–15 of the\n * publishable key, prefixed onto each StorageKeys entry in localStorage.\n */\nexport function openfortBrowserStorageScope(publishableKey: string): string | undefined {\n const trimmed = publishableKey.trim();\n if (trimmed.length < 16) {\n return undefined;\n }\n return trimmed.substring(8, 16);\n}\n\n/**\n * Drop cached Openfort auth/account state so third-party login re-runs for the\n * current Better Auth session. The SDK skips `authenticateThirdParty` when a\n * stale `userId` is already in storage, which yields 401 on `v2/accounts`.\n */\nfunction clearStaleOpenfortBrowserStorage(publishableKey: string): void {\n if (typeof localStorage === \"undefined\") {\n return;\n }\n const scope = openfortBrowserStorageScope(publishableKey);\n if (scope === undefined) {\n return;\n }\n for (const key of OPENFORT_BROWSER_STORAGE_KEYS) {\n localStorage.removeItem(`${scope}.${key}`);\n }\n}\n\nexport function createOpenfortBrowserSignerFromBootstrap(\n bootstrap: BootstrapResolution,\n options: OpenfortBrowserSignerOptions = {},\n): OpenfortBrowserSigner {\n const diagnostic = options.diagnostic;\n const telemetry = options.telemetry;\n const authBaseUrl = normalizeBetterAuthBaseUrl(bootstrap.authBaseUrl);\n\n /**\n * Closes the black hole: when the browser has no Web Crypto, OpenFort's\n * `configure` would resolve to no address and the failure would be reported\n * as `unknown`. Detect it before any network/wallet work, tag it\n * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`, breadcrumb\n * it via DiagnosticPort, and self-report via TelemetryPort.\n */\n function failNoSecureContext(): never {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"no-secure-context\",\n });\n const error = Errors.providerError(\n \"openfort\",\n \"configure\",\n new Error(\"Web Crypto unavailable: browser is not a secure context\"),\n { failure_mode: \"no-secure-context\" },\n );\n if (telemetry) {\n captureExceptionSync(telemetry, error, {\n layer: \"openfort\",\n operation: \"configure\",\n provider: \"openfort\",\n failure_mode: \"no-secure-context\",\n });\n }\n throw error;\n }\n\n function betterAuthSessionUrl(): string {\n return `${authBaseUrl}/get-session`;\n }\n\n function encryptionSessionUrl(): string {\n return `${authBaseUrl}/encryption-session`;\n }\n\n async function fetchBetterAuthAccessToken(): Promise<string | null> {\n try {\n const response = await fetch(betterAuthSessionUrl(), { credentials: \"include\" });\n if (!response.ok) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n httpStatus: response.status,\n failure_mode: \"unknown\",\n });\n return null;\n }\n const body = (await response.json()) as { session?: { token?: string } };\n const token = body.session?.token?.trim();\n if (token === undefined || token.length === 0) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n return null;\n }\n diagnostic?.trace(\"openfort.token\", { ok: true, tokenPresent: true });\n return token;\n } catch (cause) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"token\", cause);\n }\n }\n\n const openfort = new Openfort({\n baseConfiguration: {\n publishableKey: bootstrap.openfortPublishableKey,\n },\n shieldConfiguration: {\n shieldPublishableKey: bootstrap.shieldPublishableKey,\n },\n thirdPartyAuth: {\n provider: ThirdPartyOAuthProvider.BETTER_AUTH,\n getAccessToken: fetchBetterAuthAccessToken,\n },\n });\n\n let walletReadyPromise: Promise<void> | null = null;\n\n function startWalletReady(): Promise<void> {\n return (async () => {\n if (isInsecureBrowserContext()) {\n failNoSecureContext();\n }\n await openfort.waitForInitialization();\n\n const accessToken = await fetchBetterAuthAccessToken();\n if (accessToken === null) {\n throw openfortProviderError(\n \"token\",\n new Error(\"Better Auth access token unavailable for Openfort\"),\n );\n }\n\n let encryptionResponse: Response;\n try {\n encryptionResponse = await fetch(encryptionSessionUrl(), {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n });\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n if (!encryptionResponse.ok) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw Errors.providerError(\n \"openfort\",\n \"encryptionSession\",\n new Error(`Openfort encryption session failed (${encryptionResponse.status})`),\n { failure_mode: \"unknown\" },\n );\n }\n let encryptionBody: { sessionId?: string };\n try {\n encryptionBody = (await encryptionResponse.json()) as { sessionId?: string };\n if (typeof encryptionBody.sessionId !== \"string\" || encryptionBody.sessionId.length === 0) {\n throw new Error(\"Openfort encryption session response missing sessionId\");\n }\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: true,\n httpStatus: encryptionResponse.status,\n });\n\n let embeddedState: EmbeddedState;\n try {\n embeddedState = await openfort.embeddedWallet.getEmbeddedState();\n diagnostic?.trace(\"openfort.embeddedState\", { state: embeddedState });\n } catch (cause) {\n diagnostic?.trace(\"openfort.embeddedState\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"embeddedState\", cause);\n }\n if (embeddedState !== EmbeddedState.READY) {\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n diagnostic?.trace(\"openfort.storageCleared\", { beforeConfigure: true });\n try {\n await openfort.embeddedWallet.configure({\n accountType: AccountTypeEnum.EOA,\n chainType: ChainTypeEnum.EVM,\n recoveryParams: {\n recoveryMethod: RecoveryMethod.AUTOMATIC,\n encryptionSession: encryptionBody.sessionId,\n },\n });\n diagnostic?.trace(\"openfort.configure\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"configure\", cause);\n }\n }\n\n try {\n await openfort.embeddedWallet.get();\n diagnostic?.trace(\"openfort.get\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.get\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"get\", cause);\n }\n })();\n }\n\n async function ensureOpenfortWalletReady(): Promise<void> {\n walletReadyPromise ??= startWalletReady();\n try {\n await walletReadyPromise;\n } catch (cause) {\n walletReadyPromise = null;\n throw cause;\n }\n }\n\n const signer = openfortEmbeddedSignerFromWallet({\n embeddedWallet: openfort.embeddedWallet,\n ensureWalletReady: ensureOpenfortWalletReady,\n });\n\n return {\n ...signer,\n getAddress: async () => {\n try {\n const address = await signer.getAddress();\n diagnostic?.trace(\"openfort.address\", { ok: true });\n return address;\n } catch (cause) {\n diagnostic?.trace(\"openfort.address\", { ok: false, failure_mode: \"unknown\" });\n throw openfortProviderError(\"getAddress\", cause);\n }\n },\n resetSession: () => {\n walletReadyPromise = null;\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n signer.resetAddressCache();\n },\n };\n}\n\nfunction normalizeBetterAuthBaseUrl(raw: string): string {\n const trimmed = raw.replace(/\\/$/, \"\");\n return trimmed.endsWith(\"/api/auth\") ? trimmed : `${trimmed}/api/auth`;\n}\n","import { sanitizeObservationContext } from \"@capxul/wire/observation-context\";\nimport type { CapxulEnv } from \"@capxul/observability\";\n\nimport {\n observationContextProps,\n postHogFailureObservation,\n type ObservationAdapter,\n type ObservationContext,\n} from \"./observation\";\nimport type { TelemetryPort } from \"./ports/telemetry\";\nimport { postHogProductTelemetry } from \"./telemetry/from-posthog\";\nimport type { InvocationObservationSnapshot } from \"./internal/invocation-observation\";\n\nconst HOST_INVOCATION = Symbol(\"capxul.host-observability-invocation\");\n\n/** One host-owned observability module at the SDK consumer boundary. */\nexport interface HostObservability {\n readonly failures: ObservationAdapter;\n readonly product: TelemetryPort;\n}\n\nexport interface PostHogObservabilityClient {\n capture(event: string, properties?: Readonly<Record<string, unknown>>): unknown;\n captureException?(exception: Error, properties?: Readonly<Record<string, unknown>>): unknown;\n identify?(distinctId: string, properties?: Readonly<Record<string, unknown>>): unknown;\n group?(\n groupType: string,\n groupKey: string,\n properties?: Readonly<Record<string, unknown>>,\n ): unknown;\n reset?(): unknown;\n}\n\nexport interface PostHogObservabilityOptions {\n /** Consent / kill-switch seam. Defaults to enabled. */\n readonly enabled?: boolean | (() => boolean);\n /** Host environment stamped on every SDK-owned product event. */\n readonly capxulEnv?: CapxulEnv;\n /** Host-owned correlation context shared by product and failure delivery. */\n readonly context?: ObservationContext | (() => ObservationContext | undefined);\n}\n\n/** @internal One immutable host decision for one delivery invocation. */\nexport interface PostHogHostSnapshot {\n readonly active: boolean;\n readonly context?: ObservationContext;\n readonly contextProps: Readonly<Record<string, string>>;\n}\n\ntype InvocationBindableHostObservability = HostObservability & {\n readonly [HOST_INVOCATION]?: {\n readonly bind: () => HostObservability;\n readonly snapshot: () => PostHogHostSnapshot;\n };\n};\n\n/** @internal Shared policy passed to the two semantic projections. */\nexport interface PostHogHostPolicy {\n readonly client: PostHogObservabilityClient | null | undefined;\n readonly capxulEnv: CapxulEnv;\n readonly snapshot: () => PostHogHostSnapshot;\n readonly deliver: (capture: () => unknown) => void;\n}\n\n/** Build the SDK's one host module around an already-initialized PostHog client. */\nexport function postHogObservability(\n client: PostHogObservabilityClient | null | undefined,\n options: PostHogObservabilityOptions = {},\n): HostObservability {\n const inactive = Object.freeze({\n active: false,\n contextProps: Object.freeze({}),\n }) satisfies PostHogHostSnapshot;\n const snapshot = (): PostHogHostSnapshot => {\n if (client === null || client === undefined) return inactive;\n try {\n const active =\n typeof options.enabled === \"function\" ? options.enabled() : (options.enabled ?? true);\n if (!active) return inactive;\n const rawContext =\n typeof options.context === \"function\" ? options.context() : options.context;\n const sanitized = sanitizeObservationContext(rawContext) as ObservationContext | undefined;\n const context = sanitized === undefined ? undefined : Object.freeze({ ...sanitized });\n return Object.freeze({\n active: true,\n ...(context === undefined ? {} : { context }),\n contextProps: Object.freeze(observationContextProps(context)),\n });\n } catch {\n return inactive;\n }\n };\n const policy: PostHogHostPolicy = {\n client,\n capxulEnv: options.capxulEnv ?? \"unknown\",\n snapshot,\n deliver: (capture) => {\n try {\n const delivery = capture();\n if (isPromiseLike(delivery)) void Promise.resolve(delivery).catch(() => undefined);\n } catch {\n // Host observation is best effort and can never become an SDK failure.\n }\n },\n };\n const module: HostObservability = {\n failures: postHogFailureObservation(policy),\n product: postHogProductTelemetry(policy),\n };\n Object.defineProperty(module, HOST_INVOCATION, {\n enumerable: false,\n value: {\n bind: () => {\n const invocation = snapshot();\n return {\n failures: postHogFailureObservation(policy, invocation),\n product: postHogProductTelemetry(policy, invocation),\n };\n },\n snapshot,\n },\n });\n return module;\n}\n\n/** @internal Bind both projections to one call-start decision/context snapshot. */\nexport function bindHostObservabilityInvocation(\n observability: HostObservability | undefined,\n): HostObservability | undefined {\n return (\n (observability as InvocationBindableHostObservability | undefined)?.[HOST_INVOCATION]?.bind() ??\n observability\n );\n}\n\n/** @internal Read one call-start snapshot for actor/transition carriage. */\nexport function snapshotHostObservability(\n observability: HostObservability | undefined,\n): InvocationObservationSnapshot | undefined {\n const snapshot = (observability as InvocationBindableHostObservability | undefined)?.[\n HOST_INVOCATION\n ]?.snapshot();\n return snapshot === undefined\n ? undefined\n : {\n active: snapshot.active,\n ...(snapshot.context === undefined ? {} : { context: snapshot.context }),\n };\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n ((typeof value === \"object\" && value !== null) || typeof value === \"function\") &&\n \"then\" in value\n );\n}\n","import { Context, Effect, Result, Exit, Layer, Scope } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toAllowedOrigin, toPublishableKey, type ChainId } from \"@capxul/types\";\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport { makeEngineeringTelemetryLayer } from \"@capxul/observability/engineering\";\n\nimport { BetterAuthBrowserLayer, BetterAuthNodeLayer } from \"./adapters/auth-client\";\nimport { HttpBootstrapLayer } from \"./adapters/bootstrap\";\nimport { SystemClockLayer } from \"./adapters/clock\";\nimport { ConvexCallLayer, type ConvexClientShape } from \"./adapters/convex-call\";\nimport { ConvexIdentityLayer } from \"./adapters/identity\";\nimport { ConvexAccountLayer } from \"./adapters/account-read\";\nimport { ConvexSubAccountLayer } from \"./adapters/sub-account/ConvexSubAccountAdapter\";\nimport { ConvexSmartAccountLayer } from \"./adapters/smart-account\";\nimport { ConvexOrganizationAdapter } from \"./adapters/org/ConvexOrganizationAdapter\";\nimport { ConvexOrganizationSetupAdapter } from \"./adapters/org/ConvexOrganizationSetupAdapter\";\nimport { PostHogTelemetryLayer } from \"./adapters/telemetry\";\nimport { ConsoleDiagnosticAdapter } from \"./adapters/diagnostic/ConsoleDiagnosticAdapter\";\nimport { assertDevKeySignerIsTestnetOnly } from \"./dev-signer\";\nimport type { AccountRequirement } from \"./surface/account-providers\";\nimport {\n createOpenfortBrowserSignerFromBootstrap,\n type OpenfortBrowserSigner,\n} from \"./openfort/create-openfort-browser-signer\";\nimport type { CapxulSigner } from \"./signer\";\nimport {\n assembleCapxulClient,\n type CapxulClient,\n type CreateCapxulClientInput,\n} from \"./surface/create-capxul-client\";\nimport { detectAuthCacheAdapter } from \"./surface/factory\";\nimport type { CapxulResult } from \"./surface/types\";\nimport { observeFailedResult, type ObservationAdapter } from \"./observation\";\nimport {\n bindHostObservabilityInvocation,\n snapshotHostObservability,\n type HostObservability,\n} from \"./host-observability\";\nimport type { FlowPorts } from \"./flows/types\";\nimport { AuthClientPortTag, type AuthClientPort } from \"./ports/auth-client\";\nimport { AuthCachePortTag, type AuthCachePort } from \"./ports/auth-cache\";\nimport { BootstrapPortTag, type BootstrapPort, type BootstrapResolution } from \"./ports/bootstrap\";\nimport { ClockPortTag } from \"./ports/clock\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"./ports/convex-call\";\nimport { IdentityPortTag } from \"./ports/identity\";\nimport { OrgPortTag, type OrgPort } from \"./ports/org\";\nimport { AccountReadPortTag } from \"./ports/account-read\";\nimport { SubAccountPortTag } from \"./ports/sub-account\";\nimport { SmartAccountPortTag } from \"./ports/smart-account\";\nimport type { TelemetryEvent, TelemetryPort } from \"./ports/telemetry\";\nimport { TelemetryPortTag } from \"./ports/telemetry\";\n\nexport type ProductionRuntime = \"browser\" | \"node\";\nexport type ProductionAdapterClose = () => Promise<void>;\n\n/**\n * Interim default Capxul bootstrap host (SDK publish readiness · I3). Node\n * consumers pass neither `origin` nor `bootstrapBaseUrl`; both default here so\n * `createCapxulClient({ publishableKey })` reaches the Capxul backend with no\n * extra wiring. Superseded by the key-encoded host (`cap_pk_live_…`, out of\n * scope this milestone). See `packages/sdk/CONTEXT.md`.\n */\nexport const DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL = \"https://api.capxul.com\";\n\n/** Default per-request auth invocation timeout (ms) when the consumer omits it. */\nexport const DEFAULT_INVOKE_TIMEOUT_MS = 30_000;\n\n/**\n * Consumer-facing `createCapxulClient` input (SDK DX public surface · #326).\n * The publishable key is the primary input; bootstrap host, invoke timeout,\n * runtime detection, and auth-cache selection are SDK-owned defaults.\n */\nexport interface CapxulClientInput {\n readonly publishableKey: string;\n /**\n * One host-owned product/failure observability module around the host's\n * existing analytics client. Omit for zero host observation work.\n */\n readonly observability?: HostObservability;\n /**\n * Init-time account readiness target (issue #159 · AC4). Threaded into\n * `assembleCapxulClient` so `client.account.{getStatus,ensureReady}` reflect\n * the consumer's chosen requirement. Optional — defaults to `\"none\"` (SDK\n * publish readiness · I3) so `createCapxulClient({ publishableKey })` works\n * with no account lane.\n */\n readonly requirement?: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n}\n\n/**\n * Internal production adapter input for `@capxul/sdk/production` and hermetic\n * tests. Extends the consumer contract with bootstrap/fetch/runtime/auth-cache/\n * signal/timeout seams that must not appear on the bare `@capxul/sdk` barrel.\n * Org deployment port factories and deploy config live on\n * `@capxul/sdk/testing/org-deployment-client` (#327).\n */\nexport interface ProductionAdapterInput extends CapxulClientInput {\n readonly origin?: string;\n readonly bootstrapBaseUrl?: string;\n /** Optional BetterAuth host override (dogfood Vite proxy → same-origin `/api/auth`). */\n readonly authBaseUrl?: string;\n readonly runtime?: ProductionRuntime;\n readonly authCache?: AuthCachePort;\n /** @internal Adapter-layer observation seam; public callers use `observability`. */\n readonly observation?: ObservationAdapter;\n /** @internal Adapter-layer product seam; public callers use `observability`. */\n readonly telemetry?: TelemetryPort;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n}\n\n/**\n * @internal Test-injection seam. `convexClientFactory` is intentionally NOT a\n * member of the public `ProductionAdapterInput` (production-surface-policy.md):\n * consumers must not inject a Convex client. Hermetic tests pass a fake through\n * the fixture; it is read back here.\n */\ninterface ProductionConvexClientFactorySeam {\n readonly convexClientFactory?: (convexUrl: string) => ConvexClientShape;\n}\n\nexport interface ProductionAdapters {\n /**\n * THE RUNTIME (A2-Q1A, blueprint §2: \"the graph is the runtime, never\n * flattened to a record\"). This is the built Layer graph, alive in the same\n * `Scope` as `close`. Anything that needs a port resolves it from here.\n *\n * `ports` below is a PROJECTION of this context for the method bundles,\n * which still take ports as plain values — that is the shape L1 replaces\n * when it rebuilds the flows. Until then the projection is a convenience\n * VIEW of the graph, not a replacement for it: before the re-cut the graph\n * was discarded the moment the record was made, so nothing downstream could\n * resolve a tag, run an Effect against the real wiring, or add a port\n * without widening a hand-written record.\n */\n readonly context: Context.Context<ProductionFlowPortTags>;\n readonly ports: FlowPorts;\n readonly bootstrap: BootstrapResolution;\n readonly close: ProductionAdapterClose;\n}\n\nexport type ProductionAdapterLayerName =\n | \"bootstrap\"\n | \"authClient\"\n | \"authCache\"\n | \"identity\"\n | \"smartAccount\"\n | \"accountRead\"\n | \"subAccount\"\n | \"clock\"\n | \"telemetry\"\n | \"convexCall\"\n | \"org\";\n\nexport type ProductionFlowPortTags =\n | AuthClientPortTag\n | AuthCachePortTag\n | BootstrapPortTag\n | ClockPortTag\n | ConvexCallPortTag\n | IdentityPortTag\n | SmartAccountPortTag\n | AccountReadPortTag\n | SubAccountPortTag\n | TelemetryPortTag\n | OrgPortTag;\n\ntype RefreshConvexAuthRef = {\n current: (() => void) | null;\n pending: boolean;\n};\n\n/**\n * The embedded signer's session-reset callback, resolved after the graph is\n * built (the browser signer is derived from the bootstrap the graph itself\n * needs). Same late-binding idiom as `RefreshConvexAuthRef` above — the auth\n * layer closes over the ref and reads `current` at call time.\n */\ntype ResetSignerSessionRef = {\n current: (() => void) | null;\n};\n\nconst SDK_VERSION = sdkPackageJson.version;\n\ntype ProductionAdapterLayerOutput<N extends ProductionAdapterLayerName> = {\n readonly bootstrap: BootstrapPortTag;\n readonly authClient: AuthClientPortTag;\n readonly authCache: AuthCachePortTag;\n readonly identity: IdentityPortTag;\n readonly smartAccount: SmartAccountPortTag;\n readonly accountRead: AccountReadPortTag;\n readonly subAccount: SubAccountPortTag;\n readonly clock: ClockPortTag;\n readonly telemetry: TelemetryPortTag;\n readonly convexCall: ConvexCallPortTag;\n readonly org: OrgPortTag;\n}[N];\n\nexport interface ProductionRuntimeUrls {\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n}\n\nexport interface ProductionAdapterLayerInput {\n readonly bootstrap: BootstrapPort;\n readonly runtime: ProductionRuntime;\n readonly origin?: string;\n readonly runtimeUrls: ProductionRuntimeUrls;\n /**\n * Bootstrap-resolved chain. The `ConvexSubAccountAdapter`'s `transfer`\n * action reads the Safe's live `balanceOf` on this chain (canon §2/§5);\n * the consumer-facing `transfer({ from, to, amount })` carries no chainId\n * (public-surface no-consumer-chainId rule), so the adapter closes over it.\n */\n readonly chainId: ChainId;\n readonly authCache?: AuthCachePort;\n readonly telemetry?: TelemetryPort;\n readonly convexClient?: ConvexClientShape;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n /** Bootstrap-verified hint; the backend independently verifies it again. */\n readonly applicationId?: string;\n readonly observation?: ObservationAdapter;\n /**\n * Late-bound signer session reset (see `ResetSignerSessionRef`). Present when\n * the composition root intends to attach an embedded signer; the auth layer\n * wraps `signOut` with it whether or not `current` is ever filled in.\n */\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\nexport type ProductionAdapterLayerEntry<\n N extends ProductionAdapterLayerName = ProductionAdapterLayerName,\n> = {\n readonly [K in N]: {\n readonly name: K;\n readonly layer: Layer.Layer<ProductionAdapterLayerOutput<K>, unknown, unknown>;\n };\n}[N];\n\n/**\n * Project the built graph into the flat `FlowPorts` record the method bundles\n * still take. It is a VIEW of `ProductionAdapters.context`, taken from the\n * graph and never instead of it — the graph stays alive in the scope and is\n * handed to every caller.\n */\nexport const collectProductionFlowPorts: Effect.Effect<FlowPorts, never, ProductionFlowPortTags> =\n Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const authCache = yield* AuthCachePortTag;\n const bootstrap = yield* BootstrapPortTag;\n const clock = yield* ClockPortTag;\n const convexCall = yield* ConvexCallPortTag;\n const identity = yield* IdentityPortTag;\n const smartAccount = yield* SmartAccountPortTag;\n const accountRead = yield* AccountReadPortTag;\n const subAccount = yield* SubAccountPortTag;\n const telemetry = yield* TelemetryPortTag;\n return {\n authClient,\n authCache,\n identity,\n smartAccount,\n accountRead,\n subAccount,\n bootstrap,\n clock,\n telemetry,\n convexCall,\n };\n });\n\nexport function makeProductionAdapterLayerEntries(\n input: ProductionAdapterLayerInput,\n): readonly ProductionAdapterLayerEntry[] {\n const refreshConvexAuthRef: RefreshConvexAuthRef = { current: null, pending: false };\n return [\n {\n name: \"bootstrap\",\n layer: productionBootstrapPortLayer(input.bootstrap),\n },\n {\n name: \"authClient\",\n layer: productionAuthClientLayer(input, refreshConvexAuthRef, input.resetSignerSession),\n },\n {\n name: \"authCache\",\n layer: productionAuthCacheLayer(input),\n },\n {\n name: \"identity\",\n layer: ConvexIdentityLayer(),\n },\n {\n name: \"smartAccount\",\n layer: ConvexSmartAccountLayer(),\n },\n {\n name: \"accountRead\",\n layer: ConvexAccountLayer(),\n },\n {\n name: \"subAccount\",\n layer: ConvexSubAccountLayer(input.chainId),\n },\n {\n name: \"clock\",\n layer: SystemClockLayer(),\n },\n {\n name: \"telemetry\",\n layer:\n input.telemetry === undefined\n ? PostHogTelemetryLayer({ capture: () => undefined })\n : Layer.succeed(TelemetryPortTag, input.telemetry),\n },\n {\n name: \"convexCall\",\n layer: productionConvexCallLayer(input, refreshConvexAuthRef),\n },\n {\n // The org port used to be constructed by hand at the composition root\n // (`new ConvexOrganizationAdapter({ convex: ports.convexCall })`), which\n // is why `OrgPortTag` sat in `.fallowrc.json`'s ignore-list with zero\n // resolvers. It is a Convex-backed port like the four below it, so it\n // belongs IN the graph.\n name: \"org\",\n layer: Layer.effect(\n OrgPortTag,\n Effect.map(\n ConvexCallPortTag,\n (convex) => new ConvexOrganizationAdapter({ convex }) as OrgPort,\n ),\n ),\n },\n ];\n}\n\nexport function mergeProductionAdapterLayers(\n entries: readonly ProductionAdapterLayerEntry[],\n): Layer.Layer<ProductionFlowPortTags, unknown, never> {\n const byName = new Map<ProductionAdapterLayerName, Layer.Layer<never, unknown, unknown>>();\n for (const entry of entries) {\n byName.set(entry.name, entry.layer as Layer.Layer<never, unknown, unknown>);\n }\n const authClientLayer = byName.get(\"authClient\");\n const convexCallLayer = byName.get(\"convexCall\");\n // Phase 1: authClient -> convexCall. The auth wrapper reads\n // RefreshConvexAuthRef at call time, after this convex layer registers\n // the concrete refreshAuth callback during construction.\n const convexCallReadyLayer =\n convexCallLayer === undefined || authClientLayer === undefined\n ? convexCallLayer\n : convexCallLayer.pipe(Layer.provide(authClientLayer));\n\n const readyLayers = entries.map((entry) => {\n const layer = byName.get(entry.name) ?? (entry.layer as Layer.Layer<never, unknown, unknown>);\n if (entry.name === \"convexCall\") return convexCallReadyLayer ?? layer;\n if (isConvexDependentLayer(entry.name)) {\n // Phase 2: convexCallReady -> Convex-backed domain ports.\n return convexCallReadyLayer === undefined\n ? layer\n : layer.pipe(Layer.provide(convexCallReadyLayer));\n }\n return layer;\n });\n\n const merged = readyLayers.reduce((current, layer) => Layer.merge(current, layer), Layer.empty);\n // Entries are heterogeneous Layers stored behind one contract; the cast is\n // localized here, while production-layers.test.ts proves omissions fail\n // startup instead of silently assembling a partial FlowPorts graph.\n return merged as Layer.Layer<ProductionFlowPortTags, unknown, never>;\n}\n\nfunction isConvexDependentLayer(name: ProductionAdapterLayerName): boolean {\n return (\n name === \"identity\" ||\n name === \"smartAccount\" ||\n name === \"accountRead\" ||\n name === \"subAccount\" ||\n name === \"org\"\n );\n}\n\nfunction productionBootstrapPortLayer(\n bootstrap: BootstrapPort,\n): Layer.Layer<BootstrapPortTag, never, never> {\n return Layer.succeed(BootstrapPortTag, bootstrap);\n}\n\nfunction productionAuthClientLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n resetSignerSessionRef: ResetSignerSessionRef | undefined,\n): Layer.Layer<AuthClientPortTag, never, never> {\n const baseLayer =\n input.runtime === \"browser\"\n ? BetterAuthBrowserLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n })\n : BetterAuthNodeLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n });\n\n return baseLayer.pipe(\n Layer.flatMap((context) => {\n const authClient = Context.get(context, AuthClientPortTag);\n const refreshed = refreshConvexAuthOnSession(authClient, () => {\n const refresh = refreshConvexAuthRef.current;\n if (refresh === null) {\n refreshConvexAuthRef.pending = true;\n return;\n }\n refresh();\n });\n return Layer.succeedContext(\n Context.make(\n AuthClientPortTag,\n resetSignerSessionRef === undefined\n ? refreshed\n : resetSignerSessionOnSignOut(refreshed, resetSignerSessionRef),\n ),\n );\n }),\n );\n}\n\nfunction productionAuthCacheLayer(\n input: ProductionAdapterLayerInput,\n): Layer.Layer<AuthCachePortTag, never, never> {\n return Layer.succeed(AuthCachePortTag, input.authCache ?? detectAuthCacheAdapter());\n}\n\nfunction productionConvexCallLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n): Layer.Layer<ConvexCallPortTag, never, AuthClientPortTag> {\n return Layer.unwrap(\n Effect.map(AuthClientPortTag, (authClient) =>\n ConvexCallLayer({\n convexUrl: input.runtimeUrls.convexUrl,\n ...(input.applicationId === undefined ? {} : { applicationId: input.applicationId }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n ...(input.convexClient === undefined ? {} : { client: input.convexClient }),\n tokenProvider: async ({ forceRefreshToken }) => {\n const tokenResult = await Effect.runPromise(\n Effect.result(\n authClient.getConvexJwt({\n forceRefresh: forceRefreshToken,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n }),\n ),\n );\n if (Result.isFailure(tokenResult)) return null;\n return String(tokenResult.success.token);\n },\n }).pipe(\n Layer.flatMap((context) => {\n const convexCall = Context.get(context, ConvexCallPortTag);\n if (isRefreshableConvexCallPort(convexCall)) {\n refreshConvexAuthRef.current = () => convexCall.refreshAuth();\n if (refreshConvexAuthRef.pending) {\n refreshConvexAuthRef.pending = false;\n refreshConvexAuthRef.current();\n }\n }\n return Layer.succeedContext(context);\n }),\n ),\n ),\n );\n}\n\nfunction isRefreshableConvexCallPort(\n convexCall: ConvexCallPort,\n): convexCall is ConvexCallPort & { readonly refreshAuth: () => void } {\n return \"refreshAuth\" in convexCall && typeof convexCall.refreshAuth === \"function\";\n}\n\n/**\n * @internal Seam for the composition root only: `createCapxulClient` derives\n * the browser signer from the bootstrap this function resolves, so it hands in\n * a ref the auth layer closes over and fills the callback in afterwards. Not on\n * `ProductionAdapterInput` — a consumer must never reach the auth seam.\n */\ninterface ProductionResetSignerSeam {\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\ninterface ProductionInvocationObservabilitySeam {\n readonly invocationObservability?: HostObservability;\n}\n\nfunction resolveProductionObservability(input: ProductionAdapterInput) {\n const observation = input.observability?.failures ?? input.observation;\n const telemetry = input.observability?.product ?? input.telemetry;\n const invocationObservability = (input as ProductionInvocationObservabilitySeam)\n .invocationObservability;\n return {\n observation,\n telemetry,\n invocationObservation: invocationObservability?.failures ?? observation,\n invocationTelemetry: invocationObservability?.product ?? telemetry,\n };\n}\n\nexport async function createProductionAdapters(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<ProductionAdapters>> {\n const { observation, telemetry, invocationObservation, invocationTelemetry } =\n resolveProductionObservability(input);\n const resolvedInput = resolveInput(input);\n if (!resolvedInput.ok) return resolvedInput;\n\n const scope = await Effect.runPromise(Scope.make());\n const closeScope = idempotentClose(() => Effect.runPromise(Scope.close(scope, Exit.void)));\n\n const bootstrapLayer = HttpBootstrapLayer({\n bootstrapBaseUrl: resolvedInput.value.bootstrapBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(invocationObservation === undefined ? {} : { observation: invocationObservation }),\n });\n\n try {\n const bootstrapContext = await Effect.runPromise(Layer.buildWithScope(bootstrapLayer, scope));\n const bootstrap = Context.get(bootstrapContext, BootstrapPortTag);\n const bootstrapResult = await runBootstrap(\n bootstrap.resolve({\n publishableKey: resolvedInput.value.publishableKey,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n }),\n );\n if (!bootstrapResult.ok) {\n await emitBootstrapTelemetry(invocationTelemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n reason: bootstrapResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return bootstrapResult;\n }\n\n // Testnet fence for the dev-key lane (#1149, folds #1065; ADR-0018 P9).\n // A `local-private-key` signer is a disposable, deterministically derived\n // dev key — it is the AGENT signing path, never the human one. This is the\n // one place where such a signer meets a resolved chain, so the refusal\n // lives here: every consumer (MCP proof lane, exemplar, approve, reference)\n // constructs through `createProductionAdapters`. It fails BEFORE any\n // adapter, Convex client, or signer call exists.\n const chainFence = assertDevKeySignerIsTestnetOnly(input.signer, bootstrapResult.value.chainId);\n if (!chainFence.ok) {\n await closeScope().catch(() => undefined);\n return chainFence;\n }\n\n const runtimeUrlsResult = resolveRuntimeUrls(\n bootstrapResult.value,\n resolvedInput.value.runtime,\n input.authBaseUrl,\n );\n if (!runtimeUrlsResult.ok) {\n await emitBootstrapTelemetry(invocationTelemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n reason: runtimeUrlsResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return runtimeUrlsResult;\n }\n const runtimeUrls = runtimeUrlsResult;\n\n await emitBootstrapTelemetry(invocationTelemetry, {\n name: \"bootstrap_resolved\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n },\n });\n\n let injectedClient: ConvexClientShape | undefined;\n const convexClientFactory = (input as ProductionConvexClientFactorySeam).convexClientFactory;\n if (convexClientFactory !== undefined) {\n try {\n injectedClient = convexClientFactory(runtimeUrls.value.convexUrl);\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n }\n\n const portsLayer = mergeProductionAdapterLayers(\n makeProductionAdapterLayerEntries({\n bootstrap,\n runtime: resolvedInput.value.runtime,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n runtimeUrls: runtimeUrls.value,\n chainId: bootstrapResult.value.chainId,\n applicationId: bootstrapResult.value.applicationId,\n ...(observation === undefined ? {} : { observation }),\n ...(input.authCache === undefined ? {} : { authCache: input.authCache }),\n ...(telemetry === undefined ? {} : { telemetry }),\n ...(injectedClient === undefined ? {} : { convexClient: injectedClient }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...((input as ProductionResetSignerSeam).resetSignerSession === undefined\n ? {}\n : {\n resetSignerSession: (input as ProductionResetSignerSeam)\n .resetSignerSession as ResetSignerSessionRef,\n }),\n }),\n );\n const applicationLayer = Layer.merge(\n portsLayer,\n optionalEngineeringTelemetryLayer(\n bootstrapResult.value.engineeringTelemetry,\n resolvedInput.value.runtime,\n ),\n );\n // The graph, built into the same scope as `close`. It is the runtime; the\n // `FlowPorts` record below is a projection taken FROM it (A2-Q1A).\n const context = await Effect.runPromise(Layer.buildWithScope(applicationLayer, scope));\n const ports = await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context)));\n\n return {\n ok: true,\n value: { context, ports, bootstrap: bootstrapResult.value, close: closeScope },\n };\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nfunction optionalEngineeringTelemetryLayer(\n policy: BootstrapResolution[\"engineeringTelemetry\"],\n runtime: ProductionRuntime,\n) {\n if (policy === undefined) return Layer.empty;\n try {\n return makeEngineeringTelemetryLayer({\n host: policy.host,\n headers: { authorization: `Bearer ${policy.projectToken}` },\n capxulEnv: policy.capxulEnv,\n producer: runtime === \"browser\" ? \"browser\" : \"server\",\n sdkVersion: SDK_VERSION,\n });\n } catch {\n // Bootstrap remains usable when optional observability policy is invalid.\n return Layer.empty;\n }\n}\n\nfunction refreshConvexAuthOnSession(\n authClient: AuthClientPort,\n refresh: () => void,\n): AuthClientPort {\n return {\n ...authClient,\n verifyOtp: (input, options) =>\n authClient.verifyOtp(input, options).pipe(Effect.tap(() => Effect.sync(refresh))),\n signOut: (options) => authClient.signOut(options).pipe(Effect.tap(() => Effect.sync(refresh))),\n };\n}\n\n/**\n * Signer-session reset, as a port wrapper INSIDE the Layer graph (blueprint §2:\n * \"wrappers become Layers, not post-hoc spreads/Proxies\").\n *\n * This was a spread over the assembled client — `{...client, auth: {...,\n * signOut}}` — applied after composition finished, so the reset lived on one\n * particular object rather than on the auth seam itself. Here it wraps\n * `AuthClientPort.signOut`, so it holds for every route to a sign-out.\n *\n * `Effect.ensuring` (not `Effect.tap`) is deliberate: the old wrapper used\n * `try/finally`, so the session was reset even when sign-out failed. Dropping\n * to `tap` would silently strand an Openfort session on the error path.\n */\nfunction resetSignerSessionOnSignOut(\n authClient: AuthClientPort,\n resetRef: ResetSignerSessionRef,\n): AuthClientPort {\n return {\n ...authClient,\n signOut: (options) =>\n authClient.signOut(options).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n resetRef.current?.();\n }),\n ),\n ),\n };\n}\n\nexport async function createCapxulClient(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<CapxulClient>> {\n const invocationObservability = bindHostObservabilityInvocation(input.observability);\n const observation = invocationObservability?.failures ?? input.observation;\n const validation = validateCreateCapxulClientInput(input);\n if (!validation.ok) {\n return observeFailedResult(validation, observation, \"createCapxulClient\");\n }\n\n // The auth layer closes over this ref while the graph is built; the signer\n // that fills it in is derived from the bootstrap the graph itself resolves,\n // so the callback lands one step later. The WRAPPER is part of the graph\n // either way — that is the point of moving it off the assembled object.\n const resetSignerSession: ResetSignerSessionRef = { current: null };\n const adapters = await createProductionAdapters({\n ...input,\n resetSignerSession,\n ...(invocationObservability === undefined ? {} : { invocationObservability }),\n } as ProductionAdapterInput);\n if (!adapters.ok) {\n return observeFailedResult(adapters, observation, \"createCapxulClient\");\n }\n try {\n const runtime = input.runtime ?? detectRuntime();\n const resolvedAuthBaseUrl = resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: adapters.value.bootstrap.authBaseUrl,\n runtime,\n ...(input.authBaseUrl === undefined ? {} : { override: input.authBaseUrl }),\n });\n let signer: CapxulSigner | OpenfortBrowserSigner | undefined = input.signer;\n if (signer === undefined && runtime === \"browser\") {\n // Thread the diagnostic + telemetry options so the signer's breadcrumbs\n // (token, encryptionSession, embeddedState, configure, getAddress) and its\n // no-secure-context self-report actually fire on the real browser path —\n // building it with the bootstrap alone dropped #870's native cause (#1032).\n signer = createOpenfortBrowserSignerFromBootstrap(\n {\n ...adapters.value.bootstrap,\n authBaseUrl: resolvedAuthBaseUrl,\n },\n {\n diagnostic: new ConsoleDiagnosticAdapter(),\n telemetry: adapters.value.ports.telemetry,\n },\n );\n }\n if (signer !== undefined && \"resetSession\" in signer) {\n const { resetSession } = signer;\n resetSignerSession.current = () => {\n resetSession();\n };\n }\n const client = assembleCapxulClient({\n ports: adapters.value.ports,\n bootstrap: adapters.value.bootstrap,\n authCache: adapters.value.ports.authCache,\n requirement: input.requirement ?? \"none\",\n ...(signer === undefined ? {} : { signer }),\n // Resolved FROM the graph rather than constructed beside it — the org\n // adapter is a Convex-backed port and now has a layer entry like its\n // siblings (`OrgPortTag` had zero resolvers before the re-cut).\n orgPort: Context.get(adapters.value.context, OrgPortTag),\n ...(signer === undefined\n ? {}\n : {\n // Still hand-built: this adapter closes over the SIGNER, which is\n // derived from the bootstrap the graph resolves, so it cannot be a\n // layer entry until the signer moves ahead of composition. ADR-0019\n // P3 / L1 owns that; noted rather than faked.\n organizationSetup: new ConvexOrganizationSetupAdapter({\n convex: adapters.value.ports.convexCall,\n signer,\n chainId: adapters.value.bootstrap.chainId,\n }),\n }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n invokeTimeoutMs: input.invokeTimeoutMs ?? DEFAULT_INVOKE_TIMEOUT_MS,\n ...(input.observability === undefined\n ? {}\n : { hostObservationSnapshot: () => snapshotHostObservability(input.observability) }),\n effectRunner: {\n runSync: Effect.runSyncWith(adapters.value.context as Context.Context<never>),\n runPromise: Effect.runPromiseWith(adapters.value.context as Context.Context<never>),\n },\n } as CreateCapxulClientInput & {\n readonly hostObservationSnapshot?: () =>\n | ReturnType<typeof snapshotHostObservability>\n | undefined;\n });\n const upstreamClose = adapters.value.close;\n const close = idempotentClose(async () => {\n try {\n if (\"resetSession\" in (signer ?? {})) {\n (signer as OpenfortBrowserSigner).resetSession();\n }\n } finally {\n await Promise.all([client._internal.close?.(), upstreamClose()]);\n }\n });\n const value = {\n ...client,\n _internal: {\n ...client._internal,\n close,\n },\n };\n return { ok: true, value };\n } catch (cause) {\n await adapters.value.close().catch(() => undefined);\n return observeFailedResult(\n { ok: false, error: toPublicError(cause, \"createCapxulClient\") } as const,\n observation,\n \"createCapxulClient\",\n );\n }\n}\n\nfunction validateCreateCapxulClientInput(input: ProductionAdapterInput): CapxulResult<void> {\n const runtime = input.runtime ?? detectRuntime();\n if (\n (input.requirement ?? \"none\") === \"deployed\" &&\n input.signer === undefined &&\n runtime !== \"browser\"\n ) {\n return {\n ok: false,\n error: Errors.invalidInput(\"signer\", 'required when requirement is \"deployed\"'),\n };\n }\n return { ok: true, value: undefined };\n}\n\ntype ResolvedInput = {\n readonly publishableKey: ReturnType<typeof toPublishableKey>;\n readonly origin?: ReturnType<typeof toAllowedOrigin>;\n readonly bootstrapBaseUrl: string;\n readonly runtime: ProductionRuntime;\n};\n\nfunction resolveInput(input: ProductionAdapterInput): CapxulResult<ResolvedInput> {\n try {\n const runtime = input.runtime ?? detectRuntime();\n const publishableKey = toPublishableKey(input.publishableKey);\n const origin =\n input.origin === undefined\n ? runtime === \"browser\"\n ? toAllowedOrigin(derivedBrowserOrigin(runtime))\n : undefined\n : toAllowedOrigin(input.origin);\n return {\n ok: true,\n value: {\n publishableKey,\n ...(origin === undefined ? {} : { origin }),\n bootstrapBaseUrl: normalizeHttpUrl(\n \"bootstrapBaseUrl\",\n input.bootstrapBaseUrl ??\n (runtime === \"browser\"\n ? derivedBrowserOrigin(runtime)\n : DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL),\n ),\n runtime,\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\n/**\n * Address of the Capxul client-relay ingest endpoint (Pipe 1, issue #877). The\n * HTTP router that serves `/v1/client/observe` lives on the deployment's\n * `.convex.site` host, while the bootstrap-resolved `convexUrl` is the sibling\n * `.convex.cloud` (WebSocket/query) host — the same deterministic pairing\n * `mintQuickstartKey` inverts. For any standard Convex deployment (including\n * production) rewriting the suffix targets the router directly with no host\n * proxy, so it is the primary rule.\n *\n * `siteBaseUrl` is deliberately NOT the primary source: it is an app-configured\n * field that defaults to a placeholder (`https://capxul.local`, see\n * `credentials/applications.ts`) for registered applications, so trusting it\n * outright would POST to a dead host for the common case. It is only consulted\n * as a fallback for a custom-domain `convexUrl` (no deterministic `.convex.site`\n * sibling) when it carries a real, non-placeholder origin.\n */\nexport function deriveObserveIngestUrl(bootstrap: BootstrapResolution): string {\n const convexUrl = bootstrap.convexUrl.replace(/\\/+$/, \"\");\n if (convexUrl.endsWith(\".convex.cloud\")) {\n return `${convexUrl.replace(/\\.convex\\.cloud$/, \".convex.site\")}/v1/client/observe`;\n }\n const site = usableSiteOrigin(bootstrap.siteBaseUrl) ?? convexUrl;\n return `${site.replace(/\\/+$/, \"\")}/v1/client/observe`;\n}\n\n/** A configured `siteBaseUrl` usable as a router host, or `undefined` if it is the placeholder. */\nfunction usableSiteOrigin(siteBaseUrl: string): string | undefined {\n try {\n const url = new URL(siteBaseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n if (url.hostname === \"capxul.local\") return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n\nfunction detectRuntime(): ProductionRuntime {\n const globalAny = globalThis as {\n readonly window?: unknown;\n readonly document?: unknown;\n };\n return globalAny.window !== undefined || globalAny.document !== undefined ? \"browser\" : \"node\";\n}\n\nfunction derivedBrowserOrigin(runtime: ProductionRuntime): string {\n if (runtime !== \"browser\") {\n throw Errors.invalidInput(\"origin\", \"required outside browser runtime\");\n }\n const globalAny = globalThis as { readonly location?: { readonly origin?: string } };\n if (typeof globalAny.location?.origin === \"string\" && globalAny.location.origin.length > 0) {\n return globalAny.location.origin;\n }\n throw Errors.invalidInput(\"origin\", \"required when browser location is unavailable\");\n}\n\n/**\n * Browser local dev serves `/api/auth` via the Vite proxy on `window.location.origin`\n * while bootstrap returns the remote Convex site host. Openfort wallet setup reads\n * Better Auth cookies from `get-session` — those only attach on the same origin the\n * OTP flow used, so rewrite when hosts differ.\n */\nexport function resolveBrowserAuthBaseUrl(input: {\n readonly bootstrapAuthBaseUrl: string;\n readonly runtime: ProductionRuntime;\n readonly override?: string;\n}): string {\n if (input.override !== undefined) {\n return normalizeHttpUrl(\"authBaseUrl\", input.override);\n }\n const bootstrapUrl = normalizeHttpUrl(\"authBaseUrl\", input.bootstrapAuthBaseUrl);\n if (input.runtime !== \"browser\") {\n return bootstrapUrl;\n }\n try {\n const origin = derivedBrowserOrigin(input.runtime);\n const localAuthBase = normalizeHttpUrl(\"authBaseUrl\", `${origin}/api/auth`);\n const remoteAuthBase = bootstrapUrl.endsWith(\"/api/auth\")\n ? bootstrapUrl\n : `${bootstrapUrl}/api/auth`;\n if (new URL(remoteAuthBase).host !== new URL(localAuthBase).host) {\n return localAuthBase;\n }\n return bootstrapUrl;\n } catch {\n return bootstrapUrl;\n }\n}\n\nfunction resolveRuntimeUrls(\n bootstrap: BootstrapResolution,\n runtime: ProductionRuntime,\n authBaseUrlOverride?: string,\n): CapxulResult<{ readonly authBaseUrl: string; readonly convexUrl: string }> {\n try {\n return {\n ok: true,\n value: {\n authBaseUrl: resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: bootstrap.authBaseUrl,\n runtime,\n ...(authBaseUrlOverride === undefined ? {} : { override: authBaseUrlOverride }),\n }),\n convexUrl: normalizeHttpUrl(\"convexUrl\", bootstrap.convexUrl),\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nasync function runBootstrap(\n effect: ReturnType<BootstrapPort[\"resolve\"]>,\n): Promise<CapxulResult<BootstrapResolution>> {\n const result = await Effect.runPromise(Effect.result(effect));\n if (Result.isSuccess(result)) return { ok: true, value: result.success };\n return { ok: false, error: toPublicError(result.failure, \"bootstrap.resolve\") };\n}\n\n/**\n * Bootstrap-event props. `runtime` used to be called `capxulEnv`, which was a\n * name collision, not a value: it carried \"browser\"/\"node\", never an\n * environment. ADR-0020 A1 makes `capxul_env` the environment discriminator\n * every synced artifact filters on, so this field was renamed to what it\n * actually is. `sdk_version` follows the canon envelope spelling.\n */\nfunction bootstrapTelemetryEnvelope(\n input: ProductionAdapterInput,\n resolvedInput: ResolvedInput,\n): {\n readonly runtime: ProductionRuntime;\n readonly env: AccountRequirement;\n readonly origin?: string;\n readonly sdk_version: string;\n} {\n return {\n runtime: resolvedInput.runtime,\n env: input.requirement ?? \"none\",\n ...(resolvedInput.origin === undefined ? {} : { origin: resolvedInput.origin }),\n sdk_version: SDK_VERSION,\n };\n}\n\nasync function emitBootstrapTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(telemetry.emit(event).pipe(Effect.catchDefect(() => Effect.void)));\n}\n\nfunction normalizeHttpUrl(field: string, raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nfunction toPublicError(cause: unknown, operation: string): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const publicError = (cause as { readonly publicError?: unknown }).publicError;\n if (publicError instanceof CapxulError) return publicError;\n const nestedCause = (cause as { readonly cause?: unknown }).cause;\n if (nestedCause instanceof CapxulError) return nestedCause;\n }\n return Errors.providerError(\"sdk-production-adapters\", operation, cause);\n}\n\nfunction idempotentClose(close: () => Promise<void>): ProductionAdapterClose {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n}\n","import {\n createCapxulClient as createCapxulClientFromProductionAdapters,\n type CapxulClientInput,\n} from \"../production\";\nimport type { CapxulClient } from \"./create-capxul-client\";\nimport type { CapxulResult } from \"./types\";\n\n/** Consumer-facing factory — accepts only production-meaningful inputs (#326). */\nexport async function createCapxulClient(\n input: CapxulClientInput,\n): Promise<CapxulResult<CapxulClient>> {\n return createCapxulClientFromProductionAdapters(input);\n}\n"],"mappings":";;;;;;;;;;;AA8CA,SAAgB,+BAA+B,OAE3B;CAClB,MAAM,UAAU,oBAAoB,MAAM,UAAU;CACpD,MAAM,UAAU,UAAU,QAAQ,OAAO;CACzC,OAAO;EACL,QAAQ;EACR,MAAM,aAAa;GACjB,OAAO;IAAE,IAAI;IAAM,OAAO;GAAQ;EACpC;EACA,MAAM,mBAAmB;GACvB,OAAO;IAAE,IAAI;IAAM,OAAO;GAAQ;EACpC;CACF;AACF;AAEA,SAAgB,uBAAuB,OAEnB;CAelB,IAAI,gBAAgC;CACpC,IAAI,WAAkD;CAEtD,MAAM,aAAa,YAA4C;EAC7D,IAAI,kBAAkB,MACpB,OAAO;GAAE,IAAI;GAAM,OAAO;EAAc;EAE1C,IAAI,aAAa,MACf,OAAO;EAET,YAAY,YAAY;GACtB,IAAI;IAEF,MAAM,QAAQ,aAAa,MADJ,MAAM,SAAS,QAAQ,EAAE,QAAQ,eAAe,CAAC,CACrC;IACnC,IAAI,UAAU,MACZ,OAAO;KAAE,IAAI;KAAO,OAAO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