/** * R4.3: the page side of one import (plan §B.1.5 items 1, 3, 5): the worker created in a * try/catch, listeners before the post, the start timer until `ready`, the task timer * after, the file fed chunk by chunk (one travelling buffer, each chunk acknowledged), * settle once on the first of result / failed / error event / read failure / timer / * cancel, the worker terminated in every case, later messages ignored, timers paused * while hidden. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runImportTask, type ImportClientOptions, type ImportSettlement, type WorkerLike, } from '@/core/worker/client' import { PROTOCOL_VERSION } from '@/core/worker/protocol' import type { ChunkSource } from '@/core/worker/reader' import type { Visibility } from '@/core/worker/timers' /** A scripted worker: the test drives its messages and events; chunks are acknowledged. */ function scriptedWorker() { const worker: WorkerLike & { terminated: number; sent: unknown[] } = { terminated: 0, sent: [], onmessage: null, onerror: null, onmessageerror: null, postMessage: (m) => { worker.sent.push(m) const message = m as { type?: string; bytes?: ArrayBuffer } if (message.type === 'chunk') { emit({ v: PROTOCOL_VERSION, type: 'ack', bytes: message.bytes }) } }, terminate: () => { worker.terminated += 1 }, } const emit = (data: unknown) => worker.onmessage?.({ data } as MessageEvent) return { worker, ready: () => emit({ v: PROTOCOL_VERSION, type: 'ready' }), result: (out = '{"ok":true}') => emit({ v: PROTOCOL_VERSION, type: 'result', out, diag: { ms: 1, linearBytes: 0, chunks: 1 }, }), failed: (phase: 'start' | 'task', kind: string) => emit({ v: PROTOCOL_VERSION, type: 'failed', phase, kind, detail: `${kind}!`, }), error: (message: string) => worker.onerror?.({ message } as ErrorEvent), types: () => worker.sent.map((m) => (m as { type: string }).type), } } function visibility(): Visibility & { set: (hidden: boolean) => void } { let hidden = false const listeners = new Set<() => void>() return { hidden: () => hidden, onChange: (listener) => { listeners.add(listener) return () => listeners.delete(listener) }, set: (next) => { hidden = next for (const listener of listeners) listener() }, } } /** A chunk source over `parts`, each filled into the travelling buffer. */ function partsSource(parts: Uint8Array[]): ChunkSource { let at = 0 return { async next(buffer) { const part = parts[at] if (!part) return null at += 1 new Uint8Array(buffer, 0, part.byteLength).set(part) return { bytes: buffer, length: part.byteLength } }, cancel: async () => {}, } } const file = new File([new Uint8Array([1, 2, 3])], 'a.pdf') const input = { task: 'pdf' as const, file, sheet: '{}', module: null } const empty = () => partsSource([]) function options( spawn: () => WorkerLike, patch: Partial = {}, ): ImportClientOptions { return { spawn, startTimeoutMs: 100, taskTimeoutMs: 100, source: empty, ...patch, } } async function settled(run: { settled: Promise }): Promise { await vi.advanceTimersByTimeAsync(0) return run.settled } describe('import client', () => { beforeEach(() => vi.useFakeTimers()) afterEach(() => vi.useRealTimers()) it('posts the task, feeds the chunks then end, settles on the result and terminates', async () => { const s = scriptedWorker() const parts = [new Uint8Array([1, 2]), new Uint8Array([3])] const run = runImportTask( input, options(() => s.worker, { source: () => partsSource(parts) }), ) expect(s.worker.onmessage).not.toBeNull() expect(s.worker.sent).toEqual([ { v: 1, type: 'task', task: 'pdf', size: 3, sheet: '{}', module: null }, ]) s.ready() await vi.advanceTimersByTimeAsync(0) expect(s.types()).toEqual(['task', 'chunk', 'chunk', 'end']) expect((s.worker.sent[1] as { length: number }).length).toBe(2) s.result('{"ok":true}') expect(await settled(run)).toMatchObject({ kind: 'result', out: '{"ok":true}', }) expect(s.worker.terminated).toBe(1) }) it('is worker_unavailable when the spawn throws, fails before ready, or never answers ready', async () => { const thrown = runImportTask( input, options(() => { throw new DOMException('blocked', 'SecurityError') }), ) expect(await settled(thrown)).toEqual({ kind: 'failed', reason: 'worker_unavailable', detail: 'SecurityError', }) const early = scriptedWorker() const failedEarly = runImportTask( input, options(() => early.worker), ) early.failed('start', 'other') expect(await settled(failedEarly)).toMatchObject({ kind: 'failed', reason: 'worker_unavailable', }) const silent = scriptedWorker() const timedOut = runImportTask( input, options(() => silent.worker, { taskTimeoutMs: 1000 }), ) await vi.advanceTimersByTimeAsync(99) expect(silent.worker.terminated).toBe(0) await vi.advanceTimersByTimeAsync(2) expect(await timedOut.settled).toMatchObject({ kind: 'failed', reason: 'worker_unavailable', }) expect(silent.worker.terminated).toBe(1) }) it('maps task failures: trap → crashed, read → read, sheet/other → engine, timer → timeout', async () => { const cases: Array<[string, string]> = [ ['trap', 'crashed'], ['read', 'read'], ['sheet', 'engine'], ['other', 'engine'], ] for (const [kind, reason] of cases) { const s = scriptedWorker() const run = runImportTask( input, options(() => s.worker), ) s.ready() s.failed('task', kind) expect(await settled(run)).toEqual({ kind: 'failed', reason, detail: `${kind}!`, }) expect(s.worker.terminated).toBe(1) } const slow = scriptedWorker() const run = runImportTask( input, options(() => slow.worker, { startTimeoutMs: 50, taskTimeoutMs: 200 }), ) await vi.advanceTimersByTimeAsync(40) slow.ready() await vi.advanceTimersByTimeAsync(199) expect(slow.worker.terminated).toBe(0) await vi.advanceTimersByTimeAsync(2) expect(await run.settled).toMatchObject({ kind: 'failed', reason: 'timeout', }) }) it('settles once: a result after the timeout, a failure after the result, are ignored', async () => { const s = scriptedWorker() const run = runImportTask( input, options(() => s.worker), ) s.ready() await vi.advanceTimersByTimeAsync(101) s.result('{"ok":true}') expect(await run.settled).toMatchObject({ kind: 'failed', reason: 'timeout', }) expect(s.worker.terminated).toBe(1) const t = scriptedWorker() const second = runImportTask( input, options(() => t.worker), ) t.ready() t.result('{"ok":true}') t.failed('task', 'trap') t.error('late') expect(await settled(second)).toMatchObject({ kind: 'result' }) expect(t.worker.terminated).toBe(1) }) it('never masks an error event: worker_unavailable before ready, crashed after', async () => { const before = scriptedWorker() const first = runImportTask( input, options(() => before.worker), ) before.error('script failed') expect(await settled(first)).toEqual({ kind: 'failed', reason: 'worker_unavailable', detail: 'script failed', }) const after = scriptedWorker() const second = runImportTask( input, options(() => after.worker), ) after.ready() after.error('boom') expect(await settled(second)).toEqual({ kind: 'failed', reason: 'crashed', detail: 'boom', }) }) it('a file the page cannot read settles read and terminates the worker', async () => { const s = scriptedWorker() const failing: ChunkSource = { next: () => Promise.reject(new DOMException('gone', 'NotReadableError')), cancel: async () => {}, } const run = runImportTask( input, options(() => s.worker, { source: () => failing }), ) s.ready() expect(await settled(run)).toEqual({ kind: 'failed', reason: 'read', detail: 'NotReadableError: gone', }) expect(s.worker.terminated).toBe(1) }) it('cancel terminates the worker and settles cancelled, once', async () => { const s = scriptedWorker() const run = runImportTask( input, options(() => s.worker), ) s.ready() run.cancel() run.cancel() s.result() expect(await settled(run)).toMatchObject({ kind: 'failed', reason: 'cancelled', }) expect(s.worker.terminated).toBe(1) }) it('pauses the task timer while the page is hidden', async () => { const s = scriptedWorker() const vis = visibility() const run = runImportTask( input, options(() => s.worker, { visibility: vis }), ) s.ready() await vi.advanceTimersByTimeAsync(50) vis.set(true) await vi.advanceTimersByTimeAsync(10_000) expect(s.worker.terminated).toBe(0) vis.set(false) await vi.advanceTimersByTimeAsync(49) expect(s.worker.terminated).toBe(0) await vi.advanceTimersByTimeAsync(2) expect(await run.settled).toMatchObject({ kind: 'failed', reason: 'timeout', }) }) })