From ac5293f162ac369e8818a23ac2839c6183cf96a4 Mon Sep 17 00:00:00 2001 From: Yanzhen Yu Date: Wed, 1 Apr 2026 12:00:00 +0800 Subject: [PATCH] add strict null check and fix codes --- index.d.ts | 1 + src/index.ts | 1 + src/rebuild.ts | 6 +++++- src/snapshot.ts | 9 ++++++--- tsconfig.json | 1 + 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index e1d96cb4..bb15b0be 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,5 @@ import { serializedNodeWithId } from './src/types'; +export * from './src/types'; export function snapshot(n: Document): serializedNodeWithId | null; export function rebuild(n: serializedNodeWithId): Node | null; diff --git a/src/index.ts b/src/index.ts index 758f2df9..6b8e1450 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ import snapshot from './snapshot'; import rebuild from './rebuild'; +export * from './types'; export { snapshot, rebuild }; diff --git a/src/rebuild.ts b/src/rebuild.ts index bcf1f681..fce1fb36 100644 --- a/src/rebuild.ts +++ b/src/rebuild.ts @@ -62,7 +62,11 @@ function rebuild(n: serializedNodeWithId): Node | null { if (n.type === NodeType.Document || n.type === NodeType.Element) { for (const childN of n.childNodes) { const childNode = rebuild(childN); - root.appendChild(childNode); + if (!childNode) { + console.warn('Failed to rebuild', childN); + } else { + root.appendChild(childNode); + } } } return root; diff --git a/src/snapshot.ts b/src/snapshot.ts index 0501f499..913210a4 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -98,7 +98,7 @@ function serializeNode(n: Node, doc: Document): serializedNode | false { } return { type: NodeType.Text, - textContent, + textContent: textContent || '', }; case n.CDATA_SECTION_NODE: return { @@ -108,7 +108,7 @@ function serializeNode(n: Node, doc: Document): serializedNode | false { case n.COMMENT_NODE: return { type: NodeType.Comment, - textContent: (n as Comment).textContent, + textContent: (n as Comment).textContent || '', }; default: return false; @@ -130,7 +130,10 @@ function _snapshot(n: Node, doc: Document): serializedNodeWithId | null { serializedNode.type === NodeType.Element ) { for (const childN of Array.from(n.childNodes)) { - serializedNode.childNodes.push(_snapshot(childN, doc)); + const serializedChildNode = _snapshot(childN, doc); + if (serializedChildNode) { + serializedNode.childNodes.push(serializedChildNode); + } } } return serializedNode; diff --git a/tsconfig.json b/tsconfig.json index f82e02cd..d58ee546 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "module": "commonjs", "noImplicitAny": true, + "strictNullChecks": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true,