/** Calls a cloud function and resolves its `result`. */ export type CloudbaseFunctionCaller = (name: string, data: Record) => Promise interface CloudbaseApp { auth: (options?: { persistence: 'session' }) => unknown callFunction: (options: { name: string, data: Record }) => Promise<{ errCode?: number | string errMsg?: string result?: unknown } | undefined> } interface CloudbaseModule { default?: { init: (config: { auth: { detectSessionInUrl: false } env: string region: 'ap-shanghai' }) => CloudbaseApp } init?: (config: { auth: { detectSessionInUrl: false } env: string region: 'ap-shanghai' }) => CloudbaseApp } let cachedCloudbaseEnv = '' let cachedCloudbaseApp: Promise | undefined function getCloudbaseApp(env: string): Promise { if (cachedCloudbaseApp) { if (cachedCloudbaseEnv !== env) return Promise.reject(new Error('CloudBase environment cannot change at runtime')) return cachedCloudbaseApp } cachedCloudbaseEnv = env cachedCloudbaseApp = (async () => { const cloudbaseModule = await import('@cloudbase/js-sdk') as unknown as CloudbaseModule const cloudbase = cloudbaseModule.default ?? cloudbaseModule if (!cloudbase.init) throw new Error('@cloudbase/js-sdk does not expose init()') return cloudbase.init({ auth: { detectSessionInUrl: false }, env, region: 'ap-shanghai', }) })() cachedCloudbaseApp.catch(() => { cachedCloudbaseApp = undefined }) return cachedCloudbaseApp } /** Call a cloud function on the configured CloudBase environment. */ export async function callCloudbaseFunction( env: string, name: string, data: Record, ): Promise { const app = await getCloudbaseApp(env) // The auth client is created first so the call carries the app's session. app.auth({ persistence: 'session' }) const response = await app.callFunction({ name, data }) // A missing result means the call itself failed (not deployed, crashed, …). if (!response || response.result === undefined) throw new Error(`CloudBase function ${name} failed: ${response?.errCode ?? response?.errMsg ?? 'no result'}`) return response.result }