| 1 | import assert from 'node:assert/strict'; |
| 2 | import { createPrivacyController } from './browser-privacy-fixture.mjs'; |
| 3 | |
| 4 | const fixture = await createPrivacyController(); |
| 5 | const { api, cdp, waitFor, origin } = fixture; |
| 6 | const events = []; |
| 7 | const stream = new AbortController(); |
| 8 | let eventLoop; |
| 9 | try { |
| 10 | const response = await fixture.states(stream.signal); |
| 11 | assert.equal(response.status, 200); |
| 12 | eventLoop = (async () => { |
| 13 | const decoder = new TextDecoder(); |
| 14 | let buffer = ''; |
| 15 | for await (const chunk of response.body) { |
| 16 | buffer += decoder.decode(chunk, { stream: true }); |
| 17 | let end; |
| 18 | while ((end = buffer.indexOf('\n\n')) !== -1) { |
| 19 | const frame = buffer.slice(0, end); |
| 20 | buffer = buffer.slice(end + 2); |
| 21 | if (frame.startsWith('data: ')) events.push(JSON.parse(frame.slice(6))); |
| 22 | } |
| 23 | } |
| 24 | })().catch(error => { if (!stream.signal.aborted) throw error; }); |
| 25 | const assertEmpty = async () => { |
| 26 | const state = await api('/tabs'); |
| 27 | assert.deepEqual(state.tabs, []); |
| 28 | assert.equal(state.active, ''); |
| 29 | await waitFor(() => events.at(-1)?.tabs.length === 0, 'empty browser event'); |
| 30 | assert.equal(events.at(-1).active, '', 'empty snapshot must not reference a destroyed tab'); |
| 31 | }; |
| 32 | await api('/close', { id: (await api('/tabs')).active }); |
| 33 | await assertEmpty(); |
| 34 | const reopened = await api('/new', { url: origin + '/reopened' }); |
| 35 | assert.equal((await api('/tabs')).tabs.length, 1); |
| 36 | assert.equal((await api('/tabs')).active, reopened.id); |
| 37 | |
| 38 | |
| 39 | await cdp(reopened.id, 'Target.closeTarget', { targetId: reopened.id }); |
| 40 | await waitFor(async () => (await api('/tabs')).tabs.length === 0, 'external close'); |
| 41 | await assertEmpty(); |
| 42 | const privateTab = await api('/new', { url: origin + '/private', incognito: true }); |
| 43 | const context = (await cdp(privateTab.id, 'Target.getTargetInfo')).targetInfo.browserContextId; |
| 44 | await api('/close', { id: privateTab.id }); |
| 45 | await assertEmpty(); |
| 46 | const contexts = await cdp('', 'Target.getBrowserContexts'); |
| 47 | assert.ok(!contexts.browserContextIds.includes(context), 'last private tab must dispose its context'); |
| 48 | const final = await api('/new', { url: origin + '/final' }); |
| 49 | assert.equal((await api('/tabs')).active, final.id); |
| 50 | console.log(JSON.stringify({ passed: true, lastTabClosed: true, emptyEvents: true, |
| 51 | externalClose: true, privateContextDisposed: true, reopened: true })); |
| 52 | } finally { |
| 53 | stream.abort(); |
| 54 | await eventLoop; |
| 55 | await fixture.close(); |
| 56 | } |