Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,14 @@ export default function RuntimeTestsExample() {
require('./tests/runtimes/scheduleOnRuntimeWithId.test');
},
},
{
testSuiteName: 'bundle mode core',
importTest: () => {
require('./tests/runtimes/reactNativeImportShim.test');
require('./tests/runtimes/turboModuleRegistryShim.test');
},
disabled: !globalThis._WORKLETS_BUNDLE_MODE_ENABLED,
},
{
testSuiteName: 'run loop',
importTest: () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { runOnUISync, runOnRuntimeSync } from 'react-native-worklets';
import {
describe,
expect,
getWorkletRuntimeFromPool,
test,
} from '../../ReJest/RuntimeTestsApi';

describe("importing 'react-native' on Worklet Runtimes", () => {
const workerRuntime = getWorkletRuntimeFromPool('test');

const testFn = globalThis._WORKLETS_BUNDLE_MODE_ENABLED ? test : test.skip;

const targets = [
{
targetRuntime: 'UI',
runOnTarget: <TReturn>(worklet: () => TReturn) => runOnUISync(worklet),
},
{
targetRuntime: 'Worker',
runOnTarget: <TReturn>(worklet: () => TReturn) =>
runOnRuntimeSync(workerRuntime, worklet),
},
];

targets.forEach(({ targetRuntime, runOnTarget }) => {
describe(`on ${targetRuntime} Runtime`, () => {
testFn('works without access', () => {
const status = runOnTarget(() => {
'worklet';
const reactNative = require('react-native');
return typeof reactNative === 'object';
});

expect(status).toBe(true);
});

testFn('throws when accessing unsafe APIs', async () => {
await expect(() => {
runOnTarget(() => {
'worklet';
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const platform = require('react-native').Platform;
console.log(platform);
});
}).toThrow();
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { runOnUISync, runOnRuntimeSync } from 'react-native-worklets';
import {
describe,
expect,
getWorkletRuntimeFromPool,
test,
} from '../../ReJest/RuntimeTestsApi';

const expectedErrorMessage =
'[Worklets] Accessing TurboModules is not allowed on Worklet Runtimes.';

const bundleModeEnabled = !!globalThis._WORKLETS_BUNDLE_MODE_ENABLED;
const proxy = globalThis.__workletsModuleProxy as
| { getStaticFeatureFlag: (name: string) => boolean }
| undefined;
const fetchPreviewEnabled =
bundleModeEnabled && !!proxy?.getStaticFeatureFlag('FETCH_PREVIEW_ENABLED');

describe('accessing Turbo Modules on Worklet Runtimes', () => {
const workerRuntime = getWorkletRuntimeFromPool('test');

const testFn = bundleModeEnabled ? test : test.skip;
const previewOnFn = fetchPreviewEnabled ? test : test.skip;
const previewOffFn =
bundleModeEnabled && !fetchPreviewEnabled ? test : test.skip;

const targets = [
{
targetRuntime: 'UI',
runOnTarget: <T>(worklet: () => T) => runOnUISync(worklet),
},
{
targetRuntime: 'Worker',
runOnTarget: <T>(worklet: () => T) =>
runOnRuntimeSync(workerRuntime, worklet),
},
];

targets.forEach(({ targetRuntime, runOnTarget }) => {
describe(`on ${targetRuntime} Runtime`, () => {
testFn('throws for non-polyfilled modules', () => {
const errorMessage = runOnTarget(() => {
'worklet';
try {
(
require('react-native/Libraries/TurboModule/TurboModuleRegistry') as TurboModuleRegistryShape
).get('NonExistentTurboModule');
return null;
} catch (e) {
return (e as Error).message;
}
});

expect(errorMessage).toInclude(expectedErrorMessage);
});

previewOffFn(
'throws for Networking when `FETCH_PREVIEW_ENABLED` is off',
() => {
const errorMessage = runOnTarget(() => {
'worklet';
try {
(
require('react-native/Libraries/TurboModule/TurboModuleRegistry') as TurboModuleRegistryShape
).get('Networking');
return null;
} catch (e) {
return (e as Error).message;
}
});

expect(errorMessage).toInclude(expectedErrorMessage);
}
);

previewOnFn(
'returns the Networking polyfill when `FETCH_PREVIEW_ENABLED` is on',
() => {
const outcome = runOnTarget(() => {
'worklet';
try {
const value = (
require('react-native/Libraries/TurboModule/TurboModuleRegistry') as TurboModuleRegistryShape
).get('Networking');
return value !== undefined ? 'ok' : 'undefined';
} catch (e) {
return (e as Error).message;
}
});

expect(outcome).toInclude('ok');
}
);
});
});
});

type TurboModuleRegistryShape = { get: (name: string) => unknown };
64 changes: 62 additions & 2 deletions packages/react-native-worklets/bundleMode/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
const path = require('path');

const workletsPackageParentDir = path.resolve(__dirname, '../..');
const reactNativeShimPath = path.join(__dirname, 'shims', 'reactNativeShim.js');
const turboModuleRegistryShimPath = path.join(
__dirname,
'shims',
'turboModuleRegistryShim.js'
);
const turboModuleRegistryModuleName =
'react-native/Libraries/TurboModule/TurboModuleRegistry';
const turboModuleRegistryFileSuffix = path.join(
'react-native',
'Libraries',
'TurboModule',
'TurboModuleRegistry.js'
);

function isResolvedTurboModuleRegistry(/** @type {any} */ result) {
return (
result?.type === 'sourceFile' &&
typeof result.filePath === 'string' &&
result.filePath.endsWith(turboModuleRegistryFileSuffix)
);
}

const workletsPackageName = 'react-native-worklets';
const workletsDirPath = path.posix.join(workletsPackageName, '.worklets');
Expand All @@ -26,11 +48,30 @@ function bundleModeResolveRequest(
const fullModuleName = path.join(workletsPackageParentDir, moduleName);
return { type: 'sourceFile', filePath: fullModuleName };
}
return (userConfigResolveRequest || context.resolveRequest)(
if (
moduleName === 'react-native' &&
context.originModulePath !== reactNativeShimPath
) {
return { type: 'sourceFile', filePath: reactNativeShimPath };
}
if (
moduleName === turboModuleRegistryModuleName &&
context.originModulePath !== turboModuleRegistryShimPath
) {
return { type: 'sourceFile', filePath: turboModuleRegistryShimPath };
}
const resolved = (userConfigResolveRequest || context.resolveRequest)(
context,
moduleName,
platform
);
if (
context.originModulePath !== turboModuleRegistryShimPath &&
isResolvedTurboModuleRegistry(resolved)
) {
return { type: 'sourceFile', filePath: turboModuleRegistryShimPath };
}
return resolved;
}

/** Use in React Native Community projects. */
Expand All @@ -48,7 +89,26 @@ const bundleModeMetroConfig = {
const fullModuleName = path.join(workletsPackageParentDir, moduleName);
return { type: 'sourceFile', filePath: fullModuleName };
}
return context.resolveRequest(context, moduleName, platform);
if (
moduleName === 'react-native' &&
context.originModulePath !== reactNativeShimPath
) {
return { type: 'sourceFile', filePath: reactNativeShimPath };
}
if (
moduleName === turboModuleRegistryModuleName &&
context.originModulePath !== turboModuleRegistryShimPath
) {
return { type: 'sourceFile', filePath: turboModuleRegistryShimPath };
}
const resolved = context.resolveRequest(context, moduleName, platform);
if (
context.originModulePath !== turboModuleRegistryShimPath &&
isResolvedTurboModuleRegistry(resolved)
) {
return { type: 'sourceFile', filePath: turboModuleRegistryShimPath };
}
return resolved;
},
},
};
Expand Down
21 changes: 21 additions & 0 deletions packages/react-native-worklets/bundleMode/shims/reactNativeShim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

if (
globalThis.__RUNTIME_KIND === undefined ||
globalThis.__RUNTIME_KIND === 1
) {
globalThis.__RUNTIME_KIND = 1;
} else if (__DEV__) {
globalThis.__fbBatchedBridgeConfig = new Proxy(
{},
{
get() {
throw new Error(
'[Worklets] Accessing __fbBatchedBridgeConfig is not allowed on Worklet Runtimes. Perhaps you tried to access a Turbo Module?'
);
},
}
);
}

module.exports = require('react-native');
16 changes: 16 additions & 0 deletions packages/react-native-worklets/bundleMode/shims/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"module": "nodenext",
"skipLibCheck": true,
"moduleResolution": "nodenext",
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["."]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict';

/** @type {((name: string) => unknown) | undefined} */
let get;
/** @type {((name: string) => unknown) | undefined} */
let getEnforcing;

if (
globalThis.__RUNTIME_KIND === undefined ||
globalThis.__RUNTIME_KIND === 1
) {
globalThis.__RUNTIME_KIND = 1;

const TurboModuleRegistry = require('react-native/Libraries/TurboModule/TurboModuleRegistry');

get = TurboModuleRegistry.get;
getEnforcing = TurboModuleRegistry.getEnforcing;
} else {
/** @type {Map<string, unknown> | undefined} */
let TurboModulesPolyfill;

if (
globalThis.__workletsModuleProxy.getStaticFeatureFlag(
'FETCH_PREVIEW_ENABLED'
)
) {
TurboModulesPolyfill = new Map();
TurboModulesPolyfill.set('Networking', {});

globalThis.TurboModules = TurboModulesPolyfill;
}

function getPolyfill(/** @type {string} */ name) {
if (__DEV__ && !TurboModulesPolyfill?.has(name)) {
throw new Error(
'[Worklets] Accessing TurboModules is not allowed on Worklet Runtimes.'
);
} else {
return TurboModulesPolyfill?.get(name);
}
}

get = getPolyfill;
getEnforcing = getPolyfill;
}

export { get, getEnforcing };
13 changes: 13 additions & 0 deletions packages/react-native-worklets/bundleMode/shims/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export {};

declare global {
var __workletsModuleProxy: {
getStaticFeatureFlag: (name: string) => boolean;
};

var __fbBatchedBridgeConfig: unknown;

var __RUNTIME_KIND: 1 | 2 | 3 | undefined;

var TurboModules: Map<string, unknown> | undefined;
}
1 change: 1 addition & 0 deletions packages/react-native-worklets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
"compatibility.json",
"bundleMode/index.js",
"bundleMode/index.d.ts",
"bundleMode/shims/*.js",
"scripts/worklets_utils.rb",
"scripts/validate-react-native-version.js",
"jest",
Expand Down
Loading
Loading