From 1bb8546698dabcde6f70c7a0dd2b77ebc4197a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Tue, 13 May 2025 14:29:01 -0700 Subject: [PATCH] Introduce better mechanism for non-serializable built-ins in structuredClone (#51255) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/51255 Changelog: [internal] Just a small refactor of how we handle non-serializable built-ins in structuredClone Reviewed By: hoxyq Differential Revision: D74398113 fbshipit-source-id: 26211920fcd4cf11c5da278e213eaa2b6b9aa1b5 --- .../structuredClone/structuredClone.js | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/react-native/src/private/webapis/structuredClone/structuredClone.js b/packages/react-native/src/private/webapis/structuredClone/structuredClone.js index 56b1627f803..b3fa346e5a0 100644 --- a/packages/react-native/src/private/webapis/structuredClone/structuredClone.js +++ b/packages/react-native/src/private/webapis/structuredClone/structuredClone.js @@ -155,12 +155,7 @@ function structuredCloneInternal(value: T): T { } // Known non-serializable objects. - // TODO: Handle this more holistically - if ( - value instanceof WeakMap || - value instanceof WeakSet || - value instanceof Promise - ) { + if (isNonSerializableObject(value)) { throw new DOMException( `Failed to execute 'structuredClone' on 'Window': ${String(value)} could not be cloned.`, 'DataCloneError', @@ -208,3 +203,20 @@ export default function structuredClone(value: T): T { memory.clear(); } } + +const NON_SERIALIZABLE_OBJECT_KEY = Symbol('nonSerializableObject'); + +function isNonSerializableObject(obj: T): boolean { + // $FlowExpectedError[invalid-in-lhs] + return NON_SERIALIZABLE_OBJECT_KEY in obj; +} + +function markClassAsNonSerializable(cls: Class): void { + // $FlowExpectedError[incompatible-use] + cls.prototype[NON_SERIALIZABLE_OBJECT_KEY] = true; +} + +// Non-serializable built-ins. +markClassAsNonSerializable(WeakMap); +markClassAsNonSerializable(WeakSet); +markClassAsNonSerializable(Promise);