@amaster.ai/client 1.1.0-beta.30 → 1.1.0-beta.32

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 CHANGED
@@ -13,7 +13,7 @@ var httpClient = require('@amaster.ai/http-client');
13
13
 
14
14
  // src/client.ts
15
15
  function createClient(options) {
16
- const { baseURL, headers = {}, onUnauthorized, onTokenExpired } = options;
16
+ const { baseURL, headers = {}, onUnauthorized, onTokenExpired, autoHandleOAuthCallback } = options;
17
17
  const baseHttpClient = httpClient.createHttpClient({
18
18
  baseURL,
19
19
  headers
@@ -22,9 +22,22 @@ function createClient(options) {
22
22
  baseURL,
23
23
  headers,
24
24
  onTokenExpired,
25
- onUnauthorized
25
+ onUnauthorized,
26
+ autoHandleOAuthCallback
26
27
  });
27
28
  const createAuthenticatedHttpClient = () => {
29
+ let isRefreshing = false;
30
+ let refreshPromise = null;
31
+ function isTokenExpired(result) {
32
+ if (result.status !== 401) return false;
33
+ if (result.error?.message && /expired/i.test(result.error.message)) {
34
+ return true;
35
+ }
36
+ if (typeof result.data === "string" && /expired/i.test(result.data)) {
37
+ return true;
38
+ }
39
+ return !!auth.getAccessToken();
40
+ }
28
41
  return {
29
42
  async request(config) {
30
43
  const token = auth.getAccessToken();
@@ -36,9 +49,43 @@ function createClient(options) {
36
49
  ...authHeaders
37
50
  }
38
51
  };
39
- const result = await baseHttpClient.request(mergedConfig);
40
- if (result.status === 401 && onUnauthorized) {
41
- onUnauthorized();
52
+ let result = await baseHttpClient.request(mergedConfig);
53
+ if (result.status === 401) {
54
+ if (isTokenExpired(result)) {
55
+ if (!isRefreshing) {
56
+ isRefreshing = true;
57
+ refreshPromise = (async () => {
58
+ try {
59
+ const refreshResult = await auth.refreshToken();
60
+ return !!refreshResult.data;
61
+ } finally {
62
+ isRefreshing = false;
63
+ refreshPromise = null;
64
+ }
65
+ })();
66
+ }
67
+ const refreshed = await refreshPromise;
68
+ if (refreshed) {
69
+ const newToken = auth.getAccessToken();
70
+ const retryHeaders = {
71
+ ...config.headers,
72
+ ...newToken ? { Authorization: `Bearer ${newToken}` } : {}
73
+ };
74
+ const retryConfig = {
75
+ ...config,
76
+ headers: retryHeaders
77
+ };
78
+ result = await baseHttpClient.request(retryConfig);
79
+ } else {
80
+ if (onUnauthorized) {
81
+ onUnauthorized();
82
+ }
83
+ }
84
+ } else {
85
+ if (onUnauthorized) {
86
+ onUnauthorized();
87
+ }
88
+ }
42
89
  }
43
90
  return result;
44
91
  }
@@ -49,10 +96,18 @@ function createClient(options) {
49
96
  const bpm = bpmClient.createBpmClient(authenticatedHttpClient);
50
97
  const workflow = workflowClient.createWorkflowClient(authenticatedHttpClient);
51
98
  const functionClient$1 = functionClient.createFunctionClient(authenticatedHttpClient);
52
- const copilot = copilotClient.createCopilotA2UIClient(authenticatedHttpClient, baseURL);
99
+ const copilot = copilotClient.createCopilotA2UIClient(
100
+ authenticatedHttpClient,
101
+ baseURL,
102
+ () => auth.getAccessToken()
103
+ );
53
104
  const s3 = s3Client.createS3Client(authenticatedHttpClient);
54
- const asr = asrClient.createASRClient({});
55
- const tts = ttsClient.createTTSClient({});
105
+ const asr = asrClient.createASRClient({
106
+ getAccessToken: () => auth.getAccessToken()
107
+ });
108
+ const tts = ttsClient.createTTSClient({
109
+ getAccessToken: () => auth.getAccessToken()
110
+ });
56
111
  const client = {
57
112
  auth,
58
113
  entity,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts"],"names":["createHttpClient","createAuthClient","createEntityClient","createBpmClient","createWorkflowClient","functionClient","createFunctionClient","createCopilotA2UIClient","createS3Client","createASRClient","createTTSClient"],"mappings":";;;;;;;;;;;;;;AA+FO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM,EAAE,OAAA,EAAS,OAAA,GAAU,EAAC,EAAG,cAAA,EAAgB,gBAAe,GAAI,OAAA;AAGlE,EAAA,MAAM,iBAAiBA,2BAAA,CAAiB;AAAA,IACtC,OA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AAA,MAAM,GAAA,GAAiBC,yBAAA,CAAgB,EAAE,CAAA;AAGzC,EAAA,MAAM,MAAA,GAAwB;AAAA,IAC5B,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA,EAAUL,gBAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA;AAAA,IAGA,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 { createASRClient, type ASRClient } from \"@amaster.ai/asr-client\";\nimport { createCopilotA2UIClient, type CopilotA2UIClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport { createHttpClient, type HttpClient, type RequestConfig, type ClientResult } 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 { baseURL, headers = {}, onUnauthorized, onTokenExpired } = 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 });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\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 const result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n // Create the authenticated HTTP client\n const authenticatedHttpClient = createAuthenticatedHttpClient();\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: CopilotA2UIClient = createCopilotA2UIClient(authenticatedHttpClient, baseURL);\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, create with default config\n // Users can reconfigure by accessing client.asr / client.tts directly\n const asr: ASRClient = createASRClient({});\n const tts: TTSClient = createTTSClient({});\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n copilot,\n function: functionClient,\n tts,\n s3,\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","createCopilotA2UIClient","createS3Client","createASRClient","createTTSClient"],"mappings":";;;;;;;;;;;;;;AA+FO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,M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,EAAA,MAAM,0BAA0B,6BAAA,EAA8B;AAG9D,EAAA,MAAM,MAAA,GAAuBC,gCAAmB,uBAAuB,CAAA;AACvE,EAAA,MAAM,GAAA,GAAiBC,0BAAgB,uBAAuB,CAAA;AAC9D,EAAA,MAAM,QAAA,GAA2BC,oCAAqB,uBAAuB,CAAA;AAC7E,EAAA,MAAMC,gBAAA,GAAiCC,oCAAqB,uBAAuB,CAAA;AAEnF,EAAA,MAAM,OAAA,GAA6BC,qCAAA;AAAA,IACjC,uBAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAM,KAAK,cAAA;AAAe,GAC5B;AACA,EAAA,MAAM,EAAA,GAAeC,wBAAe,uBAAuB,CAAA;AAI3D,EAAA,MAAM,MAAiBC,yBAAA,CAAgB;AAAA,IACrC,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AACD,EAAA,MAAM,MAAiBC,yBAAA,CAAgB;AAAA,IACrC,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,QAAA,EAAUL,gBAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA;AAAA,IAGA,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 { createASRClient, type ASRClient } from \"@amaster.ai/asr-client\";\nimport { createCopilotA2UIClient, type CopilotA2UIClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport { createHttpClient, type HttpClient, type RequestConfig, type ClientResult } 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 { baseURL, headers = {}, onUnauthorized, onTokenExpired, autoHandleOAuthCallback } = 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 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) {\n // Check if this is a token expiration (vs. no auth / invalid credentials)\n if (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 // Wait for refresh to complete\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Token refreshed successfully, get new token and retry\n const newToken = auth.getAccessToken();\n \n // Rebuild headers with new token for retry\n const retryHeaders = {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n };\n \n const retryConfig: RequestConfig = {\n ...config,\n headers: retryHeaders,\n };\n \n // Retry the request directly with baseHttpClient (avoid recursive wrapper call)\n result = await baseHttpClient.request<T>(retryConfig);\n } else {\n // Refresh failed, trigger unauthorized callback\n if (onUnauthorized) {\n onUnauthorized();\n }\n }\n } else {\n // Not a token expiration, trigger unauthorized callback\n if (onUnauthorized) {\n onUnauthorized();\n }\n }\n }\n\n return result;\n },\n };\n };\n\n // Create the authenticated HTTP client\n const authenticatedHttpClient = createAuthenticatedHttpClient();\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 // Pass token getter for streaming authentication (SSE/fetch)\n const copilot: CopilotA2UIClient = createCopilotA2UIClient(\n authenticatedHttpClient, \n baseURL,\n () => auth.getAccessToken()\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: ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const tts: 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 copilot,\n function: functionClient,\n tts,\n s3,\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
@@ -56,6 +56,18 @@ interface AmasterClientOptions {
56
56
  * Tokens will be refreshed this many seconds before expiry
57
57
  */
58
58
  refreshThreshold?: number;
59
+ /**
60
+ * Automatically handle OAuth callback on initialization (default: true)
61
+ *
62
+ * When enabled, the client will automatically detect and process OAuth
63
+ * callback URLs containing #access_token. After processing, the hash
64
+ * is automatically cleared from the URL for security.
65
+ *
66
+ * Set to false if you want to manually handle OAuth callbacks.
67
+ *
68
+ * @default true
69
+ */
70
+ autoHandleOAuthCallback?: boolean;
59
71
  }
60
72
  /**
61
73
  * Unified Amaster Client
package/dist/index.d.ts CHANGED
@@ -56,6 +56,18 @@ interface AmasterClientOptions {
56
56
  * Tokens will be refreshed this many seconds before expiry
57
57
  */
58
58
  refreshThreshold?: number;
59
+ /**
60
+ * Automatically handle OAuth callback on initialization (default: true)
61
+ *
62
+ * When enabled, the client will automatically detect and process OAuth
63
+ * callback URLs containing #access_token. After processing, the hash
64
+ * is automatically cleared from the URL for security.
65
+ *
66
+ * Set to false if you want to manually handle OAuth callbacks.
67
+ *
68
+ * @default true
69
+ */
70
+ autoHandleOAuthCallback?: boolean;
59
71
  }
60
72
  /**
61
73
  * Unified Amaster Client
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import { createHttpClient } from '@amaster.ai/http-client';
11
11
 
12
12
  // src/client.ts
13
13
  function createClient(options) {
14
- const { baseURL, headers = {}, onUnauthorized, onTokenExpired } = options;
14
+ const { baseURL, headers = {}, onUnauthorized, onTokenExpired, autoHandleOAuthCallback } = options;
15
15
  const baseHttpClient = createHttpClient({
16
16
  baseURL,
17
17
  headers
@@ -20,9 +20,22 @@ function createClient(options) {
20
20
  baseURL,
21
21
  headers,
22
22
  onTokenExpired,
23
- onUnauthorized
23
+ onUnauthorized,
24
+ autoHandleOAuthCallback
24
25
  });
25
26
  const createAuthenticatedHttpClient = () => {
27
+ let isRefreshing = false;
28
+ let refreshPromise = null;
29
+ function isTokenExpired(result) {
30
+ if (result.status !== 401) return false;
31
+ if (result.error?.message && /expired/i.test(result.error.message)) {
32
+ return true;
33
+ }
34
+ if (typeof result.data === "string" && /expired/i.test(result.data)) {
35
+ return true;
36
+ }
37
+ return !!auth.getAccessToken();
38
+ }
26
39
  return {
27
40
  async request(config) {
28
41
  const token = auth.getAccessToken();
@@ -34,9 +47,43 @@ function createClient(options) {
34
47
  ...authHeaders
35
48
  }
36
49
  };
37
- const result = await baseHttpClient.request(mergedConfig);
38
- if (result.status === 401 && onUnauthorized) {
39
- onUnauthorized();
50
+ let result = await baseHttpClient.request(mergedConfig);
51
+ if (result.status === 401) {
52
+ if (isTokenExpired(result)) {
53
+ if (!isRefreshing) {
54
+ isRefreshing = true;
55
+ refreshPromise = (async () => {
56
+ try {
57
+ const refreshResult = await auth.refreshToken();
58
+ return !!refreshResult.data;
59
+ } finally {
60
+ isRefreshing = false;
61
+ refreshPromise = null;
62
+ }
63
+ })();
64
+ }
65
+ const refreshed = await refreshPromise;
66
+ if (refreshed) {
67
+ const newToken = auth.getAccessToken();
68
+ const retryHeaders = {
69
+ ...config.headers,
70
+ ...newToken ? { Authorization: `Bearer ${newToken}` } : {}
71
+ };
72
+ const retryConfig = {
73
+ ...config,
74
+ headers: retryHeaders
75
+ };
76
+ result = await baseHttpClient.request(retryConfig);
77
+ } else {
78
+ if (onUnauthorized) {
79
+ onUnauthorized();
80
+ }
81
+ }
82
+ } else {
83
+ if (onUnauthorized) {
84
+ onUnauthorized();
85
+ }
86
+ }
40
87
  }
41
88
  return result;
42
89
  }
@@ -47,10 +94,18 @@ function createClient(options) {
47
94
  const bpm = createBpmClient(authenticatedHttpClient);
48
95
  const workflow = createWorkflowClient(authenticatedHttpClient);
49
96
  const functionClient = createFunctionClient(authenticatedHttpClient);
50
- const copilot = createCopilotA2UIClient(authenticatedHttpClient, baseURL);
97
+ const copilot = createCopilotA2UIClient(
98
+ authenticatedHttpClient,
99
+ baseURL,
100
+ () => auth.getAccessToken()
101
+ );
51
102
  const s3 = createS3Client(authenticatedHttpClient);
52
- const asr = createASRClient({});
53
- const tts = createTTSClient({});
103
+ const asr = createASRClient({
104
+ getAccessToken: () => auth.getAccessToken()
105
+ });
106
+ const tts = createTTSClient({
107
+ getAccessToken: () => auth.getAccessToken()
108
+ });
54
109
  const client = {
55
110
  auth,
56
111
  entity,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";;;;;;;;;;;;AA+FO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM,EAAE,OAAA,EAAS,OAAA,GAAU,EAAC,EAAG,cAAA,EAAgB,gBAAe,GAAI,OAAA;AAGlE,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;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,gCAAgC,MAAkB;AACtD,IAAA,OAAO;AAAA,MACL,MAAM,QAAW,MAAA,EAAiD;AAEhE,QAAA,MAAM,KAAA,GAAQ,KAAK,cAAA,EAAe;AAGlC,QAAA,MAAM,WAAA,GAAc,QAAQ,EAAE,aAAA,EAAe,UAAU,KAAK,CAAA,CAAA,KAAO,EAAC;AACpE,QAAA,MAAM,YAAA,GAA8B;AAAA,UAClC,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AA;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 { createASRClient, type ASRClient } from \"@amaster.ai/asr-client\";\nimport { createCopilotA2UIClient, type CopilotA2UIClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport { createHttpClient, type HttpClient, type RequestConfig, type ClientResult } 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 { baseURL, headers = {}, onUnauthorized, onTokenExpired } = 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 });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\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 const result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n // Create the authenticated HTTP client\n const authenticatedHttpClient = createAuthenticatedHttpClient();\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: CopilotA2UIClient = createCopilotA2UIClient(authenticatedHttpClient, baseURL);\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, create with default config\n // Users can reconfigure by accessing client.asr / client.tts directly\n const asr: ASRClient = createASRClient({});\n const tts: TTSClient = createTTSClient({});\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n copilot,\n function: functionClient,\n tts,\n s3,\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":";;;;;;;;;;;;AA+FO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM,EAAE,SAAS,OAAA,GAAU,IAAI,cAAA,EAAgB,cAAA,EAAgB,yBAAwB,GAAI,OAAA;AAG3F,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,C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MAAiB,eAAA,CAAgB;AAAA,IACrC,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,QAAA,EAAU,cAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA;AAAA,IAGA,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 { createASRClient, type ASRClient } from \"@amaster.ai/asr-client\";\nimport { createCopilotA2UIClient, type CopilotA2UIClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport { createHttpClient, type HttpClient, type RequestConfig, type ClientResult } 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 { baseURL, headers = {}, onUnauthorized, onTokenExpired, autoHandleOAuthCallback } = 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 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) {\n // Check if this is a token expiration (vs. no auth / invalid credentials)\n if (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 // Wait for refresh to complete\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Token refreshed successfully, get new token and retry\n const newToken = auth.getAccessToken();\n \n // Rebuild headers with new token for retry\n const retryHeaders = {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n };\n \n const retryConfig: RequestConfig = {\n ...config,\n headers: retryHeaders,\n };\n \n // Retry the request directly with baseHttpClient (avoid recursive wrapper call)\n result = await baseHttpClient.request<T>(retryConfig);\n } else {\n // Refresh failed, trigger unauthorized callback\n if (onUnauthorized) {\n onUnauthorized();\n }\n }\n } else {\n // Not a token expiration, trigger unauthorized callback\n if (onUnauthorized) {\n onUnauthorized();\n }\n }\n }\n\n return result;\n },\n };\n };\n\n // Create the authenticated HTTP client\n const authenticatedHttpClient = createAuthenticatedHttpClient();\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 // Pass token getter for streaming authentication (SSE/fetch)\n const copilot: CopilotA2UIClient = createCopilotA2UIClient(\n authenticatedHttpClient, \n baseURL,\n () => auth.getAccessToken()\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: ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const tts: 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 copilot,\n function: functionClient,\n tts,\n s3,\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.1.0-beta.30",
3
+ "version": "1.1.0-beta.32",
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,17 +72,17 @@
72
72
  "registry": "https://registry.npmjs.org/"
73
73
  },
74
74
  "dependencies": {
75
- "@amaster.ai/asr-client": "1.1.0-beta.30",
76
- "@amaster.ai/asr-http-client": "1.1.0-beta.30",
77
- "@amaster.ai/copilot-client": "1.1.0-beta.30",
78
- "@amaster.ai/function-client": "1.1.0-beta.30",
79
- "@amaster.ai/http-client": "1.1.0-beta.30",
80
- "@amaster.ai/auth-client": "1.1.0-beta.30",
81
- "@amaster.ai/entity-client": "1.1.0-beta.30",
82
- "@amaster.ai/s3-client": "1.1.0-beta.30",
83
- "@amaster.ai/bpm-client": "1.1.0-beta.30",
84
- "@amaster.ai/tts-client": "1.1.0-beta.30",
85
- "@amaster.ai/workflow-client": "1.1.0-beta.30"
75
+ "@amaster.ai/bpm-client": "1.1.0-beta.32",
76
+ "@amaster.ai/entity-client": "1.1.0-beta.32",
77
+ "@amaster.ai/asr-client": "1.1.0-beta.32",
78
+ "@amaster.ai/auth-client": "1.1.0-beta.32",
79
+ "@amaster.ai/http-client": "1.1.0-beta.32",
80
+ "@amaster.ai/s3-client": "1.1.0-beta.32",
81
+ "@amaster.ai/workflow-client": "1.1.0-beta.32",
82
+ "@amaster.ai/function-client": "1.1.0-beta.32",
83
+ "@amaster.ai/copilot-client": "1.1.0-beta.32",
84
+ "@amaster.ai/asr-http-client": "1.1.0-beta.32",
85
+ "@amaster.ai/tts-client": "1.1.0-beta.32"
86
86
  },
87
87
  "peerDependencies": {
88
88
  "axios": "^1.11.0"
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Type-level tests for @amaster.ai/client
3
+ *
4
+ * These tests verify type inference and type safety at compile time.
5
+ * They ensure that the type definitions work correctly with TypeScript.
6
+ */
7
+
8
+ import { describe, it, expectTypeOf } from 'vitest';
9
+ import type {
10
+ AmasterClient,
11
+ AmasterClientOptions,
12
+ ClientResult,
13
+ ClientError,
14
+ EntityListResponse,
15
+ LoginParams,
16
+ User,
17
+ Task,
18
+ ProcessInstance,
19
+ } from '../index';
20
+
21
+ describe('Type Tests', () => {
22
+ describe('ClientResult', () => {
23
+ it('should have correct structure', () => {
24
+ type Result = ClientResult<{ id: number; name: string }>;
25
+
26
+ expectTypeOf<Result>().toMatchTypeOf<{
27
+ data: { id: number; name: string } | null;
28
+ error: ClientError | null;
29
+ status: number;
30
+ success: boolean;
31
+ }>();
32
+ });
33
+
34
+ it('should infer data type correctly', () => {
35
+ type UserResult = ClientResult<User>;
36
+
37
+ expectTypeOf<UserResult['data']>().toEqualTypeOf<User | null>();
38
+ });
39
+
40
+ it('should have success field', () => {
41
+ type Result = ClientResult<unknown>;
42
+
43
+ expectTypeOf<Result['success']>().toEqualTypeOf<boolean>();
44
+ });
45
+ });
46
+
47
+ describe('ClientError', () => {
48
+ it('should have all required fields', () => {
49
+ expectTypeOf<ClientError>().toMatchTypeOf<{
50
+ status: number;
51
+ message: string;
52
+ code?: string;
53
+ details?: unknown;
54
+ timestamp?: string;
55
+ }>();
56
+ });
57
+ });
58
+
59
+ describe('EntityListResponse', () => {
60
+ it('should infer item type correctly', () => {
61
+ type UserListResponse = EntityListResponse<{ id: number; name: string }>;
62
+
63
+ expectTypeOf<UserListResponse['items']>().toEqualTypeOf<Array<{ id: number; name: string }>>();
64
+ });
65
+
66
+ it('should have pagination fields', () => {
67
+ type Response = EntityListResponse<unknown>;
68
+
69
+ expectTypeOf<Response>().toMatchTypeOf<{
70
+ items: unknown[];
71
+ total: number;
72
+ page?: number;
73
+ perPage?: number;
74
+ }>();
75
+ });
76
+ });
77
+
78
+ describe('AmasterClient', () => {
79
+ it('should have all service modules', () => {
80
+ expectTypeOf<AmasterClient>().toHaveProperty('auth');
81
+ expectTypeOf<AmasterClient>().toHaveProperty('entity');
82
+ expectTypeOf<AmasterClient>().toHaveProperty('bpm');
83
+ expectTypeOf<AmasterClient>().toHaveProperty('workflow');
84
+ expectTypeOf<AmasterClient>().toHaveProperty('asr');
85
+ expectTypeOf<AmasterClient>().toHaveProperty('copilot');
86
+ expectTypeOf<AmasterClient>().toHaveProperty('function');
87
+ expectTypeOf<AmasterClient>().toHaveProperty('tts');
88
+ expectTypeOf<AmasterClient>().toHaveProperty('s3');
89
+ });
90
+
91
+ it('should have utility methods', () => {
92
+ expectTypeOf<AmasterClient>().toHaveProperty('isAuthenticated');
93
+ expectTypeOf<AmasterClient>().toHaveProperty('getAccessToken');
94
+ expectTypeOf<AmasterClient>().toHaveProperty('setAccessToken');
95
+ expectTypeOf<AmasterClient>().toHaveProperty('clearAuth');
96
+ });
97
+ });
98
+
99
+ describe('LoginParams', () => {
100
+ it('should accept email login', () => {
101
+ const params: LoginParams = {
102
+ email: 'user@example.com',
103
+ password: 'password123'
104
+ };
105
+
106
+ expectTypeOf(params).toMatchTypeOf<LoginParams>();
107
+ });
108
+
109
+ it('should accept username login', () => {
110
+ const params: LoginParams = {
111
+ username: 'johndoe',
112
+ password: 'password123'
113
+ };
114
+
115
+ expectTypeOf(params).toMatchTypeOf<LoginParams>();
116
+ });
117
+
118
+ it('should accept phone login', () => {
119
+ const params: LoginParams = {
120
+ phone: '+1234567890',
121
+ password: 'password123'
122
+ };
123
+
124
+ expectTypeOf(params).toMatchTypeOf<LoginParams>();
125
+ });
126
+ });
127
+
128
+ describe('Generic Type Inference', () => {
129
+ it('should infer entity list result type', () => {
130
+ type User = { id: number; name: string; email: string };
131
+ type Result = ClientResult<EntityListResponse<User>>;
132
+
133
+ // If success, data.items should be User[]
134
+ expectTypeOf<NonNullable<Result['data']>['items']>().toEqualTypeOf<User[]>();
135
+ });
136
+
137
+ it('should infer entity get result type', () => {
138
+ type Product = { id: number; title: string; price: number };
139
+ type Result = ClientResult<Product>;
140
+
141
+ expectTypeOf<NonNullable<Result['data']>>().toEqualTypeOf<Product>();
142
+ });
143
+ });
144
+
145
+ describe('BPM Types', () => {
146
+ it('should have correct Task structure', () => {
147
+ expectTypeOf<Task>().toMatchTypeOf<{
148
+ id: string;
149
+ name: string;
150
+ assignee: string | null;
151
+ processInstanceId: string;
152
+ }>();
153
+ });
154
+
155
+ it('should have correct ProcessInstance structure', () => {
156
+ expectTypeOf<ProcessInstance>().toMatchTypeOf<{
157
+ id: string;
158
+ definitionId?: string;
159
+ businessKey?: string;
160
+ }>();
161
+ });
162
+ });
163
+ });