DOM hub: open shadow roots of hosts a site names are part of the page
X renders its chat inside an open shadow root since 2026-10-01 (the XChatEmbed host [data-testid=xchatEmbedRoute]); the hub's document observer saw nothing of it, selector observers found nothing, feature sheets in <head> did not reach it and probes could not see it. A site adapter may name shadowHosts. The hub's one MutationObserver then also observes each such root (picked up on the next page mutation, or a few timed retries while a host has no root yet; dropped with the observer), selector observers search the roots too, domRoots(win) gives features the roots, a feature's ctx.css sheet is also adopted by each root (CSP-proof, updated in place, taken off on stop), and probes count matches inside the roots. Tests: hub observes and searches a root that appears later with one observer; registry adopts and removes the sheet and a probe inside a root is never a miss.
This commit is contained in:
parent
5fe65bf21f
commit
ce32a1ff0c
5 changed files with 181 additions and 15 deletions
|
|
@ -5,6 +5,11 @@
|
||||||
// text, a named attribute) and they run together in the next frame: layout readers first, then DOM
|
// text, a named attribute) and they run together in the next frame: layout readers first, then DOM
|
||||||
// writers, so a reader never forces a synchronous layout behind another feature's write. Features
|
// writers, so a reader never forces a synchronous layout behind another feature's write. Features
|
||||||
// marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat.
|
// marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat.
|
||||||
|
//
|
||||||
|
// A site that renders a part of itself inside an open shadow root (X's chat, since 2026-10-01, in
|
||||||
|
// the shadow root of its embed host) names the host in `shadowHosts`: the hub's one observer then
|
||||||
|
// observes each such root too (picked up when the host appears or gets its root, dropped with the
|
||||||
|
// observer), selector observers look inside, and `domRoots` gives features the roots to query.
|
||||||
|
|
||||||
export type DomWatch = {
|
export type DomWatch = {
|
||||||
/** Also run on text changes (characterData). */
|
/** Also run on text changes (characterData). */
|
||||||
|
|
@ -23,6 +28,8 @@ export type DomHubConfig = {
|
||||||
label: string;
|
label: string;
|
||||||
/** Pathnames where `offOnHeavy` features are skipped; null = none. */
|
/** Pathnames where `offOnHeavy` features are skipped; null = none. */
|
||||||
heavyPath: RegExp | null;
|
heavyPath: RegExp | null;
|
||||||
|
/** Selectors of hosts whose open shadow roots are part of the page (observed and searched like it). */
|
||||||
|
shadowHosts: readonly string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type DomWindow = {
|
export type DomWindow = {
|
||||||
|
|
@ -34,7 +41,7 @@ export type DomWindow = {
|
||||||
type Sub = { run: () => void; opts: DomWatch; pending: boolean };
|
type Sub = { run: () => void; opts: DomWatch; pending: boolean };
|
||||||
type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void };
|
type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void };
|
||||||
|
|
||||||
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null };
|
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null, shadowHosts: [] };
|
||||||
const hubs = new WeakMap<object, Hub>();
|
const hubs = new WeakMap<object, Hub>();
|
||||||
|
|
||||||
/** Set once by the site adapter, before features register. */
|
/** Set once by the site adapter, before features register. */
|
||||||
|
|
@ -42,6 +49,31 @@ export function configureDomHub(next: Partial<DomHubConfig>): void {
|
||||||
Object.assign(config, next);
|
Object.assign(config, next);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The page's roots: the document, then the open shadow roots of the configured hosts now in it. */
|
||||||
|
export function domRoots(win: { document: Document }): Array<Document | ShadowRoot> {
|
||||||
|
const doc = win.document;
|
||||||
|
const out: Array<Document | ShadowRoot> = [doc];
|
||||||
|
if (!config.shadowHosts.length) return out;
|
||||||
|
let hosts: Element[] = [];
|
||||||
|
try { hosts = Array.from(doc.querySelectorAll(config.shadowHosts.join(','))); } catch { return out; }
|
||||||
|
for (const host of hosts) {
|
||||||
|
const root = (host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot;
|
||||||
|
if (root) out.push(root);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The site names hosts whose shadow roots are part of the page. */
|
||||||
|
export function hasShadowHosts(): boolean {
|
||||||
|
return config.shadowHosts.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A configured host is in the page but has no open shadow root yet (it may attach one later). */
|
||||||
|
function hostWithoutRoot(doc: Document): boolean {
|
||||||
|
if (!config.shadowHosts.length) return false;
|
||||||
|
try { return Array.from(doc.querySelectorAll(config.shadowHosts.join(','))).some(host => !(host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot); } catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
export function isHeavyPath(pathname: string): boolean {
|
export function isHeavyPath(pathname: string): boolean {
|
||||||
return !!config.heavyPath && config.heavyPath.test(pathname);
|
return !!config.heavyPath && config.heavyPath.test(pathname);
|
||||||
}
|
}
|
||||||
|
|
@ -53,6 +85,28 @@ function hubFor(win: DomWindow): Hub {
|
||||||
let frameRequested = false;
|
let frameRequested = false;
|
||||||
let observer: MutationObserver | null = null;
|
let observer: MutationObserver | null = null;
|
||||||
let observing = '';
|
let observing = '';
|
||||||
|
let options: MutationObserverInit = { childList: true, subtree: true };
|
||||||
|
// Shadow roots the observer already observes (with the current options).
|
||||||
|
let roots = new WeakSet<Node>();
|
||||||
|
let retries = 0;
|
||||||
|
let retry: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
/** Observes configured shadow roots that are new; a new one marks every feature (its content is new to them). */
|
||||||
|
const observeRoots = () => {
|
||||||
|
if (!observer || !config.shadowHosts.length) return;
|
||||||
|
let added = false;
|
||||||
|
for (const root of domRoots(win).slice(1)) {
|
||||||
|
if (roots.has(root)) continue;
|
||||||
|
roots.add(root);
|
||||||
|
observer.observe(root, options);
|
||||||
|
added = true;
|
||||||
|
}
|
||||||
|
if (added) { retries = 0; for (const sub of hub.subs) hub.mark(sub); }
|
||||||
|
// attachShadow makes no mutation: a host that has no root yet is looked at again, a few times.
|
||||||
|
if (!retry && retries < 20 && hostWithoutRoot(doc)) {
|
||||||
|
retries += 1;
|
||||||
|
retry = setTimeout(() => { retry = null; observeRoots(); }, 300);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const frame = () => {
|
const frame = () => {
|
||||||
frameRequested = false;
|
frameRequested = false;
|
||||||
|
|
@ -78,6 +132,7 @@ function hubFor(win: DomWindow): Hub {
|
||||||
else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName);
|
else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (!known || childList) observeRoots();
|
||||||
for (const sub of hub.subs) {
|
for (const sub of hub.subs) {
|
||||||
if (!known || childList || (characterData && sub.opts.characterData)
|
if (!known || childList || (characterData && sub.opts.characterData)
|
||||||
|| (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub);
|
|| (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub);
|
||||||
|
|
@ -91,12 +146,15 @@ function hubFor(win: DomWindow): Hub {
|
||||||
if (observer && observing === key) return;
|
if (observer && observing === key) return;
|
||||||
observer ??= new win.MutationObserver(onRecords);
|
observer ??= new win.MutationObserver(onRecords);
|
||||||
observing = key;
|
observing = key;
|
||||||
// Re-observing the same node replaces its options.
|
options = {
|
||||||
observer.observe(doc.body, {
|
|
||||||
childList: true, subtree: true,
|
childList: true, subtree: true,
|
||||||
...(characterData ? { characterData: true } : {}),
|
...(characterData ? { characterData: true } : {}),
|
||||||
...(filter.length ? { attributes: true, attributeFilter: filter } : {}),
|
...(filter.length ? { attributes: true, attributeFilter: filter } : {}),
|
||||||
});
|
};
|
||||||
|
// Re-observing the same node replaces its options (the shadow roots get them again too).
|
||||||
|
observer.observe(doc.body, options);
|
||||||
|
roots = new WeakSet();
|
||||||
|
observeRoots();
|
||||||
};
|
};
|
||||||
|
|
||||||
const hub: Hub = {
|
const hub: Hub = {
|
||||||
|
|
@ -110,6 +168,8 @@ function hubFor(win: DomWindow): Hub {
|
||||||
observer?.disconnect();
|
observer?.disconnect();
|
||||||
observer = null;
|
observer = null;
|
||||||
observing = '';
|
observing = '';
|
||||||
|
roots = new WeakSet();
|
||||||
|
if (retry) { clearTimeout(retry); retry = null; }
|
||||||
doc.removeEventListener('DOMContentLoaded', start);
|
doc.removeEventListener('DOMContentLoaded', start);
|
||||||
hubs.delete(win);
|
hubs.delete(win);
|
||||||
return;
|
return;
|
||||||
|
|
@ -150,10 +210,12 @@ export function observeSelector(win: DomWindow, selector: string, callback: (ele
|
||||||
const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error));
|
const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error));
|
||||||
const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report };
|
const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report };
|
||||||
const scan = (target: SelectorSub) => {
|
const scan = (target: SelectorSub) => {
|
||||||
for (const element of Array.from(win.document.querySelectorAll(target.selector))) {
|
for (const root of domRoots(win)) {
|
||||||
if (target.seen.has(element)) continue;
|
for (const element of Array.from(root.querySelectorAll(target.selector))) {
|
||||||
target.seen.add(element);
|
if (target.seen.has(element)) continue;
|
||||||
try { target.callback(element); } catch (error) { target.report(error); }
|
target.seen.add(element);
|
||||||
|
try { target.callback(element); } catch (error) { target.report(error); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
owner.subs.push(sub);
|
owner.subs.push(sub);
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,8 @@
|
||||||
// rest of the area keeps working. A signed hotfix may replace a probe's selector
|
// rest of the area keeps working. A signed hotfix may replace a probe's selector
|
||||||
// (`selectors["<feature id>.<probe>"]`) or switch a feature off (`flags["<feature id>"] = false`).
|
// (`selectors["<feature id>.<probe>"]`) or switch a feature off (`flags["<feature id>"] = false`).
|
||||||
|
|
||||||
import { isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts';
|
import { domRoots, hasShadowHosts, isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts';
|
||||||
|
import { adoptStyles, type RootStyles } from './styles.ts';
|
||||||
import { HEALTH_COMMAND, areaFlag, healthKeywords, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts';
|
import { HEALTH_COMMAND, areaFlag, healthKeywords, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts';
|
||||||
import { formatMessage, type Params } from './i18n.ts';
|
import { formatMessage, type Params } from './i18n.ts';
|
||||||
import type { CommandDefinition } from './commands.ts';
|
import type { CommandDefinition } from './commands.ts';
|
||||||
|
|
@ -62,7 +63,7 @@ export type FeatureContext<Api> = {
|
||||||
readonly api: Api;
|
readonly api: Api;
|
||||||
/** The page's window (use it and its `document` instead of the globals: tests run without them). */
|
/** The page's window (use it and its `document` instead of the globals: tests run without them). */
|
||||||
readonly win: Window & typeof globalThis;
|
readonly win: Window & typeof globalThis;
|
||||||
/** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). */
|
/** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). It also styles the site's configured open shadow roots (domHub `shadowHosts`). */
|
||||||
css(css: string, name?: string): void;
|
css(css: string, name?: string): void;
|
||||||
/** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */
|
/** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */
|
||||||
observe(selector: string, callback: (element: Element) => void): void;
|
observe(selector: string, callback: (element: Element) => void): void;
|
||||||
|
|
@ -208,6 +209,8 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
|
||||||
const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } };
|
const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } };
|
||||||
const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en');
|
const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en');
|
||||||
const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild;
|
const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild;
|
||||||
|
/** A selector matches in the page or in one of its configured open shadow roots. */
|
||||||
|
const inPage = (selector: string) => domRoots(doc.defaultView ?? { document: doc }).some(root => !!root.querySelector(selector));
|
||||||
const words = (area: AreaSpec) => api.i18n.namespace(area.namespace);
|
const words = (area: AreaSpec) => api.i18n.namespace(area.namespace);
|
||||||
/** A feature's word `key`: under its own namespace when it names one (`words`), else under its area's. */
|
/** A feature's word `key`: under its own namespace when it names one (`words`), else under its area's. */
|
||||||
const wordOf = (module: FeatureModule<Api>, area: AreaSpec, key: string, params?: Params) =>
|
const wordOf = (module: FeatureModule<Api>, area: AreaSpec, key: string, params?: Params) =>
|
||||||
|
|
@ -267,6 +270,29 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
|
||||||
const name = featureName(module.id);
|
const name = featureName(module.id);
|
||||||
const domWin = win as unknown as DomWindow;
|
const domWin = win as unknown as DomWindow;
|
||||||
const styles = new Set<string>();
|
const styles = new Set<string>();
|
||||||
|
// The same sheets, adopted by each configured open shadow root of the page (a site part rendered
|
||||||
|
// inside one, e.g. X's chat embed); roots that appear later get them on the next hub frame.
|
||||||
|
const rootCss = new Map<string, string>();
|
||||||
|
const rootSheets = new Map<Node, Map<string, { sheet: RootStyles; css: string }>>();
|
||||||
|
let rootWatch: DomWatchHandle | null = null;
|
||||||
|
const syncRoots = () => {
|
||||||
|
const roots = domRoots(domWin).slice(1);
|
||||||
|
for (const [root, sheets] of rootSheets) {
|
||||||
|
if (roots.includes(root as ShadowRoot)) continue;
|
||||||
|
for (const item of sheets.values()) item.sheet.remove();
|
||||||
|
rootSheets.delete(root);
|
||||||
|
}
|
||||||
|
for (const root of roots) {
|
||||||
|
let sheets = rootSheets.get(root);
|
||||||
|
if (!sheets) { sheets = new Map(); rootSheets.set(root, sheets); }
|
||||||
|
for (const [styleId, item] of sheets) if (!rootCss.has(styleId)) { item.sheet.remove(); sheets.delete(styleId); }
|
||||||
|
for (const [styleId, css] of rootCss) {
|
||||||
|
const item = sheets.get(styleId);
|
||||||
|
if (!item) sheets.set(styleId, { sheet: adoptStyles(root as ShadowRoot, css), css });
|
||||||
|
else if (item.css !== css) { item.sheet.update(css); item.css = css; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
const ctx: FeatureContext<Api> = {
|
const ctx: FeatureContext<Api> = {
|
||||||
id: module.id,
|
id: module.id,
|
||||||
name,
|
name,
|
||||||
|
|
@ -277,6 +303,17 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
|
||||||
const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`;
|
const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`;
|
||||||
if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); }
|
if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); }
|
||||||
if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId);
|
if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId);
|
||||||
|
if (css) rootCss.set(styleId, css); else rootCss.delete(styleId);
|
||||||
|
if (!rootWatch && css && hasShadowHosts()) {
|
||||||
|
rootWatch = watchDom(domWin, syncRoots, { offOnHeavy: !spec.heavy });
|
||||||
|
scope.defer(() => {
|
||||||
|
rootWatch?.dispose(); rootWatch = null;
|
||||||
|
rootCss.clear();
|
||||||
|
for (const sheets of rootSheets.values()) for (const item of sheets.values()) item.sheet.remove();
|
||||||
|
rootSheets.clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (rootWatch) syncRoots();
|
||||||
},
|
},
|
||||||
observe(selector, callback) {
|
observe(selector, callback) {
|
||||||
scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) }));
|
scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) }));
|
||||||
|
|
@ -355,11 +392,11 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
|
||||||
if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; }
|
if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; }
|
||||||
if (typeof probe !== 'string' && probe.when) {
|
if (typeof probe !== 'string' && probe.when) {
|
||||||
let there = false;
|
let there = false;
|
||||||
try { there = !!doc.querySelector(probe.when); } catch { there = false; }
|
try { there = inPage(probe.when); } catch { there = false; }
|
||||||
if (!there) continue;
|
if (!there) continue;
|
||||||
}
|
}
|
||||||
let found = false;
|
let found = false;
|
||||||
try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; }
|
try { found = inPage(selectorOf(entry.module, name)); } catch { found = false; }
|
||||||
if (!found) missing.push(name);
|
if (!found) missing.push(name);
|
||||||
}
|
}
|
||||||
if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id);
|
if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id);
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,8 @@ export type SiteAdapter = {
|
||||||
runtimeGlobal: string;
|
runtimeGlobal: string;
|
||||||
/** Pages where heavy-page-sensitive DOM features pause (e.g. a WASM chat); null = none. */
|
/** Pages where heavy-page-sensitive DOM features pause (e.g. a WASM chat); null = none. */
|
||||||
heavyPath: RegExp | null;
|
heavyPath: RegExp | null;
|
||||||
|
/** Hosts whose open shadow roots are part of the page (the DOM hub observes and searches them; `domRoots`). */
|
||||||
|
shadowHosts?: readonly string[];
|
||||||
/** Request URL substrings that are the site's API calls; only these reach the net hub stages. */
|
/** Request URL substrings that are the site's API calls; only these reach the net hub stages. */
|
||||||
apiMarks: string[];
|
apiMarks: string[];
|
||||||
/** Extra URL substrings that reach XHR gates only. */
|
/** Extra URL substrings that reach XHR gates only. */
|
||||||
|
|
@ -38,7 +40,7 @@ export type SiteAdapter = {
|
||||||
|
|
||||||
/** Applies the adapter's global knobs (DOM hub, net hub). Call once, before features start. */
|
/** Applies the adapter's global knobs (DOM hub, net hub). Call once, before features start. */
|
||||||
export function configureRuntime(site: SiteAdapter): void {
|
export function configureRuntime(site: SiteAdapter): void {
|
||||||
configureDomHub({ label: site.product, heavyPath: site.heavyPath });
|
configureDomHub({ label: site.product, heavyPath: site.heavyPath, shadowHosts: site.shadowHosts ?? [] });
|
||||||
configureNetHub({ apiMarks: site.apiMarks, xhrMarks: site.xhrMarks });
|
configureNetHub({ apiMarks: site.apiMarks, xhrMarks: site.xhrMarks });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
// overrides and the selector health check.
|
// overrides and the selector health check.
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import { observeSelector, type DomWindow } from '../src/domHub.ts';
|
import { configureDomHub, observeSelector, type DomWindow } from '../src/domHub.ts';
|
||||||
import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts';
|
import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts';
|
||||||
import {
|
import {
|
||||||
areaFlag, effectiveFlags, manualChanges, modeFlags, modeStatus, normalizeFlags, pausedFeatures, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable,
|
areaFlag, effectiveFlags, manualChanges, modeFlags, modeStatus, normalizeFlags, pausedFeatures, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable,
|
||||||
|
|
@ -468,3 +468,31 @@ test('observeSelector: heavy pages skip observers that ask for it', () => {
|
||||||
stop();
|
stop();
|
||||||
stop();
|
stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('registry: a configured open shadow root gets the features\' sheets and counts for probes (a site part rendered inside one)', () => {
|
||||||
|
configureDomHub({ shadowHosts: ['[data-host]'] });
|
||||||
|
try {
|
||||||
|
const env = page();
|
||||||
|
const timers = fakeTimers();
|
||||||
|
class Sheet { css = ''; replaceSync(css: string) { this.css = css; } }
|
||||||
|
const inside = new Map<string, object[]>([['[data-row]', [{}]]]);
|
||||||
|
const root = {
|
||||||
|
nodeType: 11, adoptedStyleSheets: [] as Sheet[], ownerDocument: { defaultView: { CSSStyleSheet: Sheet } },
|
||||||
|
querySelector: (selector: string) => (inside.get(selector) ?? [])[0] ?? null,
|
||||||
|
querySelectorAll: (selector: string) => inside.get(selector) ?? [],
|
||||||
|
};
|
||||||
|
env.matches.set('[data-host]', [{ shadowRoot: root }]);
|
||||||
|
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
|
||||||
|
registry.define({ id: 'hideTrends', probes: { row: '[data-row]' }, start(ctx) { ctx.css('[data-row]{outline:1px solid}'); } });
|
||||||
|
registry.setFlags({ hideTrends: true });
|
||||||
|
assert.deepEqual(root.adoptedStyleSheets.map(sheet => sheet.css), ['[data-row]{outline:1px solid}'], 'the sheet is adopted by the root');
|
||||||
|
assert.deepEqual(env.liveStyles(), ['[data-row]{outline:1px solid}'], 'and the page keeps its own');
|
||||||
|
// The probe's element exists only inside the root: never a miss, however many visits.
|
||||||
|
for (let visit = 0; visit < 4; visit++) { env.go(visit % 2 ? '/home' : '/explore'); timers.advance(4000); }
|
||||||
|
assert.deepEqual(registry.health(), []);
|
||||||
|
assert.deepEqual(registry.active(), ['hideTrends']);
|
||||||
|
registry.setFlags({ hideTrends: false });
|
||||||
|
assert.deepEqual(root.adoptedStyleSheets, [], 'stopping takes the sheet off the root');
|
||||||
|
registry.dispose();
|
||||||
|
} finally { configureDomHub({ shadowHosts: [] }); }
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import { configureRuntime, isSiteUrl, type SiteAdapter } from '../src/site.ts';
|
import { configureRuntime, isSiteUrl, type SiteAdapter } from '../src/site.ts';
|
||||||
import { addGate, addRewrite, addTap, addXhrGate, fetchHooked, isApiUrl } from '../src/netHub.ts';
|
import { addGate, addRewrite, addTap, addXhrGate, fetchHooked, isApiUrl } from '../src/netHub.ts';
|
||||||
import { isHeavyPath, watchDom } from '../src/domHub.ts';
|
import { configureDomHub, domRoots, isHeavyPath, observeSelector, watchDom } from '../src/domHub.ts';
|
||||||
|
|
||||||
const SITE: SiteAdapter = {
|
const SITE: SiteAdapter = {
|
||||||
product: 'wayBetter for Test',
|
product: 'wayBetter for Test',
|
||||||
|
|
@ -210,3 +210,40 @@ test('dom hub: a failing feature does not stop the others', () => {
|
||||||
console.error = original;
|
console.error = original;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('dom hub: an open shadow root of a configured host is observed and searched like the page (the X chat embed, 2026-10-01)', async () => {
|
||||||
|
configureDomHub({ shadowHosts: ['[data-testid="embedRoute"]'] });
|
||||||
|
try {
|
||||||
|
const { win, observers, flush, mutate } = fakeDomWindow('/chat/1');
|
||||||
|
const observed: unknown[] = [];
|
||||||
|
const inRoot = [{ id: 'row-1' }, { id: 'row-2' }];
|
||||||
|
const root = { querySelectorAll: (selector: string) => (selector === '.row' ? inRoot : []) };
|
||||||
|
const host: { shadowRoot: unknown } = { shadowRoot: null };
|
||||||
|
const doc = win.document as unknown as Record<string, unknown>;
|
||||||
|
doc.querySelectorAll = (selector: string) => (selector === '[data-testid="embedRoute"]' ? [host] : []);
|
||||||
|
const seen: string[] = [];
|
||||||
|
const stop = observeSelector(win, '.row', element => seen.push((element as unknown as { id: string }).id));
|
||||||
|
// Every observe call is recorded (the page body first, then each root).
|
||||||
|
const entry = observers[0]!;
|
||||||
|
const FakeObserver = win.MutationObserver as unknown as { prototype: { observe(node: unknown, options: MutationObserverInit): void } };
|
||||||
|
const original = FakeObserver.prototype.observe;
|
||||||
|
FakeObserver.prototype.observe = function (node: unknown, options: MutationObserverInit) { observed.push(node); return original.call(this, node as Node, options); };
|
||||||
|
try {
|
||||||
|
assert.deepEqual(domRoots(win), [win.document], 'the host has no root yet: only the page');
|
||||||
|
mutate('childList'); flush();
|
||||||
|
assert.deepEqual(seen, [], 'nothing inside yet');
|
||||||
|
// The host attaches its root (no mutation for that); the next page mutation picks it up.
|
||||||
|
host.shadowRoot = root;
|
||||||
|
mutate('childList'); flush();
|
||||||
|
assert.ok(observed.includes(root), 'the root is observed by the one observer of the hub');
|
||||||
|
assert.deepEqual(domRoots(win), [win.document, root]);
|
||||||
|
assert.deepEqual(seen, ['row-1', 'row-2'], 'the selector observer found the rows inside the root');
|
||||||
|
inRoot.push({ id: 'row-3' });
|
||||||
|
entry.callback([{ type: 'childList' }] as unknown as MutationRecord[], {} as MutationObserver); flush();
|
||||||
|
assert.deepEqual(seen, ['row-1', 'row-2', 'row-3'], 'a mutation in the root wakes the same observer');
|
||||||
|
assert.equal(observers.length, 1, 'still one MutationObserver');
|
||||||
|
} finally { FakeObserver.prototype.observe = original; }
|
||||||
|
stop();
|
||||||
|
assert.equal(entry.connected, false, 'the last subscriber off disconnects it, roots included');
|
||||||
|
} finally { configureDomHub({ shadowHosts: [] }); }
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue