@amaster.ai/client 1.0.0-alpha.3 → 1.0.0-beta.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +6 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/package.json +11 -11
- package/types/asr.d.ts +11 -2
- package/types/auth/code-auth.d.ts +3 -3
- package/types/auth/index.d.ts +27 -0
- package/types/auth/user.d.ts +2 -2
- package/types/bpm.d.ts +123 -0
- package/types/copilot.d.ts +154 -37
- package/types/http.d.ts +4 -1
- package/types/index.d.ts +1 -1
package/dist/index.cjs
CHANGED
|
@@ -18,7 +18,8 @@ function createClient(options) {
|
|
|
18
18
|
headers = {},
|
|
19
19
|
onUnauthorized,
|
|
20
20
|
onTokenExpired,
|
|
21
|
-
autoHandleOAuthCallback
|
|
21
|
+
autoHandleOAuthCallback,
|
|
22
|
+
autoRedirectAfterLogin
|
|
22
23
|
} = options;
|
|
23
24
|
const baseHttpClient = httpClient.createHttpClient({
|
|
24
25
|
baseURL,
|
|
@@ -29,7 +30,8 @@ function createClient(options) {
|
|
|
29
30
|
headers,
|
|
30
31
|
onTokenExpired,
|
|
31
32
|
onUnauthorized,
|
|
32
|
-
autoHandleOAuthCallback
|
|
33
|
+
autoHandleOAuthCallback,
|
|
34
|
+
autoRedirectAfterLogin
|
|
33
35
|
});
|
|
34
36
|
const createAuthenticatedHttpClient = () => {
|
|
35
37
|
let isRefreshing = false;
|
|
@@ -131,7 +133,8 @@ function createClient(options) {
|
|
|
131
133
|
getAccessToken: () => auth.getAccessToken()
|
|
132
134
|
});
|
|
133
135
|
const asrHttp = asrClient.createASRHttpClient({
|
|
134
|
-
getAccessToken: () => auth.getAccessToken()
|
|
136
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
137
|
+
http: authenticatedHttpClient
|
|
135
138
|
});
|
|
136
139
|
const tts = ttsClient.createTTSClient({
|
|
137
140
|
getAccessToken: () => auth.getAccessToken()
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"names":["createHttpClient","createAuthClient","createEntityClient","createBpmClient","createWorkflowClient","functionClient","createFunctionClient","createCopilotClient","createS3Client","createASRClient","createASRHttpClient","createTTSClient"],"mappings":";;;;;;;;;;;;;;AA2GO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAGJ,EAAA,MAAM,iBAAiBA,2BAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,OAAmBC,2BAAA,CAAiB;AAAA,IACxC,OAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,gCAAgC,MAAkB;AAEtD,IAAA,IAAI,YAAA,GAAe,KAAA;AACnB,IAAA,IAAI,cAAA,GAA0C,IAAA;AAM9C,IAAA,SAAS,eAAe,MAAA,EAAwC;AAC9D,MAAA,IAAI,MAAA,CAAO,MAAA,KAAW,GAAA,EAAK,OAAO,KAAA;AAGlC,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,IAAW,UAAA,CAAW,KAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAG;AAClE,QAAA,OAAO,IAAA;AAAA,MACT;AAGA,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,EAAS;AACzB,QAAA,MAAM,OAAA,GAAU,OAAO,KAAA,CAAM,OAAA;AAC7B,QAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,UAAA,CAAW,IAAA,CAAK,OAAO,CAAA,EAAG;AAC3D,UAAA,O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AAe,KAAK,CAAA;AAAA,IAC5D,SAAA,EAAW,MAAM,IAAA,CAAK,SAAA;AAAU,GAClC;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * ============================================================================\n * @amaster.ai/client - Unified Amaster Client\n * ============================================================================\n *\n * Supabase-inspired unified API client for the Amaster platform\n *\n * Features:\n * - Single client instance for all services (auth, entity, bpm, workflow)\n * - Automatic token management and refresh\n * - Auto-attach authentication to all requests\n * - Centralized error handling\n *\n * @example\n * ```typescript\n * // With explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Auto-detect baseURL from env (Taro/Mini-program)\n * const client = createClient({\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Login\n * await client.auth.login({ email, password });\n *\n * // All subsequent requests automatically include auth token\n * await client.entity.list('default', 'users');\n * await client.bpm.startProcess({ processKey: 'approval' });\n * ```\n */\n\nimport { createAuthClient, type AuthClient } from \"@amaster.ai/auth-client\";\nimport { createEntityClient, type EntityClient } from \"@amaster.ai/entity-client\";\nimport { createBpmClient, type BpmClient } from \"@amaster.ai/bpm-client\";\nimport { createWorkflowClient, type WorkflowClient } from \"@amaster.ai/workflow-client\";\nimport {\n createASRClient,\n createASRHttpClient,\n type ASRClientConfig,\n type ASRClient,\n type ASRHttpClientConfig,\n type ASRHttpClient,\n} from \"@amaster.ai/asr-client\";\nimport { createCopilotClient, type CopilotClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, TTSClientConfig, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport {\n createHttpClient,\n type HttpClient,\n type RequestConfig,\n type ClientResult,\n} from \"@amaster.ai/http-client\";\nimport type { AmasterClient, AmasterClientOptions } from \"./types\";\n\n/**\n * Create a unified Amaster client instance\n *\n * This function creates a single client that provides access to all Amaster services:\n * - Authentication (login, register, logout)\n * - Entity CRUD operations\n * - BPM (Business Process Management)\n * - Workflow execution\n *\n * All sub-clients automatically share the same HTTP client and authentication state,\n * ensuring that tokens are consistently attached to all requests.\n *\n * @param options - Client configuration options\n * @returns A unified Amaster client instance\n *\n * @example\n * ```typescript\n * // Basic usage with explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai'\n * });\n *\n * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)\n * const client = createClient({});\n *\n * // With authentication callbacks\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => {\n * // Redirect to login or show auth modal\n * window.location.href = '/login';\n * },\n * onTokenExpired: () => {\n * console.log('Token expired, refreshing...');\n * }\n * });\n *\n * // Login\n * await client.auth.login({\n * email: 'user@example.com',\n * password: 'password123'\n * });\n *\n * // Now all requests automatically include the auth token\n * const users = await client.entity.list('default', 'users');\n * const tasks = await client.bpm.getMyTasks();\n * ```\n */\nexport function createClient(options: AmasterClientOptions): AmasterClient {\n const {\n baseURL,\n headers = {},\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n });\n\n // Create the auth client first (it manages its own HTTP client internally)\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\n // Track if we're currently refreshing to avoid multiple simultaneous refreshes\n let isRefreshing = false;\n let refreshPromise: Promise<boolean> | null = null;\n\n /**\n * Check if 401 error is due to token expiration\n * Traefik JWT plugin returns plain text like \"Jwt is expired\" or \"Token is expired\"\n */\n function isTokenExpired(result: ClientResult<unknown>): boolean {\n if (result.status !== 401) return false;\n\n // Check error message (could be from backend JSON response)\n if (result.error?.message && /expired/i.test(result.error.message)) {\n return true;\n }\n\n // Check error details (traefik returns plain text in details)\n if (result.error?.details) {\n const details = result.error.details;\n if (typeof details === \"string\" && /expired/i.test(details)) {\n return true;\n }\n // Also check if details is an object with message field\n if (typeof details === \"object\" && details !== null) {\n const detailsObj = details as Record<string, unknown>;\n if (typeof detailsObj.message === \"string\" && /expired/i.test(detailsObj.message)) {\n return true;\n }\n }\n }\n\n // Check raw data (could be plain text from traefik)\n if (typeof result.data === \"string\" && /expired/i.test(result.data)) {\n return true;\n }\n\n // If we have a token but got 401, assume it might be expired\n return !!auth.getAccessToken();\n }\n\n return {\n async request<T>(config: RequestConfig): Promise<ClientResult<T>> {\n // Get the current token from auth client\n const token = auth.getAccessToken();\n\n // Merge Authorization header with existing headers\n const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};\n const mergedConfig: RequestConfig = {\n ...config,\n headers: {\n ...config.headers,\n ...authHeaders,\n },\n };\n\n // Make the request with the updated config\n let result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors with automatic token refresh\n if (result.status === 401 && isTokenExpired(result)) {\n // Attempt to refresh token\n if (!isRefreshing) {\n isRefreshing = true;\n refreshPromise = (async () => {\n try {\n const refreshResult = await auth.refreshToken();\n return !!refreshResult.data;\n } finally {\n isRefreshing = false;\n refreshPromise = null;\n }\n })();\n }\n\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Retry with new token\n const newToken = auth.getAccessToken();\n result = await baseHttpClient.request<T>({\n ...config,\n headers: {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n },\n });\n }\n }\n\n // Trigger unauthorized if still 401\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n const authenticatedHttpClient = createAuthenticatedHttpClient();\n\n let cachedUserUid: string | null = null;\n\n auth.on(\"login\", (user: { uid?: string }) => {\n cachedUserUid = user?.uid ?? null;\n });\n auth.on(\"logout\", () => {\n cachedUserUid = null;\n });\n\n if (auth.isAuthenticated()) {\n auth\n .getMe()\n .then((result) => {\n if (result.data?.uid) {\n cachedUserUid = result.data.uid;\n }\n })\n .catch(() => {});\n }\n\n // Create other clients using the authenticated HTTP client\n const entity: EntityClient = createEntityClient(authenticatedHttpClient);\n const bpm: BpmClient = createBpmClient(authenticatedHttpClient);\n const workflow: WorkflowClient = createWorkflowClient(authenticatedHttpClient);\n const functionClient: FunctionClient = createFunctionClient(authenticatedHttpClient);\n const copilot: CopilotClient = createCopilotClient(\n authenticatedHttpClient,\n baseURL,\n () => auth.getAccessToken(),\n () => cachedUserUid\n );\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, pass token getter for authentication\n // Token can be appended to WebSocket URL as query parameter\n const asr: (config: ASRClientConfig) => ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient = createASRHttpClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const tts: (config: TTSClientConfig) => TTSClient = createTTSClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n asrHttp,\n copilot,\n function: functionClient,\n tts,\n s3,\n http: authenticatedHttpClient,\n\n // Expose token management methods from auth client\n isAuthenticated: () => auth.isAuthenticated(),\n getAccessToken: () => auth.getAccessToken(),\n setAccessToken: (token: string) => auth.setAccessToken(token),\n clearAuth: () => auth.clearAuth(),\n };\n\n return client;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"names":["createHttpClient","createAuthClient","createEntityClient","createBpmClient","createWorkflowClient","functionClient","createFunctionClient","createCopilotClient","createS3Client","createASRClient","createASRHttpClient","createTTSClient"],"mappings":";;;;;;;;;;;;;;AA2GO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,cAAA;AAAA,IACA,cAAA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IACA,MAAM,KAAK,cAAA,EAAe;AAAA,IAC1B,MAAM;AAAA,GACR;AACA,EAAA,MAAM,EAAA,GAAeC,wBAAe,uBAAuB,CAAA;AAI3D,EAAA,MAAM,MAA8CC,yBAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AACD,EAAA,MAAM,UAA0DC,6BAAA,CAAoB;AAAA,IAClF,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,IAAA,EAAM;AAAA,GACP,CAAA;AACD,EAAA,MAAM,MAA8CC,yBAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AAGD,EAAA,MAAM,MAAA,GAAwB;AAAA,IAC5B,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA,EAAUN,gBAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA,IACA,IAAA,EAAM,uBAAA;AAAA;AAAA,IAGN,eAAA,EAAiB,MAAM,IAAA,CAAK,eAAA,EAAgB;AAAA,IAC5C,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,cAAA,EAAgB,CAAC,KAAA,KAAkB,IAAA,CAAK,eAAe,KAAK,CAAA;AAAA,IAC5D,SAAA,EAAW,MAAM,IAAA,CAAK,SAAA;AAAU,GAClC;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * ============================================================================\n * @amaster.ai/client - Unified Amaster Client\n * ============================================================================\n *\n * Supabase-inspired unified API client for the Amaster platform\n *\n * Features:\n * - Single client instance for all services (auth, entity, bpm, workflow)\n * - Automatic token management and refresh\n * - Auto-attach authentication to all requests\n * - Centralized error handling\n *\n * @example\n * ```typescript\n * // With explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Auto-detect baseURL from env (Taro/Mini-program)\n * const client = createClient({\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Login\n * await client.auth.login({ email, password });\n *\n * // All subsequent requests automatically include auth token\n * await client.entity.list('default', 'users');\n * await client.bpm.startProcess({ processKey: 'approval' });\n * ```\n */\n\nimport { createAuthClient, type AuthClient } from \"@amaster.ai/auth-client\";\nimport { createEntityClient, type EntityClient } from \"@amaster.ai/entity-client\";\nimport { createBpmClient, type BpmClient } from \"@amaster.ai/bpm-client\";\nimport { createWorkflowClient, type WorkflowClient } from \"@amaster.ai/workflow-client\";\nimport {\n createASRClient,\n createASRHttpClient,\n type ASRClientConfig,\n type ASRClient,\n type ASRHttpClientConfig,\n type ASRHttpClient,\n} from \"@amaster.ai/asr-client\";\nimport { createCopilotClient, type CopilotClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, TTSClientConfig, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport {\n createHttpClient,\n type HttpClient,\n type RequestConfig,\n type ClientResult,\n} from \"@amaster.ai/http-client\";\nimport type { AmasterClient, AmasterClientOptions } from \"./types\";\n\n/**\n * Create a unified Amaster client instance\n *\n * This function creates a single client that provides access to all Amaster services:\n * - Authentication (login, register, logout)\n * - Entity CRUD operations\n * - BPM (Business Process Management)\n * - Workflow execution\n *\n * All sub-clients automatically share the same HTTP client and authentication state,\n * ensuring that tokens are consistently attached to all requests.\n *\n * @param options - Client configuration options\n * @returns A unified Amaster client instance\n *\n * @example\n * ```typescript\n * // Basic usage with explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai'\n * });\n *\n * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)\n * const client = createClient({});\n *\n * // With authentication callbacks\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => {\n * // Redirect to login or show auth modal\n * window.location.href = '/login';\n * },\n * onTokenExpired: () => {\n * console.log('Token expired, refreshing...');\n * }\n * });\n *\n * // Login\n * await client.auth.login({\n * email: 'user@example.com',\n * password: 'password123'\n * });\n *\n * // Now all requests automatically include the auth token\n * const users = await client.entity.list('default', 'users');\n * const tasks = await client.bpm.getMyTasks();\n * ```\n */\nexport function createClient(options: AmasterClientOptions): AmasterClient {\n const {\n baseURL,\n headers = {},\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n });\n\n // Create the auth client first using the same base HTTP implementation so\n // mini-program request handling stays consistent across all modules.\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\n // Track if we're currently refreshing to avoid multiple simultaneous refreshes\n let isRefreshing = false;\n let refreshPromise: Promise<boolean> | null = null;\n\n /**\n * Check if 401 error is due to token expiration\n * Traefik JWT plugin returns plain text like \"Jwt is expired\" or \"Token is expired\"\n */\n function isTokenExpired(result: ClientResult<unknown>): boolean {\n if (result.status !== 401) return false;\n\n // Check error message (could be from backend JSON response)\n if (result.error?.message && /expired/i.test(result.error.message)) {\n return true;\n }\n\n // Check error details (traefik returns plain text in details)\n if (result.error?.details) {\n const details = result.error.details;\n if (typeof details === \"string\" && /expired/i.test(details)) {\n return true;\n }\n // Also check if details is an object with message field\n if (typeof details === \"object\" && details !== null) {\n const detailsObj = details as Record<string, unknown>;\n if (typeof detailsObj.message === \"string\" && /expired/i.test(detailsObj.message)) {\n return true;\n }\n }\n }\n\n // Check raw data (could be plain text from traefik)\n if (typeof result.data === \"string\" && /expired/i.test(result.data)) {\n return true;\n }\n\n // If we have a token but got 401, assume it might be expired\n return !!auth.getAccessToken();\n }\n\n return {\n async request<T>(config: RequestConfig): Promise<ClientResult<T>> {\n // Get the current token from auth client\n const token = auth.getAccessToken();\n\n // Merge Authorization header with existing headers\n const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};\n const mergedConfig: RequestConfig = {\n ...config,\n headers: {\n ...config.headers,\n ...authHeaders,\n },\n };\n\n // Make the request with the updated config\n let result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors with automatic token refresh\n if (result.status === 401 && isTokenExpired(result)) {\n // Attempt to refresh token\n if (!isRefreshing) {\n isRefreshing = true;\n refreshPromise = (async () => {\n try {\n const refreshResult = await auth.refreshToken();\n return !!refreshResult.data;\n } finally {\n isRefreshing = false;\n refreshPromise = null;\n }\n })();\n }\n\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Retry with new token\n const newToken = auth.getAccessToken();\n result = await baseHttpClient.request<T>({\n ...config,\n headers: {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n },\n });\n }\n }\n\n // Trigger unauthorized if still 401\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n const authenticatedHttpClient = createAuthenticatedHttpClient();\n\n let cachedUserUid: string | null = null;\n\n auth.on(\"login\", (user: { uid?: string }) => {\n cachedUserUid = user?.uid ?? null;\n });\n auth.on(\"logout\", () => {\n cachedUserUid = null;\n });\n\n if (auth.isAuthenticated()) {\n auth\n .getMe()\n .then((result) => {\n if (result.data?.uid) {\n cachedUserUid = result.data.uid;\n }\n })\n .catch(() => {});\n }\n\n // Create other clients using the authenticated HTTP client\n const entity: EntityClient = createEntityClient(authenticatedHttpClient);\n const bpm: BpmClient = createBpmClient(authenticatedHttpClient);\n const workflow: WorkflowClient = createWorkflowClient(authenticatedHttpClient);\n const functionClient: FunctionClient = createFunctionClient(authenticatedHttpClient);\n const copilot: CopilotClient = createCopilotClient(\n authenticatedHttpClient,\n baseURL,\n () => auth.getAccessToken(),\n () => cachedUserUid\n );\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, pass token getter for authentication\n // Token can be appended to WebSocket URL as query parameter\n const asr: (config: ASRClientConfig) => ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient = createASRHttpClient({\n getAccessToken: () => auth.getAccessToken(),\n http: authenticatedHttpClient,\n });\n const tts: (config: TTSClientConfig) => TTSClient = createTTSClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n asrHttp,\n copilot,\n function: functionClient,\n tts,\n s3,\n http: authenticatedHttpClient,\n\n // Expose token management methods from auth client\n isAuthenticated: () => auth.isAuthenticated(),\n getAccessToken: () => auth.getAccessToken(),\n setAccessToken: (token: string) => auth.setAccessToken(token),\n clearAuth: () => auth.clearAuth(),\n };\n\n return client;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -9,7 +9,7 @@ export { WorkflowFile, WorkflowInputValue, WorkflowRunRequest, WorkflowRunRespon
|
|
|
9
9
|
import { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from '@amaster.ai/asr-client';
|
|
10
10
|
export { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, ASRLanguage } from '@amaster.ai/asr-client';
|
|
11
11
|
import { CopilotClient } from '@amaster.ai/copilot-client';
|
|
12
|
-
export {
|
|
12
|
+
export { Conversation, ConversationController, ConversationControllerOptions, ConversationControllerSnapshot, CopilotClient, Role as CopilotRole, ErrorMessage, FileContent, ImageContent, MessageContent, MessagesItem, TextContent, TextMessage, ThoughtMessage, ToolMessage, UIRenderMessage } from '@amaster.ai/copilot-client';
|
|
13
13
|
import { FunctionClient } from '@amaster.ai/function-client';
|
|
14
14
|
export { FunctionClient } from '@amaster.ai/function-client';
|
|
15
15
|
import { TTSClientConfig, TTSClient } from '@amaster.ai/tts-client';
|
|
@@ -69,6 +69,15 @@ interface AmasterClientOptions {
|
|
|
69
69
|
* @default true
|
|
70
70
|
*/
|
|
71
71
|
autoHandleOAuthCallback?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Automatically redirect to the current page's `?redirect=...` target after any successful login
|
|
74
|
+
*
|
|
75
|
+
* This keeps password login, verification-code login, registration auto-login,
|
|
76
|
+
* and OAuth callback flows aligned by default.
|
|
77
|
+
*
|
|
78
|
+
* @default true
|
|
79
|
+
*/
|
|
80
|
+
autoRedirectAfterLogin?: boolean;
|
|
72
81
|
}
|
|
73
82
|
/**
|
|
74
83
|
* Unified Amaster Client
|
|
@@ -161,6 +170,8 @@ interface AmasterClient {
|
|
|
161
170
|
* @example
|
|
162
171
|
* ```typescript
|
|
163
172
|
* // Real-time streaming recognition
|
|
173
|
+
* import { createClient } from "@amaster.ai/client";
|
|
174
|
+
* export const client = createClient({});
|
|
164
175
|
* const asrClient = client.asr({
|
|
165
176
|
* onReady() {
|
|
166
177
|
* console.log('ASR Ready');
|
|
@@ -194,6 +205,8 @@ interface AmasterClient {
|
|
|
194
205
|
* @example
|
|
195
206
|
* ```typescript
|
|
196
207
|
* // Press-to-talk recognition
|
|
208
|
+
* import { createClient } from "@amaster.ai/client";
|
|
209
|
+
* export const client = createClient({});
|
|
197
210
|
* const asrHttpClient = client.asrHttp({
|
|
198
211
|
* onRecordingStart() {
|
|
199
212
|
* console.log('Recording started');
|
|
@@ -247,6 +260,8 @@ interface AmasterClient {
|
|
|
247
260
|
* @example
|
|
248
261
|
* ```typescript
|
|
249
262
|
* // Connect and speak
|
|
263
|
+
* import { createClient } from "@amaster.ai/client";
|
|
264
|
+
* export const client = createClient({});
|
|
250
265
|
* const ttsClient = client.tts({
|
|
251
266
|
* voice: 'Cherry',
|
|
252
267
|
* autoPlay: true,
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export { WorkflowFile, WorkflowInputValue, WorkflowRunRequest, WorkflowRunRespon
|
|
|
9
9
|
import { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from '@amaster.ai/asr-client';
|
|
10
10
|
export { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, ASRLanguage } from '@amaster.ai/asr-client';
|
|
11
11
|
import { CopilotClient } from '@amaster.ai/copilot-client';
|
|
12
|
-
export {
|
|
12
|
+
export { Conversation, ConversationController, ConversationControllerOptions, ConversationControllerSnapshot, CopilotClient, Role as CopilotRole, ErrorMessage, FileContent, ImageContent, MessageContent, MessagesItem, TextContent, TextMessage, ThoughtMessage, ToolMessage, UIRenderMessage } from '@amaster.ai/copilot-client';
|
|
13
13
|
import { FunctionClient } from '@amaster.ai/function-client';
|
|
14
14
|
export { FunctionClient } from '@amaster.ai/function-client';
|
|
15
15
|
import { TTSClientConfig, TTSClient } from '@amaster.ai/tts-client';
|
|
@@ -69,6 +69,15 @@ interface AmasterClientOptions {
|
|
|
69
69
|
* @default true
|
|
70
70
|
*/
|
|
71
71
|
autoHandleOAuthCallback?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Automatically redirect to the current page's `?redirect=...` target after any successful login
|
|
74
|
+
*
|
|
75
|
+
* This keeps password login, verification-code login, registration auto-login,
|
|
76
|
+
* and OAuth callback flows aligned by default.
|
|
77
|
+
*
|
|
78
|
+
* @default true
|
|
79
|
+
*/
|
|
80
|
+
autoRedirectAfterLogin?: boolean;
|
|
72
81
|
}
|
|
73
82
|
/**
|
|
74
83
|
* Unified Amaster Client
|
|
@@ -161,6 +170,8 @@ interface AmasterClient {
|
|
|
161
170
|
* @example
|
|
162
171
|
* ```typescript
|
|
163
172
|
* // Real-time streaming recognition
|
|
173
|
+
* import { createClient } from "@amaster.ai/client";
|
|
174
|
+
* export const client = createClient({});
|
|
164
175
|
* const asrClient = client.asr({
|
|
165
176
|
* onReady() {
|
|
166
177
|
* console.log('ASR Ready');
|
|
@@ -194,6 +205,8 @@ interface AmasterClient {
|
|
|
194
205
|
* @example
|
|
195
206
|
* ```typescript
|
|
196
207
|
* // Press-to-talk recognition
|
|
208
|
+
* import { createClient } from "@amaster.ai/client";
|
|
209
|
+
* export const client = createClient({});
|
|
197
210
|
* const asrHttpClient = client.asrHttp({
|
|
198
211
|
* onRecordingStart() {
|
|
199
212
|
* console.log('Recording started');
|
|
@@ -247,6 +260,8 @@ interface AmasterClient {
|
|
|
247
260
|
* @example
|
|
248
261
|
* ```typescript
|
|
249
262
|
* // Connect and speak
|
|
263
|
+
* import { createClient } from "@amaster.ai/client";
|
|
264
|
+
* export const client = createClient({});
|
|
250
265
|
* const ttsClient = client.tts({
|
|
251
266
|
* voice: 'Cherry',
|
|
252
267
|
* autoPlay: true,
|
package/dist/index.js
CHANGED
|
@@ -16,7 +16,8 @@ function createClient(options) {
|
|
|
16
16
|
headers = {},
|
|
17
17
|
onUnauthorized,
|
|
18
18
|
onTokenExpired,
|
|
19
|
-
autoHandleOAuthCallback
|
|
19
|
+
autoHandleOAuthCallback,
|
|
20
|
+
autoRedirectAfterLogin
|
|
20
21
|
} = options;
|
|
21
22
|
const baseHttpClient = createHttpClient({
|
|
22
23
|
baseURL,
|
|
@@ -27,7 +28,8 @@ function createClient(options) {
|
|
|
27
28
|
headers,
|
|
28
29
|
onTokenExpired,
|
|
29
30
|
onUnauthorized,
|
|
30
|
-
autoHandleOAuthCallback
|
|
31
|
+
autoHandleOAuthCallback,
|
|
32
|
+
autoRedirectAfterLogin
|
|
31
33
|
});
|
|
32
34
|
const createAuthenticatedHttpClient = () => {
|
|
33
35
|
let isRefreshing = false;
|
|
@@ -129,7 +131,8 @@ function createClient(options) {
|
|
|
129
131
|
getAccessToken: () => auth.getAccessToken()
|
|
130
132
|
});
|
|
131
133
|
const asrHttp = createASRHttpClient({
|
|
132
|
-
getAccessToken: () => auth.getAccessToken()
|
|
134
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
135
|
+
http: authenticatedHttpClient
|
|
133
136
|
});
|
|
134
137
|
const tts = createTTSClient({
|
|
135
138
|
getAccessToken: () => auth.getAccessToken()
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";;;;;;;;;;;;AA2GO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAGJ,EAAA,MAAM,iBAAiB,gBAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,OAAmB,gBAAA,CAAiB;AAAA,IACxC,OAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,gCAAgC,MAAkB;AAEtD,IAAA,IAAI,YAAA,GAAe,KAAA;AACnB,IAAA,IAAI,cAAA,GAA0C,IAAA;AAM9C,IAAA,SAAS,eAAe,MAAA,EAAwC;AAC9D,MAAA,IAAI,MAAA,CAAO,MAAA,KAAW,GAAA,EAAK,OAAO,KAAA;AAGlC,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,IAAW,UAAA,CAAW,KAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAG;AAClE,QAAA,OAAO,IAAA;AAAA,MACT;AAGA,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,EAAS;AACzB,QAAA,MAAM,OAAA,GAAU,OAAO,KAAA,CAAM,OAAA;AAC7B,QAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,UAAA,CAAW,IAAA,CAAK,OAAO,CAAA,EAAG;AAC3D,UAAA,OAAO,IAAA;AAAA,QACT;AAEA,QAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAA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AA;AACT","file":"index.js","sourcesContent":["/**\n * ============================================================================\n * @amaster.ai/client - Unified Amaster Client\n * ============================================================================\n *\n * Supabase-inspired unified API client for the Amaster platform\n *\n * Features:\n * - Single client instance for all services (auth, entity, bpm, workflow)\n * - Automatic token management and refresh\n * - Auto-attach authentication to all requests\n * - Centralized error handling\n *\n * @example\n * ```typescript\n * // With explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Auto-detect baseURL from env (Taro/Mini-program)\n * const client = createClient({\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Login\n * await client.auth.login({ email, password });\n *\n * // All subsequent requests automatically include auth token\n * await client.entity.list('default', 'users');\n * await client.bpm.startProcess({ processKey: 'approval' });\n * ```\n */\n\nimport { createAuthClient, type AuthClient } from \"@amaster.ai/auth-client\";\nimport { createEntityClient, type EntityClient } from \"@amaster.ai/entity-client\";\nimport { createBpmClient, type BpmClient } from \"@amaster.ai/bpm-client\";\nimport { createWorkflowClient, type WorkflowClient } from \"@amaster.ai/workflow-client\";\nimport {\n createASRClient,\n createASRHttpClient,\n type ASRClientConfig,\n type ASRClient,\n type ASRHttpClientConfig,\n type ASRHttpClient,\n} from \"@amaster.ai/asr-client\";\nimport { createCopilotClient, type CopilotClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, TTSClientConfig, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport {\n createHttpClient,\n type HttpClient,\n type RequestConfig,\n type ClientResult,\n} from \"@amaster.ai/http-client\";\nimport type { AmasterClient, AmasterClientOptions } from \"./types\";\n\n/**\n * Create a unified Amaster client instance\n *\n * This function creates a single client that provides access to all Amaster services:\n * - Authentication (login, register, logout)\n * - Entity CRUD operations\n * - BPM (Business Process Management)\n * - Workflow execution\n *\n * All sub-clients automatically share the same HTTP client and authentication state,\n * ensuring that tokens are consistently attached to all requests.\n *\n * @param options - Client configuration options\n * @returns A unified Amaster client instance\n *\n * @example\n * ```typescript\n * // Basic usage with explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai'\n * });\n *\n * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)\n * const client = createClient({});\n *\n * // With authentication callbacks\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => {\n * // Redirect to login or show auth modal\n * window.location.href = '/login';\n * },\n * onTokenExpired: () => {\n * console.log('Token expired, refreshing...');\n * }\n * });\n *\n * // Login\n * await client.auth.login({\n * email: 'user@example.com',\n * password: 'password123'\n * });\n *\n * // Now all requests automatically include the auth token\n * const users = await client.entity.list('default', 'users');\n * const tasks = await client.bpm.getMyTasks();\n * ```\n */\nexport function createClient(options: AmasterClientOptions): AmasterClient {\n const {\n baseURL,\n headers = {},\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n });\n\n // Create the auth client first (it manages its own HTTP client internally)\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\n // Track if we're currently refreshing to avoid multiple simultaneous refreshes\n let isRefreshing = false;\n let refreshPromise: Promise<boolean> | null = null;\n\n /**\n * Check if 401 error is due to token expiration\n * Traefik JWT plugin returns plain text like \"Jwt is expired\" or \"Token is expired\"\n */\n function isTokenExpired(result: ClientResult<unknown>): boolean {\n if (result.status !== 401) return false;\n\n // Check error message (could be from backend JSON response)\n if (result.error?.message && /expired/i.test(result.error.message)) {\n return true;\n }\n\n // Check error details (traefik returns plain text in details)\n if (result.error?.details) {\n const details = result.error.details;\n if (typeof details === \"string\" && /expired/i.test(details)) {\n return true;\n }\n // Also check if details is an object with message field\n if (typeof details === \"object\" && details !== null) {\n const detailsObj = details as Record<string, unknown>;\n if (typeof detailsObj.message === \"string\" && /expired/i.test(detailsObj.message)) {\n return true;\n }\n }\n }\n\n // Check raw data (could be plain text from traefik)\n if (typeof result.data === \"string\" && /expired/i.test(result.data)) {\n return true;\n }\n\n // If we have a token but got 401, assume it might be expired\n return !!auth.getAccessToken();\n }\n\n return {\n async request<T>(config: RequestConfig): Promise<ClientResult<T>> {\n // Get the current token from auth client\n const token = auth.getAccessToken();\n\n // Merge Authorization header with existing headers\n const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};\n const mergedConfig: RequestConfig = {\n ...config,\n headers: {\n ...config.headers,\n ...authHeaders,\n },\n };\n\n // Make the request with the updated config\n let result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors with automatic token refresh\n if (result.status === 401 && isTokenExpired(result)) {\n // Attempt to refresh token\n if (!isRefreshing) {\n isRefreshing = true;\n refreshPromise = (async () => {\n try {\n const refreshResult = await auth.refreshToken();\n return !!refreshResult.data;\n } finally {\n isRefreshing = false;\n refreshPromise = null;\n }\n })();\n }\n\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Retry with new token\n const newToken = auth.getAccessToken();\n result = await baseHttpClient.request<T>({\n ...config,\n headers: {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n },\n });\n }\n }\n\n // Trigger unauthorized if still 401\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n const authenticatedHttpClient = createAuthenticatedHttpClient();\n\n let cachedUserUid: string | null = null;\n\n auth.on(\"login\", (user: { uid?: string }) => {\n cachedUserUid = user?.uid ?? null;\n });\n auth.on(\"logout\", () => {\n cachedUserUid = null;\n });\n\n if (auth.isAuthenticated()) {\n auth\n .getMe()\n .then((result) => {\n if (result.data?.uid) {\n cachedUserUid = result.data.uid;\n }\n })\n .catch(() => {});\n }\n\n // Create other clients using the authenticated HTTP client\n const entity: EntityClient = createEntityClient(authenticatedHttpClient);\n const bpm: BpmClient = createBpmClient(authenticatedHttpClient);\n const workflow: WorkflowClient = createWorkflowClient(authenticatedHttpClient);\n const functionClient: FunctionClient = createFunctionClient(authenticatedHttpClient);\n const copilot: CopilotClient = createCopilotClient(\n authenticatedHttpClient,\n baseURL,\n () => auth.getAccessToken(),\n () => cachedUserUid\n );\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, pass token getter for authentication\n // Token can be appended to WebSocket URL as query parameter\n const asr: (config: ASRClientConfig) => ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient = createASRHttpClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const tts: (config: TTSClientConfig) => TTSClient = createTTSClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n asrHttp,\n copilot,\n function: functionClient,\n tts,\n s3,\n http: authenticatedHttpClient,\n\n // Expose token management methods from auth client\n isAuthenticated: () => auth.isAuthenticated(),\n getAccessToken: () => auth.getAccessToken(),\n setAccessToken: (token: string) => auth.setAccessToken(token),\n clearAuth: () => auth.clearAuth(),\n };\n\n return client;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";;;;;;;;;;;;AA2GO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,cAAA;AAAA,IACA,cAAA;AAAA,IACA,uBAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAGJ,EAAA,MAAM,iBAAiB,gBAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAID,EAAA,MAAM,OAAmB,gBAAA,CAAiB;AAAA,IACxC,OAAA;AAAA,IACA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ACD,EAAA,MAAM,UAA0D,mBAAA,CAAoB;AAAA,IAClF,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,IAAA,EAAM;AAAA,GACP,CAAA;AACD,EAAA,MAAM,MAA8C,eAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AAGD,EAAA,MAAM,MAAA,GAAwB;AAAA,IAC5B,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA,EAAU,cAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA,IACA,IAAA,EAAM,uBAAA;AAAA;AAAA,IAGN,eAAA,EAAiB,MAAM,IAAA,CAAK,eAAA,EAAgB;AAAA,IAC5C,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,cAAA,EAAgB,CAAC,KAAA,KAAkB,IAAA,CAAK,eAAe,KAAK,CAAA;AAAA,IAC5D,SAAA,EAAW,MAAM,IAAA,CAAK,SAAA;AAAU,GAClC;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["/**\n * ============================================================================\n * @amaster.ai/client - Unified Amaster Client\n * ============================================================================\n *\n * Supabase-inspired unified API client for the Amaster platform\n *\n * Features:\n * - Single client instance for all services (auth, entity, bpm, workflow)\n * - Automatic token management and refresh\n * - Auto-attach authentication to all requests\n * - Centralized error handling\n *\n * @example\n * ```typescript\n * // With explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Auto-detect baseURL from env (Taro/Mini-program)\n * const client = createClient({\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Login\n * await client.auth.login({ email, password });\n *\n * // All subsequent requests automatically include auth token\n * await client.entity.list('default', 'users');\n * await client.bpm.startProcess({ processKey: 'approval' });\n * ```\n */\n\nimport { createAuthClient, type AuthClient } from \"@amaster.ai/auth-client\";\nimport { createEntityClient, type EntityClient } from \"@amaster.ai/entity-client\";\nimport { createBpmClient, type BpmClient } from \"@amaster.ai/bpm-client\";\nimport { createWorkflowClient, type WorkflowClient } from \"@amaster.ai/workflow-client\";\nimport {\n createASRClient,\n createASRHttpClient,\n type ASRClientConfig,\n type ASRClient,\n type ASRHttpClientConfig,\n type ASRHttpClient,\n} from \"@amaster.ai/asr-client\";\nimport { createCopilotClient, type CopilotClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, TTSClientConfig, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport {\n createHttpClient,\n type HttpClient,\n type RequestConfig,\n type ClientResult,\n} from \"@amaster.ai/http-client\";\nimport type { AmasterClient, AmasterClientOptions } from \"./types\";\n\n/**\n * Create a unified Amaster client instance\n *\n * This function creates a single client that provides access to all Amaster services:\n * - Authentication (login, register, logout)\n * - Entity CRUD operations\n * - BPM (Business Process Management)\n * - Workflow execution\n *\n * All sub-clients automatically share the same HTTP client and authentication state,\n * ensuring that tokens are consistently attached to all requests.\n *\n * @param options - Client configuration options\n * @returns A unified Amaster client instance\n *\n * @example\n * ```typescript\n * // Basic usage with explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai'\n * });\n *\n * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)\n * const client = createClient({});\n *\n * // With authentication callbacks\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => {\n * // Redirect to login or show auth modal\n * window.location.href = '/login';\n * },\n * onTokenExpired: () => {\n * console.log('Token expired, refreshing...');\n * }\n * });\n *\n * // Login\n * await client.auth.login({\n * email: 'user@example.com',\n * password: 'password123'\n * });\n *\n * // Now all requests automatically include the auth token\n * const users = await client.entity.list('default', 'users');\n * const tasks = await client.bpm.getMyTasks();\n * ```\n */\nexport function createClient(options: AmasterClientOptions): AmasterClient {\n const {\n baseURL,\n headers = {},\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n });\n\n // Create the auth client first using the same base HTTP implementation so\n // mini-program request handling stays consistent across all modules.\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\n // Track if we're currently refreshing to avoid multiple simultaneous refreshes\n let isRefreshing = false;\n let refreshPromise: Promise<boolean> | null = null;\n\n /**\n * Check if 401 error is due to token expiration\n * Traefik JWT plugin returns plain text like \"Jwt is expired\" or \"Token is expired\"\n */\n function isTokenExpired(result: ClientResult<unknown>): boolean {\n if (result.status !== 401) return false;\n\n // Check error message (could be from backend JSON response)\n if (result.error?.message && /expired/i.test(result.error.message)) {\n return true;\n }\n\n // Check error details (traefik returns plain text in details)\n if (result.error?.details) {\n const details = result.error.details;\n if (typeof details === \"string\" && /expired/i.test(details)) {\n return true;\n }\n // Also check if details is an object with message field\n if (typeof details === \"object\" && details !== null) {\n const detailsObj = details as Record<string, unknown>;\n if (typeof detailsObj.message === \"string\" && /expired/i.test(detailsObj.message)) {\n return true;\n }\n }\n }\n\n // Check raw data (could be plain text from traefik)\n if (typeof result.data === \"string\" && /expired/i.test(result.data)) {\n return true;\n }\n\n // If we have a token but got 401, assume it might be expired\n return !!auth.getAccessToken();\n }\n\n return {\n async request<T>(config: RequestConfig): Promise<ClientResult<T>> {\n // Get the current token from auth client\n const token = auth.getAccessToken();\n\n // Merge Authorization header with existing headers\n const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};\n const mergedConfig: RequestConfig = {\n ...config,\n headers: {\n ...config.headers,\n ...authHeaders,\n },\n };\n\n // Make the request with the updated config\n let result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors with automatic token refresh\n if (result.status === 401 && isTokenExpired(result)) {\n // Attempt to refresh token\n if (!isRefreshing) {\n isRefreshing = true;\n refreshPromise = (async () => {\n try {\n const refreshResult = await auth.refreshToken();\n return !!refreshResult.data;\n } finally {\n isRefreshing = false;\n refreshPromise = null;\n }\n })();\n }\n\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Retry with new token\n const newToken = auth.getAccessToken();\n result = await baseHttpClient.request<T>({\n ...config,\n headers: {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n },\n });\n }\n }\n\n // Trigger unauthorized if still 401\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n const authenticatedHttpClient = createAuthenticatedHttpClient();\n\n let cachedUserUid: string | null = null;\n\n auth.on(\"login\", (user: { uid?: string }) => {\n cachedUserUid = user?.uid ?? null;\n });\n auth.on(\"logout\", () => {\n cachedUserUid = null;\n });\n\n if (auth.isAuthenticated()) {\n auth\n .getMe()\n .then((result) => {\n if (result.data?.uid) {\n cachedUserUid = result.data.uid;\n }\n })\n .catch(() => {});\n }\n\n // Create other clients using the authenticated HTTP client\n const entity: EntityClient = createEntityClient(authenticatedHttpClient);\n const bpm: BpmClient = createBpmClient(authenticatedHttpClient);\n const workflow: WorkflowClient = createWorkflowClient(authenticatedHttpClient);\n const functionClient: FunctionClient = createFunctionClient(authenticatedHttpClient);\n const copilot: CopilotClient = createCopilotClient(\n authenticatedHttpClient,\n baseURL,\n () => auth.getAccessToken(),\n () => cachedUserUid\n );\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, pass token getter for authentication\n // Token can be appended to WebSocket URL as query parameter\n const asr: (config: ASRClientConfig) => ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient = createASRHttpClient({\n getAccessToken: () => auth.getAccessToken(),\n http: authenticatedHttpClient,\n });\n const tts: (config: TTSClientConfig) => TTSClient = createTTSClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n asrHttp,\n copilot,\n function: functionClient,\n tts,\n s3,\n http: authenticatedHttpClient,\n\n // Expose token management methods from auth client\n isAuthenticated: () => auth.isAuthenticated(),\n getAccessToken: () => auth.getAccessToken(),\n setAccessToken: (token: string) => auth.setAccessToken(token),\n clearAuth: () => auth.clearAuth(),\n };\n\n return client;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amaster.ai/client",
|
|
3
|
-
"version": "1.0.0-
|
|
3
|
+
"version": "1.0.0-beta.74",
|
|
4
4
|
"description": "Unified API client for Amaster platform - All services in one package",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -72,16 +72,16 @@
|
|
|
72
72
|
"registry": "https://registry.npmjs.org/"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@amaster.ai/asr-client": "1.0.0-
|
|
76
|
-
"@amaster.ai/
|
|
77
|
-
"@amaster.ai/bpm-client": "1.0.0-
|
|
78
|
-
"@amaster.ai/
|
|
79
|
-
"@amaster.ai/
|
|
80
|
-
"@amaster.ai/
|
|
81
|
-
"@amaster.ai/
|
|
82
|
-
"@amaster.ai/
|
|
83
|
-
"@amaster.ai/
|
|
84
|
-
"@amaster.ai/
|
|
75
|
+
"@amaster.ai/asr-client": "1.0.0-beta.74",
|
|
76
|
+
"@amaster.ai/auth-client": "1.0.0-beta.74",
|
|
77
|
+
"@amaster.ai/bpm-client": "1.0.0-beta.74",
|
|
78
|
+
"@amaster.ai/copilot-client": "1.0.0-beta.74",
|
|
79
|
+
"@amaster.ai/entity-client": "1.0.0-beta.74",
|
|
80
|
+
"@amaster.ai/function-client": "1.0.0-beta.74",
|
|
81
|
+
"@amaster.ai/http-client": "1.0.0-beta.74",
|
|
82
|
+
"@amaster.ai/s3-client": "1.0.0-beta.74",
|
|
83
|
+
"@amaster.ai/tts-client": "1.0.0-beta.74",
|
|
84
|
+
"@amaster.ai/workflow-client": "1.0.0-beta.74"
|
|
85
85
|
},
|
|
86
86
|
"peerDependencies": {
|
|
87
87
|
"axios": "^1.11.0"
|
package/types/asr.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type{ HttpClient } from "./http";
|
|
1
2
|
/**
|
|
2
3
|
* ASR Realtime WebSocket Client for Qwen-ASR Realtime API
|
|
3
4
|
*
|
|
@@ -6,6 +7,8 @@
|
|
|
6
7
|
*
|
|
7
8
|
* @example
|
|
8
9
|
* ```typescript
|
|
10
|
+
* import { createClient } from "@amaster.ai/client";
|
|
11
|
+
* export const client = createClient({});
|
|
9
12
|
* const asrClient = client.asr({
|
|
10
13
|
* language: "zh",
|
|
11
14
|
* enableVAD: true,
|
|
@@ -286,13 +289,17 @@ export interface RecorderOptions {
|
|
|
286
289
|
onError?: (error: Error) => void;
|
|
287
290
|
}
|
|
288
291
|
|
|
292
|
+
export type ASRHttpStatus = "idle" | "recording" | "recognizing";
|
|
293
|
+
|
|
289
294
|
export interface ASRHttpClientConfig {
|
|
295
|
+
/** Get access token */
|
|
296
|
+
http?: HttpClient;
|
|
290
297
|
/** Get access token */
|
|
291
298
|
getAccessToken?(): string | null;
|
|
292
|
-
/** Language, default 'zh' */
|
|
293
|
-
language?: string;
|
|
294
299
|
/** Create custom recorder */
|
|
295
300
|
createRecorder?(options?: RecorderOptions): Promise<Recorder>;
|
|
301
|
+
/** Language, default 'zh' */
|
|
302
|
+
language?: string;
|
|
296
303
|
/** Sample rate, default 16000 */
|
|
297
304
|
sampleRate?: number;
|
|
298
305
|
/** Called when recording starts */
|
|
@@ -303,6 +310,8 @@ export interface ASRHttpClientConfig {
|
|
|
303
310
|
onResult?: (text: string) => void;
|
|
304
311
|
/** Called on error */
|
|
305
312
|
onError?: (error: Error) => void;
|
|
313
|
+
/** Called when status changes */
|
|
314
|
+
onStatusChange?: (status: ASRHttpStatus) => void;
|
|
306
315
|
}
|
|
307
316
|
export interface ASRHttpClient {
|
|
308
317
|
/** Start recording (press-to-talk) */
|
|
@@ -71,14 +71,14 @@ export interface CaptchaResponse {
|
|
|
71
71
|
export interface CodeAuthAPI {
|
|
72
72
|
/**
|
|
73
73
|
* Login with verification code
|
|
74
|
-
*
|
|
74
|
+
*
|
|
75
75
|
* Authenticates using a verification code sent to email or phone.
|
|
76
|
-
*
|
|
76
|
+
*
|
|
77
77
|
* @param params - Email/phone and verification code
|
|
78
78
|
* @returns User info and access token
|
|
79
79
|
*
|
|
80
80
|
*/
|
|
81
|
-
|
|
81
|
+
loginWithCode(params: CodeLoginParams): Promise<ClientResult<LoginResponse>>;
|
|
82
82
|
|
|
83
83
|
/**
|
|
84
84
|
* Send verification code
|
package/types/auth/index.d.ts
CHANGED
|
@@ -98,6 +98,33 @@ export interface AuthClientAPI
|
|
|
98
98
|
*/
|
|
99
99
|
refreshToken(): Promise<ClientResult<RefreshTokenResponse>>;
|
|
100
100
|
|
|
101
|
+
// ==================== Event Handling ====================
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Subscribe to authentication events
|
|
105
|
+
*
|
|
106
|
+
* Available events:
|
|
107
|
+
* - `login` - Fired after successful login, receives User object
|
|
108
|
+
* - `logout` - Fired after logout
|
|
109
|
+
* - `tokenExpired` - Fired when access token expires
|
|
110
|
+
* - `tokenRefreshed` - Fired after token refresh, receives new token
|
|
111
|
+
* - `unauthorized` - Fired on 401 response
|
|
112
|
+
*
|
|
113
|
+
* @param event - Event name to subscribe to
|
|
114
|
+
* @param handler - Callback function
|
|
115
|
+
*
|
|
116
|
+
*/
|
|
117
|
+
on(event: "login" | "logout" | "tokenExpired" | "tokenRefreshed" | "unauthorized", handler: (...args: unknown[]) => void): void;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Unsubscribe from authentication events
|
|
121
|
+
*
|
|
122
|
+
* @param event - Event name to unsubscribe from
|
|
123
|
+
* @param handler - The same callback function that was passed to `on()`
|
|
124
|
+
*
|
|
125
|
+
*/
|
|
126
|
+
off(event: "login" | "logout" | "tokenExpired" | "tokenRefreshed" | "unauthorized", handler: (...args: unknown[]) => void): void;
|
|
127
|
+
|
|
101
128
|
// ==================== Permission Checks ====================
|
|
102
129
|
|
|
103
130
|
/**
|
package/types/auth/user.d.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Roles and permissions are returned as simple string arrays for efficient client-side use:
|
|
14
14
|
* - `roles`: ["admin", "user", "manager"]
|
|
15
|
-
* - `permissions`: ["user
|
|
15
|
+
* - `permissions`: ["user.read", "user.write", "order.read"]
|
|
16
16
|
*
|
|
17
17
|
*/
|
|
18
18
|
export interface User {
|
|
@@ -61,7 +61,7 @@ export interface User {
|
|
|
61
61
|
|
|
62
62
|
/**
|
|
63
63
|
* Permission names granted to user
|
|
64
|
-
* Format: "resource
|
|
64
|
+
* Format: "resource.action"
|
|
65
65
|
*/
|
|
66
66
|
permissions: string[];
|
|
67
67
|
|
package/types/bpm.d.ts
CHANGED
|
@@ -228,6 +228,46 @@ export interface TaskCount {
|
|
|
228
228
|
count: number;
|
|
229
229
|
}
|
|
230
230
|
|
|
231
|
+
/**
|
|
232
|
+
* Task form field metadata
|
|
233
|
+
*/
|
|
234
|
+
export interface TaskFormField {
|
|
235
|
+
id: string;
|
|
236
|
+
label?: string;
|
|
237
|
+
type?: string;
|
|
238
|
+
defaultValue?: CamundaVariableValue;
|
|
239
|
+
properties?: Record<string, unknown>;
|
|
240
|
+
validationConstraints?: Array<{
|
|
241
|
+
name: string;
|
|
242
|
+
config?: unknown;
|
|
243
|
+
}>;
|
|
244
|
+
[key: string]: unknown;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Task form schema metadata
|
|
249
|
+
*/
|
|
250
|
+
export interface TaskFormSchema {
|
|
251
|
+
key?: string;
|
|
252
|
+
contextPath?: string;
|
|
253
|
+
fields?: TaskFormField[];
|
|
254
|
+
[key: string]: unknown;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Task form variable value
|
|
259
|
+
*/
|
|
260
|
+
export interface TaskFormVariable {
|
|
261
|
+
type: string;
|
|
262
|
+
value: CamundaVariableValue;
|
|
263
|
+
valueInfo?: Record<string, unknown>;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Task form variables keyed by variable name
|
|
268
|
+
*/
|
|
269
|
+
export type TaskFormVariables = Record<string, TaskFormVariable>;
|
|
270
|
+
|
|
231
271
|
/**
|
|
232
272
|
* Historical task information
|
|
233
273
|
*/
|
|
@@ -502,6 +542,19 @@ export interface BpmClientAPI {
|
|
|
502
542
|
*/
|
|
503
543
|
getTask(taskId: string): Promise<ClientResult<Task>>;
|
|
504
544
|
|
|
545
|
+
/**
|
|
546
|
+
* Get task form schema metadata
|
|
547
|
+
*/
|
|
548
|
+
getTaskFormSchema(
|
|
549
|
+
taskId: string,
|
|
550
|
+
opts?: { redirect?: string }
|
|
551
|
+
): Promise<ClientResult<TaskFormSchema>>;
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Get task form variables
|
|
555
|
+
*/
|
|
556
|
+
getTaskFormVariables(taskId: string): Promise<ClientResult<TaskFormVariables>>;
|
|
557
|
+
|
|
505
558
|
/**
|
|
506
559
|
* Complete a user task
|
|
507
560
|
*
|
|
@@ -531,6 +584,20 @@ export interface BpmClientAPI {
|
|
|
531
584
|
inputs: Record<string, CamundaVariableValue> | VariableSubmission
|
|
532
585
|
): Promise<ClientResult<null>>;
|
|
533
586
|
|
|
587
|
+
/**
|
|
588
|
+
* Query historical tasks
|
|
589
|
+
*/
|
|
590
|
+
getHistoryTasks(
|
|
591
|
+
params?: HistoryTaskQueryParams
|
|
592
|
+
): Promise<ClientResult<HistoryTask[]>>;
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Get historical task count
|
|
596
|
+
*/
|
|
597
|
+
getHistoryTaskCount(
|
|
598
|
+
params?: HistoryTaskQueryParams
|
|
599
|
+
): Promise<ClientResult<TaskCount>>;
|
|
600
|
+
|
|
534
601
|
// ==================== History & Reporting ====================
|
|
535
602
|
|
|
536
603
|
/**
|
|
@@ -572,6 +639,13 @@ export interface BpmClientAPI {
|
|
|
572
639
|
getHistoryProcessInstanceCount(
|
|
573
640
|
params?: HistoryProcessInstanceQueryParams
|
|
574
641
|
): Promise<ClientResult<{ count: number }>>;
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Get deployed Camunda form definition for a task
|
|
645
|
+
*/
|
|
646
|
+
getTaskDeployedForm(
|
|
647
|
+
taskId: string
|
|
648
|
+
): Promise<ClientResult<CamundaFormDefinition>>;
|
|
575
649
|
}
|
|
576
650
|
|
|
577
651
|
/**
|
|
@@ -619,3 +693,52 @@ export interface HistoryProcessInstanceQueryParams {
|
|
|
619
693
|
/** Pagination: max results to return */
|
|
620
694
|
maxResults?: number;
|
|
621
695
|
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Historical task query parameters
|
|
699
|
+
*/
|
|
700
|
+
export interface HistoryTaskQueryParams {
|
|
701
|
+
/** Filter by task assignee */
|
|
702
|
+
taskAssignee?: string;
|
|
703
|
+
/** Filter by process instance ID */
|
|
704
|
+
processInstanceId?: string;
|
|
705
|
+
/** Filter finished tasks */
|
|
706
|
+
finished?: boolean;
|
|
707
|
+
/** Filter unfinished tasks */
|
|
708
|
+
unfinished?: boolean;
|
|
709
|
+
/** Pagination: first result index */
|
|
710
|
+
firstResult?: number;
|
|
711
|
+
/** Pagination: max results to return */
|
|
712
|
+
maxResults?: number;
|
|
713
|
+
/** Sort field */
|
|
714
|
+
sortBy?: string;
|
|
715
|
+
/** Sort order */
|
|
716
|
+
sortOrder?: "asc" | "desc";
|
|
717
|
+
[key: string]: string | number | boolean | undefined;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Camunda deployed form definition
|
|
722
|
+
*/
|
|
723
|
+
export interface CamundaFormDefinition {
|
|
724
|
+
components?: CamundaFormComponent[];
|
|
725
|
+
type?: string;
|
|
726
|
+
id?: string;
|
|
727
|
+
schemaVersion?: number;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Camunda form component definition
|
|
732
|
+
*/
|
|
733
|
+
export interface CamundaFormComponent {
|
|
734
|
+
key: string;
|
|
735
|
+
label?: string;
|
|
736
|
+
type: string;
|
|
737
|
+
validate?: {
|
|
738
|
+
required?: boolean;
|
|
739
|
+
readonly?: boolean;
|
|
740
|
+
};
|
|
741
|
+
defaultValue?: CamundaVariableValue;
|
|
742
|
+
values?: Array<{ label: string; value: string }>;
|
|
743
|
+
properties?: Record<string, unknown>;
|
|
744
|
+
}
|
package/types/copilot.d.ts
CHANGED
|
@@ -1,49 +1,166 @@
|
|
|
1
|
-
import type { SendStreamingMessageResponse, CancelTaskResponse, GetTaskResponse } from '@a2a-js/sdk';
|
|
2
|
-
import type { ClientResult } from './common';
|
|
3
|
-
|
|
4
1
|
interface TextContent {
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
type: "text";
|
|
3
|
+
text: string;
|
|
7
4
|
}
|
|
5
|
+
|
|
8
6
|
interface ImageContent {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
type: "image";
|
|
8
|
+
data?: string;
|
|
9
|
+
url?: string;
|
|
10
|
+
mimeType?: string;
|
|
13
11
|
}
|
|
12
|
+
|
|
14
13
|
interface FileContent {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
type: "file";
|
|
15
|
+
data?: string;
|
|
16
|
+
url?: string;
|
|
17
|
+
mimeType?: string;
|
|
18
|
+
name?: string;
|
|
20
19
|
}
|
|
20
|
+
|
|
21
21
|
type MessageContent = TextContent | ImageContent | FileContent;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
|
|
23
|
+
type Role = "user" | "assistant" | "system";
|
|
24
|
+
|
|
25
|
+
interface BaseMessage {
|
|
26
|
+
messageId: string;
|
|
27
|
+
role?: Role;
|
|
28
|
+
kind: string;
|
|
29
|
+
timestamp?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface TextMessage extends BaseMessage {
|
|
33
|
+
kind: "text-content" | "message";
|
|
34
|
+
content: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface ErrorMessage extends BaseMessage {
|
|
38
|
+
kind: "error";
|
|
39
|
+
content: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ThoughtMessage extends BaseMessage {
|
|
43
|
+
kind: "thought";
|
|
44
|
+
thought: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface ToolMessage extends BaseMessage {
|
|
48
|
+
kind: "tool";
|
|
49
|
+
toolName?: string;
|
|
50
|
+
toolStatus?: string;
|
|
51
|
+
toolDescription?: string;
|
|
52
|
+
response?: unknown;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface UIRenderMessage extends BaseMessage {
|
|
56
|
+
kind: "ui-render";
|
|
57
|
+
spec: {
|
|
58
|
+
root: string;
|
|
59
|
+
elements: Record<
|
|
60
|
+
string,
|
|
61
|
+
{
|
|
62
|
+
type: string;
|
|
63
|
+
props?: Record<string, unknown>;
|
|
64
|
+
children?: string[];
|
|
65
|
+
}
|
|
66
|
+
>;
|
|
67
|
+
};
|
|
25
68
|
}
|
|
26
|
-
|
|
27
|
-
|
|
69
|
+
|
|
70
|
+
type MessagesItem =
|
|
71
|
+
| TextMessage
|
|
72
|
+
| ErrorMessage
|
|
73
|
+
| ThoughtMessage
|
|
74
|
+
| ToolMessage
|
|
75
|
+
| UIRenderMessage
|
|
76
|
+
| BaseMessage;
|
|
77
|
+
|
|
78
|
+
interface Conversation {
|
|
79
|
+
taskId: string;
|
|
80
|
+
status: "submitted" | "working" | "completed" | "error";
|
|
81
|
+
messages: MessagesItem[];
|
|
82
|
+
lastUpdated: string;
|
|
83
|
+
historyId?: string;
|
|
84
|
+
system?: {
|
|
85
|
+
level: "newConversation";
|
|
86
|
+
content?: string;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface HistoryState {
|
|
91
|
+
next: string | null;
|
|
92
|
+
hasMore: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface UpdateMessageInput {
|
|
96
|
+
taskId: string;
|
|
97
|
+
messageId: string;
|
|
98
|
+
content?: string;
|
|
99
|
+
partial?: boolean;
|
|
100
|
+
status?: string;
|
|
101
|
+
response?: unknown;
|
|
102
|
+
metadata?: Record<string, unknown>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface ConversationControllerSnapshot {
|
|
106
|
+
starting: boolean;
|
|
107
|
+
isLoading: boolean;
|
|
108
|
+
isLoadingHistory: boolean;
|
|
109
|
+
historyState: HistoryState;
|
|
110
|
+
conversations: Conversation[];
|
|
28
111
|
}
|
|
112
|
+
|
|
113
|
+
interface ConversationStrings {
|
|
114
|
+
thinking: string;
|
|
115
|
+
errorMessage: string;
|
|
116
|
+
cancelled: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface ConversationControllerOptions {
|
|
120
|
+
strings: ConversationStrings;
|
|
121
|
+
mode?: "conversation" | "single-turn";
|
|
122
|
+
getContextId?: () => string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface ConversationController {
|
|
126
|
+
getSnapshot(): ConversationControllerSnapshot;
|
|
127
|
+
subscribe(listener: (snapshot: ConversationControllerSnapshot) => void): () => void;
|
|
128
|
+
init(): Promise<void>;
|
|
129
|
+
destroy(): void;
|
|
130
|
+
sendMessage(userContent: string): Promise<void>;
|
|
131
|
+
abort(): void;
|
|
132
|
+
cancelChat(taskId?: string): Promise<void>;
|
|
133
|
+
resetConversation(greeting?: string): void;
|
|
134
|
+
startNewConversation(): Promise<void>;
|
|
135
|
+
loadHistory(limit?: number, next?: string): Promise<void>;
|
|
136
|
+
loadMoreHistory(): Promise<void>;
|
|
137
|
+
getConversation(taskId: string): Conversation | undefined;
|
|
138
|
+
clearConversation(taskId: string): void;
|
|
139
|
+
removeMessage(taskId: string, messageId: string): void;
|
|
140
|
+
updateMessage(input: UpdateMessageInput): void;
|
|
141
|
+
}
|
|
142
|
+
|
|
29
143
|
type CopilotClientAPI = {
|
|
30
|
-
|
|
31
|
-
* Stream messages from Copilot Agent.
|
|
32
|
-
*
|
|
33
|
-
* @example
|
|
34
|
-
* ```typescript
|
|
35
|
-
* import { createCopilotClient, Data } from "@amaster.ai/copilot-client";
|
|
36
|
-
*
|
|
37
|
-
* const client = createCopilotClient();
|
|
38
|
-
*
|
|
39
|
-
* for await (const response of client.chat([{ role: "user", content: "Hello" }])) {
|
|
40
|
-
* // deal response
|
|
41
|
-
* }
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
chat(messages: ChatMessage[], options?: ChatOptions): AsyncGenerator<SendStreamingMessageResponse, void, unknown>;
|
|
45
|
-
cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;
|
|
46
|
-
getChatStatus(taskId: string): Promise<ClientResult<GetTaskResponse>>;
|
|
144
|
+
createConversationController(options: ConversationControllerOptions): ConversationController;
|
|
47
145
|
};
|
|
48
146
|
|
|
49
|
-
export {
|
|
147
|
+
export {
|
|
148
|
+
type CopilotClientAPI,
|
|
149
|
+
type ConversationController,
|
|
150
|
+
type ConversationControllerOptions,
|
|
151
|
+
type ConversationControllerSnapshot,
|
|
152
|
+
type ConversationStrings,
|
|
153
|
+
type Conversation,
|
|
154
|
+
type MessagesItem,
|
|
155
|
+
type TextMessage,
|
|
156
|
+
type ErrorMessage,
|
|
157
|
+
type ThoughtMessage,
|
|
158
|
+
type ToolMessage,
|
|
159
|
+
type UIRenderMessage,
|
|
160
|
+
type Role,
|
|
161
|
+
type UpdateMessageInput,
|
|
162
|
+
type FileContent,
|
|
163
|
+
type ImageContent,
|
|
164
|
+
type MessageContent,
|
|
165
|
+
type TextContent,
|
|
166
|
+
};
|
package/types/http.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ type AdapterResponse = {
|
|
|
21
21
|
headers?: unknown;
|
|
22
22
|
};
|
|
23
23
|
type HttpAdapter = (_config: RequestConfig) => Promise<AdapterResponse>;
|
|
24
|
+
type MiniProgramRequest = (_opts: any) => any;
|
|
24
25
|
type HttpClientOptions = {
|
|
25
26
|
/**
|
|
26
27
|
* HTTP adapter to use:
|
|
@@ -70,6 +71,8 @@ type HttpClientOptions = {
|
|
|
70
71
|
type HttpClient = {
|
|
71
72
|
request<T>(_config: RequestConfig): Promise<ClientResult<T>>;
|
|
72
73
|
};
|
|
74
|
+
declare function resolveMiniProgramGlobals(): any;
|
|
75
|
+
declare function getMiniProgramRequest(): MiniProgramRequest | null;
|
|
73
76
|
/**
|
|
74
77
|
* Create an HTTP client instance
|
|
75
78
|
*
|
|
@@ -92,4 +95,4 @@ type HttpClient = {
|
|
|
92
95
|
*/
|
|
93
96
|
declare function createHttpClient(axiosInstanceOrOptions?: AxiosInstance | HttpClientOptions): HttpClient;
|
|
94
97
|
|
|
95
|
-
export { type AdapterResponse, type ClientError, type ClientResult, type HttpAdapter, type HttpClient, type HttpClientOptions, type RequestConfig, createHttpClient };
|
|
98
|
+
export { type AdapterResponse, type ClientError, type ClientResult, type HttpAdapter, type HttpClient, type HttpClientOptions, type MiniProgramRequest, type RequestConfig, createHttpClient, getMiniProgramRequest, resolveMiniProgramGlobals };
|