// templ-support.ts: one Templ support widget for the whole app. import type { SupportContextInput, SupportFailureCapture, SupportWallet, SupportWidget, } from "https://usetempl.com/support-widget.js"; /** true only if the app has no Help button of its own. */ const SHOW_LAUNCHER = false; /** The page's style nonce, needed only when the content security policy * limits style-src. Return it from where the app keeps it. */ function styleNonce(): string | undefined { return undefined; } let wallet: SupportWallet | null = null; let widget: SupportWidget | undefined; let loading: Promise | undefined; let retries = 0; type SavedFailure = { input: SupportContextInput; capture: Promise; }; const failures = new Set(); let capturing: Promise | undefined; /** Read the selected wallet now. These reads never connect or sign. */ async function snapshotWallet(): Promise { const selected = wallet; try { if (selected?.evm) { const [accounts, chain] = await Promise.all([ selected.evm.request({ method: "eth_accounts" }), selected.evm.request({ method: "eth_chainId" }), ]); const address = Array.isArray(accounts) ? accounts[0] : undefined; const chainId = typeof chain === "string" ? Number(chain) : NaN; if ( typeof address === "string" && /^0x[0-9a-f]{40}$/i.test(address) && !/^0x0{40}$/i.test(address) && Number.isSafeInteger(chainId) && chainId > 0 ) return { network: "evm", address: address.toLowerCase() as `0x${string}`, chainId }; } else if (selected?.solana) { const address = "accounts" in selected.solana ? selected.solana.accounts.find((account) => !account.chains || account.chains.some((chain) => chain.startsWith("solana:")), )?.address : selected.solana.publicKey?.toBase58(); if (address) return { network: "solana", address }; } } catch { // An unreadable wallet stays a guest snapshot. } return null; } /** Keep each failure until the widget accepts it. Get help retries this queue. */ async function captureSavedFailures(mounted: SupportWidget): Promise { if (capturing) return capturing; const attempt = (async () => { let failed = false; let reason: unknown; for (const saved of failures) { const capture = await saved.capture; if (widget !== mounted || !failures.has(saved)) throw new Error("Support was closed."); try { await mounted.captureFailure(saved.input, capture); failures.delete(saved); } catch (error) { failed = true; reason = error; } } if (failed) throw reason; })(); capturing = attempt; try { await attempt; } finally { if (capturing === attempt) capturing = undefined; } } /** Loads and mounts the widget once. `workspace` is the Templ workspace ID. */ export function loadSupport(workspace: string): Promise { if (loading) return loading; const url = "https://usetempl.com/support-widget.js"; const source = retries ? url + "?retry=" + retries : url; const attempt: Promise = import( /* webpackIgnore: true */ /* @vite-ignore */ source ).then(({ mountSupportWidget }) => { if (loading !== attempt) throw new Error("Support was closed."); const mounted: SupportWidget = mountSupportWidget({ workspace, apiUrl: "https://community.usetempl.com", wallet, showLauncher: SHOW_LAUNCHER, styleNonce: styleNonce(), }); widget = mounted; return mounted; }); attempt.catch(() => { if (loading === attempt) { loading = undefined; retries++; } }); loading = attempt; return attempt; } /** The app's Help button. Pass context only for something the user is * looking at, such as a pending deposit; they choose whether to share it. */ export async function openSupport( workspace: string, context?: SupportContextInput, ) { const mounted = await loadSupport(workspace); await captureSavedFailures(mounted).catch(() => {}); if (widget !== mounted) throw new Error("Support was closed."); if (context) mounted.setContext(context); mounted.open(); } /** Call from the app's handler when a wallet action fails. * It saves the failure with the wallet and network at that moment. * Its details start selected. Nothing is sent until the user presses Send. */ export async function captureSupportFailure( workspace: string, failure: SupportContextInput, ) { if (!["rejected","simulation","submission","broadcast","other"].includes(failure.app?.failure?.kind ?? "")) { throw new Error("Add a failure kind."); } const capturedAt = new Date().toISOString(); const saved = { input: structuredClone(failure), capture: snapshotWallet().then((wallet) => ({ capturedAt, wallet })), }; failures.add(saved); const mounted = await loadSupport(workspace); await captureSavedFailures(mounted); } /** Call whenever the app's wallet connects, switches account or chain, or * disconnects. EVM: { evm: provider }. Solana: { solana: wallet }. None: null. */ export function setSupportWallet(next: SupportWallet | null) { wallet = next; widget?.setWallet(next); } /** Call on app sign-out and when the app shell unmounts. */ export function closeSupport() { loading = undefined; capturing = undefined; failures.clear(); widget?.destroy(); widget = undefined; }