@urbackend/sdk 0.3.1 → 0.4.1
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 +13 -10
- package/dist/index.cjs +51 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1264 -0
- package/dist/index.d.ts +1264 -0
- package/dist/index.mjs +51 -15
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1264 @@
|
|
|
1
|
+
interface UrBackendConfig {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
headers?: Record<string, string>;
|
|
5
|
+
}
|
|
6
|
+
interface RequestOptions {
|
|
7
|
+
body?: unknown;
|
|
8
|
+
token?: string;
|
|
9
|
+
isMultipart?: boolean;
|
|
10
|
+
credentials?: RequestCredentials;
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
interface QueryParams {
|
|
14
|
+
page?: number;
|
|
15
|
+
limit?: number;
|
|
16
|
+
sort?: string;
|
|
17
|
+
populate?: string | string[];
|
|
18
|
+
expand?: string | string[];
|
|
19
|
+
filter?: Record<string, unknown>;
|
|
20
|
+
[key: string]: unknown;
|
|
21
|
+
}
|
|
22
|
+
interface SignUpPayload {
|
|
23
|
+
email: string;
|
|
24
|
+
password: string;
|
|
25
|
+
username?: string;
|
|
26
|
+
name?: string;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
interface LoginPayload {
|
|
30
|
+
email: string;
|
|
31
|
+
password: string;
|
|
32
|
+
}
|
|
33
|
+
interface UpdateProfilePayload {
|
|
34
|
+
username?: string;
|
|
35
|
+
name?: string;
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
interface ChangePasswordPayload {
|
|
39
|
+
currentPassword: string;
|
|
40
|
+
newPassword: string;
|
|
41
|
+
}
|
|
42
|
+
interface VerifyEmailPayload {
|
|
43
|
+
email: string;
|
|
44
|
+
otp: string;
|
|
45
|
+
}
|
|
46
|
+
interface ResendOtpPayload {
|
|
47
|
+
email: string;
|
|
48
|
+
}
|
|
49
|
+
interface RequestPasswordResetPayload {
|
|
50
|
+
email: string;
|
|
51
|
+
}
|
|
52
|
+
interface ResetPasswordPayload {
|
|
53
|
+
email: string;
|
|
54
|
+
otp: string;
|
|
55
|
+
newPassword: string;
|
|
56
|
+
}
|
|
57
|
+
interface SocialExchangePayload {
|
|
58
|
+
token: string;
|
|
59
|
+
rtCode: string;
|
|
60
|
+
}
|
|
61
|
+
interface SocialExchangeResponse {
|
|
62
|
+
refreshToken: string;
|
|
63
|
+
}
|
|
64
|
+
interface AuthUser {
|
|
65
|
+
_id: string;
|
|
66
|
+
email: string;
|
|
67
|
+
username?: string;
|
|
68
|
+
name?: string;
|
|
69
|
+
[key: string]: unknown;
|
|
70
|
+
}
|
|
71
|
+
interface AuthResponse {
|
|
72
|
+
accessToken?: string;
|
|
73
|
+
/** @deprecated use accessToken instead */
|
|
74
|
+
token?: string;
|
|
75
|
+
expiresIn?: string;
|
|
76
|
+
userId?: string;
|
|
77
|
+
user?: AuthUser;
|
|
78
|
+
}
|
|
79
|
+
interface DocumentData {
|
|
80
|
+
_id: string;
|
|
81
|
+
[key: string]: unknown;
|
|
82
|
+
}
|
|
83
|
+
interface InsertPayload {
|
|
84
|
+
[key: string]: unknown;
|
|
85
|
+
}
|
|
86
|
+
interface UpdatePayload {
|
|
87
|
+
[key: string]: unknown;
|
|
88
|
+
}
|
|
89
|
+
interface PatchPayload {
|
|
90
|
+
[key: string]: unknown;
|
|
91
|
+
}
|
|
92
|
+
interface SchemaField {
|
|
93
|
+
key: string;
|
|
94
|
+
type: string;
|
|
95
|
+
required: boolean;
|
|
96
|
+
unique?: boolean;
|
|
97
|
+
ref?: string;
|
|
98
|
+
items?: {
|
|
99
|
+
type: string;
|
|
100
|
+
fields?: SchemaField[];
|
|
101
|
+
};
|
|
102
|
+
fields?: SchemaField[];
|
|
103
|
+
}
|
|
104
|
+
interface CollectionSchema {
|
|
105
|
+
name: string;
|
|
106
|
+
model: SchemaField[];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Mail payload contract:
|
|
110
|
+
* - Template mode: provide `templateId` or `templateName` (with optional `variables`).
|
|
111
|
+
* - Direct mode: provide `subject` and at least one of `text` or `html`.
|
|
112
|
+
*/
|
|
113
|
+
interface SendMailPayload {
|
|
114
|
+
to: string | string[];
|
|
115
|
+
variables?: Record<string, unknown>;
|
|
116
|
+
templateId?: string;
|
|
117
|
+
templateName?: string;
|
|
118
|
+
subject?: string;
|
|
119
|
+
text?: string;
|
|
120
|
+
html?: string;
|
|
121
|
+
}
|
|
122
|
+
interface SendMailResponse {
|
|
123
|
+
id: string | null;
|
|
124
|
+
provider: 'byok' | 'default';
|
|
125
|
+
monthlyUsage: number;
|
|
126
|
+
monthlyLimit: number;
|
|
127
|
+
}
|
|
128
|
+
interface UploadResponse {
|
|
129
|
+
url: string;
|
|
130
|
+
path: string;
|
|
131
|
+
provider: 'internal' | 'external';
|
|
132
|
+
message?: string;
|
|
133
|
+
}
|
|
134
|
+
interface ApiResponse<T> {
|
|
135
|
+
data: T;
|
|
136
|
+
success: boolean;
|
|
137
|
+
message?: string;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Module for authentication and user management in urBackend
|
|
142
|
+
*
|
|
143
|
+
* @class AuthModule
|
|
144
|
+
* @description Provides complete authentication functionality including signup, login,
|
|
145
|
+
* profile management, password operations, email verification, social authentication,
|
|
146
|
+
* and session management. Manages session tokens automatically.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* // Initialize the auth module
|
|
150
|
+
* const client = new UrBackendClient({ apiKey: 'pk_live_xxx', secretKey: 'sk_live_xxx' });
|
|
151
|
+
* const auth = new AuthModule(client);
|
|
152
|
+
*
|
|
153
|
+
* // Sign up a new user
|
|
154
|
+
* const user = await auth.signUp({
|
|
155
|
+
* email: 'user@example.com',
|
|
156
|
+
* password: 'securePassword123',
|
|
157
|
+
* name: 'John Doe'
|
|
158
|
+
* });
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* // Log in and manage session
|
|
162
|
+
* const session = await auth.login({
|
|
163
|
+
* email: 'user@example.com',
|
|
164
|
+
* password: 'securePassword123'
|
|
165
|
+
* });
|
|
166
|
+
* console.log('Access token:', session.accessToken);
|
|
167
|
+
*
|
|
168
|
+
* // Get current user profile
|
|
169
|
+
* const profile = await auth.me();
|
|
170
|
+
* console.log('Welcome:', profile.name);
|
|
171
|
+
*/
|
|
172
|
+
declare class AuthModule {
|
|
173
|
+
private client;
|
|
174
|
+
private sessionToken?;
|
|
175
|
+
/**
|
|
176
|
+
* Creates an instance of AuthModule
|
|
177
|
+
*
|
|
178
|
+
* @param {UrBackendClient} client - The urBackend client instance
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* const client = new UrBackendClient({ apiKey: 'pk_live_xxx' });
|
|
182
|
+
* const auth = new AuthModule(client);
|
|
183
|
+
*/
|
|
184
|
+
constructor(client: UrBackendClient);
|
|
185
|
+
/**
|
|
186
|
+
* Creates a new user account
|
|
187
|
+
*
|
|
188
|
+
* @param {SignUpPayload} payload - User registration data
|
|
189
|
+
* @param {string} payload.email - User's email address
|
|
190
|
+
* @param {string} payload.password - User's password
|
|
191
|
+
* @param {string} payload.name - User's full name
|
|
192
|
+
* @returns {Promise<AuthUser>} Promise resolving to the created user object
|
|
193
|
+
*
|
|
194
|
+
* @throws {AuthError} If email already exists
|
|
195
|
+
* @throws {AuthError} If password does not meet requirements
|
|
196
|
+
* @throws {AuthError} If validation fails
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* // Sign up a new user
|
|
200
|
+
* const user = await auth.signUp({
|
|
201
|
+
* email: 'john@example.com',
|
|
202
|
+
* password: 'StrongP@ss123',
|
|
203
|
+
* name: 'John Doe'
|
|
204
|
+
* });
|
|
205
|
+
* console.log('User created:', user._id);
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* // Sign up with error handling
|
|
209
|
+
* try {
|
|
210
|
+
* const user = await auth.signUp({
|
|
211
|
+
* email: 'existing@email.com',
|
|
212
|
+
* password: 'weak',
|
|
213
|
+
* name: 'Test'
|
|
214
|
+
* });
|
|
215
|
+
* } catch (error) {
|
|
216
|
+
* if (error.message.includes('email')) {
|
|
217
|
+
* console.log('Email already registered');
|
|
218
|
+
* } else if (error.message.includes('password')) {
|
|
219
|
+
* console.log('Password too weak');
|
|
220
|
+
* }
|
|
221
|
+
* }
|
|
222
|
+
*/
|
|
223
|
+
signUp(payload: SignUpPayload): Promise<AuthUser>;
|
|
224
|
+
/**
|
|
225
|
+
* Authenticates an existing user and stores the session token
|
|
226
|
+
*
|
|
227
|
+
* @param {LoginPayload} payload - User login credentials
|
|
228
|
+
* @param {string} payload.email - User's email address
|
|
229
|
+
* @param {string} payload.password - User's password
|
|
230
|
+
* @returns {Promise<AuthResponse>} Promise resolving to authentication response with tokens
|
|
231
|
+
*
|
|
232
|
+
* @throws {AuthError} If credentials are invalid
|
|
233
|
+
* @throws {AuthError} If account is locked or not verified
|
|
234
|
+
*
|
|
235
|
+
* @example
|
|
236
|
+
* // Log in a user
|
|
237
|
+
* const response = await auth.login({
|
|
238
|
+
* email: 'john@example.com',
|
|
239
|
+
* password: 'StrongP@ss123'
|
|
240
|
+
* });
|
|
241
|
+
* console.log('Access token:', response.accessToken);
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* // Login with error handling
|
|
245
|
+
* try {
|
|
246
|
+
* const { accessToken, user } = await auth.login({
|
|
247
|
+
* email: 'user@example.com',
|
|
248
|
+
* password: 'wrongpassword'
|
|
249
|
+
* });
|
|
250
|
+
* } catch (error) {
|
|
251
|
+
* if (error.status === 401) {
|
|
252
|
+
* console.log('Invalid email or password');
|
|
253
|
+
* }
|
|
254
|
+
* }
|
|
255
|
+
*/
|
|
256
|
+
login(payload: LoginPayload): Promise<AuthResponse>;
|
|
257
|
+
/**
|
|
258
|
+
* Retrieves the current authenticated user's profile
|
|
259
|
+
*
|
|
260
|
+
* @param {string} [token] - Optional authentication token (overrides stored token)
|
|
261
|
+
* @returns {Promise<AuthUser>} Promise resolving to the authenticated user's profile
|
|
262
|
+
*
|
|
263
|
+
* @throws {AuthError} If no authentication token is provided
|
|
264
|
+
* @throws {AuthError} If token is invalid or expired
|
|
265
|
+
*
|
|
266
|
+
* @example
|
|
267
|
+
* // Get current user profile (uses stored token from login)
|
|
268
|
+
* const user = await auth.me();
|
|
269
|
+
* console.log(`Hello ${user.name}, your email is ${user.email}`);
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* // Get profile with custom token
|
|
273
|
+
* const user = await auth.me(customToken);
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* // Get profile with error handling
|
|
277
|
+
* try {
|
|
278
|
+
* const user = await auth.me();
|
|
279
|
+
* console.log('Authenticated as:', user.email);
|
|
280
|
+
* } catch (error) {
|
|
281
|
+
* if (error.status === 401) {
|
|
282
|
+
* console.log('Please log in again');
|
|
283
|
+
* }
|
|
284
|
+
* }
|
|
285
|
+
*/
|
|
286
|
+
me(token?: string): Promise<AuthUser>;
|
|
287
|
+
/**
|
|
288
|
+
* Updates the current authenticated user's profile
|
|
289
|
+
*
|
|
290
|
+
* @param {UpdateProfilePayload} payload - Profile data to update
|
|
291
|
+
* @param {string} [payload.name] - Updated name
|
|
292
|
+
* @param {string} [payload.email] - Updated email (may require re-verification)
|
|
293
|
+
* @param {string} [token] - Optional authentication token (overrides stored token)
|
|
294
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
295
|
+
*
|
|
296
|
+
* @throws {AuthError} If no authentication token is provided
|
|
297
|
+
* @throws {AuthError} If token is invalid or expired
|
|
298
|
+
* @throws {AuthError} If email is already taken
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* // Update user's name
|
|
302
|
+
* const result = await auth.updateProfile({ name: 'Jane Smith' });
|
|
303
|
+
* console.log(result.message);
|
|
304
|
+
*
|
|
305
|
+
* @example
|
|
306
|
+
* // Update multiple fields
|
|
307
|
+
* const result = await auth.updateProfile({
|
|
308
|
+
* name: 'Jane Doe',
|
|
309
|
+
* email: 'jane@newemail.com'
|
|
310
|
+
* });
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* // Update with error handling
|
|
314
|
+
* try {
|
|
315
|
+
* await auth.updateProfile({ email: 'taken@email.com' });
|
|
316
|
+
* } catch (error) {
|
|
317
|
+
* console.log('Email already in use');
|
|
318
|
+
* }
|
|
319
|
+
*/
|
|
320
|
+
updateProfile(payload: UpdateProfilePayload, token?: string): Promise<{
|
|
321
|
+
message: string;
|
|
322
|
+
}>;
|
|
323
|
+
/**
|
|
324
|
+
* Changes the current authenticated user's password
|
|
325
|
+
*
|
|
326
|
+
* @param {ChangePasswordPayload} payload - Password change data
|
|
327
|
+
* @param {string} payload.currentPassword - User's current password
|
|
328
|
+
* @param {string} payload.newPassword - Desired new password
|
|
329
|
+
* @param {string} [token] - Optional authentication token (overrides stored token)
|
|
330
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
331
|
+
*
|
|
332
|
+
* @throws {AuthError} If no authentication token is provided
|
|
333
|
+
* @throws {AuthError} If current password is incorrect
|
|
334
|
+
* @throws {AuthError} If new password does not meet requirements
|
|
335
|
+
*
|
|
336
|
+
* @example
|
|
337
|
+
* // Change password
|
|
338
|
+
* const result = await auth.changePassword({
|
|
339
|
+
* currentPassword: 'oldPassword123',
|
|
340
|
+
* newPassword: 'newStrongP@ss456'
|
|
341
|
+
* });
|
|
342
|
+
* console.log(result.message);
|
|
343
|
+
*
|
|
344
|
+
* @example
|
|
345
|
+
* // Change password with error handling
|
|
346
|
+
* try {
|
|
347
|
+
* await auth.changePassword({
|
|
348
|
+
* currentPassword: 'wrong',
|
|
349
|
+
* newPassword: 'newPassword123'
|
|
350
|
+
* });
|
|
351
|
+
* } catch (error) {
|
|
352
|
+
* if (error.message.includes('current password')) {
|
|
353
|
+
* console.log('Current password is incorrect');
|
|
354
|
+
* }
|
|
355
|
+
* }
|
|
356
|
+
*/
|
|
357
|
+
changePassword(payload: ChangePasswordPayload, token?: string): Promise<{
|
|
358
|
+
message: string;
|
|
359
|
+
}>;
|
|
360
|
+
/**
|
|
361
|
+
* Verifies user's email address using OTP
|
|
362
|
+
*
|
|
363
|
+
* @param {VerifyEmailPayload} payload - Email verification data
|
|
364
|
+
* @param {string} payload.email - User's email address
|
|
365
|
+
* @param {string} payload.otp - One-time password sent to email
|
|
366
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
367
|
+
*
|
|
368
|
+
* @throws {AuthError} If OTP is invalid or expired
|
|
369
|
+
* @throws {AuthError} If email is not found
|
|
370
|
+
*
|
|
371
|
+
* @example
|
|
372
|
+
* // Verify email with OTP
|
|
373
|
+
* const result = await auth.verifyEmail({
|
|
374
|
+
* email: 'user@example.com',
|
|
375
|
+
* otp: '123456'
|
|
376
|
+
* });
|
|
377
|
+
* console.log('Email verified:', result.message);
|
|
378
|
+
*
|
|
379
|
+
* @example
|
|
380
|
+
* // Verify with error handling
|
|
381
|
+
* try {
|
|
382
|
+
* await auth.verifyEmail({ email: 'user@example.com', otp: '000000' });
|
|
383
|
+
* } catch (error) {
|
|
384
|
+
* console.log('Invalid OTP. Please try again.');
|
|
385
|
+
* }
|
|
386
|
+
*/
|
|
387
|
+
verifyEmail(payload: VerifyEmailPayload): Promise<{
|
|
388
|
+
message: string;
|
|
389
|
+
}>;
|
|
390
|
+
/**
|
|
391
|
+
* Resends verification OTP to user's email
|
|
392
|
+
*
|
|
393
|
+
* @param {ResendOtpPayload} payload - Resend OTP request data
|
|
394
|
+
* @param {string} payload.email - User's email address
|
|
395
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
396
|
+
*
|
|
397
|
+
* @throws {AuthError} If email is not found
|
|
398
|
+
* @throws {AuthError} If too many attempts
|
|
399
|
+
*
|
|
400
|
+
* @example
|
|
401
|
+
* // Resend verification OTP
|
|
402
|
+
* const result = await auth.resendVerificationOtp({
|
|
403
|
+
* email: 'user@example.com'
|
|
404
|
+
* });
|
|
405
|
+
* console.log('OTP resent:', result.message);
|
|
406
|
+
*/
|
|
407
|
+
resendVerificationOtp(payload: ResendOtpPayload): Promise<{
|
|
408
|
+
message: string;
|
|
409
|
+
}>;
|
|
410
|
+
/**
|
|
411
|
+
* Requests a password reset OTP to be sent to user's email
|
|
412
|
+
*
|
|
413
|
+
* @param {RequestPasswordResetPayload} payload - Password reset request data
|
|
414
|
+
* @param {string} payload.email - User's email address
|
|
415
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
416
|
+
*
|
|
417
|
+
* @throws {AuthError} If email is not found
|
|
418
|
+
* @throws {AuthError} If too many attempts
|
|
419
|
+
*
|
|
420
|
+
* @example
|
|
421
|
+
* // Request password reset
|
|
422
|
+
* const result = await auth.requestPasswordReset({
|
|
423
|
+
* email: 'user@example.com'
|
|
424
|
+
* });
|
|
425
|
+
* console.log('Reset OTP sent:', result.message);
|
|
426
|
+
*/
|
|
427
|
+
requestPasswordReset(payload: RequestPasswordResetPayload): Promise<{
|
|
428
|
+
message: string;
|
|
429
|
+
}>;
|
|
430
|
+
/**
|
|
431
|
+
* Resets user's password using OTP
|
|
432
|
+
*
|
|
433
|
+
* @param {ResetPasswordPayload} payload - Password reset data
|
|
434
|
+
* @param {string} payload.email - User's email address
|
|
435
|
+
* @param {string} payload.otp - One-time password sent via email
|
|
436
|
+
* @param {string} payload.newPassword - Desired new password
|
|
437
|
+
* @returns {Promise<{ message: string }>} Promise resolving to success message
|
|
438
|
+
*
|
|
439
|
+
* @throws {AuthError} If OTP is invalid or expired
|
|
440
|
+
* @throws {AuthError} If email is not found
|
|
441
|
+
* @throws {AuthError} If new password does not meet requirements
|
|
442
|
+
*
|
|
443
|
+
* @example
|
|
444
|
+
* // Reset password with OTP
|
|
445
|
+
* const result = await auth.resetPassword({
|
|
446
|
+
* email: 'user@example.com',
|
|
447
|
+
* otp: '123456',
|
|
448
|
+
* newPassword: 'NewStrongP@ss789'
|
|
449
|
+
* });
|
|
450
|
+
* console.log('Password reset:', result.message);
|
|
451
|
+
*
|
|
452
|
+
* @example
|
|
453
|
+
* // Reset password with error handling
|
|
454
|
+
* try {
|
|
455
|
+
* await auth.resetPassword({
|
|
456
|
+
* email: 'user@example.com',
|
|
457
|
+
* otp: 'wrong',
|
|
458
|
+
* newPassword: 'newPass123'
|
|
459
|
+
* });
|
|
460
|
+
* } catch (error) {
|
|
461
|
+
* console.log('Invalid OTP. Please request a new one.');
|
|
462
|
+
* }
|
|
463
|
+
*/
|
|
464
|
+
resetPassword(payload: ResetPasswordPayload): Promise<{
|
|
465
|
+
message: string;
|
|
466
|
+
}>;
|
|
467
|
+
/**
|
|
468
|
+
* Retrieves a public-safe user profile by username
|
|
469
|
+
*
|
|
470
|
+
* @param {string} username - Username of the user to fetch
|
|
471
|
+
* @returns {Promise<AuthUser>} Promise resolving to public user profile (sensitive fields omitted)
|
|
472
|
+
*
|
|
473
|
+
* @throws {AuthError} If user with given username does not exist
|
|
474
|
+
*
|
|
475
|
+
* @example
|
|
476
|
+
* // Get public profile
|
|
477
|
+
* const profile = await auth.publicProfile('john_doe');
|
|
478
|
+
* console.log(`${profile.name} joined on ${profile.createdAt}`);
|
|
479
|
+
*
|
|
480
|
+
* @example
|
|
481
|
+
* // Display user profile on a public page
|
|
482
|
+
* try {
|
|
483
|
+
* const user = await auth.publicProfile('username');
|
|
484
|
+
* // Show user info (no email or private data)
|
|
485
|
+
* } catch (error) {
|
|
486
|
+
* console.log('User not found');
|
|
487
|
+
* }
|
|
488
|
+
*/
|
|
489
|
+
publicProfile(username: string): Promise<AuthUser>;
|
|
490
|
+
/**
|
|
491
|
+
* Refreshes the access token using refresh token or cookie
|
|
492
|
+
*
|
|
493
|
+
* @param {string} [refreshToken] - Optional refresh token for header mode. If omitted, uses cookie mode.
|
|
494
|
+
* @returns {Promise<AuthResponse>} Promise resolving to new authentication response with fresh tokens
|
|
495
|
+
*
|
|
496
|
+
* @throws {AuthError} If refresh token is invalid or expired
|
|
497
|
+
*
|
|
498
|
+
* @example
|
|
499
|
+
* // Refresh token using cookie (if configured)
|
|
500
|
+
* const newTokens = await auth.refreshToken();
|
|
501
|
+
* console.log('New access token:', newTokens.accessToken);
|
|
502
|
+
*
|
|
503
|
+
* @example
|
|
504
|
+
* // Refresh token using explicit refresh token
|
|
505
|
+
* const newTokens = await auth.refreshToken(storedRefreshToken);
|
|
506
|
+
*
|
|
507
|
+
* @example
|
|
508
|
+
* // Auto-refresh before API calls
|
|
509
|
+
* try {
|
|
510
|
+
* await auth.me();
|
|
511
|
+
* } catch (error) {
|
|
512
|
+
* if (error.status === 401) {
|
|
513
|
+
* await auth.refreshToken();
|
|
514
|
+
* // Retry the original request
|
|
515
|
+
* }
|
|
516
|
+
* }
|
|
517
|
+
*/
|
|
518
|
+
refreshToken(refreshToken?: string): Promise<AuthResponse>;
|
|
519
|
+
/**
|
|
520
|
+
* Returns the start URL for social authentication
|
|
521
|
+
*
|
|
522
|
+
* @param {('github' | 'google')} provider - The social authentication provider
|
|
523
|
+
* @returns {string} URL to redirect the user's browser to begin the OAuth flow
|
|
524
|
+
*
|
|
525
|
+
* @example
|
|
526
|
+
* // Redirect user to social login page
|
|
527
|
+
* const githubUrl = auth.socialStart('github');
|
|
528
|
+
* window.location.href = githubUrl;
|
|
529
|
+
*
|
|
530
|
+
* @example
|
|
531
|
+
* // For Node.js backend
|
|
532
|
+
* const googleUrl = auth.socialStart('google');
|
|
533
|
+
* res.redirect(googleUrl);
|
|
534
|
+
*/
|
|
535
|
+
socialStart(provider: 'github' | 'google'): string;
|
|
536
|
+
/**
|
|
537
|
+
* Exchanges social authentication rtCode for a refresh token
|
|
538
|
+
*
|
|
539
|
+
* @param {SocialExchangePayload} payload - Social exchange data
|
|
540
|
+
* @param {string} payload.rtCode - Return code from social provider
|
|
541
|
+
* @param {string} payload.provider - Social provider ('github' or 'google')
|
|
542
|
+
* @returns {Promise<SocialExchangeResponse>} Promise resolving to authentication response
|
|
543
|
+
*
|
|
544
|
+
* @throws {AuthError} If rtCode is invalid or expired
|
|
545
|
+
* @throws {AuthError} If social provider fails
|
|
546
|
+
*
|
|
547
|
+
* @example
|
|
548
|
+
* // After user returns from social login
|
|
549
|
+
* const rtCode = new URLSearchParams(window.location.search).get('rtCode');
|
|
550
|
+
* if (rtCode) {
|
|
551
|
+
* const response = await auth.socialExchange({
|
|
552
|
+
* rtCode: rtCode,
|
|
553
|
+
* provider: 'github'
|
|
554
|
+
* });
|
|
555
|
+
* console.log('Social login successful:', response.accessToken);
|
|
556
|
+
* }
|
|
557
|
+
*/
|
|
558
|
+
socialExchange(payload: SocialExchangePayload): Promise<SocialExchangeResponse>;
|
|
559
|
+
/**
|
|
560
|
+
* Revokes the current session and clears local state
|
|
561
|
+
*
|
|
562
|
+
* @param {string} [token] - Optional authentication token (overrides stored token)
|
|
563
|
+
* @returns {Promise<{ success: boolean; message: string }>} Promise resolving to logout status
|
|
564
|
+
*
|
|
565
|
+
* @example
|
|
566
|
+
* // Log out current user
|
|
567
|
+
* const result = await auth.logout();
|
|
568
|
+
* console.log(result.message);
|
|
569
|
+
* // User is now logged out, session token is cleared
|
|
570
|
+
*
|
|
571
|
+
* @example
|
|
572
|
+
* // Log out with custom token
|
|
573
|
+
* const result = await auth.logout(customToken);
|
|
574
|
+
*
|
|
575
|
+
* @example
|
|
576
|
+
* // Logout after API calls
|
|
577
|
+
* try {
|
|
578
|
+
* await auth.logout();
|
|
579
|
+
* // Redirect to login page
|
|
580
|
+
* window.location.href = '/login';
|
|
581
|
+
* } catch (error) {
|
|
582
|
+
* console.log('Logout failed, but local session cleared');
|
|
583
|
+
* }
|
|
584
|
+
*/
|
|
585
|
+
logout(token?: string): Promise<{
|
|
586
|
+
success: boolean;
|
|
587
|
+
message: string;
|
|
588
|
+
}>;
|
|
589
|
+
/**
|
|
590
|
+
* Manually sets the session token (e.g., after social authentication exchange)
|
|
591
|
+
*
|
|
592
|
+
* @param {string} token - The session/access token to store
|
|
593
|
+
*
|
|
594
|
+
* @example
|
|
595
|
+
* // After successful social exchange
|
|
596
|
+
* const response = await auth.socialExchange({ rtCode, provider: 'github' });
|
|
597
|
+
* auth.setToken(response.accessToken);
|
|
598
|
+
*
|
|
599
|
+
* @example
|
|
600
|
+
* // Restore session from localStorage
|
|
601
|
+
* const savedToken = localStorage.getItem('authToken');
|
|
602
|
+
* if (savedToken) {
|
|
603
|
+
* auth.setToken(savedToken);
|
|
604
|
+
* const user = await auth.me();
|
|
605
|
+
* }
|
|
606
|
+
*/
|
|
607
|
+
setToken(token: string): void;
|
|
608
|
+
/**
|
|
609
|
+
* Gets the current stored session token
|
|
610
|
+
*
|
|
611
|
+
* @returns {string | undefined} The current session token, if any
|
|
612
|
+
*
|
|
613
|
+
* @example
|
|
614
|
+
* // Get token for custom API calls
|
|
615
|
+
* const token = auth.getToken();
|
|
616
|
+
* if (token) {
|
|
617
|
+
* // Use token in custom API request
|
|
618
|
+
* fetch('/api/custom', { headers: { Authorization: `Bearer ${token}` } });
|
|
619
|
+
* }
|
|
620
|
+
*
|
|
621
|
+
* @example
|
|
622
|
+
* // Save token to localStorage for persistence
|
|
623
|
+
* const token = auth.getToken();
|
|
624
|
+
* if (token) {
|
|
625
|
+
* localStorage.setItem('authToken', token);
|
|
626
|
+
* }
|
|
627
|
+
*/
|
|
628
|
+
getToken(): string | undefined;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Module for database operations in urBackend
|
|
633
|
+
*
|
|
634
|
+
* @class DatabaseModule
|
|
635
|
+
* @description Provides CRUD (Create, Read, Update, Delete) operations for collections.
|
|
636
|
+
* Supports filtering, pagination, sorting, population, and expansion of related data.
|
|
637
|
+
*
|
|
638
|
+
* @example
|
|
639
|
+
* // Initialize the database module
|
|
640
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
641
|
+
* const db = new DatabaseModule(client);
|
|
642
|
+
*
|
|
643
|
+
* // Get all users
|
|
644
|
+
* const users = await db.getAll('users');
|
|
645
|
+
* console.log(users);
|
|
646
|
+
*
|
|
647
|
+
* @example
|
|
648
|
+
* // Insert a new document
|
|
649
|
+
* const newUser = await db.insert('users', {
|
|
650
|
+
* name: 'John Doe',
|
|
651
|
+
* email: 'john@example.com'
|
|
652
|
+
* });
|
|
653
|
+
* console.log('Created:', newUser._id);
|
|
654
|
+
*/
|
|
655
|
+
declare class DatabaseModule {
|
|
656
|
+
private client;
|
|
657
|
+
/**
|
|
658
|
+
* Creates an instance of DatabaseModule
|
|
659
|
+
*
|
|
660
|
+
* @param {UrBackendClient} client - The authenticated urBackend client instance
|
|
661
|
+
*
|
|
662
|
+
* @example
|
|
663
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
664
|
+
* const db = new DatabaseModule(client);
|
|
665
|
+
*/
|
|
666
|
+
constructor(client: UrBackendClient);
|
|
667
|
+
/**
|
|
668
|
+
* Fetches all documents from a collection with optional query parameters
|
|
669
|
+
*
|
|
670
|
+
* @template T - The document type (extends DocumentData)
|
|
671
|
+
* @param {string} collection - Name of the collection to query
|
|
672
|
+
* @param {QueryParams} [params={}] - Optional query parameters for filtering, sorting, pagination
|
|
673
|
+
* @param {string} [token] - Optional authentication token (required for private-mode reads with publishable keys)
|
|
674
|
+
* @returns {Promise<T[]>} Promise resolving to an array of documents (empty array if none found)
|
|
675
|
+
*
|
|
676
|
+
* @throws {Error} If collection name is invalid
|
|
677
|
+
* @throws {Error} If authentication fails
|
|
678
|
+
* @throws {Error} If query parameters are malformed
|
|
679
|
+
*
|
|
680
|
+
* @example
|
|
681
|
+
* // Get all users
|
|
682
|
+
* const users = await db.getAll('users');
|
|
683
|
+
*
|
|
684
|
+
* @example
|
|
685
|
+
* // Get users with filters and pagination
|
|
686
|
+
* const activeUsers = await db.getAll('users', {
|
|
687
|
+
* filter: { status: 'active' },
|
|
688
|
+
* limit: 10,
|
|
689
|
+
* skip: 0,
|
|
690
|
+
* sort: '-createdAt'
|
|
691
|
+
* });
|
|
692
|
+
*
|
|
693
|
+
* @example
|
|
694
|
+
* // Get users with populated relations
|
|
695
|
+
* const usersWithPosts = await db.getAll('users', {
|
|
696
|
+
* populate: ['posts'],
|
|
697
|
+
* expand: ['profile']
|
|
698
|
+
* });
|
|
699
|
+
*/
|
|
700
|
+
getAll<T extends DocumentData>(collection: string, params?: QueryParams, token?: string): Promise<T[]>;
|
|
701
|
+
/**
|
|
702
|
+
* Counts documents in a collection with optional filters
|
|
703
|
+
*
|
|
704
|
+
* @param {string} collection - Name of the collection to count
|
|
705
|
+
* @param {Omit<QueryParams, 'count'>} [params={}] - Optional filter parameters
|
|
706
|
+
* @param {string} [token] - Optional authentication token (required for private-mode reads with publishable keys)
|
|
707
|
+
* @returns {Promise<number>} Promise resolving to the total count of matching documents
|
|
708
|
+
*
|
|
709
|
+
* @throws {Error} If collection name is invalid
|
|
710
|
+
* @throws {Error} If authentication fails
|
|
711
|
+
*
|
|
712
|
+
* @example
|
|
713
|
+
* // Count all users
|
|
714
|
+
* const totalUsers = await db.count('users');
|
|
715
|
+
* console.log(`Total users: ${totalUsers}`);
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* // Count users with filter
|
|
719
|
+
* const activeUsers = await db.count('users', {
|
|
720
|
+
* filter: { status: 'active' }
|
|
721
|
+
* });
|
|
722
|
+
*
|
|
723
|
+
* @example
|
|
724
|
+
* // Count for pagination
|
|
725
|
+
* const total = await db.count('products', {
|
|
726
|
+
* filter: { category: 'electronics' }
|
|
727
|
+
* });
|
|
728
|
+
* const totalPages = Math.ceil(total / 10);
|
|
729
|
+
*/
|
|
730
|
+
count(collection: string, params?: Omit<QueryParams, 'count'>, token?: string): Promise<number>;
|
|
731
|
+
/**
|
|
732
|
+
* Fetches a single document by its ID
|
|
733
|
+
*
|
|
734
|
+
* @template T - The document type (extends DocumentData)
|
|
735
|
+
* @param {string} collection - Name of the collection
|
|
736
|
+
* @param {string} id - Unique identifier of the document
|
|
737
|
+
* @param {Object} [options={}] - Optional parameters
|
|
738
|
+
* @param {string|string[]} [options.populate] - Fields to populate with related data
|
|
739
|
+
* @param {string|string[]} [options.expand] - Fields to expand with nested data
|
|
740
|
+
* @param {string} [token] - Optional authentication token (required for private-mode reads with publishable keys)
|
|
741
|
+
* @returns {Promise<T>} Promise resolving to the document
|
|
742
|
+
*
|
|
743
|
+
* @throws {NotFoundError} If document with given ID does not exist
|
|
744
|
+
* @throws {Error} If collection name or ID is invalid
|
|
745
|
+
* @throws {Error} If authentication fails
|
|
746
|
+
*
|
|
747
|
+
* @example
|
|
748
|
+
* // Get user by ID
|
|
749
|
+
* const user = await db.getOne('users', 'user_123');
|
|
750
|
+
* console.log(user.name);
|
|
751
|
+
*
|
|
752
|
+
* @example
|
|
753
|
+
* // Get user with populated posts
|
|
754
|
+
* const userWithPosts = await db.getOne('users', 'user_123', {
|
|
755
|
+
* populate: ['posts', 'comments']
|
|
756
|
+
* });
|
|
757
|
+
*
|
|
758
|
+
* @example
|
|
759
|
+
* // Get with error handling
|
|
760
|
+
* try {
|
|
761
|
+
* const user = await db.getOne('users', 'non_existent_id');
|
|
762
|
+
* } catch (error) {
|
|
763
|
+
* if (error instanceof NotFoundError) {
|
|
764
|
+
* console.log('User not found');
|
|
765
|
+
* }
|
|
766
|
+
* }
|
|
767
|
+
*/
|
|
768
|
+
getOne<T extends DocumentData>(collection: string, id: string, options?: {
|
|
769
|
+
populate?: string | string[];
|
|
770
|
+
expand?: string | string[];
|
|
771
|
+
}, token?: string): Promise<T>;
|
|
772
|
+
/**
|
|
773
|
+
* Inserts a new document into a collection
|
|
774
|
+
*
|
|
775
|
+
* @template T - The document type (extends DocumentData)
|
|
776
|
+
* @param {string} collection - Name of the collection
|
|
777
|
+
* @param {InsertPayload} data - Document data to insert
|
|
778
|
+
* @param {string} [token] - Optional authentication token (overrides client default)
|
|
779
|
+
* @returns {Promise<T>} Promise resolving to the created document with generated ID
|
|
780
|
+
*
|
|
781
|
+
* @throws {Error} If collection name is invalid
|
|
782
|
+
* @throws {Error} If data validation fails
|
|
783
|
+
* @throws {Error} If authentication fails
|
|
784
|
+
* @throws {Error} If unique constraint violation occurs
|
|
785
|
+
*
|
|
786
|
+
* @example
|
|
787
|
+
* // Insert a new user
|
|
788
|
+
* const newUser = await db.insert('users', {
|
|
789
|
+
* name: 'John Doe',
|
|
790
|
+
* email: 'john@example.com',
|
|
791
|
+
* age: 25
|
|
792
|
+
* });
|
|
793
|
+
* console.log('User created:', newUser._id);
|
|
794
|
+
*
|
|
795
|
+
* @example
|
|
796
|
+
* // Insert with custom token
|
|
797
|
+
* const result = await db.insert('posts', {
|
|
798
|
+
* title: 'My Post',
|
|
799
|
+
* content: 'Hello World'
|
|
800
|
+
* }, customAuthToken);
|
|
801
|
+
*
|
|
802
|
+
* @example
|
|
803
|
+
* // Insert with error handling
|
|
804
|
+
* try {
|
|
805
|
+
* const user = await db.insert('users', { email: 'existing@email.com' });
|
|
806
|
+
* } catch (error) {
|
|
807
|
+
* if (error.message.includes('duplicate')) {
|
|
808
|
+
* console.log('Email already exists');
|
|
809
|
+
* }
|
|
810
|
+
* }
|
|
811
|
+
*/
|
|
812
|
+
insert<T extends DocumentData>(collection: string, data: InsertPayload, token?: string): Promise<T>;
|
|
813
|
+
/**
|
|
814
|
+
* Updates an existing document by its ID (full replacement)
|
|
815
|
+
*
|
|
816
|
+
* @template T - The document type (extends DocumentData)
|
|
817
|
+
* @param {string} collection - Name of the collection
|
|
818
|
+
* @param {string} id - Unique identifier of the document
|
|
819
|
+
* @param {UpdatePayload} data - Complete document data for replacement
|
|
820
|
+
* @param {string} [token] - Optional authentication token (overrides client default)
|
|
821
|
+
* @returns {Promise<T>} Promise resolving to the updated document
|
|
822
|
+
*
|
|
823
|
+
* @throws {NotFoundError} If document with given ID does not exist
|
|
824
|
+
* @throws {Error} If collection name or ID is invalid
|
|
825
|
+
* @throws {Error} If data validation fails
|
|
826
|
+
* @throws {Error} If authentication fails
|
|
827
|
+
*
|
|
828
|
+
* @example
|
|
829
|
+
* // Full update of a user
|
|
830
|
+
* const updatedUser = await db.update('users', 'user_123', {
|
|
831
|
+
* name: 'Jane Doe',
|
|
832
|
+
* email: 'jane@example.com',
|
|
833
|
+
* age: 26
|
|
834
|
+
* });
|
|
835
|
+
*
|
|
836
|
+
* @example
|
|
837
|
+
* // Update with error handling
|
|
838
|
+
* try {
|
|
839
|
+
* const result = await db.update('users', 'user_123', updatedData);
|
|
840
|
+
* console.log('Update successful:', result);
|
|
841
|
+
* } catch (error) {
|
|
842
|
+
* if (error instanceof NotFoundError) {
|
|
843
|
+
* console.log('User not found');
|
|
844
|
+
* }
|
|
845
|
+
* }
|
|
846
|
+
*/
|
|
847
|
+
update<T extends DocumentData>(collection: string, id: string, data: UpdatePayload, token?: string): Promise<T>;
|
|
848
|
+
/**
|
|
849
|
+
* Partially updates an existing document by its ID (only provided fields)
|
|
850
|
+
*
|
|
851
|
+
* @template T - The document type (extends DocumentData)
|
|
852
|
+
* @param {string} collection - Name of the collection
|
|
853
|
+
* @param {string} id - Unique identifier of the document
|
|
854
|
+
* @param {PatchPayload} data - Partial data to update
|
|
855
|
+
* @param {string} [token] - Optional authentication token (overrides client default)
|
|
856
|
+
* @returns {Promise<T>} Promise resolving to the updated document
|
|
857
|
+
*
|
|
858
|
+
* @throws {NotFoundError} If document with given ID does not exist
|
|
859
|
+
* @throws {Error} If collection name or ID is invalid
|
|
860
|
+
* @throws {Error} If data validation fails
|
|
861
|
+
* @throws {Error} If authentication fails
|
|
862
|
+
*
|
|
863
|
+
* @example
|
|
864
|
+
* // Partial update - only update age
|
|
865
|
+
* const updatedUser = await db.patch('users', 'user_123', {
|
|
866
|
+
* age: 26
|
|
867
|
+
* });
|
|
868
|
+
*
|
|
869
|
+
* @example
|
|
870
|
+
* // Add a new field to document
|
|
871
|
+
* const result = await db.patch('users', 'user_123', {
|
|
872
|
+
* lastLogin: new Date().toISOString()
|
|
873
|
+
* });
|
|
874
|
+
*
|
|
875
|
+
* @example
|
|
876
|
+
* // Partial update with error handling
|
|
877
|
+
* try {
|
|
878
|
+
* const result = await db.patch('products', 'prod_123', {
|
|
879
|
+
* price: 29.99
|
|
880
|
+
* });
|
|
881
|
+
* console.log('Price updated:', result);
|
|
882
|
+
* } catch (error) {
|
|
883
|
+
* console.error('Update failed:', error.message);
|
|
884
|
+
* }
|
|
885
|
+
*/
|
|
886
|
+
patch<T extends DocumentData>(collection: string, id: string, data: PatchPayload, token?: string): Promise<T>;
|
|
887
|
+
/**
|
|
888
|
+
* Deletes a document by its ID
|
|
889
|
+
*
|
|
890
|
+
* @param {string} collection - Name of the collection
|
|
891
|
+
* @param {string} id - Unique identifier of the document to delete
|
|
892
|
+
* @param {string} [token] - Optional authentication token (overrides client default)
|
|
893
|
+
* @returns {Promise<{ deleted: boolean }>} Promise resolving to deletion status
|
|
894
|
+
*
|
|
895
|
+
* @throws {Error} If collection name or ID is invalid
|
|
896
|
+
* @throws {Error} If authentication fails
|
|
897
|
+
* @throws {Error} If user lacks permission to delete
|
|
898
|
+
*
|
|
899
|
+
* @example
|
|
900
|
+
* // Delete a user
|
|
901
|
+
* const result = await db.delete('users', 'user_123');
|
|
902
|
+
* if (result.deleted) {
|
|
903
|
+
* console.log('User deleted successfully');
|
|
904
|
+
* }
|
|
905
|
+
*
|
|
906
|
+
* @example
|
|
907
|
+
* // Delete with error handling
|
|
908
|
+
* try {
|
|
909
|
+
* const { deleted } = await db.delete('posts', 'post_456');
|
|
910
|
+
* if (deleted) {
|
|
911
|
+
* console.log('Post removed');
|
|
912
|
+
* }
|
|
913
|
+
* } catch (error) {
|
|
914
|
+
* console.error('Deletion failed:', error.message);
|
|
915
|
+
* }
|
|
916
|
+
*
|
|
917
|
+
* @example
|
|
918
|
+
* // Delete after checking existence
|
|
919
|
+
* const exists = await db.getOne('users', 'user_123').catch(() => null);
|
|
920
|
+
* if (exists) {
|
|
921
|
+
* await db.delete('users', 'user_123');
|
|
922
|
+
* console.log('User deleted');
|
|
923
|
+
* }
|
|
924
|
+
*/
|
|
925
|
+
delete(collection: string, id: string, token?: string): Promise<{
|
|
926
|
+
deleted: boolean;
|
|
927
|
+
}>;
|
|
928
|
+
/**
|
|
929
|
+
* Internal helper to build query string from QueryParams
|
|
930
|
+
*
|
|
931
|
+
* @param {QueryParams} params - Query parameters to convert
|
|
932
|
+
* @returns {string} URL query string (starting with '?' if parameters exist, otherwise empty)
|
|
933
|
+
*
|
|
934
|
+
* @internal
|
|
935
|
+
* @private
|
|
936
|
+
*
|
|
937
|
+
* @example
|
|
938
|
+
* // Returns "?limit=10&sort=-createdAt"
|
|
939
|
+
* buildQueryString({ limit: 10, sort: '-createdAt' })
|
|
940
|
+
*
|
|
941
|
+
* @example
|
|
942
|
+
* // Returns "?status=active&age=25"
|
|
943
|
+
* buildQueryString({ filter: { status: 'active', age: 25 } })
|
|
944
|
+
*/
|
|
945
|
+
private buildQueryString;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Module for handling file storage operations in urBackend
|
|
950
|
+
*
|
|
951
|
+
* @class StorageModule
|
|
952
|
+
* @description Provides methods to upload and delete files in the urBackend storage system.
|
|
953
|
+
* Supports both browser (File/Blob) and Node.js (Buffer) environments.
|
|
954
|
+
*
|
|
955
|
+
* @example
|
|
956
|
+
* // Initialize the storage module
|
|
957
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
958
|
+
* const storage = new StorageModule(client);
|
|
959
|
+
*
|
|
960
|
+
* // Upload a file (Browser)
|
|
961
|
+
* const fileInput = document.getElementById('fileInput');
|
|
962
|
+
* const result = await storage.upload(fileInput.files[0], 'my-file.pdf');
|
|
963
|
+
* console.log(result.url);
|
|
964
|
+
*
|
|
965
|
+
* @example
|
|
966
|
+
* // Upload a file (Node.js)
|
|
967
|
+
* const fs = require('fs');
|
|
968
|
+
* const buffer = fs.readFileSync('./document.pdf');
|
|
969
|
+
* const result = await storage.upload(buffer, 'document.pdf');
|
|
970
|
+
*/
|
|
971
|
+
declare class StorageModule {
|
|
972
|
+
private client;
|
|
973
|
+
/**
|
|
974
|
+
* Creates an instance of StorageModule
|
|
975
|
+
*
|
|
976
|
+
* @param {UrBackendClient} client - The authenticated urBackend client instance
|
|
977
|
+
*
|
|
978
|
+
* @example
|
|
979
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
980
|
+
* const storage = new StorageModule(client);
|
|
981
|
+
*/
|
|
982
|
+
constructor(client: UrBackendClient);
|
|
983
|
+
/**
|
|
984
|
+
* Uploads a file to the urBackend storage
|
|
985
|
+
*
|
|
986
|
+
* @param {unknown} file - The file to upload. Supports:
|
|
987
|
+
* - Browser: File, Blob
|
|
988
|
+
* - Node.js: Buffer
|
|
989
|
+
* @param {string} [filename] - Optional custom filename for the uploaded file
|
|
990
|
+
* @returns {Promise<UploadResponse>} Promise resolving to upload details including URL and file ID
|
|
991
|
+
*
|
|
992
|
+
* @throws {Error} If file is invalid or missing
|
|
993
|
+
* @throws {Error} If file size exceeds limits
|
|
994
|
+
* @throws {Error} If authentication fails
|
|
995
|
+
* @throws {Error} If storage quota is exceeded
|
|
996
|
+
*
|
|
997
|
+
* @example
|
|
998
|
+
* // Browser: Upload from file input
|
|
999
|
+
* const fileInput = document.querySelector('input[type="file"]');
|
|
1000
|
+
* const file = fileInput.files[0];
|
|
1001
|
+
* const result = await storage.upload(file, 'custom-name.pdf');
|
|
1002
|
+
* console.log('File URL:', result.url);
|
|
1003
|
+
*
|
|
1004
|
+
* @example
|
|
1005
|
+
* // Node.js: Upload Buffer
|
|
1006
|
+
* const fs = require('fs');
|
|
1007
|
+
* const buffer = fs.readFileSync('./image.png');
|
|
1008
|
+
* const result = await storage.upload(buffer, 'image.png');
|
|
1009
|
+
* console.log('Uploaded:', result.fileId);
|
|
1010
|
+
*
|
|
1011
|
+
* @example
|
|
1012
|
+
* // Upload without custom filename (uses original name)
|
|
1013
|
+
* const result = await storage.upload(file);
|
|
1014
|
+
*
|
|
1015
|
+
* @example
|
|
1016
|
+
* // Upload with error handling
|
|
1017
|
+
* try {
|
|
1018
|
+
* const result = await storage.upload(file, 'document.pdf');
|
|
1019
|
+
* console.log('Upload successful:', result.url);
|
|
1020
|
+
* } catch (error) {
|
|
1021
|
+
* console.error('Upload failed:', error.message);
|
|
1022
|
+
* // Handle error: retry, show user message, etc.
|
|
1023
|
+
* }
|
|
1024
|
+
*/
|
|
1025
|
+
upload(file: unknown, filename?: string): Promise<UploadResponse>;
|
|
1026
|
+
/**
|
|
1027
|
+
* Deletes a file from storage by its path
|
|
1028
|
+
*
|
|
1029
|
+
* @param {string} path - The file path or URL of the file to delete
|
|
1030
|
+
* @returns {Promise<{ deleted: boolean }>} Promise resolving to deletion status
|
|
1031
|
+
*
|
|
1032
|
+
* @throws {Error} If path is empty or invalid
|
|
1033
|
+
* @throws {Error} If file does not exist
|
|
1034
|
+
* @throws {Error} If authentication fails
|
|
1035
|
+
* @throws {Error} If user lacks permission to delete the file
|
|
1036
|
+
*
|
|
1037
|
+
* @example
|
|
1038
|
+
* // Delete a file by path
|
|
1039
|
+
* const result = await storage.deleteFile('uploads/document.pdf');
|
|
1040
|
+
* if (result.deleted) {
|
|
1041
|
+
* console.log('File deleted successfully');
|
|
1042
|
+
* }
|
|
1043
|
+
*
|
|
1044
|
+
* @example
|
|
1045
|
+
* // Delete with error handling
|
|
1046
|
+
* try {
|
|
1047
|
+
* const result = await storage.deleteFile('uploads/old-file.jpg');
|
|
1048
|
+
* console.log('Deleted:', result.deleted);
|
|
1049
|
+
* } catch (error) {
|
|
1050
|
+
* console.error('Deletion failed:', error.message);
|
|
1051
|
+
* }
|
|
1052
|
+
*
|
|
1053
|
+
* @example
|
|
1054
|
+
* // Delete after upload
|
|
1055
|
+
* const uploadResult = await storage.upload(file, 'temp-file.pdf');
|
|
1056
|
+
* console.log('Uploaded:', uploadResult.url);
|
|
1057
|
+
*
|
|
1058
|
+
* // Later, delete the file
|
|
1059
|
+
* await storage.deleteFile('temp-file.pdf');
|
|
1060
|
+
* console.log('File cleaned up');
|
|
1061
|
+
*/
|
|
1062
|
+
deleteFile(path: string): Promise<{
|
|
1063
|
+
deleted: boolean;
|
|
1064
|
+
}>;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/**
|
|
1068
|
+
* Module for managing database schemas in urBackend
|
|
1069
|
+
*
|
|
1070
|
+
* @class SchemaModule
|
|
1071
|
+
* @description Provides methods to fetch and manage collection schema definitions.
|
|
1072
|
+
* Schemas define the structure, validation rules, and data types for collections.
|
|
1073
|
+
*
|
|
1074
|
+
* @example
|
|
1075
|
+
* // Initialize the schema module
|
|
1076
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
1077
|
+
* const schema = new SchemaModule(client);
|
|
1078
|
+
*
|
|
1079
|
+
* // Get schema for a collection
|
|
1080
|
+
* const collectionSchema = await schema.getSchema('users');
|
|
1081
|
+
* console.log(collectionSchema.fields);
|
|
1082
|
+
*/
|
|
1083
|
+
declare class SchemaModule {
|
|
1084
|
+
private client;
|
|
1085
|
+
/**
|
|
1086
|
+
* Creates an instance of SchemaModule
|
|
1087
|
+
*
|
|
1088
|
+
* @param {UrBackendClient} client - The authenticated urBackend client instance
|
|
1089
|
+
*
|
|
1090
|
+
* @example
|
|
1091
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
1092
|
+
* const schema = new SchemaModule(client);
|
|
1093
|
+
*/
|
|
1094
|
+
constructor(client: UrBackendClient);
|
|
1095
|
+
/**
|
|
1096
|
+
* Fetches the schema definition for a specific collection
|
|
1097
|
+
*
|
|
1098
|
+
* @param {string} collection - Name of the collection to fetch schema for
|
|
1099
|
+
* @returns {Promise<CollectionSchema>} Promise resolving to the collection schema definition
|
|
1100
|
+
*
|
|
1101
|
+
* @throws {Error} If collection name is empty or contains only whitespace
|
|
1102
|
+
* @throws {Error} If collection does not exist
|
|
1103
|
+
* @throws {Error} If authentication fails
|
|
1104
|
+
*
|
|
1105
|
+
* @example
|
|
1106
|
+
* // Get schema for users collection
|
|
1107
|
+
* const userSchema = await schema.getSchema('users');
|
|
1108
|
+
* console.log(userSchema.fields);
|
|
1109
|
+
*
|
|
1110
|
+
* @example
|
|
1111
|
+
* // Get schema for products collection with error handling
|
|
1112
|
+
* try {
|
|
1113
|
+
* const productSchema = await schema.getSchema('products');
|
|
1114
|
+
* console.log('Schema fields:', Object.keys(productSchema.fields));
|
|
1115
|
+
* } catch (error) {
|
|
1116
|
+
* console.error('Failed to fetch schema:', error.message);
|
|
1117
|
+
* }
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* // Validate collection name before fetching
|
|
1121
|
+
* const collectionName = 'my_collection';
|
|
1122
|
+
* if (collectionName.trim()) {
|
|
1123
|
+
* const schemaDef = await schema.getSchema(collectionName);
|
|
1124
|
+
* // Use schema definition
|
|
1125
|
+
* }
|
|
1126
|
+
*/
|
|
1127
|
+
getSchema(collection: string): Promise<CollectionSchema>;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* Module for handling email operations in urBackend
|
|
1132
|
+
*
|
|
1133
|
+
* @class MailModule
|
|
1134
|
+
* @description Provides methods to send emails using the urBackend mail service.
|
|
1135
|
+
* Requires a Secret Key (sk_live_...) and should be called from a server environment.
|
|
1136
|
+
*
|
|
1137
|
+
* @example
|
|
1138
|
+
* // Initialize the mail module
|
|
1139
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
1140
|
+
* const mail = new MailModule(client);
|
|
1141
|
+
*
|
|
1142
|
+
* // Send an email
|
|
1143
|
+
* const result = await mail.send({
|
|
1144
|
+
* to: 'user@example.com',
|
|
1145
|
+
* subject: 'Welcome!',
|
|
1146
|
+
* html: '<h1>Hello World</h1>'
|
|
1147
|
+
* });
|
|
1148
|
+
*/
|
|
1149
|
+
declare class MailModule {
|
|
1150
|
+
private client;
|
|
1151
|
+
/**
|
|
1152
|
+
* Creates an instance of MailModule
|
|
1153
|
+
*
|
|
1154
|
+
* @param {UrBackendClient} client - The authenticated urBackend client instance
|
|
1155
|
+
*
|
|
1156
|
+
* @example
|
|
1157
|
+
* const client = new UrBackendClient({ secretKey: 'sk_live_xxx' });
|
|
1158
|
+
* const mail = new MailModule(client);
|
|
1159
|
+
*/
|
|
1160
|
+
constructor(client: UrBackendClient);
|
|
1161
|
+
/**
|
|
1162
|
+
* Sends an email using the urBackend mail service
|
|
1163
|
+
*
|
|
1164
|
+
* @param {SendMailPayload} payload - The email content and configuration
|
|
1165
|
+
* @param {string} payload.to - Recipient email address
|
|
1166
|
+
* @param {string} payload.subject - Email subject line
|
|
1167
|
+
* @param {string} payload.html - HTML content of the email
|
|
1168
|
+
* @param {string} [payload.from] - Optional sender email address (defaults to configured sender)
|
|
1169
|
+
* @param {string[]} [payload.cc] - Optional CC recipient email addresses
|
|
1170
|
+
* @param {string[]} [payload.bcc] - Optional BCC recipient email addresses
|
|
1171
|
+
* @returns {Promise<SendMailResponse>} Promise resolving to email sending status and message ID
|
|
1172
|
+
*
|
|
1173
|
+
* @throws {Error} If secret key is missing or invalid
|
|
1174
|
+
* @throws {Error} If email validation fails
|
|
1175
|
+
* @throws {Error} If rate limit is exceeded
|
|
1176
|
+
*
|
|
1177
|
+
* @example
|
|
1178
|
+
* // Send a basic email
|
|
1179
|
+
* const result = await mail.send({
|
|
1180
|
+
* to: 'user@example.com',
|
|
1181
|
+
* subject: 'Welcome to urBackend',
|
|
1182
|
+
* html: '<h1>Welcome!</h1><p>Thanks for joining.</p>'
|
|
1183
|
+
* });
|
|
1184
|
+
* console.log(result.messageId);
|
|
1185
|
+
*
|
|
1186
|
+
* @example
|
|
1187
|
+
* // Send an email with CC and custom sender
|
|
1188
|
+
* const result = await mail.send({
|
|
1189
|
+
* from: 'noreply@myapp.com',
|
|
1190
|
+
* to: 'user@example.com',
|
|
1191
|
+
* cc: ['admin@example.com'],
|
|
1192
|
+
* subject: 'Important Update',
|
|
1193
|
+
* html: '<p>Your account has been updated.</p>'
|
|
1194
|
+
* });
|
|
1195
|
+
*
|
|
1196
|
+
* @example
|
|
1197
|
+
* // Send email with error handling
|
|
1198
|
+
* try {
|
|
1199
|
+
* const result = await mail.send({
|
|
1200
|
+
* to: 'user@example.com',
|
|
1201
|
+
* subject: 'Test',
|
|
1202
|
+
* html: '<p>Test email</p>'
|
|
1203
|
+
* });
|
|
1204
|
+
* console.log('Email sent:', result);
|
|
1205
|
+
* } catch (error) {
|
|
1206
|
+
* console.error('Failed to send email:', error);
|
|
1207
|
+
* }
|
|
1208
|
+
*/
|
|
1209
|
+
send(payload: SendMailPayload): Promise<SendMailResponse>;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
declare class UrBackendClient {
|
|
1213
|
+
private apiKey;
|
|
1214
|
+
private baseUrl;
|
|
1215
|
+
private _auth?;
|
|
1216
|
+
private _db?;
|
|
1217
|
+
private _storage?;
|
|
1218
|
+
private _schema?;
|
|
1219
|
+
private _mail?;
|
|
1220
|
+
private headers;
|
|
1221
|
+
constructor(config: UrBackendConfig);
|
|
1222
|
+
get auth(): AuthModule;
|
|
1223
|
+
get db(): DatabaseModule;
|
|
1224
|
+
get storage(): StorageModule;
|
|
1225
|
+
get schema(): SchemaModule;
|
|
1226
|
+
get mail(): MailModule;
|
|
1227
|
+
getBaseUrl(): string;
|
|
1228
|
+
getApiKey(): string;
|
|
1229
|
+
/**
|
|
1230
|
+
* Internal request handler
|
|
1231
|
+
*/
|
|
1232
|
+
request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
declare class UrBackendError extends Error {
|
|
1236
|
+
message: string;
|
|
1237
|
+
statusCode: number;
|
|
1238
|
+
endpoint: string;
|
|
1239
|
+
constructor(message: string, statusCode: number, endpoint: string);
|
|
1240
|
+
}
|
|
1241
|
+
declare class AuthError extends UrBackendError {
|
|
1242
|
+
constructor(message: string, statusCode: number, endpoint: string);
|
|
1243
|
+
}
|
|
1244
|
+
declare class NotFoundError extends UrBackendError {
|
|
1245
|
+
constructor(message: string, endpoint: string);
|
|
1246
|
+
}
|
|
1247
|
+
declare class RateLimitError extends UrBackendError {
|
|
1248
|
+
retryAfter?: number;
|
|
1249
|
+
constructor(message: string, endpoint: string, retryAfter?: number);
|
|
1250
|
+
}
|
|
1251
|
+
declare class StorageError extends UrBackendError {
|
|
1252
|
+
constructor(message: string, statusCode: number, endpoint: string);
|
|
1253
|
+
}
|
|
1254
|
+
declare class ValidationError extends UrBackendError {
|
|
1255
|
+
constructor(message: string, endpoint: string);
|
|
1256
|
+
}
|
|
1257
|
+
declare function parseApiError(response: Response): Promise<UrBackendError>;
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* Factory function to create a new urBackend client
|
|
1261
|
+
*/
|
|
1262
|
+
declare function urBackend(config: UrBackendConfig): UrBackendClient;
|
|
1263
|
+
|
|
1264
|
+
export { type ApiResponse, AuthError, AuthModule, type AuthResponse, type AuthUser, type ChangePasswordPayload, type CollectionSchema, DatabaseModule, type DocumentData, type InsertPayload, type LoginPayload, MailModule, NotFoundError, type PatchPayload, type QueryParams, RateLimitError, type RequestOptions, type RequestPasswordResetPayload, type ResendOtpPayload, type ResetPasswordPayload, type SchemaField, SchemaModule, type SendMailPayload, type SendMailResponse, type SignUpPayload, type SocialExchangePayload, type SocialExchangeResponse, StorageError, StorageModule, type UpdatePayload, type UpdateProfilePayload, type UploadResponse, UrBackendClient, type UrBackendConfig, UrBackendError, ValidationError, type VerifyEmailPayload, urBackend as default, parseApiError };
|