diff --git a/src/__tests__/sanity-check.test.tsx b/src/__tests__/sanity-check.test.tsx
index 3d7b28d..c39c53d 100644
--- a/src/__tests__/sanity-check.test.tsx
+++ b/src/__tests__/sanity-check.test.tsx
@@ -1,19 +1,28 @@
-import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
+import { act, renderWithProviders, screen } from '~/test-utils/test-helper';
import { AppRoot } from '~/components/AppRoot';
-vi.mock('../decrypt-worker/client', () => {
+// Must match the dynamic import specifier used by browserCrypto (`~/decrypt-worker/client`).
+// Plain functions: vitest `mockReset` clears vi.fn mockResolvedValue between tests.
+vi.mock('~/decrypt-worker/client', () => {
return {
workerClientBus: {
- request: vi.fn().mockResolvedValue('dummy'),
+ request: () => Promise.resolve('dummy'),
+ },
+ decryptionQueue: {
+ add: () => Promise.resolve({ decrypted: 'blob://dummy', ext: 'flac' }),
},
};
});
test('should be able to render App', async () => {
- renderWithProviders();
+ await act(async () => {
+ renderWithProviders();
+ // Flush Suspense retry after platform.init() (dynamic import) settles.
+ await Promise.resolve();
+ });
- // Should eventually load sdk version
- await waitFor(() => screen.getByTestId('sdk-version'));
+ // Platform Suspense gate + SDK version fetch
+ expect(await screen.findByTestId('sdk-version')).toBeInTheDocument();
// Quick sanity check of known strings.
expect(screen.getByText(/音乐解锁/i)).toBeInTheDocument();
diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx
new file mode 100644
index 0000000..8d48faa
--- /dev/null
+++ b/src/components/AppLayout.tsx
@@ -0,0 +1,67 @@
+import { NavLink, Route, Routes } from 'react-router';
+import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
+import { Bounce, ToastContainer } from 'react-toastify';
+
+import { Footer } from '~/components/Footer';
+import { FaqHome } from '~/faq/FaqHome';
+import { FAQ_PAGES } from '~/faq/FAQPages';
+import { SettingsHome } from '~/features/settings/SettingsHome';
+import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
+import { FaqTab } from '~/tabs/FaqTab';
+import { MainTab } from '~/tabs/MainTab';
+import { SettingsTab } from '~/tabs/SettingsTab';
+
+const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
+
+/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
+export function AppLayout() {
+ return (
+ <>
+
+
+
+ 应用
+
+
+
+ 设置
+
+
+
+ 答疑
+
+
+
+
+
+
+
+
+ {Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
+
+ ))}
+
+
+
+ {FAQ_PAGES.map(({ id, Component }) => (
+
+ ))}
+
+
+
+
+
+
+
+ >
+ );
+}
diff --git a/src/components/AppRoot.tsx b/src/components/AppRoot.tsx
index 012c0e1..9affca9 100644
--- a/src/components/AppRoot.tsx
+++ b/src/components/AppRoot.tsx
@@ -1,83 +1,43 @@
-import { useEffect } from 'react';
-import { BrowserRouter, NavLink, Route, Routes } from 'react-router';
-import { MdSettings, MdHome, MdQuestionAnswer } from 'react-icons/md';
-
-import { MainTab } from '~/tabs/MainTab';
-import { SettingsTab } from '~/tabs/SettingsTab';
-
+import { Suspense } from 'react';
+import { BrowserRouter } from 'react-router';
import { Provider } from 'react-redux';
+
+import { AppLayout } from '~/components/AppLayout';
import { persistSettings } from '~/features/settings/persistSettings';
-import { setupStore } from '~/store';
-import { Footer } from '~/components/Footer';
-import { FaqTab } from '~/tabs/FaqTab';
-import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
-import { Bounce, ToastContainer } from 'react-toastify';
-import { SettingsHome } from '~/features/settings/SettingsHome';
-import { FAQ_PAGES } from '~/faq/FAQPages';
-import { FaqHome } from '~/faq/FaqHome';
import { createPlatformProvider } from '~/platform/createPlatformProvider';
+import { PlatformLoadGuard } from '~/platform/PlatformLoadGuard';
import { PlatformProviderHost } from '~/platform/PlatformContext';
import { setPlatform } from '~/platform/platformSingleton';
+import { setupStore } from '~/store';
// Private to this file only.
const store = setupStore();
const platform = createPlatformProvider();
-setPlatform(platform);
-const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
+const platformReady = platform.init().then(() => {
+ setPlatform(platform);
+ persistSettings(store, platform);
+});
+
+function AppBootFallback() {
+ return (
+
+
+ 加载中
+
+ );
+}
export function AppRoot() {
- useEffect(() => persistSettings(store, platform), []);
-
return (
-
-
-
- 应用
-
-
-
- 设置
-
-
-
- 答疑
-
-
-
-
-
-
-
-
- {Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
-
- ))}
-
-
-
- {FAQ_PAGES.map(({ id, Component }) => (
-
- ))}
-
-
-
-
-
-
-
+ }>
+
+
+
+
diff --git a/src/components/SDKVersion.tsx b/src/components/SDKVersion.tsx
index f5508df..fe49466 100644
--- a/src/components/SDKVersion.tsx
+++ b/src/components/SDKVersion.tsx
@@ -1,18 +1,15 @@
import { MdInfoOutline } from 'react-icons/md';
-import { workerClientBus } from '~/decrypt-worker/client';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
+import { usePlatform } from '~/platform/PlatformContext';
import { useEffect, useRef, useState } from 'react';
-const getSDKVersion = async (): Promise => {
- return workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
-};
-
export function SDKVersion() {
+ const { crypto } = usePlatform();
const refDialog = useRef(null);
const [sdkVersion, setSdkVersion] = useState('...');
useEffect(() => {
- getSDKVersion().then(setSdkVersion, () => setSdkVersion('N/A'));
- }, []);
+ crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null).then(setSdkVersion, () => setSdkVersion('N/A'));
+ }, [crypto]);
return (
<>
diff --git a/src/features/file-listing/__tests__/processFile.test.ts b/src/features/file-listing/__tests__/processFile.test.ts
new file mode 100644
index 0000000..de4a59c
--- /dev/null
+++ b/src/features/file-listing/__tests__/processFile.test.ts
@@ -0,0 +1,76 @@
+import type { WorkerActionName } from '~/decrypt-worker/actions';
+import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
+import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
+import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
+import { setPlatform } from '~/platform/platformSingleton';
+import { setupStore } from '~/store';
+import { ListingMode, ProcessState, processFile, selectFiles } from '../fileListingSlice';
+import { untouchedFile } from './__fixture__/file-list';
+
+describe('processFile', () => {
+ test('parses headers via platform.crypto then enqueueDecrypts', async () => {
+ const request = vi.fn((action: WorkerActionName) => {
+ if (action === 'FIND_QMC_MUSICEX_NAME') {
+ return Promise.resolve('track.mflac');
+ }
+ return Promise.resolve(null);
+ });
+ const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
+ const crypto: BrowserCrypto = { request, enqueueDecrypt };
+ setPlatform(createBrowserProvider({ crypto }));
+
+ const fileId = 'file://untouched';
+ const store = setupStore({
+ fileListing: {
+ files: { [fileId]: { ...untouchedFile } },
+ displayMode: ListingMode.LIST,
+ },
+ });
+
+ const result = await store.dispatch(processFile({ fileId }));
+
+ expect(result.type).toBe(processFile.fulfilled.type);
+ expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
+ blobURI: untouchedFile.raw,
+ });
+ expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
+ blobURI: untouchedFile.raw,
+ });
+ expect(request).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
+ blobURI: untouchedFile.raw,
+ });
+ expect(enqueueDecrypt).toHaveBeenCalledTimes(1);
+ const [decryptPayload, onPreProcess] = enqueueDecrypt.mock.calls[0] as [
+ { fileId: string; blobURI: string; options: { fileName: string } },
+ () => void,
+ ];
+ expect(decryptPayload).toMatchObject({
+ fileId,
+ blobURI: untouchedFile.raw,
+ options: { fileName: untouchedFile.fileName },
+ });
+ expect(typeof onPreProcess).toBe('function');
+
+ const file = selectFiles(store.getState())[fileId];
+ expect(file.state).toBe(ProcessState.COMPLETE);
+ expect(file.decrypted).toBe('blob://out');
+ expect(file.ext).toBe('flac');
+ });
+
+ test('rejects when file id is missing', async () => {
+ const crypto: BrowserCrypto = {
+ request: vi.fn(),
+ enqueueDecrypt: vi.fn(),
+ };
+ setPlatform(createBrowserProvider({ crypto }));
+ const store = setupStore({
+ fileListing: {
+ files: {},
+ displayMode: ListingMode.LIST,
+ },
+ });
+
+ const result = await store.dispatch(processFile({ fileId: 'missing' }));
+ expect(result.type).toBe(processFile.rejected.type);
+ });
+});
diff --git a/src/features/file-listing/fileListingSlice.ts b/src/features/file-listing/fileListingSlice.ts
index a8e50ad..8535f93 100644
--- a/src/features/file-listing/fileListingSlice.ts
+++ b/src/features/file-listing/fileListingSlice.ts
@@ -4,12 +4,12 @@ import type { RootState } from '~/store';
import { DECRYPTION_WORKER_ACTION_NAME, type DecryptionResult } from '~/decrypt-worker/constants';
import type { DecryptCommandOptions } from '~/decrypt-worker/types';
-import { decryptionQueue, workerClientBus } from '~/decrypt-worker/client';
import { DecryptErrorType } from '~/decrypt-worker/util/DecryptError';
import { selectQMCv2KeyByFileName } from '~/features/qmc/keyLookup';
import { selectKWMv2Key } from '~/features/kwm/keyLookup';
import { selectKugouKey } from '~/features/kugou/keyLookup';
import { selectQtfmAndroidKey } from '~/features/qtfm/keyLookup';
+import { getPlatform } from '~/platform/platformSingleton';
import { cleanFilename } from '~/util/cleanFilename';
export enum ProcessState {
@@ -70,14 +70,15 @@ export const processFile = createAsyncThunk<
thunkAPI.dispatch(setFileAsProcessing({ id: fileId }));
};
+ const { crypto } = getPlatform();
const [qmcv2MusicExMediaFile, kuwoHdr, kugouHdr] = await Promise.all([
- workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
+ crypto.request(DECRYPTION_WORKER_ACTION_NAME.FIND_QMC_MUSICEX_NAME, {
blobURI: file.raw,
}),
- workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
+ crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUWO_PARSE_HEADER, {
blobURI: file.raw,
}),
- workerClientBus.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
+ crypto.request(DECRYPTION_WORKER_ACTION_NAME.KUGOU_PARSE_HEADER, {
blobURI: file.raw,
}),
]);
@@ -89,7 +90,7 @@ export const processFile = createAsyncThunk<
kugouKey: selectKugouKey(state, kugouHdr),
qingTingAndroidKey: selectQtfmAndroidKey(state),
};
- return decryptionQueue.add({ fileId, blobURI: file.raw, options }, onPreProcess);
+ return crypto.enqueueDecrypt({ fileId, blobURI: file.raw, options }, onPreProcess);
});
export const fileListingSlice = createSlice({
diff --git a/src/features/qtfm/panel/PanelQingTing.tsx b/src/features/qtfm/panel/PanelQingTing.tsx
index 830615f..da632e4 100644
--- a/src/features/qtfm/panel/PanelQingTing.tsx
+++ b/src/features/qtfm/panel/PanelQingTing.tsx
@@ -6,14 +6,15 @@ import { selectStagingQtfmAndroidKey } from '~/features/qtfm/keyLookup';
import { parseQtfmDeviceInfoFromText, parseQtfmDeviceSecretFromText } from '~/features/qtfm/importKeys';
import { QingTingNotes } from '~/features/qtfm/instructions/QingTingNotes';
import { qtfmAndroidUpdateKey } from '~/features/settings/settingsSlice';
-import { workerClientBus } from '~/decrypt-worker/client.ts';
import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants.ts';
+import { usePlatform } from '~/platform/PlatformContext';
import { toast } from 'react-toastify';
const QTFM_DEVICE_ID_URL = 'https://github.com/parakeet-rs/qtfm-device-id/releases/latest';
export function PanelQingTing() {
const dispatch = useAppDispatch();
+ const { crypto } = usePlatform();
const secretKey = useAppSelector(selectStagingQtfmAndroidKey);
const setSecretKey = (secretKey: string) => {
dispatch(qtfmAndroidUpdateKey({ deviceKey: secretKey }));
@@ -31,7 +32,7 @@ export function PanelQingTing() {
const dataMap = parseQtfmDeviceInfoFromText(plainText);
if (dataMap) {
e.preventDefault();
- workerClientBus
+ crypto
.request(DECRYPTION_WORKER_ACTION_NAME.QINGTING_FM_GET_DEVICE_KEY, dataMap)
.then(setSecretKey, (err) => toast.error(`生成设备密钥时发生错误: ${err}`));
}
diff --git a/src/hooks.ts b/src/hooks.ts
index ec02f99..7d20a12 100644
--- a/src/hooks.ts
+++ b/src/hooks.ts
@@ -1,6 +1,7 @@
-import { useDispatch, useSelector } from 'react-redux';
+import { useDispatch, useSelector, useStore } from 'react-redux';
import type { TypedUseSelectorHook } from 'react-redux';
-import type { RootState, AppDispatch } from './store';
+import type { RootState, AppDispatch, AppStore } from './store';
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook = useSelector;
+export const useAppStore: () => AppStore = useStore;
diff --git a/src/platform/PlatformLoadGuard.tsx b/src/platform/PlatformLoadGuard.tsx
new file mode 100644
index 0000000..65c56f5
--- /dev/null
+++ b/src/platform/PlatformLoadGuard.tsx
@@ -0,0 +1,10 @@
+import { use, type PropsWithChildren, type ReactNode } from 'react';
+
+/**
+ * Suspends children until `ready` fulfills (e.g. `provider.init()` + `setPlatform`).
+ * Must be wrapped in ``.
+ */
+export function PlatformLoadGuard({ ready, children }: PropsWithChildren<{ ready: Promise }>): ReactNode {
+ use(ready);
+ return children;
+}
diff --git a/src/platform/PlatformProvider.ts b/src/platform/PlatformProvider.ts
index 9e58ec1..0ed442d 100644
--- a/src/platform/PlatformProvider.ts
+++ b/src/platform/PlatformProvider.ts
@@ -19,6 +19,8 @@ import type {
* - Every provider implements **all** methods; never omit methods or silently no-op.
* - Capability missing / platform will never support → `NotSupportedMethod`.
* - Declared / planned but not wired yet (stub) → `NotImplementedError`.
+ * - Heavy backends (e.g. decrypt worker) load only inside `init()`; constructing the provider
+ * and reading `crypto` must not create a Worker or fetch the worker chunk.
* - `capabilities` is the only UI switch source; UI must not call `supportsDirectoryPicker()` etc.
* (those helpers stay for BrowserProvider internal capability detection).
*/
@@ -26,7 +28,17 @@ export interface PlatformProvider {
readonly id: 'browser' | 'tauri';
readonly capabilities: PlatformCapabilities;
- /** RPC aligned with `WorkerActionMap`; UI should not import `decrypt-worker/client`. */
+ /**
+ * One-shot async setup (idempotent). Browser: dynamically import decrypt-worker/client and create Worker.
+ * Must complete before the first successful `crypto.request` / `enqueueDecrypt` (unless a test injects crypto).
+ * May run in parallel with `settings.load`.
+ */
+ init(): Promise;
+
+ /**
+ * RPC aligned with `WorkerActionMap`; UI should not import `decrypt-worker/client`.
+ * Obtaining this object has no side effects (no Worker).
+ */
crypto: {
request(
action: K,
diff --git a/src/platform/__tests__/BrowserProvider.test.ts b/src/platform/__tests__/BrowserProvider.test.ts
index 03351dd..959d890 100644
--- a/src/platform/__tests__/BrowserProvider.test.ts
+++ b/src/platform/__tests__/BrowserProvider.test.ts
@@ -1,7 +1,16 @@
import { AndroidImportType, BatchDownloadType } from '~/platform/capabilities';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
+import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
import { createPlatformProvider } from '~/platform/createPlatformProvider';
-import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
+import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
+
+function createMockCrypto(overrides: Partial = {}): BrowserCrypto {
+ return {
+ request: vi.fn().mockResolvedValue('9.9.9'),
+ enqueueDecrypt: vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' }),
+ ...overrides,
+ };
+}
describe('BrowserProvider', () => {
test('jsdom without directory/save pickers exposes only PackZip', () => {
@@ -34,10 +43,80 @@ describe('BrowserProvider', () => {
await expect(provider.keys.importAndroidAdb({})).rejects.toBeInstanceOf(NotSupportedMethod);
});
- test('unwired browser methods throw NotImplementedError', async () => {
- const provider = createBrowserProvider();
+ test('crypto before init rejects with PlatformNotInitializedError', async () => {
+ const loadCrypto = vi.fn();
+ const provider = createBrowserProvider({ loadCrypto });
+
+ await expect(provider.crypto.request('VERSION', null)).rejects.toSatisfy((err: unknown) => {
+ return (
+ err instanceof PlatformNotInitializedError &&
+ err.code === 'NOT_INITIALIZED' &&
+ err.capability === 'crypto.request'
+ );
+ });
+ expect(loadCrypto).not.toHaveBeenCalled();
+ });
+
+ test('constructing provider does not call loadCrypto', () => {
+ const loadCrypto = vi.fn();
+ createBrowserProvider({ loadCrypto });
+ expect(loadCrypto).not.toHaveBeenCalled();
+ });
+
+ test('init loads crypto once and is idempotent under concurrency', async () => {
+ const request = vi.fn().mockResolvedValue('9.9.9');
+ const loadCrypto = vi.fn().mockResolvedValue(createMockCrypto({ request }));
+ const provider = createBrowserProvider({ loadCrypto });
+
+ await Promise.all([provider.init(), provider.init()]);
+ await provider.init();
+
+ expect(loadCrypto).toHaveBeenCalledTimes(1);
+ await expect(provider.crypto.request('VERSION', null)).resolves.toBe('9.9.9');
+ expect(request).toHaveBeenCalledWith('VERSION', null);
+ });
+
+ test('crypto.* waits for in-flight init', async () => {
+ let resolveLoad!: (value: BrowserCrypto) => void;
+ const loadCrypto = vi.fn(
+ () =>
+ new Promise((resolve) => {
+ resolveLoad = resolve;
+ }),
+ );
+ const provider = createBrowserProvider({ loadCrypto });
+
+ const initPromise = provider.init();
+ const requestPromise = provider.crypto.request('VERSION', null);
+
+ resolveLoad(createMockCrypto());
+ await initPromise;
+ await expect(requestPromise).resolves.toBe('9.9.9');
+ });
+
+ test('crypto uses injected backend without init', async () => {
+ const request = vi.fn().mockResolvedValue('injected');
+ const enqueueDecrypt = vi.fn().mockResolvedValue({ decrypted: 'blob://out', ext: 'flac' });
+ const loadCrypto = vi.fn();
+ const provider = createBrowserProvider({ crypto: { request, enqueueDecrypt }, loadCrypto });
+
+ await expect(provider.crypto.request('VERSION', null)).resolves.toBe('injected');
+ await expect(
+ provider.crypto.enqueueDecrypt({
+ fileId: 'file://1',
+ blobURI: 'blob://in',
+ options: { fileName: 'a.bin' },
+ }),
+ ).resolves.toEqual({ decrypted: 'blob://out', ext: 'flac' });
+ await expect(provider.init()).resolves.toBeUndefined();
+ expect(loadCrypto).not.toHaveBeenCalled();
+ });
+
+ test('unwired download methods throw NotImplementedError', async () => {
+ const provider = createBrowserProvider({
+ crypto: createMockCrypto(),
+ });
- await expect(provider.crypto.request('VERSION', null)).rejects.toBeInstanceOf(NotImplementedError);
await expect(provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toBeInstanceOf(
NotImplementedError,
);
diff --git a/src/platform/__tests__/browserCrypto.test.ts b/src/platform/__tests__/browserCrypto.test.ts
new file mode 100644
index 0000000..51d92bb
--- /dev/null
+++ b/src/platform/__tests__/browserCrypto.test.ts
@@ -0,0 +1,46 @@
+import { loadDecryptWorkerCrypto } from '~/platform/browser/browserCrypto';
+import { DECRYPTION_WORKER_ACTION_NAME } from '~/decrypt-worker/constants';
+
+const { mockRequest, mockAdd } = vi.hoisted(() => ({
+ mockRequest: vi.fn(),
+ mockAdd: vi.fn(),
+}));
+
+vi.mock('~/decrypt-worker/client', () => ({
+ workerClientBus: {
+ request: mockRequest,
+ },
+ decryptionQueue: {
+ add: mockAdd,
+ },
+}));
+
+describe('loadDecryptWorkerCrypto', () => {
+ beforeEach(() => {
+ mockRequest.mockResolvedValue('1.2.3');
+ mockAdd.mockResolvedValue({ decrypted: 'blob://d', ext: 'mp3' });
+ });
+
+ test('request forwards to workerClientBus after dynamic import', async () => {
+ const crypto = await loadDecryptWorkerCrypto();
+
+ await expect(crypto.request(DECRYPTION_WORKER_ACTION_NAME.VERSION, null)).resolves.toBe('1.2.3');
+ expect(mockRequest).toHaveBeenCalledWith(DECRYPTION_WORKER_ACTION_NAME.VERSION, null);
+ });
+
+ test('enqueueDecrypt forwards to decryptionQueue.add after dynamic import', async () => {
+ const crypto = await loadDecryptWorkerCrypto();
+ const onPreProcess = vi.fn();
+ const payload = {
+ fileId: 'file://1',
+ blobURI: 'blob://in',
+ options: { fileName: 'a.bin' },
+ };
+
+ await expect(crypto.enqueueDecrypt(payload, onPreProcess)).resolves.toEqual({
+ decrypted: 'blob://d',
+ ext: 'mp3',
+ });
+ expect(mockAdd).toHaveBeenCalledWith(payload, onPreProcess);
+ });
+});
diff --git a/src/platform/__tests__/capabilities.test.ts b/src/platform/__tests__/capabilities.test.ts
index 6c06712..f529af8 100644
--- a/src/platform/__tests__/capabilities.test.ts
+++ b/src/platform/__tests__/capabilities.test.ts
@@ -1,5 +1,5 @@
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
-import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
+import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
describe('platform capabilities enums', () => {
test('BatchDownloadType members stay stable', () => {
@@ -74,3 +74,16 @@ describe('NotSupportedMethod', () => {
expect(unsupported.code).not.toBe(unimplemented.code);
});
});
+
+describe('PlatformNotInitializedError', () => {
+ test('exposes code, capability, and default message', () => {
+ const err = new PlatformNotInitializedError('crypto.request');
+
+ expect(err).toBeInstanceOf(Error);
+ expect(err).toBeInstanceOf(PlatformNotInitializedError);
+ expect(err.code).toBe('NOT_INITIALIZED');
+ expect(err.capability).toBe('crypto.request');
+ expect(err.name).toBe('PlatformNotInitializedError');
+ expect(err.message).toBe('Platform not initialized; call init() before using crypto.request');
+ });
+});
diff --git a/src/platform/browser/BrowserProvider.ts b/src/platform/browser/BrowserProvider.ts
index e1af557..e699f3d 100644
--- a/src/platform/browser/BrowserProvider.ts
+++ b/src/platform/browser/BrowserProvider.ts
@@ -1,5 +1,5 @@
import { AndroidImportType, type BatchDownloadType, type NativeImportType } from '~/platform/capabilities';
-import { NotImplementedError, NotSupportedMethod } from '~/platform/errors';
+import { NotImplementedError, NotSupportedMethod, PlatformNotInitializedError } from '~/platform/errors';
import type { PlatformProvider } from '~/platform/PlatformProvider';
import type {
AndroidAdbImportOptions,
@@ -8,6 +8,7 @@ import type {
NativeImportResult,
PlatformCapabilities,
} from '~/platform/types';
+import { loadDecryptWorkerCrypto, type BrowserCrypto } from './browserCrypto';
import { createBrowserSettingsIo, DEFAULT_SETTINGS_STORAGE_KEY, type SettingsStorage } from './browserSettingsIo';
import { detectBrowserDownloadTypes } from './detectDownloadCapabilities';
@@ -24,14 +25,21 @@ export interface BrowserProviderOptions {
settingsStorage?: SettingsStorage;
/** Defaults to `um-react-settings`. */
settingsStorageKey?: string;
+ /**
+ * Injected crypto backend (tests). When set, `crypto.*` works without loading the worker
+ * and `init()` resolves immediately.
+ */
+ crypto?: BrowserCrypto;
+ /** Defaults to dynamic-importing decrypt-worker/client. Injected in tests. */
+ loadCrypto?: () => Promise;
}
/**
* In-browser `PlatformProvider`.
* Capabilities follow runtime File System Access / save-picker probing (no DirectWrite).
* `settings` persists production settings via localStorage (or injected storage).
- * crypto / download currently throw `NotImplementedError` (not yet delegated to
- * the existing worker / download helpers).
+ * `crypto` binds to the decrypt worker only inside `init()` (dynamic import; no construct-time Worker).
+ * `download` currently throws `NotImplementedError` (not yet delegated to download helpers).
* Native and ADB key import throw `NotSupportedMethod` (`nativeKeyAccess` empty, `androidKeyAccess` None).
*/
export function createBrowserProvider(options: BrowserProviderOptions = {}): PlatformProvider {
@@ -46,15 +54,44 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
);
+ const loadCrypto = options.loadCrypto ?? loadDecryptWorkerCrypto;
+ let backend: BrowserCrypto | null = options.crypto ?? null;
+ let initPromise: Promise | null = options.crypto ? Promise.resolve() : null;
+
+ async function requireBackend(capability: string): Promise {
+ if (backend) {
+ return backend;
+ }
+ if (initPromise) {
+ await initPromise;
+ if (backend) {
+ return backend;
+ }
+ }
+ throw new PlatformNotInitializedError(capability);
+ }
+
+ const crypto: BrowserCrypto = {
+ request: (action, payload) => requireBackend('crypto.request').then((api) => api.request(action, payload)),
+ enqueueDecrypt: (payload, onPreProcess) =>
+ requireBackend('crypto.enqueueDecrypt').then((api) => api.enqueueDecrypt(payload, onPreProcess)),
+ };
+
return {
id: 'browser',
capabilities,
- crypto: {
- request: () => notImplemented('crypto.request'),
- enqueueDecrypt: () => notImplemented('crypto.enqueueDecrypt'),
+ init(): Promise {
+ if (!initPromise) {
+ initPromise = loadCrypto().then((loaded) => {
+ backend = loaded;
+ });
+ }
+ return initPromise;
},
+ crypto,
+
settings: {
load: () => settingsIo.load(),
save: (settings) => settingsIo.save(settings),
diff --git a/src/platform/browser/browserCrypto.ts b/src/platform/browser/browserCrypto.ts
new file mode 100644
index 0000000..f358d8a
--- /dev/null
+++ b/src/platform/browser/browserCrypto.ts
@@ -0,0 +1,26 @@
+import type { WorkerActionMap, WorkerActionName } from '~/decrypt-worker/actions';
+import type { DecryptionResult } from '~/decrypt-worker/constants';
+import type { DecryptCommandPayload } from '~/decrypt-worker/types';
+import type { PlatformProvider } from '~/platform/PlatformProvider';
+
+export type BrowserCrypto = PlatformProvider['crypto'];
+
+/**
+ * Lazily binds to decrypt-worker after a dynamic import.
+ * This module must not statically import `~/decrypt-worker/client` (Worker side effect).
+ */
+export async function loadDecryptWorkerCrypto(): Promise {
+ const { decryptionQueue, workerClientBus } = await import('~/decrypt-worker/client');
+
+ return {
+ request(
+ action: K,
+ payload: WorkerActionMap[K]['req'],
+ ): Promise {
+ return workerClientBus.request(action, payload);
+ },
+ enqueueDecrypt(payload: DecryptCommandPayload, onPreProcess?: () => void): Promise {
+ return decryptionQueue.add(payload, onPreProcess);
+ },
+ };
+}
diff --git a/src/platform/errors.ts b/src/platform/errors.ts
index 5818e33..2b0c717 100644
--- a/src/platform/errors.ts
+++ b/src/platform/errors.ts
@@ -14,6 +14,22 @@ export class NotImplementedError extends Error {
}
}
+/**
+ * Thrown when `crypto.*` (or other init-gated APIs) is used before `provider.init()` completes.
+ * Distinct from {@link NotImplementedError} (not wired) and {@link NotSupportedMethod} (unsupported).
+ */
+export class PlatformNotInitializedError extends Error {
+ readonly code = 'NOT_INITIALIZED' as const;
+
+ constructor(
+ readonly capability: string,
+ message?: string,
+ ) {
+ super(message ?? `Platform not initialized; call init() before using ${capability}`);
+ this.name = 'PlatformNotInitializedError';
+ }
+}
+
/**
* Thrown when the current platform explicitly does not support a method / mode
* (e.g. Browser `keys.importNative`, or `saveMany(DirectWrite)` when not in `downloadTypes`).
diff --git a/src/platform/platformSingleton.ts b/src/platform/platformSingleton.ts
index 1011b1d..e4ee229 100644
--- a/src/platform/platformSingleton.ts
+++ b/src/platform/platformSingleton.ts
@@ -1,6 +1,6 @@
import type { PlatformProvider } from './PlatformProvider';
-/** Non-React callers (thunks / modules) after AppRoot initializes the singleton. */
+/** Non-React callers (thunks / modules) after AppRoot finishes `init()` and publishes the singleton. */
let platformSingleton: PlatformProvider | null = null;
export function setPlatform(provider: PlatformProvider): void {
@@ -9,7 +9,7 @@ export function setPlatform(provider: PlatformProvider): void {
export function getPlatform(): PlatformProvider {
if (!platformSingleton) {
- throw new Error('Platform provider is not initialized. Call setPlatform() from AppRoot first.');
+ throw new Error('Platform provider is not ready. Call setPlatform() after provider.init() completes.');
}
return platformSingleton;
}
diff --git a/src/test-utils/test-helper.tsx b/src/test-utils/test-helper.tsx
index 1935caa..36b6bf9 100644
--- a/src/test-utils/test-helper.tsx
+++ b/src/test-utils/test-helper.tsx
@@ -2,8 +2,10 @@ import { RenderOptions, render } from '@testing-library/react';
import { PropsWithChildren } from 'react';
import { Provider } from 'react-redux';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
+import type { BrowserCrypto } from '~/platform/browser/browserCrypto';
import { PlatformProviderHost } from '~/platform/PlatformContext';
import type { PlatformProvider } from '~/platform/PlatformProvider';
+import { setPlatform } from '~/platform/platformSingleton';
import { AppStore, RootState, setupStore } from '~/store';
// Adapted from: https://redux.js.org/usage/writing-tests
@@ -11,10 +13,16 @@ import { AppStore, RootState, setupStore } from '~/store';
// eslint-disable-next-line react-refresh/only-export-components
export * from '@testing-library/react';
+/** Default test crypto: no dynamic import of decrypt-worker (avoids teardown races). */
+const defaultTestCrypto: BrowserCrypto = {
+ request: () => Promise.resolve(null as never),
+ enqueueDecrypt: () => Promise.reject(new Error('default test crypto: enqueueDecrypt not configured')),
+};
+
export interface ExtendedRenderOptions extends RenderOptions {
preloadedState?: Partial;
store?: AppStore;
- /** Override platform backend (defaults to BrowserProvider). */
+ /** Override platform backend (defaults to BrowserProvider with stub crypto). */
platform?: PlatformProvider;
}
@@ -23,10 +31,15 @@ export function renderWithProviders(
{
preloadedState = {},
store = setupStore(preloadedState),
- platform = createBrowserProvider(),
+ platform = createBrowserProvider({ crypto: defaultTestCrypto }),
...renderOptions
}: ExtendedRenderOptions = {},
) {
+ // Publish singleton only after init (matches AppRoot). Stub crypto resolves immediately.
+ void platform.init().then(() => {
+ setPlatform(platform);
+ });
+
function Wrapper({ children }: PropsWithChildren): React.JSX.Element {
return (