Remove INode (node.__sn) and use Mirror as source of truth (#868)

* Move ids to weakmap

* Fix typo

* Move from INode to storing serialized data in mirror

* Update packages/rrweb-snapshot/src/rebuild.ts

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>

* Remove unnessisary `as Node` typecastings

Fixes: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842240758

* Remove unnessisary `as unknown as ...`

* Remove unnessisary `as unknown as ...`

* Reset mirror when recording starts

Solves: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842249599

* API has changed for snapshot, change test to reflect that

* Allow for es5 compatibility

* Remove unnessisary as unknown as ... and change test to reflect the API change

* Refactor mirror to remove `nodeIdMap`

Fixes: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842732696

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>
This commit is contained in:
Justin Halsall
2026-04-01 12:00:00 +08:00
committed by GitHub
parent 65237a5ee9
commit d4f5d8dc48
36 changed files with 442 additions and 382 deletions

View File

@@ -37,4 +37,4 @@ There are several things will be done during rebuild:
#### buildNodeWithSN
`buildNodeWithSN` will build DOM from serialized node and store serialized information in `__sn` property.
`buildNodeWithSN` will build DOM from serialized node and store serialized information in the `mirror.getMeta(node)`.

View File

@@ -892,7 +892,7 @@ function addParent(obj: Stylesheet, parent?: Stylesheet) {
addParent(v, childParent);
});
} else if (value && typeof value === 'object') {
addParent((value as unknown) as Stylesheet, childParent);
addParent(value as Stylesheet, childParent);
}
}

View File

@@ -4,11 +4,9 @@ import {
NodeType,
tagMap,
elementNode,
idNodeMap,
INode,
BuildCache,
} from './types';
import { isElement } from './utils';
import { isElement, Mirror } from './utils';
const tagMap: tagMap = {
script: 'noscript',
@@ -215,7 +213,10 @@ function buildNode(
n.attributes.rr_dataURL
) {
// backup original img srcset
node.setAttribute('rrweb-original-srcset', n.attributes.srcset as string);
node.setAttribute(
'rrweb-original-srcset',
n.attributes.srcset as string,
);
} else {
node.setAttribute(name, value);
}
@@ -307,16 +308,16 @@ export function buildNodeWithSN(
n: serializedNodeWithId,
options: {
doc: Document;
map: idNodeMap;
mirror: Mirror;
skipChild?: boolean;
hackCss: boolean;
afterAppend?: (n: INode) => unknown;
afterAppend?: (n: Node) => unknown;
cache: BuildCache;
},
): INode | null {
): Node | null {
const {
doc,
map,
mirror,
skipChild = false,
hackCss = true,
afterAppend,
@@ -328,7 +329,7 @@ export function buildNodeWithSN(
}
if (n.rootId) {
console.assert(
((map[n.rootId] as unknown) as Document) === doc,
(mirror.getNode(n.rootId) as Document) === doc,
'Target document should has the same root id.',
);
}
@@ -362,8 +363,7 @@ export function buildNodeWithSN(
node = doc;
}
(node as INode).__sn = n;
map[n.id] = node as INode;
mirror.add(node, n);
if (
(n.type === NodeType.Document || n.type === NodeType.Element) &&
@@ -372,7 +372,7 @@ export function buildNodeWithSN(
for (const childN of n.childNodes) {
const childNode = buildNodeWithSN(childN, {
doc,
map,
mirror,
skipChild: false,
hackCss,
afterAppend,
@@ -394,27 +394,27 @@ export function buildNodeWithSN(
}
}
return node as INode;
return node;
}
function visit(idNodeMap: idNodeMap, onVisit: (node: INode) => void) {
function walk(node: INode) {
function visit(mirror: Mirror, onVisit: (node: Node) => void) {
function walk(node: Node) {
onVisit(node);
}
for (const key in idNodeMap) {
if (idNodeMap[key]) {
walk(idNodeMap[key]);
for (const id of mirror.getIds()) {
if (mirror.has(id)) {
walk(mirror.getNode(id)!);
}
}
}
function handleScroll(node: INode) {
const n = node.__sn;
if (n.type !== NodeType.Element) {
function handleScroll(node: Node, mirror: Mirror) {
const n = mirror.getMeta(node);
if (n?.type !== NodeType.Element) {
return;
}
const el = (node as Node) as HTMLElement;
const el = node as HTMLElement;
for (const name in n.attributes) {
if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {
continue;
@@ -433,29 +433,36 @@ function rebuild(
n: serializedNodeWithId,
options: {
doc: Document;
onVisit?: (node: INode) => unknown;
onVisit?: (node: Node) => unknown;
hackCss?: boolean;
afterAppend?: (n: INode) => unknown;
afterAppend?: (n: Node) => unknown;
cache: BuildCache;
mirror: Mirror;
},
): [Node | null, idNodeMap] {
const { doc, onVisit, hackCss = true, afterAppend, cache } = options;
const idNodeMap: idNodeMap = {};
): Node | null {
const {
doc,
onVisit,
hackCss = true,
afterAppend,
cache,
mirror = new Mirror(),
} = options;
const node = buildNodeWithSN(n, {
doc,
map: idNodeMap,
mirror,
skipChild: false,
hackCss,
afterAppend,
cache,
});
visit(idNodeMap, (visitedNode) => {
visit(mirror, (visitedNode) => {
if (onVisit) {
onVisit(visitedNode);
}
handleScroll(visitedNode);
handleScroll(visitedNode, mirror);
});
return [node, idNodeMap];
return node;
}
export default rebuild;

View File

@@ -3,8 +3,6 @@ import {
serializedNodeWithId,
NodeType,
attributes,
INode,
idNodeMap,
MaskInputOptions,
SlimDOMOptions,
DataURLOptions,
@@ -14,6 +12,7 @@ import {
ICanvas,
} from './types';
import {
Mirror,
is2DCanvasBlank,
isElement,
isShadowRoot,
@@ -377,6 +376,7 @@ function serializeNode(
n: Node,
options: {
doc: Document;
mirror: Mirror;
blockClass: string | RegExp;
blockSelector: string | null;
maskTextClass: string | RegExp;
@@ -393,6 +393,7 @@ function serializeNode(
): serializedNode | false {
const {
doc,
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -408,8 +409,8 @@ function serializeNode(
} = options;
// Only record root id when document object is not the base document
let rootId: number | undefined;
if (((doc as unknown) as INode).__sn) {
const docId = ((doc as unknown) as INode).__sn.id;
if (mirror.getMeta(doc)) {
const docId = mirror.getId(doc);
rootId = docId === 1 ? undefined : docId;
}
switch (n.nodeType) {
@@ -786,10 +787,10 @@ function slimDOMExcluded(
}
export function serializeNodeWithId(
n: Node | INode,
n: Node,
options: {
doc: Document;
map: idNodeMap;
mirror: Mirror;
blockClass: string | RegExp;
blockSelector: string | null;
maskTextClass: string | RegExp;
@@ -805,14 +806,17 @@ export function serializeNodeWithId(
inlineImages?: boolean;
recordCanvas?: boolean;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
onSerialize?: (n: Node) => unknown;
onIframeLoad?: (
iframeNode: HTMLIFrameElement,
node: serializedNodeWithId,
) => unknown;
iframeLoadTimeout?: number;
},
): serializedNodeWithId | null {
const {
doc,
map,
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -834,6 +838,7 @@ export function serializeNodeWithId(
let { preserveWhiteSpace = true } = options;
const _serializedNode = serializeNode(n, {
doc,
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -853,10 +858,10 @@ export function serializeNodeWithId(
return null;
}
let id;
// Try to reuse the previous id
if ('__sn' in n) {
id = n.__sn.id;
let id: number | undefined;
if (mirror.hasNode(n)) {
// Reuse the previous id
id = mirror.getId(n);
} else if (
slimDOMExcluded(_serializedNode, slimDOMOptions) ||
(!preserveWhiteSpace &&
@@ -868,14 +873,16 @@ export function serializeNodeWithId(
} else {
id = genId();
}
const serializedNode = Object.assign(_serializedNode, { id });
(n as INode).__sn = serializedNode;
if (id === IGNORED_NODE) {
return null; // slimDOM
}
map[id] = n as INode;
const serializedNode = Object.assign(_serializedNode, { id });
mirror.add(n, serializedNode);
if (onSerialize) {
onSerialize(n as INode);
onSerialize(n);
}
let recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) {
@@ -891,15 +898,15 @@ export function serializeNodeWithId(
) {
if (
slimDOMOptions.headWhitespace &&
_serializedNode.type === NodeType.Element &&
_serializedNode.tagName === 'head'
serializedNode.type === NodeType.Element &&
serializedNode.tagName === 'head'
// would impede performance: || getComputedStyle(n)['white-space'] === 'normal'
) {
preserveWhiteSpace = false;
}
const bypassOptions = {
doc,
map,
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -952,7 +959,7 @@ export function serializeNodeWithId(
if (iframeDoc && onIframeLoad) {
const serializedIframeNode = serializeNodeWithId(iframeDoc, {
doc: iframeDoc,
map,
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -974,7 +981,7 @@ export function serializeNodeWithId(
});
if (serializedIframeNode) {
onIframeLoad(n as INode, serializedIframeNode);
onIframeLoad(n as HTMLIFrameElement, serializedIframeNode);
}
}
},
@@ -988,6 +995,7 @@ export function serializeNodeWithId(
function snapshot(
n: Document,
options?: {
mirror?: Mirror;
blockClass?: string | RegExp;
blockSelector?: string | null;
maskTextClass?: string | RegExp;
@@ -1001,13 +1009,17 @@ function snapshot(
inlineImages?: boolean;
recordCanvas?: boolean;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
onSerialize?: (n: Node) => unknown;
onIframeLoad?: (
iframeNode: HTMLIFrameElement,
node: serializedNodeWithId,
) => unknown;
iframeLoadTimeout?: number;
keepIframeSrcFn?: KeepIframeSrcFn;
},
): [serializedNodeWithId | null, idNodeMap] {
): serializedNodeWithId | null {
const {
mirror = new Mirror(),
blockClass = 'rr-block',
blockSelector = null,
maskTextClass = 'rr-mask',
@@ -1026,7 +1038,6 @@ function snapshot(
iframeLoadTimeout,
keepIframeSrcFn = () => false,
} = options || {};
const idNodeMap: idNodeMap = {};
const maskInputOptions: MaskInputOptions =
maskAllInputs === true
? {
@@ -1070,31 +1081,28 @@ function snapshot(
: slimDOM === false
? {}
: slimDOM;
return [
serializeNodeWithId(n, {
doc: n,
map: idNodeMap,
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
keepIframeSrcFn,
}),
idNodeMap,
];
return serializeNodeWithId(n, {
doc: n,
mirror,
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
keepIframeSrcFn,
});
}
export function visitSnapshot(

View File

@@ -67,6 +67,7 @@ export type tagMap = {
[key: string]: string;
};
// @deprecated
export interface INode extends Node {
__sn: serializedNodeWithId;
}
@@ -75,9 +76,9 @@ export interface ICanvas extends HTMLCanvasElement {
__context: string;
}
export type idNodeMap = {
[key: number]: INode;
};
export type idNodeMap = Map<number, Node>;
export type nodeMetaMap = WeakMap<Node, serializedNodeWithId>;
export type MaskInputOptions = Partial<{
color: boolean;

View File

@@ -1,6 +1,12 @@
import { INode, MaskInputFn, MaskInputOptions } from './types';
import {
idNodeMap,
MaskInputFn,
MaskInputOptions,
nodeMetaMap,
serializedNodeWithId,
} from './types';
export function isElement(n: Node | INode): n is Element {
export function isElement(n: Node): n is Element {
return n.nodeType === n.ELEMENT_NODE;
}
@@ -9,6 +15,69 @@ export function isShadowRoot(n: Node): n is ShadowRoot {
return Boolean(host && host.shadowRoot && host.shadowRoot === n);
}
export class Mirror {
private idNodeMap: idNodeMap = new Map();
private nodeMetaMap: nodeMetaMap = new WeakMap();
getId(n: Node | undefined | null): number {
if (!n) return -1;
const id = this.getMeta(n)?.id;
// if n is not a serialized Node, use -1 as its id.
return id ?? -1;
}
getNode(id: number): Node | null {
return this.idNodeMap.get(id) || null;
}
getIds(): number[] {
return Array.from(this.idNodeMap.keys());
}
getMeta(n: Node): serializedNodeWithId | null {
return this.nodeMetaMap.get(n) || null;
}
// removes the node from idNodeMap
// doesn't remove the node from nodeMetaMap
removeNodeFromMap(n: Node) {
const id = this.getId(n);
this.idNodeMap.delete(id);
if (n.childNodes) {
n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));
}
}
has(id: number): boolean {
return this.idNodeMap.has(id);
}
hasNode(node: Node): boolean {
return this.nodeMetaMap.has(node);
}
add(n: Node, meta: serializedNodeWithId) {
const id = meta.id;
this.idNodeMap.set(id, n);
this.nodeMetaMap.set(n, meta);
}
replace(id: number, n: Node) {
this.idNodeMap.set(id, n);
}
reset() {
this.idNodeMap = new Map();
this.nodeMetaMap = new WeakMap();
}
}
export function createMirror(): Mirror {
return new Mirror();
}
export function maskInputValue({
maskInputOptions,
tagName,

View File

@@ -131,8 +131,8 @@ describe('integration tests', function (this: ISuite) {
const rebuildHtml = (
await page.evaluate(`${code}
const x = new XMLSerializer();
const [snap] = rrweb.snapshot(document);
let out = x.serializeToString(rrweb.rebuild(snap, { doc: document })[0]);
const snap = rrweb.snapshot(document);
let out = x.serializeToString(rrweb.rebuild(snap, { doc: document }));
if (document.querySelector('html').getAttribute('xmlns') !== 'http://www.w3.org/1999/xhtml') {
// this is just an artefact of serializeToString
out = out.replace(' xmlns=\"http://www.w3.org/1999/xhtml\"', '');
@@ -168,7 +168,7 @@ describe('integration tests', function (this: ISuite) {
`pre-check: images will be rendered ~326px high in BackCompat mode, and ~588px in CSS1Compat mode; getting: ${renderedHeight}px`,
);
const rebuildRenderedHeight = await page.evaluate(`${code}
const [snap] = rrweb.snapshot(document);
const snap = rrweb.snapshot(document);
const iframe = document.createElement('iframe');
iframe.setAttribute('width', document.body.clientWidth)
iframe.setAttribute('height', document.body.clientHeight)
@@ -205,9 +205,7 @@ iframe.contentDocument.querySelector('center').clientHeight
inlineStylesheet: false
})`);
await page.waitFor(100);
const snapshot = await page.evaluate(
'JSON.stringify(snapshot[0], null, 2);',
);
const snapshot = await page.evaluate('JSON.stringify(snapshot, null, 2);');
assert(snapshot.includes('"rr_dataURL"'));
assert(snapshot.includes('data:image/webp;base64,'));
});
@@ -253,7 +251,7 @@ describe('iframe integration tests', function (this: ISuite) {
});
const snapshotResult = JSON.stringify(
await page.evaluate(`${code};
rrweb.snapshot(document)[0];
rrweb.snapshot(document);
`),
null,
2,
@@ -302,7 +300,7 @@ describe('shadow DOM integration tests', function (this: ISuite) {
});
const snapshotResult = JSON.stringify(
await page.evaluate(`${code};
rrweb.snapshot(document)[0];
rrweb.snapshot(document);
`),
null,
2,

View File

@@ -8,6 +8,7 @@ import {
_isBlockedElement,
} from '../src/snapshot';
import { serializedNodeWithId } from '../src/types';
import { Mirror } from '../src/utils';
describe('absolute url to stylesheet', () => {
const href = 'http://localhost/css/style.css';
@@ -139,7 +140,7 @@ describe('style elements', () => {
const serializeNode = (node: Node): serializedNodeWithId | null => {
return serializeNodeWithId(node, {
doc: document,
map: {},
mirror: new Mirror(),
blockClass: 'blockblock',
blockSelector: null,
maskTextClass: 'maskmask',

View File

@@ -1,19 +1,21 @@
import { serializedNodeWithId, idNodeMap, INode, BuildCache } from './types';
import { serializedNodeWithId, BuildCache } from './types';
import { Mirror } from './utils';
export declare function addHoverClass(cssText: string, cache: BuildCache): string;
export declare function createCache(): BuildCache;
export declare function buildNodeWithSN(n: serializedNodeWithId, options: {
doc: Document;
map: idNodeMap;
mirror: Mirror;
skipChild?: boolean;
hackCss: boolean;
afterAppend?: (n: INode) => unknown;
afterAppend?: (n: Node) => unknown;
cache: BuildCache;
}): INode | null;
}): Node | null;
declare function rebuild(n: serializedNodeWithId, options: {
doc: Document;
onVisit?: (node: INode) => unknown;
onVisit?: (node: Node) => unknown;
hackCss?: boolean;
afterAppend?: (n: INode) => unknown;
afterAppend?: (n: Node) => unknown;
cache: BuildCache;
}): [Node | null, idNodeMap];
mirror: Mirror;
}): Node | null;
export default rebuild;

View File

@@ -1,13 +1,14 @@
import { serializedNodeWithId, INode, idNodeMap, MaskInputOptions, SlimDOMOptions, DataURLOptions, MaskTextFn, MaskInputFn, KeepIframeSrcFn } from './types';
import { serializedNodeWithId, MaskInputOptions, SlimDOMOptions, DataURLOptions, MaskTextFn, MaskInputFn, KeepIframeSrcFn } from './types';
import { Mirror } from './utils';
export declare const IGNORED_NODE = -2;
export declare function absoluteToStylesheet(cssText: string | null, href: string): string;
export declare function absoluteToDoc(doc: Document, attributeValue: string): string;
export declare function transformAttribute(doc: Document, tagName: string, name: string, value: string): string;
export declare function _isBlockedElement(element: HTMLElement, blockClass: string | RegExp, blockSelector: string | null): boolean;
export declare function needMaskingText(node: Node | null, maskTextClass: string | RegExp, maskTextSelector: string | null): boolean;
export declare function serializeNodeWithId(n: Node | INode, options: {
export declare function serializeNodeWithId(n: Node, options: {
doc: Document;
map: idNodeMap;
mirror: Mirror;
blockClass: string | RegExp;
blockSelector: string | null;
maskTextClass: string | RegExp;
@@ -23,11 +24,12 @@ export declare function serializeNodeWithId(n: Node | INode, options: {
inlineImages?: boolean;
recordCanvas?: boolean;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeNode: HTMLIFrameElement, node: serializedNodeWithId) => unknown;
iframeLoadTimeout?: number;
}): serializedNodeWithId | null;
declare function snapshot(n: Document, options?: {
mirror?: Mirror;
blockClass?: string | RegExp;
blockSelector?: string | null;
maskTextClass?: string | RegExp;
@@ -41,11 +43,11 @@ declare function snapshot(n: Document, options?: {
inlineImages?: boolean;
recordCanvas?: boolean;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeNode: HTMLIFrameElement, node: serializedNodeWithId) => unknown;
iframeLoadTimeout?: number;
keepIframeSrcFn?: KeepIframeSrcFn;
}): [serializedNodeWithId | null, idNodeMap];
}): serializedNodeWithId | null;
export declare function visitSnapshot(node: serializedNodeWithId, onVisit: (node: serializedNodeWithId) => unknown): void;
export declare function cleanupSnapshot(): void;
export default snapshot;

View File

@@ -58,9 +58,8 @@ export interface INode extends Node {
export interface ICanvas extends HTMLCanvasElement {
__context: string;
}
export declare type idNodeMap = {
[key: number]: INode;
};
export declare type idNodeMap = Map<number, Node>;
export declare type nodeMetaMap = WeakMap<Node, serializedNodeWithId>;
export declare type MaskInputOptions = Partial<{
color: boolean;
date: boolean;

View File

@@ -1,6 +1,21 @@
import { INode, MaskInputFn, MaskInputOptions } from './types';
export declare function isElement(n: Node | INode): n is Element;
import { MaskInputFn, MaskInputOptions, serializedNodeWithId } from './types';
export declare function isElement(n: Node): n is Element;
export declare function isShadowRoot(n: Node): n is ShadowRoot;
export declare class Mirror {
private idNodeMap;
private nodeMetaMap;
getId(n: Node | undefined | null): number;
getNode(id: number): Node | null;
getIds(): number[];
getMeta(n: Node): serializedNodeWithId | null;
removeNodeFromMap(n: Node): void;
has(id: number): boolean;
hasNode(node: Node): boolean;
add(n: Node, meta: serializedNodeWithId): void;
replace(id: number, n: Node): void;
reset(): void;
}
export declare function createMirror(): Mirror;
export declare function maskInputValue({ maskInputOptions, tagName, type, value, maskInputFn, }: {
maskInputOptions: MaskInputOptions;
tagName: string;

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, INode } from 'rrweb-snapshot';
import { Mirror, serializedNodeWithId } from 'rrweb-snapshot';
import { mutationCallBack } from '../types';
export class IframeManager {
@@ -18,11 +18,15 @@ export class IframeManager {
this.loadListener = cb;
}
public attachIframe(iframeEl: INode, childSn: serializedNodeWithId) {
public attachIframe(
iframeEl: HTMLIFrameElement,
childSn: serializedNodeWithId,
mirror: Mirror,
) {
this.mutationCb({
adds: [
{
parentId: iframeEl.__sn.id,
parentId: mirror.getId(iframeEl),
nextId: null,
node: childSn,
},
@@ -32,6 +36,6 @@ export class IframeManager {
attributes: [],
isAttachIframe: true,
});
this.loadListener?.((iframeEl as unknown) as HTMLIFrameElement);
this.loadListener?.(iframeEl);
}
}

View File

@@ -1,13 +1,17 @@
import { snapshot, MaskInputOptions, SlimDOMOptions } from 'rrweb-snapshot';
import {
snapshot,
MaskInputOptions,
SlimDOMOptions,
createMirror,
} from 'rrweb-snapshot';
import { initObservers, mutationBuffers } from './observer';
import {
on,
getWindowWidth,
getWindowHeight,
polyfill,
isIframeINode,
hasShadowRoot,
createMirror,
isSerializedIframe,
} from '../utils';
import {
EventType,
@@ -74,6 +78,9 @@ function record<T = eventWithTime>(
sampling.mousemove = mousemoveWait;
}
// reset mirror in case `record` this was called earlier
mirror.reset();
const maskInputOptions: MaskInputOptions =
maskAllInputs === true
? {
@@ -252,7 +259,8 @@ function record<T = eventWithTime>(
);
mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting
const [node, idNodeMap] = snapshot(document, {
const node = snapshot(document, {
mirror,
blockClass,
blockSelector,
maskTextClass,
@@ -264,18 +272,16 @@ function record<T = eventWithTime>(
recordCanvas,
inlineImages,
onSerialize: (n) => {
if (isIframeINode(n)) {
iframeManager.addIframe(n);
if (isSerializedIframe(n, mirror)) {
iframeManager.addIframe(n as HTMLIFrameElement);
}
if (hasShadowRoot(n)) {
shadowDomManager.addShadowRoot(n.shadowRoot, document);
}
},
onIframeLoad: (iframe, childSn) => {
iframeManager.attachIframe(iframe, childSn);
shadowDomManager.observeAttachShadow(
(iframe as Node) as HTMLIFrameElement,
);
iframeManager.attachIframe(iframe, childSn, mirror);
shadowDomManager.observeAttachShadow(iframe);
},
keepIframeSrcFn,
});
@@ -284,7 +290,6 @@ function record<T = eventWithTime>(
return console.warn('Failed to snapshot the document');
}
mirror.map = idNodeMap;
wrappedEmit(
wrapEvent({
type: EventType.FullSnapshot,

View File

@@ -1,11 +1,11 @@
import {
INode,
serializeNodeWithId,
transformAttribute,
IGNORED_NODE,
isShadowRoot,
needMaskingText,
maskInputValue,
Mirror,
} from 'rrweb-snapshot';
import {
mutationRecord,
@@ -13,7 +13,6 @@ import {
attributeCursor,
removedNodeMutation,
addedNodeMutation,
Mirror,
styleAttributeValue,
observerParam,
MutationBufferParam,
@@ -23,8 +22,8 @@ import {
isBlocked,
isAncestorRemoved,
isIgnored,
isIframeINode,
hasShadowRoot,
isSerializedIframe,
} from '../utils';
type DoubleLinkedListNode = {
@@ -39,6 +38,7 @@ type NodeInLinkedList = Node & {
function isNodeInLinkedList(n: Node | NodeInLinkedList): n is NodeInLinkedList {
return '__ln' in n;
}
class DoubleLinkedList {
public length = 0;
public head: DoubleLinkedListNode | null = null;
@@ -117,9 +117,6 @@ class DoubleLinkedList {
}
const moveKey = (id: number, parentId: number) => `${id}@${parentId}`;
function isINode(n: Node | INode): n is INode {
return '__sn' in n;
}
/**
* controls behaviour of a MutationObserver
@@ -255,7 +252,7 @@ export default class MutationBuffer {
let nextId: number | null = IGNORED_NODE; // slimDOM: ignored
while (nextId === IGNORED_NODE) {
ns = ns && ns.nextSibling;
nextId = ns && this.mirror.getId((ns as unknown) as INode);
nextId = ns && this.mirror.getId(ns);
}
return nextId;
};
@@ -277,15 +274,15 @@ export default class MutationBuffer {
return;
}
const parentId = isShadowRoot(n.parentNode)
? this.mirror.getId((shadowHost as unknown) as INode)
: this.mirror.getId((n.parentNode as Node) as INode);
? this.mirror.getId(shadowHost)
: this.mirror.getId(n.parentNode);
const nextId = getNextId(n);
if (parentId === -1 || nextId === -1) {
return addList.addNode(n);
}
let sn = serializeNodeWithId(n, {
doc: this.doc,
map: this.mirror.map,
mirror: this.mirror,
blockClass: this.blockClass,
blockSelector: this.blockSelector,
maskTextClass: this.maskTextClass,
@@ -299,7 +296,7 @@ export default class MutationBuffer {
recordCanvas: this.recordCanvas,
inlineImages: this.inlineImages,
onSerialize: (currentN) => {
if (isIframeINode(currentN)) {
if (isSerializedIframe(currentN, this.mirror)) {
this.iframeManager.addIframe(currentN);
}
if (hasShadowRoot(n)) {
@@ -307,10 +304,8 @@ export default class MutationBuffer {
}
},
onIframeLoad: (iframe, childSn) => {
this.iframeManager.attachIframe(iframe, childSn);
this.shadowDomManager.observeAttachShadow(
(iframe as Node) as HTMLIFrameElement,
);
this.iframeManager.attachIframe(iframe, childSn, this.mirror);
this.shadowDomManager.observeAttachShadow(iframe);
},
});
if (sn) {
@@ -323,7 +318,7 @@ export default class MutationBuffer {
};
while (this.mapRemoves.length) {
this.mirror.removeNodeFromMap(this.mapRemoves.shift() as INode);
this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);
}
for (const n of this.movedSet) {
@@ -353,9 +348,7 @@ export default class MutationBuffer {
while (addList.length) {
let node: DoubleLinkedListNode | null = null;
if (candidate) {
const parentId = this.mirror.getId(
(candidate.value.parentNode as Node) as INode,
);
const parentId = this.mirror.getId(candidate.value.parentNode);
const nextId = getNextId(candidate.value);
if (parentId !== -1 && nextId !== -1) {
node = candidate;
@@ -366,9 +359,7 @@ export default class MutationBuffer {
const _node = addList.get(index)!;
// ensure _node is defined before attempting to find value
if (_node) {
const parentId = this.mirror.getId(
(_node.value.parentNode as Node) as INode,
);
const parentId = this.mirror.getId(_node.value.parentNode);
const nextId = getNextId(_node.value);
if (parentId !== -1 && nextId !== -1) {
node = _node;
@@ -396,14 +387,14 @@ export default class MutationBuffer {
const payload = {
texts: this.texts
.map((text) => ({
id: this.mirror.getId(text.node as INode),
id: this.mirror.getId(text.node),
value: text.value,
}))
// text mutation's id was not in the mirror map means the target node has been removed
.filter((text) => this.mirror.has(text.id)),
attributes: this.attributes
.map((attribute) => ({
id: this.mirror.getId(attribute.node as INode),
id: this.mirror.getId(attribute.node),
attributes: attribute.attributes,
}))
// attribute mutation's id was not in the mirror map means the target node has been removed
@@ -434,7 +425,7 @@ export default class MutationBuffer {
};
private processMutation = (m: mutationRecord) => {
if (isIgnored(m.target)) {
if (isIgnored(m.target, this.mirror)) {
return;
}
switch (m.type) {
@@ -528,11 +519,14 @@ export default class MutationBuffer {
case 'childList': {
m.addedNodes.forEach((n) => this.genAdds(n, m.target));
m.removedNodes.forEach((n) => {
const nodeId = this.mirror.getId(n as INode);
const nodeId = this.mirror.getId(n);
const parentId = isShadowRoot(m.target)
? this.mirror.getId((m.target.host as unknown) as INode)
: this.mirror.getId(m.target as INode);
if (isBlocked(m.target, this.blockClass) || isIgnored(n)) {
? this.mirror.getId(m.target.host)
: this.mirror.getId(m.target);
if (
isBlocked(m.target, this.blockClass) ||
isIgnored(n, this.mirror)
) {
return;
}
// removed node has not been serialized yet, just remove it from the Set
@@ -547,7 +541,7 @@ export default class MutationBuffer {
* newly added node will be serialized without child nodes.
* TODO: verify this
*/
} else if (isAncestorRemoved(m.target as INode, this.mirror)) {
} else if (isAncestorRemoved(m.target, this.mirror)) {
/**
* If parent id was not in the mirror map any more, it
* means the parent node has already been removed. So
@@ -575,22 +569,23 @@ export default class MutationBuffer {
}
};
private genAdds = (n: Node | INode, target?: Node | INode) => {
private genAdds = (n: Node, target?: Node) => {
// parent was blocked, so we can ignore this node
if (target && isBlocked(target, this.blockClass)) {
return;
}
if (isINode(n)) {
if (isIgnored(n)) {
if (this.mirror.getMeta(n)) {
if (isIgnored(n, this.mirror)) {
return;
}
this.movedSet.add(n);
let targetId: number | null = null;
if (target && isINode(target)) {
targetId = target.__sn.id;
if (target && this.mirror.getMeta(target)) {
targetId = this.mirror.getId(target);
}
if (targetId) {
this.movedMap[moveKey(n.__sn.id, targetId)] = true;
if (targetId && targetId !== -1) {
this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
}
} else {
this.addedSet.add(n);
@@ -600,7 +595,7 @@ export default class MutationBuffer {
// if this node is blocked `serializeNode` will turn it into a placeholder element
// but we have to remove it's children otherwise they will be added as placeholders too
if (!isBlocked(n, this.blockClass))
n.childNodes.forEach((childN) => this.genAdds(childN));
(n as Node).childNodes.forEach((childN) => this.genAdds(childN));
};
}
@@ -624,7 +619,7 @@ function isParentRemoved(
if (!parentNode) {
return false;
}
const parentId = mirror.getId((parentNode as Node) as INode);
const parentId = mirror.getId(parentNode);
if (removes.some((r) => r.id === parentId)) {
return true;
}

View File

@@ -1,4 +1,4 @@
import { INode, MaskInputOptions, maskInputValue } from 'rrweb-snapshot';
import { MaskInputOptions, maskInputValue } from 'rrweb-snapshot';
import { FontFaceSet } from 'css-font-loading-module';
import {
throttle,
@@ -173,7 +173,7 @@ function initMoveObserver({
positions.push({
x: clientX,
y: clientY,
id: mirror.getId(target as INode),
id: mirror.getId(target as Node),
timeOffset: Date.now() - timeBaseline,
});
// it is possible DragEvent is undefined even on devices
@@ -221,14 +221,14 @@ function initMouseInteractionObserver({
const getHandler = (eventKey: keyof typeof MouseInteractions) => {
return (event: MouseEvent | TouchEvent) => {
const target = getEventTarget(event) as Node;
if (isBlocked(target as Node, blockClass)) {
if (isBlocked(target, blockClass)) {
return;
}
const e = isTouchEvent(event) ? event.changedTouches[0] : event;
if (!e) {
return;
}
const id = mirror.getId(target as INode);
const id = mirror.getId(target);
const { clientX, clientY } = e;
mouseInteractionCb({
type: MouseInteractions[eventKey],
@@ -270,7 +270,7 @@ export function initScrollObserver({
if (!target || isBlocked(target as Node, blockClass)) {
return;
}
const id = mirror.getId(target as INode);
const id = mirror.getId(target as Node);
if (target === doc) {
const scrollEl = (doc.scrollingElement || doc.documentElement)!;
scrollCb({
@@ -408,7 +408,7 @@ function initInputObserver({
lastInputValue.isChecked !== v.isChecked
) {
lastInputValueMap.set(target, v);
const id = mirror.getId(target as INode);
const id = mirror.getId(target as Node);
inputCb({
...v,
id,
@@ -497,7 +497,7 @@ function initStyleSheetObserver(
rule: string,
index?: number,
) {
const id = mirror.getId(this.ownerNode as INode);
const id = mirror.getId(this.ownerNode);
if (id !== -1) {
styleSheetRuleCb({
id,
@@ -509,7 +509,7 @@ function initStyleSheetObserver(
const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
win.CSSStyleSheet.prototype.deleteRule = function (index: number) {
const id = mirror.getId(this.ownerNode as INode);
const id = mirror.getId(this.ownerNode);
if (id !== -1) {
styleSheetRuleCb({
id,
@@ -554,7 +554,7 @@ function initStyleSheetObserver(
};
type.prototype.insertRule = function (rule: string, index?: number) {
const id = mirror.getId(this.parentStyleSheet.ownerNode as INode);
const id = mirror.getId(this.parentStyleSheet.ownerNode);
if (id !== -1) {
styleSheetRuleCb({
id,
@@ -573,7 +573,7 @@ function initStyleSheetObserver(
};
type.prototype.deleteRule = function (index: number) {
const id = mirror.getId(this.parentStyleSheet.ownerNode as INode);
const id = mirror.getId(this.parentStyleSheet.ownerNode);
if (id !== -1) {
styleSheetRuleCb({
id,
@@ -605,9 +605,7 @@ function initStyleDeclarationObserver(
value: string,
priority: string,
) {
const id = mirror.getId(
(this.parentRule?.parentStyleSheet?.ownerNode as unknown) as INode,
);
const id = mirror.getId(this.parentRule?.parentStyleSheet?.ownerNode);
if (id !== -1) {
styleDeclarationCb({
id,
@@ -627,9 +625,7 @@ function initStyleDeclarationObserver(
this: CSSStyleDeclaration,
property: string,
) {
const id = mirror.getId(
(this.parentRule?.parentStyleSheet?.ownerNode as unknown) as INode,
);
const id = mirror.getId(this.parentRule?.parentStyleSheet?.ownerNode);
if (id !== -1) {
styleDeclarationCb({
id,
@@ -663,7 +659,7 @@ function initMediaInteractionObserver({
const { currentTime, volume, muted } = target as HTMLMediaElement;
mediaInteractionCb({
type,
id: mirror.getId(target as INode),
id: mirror.getId(target as Node),
currentTime,
volume,
muted,

View File

@@ -1,11 +1,10 @@
import { INode } from 'rrweb-snapshot';
import { Mirror } from 'rrweb-snapshot';
import {
blockClass,
CanvasContext,
canvasManagerMutationCallback,
IWindow,
listenerHandler,
Mirror,
} from '../../../types';
import { hookSetter, isBlocked, patch } from '../../../utils';
@@ -36,7 +35,7 @@ export default function initCanvas2DMutationObserver(
this: CanvasRenderingContext2D,
...args: Array<unknown>
) {
if (!isBlocked((this.canvas as unknown) as INode, blockClass)) {
if (!isBlocked(this.canvas, blockClass)) {
// Using setTimeout as getImageData + JSON.stringify can be heavy
// and we'd rather not block the main thread
setTimeout(() => {

View File

@@ -1,4 +1,4 @@
import { INode } from 'rrweb-snapshot';
import { Mirror } from 'rrweb-snapshot';
import {
blockClass,
canvasManagerMutationCallback,
@@ -7,7 +7,6 @@ import {
canvasMutationWithType,
IWindow,
listenerHandler,
Mirror,
} from '../../../types';
import initCanvas2DMutationObserver from './2d';
import initCanvasContextObserver from './canvas';
@@ -126,7 +125,7 @@ export class CanvasManager {
flushPendingCanvasMutations() {
this.pendingCanvasMutations.forEach(
(values: canvasMutationCommand[], canvas: HTMLCanvasElement) => {
const id = this.mirror.getId((canvas as unknown) as INode);
const id = this.mirror.getId(canvas);
this.flushPendingCanvasMutationFor(canvas, id);
},
);

View File

@@ -1,4 +1,4 @@
import { INode, ICanvas } from 'rrweb-snapshot';
import { ICanvas } from 'rrweb-snapshot';
import { blockClass, IWindow, listenerHandler } from '../../../types';
import { isBlocked, patch } from '../../../utils';
@@ -17,7 +17,7 @@ export default function initCanvasContextObserver(
contextType: string,
...args: Array<unknown>
) {
if (!isBlocked((this as unknown) as INode, blockClass)) {
if (!isBlocked(this, blockClass)) {
if (!('__context' in this))
(this as ICanvas).__context = contextType;
}

View File

@@ -1,4 +1,4 @@
import { INode } from 'rrweb-snapshot';
import { Mirror } from 'rrweb-snapshot';
import {
blockClass,
CanvasContext,
@@ -6,7 +6,6 @@ import {
canvasMutationWithType,
IWindow,
listenerHandler,
Mirror,
} from '../../../types';
import { hookSetter, isBlocked, patch } from '../../../utils';
import { saveWebGLVar, serializeArgs } from './serialize-args';
@@ -32,8 +31,8 @@ function patchGLPrototype(
return function (this: typeof prototype, ...args: Array<unknown>) {
const result = original.apply(this, args);
saveWebGLVar(result, win, prototype);
if (!isBlocked((this.canvas as unknown) as INode, blockClass)) {
const id = mirror.getId((this.canvas as unknown) as INode);
if (!isBlocked(this.canvas, blockClass)) {
const id = mirror.getId(this.canvas);
const recordArgs = serializeArgs([...args], win, prototype);
const mutation: canvasMutationWithType = {

View File

@@ -1,12 +1,12 @@
import {
mutationCallBack,
Mirror,
scrollCallback,
MutationBufferParam,
SamplingStrategy,
} from '../types';
import { initMutationObserver, initScrollObserver } from './observer';
import { patch } from '../utils';
import { Mirror } from 'rrweb-snapshot';
type BypassOptions = Omit<
MutationBufferParam,

View File

@@ -15,7 +15,7 @@ export default function canvasMutation({
errorHandler: Replayer['warnCanvasMutationFailed'];
}): void {
try {
const ctx = ((target as unknown) as HTMLCanvasElement).getContext('2d')!;
const ctx = target.getContext('2d')!;
if (mutation.setter) {
// skip some read-only type checks

View File

@@ -1,10 +1,11 @@
import {
rebuild,
buildNodeWithSN,
INode,
NodeType,
BuildCache,
createCache,
Mirror,
createMirror,
} from 'rrweb-snapshot';
import * as mittProxy from 'mitt';
import { polyfill as smoothscrollPolyfill } from './smoothscroll';
@@ -33,7 +34,6 @@ import {
scrollData,
inputData,
canvasMutationData,
Mirror,
ElementState,
styleAttributeValue,
styleValueWithPriority,
@@ -43,15 +43,14 @@ import {
textMutation,
} from '../types';
import {
createMirror,
polyfill,
TreeIndex,
queueToResolveTrees,
iterateResolveTree,
AppendedIframe,
isIframeINode,
getBaseDimension,
hasShadowRoot,
isSerializedIframe,
} from '../utils';
import getInjectStyleRules from './styles/inject-style';
import './styles/style.css';
@@ -115,8 +114,8 @@ export class Replayer {
private legacy_missingNodeRetryMap: missingNodeMap = {};
private treeIndex!: TreeIndex;
private fragmentParentMap!: Map<INode, INode>;
private elementStateMap!: Map<INode, ElementState>;
private fragmentParentMap!: Map<Node, Node>;
private elementStateMap!: Map<Node, ElementState>;
// Hold the list of CSSRules for in-memory state restoration
private virtualStyleRulesMap!: VirtualStyleRulesMap;
@@ -167,8 +166,8 @@ export class Replayer {
this.setupDom();
this.treeIndex = new TreeIndex();
this.fragmentParentMap = new Map<INode, INode>();
this.elementStateMap = new Map<INode, ElementState>();
this.fragmentParentMap = new Map<Node, Node>();
this.elementStateMap = new Map<Node, ElementState>();
this.virtualStyleRulesMap = new Map();
this.emitter.on(ReplayerEvents.Flush, () => {
@@ -657,13 +656,14 @@ export class Replayer {
}
this.legacy_missingNodeRetryMap = {};
const collected: AppendedIframe[] = [];
this.mirror.map = rebuild(event.data.node, {
rebuild(event.data.node, {
doc: this.iframe.contentDocument,
afterAppend: (builtNode) => {
this.collectIframeAndAttachDocument(collected, builtNode);
},
cache: this.cache,
})[1];
mirror: this.mirror,
});
for (const { mutationInQueue, builtNode } of collected) {
this.attachDocumentToIframe(mutationInQueue, builtNode);
this.newDocumentQueue = this.newDocumentQueue.filter(
@@ -715,8 +715,8 @@ export class Replayer {
let parent = iframeEl.parentNode;
while (parent) {
// The parent of iframeEl is virtual parent and we need to mount it on the dom.
if (this.fragmentParentMap.has((parent as unknown) as INode)) {
const frag = (parent as unknown) as INode;
if (this.fragmentParentMap.has(parent)) {
const frag = parent;
const realParent = this.fragmentParentMap.get(frag)!;
this.restoreRealParent(frag, realParent);
break;
@@ -726,14 +726,15 @@ export class Replayer {
}
buildNodeWithSN(mutation.node, {
doc: iframeEl.contentDocument!,
map: this.mirror.map,
mirror: this.mirror,
hackCss: true,
skipChild: false,
afterAppend: (builtNode) => {
this.collectIframeAndAttachDocument(collected, builtNode);
const sn = this.mirror.getMeta(builtNode);
if (
builtNode.__sn.type === NodeType.Element &&
builtNode.__sn.tagName.toUpperCase() === 'HTML'
sn?.type === NodeType.Element &&
sn?.tagName.toUpperCase() === 'HTML'
) {
const { documentElement, head } = iframeEl.contentDocument!;
this.insertStyleRules(documentElement, head);
@@ -751,11 +752,11 @@ export class Replayer {
private collectIframeAndAttachDocument(
collected: AppendedIframe[],
builtNode: INode,
builtNode: Node,
) {
if (isIframeINode(builtNode)) {
if (isSerializedIframe(builtNode, this.mirror)) {
const mutationInQueue = this.newDocumentQueue.find(
(m) => m.parentId === builtNode.__sn.id,
(m) => m.parentId === this.mirror.getId(builtNode),
);
if (mutationInQueue) {
collected.push({ mutationInQueue, builtNode });
@@ -905,7 +906,7 @@ export class Replayer {
d.adds.forEach((m) => this.treeIndex.add(m));
d.texts.forEach((m) => {
const target = this.mirror.getNode(m.id);
const parent = (target?.parentNode as unknown) as INode | null;
const parent = target?.parentNode;
// remove any style rules that pending
// for stylesheets where the contents get replaced
if (parent && this.virtualStyleRulesMap.has(parent))
@@ -973,13 +974,13 @@ export class Replayer {
const { triggerFocus } = this.config;
switch (d.type) {
case MouseInteractions.Blur:
if ('blur' in ((target as Node) as HTMLElement)) {
((target as Node) as HTMLElement).blur();
if ('blur' in (target as HTMLElement)) {
(target as HTMLElement).blur();
}
break;
case MouseInteractions.Focus:
if (triggerFocus && ((target as Node) as HTMLElement).focus) {
((target as Node) as HTMLElement).focus({
if (triggerFocus && (target as HTMLElement).focus) {
(target as HTMLElement).focus({
preventScroll: true,
});
}
@@ -1080,7 +1081,7 @@ export class Replayer {
if (!target) {
return this.debugNodeNotFound(d, d.id);
}
const mediaEl = (target as Node) as HTMLMediaElement;
const mediaEl = target as HTMLMediaElement;
try {
if (d.currentTime) {
mediaEl.currentTime = d.currentTime;
@@ -1116,8 +1117,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id);
}
const styleEl = (target as Node) as HTMLStyleElement;
const parent = (target.parentNode as unknown) as INode;
const styleEl = target as HTMLStyleElement;
const parent = target.parentNode!;
const usingVirtualParent = this.fragmentParentMap.has(parent);
/**
@@ -1218,8 +1219,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id);
}
const styleEl = (target as Node) as HTMLStyleElement;
const parent = (target.parentNode as unknown) as INode;
const styleEl = target as HTMLStyleElement;
const parent = target.parentNode!;
const usingVirtualParent = this.fragmentParentMap.has(parent);
const styleSheet = usingVirtualParent ? null : styleEl.sheet;
@@ -1279,7 +1280,7 @@ export class Replayer {
canvasMutation({
event: e,
mutation: d,
target: (target as unknown) as HTMLCanvasElement,
target: target as HTMLCanvasElement,
imageMap: this.imageMap,
errorHandler: this.warnCanvasMutationFailed.bind(this),
});
@@ -1318,7 +1319,7 @@ export class Replayer {
if (this.virtualStyleRulesMap.has(target)) {
this.virtualStyleRulesMap.delete(target);
}
let parent: INode | null | ShadowRoot = this.mirror.getNode(
let parent: Node | null | ShadowRoot = this.mirror.getNode(
mutation.parentId,
);
if (!parent) {
@@ -1331,8 +1332,9 @@ export class Replayer {
this.mirror.removeNodeFromMap(target);
if (parent) {
let realTarget = null;
const realParent =
'__sn' in parent ? this.fragmentParentMap.get(parent) : undefined;
const realParent = this.mirror.getMeta(parent)
? this.fragmentParentMap.get(parent)
: undefined;
if (realParent && realParent.contains(target)) {
parent = realParent;
} else if (this.fragmentParentMap.has(target)) {
@@ -1373,7 +1375,7 @@ export class Replayer {
const nextNotInDOM = (mutation: addedNodeMutation) => {
let next: Node | null = null;
if (mutation.nextId) {
next = this.mirror.getNode(mutation.nextId) as Node;
next = this.mirror.getNode(mutation.nextId);
}
// next not present at this moment
if (
@@ -1391,7 +1393,7 @@ export class Replayer {
if (!this.iframe.contentDocument) {
return console.warn('Looks like your replayer has been destroyed.');
}
let parent: INode | null | ShadowRoot = this.mirror.getNode(
let parent: Node | null | ShadowRoot = this.mirror.getNode(
mutation.parentId,
);
if (!parent) {
@@ -1412,20 +1414,19 @@ export class Replayer {
}
const hasIframeChild =
((parent as unknown) as HTMLElement).getElementsByTagName?.('iframe')
.length > 0;
(parent as HTMLElement).getElementsByTagName?.('iframe').length > 0;
/**
* Why !isIframeINode(parent)? If parent element is an iframe, iframe document can't be appended to virtual parent.
* Why !isSerializedIframe(parent)? If parent element is an iframe, iframe document can't be appended to virtual parent.
* Why !hasIframeChild? If we move iframe elements from dom to fragment document, we will lose the contentDocument of iframe. So we need to disable the virtual dom optimization if a parent node contains iframe elements.
*/
if (
useVirtualParent &&
parentInDocument &&
!isIframeINode(parent) &&
!isSerializedIframe(parent, this.mirror) &&
!hasIframeChild
) {
const virtualParent = (document.createDocumentFragment() as unknown) as INode;
this.mirror.map[mutation.parentId] = virtualParent;
const virtualParent = document.createDocumentFragment();
this.mirror.replace(mutation.parentId, virtualParent);
this.fragmentParentMap.set(virtualParent, parent);
// store the state, like scroll position, of child nodes before they are unmounted from dom
@@ -1440,18 +1441,18 @@ export class Replayer {
if (mutation.node.isShadow) {
// If the parent is attached a shadow dom after it's created, it won't have a shadow root.
if (!hasShadowRoot(parent)) {
((parent as Node) as HTMLElement).attachShadow({ mode: 'open' });
parent = ((parent as Node) as HTMLElement).shadowRoot!;
(parent as HTMLElement).attachShadow({ mode: 'open' });
parent = (parent as HTMLElement).shadowRoot!;
} else parent = parent.shadowRoot;
}
let previous: Node | null = null;
let next: Node | null = null;
if (mutation.previousId) {
previous = this.mirror.getNode(mutation.previousId) as Node;
previous = this.mirror.getNode(mutation.previousId);
}
if (mutation.nextId) {
next = this.mirror.getNode(mutation.nextId) as Node;
next = this.mirror.getNode(mutation.nextId);
}
if (nextNotInDOM(mutation)) {
return queue.push(mutation);
@@ -1464,17 +1465,17 @@ export class Replayer {
const targetDoc = mutation.node.rootId
? this.mirror.getNode(mutation.node.rootId)
: this.iframe.contentDocument;
if (isIframeINode(parent)) {
if (isSerializedIframe(parent, this.mirror)) {
this.attachDocumentToIframe(mutation, parent);
return;
}
const target = buildNodeWithSN(mutation.node, {
doc: targetDoc as Document,
map: this.mirror.map,
mirror: this.mirror,
skipChild: true,
hackCss: true,
cache: this.cache,
}) as INode;
})!;
// legacy data, we should not have -1 siblings any more
if (mutation.previousId === -1 || mutation.nextId === -1) {
@@ -1485,10 +1486,11 @@ export class Replayer {
return;
}
const parentSn = this.mirror.getMeta(parent);
if (
'__sn' in parent &&
parent.__sn.type === NodeType.Element &&
parent.__sn.tagName === 'textarea' &&
parentSn &&
parentSn.type === NodeType.Element &&
parentSn.tagName === 'textarea' &&
mutation.node.type === NodeType.Text
) {
// https://github.com/rrweb-io/rrweb/issues/745
@@ -1521,9 +1523,10 @@ export class Replayer {
parent.appendChild(target);
}
if (isIframeINode(target)) {
if (isSerializedIframe(target, this.mirror)) {
const targetId = this.mirror.getId(target);
const mutationInQueue = this.newDocumentQueue.find(
(m) => m.parentId === target.__sn.id,
(m) => m.parentId === targetId,
);
if (mutationInQueue) {
this.attachDocumentToIframe(mutationInQueue, target);
@@ -1611,10 +1614,10 @@ export class Replayer {
if (typeof attributeName === 'string') {
const value = mutation.attributes[attributeName];
if (value === null) {
((target as Node) as Element).removeAttribute(attributeName);
(target as Element).removeAttribute(attributeName);
} else if (typeof value === 'string') {
try {
((target as Node) as Element).setAttribute(attributeName, value);
(target as Element).setAttribute(attributeName, value);
} catch (error) {
if (this.config.showWarning) {
console.warn(
@@ -1625,7 +1628,7 @@ export class Replayer {
}
} else if (attributeName === 'style') {
let styleValues = value as styleAttributeValue;
const targetEl = (target as Node) as HTMLElement;
const targetEl = target as HTMLElement;
for (var s in styleValues) {
if (styleValues[s] === false) {
targetEl.style.removeProperty(s);
@@ -1654,23 +1657,24 @@ export class Replayer {
if (!target) {
return this.debugNodeNotFound(d, d.id);
}
if ((target as Node) === this.iframe.contentDocument) {
const sn = this.mirror.getMeta(target);
if (target === this.iframe.contentDocument) {
this.iframe.contentWindow!.scrollTo({
top: d.y,
left: d.x,
behavior: isSync ? 'auto' : 'smooth',
});
} else if (target.__sn.type === NodeType.Document) {
} else if (sn?.type === NodeType.Document) {
// nest iframe content document
((target as unknown) as Document).defaultView!.scrollTo({
(target as Document).defaultView!.scrollTo({
top: d.y,
left: d.x,
behavior: isSync ? 'auto' : 'smooth',
});
} else {
try {
((target as Node) as Element).scrollTop = d.y;
((target as Node) as Element).scrollLeft = d.x;
(target as Element).scrollTop = d.y;
(target as Element).scrollLeft = d.x;
} catch (error) {
/**
* Seldomly we may found scroll target was removed before
@@ -1686,8 +1690,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id);
}
try {
((target as Node) as HTMLInputElement).checked = d.isChecked;
((target as Node) as HTMLInputElement).value = d.text;
(target as HTMLInputElement).checked = d.isChecked;
(target as HTMLInputElement).value = d.text;
} catch (error) {
// for safe
}
@@ -1699,7 +1703,7 @@ export class Replayer {
return this.debugNodeNotFound(mutation, d.id);
}
try {
((target as Node) as HTMLElement).textContent = d.value;
(target as HTMLElement).textContent = d.value;
} catch (error) {
// for safe
}
@@ -1720,7 +1724,7 @@ export class Replayer {
delete map[mutation.node.id];
delete this.legacy_missingNodeRetryMap[mutation.node.id];
if (mutation.previousId || mutation.nextId) {
this.legacy_resolveMissingNode(map, parent, node as Node, mutation);
this.legacy_resolveMissingNode(map, parent, node, mutation);
}
}
if (nextInMap) {
@@ -1729,7 +1733,7 @@ export class Replayer {
delete map[mutation.node.id];
delete this.legacy_missingNodeRetryMap[mutation.node.id];
if (mutation.previousId || mutation.nextId) {
this.legacy_resolveMissingNode(map, parent, node as Node, mutation);
this.legacy_resolveMissingNode(map, parent, node, mutation);
}
}
}
@@ -1755,7 +1759,7 @@ export class Replayer {
if (!isSync) {
this.drawMouseTail({ x: _x, y: _y });
}
this.hoverElements((target as Node) as Element);
this.hoverElements(target as Element);
}
private drawMouseTail(position: { x: number; y: number }) {
@@ -1835,18 +1839,21 @@ export class Replayer {
* @param frag fragment document, the virtual parent
* @param parent real parent element
*/
private restoreRealParent(frag: INode, parent: INode) {
this.mirror.map[parent.__sn.id] = parent;
private restoreRealParent(frag: Node, parent: Node) {
const id = this.mirror.getId(frag);
const parentSn = this.mirror.getMeta(parent);
this.mirror.replace(id, parent);
/**
* If we have already set value attribute on textarea,
* then we could not apply text content as default value any more.
*/
if (
parent.__sn.type === NodeType.Element &&
parent.__sn.tagName === 'textarea' &&
parentSn?.type === NodeType.Element &&
parentSn?.tagName === 'textarea' &&
frag.textContent
) {
((parent as unknown) as HTMLTextAreaElement).value = frag.textContent;
(parent as HTMLTextAreaElement).value = frag.textContent;
}
parent.appendChild(frag);
// restore state of elements after they are mounted
@@ -1858,10 +1865,10 @@ export class Replayer {
* the state should be restored in the handler of event ReplayerEvents.Flush
* e.g. browser would lose scroll position after the process that we add children of parent node to Fragment Document as virtual dom
*/
private storeState(parent: INode) {
private storeState(parent: Node) {
if (parent) {
if (parent.nodeType === parent.ELEMENT_NODE) {
const parentElement = (parent as unknown) as HTMLElement;
const parentElement = parent as HTMLElement;
if (parentElement.scrollLeft || parentElement.scrollTop) {
// store scroll position state
this.elementStateMap.set(parent, {
@@ -1875,7 +1882,7 @@ export class Replayer {
);
const children = parentElement.children;
for (const child of Array.from(children)) {
this.storeState((child as unknown) as INode);
this.storeState(child);
}
}
}
@@ -1885,9 +1892,9 @@ export class Replayer {
* restore the state of elements recursively, which was stored before elements were unmounted from dom in virtual parent mode
* this function corresponds to function storeState
*/
private restoreState(parent: INode) {
private restoreState(parent: Node) {
if (parent.nodeType === parent.ELEMENT_NODE) {
const parentElement = (parent as unknown) as HTMLElement;
const parentElement = parent as HTMLElement;
if (this.elementStateMap.has(parent)) {
const storedState = this.elementStateMap.get(parent)!;
// restore scroll position
@@ -1899,12 +1906,12 @@ export class Replayer {
}
const children = parentElement.children;
for (const child of Array.from(children)) {
this.restoreState((child as unknown) as INode);
this.restoreState(child);
}
}
}
private restoreNodeSheet(node: INode) {
private restoreNodeSheet(node: Node) {
const storedRules = this.virtualStyleRulesMap.get(node);
if (node.nodeName !== 'STYLE') {
return;
@@ -1914,7 +1921,7 @@ export class Replayer {
return;
}
const styleNode = (node as unknown) as HTMLStyleElement;
const styleNode = node as HTMLStyleElement;
applyVirtualStyleRulesToNode(storedRules, styleNode);
}

View File

@@ -1,5 +1,3 @@
import { INode } from 'rrweb-snapshot';
export enum StyleRuleType {
Insert,
Remove,
@@ -37,7 +35,7 @@ type RemovePropertyRule = {
export type VirtualStyleRules = Array<
InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule
>;
export type VirtualStyleRulesMap = Map<INode, VirtualStyleRules>;
export type VirtualStyleRulesMap = Map<Node, VirtualStyleRules>;
export function getNestedRule(
rules: CSSRuleList,
@@ -173,7 +171,7 @@ export function storeCSSRules(
const cssTexts = Array.from(
(parentElement as HTMLStyleElement).sheet?.cssRules || [],
).map((rule) => rule.cssText);
virtualStyleRulesMap.set((parentElement as unknown) as INode, [
virtualStyleRulesMap.set(parentElement, [
{
type: StyleRuleType.Snapshot,
cssTexts,

View File

@@ -1,6 +1,6 @@
import {
serializedNodeWithId,
idNodeMap,
Mirror,
INode,
MaskInputOptions,
SlimDOMOptions,
@@ -571,11 +571,13 @@ export type DocumentDimension = {
absoluteScale: number;
};
export type Mirror = {
map: idNodeMap;
getId: (n: INode) => number;
export type DeprecatedMirror = {
map: {
[key: number]: INode;
};
getId: (n: Node) => number;
getNode: (id: number) => INode | null;
removeNodeFromMap: (n: INode) => void;
removeNodeFromMap: (n: Node) => void;
has: (id: number) => boolean;
reset: () => void;
};

View File

@@ -1,5 +1,4 @@
import {
Mirror,
throttleOptions,
listenerHandler,
hookResetter,
@@ -14,14 +13,9 @@ import {
inputData,
DocumentDimension,
IWindow,
DeprecatedMirror,
} from './types';
import {
INode,
IGNORED_NODE,
serializedNodeWithId,
NodeType,
isShadowRoot,
} from 'rrweb-snapshot';
import { Mirror, IGNORED_NODE, isShadowRoot } from 'rrweb-snapshot';
export function on(
type: string,
@@ -33,38 +27,6 @@ export function on(
return () => target.removeEventListener(type, fn, options);
}
export function createMirror(): Mirror {
return {
map: {},
getId(n) {
// if n is not a serialized INode, use -1 as its id.
if (!n || !n.__sn) {
return -1;
}
return n.__sn.id;
},
getNode(id) {
return this.map[id] || null;
},
// TODO: use a weakmap to get rid of manually memory management
removeNodeFromMap(n) {
const id = n.__sn && n.__sn.id;
delete this.map[id];
if (n.childNodes) {
n.childNodes.forEach((child) =>
this.removeNodeFromMap((child as Node) as INode),
);
}
},
has(id) {
return this.map.hasOwnProperty(id);
},
reset() {
this.map = {};
},
};
}
// https://github.com/rrweb-io/rrweb/pull/407
const DEPARTED_MIRROR_ACCESS_WARNING =
'Please stop import mirror directly. Instead of that,' +
@@ -72,7 +34,7 @@ const DEPARTED_MIRROR_ACCESS_WARNING =
'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
'\r\n' +
'or you can use record.mirror to access the mirror instance during recording.';
export let _mirror: Mirror = {
export let _mirror: DeprecatedMirror = {
map: {},
getId() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
@@ -251,16 +213,13 @@ export function isBlocked(node: Node | null, blockClass: blockClass): boolean {
return isBlocked(node.parentNode, blockClass);
}
export function isIgnored(n: Node | INode): boolean {
if ('__sn' in n) {
return (n as INode).__sn.id === IGNORED_NODE;
}
export function isIgnored(n: Node, mirror: Mirror): boolean {
// The main part of the slimDOM check happens in
// rrweb-snapshot::serializeNodeWithId
return false;
return mirror.getId(n) === IGNORED_NODE;
}
export function isAncestorRemoved(target: INode, mirror: Mirror): boolean {
export function isAncestorRemoved(target: Node, mirror: Mirror): boolean {
if (isShadowRoot(target)) {
return false;
}
@@ -278,7 +237,7 @@ export function isAncestorRemoved(target: INode, mirror: Mirror): boolean {
if (!target.parentNode) {
return true;
}
return isAncestorRemoved((target.parentNode as unknown) as INode, mirror);
return isAncestorRemoved(target.parentNode, mirror);
}
export function isTouchEvent(
@@ -325,6 +284,7 @@ export type TreeNode = {
texts: textMutation[];
attributes: attributeMutation[];
};
export class TreeIndex {
public tree!: Record<number, TreeNode>;
@@ -363,12 +323,12 @@ export class TreeIndex {
const treeNode = this.indexes.get(mutation.id);
const deepRemoveFromMirror = (id: number) => {
if (id === -1) return;
this.removeIdSet.add(id);
const node = mirror.getNode(id);
node?.childNodes.forEach((childNode) => {
if ('__sn' in childNode) {
deepRemoveFromMirror(((childNode as unknown) as INode).__sn.id);
}
deepRemoveFromMirror(mirror.getId(childNode));
});
};
const deepRemoveFromTreeIndex = (node: TreeNode) => {
@@ -576,24 +536,16 @@ export function iterateResolveTree(
}
}
type HTMLIFrameINode = HTMLIFrameElement & {
__sn: serializedNodeWithId;
};
export type AppendedIframe = {
mutationInQueue: addedNodeMutation;
builtNode: HTMLIFrameINode;
builtNode: HTMLIFrameElement;
};
export function isIframeINode(
node: INode | ShadowRoot,
): node is HTMLIFrameINode {
if ('__sn' in node) {
return (
node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe'
);
}
// node can be document fragment when using the virtual parent feature
return false;
export function isSerializedIframe(
n: Node,
mirror: Mirror,
): n is HTMLIFrameElement {
return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
}
export function getBaseDimension(

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, INode } from 'rrweb-snapshot';
import { Mirror, serializedNodeWithId } from 'rrweb-snapshot';
import { mutationCallBack } from '../types';
export declare class IframeManager {
private iframes;
@@ -9,5 +9,5 @@ export declare class IframeManager {
});
addIframe(iframeEl: HTMLIFrameElement): void;
addLoadListener(cb: (iframeEl: HTMLIFrameElement) => unknown): void;
attachIframe(iframeEl: INode, childSn: serializedNodeWithId): void;
attachIframe(iframeEl: HTMLIFrameElement, childSn: serializedNodeWithId, mirror: Mirror): void;
}

View File

@@ -4,6 +4,6 @@ declare namespace record {
var addCustomEvent: <T>(tag: string, payload: T) => void;
var freezePage: () => void;
var takeFullSnapshot: (isCheckout?: boolean | undefined) => void;
var mirror: import("../types").Mirror;
var mirror: import("rrweb-snapshot").Mirror;
}
export default record;

View File

@@ -1,2 +1,3 @@
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler, Mirror } from '../../../types';
import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler } from '../../../types';
export default function initCanvas2DMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler;

View File

@@ -1,4 +1,5 @@
import { blockClass, canvasMutationCallback, IWindow, Mirror } from '../../../types';
import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasMutationCallback, IWindow } from '../../../types';
export declare type RafStamps = {
latestId: number;
invokeId: number | null;

View File

@@ -1,2 +1,3 @@
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler, Mirror } from '../../../types';
import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler } from '../../../types';
export default function initCanvasWebGLMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler;

View File

@@ -1,4 +1,5 @@
import { mutationCallBack, Mirror, scrollCallback, MutationBufferParam, SamplingStrategy } from '../types';
import { mutationCallBack, scrollCallback, MutationBufferParam, SamplingStrategy } from '../types';
import { Mirror } from 'rrweb-snapshot';
declare type BypassOptions = Omit<MutationBufferParam, 'doc' | 'mutationCb' | 'mirror' | 'shadowDomManager'> & {
sampling: SamplingStrategy;
};

View File

@@ -1,6 +1,7 @@
import { Mirror } from 'rrweb-snapshot';
import { Timer } from './timer';
import { createPlayerService, createSpeedService } from './machine';
import { eventWithTime, playerConfig, playerMetaData, Handler, Mirror } from '../types';
import { eventWithTime, playerConfig, playerMetaData, Handler } from '../types';
import './styles/style.css';
export declare class Replayer {
wrapper: HTMLDivElement;

View File

@@ -1,4 +1,3 @@
import { INode } from 'rrweb-snapshot';
export declare enum StyleRuleType {
Insert = 0,
Remove = 1,
@@ -32,7 +31,7 @@ declare type RemovePropertyRule = {
property: string;
};
export declare type VirtualStyleRules = Array<InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule>;
export declare type VirtualStyleRulesMap = Map<INode, VirtualStyleRules>;
export declare type VirtualStyleRulesMap = Map<Node, VirtualStyleRules>;
export declare function getNestedRule(rules: CSSRuleList, position: number[]): CSSGroupingRule;
export declare function getPositionsAndIndex(nestedIndex: number[]): {
positions: number[];

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, idNodeMap, INode, MaskInputOptions, SlimDOMOptions, MaskInputFn, MaskTextFn } from 'rrweb-snapshot';
import { serializedNodeWithId, Mirror, INode, MaskInputOptions, SlimDOMOptions, MaskInputFn, MaskTextFn } from 'rrweb-snapshot';
import { PackFn, UnpackFn } from './packer/base';
import { IframeManager } from './record/iframe-manager';
import { ShadowDomManager } from './record/shadow-dom-manager';
@@ -401,11 +401,13 @@ export declare type DocumentDimension = {
relativeScale: number;
absoluteScale: number;
};
export declare type Mirror = {
map: idNodeMap;
getId: (n: INode) => number;
export declare type DeprecatedMirror = {
map: {
[key: number]: INode;
};
getId: (n: Node) => number;
getNode: (id: number) => INode | null;
removeNodeFromMap: (n: INode) => void;
removeNodeFromMap: (n: Node) => void;
has: (id: number) => boolean;
reset: () => void;
};

View File

@@ -1,8 +1,7 @@
import { Mirror, throttleOptions, listenerHandler, hookResetter, blockClass, addedNodeMutation, removedNodeMutation, textMutation, attributeMutation, mutationData, scrollData, inputData, DocumentDimension, IWindow } from './types';
import { INode, serializedNodeWithId } from 'rrweb-snapshot';
import { throttleOptions, listenerHandler, hookResetter, blockClass, addedNodeMutation, removedNodeMutation, textMutation, attributeMutation, mutationData, scrollData, inputData, DocumentDimension, IWindow, DeprecatedMirror } from './types';
import { Mirror } from 'rrweb-snapshot';
export declare function on(type: string, fn: EventListenerOrEventListenerObject, target?: Document | IWindow): listenerHandler;
export declare function createMirror(): Mirror;
export declare let _mirror: Mirror;
export declare let _mirror: DeprecatedMirror;
export declare function throttle<T>(func: (arg: T) => void, wait: number, options?: throttleOptions): (arg: T) => void;
export declare function hookSetter<T>(target: T, key: string | number | symbol, d: PropertyDescriptor, isRevoked?: boolean, win?: Window & typeof globalThis): hookResetter;
export declare function patch(source: {
@@ -11,8 +10,8 @@ export declare function patch(source: {
export declare function getWindowHeight(): number;
export declare function getWindowWidth(): number;
export declare function isBlocked(node: Node | null, blockClass: blockClass): boolean;
export declare function isIgnored(n: Node | INode): boolean;
export declare function isAncestorRemoved(target: INode, mirror: Mirror): boolean;
export declare function isIgnored(n: Node, mirror: Mirror): boolean;
export declare function isAncestorRemoved(target: Node, mirror: Mirror): boolean;
export declare function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent;
export declare function polyfill(win?: Window & typeof globalThis): void;
export declare type TreeNode = {
@@ -54,14 +53,11 @@ declare type ResolveTree = {
};
export declare function queueToResolveTrees(queue: addedNodeMutation[]): ResolveTree[];
export declare function iterateResolveTree(tree: ResolveTree, cb: (mutation: addedNodeMutation) => unknown): void;
declare type HTMLIFrameINode = HTMLIFrameElement & {
__sn: serializedNodeWithId;
};
export declare type AppendedIframe = {
mutationInQueue: addedNodeMutation;
builtNode: HTMLIFrameINode;
builtNode: HTMLIFrameElement;
};
export declare function isIframeINode(node: INode | ShadowRoot): node is HTMLIFrameINode;
export declare function isSerializedIframe(n: Node, mirror: Mirror): n is HTMLIFrameElement;
export declare function getBaseDimension(node: Node, rootIframe: Node): DocumentDimension;
export declare function hasShadowRoot<T extends Node>(n: T): n is T & {
shadowRoot: ShadowRoot;