diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index 0e241f1..0c3a5e1 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test, type Page } from '@playwright/test'; import { bech32m } from '@scure/base'; import { E2E_MOCK_DPNS_WIF, @@ -12,6 +12,21 @@ import { const MOCK_QUERY = '/?network=testnet&e2e=mock'; +/** Failure injection read by the mock flows (E2EMockFailures in src/main.ts). */ +function injectMockFailures(page: Page, failures: { sdkLoadFailures?: number; submissionFailures?: number }) { + return page.addInitScript((f) => { + (window as { __e2eMockFailures?: typeof f }).__e2eMockFailures = f; + }, failures); +} + +/** Pretend the deposit arrived (the mock flows wait for this hook). */ +async function advanceMockDeposit(page: Page) { + await expect.poll(async () => { + return page.evaluate(() => typeof (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance); + }).toBe('function'); + await page.evaluate(() => (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance?.()); +} + test.describe('Deterministic UI E2E (mock mode)', () => { test('testnet discovers evonodes from the quorum service, never calls digitalcash.dev and does not load the SDK for the health poll', async ({ page }) => { const digitalcashRequests: string[] = []; @@ -87,6 +102,96 @@ test.describe('Deterministic UI E2E (mock mode)', () => { await expect(page.getByText('Registration Complete!')).toBeVisible(); }); + test.describe('Platform component gate before funding', () => { + test('a dropped SDK download is retried and the flow reaches the deposit address', async ({ page }) => { + const warnings: string[] = []; + const events: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warning') warnings.push(msg.text()); + if (msg.text().includes('Chunk "evo-sdk" failed to load')) events.push('sdk-failure'); + }); + // The key backup download must wait for the gate: on iOS its prompt + // cancels in-flight loads (that poisoned the SDK import in production). + page.on('download', () => events.push('backup-download')); + await injectMockFailures(page, { sdkLoadFailures: 2 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + + // The retries' backoff (0.5 + 1.5 s) keeps the gate on screen. + await expect(page.locator('.preparing-step')).toContainText('Preparing…'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + expect(warnings.filter((w) => w.includes('Chunk "evo-sdk" failed to load'))).toHaveLength(2); + await expect.poll(() => events).toEqual(['sdk-failure', 'sdk-failure', 'backup-download']); + }); + + for (const flow of ['create', 'topup'] as const) { + test(`${flow}: an SDK that cannot load stops the flow before any deposit address, with Reload`, async ({ page }) => { + let downloads = 0; + page.on('download', () => { downloads += 1; }); + await injectMockFailures(page, { sdkLoadFailures: 3 }); + await page.goto(MOCK_QUERY); + if (flow === 'create') { + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + } else { + await page.click('#mode-manage-btn'); + await page.click('#manage-action-topup-btn'); + await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); + await page.click('#continue-topup-btn'); + } + + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1017'); + await expect(page.locator('.error-step')).toContainText('The page failed to load a required component "evo-sdk"'); + await expect(page.locator('.error-step')).toContainText('No funds have been sent'); + await expect(page.locator('.deposit-headline')).toHaveCount(0); + await expect(page.locator('#download-keys-btn')).toHaveCount(0); + expect(downloads).toBe(0); + await page.locator('.error-technical summary').click(); + await expect(page.locator('.error-technical-content')).toContainText('Failed to load: evo-sdk'); + + // Reload is safe here: nothing was funded. The reloaded page starts over. + await page.click('#reload-page-btn'); + await expect(page.locator('#mode-create-btn')).toBeVisible(); + }); + } + + test('registration failing after the lock arrived says so, and Retry Registration completes it', async ({ page }) => { + await injectMockFailures(page, { submissionFailures: 1 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + await advanceMockDeposit(page); + + const errorStep = page.locator('.error-step'); + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1006'); + await expect(errorStep).toContainText('the InstantSend lock arrived'); + await expect(errorStep).not.toContainText("InstantSend didn't go through"); + await expect(page.locator('#download-keys-btn')).toBeVisible(); + + await page.click('#retry-registration-btn'); + await expect(page.getByText('Save your keys')).toBeVisible(); + await expect(page.locator('.contract-id-section', { hasText: 'Your Identity ID' }).locator('.identity-id')).toHaveText(E2E_MOCK_IDENTITY_ID); + }); + + test('top-up failing after the lock arrived offers Retry Top-up, which completes it', async ({ page }) => { + await injectMockFailures(page, { submissionFailures: 1 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-manage-btn'); + await page.click('#manage-action-topup-btn'); + await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); + await page.click('#continue-topup-btn'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + await advanceMockDeposit(page); + + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1007'); + await expect(page.locator('#retry-registration-btn')).toHaveText('Retry Top-up'); + await page.click('#retry-registration-btn'); + await expect(page.getByText('Top-up complete!')).toBeVisible(); + }); + }); + test('top up flow validates identity input and reaches completion', async ({ page }) => { await page.goto(MOCK_QUERY); diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index ab2fe74..240dcf7 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; // Guard the Lighthouse fix: the initial page must not preload or statically @@ -62,6 +62,34 @@ if (staticImportPattern.test(entryChunk)) { fail('entry chunk statically imports a heavy Dash chunk'); } +// Lazy chunks may statically import only the entry chunk, which is already +// loaded. A shared dependency chunk can fail to download on its own, and +// WebKit keeps that failure across reloads, which would make every lazy chunk +// importing it unloadable (see experimentalMinChunkSize in vite.config.ts). +const entryFile = entryRelativePath.replace(/^assets\//, ''); +const assetsDir = join(distDir.pathname, 'assets'); +for (const file of readdirSync(assetsDir).filter((f) => f.endsWith('.js') && f !== entryFile)) { + const code = readFileSync(join(assetsDir, file), 'utf8'); + const staticDeps = [...code.matchAll(/(?:^|[;}\s])import\s*(?:[\w*{}\s,$]+from\s*)?["']\.\/([^"']+)["']/g)] + .map((m) => m[1]) + .filter((dep) => dep !== entryFile); + if (staticDeps.length > 0) { + fail(`assets/${file} statically imports ${staticDeps.join(', ')}; lazy chunks may only import the entry chunk`); + } +} + +// Cache-busted chunk retries (src/platform/chunk-loader.ts) import the URL +// that virtual:chunk-url put in the entry: it must name an asset the entry +// also loads with import(), or the retry would fetch something else. +const chunkUrls = [...entryChunk.matchAll(/new URL\(["']([^"']+\.js)["'],\s*import\.meta\.url\)/g)].map((m) => m[1]); +if (!chunkUrls.some((u) => u.startsWith('evo-sdk'))) { + fail('entry chunk has no virtual:chunk-url URL for the evo-sdk chunk'); +} +for (const url of chunkUrls) { + if (!existsSync(join(assetsDir, url))) fail(`chunk URL ${url} in the entry names no file in dist/assets`); + if (!entryChunk.includes(`import("./${url}")`)) fail(`chunk URL ${url} is not a dynamic import() target of the entry`); +} + // The embeddable widget SDK (docs/widget.md) must ship, stay tiny, and never // pull in the Dash SDK or other heavy dependencies. const WIDGET_MAX_BYTES = 30 * 1024; diff --git a/src/config/vite-chunk-url.ts b/src/config/vite-chunk-url.ts new file mode 100644 index 0000000..3ead7b7 --- /dev/null +++ b/src/config/vite-chunk-url.ts @@ -0,0 +1,62 @@ +import type { Plugin } from 'vite'; + +/** + * `import url from 'virtual:chunk-url:'` gives the built URL of + * the chunk that `import('')` loads (resolved like an import from + * the importing file), or null outside a production build. + * + * Why: a failed dynamic import is remembered in the browser's module map for + * the page's lifetime (Chromium, per the HTML spec), so retrying the same + * `import()` never re-fetches. Importing the same chunk under a URL with a + * query string is a new module map entry and does re-fetch (see + * platform/chunk-loader.ts). + * + * Only use it for modules that are already loaded lazily (dynamic import + * targets): the chunk is emitted explicitly (loaded after its importer), so a + * module that is statically imported elsewhere would be split out of the + * chunk it lives in now. + */ +const CHUNK_URL_PREFIX = 'virtual:chunk-url:'; +const RESOLVED_PREFIX = '\0' + CHUNK_URL_PREFIX; +// The dev server and vitest serve modules unbundled: there is no chunk to +// name. One id for all, which also keeps target paths out of dev request URLs. +const RESOLVED_DEV_ID = '\0virtual:chunk-url-dev'; + +export function chunkUrlPlugin(): Plugin { + let isBuild = false; + // Resolved virtual id -> the module that imports it. + const importers = new Map(); + return { + name: 'dash-bridge:chunk-url', + configResolved(config) { + isBuild = config.command === 'build'; + }, + async resolveId(source, importer) { + if (!source.startsWith(CHUNK_URL_PREFIX)) return null; + if (!isBuild) return RESOLVED_DEV_ID; + const target = source.slice(CHUNK_URL_PREFIX.length); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved || resolved.external) { + this.error(`chunk-url: cannot resolve "${target}" from ${importer ?? '(unknown)'}`); + } + const id = RESOLVED_PREFIX + resolved.id; + if (importer) importers.set(id, importer); + return id; + }, + load(id) { + if (id === RESOLVED_DEV_ID) return 'export default null;'; + if (!id.startsWith(RESOLVED_PREFIX)) return null; + const importer = importers.get(id); + const ref = this.emitFile({ + type: 'chunk', + id: id.slice(RESOLVED_PREFIX.length), + // The chunk is only ever loaded after its importer, as with the + // dynamic import it mirrors. Without this Rollup must assume it can + // load first and splits every module it shares with the main bundle + // out into separate chunks. + ...(importer ? { implicitlyLoadedAfterOneOf: [importer] } : {}), + }); + return `export default import.meta.ROLLUP_FILE_URL_${ref};`; + }, + }; +} diff --git a/src/main.ts b/src/main.ts index 0aca256..4ace06c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -207,10 +207,12 @@ import { loadIslockModule, loadPlatformClientModule, loadPlatformModule, + loadPlatformForFunding, loadUsernameTransferModule, warmDashModules, warmPlatformSdkForFunding, } from './platform/loaders.js'; +import { DEFAULT_CHUNK_LOAD_ATTEMPTS, ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; import { deriveCandidateKeys, explainKeyIneligibility, @@ -341,18 +343,66 @@ function preloadDashWarmup(): void { } /** - * Funding is about to start: begin connecting the SDK (testnet only), so the - * health indicator reads Platform before the asset lock is broadcast. Polls - * right after the connect settles instead of waiting for the next 30 s tick. + * The deposit-step key backup. Must run after preparePlatformForFunding: on + * iOS Safari the download raises "Do you want to download …?", which cancels + * the page's in-flight loads and fails new ones until answered. A chunk + * import cancelled that way stays failed for the page (that was the + * "Importing a module script failed." at registration). The testnet SDK + * connect may still be running past the gate's bounded wait and be cancelled + * too, so connect again once the page is back (focus) or after 15 s, for the + * health indicator; registration would reconnect anyway. */ -function startPlatformSdkForFunding(): void { - // Mock-mode flows must not touch the network. +function downloadFundingKeyBackup(backupState: BridgeState): void { + downloadKeyBackup(backupState); if (isE2EMockMode()) return; - void warmPlatformSdkForFunding(state.network).then((attempted) => { + const network = backupState.network; + const rewarm = () => { + window.removeEventListener('focus', rewarm); + clearTimeout(timer); + if (state.network === network) void warmFundingConnect(network); + }; + const timer = setTimeout(rewarm, 15_000); + window.addEventListener('focus', rewarm); +} + +/** + * Testnet: connect the SDK (shared with any connect in flight) and poll the + * health indicator as soon as it settles. Other networks: nothing. + */ +function warmFundingConnect(network: string): Promise { + return warmPlatformSdkForFunding(network).then((attempted) => { if (attempted) pollNetworkStatusNow?.(); }); } +/** How long a funding flow waits for the testnet SDK connect before showing its deposit address anyway. */ +const FUNDING_SDK_CONNECT_WAIT_MS = 5000; + +/** + * Gate in front of every funding flow's deposit address (shown as "Preparing + * Dash Platform..."). Loads the chunks the Platform submission needs, with + * retries, so that once funds are committed nothing depends on a download; + * when they still fail (or stall for 5 min) this throws a ChunkLoadError + * while nothing is at risk (error screen with Reload). + * + * Testnet also starts connecting the SDK, so the health indicator reads + * Platform before the asset lock is broadcast (polls right after the connect + * settles instead of waiting for the next 30 s tick). The flow waits for that + * connect at most FUNDING_SDK_CONNECT_WAIT_MS; it continues in the background + * and a failure stays a health-indicator matter, as before. + */ +async function preparePlatformForFunding(): Promise { + // Mock-mode flows must not touch the network. + if (isE2EMockMode()) { + await loadE2EMockSdk(); + return; + } + await loadPlatformForFunding(); + // Connected before the deposit-step backup download, whose iOS prompt would + // cancel a connect still in flight (see downloadFundingKeyBackup). + await Promise.race([warmFundingConnect(state.network), delay(FUNDING_SDK_CONNECT_WAIT_MS)]); +} + // ── Network-status polling ────────────────────────────────────────────────── // Periodically compares Core (Insight) height against Platform (DAPI) status // so the header can warn when Platform consensus stalls while Core keeps @@ -516,6 +566,59 @@ function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +/** + * Failure injection for mock-mode e2e tests, set with page.addInitScript as + * window.__e2eMockFailures: `sdkLoadFailures` failed SDK chunk loads before + * the gate's loader succeeds (DEFAULT_CHUNK_LOAD_ATTEMPTS or more exhausts its + * retries), `submissionFailures` failed Platform submissions after the + * InstantSend lock arrived. + */ +interface E2EMockFailures { + sdkLoadFailures?: number; + submissionFailures?: number; +} + +/** Use up one injected failure of this kind; true if there was one left. */ +function consumeE2EMockFailure(kind: keyof E2EMockFailures): boolean { + const failures = (window as typeof window & { __e2eMockFailures?: E2EMockFailures }).__e2eMockFailures; + const remaining = failures?.[kind] ?? 0; + if (!failures || remaining <= 0) return false; + failures[kind] = remaining - 1; + return true; +} + +function mockImportFailure(): TypeError { + return new TypeError('Importing a module script failed.'); +} + +// The real retrying loader around a fake SDK import, so the e2e suite +// exercises its retries and error. +const loadE2EMockSdk = createChunkLoader('evo-sdk', null, async () => { + if (consumeE2EMockFailure('sdkLoadFailures')) throw mockImportFailure(); + return {}; +}); + +function e2eMockSubmissionSteps(mode: BridgeState['mode']): { + step: BridgeStep; + complete: (s: BridgeState) => BridgeState; +} { + switch (mode) { + case 'topup': + return { step: 'topping_up', complete: setTopUpComplete }; + case 'send_to_address': + return { step: 'sending_to_address', complete: setSendToAddressComplete }; + default: + return { step: 'registering_identity', complete: (s) => setIdentityRegistered(s, E2E_MOCK_IDENTITY_ID) }; + } +} + +async function runE2EMockSubmission(): Promise { + await delay(120); + if (consumeE2EMockFailure('submissionFailures')) { + throw new ChunkLoadError('evo-sdk', DEFAULT_CHUNK_LOAD_ATTEMPTS, mockImportFailure()); + } +} + function createE2EMockUtxo(): UTXO { return { txid: 'a'.repeat(64), @@ -1126,15 +1229,21 @@ function setupEventListeners(container: HTMLElement) { }); } - // Retry registration (offered on the error screen when an identity - // registration was submitted but could not be confirmed) - const retryRegistrationBtn = container.querySelector('#retry-registration-btn'); - if (retryRegistrationBtn) { - retryRegistrationBtn.addEventListener('click', () => { - void retryIdentityRegistration(); + // Retry the Platform submission with the lock already received (offered on + // the error screen when the submission failed after the lock arrived) + const retrySubmissionBtn = container.querySelector('#retry-registration-btn'); + if (retrySubmissionBtn) { + retrySubmissionBtn.addEventListener('click', () => { + void retryPlatformSubmission(); }); } + // Reload (offered when a required chunk failed to load before any deposit + // address was shown, so nothing is lost by reloading) + container.querySelector('#reload-page-btn')?.addEventListener('click', () => { + window.location.reload(); + }); + // Chainlock fallback button (offered on the error screen when applicable) const chainlockFallbackBtn = container.querySelector('#chainlock-fallback-btn'); if (chainlockFallbackBtn) { @@ -2714,7 +2823,9 @@ async function startTopUp() { updateState(setStep(state, 'generating_keys')); await delay(120); + await preparePlatformForFunding(); updateState(setOneTimeKeyPair(state, assetLockKeyPair, depositAddress)); + downloadFundingKeyBackup(state); updateState(setStep(state, 'detecting_deposit')); clearE2EMockAdvanceHook(); await waitForE2EMockAdvance(); @@ -2731,14 +2842,14 @@ async function startTopUp() { outputIndex: 0, })); updateState(setStep(state, 'topping_up')); - await delay(120); + await runE2EMockSubmission(); updateState(setTopUpComplete(state)); return; } updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2752,7 +2863,8 @@ async function startTopUp() { // Auto-download key backup immediately for safety // CRITICAL: User must have this to recover funds if something goes wrong - downloadKeyBackup(stateWithKeys); + // (after preparePlatformForFunding: see downloadFundingKeyBackup) + downloadFundingKeyBackup(stateWithKeys); // Step 2: Wait for deposit updateState(setStep(stateWithKeys, 'detecting_deposit')); @@ -2863,7 +2975,7 @@ async function startSendToAddress() { try { updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2876,7 +2988,7 @@ async function startSendToAddress() { updateState(stateWithKeys); // Auto-download key backup for safety - downloadKeyBackup(stateWithKeys); + downloadFundingKeyBackup(stateWithKeys); // Step 2: Wait for deposit updateState(setStep(stateWithKeys, 'detecting_deposit')); @@ -2970,14 +3082,15 @@ async function startSendToAddress() { } /** - * Resubmit identity registration with the asset lock proof already in - * state. Offered on the error screen after an unconfirmed submission: the - * asset lock can only be consumed once and the identity ID is - * deterministic, so resubmitting can't create a second identity. + * Resubmit the Platform operation (registration, top-up or send) with the + * asset lock proof already in state. Offered on the error screen when the + * submission failed after the lock arrived: the asset lock can only be + * consumed once and the identity ID is deterministic, so resubmitting can't + * spend the deposit twice or create a second identity. */ -async function retryIdentityRegistration(): Promise { +async function retryPlatformSubmission(): Promise { if (!state.assetLockProof || !state.assetLockKeyPair) { - console.error('Retry registration unavailable: missing asset lock proof or key'); + console.error('Retry submission unavailable: missing asset lock proof or key'); return; } try { @@ -2987,7 +3100,7 @@ async function retryIdentityRegistration(): Promise { ); await runPlatformSubmission(state.assetLockProof, assetLockPrivateKeyWif); } catch (error) { - console.error('Retry registration error:', error); + console.error('Retry submission error:', error); updateState(setError(state, toError(error))); } } @@ -3005,7 +3118,9 @@ async function startBridge() { clearE2EMockAdvanceHook(); updateState(setStep(state, 'generating_keys')); await delay(120); + await preparePlatformForFunding(); updateState(setKeyPairs(state, assetLockKeyPair, depositAddress)); + downloadFundingKeyBackup(state); updateState(setStep(state, 'detecting_deposit')); await waitForE2EMockAdvance(); updateState(setUtxoDetected(state, createE2EMockUtxo())); @@ -3020,7 +3135,7 @@ async function startBridge() { instantLockBytes: new Uint8Array([5, 6, 7, 8]), outputIndex: 0, })); - await delay(120); + await runE2EMockSubmission(); updateState(setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); return; } @@ -3035,7 +3150,7 @@ async function startBridge() { // Step 1: Derive asset lock key from mnemonic (identity keys are pre-configured in state) updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const { privateKey, publicKey } = deriveAssetLockKeyPair(state.mnemonic, state.network); @@ -3048,7 +3163,7 @@ async function startBridge() { // Auto-download key backup immediately for safety // This ensures users can recover funds if they reload the page - downloadKeyBackup(state); + downloadFundingKeyBackup(state); // Step 2: Wait for deposit updateState(setStep(state, 'detecting_deposit')); @@ -3138,15 +3253,7 @@ async function startBridge() { state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - - // Auto-download final key backup on "Save your keys" page - // This backup includes the identity ID in the filename - // (Earlier download at deposit step used pending filename) - downloadKeyBackup(state); - - // Auto-publish contract if this identity was created for contract registration - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); } catch (error) { if (isE2EMockMode()) { @@ -3281,12 +3388,7 @@ async function recheckDeposit() { state.identityKeys, state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - // Auto-download final key backup on "Save your keys" page - downloadKeyBackup(state); - - // Auto-publish contract if applicable - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); } else { throw new Error(`recheckDeposit: unexpected mode '${state.mode}'`); } @@ -3316,6 +3418,14 @@ async function runPlatformSubmission( assetLockProof: AssetLockProofData, assetLockPrivateKeyWif: string ): Promise { + if (isE2EMockMode()) { + const { step, complete } = e2eMockSubmissionSteps(state.mode); + updateState(setStep(state, step)); + await runE2EMockSubmission(); + updateState(complete(state)); + return; + } + if (state.mode === 'topup') { updateState(setStep(state, 'topping_up')); const { topUpIdentity } = await loadPlatformModule(); @@ -3351,10 +3461,7 @@ async function runPlatformSubmission( state.identityKeys, state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - downloadKeyBackup(state); - - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); return; } @@ -3515,6 +3622,22 @@ async function startChainlockFallback(): Promise { // Contract Registration Functions // ============================================================================ +/** + * Identity registered: show it, publish the contract it was created for (if + * any), then download the final key backup (its filename has the identity + * ID; the deposit-step backup already holds the keys). The download goes + * last: on iOS Safari it raises a prompt that makes the page's requests fail + * until answered, which would fail the contract publish. + */ +async function completeIdentityCreation(identityId: string): Promise { + updateState(setIdentityRegistered(state, identityId)); + try { + await autoPublishContractIfNeeded(identityId); + } finally { + downloadKeyBackup(state); + } +} + /** * Auto-publish contract after identity creation if the identity was created * for contract registration. Finds the first suitable auth key and publishes. diff --git a/src/platform/chunk-loader.test.ts b/src/platform/chunk-loader.test.ts new file mode 100644 index 0000000..89e0dd1 --- /dev/null +++ b/src/platform/chunk-loader.test.ts @@ -0,0 +1,237 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ChunkLoadError, cacheBustedUrl, createChunkLoader, noteDownloadStarted, withChunkTimeout } from './chunk-loader.js'; + +const noSleep = { sleep: async () => {} }; + +describe('createChunkLoader', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('reuses one in-flight promise for concurrent calls', async () => { + let calls = 0; + let resolveLoad: ((value: string) => void) | undefined; + const loader = createChunkLoader('x', null, () => { + calls += 1; + return new Promise((resolve) => { + resolveLoad = resolve; + }); + }); + + const first = loader(); + const second = loader(); + + expect(first).toBe(second); + expect(calls).toBe(1); + + resolveLoad?.('ready'); + await expect(first).resolves.toBe('ready'); + await expect(second).resolves.toBe('ready'); + }); + + it('retries the plain import with backoff when the chunk URL is unknown', async () => { + const sleeps: number[] = []; + let calls = 0; + const loader = createChunkLoader('x', null, async () => { + calls += 1; + if (calls < 3) throw new TypeError('Importing a module script failed.'); + return 'loaded'; + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + await expect(loader()).resolves.toBe('loaded'); + expect(calls).toBe(3); + expect(sleeps).toEqual([500, 1500]); + }); + + it('retries under a cache-busted chunk URL, because a failed import() is remembered per URL', async () => { + const importUrl = vi.fn(async (url: string) => ({ from: url })); + const load = vi.fn(async () => { + throw new TypeError('Failed to fetch dynamically imported module'); + }); + const loader = createChunkLoader( + 'evo-sdk', + 'https://bridge.example/assets/evo-sdk.module-abc.js', + load, + { ...noSleep, importUrl } + ); + + const mod = (await loader()) as unknown as { from: string }; + expect(load).toHaveBeenCalledTimes(1); + expect(importUrl).toHaveBeenCalledTimes(1); + const url = new URL(mod.from); + expect(url.origin + url.pathname).toBe('https://bridge.example/assets/evo-sdk.module-abc.js'); + expect(url.searchParams.get('retry')).toMatch(/^1\./); + }); + + it('never reuses a failed URL in a later round, as the browser would answer it from its module map', async () => { + const failed = new Set(); + let networkUp = false; + const requests: string[] = []; + const importUrl = async (url: string) => { + if (failed.has(url)) throw new TypeError('Importing a module script failed.'); // no request + requests.push(url); + if (!networkUp) { + failed.add(url); + throw new TypeError('Importing a module script failed.'); + } + return { url }; + }; + const chunkUrl = 'https://bridge.example/assets/evo-sdk.module-abc.js'; + const loader = createChunkLoader('evo-sdk', chunkUrl, () => importUrl(chunkUrl), { ...noSleep, importUrl }); + + await expect(loader()).rejects.toBeInstanceOf(ChunkLoadError); + expect(requests).toHaveLength(3); + networkUp = true; + await expect(loader()).resolves.toBeTruthy(); + expect(requests).toHaveLength(4); + expect(new Set(requests).size).toBe(4); + }); + + it('makes concurrent callers during a failing round share one request sequence and one error', async () => { + const requests: string[] = []; + const importUrl = async (url: string) => { + requests.push(url); + throw new TypeError('Importing a module script failed.'); + }; + const chunkUrl = 'https://bridge.example/assets/evo-sdk.module-abc.js'; + const loader = createChunkLoader('evo-sdk', chunkUrl, () => importUrl(chunkUrl), { ...noSleep, importUrl }); + + const [a, b] = await Promise.all([loader().catch((e: unknown) => e), loader().catch((e: unknown) => e)]); + expect(a).toBeInstanceOf(ChunkLoadError); + expect(b).toBe(a); + expect(requests).toHaveLength(3); + }); + + it('does not retry an error that is not a failed download', async () => { + let calls = 0; + const loader = createChunkLoader('x', 'https://h.example/x.js', async () => { + calls += 1; + throw new SyntaxError('Unexpected token'); + }, noSleep); + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.attempts).toBe(1); + expect(calls).toBe(1); + }); + + it('gives up after 3 attempts with a ChunkLoadError naming the chunk, logs each failure, then lets a later call start over', async () => { + let calls = 0; + const loader = createChunkLoader('evo-sdk', null, async () => { + calls += 1; + if (calls <= 3) throw new TypeError('Importing a module script failed.'); + return 'recovered'; + }, noSleep); + + const error = await loader().catch((e: unknown) => e); + expect(error).toBeInstanceOf(ChunkLoadError); + expect((error as ChunkLoadError).chunk).toBe('evo-sdk'); + expect((error as ChunkLoadError).attempts).toBe(3); + expect((error as ChunkLoadError).message).toBe( + 'Could not load the "evo-sdk" component after 3 attempts: Importing a module script failed.' + ); + const warn = vi.mocked(console.warn); + expect(warn).toHaveBeenCalledTimes(3); + expect(String(warn.mock.calls[0][0])).toContain('Chunk "evo-sdk" failed to load (attempt 1/3); retrying in 500 ms'); + expect(String(warn.mock.calls[2][0])).toContain('(attempt 3/3)'); + + await expect(loader()).resolves.toBe('recovered'); + expect(calls).toBe(4); + }); +}); + +describe('createChunkLoader right after a file download started', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + noteDownloadStarted(0); // long ago: outside the prompt window again + vi.restoreAllMocks(); + }); + + it('keeps retrying for about a minute, since an open download prompt fails every load until answered', async () => { + noteDownloadStarted(); + const sleeps: number[] = []; + let calls = 0; + const loader = createChunkLoader('evo-sdk', null, async () => { + calls += 1; + if (calls < 5) throw new TypeError('Importing a module script failed.'); + return 'loaded'; + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + await expect(loader()).resolves.toBe('loaded'); + expect(sleeps).toEqual([2000, 5000, 10000, 15000]); + expect(String(vi.mocked(console.warn).mock.calls[0][0])).toContain('its prompt may be blocking loads'); + }); + + it('flags the download prompt on the error when it never clears', async () => { + noteDownloadStarted(); + const loader = createChunkLoader('evo-sdk', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, noSleep); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.attempts).toBe(6); + expect(error.downloadPromptSuspected).toBe(true); + }); + + it('picks the backoff at the first failure only: a download during the round does not stretch it', async () => { + const sleeps: number[] = []; + const loader = createChunkLoader('x', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, { sleep: async (ms) => { sleeps.push(ms); noteDownloadStarted(); } }); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(sleeps).toEqual([500, 1500]); + expect(error.attempts).toBe(3); + expect(error.downloadPromptSuspected).toBe(false); + }); + + it('uses the short backoff once the download is long past', async () => { + noteDownloadStarted(Date.now() - 61_000); + const sleeps: number[] = []; + const loader = createChunkLoader('x', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(sleeps).toEqual([500, 1500]); + expect(error.downloadPromptSuspected).toBe(false); + }); +}); + +describe('cacheBustedUrl', () => { + it('keeps the path, adds a per-attempt retry parameter and preserves other query params', () => { + const a = new URL(cacheBustedUrl('https://h.example/a/chunk.js?x=1', 1)); + const b = new URL(cacheBustedUrl('https://h.example/a/chunk.js?x=1', 2)); + expect(a.pathname).toBe('/a/chunk.js'); + expect(a.searchParams.get('x')).toBe('1'); + expect(a.searchParams.get('retry')).not.toBe(b.searchParams.get('retry')); + }); +}); + +describe('withChunkTimeout', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('rejects with a ChunkLoadError naming the stalled chunk', async () => { + vi.useFakeTimers(); + const stalled = withChunkTimeout(new Promise(() => {}), 'platform', 300_000).catch((e: unknown) => e); + await vi.advanceTimersByTimeAsync(300_000); + const error = (await stalled) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.chunk).toBe('platform'); + expect(error.message).toContain('still loading after 300 s'); + }); + + it('passes a load that finishes in time through', async () => { + await expect(withChunkTimeout(Promise.resolve('ok'), 'evo-sdk', 1000)).resolves.toBe('ok'); + }); +}); diff --git a/src/platform/chunk-loader.ts b/src/platform/chunk-loader.ts new file mode 100644 index 0000000..458bacc --- /dev/null +++ b/src/platform/chunk-loader.ts @@ -0,0 +1,169 @@ +/** + * Lazy chunk loading that survives a dropped download. + * + * Browsers remember a failed `import()` for the page's lifetime (Chromium + * follows the HTML spec's module map; iOS WebKit may too), so retrying the same + * import rejects again without touching the network. Retries therefore import + * the chunk's built URL with a query string, which is a new module map entry. + * The chunk's own static imports still resolve to the shared, already-loaded + * modules, so nothing is instantiated twice. + * + * iOS Safari: a programmatic file download (the key backup) raises "Do you + * want to download …?", and until the user answers it the page's loads fail. + * That is how the EvoSDK chunk got poisoned mid-flow. Funding flows therefore + * load their chunks before the first backup download; as a fallback, a load + * failing right after a download retries for about a minute and says why. + */ + +/** Thrown when a lazily loaded part of the app could not be downloaded. */ +export class ChunkLoadError extends Error { + readonly chunk: string; + readonly attempts: number; + /** A file download had just started, so a browser download prompt may have blocked the load. */ + readonly downloadPromptSuspected: boolean; + + constructor(chunk: string, attempts: number, cause: unknown, downloadPromptSuspected = false) { + const reason = cause instanceof Error ? cause.message : String(cause); + super(`Could not load the "${chunk}" component after ${attempts} attempt${attempts === 1 ? '' : 's'}: ${reason}`); + this.name = 'ChunkLoadError'; + this.chunk = chunk; + this.attempts = attempts; + this.downloadPromptSuspected = downloadPromptSuspected; + (this as { cause?: unknown }).cause = cause; + } +} + +interface ChunkLoaderOptions { + /** Overridable for tests. */ + sleep?: (ms: number) => Promise; + /** Imports a URL (overridable for tests). */ + importUrl?: (url: string) => Promise; +} + +/** Delay before each retry. */ +const RETRY_DELAYS_MS: readonly number[] = [500, 1500]; +/** Attempts per round normally; a round right after a download prompt makes more. */ +export const DEFAULT_CHUNK_LOAD_ATTEMPTS = RETRY_DELAYS_MS.length + 1; +/** Retry delays while a download prompt may be open (about a minute in total). */ +const PROMPT_RETRY_DELAYS_MS: readonly number[] = [2000, 5000, 10000, 15000, 30000]; +const DOWNLOAD_PROMPT_WINDOW_MS = 60_000; + +let lastDownloadStartedAt = -Infinity; + +/** + * Call when the page starts a file download that raises a prompt blocking the + * page's loads (iOS/iPadOS Safari and other iOS browsers, all WebKit). + */ +export function noteDownloadStarted(now = Date.now()): void { + lastDownloadStartedAt = now; +} + +function downloadPromptMayBeOpen(): boolean { + return Date.now() - lastDownloadStartedAt < DOWNLOAD_PROMPT_WINDOW_MS; +} + +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const defaultImportUrl = (url: string) => import(/* @vite-ignore */ url); + +/** Unique per page load, so a CDN cannot answer the retry from a cached error. */ +const pageToken = Date.now().toString(36); + +/** + * Reject with a ChunkLoadError naming `chunk` if `promise` has not settled + * within `ms` (a stalled download would otherwise wait forever). The load + * itself keeps going; a later call may still use it. + */ +export async function withChunkTimeout(promise: Promise, chunk: string, ms: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new ChunkLoadError(chunk, 1, new Error(`still loading after ${ms / 1000} s`))), ms); + }); + try { + return await Promise.race([promise, timeout]); + } finally { + clearTimeout(timer); + } +} + +export function cacheBustedUrl(url: string, attempt: number): string { + const parsed = new URL(url, globalThis.location?.href); + parsed.searchParams.set('retry', `${attempt}.${pageToken}`); + return parsed.href; +} + +/** + * Memoized loader for a lazily imported chunk. Concurrent callers share one + * load; a failed download is retried with backoff (re-fetching under a + * cache-busted URL when the chunk URL is known), then the memo is cleared so a + * later call starts over, and a ChunkLoadError naming the chunk is thrown. + * Every cache-busted URL is used once per page: the browser remembers the ones + * that failed, so a later round must not repeat them. Errors other than a + * failed download (TypeError), e.g. a SyntaxError while evaluating, are not + * retried. + * + * @param chunk name for logs and the error screen + * @param chunkUrl built URL of the chunk (virtual:chunk-url), null in dev + * @param load the plain dynamic import + */ +export function createChunkLoader( + chunk: string, + chunkUrl: string | null, + load: () => Promise, + options: ChunkLoaderOptions = {} +): () => Promise { + const sleep = options.sleep ?? defaultSleep; + const importUrl = options.importUrl ?? defaultImportUrl; + // Across rounds: once the plain import failed, the browser may answer it + // from its module map forever, and each busted URL is likewise good once. + let plainImportFailed = false; + let bustedUrls = 0; + + const loadOnce = async (): Promise => { + if (!chunkUrl || !plainImportFailed) { + try { + return await load(); + } catch (error) { + plainImportFailed = true; + throw error; + } + } + bustedUrls += 1; + return (await importUrl(cacheBustedUrl(chunkUrl, bustedUrls))) as T; + }; + + const loadWithRetries = async (): Promise => { + // Picked at the first failure: a download prompt that is open then keeps + // every load failing until the user answers it. + let delays = RETRY_DELAYS_MS; + let promptSuspected = false; + for (let attempt = 0; ; attempt++) { + try { + return await loadOnce(); + } catch (error) { + if (!(error instanceof TypeError)) throw new ChunkLoadError(chunk, attempt + 1, error); + if (attempt === 0 && downloadPromptMayBeOpen()) { + delays = PROMPT_RETRY_DELAYS_MS; + promptSuspected = true; + } + const attempts = delays.length + 1; + const retryDelay: number | undefined = delays[attempt]; + const retrying = retryDelay === undefined ? '' : `; retrying in ${retryDelay} ms`; + const why = promptSuspected ? ' (a file download just started; its prompt may be blocking loads)' : ''; + console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${attempts})${why}${retrying}:`, error); + if (retryDelay === undefined) throw new ChunkLoadError(chunk, attempts, error, promptSuspected); + await sleep(retryDelay); + } + } + }; + + let promise: Promise | null = null; + return () => { + if (!promise) { + promise = loadWithRetries().catch((err) => { + promise = null; + throw err; + }); + } + return promise; + }; +} diff --git a/src/platform/loaders.test.ts b/src/platform/loaders.test.ts deleted file mode 100644 index 7296055..0000000 --- a/src/platform/loaders.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { createCachedLoader } from './loaders.js'; - -describe('createCachedLoader', () => { - it('reuses one in-flight promise for concurrent calls', async () => { - let calls = 0; - let resolveLoad: ((value: string) => void) | undefined; - const loader = createCachedLoader(() => { - calls += 1; - return new Promise((resolve) => { - resolveLoad = resolve; - }); - }); - - const first = loader(); - const second = loader(); - - expect(first).toBe(second); - expect(calls).toBe(1); - - resolveLoad?.('ready'); - await expect(first).resolves.toBe('ready'); - await expect(second).resolves.toBe('ready'); - }); - - it('clears a rejected promise so a later call can retry', async () => { - let calls = 0; - const loader = createCachedLoader(async () => { - calls += 1; - if (calls === 1) { - throw new Error('chunk failed'); - } - return 'recovered'; - }); - - await expect(loader()).rejects.toThrow('chunk failed'); - await expect(loader()).resolves.toBe('recovered'); - expect(calls).toBe(2); - }); -}); diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index 09a9123..8099b6c 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -1,25 +1,30 @@ +import platformChunkUrl from 'virtual:chunk-url:./index.js'; +import dpnsChunkUrl from 'virtual:chunk-url:./dpns.js'; +import contractChunkUrl from 'virtual:chunk-url:./contract.js'; +import usernameTransferChunkUrl from 'virtual:chunk-url:./username-transfer.js'; +import feeEstimatorChunkUrl from 'virtual:chunk-url:dash-contract-fee-estimator'; +import islockChunkUrl from 'virtual:chunk-url:../api/islock.js'; import { getNetwork } from '../config.js'; +import { createChunkLoader, withChunkTimeout } from './chunk-loader.js'; +import { loadSdkModule } from './sdkModule.js'; -export function createCachedLoader(load: () => Promise): () => Promise { - let promise: Promise | null = null; - return () => { - if (!promise) { - promise = load().catch((err) => { - promise = null; - throw err; - }); - } - return promise; - }; -} - -export const loadPlatformModule = createCachedLoader(() => import('./index.js')); -export const loadDpnsModule = createCachedLoader(() => import('./dpns.js')); -export const loadContractModule = createCachedLoader(() => import('./contract.js')); -export const loadUsernameTransferModule = createCachedLoader(() => import('./username-transfer.js')); -export const loadPlatformClientModule = createCachedLoader(() => import('./client.js')); -export const loadFeeEstimatorModule = createCachedLoader(() => import('dash-contract-fee-estimator')); -export const loadIslockModule = createCachedLoader(() => import('../api/islock.js')); +export const loadPlatformModule = createChunkLoader('platform', platformChunkUrl, () => import('./index.js')); +export const loadDpnsModule = createChunkLoader('dpns', dpnsChunkUrl, () => import('./dpns.js')); +export const loadContractModule = createChunkLoader('contract', contractChunkUrl, () => import('./contract.js')); +export const loadUsernameTransferModule = createChunkLoader( + 'username-transfer', + usernameTransferChunkUrl, + () => import('./username-transfer.js') +); +// client.ts is statically imported by other platform modules, so it lives in +// the main chunk and this import never fetches anything: no chunk URL needed. +export const loadPlatformClientModule = createChunkLoader('platform-client', null, () => import('./client.js')); +export const loadFeeEstimatorModule = createChunkLoader( + 'fee-estimator', + feeEstimatorChunkUrl, + () => import('dash-contract-fee-estimator') +); +export const loadIslockModule = createChunkLoader('islock', islockChunkUrl, () => import('../api/islock.js')); export function warmDashModules(): Promise[]> { return Promise.allSettled([ @@ -33,6 +38,20 @@ export function warmDashModules(): Promise[]> { ]); } +/** + * Load the chunks a Platform submission needs (EvoSDK and platform + * operations), for the funding gate in main.ts. Rejects with a ChunkLoadError + * naming the chunk when it still fails after the loaders' retries, or is + * still loading after `timeoutMs` (the SDK is ~7 MB gzipped: 5 min covers + * about 200 kbit/s; Reload would throw a partial download away). + */ +export async function loadPlatformForFunding(timeoutMs = 5 * 60_000): Promise { + await Promise.all([ + withChunkTimeout(loadSdkModule(), 'evo-sdk', timeoutMs), + withChunkTimeout(loadPlatformModule(), 'platform', timeoutMs), + ]); +} + /** * Start connecting the EvoSDK when the user enters a funding flow (create, * top-up, send-to-address), before any funds can be committed. Registration diff --git a/src/platform/sdkModule.ts b/src/platform/sdkModule.ts index 679e652..41134a2 100644 --- a/src/platform/sdkModule.ts +++ b/src/platform/sdkModule.ts @@ -1,5 +1,6 @@ -import { createCachedLoader } from './loaders.js'; +import evoSdkChunkUrl from 'virtual:chunk-url:@dashevo/evo-sdk'; +import { createChunkLoader } from './chunk-loader.js'; export type SdkModule = typeof import('@dashevo/evo-sdk'); -export const loadSdkModule = createCachedLoader(() => import('@dashevo/evo-sdk')); +export const loadSdkModule = createChunkLoader('evo-sdk', evoSdkChunkUrl, () => import('@dashevo/evo-sdk')); diff --git a/src/ui/components.error-recovery.test.ts b/src/ui/components.error-recovery.test.ts new file mode 100644 index 0000000..7be8025 --- /dev/null +++ b/src/ui/components.error-recovery.test.ts @@ -0,0 +1,96 @@ +// @vitest-environment happy-dom +import { describe, it, expect, vi } from 'vitest'; + +// QR rendering needs a canvas, which happy-dom does not provide. +vi.mock('./qrcode.js', () => ({ + generateQRCodeDataUrl: () => new Promise(() => {}), +})); + +import { render } from './components.js'; +import { createInitialState, setError } from './state.js'; +import type { BridgeState } from '../types.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; + +const importFailure = () => new ChunkLoadError('evo-sdk', 3, new TypeError('Importing a module script failed.')); + +function renderError(state: BridgeState, error: Error): HTMLElement { + const container = document.createElement('div'); + render(setError(state, error), container); + return container; +} + +const lockReceived: BridgeState = { + ...createInitialState('testnet'), + step: 'registering_identity', + depositAddress: 'yAddr', + txid: 'ab'.repeat(32), + signedTxBytes: new Uint8Array([0]), + assetLockKeyPair: { privateKey: new Uint8Array(32), publicKey: new Uint8Array(33) }, + assetLockProof: { type: 'instant', transactionBytes: new Uint8Array([1]), instantLockBytes: new Uint8Array([2]), outputIndex: 0 }, +}; + +describe('error screen recovery copy', () => { + it('after the lock arrived: says so, offers Retry Registration and the chain lock proof, names the failed chunk', () => { + const el = renderError(lockReceived, importFailure()); + const text = el.textContent ?? ''; + expect(text).toContain('Identity registration failed'); + expect(text).not.toContain("InstantSend didn't go through"); + expect(text).toContain('the InstantSend lock arrived'); + expect(text).toContain('could not load the "evo-sdk" component'); + expect(el.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Registration'); + expect(el.querySelector('#chainlock-fallback-btn')).not.toBeNull(); + expect(el.querySelector('#reload-page-btn')).toBeNull(); + expect(el.querySelector('.error-technical-content')?.textContent).toContain('Failed to load: evo-sdk'); + }); + + it('labels the retry for top-up and send', () => { + const el = renderError( + { ...lockReceived, mode: 'topup', step: 'topping_up' }, + new Error('Dapi client error: transport error: grpc error: TypeError: Failed to fetch') + ); + expect(el.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Top-up'); + expect(el.textContent).toContain('the Platform step failed'); + const send = renderError({ ...lockReceived, mode: 'send_to_address', step: 'sending_to_address' }, importFailure()); + expect(send.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Send'); + }); + + it('still says InstantSend did not go through when the lock never arrived', () => { + const el = renderError( + { ...lockReceived, step: 'waiting_islock', assetLockProof: undefined }, + new Error('Timed out waiting for InstantSend lock') + ); + expect(el.textContent).toContain("InstantSend didn't go through"); + expect(el.querySelector('#retry-registration-btn')).toBeNull(); + }); + + it('before the deposit address: explains the failed component and offers Reload, no funding UI', () => { + const el = renderError({ ...createInitialState('testnet'), step: 'generating_keys' }, importFailure()); + const text = el.textContent ?? ''; + expect(text).toContain('ERR-1017'); + expect(text).toContain('The page failed to load a required component "evo-sdk"'); + expect(text).toContain('No funds have been sent'); + expect(el.querySelector('#reload-page-btn')?.textContent).toBe('Reload'); + expect(el.querySelector('#retry-registration-btn')).toBeNull(); + expect(el.querySelector('#chainlock-fallback-btn')).toBeNull(); + expect(el.querySelector('#download-keys-btn')).toBeNull(); + }); +}); + +describe('component failure right after a backup download started', () => { + it('points at the browser download prompt instead of the network', () => { + const error = new ChunkLoadError('evo-sdk', 6, new TypeError('Importing a module script failed.'), true); + const el = renderError({ ...createInitialState('testnet'), step: 'generating_keys' }, error); + expect(el.textContent).toContain('asking whether to download the key backup file: answer that prompt first'); + expect(el.textContent).not.toContain('network interruption'); + expect(el.querySelector('#reload-page-btn')).not.toBeNull(); + }); +}); + +describe('funding gate screen', () => { + it('shows Preparing… (not a blank page) while the Platform components load', () => { + const container = document.createElement('div'); + render({ ...createInitialState('testnet'), step: 'generating_keys' }, container); + expect(container.querySelector('.preparing-step')?.textContent).toContain('Preparing…'); + expect(container.querySelector('.address')).toBeNull(); + }); +}); diff --git a/src/ui/components.ts b/src/ui/components.ts index 28db465..5731afb 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -1,6 +1,6 @@ import type { BridgeState, KeyType, KeyPurpose, SecurityLevel, NetworkHealth, NetworkStatus, EmbedNotice, NearIntentsState, NearIntentsSwap } from '../types.js'; import { canCancel } from '../embed/bridge.js'; -import { getStepProgress, getStepDescription, ErrorCodes, ErrorCodeLabels } from './state.js'; +import { getStepProgress, getStepDescription, getErrorRecovery, ErrorCodes, ErrorCodeLabels, type ErrorRecovery } from './state.js'; import { formatUnits, formatUnitsShort, @@ -31,6 +31,7 @@ import { bytesToHex } from '../utils/hex.js'; import { getNetwork, getAvailableNetworks } from '../config.js'; import { getAssetLockDerivationPath } from '../crypto/hd.js'; import { formatAge } from '../api/network-status.js'; +import { noteDownloadStarted } from '../platform/chunk-loader.js'; /** Dot color + label for each network-health verdict. */ const NETWORK_HEALTH_META: Record< @@ -274,6 +275,10 @@ export function render(state: BridgeState, container: HTMLElement): void { content.appendChild(renderEnterRecipientAddressStep(state)); break; + case 'generating_keys': + content.appendChild(renderPreparingStep()); + break; + case 'awaiting_deposit': case 'detecting_deposit': content.appendChild(renderDepositStep(state)); @@ -1557,6 +1562,21 @@ function renderNearSwap(swap: NearIntentsSwap): HTMLElement { return el; } +/** + * Shown while a funding flow loads the Platform components it needs before + * showing a deposit address (the SDK is several MB, slow on mobile networks). + */ +function renderPreparingStep(): HTMLElement { + const div = document.createElement('div'); + div.className = 'processing-step preparing-step'; + div.innerHTML = ` +

Preparing…

+

Loading the Dash Platform components needed to finish. Your deposit address appears next.

+
+ `; + return div; +} + function renderProcessingStep(state: BridgeState): HTMLElement { const div = document.createElement('div'); div.className = 'processing-step'; @@ -1794,6 +1814,8 @@ function buildErrorDiagnostics(state: BridgeState): Record { mode: state.mode, timestamp: new Date().toISOString(), }; + const { failedChunk } = getErrorRecovery(state); + if (failedChunk) diag.failedChunk = failedChunk; // Transaction context — critical for tracking on-chain state // NOTE: signedTxHex is intentionally excluded — if the error occurred before @@ -1863,6 +1885,50 @@ function buildErrorDiagnostics(state: BridgeState): Record { return diag; } +/** ` "evo-sdk"` (leading space) when a chunk failed to load, else empty. */ +function chunkLabel(recovery: ErrorRecovery): string { + return recovery.failedChunk ? ` "${recovery.failedChunk}"` : ''; +} + +function chunkFailureCause(recovery: ErrorRecovery): string { + return recovery.downloadPromptSuspected + ? 'most likely your browser was asking whether to download the key backup file: answer that prompt first' + : 'most likely a network interruption'; +} + +function chainlockFallbackHint(state: BridgeState, recovery: ErrorRecovery): string { + if (recovery.lockReceived) { + return 'If Platform keeps rejecting the InstantSend proof, you can wait for a chain lock and submit a chain-based proof instead.'; + } + if (state.errorCode === ErrorCodes.ISLOCK) { + return "InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead."; + } + return 'You can wait for a chain lock and try again with a chain-based proof instead.'; +} + +function retrySubmissionLabel(mode: BridgeState['mode']): string { + switch (mode) { + case 'topup': return 'Retry Top-up'; + case 'send_to_address': return 'Retry Send'; + default: return 'Retry Registration'; + } +} + +// The asset lock can be consumed only once and the identity ID is derived +// from it, so resubmitting the proof in state cannot spend the deposit twice. +function retrySubmissionHint(state: BridgeState, recovery: ErrorRecovery): string { + if (isIdentityRegistrationUnconfirmedError(state.error)) { + return 'Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.'; + } + if (recovery.lockReceived && recovery.failedChunk) { + return `Your deposit is safe: the InstantSend lock arrived, but the page could not load the${chunkLabel(recovery)} component needed to submit it to Platform (${chunkFailureCause(recovery)}). Retry once that is resolved — it reuses the same lock and cannot spend your deposit twice.`; + } + if (recovery.lockReceived) { + return 'Your deposit is safe: the InstantSend lock arrived, but the Platform step failed. Retrying reuses the same lock and cannot spend your deposit twice.'; + } + return 'Retrying reuses the same asset lock proof and cannot spend your deposit twice.'; +} + function renderErrorStep(state: BridgeState): HTMLElement { const div = document.createElement('div'); div.className = 'error-step'; @@ -1880,6 +1946,7 @@ function renderErrorStep(state: BridgeState): HTMLElement { // Build a concise technical summary from the diagnostic object const techLines: string[] = []; if (diag.errorStep) techLines.push(`Step: ${diag.errorStep}`); + if (diag.failedChunk) techLines.push(`Failed to load: ${diag.failedChunk}`); if (diag.depositAddress) techLines.push(`Deposit: ${diag.depositAddress}`); if (diag.txid) techLines.push(`TxID: ${diag.txid}`); if (diag.identityId) techLines.push(`Identity: ${diag.identityId}`); @@ -1895,29 +1962,36 @@ function renderErrorStep(state: BridgeState): HTMLElement { ` : ''; + const recovery = getErrorRecovery(state); + + // Failed while preparing, before any deposit address: nothing is at risk. + const reloadHtml = recovery.reloadSafe + ? ` +
+

The page failed to load a required component${escapeHtml(chunkLabel(recovery))} (${escapeHtml(chunkFailureCause(recovery))}). No funds have been sent. Reload the page to try again.

+ +
+ ` + : ''; + const chainlockFallbackHtml = state.chainlockFallbackAvailable ? `
-

InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead.

+

${escapeHtml(chainlockFallbackHint(state, recovery))}

` : ''; - // An identity registration that was submitted but not confirmed can be - // resubmitted safely with the same asset lock proof. - const retryRegistrationHtml = - state.mode === 'create' && - isIdentityRegistrationUnconfirmedError(state.error) && - state.assetLockProof && - state.assetLockKeyPair - ? ` + // The DOM id predates top-up/send retries; kept for main.ts and the tests. + const retrySubmissionHtml = recovery.canRetrySubmission + ? `
-

Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.

- +

${escapeHtml(retrySubmissionHint(state, recovery))}

+
` - : ''; + : ''; // Once an asset lock key exists, funds may be in flight: keep the // recovery backup one click away on every error screen. @@ -1938,7 +2012,8 @@ function renderErrorStep(state: BridgeState): HTMLElement { ${failedStepHtml}

${escapeHtml(errorMessage)}

${techDetailsHtml} - ${retryRegistrationHtml} + ${reloadHtml} + ${retrySubmissionHtml} ${chainlockFallbackHtml} ${keyBackupHtml}
@@ -2059,9 +2134,16 @@ export function downloadKeyBackup(state: BridgeState): void { a.href = url; a.download = filename; document.body.appendChild(a); + // Only iOS browsers (all WebKit) ask before downloading, and block the + // page's loads while they ask; elsewhere a chunk failure is not the prompt. + if (getCurrentMobilePlatform() === 'ios') noteDownloadStarted(); a.click(); document.body.removeChild(a); - URL.revokeObjectURL(url); + // iOS Safari reads the blob only when the user answers its download prompt, + // which can be minutes later; revoking now would make that download fail. + // 5 min bounds how long the backup stays in memory; a later answer gets + // nothing, and the error screens keep a Download Key Backup button. + setTimeout(() => URL.revokeObjectURL(url), 5 * 60_000); } // ============================================================================ diff --git a/src/ui/state.error-recovery.test.ts b/src/ui/state.error-recovery.test.ts new file mode 100644 index 0000000..358d633 --- /dev/null +++ b/src/ui/state.error-recovery.test.ts @@ -0,0 +1,152 @@ +import { describe, it, expect } from 'vitest'; + +import { ErrorCodes, createInitialState, getErrorRecovery, setError } from './state.js'; +import type { AssetLockProofData, BridgeState } from '../types.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; +import { + AssetLockConsumedElsewhereError, + IdentityRegistrationUnconfirmedError, +} from '../platform/identity-confirm.js'; + +const importFailure = () => new ChunkLoadError('evo-sdk', 3, new TypeError('Importing a module script failed.')); +/** What the SDK throws when the broadcast never reached Platform (seen in WebKit). */ +const transportFailure = () => new Error("Failed to create identity: Dapi client error: transport error: grpc error: code: 'Internal error', message: \"Failed to call gRPC service: JS API error: TypeError: Load failed\""); + +const instantProof: AssetLockProofData = { + type: 'instant', + transactionBytes: new Uint8Array([1]), + instantLockBytes: new Uint8Array([2]), + outputIndex: 0, +}; + +/** Create flow right after the InstantSend lock arrived (as setInstantLockReceived leaves it). */ +function lockReceived(overrides: Partial = {}): BridgeState { + return { + ...createInitialState('testnet'), + step: 'registering_identity', + depositAddress: 'yAddr', + txid: 'ab'.repeat(32), + signedTxBytes: new Uint8Array([0]), + assetLockKeyPair: { privateKey: new Uint8Array(32), publicKey: new Uint8Array(33) }, + instantLockBytes: new Uint8Array([2]), + assetLockProof: instantProof, + ...overrides, + }; +} + +describe('getErrorRecovery after the InstantSend lock arrived', () => { + it('reports the lock as received and offers both a retry and the chain lock proof when the SDK chunk failed', () => { + const errored = setError(lockReceived(), importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.REGISTER); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toEqual({ + lockReceived: true, + canRetrySubmission: true, + reloadSafe: false, + failedChunk: 'evo-sdk', + downloadPromptSuspected: false, + }); + }); + + it('offers a retry for every funding mode (top-up, send to address) with the proof in state', () => { + for (const [mode, step, code] of [ + ['topup', 'topping_up', ErrorCodes.TOPUP], + ['send_to_address', 'sending_to_address', ErrorCodes.SEND_ADDRESS], + ] as const) { + const errored = setError(lockReceived({ mode, step }), transportFailure()); + expect(errored.errorCode).toBe(code); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: true, canRetrySubmission: true }); + } + }); + + it('keeps offering a retry for an unconfirmed registration', () => { + const errored = setError(lockReceived(), new IdentityRegistrationUnconfirmedError('someId')); + expect(getErrorRecovery(errored).canRetrySubmission).toBe(true); + expect(errored.chainlockFallbackAvailable).toBe(false); + }); + + it('offers no retry once the asset lock was consumed elsewhere', () => { + const errored = setError(lockReceived(), new AssetLockConsumedElsewhereError('someId')); + expect(getErrorRecovery(errored).canRetrySubmission).toBe(false); + }); + + it('offers no retry without the proof or the asset lock key', () => { + expect(getErrorRecovery(setError(lockReceived({ assetLockProof: undefined }), importFailure()))) + .toMatchObject({ lockReceived: false, canRetrySubmission: false }); + expect(getErrorRecovery(setError(lockReceived({ assetLockKeyPair: undefined }), importFailure()))) + .toMatchObject({ lockReceived: true, canRetrySubmission: false }); + }); + + it('does not call a chain proof an InstantSend lock', () => { + const chainProof: AssetLockProofData = { type: 'chain', coreChainLockedHeight: 10, txid: 'ab'.repeat(32), vout: 0 }; + const errored = setError(lockReceived({ assetLockProof: chainProof }), transportFailure()); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: false, canRetrySubmission: true }); + }); + + it('offers no retry when Platform rejected the transition (same proof, same verdict), only the chain lock proof', () => { + const errored = setError(lockReceived(), new Error('Failed to create identity: invalid instant asset lock proof signature')); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: true, canRetrySubmission: false }); + }); +}); + +describe('which submission failures offer a retry', () => { + const offersRetry = (error: Error) => getErrorRecovery(setError(lockReceived(), error)).canRetrySubmission; + + it('retries a client-side timeout (PlatformOperationTimeoutError)', () => { + const timeout = new Error('Timed out while broadcasting identity create state transition'); + timeout.name = 'PlatformOperationTimeoutError'; + expect(offersRetry(timeout)).toBe(true); + expect(offersRetry(new Error('Failed to create identity: Timed out while waiting for the result'))).toBe(true); + }); + + it('retries when the SDK has no node left to use, and a devnet polling window that ran out', () => { + expect(offersRetry(new Error('Dapi client error: no available addresses to use'))).toBe(true); + expect(offersRetry(new Error('Identity 9Wz7 did not appear on Platform within 60s polling window. Check later.'))).toBe(true); + expect(offersRetry(new Error("grpc error: code: 'Unavailable', message: \"connection reset\""))).toBe(true); + }); + + it('does not retry Platform rejections that merely contain status-code digits or the word timeout', () => { + expect(offersRetry(new Error('Failed to create identity: insufficient asset lock balance 5030000 < 5029000'))).toBe(false); + expect(offersRetry(new Error('Invalid identity public key: signature verification timeout field 429'))).toBe(false); + expect(offersRetry(new Error('Failed to create identity: invalid instant asset lock proof signature'))).toBe(false); + }); +}); + +describe('getErrorRecovery for a missing InstantSend lock', () => { + it('is not a received lock and has nothing to retry', () => { + const waiting: BridgeState = { ...lockReceived(), step: 'waiting_islock', assetLockProof: undefined, instantLockBytes: undefined }; + const errored = setError(waiting, new Error('timeout')); + expect(errored.errorCode).toBe(ErrorCodes.ISLOCK); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: false, canRetrySubmission: false, reloadSafe: false }); + }); +}); + +describe('component load failure while preparing a funding flow', () => { + it('gets its own code and is safe to reload before any deposit address exists', () => { + const preparing: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys' }; + const errored = setError(preparing, importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.COMPONENT_LOAD); + expect(errored.chainlockFallbackAvailable).toBe(false); + expect(getErrorRecovery(errored)).toEqual({ + lockReceived: false, + canRetrySubmission: false, + reloadSafe: true, + failedChunk: 'evo-sdk', + downloadPromptSuspected: false, + }); + }); + + it('keeps the key generation code for other errors in that step', () => { + const preparing: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys' }; + expect(setError(preparing, new Error('boom')).errorCode).toBe(ErrorCodes.KEY_GEN); + }); + + it('is never "safe to reload" once a deposit address was shown', () => { + const shown: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys', depositAddress: 'yAddr' }; + const errored = setError(shown, importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.KEY_GEN); + expect(getErrorRecovery(errored).reloadSafe).toBe(false); + }); +}); diff --git a/src/ui/state.ts b/src/ui/state.ts index 082b1d1..1b3c4f8 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -38,6 +38,7 @@ import { isIdentityRegistrationUnconfirmedError, type IdentityRegistrationUnconfirmedError, } from '../platform/identity-confirm.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; import { shouldRecommendMobileApp } from './mobile-app.js'; /** @@ -63,6 +64,7 @@ export const ErrorCodes = { CHAINLOCK: 'ERR-1014', WITHDRAW: 'ERR-1015', USERNAME_TRANSFER: 'ERR-1016', + COMPONENT_LOAD: 'ERR-1017', } as const; /** Human-readable labels for error codes */ @@ -84,6 +86,7 @@ export const ErrorCodeLabels: Record = { [ErrorCodes.CHAINLOCK]: 'Chain lock fallback failed', [ErrorCodes.WITHDRAW]: 'Credit withdrawal failed', [ErrorCodes.USERNAME_TRANSFER]: 'Username transfer failed', + [ErrorCodes.COMPONENT_LOAD]: 'A required component failed to load', }; /** Map a processing step to its error code */ @@ -596,8 +599,90 @@ function computeChainlockFallbackAvailable( return false; } +/** Error codes of the Platform submission that spends the asset lock. */ +const SUBMISSION_ERROR_CODES = new Set([ + ErrorCodes.REGISTER, + ErrorCodes.TOPUP, + ErrorCodes.SEND_ADDRESS, +]); + +/** + * A chunk that failed while a funding flow was still preparing (before its + * deposit address) gets its own code: nothing is at risk and reloading is safe. + */ +function resolveErrorCode(state: BridgeState, error: Error): string { + if (error instanceof ChunkLoadError && state.step === 'generating_keys' && !state.depositAddress) { + return ErrorCodes.COMPONENT_LOAD; + } + return StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; +} + +/** + * Failures where the submission did not reach Platform or its outcome is + * unknown. Deliberately narrow (no bare status codes or "timeout" substrings, + * which also occur in amounts, IDs and Platform's own rejection texts). + * - "Dapi client error: transport error: … TypeError: Failed to fetch" + * (Chromium) / "… Load failed" (WebKit): the request never got through + * - "no available addresses": the SDK banned every node after failures + * - gRPC "Unavailable" / "Deadline exceeded" + * - "Timed out while …" (PlatformOperationTimeoutError, client.ts) + * - "… did not appear on Platform within 60s polling window" (non-trusted + * devnets, identity.ts) + */ +const TRANSIENT_SUBMISSION_MESSAGE = + /failed to fetch|load failed|networkerror|no available addresses|\bunavailable\b|deadline exceeded|\btimed out while\b|did not appear on platform within/i; + +/** + * Whether resubmitting the same proof can help. A rejection by Platform is + * not retried: resubmitting the same transition gets the same verdict. + */ +function isTransientSubmissionError(error: Error | undefined): boolean { + if (!error) return false; + if (error instanceof ChunkLoadError || isIdentityRegistrationUnconfirmedError(error)) return true; + if (error.name === 'PlatformOperationTimeoutError') return true; + return TRANSIENT_SUBMISSION_MESSAGE.test(error.message); +} + +export interface ErrorRecovery { + /** + * The Platform submission failed while the InstantSend lock had arrived + * (its proof is in state): the error screen must not claim InstantSend failed. + */ + lockReceived: boolean; + /** The submission can be resubmitted with the asset lock proof in state. */ + canRetrySubmission: boolean; + /** Failed before any deposit address was shown, so reloading the page is safe. */ + reloadSafe: boolean; + /** Name of the lazily loaded chunk that could not be downloaded, if that was the cause. */ + failedChunk?: string; + /** That chunk failed right after a file download started (a download prompt may have blocked it). */ + downloadPromptSuspected: boolean; +} + +/** What the error screen can offer for the current error. */ +export function getErrorRecovery(state: BridgeState): ErrorRecovery { + const submissionFailed = SUBMISSION_ERROR_CODES.has(state.errorCode); + return { + lockReceived: submissionFailed && state.assetLockProof?.type === 'instant', + // Resubmitting is safe: the asset lock can be consumed only once and the + // identity ID is derived from it. Once Platform has consumed it elsewhere + // there is nothing left to retry. + canRetrySubmission: + submissionFailed && + !!state.assetLockProof && + !!state.assetLockKeyPair && + !isAssetLockConsumedElsewhereError(state.error) && + isTransientSubmissionError(state.error), + // resolveErrorCode already implies no deposit address; re-checked because + // a wrong "safe to reload" could lose track of funds in flight. + reloadSafe: state.errorCode === ErrorCodes.COMPONENT_LOAD && !state.depositAddress && !state.txid, + failedChunk: state.error instanceof ChunkLoadError ? state.error.chunk : undefined, + downloadPromptSuspected: state.error instanceof ChunkLoadError && state.error.downloadPromptSuspected, + }; +} + export function setError(state: BridgeState, error: Error, errorCode?: string): BridgeState { - const resolvedCode = errorCode ?? StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; + const resolvedCode = errorCode ?? resolveErrorCode(state, error); const unconfirmed = isIdentityRegistrationUnconfirmedError(error); return { ...state, @@ -607,9 +692,8 @@ export function setError(state: BridgeState, error: Error, errorCode?: string): errorStep: state.step, // Both errors mean the deposit's asset lock already reached Platform, so // a chain-lock proof for the same asset lock can't change the outcome - // (and the fallback's "InstantSend didn't go through" hint would be - // wrong). Unconfirmed → Retry Registration; consumed elsewhere → nothing - // to retry. + // (and offering it would suggest the lock was the problem). Unconfirmed → + // Retry Registration; consumed elsewhere → nothing to retry. chainlockFallbackAvailable: !unconfirmed && !isAssetLockConsumedElsewhereError(error) && diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe..a8d8167 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,7 @@ /// + +/** Built URL of a lazily imported chunk; null in dev and tests. See src/config/vite-chunk-url.ts. */ +declare module 'virtual:chunk-url:*' { + const url: string | null; + export default url; +} diff --git a/vite.config.ts b/vite.config.ts index 01aff52..1ac9495 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,10 +1,12 @@ import { defineConfig } from 'vite'; import { nodePolyfills } from 'vite-plugin-node-polyfills'; import { shouldPreloadDashChunk } from './src/config/vite-preload.js'; +import { chunkUrlPlugin } from './src/config/vite-chunk-url.js'; export default defineConfig({ base: process.env.BASE_PATH || '/', plugins: [ + chunkUrlPlugin(), nodePolyfills({ include: ['util', 'stream', 'events', 'buffer', 'process', 'path', 'os', 'string_decoder', 'crypto'], globals: { @@ -23,6 +25,17 @@ export default defineConfig({ commonjsOptions: { transformMixedEsModules: true, }, + rollupOptions: { + output: { + // Merge tiny shared chunks (the 0.24 kB commonjs helper the islock and + // evo-sdk chunks share) into a chunk that is always loaded with them: + // the entry. A lazy chunk then depends only on the already loaded + // entry. WebKit keeps a failed fetch of a static dependency across + // reloads, so a dropped download of such a shared chunk would make + // the lazy chunks that import it unloadable until the tab is closed. + experimentalMinChunkSize: 1024, + }, + }, }, optimizeDeps: { esbuildOptions: { diff --git a/vitest.config.ts b/vitest.config.ts index 9fa19e1..9474403 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,6 +1,8 @@ import { defineConfig } from 'vitest/config'; +import { chunkUrlPlugin } from './src/config/vite-chunk-url.js'; export default defineConfig({ + plugins: [chunkUrlPlugin()], test: { exclude: [ 'e2e/**',