@lumi.new/sdk 0.4.1 → 0.4.3-beta.0

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/README.md CHANGED
@@ -58,6 +58,7 @@ When using the SDK in a server-side environment (like Node.js), please note the
58
58
  - **Initialization**: You must provide an `authorization` token when creating the client. See the `createClient` API Reference for more details.
59
59
  - **Disabled Methods**: Methods that rely on a browser environment are disabled and will throw an error if called. This includes:
60
60
  - `lumi.auth.signIn()`
61
+ - `lumi.auth.signInWithOAuth()`
61
62
  - `lumi.auth.signOut()`
62
63
  - `lumi.auth.onAuthChange()`
63
64
  - **Fetching User Data**: On the server, `lumi.auth.user` is `null` by default. You must explicitly call `await lumi.auth.refreshUser()` to fetch the user's profile based on the token provided during initialization.
@@ -82,6 +83,96 @@ async function handleSignIn(lumi: LumiClient) {
82
83
  }
83
84
  ```
84
85
 
86
+ ### Sign In with Password
87
+
88
+ Sign in a user using their email and password.
89
+
90
+ ```typescript
91
+ async function handleSignInWithPassword(lumi: LumiClient) {
92
+ try {
93
+ const { user, accessToken } = await lumi.auth.signInWithPassword({
94
+ email: 'user@example.com',
95
+ password: 'your-password',
96
+ })
97
+ console.log('Signed in as:', user)
98
+ } catch (error) {
99
+ console.error('Authentication failed:', error)
100
+ }
101
+ }
102
+ ```
103
+
104
+ ### Sign In with OAuth
105
+
106
+ Sign in a user using a third-party OAuth provider (e.g., Google). This will open a popup window for the user to authenticate with the provider.
107
+
108
+ ```typescript
109
+ async function handleSignInWithGoogle(lumi: LumiClient) {
110
+ try {
111
+ const { user, accessToken } = await lumi.auth.signInWithOAuth({
112
+ provider: 'google',
113
+ })
114
+ console.log('Signed in with Google as:', user)
115
+ } catch (error) {
116
+ console.error('OAuth authentication failed:', error)
117
+ }
118
+ }
119
+ ```
120
+
121
+ ### Sign Up with Password
122
+
123
+ Register a new user with email and password. You must first send an OTP to the user's email using `sendOtp`.
124
+
125
+ ```typescript
126
+ async function handleSignUp(lumi: LumiClient) {
127
+ const email = 'newuser@example.com'
128
+
129
+ // Step 1: Send OTP to the user's email
130
+ await lumi.auth.sendOtp({ email, type: 'register' })
131
+ console.log('OTP sent to email')
132
+
133
+ // Step 2: After user receives OTP, complete registration
134
+ const otp = '123456' // OTP entered by user
135
+ try {
136
+ await lumi.auth.signUpWithPassword({
137
+ email,
138
+ password: 'secure-password',
139
+ otp,
140
+ userName: 'New User', // optional
141
+ })
142
+ console.log('Registration successful')
143
+ } catch (error) {
144
+ console.error('Registration failed:', error)
145
+ }
146
+ }
147
+ ```
148
+
149
+ ### Reset Password
150
+
151
+ Reset a user's password. You must first send an OTP to the user's email using `sendOtp`.
152
+
153
+ ```typescript
154
+ async function handleResetPassword(lumi: LumiClient) {
155
+ const email = 'user@example.com'
156
+
157
+ // Step 1: Send OTP to the user's email
158
+ await lumi.auth.sendOtp({ email, type: 'resetPassword' })
159
+ console.log('OTP sent to email')
160
+
161
+ // Step 2: After user receives OTP, reset password
162
+ const otp = '123456' // OTP entered by user
163
+ try {
164
+ await lumi.auth.resetPassword({
165
+ email,
166
+ newPassword: 'new-secure-password',
167
+ otp,
168
+ })
169
+ console.log('Password reset successful')
170
+ } catch (error) {
171
+ console.error('Password reset failed:', error)
172
+ }
173
+ }
174
+ ```
175
+
85
176
  ### Sign Out
86
177
 
87
178
  To sign out a user, simply call the `signOut` method. This will clear the stored access token and user information.
@@ -553,6 +644,86 @@ Initiates the sign-in process by opening a popup window.
553
644
  - `createdTime` (`string`): The timestamp of when the user was created.
554
645
  - `accessToken` (`string`): The access token for the session.
555
646
 
647
+ #### `signInWithPassword(options)`
648
+
649
+ Signs in a user using their email and password.
650
+
651
+ **Parameters:**
652
+
653
+ - `options` (`object`):
654
+ - `email` (`string`): The user's email address.
655
+ - `password` (`string`): The user's password.
656
+
657
+ **Returns:**
658
+
659
+ - `Promise<object>`: A promise that resolves with an object containing:
660
+ - `projectId` (`string`): The project ID associated with the authenticated session.
661
+ - `user` (`object`): The authenticated user's information.
662
+ - `accessToken` (`string`): The access token for the session.
663
+
664
+ #### `signInWithOAuth(options)`
665
+
666
+ > **Note:** This method is not available in server-side environments and will throw an error if called.
667
+
668
+ Signs in a user using a third-party OAuth provider. This will open a popup window for the user to authenticate with the provider.
669
+
670
+ **Parameters:**
671
+
672
+ - `options` (`object`):
673
+ - `provider` (`'google'`): The OAuth provider to use. Currently only `'google'` is supported.
674
+
675
+ **Returns:**
676
+
677
+ - `Promise<object>`: A promise that resolves with an object containing:
678
+ - `projectId` (`string`): The project ID associated with the authenticated session.
679
+ - `user` (`object`): The authenticated user's information.
680
+ - `accessToken` (`string`): The access token for the session.
681
+
682
+ #### `sendOtp(options)`
683
+
684
+ Sends a one-time password (OTP) to the user's email for registration or password reset.
685
+
686
+ **Parameters:**
687
+
688
+ - `options` (`object`):
689
+ - `email` (`string`): The user's email address.
690
+ - `type` (`'register' | 'resetPassword'`): The purpose of the OTP.
691
+
692
+ **Returns:**
693
+
694
+ - `Promise<void>`: A promise that resolves when the OTP is sent.
695
+
696
+ #### `signUpWithPassword(options)`
697
+
698
+ Registers a new user with email and password. Requires a valid OTP obtained via `sendOtp`.
699
+
700
+ **Parameters:**
701
+
702
+ - `options` (`object`):
703
+ - `email` (`string`): The user's email address.
704
+ - `password` (`string`): The user's password.
705
+ - `otp` (`string`): The OTP received via email.
706
+ - `userName` (`string`, optional): The user's display name.
707
+
708
+ **Returns:**
709
+
710
+ - `Promise<void>`: A promise that resolves when registration is complete.
711
+
712
+ #### `resetPassword(options)`
713
+
714
+ Resets a user's password. Requires a valid OTP obtained via `sendOtp`.
715
+
716
+ **Parameters:**
717
+
718
+ - `options` (`object`):
719
+ - `email` (`string`): The user's email address.
720
+ - `newPassword` (`string`): The new password.
721
+ - `otp` (`string`): The OTP received via email.
722
+
723
+ **Returns:**
724
+
725
+ - `Promise<void>`: A promise that resolves when the password is reset.
726
+
556
727
  #### `signOut()`
557
728
 
558
729
  > **Note:** This method is not available in server-side environments and will throw an error if called.
package/dist/index.d.mts CHANGED
@@ -1,31 +1,21 @@
1
1
  import { FetchOptions } from 'ofetch';
2
2
 
3
- /** popup 句柄 */
4
- interface AuthPopupHandle {
5
- /** popup 发送消息 */
6
- postMessage: (data: any) => void;
7
- /** 关闭 popup */
8
- close: () => void;
9
- /** 聚焦 popup(可选) */
10
- focus?: () => void;
11
- /** 检查 popup 是否已关闭 */
12
- closed: boolean;
3
+ declare enum ReceiveMessageType {
4
+ /** 网页加载完成 */
5
+ READY = "lumi-ready",
6
+ /** 登录成功 */
7
+ SIGN_IN = "lumi-sign-in",
8
+ /** 登录失败 */
9
+ SIGN_IN_FAILED = "lumi-sign-in-failed"
13
10
  }
14
- /** window 适配器 */
15
- interface AuthAdapter {
16
- /** 打开认证弹窗。成功返回 popup 句柄,失败返回 null */
17
- open: (url: string, name?: string) => AuthPopupHandle | null;
18
- /** 监听来自指定 popup 的消息。返回取消监听函数 */
19
- listenMessage: (callback: (data: any, origin: string) => void) => () => void;
20
- /** 监听全局点击。返回取消监听函数 */
21
- listenGlobalClick?: (callback: (e: MouseEvent) => void) => () => void;
22
- /** 获取当前页面的 icon */
23
- getIcon: () => string | null;
24
- /** 获取当前页面的 title */
25
- getTitle: () => string | null;
11
+ declare enum SendMessageType {
12
+ /** 初始化信息 */
13
+ INIT = "lumi-init"
26
14
  }
27
- /** 创建默认的 window 适配器 */
28
- declare function createDefaultAuthAdapter(): AuthAdapter;
15
+ /** 第三方登录提供商 */
16
+ type OAuthProvider = 'google';
17
+ /** 验证码类型 */
18
+ type OtpType = 'register' | 'resetPassword';
29
19
 
30
20
  interface StorageAdapter {
31
21
  storage: {
@@ -33,17 +23,11 @@ interface StorageAdapter {
33
23
  setItem: (key: string, value: string) => void;
34
24
  removeItem: (key: string) => void;
35
25
  };
36
- listen: (callback: (key: string | null | undefined, value: string | null) => void) => () => void;
26
+ listen: (callback: (key: string | null, value: string | null) => void) => () => void;
37
27
  }
38
- declare function createDefaultStorageAdapter(): StorageAdapter;
39
28
 
40
29
  type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
41
30
 
42
- interface ApiResponse<T> {
43
- code: number;
44
- message: string;
45
- data: T;
46
- }
47
31
  interface PaginationData<T> {
48
32
  total: number;
49
33
  list: T[];
@@ -180,7 +164,6 @@ interface LumiClientConfig {
180
164
  apiBaseUrl: string;
181
165
  authOrigin: string;
182
166
  storageAdapter: StorageAdapter;
183
- authAdapter: AuthAdapter;
184
167
  authorization?: string;
185
168
  }
186
169
  declare class LumiClient {
@@ -189,19 +172,9 @@ declare class LumiClient {
189
172
  entities: EntitiesClient;
190
173
  tools: ToolsClient;
191
174
  functions: FunctionsClient;
192
- constructor(config: Optional<LumiClientConfig, 'storageAdapter' | 'authAdapter'>);
193
- }
194
- declare function createClient(config: Optional<LumiClientConfig, 'storageAdapter' | 'authAdapter'>): LumiClient;
195
-
196
- declare enum StorageKey {
197
- ACCESS_TOKEN = "lumi-access-token",
198
- USER = "lumi-user"
199
- }
200
- declare enum MessageType {
201
- READY = "lumi-ready",
202
- INIT = "lumi-init",
203
- SIGN_IN = "lumi-sign-in"
175
+ constructor(config: Optional<LumiClientConfig, 'storageAdapter'>);
204
176
  }
177
+ declare function createClient(config: Optional<LumiClientConfig, 'storageAdapter'>): LumiClient;
205
178
 
206
179
  interface User {
207
180
  userId: string;
@@ -210,15 +183,18 @@ interface User {
210
183
  userRole: 'ADMIN' | 'USER';
211
184
  createdTime: string;
212
185
  }
186
+ interface UserWithToken extends User {
187
+ userToken: string;
188
+ }
213
189
  interface MessageSignInData {
214
190
  projectId: string;
215
191
  accessToken: string;
216
192
  user: User;
217
193
  }
218
194
  type MessageDataReceive = {
219
- type: MessageType.READY;
195
+ type: ReceiveMessageType.READY | ReceiveMessageType.SIGN_IN_FAILED;
220
196
  } | {
221
- type: MessageType.SIGN_IN;
197
+ type: ReceiveMessageType.SIGN_IN;
222
198
  data: MessageSignInData;
223
199
  };
224
200
  interface MessageInitData {
@@ -227,7 +203,7 @@ interface MessageInitData {
227
203
  title: string | null;
228
204
  }
229
205
  interface MessageDataSend {
230
- type: MessageType.INIT;
206
+ type: SendMessageType.INIT;
231
207
  data: MessageInitData;
232
208
  }
233
209
  declare class LumiAuthClient {
@@ -242,6 +218,33 @@ declare class LumiAuthClient {
242
218
  get isAuthenticated(): boolean;
243
219
  /** 登录 */
244
220
  signIn(): Promise<MessageSignInData>;
221
+ /** 使用密码登录 */
222
+ signInWithPassword({ email, password, }: {
223
+ email: string;
224
+ password: string;
225
+ }): Promise<MessageSignInData>;
226
+ /** 发送验证码 */
227
+ sendOtp({ email, type, }: {
228
+ email: string;
229
+ type: OtpType;
230
+ }): Promise<void>;
231
+ /** 使用密码注册 */
232
+ signUpWithPassword({ email, password, otp, userName, }: {
233
+ email: string;
234
+ password: string;
235
+ otp: string;
236
+ userName?: string;
237
+ }): Promise<void>;
238
+ /** 重置密码 */
239
+ resetPassword({ email, newPassword, otp, }: {
240
+ email: string;
241
+ newPassword: string;
242
+ otp: string;
243
+ }): Promise<void>;
244
+ /** 第三方登录 */
245
+ signInWithOAuth({ provider, }: {
246
+ provider: OAuthProvider;
247
+ }): Promise<MessageSignInData>;
245
248
  /** 退出登录 */
246
249
  signOut(): void;
247
250
  /** 获取当前用户 */
@@ -253,10 +256,4 @@ declare class LumiAuthClient {
253
256
  }) => void): () => void;
254
257
  }
255
258
 
256
- declare class LumiError extends Error {
257
- name: string;
258
- code: number;
259
- constructor(code: number, message: string);
260
- }
261
-
262
- export { AITool, type ApiResponse, type ApiStreamResponse, type AuthAdapter, type AuthPopupHandle, EmailTool, EntitiesClient, type Entity, EntityClient, FileTool, FunctionsClient, type GenerateImageResult, type GenerateTextResult, LumiAuthClient, LumiClient, type LumiClientConfig, LumiError, type Message, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageMedia, type MessageSignInData, MessageType, type Optional, type PaginationData, type StorageAdapter, StorageKey, type StreamChunk, ToolsClient, type UploadItem, type User, createClient, createDefaultAuthAdapter, createDefaultStorageAdapter };
259
+ export { AITool, EmailTool, EntitiesClient, type Entity, EntityClient, FileTool, FunctionsClient, type GenerateImageResult, type GenerateTextResult, LumiAuthClient, LumiClient, type LumiClientConfig, type Message, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageMedia, type MessageSignInData, type StreamChunk, ToolsClient, type UploadItem, type User, type UserWithToken, createClient };
package/dist/index.d.ts CHANGED
@@ -1,31 +1,21 @@
1
1
  import { FetchOptions } from 'ofetch';
2
2
 
3
- /** popup 句柄 */
4
- interface AuthPopupHandle {
5
- /** popup 发送消息 */
6
- postMessage: (data: any) => void;
7
- /** 关闭 popup */
8
- close: () => void;
9
- /** 聚焦 popup(可选) */
10
- focus?: () => void;
11
- /** 检查 popup 是否已关闭 */
12
- closed: boolean;
3
+ declare enum ReceiveMessageType {
4
+ /** 网页加载完成 */
5
+ READY = "lumi-ready",
6
+ /** 登录成功 */
7
+ SIGN_IN = "lumi-sign-in",
8
+ /** 登录失败 */
9
+ SIGN_IN_FAILED = "lumi-sign-in-failed"
13
10
  }
14
- /** window 适配器 */
15
- interface AuthAdapter {
16
- /** 打开认证弹窗。成功返回 popup 句柄,失败返回 null */
17
- open: (url: string, name?: string) => AuthPopupHandle | null;
18
- /** 监听来自指定 popup 的消息。返回取消监听函数 */
19
- listenMessage: (callback: (data: any, origin: string) => void) => () => void;
20
- /** 监听全局点击。返回取消监听函数 */
21
- listenGlobalClick?: (callback: (e: MouseEvent) => void) => () => void;
22
- /** 获取当前页面的 icon */
23
- getIcon: () => string | null;
24
- /** 获取当前页面的 title */
25
- getTitle: () => string | null;
11
+ declare enum SendMessageType {
12
+ /** 初始化信息 */
13
+ INIT = "lumi-init"
26
14
  }
27
- /** 创建默认的 window 适配器 */
28
- declare function createDefaultAuthAdapter(): AuthAdapter;
15
+ /** 第三方登录提供商 */
16
+ type OAuthProvider = 'google';
17
+ /** 验证码类型 */
18
+ type OtpType = 'register' | 'resetPassword';
29
19
 
30
20
  interface StorageAdapter {
31
21
  storage: {
@@ -33,17 +23,11 @@ interface StorageAdapter {
33
23
  setItem: (key: string, value: string) => void;
34
24
  removeItem: (key: string) => void;
35
25
  };
36
- listen: (callback: (key: string | null | undefined, value: string | null) => void) => () => void;
26
+ listen: (callback: (key: string | null, value: string | null) => void) => () => void;
37
27
  }
38
- declare function createDefaultStorageAdapter(): StorageAdapter;
39
28
 
40
29
  type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
41
30
 
42
- interface ApiResponse<T> {
43
- code: number;
44
- message: string;
45
- data: T;
46
- }
47
31
  interface PaginationData<T> {
48
32
  total: number;
49
33
  list: T[];
@@ -180,7 +164,6 @@ interface LumiClientConfig {
180
164
  apiBaseUrl: string;
181
165
  authOrigin: string;
182
166
  storageAdapter: StorageAdapter;
183
- authAdapter: AuthAdapter;
184
167
  authorization?: string;
185
168
  }
186
169
  declare class LumiClient {
@@ -189,19 +172,9 @@ declare class LumiClient {
189
172
  entities: EntitiesClient;
190
173
  tools: ToolsClient;
191
174
  functions: FunctionsClient;
192
- constructor(config: Optional<LumiClientConfig, 'storageAdapter' | 'authAdapter'>);
193
- }
194
- declare function createClient(config: Optional<LumiClientConfig, 'storageAdapter' | 'authAdapter'>): LumiClient;
195
-
196
- declare enum StorageKey {
197
- ACCESS_TOKEN = "lumi-access-token",
198
- USER = "lumi-user"
199
- }
200
- declare enum MessageType {
201
- READY = "lumi-ready",
202
- INIT = "lumi-init",
203
- SIGN_IN = "lumi-sign-in"
175
+ constructor(config: Optional<LumiClientConfig, 'storageAdapter'>);
204
176
  }
177
+ declare function createClient(config: Optional<LumiClientConfig, 'storageAdapter'>): LumiClient;
205
178
 
206
179
  interface User {
207
180
  userId: string;
@@ -210,15 +183,18 @@ interface User {
210
183
  userRole: 'ADMIN' | 'USER';
211
184
  createdTime: string;
212
185
  }
186
+ interface UserWithToken extends User {
187
+ userToken: string;
188
+ }
213
189
  interface MessageSignInData {
214
190
  projectId: string;
215
191
  accessToken: string;
216
192
  user: User;
217
193
  }
218
194
  type MessageDataReceive = {
219
- type: MessageType.READY;
195
+ type: ReceiveMessageType.READY | ReceiveMessageType.SIGN_IN_FAILED;
220
196
  } | {
221
- type: MessageType.SIGN_IN;
197
+ type: ReceiveMessageType.SIGN_IN;
222
198
  data: MessageSignInData;
223
199
  };
224
200
  interface MessageInitData {
@@ -227,7 +203,7 @@ interface MessageInitData {
227
203
  title: string | null;
228
204
  }
229
205
  interface MessageDataSend {
230
- type: MessageType.INIT;
206
+ type: SendMessageType.INIT;
231
207
  data: MessageInitData;
232
208
  }
233
209
  declare class LumiAuthClient {
@@ -242,6 +218,33 @@ declare class LumiAuthClient {
242
218
  get isAuthenticated(): boolean;
243
219
  /** 登录 */
244
220
  signIn(): Promise<MessageSignInData>;
221
+ /** 使用密码登录 */
222
+ signInWithPassword({ email, password, }: {
223
+ email: string;
224
+ password: string;
225
+ }): Promise<MessageSignInData>;
226
+ /** 发送验证码 */
227
+ sendOtp({ email, type, }: {
228
+ email: string;
229
+ type: OtpType;
230
+ }): Promise<void>;
231
+ /** 使用密码注册 */
232
+ signUpWithPassword({ email, password, otp, userName, }: {
233
+ email: string;
234
+ password: string;
235
+ otp: string;
236
+ userName?: string;
237
+ }): Promise<void>;
238
+ /** 重置密码 */
239
+ resetPassword({ email, newPassword, otp, }: {
240
+ email: string;
241
+ newPassword: string;
242
+ otp: string;
243
+ }): Promise<void>;
244
+ /** 第三方登录 */
245
+ signInWithOAuth({ provider, }: {
246
+ provider: OAuthProvider;
247
+ }): Promise<MessageSignInData>;
245
248
  /** 退出登录 */
246
249
  signOut(): void;
247
250
  /** 获取当前用户 */
@@ -253,10 +256,4 @@ declare class LumiAuthClient {
253
256
  }) => void): () => void;
254
257
  }
255
258
 
256
- declare class LumiError extends Error {
257
- name: string;
258
- code: number;
259
- constructor(code: number, message: string);
260
- }
261
-
262
- export { AITool, type ApiResponse, type ApiStreamResponse, type AuthAdapter, type AuthPopupHandle, EmailTool, EntitiesClient, type Entity, EntityClient, FileTool, FunctionsClient, type GenerateImageResult, type GenerateTextResult, LumiAuthClient, LumiClient, type LumiClientConfig, LumiError, type Message, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageMedia, type MessageSignInData, MessageType, type Optional, type PaginationData, type StorageAdapter, StorageKey, type StreamChunk, ToolsClient, type UploadItem, type User, createClient, createDefaultAuthAdapter, createDefaultStorageAdapter };
259
+ export { AITool, EmailTool, EntitiesClient, type Entity, EntityClient, FileTool, FunctionsClient, type GenerateImageResult, type GenerateTextResult, LumiAuthClient, LumiClient, type LumiClientConfig, type Message, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageMedia, type MessageSignInData, type StreamChunk, ToolsClient, type UploadItem, type User, type UserWithToken, createClient };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var we=Object.create;var R=Object.defineProperty,Ae=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyDescriptors,Ee=Object.getOwnPropertyNames,X=Object.getOwnPropertySymbols,Ie=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var ee=r=>{throw TypeError(r)};var Z=(r,e,t)=>e in r?R(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,I=(r,e)=>{for(var t in e||(e={}))W.call(e,t)&&Z(r,t,e[t]);if(X)for(var t of X(e))Te.call(e,t)&&Z(r,t,e[t]);return r},_=(r,e)=>Ae(r,be(e));var Ce=(r,e)=>{for(var t in e)R(r,t,{get:e[t],enumerable:!0})},te=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ee(e))!W.call(r,o)&&o!==t&&R(r,o,{get:()=>e[o],enumerable:!(i=Se(e,o))||i.enumerable});return r};var L=(r,e,t)=>(t=r!=null?we(Ie(r)):{},te(e||!r||!r.__esModule?R(t,"default",{value:r,enumerable:!0}):t,r)),xe=r=>te(R({},"__esModule",{value:!0}),r);var re=(r,e,t)=>e.has(r)||ee("Cannot "+t);var s=(r,e,t)=>(re(r,e,"read from private field"),t?t.call(r):e.get(r)),p=(r,e,t)=>e.has(r)?ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),d=(r,e,t,i)=>(re(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t);var a=(r,e,t)=>new Promise((i,o)=>{var n=h=>{try{f(t.next(h))}catch(y){o(y)}},c=h=>{try{f(t.throw(h))}catch(y){o(y)}},f=h=>h.done?i(h.value):Promise.resolve(h.value).then(n,c);f((t=t.apply(r,e)).next())});var Me={};Ce(Me,{AITool:()=>N,EmailTool:()=>q,EntitiesClient:()=>D,EntityClient:()=>O,FileTool:()=>$,FunctionsClient:()=>U,LumiAuthClient:()=>P,LumiClient:()=>B,LumiError:()=>u,MessageType:()=>J,StorageKey:()=>z,ToolsClient:()=>j,createClient:()=>Pe,createDefaultAuthAdapter:()=>F,createDefaultStorageAdapter:()=>K});module.exports=xe(Me);var he=require("uuid");var z=(t=>(t.ACCESS_TOKEN="lumi-access-token",t.USER="lumi-user",t))(z||{}),J=(i=>(i.READY="lumi-ready",i.INIT="lumi-init",i.SIGN_IN="lumi-sign-in",i))(J||{});var u=class extends Error{constructor(t,i){super(i);this.name="LumiError";this.code=t}};var ce=L(require("crypto-js/enc-base64")),le=L(require("crypto-js/enc-hex")),me=L(require("crypto-js/hmac-sha256")),ue=L(require("crypto-js/sha256")),pe=L(require("object-hash")),Q=require("ofetch");var ie,w=typeof window=="undefined"&&((ie=globalThis.navigator)==null?void 0:ie.product)!=="ReactNative";function se(r){return new Promise(e=>setTimeout(e,r))}function ne(r){var e;return typeof process!="undefined"&&(e=process==null?void 0:process.env[r])!=null?e:null}var ve="6QrJZ7pFCmBZAeIJF7IArvkCz+EtzA0RVcpHkiQIsQyhs7QtCS9P+CueZdHfB2OtJcgX3BbqY9pfpWeAVTqCwQ==";function oe(r){return encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Re(r){let e=Math.floor(Date.now()/1e3).toString(),t=Math.random().toString(36).substring(2,15),i=I({},r.query),o=Object.keys(i).sort().map(m=>`${oe(m)}=${oe(String(i[m]))}`).join("&"),n={"x-timestamp":e,"x-nonce":t},c=Object.keys(n).sort().map(m=>`${m}:${n[m]}`).join(`
2
- `),f=r.body&&!(r.body instanceof FormData)?JSON.stringify(r.body):"",h=(0,ue.default)(f).toString(le.default),y=[o,c,h].join(`
3
- `),b=ce.default.stringify((0,me.default)(y,ve)),E=new Headers(r.headers);Object.entries(n).forEach(([m,x])=>{E.set(m,x)}),E.set("X-Sign",b),r.headers=E}var ae=new Map;function Le(r,e){var c;let t=I({},e);e.body instanceof FormData&&(t.body=Array.from(e.body.entries())),t.headers=void 0;let i=(0,pe.default)([r,t]),o=Date.now(),n=((c=ae.get(i))==null?void 0:c.filter(f=>o-f<1e3))||[];if(n.length>=4)throw new u(429,"Too many requests");n.push(o),ae.set(i,n)}function de(r,e,t,i=!1){t.headers=new Headers(t.headers),r.auth.accessToken&&t.headers.set("Authorization",`Bearer ${r.auth.accessToken}`),i&&(t.headers.get("Accept")||t.headers.set("Accept","text/event-stream"),t.headers.get("Cache-Control")||t.headers.set("Cache-Control","no-cache"),t.headers.get("X-Accel-Buffering")||t.headers.set("X-Accel-Buffering","no")),Le(e,t),Re(t)}function l(r,e,t={}){de(r,e,t);let i=r.auth.isAuthenticated;return(0,Q.ofetch)(e,_(I({baseURL:r.config.apiBaseUrl},t),{onResponse:({response:o})=>{var n;!w&&i&&((n=o._data)==null?void 0:n.code)===2100&&r.auth.signOut()}}))}function ge(i,o){return a(this,arguments,function*(r,e,t={}){return de(r,e,t,!0),yield(0,Q.ofetch)(e,_(I({baseURL:r.config.apiBaseUrl},t),{responseType:"stream"}))})}function Y(r,e,t){let i=r.config.storageAdapter.storage;t!==null?i.setItem(e,JSON.stringify(t)):i.removeItem(e)}function V(r,e){let i=r.config.storageAdapter.storage.getItem(e);try{return i?JSON.parse(i):null}catch(o){return null}}var g,G,M,P=class{constructor(e){p(this,g);p(this,G,`lumi-auth-${(0,he.v4)()}`);p(this,M,null);d(this,g,e),Promise.resolve().then(()=>{!w&&this.isAuthenticated&&this.refreshUser()})}get accessToken(){if(w){let e=s(this,g).config.authorization;return e?e.replace("Bearer ",""):null}return V(s(this,g),"lumi-access-token")}set accessToken(e){if(w){s(this,g).config.authorization=e?`Bearer ${e}`:void 0;return}Y(s(this,g),"lumi-access-token",e)}get user(){return w?s(this,M):V(s(this,g),"lumi-user")}set user(e){if(w){d(this,M,e);return}Y(s(this,g),"lumi-user",e)}get isAuthenticated(){return!!this.accessToken}signIn(){if(w)throw new Error("auth.signIn() can only be called on the client side");let{authAdapter:e}=s(this,g).config,t=e.open(s(this,g).config.authOrigin,s(this,G)),i;return new Promise((o,n)=>{var E;if(!t)return n(new Error("Open auth window failed"));let c=setInterval(()=>{t.closed&&n(new u(499,"Auth window closed"))},1e3),f=m=>{var x;t.closed||((x=t.focus)==null||x.call(t),m.stopPropagation(),m.preventDefault())},h=(m,x)=>{if(!(x!==s(this,g).config.authOrigin||!m))switch(m.type){case"lumi-ready":{t.postMessage({type:"lumi-init",data:{projectId:s(this,g).config.projectId,icon:e.getIcon(),title:e.getTitle()}});break}case"lumi-sign-in":{if(m.data.projectId!==s(this,g).config.projectId)break;t.close(),this.accessToken=m.data.accessToken,this.user=m.data.user,o(m.data);break}}},y=e.listenMessage(h),b=(E=e.listenGlobalClick)==null?void 0:E.call(e,f);i=()=>{clearInterval(c),y(),b==null||b()}}).finally(()=>i==null?void 0:i())}signOut(){if(w)throw new Error("auth.signOut() can only be called on the client side");this.accessToken=null,this.user=null}refreshUser(){return a(this,null,function*(){let e=yield l(s(this,g),"/lm/user/info",{method:"POST"});if(e.code!==200)throw new Error(e.message);return this.user=e.data,e.data})}onAuthChange(e){if(w)throw new Error("auth.onAuthChange() can only be called on the client side");let t=s(this,g).config.storageAdapter.listen(i=>{(i==="lumi-access-token"||i==="lumi-user"||!i)&&e({isAuthenticated:this.isAuthenticated,user:this.user})});return()=>t()}};g=new WeakMap,G=new WeakMap,M=new WeakMap;var A,O=class{constructor(e,t){p(this,A);d(this,A,e),this.entityName=t}list(){return a(this,arguments,function*({filter:e,sort:t,limit:i,skip:o}={}){if(i){let n=yield l(s(this,A),this.uri("/find"),{method:"POST",body:{filter:e,sort:t,limit:i,skip:o}});if(n.code!==200)throw new Error(n.message);return n.data}else{let n=yield l(s(this,A),this.uri("/list"),{method:"POST",body:{filter:e,sort:t}});if(n.code!==200)throw new Error(n.message);return{total:n.data.length,list:n.data}}})}get(e){return a(this,null,function*(){let t=yield l(s(this,A),this.uri(`/${e}`),{method:"GET"});if(t.code!==200)throw new Error(t.message);return t.data})}create(e){return a(this,null,function*(){let t=yield l(s(this,A),this.uri(),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}createMany(e){return a(this,null,function*(){let t=yield l(s(this,A),this.uri("/batch"),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}update(e,t){return a(this,null,function*(){let i=yield l(s(this,A),this.uri(),{method:"PUT",body:{filter:{_id:e},update:t}});if(i.code!==200)throw new Error(i.message);return i.data})}delete(e){return a(this,null,function*(){let t=yield l(s(this,A),this.uri(`/${e}`),{method:"DELETE"});if(t.code!==200)throw new Error(t.message)})}deleteMany(e){return a(this,null,function*(){let t=yield l(s(this,A),this.uri("/batch-by-ids"),{method:"DELETE",params:{ids:e}});if(t.code!==200)throw new Error(t.message)})}uri(e=""){return`/lm/${s(this,A).config.projectId}/${this.entityName}/documents${e}`}};A=new WeakMap;var k,D=class{constructor(e){p(this,k);return d(this,k,e),new Proxy(this,{get(t,i){return i in t||(t[i]=new O(s(t,k),i)),t[i]}})}};k=new WeakMap;var fe=require("ofetch");var T,U=class{constructor(e){p(this,T);d(this,T,e)}invoke(e,t={}){return s(this,T).auth.accessToken&&(t.headers=I({Authorization:`Bearer ${s(this,T).auth.accessToken}`},t.headers)),(0,fe.ofetch)(`/v1/functions/${s(this,T).config.projectId}/${e}`,I({baseURL:s(this,T).config.apiBaseUrl},t))}};T=new WeakMap;function F(){return{open:(r,e)=>{let o=(window.screen.width-800)/2,n=(window.screen.height-600)/2,c=window.open(r,e,`width=800,height=600,left=${o},top=${n}`);return c?{postMessage:f=>c.postMessage(f,r),close:()=>c.close(),focus:()=>c.focus(),get closed(){return c.closed}}:null},listenMessage:r=>{let e=t=>{r(t.data,t.origin)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},listenGlobalClick:r=>(window.addEventListener("click",r,!0),()=>window.removeEventListener("click",r,!0)),getIcon:()=>{var r,e;return(e=(r=document.querySelector('link[rel="icon"]'))==null?void 0:r.href)!=null?e:null},getTitle:()=>document.title}}function K(){return{storage:{getItem:localStorage.getItem,setItem:(r,e)=>{localStorage.setItem(r,e),window.dispatchEvent(new StorageEvent("storage",{key:r,oldValue:null,newValue:e,storageArea:localStorage}))},removeItem:localStorage.removeItem},listen:r=>{let e=t=>{r(t.key,t.newValue)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)}}}var ye=require("eventsource-parser/stream");var S,N=class{constructor(e){p(this,S);d(this,S,e)}generateText(i){return a(this,arguments,function*({model:e="gemini-2.5-flash",messages:t}){let o=this.checkLumiApiKey(),n=yield l(s(this,S),`/lm/${s(this,S).config.projectId}/ai/chat/completions`,{method:"POST",body:{lumiApiKey:o,modelName:e,chatMessages:t}});if(n.code!==200)throw new u(n.code,n.message);return n.data})}generateTextStream(i){return a(this,arguments,function*({model:e="gemini-2.5-flash",messages:t}){let o=this.checkLumiApiKey();return ge(s(this,S),`/lm/${s(this,S).config.projectId}/ai/chat/stream`,{method:"POST",body:{lumiApiKey:o,modelName:e,chatMessages:t}})})}generateImage(i){return a(this,arguments,function*({model:e="gemini-2.5-flash-image",messages:t}){let o=this.checkLumiApiKey(),{code:n,message:c,data:f}=yield l(s(this,S),`/lm/${s(this,S).config.projectId}/ai/image/task`,{method:"POST",body:{lumiApiKey:o,modelName:e,chatMessages:t}});if(n!==200)throw new u(n,c);let h=f,y=1e3;for(;h.generationStatus==="PROCESSING";){yield se(y),y<5e3&&(y+=500);let{code:b,message:E,data:m}=yield l(s(this,S),`/lm/${s(this,S).config.projectId}/ai/image/get`,{method:"POST",body:{lumiApiKey:o,messageId:h.messageId}});if(b!==200)throw new u(b,E);h=m}return h})}parseStream(e){return a(this,null,function*(){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ye.EventSourceParserStream).pipeThrough(new TransformStream({transform:(t,i)=>{try{let o=JSON.parse(t.data);i.enqueue({event:t.event,data:o})}catch(o){console.error(`Parse stream chunk failed: Invalid JSON.
4
- ${t.data}`)}}}))})}checkLumiApiKey(){if(!w)throw new u(400,"lumi.tools.ai is only available on the server-side");let e=ne("LUMI_API_KEY");if(!e)throw new u(400,"LUMI_API_KEY is required");return e}};S=new WeakMap;var v,q=class{constructor(e){p(this,v);d(this,v,e)}send(h){return a(this,arguments,function*({to:e,subject:t,fromName:i,html:o,text:n="",replyTo:c,scheduledAt:f}){if(!e||!t||!o&&!n)throw new Error("Failed to send email: Missing required parameters.");typeof e=="string"&&(e=[e]),typeof c=="string"&&(c=[c]);let y=yield l(s(this,v),`/lm/${s(this,v).config.projectId}/email/send`,{method:"POST",body:{to:e,subject:t,fromName:i,html:o,text:n,replyTo:c,scheduledAt:f}});if(y.code!==200)throw new u(y.code,y.message)})}};v=new WeakMap;var C,$=class{constructor(e){p(this,C);d(this,C,e)}upload(e){return a(this,null,function*(){let t=new FormData;e.forEach(o=>{t.append("files",o)});let i=yield l(s(this,C),`/lm/${s(this,C).config.projectId}/file/batch`,{method:"POST",body:t});if(i.code!==200)throw new u(i.code,i.message);return i.data})}delete(e){return a(this,null,function*(){let t=yield l(s(this,C),`/lm/${s(this,C).config.projectId}/file/batch`,{method:"DELETE",body:{fileUrls:e}});if(t.code!==200)throw new u(t.code,t.message)})}};C=new WeakMap;var H,j=class{constructor(e){p(this,H);d(this,H,e),this.email=new q(e),this.file=new $(e),this.ai=new N(e)}};H=new WeakMap;var B=class{constructor(e){var t,i;(t=e.storageAdapter)!=null||(e.storageAdapter=K()),(i=e.authAdapter)!=null||(e.authAdapter=F()),this.config=e,this.auth=new P(this),this.entities=new D(this),this.tools=new j(this),this.functions=new U(this)}};function Pe(r){return new B(r)}0&&(module.exports={AITool,EmailTool,EntitiesClient,EntityClient,FileTool,FunctionsClient,LumiAuthClient,LumiClient,LumiError,MessageType,StorageKey,ToolsClient,createClient,createDefaultAuthAdapter,createDefaultStorageAdapter});
1
+ "use strict";var Ie=Object.create;var L=Object.defineProperty,Ee=Object.defineProperties,ve=Object.getOwnPropertyDescriptor,Re=Object.getOwnPropertyDescriptors,Ce=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols,Pe=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,Le=Object.prototype.propertyIsEnumerable;var re=r=>{throw TypeError(r)};var ee=(r,e,t)=>e in r?L(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,T=(r,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(r,t,e[t]);if(Z)for(var t of Z(e))Le.call(e,t)&&ee(r,t,e[t]);return r},z=(r,e)=>Ee(r,Re(e));var xe=(r,e)=>{for(var t in e)L(r,t,{get:e[t],enumerable:!0})},ie=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ce(e))!te.call(r,n)&&n!==t&&L(r,n,{get:()=>e[n],enumerable:!(s=ve(e,n))||s.enumerable});return r};var C=(r,e,t)=>(t=r!=null?Ie(Pe(r)):{},ie(e||!r||!r.__esModule?L(t,"default",{value:r,enumerable:!0}):t,r)),Oe=r=>ie(L({},"__esModule",{value:!0}),r);var J=(r,e,t)=>e.has(r)||re("Cannot "+t);var i=(r,e,t)=>(J(r,e,"read from private field"),t?t.call(r):e.get(r)),p=(r,e,t)=>e.has(r)?re("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),d=(r,e,t,s)=>(J(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),Q=(r,e,t)=>(J(r,e,"access private method"),t);var c=(r,e,t)=>new Promise((s,n)=>{var o=h=>{try{g(t.next(h))}catch(f){n(f)}},m=h=>{try{g(t.throw(h))}catch(f){n(f)}},g=h=>h.done?s(h.value):Promise.resolve(h.value).then(o,m);g((t=t.apply(r,e)).next())});var je={};xe(je,{AITool:()=>N,EmailTool:()=>$,EntitiesClient:()=>k,EntityClient:()=>U,FileTool:()=>q,FunctionsClient:()=>j,LumiAuthClient:()=>x,LumiClient:()=>H,ToolsClient:()=>K,createClient:()=>De});module.exports=Oe(je);var G=C(require("crypto-js/sha256")),ye=require("uuid");var u=class extends Error{constructor(t,s){super(s);this.name="LumiError";this.code=t}};var le=C(require("crypto-js/enc-base64")),ue=C(require("crypto-js/enc-hex")),pe=C(require("crypto-js/hmac-sha256")),de=C(require("crypto-js/sha256")),ge=C(require("object-hash")),V=require("ofetch");function ne(){var r,e;return(e=(r=document.querySelector('link[rel="icon"]'))==null?void 0:r.href)!=null?e:null}function oe(){var r;return(r=document.title)!=null?r:null}var se,y=typeof window=="undefined"&&((se=globalThis.navigator)==null?void 0:se.product)!=="ReactNative";function ae(r){return new Promise(e=>setTimeout(e,r))}function F(r){var e;return typeof process!="undefined"&&(e=process==null?void 0:process.env[r])!=null?e:null}var Me="6QrJZ7pFCmBZAeIJF7IArvkCz+EtzA0RVcpHkiQIsQyhs7QtCS9P+CueZdHfB2OtJcgX3BbqY9pfpWeAVTqCwQ==";function ce(r){return encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Ue(r){let e=Math.floor(Date.now()/1e3).toString(),t=Math.random().toString(36).substring(2,15),s=T(T({},r.query),r.params),n=Object.keys(s).sort().map(S=>`${ce(S)}=${ce(String(s[S]))}`).join("&"),o={"x-timestamp":e,"x-nonce":t},m=Object.keys(o).sort().map(S=>`${S}:${o[S]}`).join(`
2
+ `),g=r.body&&!(r.body instanceof FormData)?JSON.stringify(r.body):"",h=(0,de.default)(g).toString(ue.default),f=[n,m,h].join(`
3
+ `),R=le.default.stringify((0,pe.default)(f,Me)),I=new Headers(r.headers);Object.entries(o).forEach(([S,b])=>{I.set(S,b)}),I.set("X-Sign",R),r.headers=I}var me=new Map;function ke(r,e){var m;let t=T({},e);e.body instanceof FormData&&(t.body=Array.from(e.body.entries())),t.headers=void 0;let s=(0,ge.default)([r,t]),n=Date.now(),o=((m=me.get(s))==null?void 0:m.filter(g=>n-g<1e3))||[];if(o.length>=4)throw new u(10429,"Too many requests");o.push(n),me.set(s,o)}function he(r,e,t,s=!1){t.headers=new Headers(t.headers),r.auth.accessToken&&t.headers.set("Authorization",`Bearer ${r.auth.accessToken}`);let n=F("TOP_ACCESS_KEY");n&&t.headers.set("X-Top-Access",n),s&&(t.headers.get("Accept")||t.headers.set("Accept","text/event-stream"),t.headers.get("Cache-Control")||t.headers.set("Cache-Control","no-cache"),t.headers.get("X-Accel-Buffering")||t.headers.set("X-Accel-Buffering","no")),ke(e,t),Ue(t)}function l(r,e,t={}){he(r,e,t);let s=r.auth.isAuthenticated;return(0,V.ofetch)(e,z(T({baseURL:r.config.apiBaseUrl},t),{onResponse:({response:n})=>{var o;!y&&s&&((o=n._data)==null?void 0:o.code)===2100&&r.auth.signOut()}}))}function fe(s,n){return c(this,arguments,function*(r,e,t={}){return he(r,e,t,!0),yield(0,V.ofetch)(e,z(T({baseURL:r.config.apiBaseUrl},t),{responseType:"stream"}))})}function Y(r,e,t){let s=r.config.storageAdapter.storage;t!==null?s.setItem(e,JSON.stringify(t)):s.removeItem(e)}function W(r,e){let s=r.config.storageAdapter.storage.getItem(e);try{return s?JSON.parse(s):null}catch(n){return null}}var a,_,O,M,X,x=class{constructor(e){p(this,M);p(this,a);p(this,_,`lumi-auth-${(0,ye.v4)()}`);p(this,O,null);d(this,a,e),Promise.resolve().then(()=>{!y&&this.isAuthenticated&&this.refreshUser()})}get accessToken(){if(y){let e=i(this,a).config.authorization;return e?e.replace("Bearer ",""):null}return W(i(this,a),"lumi-access-token")}set accessToken(e){if(y){i(this,a).config.authorization=e?`Bearer ${e}`:void 0;return}Y(i(this,a),"lumi-access-token",e)}get user(){return y?i(this,O):W(i(this,a),"lumi-user")}set user(e){if(y){d(this,O,e);return}Y(i(this,a),"lumi-user",e)}get isAuthenticated(){return!!this.accessToken}signIn(){return Q(this,M,X).call(this,i(this,a).config.authOrigin)}signInWithPassword(s){return c(this,arguments,function*({email:e,password:t}){let n=yield l(i(this,a),"/lm/user/password/login",{method:"POST",body:{projectId:i(this,a).config.projectId,email:e,password:(0,G.default)(t).toString()}});if(n.code!==200)throw new u(n.code,n.message);return{projectId:i(this,a).config.projectId,accessToken:n.data.userToken,user:n.data}})}sendOtp(s){return c(this,arguments,function*({email:e,type:t}){let n=yield l(i(this,a),"/lm/user/email/code/send",{method:"POST",body:{projectId:i(this,a).config.projectId,email:e,emailType:t}});if(n.code!==200)throw new u(n.code,n.message)})}signUpWithPassword(o){return c(this,arguments,function*({email:e,password:t,otp:s,userName:n}){let m=yield l(i(this,a),"/lm/user/password/register",{method:"POST",body:{projectId:i(this,a).config.projectId,email:e,password:(0,G.default)(t).toString(),code:s,userName:n}});if(m.code!==200)throw new u(m.code,m.message)})}resetPassword(n){return c(this,arguments,function*({email:e,newPassword:t,otp:s}){let o=yield l(i(this,a),"/lm/user/password/reset",{method:"POST",body:{projectId:i(this,a).config.projectId,email:e,newPassword:(0,G.default)(t).toString(),code:s}});if(o.code!==200)throw new u(o.code,o.message)})}signInWithOAuth({provider:e}){return Q(this,M,X).call(this,`${i(this,a).config.authOrigin}/oauth/${e}`)}signOut(){if(y)throw new Error("auth.signOut() can only be called on the client side");this.accessToken=null,this.user=null}refreshUser(){return c(this,null,function*(){let e=yield l(i(this,a),"/lm/user/info",{method:"POST"});if(e.code!==200)throw new Error(e.message);return this.user=e.data,e.data})}onAuthChange(e){if(y)throw new Error("auth.onAuthChange() can only be called on the client side");let t=i(this,a).config.storageAdapter.listen(s=>{(s==="lumi-access-token"||s==="lumi-user"||!s)&&e({isAuthenticated:this.isAuthenticated,user:this.user})});return()=>t()}};a=new WeakMap,_=new WeakMap,O=new WeakMap,M=new WeakSet,X=function(e){if(y)throw new u(10400,"This method can only be called on the client side");let t=800,s=600,n=(window.screen.width-t)/2,o=(window.screen.height-s)/2,m=window.open(e,i(this,_),`width=${t},height=${s},left=${n},top=${o}`),g;return new Promise((h,f)=>{if(!m)return f(new u(10500,"Open auth window failed"));let R=setInterval(()=>{m.closed&&f(new u(10499,"Auth window closed"))},1e3),I=b=>{m.closed||(m.focus(),b.stopPropagation(),b.preventDefault())},S=({data:b,origin:Ae,source:Te})=>{if(!(Ae!==i(this,a).config.authOrigin||Te!==m))switch(b==null?void 0:b.type){case"lumi-ready":{m.postMessage({type:"lumi-init",data:{projectId:i(this,a).config.projectId,icon:ne(),title:oe()}},i(this,a).config.authOrigin);break}case"lumi-sign-in":{if(b.data.projectId!==i(this,a).config.projectId)break;m.close(),window.focus(),this.accessToken=b.data.accessToken,this.user=b.data.user,h(b.data);break}}};window.addEventListener("message",S),document.addEventListener("click",I,!0),g=()=>{clearInterval(R),window.removeEventListener("message",S),document.removeEventListener("click",I,!0)}}).finally(()=>g==null?void 0:g())};var w,U=class{constructor(e,t){p(this,w);d(this,w,e),this.entityName=t}list(){return c(this,arguments,function*({filter:e,sort:t,limit:s,skip:n}={}){if(s){let o=yield l(i(this,w),this.uri("/listByPage"),{method:"POST",body:{filter:e,sort:t,limit:s,skip:n}});if(o.code!==200)throw new Error(o.message);return o.data}else{let o=yield l(i(this,w),this.uri("/list"),{method:"POST",body:{filter:e,sort:t}});if(o.code!==200)throw new Error(o.message);return{total:o.data.length,list:o.data}}})}get(e){return c(this,null,function*(){let t=yield l(i(this,w),this.uri(`/${e}`),{method:"GET"});if(t.code!==200)throw new Error(t.message);return t.data})}create(e){return c(this,null,function*(){let t=yield l(i(this,w),this.uri(),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}createMany(e){return c(this,null,function*(){let t=yield l(i(this,w),this.uri("/batch"),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}update(e,t){return c(this,null,function*(){let s=yield l(i(this,w),this.uri(),{method:"PUT",body:{filter:{_id:e},update:t}});if(s.code!==200)throw new Error(s.message);return s.data})}delete(e){return c(this,null,function*(){let t=yield l(i(this,w),this.uri(`/${e}`),{method:"DELETE"});if(t.code!==200)throw new Error(t.message)})}deleteMany(e){return c(this,null,function*(){let t=yield l(i(this,w),this.uri("/batch-by-ids"),{method:"DELETE",params:{ids:e}});if(t.code!==200)throw new Error(t.message)})}uri(e=""){return`/lm/${i(this,w).config.projectId}/${this.entityName}/documents${e}`}};w=new WeakMap;var D,k=class{constructor(e){p(this,D);return d(this,D,e),new Proxy(this,{get(t,s){return s in t||(t[s]=new U(i(t,D),s)),t[s]}})}};D=new WeakMap;var we=require("ofetch");var E,j=class{constructor(e){p(this,E);d(this,E,e)}invoke(e,t={}){return i(this,E).auth.accessToken&&(t.headers=T({Authorization:`Bearer ${i(this,E).auth.accessToken}`},t.headers)),(0,we.ofetch)(`/v1/functions/${i(this,E).config.projectId}/${e}`,T({baseURL:i(this,E).config.apiBaseUrl},t))}};E=new WeakMap;function Se(){return{storage:{getItem:r=>localStorage.getItem(r),setItem:(r,e)=>{localStorage.setItem(r,e),window.dispatchEvent(new StorageEvent("storage",{key:r,oldValue:null,newValue:e,storageArea:localStorage}))},removeItem:r=>{localStorage.removeItem(r),window.dispatchEvent(new StorageEvent("storage",{key:r,oldValue:null,newValue:null,storageArea:localStorage}))}},listen:r=>{let e=t=>{r(t.key,t.newValue)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)}}}var be=require("eventsource-parser/stream");var A,N=class{constructor(e){p(this,A);d(this,A,e)}generateText(s){return c(this,arguments,function*({model:e="gemini-2.5-flash",messages:t}){let n=this.checkLumiApiKey(),o=yield l(i(this,A),`/lm/${i(this,A).config.projectId}/ai/chat/completions`,{method:"POST",body:{lumiApiKey:n,modelName:e,chatMessages:t}});if(o.code!==200)throw new u(o.code,o.message);return o.data})}generateTextStream(s){return c(this,arguments,function*({model:e="gemini-2.5-flash",messages:t}){let n=this.checkLumiApiKey();return fe(i(this,A),`/lm/${i(this,A).config.projectId}/ai/chat/stream`,{method:"POST",body:{lumiApiKey:n,modelName:e,chatMessages:t}})})}generateImage(s){return c(this,arguments,function*({model:e="gemini-2.5-flash-image",messages:t}){let n=this.checkLumiApiKey(),{code:o,message:m,data:g}=yield l(i(this,A),`/lm/${i(this,A).config.projectId}/ai/image/task`,{method:"POST",body:{lumiApiKey:n,modelName:e,chatMessages:t}});if(o!==200)throw new u(o,m);let h=g,f=1e3;for(;h.generationStatus==="PROCESSING";){yield ae(f),f<5e3&&(f+=500);let{code:R,message:I,data:S}=yield l(i(this,A),`/lm/${i(this,A).config.projectId}/ai/image/get`,{method:"POST",body:{lumiApiKey:n,messageId:h.messageId}});if(R!==200)throw new u(R,I);h=S}return h})}parseStream(e){return c(this,null,function*(){return e.pipeThrough(new TextDecoderStream).pipeThrough(new be.EventSourceParserStream).pipeThrough(new TransformStream({transform:(t,s)=>{try{let n=JSON.parse(t.data);s.enqueue({event:t.event,data:n})}catch(n){console.error(`Parse stream chunk failed: Invalid JSON.
4
+ ${t.data}`)}}}))})}checkLumiApiKey(){if(!y)throw new u(10400,"lumi.tools.ai is only available on the server-side");let e=F("LUMI_API_KEY");if(!e)throw new u(10400,"LUMI_API_KEY is required");return e}};A=new WeakMap;var P,$=class{constructor(e){p(this,P);d(this,P,e)}send(h){return c(this,arguments,function*({to:e,subject:t,fromName:s,html:n,text:o="",replyTo:m,scheduledAt:g}){if(!e||!t||!n&&!o)throw new Error("Failed to send email: Missing required parameters.");typeof e=="string"&&(e=[e]),typeof m=="string"&&(m=[m]);let f=yield l(i(this,P),`/lm/${i(this,P).config.projectId}/email/send`,{method:"POST",body:{to:e,subject:t,fromName:s,html:n,text:o,replyTo:m,scheduledAt:g}});if(f.code!==200)throw new u(f.code,f.message)})}};P=new WeakMap;var v,q=class{constructor(e){p(this,v);d(this,v,e)}upload(e){return c(this,null,function*(){let t=new FormData;e.forEach(n=>{t.append("files",n)});let s=yield l(i(this,v),`/lm/${i(this,v).config.projectId}/file/batch`,{method:"POST",body:t});if(s.code!==200)throw new u(s.code,s.message);return s.data})}delete(e){return c(this,null,function*(){let t=yield l(i(this,v),`/lm/${i(this,v).config.projectId}/file/batch`,{method:"DELETE",body:{fileUrls:e}});if(t.code!==200)throw new u(t.code,t.message)})}};v=new WeakMap;var B,K=class{constructor(e){p(this,B);d(this,B,e),this.email=new $(e),this.file=new q(e),this.ai=new N(e)}};B=new WeakMap;var H=class{constructor(e){var t;(t=e.storageAdapter)!=null||(e.storageAdapter=Se()),this.config=e,this.auth=new x(this),this.entities=new k(this),this.tools=new K(this),this.functions=new j(this)}};function De(r){return new H(r)}0&&(module.exports={AITool,EmailTool,EntitiesClient,EntityClient,FileTool,FunctionsClient,LumiAuthClient,LumiClient,ToolsClient,createClient});
5
5
  //# sourceMappingURL=index.js.map