Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1829 lines (1544 loc) · 48.7 KB
/
Copy pathbackground.js
File metadata and controls
1829 lines (1544 loc) · 48.7 KB
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* =============================================================================
* Persistent Containers - Background Service Script
* =============================================================================
*
* Core Responsibilities:
* 1. Active Container Inheritance:
* Ensures newly opened tabs (via Ctrl+T, links, or bookmarks) open in the
* same Firefox Multi-Account Container as the active tab.
* 2. Multi-Account Containers (MAC) Coordination:
* Queries MAC for domain assignments so explicit user rules are not overridden.
* 3. Tab Grouping Inheritance:
* Preserves tab grouping for newly spawned tabs (Firefox 138+).
* 4. Asynchronous State & Grace Recovery:
* Persists active tab lineage to storage.session to safely recover after
* background worker unloads or browser restarts.
*/
console.info("Persistent Containers: Background script initialized.");
// -----------------------------------------------------------------------------
// Configuration & Constants
// -----------------------------------------------------------------------------
const DEFAULT_CONTAINER = "firefox-default";
const MAC_EXTENSION_ID = "@testpilot-containers";
const STATE_KEY = "persistentContainersRuntimeStateV3";
// Timing parameters (in milliseconds)
const STARTUP_GRACE_MS = 3000; // Grace window after launch to prevent tab thrashing
const BLANK_SETTLE_MS = 300; // Settle time for intentional about:blank tabs
const BLANK_WAIT_LIMIT_MS = 10000; // Max wait time for a new tab's destination URL to populate
const MAC_TIMEOUT_MS = 1500; // Response timeout when querying Multi-Account Containers
const MAX_DESTINATION_ATTEMPTS = 3; // Maximum retries if destination URL keeps changing
const MAX_REDIRECTS = 512; // Bound for replacement ID redirection map
// Default extension preferences
const DEFAULT_SETTINGS = {
openNextToCurrent: true,
inheritTabGroup: true,
};
const settings = {
...DEFAULT_SETTINGS,
};
const changedSettings = new Set();
// Session storage reference (used to survive background page unloads)
const addonSession = browser.storage?.session ?? null;
// Tab activation tracking (Window ID -> { current, previous })
const activeHistory = new Map();
const savedHistory = new Map();
const bootstrapActiveTabs = new Map();
// Window tracking & versioning
const touchedWindows = new Set();
const windowVersions = new Map();
// Active processing queues & tab lifecycle tracking
const pendingTabs = new Map();
const ownedTabIds = new Set();
const creationOperations = new Set();
const replacementIds = new Map();
let creationSequence = 0;
let startupGraceUntil = 0;
let initializing = true;
let persistenceRequested = false;
let persistenceRunning = false;
const LOG_PREFIX = "Persistent Containers";
// -----------------------------------------------------------------------------
// Diagnostics & Error Reporting
// -----------------------------------------------------------------------------
/**
* Normalizes an unknown error into a structured object for diagnostics.
* @param {unknown} error - Caught error or exception.
* @returns {{ name: string, message: string, stack?: string }}
*/
function describeError(error) {
if (error instanceof Error) {
return {
name: error.name,
message: error.message,
stack: error.stack,
};
}
if (
error &&
typeof error === "object" &&
typeof error.message === "string"
) {
return {
name: error.name ?? "Error",
message: error.message,
stack: error.stack,
};
}
return {
name: "UnknownError",
message: String(error),
};
}
/**
* Formats and outputs structured errors to the Browser Console.
* @param {string} code - Diagnostic error code.
* @param {string} message - Human-readable explanation.
* @param {unknown} error - The caught error instance.
* @param {object} [context={}] - Contextual state (e.g. tabId, windowId).
* @param {string} [recovery=""] - Suggested troubleshooting or recovery step.
*/
function reportError(code, message, error, context = {}, recovery = "") {
console.error(
`[${LOG_PREFIX}] ${code}: ${message}`, {
...context,
error: describeError(error),
recovery,
},
);
}
/**
* Formats and outputs non-fatal diagnostic warnings.
* @param {string} code - Diagnostic warning code.
* @param {string} message - Warning message.
* @param {object} [context={}] - Relevant contextual information.
*/
function reportWarning(code, message, context = {}) {
console.warn(
`[${LOG_PREFIX}] ${code}: ${message}`,
context,
);
}
// Global runtime failure listeners
globalThis.addEventListener("error", (event) => {
reportError(
"BACKGROUND_UNCAUGHT",
"An uncaught background-script error occurred.",
event.error ?? event.message, {
file: event.filename,
line: event.lineno,
column: event.colno,
},
"Copy the first error and stack trace from the Browser Console.",
);
});
globalThis.addEventListener("unhandledrejection", (event) => {
reportError(
"BACKGROUND_UNHANDLED_PROMISE",
"An asynchronous operation failed without a local error handler.",
event.reason, {},
"Report this error with the action that triggered it.",
);
});
// -----------------------------------------------------------------------------
// Basic Helpers & Inspection
// -----------------------------------------------------------------------------
/**
* Checks whether a value is a valid non-negative integer tab ID.
*/
function isTabId(value) {
return Number.isInteger(value) && value >= 0;
}
/**
* Checks if a URL represents an empty or uninitialized page.
*/
function isBlankUrl(url) {
return !url || url === "about:blank";
}
/**
* Checks if a URL is the default browser New Tab page.
*/
function isNewTabUrl(url) {
return url === "about:newtab";
}
/**
* Checks whether a tab belongs to a Private Browsing context.
*/
function isPrivateTab(tab) {
return Boolean(
tab.incognito ||
tab.cookieStoreId === "firefox-private"
);
}
/**
* Checks whether a URL is a browser internal, extension, or privileged page.
*/
function isSystemUrl(url) {
if (!url) {
return false;
}
return (
(
url.startsWith("about:") &&
url !== "about:blank" &&
url !== "about:newtab"
) ||
url.startsWith("moz-extension://") ||
url.startsWith("chrome://")
);
}
/**
* Determines whether a URL can be safely navigated to within a replacement tab.
* Avoids recreating file:, data:, blob:, or privileged internal schemes.
*/
function canRecreateUrl(url) {
if (isBlankUrl(url) || isNewTabUrl(url)) {
return true;
}
try {
const parsed = new URL(url);
// Avoid recreating file:, data:, javascript:, blob:, and privileged
// pages. Their state or permissions may not survive a replacement.
return (
parsed.protocol === "http:" ||
parsed.protocol === "https:"
);
} catch {
return false;
}
}
/**
* Checks whether a tab participates in Firefox Split View.
*/
function hasSplitView(tab) {
return (
Number.isInteger(tab.splitViewId) &&
tab.splitViewId >= 0
);
}
/**
* Evaluates whether an error indicates a tab was closed during processing.
*/
function isMissingTabError(error) {
const message = describeError(error).message;
return (
/invalid tab id/i.test(message) ||
/no tab with id/i.test(message) ||
/tab .* does not exist/i.test(message)
);
}
/**
* Safely fetches a tab by ID, returning null if closed or invalid.
*/
async function getTab(tabId) {
if (!isTabId(tabId)) {
return null;
}
try {
return await browser.tabs.get(tabId);
} catch (error) {
if (isMissingTabError(error)) {
return null;
}
reportError(
"TAB_LOOKUP_FAILED",
"Firefox could not retrieve a tab.",
error, {
tabId,
},
"Check extension permissions and the preceding Browser Console errors.",
);
throw error;
}
}
/**
* Closes a temporary tab without logging benign 'missing tab' errors.
*/
async function removeTabQuietly(tabId) {
if (!isTabId(tabId)) {
return;
}
try {
await browser.tabs.remove(tabId);
} catch (error) {
if (isMissingTabError(error)) {
return;
}
reportError(
"TAB_CLEANUP_FAILED",
"Could not remove a temporary replacement tab.",
error, {
tabId,
},
"The original and replacement may both remain open. Check them before closing either.",
);
}
}
/**
* Wraps a promise with a maximum timeout, returning a fallback value if exceeded.
*/
async function withTimeout(promise, milliseconds, fallback) {
let timer;
try {
return await Promise.race([
promise,
new Promise((resolve) => {
timer = setTimeout(() => {
resolve(fallback);
}, milliseconds);
}),
]);
} finally {
clearTimeout(timer);
}
}
/**
* Increments the window version counter to invalidate outdated in-flight syncs.
*/
function touchWindow(windowId) {
if (initializing) {
touchedWindows.add(windowId);
}
windowVersions.set(
windowId,
(windowVersions.get(windowId) ?? 0) + 1,
);
}
/**
* Resolves a tab ID through any replacement redirects.
*/
function followReplacement(tabId) {
const visited = new Set();
while (
replacementIds.has(tabId) &&
!visited.has(tabId)
) {
visited.add(tabId);
tabId = replacementIds.get(tabId);
}
return tabId;
}
// -----------------------------------------------------------------------------
// Session-State Persistence
// -----------------------------------------------------------------------------
/**
* Persists active tab history to session storage so container lineage is preserved
* across background script suspensions.
*/
function persistState() {
if (!addonSession) {
return;
}
persistenceRequested = true;
if (persistenceRunning) {
return;
}
persistenceRunning = true;
Promise.resolve()
.then(async () => {
await ready;
while (persistenceRequested) {
persistenceRequested = false;
await addonSession.set({
[STATE_KEY]: {
startupGraceUntil,
windows: Object.fromEntries(activeHistory),
},
});
}
})
.catch((error) => {
persistenceRequested = false;
reportError(
"SESSION_SAVE_FAILED",
"Could not save the active-tab recovery state.",
error, {
trackedWindows: activeHistory.size,
},
"Inheritance after background unloading may be affected. Check initialization and storage errors.",
);
})
.finally(() => {
persistenceRunning = false;
if (persistenceRequested) {
persistState();
}
});
}
/**
* Records the currently active tab and previous tab for a given window.
*/
function rememberActiveTab(windowId, tabId, previousTabId) {
if (!isTabId(tabId)) {
return;
}
touchWindow(windowId);
const old = activeHistory.get(windowId);
const explicitPrevious =
isTabId(previousTabId) && previousTabId !== tabId ?
previousTabId :
null;
if (old?.current === tabId) {
// onCreated may already have stored the new current ID.
// Do not discard useful previousTabId information from onActivated.
if (
explicitPrevious !== null &&
old.previous !== explicitPrevious
) {
activeHistory.set(windowId, {
current: tabId,
previous: explicitPrevious,
});
persistState();
}
return;
}
activeHistory.set(windowId, {
current: tabId,
previous: explicitPrevious ?? old?.current ?? null,
});
persistState();
}
/**
* Purges closed tabs from history tracking structures.
*/
function forgetTabFromHistory(tabId, windowId) {
let changed = false;
for (const map of [activeHistory, savedHistory]) {
const history = map.get(windowId);
if (!history) {
continue;
}
if (
history.current !== tabId &&
history.previous !== tabId
) {
continue;
}
map.set(windowId, {
current: history.current === tabId ? null : history.current,
previous: history.previous === tabId ? null : history.previous,
});
changed = true;
}
if (bootstrapActiveTabs.get(windowId) === tabId) {
bootstrapActiveTabs.delete(windowId);
}
if (changed) {
persistState();
}
}
/**
* Registers an original tab ID -> replacement tab ID mapping.
*/
function rememberReplacement(originalId, replacementId, windowId) {
replacementIds.set(originalId, replacementId);
while (replacementIds.size > MAX_REDIRECTS) {
const oldestId = replacementIds.keys().next().value;
replacementIds.delete(oldestId);
}
for (const map of [activeHistory, savedHistory]) {
const history = map.get(windowId);
if (!history) {
continue;
}
map.set(windowId, {
current: history.current === originalId ?
replacementId : history.current,
previous: history.previous === originalId ?
replacementId : history.previous,
});
}
if (bootstrapActiveTabs.get(windowId) === originalId) {
bootstrapActiveTabs.set(windowId, replacementId);
}
persistState();
}
/**
* Synchronizes active tab state after async operations verify current state.
*/
async function syncActiveTab(tabId, windowId) {
const version = windowVersions.get(windowId) ?? 0;
const tab = await getTab(tabId);
if (
!tab ||
!tab.active ||
tab.windowId !== windowId ||
isPrivateTab(tab) ||
version !== (windowVersions.get(windowId) ?? 0)
) {
return;
}
rememberActiveTab(windowId, tab.id);
}
// -----------------------------------------------------------------------------
// Initialization
// -----------------------------------------------------------------------------
/**
* Reads settings, restores runtime session state, and maps active windows/tabs.
*/
async function initialize() {
const settingsPromise = browser.storage.local
.get(DEFAULT_SETTINGS)
.catch((error) => {
console.warn(
"Persistent Containers: Could not load settings:",
error,
);
return DEFAULT_SETTINGS;
});
const sessionPromise = addonSession ?
addonSession.get(STATE_KEY).catch((error) => {
console.warn(
"Persistent Containers: Could not load runtime state:",
error,
);
return {};
}) :
Promise.resolve({});
const windowsPromise = browser.windows
.getAll({
populate: true,
windowTypes: ["normal"],
})
.catch((error) => {
console.warn(
"Persistent Containers: Could not inspect windows:",
error,
);
return [];
});
const [storedSettings, sessionResult, windows] = await Promise.all([
settingsPromise,
sessionPromise,
windowsPromise,
]);
for (const key of Object.keys(DEFAULT_SETTINGS)) {
if (!changedSettings.has(key)) {
settings[key] =
typeof storedSettings[key] === "boolean" ?
storedSettings[key] :
DEFAULT_SETTINGS[key];
}
}
const storedState = sessionResult[STATE_KEY];
if (storedState && typeof storedState === "object") {
const storedGrace = storedState.startupGraceUntil;
// Avoid trusting an implausibly distant deadline after a clock change.
if (
Number.isFinite(storedGrace) &&
storedGrace <= Date.now() + STARTUP_GRACE_MS
) {
startupGraceUntil = Math.max(
startupGraceUntil,
storedGrace,
);
}
const storedWindows = storedState.windows;
if (storedWindows && typeof storedWindows === "object") {
for (const [key, history] of Object.entries(storedWindows)) {
const windowId = Number(key);
if (
!Number.isInteger(windowId) ||
!history ||
typeof history !== "object"
) {
continue;
}
const entry = {
current: isTabId(history.current) ?
history.current : null,
previous: isTabId(history.previous) ?
history.previous : null,
};
savedHistory.set(windowId, entry);
if (!touchedWindows.has(windowId)) {
activeHistory.set(windowId, {
...entry,
});
}
}
}
}
for (const win of windows) {
if (win.incognito) {
continue;
}
const activeTab = win.tabs?.find((tab) => tab.active);
if (!activeTab || isPrivateTab(activeTab)) {
continue;
}
bootstrapActiveTabs.set(win.id, activeTab.id);
if (!touchedWindows.has(win.id)) {
const old = activeHistory.get(win.id);
activeHistory.set(win.id, {
current: activeTab.id,
previous: old?.current === activeTab.id ?
old.previous : old?.current ?? null,
});
}
}
if (!addonSession) {
console.warn(
"Persistent Containers: storage.session is unavailable; " +
"recovery after background unloading is limited.",
);
}
}
// -----------------------------------------------------------------------------
// Multi-Account Containers (MAC) Integration
// -----------------------------------------------------------------------------
function isMissingMessageReceiver(error) {
const message = describeError(error).message;
return (
/receiving end does not exist/i.test(message) ||
/could not establish connection/i.test(message)
);
}
/**
* Checks whether Firefox Multi-Account Containers assigns the given URL to an
* explicit container. If so, we do not override MAC's native handling.
*/
async function hasMACAssignment(url) {
let parsed;
try {
parsed = new URL(url);
} catch {
return false;
}
if (
parsed.protocol !== "http:" &&
parsed.protocol !== "https:"
) {
return false;
}
const timedOut = Symbol("mac-message-timeout");
try {
const assignment = await withTimeout(
browser.runtime.sendMessage(MAC_EXTENSION_ID, {
method: "getAssignment",
url,
}),
MAC_TIMEOUT_MS,
timedOut,
);
if (assignment === timedOut) {
reportWarning(
"MAC_ASSIGNMENT_TIMEOUT",
"Multi-Account Containers did not respond in time. Falling back to ordinary inheritance.", {
timeoutMs: MAC_TIMEOUT_MS,
},
);
return false;
}
if (assignment === null || assignment === undefined) {
return false;
}
if (typeof assignment !== "object") {
reportWarning(
"MAC_UNEXPECTED_RESPONSE",
"Multi-Account Containers returned an unexpected response.", {
responseType: typeof assignment,
},
);
return false;
}
const contextId = assignment.userContextId;
// An empty object can represent no assignment.
if (contextId === null || contextId === undefined) {
return false;
}
const valid =
(
typeof contextId === "string" ||
typeof contextId === "number"
) &&
/^[1-9]\d*$/.test(String(contextId));
if (!valid) {
reportWarning(
"MAC_INVALID_CONTEXT_ID",
"Multi-Account Containers returned an unsupported assignment ID.", {
contextIdType: typeof contextId,
},
);
}
return valid;
} catch (error) {
if (!isMissingMessageReceiver(error)) {
reportError(
"MAC_ASSIGNMENT_FAILED",
"Could not check the optional Multi-Account Containers assignment.",
error, {},
"Ordinary inheritance will continue. Check whether the installed MAC version supports this message.",
);
}
return false;
}
}
// -----------------------------------------------------------------------------
// Tab Grouping
// -----------------------------------------------------------------------------
/**
* Assigns or unassigns a tab group based on user preferences and source tab group.
*/
async function applyTabGrouping(
targetTabId,
sourceTabId,
originalGroupId = -1,
) {
if (typeof browser.tabs.group !== "function") {
return;
}
const [target, source] = await Promise.all([
getTab(targetTabId),
getTab(sourceTabId),
]);
if (!target || target.pinned || hasSplitView(target)) {
return;
}
let desiredGroupId = originalGroupId;
if (
settings.inheritTabGroup &&
source &&
source.windowId === target.windowId
) {
desiredGroupId = source.groupId;
}
if (!Number.isInteger(desiredGroupId)) {
desiredGroupId = -1;
}
try {
if (desiredGroupId >= 0) {
if (target.groupId !== desiredGroupId) {
await browser.tabs.group({
tabIds: [target.id],
groupId: desiredGroupId,
});
}
} else if (
Number.isInteger(target.groupId) &&
target.groupId >= 0 &&
typeof browser.tabs.ungroup === "function"
) {
await browser.tabs.ungroup([target.id]);
}
} catch (error) {
// A grouping failure must not undo successful container inheritance.
reportError(
"TAB_GROUPING_FAILED",
"Could not apply the requested tab group.",
error, {
targetTabId,
sourceTabId,
desiredGroupId,
},
"Container handling can continue, but the tab group may be unchanged.",
);
}
}
// -----------------------------------------------------------------------------
// Tracking Extension-Created Tabs
// -----------------------------------------------------------------------------
/**
* Creates a tab and marks it as extension-owned so it is not recursively processed.
*/
async function createOwnedTab(properties) {
let resolveOperation;
const operation = {
windowId: properties.windowId,
finished: new Promise((resolve) => {
resolveOperation = resolve;
}),
};
creationOperations.add(operation);
let createdId = null;
try {
const tab = await browser.tabs.create(properties);
createdId = tab.id;
ownedTabIds.add(tab.id);
return tab;
} finally {
resolveOperation(createdId);
creationOperations.delete(operation);
}
}
// -----------------------------------------------------------------------------
// Pending Tab Records & Signals
// -----------------------------------------------------------------------------
function candidateFor(tabId) {
if (!isTabId(tabId)) {
return null;
}
return {
id: tabId,
pending: pendingTabs.get(tabId) ?? null,
};
}
function historyCandidate(history, newTabId) {
if (!history) {
return null;
}
// Previous is useful only if "current" is already the new tab.
// Otherwise an unrelated older container must not become a fallback.
const tabId =
history.current === newTabId ?
history.previous :
history.current;
return candidateFor(tabId);
}
function signalRecord(record) {
record.version += 1;
if (record.wake) {
record.wake();
}
}
function waitForChange(record, version, milliseconds) {
if (
record.cancelled ||
record.version !== version
) {
return Promise.resolve();
}
return new Promise((resolve) => {
let timer;
const finish = () => {
clearTimeout(timer);
if (record.wake === finish) {
record.wake = null;
}
resolve();
};
record.wake = finish;
timer = setTimeout(finish, milliseconds);
});
}
function cancelRecord(record) {
record.cancelled = true;
signalRecord(record);
}
// -----------------------------------------------------------------------------
// Inheritance Source Resolution
// -----------------------------------------------------------------------------
/**
* Discovers the tab that spawned or was active prior to the newly created tab.
*/
async function resolveSource(record) {
const eventCandidates = [
record.activationSource,
...record.sources,
].filter(Boolean);
const candidates = [...eventCandidates];
// Consult the load-time snapshot only when live event history did not
// identify a source. Do not replace a known source with an older one.
if (eventCandidates.length === 0) {
candidates.push(
historyCandidate(
savedHistory.get(record.windowId),
record.id,
),
);
}
candidates.push(candidateFor(record.initial.openerTabId));
if (eventCandidates.length === 0) {
candidates.push(
candidateFor(bootstrapActiveTabs.get(record.windowId)),
);
}
const visited = new Set();
for (const candidate of candidates.filter(Boolean)) {
if (
candidate.id === record.id ||
visited.has(candidate.id)
) {
continue;
}
visited.add(candidate.id);
let sourceId = followReplacement(candidate.id);
const sourceRecord =
candidate.pending ??
pendingTabs.get(sourceId);