Skip to content

Commit 428066e

Browse files
raju-opticlaude
andcommitted
[FSSDK-13287] restructure react native optional import shims
Shims now live in lib/import.react_native, are named after the package they require, and export isAvailable plus the package's exports used by the SDK. They never throw; importers handle a missing package: - index.react_native.ts throws if TextEncoder or crypto.getRandomValues is still missing after the polyfill shims run - AsyncStorageCache throws "Module not found" when AsyncStorage is missing The async-storage compat helper is merged into its shim, which applies ensureMultiGet right after the require and exports the result as default. The CJS bundles read shim default exports with Rollup's esModule interop. A rollup check fails the build unless every built shim contains exactly one require(), of its own package. A README in the shim directory explains the Metro bug behind this setup and the rules for writing a shim. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9a46d92 commit 428066e

13 files changed

Lines changed: 341 additions & 192 deletions

‎lib/event_processor/event_processor_factory.react_native.spec.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,9 @@ vi.mock('@react-native-community/netinfo', () => {
5656
let isAsyncStorageAvailable = true;
5757

5858
// Simulate a missing @react-native-async-storage/async-storage
59-
vi.mock('../react_native_optional/async_storage', () => ({
60-
loadAsyncStorageModule: () => (isAsyncStorageAvailable ? { default: {} } : undefined),
59+
vi.mock('../import.react_native/@react-native-async-storage/async-storage', () => ({
60+
get isAvailable() { return isAsyncStorageAvailable; },
61+
get default() { return isAsyncStorageAvailable ? {} : undefined; },
6162
}));
6263

6364
import { createForwardingEventProcessor, createBatchEventProcessor } from './event_processor_factory.react_native';
@@ -67,7 +68,6 @@ import { getOpaqueBatchEventProcessor } from './event_processor_factory';
6768
import { AsyncStore, AsyncPrefixStore, SyncStore, SyncPrefixStore } from '../utils/cache/store';
6869
import { AsyncStorageCache } from '../utils/cache/async_storage_cache.react_native';
6970
import { EVENT_STORE_PREFIX, EventStore } from './event_store';
70-
import { MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE } from '../utils/import.react_native/@react-native-async-storage/async-storage';
7171

7272
describe('createForwardingEventProcessor', () => {
7373
const mockGetForwardingEventProcessor = vi.mocked(getForwardingEventProcessor);
@@ -143,7 +143,7 @@ describe('createBatchEventProcessor', () => {
143143

144144
it('should throw error if @react-native-async-storage/async-storage is not available', async () => {
145145
isAsyncStorageAvailable = false;
146-
const { AsyncStorageCache } = await vi.importActual<
146+
const { AsyncStorageCache, MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE } = await vi.importActual<
147147
typeof import('../utils/cache/async_storage_cache.react_native')
148148
>('../utils/cache/async_storage_cache.react_native');
149149

lib/utils/import.react_native/@react-native-async-storage/async-storage.spec.ts renamed to lib/import.react_native/@react-native-async-storage/async-storage.spec.ts

Lines changed: 51 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2025, Optimizely
2+
* Copyright 2025-2026, Optimizely
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -15,48 +15,45 @@
1515
*/
1616

1717
import { vi, describe, it, expect } from 'vitest';
18-
19-
vi.mock('../../../react_native_optional/async_storage', () => ({
20-
loadAsyncStorageModule: vi.fn(),
21-
}));
22-
23-
import { ensureMultiGet, getDefaultAsyncStorage, MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE } from './async-storage';
24-
import { loadAsyncStorageModule } from '../../../react_native_optional/async_storage';
25-
26-
describe('getDefaultAsyncStorage', () => {
27-
it('should throw module not found error when async storage is not installed', () => {
28-
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce(undefined);
29-
30-
expect(() => getDefaultAsyncStorage()).toThrow(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
18+
import Module from 'module';
19+
20+
// The shim requires the package when it loads, so each case loads a fresh copy of the shim with the
21+
// package's require replaced by `load`. vi.mock does not intercept the shim's plain require.
22+
const loadShimWith = async (load: () => unknown) => {
23+
const M = Module as unknown as { _load: (request: string, ...rest: unknown[]) => unknown };
24+
const originalLoad = M._load;
25+
M._load = function (this: unknown, request: string, ...rest: unknown[]) {
26+
if (request === '@react-native-async-storage/async-storage') return load();
27+
return originalLoad.call(this, request, ...rest);
28+
};
29+
try {
30+
vi.resetModules();
31+
return await import('./async-storage');
32+
} finally {
33+
M._load = originalLoad;
34+
}
35+
};
36+
37+
const loadShimWithStorage = (storage: unknown) => loadShimWith(() => ({ default: storage }));
38+
39+
describe('@react-native-async-storage/async-storage shim', () => {
40+
it('should export isAvailable as false and an undefined default when the package is not installed', async () => {
41+
const shim = await loadShimWith(() => {
42+
throw new Error('Cannot find module');
43+
});
44+
45+
expect(shim.isAvailable).toBe(false);
46+
expect(shim.default).toBeUndefined();
3147
});
3248

33-
it('should throw module not found error when the module has no default export', () => {
34-
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce({});
35-
36-
expect(() => getDefaultAsyncStorage()).toThrow(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
37-
});
38-
39-
it('should return the default export of the async storage module', () => {
40-
const multiGet = vi.fn();
41-
const storage = {
42-
getItem: vi.fn(),
43-
setItem: vi.fn(),
44-
removeItem: vi.fn(),
45-
getAllKeys: vi.fn(),
46-
clear: vi.fn(),
47-
multiGet,
48-
};
49-
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce({ default: storage });
50-
51-
const result = getDefaultAsyncStorage();
49+
it('should export an undefined default when the package has no default export', async () => {
50+
const shim = await loadShimWithStorage(undefined);
5251

53-
expect(result).toBe(storage);
54-
expect(result.multiGet).toBe(multiGet);
52+
expect(shim.isAvailable).toBe(true);
53+
expect(shim.default).toBeUndefined();
5554
});
56-
});
5755

58-
describe('ensureMultiGet', () => {
59-
it('should preserve multiGet when already present (v1/v2)', () => {
56+
it('should export the package default as-is when multiGet is present (v1/v2)', async () => {
6057
const multiGet = vi.fn();
6158
const storage = {
6259
getItem: vi.fn(),
@@ -67,9 +64,11 @@ describe('ensureMultiGet', () => {
6764
multiGet,
6865
};
6966

70-
const result = ensureMultiGet(storage);
67+
const shim = await loadShimWithStorage(storage);
7168

72-
expect(result.multiGet).toBe(multiGet);
69+
expect(shim.isAvailable).toBe(true);
70+
expect(shim.default).toBe(storage);
71+
expect(shim.default?.multiGet).toBe(multiGet);
7372
});
7473

7574
it('should construct multiGet from getMany when multiGet is absent (v3)', async () => {
@@ -87,19 +86,19 @@ describe('ensureMultiGet', () => {
8786
}),
8887
};
8988

90-
const result = ensureMultiGet(storage);
89+
const result = (await loadShimWithStorage(storage)).default;
9190

92-
expect(result.multiGet).toBeDefined();
91+
expect(result?.multiGet).toBeDefined();
9392

94-
const pairs = await result.multiGet(['b', 'missing', 'a']);
93+
const pairs = await result?.multiGet(['b', 'missing', 'a']);
9594
expect(pairs).toEqual([
9695
['b', '2'],
9796
['missing', null],
9897
['a', '1'],
9998
]);
10099
});
101100

102-
it('should not modify the original storage when constructing multiGet (v3)', () => {
101+
it('should not modify the original storage when constructing multiGet (v3)', async () => {
103102
const storage = {
104103
getItem: vi.fn(),
105104
setItem: vi.fn(),
@@ -109,16 +108,16 @@ describe('ensureMultiGet', () => {
109108
getMany: vi.fn(),
110109
};
111110

112-
const result = ensureMultiGet(storage);
111+
const result = (await loadShimWithStorage(storage)).default;
113112

114113
expect(result).not.toBe(storage);
115114
expect('multiGet' in storage).toBe(false);
116115
expect(Object.getPrototypeOf(result)).toBe(storage);
117-
expect(result.getItem).toBe(storage.getItem);
118-
expect(result.setItem).toBe(storage.setItem);
119-
expect(result.removeItem).toBe(storage.removeItem);
120-
expect(result.getAllKeys).toBe(storage.getAllKeys);
121-
expect(result.clear).toBe(storage.clear);
116+
expect(result?.getItem).toBe(storage.getItem);
117+
expect(result?.setItem).toBe(storage.setItem);
118+
expect(result?.removeItem).toBe(storage.removeItem);
119+
expect(result?.getAllKeys).toBe(storage.getAllKeys);
120+
expect(result?.clear).toBe(storage.clear);
122121
});
123122

124123
it('should return pairs in the requested key order regardless of getMany record order', async () => {
@@ -137,8 +136,8 @@ describe('ensureMultiGet', () => {
137136
}),
138137
};
139138

140-
const result = ensureMultiGet(storage);
141-
const pairs = await result.multiGet(['z', 'x', 'y']);
139+
const result = (await loadShimWithStorage(storage)).default;
140+
const pairs = await result?.multiGet(['z', 'x', 'y']);
142141

143142
expect(pairs).toEqual([
144143
['z', 'vz'],

lib/utils/import.react_native/@react-native-async-storage/async-storage.ts renamed to lib/import.react_native/@react-native-async-storage/async-storage.ts

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
/**
2-
* Copyright 2024, Optimizely
2+
* Copyright 2024-2026, Optimizely
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
66
* You may obtain a copy of the License at
77
*
8-
* http://www.apache.org/licenses/LICENSE-2.0
8+
* https://www.apache.org/licenses/LICENSE-2.0
99
*
1010
* Unless required by applicable law or agreed to in writing, software
1111
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,8 +14,9 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { Platform } from '../../../platform_support';
18-
import { loadAsyncStorageModule } from '../../../react_native_optional/async_storage';
17+
import { Platform } from '../../platform_support';
18+
19+
// Optional import shim; see ../README.md.
1920

2021
export interface AsyncStorageCompat {
2122
getItem(key: string): Promise<string | null>;
@@ -36,35 +37,42 @@ interface RawAsyncStorage {
3637
getMany?(keys: readonly string[]): Promise<Record<string, string | null>>;
3738
}
3839

39-
export const MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE = 'Module not found: @react-native-async-storage/async-storage';
40-
4140
type RawAsyncStorageWithGetMany = RawAsyncStorage & Required<Pick<RawAsyncStorage, 'getMany'>>;
4241

43-
// Returns a wrapper with the original as its prototype, so the shared AsyncStorage object is not mutated.
44-
export const ensureMultiGet = (storage: RawAsyncStorage): AsyncStorageCompat => {
42+
// AsyncStorage v3 replaced multiGet with getMany. Returns a wrapper with the original as its prototype,
43+
// so the shared AsyncStorage object is not mutated.
44+
// multiGet avoids async/await, which would compile to a tslib helper import.
45+
const ensureMultiGet = (storage: RawAsyncStorage): AsyncStorageCompat => {
4546
if (storage.multiGet || !storage.getMany) {
4647
return storage as AsyncStorageCompat;
4748
}
4849

4950
return Object.create(storage, {
5051
multiGet: {
51-
value: async function(
52+
value: function(
5253
this: RawAsyncStorageWithGetMany,
5354
keys: readonly string[],
5455
): Promise<[string, string | null][]> {
55-
const record = await this.getMany(keys);
56-
return keys.map((key: string) => [key, record[key] ?? null] as [string, string | null]);
56+
return this.getMany(keys).then((record) =>
57+
keys.map((key: string) => [key, record[key] ?? null] as [string, string | null])
58+
);
5759
},
5860
},
5961
});
6062
};
6163

62-
export const getDefaultAsyncStorage = (): AsyncStorageCompat => {
63-
const storage = loadAsyncStorageModule()?.default as RawAsyncStorage | undefined;
64-
if (!storage) {
65-
throw new Error(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
66-
}
67-
return ensureMultiGet(storage);
68-
};
64+
export let isAvailable = true;
65+
66+
let storage: RawAsyncStorage | undefined;
67+
68+
try {
69+
// eslint-disable-next-line @typescript-eslint/no-var-requires
70+
storage = require('@react-native-async-storage/async-storage').default;
71+
} catch (e) {
72+
isAvailable = false;
73+
}
74+
75+
// The package's default export, with multiGet added when it is missing (v3).
76+
export default storage ? ensureMultiGet(storage) : undefined;
6977

7078
export const __platforms: Platform[] = ['__universal__'];

0 commit comments

Comments
 (0)