import type { Config } from "~/client/api-client/client"; import { createClient, createConfig } from "~/client/api-client/client"; export type RequestClient = ReturnType; type RequestClientStore = { getStore: () => RequestClient | undefined; run: (client: RequestClient, fn: () => T) => T; }; type AsyncLocalStorageConstructor = new () => { getStore: () => T | undefined; run: (store: T, callback: () => R) => R; }; let requestClientStore: RequestClientStore | undefined; let requestClientStorePromise: Promise | undefined; const ASYNC_HOOKS_MODULE = "node:async_hooks"; const loadRequestClientStore = async (): Promise => { if (typeof window !== "undefined") { return undefined; } if (!requestClientStorePromise) { requestClientStorePromise = (async () => { const asyncHooksModule = (await import(/* @vite-ignore */ ASYNC_HOOKS_MODULE)) as { AsyncLocalStorage: AsyncLocalStorageConstructor; }; requestClientStore = new asyncHooksModule.AsyncLocalStorage(); return requestClientStore; })(); } return requestClientStorePromise; }; export function getRequestClient(): RequestClient { const client = requestClientStore?.getStore(); if (!client) { throw new Error("No request client available"); } return client; } export async function runWithRequestClient(client: RequestClient, fn: () => T): Promise { const store = await loadRequestClientStore(); if (!store) { return fn(); } return store.run(client, fn); } export function createRequestClient(config: Config): RequestClient { return createClient(createConfig(config)); }