|
1 | | -import { AsyncLocalStorage } from "node:async_hooks"; |
2 | | -import type { ApiClientConfiguration } from "../apiClientManager/types.js"; |
| 1 | +import type { SdkScope, SdkScopeStorage } from "./types.js"; |
3 | 2 |
|
4 | | -export type SdkScope = { |
5 | | - apiClientConfig: ApiClientConfiguration; |
6 | | - inheritContext: boolean; |
7 | | -}; |
| 3 | +export type { SdkScope, SdkScopeStorage } from "./types.js"; |
| 4 | + |
| 5 | +// Storage slot. Filled at runtime by a Node-only module |
| 6 | +// (`@trigger.dev/core/v3/sdk-scope-storage`) that owns the |
| 7 | +// AsyncLocalStorage instance. Left undefined in environments that |
| 8 | +// never import that module (browsers, edge runtimes), where |
| 9 | +// `sdkScope.withScope` falls through to invoking the callback |
| 10 | +// directly. `sdkScope/index.ts` deliberately does not statically |
| 11 | +// import `node:async_hooks` or `storage-node.ts` so it is safe to |
| 12 | +// include in any browser-side bundle that reaches `@trigger.dev/core/v3`. |
| 13 | +let installedStorage: SdkScopeStorage | undefined; |
8 | 14 |
|
9 | | -const storage = new AsyncLocalStorage<SdkScope>(); |
| 15 | +export function _installSdkScopeStorage(storage: SdkScopeStorage): void { |
| 16 | + installedStorage = storage; |
| 17 | +} |
10 | 18 |
|
11 | 19 | export const sdkScope = { |
| 20 | + hasStorage(): boolean { |
| 21 | + return installedStorage !== undefined; |
| 22 | + }, |
12 | 23 | getStore(): SdkScope | undefined { |
13 | | - return storage.getStore(); |
| 24 | + return installedStorage?.getStore(); |
14 | 25 | }, |
15 | 26 | withScope<R>(scope: SdkScope, fn: () => R): R { |
16 | | - return storage.run(scope, fn); |
| 27 | + return installedStorage ? installedStorage.run(scope, fn) : fn(); |
17 | 28 | }, |
18 | 29 | }; |
0 commit comments