// Copyright 2026 The Lynx Authors. All rights reserved. // Licensed under the Apache License Version 2.0 that can be found in the // LICENSE file in the root directory of this source tree. import assert from 'node:assert/strict'; import { afterEach, beforeEach, rstest, test } from '@rstest/core'; let initializeIslandBackground; let mountIsland; let requestIslandBundle; function loadRuntime() { rstest.resetModules(); return import('@lynx-js/islands'); } const restorers = []; afterEach(() => { for (const restore of restorers.splice(0).reverse()) restore(); }); function globals(values) { for (const [key, value] of Object.entries(values)) { const previous = Object.getOwnPropertyDescriptor(globalThis, key); Object.defineProperty(globalThis, key, { configurable: true, value }); restorers.push(() => { if (previous) Object.defineProperty(globalThis, key, previous); else delete globalThis[key]; }); } } beforeEach(async () => { ({ initializeIslandBackground, mountIsland, requestIslandBundle } = await loadRuntime()); const page = { id: 0 }; globals({ __GetPageElement: () => page, __GetElementUniqueID: element => element.id, __QuerySelector: assert.fail, }); }); test.each([undefined, 'async'])( '%s loading never waits for a pending bundle', mode => { const wait = rstest.fn(() => ({ code: 0, url: 'ready' })); globals({ lynx: { fetchBundle: () => ({ then: () => undefined, wait }), }, }); assert.equal(requestIslandBundle('pending', mode), undefined); assert.equal(wait.mock.calls.length, 0); }, ); test('sync loading returns the wait result and caches it for both modes', async () => { let finish; const response = { then(resolve) { finish = resolve; }, wait: rstest.fn(function(timeout) { assert.equal(this, response); assert.equal(timeout, 5); return { code: 0, url: 'resolved' }; }), }; const fetchBundle = rstest.fn(() => response); const loadScript = rstest.fn(); globals({ lynx: { fetchBundle, loadScript } }); assert.equal(requestIslandBundle('source', 'sync'), 'resolved'); assert.equal(requestIslandBundle('source'), 'resolved'); assert.equal(requestIslandBundle('source', 'sync'), 'resolved'); assert.equal(await initializeIslandBackground('source', 'card'), 'resolved'); // A delayed callback must not replace the already resolved wait result. finish({ code: 1, error_msg: 'late callback' }); assert.equal(requestIslandBundle('source', 'sync'), 'resolved'); assert.equal(fetchBundle.mock.calls.length, 1); assert.equal(response.wait.mock.calls.length, 1); assert.deepEqual(loadScript.mock.calls, [['card', { bundleName: 'resolved', }]]); }); test('a sync consumer can wait on an existing async request and resolve its subscribers', async () => { const wait = rstest.fn(() => ({ code: 0, url: 'shared' })); const fetchBundle = rstest.fn(() => ({ then: () => undefined, wait })); const loadScript = rstest.fn(); globals({ lynx: { fetchBundle, loadScript } }); assert.equal(requestIslandBundle('source'), undefined); const first = initializeIslandBackground('source', 'card'); const second = initializeIslandBackground('source', 'card'); assert.equal(requestIslandBundle('source', 'sync'), 'shared'); assert.deepEqual(await Promise.all([first, second]), ['shared', 'shared']); assert.equal(fetchBundle.mock.calls.length, 1); assert.equal(wait.mock.calls.length, 1); assert.equal(loadScript.mock.calls.length, 1); }); test('sync loading skips wait when the native callback completes immediately', () => { const wait = rstest.fn(); globals({ lynx: { fetchBundle: () => ({ then(resolve) { resolve({ code: 0, url: 'cached' }); }, wait, }), }, }); assert.equal(requestIslandBundle('cached', 'sync'), 'cached'); assert.equal(wait.mock.calls.length, 0); }); test('the explicit mode controls waiting and leaves URL queries unchanged', () => { const wait = rstest.fn(() => ({ code: 0, url: 'ready' })); const fetchBundle = rstest.fn(() => ({ then: () => undefined, wait })); globals({ lynx: { fetchBundle } }); assert.equal(requestIslandBundle('bundle?sync=true', 'async'), undefined); assert.equal(wait.mock.calls.length, 0); assert.equal(requestIslandBundle('bundle?sync=false', 'sync'), 'ready'); assert.equal(wait.mock.calls.length, 1); assert.deepEqual(fetchBundle.mock.calls, [ ['bundle?sync=true', {}], ['bundle?sync=false', {}], ]); }); test('a native callback fired during wait resolves shared consumers only once', async () => { let finish; const fetchBundle = rstest.fn(() => ({ then(resolve) { finish = resolve; }, wait() { const info = { code: 0, url: 'ready-during-wait' }; finish(info); return info; }, })); const loadScript = rstest.fn(); globals({ lynx: { fetchBundle, loadScript } }); const background = initializeIslandBackground('pending', 'card'); assert.equal(requestIslandBundle('pending', 'sync'), 'ready-during-wait'); assert.equal(await background, 'ready-during-wait'); assert.equal(fetchBundle.mock.calls.length, 1); assert.equal(loadScript.mock.calls.length, 1); }); test.each([ ['timeout', () => ({ code: 1, error_msg: 'timeout' })], ['missing result', () => undefined], ['missing URL', () => ({ code: 0 })], ['exception', () => { throw Error('wait failed'); }], ])( 'a sync %s keeps the async request pending without repeated blocking', async (_kind, result) => { let finish; const wait = rstest.fn(result); const fetchBundle = rstest.fn(() => ({ then(resolve) { finish = resolve; }, wait, })); globals({ lynx: { fetchBundle, loadScript: () => undefined } }); assert.equal(requestIslandBundle('pending', 'sync'), undefined); const initialized = initializeIslandBackground('pending', 'card'); assert.equal(requestIslandBundle('pending', 'sync'), undefined); assert.equal(requestIslandBundle('pending'), undefined); assert.equal(wait.mock.calls.length, 1); assert.equal(fetchBundle.mock.calls.length, 1); finish({ code: 0, url: 'eventually-ready' }); assert.equal(await initialized, 'eventually-ready'); assert.equal(requestIslandBundle('pending', 'sync'), 'eventually-ready'); }, ); test('an async failure after a sync timeout reaches subscribers and remains cached', async () => { let finish; const wait = rstest.fn(() => ({ code: 1, error_msg: 'timeout' })); const fetchBundle = rstest.fn(() => ({ then(resolve) { finish = resolve; }, wait, })); globals({ lynx: { fetchBundle } }); requestIslandBundle('failed', 'sync'); const failed = initializeIslandBackground('failed', 'card'); const rejection = assert.rejects(failed, /offline/); finish({ code: 1, error_msg: 'offline' }); await rejection; assert.equal(requestIslandBundle('failed', 'sync'), undefined); await assert.rejects(initializeIslandBackground('failed', 'card'), /offline/); assert.equal(fetchBundle.mock.calls.length, 1); assert.equal(wait.mock.calls.length, 1); }); test('sync loading on Web falls back to its Promise without a wait method', async () => { const fetchBundle = rstest.fn(() => Promise.resolve({ code: 0, url: 'web-ready' }) ); globals({ lynx: { fetchBundle, loadScript: () => undefined }, SystemInfo: { platform: 'web' }, }); assert.equal(requestIslandBundle('web', 'sync'), undefined); assert.equal(await initializeIslandBackground('web', 'card'), 'web-ready'); assert.equal(requestIslandBundle('web', 'sync'), 'web-ready'); assert.equal(fetchBundle.mock.calls.length, 1); }); test('a first-frame request keeps a failed download cached', () => { let finish; let fetches = 0; globals({ lynx: { fetchBundle() { fetches++; return { then(resolve) { finish = resolve; }, }; }, }, }); assert.equal(requestIslandBundle('first-frame'), undefined); assert.equal(requestIslandBundle('first-frame'), undefined); assert.equal(fetches, 1); finish({ code: 1, error_msg: 'offline' }); assert.equal(requestIslandBundle('first-frame'), undefined); assert.equal(fetches, 1); }); test('concurrent consumers share the fetch and evaluate each resolved background section once', async () => { const fetches = []; const sections = []; let finish; globals({ lynx: { fetchBundle(entry) { fetches.push(entry); return { then(resolve) { finish = resolve; }, }; }, getCustomSectionSync(key, bundle) { assert.deepEqual([key, bundle], ['__sectionMap', 'resolved']); return { math: 'math.123' }; }, loadScript(name, { bundleName }) { sections.push([name, bundleName]); return { name }; }, }, }); assert.equal(requestIslandBundle('requested'), undefined); let active = true; const superseded = initializeIslandBackground( 'requested', 'old', () => active, ); const first = initializeIslandBackground('requested', 'math'); const second = initializeIslandBackground('requested', 'math'); const third = initializeIslandBackground('requested', 'card'); active = false; finish({ code: 0, url: 'resolved' }); assert.equal(await superseded, undefined); assert.equal(await first, await second); assert.equal(await third, 'resolved'); assert.deepEqual(fetches, ['requested']); assert.deepEqual(sections, [['math.123', 'resolved'], ['card', 'resolved']]); }); test('a failed URL stays failed while a new URL initializes independently', async () => { let fetches = 0; let loads = 0; globals({ lynx: { fetchBundle() { return { then(resolve) { resolve( ++fetches === 1 ? { code: 1, error_msg: 'offline' } : { code: 0, url: 'retried' }, ); }, }; }, loadScript() { if (++loads === 1) throw Error('script failed'); return 42; }, }, }); await assert.rejects(initializeIslandBackground('retry', 'math'), /offline/); await assert.rejects(initializeIslandBackground('retry', 'math'), /offline/); await assert.rejects( initializeIslandBackground('other', 'math'), /script failed/, ); assert.equal(await initializeIslandBackground('other', 'math'), 'retried'); assert.equal(fetches, 2); assert.equal(loads, 2); }); test('two mounts share script and CSS and own independent renderers', () => { const calls = []; let count = 0; globals({ lynx: { loadScript: (name, { bundleName }) => { calls.push([name, bundleName]); return { create() { const id = ++count; return { render({ container }, props) { calls.push([id, container, props]); }, update(props) { calls.push([id, props]); }, dispose() { calls.push([id, 'dispose']); }, }; }, }; }, }, __LoadStyleSheet(name, url) { calls.push([name, url]); return 0; }, __AdoptStyleSheet(sheet) { calls.push(['adopt', sheet]); }, }); const one = { id: 1 }; const two = { id: 2 }; const first = mountIsland('resource', 'math', one, 'A'); const second = mountIsland('resource', 'math', two, 'B'); first.update('C'); first.dispose(); second.update('D'); assert.deepEqual(calls, [ ['math__main-thread', 'resource'], ['math:CSS', 'resource'], ['adopt', 0], [1, one, 'A'], [2, two, 'B'], [1, 'C'], [1, 'dispose'], [2, 'D'], ]); }); test('an island without CSS can mount, and a partially mounted renderer is disposed on error', () => { let disposed = false; globals({ lynx: { loadScript: () => ({ create: () => ({ render() { throw Error('render failed'); }, dispose() { disposed = true; }, }), }), }, __LoadStyleSheet: () => null, __AdoptStyleSheet: assert.fail, }); assert.throws( () => mountIsland('no-css', 'card', {}, {}), /render failed/, ); assert.equal(disposed, true); }); test.each(['async', 'sync'])( 'a rejected Web %s fetch reaches pending and later callers with the original error', async mode => { let attempts = 0; const failure = new Error('RPC disconnected'); globals({ lynx: { fetchBundle() { attempts++; if (attempts === 1) return Promise.reject(failure); if (attempts === 2) { return Promise.resolve({ code: -1, errorMsg: 'Web timeout' }); } return Promise.resolve({ code: 0, url: 'ready' }); }, loadScript: () => undefined, }, }); requestIslandBundle('web', mode); await Promise.all([ assert.rejects(initializeIslandBackground('web', 'one'), failure), assert.rejects(initializeIslandBackground('web', 'two'), failure), ]); await assert.rejects(initializeIslandBackground('web', 'two'), failure); await assert.rejects( initializeIslandBackground('timeout', 'two'), /Web timeout/, ); await assert.rejects( initializeIslandBackground('timeout', 'two'), /Web timeout/, ); assert.equal(await initializeIslandBackground('fresh', 'two'), 'ready'); assert.equal(attempts, 3); }, ); test('re-evaluating the modules resets bundle, section and stylesheet caches', async () => { for (let i = 0; i < 2; i++) { const runtime = await loadRuntime(); const fetches = []; const loads = []; globals({ lynx: { fetchBundle: url => { fetches.push(url); return Promise.resolve({ code: 0, url }); }, loadScript(name, { bundleName }) { loads.push([bundleName, name]); return { create: () => ({ render: () => undefined }) }; }, }, __LoadStyleSheet: (name, url) => [url, name], __AdoptStyleSheet: sheet => loads.push(sheet), }); for (const [url, name] of [['x:y', 'z'], ['x', 'y:z'], ['x:y', 'z']]) { await runtime.initializeIslandBackground(url, name); runtime.mountIsland(url, name, {}, {}); } assert.deepEqual(fetches, ['x:y', 'x']); assert.deepEqual(loads, [ ['x:y', 'z'], ['x:y', 'z__main-thread'], ['x:y', 'z:CSS'], ['x', 'y:z'], ['x', 'y:z__main-thread'], ['x', 'y:z:CSS'], ]); } }); test('without stylesheet APIs a renderer can mount and rollback preserves its original error', () => { const errors = []; globals({ lynx: { loadScript: () => ({ create: () => ({ render(_context, fail) { if (fail) throw Error('render failed'); }, dispose() { throw Error('cleanup failed'); }, }), }), reportError: error => errors.push(String(error)), }, __LoadStyleSheet: undefined, __AdoptStyleSheet: undefined, }); mountIsland('web-card', 'card', {}, false); assert.throws( () => mountIsland('web-card', 'card', {}, true), /render failed/, ); assert.deepEqual(errors, ['Error: cleanup failed']); }); test('mount context uses the current page and each resolved container without caching handles', () => { const firstPage = { id: 0 }; const nextPage = { id: 9 }; const firstContainer = { owner: 'first' }; const nextContainer = { owner: 'next' }; let page = firstPage; let loads = 0; const contexts = []; globals({ lynx: { loadScript() { loads++; return { create: () => ({ render(...args) { contexts.push(args); }, }), }; }, }, __GetPageElement: () => page, __GetElementUniqueID: element => element.id, __LoadStyleSheet: undefined, __AdoptStyleSheet: undefined, }); mountIsland('context', 'card', firstContainer, { title: 'First' }); page = nextPage; mountIsland('context', 'card', nextContainer, { title: 'Next' }); assert.deepEqual(contexts, [ [{ page: firstPage, pageId: 0, container: firstContainer, }, { title: 'First' }], [{ page: nextPage, pageId: 9, container: nextContainer, }, { title: 'Next' }], ]); assert.equal(loads, 1); }); test('a missing mount page or container disposes the renderer before its render method runs', () => { for (const missing of ['page', 'container']) { let renders = 0; let disposals = 0; const page = { id: 0 }; globals({ lynx: { loadScript: () => ({ create: () => ({ render() { renders++; }, dispose() { disposals++; }, }), }), }, __GetPageElement: () => missing === 'page' ? undefined : page, __LoadStyleSheet: undefined, __AdoptStyleSheet: undefined, }); assert.throws( () => mountIsland( 'missing-' + missing, 'card', missing === 'container' ? null : {}, {}, ), missing === 'page' ? /without a host page/ : /without a container/, ); assert.equal(renders, 0); assert.equal(disposals, 1); } });