import { test } from 'node:test'; import { strict as assert } from 'node:assert'; import { readFileSync, readdirSync } from 'node:fs'; import { transpileModule, ModuleKind, ScriptTarget } from 'typescript'; import { GuestLoginPresenter } from '../assets/login/scripts/GuestLoginPresenter'; import { GameRepository } from '../assets/orchard/scripts/GameRepository'; import { GameSession } from '../assets/orchard/scripts/GameSession'; import { StartupProgress } from '../assets/startup/scripts/StartupProgress'; test('waiting progress stays monotonic and below completion, even after long waits', () => { const progress = new StartupProgress(); progress.begin(); let previous = progress.value; for (let i = 0; i < 6000; i++) { const value = progress.tick(.1); assert.ok(value >= previous && value <= .9); previous = value; } assert.equal(progress.phase, 'loading'); const before = progress.value; progress.tick(NaN); progress.tick(-1); progress.tick(Infinity); assert.equal(progress.value, before); }); test('only real completion reaches 100%; retry resets progress and stale finish is ignored', () => { const progress = new StartupProgress(); progress.finish(); assert.equal(progress.phase, 'idle'); progress.begin(); progress.tick(.1); progress.finish(); const first = progress.tick(.1); progress.finish(); assert.ok(first < 1); progress.tick(.1); progress.tick(.1); assert.equal(progress.phase, 'complete'); assert.equal(progress.value, 1); progress.begin(); assert.equal(progress.phase, 'loading'); assert.equal(progress.value, .03); progress.reset(); progress.finish(); progress.tick(.1); assert.equal(progress.phase, 'idle'); assert.equal(progress.value, 0); }); // 场景必须由领域工具保存;测试只读取布局和资源引用。 / Domain tools author the scene; tests only inspect its saved layout and references. type Entry = Record; const scene: Entry[] = JSON.parse(readFileSync('assets/Welcome.scene', 'utf8')); const node = (name: string): Entry => scene.find(item => item.__type__ === 'cc.Node' && item._name === name)!; const components = (name: string): Entry[] => node(name)._components.map((ref: Entry) => scene[ref.__id__]); const component = (name: string, type: string): Entry => components(name).find(item => item.__type__ === type)!; test('loading has independent editable labels and renamed frame/fill resources with preserved caps', () => { assert.ok(node('PreparationPanel')._children.length >= 5); for (const [name, text] of [['PreparationTitle', 'LOADING...'], ['PreparationPercent', '70%'], ['PreparationCaption', 'Getting things ready']]) { assert.equal(component(name, 'cc.Label')._string, text); } assert.equal(component('PreparationFrame', 'cc.UITransform')._contentSize.width, 973); assert.equal(component('PreparationFrame', 'cc.UITransform')._contentSize.height, 168); assert.equal(node('PreparationFrame')._lpos.y, -576); assert.equal(component('PreparationFill', 'cc.UITransform')._anchorPoint.x, 0); assert.equal(component('PreparationFill', 'cc.UITransform')._contentSize.width, 906 * .7); assert.equal(component('PreparationFill', 'cc.Sprite')._type, 1); for (const [name, file] of [['PreparationFrame', 'prep-meter-frame'], ['PreparationFill', 'prep-meter-fill']]) { const meta = JSON.parse(readFileSync(`assets/startup/visuals/${file}.png.meta`, 'utf8')); assert.equal(component(name, 'cc.Sprite')._spriteFrame.__uuid__, meta.uuid + '@f9941'); if (name === 'PreparationFill') { assert.equal(meta.subMetas.f9941.userData.borderLeft, 48); assert.equal(meta.subMetas.f9941.userData.borderRight, 48); } } assert.deepEqual(readdirSync('assets/startup/visuals').filter(file => !file.endsWith('.meta')).sort(), ['prep-meter-fill.png', 'prep-meter-frame.png']); }); test('loading binds the existing login without hiding its request-owning node', () => { const loading = components('Canvas').find(item => item.panel && item.meter)!; assert.ok(loading); assert.equal(scene[loading.panel.__id__]._name, 'PreparationPanel'); assert.equal(scene[loading.login.__id__].node.__id__, scene.indexOf(node('WelcomeComposition'))); assert.equal(scene[loading.meter.__id__].node.__id__, scene.indexOf(node('PreparationFill'))); const hidden = loading.loginControls.map((ref: Entry) => scene[ref.__id__]._name); assert.ok(hidden.includes('GuestAccess')); assert.ok(hidden.includes('PrivacyLink')); assert.ok(!hidden.includes('WelcomeComposition')); assert.ok(!hidden.includes('BrandMark')); }); // Exercise the real adapters with tiny engine ports, without importing credentials or booting a scene. function adapter(file: string, imports: Record): T { const compiled = transpileModule(readFileSync(file, 'utf8'), { compilerOptions: { module: ModuleKind.CommonJS, target: ScriptTarget.ES2020, experimentalDecorators: true }, }); const exports = {}; new Function('require', 'exports', compiled.outputText)((id: string) => { assert.ok(Object.prototype.hasOwnProperty.call(imports, id), `Unexpected adapter import: ${id}`); return imports[id]; }, exports); return exports as T; } class TestNode { active = true; isValid = true; private listeners = new Map void; target: unknown }[]>(); on(event: string, callback: (...args: any[]) => void, target: unknown): void { this.listeners.set(event, [...(this.listeners.get(event) ?? []), { callback, target }]); } off(event: string, callback: (...args: any[]) => void, target: unknown): void { this.listeners.set(event, (this.listeners.get(event) ?? []).filter(item => item.callback !== callback || item.target !== target)); } emit(event: string, ...args: unknown[]): void { for (const item of this.listeners.get(event) ?? []) item.callback.apply(item.target, args); } } function pendingScene() { let resolve!: (scene: any) => void; let reject!: (error: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } function loadingHarness() { const pending = pendingScene(); const calls = { signIn: 0, prepare: 0, load: 0, clear: 0, launch: 0 }; let sceneRequest = pending.promise; let transitionFailure: 'before' | 'after' | null = null; const loaded = { scene: { getComponentInChildren: (name: string) => name === 'OrchardView' ? { enabled: true } : null } }; class TestComponent { node = new TestNode(); enabledInHierarchy = true; isValid = true; } const engine = { _decorator: { ccclass: () => (type: unknown) => type, property: (...args: unknown[]) => args.length > 1 ? undefined : () => {} }, Component: TestComponent, Node: TestNode, Button: { EventType: { CLICK: 'click' } }, Label: class {}, Sprite: class {}, SpriteFrame: class {}, SceneAsset: class {}, UITransform: class {}, director: { runSceneImmediate: () => { calls.launch++; if (transitionFailure === 'before') throw new Error('private transition error'); loading.onDisable(); Object.assign(loading, { isValid: false }); loading.onDestroy(); if (transitionFailure === 'after') throw new Error('private transition error'); } }, }; const { GuestLoginView: Login } = adapter( 'assets/login/scripts/GuestLoginView.ts', { cc: engine, './GuestLoginPresenter': { GuestLoginPresenter }, './GuestRuntime': { createGuestLogin: () => ({ signIn: async () => { calls.signIn++; return { guestId: identity, token: 'fixture-token', expires: 1 }; } }) }, }); const runtime = { LOCK_IN_USE: 'This saved game is already open in another tab. Close it and tap the guest button to retry.', LOCK_UNAVAILABLE: 'Exclusive saved game access is unavailable on this platform. Please use a supported browser and retry.', session: null as GameSession | null, prepareExclusive: async (id: string, signal?: AbortSignal): Promise => { assert.equal(id, identity); calls.prepare++; const session = {} as GameSession; runtime.session = session; signal?.addEventListener('abort', () => runtime.clear(session), { once: true }); return session; }, loadScene: () => { calls.load++; return sceneRequest; }, clear: (expected?: GameSession) => { if (expected && runtime.session !== expected) return; runtime.session = null; calls.clear++; }, }; const { StartupLoadingView: Loading } = adapter( 'assets/startup/scripts/StartupLoadingView.ts', { cc: engine, '../../login/scripts/GuestLoginView': { GuestLoginView: Login }, '../../orchard/scripts/OrchardRuntime': { OrchardRuntime: runtime }, './StartupProgress': { StartupProgress }, }); const login = new Login(); const button = { node: new TestNode(), interactable: true, isValid: true }; const status = { node: new TestNode(), string: '' }; login.guestButton = button as unknown as NonNullable; login.statusLabel = status as unknown as NonNullable; const loading = new Loading(); const panel = new TestNode(); const percent = { string: '' }; loading.login = login; loading.panel = panel as unknown as NonNullable; loading.loginControls = [button.node, status.node] as unknown as typeof loading.loginControls; loading.meter = { node: new TestNode(), getComponent: () => ({ setContentSize: () => {} }) } as unknown as NonNullable; loading.percentage = percent as NonNullable; loading.caption = { string: '' } as NonNullable; loading.onLoad(); login.onLoad(); loading.onEnable(); return { loading, login, calls, runtime, button, status, panel, percent, pending, loaded, useScene: (request: Promise) => { sceneRequest = request; }, failTransition: (when: 'before' | 'after') => { transitionFailure = when; } }; } const identity = '0123456789abcdef0123456789abcdef'; const flush = async () => { for (let turn = 0; turn < 16; turn++) await Promise.resolve(); }; function finishLoading(view: { update(dt: number): void }): void { for (let frame = 0; frame < 8; frame++) view.update(.1); } test('authenticated state waits for the credential-free success event and scene dependencies before 100%', async () => { const h = loadingHarness(); assert.equal(h.panel.active, false); let authenticatedState = false; h.login.node.on('guest-login-state-changed', (state: { phase: string }) => { if (state.phase === 'authenticated') { authenticatedState = true; assert.equal(h.calls.prepare, 0); assert.equal(h.login.guestId, null); } }, null); h.button.node.emit('click'); h.loading.update(.1); h.loading.update(.1); const waiting = Number.parseInt(h.percent.string); await flush(); assert.equal(authenticatedState, true); assert.notEqual(h.percent.string, '100%'); assert.equal(h.login.guestId, identity); assert.equal(h.calls.prepare, 1); assert.equal(h.calls.load, 1); assert.ok(Number.parseInt(h.percent.string) >= waiting); finishLoading(h.loading); assert.equal(h.calls.launch, 0); h.pending.resolve(h.loaded); await flush(); h.loading.update(.1); h.loading.update(.1); h.loading.update(.1); assert.equal(h.percent.string, '100%'); assert.equal(h.panel.active, true); assert.equal(h.calls.launch, 0); h.loading.update(.1); assert.equal(h.calls.launch, 1); }); test('scene failure restores a usable guest button and retries preparation without authenticating again', async () => { const h = loadingHarness(); h.button.node.emit('click'); await flush(); h.pending.reject(new Error('private loader details')); await flush(); assert.equal(h.panel.active, false); assert.equal(h.status.node.active, true); assert.match(h.status.string, /tap the guest button to retry/); assert.ok(!h.status.string.includes('private')); assert.equal(h.button.interactable, true); h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); h.button.node.emit('click'); await flush(); finishLoading(h.loading); assert.equal(h.calls.signIn, 1); assert.equal(h.calls.prepare, 2); assert.equal(h.calls.launch, 1); }); test('storage failure is sanitized and the authenticated preparation can retry', async () => { const h = loadingHarness(); h.runtime.prepareExclusive = async () => { throw new Error('private storage key'); }; h.button.node.emit('click'); await flush(); assert.equal(h.calls.load, 0); assert.equal(h.panel.active, false); assert.match(h.status.string, /saved game has not been reset/); assert.ok(!h.status.string.includes('private')); h.runtime.prepareExclusive = async () => { h.calls.prepare++; return {} as GameSession; }; h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); await flush(); finishLoading(h.loading); assert.equal(h.calls.signIn, 1); assert.equal(h.calls.launch, 1); }); test('disabled or destroyed loading ignores late scenes and an enabled authenticated view can resume', async () => { for (const destroy of [false, true]) { const h = loadingHarness(); h.button.node.emit('click'); await flush(); Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable(); if (destroy) { Object.assign(h.loading, { isValid: false }); h.loading.onDestroy(); } h.pending.resolve(h.loaded); await flush(); finishLoading(h.loading); assert.equal(h.calls.launch, 0); assert.equal(h.panel.active, false); if (!destroy) { h.useScene(Promise.resolve(h.loaded)); Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush(); finishLoading(h.loading); assert.equal(h.calls.launch, 1); assert.equal(h.calls.signIn, 1); } } }); test('missing game view is recoverable and pure authentication mode keeps the existing success display', async () => { const h = loadingHarness(); h.useScene(Promise.resolve({ scene: { getComponentInChildren: () => null } })); h.button.node.emit('click'); await flush(); finishLoading(h.loading); assert.equal(h.calls.launch, 0); assert.equal(h.button.interactable, true); const pure = loadingHarness(); pure.loading.transitionToGame = false; let ready = 0; pure.loading.node.on('startup-preparation-ready', () => ready++, null); pure.button.node.emit('click'); await flush(); finishLoading(pure.loading); assert.equal(ready, 1); assert.equal(pure.calls.prepare, 0); assert.equal(pure.calls.launch, 0); assert.equal(pure.status.string, 'Signed in successfully.'); assert.equal(pure.status.node.active, true); }); test('local runtime isolates authenticated guests, refuses corrupt saves and uses all 32 random bits', () => { const values = new Map(); const storage = { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } }; const { OrchardRuntime: Runtime } = adapter( 'assets/orchard/scripts/OrchardRuntime.ts', { cc: { sys: { localStorage: storage }, assetManager: {} }, './GameRepository': { GameRepository }, './GameSession': { GameSession }, '../../login/scripts/GuestRuntime': { GUEST_SERVICE: { origin: 'https://fixture.test/', product: 'Fixture' } }, }); const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'crypto'); let bits = 0; try { Object.defineProperty(globalThis, 'crypto', { configurable: true, value: { getRandomValues: (array: Uint32Array) => { array[0] = bits; return array; }, } }); assert.throws(() => Runtime.getSession(), /Sign in to continue\./); assert.throws(() => Runtime.prepare(''), /Sign in to continue\./); assert.equal(values.size, 0); const first = Runtime.prepare(identity); assert.equal(Runtime.getSession(), first); const scope = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`; assert.deepEqual([...values.keys()], [scope]); const injected = first as unknown as { random(): number }; assert.equal(injected.random(), 0); bits = 0xffffffff; assert.equal(injected.random(), 0xffffffff / 0x100000000); assert.ok(injected.random() < 1); first.setBet(5000); Runtime.clear(); assert.throws(() => Runtime.getSession(), /Sign in to continue\./); assert.equal(Runtime.prepare(identity).state.bet, 5000); assert.equal(Runtime.prepare('fedcba9876543210fedcba9876543210').state.bet, 2000); values.set(scope, 'corrupt existing save'); assert.throws(() => Runtime.prepare(identity), /saved game has not been reset/); assert.equal(values.get(scope), 'corrupt existing save'); assert.equal(Runtime.session, null); Object.defineProperty(globalThis, 'crypto', { configurable: true, value: undefined }); assert.throws(() => Runtime.prepare(identity), /Secure game preparation is unavailable/); assert.equal(values.get(scope), 'corrupt existing save'); } finally { if (cryptoDescriptor) Object.defineProperty(globalThis, 'crypto', cryptoDescriptor); else Reflect.deleteProperty(globalThis, 'crypto'); } }); type Runtime = typeof import('../assets/orchard/scripts/OrchardRuntime').OrchardRuntime; function exclusiveHarness() { const navigatorDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator'); const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'crypto'); const values = new Map(); const held = new Map(); const reads: string[] = []; const writes: string[] = []; const requests: { name: string; options: LockOptions; deliver(): void; settled: boolean }[] = []; const runtimes: Runtime[] = []; let deferred = false; const locks = { request: (name: string, options: LockOptions, callback: (lock: Lock | null) => unknown): Promise => { return new Promise((resolve, reject) => { let delivered = false; const request = { name, options, settled: false, deliver: () => { if (delivered) return; delivered = true; const owner = {}; const available = !held.has(name); if (available) held.set(name, owner); const finish = (): void => { if (held.get(name) === owner) held.delete(name); request.settled = true; }; try { const result = callback(available ? { name, mode: 'exclusive' } : null); Promise.resolve(result).then(value => { finish(); resolve(value); }, error => { finish(); reject(error); }); } catch (error) { finish(); reject(error); } } }; requests.push(request); if (!deferred) queueMicrotask(request.deliver); }); }, }; Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks } }); Object.defineProperty(globalThis, 'crypto', { configurable: true, value: { getRandomValues: (array: Uint32Array) => { array.fill(0); return array; }, } }); const createRuntime = (): Runtime => { const { OrchardRuntime } = adapter<{ OrchardRuntime: Runtime }>('assets/orchard/scripts/OrchardRuntime.ts', { cc: { sys: { localStorage: { getItem: (key: string) => { assert.ok(held.has(key), 'storage read before exclusive acquisition'); reads.push(key); return values.get(key) ?? null; }, setItem: (key: string, value: string) => { assert.ok(held.has(key), 'storage write without exclusive ownership'); writes.push(key); values.set(key, value); }, } }, assetManager: {} }, './GameRepository': { GameRepository }, './GameSession': { GameSession }, '../../login/scripts/GuestRuntime': { GUEST_SERVICE: { origin: 'https://fixture.test/', product: 'Fixture' } }, }); runtimes.push(OrchardRuntime); return OrchardRuntime; }; return { values, held, reads, writes, requests, locks, createRuntime, defer: () => { deferred = true; }, restore: async () => { for (const runtime of runtimes) runtime.clear(); for (const request of requests) request.deliver(); await flush(); if (navigatorDescriptor) Object.defineProperty(globalThis, 'navigator', navigatorDescriptor); else Reflect.deleteProperty(globalThis, 'navigator'); if (cryptoDescriptor) Object.defineProperty(globalThis, 'crypto', cryptoDescriptor); else Reflect.deleteProperty(globalThis, 'crypto'); }, }; } async function withExclusiveHarness(action: (h: ReturnType) => Promise): Promise { const harness = exclusiveHarness(); try { await action(harness); } finally { await harness.restore(); } } test('exclusive preparation denies another tab immediately without reading or writing its save', async () => { await withExclusiveHarness(async h => { const owner = h.createRuntime(); const contender = h.createRuntime(); const session = await owner.prepareExclusive(identity); const scope = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`; assert.equal(h.requests[0].name, scope); assert.deepEqual(h.requests[0].options, { mode: 'exclusive', ifAvailable: true }); assert.equal(h.requests[0].settled, false); assert.equal(h.held.size, 1); const reads = h.reads.length; const writes = h.writes.length; await assert.rejects(contender.prepareExclusive(identity), { message: contender.LOCK_IN_USE }); assert.equal(h.reads.length, reads); assert.equal(h.writes.length, writes); assert.equal(contender.session, null); assert.equal(owner.getSession(), session); session.setBet(5000); assert.equal(h.requests[0].settled, false); owner.clear(); await flush(); assert.equal(h.requests[0].settled, true); assert.equal(h.held.size, 0); const restored = await contender.prepareExclusive(identity); assert.equal(restored.state.bet, 5000); assert.equal(restored.state.balance, 100_000); assert.equal(h.writes.length, writes + 1); }); }); test('unsupported browsers and lock service errors never touch saved data and can retry', async () => { await withExclusiveHarness(async h => { const runtime = h.createRuntime(); for (const navigator of [undefined, {}, { locks: {} }, { locks: { request: () => { throw new Error('private lock details'); } } }, { locks: { request: () => Promise.reject(new Error('private lock details')) } }]) { Object.defineProperty(globalThis, 'navigator', { configurable: true, value: navigator }); await assert.rejects(runtime.prepareExclusive(identity), { message: runtime.LOCK_UNAVAILABLE }); assert.equal(runtime.session, null); assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0); } Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: h.locks } }); await runtime.prepareExclusive(identity); assert.equal(h.writes.length, 1); }); }); test('same guest reuses its lifetime lock and rereads the stored session without granting again', async () => { await withExclusiveHarness(async h => { const runtime = h.createRuntime(); const first = await runtime.prepareExclusive(identity); first.setBet(5000); const reads = h.reads.length; const writes = h.writes.length; const next = await runtime.prepareExclusive(identity); assert.notEqual(next, first); assert.equal(next.state.bet, 5000); assert.equal(h.requests.length, 1); assert.equal(h.requests[0].settled, false); assert.ok(h.reads.length > reads); assert.equal(h.writes.length, writes); runtime.clear(first); await flush(); assert.equal(runtime.getSession(), next); assert.equal(h.requests[0].settled, false); }); }); test('switching guests releases only the old scope and invalid guests never write', async () => { await withExclusiveHarness(async h => { const runtime = h.createRuntime(); const old = await runtime.prepareExclusive(identity); old.setBet(5000); const other = await runtime.prepareExclusive('fedcba9876543210fedcba9876543210'); assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false); assert.notEqual(h.requests[0].name, h.requests[1].name); assert.equal(other.state.bet, 2000); assert.equal(h.held.size, 1); runtime.clear(old); assert.equal(runtime.getSession(), other); const writes = h.writes.length; await assert.rejects(runtime.prepareExclusive(''), /Sign in to continue\./); await flush(); assert.equal(h.writes.length, writes); assert.equal(runtime.session, null); assert.equal(h.held.size, 0); }); }); test('clear and cancellation settle a delayed acquisition without writing or clearing a newer lock', async () => { for (const cancel of ['clear', 'abort'] as const) { await withExclusiveHarness(async h => { h.defer(); const runtime = h.createRuntime(); const controller = new AbortController(); const stale = runtime.prepareExclusive(identity, controller.signal); const rejected = assert.rejects(stale, /cancelled/); assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0); if (cancel === 'clear') runtime.clear(); else controller.abort(); await rejected; const current = runtime.prepareExclusive(identity); h.requests[1].deliver(); const session = await current; h.requests[0].deliver(); await flush(); assert.equal(runtime.getSession(), session); assert.equal(h.requests[1].settled, false); assert.equal(h.writes.length, 1); assert.equal(h.held.size, 1); runtime.clear(); runtime.clear(); await flush(); assert.equal(h.held.size, 0); }); } }); test('concurrent same-guest preparation shares one request and an obsolete abort cannot release the new owner', async () => { await withExclusiveHarness(async h => { h.defer(); const runtime = h.createRuntime(); const firstController = new AbortController(); const secondController = new AbortController(); const first = runtime.prepareExclusive(identity, firstController.signal); const rejected = assert.rejects(first, /cancelled/); const second = runtime.prepareExclusive(identity, secondController.signal); firstController.abort(); assert.equal(h.requests.length, 1); h.requests[0].deliver(); const session = await second; await rejected; assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1); assert.equal(h.requests[0].settled, false); secondController.abort(); await flush(); assert.equal(runtime.session, null); assert.equal(h.held.size, 0); }); }); test('a late old-guest callback cannot prepare or release the current guest', async () => { await withExclusiveHarness(async h => { h.defer(); const runtime = h.createRuntime(); const stale = runtime.prepareExclusive(identity); const rejected = assert.rejects(stale, /cancelled/); const current = runtime.prepareExclusive('fedcba9876543210fedcba9876543210'); await rejected; h.requests[1].deliver(); const session = await current; h.requests[0].deliver(); await flush(); assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1); assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false); }); }); test('cancellation between lock acquisition and restoration never reads or writes the old session', async () => { await withExclusiveHarness(async h => { h.defer(); const runtime = h.createRuntime(); const controller = new AbortController(); const stale = runtime.prepareExclusive(identity, controller.signal); const rejected = assert.rejects(stale, /cancelled/); h.requests[0].deliver(); controller.abort(); assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0); const current = runtime.prepareExclusive('fedcba9876543210fedcba9876543210'); h.requests[1].deliver(); const session = await current; await rejected; await flush(); assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1); assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false); }); }); test('cancelled callers and corrupt preparation never retain a lock or overwrite data', async () => { await withExclusiveHarness(async h => { const runtime = h.createRuntime(); const controller = new AbortController(); controller.abort(); await assert.rejects(runtime.prepareExclusive(identity, controller.signal), /cancelled/); assert.equal(h.requests.length, 0); assert.equal(h.writes.length, 0); const key = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`; h.values.set(key, 'corrupt existing save'); await assert.rejects(runtime.prepareExclusive(identity), /saved game has not been reset/); await flush(); assert.equal(h.values.get(key), 'corrupt existing save'); assert.equal(h.writes.length, 0); assert.equal(h.requests[0].settled, true); assert.equal(h.held.size, 0); assert.equal(runtime.session, null); }); }); test('an immediate same-guest retry after clear reacquires and never overwrites the save', async () => { await withExclusiveHarness(async h => { const runtime = h.createRuntime(); const first = await runtime.prepareExclusive(identity); first.setBet(5000); runtime.clear(); const second = await runtime.prepareExclusive(identity); assert.equal(second.state.bet, 5000); assert.equal(h.writes.length, 2); assert.equal(h.requests.length, 2); assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false); assert.equal(h.held.size, 1); }); }); test('loading shows a fixed lock denial, retries without reauthentication and hands the session to the game', async () => { const h = loadingHarness(); const prepare = h.runtime.prepareExclusive; h.runtime.prepareExclusive = async () => { throw new Error(h.runtime.LOCK_IN_USE); }; h.button.node.emit('click'); await flush(); assert.equal(h.status.string, h.runtime.LOCK_IN_USE); assert.equal(h.button.interactable, true); assert.equal(h.panel.active, false); assert.equal(h.calls.load, 0); h.runtime.prepareExclusive = prepare; h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); await flush(); const session = h.runtime.session; assert.ok(session); finishLoading(h.loading); assert.equal(h.calls.signIn, 1); assert.equal(h.calls.launch, 1); assert.equal(h.calls.clear, 0); assert.equal(h.runtime.session, session); }); test('loading releases failed scenes and destruction but successful scene handoff keeps the lock', async () => { const failed = loadingHarness(); failed.button.node.emit('click'); await flush(); failed.pending.reject(new Error('private scene error')); await flush(); assert.equal(failed.runtime.session, null); assert.equal(failed.calls.clear, 1); const missing = loadingHarness(); missing.useScene(Promise.resolve({ scene: { getComponentInChildren: () => null } })); missing.button.node.emit('click'); await flush(); assert.equal(missing.runtime.session, null); assert.equal(missing.calls.clear, 1); const cancelled = loadingHarness(); cancelled.button.node.emit('click'); await flush(); cancelled.loading.onDestroy(); assert.equal(cancelled.runtime.session, null); assert.equal(cancelled.calls.clear, 1); const success = loadingHarness(); success.useScene(Promise.resolve(success.loaded)); success.button.node.emit('click'); await flush(); finishLoading(success.loading); assert.equal(success.calls.launch, 1); assert.equal(success.calls.clear, 0); }); test('failed scene handoff releases the session even if the old loading view has already been destroyed', async () => { for (const when of ['before', 'after'] as const) { const h = loadingHarness(); h.failTransition(when); h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); await flush(); finishLoading(h.loading); assert.equal(h.calls.launch, 1); assert.equal(h.runtime.session, null); assert.equal(h.calls.clear, 1); if (when === 'before') { assert.equal(h.button.interactable, true); assert.equal(h.panel.active, false); assert.match(h.status.string, /Unable to open the game/); assert.ok(!h.status.string.includes('private')); } } }); test('loading ignores a late exclusive preparation without loading a scene or clearing a newer session', async () => { const h = loadingHarness(); const late = pendingScene(); let signal: AbortSignal | undefined; const prepare = h.runtime.prepareExclusive; h.runtime.prepareExclusive = async (_id, cancellation) => { signal = cancellation; return late.promise; }; h.button.node.emit('click'); await flush(); Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable(); assert.equal(signal?.aborted, true); h.runtime.prepareExclusive = prepare; h.useScene(Promise.resolve(h.loaded)); Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush(); const current = h.runtime.session; late.resolve({}); await flush(); finishLoading(h.loading); assert.equal(h.calls.load, 1); assert.equal(h.calls.launch, 1); assert.equal(h.runtime.session, current); assert.equal(h.calls.clear, 0); }); test('a late scene failure after cancellation cannot release the resumed session', async () => { const h = loadingHarness(); h.button.node.emit('click'); await flush(); const previous = h.runtime.session; Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable(); assert.equal(h.calls.clear, 1); assert.equal(h.runtime.session, null); h.useScene(Promise.resolve(h.loaded)); Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush(); const current = h.runtime.session; assert.notEqual(current, previous); h.pending.reject(new Error('late old failure')); await flush(); finishLoading(h.loading); assert.equal(h.runtime.session, current); assert.equal(h.calls.clear, 1); assert.equal(h.calls.launch, 1); }); test('a late preparation rejection and login cancellation do not clear a newer preparation', async () => { const h = loadingHarness(); const late = pendingScene(); let signal: AbortSignal | undefined; const prepare = h.runtime.prepareExclusive; h.runtime.prepareExclusive = async (_id, cancellation) => { signal = cancellation; return late.promise; }; h.button.node.emit('click'); await flush(); h.login.render({ phase: 'idle', message: '', enabled: true }); assert.equal(signal?.aborted, true); assert.equal(h.panel.active, false); h.runtime.prepareExclusive = prepare; h.useScene(Promise.resolve(h.loaded)); Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable(); Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush(); const current = h.runtime.session; late.reject(new Error('private stale prepare error')); await flush(); finishLoading(h.loading); assert.equal(h.calls.launch, 1); assert.equal(h.calls.clear, 0); assert.equal(h.runtime.session, current); assert.ok(!h.status.string.includes('private')); });