File size: 30,799 Bytes
af1e456
d101ec0
 
af1e456
 
 
 
 
 
eeb144a
af1e456
aeb21e9
af1e456
 
 
63e3e38
af1e456
bec35e9
 
af1e456
 
 
 
 
d101ec0
9bec131
af1e456
 
9bec131
 
 
af1e456
 
 
d101ec0
9bec131
63e3e38
bec35e9
aeb21e9
af1e456
bec35e9
 
af1e456
 
aeb21e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1e456
 
d101ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
d101ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
bec35e9
d101ec0
 
 
 
 
63e3e38
d101ec0
63e3e38
 
d101ec0
 
63e3e38
 
 
 
 
 
 
 
 
 
 
9bec131
 
 
 
86f0df6
 
 
 
9bec131
 
 
86f0df6
9bec131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6dfdc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
 
bec35e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88568e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d101ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1e456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bec131
 
af1e456
 
 
 
 
 
 
 
9bec131
 
af1e456
 
 
 
 
 
 
 
70e4ef8
 
 
 
 
af1e456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70e4ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
// Synthetic contracts for the existing search-host navigation module. These
// cover URL/session rules and DOM ownership with a synthetic shell. Real browser
// traversal, layout, speech and native navigation remain browser-test contracts.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import vm from 'node:vm';

const filename = path.join(process.cwd(), 'static/search/reader-host/application/navigation.js');
const source = fs.readFileSync(filename, 'utf8');
const contract = fs.readFileSync('static/reader/core/reader-contract.js', 'utf8');
const origin = 'https://search.example';
const readerPath = '/search/static/reader.html';

function fixture(readerDestination = readerPath, document = {readyState: 'loading', addEventListener() {}}, options) {
  const data = new Map();
  const calls = [], ticks = [];
  let now = 1000;
  const storage = {
    getItem(key) { return data.has(key) ? data.get(key) : null; },
    setItem(key, value) { data.set(key, String(value)); },
    removeItem(key) { data.delete(key); }
  };
  const root = new EventTarget();
  const location = new URL(origin + '/search/#/');
  const crypto = {randomUUID: () => 'fixed-token'};
  const history = {
    state: null,
    pushState(...args) { calls.push(['push', ...args]); history.state = args[0]; location.href = args[2]; },
    replaceState(...args) { calls.push(['replace', ...args]); history.state = args[0]; location.href = args[2]; }
  };
  // Supply location and storage through the global as in browsers. Unrelated
  // DOM and asynchronous Reader services remain intentionally unstubbed.
  const context = vm.createContext({self: root, window: root, document, sessionStorage: storage,
    localStorage: storage, location, URL, URLSearchParams,
    crypto, history, console, HTMLElement: ShellElement, Event, CustomEvent,
    Date: {now: () => now}, setInterval: fn => ticks.push(fn), clearInterval() {}});
  vm.runInContext(contract, context, {filename: 'reader-contract.js'});
  vm.runInContext(source, context, {filename});
  return {nav: root.VoiceOfMLReaderNavigation.createNavigation(readerDestination, options), data, storage, crypto, calls, context, location,
    tick(ms) {now += ms; ticks.at(-1)?.();}};
}

test('speech frame payload is consumed once and foreign names are left intact', () => {
  const {context} = fixture();
  const {speechHandoff} = context.self.VoiceOfMLReader;
  const settings = {rate: 1.3, timer: 'off', deadline: 0};
  for (const target of [{pending: true, settings}, {unit: 7, offset: 22, settings}]) {
    const frame = {name: speechHandoff.frameName(target)};
    assert.deepEqual(JSON.parse(speechHandoff.takeFramePayload(frame)), target);
    assert.equal(frame.name, '');
    assert.equal(speechHandoff.takeFramePayload(frame), '');
  }
  const foreign = {name: 'other-frame-name'};
  assert.equal(speechHandoff.takeFramePayload(foreign), '');
  assert.equal(foreign.name, 'other-frame-name');
});

const json = value => JSON.parse(JSON.stringify(value));

// Deliberately small DOM double: events run synchronously so dispose reentry is
// observable. It does not simulate layout, iframe loading or browser history.
class ShellElement extends EventTarget {
  constructor(document, tagName) {
    super();
    this.document = document;
    this.tagName = tagName;
    this.children = [];
    this.attributes = new Map();
    this.styles = new Map();
    this.style = {
      setProperty: (key, value) => this.styles.set(key, value),
      removeProperty: key => this.styles.delete(key)
    };
    const classes = new Set();
    this.classList = {
      add: value => classes.add(value), remove: value => classes.delete(value),
      contains: value => classes.has(value)
    };
    if (tagName === 'iframe') {
      this.contentWindow = new EventTarget();
      this.contentWindow.postMessage = () => {};
      this.contentDocument = {title: 'VoiceOfML Reader', URL: 'about:blank', querySelector: () => null};
    }
  }
  append(...children) {
    for (const child of children) { child.parent = this; this.children.push(child); }
  }
  replaceChildren(...children) {
    for (const child of [...this.children]) child.remove();
    this.append(...children);
  }
  remove() {
    if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
    this.parent = null;
  }
  focus() { this.document.activeElement = this; }
  setAttribute(key, value) { this.attributes.set(key, value); }
  getAttribute(key) { return this.attributes.get(key) ?? null; }
  hasAttribute(key) { return this.attributes.has(key); }
  removeAttribute(key) { this.attributes.delete(key); }
}

function shellFixture(destination = readerPath, options) {
  const document = Object.assign(new EventTarget(), {readyState: 'loading', title: 'Search'});
  document.createElement = tag => new ShellElement(document, tag);
  document.body = document.createElement('body');
  const input = document.createElement('input');
  document.body.append(input);
  input.focus();
  const state = fixture(destination, document, options);
  return {...state, document, input,
    shell: () => document.body.children.find(child => child.className === 'reader-overlay-opening'),
    mini: () => document.body.children.find(child => child.className === 'reader-speech-mini')};
}

function parkSpeakingReader(nav, url) {
  const frame = nav.mount(url);
  frame.contentDocument.URL = frame.src;
  frame.dispatchEvent(new Event('load'));
  let reveals = 0;
  frame.contentWindow.CCRDSpeech = {state: () => ({active: true}), reveal: () => reveals++};
  nav.unmount();
  assert.equal(nav.backgroundReader, frame);
  return {frame, reveals: () => reveals};
}

test('parked reuse keeps the new navigation identity through replacement and recovery', () => {
  const {nav, context, input, shell} = shellFixture();
  const first = new URL(origin + readerPath + '?id=book&nav=old&return=%2Fold');
  const parked = parkSpeakingReader(nav, first);
  const resumes = [];
  parked.frame.contentWindow.addEventListener('voice-reader-overlay-resume', () => {
    resumes.push({url: nav.readerUrl, inert: parked.frame.hasAttribute('inert')});
  });
  input.focus();
  const fresh = new URL(origin + readerPath + '?id=book&nav=new&return=%2Fsearch%2F%3Fq%3Dlatest');
  assert.equal(nav.mount(fresh, true), parked.frame);
  assert.deepEqual(resumes, [{url: fresh.href, inert: false}]);
  assert.equal(nav.readerUrl, fresh.href);
  assert.equal(nav.reusedMount, true);
  assert.equal(nav.returnFocus, input);
  assert.equal(parked.reveals(), 1);
  nav.remember(fresh, {});
  nav.dismiss();
  nav.showCloseRecovery('/search/?q=latest');
  const link = shell().children[1];
  link.dispatchEvent(new Event('click'));
  assert.equal(JSON.parse(context.sessionStorage.getItem('reader-navigation-restore')).readerUrl, fresh.href);
  const next = nav.replace(readerPath + '?id=next', {});
  const nextUrl = new URL(next.src);
  assert.equal(nextUrl.searchParams.get('nav'), 'new');
  assert.equal(nextUrl.searchParams.get('return'), '/search/?q=latest');
  assert.equal(nav.returnFocus, input);
  assert.equal(nav.reusedMount, false);
  assert.equal(nav.readerUrl, next.src);
  assert.equal(context.history.state.searchUrl, origin + '/search/#/');
  nav.unmount(false);
});

test('ordinary frames expose a changed src and replacement rejects unowned history', () => {
  const {nav, context, location} = shellFixture();
  const frame = nav.mount(new URL(origin + readerPath + '?id=ordinary&nav=original'));
  nav.remember(new URL(frame.src), {});
  frame.src = origin + readerPath + '?id=ordinary&nav=updated&return=%2Fsearch%2F%3Fq%3Dchanged';
  assert.equal(nav.reusedMount, false);
  assert.equal(nav.readerUrl, frame.src);
  // The visible address no longer matches the history entry: do not trust it.
  location.hash = '#unrelated';
  const next = nav.replace(readerPath + '?id=next', {});
  assert.equal(new URL(next.src).searchParams.get('nav'), 'updated');
  assert.equal(new URL(next.src).searchParams.get('return'), '/search/?q=changed');
  assert.equal(context.history.state.searchUrl, null);
  nav.unmount(false);
});

test('explicit fragment and bookmark opens bypass parked reuse without stopping speech', () => {
  for (const target of ['#chapter%202', '&bookmark=saved&bookmark_source=https%3A%2F%2Ffiles.example%2Fbook.md']) {
    const {nav, document, mini} = shellFixture();
    const ordinary = nav.parse(readerPath + '?id=book&ext=md');
    const url = nav.parse(ordinary.href + target);
    const parked = parkSpeakingReader(nav, url);
    const bar = mini();
    // Even the identical opening URL is a fresh request when it comes from a link.
    const next = nav.mount(url);
    assert.notEqual(next, parked.frame);
    assert.equal(next.src, url.href);
    assert.equal(parked.reveals(), 0);
    assert.equal(nav.backgroundReader, parked.frame);
    assert.equal(parked.frame.parent, document.body);
    assert.equal(mini(), bar);
    nav.unmount(false);
    assert.equal(nav.mount(ordinary), parked.frame);
    assert.equal(parked.reveals(), 1);
    assert.equal(nav.backgroundReader, null);
    assert.equal(mini(), undefined);
    nav.unmount(false);
  }
});

test('mini-player resumes the live Reader even when its iframe src contains opening targets', () => {
  let resumed;
  const resume = raw => {
    const url = nav.prepare(raw, '/search/#/?q=book');
    resumed = nav.mount(url, true);
    nav.remember(url, {});
  };
  const {nav, mini, calls} = shellFixture(readerPath, {resume});
  const ordinary = nav.parse(readerPath + '?id=book&ext=md&title=Book');
  const url = nav.parse(ordinary.href + '&bookmark=saved&bookmark_source=source#opening');
  const parked = parkSpeakingReader(nav, url);
  mini().children.find(child => child.className === 'reader-speech-mini-back').dispatchEvent(new Event('click'));
  assert.equal(resumed, parked.frame);
  assert.equal(parked.reveals(), 1);
  assert.equal(parked.frame.src, url.href, 'resuming must not reload the live iframe');
  assert.equal(calls[0][3], ordinary.href, 'mini-player history must not carry stale position requests');
  assert.equal(nav.backgroundReader, null);
  assert.equal(mini(), undefined);
  nav.unmount(false);
});

test('pending background handoff survives opening another book and reopening the same frame', () => {
  const {nav, storage, document, mini, tick} = shellFixture();
  const url = nav.parse(readerPath + '?id=book');
  storage.setItem('reader-speech-handoff', JSON.stringify({readerUrl:url.href,pending:true,at:1000}));
  document.dispatchEvent(new Event('DOMContentLoaded'));
  const pending = nav.backgroundReader;
  assert.ok(pending);
  assert.match(mini().children[0].textContent, /正在恢复朗读/);
  const other = nav.mount(nav.parse(readerPath + '?id=other'));
  assert.notEqual(other, pending);
  assert.equal(nav.backgroundReader, pending);
  nav.unmount(false);
  assert.equal(nav.mount(url), pending);
  nav.unmount();
  assert.equal(nav.backgroundReader, pending);
  tick(1000);
  assert.equal(nav.backgroundReader, pending);
  tick(300000);
  assert.equal(nav.backgroundReader, null);
});

test('handoff accepts an exact cursor and can be dismissed while still starting', () => {
  const {nav, storage, document, mini} = shellFixture();
  const url = nav.parse(readerPath + '?id=old&nav=private&return=%2Fsearch%2F');
  storage.setItem('reader-speech-handoff', JSON.stringify({readerUrl:url.href,unit:17,offset:22,at:1000}));
  document.dispatchEvent(new Event('DOMContentLoaded'));
  const frame = nav.backgroundReader;
  assert.ok(frame);
  assert.equal(new URL(frame.src).searchParams.has('nav'), false);
  assert.ok(frame.name.startsWith('reader-speech-resume:'));
  assert.deepEqual(JSON.parse(frame.name.slice('reader-speech-resume:'.length)), {unit:17,offset:22});
  mini().children.at(-1).dispatchEvent(new Event('click'));
  assert.equal(nav.backgroundReader, null);
  assert.equal(frame.parent, null);
});

test('handoff ignores expired and foreign navigation targets', () => {
  for (const target of [
    {readerUrl:origin+readerPath,at:-300000},
    {readerUrl:'https://other.example'+readerPath,at:1000},
    {readerUrl:origin+readerPath,at:1000,settings:{deadline:999}},
  ]) {
    const {nav, storage, document, mini} = shellFixture();
    storage.setItem('reader-speech-handoff',JSON.stringify(target));
    document.dispatchEvent(new Event('DOMContentLoaded'));
    assert.equal(nav.backgroundReader,null);
    assert.equal(mini(),undefined);
    assert.equal(storage.getItem('reader-speech-handoff'),null);
  }
});

test('a targeted Reader replacement keeps parked speech until the new Reader starts speaking', () => {
  const {nav, context} = shellFixture();
  const raw = readerPath + '?url=https%3A%2F%2Ffiles.example%2Fbook.md&ext=md';
  const parked = parkSpeakingReader(nav, nav.parse(raw));
  nav.mount(nav.parse(readerPath + '?id=other&nav=token'));
  const next = nav.replace(raw + '#heading', {});
  assert.notEqual(next, parked.frame);
  const url = new URL(next.src);
  assert.equal(url.hash, '#heading');
  assert.equal(url.searchParams.get('nav'), 'token');
  assert.equal(parked.reveals(), 0);
  assert.equal(nav.backgroundReader, parked.frame);
  const message = new Event('message');
  Object.assign(message, {origin, source: next.contentWindow, data: {type: 'voice-reader-speech-start'}});
  context.window.dispatchEvent(message);
  assert.equal(nav.backgroundReader, null);
  assert.equal(parked.frame.parent, null);
  nav.unmount(false);
});

test('deferred titles survive failed history and release only for the requested URL', () => {
  const {nav, document, context} = shellFixture();
  const url = new URL(origin + readerPath + '?id=book&title=Filename&nav=new');
  const frame = nav.mount(url, true);
  assert.equal(document.title, 'Search');
  assert.equal(frame.title, 'Filename');
  const push = context.history.pushState;
  context.history.pushState = () => { throw new Error('push failed'); };
  assert.throws(() => nav.remember(url, {}), /push failed/);
  frame.contentDocument = {URL: url.href, title: 'Loaded title'};
  frame.dispatchEvent(new Event('load'));
  assert.equal(frame.title, 'Loaded title');
  assert.equal(document.title, 'Search');
  const message = new Event('message');
  Object.assign(message, {origin, source: frame.contentWindow, data: {type: 'voice-reader-title', title: 'Resolved title'}});
  context.window.dispatchEvent(message);
  assert.equal(frame.title, 'Resolved title');
  assert.equal(document.title, 'Search', 'messages cannot bypass a failed history write');
  context.history.pushState = push;
  nav.remember(new URL(origin + readerPath + '?id=other'), {});
  assert.equal(document.title, 'Search', 'an unrelated history write cannot release the pending title');
  nav.remember(url, {});
  assert.equal(document.title, 'Resolved title');
  nav.dismiss();
  document.title = 'Browser traversal title';
  nav.unmount(false);
  assert.equal(document.title, 'Search', 'dismiss retains the original title for post-traversal unmount');
});

test('history reentry cannot release a newer mount of the same URL', () => {
  const {nav, document, context} = shellFixture();
  const url = new URL(origin + readerPath + '?id=book&title=Book');
  nav.mount(url, true);
  const push = context.history.pushState;
  context.history.pushState = (...args) => {
    push(...args);
    nav.mount(url, true);
  };
  nav.remember(url, {});
  assert.equal(document.title, 'Search');
  context.history.pushState = push;
  nav.remember(url, {});
  assert.equal(document.title, 'Book');
  nav.unmount(false);
});

test('direct mount yields to disposal reentry and keeps the newer title', () => {
  const {nav, document} = shellFixture();
  const first = nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
  let newest;
  first.contentWindow.addEventListener('voice-reader-dispose', () => {
    newest = nav.mount(new URL(origin + readerPath + '?id=newest&title=Newest'));
  });
  const result = nav.mount(new URL(origin + readerPath + '?id=stale&title=Stale'), true);
  assert.equal(result, newest);
  assert.equal(document.title, 'Newest');
  assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);
  nav.unmount(false);
  assert.equal(document.title, 'Search');
});

test('close during disposal cancels the in-flight mount even after frame ownership is released', () => {
  const {nav, document, input} = shellFixture();
  const first = nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
  first.contentWindow.addEventListener('voice-reader-dispose', () => {
    assert.equal(nav.unmount(false), null);
  });
  const result = nav.mount(new URL(origin + readerPath + '?id=cancelled&title=Cancelled'), true);
  assert.equal(result, null);
  assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 0);
  assert.equal(document.body.classList.contains('reader-overlay-open'), false);
  assert.equal(input.hasAttribute('inert'), false);
  assert.equal(input.hasAttribute('aria-hidden'), false);
  assert.equal(document.title, 'Search');
  assert.equal(nav.returnFocus, null);
  assert.equal(nav.backgroundReader, null);
});

test('replacement and history restoration publish titles without a deferred push', () => {
  const {nav, document} = shellFixture();
  nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
  assert.equal(document.title, 'First');
  nav.replace(readerPath + '?id=second&title=Second', {});
  assert.equal(document.title, 'Second');
  nav.replace(readerPath + '?id=third&title=Third', {});
  assert.equal(document.title, 'Third');
  nav.unmount(false);
  assert.equal(document.title, 'Search');
});

test('replacement revision preserves a Reader opened synchronously during disposal', () => {
  const {nav, document, input} = shellFixture();
  const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
  assert.equal(nav.returnFocus, input);
  assert.equal(nav.backgroundReader, null);
  let newest;
  first.contentWindow.addEventListener('voice-reader-dispose', () => {
    newest = nav.mount(new URL(origin + readerPath + '?id=newest'));
  });
  const result = nav.replace(readerPath + '?id=stale', {top: 50});
  assert.equal(result, newest, 'outer replacement must yield to the reentrant mount');
  assert.equal(first.parent, null);
  assert.equal(first.src, 'about:blank');
  assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);
  assert.equal(nav.accepts({origin, source: newest.contentWindow}), true);
  assert.equal(nav.accepts({origin: 'https://other.example', source: newest.contentWindow}), false);
  assert.equal(nav.accepts({origin, source: {frameElement: newest}}), true);
  assert.equal(nav.accepts({origin, source: null}), false);
  assert.equal(nav.accepts({origin, source: {get frameElement() { throw new Error('cross-origin'); }}}), false);
  assert.equal(nav.accepts({origin, source: first.contentWindow}), false);
  nav.unmount(false);
  assert.equal(nav.returnFocus, null);
  assert.equal(nav.unmount(), null);
});

test('ordinary replacement carries handoff and focus while releasing background ownership', () => {
  const {nav, document, input, data} = shellFixture();
  const hidden = document.createElement('aside');
  hidden.setAttribute('inert', '');
  hidden.setAttribute('aria-hidden', 'false');
  document.body.append(hidden);
  const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
  const next = nav.replace(readerPath + '?id=next', {top: 50});
  assert.notEqual(next, first);
  assert.equal(new URL(next.src).searchParams.get('nav'), 'token');
  assert.equal(new URL(next.src).searchParams.get('return'), '/search/');
  assert.equal(JSON.parse(data.get('reader-navigation-current')).readerUrl, next.src);
  assert.equal(nav.returnFocus, input);
  assert.equal(nav.unmount(false), input);
  assert.equal(input.hasAttribute('inert'), false);
  assert.equal(input.hasAttribute('aria-hidden'), false);
  assert.equal(hidden.hasAttribute('inert'), true);
  assert.equal(hidden.getAttribute('aria-hidden'), 'false');
});

test('close recovery validates both search routes without changing history or private handoff', () => {
  for (const destination of [readerPath, '/static/reader.html']) {
    const {nav, document, input, shell, data, calls} = shellFixture(destination);
    const search = destination === readerPath ? '/search/' : '/';
    nav.showCloseRecovery(search);
    assert.equal(shell(), undefined, 'no recovery without an active Reader');
    const url = nav.prepare(destination + '?id=book&title=Book', origin + search);
    nav.mount(url);
    nav.remember(url, {top: 50});
    const saved = data.get('reader-navigation-current');
    nav.showCloseRecovery(search);
    assert.equal(shell().children.some(child => child.tagName === 'a'), false, 'no recovery before close');
    nav.dismiss();
    assert.equal(document.title, 'Search');
    const valid = destination === readerPath ? '/search/#/Repo?q=book' : '/Repo?q=book';
    for (const [raw, expected] of [
      [valid, valid], ['https://other.example/', search], ['javascript:alert(1)', search],
      ['/static/reader.html', search], ['/elsewhere/page', search], ['http://[', search],
      ['https://user:password@search.example' + search, search]
    ]) {
      nav.showCloseRecovery(raw);
      const link = shell().children.find(child => child.tagName === 'a');
      assert.equal(link.href, origin + expected);
      assert.equal(shell().parent, document.body);
      assert.equal(shell().hasAttribute('inert'), false);
      assert.equal(shell().styles.has('opacity'), false);
      assert.equal(shell().styles.has('pointer-events'), false);
      assert.equal(document.activeElement, link);
      assert.equal(input.hasAttribute('inert'), true);
    }
    assert.equal(calls.length, 1, 'recovery must not push or replace history');
    assert.equal(data.get('reader-navigation-current'), saved);
    assert.equal(data.has('reader-navigation-restore'), false, 'handoff waits for explicit activation');
    assert.equal(nav.returnFocus, input);
    nav.unmount(false);
    assert.equal(shell(), undefined);
  }
});

test('recovery survives late shell load and records handoff only on native link activation', () => {
  const {nav, document, shell, data, calls, storage} = shellFixture();
  const target = origin + '/search/#/?q=book';
  const url = nav.prepare(readerPath + '?id=book', target);
  const frame = nav.mount(url);
  frame.contentDocument.URL = frame.src;
  frame.dispatchEvent(new Event('load'));
  assert.equal(shell(), undefined);
  nav.dismiss();
  nav.showCloseRecovery(target);
  const recovery = shell();
  const link = recovery.children.find(child => child.tagName === 'a');
  frame.dispatchEvent(new Event('load'));
  assert.equal(shell(), recovery);
  assert.equal(document.activeElement, link);
  const click = new Event('click', {cancelable: true});
  link.dispatchEvent(click);
  assert.equal(click.defaultPrevented, false, 'native href remains the navigation action');
  assert.deepEqual(JSON.parse(data.get('reader-navigation-restore')), {readerUrl: url.href, returnUrl: target});
  storage.setItem = () => { throw new Error('quota'); };
  assert.doesNotThrow(() => link.dispatchEvent(new Event('click')));
  assert.deepEqual(calls, []);
  assert.equal(nav.unmount(false).tagName, 'input');
  nav.showCloseRecovery(target);
  assert.equal(shell(), undefined);
});

test('parse accepts only the same-origin reader pathname', () => {
  const {nav} = fixture();
  assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,
    origin + readerPath + '?title=a%20b#part');
  for (const raw of ['https://other.example' + readerPath, '/reader.html', readerPath + '/extra'])
    assert.throws(() => nav.parse(raw), {message: 'Invalid reader destination'});
  assert.throws(() => nav.parse('http://['), {name: 'TypeError'});
});

test('ordinary query merging replaces only selected keys and keeps repeated values', () => {
  const {nav} = fixture();
  const original = new URL(origin + '/search/?keep=1&q=old&q=older&ext=pdf#section');
  const source = new URLSearchParams('q=first&q=second&ext=txt&unused=x');
  const result = nav.mergeSearchParams(original, source, {keys: ['q', 'ext', 'missing']});
  assert.equal(result.href, origin + '/search/?keep=1&q=first&q=second&ext=txt#section');
  assert.equal(original.href, origin + '/search/?keep=1&q=old&q=older&ext=pdf#section');
  assert.equal(source.toString(), 'q=first&q=second&ext=txt&unused=x');
});

test('hash query merging preserves route and unrelated query components', () => {
  const {nav} = fixture();
  const result = nav.mergeSearchParams('/search/?outer=1#/Repo?path=dir%2Fone&q=old&folder=x',
    'q=hello+world&q=two&folder=', {hashRoute: true, keys: ['q', 'folder', 'absent']});
  assert.equal(result.pathname, '/search/');
  assert.equal(result.search, '?outer=1');
  assert.equal(result.hash, '#/Repo?path=dir%2Fone&q=hello+world&q=two&folder=');
  assert.equal(nav.mergeSearchParams('/search/#/Repo?q=x', '',
    {hashRoute: true, keys: ['q']}).hash, '#/Repo');
});

test('merge without selected keys preserves existing query and returns a new URL', () => {
  const {nav} = fixture();
  const target = new URL(origin + '/search/?a=1&a=2#/Repo?b=3');
  const result = nav.mergeSearchParams(target, 'a=other');
  assert.notEqual(result, target);
  assert.equal(result.href, target.href);
});

test('prepare records the return location and removes the previous handoff', () => {
  const {nav, data} = fixture();
  const old = origin + readerPath + '?nav=old-token&ext=txt';
  data.set('reader-return:old-token', origin + '/old');
  data.set('reader-navigation-current', JSON.stringify({readerUrl: old}));
  const url = nav.prepare(readerPath + '?url=book&nav=stale', '/search/#/Repo?path=a');
  assert.equal(url.searchParams.get('return'), '/search/#/Repo?path=a');
  assert.equal(url.searchParams.get('nav'), 'fixed-token');
  assert.equal(data.get('reader-return:fixed-token'), origin + '/search/#/Repo?path=a');
  assert.equal(data.has('reader-return:old-token'), false);
  assert.equal(data.has('reader-navigation-current'), false);
});

test('prepare tolerates unavailable storage or token generation without skipping destination validation', () => {
  for (const broken of ['storage', 'crypto']) {
    const {nav, storage, crypto} = fixture();
    if (broken === 'storage') storage.setItem = () => { throw new Error('storage unavailable'); };
    else crypto.randomUUID = () => { throw new Error('crypto unavailable'); };
    const url = nav.prepare(readerPath + '?ext=txt', '/search/#/');
    assert.equal(url.searchParams.get('return'), '/search/#/');
    assert.equal(url.searchParams.has('nav'), false);
    assert.throws(() => nav.prepare('https://other.example' + readerPath, '/search/'),
      {message: 'Invalid reader destination'});
  }
});

test('remember stores a private reader URL but exposes a sanitized history URL', () => {
  const {nav, data, calls, location} = fixture();
  const searchUrl = location.href;
  const url = new URL(origin + readerPath + '?url=book&return=%2Fsearch%2F&nav=secret&ext=txt');
  const scroll = {top: 125, key: 'entry'};
  nav.remember(url, scroll);
  nav.remember(url, scroll, true);
  const share = origin + readerPath + '?url=book&ext=txt';
  assert.deepEqual(json(nav.saved()), {shareUrl: share, readerUrl: url.href, returnScroll: scroll});
  assert.equal(data.has('reader-navigation-current'), true);
  assert.deepEqual(json(calls), [
    ['push', {voiceReaderOverlay: true, readerUrl: url.href, searchUrl}, '', share],
    ['replace', {voiceReaderOverlay: true, readerUrl: url.href, searchUrl}, '', share]
  ]);
  assert.equal(url.searchParams.get('nav'), 'secret');
});

test('remember still updates history when storage fails and saved rejects malformed JSON', () => {
  const {nav, data, storage, calls} = fixture();
  data.set('reader-navigation-current', '{not-json');
  assert.equal(nav.saved(), null);
  // Valid JSON is returned verbatim; it is not guaranteed to be our record.
  for (const value of [true, 17, 'text', ['item'], {readerUrl: 23}]) {
    data.set('reader-navigation-current', JSON.stringify(value));
    assert.deepEqual(json(nav.saved()), value);
  }
  storage.setItem = () => { throw new Error('quota'); };
  const url = new URL(origin + readerPath + '?nav=secret');
  nav.remember(url, {top: 2});
  assert.equal(calls.length, 1);
  assert.equal(calls[0][0], 'push');
  assert.equal(calls[0][3], origin + readerPath);
});

test('clear removes only the matching session and selected return token', () => {
  const {nav, data} = fixture();
  const current = new URL(origin + readerPath + '?nav=current');
  const other = new URL(origin + readerPath + '?nav=other');
  data.set('reader-navigation-current', JSON.stringify({readerUrl: current.href}));
  data.set('reader-return:current', 'current');
  data.set('reader-return:other', 'other');
  nav.clear(other);
  assert.equal(data.has('reader-return:other'), false);
  assert.equal(data.has('reader-navigation-current'), true);
  nav.clear(current);
  assert.equal(data.has('reader-return:current'), false);
  assert.equal(data.has('reader-navigation-current'), false);
});

test('messages are rejected when no reader iframe is active', () => {
  const {nav} = fixture();
  assert.equal(nav.accepts({origin, source: {}}), false);
  assert.equal(nav.accepts({origin: 'https://other.example', source: null}), false);
});

test('pathname and search parameter prototype overrides retain their original effects', () => {
  const {nav, context} = fixture();
  const path = Object.getOwnPropertyDescriptor(URL.prototype, 'pathname');
  const get = URLSearchParams.prototype.get;
  try {
    Object.defineProperty(URL.prototype, 'pathname', {...path, get() { return undefined; }});
    assert.throws(() => nav.parse(readerPath), {message: 'Invalid reader destination'});
    Object.defineProperty(URL.prototype, 'pathname', path);
    const result = nav.mergeSearchParams('/search/#/Repo?path=first', 'q=ok', {hashRoute:true, keys:['q']});
    assert.equal(result.hash, '#/Repo?path=first&q=ok');
    URLSearchParams.prototype.get = function() { return undefined; };
    assert.equal(nav.prepare(readerPath, '/search/').searchParams.get('nav'), undefined);
    vm.runInContext('String.prototype.split = function() { return []; }', context);
    assert.match(nav.mergeSearchParams('/search/#/Repo', '', {hashRoute:true}).hash, /^#undefined/);
  } finally {
    Object.defineProperty(URL.prototype, 'pathname', path);
    URLSearchParams.prototype.get = get;
  }
});