@cloudbase/js-sdk 3.6.2 → 3.6.3

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.
Files changed (74) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/ai/dist/index.esm.js +1 -1
  3. package/ai/dist/index.esm.js.map +1 -1
  4. package/ai/dist/index.js +1 -1
  5. package/ai/dist/index.js.map +1 -1
  6. package/app/dist/index.esm.js +1 -1
  7. package/app/dist/index.esm.js.map +1 -1
  8. package/app/dist/index.js +1 -1
  9. package/app/dist/index.js.map +1 -1
  10. package/app/dist/index.node.esm.js +1 -1
  11. package/app/dist/index.node.esm.js.map +1 -1
  12. package/app/dist/index.node.js +1 -1
  13. package/app/dist/index.node.js.map +1 -1
  14. package/auth/dist/index.esm.js +1 -1
  15. package/auth/dist/index.esm.js.map +1 -1
  16. package/auth/dist/index.js +1 -1
  17. package/auth/dist/index.js.map +1 -1
  18. package/core.d.ts +4331 -0
  19. package/core.node.d.ts +294 -0
  20. package/dist/index.cjs.js +1 -1
  21. package/dist/index.cjs.js.map +1 -1
  22. package/dist/index.esm.js +1 -1
  23. package/dist/index.esm.js.map +1 -1
  24. package/dist/index.node.cjs.js +1 -1
  25. package/dist/index.node.cjs.js.map +1 -1
  26. package/dist/index.node.esm.js +1 -1
  27. package/dist/index.node.esm.js.map +1 -1
  28. package/index.d.ts +5 -4268
  29. package/index.node.d.ts +13 -0
  30. package/miniprogram_dist/ai/index.d.ts +42 -0
  31. package/miniprogram_dist/ai/index.js +2 -0
  32. package/miniprogram_dist/apis/index.d.ts +5 -0
  33. package/miniprogram_dist/{apis.js → apis/index.js} +1 -1
  34. package/miniprogram_dist/app/index.d.ts +67 -0
  35. package/miniprogram_dist/app/index.js +2 -0
  36. package/miniprogram_dist/auth/index.d.ts +284 -0
  37. package/miniprogram_dist/auth/index.js +2 -0
  38. package/miniprogram_dist/cloudrun/index.d.ts +4 -0
  39. package/miniprogram_dist/cloudrun/index.js +1 -0
  40. package/miniprogram_dist/container/index.d.ts +13 -0
  41. package/miniprogram_dist/container/index.js +1 -0
  42. package/miniprogram_dist/database/index.d.ts +3 -0
  43. package/miniprogram_dist/functions/index.d.ts +2 -0
  44. package/miniprogram_dist/functions/index.js +1 -0
  45. package/miniprogram_dist/index.js +1 -1
  46. package/miniprogram_dist/model/index.d.ts +5 -0
  47. package/miniprogram_dist/model/index.js +1 -0
  48. package/miniprogram_dist/mysql/index.d.ts +3 -0
  49. package/miniprogram_dist/mysql/index.js +1 -0
  50. package/miniprogram_dist/oauth/index.d.ts +22 -0
  51. package/miniprogram_dist/oauth/index.js +2 -0
  52. package/miniprogram_dist/realtime/index.d.ts +2 -0
  53. package/miniprogram_dist/realtime/index.js +1 -0
  54. package/miniprogram_dist/storage/index.d.ts +13 -0
  55. package/miniprogram_dist/{storage.js → storage/index.js} +1 -1
  56. package/oauth/dist/index.esm.js +1 -1
  57. package/oauth/dist/index.esm.js.map +1 -1
  58. package/oauth/dist/index.js +1 -1
  59. package/oauth/dist/index.js.map +1 -1
  60. package/package.json +6 -2
  61. package/types/package.json +1 -1
  62. package/utilities/package.json +2 -2
  63. package/dist/index.d.ts +0 -9
  64. package/miniprogram_dist/ai.js +0 -2
  65. package/miniprogram_dist/app.js +0 -2
  66. package/miniprogram_dist/auth.js +0 -2
  67. package/miniprogram_dist/cloudrun.js +0 -1
  68. package/miniprogram_dist/container.js +0 -1
  69. package/miniprogram_dist/functions.js +0 -1
  70. package/miniprogram_dist/model.js +0 -1
  71. package/miniprogram_dist/mysql.js +0 -1
  72. package/miniprogram_dist/oauth.js +0 -2
  73. package/miniprogram_dist/realtime.js +0 -1
  74. /package/miniprogram_dist/{database.js → database/index.js} +0 -0
package/index.d.ts CHANGED
@@ -1,4274 +1,11 @@
1
- import { OrmClient, OrmRawQueryClient } from '@cloudbase/model'
2
- import { IMySqlClient } from '@cloudbase/mysql'
3
- import { authModels } from '@cloudbase/oauth'
4
- import type {
5
- SignInRes,
6
- GetUserRes,
7
- CommonRes,
8
- SignInWithOtpRes,
9
- SignInOAuthRes,
10
- GetClaimsRes,
11
- ResetPasswordForEmailRes,
12
- GetUserIdentitiesRes,
13
- LinkIdentityRes,
14
- ReauthenticateRes,
15
- ResendRes,
16
- UpdateUserWithVerificationRes,
17
- OnAuthStateChangeCallback,
18
- SignInWithPasswordReq,
19
- SignInWithIdTokenReq,
20
- SignInWithOAuthReq,
21
- VerifyOAuthReq,
22
- VerifyOtpReq,
23
- LinkIdentityReq,
24
- UnlinkIdentityReq,
25
- UpdateUserReq,
26
- SignInWithOtpReq,
27
- ResetPasswordForOldReq,
28
- ResendReq,
29
- SetSessionReq,
30
- DeleteMeReq,
31
- SignUpRes,
32
- } from '@cloudbase/auth'
33
- import { AI } from '@cloudbase/ai'
34
- import { CloudbaseAdapter, ResponseObject } from '@cloudbase/adapter-interface'
35
- import { ICloudbaseUpgradedConfig, ICloudbase, Persistence } from '@cloudbase/types'
36
- import { LANGS } from '@cloudbase/types'
37
- import { ICustomReqOpts } from '@cloudbase/types/functions'
1
+ /// <reference path="./core.d.ts" />
38
2
 
39
- type KV<T> = {
40
- [key: string]: T
41
- }
42
-
43
- type ExcludeOf<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
44
-
45
- declare type MethodType = 'request' | 'post' | 'get' | 'head' | 'patch' | 'delete' | 'put'
46
-
47
- interface ICallApiOptions {
48
- /** 请求的path */
49
- path?: string
50
- /**请求方法 */
51
- method?: MethodType
52
- /**请求头 */
53
- headers?: KV<any>
54
- /** 请求体,根据content-type可以是不同类型 */
55
- body?: KV<any> | string
56
- /**可传token,如果没有传值,则默认用当前登录的token */
57
- token?: string
58
- }
59
-
60
- interface ICloudbaseApis {
61
- [apiName: string]: {
62
- [method in MethodType]: (callApiOptions: ICallApiOptions, opts?: KV<any>) => Promise<ResponseObject['data']>
63
- }
64
- }
65
-
66
- /**
67
- * module
68
- */
69
- declare namespace cloudbase {
70
- interface SimpleStorage {
71
- getItem: (key: string) => Promise<string | null>
72
- removeItem: (key: string) => Promise<void>
73
- setItem: (key: string, value: string) => Promise<void>
74
- getItemSync: (key: string) => string | null
75
- removeItemSync: (key: string) => void
76
- setItemSync: (key: string, value: string) => void
77
- }
78
-
79
- interface ICloudbaseConfig {
80
- /** 是否国际站标记 */
81
- intl?: boolean
82
- /** 环境 ID,在腾讯云开发控制台 → 环境 → 环境总览中获取 */
83
- env: string
84
- /**
85
- * 地域信息
86
- * @example 'ap-shanghai'
87
- */
88
- region?: string
89
- /** 网络请求超时上限,单位 ms,默认 15000 */
90
- timeout?: number
91
- /** 本地登录态保留期限 */
92
- persistence?: Persistence
93
- oauthClient?: any
94
- /** 是否开启调试模式 */
95
- debug?: boolean
96
- _fromApp?: ICloudbase
97
- clientId?: string
98
- oauthInstance?: any
99
- wxCloud?: any
100
- i18n?: {
101
- t: (text: string) => string
102
- LANG_HEADER_KEY: string
103
- lang: LANGS
104
- }
105
- accessKey?: string
106
- endPointMode?: EndPointKey
107
- lang?: LANGS
108
- /**
109
- * 认证相关配置
110
- * @example
111
- * ```typescript
112
- * cloudbase.init({
113
- * env: 'your-env-id',
114
- * auth: {
115
- * detectSessionInUrl: true // 自动检测 URL 中的 OAuth 回调参数
116
- * }
117
- * })
118
- * ```
119
- */
120
- auth?: {
121
- /** 是否自动检测 URL 中的 OAuth 回调参数,默认 false */
122
- detectSessionInUrl?: boolean
123
- /** 密钥 ID(Node.js 端使用) */
124
- secretId?: string
125
- /** 密钥(Node.js 端使用) */
126
- secretKey?: string
127
- /** 临时会话 Token(Node.js 端使用) */
128
- sessionToken?: string
129
- /** 密钥类型 */
130
- secretType?: 'SESSION_SECRET' | 'SECRET'
131
- }
132
- }
133
-
134
- interface ICloudbaseExtension {
135
- name: string
136
- invoke(opts: any, app: ICloudbase): Promise<any>
137
- }
138
-
139
- interface Listeners {
140
- [key: string]: Function[]
141
- }
142
-
143
- interface ICloudbaseEvent {
144
- name: string
145
- target: any
146
- data: any
147
- }
148
-
149
- interface ICloudbaseEventEmitter {
150
- on(name: string, listener: Function): this
151
- off(name: string, listener: Function): this
152
- fire(event: string | ICloudbaseEvent, data?: any): this
153
- }
154
-
155
- interface ICloudbaseComponent {
156
- name: string
157
- entity: any
158
- namespace?: string
159
- injectEvents?: {
160
- bus: ICloudbaseEventEmitter
161
- events: string[]
162
- }
163
- IIFE?: boolean
164
- }
165
-
166
- interface ICloudbaseHook {
167
- entity: any
168
- target: string
169
- }
170
-
171
- type EndPointKey = 'CLOUD_API' | 'GATEWAY'
172
-
173
- interface ISetEndPointWithKey {
174
- key: EndPointKey
175
- url?: string
176
- protocol?: 'http' | 'https'
177
- }
178
-
179
- /**
180
- * 初始化Cloudbase
181
- *
182
- * @example
183
- * ```javascript
184
- * // 基本用法
185
- * const app = cloudbase.init({
186
- * env: 'your-envid',
187
- * timeout: 15000
188
- * });
189
- *
190
- * // 推荐:从环境变量读取环境 ID
191
- * const app = cloudbase.init({
192
- * env: process.env.CLOUDBASE_ENV || import.meta.env.VITE_CLOUDBASE_ENV || 'your-envid'
193
- * });
194
- *
195
- * // 使用认证配置
196
- * const app = cloudbase.init({
197
- * env: 'your-envid',
198
- * auth: {
199
- * detectSessionInUrl: true // 自动检测 URL 中的 OAuth 回调参数
200
- * }
201
- * });
202
- * ```
203
- *
204
- * @param config 初始化配置
205
- * @param config.env 环境ID,在腾讯云开发控制台 → 环境 → 环境总览中获取
206
- * @param config.timeout 【可选】网络请求超时上限,单位`ms`,默认值`15000`
207
- * @param config.auth 【可选】认证相关配置
208
- *
209
- * @return {!cloudbase.app.App} 初始化成功的Cloudbase实例
210
- */
211
- function init(config: ICloudbaseConfig): cloudbase.app.App
212
-
213
- /**
214
- * 检查 Cloudbase 实例是否已完成初始化
215
- *
216
- * @example
217
- * ```javascript
218
- * if (!cloudbase.isInitialized()) {
219
- * cloudbase.init({ env: 'your-envid' });
220
- * }
221
- * ```
222
- *
223
- * @returns 是否已初始化
224
- */
225
- function isInitialized(): boolean
226
-
227
- function updateConfig(config: ICloudbaseUpgradedConfig): void
228
-
229
- function updateLang(lang: LANGS): void
230
- /**
231
- * 使用适配器,使用方式参考 {@link https://docs.cloudbase.net/api-reference/webv3/adapter#%E7%AC%AC-1-%E6%AD%A5%E5%AE%89%E8%A3%85%E5%B9%B6%E5%BC%95%E5%85%A5%E9%80%82%E9%85%8D%E5%99%A8}
232
- *
233
- * @example
234
- * ```javascript
235
- * cloudbase.useAdapters(adapter); // 使用单个适配器
236
- * cloudbase.useAdapters([ // 使用多个适配器
237
- * adapterA,
238
- * adapterB
239
- * ]);
240
- * ```
241
- *
242
- * @param adapters 适配器对象,入参可以为单个适配器对象,也可以是多个适配器对象的数组
243
- * @param options 适配器参数,可以在genAdapter中获取到该参数
244
- */
245
- function useAdapters(adapters: CloudbaseAdapter | CloudbaseAdapter[], options?: any): void
246
- /**
247
- * 注册扩展能力插件,使用方式参考 {@link https://docs.cloudbase.net/extension/abilities/image-examination.html#shi-yong-kuo-zhan}
248
- *
249
- * @example
250
- * ```javascript
251
- * cloudbase.registerExtension(ext);
252
- * ```
253
- *
254
- * @param ext 扩展能力插件对象
255
- */
256
- function registerExtension(ext: ICloudbaseExtension): void
257
- /**
258
- * 【谨慎操作】注册SDK的版本
259
- *
260
- * @example
261
- * ```javascript
262
- * cloudbase.registerVersion('1.2.1');
263
- * ```
264
- *
265
- * @param version SDK版本
266
- */
267
- function registerVersion(version: string): void
268
- /**
269
- * 【谨慎操作】注册SDK的名称
270
- *
271
- * @example
272
- * ```javascript
273
- * cloudbase.registerSdkName('cloudbase-js-sdk');
274
- * ```
275
- *
276
- * @param name SDK名称
277
- */
278
- function registerSdkName(name: string): void
279
- /**
280
- * 【谨慎操作】修改SDK请求的云开发服务地址
281
- *
282
- * @example
283
- * ```javascript
284
- * cloudbase.registerEndPoint('url','https');
285
- * ```
286
- *
287
- * @param url 服务地址
288
- * @param protocol 【可选】强制使用某种协议,默认与主站协议一致
289
- */
290
- function registerEndPoint(url: string, protocol?: 'http' | 'https'): void
291
- /**
292
- * 【谨慎操作】修改SDK请求的「云开发/网关」服务地址
293
- *
294
- * @example
295
- * ```javascript
296
- * cloudbase.registerEndPointWithKey({
297
- * key: "GATEWAY",
298
- * url: "",
299
- * protocol: ""
300
- * });
301
- * ```
302
- *
303
- */
304
- function registerEndPointWithKey(props: ISetEndPointWithKey): void
305
- /**
306
- * 一次性设置所有端点,只需传入 host 地址,自动拼接路径
307
- * @param host - 主机地址,如 "43.144.98.4" 或 "//43.144.98.4"
308
- * @param protocol - 协议,默认 "http"
309
- */
310
- function registerHost(host: string, protocol?: 'http' | 'https'): void
311
- /**
312
- * 【谨慎操作】注册功能模块
313
- *
314
- * @example
315
- * ```javascript
316
- * cloudbase.registerComponent({});
317
- * ```
318
- *
319
- * @param component 功能模块对象
320
- */
321
- function registerComponent(component: ICloudbaseComponent): void
322
- /**
323
- * 【谨慎操作】注册hook
324
- *
325
- * @example
326
- * ```javascript
327
- * cloudbase.registerHook({});
328
- * ```
329
- *
330
- * @param hook hook对象
331
- */
332
- function registerHook(hook: ICloudbaseHook): void
333
-
334
- export interface models extends OrmClient, OrmRawQueryClient {}
335
- }
336
- /**
337
- * instance
338
- */
339
- declare namespace cloudbase.app {
340
- interface App {
341
- /**
342
- * 创建Auth对象
343
- *
344
- * {@link https://docs.cloudbase.net/api-reference/webv3/authentication#appauth}
345
- *
346
- * @example
347
- * ```javascript
348
- * const app = cloudbase.init({
349
- * env: 'your-envid'
350
- * });
351
- * const auth = app.auth({
352
- * persistence: 'local'
353
- * });
354
- * ```
355
- *
356
- * @param options Auth初始化配置
357
- * @param options.persistence 本地登录态保留期限
358
- *
359
- * @return {!cloudbase.auth.App} Auth实例
360
- */
361
- auth: ((options?: { persistence: cloudbase.auth.Persistence }) => cloudbase.auth.App) & cloudbase.auth.App
362
- /**
363
- * 调用云函数
364
- *
365
- * {@link https://docs.cloudbase.net/api-reference/webv3/functions#callfunction}
366
- *
367
- * @example
368
- * ```javascript
369
- * const app = cloudbase.init({
370
- * env: 'your-envid'
371
- * });
372
- * app.callFunction({
373
- * name: 'function-name'
374
- * data: {
375
- * a: 1,
376
- * b: 2
377
- * }
378
- * }).then(res=>{
379
- * console.log(res.result);
380
- * }});
381
- * ```
382
- *
383
- * @param options 被调用的云函数信息
384
- * @param options.name 云函数的名称
385
- * @param options.data 【可选】云函数的参数,默认为空
386
- * @param options.parse 【可选】设置为 `true` 时,当函数返回值为对象时,API 请求会返回解析对象,而不是 JSON 字符串,默认为`false`
387
- *
388
- * @return Promise-函数执行结果
389
- */
390
- callFunction(
391
- options: cloudbase.functions.ICallFunctionOptions,
392
- callback?: Function,
393
- customReqOpts?: ICustomReqOpts,
394
- ): Promise<cloudbase.functions.ICallFunctionResponse>
395
- /**
396
- * 调用云托管
397
- *
398
- * {@link https://docs.cloudbase.net/api-reference/webv3/cloudrun}
399
- *
400
- * @example
401
- * ```javascript
402
- * const app = cloudbase.init({
403
- * env: 'your-envid'
404
- * });
405
- * app
406
- * .callContainer({
407
- * name: 'helloworld',
408
- * method: 'POST',
409
- * path: '/abc',
410
- * header:{
411
- * 'Content-Type': 'application/json; charset=utf-8'
412
- * },
413
- * data: {
414
- * key1: 'test value 1',
415
- * key2: 'test value 2'
416
- * },
417
- * })
418
- * .then((res) => {
419
- * console.log(res)
420
- * });
421
- * ```
422
- *
423
- * @param options 被调用的云托管信息
424
- * @param options.name 云托管的名称
425
- * @param options.data 【可选】云托管的参数,默认为空
426
- *
427
- * @return Promise-云托管执行结果
428
- */
429
- callContainer(
430
- options: cloudbase.functions.ICallFunctionOptions,
431
- customReqOpts?: ICustomReqOpts,
432
- ): Promise<ResponseObject>
433
- /**
434
- * 云存储-上传文件
435
- *
436
- * {@link https://docs.cloudbase.net/api-reference/webv3/storage#uploadfile}
437
- *
438
- * @example
439
- * ```javascript
440
- * const app = cloudbase.init({
441
- * env: 'your-envid'
442
- * });
443
- * app.uploadFile({
444
- * cloudPath: 'cloudPath',
445
- * filePath: 'filePath',
446
- * method: 'put',
447
- * headers: {
448
- * 'Content-MD5': 'xxxxxx'
449
- * }
450
- * onUploadProgress: function(event){}
451
- * });
452
- * ```
453
- *
454
- * @param params
455
- * @param params.cloudPath 文件上传到云端后的绝对路径,包含文件名
456
- * @param params.filePath 被上传的文件对象
457
- * @param params.method 上传方法,默认为 put
458
- * @param params.headers 自定义头部字段
459
- * @param params.onUploadProgress 【可选】上传进度回调函数
460
- *
461
- * @return Promise-上传结果
462
- *
463
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().upload()`。
464
- */
465
- uploadFile(
466
- params: cloudbase.storage.ICloudbaseUploadFileParams,
467
- callback?: Function,
468
- ): Promise<cloudbase.storage.ICloudbaseUploadFileResult>
469
- /**
470
- * 云存储-下载文件
471
- *
472
- * {@link https://docs.cloudbase.net/api-reference/webv3/storage#downloadfile}
473
- *
474
- * @example
475
- * ```javascript
476
- * const app = cloudbase.init({
477
- * env: 'your-envid'
478
- * });
479
- * app.downloadFile({
480
- * fileID: 'cloudPath'
481
- * });
482
- * ```
483
- *
484
- * @param params
485
- * @param params.fileID 要下载的文件的 `id`,在控制台云存储中查看
486
- *
487
- * @return Promise-下载结果
488
- *
489
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().download()`。
490
- */
491
- downloadFile(
492
- params: cloudbase.storage.ICloudbaseDownloadFileParams,
493
- callback?: Function,
494
- ): Promise<cloudbase.storage.ICloudbaseDownloadFileResult>
495
- /**
496
- * 云存储-批量复制文件
497
- *
498
- *
499
- * @example
500
- * ```javascript
501
- * const app = cloudbase.init({
502
- * env: 'your-envid'
503
- * });
504
- * app.copyFile({
505
- * fileList: [
506
- * {
507
- * srcPath: '源文件的绝对路径,包含文件名。例如 foo/bar.jpg、foo/bar/baz.jpg 等,不能包含除[0-9 , a-z , A-Z]、/、!、-、_、.、、*和中文以外的字符,使用 / 字符来实现类似传统文件系统的层级结构',
508
- * dstPath: '目标文件的绝对路径,包含文件名。例如 foo/bar.jpg、foo/bar/baz.jpg 等,不能包含除[0-9 , a-z , A-Z]、/、!、-、_、.、、*和中文以外的字符,使用 / 字符来实现类似传统文件系统的层级结构',
509
- * overwrite: '当目标文件已经存在时,是否允许覆盖已有文件,默认 true',
510
- * removeOriginal: '复制文件后是否删除源文件,默认 false'
511
- * }
512
- * ]
513
- * });
514
- * ```
515
- *
516
- * @param params
517
- * @param params.fileList 要复制的文件信息组成的数组
518
- *
519
- * @return Promise-复制结果
520
- *
521
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().copy()`。
522
- */
523
- copyFile(
524
- params: cloudbase.storage.ICloudbaseCopyFileParams,
525
- callback?: Function,
526
- ): Promise<cloudbase.storage.ICloudbaseCopyFileResult>
527
- /**
528
- * 云存储-获取文件的下载链接
529
- *
530
- * {@link https://docs.cloudbase.net/api-reference/webv3/storage#gettempfileurl}
531
- *
532
- * @example
533
- * ```javascript
534
- * const app = cloudbase.init({
535
- * env: 'your-envid'
536
- * });
537
- * app.getTempFileURL({
538
- * fileList: [
539
- * '文件A的fileID',
540
- * {
541
- * fileID: '文件B的fileID',
542
- * maxAge: 600 // 文件B的链接有效期,单位`ms`
543
- * }
544
- * ]
545
- * });
546
- * ```
547
- *
548
- * @param params
549
- * @param params.fileList 要下载的文件数组,数组元素可以是`string`或`Object`,如果是`string`代表文件ID,如果是`Object`可配置以下信息
550
- * @param params.fileList[].fileID 要下载的文件ID
551
- * @param params.fileList[].maxAge 下载链接的有效期,单位`ms`
552
- *
553
- * @return Promise-文件下载链接
554
- *
555
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().createSignedUrl()`。
556
- */
557
- getTempFileURL(
558
- params: cloudbase.storage.ICloudbaseGetTempFileURLParams,
559
- callback?: Function,
560
- ): Promise<cloudbase.storage.ICloudbaseGetTempFileURLResult>
561
- /**
562
- * 云存储-删除文件
563
- *
564
- * {@link https://docs.cloudbase.net/api-reference/webv3/storage#deletefile}
565
- *
566
- * @example
567
- * ```javascript
568
- * const app = cloudbase.init({
569
- * env: 'your-envid'
570
- * });
571
- * app.deleteFile({
572
- * fileList: [
573
- * '文件A的fileID',
574
- * '文件B的fileID'
575
- * ]
576
- * });
577
- * ```
578
- *
579
- * @param params
580
- * @param params.fileList 要删除的文件ID数组
581
- *
582
- * @return Promise-删除结果
583
- *
584
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().remove()`。
585
- */
586
- deleteFile(
587
- params: cloudbase.storage.ICloudbaseDeleteFileParams,
588
- callback?: Function,
589
- ): Promise<cloudbase.storage.ICloudbaseDeleteFileResult>
590
-
591
- /**
592
- * 云存储-获取文件信息
593
- *
594
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().info()`。
595
- */
596
- getFileInfo(
597
- params: cloudbase.storage.ICloudbaseGetTempFileURLParams,
598
- ): Promise<cloudbase.storage.ICloudbaseGetFileInfoResult>
599
- /**
600
- * 云存储-获取上传元信息
601
- *
602
- *
603
- * @param params
604
- * @param callback
605
- *
606
- * @deprecated 传统云存储 API 已不推荐使用,请改用 `app.storage.from().createSignedUploadUrl()`。
607
- */
608
- getUploadMetadata(params: cloudbase.storage.ICloudbaseGetUploadMetadataParams, callback?: Function): Promise<any>
609
-
610
- /**
611
- * Supabase 风格的文件存储 API
612
- *
613
- * @example
614
- * ```typescript
615
- * const bucket = app.storage.from('my-bucket')
616
- * const { data, error } = await bucket.upload('path/to/file.jpg', file)
617
- * ```
618
- */
619
- storage: cloudbase.storage.StorageClient
620
- /**
621
- * 获取数据库实例
622
- *
623
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#%E8%8E%B7%E5%8F%96%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%9E%E4%BE%8B}
624
- *
625
- * @example
626
- * ```javascript
627
- * const app = cloudbase.init({
628
- * env: 'your-envid'
629
- * });
630
- * const db = app.database();
631
- * ```
632
- *
633
- * @return 数据库实例
634
- */
635
- database(dbConfig?: { instance?: string; database?: string }): cloudbase.database.App
636
- /**
637
- * 调用扩展能力插件功能
638
- *
639
- * @example
640
- * ```javascript
641
- * const app = cloudbase.init({
642
- * env: 'your-envid'
643
- * });
644
- * // 调用前需要先注册
645
- * app.registerExtension(ext);
646
- *
647
- * app.invokeExtension('扩展能力插件名称',{
648
- * // ...扩展能力插件的入参
649
- * });
650
- * ```
651
- *
652
- * @param name 扩展能力插件的名称
653
- * @param opts 【可选】扩展能力插件的参数,根据插件具体需求而定
654
- *
655
- * @return Promise-扩展能力插件执行结果
656
- */
657
- invokeExtension(name: string, opts: any): Promise<any>
658
-
659
- eventBus: any
660
-
661
- /**
662
- * 调用 数据模型 SDK
663
- *
664
- * {@link https://docs.cloudbase.net/model/sdk-reference/model}
665
- * @example
666
- * ```javascript
667
- models.<model_name>.create() // 创建单条数据
668
- models.<model_name>.createMany() // 创建多条数据
669
- models.<model_name>.update() // 更新单条数据
670
- models.<model_name>.updateMany() // 更新多条数据
671
- models.<model_name>.delete() // 删除单条数据
672
- models.<model_name>.deleteMany() // 删除多条数据
673
- models.<model_name>.get() // 查询单条数据
674
- models.<model_name>.list() // 查询多条数据
675
- models.$runSQL() // 执行原生 SQL 语句
676
- * ```
677
- */
678
- models: OrmClient & OrmRawQueryClient
679
-
680
- /**
681
- * MySQL 数据库
682
- *
683
- * @example
684
- * ```javascript
685
- * const app = cloudbase.init({
686
- * env: "xxxx-yyy"
687
- * });
688
- *
689
- * app.mysql().from('todos').select().then((res) => {
690
- * console.log(res.data);
691
- * });
692
- * ```
693
- */
694
- mysql: IMySqlClient
695
- rdb: IMySqlClient
696
-
697
- ai(options?: { baseUrl?: string }): AI
698
-
699
- apis: ICloudbaseApis
700
-
701
- /**
702
- * 一次性设置所有端点,只需传入 host 地址,自动拼接路径
703
- * @param host - 主机地址,如 "43.144.98.4" 或 "//43.144.98.4"
704
- * @param protocol - 协议,默认 "http"
705
- */
706
- registerHost(host: string, protocol?: 'http' | 'https'): void
707
-
708
- /**
709
- * 获取指定类型的端点信息
710
- * @param key - 端点类型
711
- */
712
- getEndPointWithKey(key: cloudbase.EndPointKey): { BASE_URL: string; PROTOCOL: string }
713
-
714
- /**
715
- * 修改SDK请求的云开发服务地址
716
- * @param url 服务地址
717
- * @param protocol 【可选】强制使用某种协议,默认与主站协议一致
718
- */
719
- registerEndPoint(url: string, protocol?: 'http' | 'https'): void
720
-
721
- /**
722
- * 修改SDK请求的「云开发/网关」服务地址,通过 key 指定
723
- */
724
- registerEndPointWithKey(props: cloudbase.ISetEndPointWithKey): void
725
-
726
- /**
727
- * 解析验证码 URL 参数
728
- */
729
- parseCaptcha(url: string): any
730
- }
731
- }
732
- /**
733
- * auth
734
- */
735
- declare namespace cloudbase.auth {
736
- type Persistence = 'local' | 'session' | 'none'
737
-
738
- interface IAccessTokenInfo {
739
- accessToken: string
740
- env: string
741
- }
742
-
743
- interface ILoginState {
744
- /**
745
- * 当前登录用户的信息
746
- */
747
- user: IUser
748
- }
749
-
750
- interface ICredential {
751
- accessToken?: string
752
- accessTokenExpire?: string
753
- }
754
-
755
- interface IAuthProvider {
756
- signInWithRedirect: () => any
757
- }
758
-
759
- /**
760
- * 用户信息
761
- */
762
- interface IUserInfo {
763
- uid?: string
764
- loginType?: string
765
- openid?: string
766
- wxOpenId?: string
767
- wxPublicId?: string
768
- unionId?: string
769
- qqMiniOpenId?: string
770
- customUserId?: string
771
- name?: string
772
- displayName?: string
773
- gender?: string
774
- email?: string
775
- username?: string
776
- hasPassword?: boolean
777
- location?: {
778
- country?: string
779
- province?: string
780
- city?: string
781
- }
782
- country?: string
783
- province?: string
784
- city?: string
785
- }
786
-
787
- interface IUser extends IUserInfo {
788
- /**
789
- * 更新用户信息
790
- *
791
- * {@link https://docs.cloudbase.net/api-reference/webv3/authentication#userupdate}
792
- *
793
- * @example
794
- * ```javascript
795
- * const app = cloudbase.init({
796
- * env: "xxxx-yyy"
797
- * });
798
- * const auth = app.auth();
799
- * const user = auth.currentUser;
800
- * user.update({
801
- * nickName: '新昵称'
802
- * }).then(()=>{});
803
- * ```
804
- *
805
- * @param userinfo 用户信息
806
- *
807
- * @return Promise
808
- *
809
- */
810
- update(userinfo: IUserInfo): Promise<void>
811
- /**
812
- * 刷新本地用户信息
813
- *
814
- * {@link https://docs.cloudbase.net/api-reference/webv3/authentication#userrefresh}
815
- *
816
- * @example
817
- * ```javascript
818
- * const app = cloudbase.init({
819
- * env: "xxxx-yyy"
820
- * });
821
- * const auth = app.auth();
822
- * const user = auth.currentUser;
823
- * user.refresh().then(()=>{});
824
- * ```
825
- *
826
- * @return Promise-刷新后的用户信息
827
- *
828
- */
829
- refresh(): Promise<IUserInfo>
830
- /**
831
- * 同步获取本地用户信息
832
- */
833
- checkLocalInfo: () => void
834
- /**
835
- * 异步获取本地用户信息
836
- */
837
- checkLocalInfoAsync: () => Promise<void>
838
- linkWithTicket?: (ticket: string) => Promise<void>
839
- linkWithRedirect?: (provider: IAuthProvider) => void
840
- getLinkedUidList?: () => Promise<{ hasPrimaryUid: boolean; users: IUserInfo[] }>
841
- setPrimaryUid?: (uid: string) => Promise<void>
842
- unlink?: (loginType: 'CUSTOM' | 'WECHAT-OPEN' | 'WECHAT-PUBLIC' | 'WECHAT-UNION') => Promise<void>
843
- }
844
-
845
- interface App {
846
- /**
847
- * 获取当前登录的用户信息-同步操作
848
- *
849
- * {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authhasloginstate}
850
- *
851
- * @example
852
- * ```javascript
853
- * const app = cloudbase.init({
854
- * env: "xxxx-yyy"
855
- * });
856
- * const userInfo = app.auth().currentUser;
857
- * ```
858
- *
859
- * @return 用户信息,如果未登录返回`null`
860
- */
861
- currentUser: IUser | null
862
- /**
863
- * 获取当前登录的用户信息-异步操作,文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetcurrentuser}
864
- *
865
- * @example
866
- * ```javascript
867
- * const app = cloudbase.init({
868
- * env: "xxxx-yyy"
869
- * });
870
- * app.auth().getCurrentUser().then(userInfo=>{
871
- * // ...
872
- * });
873
- * ```
874
- *
875
- * @return Promise-用户信息,如果未登录返回`null`
876
- */
877
- getCurrentUser(): Promise<IUser | null>
878
- /**
879
- * 绑定手机号码
880
- *
881
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authbindphonenumber}
882
- *
883
- * @param params
884
- */
885
- bindPhoneNumber(params: authModels.BindPhoneRequest): Promise<void>
886
- /**
887
- * 绑定邮箱
888
- *
889
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authbindemail}
890
- *
891
- * @param params
892
- */
893
- bindEmail(params: authModels.BindEmailRequest): Promise<void>
894
- /**
895
- * 解除三方绑定
896
- *
897
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authunbindprovider}
898
- *
899
- * @param params
900
- */
901
- unbindProvider(params: authModels.UnbindProviderRequest): Promise<void>
902
-
903
- /**
904
- * 验证码验证
905
- *
906
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authverify}
907
- *
908
- * @param params
909
- */
910
- verify(params: authModels.VerifyRequest): Promise<authModels.VerifyResponse>
911
- /**
912
- * 获取验证码
913
- *
914
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetverification}
915
- *
916
- * @param params
917
- * @param options
918
- */
919
- getVerification(
920
- params: authModels.GetVerificationRequest,
921
- options?: { withCaptcha: boolean },
922
- ): Promise<authModels.GetVerificationResponse>
923
- /**
924
- * 匿名登录。无需用户注册即可使用应用功能,适合游客模式、临时体验等场景。
925
- *
926
- * **前置条件**:需要在云开发控制台(环境 → 登录授权 → 身份源列表)开启「匿名登录」。
927
- *
928
- * **重要**:匿名登录必须在使用 `watch()` 等实时数据库功能**之前**完成,
929
- * 否则 WebSocket 连接会因缺少认证信息而失败。
930
- *
931
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsigninanonymously}
932
- *
933
- * @example
934
- * ```typescript
935
- * import Cloudbase from '@cloudbase/js-sdk';
936
- *
937
- * const app = Cloudbase.init({
938
- * env: 'your-env-id',
939
- * region: 'ap-shanghai'
940
- * });
941
- * const auth = app.auth();
942
- *
943
- * // 匿名登录
944
- * const { data, error } = await auth.signInAnonymously();
945
- * if (error) {
946
- * console.error('匿名登录失败:', error.message);
947
- * return;
948
- * }
949
- * console.log('匿名登录成功, 用户ID:', data.user.id);
950
- * console.log('是否匿名用户:', data.user.is_anonymous); // true
951
- *
952
- * // 登录成功后,即可使用 watch() 等实时功能
953
- * const db = app.database();
954
- * const listener = db.collection('rooms').where({ status: 'active' }).watch({
955
- * onChange: (snapshot) => {
956
- * console.log('数据变化:', snapshot.docs);
957
- * },
958
- * onError: (err) => {
959
- * console.error('监听错误:', err);
960
- * }
961
- * });
962
- *
963
- * // 不再需要时关闭监听
964
- * listener.close();
965
- * ```
966
- *
967
- * @param data 可选参数
968
- * @param data.provider_token 提供令牌(通常不需要手动传入)
969
- * @returns 登录结果,包含 `data.user`(用户信息)和 `data.session`(会话信息),
970
- * 或 `error`(登录失败时的错误信息)
971
- */
972
- signInAnonymously(data?: { provider_token?: string }): Promise<SignInRes>
973
- /**
974
- * 小程序匿名登录
975
- *
976
- * @param params
977
- */
978
- signInAnonymouslyInWx(params?: { useWxCloud?: boolean }): Promise<ILoginState>
979
- /**
980
- * 小程序绑定OpenID
981
- *
982
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authbindopenid}
983
- *
984
- */
985
- bindOpenId(): Promise<void>
986
- /**
987
- * 小程序unionId静默登录
988
- *
989
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsigninwithunionid}
990
- *
991
- */
992
- signInWithUnionId(): Promise<ILoginState>
993
- /**
994
- * 短信验证码登录
995
- *
996
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsigninwithsms}
997
- *
998
- * @param params
999
- */
1000
- signInWithSms(params: {
1001
- verificationInfo?: { verification_id: string; is_user: boolean }
1002
- verificationCode?: string
1003
- phoneNum?: string
1004
- bindInfo?: any
1005
- }): Promise<ILoginState>
1006
- /**
1007
- * 邮箱验证码登录
1008
- *
1009
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsigninwithemail}
1010
- *
1011
- * @param params
1012
- */
1013
- signInWithEmail(params: {
1014
- verificationInfo?: { verification_id: string; is_user: boolean }
1015
- verificationCode?: string
1016
- email?: string
1017
- bindInfo?: any
1018
- }): Promise<ILoginState>
1019
- /**
1020
- * 设置获取自定义登录 ticket 的函数
1021
- *
1022
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsetcustomsignfunc}
1023
- *
1024
- *
1025
- * @param getTickFn
1026
- */
1027
- setCustomSignFunc(getTickFn: authModels.GetCustomSignTicketFn): void
1028
- /**
1029
- * 设置密码(已登录状态下,更新用户密码)
1030
- *
1031
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsetpassword}
1032
- *
1033
- */
1034
- setPassword(params: authModels.SetPasswordRequest): Promise<void>
1035
- /**
1036
- * 获取用户信息
1037
- * @deprecated 请使用 getCurrentUser 代替
1038
- *
1039
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetuserinfo}
1040
- */
1041
- getUserInfo(): Promise<IUserInfo>
1042
- /**
1043
- * 获取微搭插件用户信息
1044
- *
1045
- */
1046
- getWedaUserInfo(): Promise<any>
1047
- /**
1048
- * 更新用户基本信息
1049
- *
1050
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authupdateuserbasicinfo}
1051
- *
1052
- * @param params
1053
- */
1054
- updateUserBasicInfo(params: authModels.ModifyUserBasicInfoRequest): Promise<void>
1055
- /**
1056
- * 获取本地登录态-同步操作
1057
- *
1058
- * {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authhasloginstate}
1059
- *
1060
- * @example
1061
- * ```javascript
1062
- * const app = cloudbase.init({
1063
- * env: "xxxx-yyy"
1064
- * });
1065
- * const loginState = app.auth().hasLoginState();
1066
- * ```
1067
- *
1068
- * @return 登录态信息,如果未登录返回`null`
1069
- */
1070
- hasLoginState(): ILoginState | null
1071
- /**
1072
- * 获取本地登录态-异步操作
1073
- *
1074
- * {@link https://docs.cloudbase.net/api-reference/webv2/authentication.html#auth-getloginstate}
1075
- *
1076
- * @example
1077
- * ```javascript
1078
- * const app = cloudbase.init({
1079
- * env: "xxxx-yyy"
1080
- * });
1081
- * app.auth().getLoginState().then(loginState=>{
1082
- * // ...
1083
- * });
1084
- * ```
1085
- *
1086
- * @return Promise-登录态信息,如果未登录返回`null`
1087
- */
1088
- getLoginState(): Promise<ILoginState | null>
1089
- /**
1090
- * @deprecated
1091
- */
1092
- getAuthHeader(): {}
1093
- /**
1094
- * 为已有账户绑定第三方账户
1095
- *
1096
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authbindwithprovider}
1097
- */
1098
- bindWithProvider(params: authModels.BindWithProviderRequest): Promise<void>
1099
- /**
1100
- * 查询用户(自定义登录场景和匿名登录场景,不支持使用该接口查询用户信息)
1101
- *
1102
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authqueryuser}
1103
- *
1104
- */
1105
- queryUser(queryObj: authModels.QueryUserProfileRequest): Promise<authModels.QueryUserProfileResponse>
1106
- /**
1107
- * 获取当前登录用户的访问凭证
1108
- *
1109
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetaccesstoken}
1110
- */
1111
- getAccessToken(): Promise<{ accessToken: string; env: string }>
1112
- /**
1113
- * 提供第三方平台登录 token
1114
- *
1115
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgrantprovidertoken}
1116
- */
1117
- grantProviderToken(params: authModels.GrantProviderTokenRequest): Promise<authModels.GrantProviderTokenResponse>
1118
- patchProviderToken(params: authModels.PatchProviderTokenRequest): Promise<authModels.PatchProviderTokenResponse>
1119
- /**
1120
- * 第三方平台登录
1121
- *
1122
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsigninwithprovider}
1123
- */
1124
- signInWithProvider(params: authModels.SignInWithProviderRequest): Promise<ILoginState>
1125
- /**
1126
- * 微信登录
1127
- */
1128
- signInWithWechat(params?: any): Promise<ILoginState>
1129
- grantToken(params: authModels.GrantTokenRequest): Promise<ILoginState>
1130
- /**
1131
- * 生成第三方平台授权 Uri (如微信二维码扫码授权网页)
1132
- *
1133
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgenproviderredirecturi}
1134
- */
1135
- genProviderRedirectUri(
1136
- params: authModels.GenProviderRedirectUriRequest,
1137
- ): Promise<authModels.GenProviderRedirectUriResponse>
1138
- /**
1139
- * 重置密码(用户忘记密码无法登录时,可使用该接口强制设置密码)
1140
- *
1141
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authresetpassword}
1142
- */
1143
- resetPassword(params: authModels.ResetPasswordRequest): Promise<void>
1144
- deviceAuthorize(params: authModels.DeviceAuthorizeRequest): Promise<authModels.DeviceAuthorizeResponse>
1145
- /**
1146
- * 通过 sudo 接口获取高级操作权限,如修改用户密码,修改手机号,邮箱等操作
1147
- *
1148
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authsudo}
1149
- */
1150
- sudo(params: authModels.SudoRequest): Promise<authModels.SudoResponse>
1151
- /**
1152
- * 删除用户
1153
- *
1154
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authdeleteme}
1155
- */
1156
- deleteMe(params: authModels.WithSudoRequest): Promise<authModels.UserProfile>
1157
- /**
1158
- * 获取第三方绑定列表
1159
- *
1160
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetproviders}
1161
- */
1162
- getProviders(): Promise<authModels.UserProfileProvider>
1163
- /**
1164
- * 用于查询用户是否为匿名登录状态
1165
- *
1166
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authloginscope}
1167
- */
1168
- loginScope(): Promise<string>
1169
- loginGroups(): Promise<string[]>
1170
- onLoginStateChanged(callback: Function)
1171
- createLoginState(
1172
- params?: { version?: string; query?: any },
1173
- options?: { asyncRefreshUser?: boolean; userInfo?: any },
1174
- ): Promise<ILoginState>
1175
- /**
1176
- * 强制刷新token
1177
- *
1178
- * @param params
1179
- */
1180
- refreshTokenForce(params: { version?: string }): Promise<authModels.Credentials>
1181
- /**
1182
- * 获取身份信息
1183
- *
1184
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetcredentials}
1185
- */
1186
- getCredentials(): Promise<authModels.Credentials>
1187
- /**
1188
- * 写入身份信息
1189
- *
1190
- * @param credentials
1191
- */
1192
- setCredentials(credentials: authModels.Credentials): Promise<void>
1193
- /**
1194
- * 获取身份源类型
1195
- *
1196
- */
1197
- getProviderSubType(): Promise<authModels.ProviderSubType>
1198
- /**
1199
- * 创建验证码数据
1200
- *
1201
- * @param params
1202
- */
1203
- createCaptchaData(params: { state: string; redirect_uri?: string }): Promise<any>
1204
- /**
1205
- * 验证验证码数据
1206
- *
1207
- * @param params
1208
- */
1209
- verifyCaptchaData(params: { token: string; key: string }): Promise<any>
1210
- /**
1211
- * 修改密码
1212
- *
1213
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authmodifypassword}
1214
- *
1215
- * @param params
1216
- */
1217
- modifyPassword(params: authModels.ModifyUserBasicInfoRequest): Promise<void>
1218
- /**
1219
- * 未登录状态修改密码
1220
- *
1221
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authmodifypasswordwithoutlogin}
1222
- *
1223
- * @param params
1224
- */
1225
- modifyPasswordWithoutLogin(params: authModels.ModifyPasswordWithoutLoginRequest): Promise<void>
1226
- /**
1227
- * 获取用户行为日志
1228
- *
1229
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authgetuserbehaviorlog}
1230
- *
1231
- * @param params
1232
- */
1233
- getUserBehaviorLog(params: authModels.GetUserBehaviorLog): Promise<authModels.GetUserBehaviorLogRes>
1234
- /**
1235
- * 检查用户名是否被绑定过
1236
- *
1237
- * {@link https://docs.cloudbase.net/api-reference/webv2/authentication.html#authisusernameregistered}
1238
- *
1239
- * @example
1240
- * ```javascript
1241
- * const app = cloudbase.init({
1242
- * env: "xxxx-yyy"
1243
- * });
1244
- * const auth = app.auth();
1245
- * const username = "your_awesome_username";
1246
- * auth.isUsernameRegistered(username).then(registered=>{
1247
- * // ...
1248
- * });
1249
- * ```
1250
- *
1251
- * @param username 用户名
1252
- *
1253
- * @return Promise-用户是否被绑定
1254
- */
1255
- isUsernameRegistered(username: string): Promise<boolean>
1256
- getMiniProgramQrCode(
1257
- params: authModels.GetMiniProgramQrCodeRequest,
1258
- ): Promise<authModels.GetMiniProgramQrCodeResponse>
1259
- getMiniProgramQrCodeStatus(
1260
- params: authModels.GetMiniProgramQrCodeStatusRequest,
1261
- ): Promise<authModels.GetMiniProgramQrCodeStatusResponse>
1262
- /**
1263
- * 跳转到默认登录页
1264
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv2/authentication#authtodefaultloginpage}
1265
- * @param params
1266
- */
1267
- toDefaultLoginPage(params?: authModels.ToDefaultLoginPage): Promise<CommonRes>
1268
-
1269
- /**
1270
- * 退出登录
1271
- *
1272
- * {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signout}
1273
- *
1274
- * @example
1275
- * ```javascript
1276
- * const app = cloudbase.init({
1277
- * env: "xxxx-yyy"
1278
- * });
1279
- * app.auth.signOut().then(()=>{});
1280
- * ```
1281
- *
1282
- * @return Promise
1283
- */
1284
- signOut(params?: authModels.SignoutRequest): Promise<void | authModels.SignoutResponse>
1285
- /**
1286
- * 使用自定义登录 ticket 登录
1287
- *
1288
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithcustomticket}
1289
- *
1290
- * @param getTickFn
1291
- */
1292
- signInWithCustomTicket(getTickFn?: authModels.GetCustomSignTicketFn): Promise<ILoginState>
1293
- /**
1294
- * 用户登录,目前支持手机号,邮箱,用户名密码登录
1295
- *
1296
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signin}
1297
- */
1298
- signIn(params: authModels.SignInRequest): Promise<ILoginState>
1299
- /**
1300
- * 用户注册,目前支持手机号验证码注册,邮箱验证码注册
1301
- *
1302
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signup}
1303
- */
1304
- signUp(params: authModels.SignUpRequest): Promise<SignUpRes>
1305
- /**
1306
- * 监听认证状态变化
1307
- *
1308
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#onauthstatechange}
1309
- *
1310
- * @param callback
1311
- */
1312
- onAuthStateChange(callback: OnAuthStateChangeCallback): {
1313
- data: { subscription: { id: string; callback: Function; unsubscribe: () => void } }
1314
- }
1315
- /**
1316
- * 使用用户名和密码登录
1317
- *
1318
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithpassword}
1319
- *
1320
- * @param params
1321
- */
1322
- signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes>
1323
- /**
1324
- * 使用第三方平台 ID Token 登录
1325
- *
1326
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithidtoken}
1327
- *
1328
- * @param params
1329
- */
1330
- signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes>
1331
- /**
1332
- * 使用一次性密码(OTP)登录,支持手机号和邮箱两种方式。
1333
- *
1334
- * **注意**:手机号验证码登录需要在初始化时设置 `region: 'ap-shanghai'`。
1335
- *
1336
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithotp}
1337
- *
1338
- * @example
1339
- * ```typescript
1340
- * // 完整的手机号验证码登录流程
1341
- * import Cloudbase from '@cloudbase/js-sdk';
1342
- *
1343
- * // 第一步:初始化(region 必须为 ap-shanghai)
1344
- * const app = Cloudbase.init({
1345
- * env: 'your-env-id',
1346
- * region: 'ap-shanghai'
1347
- * });
1348
- * const auth = app.auth();
1349
- *
1350
- * // 第二步:发送验证码
1351
- * const { data, error } = await auth.signInWithOtp({ phone: '+8613800138000' });
1352
- * if (error) {
1353
- * console.error('发送验证码失败:', error.message);
1354
- * return;
1355
- * }
1356
- *
1357
- * // 第三步:用户输入验证码后,调用 verifyOtp 完成登录
1358
- * const { data: loginData, error: loginError } = await data.verifyOtp({
1359
- * token: userInputCode // 用户输入的验证码
1360
- * });
1361
- * if (loginError) {
1362
- * console.error('验证失败:', loginError.message);
1363
- * return;
1364
- * }
1365
- * console.log('登录成功:', loginData.user);
1366
- * ```
1367
- *
1368
- * @param params 登录参数,包含 email 或 phone(二选一)
1369
- */
1370
- signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes>
1371
- /**
1372
- * 校验第三方平台授权登录回调
1373
- *
1374
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#verifyoauth}
1375
- *
1376
- * @param params
1377
- */
1378
- verifyOAuth(params?: VerifyOAuthReq): Promise<SignInRes>
1379
- /**
1380
- * 生成第三方平台授权 Uri
1381
- *
1382
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithoauth}
1383
- *
1384
- * @param params
1385
- */
1386
- signInWithOAuth(params: SignInWithOAuthReq): Promise<SignInOAuthRes>
1387
- /**
1388
- * 获取当前访问令牌中的声明信息
1389
- *
1390
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#getclaims}
1391
- */
1392
- getClaims(): Promise<GetClaimsRes>
1393
- /**
1394
- * 通过邮箱重置密码
1395
- *
1396
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#resetpasswordforemail}
1397
- *
1398
- * @param emailOrPhone
1399
- * @param options
1400
- */
1401
- resetPasswordForEmail(emailOrPhone: string, options?: { redirectTo?: string }): Promise<ResetPasswordForEmailRes>
1402
- /**
1403
- * 通过旧密码重置密码
1404
- *
1405
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#resetpasswordforold}
1406
- *
1407
- * @param params
1408
- */
1409
- resetPasswordForOld(params: ResetPasswordForOldReq): Promise<SignInRes>
1410
- /**
1411
- * 验证一次性密码(OTP)
1412
- *
1413
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#verifyotp}
1414
- *
1415
- * @param params
1416
- */
1417
- verifyOtp(params: VerifyOtpReq): Promise<SignInRes>
1418
- /**
1419
- * 获取当前会话
1420
- *
1421
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#getsession}
1422
- */
1423
- getSession(): Promise<SignInRes>
1424
- /**
1425
- * 刷新会话
1426
- *
1427
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#refreshsession}
1428
- *
1429
- * @param refresh_token
1430
- */
1431
- refreshSession(refresh_token?: string): Promise<SignInRes>
1432
- /**
1433
- * 获取当前用户详细信息
1434
- *
1435
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#getuser}
1436
- */
1437
- getUser(): Promise<GetUserRes>
1438
- /**
1439
- * 刷新用户信息
1440
- *
1441
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#refreshuser}
1442
- */
1443
- refreshUser(): Promise<CommonRes>
1444
- /**
1445
- * 更新用户信息
1446
- *
1447
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#updateuser}
1448
- *
1449
- * @param params
1450
- */
1451
- updateUser(params: UpdateUserReq): Promise<GetUserRes | UpdateUserWithVerificationRes>
1452
- /**
1453
- * 获取已绑定的身份源
1454
- *
1455
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#getuseridentities}
1456
- */
1457
- getUserIdentities(): Promise<GetUserIdentitiesRes>
1458
- /**
1459
- * 绑定身份源到当前用户
1460
- *
1461
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#linkidentity}
1462
- *
1463
- * @param params
1464
- */
1465
- linkIdentity(params: LinkIdentityReq): Promise<LinkIdentityRes>
1466
- /**
1467
- * 解绑身份源
1468
- *
1469
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#unlinkidentity}
1470
- *
1471
- * @param params
1472
- */
1473
- unlinkIdentity(params: UnlinkIdentityReq): Promise<CommonRes>
1474
- /**
1475
- * 重新认证
1476
- *
1477
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#reauthenticate}
1478
- */
1479
- reauthenticate(): Promise<ReauthenticateRes>
1480
- /**
1481
- * 重新发送验证码
1482
- *
1483
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#resend}
1484
- *
1485
- * @param params
1486
- */
1487
- resend(params: ResendReq): Promise<ResendRes>
1488
- /**
1489
- * 使用 access_token 和 refresh_token 设置会话
1490
- *
1491
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#setsession}
1492
- *
1493
- * @param params
1494
- */
1495
- setSession(params: SetSessionReq): Promise<SignInRes>
1496
- /**
1497
- * 删除当前用户
1498
- *
1499
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#deleteuser}
1500
- *
1501
- * @param params
1502
- */
1503
- deleteUser(params: DeleteMeReq): Promise<CommonRes>
1504
- /**
1505
- * 小程序 openId 静默登录
1506
- *
1507
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithopenid}
1508
- *
1509
- * @param params
1510
- */
1511
- signInWithOpenId(params?: { useWxCloud?: boolean }): Promise<SignInRes>
1512
- /**
1513
- * 小程序手机号授权登录
1514
- *
1515
- * 文档 {@link https://docs.cloudbase.net/api-reference/webv3/authentication#signinwithphoneauth}
1516
- *
1517
- * @param params
1518
- */
1519
- signInWithPhoneAuth(params: { phoneCode: string }): Promise<SignInRes>
1520
-
1521
- // ========== v1 兼容 API ==========
1522
-
1523
- /**
1524
- * v1 API: 获取用于微信登录的 WeixinAuthProvider
1525
- *
1526
- * @deprecated 建议使用 auth.signInWithOAuth({ provider: appid }) 替代。
1527
- *
1528
- * @example
1529
- * ```javascript
1530
- * const provider = auth.weixinAuthProvider({ appid: 'wx-appid', scope: 'snsapi_login' });
1531
- * provider.signInWithRedirect();
1532
- * ```
1533
- *
1534
- * @param options
1535
- * @param options.appid 微信 AppID
1536
- * @param options.scope 微信授权范围
1537
- */
1538
- weixinAuthProvider(options: { appid: string; scope: string }): cloudbase.auth.WeixinAuthProvider
1539
-
1540
- /**
1541
- * v1 API: 获取用于自定义登录的 CustomAuthProvider
1542
- *
1543
- * @deprecated 建议使用 auth.signInWithCustomTicket(() => Promise.resolve(ticket)) 替代。
1544
- *
1545
- * @example
1546
- * ```javascript
1547
- * const provider = auth.customAuthProvider();
1548
- * await provider.signIn(ticket);
1549
- * ```
1550
- */
1551
- customAuthProvider(): cloudbase.auth.CustomAuthProvider
1552
-
1553
- /**
1554
- * v1 API: 获取用于匿名登录的 AnonymousAuthProvider
1555
- *
1556
- * @deprecated 建议使用 auth.signInAnonymously({}) 替代。
1557
- *
1558
- * @example
1559
- * ```javascript
1560
- * const provider = auth.anonymousAuthProvider();
1561
- * await provider.signIn();
1562
- * ```
1563
- */
1564
- anonymousAuthProvider(): cloudbase.auth.AnonymousAuthProvider
1565
-
1566
- /**
1567
- * v1 API: 使用邮箱和密码注册云开发账户
1568
- *
1569
- * @deprecated 建议使用 auth.signUp({ email, password }) 替代。
1570
- *
1571
- * @example
1572
- * ```javascript
1573
- * await auth.signUpWithEmailAndPassword('user@example.com', 'password123');
1574
- * ```
1575
- *
1576
- * @param email 邮箱
1577
- * @param password 密码
1578
- */
1579
- signUpWithEmailAndPassword(email: string, password: string): Promise<SignUpRes>
1580
-
1581
- /**
1582
- * v1 API: 使用邮箱和密码登录云开发(支持两种调用方式)
1583
- *
1584
- * @deprecated 建议使用 auth.signInWithPassword({ email, password }) 替代。
1585
- *
1586
- * @example
1587
- * ```javascript
1588
- * // 方式一(v1 风格):
1589
- * await auth.signInWithEmailAndPassword('user@example.com', 'password123');
1590
- *
1591
- * // 方式二(v3 风格):
1592
- * const { data, error } = await auth.signInWithEmailAndPassword({
1593
- * email: 'user@example.com',
1594
- * password: 'password123'
1595
- * });
1596
- * ```
1597
- *
1598
- * @param emailOrParams - 邮箱字符串(v1)或包含 email 和 password 的对象(v3)
1599
- * @param password - 密码(仅 v1 风格时使用)
1600
- */
1601
- signInWithEmailAndPassword(emailOrParams: string | { email: string; password: string; is_encrypt?: boolean }, password?: string): Promise<SignInRes | ILoginState>
1602
-
1603
- /**
1604
- * v1 API: 发送重置密码的邮件
1605
- *
1606
- * @deprecated 建议使用 auth.resetPasswordForEmail(email) 替代。
1607
- *
1608
- * @example
1609
- * ```javascript
1610
- * await auth.sendPasswordResetEmail('user@example.com');
1611
- * ```
1612
- *
1613
- * @param email 邮箱
1614
- */
1615
- sendPasswordResetEmail(email: string): Promise<void>
1616
-
1617
- /**
1618
- * v1 API: 使用用户名和密码登录云开发
1619
- *
1620
- * @deprecated 建议使用 auth.signInWithPassword({ username, password }) 替代。
1621
- *
1622
- * @example
1623
- * ```javascript
1624
- * const loginState = await auth.signInWithUsernameAndPassword('username', 'password123');
1625
- * ```
1626
- *
1627
- * @param username 用户名
1628
- * @param password 密码
1629
- */
1630
- signInWithUsernameAndPassword(username: string, password: string): Promise<ILoginState>
1631
-
1632
- /**
1633
- * v1 API: 发送手机验证码
1634
- *
1635
- * @deprecated 此方法仅发送验证码并返回布尔值,不返回 verifyOtp 回调。
1636
- * 推荐使用 v3 API `auth.signInWithOtp({ phone })` 替代,它会返回包含 `verifyOtp` 方法的对象,
1637
- * 可直接完成"发送验证码 → 用户输入 → 验证并登录"的完整流程。
1638
- *
1639
- * **迁移示例**:
1640
- * ```typescript
1641
- * // ❌ 旧方式 (v1)
1642
- * await auth.sendPhoneCode('+8613800138000');
1643
- * // 需要单独调用其他 API 验证
1644
- *
1645
- * // ✅ 新方式 (v3) - 完整的手机号验证码登录流程
1646
- * // 注意:初始化时必须设置 region: 'ap-shanghai'
1647
- * const app = Cloudbase.init({ env: 'your-env-id', region: 'ap-shanghai' });
1648
- * const auth = app.auth();
1649
- * const { data, error } = await auth.signInWithOtp({ phone: '+8613800138000' });
1650
- * if (error) throw error;
1651
- * // 用户输入验证码后调用 verifyOtp
1652
- * const { data: loginData, error: loginError } = await data.verifyOtp({ token: '123456' });
1653
- * console.log('登录成功', loginData.user);
1654
- * ```
1655
- *
1656
- * @param phoneNumber 手机号(需含国际区号,如 +86)
1657
- * @returns 是否发送成功
1658
- */
1659
- sendPhoneCode(phoneNumber: string): Promise<boolean>
1660
-
1661
- /**
1662
- * v1 API: 手机号注册(支持短信验证码+密码方式)
1663
- *
1664
- * @deprecated 建议使用 auth.signUp({ phone_number, verification_code, password? }) 替代。
1665
- *
1666
- * @example
1667
- * ```javascript
1668
- * const loginState = await auth.signUpWithPhoneCode('+8613800138000', '123456', 'password');
1669
- * ```
1670
- *
1671
- * @param phoneNumber 手机号
1672
- * @param phoneCode 验证码
1673
- * @param password 可选密码
1674
- */
1675
- signUpWithPhoneCode(phoneNumber: string, phoneCode: string, password?: string): Promise<ILoginState>
1676
-
1677
- /**
1678
- * v1 API: 手机号登录(支持短信验证码 or 密码方式)
1679
- *
1680
- * @deprecated 推荐使用 v3 API 替代:
1681
- * - 密码登录:`auth.signInWithPassword({ phone, password })`
1682
- * - 验证码登录:`auth.signInWithOtp({ phone })`
1683
- *
1684
- * **迁移示例**:
1685
- * ```typescript
1686
- * // ❌ 旧方式 (v1) - 验证码登录
1687
- * const loginState = await auth.signInWithPhoneCodeOrPassword({
1688
- * phoneNumber: '+8613800138000',
1689
- * phoneCode: '123456'
1690
- * });
1691
- *
1692
- * // ✅ 新方式 (v3) - 验证码登录
1693
- * const { data, error } = await auth.signInWithOtp({ phone: '+8613800138000' });
1694
- * if (error) throw error;
1695
- * const { data: result } = await data.verifyOtp({ token: '123456' });
1696
- *
1697
- * // ✅ 新方式 (v3) - 密码登录
1698
- * const { data, error } = await auth.signInWithPassword({
1699
- * phone: '+8613800138000',
1700
- * password: 'password123'
1701
- * });
1702
- * ```
1703
- *
1704
- * @param params
1705
- */
1706
- signInWithPhoneCodeOrPassword(params: {
1707
- phoneNumber: string
1708
- phoneCode?: string
1709
- password?: string
1710
- }): Promise<ILoginState>
1711
-
1712
- /**
1713
- * v1 API: 手机号强制重置密码
1714
- *
1715
- * @deprecated 建议使用 auth.resetPasswordForEmail(phoneNumber) 替代。
1716
- *
1717
- * @example
1718
- * ```javascript
1719
- * const loginState = await auth.forceResetPwdByPhoneCode({
1720
- * phoneNumber: '+8613800138000',
1721
- * phoneCode: '123456',
1722
- * password: 'newPassword'
1723
- * });
1724
- * ```
1725
- *
1726
- * @param params
1727
- */
1728
- forceResetPwdByPhoneCode(params: {
1729
- phoneNumber: string
1730
- phoneCode: string
1731
- password: string
1732
- }): Promise<ILoginState>
1733
-
1734
- /**
1735
- * v1 API: 接收一个回调函数,在刷新短期访问令牌前调用,根据返回值决定是否刷新
1736
- *
1737
- * @deprecated 建议使用 auth.onAuthStateChange(callback) 监听 TOKEN_REFRESHED 事件替代。
1738
- *
1739
- * @param callback 回调函数,返回 true 则刷新,返回 false 则不刷新
1740
- */
1741
- shouldRefreshAccessToken(callback: () => boolean): void
1742
-
1743
- /**
1744
- * v1 API: 接收一个回调函数,在登录状态过期时调用
1745
- *
1746
- * @deprecated 建议使用 auth.onAuthStateChange(callback) 替代,监听 SIGNED_OUT 事件。
1747
- *
1748
- * @param callback 登录态过期回调
1749
- */
1750
- onLoginStateExpired(callback: Function): void
1751
-
1752
- /**
1753
- * v1 API: 接收一个回调函数,在短期访问令牌刷新后调用
1754
- *
1755
- * @deprecated 建议使用 auth.onAuthStateChange(callback) 替代,监听 TOKEN_REFRESHED 事件。
1756
- *
1757
- * @param callback 令牌刷新回调
1758
- */
1759
- onAccessTokenRefreshed(callback: Function): void
1760
-
1761
- /**
1762
- * v1 API: 接收一个回调函数,在匿名登录状态被转换后调用
1763
- *
1764
- * @deprecated 建议使用 auth.onAuthStateChange(callback) 替代,监听 SIGNED_IN 事件。
1765
- *
1766
- * @param callback 匿名转正回调
1767
- */
1768
- onAnonymousConverted(callback: Function): void
1769
-
1770
- /**
1771
- * v1 API: 接收一个回调函数,在登录类型发生变化后调用
1772
- *
1773
- * @deprecated 建议使用 auth.onAuthStateChange(callback) 替代,监听 SIGNED_IN / SIGNED_OUT 事件。
1774
- *
1775
- * @param callback 登录类型变化回调
1776
- */
1777
- onLoginTypeChanged(callback: Function): void
1778
- }
1779
-
1780
- // ========== v1 兼容 Provider 类 ==========
1781
-
1782
- /**
1783
- * v1 微信登录 Provider
1784
- *
1785
- * @deprecated 建议使用 auth.signInWithOAuth({ provider }) 替代。
1786
- */
1787
- interface WeixinAuthProvider {
1788
- /**
1789
- * 跳转微信授权页面进行登录
1790
- * @deprecated 建议使用 auth.signInWithOAuth({ provider: 'providerId' }) 替代。
1791
- */
1792
- signInWithRedirect(): void
1793
- /**
1794
- * 获取微信授权重定向结果
1795
- * @deprecated 建议使用 auth.verifyOAuth({ code, state, provider }) 替代。
1796
- */
1797
- getRedirectResult(options?: { createUser?: boolean; syncUserInfo?: boolean }): Promise<any>
1798
- /**
1799
- * 获取微信绑定重定向结果
1800
- * @deprecated 建议使用 auth.linkIdentity({ provider: 'providerId' }) 替代。
1801
- */
1802
- getLinkRedirectResult(options?: { withUnionId?: boolean }): Promise<void>
1803
- }
1804
-
1805
- /**
1806
- * v1 自定义登录 Provider
1807
- *
1808
- * @deprecated 建议使用 auth.signInWithCustomTicket(() => Promise.resolve(ticket)) 替代。
1809
- */
1810
- interface CustomAuthProvider {
1811
- /**
1812
- * 使用自定义登录凭据 ticket 登录云开发
1813
- * @param ticket 自定义登录 ticket
1814
- * @deprecated 建议使用 auth.signInWithCustomTicket(() => Promise.resolve(ticket)) 替代。
1815
- */
1816
- signIn(ticket: string): Promise<void>
1817
- }
1818
-
1819
- /**
1820
- * v1 匿名登录 Provider
1821
- *
1822
- * @deprecated 建议使用 auth.signInAnonymously({}) 替代。
1823
- */
1824
- interface AnonymousAuthProvider {
1825
- /**
1826
- * 匿名登录云开发
1827
- * @deprecated 建议使用 auth.signInAnonymously({}) 替代。
1828
- */
1829
- signIn(): Promise<void>
1830
- }
1831
- }
1832
3
  /**
1833
- * functions
4
+ * Web / 浏览器(默认)环境类型入口。
5
+ *
6
+ * 仅聚合共享类型定义(core.d.ts),不包含任何 Node.js 专属定义。
7
+ * Node.js 环境请使用 `index.node.d.ts`(通过 package.json 的 exports.node.types 自动解析)。
1834
8
  */
1835
- declare namespace cloudbase.functions {
1836
- interface ICallFunctionOptions {
1837
- name: string
1838
- data?: KV<any>
1839
- query?: KV<any>
1840
- search?: string
1841
- parse?: boolean
1842
- }
1843
-
1844
- interface ICallFunctionResponse {
1845
- requestId: string
1846
- result: any
1847
- }
1848
- }
1849
- /**
1850
- * storage
1851
- */
1852
- declare namespace cloudbase.storage {
1853
- interface ICloudbaseUploadFileParams {
1854
- cloudPath: string
1855
- filePath?: string
1856
- method?: 'post' | 'put'
1857
- headers?: KV<string>
1858
- onUploadProgress?: Function
1859
- // 文件内容 Buffer 或 文件可读流, node端使用
1860
- fileContent?: any
1861
- customReqOpts?: ICustomReqOpts
1862
- }
1863
- interface ICloudbaseUploadFileResult {
1864
- fileID: string
1865
- requestId: string
1866
- }
1867
- interface ICloudbaseGetUploadMetadataParams {
1868
- cloudPath: string
1869
- customReqOpts?: ICustomReqOpts
1870
- }
1871
- interface ICloudbaseDeleteFileParams {
1872
- fileList: string[]
1873
- customReqOpts?: ICustomReqOpts
1874
- }
1875
- interface ICloudbaseDeleteFileResult {
1876
- code?: string
1877
- message?: string
1878
- fileList?: {
1879
- code?: string
1880
- fileID: string
1881
- }[]
1882
- requestId?: string
1883
- }
1884
-
1885
- interface ICloudbaseFileInfo {
1886
- fileID: string
1887
- maxAge: number
1888
- }
1889
-
1890
- interface ICloudbaseGetTempFileURLParams {
1891
- fileList: string[] | ICloudbaseFileInfo[]
1892
- customReqOpts?: ICustomReqOpts
1893
- }
1894
-
1895
- interface ICloudbaseGetTempFileURLResult {
1896
- code?: string
1897
- message?: string
1898
- fileList?: {
1899
- code?: string
1900
- message?: string
1901
- fileID: string
1902
- tempFileURL: string
1903
- download_url?: string
1904
- }[]
1905
- requestId?: string
1906
- }
1907
- interface ICloudbaseDownloadFileParams {
1908
- fileID: string
1909
- tempFilePath?: string
1910
- customReqOpts?: ICustomReqOpts
1911
- }
1912
- interface ICloudbaseDownloadFileResult {
1913
- code?: string
1914
- message?: string
1915
- fileContent?: any
1916
- requestId?: string
1917
- }
1918
- interface ICloudbaseFileMetaData {
1919
- url: string
1920
- token: string
1921
- authorization: string
1922
- fileId: string
1923
- cosFileId: string
1924
- download_url: string
1925
- }
1926
-
1927
- interface ICloudbaseFileMetaDataRes {
1928
- data: ICloudbaseFileMetaData
1929
- requestId: string
1930
- }
1931
-
1932
- interface ICloudbaseCopyFileParams {
1933
- fileList: Array<{
1934
- srcPath: string
1935
- dstPath: string
1936
- overwrite?: boolean
1937
- removeOriginal?: boolean
1938
- }>
1939
- customReqOpts?: ICustomReqOpts
1940
- }
1941
-
1942
- interface ICloudbaseCopyFileResult {
1943
- fileList: Array<{
1944
- fileId?: string
1945
- code?: string
1946
- message?: string
1947
- }>
1948
- requestId?: string
1949
- }
1950
-
1951
- interface ICloudbaseGetFileInfoResultItem {
1952
- code?: string
1953
- message?: string
1954
- fileID: string
1955
- tempFileURL: string
1956
- fileName?: string
1957
- cloudId?: string
1958
- contentType?: string
1959
- mime?: string
1960
- size?: number
1961
- cacheControl?: string
1962
- lastModified?: string
1963
- etag?: string
1964
- }
1965
-
1966
- interface ICloudbaseGetFileInfoResult {
1967
- fileList: ICloudbaseGetFileInfoResultItem[]
1968
- requestId: string
1969
- }
1970
-
1971
- // ---- Supabase-like Storage Types ----
1972
-
1973
- /** Node.js 风格可读流的最小兼容类型,避免依赖 `@types/node`。 */
1974
- interface NodeReadableStreamLike {
1975
- /** 将当前流管道输出到目标流。 */
1976
- pipe(destination: any, options?: any): any
1977
- }
1978
-
1979
- /**
1980
- * Node.js `Buffer` 的兼容类型。
1981
- *
1982
- * 在安装了 `@types/node` 的项目中解析为 `Buffer`,未安装时退化为 `never`,
1983
- * 从而既能让 Node 端继续显式传入 `Buffer`,又不会让纯浏览器项目因缺少
1984
- * `@types/node` 而报“找不到名称 Buffer”,避免对 `@types/node` 的硬依赖。
1985
- */
1986
- type MaybeNodeBuffer = typeof globalThis extends { Buffer: new (...args: any[]) => infer B } ? B : never
1987
-
1988
- /**
1989
- * 可上传的文件内容类型。
1990
- *
1991
- * @remarks
1992
- * - Node.js `Buffer`:通过 `MaybeNodeBuffer` 兼容(装有 `@types/node` 时可直接传入);
1993
- * 即便未装 `@types/node`,`Buffer` 仍可作为 `ArrayBufferView` / `Uint8Array` 传入。
1994
- * - Node.js 可读流(如 `NodeJS.ReadableStream` / `fs.ReadStream`):可作为 `NodeReadableStreamLike` 传入。
1995
- */
1996
- type FileBody =
1997
- | ArrayBuffer
1998
- | ArrayBufferView
1999
- | Blob
2000
- | File
2001
- | FormData
2002
- | MaybeNodeBuffer
2003
- | NodeReadableStreamLike
2004
- | ReadableStream<Uint8Array>
2005
- | URLSearchParams
2006
- | string
2007
-
2008
- /** 上传 / 覆盖对象选项。 */
2009
- interface FileOptions {
2010
- /** 缓存时间,单位为秒;会转换为 `Cache-Control: max-age=<seconds>`。 */
2011
- cacheControl?: string
2012
- /** 文件 MIME 类型;当 `fileBody` 不是 `Blob` / `File` / `FormData` 时建议显式指定。 */
2013
- contentType?: string
2014
- /** 是否允许覆盖同名对象。 */
2015
- upsert?: boolean
2016
- /** 透传给底层 `fetch` 的 duplex 配置,用于流式请求场景。 */
2017
- duplex?: string
2018
- /** 用户自定义元数据。 */
2019
- metadata?: Record<string, any>
2020
- /** 额外请求头。 */
2021
- headers?: Record<string, string>
2022
- }
2023
-
2024
- /** 图片转换选项。 */
2025
- interface TransformOptions {
2026
- /** 图片宽度,单位为像素。 */
2027
- width?: number
2028
- /** 图片高度,单位为像素。 */
2029
- height?: number
2030
- /** 缩放模式:`cover` 保持比例裁剪填满;`contain` 保持比例完整适配;`fill` 拉伸填满。 */
2031
- resize?: 'cover' | 'contain' | 'fill'
2032
- /** 图片质量,通常取值 20 到 100,数值越大质量越高。 */
2033
- quality?: number
2034
- /** 输出格式;`origin` 表示保持原图格式。 */
2035
- format?: 'origin'
2036
- }
2037
-
2038
- interface FileObject {
2039
- name: string
2040
- bucket_id: string
2041
- owner: string
2042
- id: string
2043
- updated_at: string
2044
- created_at: string
2045
- /** @deprecated */
2046
- last_accessed_at: string
2047
- metadata: Record<string, any>
2048
- buckets: {
2049
- id: string
2050
- name: string
2051
- owner: string
2052
- public: boolean
2053
- created_at: string
2054
- updated_at: string
2055
- }
2056
- }
2057
-
2058
- interface FileObjectV2 {
2059
- id: string
2060
- version: string
2061
- name: string
2062
- bucketId: string
2063
- updatedAt: string
2064
- createdAt: string
2065
- /** @deprecated */
2066
- lastAccessedAt: string
2067
- size?: number
2068
- cacheControl?: string
2069
- contentType?: string
2070
- etag?: string
2071
- lastModified?: string
2072
- metadata?: Record<string, any>
2073
- }
2074
-
2075
- class StorageError extends Error {
2076
- name: 'StorageError'
2077
- constructor(message: string)
2078
- }
2079
-
2080
- /**
2081
- * Supabase 风格的文件存储 API
2082
- *
2083
- * 通过 `app.storage` 获取实例,提供类似 Supabase Storage 的操作接口。
2084
- *
2085
- * @example
2086
- * ```typescript
2087
- * const app = cloudbase.init({ env: 'your-envid' })
2088
- * const bucket = app.storage.from('my-bucket')
2089
- *
2090
- * // 上传文件
2091
- * const { data, error } = await bucket.upload('path/to/file.jpg', file)
2092
- *
2093
- * // 获取签名 URL
2094
- * const { data } = await bucket.createSignedUrl('path/to/file.jpg', 3600)
2095
- *
2096
- * // 下载文件
2097
- * const { data } = await bucket.download('path/to/file.jpg')
2098
- * ```
2099
- */
2100
- interface ClassicStorageFileApi {
2101
- /**
2102
- * 启用错误抛出模式,而非返回 `{ data: null, error }` 格式
2103
- */
2104
- throwOnError(): this
2105
-
2106
- /**
2107
- * 上传文件
2108
- *
2109
- * @param path 文件路径
2110
- * @param fileBody 文件内容
2111
- * @param fileOptions 上传选项
2112
- */
2113
- upload(
2114
- path: string,
2115
- fileBody: FileBody,
2116
- fileOptions?: FileOptions,
2117
- ): Promise<
2118
- | { data: { id: string; path: string; fullPath: string }; error: null }
2119
- | { data: null; error: StorageError }
2120
- >
2121
-
2122
- /**
2123
- * 上传文件到已签名的 URL
2124
- *
2125
- * @param path 文件路径
2126
- * @param token 签名 Token
2127
- * @param fileBody 文件内容
2128
- * @param fileOptions 上传选项
2129
- */
2130
- uploadToSignedUrl(
2131
- path: string,
2132
- token: string,
2133
- fileBody: FileBody,
2134
- fileOptions?: FileOptions,
2135
- ): Promise<
2136
- | { data: { id: string; path: string; fullPath: string }; error: null }
2137
- | { data: null; error: StorageError }
2138
- >
2139
-
2140
- /**
2141
- * 创建用于上传的签名 URL
2142
- *
2143
- * @param path 文件路径
2144
- */
2145
- createSignedUploadUrl(path: string): Promise<
2146
- | {
2147
- data: {
2148
- signedUrl: string
2149
- token: string
2150
- path: string
2151
- authorization?: string
2152
- id?: string
2153
- cosFileId?: string
2154
- downloadUrl?: string
2155
- }
2156
- error: null
2157
- }
2158
- | { data: null; error: StorageError }
2159
- >
2160
-
2161
- /**
2162
- * 更新(覆盖)文件
2163
- *
2164
- * @param path 文件路径
2165
- * @param fileBody 文件内容
2166
- * @param fileOptions 上传选项
2167
- */
2168
- update(
2169
- path: string,
2170
- fileBody: FileBody,
2171
- fileOptions?: FileOptions,
2172
- ): Promise<
2173
- | { data: { id: string; path: string; fullPath: string }; error: null }
2174
- | { data: null; error: StorageError }
2175
- >
2176
-
2177
- /**
2178
- * 移动文件(复制后删除源文件)
2179
- *
2180
- * @param fromPath 源文件路径
2181
- * @param toPath 目标文件路径
2182
- */
2183
- move(
2184
- fromPath: string,
2185
- toPath: string,
2186
- ): Promise<
2187
- | { data: { message: string }; error: null }
2188
- | { data: null; error: StorageError }
2189
- >
2190
-
2191
- /**
2192
- * 复制文件
2193
- *
2194
- * @param fromPath 源文件路径
2195
- * @param toPath 目标文件路径
2196
- */
2197
- copy(
2198
- fromPath: string,
2199
- toPath: string,
2200
- ): Promise<
2201
- | { data: { path: string }; error: null }
2202
- | { data: null; error: StorageError }
2203
- >
2204
-
2205
- /**
2206
- * 创建签名下载 URL
2207
- *
2208
- * @param path 文件路径
2209
- * @param expiresIn 有效期(秒)
2210
- * @param options 可选配置
2211
- */
2212
- createSignedUrl(
2213
- path: string,
2214
- expiresIn: number,
2215
- options?: {
2216
- download?: string | boolean
2217
- transform?: TransformOptions
2218
- },
2219
- ): Promise<
2220
- | { data: { signedUrl: string }; error: null }
2221
- | { data: null; error: StorageError }
2222
- >
2223
-
2224
- /**
2225
- * 批量创建签名下载 URL
2226
- *
2227
- * @param paths 文件路径数组
2228
- * @param expiresIn 有效期(秒)
2229
- */
2230
- createSignedUrls(
2231
- paths: string[],
2232
- expiresIn: number,
2233
- ): Promise<
2234
- | { data: Array<{ path: string; signedUrl: string; error: string | null }>; error: null }
2235
- | { data: null; error: StorageError }
2236
- >
2237
-
2238
- /**
2239
- * 下载文件,返回 Blob
2240
- *
2241
- * @param path 文件路径
2242
- * @param options 图片转换选项
2243
- */
2244
- download(
2245
- path: string,
2246
- options?: TransformOptions,
2247
- ): Promise<{ data: Blob; error: StorageError | null }>
2248
-
2249
- /**
2250
- * 获取文件详细信息
2251
- *
2252
- * @param pathOrFileId 相对路径或 CloudBase fileID
2253
- */
2254
- info(pathOrFileId: string): Promise<
2255
- | { data: FileObjectV2; error: null }
2256
- | { data: null; error: StorageError }
2257
- >
2258
-
2259
- /**
2260
- * 检查文件是否存在
2261
- *
2262
- * @param pathOrFileId 相对路径或 CloudBase fileID
2263
- */
2264
- exists(pathOrFileId: string): Promise<
2265
- | { data: boolean; error: null }
2266
- | { data: null; error: StorageError }
2267
- >
2268
-
2269
- /**
2270
- * 获取文件的公开 URL
2271
- *
2272
- * @param path 文件路径
2273
- * @param options 可选配置
2274
- */
2275
- getPublicUrl(
2276
- path: string,
2277
- options?: {
2278
- download?: string | boolean
2279
- transform?: TransformOptions
2280
- },
2281
- ): Promise<
2282
- | { data: { publicUrl: string } }
2283
- | { data: null; error: StorageError }
2284
- >
2285
-
2286
- /**
2287
- * 批量删除文件
2288
- *
2289
- * @param paths 文件路径数组
2290
- */
2291
- remove(paths: string[]): Promise<
2292
- | { data: FileObject[]; error: null }
2293
- | { data: null; error: StorageError }
2294
- >
2295
- }
2296
-
2297
- /**
2298
- * Bucket 管理 API,挂载在 `app.storage` 上。
2299
- *
2300
- * @remarks 权限由 `storage.buckets` 的 RLS Policy 决定。暂不提供
2301
- * `emptyBucket()`、`headBucket()`、Bucket CORS、Bucket ACL 等 COS/S3 风格 Bucket 管理 API。
2302
- */
2303
- interface StorageBucketApi {
2304
- /**
2305
- * 启用错误抛出模式。开启后请求失败会抛异常;请求成功仍返回 `{ data, error: null }`。
2306
- * 该设置会传递给 `from()` 返回的客户端。
2307
- */
2308
- throwOnError(): this
2309
-
2310
- /**
2311
- * 获取 Bucket 列表,支持偏移分页、排序和搜索。
2312
- *
2313
- * @param options 查询参数:`limit`、`offset`、`sortColumn`、`sortOrder`、`search`。
2314
- */
2315
- listBuckets(options?: ListBucketOptions): Promise<
2316
- | { data: Bucket[]; error: null }
2317
- | { data: null; error: StorageError }
2318
- >
2319
-
2320
- /**
2321
- * 获取指定 Bucket 详情。
2322
- *
2323
- * @param bucketId Bucket ID。
2324
- */
2325
- getBucket(bucketId: string): Promise<
2326
- | { data: Bucket; error: null }
2327
- | { data: null; error: StorageError }
2328
- >
2329
-
2330
- /**
2331
- * 创建 Bucket。
2332
- *
2333
- * @param bucketId Bucket ID,同时作为后端 `id` 与 `name` 传入。
2334
- * @param options 创建参数:`public`、`fileSizeLimit`、`allowedMimeTypes`、`type`。
2335
- * @remarks `public` 默认 `false`。
2336
- */
2337
- createBucket(bucketId: string, options?: CreateBucketOptions): Promise<
2338
- | { data: { name: string }; error: null }
2339
- | { data: null; error: StorageError }
2340
- >
2341
-
2342
- /**
2343
- * 更新 Bucket 配置。
2344
- *
2345
- * @param bucketId Bucket ID。
2346
- * @param options 更新参数:`public`、`fileSizeLimit`、`allowedMimeTypes`。不支持更新 `type`。
2347
- */
2348
- updateBucket(bucketId: string, options: UpdateBucketOptions): Promise<
2349
- | { data: { message: string }; error: null }
2350
- | { data: null; error: StorageError }
2351
- >
2352
-
2353
- /**
2354
- * 删除空 Bucket。
2355
- *
2356
- * @param bucketId Bucket ID。
2357
- * @remarks Bucket 非空时后端会返回错误。
2358
- */
2359
- deleteBucket(bucketId: string): Promise<
2360
- | { data: { message: string }; error: null }
2361
- | { data: null; error: StorageError }
2362
- >
2363
- }
2364
-
2365
- /**
2366
- * `app.storage` 命名空间(分流器)。继承 `StorageBucketApi` 的 Bucket 管理能力,并提供 `from()` 分流。
2367
- *
2368
- * `from()` 分流到两个**对等且独立**的客户端——`ClassicStorageFileApi`(传统环境)
2369
- * 与 `StorageFileApi`(针对全新的 Neo 环境)。
2370
- *
2371
- * - `from()`:返回 `ClassicStorageFileApi`;
2372
- * - `from(bucketId)`:返回 `StorageFileApi`。
2373
- */
2374
- interface StorageClient extends StorageBucketApi {
2375
- /**
2376
- * 进入对象操作客户端。
2377
- *
2378
- * - `from()`(不传 bucketId):返回传统环境对象操作客户端;
2379
- * - `from(bucketId)`:返回 Neo 环境对象操作(`bucketId + objectName` 语义)客户端。
2380
- *
2381
- * @remarks 传入 `bucketId` 时返回的客户端仅 Neo 环境可用。
2382
- *
2383
- * @example
2384
- * ```typescript
2385
- * // 传统环境
2386
- * const file = app.storage.from()
2387
- * // Neo 环境
2388
- * const avatars = app.storage.from('avatars')
2389
- * ```
2390
- */
2391
- from(): ClassicStorageFileApi
2392
- from<B extends string>(bucketId: B): StorageFileApi
2393
- }
2394
-
2395
- // ==================== Storage 类型 ====================
2396
- // 以下类型通过 app.storage.from(bucketId) 与 Bucket 管理 API 暴露。
2397
-
2398
- type BucketType = 'STANDARD'
2399
-
2400
- /** Bucket 资源(对应 storage.buckets 表记录)。 */
2401
- interface Bucket {
2402
- /** Bucket ID。 */
2403
- id: string
2404
- /** Bucket 名称。 */
2405
- name: string
2406
- /** 创建者用户 ID;可能为空。 */
2407
- owner_id?: string | null
2408
- /** 是否为公开 Bucket。 */
2409
- public: boolean
2410
- /** Bucket 类型。 */
2411
- type?: BucketType
2412
- /** 文件大小限制,单位为字节;`null` 表示不限制。 */
2413
- file_size_limit?: number | null
2414
- /** 允许上传的 MIME 类型列表;`null` 表示不限制。 */
2415
- allowed_mime_types?: string[] | null
2416
- /** 创建时间,ISO 8601 日期时间字符串。 */
2417
- created_at: string
2418
- /** 更新时间,ISO 8601 日期时间字符串。 */
2419
- updated_at: string
2420
- }
2421
-
2422
- interface ListBucketOptions {
2423
- /** 返回数量限制。 */
2424
- limit?: number
2425
- /** 分页偏移量。 */
2426
- offset?: number
2427
- /** 排序字段。 */
2428
- sortColumn?: 'id' | 'name' | 'created_at' | 'updated_at'
2429
- /** 排序方向。 */
2430
- sortOrder?: 'asc' | 'desc'
2431
- /** 搜索关键词。 */
2432
- search?: string
2433
- }
2434
-
2435
- interface CreateBucketOptions {
2436
- /** 是否公开,默认 `false`。 */
2437
- public?: boolean
2438
- /** 文件大小限制;数字按字节处理,字符串支持如 `100MB`,`null` 表示不限制。 */
2439
- fileSizeLimit?: number | string | null
2440
- /** 允许上传的 MIME 类型列表,`null` 表示不限制。 */
2441
- allowedMimeTypes?: string[] | null
2442
- /** Bucket 类型,仅创建时可传。 */
2443
- type?: BucketType
2444
- }
2445
-
2446
- interface UpdateBucketOptions {
2447
- /** 是否公开。 */
2448
- public?: boolean
2449
- /** 文件大小限制;数字按字节处理,字符串支持如 `100MB`,`null` 表示不限制。 */
2450
- fileSizeLimit?: number | string | null
2451
- /** 允许上传的 MIME 类型列表,`null` 表示不限制。 */
2452
- allowedMimeTypes?: string[] | null
2453
- }
2454
-
2455
- /** 上传选项。 */
2456
- type UploadOptions = FileOptions
2457
-
2458
- interface UploadResult {
2459
- /** 对象 UUID(后端 `Id`)。 */
2460
- id: string
2461
- /** Bucket 内相对路径。 */
2462
- path: string
2463
- /** 对象完整路径 `bucketId/objectName`(后端 `Key`)。 */
2464
- fullPath: string
2465
- }
2466
-
2467
- interface DownloadOptions {
2468
- /** 触发浏览器下载,传字符串作为下载文件名。 */
2469
- download?: string | boolean
2470
- /** 缓存失效 nonce,追加到请求 URL 以绕过 CDN 缓存。 */
2471
- cacheNonce?: string
2472
- }
2473
-
2474
- interface ListOptions {
2475
- /** 返回数量限制。 */
2476
- limit?: number
2477
- /** 翻页游标,由上一页响应的 `nextCursor` 提供。 */
2478
- cursor?: string
2479
- /** 是否使用 `/` 作为分隔符区分文件夹。 */
2480
- withDelimiter?: boolean
2481
- /** 排序配置。 */
2482
- sortBy?: {
2483
- /** 排序字段。 */
2484
- column?: 'name' | 'created_at' | 'updated_at'
2485
- /** 排序方向。 */
2486
- order?: 'asc' | 'desc'
2487
- }
2488
- }
2489
-
2490
- interface ListObjectsEntry {
2491
- /** 对象完整 key;文件夹条目可能为空。 */
2492
- key?: string | null
2493
- /** 对象名或文件夹名。 */
2494
- name: string
2495
- /** 对象 UUID;文件夹条目可能为空。 */
2496
- id?: string | null
2497
- /** 更新时间,ISO 8601 日期时间字符串。 */
2498
- updated_at?: string | null
2499
- /** 创建时间,ISO 8601 日期时间字符串。 */
2500
- created_at?: string | null
2501
- /** 最后访问时间,ISO 8601 日期时间字符串。 */
2502
- last_accessed_at?: string | null
2503
- /** 对象元数据。 */
2504
- metadata?: Record<string, any> | null
2505
- }
2506
-
2507
- interface ListObjectsResponse {
2508
- /** 当前前缀下的文件夹条目。 */
2509
- folders: ListObjectsEntry[]
2510
- /** 当前前缀下的对象条目。 */
2511
- objects: ListObjectsEntry[]
2512
- /** 是否还有下一页。 */
2513
- hasNext: boolean
2514
- /** 下一页游标。 */
2515
- nextCursor?: string
2516
- /** 下一页起始 key。 */
2517
- nextCursorKey?: string
2518
- }
2519
-
2520
- interface ObjectInfo {
2521
- /** 对象 UUID。 */
2522
- id: string
2523
- /** Bucket 内相对路径。 */
2524
- name: string
2525
- /** 对象版本标识;可能为空。 */
2526
- version?: string | null
2527
- /** 所属 Bucket ID。 */
2528
- bucketId: string
2529
- /** 文件大小,单位为字节;可能为空。 */
2530
- size?: number | null
2531
- /** 文件 MIME 类型;可能为空。 */
2532
- contentType?: string | null
2533
- /** 缓存控制信息;可能为空。 */
2534
- cacheControl?: string | null
2535
- /** 对象 ETag;可能为空。 */
2536
- etag?: string | null
2537
- /** 用户自定义元数据。 */
2538
- metadata?: Record<string, any>
2539
- /** 最后修改时间,ISO 8601 日期时间字符串。 */
2540
- lastModified?: string | null
2541
- /** 创建时间,ISO 8601 日期时间字符串。 */
2542
- createdAt?: string | null
2543
- }
2544
-
2545
- interface FullObject {
2546
- /** Bucket 内相对路径。 */
2547
- name: string
2548
- /** 所属 Bucket ID。 */
2549
- bucket_id: string
2550
- /** 创建者用户 ID;可能为空。 */
2551
- owner_id?: string | null
2552
- /** 对象版本标识;可能为空。 */
2553
- version?: string | null
2554
- /** 对象 UUID;可能为空。 */
2555
- id?: string | null
2556
- /** 更新时间,ISO 8601 日期时间字符串。 */
2557
- updated_at?: string | null
2558
- /** 创建时间,ISO 8601 日期时间字符串。 */
2559
- created_at?: string | null
2560
- /** 最后访问时间,ISO 8601 日期时间字符串。 */
2561
- last_accessed_at?: string | null
2562
- /** 系统或对象元数据。 */
2563
- metadata?: Record<string, any>
2564
- /** 用户自定义元数据。 */
2565
- user_metadata?: Record<string, any>
2566
- }
2567
-
2568
- interface DestinationOptions {
2569
- /** 目标 Bucket ID,默认与源相同。 */
2570
- destinationBucket?: string
2571
- /** 允许覆盖目标位置已有对象。 */
2572
- upsert?: boolean
2573
- /** 是否复制源对象元数据,默认 true。 */
2574
- copyMetadata?: boolean
2575
- /** `copyMetadata=false` 时合并到目标对象的用户元数据。 */
2576
- metadata?: Record<string, any>
2577
- }
2578
-
2579
- interface SignedUrlOptions {
2580
- /** 触发浏览器下载,传字符串作为下载文件名。 */
2581
- download?: string | boolean
2582
- /** 缓存失效 nonce,追加到请求 URL 以绕过 CDN 缓存。 */
2583
- cacheNonce?: string
2584
- }
2585
-
2586
- /** 公开 URL 选项。 */
2587
- interface PublicUrlOptions {
2588
- /** 触发浏览器下载,传字符串作为下载文件名。 */
2589
- download?: string | boolean
2590
- /** 缓存失效 nonce,追加到请求 URL 以绕过 CDN 缓存。 */
2591
- cacheNonce?: string
2592
- }
2593
-
2594
- /**
2595
- * 请求级 fetch 控制参数(对齐 Supabase `FetchParameters`)。
2596
- *
2597
- * 纯客户端能力:`signal` 用于取消请求;`cache` 透传给底层 fetch 的缓存策略
2598
- * (主要在浏览器 fetch 路径生效,XHR / 部分运行时会忽略)。
2599
- */
2600
- interface FetchParameters {
2601
- /** 请求取消信号。 */
2602
- signal?: AbortSignal
2603
- /** 透传给底层 `fetch` 的缓存策略。 */
2604
- cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache' | 'only-if-cached'
2605
- }
2606
-
2607
- /**
2608
- * 流式下载构建器(thenable)。`await` 后 resolve 为 `Result<ReadableStream>`。
2609
- * 由 `DownloadBuilder.asStream()` 创建。
2610
- */
2611
- interface StreamDownloadBuilder extends PromiseLike<
2612
- | { data: ReadableStream<Uint8Array>; error: null }
2613
- | { data: null; error: StorageError }
2614
- > {}
2615
-
2616
- /**
2617
- * 下载构建器(thenable)。默认 `await` 得 `Result<Blob>`;`.asStream()` 切换为流式终态。
2618
- * 惰性执行:请求在 `await` / `.then()` 时才真正发出。
2619
- */
2620
- interface DownloadBuilder extends PromiseLike<
2621
- | { data: Blob; error: null }
2622
- | { data: null; error: StorageError }
2623
- > {
2624
- /** 切换为流式下载终态,返回 `StreamDownloadBuilder`。 */
2625
- asStream(): StreamDownloadBuilder
2626
- }
2627
-
2628
- /**
2629
- * 单 Bucket 对象操作客户端。通过 `app.storage.from(bucketId)` 获取。
2630
- *
2631
- * @remarks 所有 `objectName` 均为 Bucket 内相对路径。
2632
- */
2633
- interface StorageFileApi {
2634
- /** 当前客户端绑定的 Bucket ID。 */
2635
- readonly bucketId: string
2636
-
2637
- /**
2638
- * 启用错误抛出模式。开启后请求失败会抛异常;请求成功仍返回 `{ data, error: null }`。
2639
- */
2640
- throwOnError(): this
2641
-
2642
- /**
2643
- * 设置自定义请求头(链式)。
2644
- *
2645
- * @remarks 设置后对当前实例后续所有请求生效;每个 `from(bucketId)` 返回独立实例,互不影响。
2646
- * 单次请求内部的功能性头(如上传的 `Content-Type` / `x-upsert`)优先级更高,会覆盖此处同名头。
2647
- * name 为空或 name/value 含 CR/LF 时抛 `StorageError`。
2648
- */
2649
- setHeader(name: string, value: string): this
2650
-
2651
- /**
2652
- * 直接上传对象,默认不覆盖同名对象。
2653
- *
2654
- * 需要当前用户已登录,权限由 `storage.objects` 的 RLS `INSERT` / `UPDATE` 策略判定。
2655
- *
2656
- * 上传行为:
2657
- * - `options.upsert` 默认 `false`:目标路径已有对象时,上传失败。
2658
- * - `options.upsert` 设为 `true`:目标路径已有对象时,覆盖写入。
2659
- * - 成功时返回 `{ id, path, fullPath }`。
2660
- *
2661
- * @param path Bucket 内相对路径。
2662
- * @param fileBody 文件内容。
2663
- * @param fileOptions 上传选项,如 `contentType`、`cacheControl`、`upsert`、`metadata`。
2664
- * @see createSignedUploadUrl uploadToSignedUrl
2665
- */
2666
- upload(path: string, fileBody: FileBody, fileOptions?: UploadOptions): Promise<
2667
- | { data: UploadResult; error: null }
2668
- | { data: null; error: StorageError }
2669
- >
2670
-
2671
- /**
2672
- * 覆盖更新对象。
2673
- *
2674
- * 与 `upload` 共享同一底层,区别:
2675
- * - 使用 `PUT` 方法(语义为覆盖)。
2676
- * - 目标路径不存在时也会创建(upsert 行为)。
2677
- *
2678
- * @param path Bucket 内相对路径。
2679
- * @param fileBody 文件内容。
2680
- * @param fileOptions 上传选项,如 `contentType`、`cacheControl`、`metadata`。
2681
- */
2682
- update(path: string, fileBody: FileBody, fileOptions?: UploadOptions): Promise<
2683
- | { data: UploadResult; error: null }
2684
- | { data: null; error: StorageError }
2685
- >
2686
-
2687
- /**
2688
- * 下载对象。返回**下载构建器**(thenable),默认 `await` 得到 `Blob`。
2689
- *
2690
- * 需要登录态,权限由 `storage.objects` 的 RLS `SELECT` 策略判定。
2691
- *
2692
- * 两种终态:
2693
- * - 默认:`await bucket.download(path)` → `{ data: Blob, error }`。
2694
- * - 流式:`await bucket.download(path).asStream()` → `{ data: ReadableStream, error }`,
2695
- * 适合 Node 大文件等不希望整体读入内存的场景。
2696
- *
2697
- * 两者统一走原生 `fetch` 的 `Response`:流式终态返回 `Response.body`,Blob 终态调 `Response.blob()`。
2698
- *
2699
- * 下载行为:
2700
- * - 惰性执行:请求在 `await` / `.then()` 时才真正发出。
2701
- * - 返回的 `Blob` 不会自动触发浏览器下载或渲染,需配合 `URL.createObjectURL` 手动处理。
2702
- * - 支持 `parameters.signal`(AbortSignal)取消进行中的下载。
2703
- *
2704
- * @param path Bucket 内相对路径。
2705
- * @param options 下载选项,支持 `download`(触发浏览器下载)、`cacheNonce`(绕过 CDN 缓存)。
2706
- * @param parameters 请求控制参数,支持 `signal` / `cache`。
2707
- * @returns `DownloadBuilder`:可 `await` 得 `Blob`,或 `.asStream()` 后得 `ReadableStream`。
2708
- */
2709
- download(path: string, options?: DownloadOptions, parameters?: FetchParameters): DownloadBuilder
2710
-
2711
- /**
2712
- * 获取对象列表(游标分页)。
2713
- *
2714
- * 采用**游标分页**,与 Supabase 的 `listV2` 对应。
2715
- *
2716
- * - 首次查询不传 `cursor`,后续用上一页的 `nextCursor` 继续翻页。
2717
- * - 返回 `{ folders, objects, hasNext, nextCursor }`(区别于 Supabase `list` 的 offset 分页 `FileObject[]`)。
2718
- * - `path` 不传时列出 Bucket 根目录。
2719
- * - `options.withDelimiter` 为 `true` 时以 `/` 分隔文件夹和文件。
2720
- *
2721
- * @param path 路径前缀,不传表示 Bucket 根目录。
2722
- * @param options 列表选项,支持 `limit`、`cursor`、`withDelimiter`、`sortBy`。
2723
- * @param parameters 请求控制参数,支持 `signal` / `cache`。
2724
- * @remarks 本方法对应 Supabase 的 `listV2`(游标分页),而非 `list`(offset 分页)。
2725
- */
2726
- list(path?: string, options?: ListOptions, parameters?: FetchParameters): Promise<
2727
- | { data: ListObjectsResponse; error: null }
2728
- | { data: null; error: StorageError }
2729
- >
2730
-
2731
- /**
2732
- * 删除一个或多个对象。
2733
- *
2734
- * 权限由 `storage.objects` 的 RLS `DELETE` 策略判定。
2735
- *
2736
- * - 后端单次最多删除 100 个对象,超出时 SDK 自动分批发送。
2737
- * - 返回所有被成功删除的对象信息(`FullObject[]`)。
2738
- *
2739
- * @param paths Bucket 内相对路径数组。
2740
- */
2741
- remove(paths: string[]): Promise<
2742
- | { data: FullObject[]; error: null }
2743
- | { data: null; error: StorageError }
2744
- >
2745
-
2746
- /**
2747
- * 复制对象,支持跨 Bucket。
2748
- *
2749
- * 权限由 `storage.objects` 的 RLS 策略判定:读取源需要 `SELECT`,写入目标需要 `INSERT`。
2750
- *
2751
- * - `options.destinationBucket` 不传时在同一 Bucket 内复制。
2752
- * - `options.upsert` 为 `true` 时,目标路径已有对象则覆盖。
2753
- * - `options.copyMetadata` 设为 `false` 并传 `options.metadata` 时替换原 metadata。
2754
- * - 返回目标对象的完整路径。
2755
- *
2756
- * @param fromPath 源对象 Bucket 内相对路径。
2757
- * @param toPath 目标对象相对路径。
2758
- * @param options 目标 Bucket、覆盖、元数据复制等选项。
2759
- */
2760
- copy(fromPath: string, toPath: string, options?: DestinationOptions): Promise<
2761
- | { data: { path: string }; error: null }
2762
- | { data: null; error: StorageError }
2763
- >
2764
-
2765
- /**
2766
- * 移动对象,支持跨 Bucket;源对象会被删除。
2767
- *
2768
- * 语义为"复制到目标 → 删除源",非原地重命名。
2769
- * 权限由 `storage.objects` 的 RLS 策略判定:读取源需要 `SELECT`,写入目标需要 `INSERT`,删除源需要 `DELETE`。
2770
- *
2771
- * - `options.destinationBucket` 不传时在同一 Bucket 内移动。
2772
- *
2773
- * @param fromPath 源对象 Bucket 内相对路径。
2774
- * @param toPath 目标对象相对路径。
2775
- * @param options 目标 Bucket 等选项。
2776
- */
2777
- move(fromPath: string, toPath: string, options?: DestinationOptions): Promise<
2778
- | { data: { message: string }; error: null }
2779
- | { data: null; error: StorageError }
2780
- >
2781
-
2782
- /**
2783
- * 获取对象元信息。
2784
- *
2785
- * 返回对象在 `storage.objects` 表中的记录信息,包括 `bucketId`、`version`、`etag`、
2786
- * `contentType`、`cacheControl`、`metadata`、`lastModified`、`createdAt` 等。
2787
- *
2788
- * @param path Bucket 内相对路径。
2789
- */
2790
- info(path: string): Promise<
2791
- | { data: ObjectInfo; error: null }
2792
- | { data: null; error: StorageError }
2793
- >
2794
-
2795
- /**
2796
- * 判断对象是否存在。
2797
- *
2798
- * 底层调用 `info` 端点:
2799
- * - HTTP 200 → 存在(返回 `true`)。
2800
- * - HTTP 400 或 404 → 不存在(返回 `false`)。
2801
- * - 其他异常 → 返回 `{ data: null, error }`。
2802
- *
2803
- * @param path Bucket 内相对路径。
2804
- */
2805
- exists(path: string): Promise<
2806
- | { data: boolean; error: null }
2807
- | { data: null; error: StorageError }
2808
- >
2809
-
2810
- /**
2811
- * 生成单个对象的签名下载 URL。
2812
- *
2813
- * 需要登录态,权限由 `storage.objects` 的 RLS `SELECT` 策略判定。
2814
- *
2815
- * - `expiresIn` 以秒为单位,过期后 URL 不可用。
2816
- * - 返回的 `fullSignedURL` 是服务端已拼接好的完整 URL,客户端可直接使用(无需再拼 HOST)。
2817
- * - `options.download` 为 `true` 时追加 `?download`,浏览器访问时自动触发下载。
2818
- *
2819
- * @param path Bucket 内相对路径。
2820
- * @param expiresIn 过期时间,单位为秒。
2821
- * @param options 签名下载 URL 选项;当前仅支持 `download`,不支持图片 `transform`。
2822
- */
2823
- createSignedUrl(path: string, expiresIn: number, options?: SignedUrlOptions): Promise<
2824
- | { data: { fullSignedURL: string }; error: null }
2825
- | { data: null; error: StorageError }
2826
- >
2827
-
2828
- /**
2829
- * 批量生成对象的签名下载 URL。
2830
- *
2831
- * 需要登录态,权限由 `storage.objects` 的 RLS `SELECT` 策略判定。
2832
- *
2833
- * - 后端单次最多 500 个,超出时 SDK 自动分批发送。
2834
- * - 返回数组中每个元素包含 `path`、`fullSignedURL`(完整 URL,生成失败时为 `null`)、`error`。
2835
- * - 部分路径生成失败不会影响其他路径。
2836
- *
2837
- * @param paths Bucket 内相对路径数组。
2838
- * @param expiresIn 过期时间,单位为秒。
2839
- * @param options 签名下载 URL 选项;当前仅支持 `download`,不支持图片 `transform`。
2840
- */
2841
- createSignedUrls(paths: string[], expiresIn: number, options?: SignedUrlOptions): Promise<
2842
- | { data: Array<{ path: string; fullSignedURL: string | null; error: string | null }>; error: null }
2843
- | { data: null; error: StorageError }
2844
- >
2845
-
2846
- /**
2847
- * 两阶段上传(第一阶段):生成签名上传 URL,需登录态。
2848
- *
2849
- * 服务端基于调用者身份 + RLS 策略判断上传权限,生成临时签名 URL 和 token。
2850
- * 适合的场景:服务端鉴定用户权限后,将 `token` 下发给不受信客户端(如浏览器前端),
2851
- * 让客户端用 `uploadToSignedUrl` 直接上传文件,无需暴露登录凭证。
2852
- *
2853
- * - 返回的 `fullSignedURL` 是服务端已拼接好的完整上传 URL。
2854
- * - 返回的 `token` 是临时凭证,与 `uploadToSignedUrl` 配合使用。
2855
- * - `options.upsert` 为 `true` 时允许覆盖同名对象。
2856
- *
2857
- * @param path Bucket 内相对路径。
2858
- * @param options 签名上传选项,`upsert=true` 时允许覆盖。
2859
- * @see uploadToSignedUrl
2860
- */
2861
- createSignedUploadUrl(path: string, options?: { upsert?: boolean }): Promise<
2862
- | { data: { fullSignedURL: string; token: string; path: string }; error: null }
2863
- | { data: null; error: StorageError }
2864
- >
2865
-
2866
- /**
2867
- * 两阶段上传(第二阶段):使用签名上传 token 上传对象,无需登录态。
2868
- *
2869
- * 配合 `createSignedUploadUrl` 完成两阶段上传:
2870
- * 1. 服务端调用 `createSignedUploadUrl` 生成 token(需登录态)
2871
- * 2. 客户端调用本方法,凭 token 上传文件(无需登录态)
2872
- *
2873
- * - 请求**不携带**登录态,仅凭 `token` 鉴权。
2874
- * - `path` 和 `token` 必须与 `createSignedUploadUrl` 的返回值对应。
2875
- *
2876
- * @param path Bucket 内相对路径,需与 `createSignedUploadUrl` 的 `path` 一致。
2877
- * @param token `createSignedUploadUrl()` 返回的 `token`。
2878
- * @param fileBody 文件内容。
2879
- * @param fileOptions 上传选项。
2880
- * @see createSignedUploadUrl
2881
- */
2882
- uploadToSignedUrl(path: string, token: string, fileBody: FileBody, fileOptions?: UploadOptions): Promise<
2883
- | { data: { path: string; fullPath: string }; error: null }
2884
- | { data: null; error: StorageError }
2885
- >
2886
-
2887
- /**
2888
- * 同步获取 public bucket 对象的公开访问 URL;不发请求、不返回 `error`。
2889
- *
2890
- * **同步方法**,不发起网络请求,不会抛异常。
2891
- *
2892
- * - URL 由客户端直接拼接 `{gateway}/v1/storages/object/public/{bucketId}/{path}` 得到。
2893
- * - URL 是否可访问取决于 Bucket 的 `public` 属性。
2894
- * - `options.download` 为 `true` 时追加 `?download`。
2895
- *
2896
- * @param path Bucket 内相对路径。
2897
- * @param options 公开 URL 选项;当前仅支持 `download`,不支持图片 `transform`。
2898
- */
2899
- getPublicUrl(path: string, options?: PublicUrlOptions): { data: { publicUrl: string } }
2900
- }
2901
- }
2902
-
2903
- declare namespace cloudbase.database {
2904
- /**
2905
- * realtime types
2906
- */
2907
- /**
2908
- * watch() 监听选项
2909
- */
2910
- interface IWatchOptions {
2911
- /**
2912
- * 数据变化回调。首次建立连接时会触发 `type: 'init'` 的初始化快照,
2913
- * 后续每次数据变化(增/删/改)都会触发此回调。
2914
- *
2915
- * @param snapshot 数据快照,包含当前完整文档列表 `docs` 和本次变化详情 `docChanges`
2916
- */
2917
- onChange: (snapshot: ISnapshot) => void
2918
- /**
2919
- * 错误回调。在连接失败、token 过期、权限不足等异常时触发。
2920
- *
2921
- * **常见错误场景**:
2922
- * - 未登录或 token 过期:需先调用 `auth.signInAnonymously()` 等方法完成认证
2923
- * - 权限不足:检查安全规则配置
2924
- * - 网络中断:SDK 会自动尝试重连,重连失败后触发此回调
2925
- *
2926
- * @param error 错误信息
2927
- */
2928
- onError: (error: any) => void
2929
- }
2930
-
2931
- /**
2932
- * 实时数据推送监听器。通过 `watch()` 方法返回,用于管理实时监听的生命周期。
2933
- *
2934
- * **重要**:在 React 组件卸载或不再需要监听时,务必调用 `close()` 释放资源,
2935
- * 避免内存泄漏和不必要的网络连接。
2936
- */
2937
- interface DBRealtimeListener {
2938
- /**
2939
- * 关闭实时推送,释放 WebSocket 连接和相关资源。
2940
- *
2941
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#shu-ju-ku-shi-shi-tui-song}
2942
- *
2943
- * @example
2944
- * ```typescript
2945
- * // 启动监听
2946
- * const listener = db
2947
- * .collection('messages')
2948
- * .where({ roomId: 'room-1' })
2949
- * .watch({
2950
- * onChange: (snapshot) => {
2951
- * console.log('数据更新:', snapshot.docs);
2952
- * },
2953
- * onError: (error) => {
2954
- * console.error('监听异常:', error);
2955
- * }
2956
- * });
2957
- *
2958
- * // 不再需要时关闭监听
2959
- * listener.close();
2960
- *
2961
- * // React 组件中的最佳实践
2962
- * useEffect(() => {
2963
- * const listener = db.collection('xxx').watch({ onChange, onError });
2964
- * return () => listener.close(); // 组件卸载时自动清理
2965
- * }, []);
2966
- * ```
2967
- */
2968
- close: () => void
2969
- }
2970
-
2971
- /**
2972
- * 数据变化类型
2973
- * - `'init'`:初始化数据(首次连接时返回的完整数据)
2974
- * - `'update'`:文档被更新
2975
- * - `'add'`:新增文档
2976
- * - `'remove'`:文档被删除
2977
- * - `'replace'`:文档被替换(set 操作)
2978
- * - `'limit'`:因 limit 限制导致的数据变化
2979
- */
2980
- type DataType = 'init' | 'update' | 'add' | 'remove' | 'replace' | 'limit'
2981
-
2982
- /**
2983
- * 队列操作类型
2984
- * - `'init'`:初始化(对应 DataType 的 init)
2985
- * - `'enqueue'`:文档进入监听结果集(新增或开始匹配查询条件)
2986
- * - `'dequeue'`:文档离开监听结果集(删除或不再匹配查询条件)
2987
- * - `'update'`:文档在结果集中被更新
2988
- */
2989
- type QueueType = 'init' | 'enqueue' | 'dequeue' | 'update'
2990
-
2991
- /**
2992
- * 数据快照,每次 watch 回调都会收到此对象。
2993
- *
2994
- * **使用方式**:
2995
- * - 获取当前完整数据列表:使用 `snapshot.docs`(数组,包含所有匹配文档的最新状态)
2996
- * - 获取本次变化详情:使用 `snapshot.docChanges`(数组,仅包含本次变化的文档信息)
2997
- * - 判断是否为初始化数据:检查 `snapshot.type === 'init'`
2998
- *
2999
- * @example
3000
- * ```typescript
3001
- * onChange: (snapshot) => {
3002
- * if (snapshot.type === 'init') {
3003
- * // 首次连接,snapshot.docs 包含初始完整数据
3004
- * console.log('初始数据:', snapshot.docs);
3005
- * } else {
3006
- * // 后续变化
3007
- * snapshot.docChanges.forEach(change => {
3008
- * switch (change.dataType) {
3009
- * case 'add':
3010
- * console.log('新增文档:', change.doc);
3011
- * break;
3012
- * case 'update':
3013
- * console.log('更新文档:', change.docId, change.updatedFields);
3014
- * break;
3015
- * case 'remove':
3016
- * console.log('删除文档:', change.docId);
3017
- * break;
3018
- * }
3019
- * });
3020
- * // snapshot.docs 始终是变化后的完整数据列表
3021
- * console.log('当前全部数据:', snapshot.docs);
3022
- * }
3023
- * }
3024
- * ```
3025
- */
3026
- interface ISnapshot {
3027
- /** 快照序列号,单调递增 */
3028
- id: number
3029
- /** 本次变化的文档详情列表 */
3030
- docChanges: ISingleDBEvent[]
3031
- /** 当前完整的文档列表(变化后的最新状态) */
3032
- docs: Record<string, any>[]
3033
- /** 快照类型,`'init'` 表示初始化数据 */
3034
- type?: SnapshotType
3035
- }
3036
-
3037
- /**
3038
- * 单个文档变化事件
3039
- */
3040
- interface ISingleDBEvent {
3041
- /** 事件序列号 */
3042
- id: number
3043
- /** 数据变化类型:init/add/update/remove/replace/limit */
3044
- dataType: DataType
3045
- /** 队列操作类型:init/enqueue/dequeue/update */
3046
- queueType: QueueType
3047
- /** 变化文档的 ID */
3048
- docId: string
3049
- /** 变化后的完整文档内容(remove 时为删除前的文档) */
3050
- doc: Record<string, any>
3051
- /** 被更新的字段及新值(仅 dataType 为 update 时存在) */
3052
- updatedFields?: any
3053
- /** 被删除的字段列表(仅 dataType 为 update 时存在) */
3054
- removedFields?: any
3055
- }
3056
-
3057
- /** 快照类型。`'init'` 表示首次连接时返回的初始化数据 */
3058
- type SnapshotType = 'init'
3059
-
3060
- interface IWatchable {
3061
- /**
3062
- * 开启实时数据推送,监听集合或文档的数据变化。
3063
- *
3064
- * **前置条件**:使用 `watch()` 前必须先完成用户认证(如匿名登录),
3065
- * 否则 WebSocket 连接会因缺少认证信息而失败。
3066
- *
3067
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%9E%E6%97%B6%E6%8E%A8%E9%80%81}
3068
- *
3069
- * @example
3070
- * ```typescript
3071
- * // === 完整示例:匿名登录 + watch + React 集成 ===
3072
- * import Cloudbase from '@cloudbase/js-sdk';
3073
- * import { useEffect, useState } from 'react';
3074
- *
3075
- * const app = Cloudbase.init({ env: 'your-env-id', region: 'ap-shanghai' });
3076
- *
3077
- * function RoomList() {
3078
- * const [rooms, setRooms] = useState<any[]>([]);
3079
- * const [error, setError] = useState<string | null>(null);
3080
- *
3081
- * useEffect(() => {
3082
- * let listener: cloudbase.database.DBRealtimeListener | null = null;
3083
- *
3084
- * async function setup() {
3085
- * // 第一步:必须先完成认证
3086
- * const auth = app.auth();
3087
- * const { error: authError } = await auth.signInAnonymously();
3088
- * if (authError) {
3089
- * setError('登录失败: ' + authError.message);
3090
- * return;
3091
- * }
3092
- *
3093
- * // 第二步:认证成功后开启 watch
3094
- * const db = app.database();
3095
- * listener = db.collection('rooms')
3096
- * .where({ status: 'active' })
3097
- * .watch({
3098
- * onChange: (snapshot) => {
3099
- * // snapshot.docs 包含当前所有匹配文档
3100
- * setRooms(snapshot.docs as any[]);
3101
- * },
3102
- * onError: (err) => {
3103
- * console.error('watch 错误:', err);
3104
- * setError('实时同步异常: ' + (err?.message || err));
3105
- * }
3106
- * });
3107
- * }
3108
- *
3109
- * setup();
3110
- *
3111
- * // 第三步:组件卸载时清理监听
3112
- * return () => {
3113
- * if (listener) listener.close();
3114
- * };
3115
- * }, []);
3116
- *
3117
- * if (error) return <div>错误: {error}</div>;
3118
- * return (
3119
- * <ul>
3120
- * {rooms.map(room => <li key={room._id}>{room.name}</li>)}
3121
- * </ul>
3122
- * );
3123
- * }
3124
- * ```
3125
- *
3126
- * @param options 监听选项
3127
- * @param options.onChange 数据变化回调,接收 {@link ISnapshot} 快照对象
3128
- * @param options.onError 错误回调,在连接异常、认证失败等情况下触发
3129
- *
3130
- * @returns {@link DBRealtimeListener} 监听器实例,调用 `close()` 可停止监听
3131
- */
3132
- watch(options: IWatchOptions): DBRealtimeListener
3133
- }
3134
- /**
3135
- * collection types
3136
- */
3137
- interface ICollection extends IQuery {
3138
- /**
3139
- * 向集合中添加一条新记录
3140
- *
3141
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#add}
3142
- *
3143
- * @example
3144
- * const result = await db.collection('todos').add({
3145
- * title: '学习 CloudBase',
3146
- * completed: false
3147
- * })
3148
- * console.log('新增成功,文档 ID:', result.id)
3149
- *
3150
- * @param data 要新增的数据对象或数据对象数组,支持嵌套对象、数组、地理位置等数据类型
3151
- *
3152
- * @return Promise<AddRes> 包含新增文档的 id(单条)或 ids(批量)和 requestId
3153
- */
3154
- add(data: Object | Object[]): Promise<AddRes>
3155
- /**
3156
- * 获取一条文档的引用
3157
- *
3158
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#record--document}
3159
- *
3160
- * @param id 文档ID
3161
- */
3162
- doc(id: string | number): IDocument
3163
- /**
3164
- * 获取聚合操作对象
3165
- *
3166
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#aggregate}
3167
- *
3168
- * @example
3169
- * const result = await db.collection('todos')
3170
- * .aggregate()
3171
- * .group({ _id: '$priority', count: { $sum: 1 } })
3172
- * .end()
3173
- *
3174
- * @return 聚合操作对象,可链式调用各种聚合阶段方法
3175
- */
3176
- aggregate(): IAggregate
3177
- }
3178
- /**
3179
- * command types
3180
- */
3181
- interface IGeoNearOptions {
3182
- geometry: IGeo['Point'] // 点的地理位置
3183
- maxDistance?: number // 选填,最大距离,米为单位
3184
- minDistance?: number // 选填,最小距离,米为单位
3185
- }
3186
- interface IGeoWithinOptions {
3187
- geometry: IPolygon | IMultiPolygon
3188
- }
3189
- interface IGeoIntersectsOptions {
3190
- geometry: IPoint | ILineString | IMultiPoint | IMultiLineString | IPolygon | IMultiPolygon
3191
- }
3192
- interface ICommand {
3193
- /**
3194
- * 表示字段等于某个值
3195
- *
3196
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#eq}
3197
- *
3198
- * @example
3199
- * const _ = db.command;
3200
- * db.collection("demo").where({
3201
- * num: _.eq(10)
3202
- * })
3203
- *
3204
- * @param val 接受一个字面量 (literal),可以是 `number`, `boolean`, `string`, `object`, `array`
3205
- *
3206
- */
3207
- eq(val: number | string | boolean | Object | any[]): any
3208
- /**
3209
- * 表示字段不等于某个值
3210
- *
3211
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#neq}
3212
- *
3213
- * @example
3214
- * const _ = db.command;
3215
- * db.collection("demo").where({
3216
- * num: _.neq(10)
3217
- * })
3218
- *
3219
- * @param val 接受一个字面量 (literal),可以是 `number`, `boolean`, `string`, `object`, `array`
3220
- *
3221
- */
3222
- neq(val: number | string | boolean | Object | any[]): any
3223
- /**
3224
- * 字段大于指定值
3225
- *
3226
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#gt}
3227
- *
3228
- * @example
3229
- * const _ = db.command;
3230
- * db.collection("demo").where({
3231
- * num: _.gt(10)
3232
- * })
3233
- *
3234
- * @param val 数字
3235
- *
3236
- */
3237
- gt(val: number): any
3238
- /**
3239
- * 字段大于或等于指定值
3240
- *
3241
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#neq}
3242
- *
3243
- * @example
3244
- * const _ = db.command;
3245
- * db.collection("demo").where({
3246
- * num: _.gte(10)
3247
- * })
3248
- *
3249
- * @param val 数字
3250
- *
3251
- */
3252
- gte(val: number): any
3253
- /**
3254
- * 字段小于指定值
3255
- *
3256
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#lt}
3257
- *
3258
- * @example
3259
- * const _ = db.command;
3260
- * db.collection("demo").where({
3261
- * num: _.lt(10)
3262
- * })
3263
- *
3264
- * @param val 数字
3265
- *
3266
- */
3267
- lt(val: number): any
3268
- /**
3269
- * 字段小于或等于指定值
3270
- *
3271
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#lte}
3272
- *
3273
- * @example
3274
- * const _ = db.command;
3275
- * db.collection("demo").where({
3276
- * num: _.lte(10)
3277
- * })
3278
- *
3279
- * @param val 数字
3280
- *
3281
- */
3282
- lte(val: number): any
3283
- /**
3284
- * 字段值在给定的数组中
3285
- *
3286
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#in}
3287
- *
3288
- * @example
3289
- * const _ = db.command;
3290
- * db.collection("demo").where({
3291
- * num: _.in([1,2,3])
3292
- * })
3293
- *
3294
- * @param list 数组
3295
- *
3296
- */
3297
- in(list: any[]): any
3298
- /**
3299
- * 字段值不在给定的数组中
3300
- *
3301
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#nin}
3302
- *
3303
- * @example
3304
- * const _ = db.command;
3305
- * db.collection("demo").where({
3306
- * num: _.nin([1,2,3])
3307
- * })
3308
- *
3309
- * @param list 数组
3310
- *
3311
- */
3312
- nin(list: any[]): any
3313
- /**
3314
- * 表示需同时满足指定的两个或以上的条件
3315
- *
3316
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#and}
3317
- *
3318
- * @example
3319
- * const _ = db.command;
3320
- * db.collection("demo").where({
3321
- * num: _.and(_.gt(4), _.lt(32))
3322
- * })
3323
- *
3324
- * @param args 多个条件
3325
- *
3326
- */
3327
- and(...args: any[]): any
3328
- /**
3329
- * 表示需满足所有指定条件中的至少一个
3330
- *
3331
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#or}
3332
- *
3333
- * @example
3334
- * const _ = db.command;
3335
- * db.collection("demo").where({
3336
- * num: _.or(_.gt(4), _.lt(32))
3337
- * })
3338
- *
3339
- * @param args 多个条件
3340
- *
3341
- */
3342
- or(...args: any[]): any
3343
- /**
3344
- * 用于设定字段等于指定值
3345
- *
3346
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#set}
3347
- *
3348
- * @example
3349
- * const _ = db.command;
3350
- * db.collection("demo")
3351
- * .doc("doc-id")
3352
- * .update({
3353
- * data: {
3354
- * style: _.set({
3355
- * color: "red"
3356
- * })
3357
- * }
3358
- * });
3359
- *
3360
- * @param val 被设定的属性对象
3361
- *
3362
- */
3363
- set(val: any): any
3364
- /**
3365
- * 用于指示字段自增某个值
3366
- *
3367
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#inc}
3368
- *
3369
- * @example
3370
- * const _ = db.command;
3371
- * db.collection("demo")
3372
- * .doc("doc-id")
3373
- * .update({
3374
- * count: {
3375
- * favorites: _.inc(1)
3376
- * }
3377
- * });
3378
- *
3379
- * @param val 自增的值
3380
- *
3381
- */
3382
- inc(val: number): any
3383
- /**
3384
- * 用于指示字段自乘某个值
3385
- *
3386
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#mul}
3387
- *
3388
- * @example
3389
- * const _ = db.command;
3390
- * db.collection("demo")
3391
- * .doc("doc-id")
3392
- * .update({
3393
- * count: {
3394
- * favorites: _.mul(21)
3395
- * }
3396
- * });
3397
- *
3398
- * @param val 自乘的值
3399
- *
3400
- */
3401
- mul(val: number): any
3402
- /**
3403
- * 用于表示删除某个字段
3404
- *
3405
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#remove}
3406
- *
3407
- * @example
3408
- * const _ = db.command;
3409
- * db.collection("demo")
3410
- * .doc("doc-id")
3411
- * .update({
3412
- * rating: _.remove()
3413
- * });
3414
- *
3415
- */
3416
- remove(): any
3417
- /**
3418
- * 向数组尾部追加元素
3419
- *
3420
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#push}
3421
- *
3422
- * @example
3423
- * const _ = db.command;
3424
- * db.collection("demo")
3425
- * .doc("doc-id")
3426
- * .update({
3427
- * users: _.push(["aaa", "bbb"])
3428
- * });
3429
- *
3430
- * @param val 支持传入单个元素或数组
3431
- */
3432
- push(val: any): any
3433
- /**
3434
- * 删除数组尾部元素
3435
- *
3436
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#pop}
3437
- *
3438
- * @example
3439
- * const _ = db.command;
3440
- * db.collection("demo")
3441
- * .doc("doc-id")
3442
- * .update({
3443
- * users: _.pop()
3444
- * });
3445
- *
3446
- */
3447
- pop(): any
3448
- /**
3449
- * 向数组头部添加元素
3450
- *
3451
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#unshift}
3452
- *
3453
- * @example
3454
- * const _ = db.command;
3455
- * db.collection("demo")
3456
- * .doc("doc-id")
3457
- * .update({
3458
- * users: _.unshift(["aaa", "bbb"])
3459
- * });
3460
- *
3461
- * @param val 支持传入单个元素或数组
3462
- */
3463
- unshift(val: any): any
3464
- /**
3465
- * 删除数组头部元素
3466
- *
3467
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#shift}
3468
- *
3469
- * @example
3470
- * const _ = db.command;
3471
- * db.collection("demo")
3472
- * .doc("doc-id")
3473
- * .update({
3474
- * users: _.unshift()
3475
- * });
3476
- *
3477
- */
3478
- shift(): any
3479
- /**
3480
- * 条件取反
3481
- *
3482
- * @example
3483
- * const _ = db.command;
3484
- * db.collection('users').where({
3485
- * status: _.not(_.eq('deleted'))
3486
- * })
3487
- *
3488
- * @param condition 查询条件
3489
- */
3490
- not(condition: any): any
3491
- /**
3492
- * 都不满足指定的条件
3493
- *
3494
- * @example
3495
- * const _ = db.command;
3496
- * db.collection('users').where(
3497
- * _.nor([{ status: 'banned' }, { status: 'deleted' }])
3498
- * )
3499
- *
3500
- * @param conditions 条件数组
3501
- */
3502
- nor(conditions: any[]): any
3503
- /**
3504
- * 判断字段是否存在
3505
- *
3506
- * @example
3507
- * const _ = db.command;
3508
- * db.collection('users').where({
3509
- * avatar: _.exists(true)
3510
- * })
3511
- *
3512
- * @param val true 表示字段存在,false 表示不存在
3513
- */
3514
- exists(val: boolean): any
3515
- /**
3516
- * 取模运算
3517
- *
3518
- * @example
3519
- * const _ = db.command;
3520
- * db.collection('users').where({
3521
- * age: _.mod([2, 0])
3522
- * })
3523
- *
3524
- * @param val [除数, 余数]
3525
- */
3526
- mod(val: [number, number]): any
3527
- /**
3528
- * 数组包含所有指定元素
3529
- *
3530
- * @example
3531
- * const _ = db.command;
3532
- * db.collection('articles').where({
3533
- * tags: _.all(['javascript', 'nodejs'])
3534
- * })
3535
- *
3536
- * @param list 必须包含的元素数组
3537
- */
3538
- all(list: any[]): any
3539
- /**
3540
- * 数组元素匹配
3541
- *
3542
- * @example
3543
- * const _ = db.command;
3544
- * db.collection('orders').where({
3545
- * items: _.elemMatch({ price: _.gt(100) })
3546
- * })
3547
- *
3548
- * @param condition 匹配条件对象
3549
- */
3550
- elemMatch(condition: Object): any
3551
- /**
3552
- * 数组长度匹配
3553
- *
3554
- * @example
3555
- * const _ = db.command;
3556
- * db.collection('articles').where({
3557
- * tags: _.size(3)
3558
- * })
3559
- *
3560
- * @param size 数组长度
3561
- */
3562
- size(size: number): any
3563
- /**
3564
- * 取最小值更新
3565
- *
3566
- * @param val 比较值
3567
- */
3568
- min(val: number): any
3569
- /**
3570
- * 取最大值更新
3571
- *
3572
- * @param val 比较值
3573
- */
3574
- max(val: number): any
3575
- /**
3576
- * 重命名字段
3577
- *
3578
- * @param newFieldName 新字段名
3579
- */
3580
- rename(newFieldName: string): any
3581
- /**
3582
- * 位运算
3583
- *
3584
- * @param options 位运算选项,如 { and: 5 }
3585
- */
3586
- bit(options: Object): any
3587
- /**
3588
- * 删除数组中匹配的元素
3589
- *
3590
- * @example
3591
- * const _ = db.command;
3592
- * db.collection('articles').doc('id').update({
3593
- * tags: _.pull('要删除的标签')
3594
- * })
3595
- *
3596
- * @param val 要删除的元素或匹配条件
3597
- */
3598
- pull(val: any): any
3599
- /**
3600
- * 删除数组中所有匹配的元素
3601
- *
3602
- * @param list 要删除的元素数组
3603
- */
3604
- pullAll(list: any[]): any
3605
- /**
3606
- * 向数组添加不重复的元素
3607
- *
3608
- * @example
3609
- * const _ = db.command;
3610
- * db.collection('articles').doc('id').update({
3611
- * tags: _.addToSet('唯一标签')
3612
- * })
3613
- *
3614
- * @param val 要添加的元素
3615
- */
3616
- addToSet(val: any): any
3617
- /**
3618
- * 按从近到远的顺序,找出字段值在给定点的附近的文档
3619
- *
3620
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#geonear}
3621
- *
3622
- * @example
3623
- * const _ = db.command;
3624
- * db.collection("demo").where({
3625
- * location: _.geoNear({
3626
- * geometry: new db.Geo.Point(lngA, latA),
3627
- * maxDistance: 1000,
3628
- * minDistance: 0
3629
- * })
3630
- * });
3631
- *
3632
- * @param options
3633
- * @param options.geometry 点的地理位置
3634
- * @param options.maxDistance 【可选】最大距离,米为单位
3635
- * @param options.minDistance 【可选】最小距离,米为单位
3636
- */
3637
- geoNear(options: IGeoNearOptions): any
3638
- /**
3639
- * 找出字段值在指定 Polygon / MultiPolygon 内的文档,无排序
3640
- *
3641
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#geowithin}
3642
- *
3643
- * @example
3644
- * const _ = db.command;
3645
- * db.collection("demo").where({
3646
- * location: _.geoWithin({
3647
- * geometry: new Polygon({
3648
- * new LineString([...Points])
3649
- * }),
3650
- * })
3651
- * });
3652
- *
3653
- * @param options
3654
- * @param options.geometry 地理位置
3655
- */
3656
- geoWithin(options: IGeoWithinOptions): any
3657
- /**
3658
- * 找出字段值和给定的地理位置图形相交的文档
3659
- *
3660
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#geointersects}
3661
- *
3662
- * @example
3663
- * const _ = db.command;
3664
- * db.collection("user").where({
3665
- * location: _.geoNear({
3666
- * geometry: new LineString([new Point(lngA, latA), new Point(lngB, latB)]);
3667
- * })
3668
- * });
3669
- *
3670
- * @param options
3671
- * @param options.geometry 地理位置
3672
- */
3673
- geoIntersects(options: IGeoIntersectsOptions): any
3674
- }
3675
- /**
3676
- * document types
3677
- */
3678
- interface IDocument extends IWatchable {
3679
- /**
3680
- * 设置文档数据,如果文档不存在则创建新文档
3681
- *
3682
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#update-set}
3683
- *
3684
- * @example
3685
- * collection
3686
- * .doc('docId')
3687
- * .set({name:'cloudbase'})
3688
- * .then(res=>{})
3689
- *
3690
- * @param data 要设置的数据对象,将完全替换原有文档内容
3691
- *
3692
- * @return Promise<SetRes> 包含 updated 或 upsertedId
3693
- */
3694
- set(data: Object): Promise<SetRes>
3695
- /**
3696
- * 获取文档数据
3697
- *
3698
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#get}
3699
- *
3700
- * @example
3701
- * collection
3702
- * .doc('docId')
3703
- * .get()
3704
- * .then(res=>{ console.log(res.data) })
3705
- *
3706
- * @return Promise<GetRes> 包含 data 数组和 requestId
3707
- */
3708
- get(): Promise<GetRes>
3709
- /**
3710
- * 更新文档数据,如果文档不存在则不做任何操作
3711
- *
3712
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#update--set}
3713
- *
3714
- * @example
3715
- * collection
3716
- * .doc('docId')
3717
- * .update({completed: true})
3718
- * .then(res=>{ console.log(res.updated) })
3719
- *
3720
- * @param data 要更新的数据对象,支持操作符
3721
- *
3722
- * @return Promise<UpdateRes> 包含 updated 字段
3723
- */
3724
- update(data: Object): Promise<UpdateRes>
3725
- /**
3726
- * 删除一条文档
3727
- *
3728
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#remove-2}
3729
- *
3730
- * @example
3731
- * collection
3732
- * .doc('docId')
3733
- * .remove()
3734
- * .then(res=>{ console.log(res.deleted) })
3735
- *
3736
- * @return Promise<RemoveRes> 包含 deleted 字段
3737
- */
3738
- remove(): Promise<RemoveRes>
3739
- /**
3740
- * 指定要返回的字段
3741
- *
3742
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#field}
3743
- *
3744
- * @param projection 字段投影对象,true 表示返回,false 表示不返回
3745
- *
3746
- * @return 文档引用,可继续链式调用 get()
3747
- */
3748
- field(projection: Object): IDocument
3749
- }
3750
- /**
3751
- * query types
3752
- */
3753
- interface SetRes {
3754
- code?: string
3755
- message?: string
3756
- updated?: number
3757
- upsertedId?: string
3758
- requestId: string
3759
- }
3760
- interface GetRes {
3761
- data: any[]
3762
- requestId: string
3763
- code?: string
3764
- message?: string
3765
- }
3766
-
3767
- interface UpdateRes {
3768
- requestId: string
3769
- updated?: number
3770
- upsertedId?: string
3771
- code?: string
3772
- message?: string
3773
- }
3774
-
3775
- interface AddRes {
3776
- id?: string
3777
- ids?: string[]
3778
- insertedIds?: string[]
3779
- requestId: string
3780
- code?: string
3781
- message?: string
3782
- }
3783
-
3784
- interface CountRes {
3785
- total: number
3786
- requestId: string
3787
- code?: string
3788
- message?: string
3789
- }
3790
-
3791
- interface RemoveRes {
3792
- deleted: number
3793
- requestId: string
3794
- code?: string
3795
- message?: string
3796
- }
3797
-
3798
- interface CreateCollectionRes {
3799
- data: string
3800
- requestId: string
3801
- code?: string
3802
- message?: string
3803
- }
3804
-
3805
- interface IRunCommandsReq {
3806
- /** 命令对象数组 */
3807
- commands: Object[]
3808
- /** 事务 ID(可选) */
3809
- transactionId?: string
3810
- }
3811
-
3812
- interface IRunCommandsResult {
3813
- requestId: string
3814
- /** 命令执行结果数组 */
3815
- list: Object[][]
3816
- code?: string
3817
- message?: string
3818
- }
3819
-
3820
- /**
3821
- * 数据库配置
3822
- */
3823
- interface IDbConfig {
3824
- /** 实例 ID(可选),不填则使用默认实例 */
3825
- instance?: string
3826
- /** 数据库名称(可选),不填则使用默认数据库 */
3827
- database?: string
3828
- }
3829
-
3830
- /**
3831
- * 聚合操作对象
3832
- */
3833
- interface IAggregate {
3834
- /**
3835
- * 添加新字段
3836
- */
3837
- addFields(fieldObj: Object): IAggregate
3838
- /**
3839
- * 分桶
3840
- */
3841
- bucket(bucketObj: Object): IAggregate
3842
- /**
3843
- * 自动分桶
3844
- */
3845
- bucketAuto(bucketObj: Object): IAggregate
3846
- /**
3847
- * 计数
3848
- */
3849
- count(fieldName: string): IAggregate
3850
- /**
3851
- * 地理位置附近查询
3852
- */
3853
- geoNear(options: Object): IAggregate
3854
- /**
3855
- * 分组统计
3856
- *
3857
- * @example
3858
- * db.collection('todos').aggregate()
3859
- * .group({ _id: '$priority', count: { $sum: 1 } })
3860
- * .end()
3861
- */
3862
- group(groupObj: Object): IAggregate
3863
- /**
3864
- * 限制结果数量
3865
- */
3866
- limit(limit: number): IAggregate
3867
- /**
3868
- * 联表查询
3869
- */
3870
- lookup(lookupObj: Object): IAggregate
3871
- /**
3872
- * 条件筛选
3873
- */
3874
- match(matchObj: Object): IAggregate
3875
- /**
3876
- * 字段投影
3877
- */
3878
- project(projectObj: Object): IAggregate
3879
- /**
3880
- * 替换根文档
3881
- */
3882
- replaceRoot(replaceObj: Object): IAggregate
3883
- /**
3884
- * 随机采样
3885
- */
3886
- sample(sampleObj: Object): IAggregate
3887
- /**
3888
- * 跳过数量
3889
- */
3890
- skip(skip: number): IAggregate
3891
- /**
3892
- * 排序
3893
- */
3894
- sort(sortObj: Object): IAggregate
3895
- /**
3896
- * 按数量排序
3897
- */
3898
- sortByCount(fieldName: string): IAggregate
3899
- /**
3900
- * 展开数组
3901
- */
3902
- unwind(fieldPath: string | Object): IAggregate
3903
- /**
3904
- * 结束聚合管道,返回结果
3905
- */
3906
- end(): Promise<GetRes>
3907
- }
3908
-
3909
- /**
3910
- * 事务对象
3911
- */
3912
- interface ITransaction {
3913
- /**
3914
- * 获取事务内的集合引用
3915
- */
3916
- collection(name: string): ITransactionCollection
3917
- /**
3918
- * 提交事务
3919
- */
3920
- commit(): Promise<void>
3921
- /**
3922
- * 回滚事务
3923
- *
3924
- * @param reason 回滚原因
3925
- */
3926
- rollback(reason?: any): Promise<void>
3927
- }
3928
-
3929
- /**
3930
- * 事务内的集合引用
3931
- */
3932
- interface ITransactionCollection {
3933
- doc(id: string): ITransactionDocument
3934
- }
3935
-
3936
- /**
3937
- * 事务内的文档引用
3938
- */
3939
- interface ITransactionDocument {
3940
- get(): Promise<GetRes>
3941
- create(data: Object): Promise<any>
3942
- set(data: Object): Promise<SetRes>
3943
- update(data: Object): Promise<UpdateRes>
3944
- remove(): Promise<RemoveRes>
3945
- }
3946
-
3947
- interface QueryOrder {
3948
- field?: string
3949
- direction?: 'asc' | 'desc'
3950
- }
3951
-
3952
- interface QueryOption {
3953
- // 查询数量
3954
- limit?: number
3955
- // 偏移量
3956
- offset?: number
3957
- // 指定显示或者不显示哪些字段
3958
- projection?: Object
3959
- }
3960
- interface IQuery extends IWatchable {
3961
- /**
3962
- * 获取数据库查询结果
3963
- *
3964
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#get}
3965
- *
3966
- * @example
3967
- * collection
3968
- * .where({
3969
- * name: 'cloudbase'
3970
- * })
3971
- * .get()
3972
- * .then(res=>{})
3973
- *
3974
- * @return Promise-查询结果
3975
- */
3976
- get(): Promise<GetRes>
3977
- /**
3978
- * 更新数据库文档
3979
- *
3980
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#update-set}
3981
- *
3982
- * @example
3983
- * collection
3984
- * .where({
3985
- * name: 'cloudbase'
3986
- * })
3987
- * .update({
3988
- * name: 'newCloudbase'
3989
- * })
3990
- * .then(res=>{})
3991
- *
3992
- * @return Promise-查询结果
3993
- */
3994
- update(data: Object): Promise<UpdateRes>
3995
- /**
3996
- * 获取数据库查询结果的数目
3997
- *
3998
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#count}
3999
- *
4000
- * @example
4001
- * collection
4002
- * .where({
4003
- * name: 'cloudbase'
4004
- * })
4005
- * .count()
4006
- * .then(res=>{})
4007
- *
4008
- * @return Promise<CountRes> 包含 total 字段
4009
- */
4010
- count(): Promise<CountRes>
4011
- /**
4012
- * 设置过滤条件
4013
- *
4014
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#where}
4015
- *
4016
- * @example
4017
- * collection
4018
- * .where({
4019
- * name: 'cloudbase'
4020
- * })
4021
- *
4022
- * @param query 可接收对象作为参数,表示筛选出拥有和传入对象相同的 key-value 的文档
4023
- *
4024
- */
4025
- where(query: Object): ExcludeOf<IQuery, 'where'>
4026
- /**
4027
- * 指定查询结果集数量上限
4028
- *
4029
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#limit}
4030
- *
4031
- * @example
4032
- * collection
4033
- * .where({
4034
- * name: 'cloudbase'
4035
- * })
4036
- * .limit(1)
4037
- *
4038
- * @param limit 查询结果数量上限
4039
- */
4040
- limit(limit: number): ExcludeOf<IQuery, 'where'>
4041
- /**
4042
- * 指定查询返回结果时从指定序列后的结果开始返回,常用于分页
4043
- *
4044
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#skip}
4045
- *
4046
- * @example
4047
- * collection
4048
- * .where({
4049
- * name: 'cloudbase'
4050
- * })
4051
- * .skip(4)
4052
- *
4053
- * @param offset 跳过的条目数量
4054
- */
4055
- skip(offset: number): ExcludeOf<IQuery, 'where'>
4056
- /**
4057
- * 指定查询排序条件
4058
- *
4059
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#orderby}
4060
- *
4061
- * @example
4062
- * collection
4063
- * .where({
4064
- * name: 'cloudbase'
4065
- * })
4066
- * .orderBy("name", "asc")
4067
- *
4068
- * @param field 排序的字段
4069
- * @param orderType 排序的顺序,升序(asc) 或 降序(desc)
4070
- */
4071
- orderBy(field: string, orderType: 'desc' | 'asc'): ExcludeOf<IQuery, 'where'>
4072
- /**
4073
- * 指定返回结果中文档需返回的字段
4074
- *
4075
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#field}
4076
- *
4077
- * @example
4078
- * collection
4079
- * .where({
4080
- * name: 'cloudbase'
4081
- * })
4082
- * .field({ age: true })
4083
- *
4084
- * @param projection 要过滤的字段集合,不返回传 false,返回传 true
4085
- */
4086
- field(projection: Object): ExcludeOf<IQuery, 'where'>
4087
- /**
4088
- * 删除查询到的结果
4089
- *
4090
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#remove-1}
4091
- *
4092
- * @example
4093
- * collection
4094
- * .where({
4095
- * name: 'cloudbase'
4096
- * })
4097
- * .remove()
4098
- *
4099
- * @return Promise<RemoveRes> 包含 deleted 字段
4100
- */
4101
- remove(): Promise<RemoveRes>
4102
- }
4103
- /**
4104
- * geo types
4105
- */
4106
- interface IPoint {}
4107
- interface ILineString {}
4108
- interface IPolygon {}
4109
- interface IMultiPoint {}
4110
- interface IMultiLineString {}
4111
- interface IMultiPolygon {}
4112
- interface IGeo {
4113
- /**
4114
- * 用于表示地理位置点
4115
- *
4116
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#point}
4117
- *
4118
- * @example
4119
- * const point = new db.Geo.Point(lng,lat);
4120
- *
4121
- * @param longitude 经度
4122
- * @param latitude 纬度
4123
- *
4124
- * @return Point
4125
- */
4126
- Point: {
4127
- new (longitude: number, latitude: number): IPoint
4128
- }
4129
- /**
4130
- * 用于表示地理路径,是由两个或者更多的 Point 组成的线段
4131
- *
4132
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#linestring}
4133
- *
4134
- * @example
4135
- * const point = new db.Geo.LineString([pointA,pointB]);
4136
- *
4137
- * @param points Point数组
4138
- *
4139
- * @return LineString
4140
- */
4141
- LineString: {
4142
- new (points: IPoint[]): ILineString
4143
- }
4144
- /**
4145
- * 用于表示地理上的一个多边形
4146
- *
4147
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#polygon}
4148
- *
4149
- * @example
4150
- * const point = new db.Geo.Polygon([lineStringA,lineStringB]);
4151
- *
4152
- * @param lines LineString数组
4153
- *
4154
- * @return Polygon
4155
- */
4156
- Polygon: {
4157
- new (lines: ILineString[]): IPolygon
4158
- }
4159
- /**
4160
- * 用于表示多个点 Point 的集合
4161
- *
4162
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#multipoint}
4163
- *
4164
- * @example
4165
- * const point = new db.Geo.MultiPoint([pointA,pointB]);
4166
- *
4167
- * @param points Point数组
4168
- *
4169
- * @return MultiPoint
4170
- */
4171
- MultiPoint: {
4172
- new (points: IPoint[]): IMultiPoint
4173
- }
4174
- /**
4175
- * 用于表示多个地理路径 LineString 的集合
4176
- *
4177
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#multilinestring}
4178
- *
4179
- * @example
4180
- * const point = new db.Geo.MultiLineString([lineA,lineB]);
4181
- *
4182
- * @param lines LineString数组
4183
- *
4184
- * @return MultiLineString
4185
- */
4186
- MultiLineString: {
4187
- new (lines: ILineString[]): IMultiLineString
4188
- }
4189
- /**
4190
- * 用于表示多个地理多边形 Polygon 的集合
4191
- *
4192
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#multipolygon}
4193
- *
4194
- * @example
4195
- * const point = new db.Geo.MultiPolygon([polygonA,polygonB]);
4196
- *
4197
- * @param polygons Polygon数组
4198
- *
4199
- * @return MultiPolygon
4200
- */
4201
- MultiPolygon: {
4202
- new (polygons: IPolygon[]): IMultiPolygon
4203
- }
4204
- }
4205
- /**
4206
- * regexp types
4207
- */
4208
- interface IRegExpOptions {
4209
- regexp: string
4210
- options?: string
4211
- }
4212
- interface IRegExp {
4213
- (options: IRegExpOptions): any
4214
- }
4215
- /**
4216
- * instance types
4217
- */
4218
- interface App {
4219
- /**
4220
- * 数据库指令
4221
- *
4222
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database#%E6%9F%A5%E8%AF%A2%E6%8C%87%E4%BB%A4}
4223
- */
4224
- command: ICommand
4225
- /**
4226
- * 数据库Geo地理位置
4227
- *
4228
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#geo-shu-ju-lei-xing}
4229
- */
4230
- Geo: IGeo
4231
- /**
4232
- * 根据正则表达式进行筛选
4233
- *
4234
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#regexp}
4235
- *
4236
- * @example
4237
- * db.collection('articles').where({
4238
- * version: new db.RegExp({
4239
- * regexp: '^\\ds' // 正则表达式为 /^\ds/,转义后变成 '^\\ds'
4240
- * options: 'i' // i表示忽略大小写
4241
- * })
4242
- * })
4243
- *
4244
- * @param options
4245
- * @param options.regexp 正则表达式Pattern
4246
- * @param options.options 正则表达式Flags
4247
- */
4248
- RegExp: IRegExp
4249
- /**
4250
- * 创建集合的引用
4251
- *
4252
- * {@link https://docs.cloudbase.net/api-reference/webv3-next/database.html#collection}
4253
- *
4254
- * @example
4255
- * const coll = db.collection('demo');
4256
- *
4257
- * @param name 集合名称
4258
- *
4259
- * @return 集合的引用
4260
- */
4261
- collection(name: string): ICollection
4262
-
4263
- runCommands(params: IRunCommandsReq): Promise<{
4264
- statusCode: number
4265
- requestId: string
4266
- list?: Object[][]
4267
- code?: string
4268
- message?: string
4269
- }>
4270
- }
4271
- }
4272
9
 
4273
10
  export = cloudbase
4274
11
  export as namespace cloudbase