@cloudbase/oauth 2.23.3 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cjs/auth/apis.js +170 -14
  2. package/dist/cjs/auth/auth-error.js +32 -0
  3. package/dist/cjs/auth/consts.js +24 -2
  4. package/dist/cjs/auth/models.js +1 -1
  5. package/dist/cjs/captcha/captcha-dom.js +223 -0
  6. package/dist/cjs/captcha/captcha.js +11 -102
  7. package/dist/cjs/index.js +25 -3
  8. package/dist/cjs/oauth2client/interface.js +1 -1
  9. package/dist/cjs/oauth2client/models.js +1 -1
  10. package/dist/cjs/oauth2client/oauth2client.js +384 -110
  11. package/dist/cjs/utils/base64.js +15 -2
  12. package/dist/esm/auth/apis.js +113 -2
  13. package/dist/esm/auth/auth-error.js +9 -0
  14. package/dist/esm/auth/consts.js +22 -0
  15. package/dist/esm/captcha/captcha-dom.js +129 -0
  16. package/dist/esm/captcha/captcha.js +14 -97
  17. package/dist/esm/index.js +18 -2
  18. package/dist/esm/oauth2client/oauth2client.js +162 -36
  19. package/dist/esm/utils/base64.js +12 -0
  20. package/dist/miniprogram/index.js +1 -1
  21. package/dist/types/auth/apis.d.ts +19 -1
  22. package/dist/types/auth/auth-error.d.ts +6 -0
  23. package/dist/types/auth/consts.d.ts +22 -0
  24. package/dist/types/auth/models.d.ts +2 -0
  25. package/dist/types/captcha/captcha-dom.d.ts +3 -0
  26. package/dist/types/captcha/captcha.d.ts +3 -1
  27. package/dist/types/index.d.ts +11 -2
  28. package/dist/types/oauth2client/interface.d.ts +1 -1
  29. package/dist/types/oauth2client/models.d.ts +14 -0
  30. package/dist/types/oauth2client/oauth2client.d.ts +58 -2
  31. package/dist/types/utils/base64.d.ts +5 -0
  32. package/package.json +4 -4
  33. package/src/auth/apis.ts +189 -4
  34. package/src/auth/auth-error.ts +21 -0
  35. package/src/auth/consts.ts +28 -0
  36. package/src/auth/models.ts +2 -0
  37. package/src/captcha/captcha-dom.ts +178 -0
  38. package/src/captcha/captcha.ts +25 -115
  39. package/src/index.ts +51 -3
  40. package/src/oauth2client/interface.ts +1 -1
  41. package/src/oauth2client/models.ts +28 -0
  42. package/src/oauth2client/oauth2client.ts +254 -34
  43. package/src/utils/base64.ts +12 -0
@@ -1,5 +1,5 @@
1
1
  import { ErrorType } from './consts';
2
- import { ApiUrls, ApiUrlsV2, AUTH_API_PREFIX } from '../auth/consts';
2
+ import { ApiUrls, ApiUrlsV2, AUTH_API_PREFIX, AUTH_STATE_CHANGED_TYPE, EVENTS } from '../auth/consts';
3
3
  import { uuidv4 } from '../utils/uuid';
4
4
  import { getPathName } from '../utils/index';
5
5
  import { SinglePromise } from '../utils/function/single-promise';
@@ -188,6 +188,9 @@ class LocalCredentials {
188
188
  }
189
189
  class OAuth2Client {
190
190
  constructor(options) {
191
+ this.initializePromise = null;
192
+ this.lockAcquired = false;
193
+ this.pendingInLock = [];
191
194
  this.singlePromise = null;
192
195
  if (!options.clientSecret) {
193
196
  options.clientSecret = '';
@@ -199,6 +202,7 @@ class OAuth2Client {
199
202
  this.apiPath = options.apiPath || AUTH_API_PREFIX;
200
203
  this.clientId = options.clientId;
201
204
  this.i18n = options.i18n;
205
+ this.eventBus = options.eventBus;
202
206
  this.singlePromise = new SinglePromise({ clientId: this.clientId });
203
207
  this.retry = this.formatRetry(options.retry, OAuth2Client.defaultRetry);
204
208
  if (options.baseRequest) {
@@ -234,17 +238,35 @@ class OAuth2Client {
234
238
  this.refreshTokenFunc = options.refreshTokenFunc || this.defaultRefreshTokenFunc;
235
239
  this.anonymousSignInFunc = options.anonymousSignInFunc;
236
240
  this.onCredentialsError = options.onCredentialsError;
241
+ this.getInitialSession = options.getInitialSession;
242
+ this.onInitialSessionObtained = options.onInitialSessionObtained;
243
+ this.logDebugMessages = options.debug ?? false;
237
244
  langEvent.bus.on(langEvent.LANG_CHANGE_EVENT, (params) => {
238
245
  this.i18n = params.data?.i18n || this.i18n;
239
246
  });
240
247
  }
241
- setCredentials(credentials) {
242
- return this.localCredentials.setCredentials(credentials);
248
+ setGetInitialSession(callback) {
249
+ this.getInitialSession = callback;
250
+ }
251
+ setOnInitialSessionObtained(callback) {
252
+ this.onInitialSessionObtained = callback;
253
+ }
254
+ async initialize() {
255
+ if (this.initializePromise) {
256
+ return await this.initializePromise;
257
+ }
258
+ this.initializePromise = (async () => await this._acquireLock(-1, async () => await this._initialize()))();
259
+ return await this.initializePromise;
260
+ }
261
+ async setCredentials(credentials) {
262
+ await this.initializePromise;
263
+ return this._acquireLock(-1, async () => this.localCredentials.setCredentials(credentials));
243
264
  }
244
265
  setAccessKeyCredentials(credentials) {
245
266
  return this.localCredentials.setAccessKeyCredentials(credentials);
246
267
  }
247
268
  async getAccessToken() {
269
+ await this.initializePromise;
248
270
  const credentials = await this.getCredentials();
249
271
  if (credentials?.access_token) {
250
272
  return Promise.resolve(credentials.access_token);
@@ -275,7 +297,7 @@ class OAuth2Client {
275
297
  options.headers.Authorization = this.basicAuth;
276
298
  }
277
299
  if (options?.withCredentials) {
278
- const credentials = await this.getCredentials();
300
+ const credentials = options.getCredentials ? await options.getCredentials() : await this.getCredentials();
279
301
  if (credentials) {
280
302
  if (this.tokenInURL) {
281
303
  if (url.indexOf('?') < 0) {
@@ -367,37 +389,8 @@ class OAuth2Client {
367
389
  }
368
390
  }
369
391
  async getCredentials() {
370
- let credentials = await this.localCredentials.getCredentials();
371
- if (!credentials) {
372
- const msg = 'credentials not found';
373
- this.onCredentialsError?.({ msg });
374
- return this.unAuthenticatedError(msg);
375
- }
376
- if (isCredentialsExpired(credentials)) {
377
- if (credentials.refresh_token) {
378
- try {
379
- credentials = await this.refreshToken(credentials);
380
- }
381
- catch (error) {
382
- if (credentials.scope === 'anonymous') {
383
- credentials = await this.anonymousLogin(credentials);
384
- }
385
- else {
386
- this.onCredentialsError?.({ msg: error.error_description });
387
- return Promise.reject(error);
388
- }
389
- }
390
- }
391
- else if (credentials.scope === 'anonymous') {
392
- credentials = await this.anonymousLogin(credentials);
393
- }
394
- else {
395
- const msg = 'no refresh token found in credentials';
396
- this.onCredentialsError?.({ msg });
397
- return this.unAuthenticatedError(msg);
398
- }
399
- }
400
- return credentials;
392
+ await this.initializePromise;
393
+ return this._acquireLock(-1, async () => this._getCredentials());
401
394
  }
402
395
  getCredentialsSync() {
403
396
  const credentials = this.localCredentials.getStorageCredentialsSync();
@@ -424,7 +417,11 @@ class OAuth2Client {
424
417
  }
425
418
  return credentials.groups;
426
419
  }
427
- async refreshToken(credentials) {
420
+ async refreshToken(credentials, options) {
421
+ await this.initializePromise;
422
+ return this._acquireLock(-1, async () => this._refreshToken(credentials, options));
423
+ }
424
+ async _refreshToken(credentials, options) {
428
425
  return this.singlePromise.run('_refreshToken', async () => {
429
426
  if (!credentials || !credentials.refresh_token) {
430
427
  const msg = 'no refresh token found in credentials';
@@ -434,9 +431,13 @@ class OAuth2Client {
434
431
  try {
435
432
  const newCredentials = await this.refreshTokenFunc(credentials.refresh_token, credentials);
436
433
  await this.localCredentials.setCredentials(newCredentials);
434
+ this.eventBus?.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.TOKEN_REFRESHED });
437
435
  return newCredentials;
438
436
  }
439
437
  catch (error) {
438
+ if (options?.throwError) {
439
+ throw error;
440
+ }
440
441
  if (error.error === ErrorType.INVALID_GRANT) {
441
442
  await this.localCredentials.setCredentials(null);
442
443
  const msg = error.error_description;
@@ -549,6 +550,131 @@ class OAuth2Client {
549
550
  };
550
551
  return Promise.reject(respErr);
551
552
  }
553
+ _debug(...args) {
554
+ if (this.logDebugMessages) {
555
+ console.log('[OAuth2Client]', ...args);
556
+ }
557
+ }
558
+ async _initialize() {
559
+ try {
560
+ if (!this.getInitialSession) {
561
+ this._debug('#_initialize()', 'no getInitialSession callback set, skipping');
562
+ return { error: null };
563
+ }
564
+ this._debug('#_initialize()', 'calling getInitialSession callback');
565
+ try {
566
+ const { data, error } = await this.getInitialSession();
567
+ if (data?.session) {
568
+ this._debug('#_initialize()', 'session obtained from getInitialSession', data.session);
569
+ await this.localCredentials.setCredentials(data?.session);
570
+ }
571
+ if (this.onInitialSessionObtained) {
572
+ this._debug('#_initialize()', 'calling onInitialSessionObtained callback');
573
+ try {
574
+ await this.onInitialSessionObtained(data, error);
575
+ }
576
+ catch (callbackError) {
577
+ this._debug('#_initialize()', 'error in onInitialSessionObtained', callbackError);
578
+ }
579
+ }
580
+ if (error) {
581
+ this._debug('#_initialize()', 'error from getInitialSession', error);
582
+ return { error };
583
+ }
584
+ return { error: null };
585
+ }
586
+ catch (err) {
587
+ this._debug('#_initialize()', 'exception during getInitialSession', err);
588
+ return { error: err instanceof Error ? err : new Error(String(err)) };
589
+ }
590
+ }
591
+ catch (error) {
592
+ this._debug('#_initialize()', 'unexpected error', error);
593
+ return { error: error instanceof Error ? error : new Error(String(error)) };
594
+ }
595
+ finally {
596
+ this._debug('#_initialize()', 'end');
597
+ }
598
+ }
599
+ async _acquireLock(acquireTimeout, fn) {
600
+ this._debug('#_acquireLock', 'begin', acquireTimeout);
601
+ try {
602
+ if (this.lockAcquired) {
603
+ const last = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve();
604
+ const result = (async () => {
605
+ await last;
606
+ return await fn();
607
+ })();
608
+ this.pendingInLock.push((async () => {
609
+ try {
610
+ await result;
611
+ }
612
+ catch (_e) {
613
+ }
614
+ })());
615
+ return result;
616
+ }
617
+ this._debug('#_acquireLock', 'acquiring lock for client', this.clientId);
618
+ try {
619
+ this.lockAcquired = true;
620
+ const result = fn();
621
+ this.pendingInLock.push((async () => {
622
+ try {
623
+ await result;
624
+ }
625
+ catch (_e) {
626
+ }
627
+ })());
628
+ await result;
629
+ while (this.pendingInLock.length) {
630
+ const waitOn = [...this.pendingInLock];
631
+ await Promise.all(waitOn);
632
+ this.pendingInLock.splice(0, waitOn.length);
633
+ }
634
+ return await result;
635
+ }
636
+ finally {
637
+ this._debug('#_acquireLock', 'releasing lock for client', this.clientId);
638
+ this.lockAcquired = false;
639
+ }
640
+ }
641
+ finally {
642
+ this._debug('#_acquireLock', 'end');
643
+ }
644
+ }
645
+ async _getCredentials() {
646
+ let credentials = await this.localCredentials.getCredentials();
647
+ if (!credentials) {
648
+ const msg = 'credentials not found';
649
+ this.onCredentialsError?.({ msg });
650
+ return this.unAuthenticatedError(msg);
651
+ }
652
+ if (isCredentialsExpired(credentials)) {
653
+ if (credentials.refresh_token) {
654
+ try {
655
+ credentials = await this._refreshToken(credentials);
656
+ }
657
+ catch (error) {
658
+ if (credentials.scope === 'anonymous') {
659
+ credentials = await this.anonymousLogin(credentials);
660
+ }
661
+ else {
662
+ this.onCredentialsError?.({ msg: error.error_description });
663
+ return Promise.reject(error);
664
+ }
665
+ }
666
+ }
667
+ else if (credentials.scope === 'anonymous') {
668
+ credentials = await this.anonymousLogin(credentials);
669
+ }
670
+ else {
671
+ const msg = 'no refresh token found in credentials';
672
+ this.onCredentialsError?.({ msg });
673
+ return this.unAuthenticatedError(msg);
674
+ }
675
+ }
676
+ return credentials;
677
+ }
552
678
  }
553
679
  OAuth2Client.defaultRetry = 2;
554
680
  OAuth2Client.minRetry = 0;
@@ -89,3 +89,15 @@ export function weappJwtDecode(token, options) {
89
89
  throw new Error(`Invalid token specified: ${e}` ? e.message : '');
90
90
  }
91
91
  }
92
+ export function weappJwtDecodeAll(token) {
93
+ if (typeof token !== 'string') {
94
+ throw new Error('Invalid token specified');
95
+ }
96
+ try {
97
+ const parts = token.split('.').map((segment, i) => i === 2 ? segment : JSON.parse(base64_url_decode(segment)));
98
+ return { claims: parts[1], header: parts[0], signature: parts[2] };
99
+ }
100
+ catch (e) {
101
+ throw new Error(`Invalid token specified: ${e}` ? e.message : '');
102
+ }
103
+ }
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("tcboauth",[],t):"object"==typeof exports?exports.tcboauth=t():e.tcboauth=t()}("undefined"!=typeof window?window:this,()=>(()=>{"use strict";var e={3:(e,t,r)=>{r.r(t),r.d(t,{getEncryptInfo:()=>i});const n=void 0;var o=r(912),i=function(){var{publicKey:e="",payload:t={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!e)return"";try{var r=(0,o.I)(t),i=new n;i.setPublicKey(e);var a=i.encryptLong("object"==typeof r?JSON.stringify(r):r);return a}catch(e){console.error("encrypt error:",e)}return""}},912:(e,t,r)=>{r.d(t,{I:()=>n,y:()=>o});var n=e=>{var t=t=>{for(var r in e)e.hasOwnProperty(r)&&(t[r]=n(e[r]));return t},r=null==e?"NullOrUndefined":Object.prototype.toString.call(e).slice(8,-1);if(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"].includes(r))return e.slice();switch(r){case"Object":return t(Object.create(Object.getPrototypeOf(e)));case"Array":return t([]);case"Date":return new Date(e.valueOf());case"RegExp":return new RegExp(e.source,(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":""));default:return e}},o=e=>{var t=e.match(/^(?:http(s)?:\/\/[^\/]+)?(\/[^\?#]*)/);return t&&t[2]||""}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{AUTH_API_PREFIX:()=>c,Auth:()=>pe,CloudbaseOAuth:()=>ge,authModels:()=>e});var e={};r.r(e);var t,o,i,a,s,c="/auth";function u(){return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}!function(e){e.AUTH_SIGN_UP_URL="/v1/signup",e.AUTH_TOKEN_URL="/v1/token",e.AUTH_REVOKE_URL="/v1/revoke",e.WEDA_USER_URL="/v1/plugin/weda/userinfo",e.AUTH_RESET_PASSWORD="/v1/reset",e.AUTH_GET_DEVICE_CODE="/v1/device/code",e.CHECK_USERNAME="/v1/checkUsername",e.CHECK_IF_USER_EXIST="/v1/checkIfUserExist",e.GET_PROVIDER_TYPE="/v1/mgr/provider/providerSubType",e.AUTH_SIGN_IN_URL="/v1/signin",e.AUTH_SIGN_IN_ANONYMOUSLY_URL="/v1/signin/anonymously",e.AUTH_SIGN_IN_WITH_PROVIDER_URL="/v1/signin/with/provider",e.AUTH_SIGN_IN_WITH_WECHAT_URL="/v1/signin/wechat/noauth",e.AUTH_SIGN_IN_CUSTOM="/v1/signin/custom",e.PROVIDER_TOKEN_URL="/v1/provider/token",e.PROVIDER_URI_URL="/v1/provider/uri",e.USER_ME_URL="/v1/user/me",e.AUTH_SIGNOUT_URL="/v1/user/signout",e.USER_QUERY_URL="/v1/user/query",e.USER_PRIFILE_URL="/v1/user/profile",e.USER_BASIC_EDIT_URL="/v1/user/basic/edit",e.USER_TRANS_BY_PROVIDER_URL="/v1/user/trans/by/provider",e.PROVIDER_LIST="/v1/user/provider",e.PROVIDER_BIND_URL="/v1/user/provider/bind",e.PROVIDER_UNBIND_URL="/v1/user/provider",e.CHECK_PWD_URL="/v1/user/sudo",e.SUDO_URL="/v1/user/sudo",e.BIND_CONTACT_URL="/v1/user/contact",e.AUTH_SET_PASSWORD="/v1/user/password",e.AUTHORIZE_DEVICE_URL="/v1/user/device/authorize",e.AUTHORIZE_URL="/v1/user/authorize",e.AUTHORIZE_INFO_URL="/v1/user/authorize/info",e.AUTHORIZED_DEVICES_DELETE_URL="/v1/user/authorized/devices/",e.AUTH_REVOKE_ALL_URL="/v1/user/revoke/all",e.GET_USER_BEHAVIOR_LOG="/v1/user/security/history",e.VERIFICATION_URL="/v1/verification",e.VERIFY_URL="/v1/verification/verify",e.CAPTCHA_DATA_URL="/v1/captcha/data",e.VERIFY_CAPTCHA_DATA_URL="/v1/captcha/data/verify",e.GET_CAPTCHA_URL="/v1/captcha/init",e.GET_MINIPROGRAM_QRCODE="/v1/qrcode/generate",e.GET_MINIPROGRAM_QRCODE_STATUS="/v1/qrcode/get/status"}(t||(t={})),function(e){e.AUTH_SIGN_IN_URL="/v2/signin/username",e.AUTH_TOKEN_URL="/v2/token",e.USER_ME_URL="/v2/user/me",e.VERIFY_URL="/v2/signin/verificationcode",e.AUTH_SIGN_IN_WITH_PROVIDER_URL="/v2/signin/with/provider",e.AUTH_PUBLIC_KEY="/v2/signin/publichkey",e.AUTH_RESET_PASSWORD="/v2/signin/password/update"}(o||(o={})),function(e){e.REGISTER="REGISTER",e.SIGN_IN="SIGN_IN",e.PASSWORD_RESET="PASSWORD_RESET",e.EMAIL_ADDRESS_CHANGE="EMAIL_ADDRESS_CHANGE",e.PHONE_NUMBER_CHANGE="PHONE_NUMBER_CHANGE"}(i||(i={})),function(e){e.UNREACHABLE="unreachable",e.LOCAL="local",e.CANCELLED="cancelled",e.UNKNOWN="unknown",e.UNAUTHENTICATED="unauthenticated",e.RESOURCE_EXHAUSTED="resource_exhausted",e.FAILED_PRECONDITION="failed_precondition",e.INVALID_ARGUMENT="invalid_argument",e.DEADLINE_EXCEEDED="deadline_exceeded",e.NOT_FOUND="not_found",e.ALREADY_EXISTS="already_exists",e.PERMISSION_DENIED="permission_denied",e.ABORTED="aborted",e.OUT_OF_RANGE="out_of_range",e.UNIMPLEMENTED="unimplemented",e.INTERNAL="internal",e.UNAVAILABLE="unavailable",e.DATA_LOSS="data_loss",e.INVALID_PASSWORD="invalid_password",e.PASSWORD_NOT_SET="password_not_set",e.INVALID_STATUS="invalid_status",e.USER_PENDING="user_pending",e.USER_BLOCKED="user_blocked",e.INVALID_VERIFICATION_CODE="invalid_verification_code",e.TWO_FACTOR_REQUIRED="two_factor_required",e.INVALID_TWO_FACTOR="invalid_two_factor",e.INVALID_TWO_FACTOR_RECOVERY="invalid_two_factor_recovery",e.UNDER_REVIEW="under_review",e.INVALID_REQUEST="invalid_request",e.UNAUTHORIZED_CLIENT="unauthorized_client",e.ACCESS_DENIED="access_denied",e.UNSUPPORTED_RESPONSE_TYPE="unsupported_response_type",e.INVALID_SCOPE="invalid_scope",e.INVALID_GRANT="invalid_grant",e.SERVER_ERROR="server_error",e.TEMPORARILY_UNAVAILABLE="temporarily_unavailable",e.INTERACTION_REQUIRED="interaction_required",e.LOGIN_REQUIRED="login_required",e.ACCOUNT_SELECTION_REQUIRED="account_selection_required",e.CONSENT_REQUIRED="consent_required",e.INVALID_REQUEST_URI="invalid_request_uri",e.INVALID_REQUEST_OBJECT="invalid_request_object",e.REQUEST_NOT_SUPPORTED="request_not_supported",e.REQUEST_URI_NOT_SUPPORTED="request_uri_not_supported",e.REGISTRATION_NOT_SUPPORTED="registration_not_supported",e.CAPTCHA_REQUIRED="captcha_required",e.CAPTCHA_INVALID="captcha_invalid"}(a||(a={})),function(e){e.CLIENT_ID="client_id",e.CLIENT_SECRET="client_secret",e.RESPONSE_TYPE="response_type",e.SCOPE="scope",e.STATE="state",e.REDIRECT_URI="redirect_uri",e.ERROR="error",e.ERROR_DESCRIPTION="error_description",e.ERROR_URI="error_uri",e.GRANT_TYPE="grant_type",e.CODE="code",e.ACCESS_TOKEN="access_token",e.TOKEN_TYPE="token_type",e.EXPIRES_IN="expires_in",e.USERNAME="username",e.PASSWORD="password",e.REFRESH_TOKEN="refresh_token"}(s||(s={}));var l=r(912);function d(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function h(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){d(i,n,o,a,s,"next",e)}function s(e){d(i,n,o,a,s,"throw",e)}a(void 0)}))}}var f=new Map;class p{constructor(e){this.clientId=(null==e?void 0:e.clientId)||"",f=f||new Map}run(e,t){var r=this;return h((function*(){e="".concat(r.clientId,"_").concat(e);var n=f.get(e);return n||(n=new Promise((n,o)=>{h((function*(){try{yield r.runIdlePromise();var i=t();n(yield i)}catch(e){o(e)}finally{f.delete(e)}}))()}),f.set(e,n)),n}))()}runIdlePromise(){return Promise.resolve()}}var v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function y(){if("undefined"==typeof globalThis)return!1;var{wx:e}=globalThis;if(void 0===e)return!1;if(void 0===globalThis.Page)return!1;if(!e.getSystemInfoSync)return!1;if(!e.getStorageSync)return!1;if(!e.setStorageSync)return!1;if(!e.connectSocket)return!1;if(!e.request)return!1;try{if(!e.getSystemInfoSync())return!1;if("qq"===e.getSystemInfoSync().AppPlatform)return!1}catch(e){return!1}return!0}var _=!1;function g(){_=_||void 0!==typeof window&&"miniprogram"===window.__wxjs_environment}try{y()||(_=_||!!navigator.userAgent.match(/miniprogram/i)||"miniprogram"===window.__wxjs_environment,window&&window.WeixinJSBridge&&window.WeixinJSBridge.invoke?g():"undefined"!=typeof document&&document.addEventListener("WeixinJSBridgeReady",g,!1))}catch(B){}function m(){return _}var E="@cloudbase/js-sdk";function I(){return E}var b="https:";var R,C="INVALID_PARAMS",T="INVALID_OPERATION",O="OPERATION_FAIL";!function(e){e.local="local",e.none="none",e.session="session"}(R||(R={}));var S=function(){};function w(e,t){console.warn("[".concat(I(),"][").concat(e,"]:").concat(t))}var A,P=(A=function(e,t){return(A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}A(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),U=function(){return(U=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},N=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((n=n.apply(e,t||[])).next())}))},L=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};!function(e){function t(t){var r=e.call(this)||this,n=t.timeout,o=t.timeoutMsg,i=t.restrictedMethods;return r.timeout=n||0,r.timeoutMsg=o||"请求超时",r.restrictedMethods=i||["get","post","upload","download"],r}P(t,e),t.prototype.get=function(e){return this.request(U(U({},e),{method:"get"}),this.restrictedMethods.includes("get"))},t.prototype.post=function(e){return this.request(U(U({},e),{method:"post"}),this.restrictedMethods.includes("post"))},t.prototype.put=function(e){return this.request(U(U({},e),{method:"put"}))},t.prototype.upload=function(e){var t=e.data,r=e.file,n=e.name,o=e.method,i=e.headers,a=void 0===i?{}:i,s={post:"post",put:"put"}[null==o?void 0:o.toLowerCase()]||"put",c=new FormData;return"post"===s?(Object.keys(t).forEach((function(e){c.append(e,t[e])})),c.append("key",n),c.append("file",r),this.request(U(U({},e),{data:c,method:s}),this.restrictedMethods.includes("upload"))):this.request(U(U({},e),{method:"put",headers:a,body:r}),this.restrictedMethods.includes("upload"))},t.prototype.download=function(e){return N(this,void 0,void 0,(function(){var t,r,n,o;return L(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.get(U(U({},e),{headers:{},responseType:"blob"}))];case 1:return t=i.sent().data,r=window.URL.createObjectURL(new Blob([t])),n=decodeURIComponent(new URL(e.url).pathname.split("/").pop()||""),(o=document.createElement("a")).href=r,o.setAttribute("download",n),o.style.display="none",document.body.appendChild(o),o.click(),window.URL.revokeObjectURL(r),document.body.removeChild(o),[3,3];case 2:return i.sent(),[3,3];case 3:return[2,new Promise((function(t){t({statusCode:200,tempFilePath:e.url})}))]}}))}))},t.prototype.fetch=function(e){var t;return N(this,void 0,void 0,(function(){var r,n,o,i,a,s,c,u,l,d,h,f,p,v=this;return L(this,(function(y){switch(y.label){case 0:return r=new AbortController,n=e.url,o=e.enableAbort,i=void 0!==o&&o,a=e.stream,s=void 0!==a&&a,c=e.signal,u=e.timeout,l=e.shouldThrowOnError,d=void 0===l||l,h=null!=u?u:this.timeout,c&&(c.aborted&&r.abort(),c.addEventListener("abort",(function(){return r.abort()}))),f=null,i&&h&&(f=setTimeout((function(){console.warn(v.timeoutMsg),r.abort(new Error(v.timeoutMsg))}),h)),[4,fetch(n,U(U({},e),{signal:r.signal})).then((function(e){return N(v,void 0,void 0,(function(){var t,r,n;return L(this,(function(o){switch(o.label){case 0:return clearTimeout(f),d?e.ok?(t=e,[3,3]):[3,1]:[3,4];case 1:return n=(r=Promise).reject,[4,e.json()];case 2:t=n.apply(r,[o.sent()]),o.label=3;case 3:return[2,t];case 4:return[2,e]}}))}))})).catch((function(e){if(clearTimeout(f),d)return Promise.reject(e)}))];case 1:return p=y.sent(),[2,{data:s?p.body:(null===(t=p.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json"))?p.json():p.text(),statusCode:p.status,header:p.headers}]}}))}))},t.prototype.request=function(e,t){var r=this;void 0===t&&(t=!1);var n=String(e.method).toLowerCase()||"get";return new Promise((function(o){var i,a,s,c=e.url,u=e.headers,l=void 0===u?{}:u,d=e.data,h=e.responseType,f=e.withCredentials,p=e.body,v=e.onUploadProgress,y=function(e,t,r){void 0===r&&(r={});var n=/\?/.test(t),o="";return Object.keys(r).forEach((function(e){""===o?!n&&(t+="?"):o+="&",o+="".concat(e,"=").concat(encodeURIComponent(r[e]))})),/^http(s)?:\/\//.test(t+=o)?t:"".concat(e).concat(t)}(b,c,"get"===n?d:{}),_=new XMLHttpRequest;_.open(n,y),h&&(_.responseType=h),Object.keys(l).forEach((function(e){_.setRequestHeader(e,l[e])})),v&&_.upload.addEventListener("progress",v),_.onreadystatechange=function(){var e={};if(4===_.readyState){var t=_.getAllResponseHeaders().trim().split(/[\r\n]+/),r={};t.forEach((function(e){var t=e.split(": "),n=t.shift().toLowerCase(),o=t.join(": ");r[n]=o})),e.header=r,e.statusCode=_.status;try{e.data="blob"===h?_.response:JSON.parse(_.responseText)}catch(t){e.data="blob"===h?_.response:_.responseText}clearTimeout(i),o(e)}},t&&r.timeout&&(i=setTimeout((function(){console.warn(r.timeoutMsg),_.abort()}),r.timeout)),s=d,a="[object FormData]"===Object.prototype.toString.call(s)?d:"application/x-www-form-urlencoded"===l["content-type"]?function(e){void 0===e&&(e={});var t=[];return Object.keys(e).forEach((function(r){t.push("".concat(r,"=").concat(encodeURIComponent(e[r])))})),t.join("&")}(d):p||(d?JSON.stringify(d):void 0),f&&(_.withCredentials=!0),_.send(a)}))}}((function(){}));var D;!function(e){e.WEB="web",e.WX_MP="wx_mp"}(D||(D={}));var k=function(){var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),x=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((n=n.apply(e,t||[])).next())}))},j=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},q=function(e){function t(t){var r=e.call(this)||this;return r.root=t,t.tcbCacheObject||(t.tcbCacheObject={}),r}return k(t,e),t.prototype.setItem=function(e,t){this.root.tcbCacheObject[e]=t},t.prototype.getItem=function(e){return this.root.tcbCacheObject[e]},t.prototype.removeItem=function(e){delete this.root.tcbCacheObject[e]},t.prototype.clear=function(){delete this.root.tcbCacheObject},t}(S);!function(){function e(e){this.keys={};var t=e.persistence,r=e.platformInfo,n=void 0===r?{}:r,o=e.keys,i=void 0===o?{}:o;this.platformInfo=n,this.storage||(this.persistenceTag=this.platformInfo.adapter.primaryStorage||t,this.storage=function(e,t){switch(e){case"local":return t.localStorage?t.localStorage:(w(C,"localStorage is not supported on current platform"),new q(t.root));case"none":return new q(t.root);default:return t.localStorage?t.localStorage:(w(C,"localStorage is not supported on current platform"),new q(t.root))}}(this.persistenceTag,this.platformInfo.adapter),this.keys=i)}Object.defineProperty(e.prototype,"mode",{get:function(){return this.storage.mode||"sync"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"persistence",{get:function(){return this.persistenceTag},enumerable:!1,configurable:!0}),e.prototype.setStore=function(e,t,r){if("async"!==this.mode){if(this.storage)try{var n={version:r||"localCachev1",content:t};this.storage.setItem(e,JSON.stringify(n))}catch(e){throw new Error(JSON.stringify({code:O,msg:"[".concat(I(),"][").concat(O,"]setStore failed"),info:e}))}}else w(T,"current platform's storage is asynchronous, please use setStoreAsync insteed")},e.prototype.setStoreAsync=function(e,t,r){return x(this,void 0,void 0,(function(){var n;return j(this,(function(o){switch(o.label){case 0:if(!this.storage)return[2];o.label=1;case 1:return o.trys.push([1,3,,4]),n={version:r||"localCachev1",content:t},[4,this.storage.setItem(e,JSON.stringify(n))];case 2:return o.sent(),[3,4];case 3:return o.sent(),[2];case 4:return[2]}}))}))},e.prototype.getStore=function(e,t){var r;if("async"!==this.mode){try{if("undefined"!=typeof process&&(null===(r=process.env)||void 0===r?void 0:r.tcb_token))return process.env.tcb_token;if(!this.storage)return""}catch(e){return""}t=t||"localCachev1";var n=this.storage.getItem(e);return n&&n.indexOf(t)>=0?JSON.parse(n).content:""}w(T,"current platform's storage is asynchronous, please use getStoreAsync insteed")},e.prototype.getStoreAsync=function(e,t){var r;return x(this,void 0,void 0,(function(){var n;return j(this,(function(o){switch(o.label){case 0:try{if("undefined"!=typeof process&&(null===(r=process.env)||void 0===r?void 0:r.tcb_token))return[2,process.env.tcb_token];if(!this.storage)return[2,""]}catch(e){return[2,""]}return t=t||"localCachev1",[4,this.storage.getItem(e)];case 1:return(n=o.sent())&&n.indexOf(t)>=0?[2,JSON.parse(n).content]:[2,""]}}))}))},e.prototype.removeStore=function(e){"async"!==this.mode?this.storage.removeItem(e):w(T,"current platform's storage is asynchronous, please use removeStoreAsync insteed")},e.prototype.removeStoreAsync=function(e){return x(this,void 0,void 0,(function(){return j(this,(function(t){switch(t.label){case 0:return[4,this.storage.removeItem(e)];case 1:return t.sent(),[2]}}))}))}}();var H=function(){var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),G=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))};var V=function(e,t){this.data=t||null,this.name=e},M=function(e){function t(t,r){var n=e.call(this,"error",{error:t,data:r})||this;return n.error=t,n}return H(t,e),t}(V),W=function(){function e(){this.listeners={}}return e.prototype.on=function(e,t){return function(e,t,r){r[e]=r[e]||[],r[e].push(t)}(e,t,this.listeners),this},e.prototype.off=function(e,t){return function(e,t,r){if(null==r?void 0:r[e]){var n=r[e].indexOf(t);-1!==n&&r[e].splice(n,1)}}(e,t,this.listeners),this},e.prototype.fire=function(e,t){if(e instanceof M)return console.error(e.error),this;var r="string"==typeof e?new V(e,t||{}):e,n=r.name;if(this.listens(n)){r.target=this;for(var o=0,i=this.listeners[n]?G([],this.listeners[n],!0):[];o<i.length;o++){i[o].call(this,r)}}return this},e.prototype.listens=function(e){return this.listeners[e]&&this.listeners[e].length>0},e}();new W;var F=new W;"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox");!function(){function e(){var e=this;this.listeners=[],this.signal={aborted:!1,addEventListener:function(t,r){"abort"===t&&e.listeners.push(r)}}}e.prototype.abort=function(){this.signal.aborted||(this.signal.aborted=!0,this.listeners.forEach((function(e){return e()})))}}();function B(e){this.message=e}B.prototype=new Error,B.prototype.name="InvalidCharacterError";"undefined"!=typeof window&&window.atob&&window.atob.bind(window);function K(e){this.message=e}K.prototype=new Error,K.prototype.name="InvalidTokenError";function Y(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Q(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Y(Object(r),!0).forEach((function(t){J(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Y(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function J(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function z(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function X(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){z(i,n,o,a,s,"next",e)}function s(e){z(i,n,o,a,s,"throw",e)}a(void 0)}))}}var Z=function(){var e=X((function*(e,t){var r=null,n=null;try{var o=Object.assign({},t);o.method||(o.method="GET"),o.body&&"string"!=typeof o.body&&(o.body=JSON.stringify(o.body));var i=yield fetch(e,o),s=yield i.json();null!=s&&s.error?(n=s).error_uri=new URL(e).pathname:r=s}catch(t){n={error:a.UNREACHABLE,error_description:t.message,error_uri:new URL(e).pathname}}if(n)throw n;return r}));return function(t,r){return e.apply(this,arguments)}}();var $=new class{constructor(e){this._env=(null==e?void 0:e.env)||""}getItem(e){var t=this;return X((function*(){return window.localStorage.getItem("".concat(e).concat(t._env))}))()}removeItem(e){var t=this;return X((function*(){window.localStorage.removeItem("".concat(e).concat(t._env))}))()}setItem(e,t){var r=this;return X((function*(){window.localStorage.setItem("".concat(e).concat(r._env),t)}))()}getItemSync(e){return window.localStorage.getItem("".concat(e).concat(this._env))}removeItemSync(e){window.localStorage.removeItem("".concat(e).concat(this._env))}setItemSync(e,t){window.localStorage.setItem("".concat(e).concat(this._env),t)}};function ee(e){var t=!0;return null!=e&&e.expires_at&&null!=e&&e.access_token&&(t=e.expires_at<new Date),t}class te{constructor(e){this.credentials=null,this.accessKeyCredentials=null,this.singlePromise=null,this.tokenSectionName=e.tokenSectionName,this.storage=e.storage,this.clientId=e.clientId,this.singlePromise=new p({clientId:this.clientId}),this.credentials=e.credentials||null}getStorageCredentialsSync(){var e=null,t=this.storage.getItemSync(this.tokenSectionName);if(null!=t)try{var r;null!==(r=e=JSON.parse(t))&&void 0!==r&&r.expires_at&&(e.expires_at=new Date(e.expires_at))}catch(t){this.storage.removeItem(this.tokenSectionName),e=null}return e}setCredentials(e){var t=this;return X((function*(){if(null!=e&&e.expires_in){if(null!=e&&e.expires_at||(e.expires_at=new Date(Date.now()+1e3*(e.expires_in-30))),t.storage){var r=JSON.stringify(e);yield t.storage.setItem(t.tokenSectionName,r)}t.credentials=e}else t.storage&&(yield t.storage.removeItem(t.tokenSectionName)),t.credentials=null}))()}setAccessKeyCredentials(e){this.accessKeyCredentials=e}getCredentials(){var e=this;return X((function*(){return e.singlePromise.run("getCredentials",X((function*(){if(ee(e.credentials)){var{credentials:t,isAccessKeyCredentials:r}=yield e.getStorageCredentials();if(r)return t;e.credentials=t}return e.credentials})))}))()}getStorageCredentials(){var e=this;return X((function*(){return e.singlePromise.run("_getStorageCredentials",X((function*(){var t=null,r=!1,n=yield e.storage.getItem(e.tokenSectionName);if(n)try{var o;null!==(o=t=JSON.parse(n))&&void 0!==o&&o.expires_at&&(t.expires_at=new Date(t.expires_at))}catch(r){yield e.storage.removeItem(e.tokenSectionName),t=null}else t=e.accessKeyCredentials||null,r=!0;return{credentials:t,isAccessKeyCredentials:r}})))}))()}}class re{constructor(e){this.singlePromise=null,e.clientSecret||(e.clientSecret=""),!e.clientId&&e.env&&(e.clientId=e.env),this.apiOrigin=e.apiOrigin,this.apiPath=e.apiPath||c,this.clientId=e.clientId,this.i18n=e.i18n,this.singlePromise=new p({clientId:this.clientId}),this.retry=this.formatRetry(e.retry,re.defaultRetry),e.baseRequest?this.baseRequest=e.baseRequest:this.baseRequest=Z,this.tokenInURL=e.tokenInURL,this.headers=e.headers,this.storage=e.storage||$,this.localCredentials=new te({tokenSectionName:"credentials_".concat(e.clientId),storage:this.storage,clientId:e.clientId}),this.clientSecret=e.clientSecret,e.clientId&&(this.basicAuth="Basic ".concat(function(e){for(var t,r,n,o,i="",a=0,s=(e=String(e)).length%3;a<e.length;){if((r=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");i+=v.charAt((t=r<<16|n<<8|o)>>18&63)+v.charAt(t>>12&63)+v.charAt(t>>6&63)+v.charAt(63&t)}return s?i.slice(0,s-3)+"===".substring(s):i}("".concat(e.clientId,":").concat(this.clientSecret)))),this.wxCloud=e.wxCloud;try{y()&&(this.useWxCloud=e.useWxCloud,void 0===this.wxCloud&&e.env&&(wx.cloud.init({env:e.env}),this.wxCloud=wx.cloud))}catch(e){}this.refreshTokenFunc=e.refreshTokenFunc||this.defaultRefreshTokenFunc,this.anonymousSignInFunc=e.anonymousSignInFunc,this.onCredentialsError=e.onCredentialsError,F.on("lang_change",e=>{var t;this.i18n=(null===(t=e.data)||void 0===t?void 0:t.i18n)||this.i18n})}setCredentials(e){return this.localCredentials.setCredentials(e)}setAccessKeyCredentials(e){return this.localCredentials.setAccessKeyCredentials(e)}getAccessToken(){var e=this;return X((function*(){var t=yield e.getCredentials();if(null!=t&&t.access_token)return Promise.resolve(t.access_token);var r={error:a.UNAUTHENTICATED};return Promise.reject(r)}))()}request(e,t){var r=this;return X((function*(){var n,o,i,s;t||(t={});var c=r.formatRetry(t.retry,r.retry);if(t.headers=Q(Q({},t.headers),{},{[null===(n=r.i18n)||void 0===n?void 0:n.LANG_HEADER_KEY]:null===(o=r.i18n)||void 0===o?void 0:o.lang}),r.headers&&(t.headers=Q(Q({},r.headers),t.headers)),t.headers["x-request-id"]||(t.headers["x-request-id"]=u()),!t.headers["x-device-id"]){var l=yield r.getDeviceId();t.headers["x-device-id"]=l}if(null!==(i=t)&&void 0!==i&&i.withBasicAuth&&r.basicAuth&&(t.headers.Authorization=r.basicAuth),null!==(s=t)&&void 0!==s&&s.withCredentials){var d=yield r.getCredentials();d&&(r.tokenInURL?(e.indexOf("?")<0&&(e+="?"),e+="access_token=".concat(d.access_token)):t.headers.Authorization="".concat(d.token_type," ").concat(d.access_token))}else r.clientId&&e.indexOf("client_id")<0&&(e+=e.indexOf("?")<0?"?":"&",e+="client_id=".concat(r.clientId));e.startsWith("/")&&(e="".concat(r.apiOrigin).concat(r.apiPath).concat(e));for(var h=null,f=c+1,p=0;p<f;p++){try{h=t.useWxCloud||r.useWxCloud?yield r.wxCloudCallFunction(e,t):yield r.baseRequest(e,t);break}catch(e){if(t.withCredentials&&e&&e.error===a.UNAUTHENTICATED)return yield r.setCredentials(null),Promise.reject(e);if(p===c||!e||"unreachable"!==e.error)return Promise.reject(e)}yield r.sleep(re.retryInterval)}return h}))()}wxCloudCallFunction(e,t){var r=this;return X((function*(){var n=null,o=null;try{var i,s="";try{s=yield wx.getRendererUserAgent()}catch(e){}var{result:c}=yield r.wxCloud.callFunction({name:"httpOverCallFunction",data:{url:e,method:t.method,headers:Q({origin:"https://servicewechat.com","User-Agent":s},t.headers),body:t.body}});null!=c&&null!==(i=c.body)&&void 0!==i&&i.error_code?(o=null==c?void 0:c.body).error_uri=(0,l.y)(e):n=null==c?void 0:c.body}catch(t){o={error:a.UNREACHABLE,error_description:t.message,error_uri:(0,l.y)(e)}}if(o)throw o;return n}))()}getCredentials(){var e=this;return X((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}if(ee(t))if(t.refresh_token)try{t=yield e.refreshToken(t)}catch(r){var o;if("anonymous"!==t.scope)return null===(o=e.onCredentialsError)||void 0===o||o.call(e,{msg:r.error_description}),Promise.reject(r);t=yield e.anonymousLogin(t)}else{if("anonymous"!==t.scope){var i,a="no refresh token found in credentials";return null===(i=e.onCredentialsError)||void 0===i||i.call(e,{msg:a}),e.unAuthenticatedError(a)}t=yield e.anonymousLogin(t)}return t}))()}getCredentialsSync(){return this.localCredentials.getStorageCredentialsSync()}getCredentialsAsync(){return this.getCredentials()}getScope(){var e=this;return X((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}return t.scope}))()}getGroups(){var e=this;return X((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}return t.groups}))()}refreshToken(e){var t=this;return X((function*(){return t.singlePromise.run("_refreshToken",X((function*(){if(!e||!e.refresh_token){var r,n="no refresh token found in credentials";return null===(r=t.onCredentialsError)||void 0===r||r.call(t,{msg:n}),t.unAuthenticatedError(n)}try{var o=yield t.refreshTokenFunc(e.refresh_token,e);return yield t.localCredentials.setCredentials(o),o}catch(e){var i;if(e.error===a.INVALID_GRANT){var s;yield t.localCredentials.setCredentials(null);var c=e.error_description;return null===(s=t.onCredentialsError)||void 0===s||s.call(t,{msg:c}),t.unAuthenticatedError(c)}return null===(i=t.onCredentialsError)||void 0===i||i.call(t,{msg:e.error_description}),Promise.reject(e)}})))}))()}anonymousLogin(e){var t=this;return X((function*(){return t.singlePromise.run("_anonymousLogin",X((function*(){if(t.anonymousSignInFunc){var r=yield t.anonymousSignInFunc(e);e=r||(yield t.localCredentials.getCredentials())}else e=yield t.anonymousSignIn(e);return e})))}))()}checkRetry(e){var t=null;if(("number"!=typeof e||e<re.minRetry||e>re.maxRetry)&&(t={error:a.UNREACHABLE,error_description:"wrong options param: retry"}),t)throw t;return e}formatRetry(e,t){return void 0===e?t:this.checkRetry(e)}sleep(e){return X((function*(){return new Promise(t=>{setTimeout(()=>{t()},e)})}))()}anonymousSignIn(e){var r=this;return X((function*(){return r.singlePromise.run("_anonymous",X((function*(){if(!e||"anonymous"!==e.scope)return r.unAuthenticatedError("no anonymous in credentials");try{var n=yield r.request(t.AUTH_SIGN_IN_ANONYMOUSLY_URL,{method:"POST",withBasicAuth:!0,body:{}});return yield r.localCredentials.setCredentials(n),n}catch(e){return e.error===a.INVALID_GRANT?(yield r.localCredentials.setCredentials(null),r.unAuthenticatedError(e.error_description)):Promise.reject(e)}})))}))()}defaultRefreshTokenFunc(e,r){var n=this;return X((function*(){if(void 0===e||""===e){var i,a="refresh token not found";return null===(i=n.onCredentialsError)||void 0===i||i.call(n,{msg:a}),n.unAuthenticatedError(a)}var s=t.AUTH_TOKEN_URL;return"v2"===(null==r?void 0:r.version)&&(s=o.AUTH_TOKEN_URL),Q(Q({},yield n.request(s,{method:"POST",body:{client_id:n.clientId,client_secret:n.clientSecret,grant_type:"refresh_token",refresh_token:e}})),{},{version:(null==r?void 0:r.version)||"v1"})}))()}getDeviceId(){var e=this;return X((function*(){if(e.deviceID)return e.deviceID;var t=yield e.storage.getItem("device_id");return"string"==typeof t&&t.length>=16&&t.length<=48||(t=u(),yield e.storage.setItem("device_id",t)),e.deviceID=t,t}))()}unAuthenticatedError(e){var t={error:a.UNAUTHENTICATED,error_description:e};return Promise.reject(t)}}re.defaultRetry=2,re.minRetry=0,re.maxRetry=5,re.retryInterval=1e3;const ne=class{constructor(e){if(this.params={},"string"==typeof e)this.parse(e);else if(e&&"object"==typeof e)for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.append(t,e[t])}parse(e){e.split("&").forEach(e=>{var[t,r]=e.split("=").map(decodeURIComponent);this.append(t,r)})}append(e,t){this.params[e]?this.params[e]=this.params[e].concat([t]):this.params[e]=[t]}get(e){return this.params[e]?this.params[e][0]:null}getAll(e){return this.params[e]||[]}delete(e){delete this.params[e]}has(e){return Object.prototype.hasOwnProperty.call(this.params,e)}set(e,t){this.params[e]=[t]}toString(){var e=this,t=[],r=function(r){Object.prototype.hasOwnProperty.call(e.params,r)&&e.params[r].forEach(e=>{t.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(e)))})};for(var n in this.params)r(n);return t.join("&")}};function oe(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function ie(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){oe(i,n,o,a,s,"next",e)}function s(e){oe(i,n,o,a,s,"throw",e)}a(void 0)}))}}class ae{constructor(e){e.openURIWithCallback||(e.openURIWithCallback=this.getDefaultOpenURIWithCallback()),e.storage||(e.storage=$),this.config=e,this.tokenSectionName="captcha_".concat(e.clientId)}isMatch(){var e,t;return(null===(e=this.config)||void 0===e||null===(e=e.adapter)||void 0===e||null===(t=e.isMatch)||void 0===t?void 0:t.call(e))||y()}request(e,t){var r=this;return ie((function*(){t||(t={}),t.method||(t.method="GET");var n,o="".concat(t.method,":").concat(e),i=e;t.withCaptcha&&(i=yield r.appendCaptchaTokenToURL(e,o,!1));try{n=yield r.config.request(i,t)}catch(n){return n.error===a.CAPTCHA_REQUIRED||n.error===a.CAPTCHA_INVALID?(e=yield r.appendCaptchaTokenToURL(e,o,n.error===a.CAPTCHA_INVALID),r.config.request(e,t)):Promise.reject(n)}return n}))()}getDefaultOpenURIWithCallback(){if(!this.isMatch()&&!m()&&(window.location.search.indexOf("__captcha")>0&&(document.body.style.display="none"),null===document.getElementById("captcha_panel_wrap"))){var e=document.createElement("div");e.style.cssText="background-color: rgba(0, 0, 0, 0.7);position: fixed;left: 0px;right: 0px;top: 0px;bottom: 0px;padding: 9vw 0 0 0;display: none;z-index:100;",e.setAttribute("id","captcha_panel_wrap"),setTimeout(()=>{document.body.appendChild(e)},0)}return this.defaultOpenURIWithCallback}defaultOpenURIWithCallback(e,t){return ie((function*(){var{width:r="355px",height:n="355px"}=t||{};if(e.match(/^(data:.*)$/))return Promise.reject({error:a.UNIMPLEMENTED,error_description:"need to impl captcha data"});var o=document.getElementById("captcha_panel_wrap"),i=document.createElement("iframe");return o.innerHTML="",i.setAttribute("src",e),i.setAttribute("id","review-panel-iframe"),i.style.cssText="min-width:".concat(r,";display:block;height:").concat(n,";margin:0 auto;background-color: rgb(255, 255, 255);border: none;"),o.appendChild(i),o.style.display="block",new Promise((e,t)=>{i.onload=function(){try{var r=window.location,n=i.contentWindow.location;if(n.host+n.pathname===r.host+r.pathname){o.style.display="none";var a=new ne(n.search),s=a.get("captcha_token");return s?e({captcha_token:s,expires_in:Number(a.get("expires_in"))}):t({error:a.get("error"),error_description:a.get("error_description")})}o.style.display="block"}catch(e){o.style.display="block"}}})}))()}getCaptchaToken(e,r){var n=this;return ie((function*(){if(!e){var o=yield n.findCaptchaToken();if(o)return o}var i;if(n.isMatch()||m()){var a=yield n.config.request(t.CAPTCHA_DATA_URL,{method:"POST",body:{state:r,redirect_uri:""},withCredentials:!1});i={url:"".concat(a.data,"?state=").concat(encodeURIComponent(r),"&token=").concat(encodeURIComponent(a.token))}}else{var s="".concat(window.location.origin+window.location.pathname,"?__captcha=on");if((i=yield n.config.request(t.GET_CAPTCHA_URL,{method:"POST",body:{client_id:n.config.clientId,redirect_uri:s,state:r},withCredentials:!1})).captcha_token){var c={captcha_token:i.captcha_token,expires_in:i.expires_in};return n.saveCaptchaToken(c),i.captcha_token}}var u=yield n.config.openURIWithCallback(i.url);return n.saveCaptchaToken(u),u.captcha_token}))()}appendCaptchaTokenToURL(e,t,r){var n=this;return ie((function*(){var o=yield n.getCaptchaToken(r,t);return e.indexOf("?")>0?e+="&captcha_token=".concat(o):e+="?captcha_token=".concat(o),e}))()}saveCaptchaToken(e){var t=this;return ie((function*(){e.expires_at=new Date(Date.now()+1e3*(e.expires_in-10));var r=JSON.stringify(e);yield t.config.storage.setItem(t.tokenSectionName,r)}))()}findCaptchaToken(){var e=this;return ie((function*(){var t=yield e.config.storage.getItem(e.tokenSectionName);if(null!=t)try{var r=JSON.parse(t);return null!=r&&r.expires_at&&(r.expires_at=new Date(r.expires_at)),r.expires_at<new Date?null:r.captcha_token}catch(t){return yield e.config.storage.removeItem(e.tokenSectionName),null}return null}))()}}var se=["provider_redirect_uri","other_params"];function ce(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function ue(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ce(i,n,o,a,s,"next",e)}function s(e){ce(i,n,o,a,s,"throw",e)}a(void 0)}))}}function le(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function de(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?le(Object(r),!0).forEach((function(t){he(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):le(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function he(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function fe(e,t){try{var n;if(((null==t||null===(n=t.root)||void 0===n?void 0:n.globalThis)||globalThis).IS_MP_BUILD)return;0}catch(t){if(e)return(()=>{try{return r(3)}catch(e){return}})()}}class pe{static parseParamsToSearch(e){return Object.keys(e).forEach(t=>{e[t]||delete e[t]}),new ne(e).toString()}constructor(e){var{request:t}=e,r=e.credentialsClient;if(!r){var n={apiOrigin:e.apiOrigin,apiPath:e.apiPath,clientId:e.clientId,storage:e.storage,env:e.env,baseRequest:e.baseRequest,anonymousSignInFunc:e.anonymousSignInFunc,wxCloud:e.wxCloud,onCredentialsError:e.onCredentialsError,headers:e.headers||{},i18n:e.i18n};r=new re(n)}if(!t){var o=r.request.bind(r),i=new ae(de({clientId:e.clientId,request:o,storage:e.storage,adapter:e.adapter},e.captchaOptions));t=i.request.bind(i)}this.config={env:e.env,apiOrigin:e.apiOrigin,apiPath:e.apiPath,clientId:e.clientId,request:t,credentialsClient:r,storage:e.storage||$,adapter:e.adapter}}getParamsByVersion(e,r){var n,i=(0,l.I)(e),a=(null===(n={v2:o}[null==i?void 0:i.version])||void 0===n?void 0:n[r])||t[r];return i&&delete i.version,{params:i,url:a}}signIn(e){var t=this;return ue((function*(){var r=e.version||"v1",n=t.getParamsByVersion(e,"AUTH_SIGN_IN_URL");n.params.query&&delete n.params.query;var o=yield t.getEncryptParams(n.params),i=yield t.config.request(n.url,{method:"POST",body:o});return yield t.config.credentialsClient.setCredentials(de(de({},i),{},{version:r})),Promise.resolve(i)}))()}signInAnonymously(){var e=arguments,r=this;return ue((function*(){var n=e.length>0&&void 0!==e[0]?e[0]:{},o=e.length>1&&void 0!==e[1]&&e[1],i=yield r.config.request(t.AUTH_SIGN_IN_ANONYMOUSLY_URL,{method:"POST",body:n,useWxCloud:o});return yield r.config.credentialsClient.setCredentials(i),Promise.resolve(i)}))()}signUp(e){var r=this;return ue((function*(){var n=yield r.config.request(t.AUTH_SIGN_UP_URL,{method:"POST",body:e});return yield r.config.credentialsClient.setCredentials(n),Promise.resolve(n)}))()}signOut(e){var r=this;return ue((function*(){var n={};if(e){try{n=yield r.config.request(t.AUTH_SIGNOUT_URL,{method:"POST",withCredentials:!0,body:e})}catch(e){e.error!==a.UNAUTHENTICATED&&console.log("sign_out_error",e)}return yield r.config.credentialsClient.setCredentials(),n}var o=yield r.config.credentialsClient.getAccessToken(),i=yield r.config.request(t.AUTH_REVOKE_URL,{method:"POST",body:{token:o}});return yield r.config.credentialsClient.setCredentials(),Promise.resolve(i)}))()}revokeAllDevices(){var e=this;return ue((function*(){yield e.config.request(t.AUTH_REVOKE_ALL_URL,{method:"DELETE",withCredentials:!0})}))()}revokeDevice(e){var r=this;return ue((function*(){yield r.config.request(t.AUTHORIZED_DEVICES_DELETE_URL+e.device_id,{method:"DELETE",withCredentials:!0})}))()}getVerification(e,r){var n=this;return ue((function*(){var o=!1;"CUR_USER"===e.target?o=!0:(yield n.hasLoginState())&&(o=!0);var i=(0,l.I)(e);return i.phone_number&&!/^\+\d{1,3}\s+\d+/.test(i.phone_number)&&(i.phone_number="+86 ".concat(i.phone_number)),n.config.request(t.VERIFICATION_URL,{method:"POST",body:i,withCaptcha:(null==r?void 0:r.withCaptcha)||!1,withCredentials:o})}))()}verify(e){var t=this;return ue((function*(){var r=t.getParamsByVersion(e,"VERIFY_URL"),n=yield t.config.request(r.url,{method:"POST",body:r.params});return"v2"===(null==e?void 0:e.version)&&(yield t.config.credentialsClient.setCredentials(de(de({},n),{},{version:"v2"}))),n}))()}genProviderRedirectUri(e){var r=this;return ue((function*(){var{provider_redirect_uri:n,other_params:o={}}=e,i=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.includes(r)||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,se);n&&!i.redirect_uri&&(i.redirect_uri=n);var a="".concat(t.PROVIDER_URI_URL,"?").concat(pe.parseParamsToSearch(i));return Object.keys(o).forEach(e=>{var t=o[e];("sign_out_uri"!==e||(null==t?void 0:t.length)>0)&&(a+="&other_params[".concat(e,"]=").concat(encodeURIComponent(t)))}),r.config.request(a,{method:"GET"})}))()}grantProviderToken(e){var r=arguments,n=this;return ue((function*(){var o=r.length>1&&void 0!==r[1]&&r[1];return n.config.request(t.PROVIDER_TOKEN_URL,{method:"POST",body:e,useWxCloud:o})}))()}patchProviderToken(e){var r=this;return ue((function*(){return r.config.request(t.PROVIDER_TOKEN_URL,{method:"PATCH",body:e})}))()}signInWithProvider(e){var t=arguments,r=this;return ue((function*(){var n=t.length>1&&void 0!==t[1]&&t[1],o=r.getParamsByVersion(e,"AUTH_SIGN_IN_WITH_PROVIDER_URL"),i=yield r.config.request(o.url,{method:"POST",body:o.params,useWxCloud:n});return yield r.config.credentialsClient.setCredentials(de(de({},i),{},{version:(null==e?void 0:e.version)||"v1"})),Promise.resolve(i)}))()}signInCustom(e){var r=this;return ue((function*(){var n=yield r.config.request(t.AUTH_SIGN_IN_CUSTOM,{method:"POST",body:e});return yield r.config.credentialsClient.setCredentials(n),Promise.resolve(n)}))()}signInWithWechat(){var e=arguments,r=this;return ue((function*(){var n=e.length>0&&void 0!==e[0]?e[0]:{},o=yield r.config.request(t.AUTH_SIGN_IN_WITH_WECHAT_URL,{method:"POST",body:n});return yield r.config.credentialsClient.setCredentials(o),Promise.resolve(o)}))()}bindWithProvider(e){var r=this;return ue((function*(){return r.config.request(t.PROVIDER_BIND_URL,{method:"POST",body:e,withCredentials:!0})}))()}getUserProfile(e){var t=this;return ue((function*(){return t.getUserInfo(e)}))()}getUserInfo(){var e=arguments,t=this;return ue((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},o=t.getParamsByVersion(n,"USER_ME_URL");if(null!==(r=o.params)&&void 0!==r&&r.query){var i=new ne(o.params.query);o.url+="?".concat(i.toString())}var a=yield t.config.request(o.url,{method:"GET",withCredentials:!0});return a.sub&&(a.uid=a.sub),a}))()}getWedaUserInfo(){var e=this;return ue((function*(){return yield e.config.request(t.WEDA_USER_URL,{method:"GET",withCredentials:!0})}))()}deleteMe(e){var t=this;return ue((function*(){var r=t.getParamsByVersion(e,"USER_ME_URL"),n="".concat(r.url,"?").concat(pe.parseParamsToSearch(r.params));return t.config.request(n,{method:"DELETE",withCredentials:!0})}))()}hasLoginState(){var e=this;return ue((function*(){try{return yield e.config.credentialsClient.getAccessToken(),!0}catch(e){return!1}}))()}hasLoginStateSync(){return this.config.credentialsClient.getCredentialsSync()}getLoginState(){var e=this;return ue((function*(){return e.config.credentialsClient.getCredentialsAsync()}))()}transByProvider(e){var r=this;return ue((function*(){return r.config.request(t.USER_TRANS_BY_PROVIDER_URL,{method:"PATCH",body:e,withCredentials:!0})}))()}grantToken(e){var t=this;return ue((function*(){var r=t.getParamsByVersion(e,"AUTH_TOKEN_URL");return t.config.request(r.url,{method:"POST",body:r.params})}))()}getProviders(){var e=this;return ue((function*(){return e.config.request(t.PROVIDER_LIST,{method:"GET",withCredentials:!0})}))()}unbindProvider(e){var r=this;return ue((function*(){return r.config.request("".concat(t.PROVIDER_UNBIND_URL,"/").concat(e.provider_id),{method:"DELETE",withCredentials:!0})}))()}checkPassword(e){var r=this;return ue((function*(){return r.config.request("".concat(t.CHECK_PWD_URL),{method:"POST",withCredentials:!0,body:e})}))()}editContact(e){var r=this;return ue((function*(){return r.config.request("".concat(t.BIND_CONTACT_URL),{method:"PATCH",withCredentials:!0,body:e})}))()}setPassword(e){var r=this;return ue((function*(){return r.config.request("".concat(t.AUTH_SET_PASSWORD),{method:"PATCH",withCredentials:!0,body:e})}))()}updatePasswordByOld(e){var t=this;return ue((function*(){var r=yield t.sudo({password:e.old_password});return t.setPassword({sudo_token:r.sudo_token,new_password:e.new_password})}))()}sudo(e){var r=this;return ue((function*(){return r.config.request("".concat(t.SUDO_URL),{method:"POST",withCredentials:!0,body:e})}))()}sendVerificationCodeToCurrentUser(e){var r=this;return ue((function*(){return e.target="CUR_USER",r.config.request(t.VERIFICATION_URL,{method:"POST",body:e,withCredentials:!0,withCaptcha:!0})}))()}changeBoundProvider(e){var r=this;return ue((function*(){return r.config.request("".concat(t.PROVIDER_LIST,"/").concat(e.provider_id,"/trans"),{method:"POST",body:{provider_trans_token:e.trans_token},withCredentials:!0})}))()}setUserProfile(e){var r=this;return ue((function*(){return r.config.request(t.USER_PRIFILE_URL,{method:"PATCH",body:e,withCredentials:!0})}))()}updateUserBasicInfo(e){var r=this;return ue((function*(){return r.config.request(t.USER_BASIC_EDIT_URL,{method:"POST",withCredentials:!0,body:e})}))()}queryUserProfile(e){var r=this;return ue((function*(){var n=new ne(e);return r.config.request("".concat(t.USER_QUERY_URL,"?").concat(n.toString()),{method:"GET",withCredentials:!0})}))()}setCustomSignFunc(e){this.getCustomSignTicketFn=e}signInWithCustomTicket(){var e=this;return ue((function*(){var t=e.getCustomSignTicketFn;if(!t)return Promise.reject({error:"failed_precondition",error_description:"please use setCustomSignFunc to set custom sign function"});var r=yield t();return e.signInCustom({provider_id:"custom",ticket:r})}))()}resetPassword(e){var r=this;return ue((function*(){return r.config.request(t.AUTH_RESET_PASSWORD,{method:"POST",body:e})}))()}authorize(e){var r=this;return ue((function*(){return r.config.request(t.AUTHORIZE_URL,{method:"POST",withCredentials:!0,body:e})}))()}authorizeDevice(e){var r=this;return ue((function*(){return r.config.request(t.AUTHORIZE_DEVICE_URL,{method:"POST",withCredentials:!0,body:e})}))()}deviceAuthorize(e){var r=this;return ue((function*(){return r.config.request(t.AUTH_GET_DEVICE_CODE,{method:"POST",body:e,withCredentials:!0})}))()}authorizeInfo(e){var r=this;return ue((function*(){var n="".concat(t.AUTHORIZE_INFO_URL,"?").concat(pe.parseParamsToSearch(e)),o=!0,i=!1;return(yield r.hasLoginState())&&(i=!0,o=!1),r.config.request(n,{method:"GET",withBasicAuth:o,withCredentials:i})}))()}checkUsername(e){var r=this;return ue((function*(){return r.config.request(t.CHECK_USERNAME,{method:"GET",body:e,withCredentials:!0})}))()}checkIfUserExist(e){var r=this;return ue((function*(){var n=new ne(e);return r.config.request("".concat(t.CHECK_IF_USER_EXIST,"?").concat(n.toString()),{method:"GET"})}))()}loginScope(){var e=this;return ue((function*(){return e.config.credentialsClient.getScope()}))()}loginGroups(){var e=this;return ue((function*(){return e.config.credentialsClient.getGroups()}))()}refreshTokenForce(e){var t=this;return ue((function*(){var r=yield t.config.credentialsClient.getCredentials();return yield t.config.credentialsClient.refreshToken(de(de({},r),{},{version:(null==e?void 0:e.version)||"v1"}))}))()}getCredentials(){var e=this;return ue((function*(){return e.config.credentialsClient.getCredentials()}))()}getPublicKey(){var e=this;return ue((function*(){return e.config.request(o.AUTH_PUBLIC_KEY,{method:"POST",body:{}})}))()}getEncryptParams(e){var t=this;return ue((function*(){var{isEncrypt:r}=e;delete e.isEncrypt;var n=(0,l.I)(e),o=fe(r,t.config.adapter);if(!o)return e;var i="",a="";try{var s=yield t.getPublicKey();if(i=s.public_key,a=s.public_key_thumbprint,!i||!a)throw s}catch(e){throw e}return{params:o.getEncryptInfo({publicKey:i,payload:n}),public_key_thumbprint:a}}))()}getProviderSubType(){var e=this;return ue((function*(){return e.config.request(t.GET_PROVIDER_TYPE,{method:"POST",body:{provider_id:"weda"}})}))()}verifyCaptchaData(e){var r=this;return ue((function*(){var{token:n,key:o}=e;return r.config.request(t.VERIFY_CAPTCHA_DATA_URL,{method:"POST",body:{token:n,key:o},withCredentials:!1})}))()}createCaptchaData(e){var r=this;return ue((function*(){var{state:n,redirect_uri:o}=e;return r.config.request(t.CAPTCHA_DATA_URL,{method:"POST",body:{state:n,redirect_uri:o},withCredentials:!1})}))()}getMiniProgramCode(e){var r=this;return ue((function*(){return r.config.request(t.GET_MINIPROGRAM_QRCODE,{method:"POST",body:e})}))()}getMiniProgramQrCodeStatus(e){var r=this;return ue((function*(){return r.config.request(t.GET_MINIPROGRAM_QRCODE_STATUS,{method:"POST",body:e})}))()}getUserBehaviorLog(e){var r=this;return ue((function*(){var n="".concat(t.GET_USER_BEHAVIOR_LOG,"?").concat({LOGIN:"query[action]=USER_LOGIN",MODIFY:"ne_query[action]=USER_LOGIN"}[e.type],"&limit=").concat(e.limit).concat(e.page_token?"&page_token=".concat(e.page_token):"");return r.config.request(n,{method:"GET",withCredentials:!0})}))()}modifyPassword(e){var r=this;return ue((function*(){var n="",o="",i=fe(!0,r.config.adapter);if(!i)throw new Error("do not support encrypt, a encrypt util required.");try{var a=yield r.getPublicKey();if(n=a.public_key,o=a.public_key_thumbprint,!n||!o)throw a}catch(e){throw e}var s=e.password?i.getEncryptInfo({publicKey:n,payload:e.password}):"",c=i.getEncryptInfo({publicKey:n,payload:e.new_password});return r.config.request(t.USER_BASIC_EDIT_URL,{method:"POST",withCredentials:!0,body:{user_id:e.user_id,encrypt_password:s,encrypt_new_password:c,public_key_thumbprint:o}})}))()}modifyPasswordWithoutLogin(e){var t=this;return ue((function*(){var r="",n="",i=fe(!0,t.config.adapter);if(!i)throw new Error("do not support encrypt, a encrypt util required.");try{var a=yield t.getPublicKey();if(r=a.public_key,n=a.public_key_thumbprint,!r||!n)throw a}catch(e){throw e}var s=e.password?i.getEncryptInfo({publicKey:r,payload:e.password}):"",c=i.getEncryptInfo({publicKey:r,payload:e.new_password});return t.config.request(o.AUTH_RESET_PASSWORD,{method:"POST",body:{username:e.username,password:s,new_password:c,public_key_thumbprint:n}})}))()}}function ve(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ye(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(r),!0).forEach((function(t){_e(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ve(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _e(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class ge{constructor(e){var{apiOrigin:t,apiPath:r=c,clientId:n,env:o,storage:i,request:a,baseRequest:s,anonymousSignInFunc:u,wxCloud:l,adapter:d,onCredentialsError:h,headers:f,i18n:p,useWxCloud:v}=e;this.oauth2client=new re({apiOrigin:t,apiPath:r,clientId:n,env:o,storage:i,baseRequest:s||a,anonymousSignInFunc:u,wxCloud:l,onCredentialsError:h,headers:f||{},i18n:p,useWxCloud:v}),this.authApi=new pe(ye(ye({credentialsClient:this.oauth2client},e),{},{request:a?this.oauth2client.request.bind(this.oauth2client):void 0,adapter:d}))}}})(),n})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("tcboauth",[],t):"object"==typeof exports?exports.tcboauth=t():e.tcboauth=t()}("undefined"!=typeof window?window:this,()=>(()=>{"use strict";var e={3:(e,t,r)=>{r.r(t),r.d(t,{getEncryptInfo:()=>i});const n=void 0;var o=r(912),i=function(){var{publicKey:e="",payload:t={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!e)return"";try{var r=(0,o.I)(t),i=new n;i.setPublicKey(e);var a=i.encryptLong("object"==typeof r?JSON.stringify(r):r);return a}catch(e){console.error("encrypt error:",e)}return""}},912:(e,t,r)=>{r.d(t,{I:()=>n,y:()=>o});var n=e=>{var t=t=>{for(var r in e)e.hasOwnProperty(r)&&(t[r]=n(e[r]));return t},r=null==e?"NullOrUndefined":Object.prototype.toString.call(e).slice(8,-1);if(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"].includes(r))return e.slice();switch(r){case"Object":return t(Object.create(Object.getPrototypeOf(e)));case"Array":return t([]);case"Date":return new Date(e.valueOf());case"RegExp":return new RegExp(e.source,(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":""));default:return e}},o=e=>{var t=e.match(/^(?:http(s)?:\/\/[^\/]+)?(\/[^\?#]*)/);return t&&t[2]||""}},946:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COMMUNITY_SITE_URL=t.IS_DEBUG_MODE=t.getProtocol=t.setProtocol=t.getSdkName=t.setSdkName=void 0;var r="@cloudbase/js-sdk";t.setSdkName=function(e){r=e},t.getSdkName=function(){return r};var n="https:";t.setProtocol=function(e){n=e},t.getProtocol=function(){return n},t.IS_DEBUG_MODE=!1,t.COMMUNITY_SITE_URL="https://support.qq.com/products/148793"},205:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ERRORS=void 0,t.ERRORS={INVALID_PARAMS:"INVALID_PARAMS",INVALID_SYNTAX:"INVALID_SYNTAX",INVALID_OPERATION:"INVALID_OPERATION",OPERATION_FAIL:"OPERATION_FAIL",NETWORK_ERROR:"NETWORK_ERROR",UNKOWN_ERROR:"UNKOWN_ERROR"}},794:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.OATUH_LOGINTYPE=void 0,o(r(946),t),o(r(205),t),t.OATUH_LOGINTYPE="constants"},689:function(e,t,r){var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.removeEventListener=t.activateEvent=t.addEventListener=t.CloudbaseEventEmitter=t.IErrorEvent=t.CloudbaseEvent=void 0;var a=r(616);var s=function(e,t){this.data=t||null,this.name=e};t.CloudbaseEvent=s;var c=function(e){function t(t,r){var n=e.call(this,"error",{error:t,data:r})||this;return n.error=t,n}return o(t,e),t}(s);t.IErrorEvent=c;var u=function(){function e(){this.listeners={}}return e.prototype.on=function(e,t){return function(e,t,r){r[e]=r[e]||[],r[e].push(t)}(e,t,this.listeners),this},e.prototype.off=function(e,t){return function(e,t,r){if(null==r?void 0:r[e]){var n=r[e].indexOf(t);-1!==n&&r[e].splice(n,1)}}(e,t,this.listeners),this},e.prototype.fire=function(e,t){if((0,a.isInstanceOf)(e,c))return console.error(e.error),this;var r=(0,a.isString)(e)?new s(e,t||{}):e,n=r.name;if(this.listens(n)){r.target=this;for(var o=0,u=this.listeners[n]?i([],this.listeners[n],!0):[];o<u.length;o++){u[o].call(this,r)}}return this},e.prototype.listens=function(e){return this.listeners[e]&&this.listeners[e].length>0},e}();t.CloudbaseEventEmitter=u;var l=new u;t.addEventListener=function(e,t){l.on(e,t)},t.activateEvent=function(e,t){void 0===t&&(t={}),l.fire(e,t)},t.removeEventListener=function(e,t){l.off(e,t)}},616:function(e,t,r){var n=this&&this.__rest||function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r};Object.defineProperty(t,"__esModule",{value:!0}),t.parseCaptcha=t.parseQueryString=t.transformPhone=t.sleep=t.printGroupLog=t.throwError=t.printInfo=t.printError=t.printWarn=t.execCallback=t.createPromiseCallback=t.removeParam=t.getHash=t.getQuery=t.toQueryString=t.formatUrl=t.generateRequestId=t.genSeqId=t.isFormData=t.isInstanceOf=t.isNull=t.isPalinObject=t.isUndefined=t.isString=t.isArray=void 0;var o=r(794);t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.isString=function(e){return"string"==typeof e},t.isUndefined=function(e){return void 0===e},t.isPalinObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.isNull=function(e){return"[object Null]"===Object.prototype.toString.call(e)},t.isInstanceOf=function(e,t){return e instanceof t},t.isFormData=function(e){return"[object FormData]"===Object.prototype.toString.call(e)},t.genSeqId=function(){return Math.random().toString(16).slice(2)},t.generateRequestId=function(){var e=(new Date).getTime(),t=(null===Date||void 0===Date?void 0:Date.now)&&1e3*Date.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(r){var n=16*Math.random();return e>0?(n=(e+n)%16|0,e=Math.floor(e/16)):(n=(t+n)%16|0,t=Math.floor(t/16)),("x"===r?n:7&n|8).toString(16)}))},t.formatUrl=function(e,t,r){void 0===r&&(r={});var n=/\?/.test(t),o="";return Object.keys(r).forEach((function(e){""===o?!n&&(t+="?"):o+="&",o+="".concat(e,"=").concat(encodeURIComponent(r[e]))})),/^http(s)?:\/\//.test(t+=o)?t:"".concat(e).concat(t)},t.toQueryString=function(e){void 0===e&&(e={});var t=[];return Object.keys(e).forEach((function(r){t.push("".concat(r,"=").concat(encodeURIComponent(e[r])))})),t.join("&")},t.getQuery=function(e,t){if("undefined"==typeof window)return!1;var r=t||decodeURIComponent(window.location.search),n=new RegExp("(^|&)".concat(e,"=([^&]*)(&|$)")),o=r.substr(r.indexOf("?")+1).match(n);return null!=o?o[2]:""};t.getHash=function(e){if("undefined"==typeof window)return"";var t=window.location.hash.match(new RegExp("[#?&/]".concat(e,"=([^&#]*)")));return t?t[1]:""},t.removeParam=function(e,t){var r=t.split("?")[0],n=[],o=-1!==t.indexOf("?")?t.split("?")[1]:"";if(""!==o){for(var i=(n=o.split("&")).length-1;i>=0;i-=1)n[i].split("=")[0]===e&&n.splice(i,1);r="".concat(r,"?").concat(n.join("&"))}return r},t.createPromiseCallback=function(){var e={};if(!Promise){(e=function(){}).promise={};var t=function(){throw new Error('Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.')};return Object.defineProperty(e.promise,"then",{get:t}),Object.defineProperty(e.promise,"catch",{get:t}),e}var r=new Promise((function(t,r){e=function(e,n){return e?r(e):t(n)}}));return e.promise=r,e},t.execCallback=function(e,t,r){if(void 0===r&&(r=null),e&&"function"==typeof e)return e(t,r);if(t)throw t;return r},t.printWarn=function(e,t){console.warn("[".concat((0,o.getSdkName)(),"][").concat(e,"]:").concat(t))},t.printError=function(e,t){console.error({code:e,msg:"[".concat((0,o.getSdkName)(),"][").concat(e,"]:").concat(t)})},t.printInfo=function(e,t){console.log("[".concat((0,o.getSdkName)(),"][").concat(e,"]:").concat(t))},t.throwError=function(e,t){throw new Error(JSON.stringify({code:e,msg:"[".concat((0,o.getSdkName)(),"][").concat(e,"]:").concat(t)}))},t.printGroupLog=function(e){var t,r=e.title,n=e.subtitle,o=void 0===n?"":n,i=e.content,a=void 0===i?[]:i,s=e.printTrace,c=void 0!==s&&s,u=e.collapsed;void 0!==u&&u?(console.groupCollapsed||console.error)(r,o):(console.group||console.error)(r,o);for(var l=0,d=a;l<d.length;l++){var f=d[l],p=f.type,h=f.body;switch(p){case"info":console.log(h);break;case"warn":console.warn(h);break;case"error":console.error(h)}}c&&(console.trace||console.log)("stack trace:"),null===(t=console.groupEnd)||void 0===t||t.call(console)};t.sleep=function(e){return void 0===e&&(e=0),new Promise((function(t){return setTimeout(t,e)}))},t.transformPhone=function(e){return"+86".concat(e)};t.parseQueryString=function(e){e=e.replace(/^\?/,"");var t={};return e.split("&").forEach((function(e){var r=e.split("="),n=r[0],o=r[1];n=decodeURIComponent(n),o=decodeURIComponent(o),n&&(t[n]?Array.isArray(t[n])?t[n].push(o):t[n]=[t[n],o]:t[n]=o)})),t},t.parseCaptcha=function(e){var r={},o=e.match(/^(data:.*?)(\?[^#\s]*)?$/);if(o){e=o[1];var i=o[2];i&&(r=(0,t.parseQueryString)(i))}var a=r.token,s=n(r,["token"]);return/^data:/.test(e)&&!a?{error:"invalid_argument",error_description:"invalid captcha data: ".concat(e)}:a?{state:s.state,token:a,captchaData:e}:{error:"unimplemented",error_description:"need to impl captcha data"}}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{AUTH_API_PREFIX:()=>s,AUTH_STATE_CHANGED_TYPE:()=>l,Auth:()=>Me,AuthError:()=>Be,CloudbaseOAuth:()=>Ye,EVENTS:()=>d,LOGIN_STATE_CHANGED_TYPE:()=>u,OAUTH_TYPE:()=>f,authModels:()=>e,weappJwtDecodeAll:()=>O});var e={};r.r(e);var t,o,i,a,s="/auth";!function(e){e.AUTH_SIGN_UP_URL="/v1/signup",e.AUTH_TOKEN_URL="/v1/token",e.AUTH_REVOKE_URL="/v1/revoke",e.WEDA_USER_URL="/v1/plugin/weda/userinfo",e.AUTH_RESET_PASSWORD="/v1/reset",e.AUTH_GET_DEVICE_CODE="/v1/device/code",e.CHECK_USERNAME="/v1/checkUsername",e.CHECK_IF_USER_EXIST="/v1/checkIfUserExist",e.GET_PROVIDER_TYPE="/v1/mgr/provider/providerSubType",e.AUTH_SIGN_IN_URL="/v1/signin",e.AUTH_SIGN_IN_ANONYMOUSLY_URL="/v1/signin/anonymously",e.AUTH_SIGN_IN_WITH_PROVIDER_URL="/v1/signin/with/provider",e.AUTH_SIGN_IN_WITH_WECHAT_URL="/v1/signin/wechat/noauth",e.AUTH_SIGN_IN_CUSTOM="/v1/signin/custom",e.PROVIDER_TOKEN_URL="/v1/provider/token",e.PROVIDER_URI_URL="/v1/provider/uri",e.USER_ME_URL="/v1/user/me",e.AUTH_SIGNOUT_URL="/v1/user/signout",e.USER_QUERY_URL="/v1/user/query",e.USER_PRIFILE_URL="/v1/user/profile",e.USER_BASIC_EDIT_URL="/v1/user/basic/edit",e.USER_TRANS_BY_PROVIDER_URL="/v1/user/trans/by/provider",e.PROVIDER_LIST="/v1/user/provider",e.PROVIDER_BIND_URL="/v1/user/provider/bind",e.PROVIDER_UNBIND_URL="/v1/user/provider",e.CHECK_PWD_URL="/v1/user/sudo",e.SUDO_URL="/v1/user/sudo",e.BIND_CONTACT_URL="/v1/user/contact",e.AUTH_SET_PASSWORD="/v1/user/password",e.AUTHORIZE_DEVICE_URL="/v1/user/device/authorize",e.AUTHORIZE_URL="/v1/user/authorize",e.AUTHORIZE_INFO_URL="/v1/user/authorize/info",e.AUTHORIZED_DEVICES_DELETE_URL="/v1/user/authorized/devices/",e.AUTH_REVOKE_ALL_URL="/v1/user/revoke/all",e.GET_USER_BEHAVIOR_LOG="/v1/user/security/history",e.VERIFICATION_URL="/v1/verification",e.VERIFY_URL="/v1/verification/verify",e.CAPTCHA_DATA_URL="/v1/captcha/data",e.VERIFY_CAPTCHA_DATA_URL="/v1/captcha/data/verify",e.GET_CAPTCHA_URL="/v1/captcha/init",e.GET_MINIPROGRAM_QRCODE="/v1/qrcode/generate",e.GET_MINIPROGRAM_QRCODE_STATUS="/v1/qrcode/get/status"}(t||(t={})),function(e){e.AUTH_SIGN_IN_URL="/v2/signin/username",e.AUTH_TOKEN_URL="/v2/token",e.USER_ME_URL="/v2/user/me",e.VERIFY_URL="/v2/signin/verificationcode",e.AUTH_SIGN_IN_WITH_PROVIDER_URL="/v2/signin/with/provider",e.AUTH_PUBLIC_KEY="/v2/signin/publichkey",e.AUTH_RESET_PASSWORD="/v2/signin/password/update"}(o||(o={})),function(e){e.REGISTER="REGISTER",e.SIGN_IN="SIGN_IN",e.PASSWORD_RESET="PASSWORD_RESET",e.EMAIL_ADDRESS_CHANGE="EMAIL_ADDRESS_CHANGE",e.PHONE_NUMBER_CHANGE="PHONE_NUMBER_CHANGE"}(i||(i={})),function(e){e.UNREACHABLE="unreachable",e.LOCAL="local",e.CANCELLED="cancelled",e.UNKNOWN="unknown",e.UNAUTHENTICATED="unauthenticated",e.RESOURCE_EXHAUSTED="resource_exhausted",e.FAILED_PRECONDITION="failed_precondition",e.INVALID_ARGUMENT="invalid_argument",e.DEADLINE_EXCEEDED="deadline_exceeded",e.NOT_FOUND="not_found",e.ALREADY_EXISTS="already_exists",e.PERMISSION_DENIED="permission_denied",e.ABORTED="aborted",e.OUT_OF_RANGE="out_of_range",e.UNIMPLEMENTED="unimplemented",e.INTERNAL="internal",e.UNAVAILABLE="unavailable",e.DATA_LOSS="data_loss",e.INVALID_PASSWORD="invalid_password",e.PASSWORD_NOT_SET="password_not_set",e.INVALID_STATUS="invalid_status",e.USER_PENDING="user_pending",e.USER_BLOCKED="user_blocked",e.INVALID_VERIFICATION_CODE="invalid_verification_code",e.TWO_FACTOR_REQUIRED="two_factor_required",e.INVALID_TWO_FACTOR="invalid_two_factor",e.INVALID_TWO_FACTOR_RECOVERY="invalid_two_factor_recovery",e.UNDER_REVIEW="under_review",e.INVALID_REQUEST="invalid_request",e.UNAUTHORIZED_CLIENT="unauthorized_client",e.ACCESS_DENIED="access_denied",e.UNSUPPORTED_RESPONSE_TYPE="unsupported_response_type",e.INVALID_SCOPE="invalid_scope",e.INVALID_GRANT="invalid_grant",e.SERVER_ERROR="server_error",e.TEMPORARILY_UNAVAILABLE="temporarily_unavailable",e.INTERACTION_REQUIRED="interaction_required",e.LOGIN_REQUIRED="login_required",e.ACCOUNT_SELECTION_REQUIRED="account_selection_required",e.CONSENT_REQUIRED="consent_required",e.INVALID_REQUEST_URI="invalid_request_uri",e.INVALID_REQUEST_OBJECT="invalid_request_object",e.REQUEST_NOT_SUPPORTED="request_not_supported",e.REQUEST_URI_NOT_SUPPORTED="request_uri_not_supported",e.REGISTRATION_NOT_SUPPORTED="registration_not_supported",e.CAPTCHA_REQUIRED="captcha_required",e.CAPTCHA_INVALID="captcha_invalid"}(a||(a={}));var c,u={SIGN_OUT:"sign_out",SIGN_IN:"sign_in",CREDENTIALS_ERROR:"credentials_error"},l={SIGNED_OUT:"SIGNED_OUT",SIGNED_IN:"SIGNED_IN",INITIAL_SESSION:"INITIAL_SESSION",PASSWORD_RECOVERY:"PASSWORD_RECOVERY",TOKEN_REFRESHED:"TOKEN_REFRESHED",USER_UPDATED:"USER_UPDATED",BIND_IDENTITY:"BIND_IDENTITY"},d={LOGIN_STATE_CHANGED:"loginStateChanged",AUTH_STATE_CHANGED:"authStateChanged"},f={SIGN_IN:"sign_in",BIND_IDENTITY:"bind_identity"};function p(){return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}!function(e){e.CLIENT_ID="client_id",e.CLIENT_SECRET="client_secret",e.RESPONSE_TYPE="response_type",e.SCOPE="scope",e.STATE="state",e.REDIRECT_URI="redirect_uri",e.ERROR="error",e.ERROR_DESCRIPTION="error_description",e.ERROR_URI="error_uri",e.GRANT_TYPE="grant_type",e.CODE="code",e.ACCESS_TOKEN="access_token",e.TOKEN_TYPE="token_type",e.EXPIRES_IN="expires_in",e.USERNAME="username",e.PASSWORD="password",e.REFRESH_TOKEN="refresh_token"}(c||(c={}));var h=r(912);function v(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function y(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){v(i,n,o,a,s,"next",e)}function s(e){v(i,n,o,a,s,"throw",e)}a(void 0)}))}}var g=new Map;class _{constructor(e){this.clientId=(null==e?void 0:e.clientId)||"",g=g||new Map}run(e,t){var r=this;return y((function*(){e="".concat(r.clientId,"_").concat(e);var n=g.get(e);return n||(n=new Promise((n,o)=>{y((function*(){try{yield r.runIdlePromise();var i=t();n(yield i)}catch(e){o(e)}finally{g.delete(e)}}))()}),g.set(e,n)),n}))()}runIdlePromise(){return Promise.resolve()}}var m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",E=/^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;var I=function(e){if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!E.test(e))throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");var t;e+="==".slice(2-(3&e.length));for(var r,n,o="",i=0;i<e.length;)t=m.indexOf(e.charAt(i++))<<18|m.indexOf(e.charAt(i++))<<12|(r=m.indexOf(e.charAt(i++)))<<6|(n=m.indexOf(e.charAt(i++))),o+=64===r?String.fromCharCode(t>>16&255):64===n?String.fromCharCode(t>>16&255,t>>8&255):String.fromCharCode(t>>16&255,t>>8&255,255&t);return o};function b(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("Illegal base64url string!")}try{return function(e){return decodeURIComponent(I(e).replace(/(.)/g,e=>{var t=e.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0".concat(t)),"%".concat(t)}))}(t)}catch(e){return I(t)}}function O(e){if("string"!=typeof e)throw new Error("Invalid token specified");try{var t=e.split(".").map((e,t)=>2===t?e:JSON.parse(b(e)));return{claims:t[1],header:t[0],signature:t[2]}}catch(e){throw new Error("Invalid token specified: ".concat(e)?e.message:0)}}function S(){if("undefined"==typeof globalThis)return!1;var{wx:e}=globalThis;if(void 0===e)return!1;if(void 0===globalThis.Page)return!1;if(!e.getSystemInfoSync)return!1;if(!e.getStorageSync)return!1;if(!e.setStorageSync)return!1;if(!e.connectSocket)return!1;if(!e.request)return!1;try{if(!e.getSystemInfoSync())return!1;if("qq"===e.getSystemInfoSync().AppPlatform)return!1}catch(e){return!1}return!0}var R=!1;function C(){R=R||void 0!==typeof window&&"miniprogram"===window.__wxjs_environment}try{S()||(R=R||!!navigator.userAgent.match(/miniprogram/i)||"miniprogram"===window.__wxjs_environment,window&&window.WeixinJSBridge&&window.WeixinJSBridge.invoke?C():"undefined"!=typeof document&&document.addEventListener("WeixinJSBridgeReady",C,!1))}catch(X){}var T="@cloudbase/js-sdk";function w(){return T}var A="https:";var P,U="INVALID_PARAMS",N="INVALID_OPERATION",D="OPERATION_FAIL";!function(e){e.local="local",e.none="none",e.session="session"}(P||(P={}));var x=function(){};function k(e,t){console.warn("[".concat(w(),"][").concat(e,"]:").concat(t))}var L,j=(L=function(e,t){return(L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}L(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),q=function(){return(q=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},H=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((n=n.apply(e,t||[])).next())}))},G=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};!function(e){function t(t){var r=e.call(this)||this,n=t.timeout,o=t.timeoutMsg,i=t.restrictedMethods;return r.timeout=n||0,r.timeoutMsg=o||"请求超时",r.restrictedMethods=i||["get","post","upload","download"],r}j(t,e),t.prototype.get=function(e){return this.request(q(q({},e),{method:"get"}),this.restrictedMethods.includes("get"))},t.prototype.post=function(e){return this.request(q(q({},e),{method:"post"}),this.restrictedMethods.includes("post"))},t.prototype.put=function(e){return this.request(q(q({},e),{method:"put"}))},t.prototype.upload=function(e){var t=e.data,r=e.file,n=e.name,o=e.method,i=e.headers,a=void 0===i?{}:i,s={post:"post",put:"put"}[null==o?void 0:o.toLowerCase()]||"put",c=new FormData;return"post"===s?(Object.keys(t).forEach((function(e){c.append(e,t[e])})),c.append("key",n),c.append("file",r),this.request(q(q({},e),{data:c,method:s}),this.restrictedMethods.includes("upload"))):this.request(q(q({},e),{method:"put",headers:a,body:r}),this.restrictedMethods.includes("upload"))},t.prototype.download=function(e){return H(this,void 0,void 0,(function(){var t,r,n,o;return G(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.get(q(q({},e),{headers:{},responseType:"blob"}))];case 1:return t=i.sent().data,r=window.URL.createObjectURL(new Blob([t])),n=decodeURIComponent(new URL(e.url).pathname.split("/").pop()||""),(o=document.createElement("a")).href=r,o.setAttribute("download",n),o.style.display="none",document.body.appendChild(o),o.click(),window.URL.revokeObjectURL(r),document.body.removeChild(o),[3,3];case 2:return i.sent(),[3,3];case 3:return[2,new Promise((function(t){t({statusCode:200,tempFilePath:e.url})}))]}}))}))},t.prototype.fetch=function(e){var t;return H(this,void 0,void 0,(function(){var r,n,o,i,a,s,c,u,l,d,f,p,h,v=this;return G(this,(function(y){switch(y.label){case 0:return r=new AbortController,n=e.url,o=e.enableAbort,i=void 0!==o&&o,a=e.stream,s=void 0!==a&&a,c=e.signal,u=e.timeout,l=e.shouldThrowOnError,d=void 0===l||l,f=null!=u?u:this.timeout,c&&(c.aborted&&r.abort(),c.addEventListener("abort",(function(){return r.abort()}))),p=null,i&&f&&(p=setTimeout((function(){console.warn(v.timeoutMsg),r.abort(new Error(v.timeoutMsg))}),f)),[4,fetch(n,q(q({},e),{signal:r.signal})).then((function(e){return H(v,void 0,void 0,(function(){var t,r,n;return G(this,(function(o){switch(o.label){case 0:return clearTimeout(p),d?e.ok?(t=e,[3,3]):[3,1]:[3,4];case 1:return n=(r=Promise).reject,[4,e.json()];case 2:t=n.apply(r,[o.sent()]),o.label=3;case 3:return[2,t];case 4:return[2,e]}}))}))})).catch((function(e){if(clearTimeout(p),d)return Promise.reject(e)}))];case 1:return h=y.sent(),[2,{data:s?h.body:(null===(t=h.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json"))?h.json():h.text(),statusCode:h.status,header:h.headers}]}}))}))},t.prototype.request=function(e,t){var r=this;void 0===t&&(t=!1);var n=String(e.method).toLowerCase()||"get";return new Promise((function(o){var i,a,s,c=e.url,u=e.headers,l=void 0===u?{}:u,d=e.data,f=e.responseType,p=e.withCredentials,h=e.body,v=e.onUploadProgress,y=function(e,t,r){void 0===r&&(r={});var n=/\?/.test(t),o="";return Object.keys(r).forEach((function(e){""===o?!n&&(t+="?"):o+="&",o+="".concat(e,"=").concat(encodeURIComponent(r[e]))})),/^http(s)?:\/\//.test(t+=o)?t:"".concat(e).concat(t)}(A,c,"get"===n?d:{}),g=new XMLHttpRequest;g.open(n,y),f&&(g.responseType=f),Object.keys(l).forEach((function(e){g.setRequestHeader(e,l[e])})),v&&g.upload.addEventListener("progress",v),g.onreadystatechange=function(){var e={};if(4===g.readyState){var t=g.getAllResponseHeaders().trim().split(/[\r\n]+/),r={};t.forEach((function(e){var t=e.split(": "),n=t.shift().toLowerCase(),o=t.join(": ");r[n]=o})),e.header=r,e.statusCode=g.status;try{e.data="blob"===f?g.response:JSON.parse(g.responseText)}catch(t){e.data="blob"===f?g.response:g.responseText}clearTimeout(i),o(e)}},t&&r.timeout&&(i=setTimeout((function(){console.warn(r.timeoutMsg),g.abort()}),r.timeout)),s=d,a="[object FormData]"===Object.prototype.toString.call(s)?d:"application/x-www-form-urlencoded"===l["content-type"]?function(e){void 0===e&&(e={});var t=[];return Object.keys(e).forEach((function(r){t.push("".concat(r,"=").concat(encodeURIComponent(e[r])))})),t.join("&")}(d):h||(d?JSON.stringify(d):void 0),p&&(g.withCredentials=!0),g.send(a)}))}}((function(){}));var V;!function(e){e.WEB="web",e.WX_MP="wx_mp"}(V||(V={}));var M=function(){var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),B=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}c((n=n.apply(e,t||[])).next())}))},W=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},F=function(e){function t(t){var r=e.call(this)||this;return r.root=t,t.tcbCacheObject||(t.tcbCacheObject={}),r}return M(t,e),t.prototype.setItem=function(e,t){this.root.tcbCacheObject[e]=t},t.prototype.getItem=function(e){return this.root.tcbCacheObject[e]},t.prototype.removeItem=function(e){delete this.root.tcbCacheObject[e]},t.prototype.clear=function(){delete this.root.tcbCacheObject},t}(x);!function(){function e(e){this.keys={};var t=e.persistence,r=e.platformInfo,n=void 0===r?{}:r,o=e.keys,i=void 0===o?{}:o;this.platformInfo=n,this.storage||(this.persistenceTag=this.platformInfo.adapter.primaryStorage||t,this.storage=function(e,t){switch(e){case"local":return t.localStorage?t.localStorage:(k(U,"localStorage is not supported on current platform"),new F(t.root));case"none":return new F(t.root);default:return t.localStorage?t.localStorage:(k(U,"localStorage is not supported on current platform"),new F(t.root))}}(this.persistenceTag,this.platformInfo.adapter),this.keys=i)}Object.defineProperty(e.prototype,"mode",{get:function(){return this.storage.mode||"sync"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"persistence",{get:function(){return this.persistenceTag},enumerable:!1,configurable:!0}),e.prototype.setStore=function(e,t,r){if("async"!==this.mode){if(this.storage)try{var n={version:r||"localCachev1",content:t};this.storage.setItem(e,JSON.stringify(n))}catch(e){throw new Error(JSON.stringify({code:D,msg:"[".concat(w(),"][").concat(D,"]setStore failed"),info:e}))}}else k(N,"current platform's storage is asynchronous, please use setStoreAsync insteed")},e.prototype.setStoreAsync=function(e,t,r){return B(this,void 0,void 0,(function(){var n;return W(this,(function(o){switch(o.label){case 0:if(!this.storage)return[2];o.label=1;case 1:return o.trys.push([1,3,,4]),n={version:r||"localCachev1",content:t},[4,this.storage.setItem(e,JSON.stringify(n))];case 2:return o.sent(),[3,4];case 3:return o.sent(),[2];case 4:return[2]}}))}))},e.prototype.getStore=function(e,t){var r;if("async"!==this.mode){try{if("undefined"!=typeof process&&(null===(r=process.env)||void 0===r?void 0:r.tcb_token))return process.env.tcb_token;if(!this.storage)return""}catch(e){return""}t=t||"localCachev1";var n=this.storage.getItem(e);return n&&n.indexOf(t)>=0?JSON.parse(n).content:""}k(N,"current platform's storage is asynchronous, please use getStoreAsync insteed")},e.prototype.getStoreAsync=function(e,t){var r;return B(this,void 0,void 0,(function(){var n;return W(this,(function(o){switch(o.label){case 0:try{if("undefined"!=typeof process&&(null===(r=process.env)||void 0===r?void 0:r.tcb_token))return[2,process.env.tcb_token];if(!this.storage)return[2,""]}catch(e){return[2,""]}return t=t||"localCachev1",[4,this.storage.getItem(e)];case 1:return(n=o.sent())&&n.indexOf(t)>=0?[2,JSON.parse(n).content]:[2,""]}}))}))},e.prototype.removeStore=function(e){"async"!==this.mode?this.storage.removeItem(e):k(N,"current platform's storage is asynchronous, please use removeStoreAsync insteed")},e.prototype.removeStoreAsync=function(e){return B(this,void 0,void 0,(function(){return W(this,(function(t){switch(t.label){case 0:return[4,this.storage.removeItem(e)];case 1:return t.sent(),[2]}}))}))}}();var K=function(){var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),Y=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))};var z=function(e,t){this.data=t||null,this.name=e},Q=function(e){function t(t,r){var n=e.call(this,"error",{error:t,data:r})||this;return n.error=t,n}return K(t,e),t}(z),J=function(){function e(){this.listeners={}}return e.prototype.on=function(e,t){return function(e,t,r){r[e]=r[e]||[],r[e].push(t)}(e,t,this.listeners),this},e.prototype.off=function(e,t){return function(e,t,r){if(null==r?void 0:r[e]){var n=r[e].indexOf(t);-1!==n&&r[e].splice(n,1)}}(e,t,this.listeners),this},e.prototype.fire=function(e,t){if(e instanceof Q)return console.error(e.error),this;var r="string"==typeof e?new z(e,t||{}):e,n=r.name;if(this.listens(n)){r.target=this;for(var o=0,i=this.listeners[n]?Y([],this.listeners[n],!0):[];o<i.length;o++){i[o].call(this,r)}}return this},e.prototype.listens=function(e){return this.listeners[e]&&this.listeners[e].length>0},e}();new J;var Z=new J;"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox");!function(){function e(){var e=this;this.listeners=[],this.signal={aborted:!1,addEventListener:function(t,r){"abort"===t&&e.listeners.push(r)}}}e.prototype.abort=function(){this.signal.aborted||(this.signal.aborted=!0,this.listeners.forEach((function(e){return e()})))}}();function X(e){this.message=e}X.prototype=new Error,X.prototype.name="InvalidCharacterError";"undefined"!=typeof window&&window.atob&&window.atob.bind(window);function $(e){this.message=e}$.prototype=new Error,$.prototype.name="InvalidTokenError";function ee(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function te(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ee(Object(r),!0).forEach((function(t){re(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ee(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function re(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ne(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function oe(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ne(i,n,o,a,s,"next",e)}function s(e){ne(i,n,o,a,s,"throw",e)}a(void 0)}))}}var ie=function(){var e=oe((function*(e,t){var r=null,n=null;try{var o=Object.assign({},t);o.method||(o.method="GET"),o.body&&"string"!=typeof o.body&&(o.body=JSON.stringify(o.body));var i=yield fetch(e,o),s=yield i.json();null!=s&&s.error?(n=s).error_uri=new URL(e).pathname:r=s}catch(t){n={error:a.UNREACHABLE,error_description:t.message,error_uri:new URL(e).pathname}}if(n)throw n;return r}));return function(t,r){return e.apply(this,arguments)}}();var ae=new class{constructor(e){this._env=(null==e?void 0:e.env)||""}getItem(e){var t=this;return oe((function*(){return window.localStorage.getItem("".concat(e).concat(t._env))}))()}removeItem(e){var t=this;return oe((function*(){window.localStorage.removeItem("".concat(e).concat(t._env))}))()}setItem(e,t){var r=this;return oe((function*(){window.localStorage.setItem("".concat(e).concat(r._env),t)}))()}getItemSync(e){return window.localStorage.getItem("".concat(e).concat(this._env))}removeItemSync(e){window.localStorage.removeItem("".concat(e).concat(this._env))}setItemSync(e,t){window.localStorage.setItem("".concat(e).concat(this._env),t)}};function se(e){var t=!0;return null!=e&&e.expires_at&&null!=e&&e.access_token&&(t=e.expires_at<new Date),t}class ce{constructor(e){this.credentials=null,this.accessKeyCredentials=null,this.singlePromise=null,this.tokenSectionName=e.tokenSectionName,this.storage=e.storage,this.clientId=e.clientId,this.singlePromise=new _({clientId:this.clientId}),this.credentials=e.credentials||null}getStorageCredentialsSync(){var e=null,t=this.storage.getItemSync(this.tokenSectionName);if(null!=t)try{var r;null!==(r=e=JSON.parse(t))&&void 0!==r&&r.expires_at&&(e.expires_at=new Date(e.expires_at))}catch(t){this.storage.removeItem(this.tokenSectionName),e=null}return e}setCredentials(e){var t=this;return oe((function*(){if(null!=e&&e.expires_in){if(null!=e&&e.expires_at||(e.expires_at=new Date(Date.now()+1e3*(e.expires_in-30))),t.storage){var r=JSON.stringify(e);yield t.storage.setItem(t.tokenSectionName,r)}t.credentials=e}else t.storage&&(yield t.storage.removeItem(t.tokenSectionName)),t.credentials=null}))()}setAccessKeyCredentials(e){this.accessKeyCredentials=e}getCredentials(){var e=this;return oe((function*(){return e.singlePromise.run("getCredentials",oe((function*(){if(se(e.credentials)){var{credentials:t,isAccessKeyCredentials:r}=yield e.getStorageCredentials();if(r)return t;e.credentials=t}return e.credentials})))}))()}getStorageCredentials(){var e=this;return oe((function*(){return e.singlePromise.run("_getStorageCredentials",oe((function*(){var t=null,r=!1,n=yield e.storage.getItem(e.tokenSectionName);if(n)try{var o;null!==(o=t=JSON.parse(n))&&void 0!==o&&o.expires_at&&(t.expires_at=new Date(t.expires_at))}catch(r){yield e.storage.removeItem(e.tokenSectionName),t=null}else t=e.accessKeyCredentials||null,r=!0;return{credentials:t,isAccessKeyCredentials:r}})))}))()}}class ue{constructor(e){var t;this.initializePromise=null,this.lockAcquired=!1,this.pendingInLock=[],this.singlePromise=null,e.clientSecret||(e.clientSecret=""),!e.clientId&&e.env&&(e.clientId=e.env),this.apiOrigin=e.apiOrigin,this.apiPath=e.apiPath||s,this.clientId=e.clientId,this.i18n=e.i18n,this.eventBus=e.eventBus,this.singlePromise=new _({clientId:this.clientId}),this.retry=this.formatRetry(e.retry,ue.defaultRetry),e.baseRequest?this.baseRequest=e.baseRequest:this.baseRequest=ie,this.tokenInURL=e.tokenInURL,this.headers=e.headers,this.storage=e.storage||ae,this.localCredentials=new ce({tokenSectionName:"credentials_".concat(e.clientId),storage:this.storage,clientId:e.clientId}),this.clientSecret=e.clientSecret,e.clientId&&(this.basicAuth="Basic ".concat(function(e){for(var t,r,n,o,i="",a=0,s=(e=String(e)).length%3;a<e.length;){if((r=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");i+=m.charAt((t=r<<16|n<<8|o)>>18&63)+m.charAt(t>>12&63)+m.charAt(t>>6&63)+m.charAt(63&t)}return s?i.slice(0,s-3)+"===".substring(s):i}("".concat(e.clientId,":").concat(this.clientSecret)))),this.wxCloud=e.wxCloud;try{S()&&(this.useWxCloud=e.useWxCloud,void 0===this.wxCloud&&e.env&&(wx.cloud.init({env:e.env}),this.wxCloud=wx.cloud))}catch(e){}this.refreshTokenFunc=e.refreshTokenFunc||this.defaultRefreshTokenFunc,this.anonymousSignInFunc=e.anonymousSignInFunc,this.onCredentialsError=e.onCredentialsError,this.getInitialSession=e.getInitialSession,this.onInitialSessionObtained=e.onInitialSessionObtained,this.logDebugMessages=null!==(t=e.debug)&&void 0!==t&&t,Z.on("lang_change",e=>{var t;this.i18n=(null===(t=e.data)||void 0===t?void 0:t.i18n)||this.i18n})}setGetInitialSession(e){this.getInitialSession=e}setOnInitialSessionObtained(e){this.onInitialSessionObtained=e}initialize(){var e=this;return oe((function*(){return e.initializePromise||(e.initializePromise=oe((function*(){return yield e._acquireLock(-1,oe((function*(){return yield e._initialize()})))}))()),yield e.initializePromise}))()}setCredentials(e){var t=this;return oe((function*(){return yield t.initializePromise,t._acquireLock(-1,oe((function*(){return t.localCredentials.setCredentials(e)})))}))()}setAccessKeyCredentials(e){return this.localCredentials.setAccessKeyCredentials(e)}getAccessToken(){var e=this;return oe((function*(){yield e.initializePromise;var t=yield e.getCredentials();if(null!=t&&t.access_token)return Promise.resolve(t.access_token);var r={error:a.UNAUTHENTICATED};return Promise.reject(r)}))()}request(e,t){var r=this;return oe((function*(){var n,o,i,s;t||(t={});var c=r.formatRetry(t.retry,r.retry);if(t.headers=te(te({},t.headers),{},{[null===(n=r.i18n)||void 0===n?void 0:n.LANG_HEADER_KEY]:null===(o=r.i18n)||void 0===o?void 0:o.lang}),r.headers&&(t.headers=te(te({},r.headers),t.headers)),t.headers["x-request-id"]||(t.headers["x-request-id"]=p()),!t.headers["x-device-id"]){var u=yield r.getDeviceId();t.headers["x-device-id"]=u}if(null!==(i=t)&&void 0!==i&&i.withBasicAuth&&r.basicAuth&&(t.headers.Authorization=r.basicAuth),null!==(s=t)&&void 0!==s&&s.withCredentials){var l=t.getCredentials?yield t.getCredentials():yield r.getCredentials();l&&(r.tokenInURL?(e.indexOf("?")<0&&(e+="?"),e+="access_token=".concat(l.access_token)):t.headers.Authorization="".concat(l.token_type," ").concat(l.access_token))}else r.clientId&&e.indexOf("client_id")<0&&(e+=e.indexOf("?")<0?"?":"&",e+="client_id=".concat(r.clientId));e.startsWith("/")&&(e="".concat(r.apiOrigin).concat(r.apiPath).concat(e));for(var d=null,f=c+1,h=0;h<f;h++){try{d=t.useWxCloud||r.useWxCloud?yield r.wxCloudCallFunction(e,t):yield r.baseRequest(e,t);break}catch(e){if(t.withCredentials&&e&&e.error===a.UNAUTHENTICATED)return yield r.setCredentials(null),Promise.reject(e);if(h===c||!e||"unreachable"!==e.error)return Promise.reject(e)}yield r.sleep(ue.retryInterval)}return d}))()}wxCloudCallFunction(e,t){var r=this;return oe((function*(){var n=null,o=null;try{var i,s="";try{s=yield wx.getRendererUserAgent()}catch(e){}var{result:c}=yield r.wxCloud.callFunction({name:"httpOverCallFunction",data:{url:e,method:t.method,headers:te({origin:"https://servicewechat.com","User-Agent":s},t.headers),body:t.body}});null!=c&&null!==(i=c.body)&&void 0!==i&&i.error_code?(o=null==c?void 0:c.body).error_uri=(0,h.y)(e):n=null==c?void 0:c.body}catch(t){o={error:a.UNREACHABLE,error_description:t.message,error_uri:(0,h.y)(e)}}if(o)throw o;return n}))()}getCredentials(){var e=this;return oe((function*(){return yield e.initializePromise,e._acquireLock(-1,oe((function*(){return e._getCredentials()})))}))()}getCredentialsSync(){return this.localCredentials.getStorageCredentialsSync()}getCredentialsAsync(){return this.getCredentials()}getScope(){var e=this;return oe((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}return t.scope}))()}getGroups(){var e=this;return oe((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}return t.groups}))()}refreshToken(e,t){var r=this;return oe((function*(){return yield r.initializePromise,r._acquireLock(-1,oe((function*(){return r._refreshToken(e,t)})))}))()}_refreshToken(e,t){var r=this;return oe((function*(){return r.singlePromise.run("_refreshToken",oe((function*(){if(!e||!e.refresh_token){var n,o="no refresh token found in credentials";return null===(n=r.onCredentialsError)||void 0===n||n.call(r,{msg:o}),r.unAuthenticatedError(o)}try{var i,s=yield r.refreshTokenFunc(e.refresh_token,e);return yield r.localCredentials.setCredentials(s),null===(i=r.eventBus)||void 0===i||i.fire(d.AUTH_STATE_CHANGED,{event:l.TOKEN_REFRESHED}),s}catch(e){var c;if(null!=t&&t.throwError)throw e;if(e.error===a.INVALID_GRANT){var u;yield r.localCredentials.setCredentials(null);var f=e.error_description;return null===(u=r.onCredentialsError)||void 0===u||u.call(r,{msg:f}),r.unAuthenticatedError(f)}return null===(c=r.onCredentialsError)||void 0===c||c.call(r,{msg:e.error_description}),Promise.reject(e)}})))}))()}anonymousLogin(e){var t=this;return oe((function*(){return t.singlePromise.run("_anonymousLogin",oe((function*(){if(t.anonymousSignInFunc){var r=yield t.anonymousSignInFunc(e);e=r||(yield t.localCredentials.getCredentials())}else e=yield t.anonymousSignIn(e);return e})))}))()}checkRetry(e){var t=null;if(("number"!=typeof e||e<ue.minRetry||e>ue.maxRetry)&&(t={error:a.UNREACHABLE,error_description:"wrong options param: retry"}),t)throw t;return e}formatRetry(e,t){return void 0===e?t:this.checkRetry(e)}sleep(e){return oe((function*(){return new Promise(t=>{setTimeout(()=>{t()},e)})}))()}anonymousSignIn(e){var r=this;return oe((function*(){return r.singlePromise.run("_anonymous",oe((function*(){if(!e||"anonymous"!==e.scope)return r.unAuthenticatedError("no anonymous in credentials");try{var n=yield r.request(t.AUTH_SIGN_IN_ANONYMOUSLY_URL,{method:"POST",withBasicAuth:!0,body:{}});return yield r.localCredentials.setCredentials(n),n}catch(e){return e.error===a.INVALID_GRANT?(yield r.localCredentials.setCredentials(null),r.unAuthenticatedError(e.error_description)):Promise.reject(e)}})))}))()}defaultRefreshTokenFunc(e,r){var n=this;return oe((function*(){if(void 0===e||""===e){var i,a="refresh token not found";return null===(i=n.onCredentialsError)||void 0===i||i.call(n,{msg:a}),n.unAuthenticatedError(a)}var s=t.AUTH_TOKEN_URL;return"v2"===(null==r?void 0:r.version)&&(s=o.AUTH_TOKEN_URL),te(te({},yield n.request(s,{method:"POST",body:{client_id:n.clientId,client_secret:n.clientSecret,grant_type:"refresh_token",refresh_token:e}})),{},{version:(null==r?void 0:r.version)||"v1"})}))()}getDeviceId(){var e=this;return oe((function*(){if(e.deviceID)return e.deviceID;var t=yield e.storage.getItem("device_id");return"string"==typeof t&&t.length>=16&&t.length<=48||(t=p(),yield e.storage.setItem("device_id",t)),e.deviceID=t,t}))()}unAuthenticatedError(e){var t={error:a.UNAUTHENTICATED,error_description:e};return Promise.reject(t)}_debug(){if(this.logDebugMessages){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];console.log("[OAuth2Client]",...t)}}_initialize(){var e=this;return oe((function*(){try{if(!e.getInitialSession)return e._debug("#_initialize()","no getInitialSession callback set, skipping"),{error:null};e._debug("#_initialize()","calling getInitialSession callback");try{var{data:t,error:r}=yield e.getInitialSession();if(null!=t&&t.session&&(e._debug("#_initialize()","session obtained from getInitialSession",t.session),yield e.localCredentials.setCredentials(null==t?void 0:t.session)),e.onInitialSessionObtained){e._debug("#_initialize()","calling onInitialSessionObtained callback");try{yield e.onInitialSessionObtained(t,r)}catch(t){e._debug("#_initialize()","error in onInitialSessionObtained",t)}}return r?(e._debug("#_initialize()","error from getInitialSession",r),{error:r}):{error:null}}catch(t){return e._debug("#_initialize()","exception during getInitialSession",t),{error:t instanceof Error?t:new Error(String(t))}}}catch(r){return e._debug("#_initialize()","unexpected error",r),{error:r instanceof Error?r:new Error(String(r))}}finally{e._debug("#_initialize()","end")}}))()}_acquireLock(e,t){var r=this;return oe((function*(){r._debug("#_acquireLock","begin",e);try{if(r.lockAcquired){var n=r.pendingInLock.length?r.pendingInLock[r.pendingInLock.length-1]:Promise.resolve(),o=oe((function*(){return yield n,yield t()}))();return r.pendingInLock.push(oe((function*(){try{yield o}catch(e){}}))()),o}r._debug("#_acquireLock","acquiring lock for client",r.clientId);try{r.lockAcquired=!0;var i=t();for(r.pendingInLock.push(oe((function*(){try{yield i}catch(e){}}))()),yield i;r.pendingInLock.length;){var a=[...r.pendingInLock];yield Promise.all(a),r.pendingInLock.splice(0,a.length)}return yield i}finally{r._debug("#_acquireLock","releasing lock for client",r.clientId),r.lockAcquired=!1}}finally{r._debug("#_acquireLock","end")}}))()}_getCredentials(){var e=this;return oe((function*(){var t=yield e.localCredentials.getCredentials();if(!t){var r,n="credentials not found";return null===(r=e.onCredentialsError)||void 0===r||r.call(e,{msg:n}),e.unAuthenticatedError(n)}if(se(t))if(t.refresh_token)try{t=yield e._refreshToken(t)}catch(r){var o;if("anonymous"!==t.scope)return null===(o=e.onCredentialsError)||void 0===o||o.call(e,{msg:r.error_description}),Promise.reject(r);t=yield e.anonymousLogin(t)}else{if("anonymous"!==t.scope){var i,a="no refresh token found in credentials";return null===(i=e.onCredentialsError)||void 0===i||i.call(e,{msg:a}),e.unAuthenticatedError(a)}t=yield e.anonymousLogin(t)}return t}))()}}ue.defaultRetry=2,ue.minRetry=0,ue.maxRetry=5,ue.retryInterval=1e3;var le=r(689),de=r(616);function fe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function pe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?fe(Object(r),!0).forEach((function(t){he(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fe(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function he(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ve(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function ye(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ve(i,n,o,a,s,"next",e)}function s(e){ve(i,n,o,a,s,"throw",e)}a(void 0)}))}}var ge=(e,t)=>{var r;return function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];clearTimeout(r),r=setTimeout(()=>e.apply(null,o),t)}},_e=new le.CloudbaseEventEmitter,me="resolveCaptchaData",Ee="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:999",Ie="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:320px;padding:20px;background:#fff;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.2);z-index:1000",be="margin-bottom:15px",Oe="display:flex;align-items:center;justify-content:space-between;margin-bottom:15px",Se="width:100%;height:auto;border:1px solid #eee",Re="padding:10px 8px;background:#007bff;color:#fff;border:none;border-radius:4px;cursor:pointer;flex:1;white-space:nowrap;margin-left:10px",Ce="width:100%;padding:14px 16px;margin-bottom:15px;box-sizing:border-box;border:2px solid #e8ecf4;border-radius:10px;font-size:15px",Te="width:100%;padding:10px;background:#007bff;color:#fff;border:none;border-radius:4px;cursor:pointer",we="background:#6c757d;cursor:not-allowed",Ae=e=>{var{oauthInstance:t,captchaState:r}=e,n=function(){var e=ye((function*(){try{var e=yield t.createCaptchaData({state:r.state});r=pe(pe({},r),{},{captchaData:e.data,token:e.token}),document.getElementById("captcha-image").src=e.data}catch(e){console.error("刷新图形验证码失败",e)}}));return function(){return e.apply(this,arguments)}}(),o=(e,t,r)=>{var n=document.createElement(e);return t&&(n.style.cssText=t),r&&(n.textContent=r),n},i=o("div",Ee),a=o("div",Ie);a.appendChild(o("p",be,"请输入你看到的字符:"));var s=o("div",Oe),c=o("img",Se);c.id="captcha-image",c.src=r.captchaData,s.appendChild(c);var u=o("button",Re,"刷新");u.onclick=ge(ye((function*(){u.textContent="加载中...",u.disabled=!0,u.style.cssText="".concat(Re,";").concat(we);try{yield n()}finally{u.textContent="刷新",u.disabled=!1,u.style.cssText=Re}})),500),s.appendChild(u),a.appendChild(s);var l=o("input",Ce);l.type="text",l.placeholder="输入字符",l.maxLength=4,a.appendChild(l);var d=o("div","color:#dc3545;font-size:12px;margin-bottom:10px;display:none;padding:8px;background:#f8d7da;border:1px solid #f5c6cb;border-radius:4px");a.appendChild(d);var f=e=>{d.textContent=e,d.style.display="block"},p=o("button",Te,"确定");p.onclick=ge(ye((function*(){var e=l.value.trim();if(e){d.style.display="none",p.textContent="验证中...",p.disabled=!0,p.style.cssText="".concat(Te,";").concat(we);try{var o=yield t.verifyCaptchaData({token:r.token,key:e});_e.fire(me,o),console.log("图形验证码校验成功"),document.body.removeChild(i),document.body.removeChild(a)}catch(e){console.error("图形验证码校验失败",e);var s=e.error_description||"图形验证码校验失败";f(s),l.value="",l.focus(),yield n()}finally{p.textContent="确定",p.disabled=!1,p.style.cssText=Te}}else f("请输入字符")})),500),a.appendChild(p),document.body.appendChild(i),document.body.appendChild(a)},Pe=function(){var e=ye((function*(e,t){var{captchaData:r,state:n,token:o}=(0,de.parseCaptcha)(e);return Ae({oauthInstance:t,captchaState:{captchaData:r,state:n,token:o}}),new Promise(e=>{console.log("等待图形验证码校验结果..."),_e.on(me,t=>{e(null==t?void 0:t.data)})})}));return function(t,r){return e.apply(this,arguments)}}();function Ue(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Ne(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){Ue(i,n,o,a,s,"next",e)}function s(e){Ue(i,n,o,a,s,"throw",e)}a(void 0)}))}}class De{constructor(e){e.openURIWithCallback||(e.openURIWithCallback=this.getDefaultOpenURIWithCallback()),e.storage||(e.storage=ae),this.config=e,this.tokenSectionName="captcha_".concat(e.clientId||e.env)}isMatch(){var e,t;return(null===(e=this.config)||void 0===e||null===(e=e.adapter)||void 0===e||null===(t=e.isMatch)||void 0===t?void 0:t.call(e))||S()}request(e,t){var r=this;return Ne((function*(){t||(t={}),t.method||(t.method="GET");var n,o="".concat(t.method,":").concat(e),i=e;t.withCaptcha&&(i=yield r.appendCaptchaTokenToURL(e,o,!1));try{n=yield r.config.request(i,t)}catch(n){return n.error===a.CAPTCHA_REQUIRED||n.error===a.CAPTCHA_INVALID?(e=yield r.appendCaptchaTokenToURL(e,o,n.error===a.CAPTCHA_INVALID),r.config.request(e,t)):Promise.reject(n)}return n}))()}getDefaultOpenURIWithCallback(){return e=>Pe(e,this.config.oauthInstance)}getCaptchaToken(e,r){var n=this;return Ne((function*(){if(!e){var o=yield n.findCaptchaToken();if(o)return o}var i=yield n.config.request(t.CAPTCHA_DATA_URL,{method:"POST",body:{state:r,redirect_uri:""},withCredentials:!1}),a="".concat(i.data,"?state=").concat(encodeURIComponent(r),"&token=").concat(encodeURIComponent(i.token)),s=yield n.config.openURIWithCallback(a);return n.saveCaptchaToken(s),s.captcha_token}))()}appendCaptchaTokenToURL(e,t,r){var n=this;return Ne((function*(){var o=yield n.getCaptchaToken(r,t);return e.indexOf("?")>0?e+="&captcha_token=".concat(o):e+="?captcha_token=".concat(o),e}))()}saveCaptchaToken(e){var t=this;return Ne((function*(){e.expires_at=new Date(Date.now()+1e3*(e.expires_in-10));var r=JSON.stringify(e);yield t.config.storage.setItem(t.tokenSectionName,r)}))()}findCaptchaToken(){var e=this;return Ne((function*(){var t=yield e.config.storage.getItem(e.tokenSectionName);if(null!=t)try{var r=JSON.parse(t);return null!=r&&r.expires_at&&(r.expires_at=new Date(r.expires_at)),r.expires_at<new Date?null:r.captcha_token}catch(t){return yield e.config.storage.removeItem(e.tokenSectionName),null}return null}))()}}const xe=class{constructor(e){if(this.params={},"string"==typeof e)this.parse(e);else if(e&&"object"==typeof e)for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.append(t,e[t])}parse(e){e.split("&").forEach(e=>{var[t,r]=e.split("=").map(decodeURIComponent);this.append(t,r)})}append(e,t){this.params[e]?this.params[e]=this.params[e].concat([t]):this.params[e]=[t]}get(e){return this.params[e]?this.params[e][0]:null}getAll(e){return this.params[e]||[]}delete(e){delete this.params[e]}has(e){return Object.prototype.hasOwnProperty.call(this.params,e)}set(e,t){this.params[e]=[t]}toString(){var e=this,t=[],r=function(r){Object.prototype.hasOwnProperty.call(e.params,r)&&e.params[r].forEach(e=>{t.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(e)))})};for(var n in this.params)r(n);return t.join("&")}};var ke=["provider_redirect_uri","other_params"];function Le(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function je(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){Le(i,n,o,a,s,"next",e)}function s(e){Le(i,n,o,a,s,"throw",e)}a(void 0)}))}}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function He(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?qe(Object(r),!0).forEach((function(t){Ge(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):qe(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ge(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ve(e,t){try{var n;if(((null==t||null===(n=t.root)||void 0===n?void 0:n.globalThis)||globalThis).IS_MP_BUILD)return;0}catch(t){if(e)return(()=>{try{return r(3)}catch(e){return}})()}}class Me{static parseParamsToSearch(e){return Object.keys(e).forEach(t=>{e[t]||delete e[t]}),new xe(e).toString()}constructor(e){var{request:t}=e,r=e.credentialsClient;if(!r){var n={apiOrigin:e.apiOrigin,apiPath:e.apiPath,clientId:e.clientId,storage:e.storage,env:e.env,baseRequest:e.baseRequest,anonymousSignInFunc:e.anonymousSignInFunc,wxCloud:e.wxCloud,onCredentialsError:e.onCredentialsError,headers:e.headers||{},i18n:e.i18n,debug:e.debug};r=new ue(n)}if(!t){var o=r.request.bind(r),i=new De(He({env:e.env,clientId:e.clientId,request:o,storage:e.storage,adapter:e.adapter,oauthInstance:this},e.captchaOptions));t=i.request.bind(i)}this.config={env:e.env,apiOrigin:e.apiOrigin,apiPath:e.apiPath,clientId:e.clientId,request:t,credentialsClient:r,storage:e.storage||ae,adapter:e.adapter}}getParamsByVersion(e,r){var n,i=(0,h.I)(e),a=(null===(n={v2:o}[null==i?void 0:i.version])||void 0===n?void 0:n[r])||t[r];return i&&delete i.version,{params:i,url:a}}signIn(e){var t=this;return je((function*(){var r=e.version||"v1",n=t.getParamsByVersion(e,"AUTH_SIGN_IN_URL");n.params.query&&delete n.params.query;var o=yield t.getEncryptParams(n.params),i=yield t.config.request(n.url,{method:"POST",body:o});return yield t.config.credentialsClient.setCredentials(He(He({},i),{},{version:r})),Promise.resolve(i)}))()}signInAnonymously(){var e=arguments,r=this;return je((function*(){var n=e.length>0&&void 0!==e[0]?e[0]:{},o=e.length>1&&void 0!==e[1]&&e[1],i=yield r.config.request(t.AUTH_SIGN_IN_ANONYMOUSLY_URL,{method:"POST",body:n,useWxCloud:o});return yield r.config.credentialsClient.setCredentials(i),Promise.resolve(i)}))()}signUp(e){var r=this;return je((function*(){var n=yield r.config.request(t.AUTH_SIGN_UP_URL,{method:"POST",body:e});return yield r.config.credentialsClient.setCredentials(n),Promise.resolve(n)}))()}signOut(e){var r=this;return je((function*(){var n={};if(e){try{n=yield r.config.request(t.AUTH_SIGNOUT_URL,{method:"POST",withCredentials:!0,body:e})}catch(e){e.error!==a.UNAUTHENTICATED&&console.log("sign_out_error",e)}return yield r.config.credentialsClient.setCredentials(),n}var o=yield r.config.credentialsClient.getAccessToken(),i=yield r.config.request(t.AUTH_REVOKE_URL,{method:"POST",body:{token:o}});return yield r.config.credentialsClient.setCredentials(),Promise.resolve(i)}))()}revokeAllDevices(){var e=this;return je((function*(){yield e.config.request(t.AUTH_REVOKE_ALL_URL,{method:"DELETE",withCredentials:!0})}))()}revokeDevice(e){var r=this;return je((function*(){yield r.config.request(t.AUTHORIZED_DEVICES_DELETE_URL+e.device_id,{method:"DELETE",withCredentials:!0})}))()}getVerification(e,r){var n=this;return je((function*(){var o=!1;"CUR_USER"===e.target?o=!0:(yield n.hasLoginState())&&(o=!0);var i=(0,h.I)(e);return i.phone_number&&!/^\+\d{1,3}\s+\d+/.test(i.phone_number)&&(i.phone_number="+86 ".concat(i.phone_number)),n.config.request(t.VERIFICATION_URL,{method:"POST",body:i,withCaptcha:(null==r?void 0:r.withCaptcha)||!1,withCredentials:o})}))()}verify(e){var t=this;return je((function*(){var r=t.getParamsByVersion(e,"VERIFY_URL"),n=yield t.config.request(r.url,{method:"POST",body:r.params});return"v2"===(null==e?void 0:e.version)&&(yield t.config.credentialsClient.setCredentials(He(He({},n),{},{version:"v2"}))),n}))()}genProviderRedirectUri(e){var r=this;return je((function*(){var{provider_redirect_uri:n,other_params:o={}}=e,i=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.includes(r)||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,ke);n&&!i.redirect_uri&&(i.redirect_uri=n);var a="".concat(t.PROVIDER_URI_URL,"?").concat(Me.parseParamsToSearch(i));return Object.keys(o).forEach(e=>{var t=o[e];("sign_out_uri"!==e||(null==t?void 0:t.length)>0)&&(a+="&other_params[".concat(e,"]=").concat(encodeURIComponent(t)))}),r.config.request(a,{method:"GET"})}))()}grantProviderToken(e){var r=arguments,n=this;return je((function*(){var o=r.length>1&&void 0!==r[1]&&r[1];return n.config.request(t.PROVIDER_TOKEN_URL,{method:"POST",body:e,useWxCloud:o})}))()}patchProviderToken(e){var r=this;return je((function*(){return r.config.request(t.PROVIDER_TOKEN_URL,{method:"PATCH",body:e})}))()}signInWithProvider(e){var t=arguments,r=this;return je((function*(){var n=t.length>1&&void 0!==t[1]&&t[1],o=r.getParamsByVersion(e,"AUTH_SIGN_IN_WITH_PROVIDER_URL"),i=yield r.config.request(o.url,{method:"POST",body:o.params,useWxCloud:n});return yield r.config.credentialsClient.setCredentials(He(He({},i),{},{version:(null==e?void 0:e.version)||"v1"})),Promise.resolve(i)}))()}toBindIdentity(e){var t=this;return je((function*(){var r,n,o,i=e.credentials||(yield t.config.credentialsClient.localCredentials.getCredentials());try{yield t.bindWithProvider({provider_token:e.provider_token},i),r={data:{type:f.BIND_IDENTITY,provider:e.provider},error:null}}catch(e){r={data:{type:f.BIND_IDENTITY},error:new Be(e)}}e.fireEvent&&(null===(n=t.config.eventBus)||void 0===n||null===(o=n.fire)||void 0===o||o.call(n,d.AUTH_STATE_CHANGED,{event:l.BIND_IDENTITY,info:r}));return r}))()}getInitialSession(){var e=this;return je((function*(){var t={};try{var r,n,o,i,a;if("undefined"==typeof window||"undefined"==typeof document)return{data:null,error:null};var s=new URLSearchParams(null===(r=location)||void 0===r?void 0:r.search),c=s.get("code"),u=s.get("state");if(!c||!u)return{data:null,error:null};var l=null;try{l=JSON.parse(sessionStorage.getItem(u)||"null")}catch(e){}t={type:null===(n=l)||void 0===n?void 0:n.type};var d=s.get("error"),p=s.get("error_description");if(d||p)return{data:t,error:new Be({message:p||d||"Unknown error from OAuth provider"})};var h=(null===(o=l)||void 0===o?void 0:o.provider)||s.get("provider");if(!h)return{data:t,error:new Be({message:"Provider is required for OAuth verification"})};var v,y,g=location.origin+location.pathname,{provider_token:_}=yield e.grantProviderToken({provider_id:h,provider_redirect_uri:g,provider_code:c}),m=null;if(l.type===f.BIND_IDENTITY)v=yield e.config.credentialsClient.localCredentials.getCredentials(),y=yield e.toBindIdentity({provider:h,provider_token:_,credentials:v});else if(l.type===f.SIGN_IN){y=e.getParamsByVersion({provider:h},"AUTH_SIGN_IN_WITH_PROVIDER_URL"),v=yield e.config.request(y.url,{method:"POST",body:{provider_token:_}});try{m=yield e.getUserInfo({credentials:v})}catch(e){console.error("get user info error",e)}y={data:He(He({},t),{},{session:v,user:m}),error:null}}s.delete("code"),s.delete("state"),s.delete("provider"),e.restoreUrlState(void 0===(null===(i=l)||void 0===i?void 0:i.search)?"?".concat(s.toString()):l.search,(null===(a=l)||void 0===a?void 0:a.hash)||location.hash);try{sessionStorage.removeItem(u)}catch(e){}return y}catch(e){return{data:t,error:new Be(e)}}}))()}signInCustom(e){var r=this;return je((function*(){var n=yield r.config.request(t.AUTH_SIGN_IN_CUSTOM,{method:"POST",body:e});return yield r.config.credentialsClient.setCredentials(n),Promise.resolve(n)}))()}signInWithWechat(){var e=arguments,r=this;return je((function*(){var n=e.length>0&&void 0!==e[0]?e[0]:{},o=yield r.config.request(t.AUTH_SIGN_IN_WITH_WECHAT_URL,{method:"POST",body:n});return yield r.config.credentialsClient.setCredentials(o),Promise.resolve(o)}))()}bindWithProvider(e,r){var n=this;return je((function*(){return n.config.request(t.PROVIDER_BIND_URL,{method:"POST",body:e,withCredentials:!0,getCredentials:r?()=>r:void 0})}))()}getUserProfile(e){var t=this;return je((function*(){return t.getUserInfo(e)}))()}getUserInfo(){var e=arguments,t=this;return je((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},o=t.getParamsByVersion(n,"USER_ME_URL");if(null!==(r=o.params)&&void 0!==r&&r.query){var i=new xe(o.params.query);o.url+="?".concat(i.toString())}var a=yield t.config.request(o.url,{method:"GET",withCredentials:!0,getCredentials:n.credentials?()=>n.credentials:void 0});return a.sub&&(a.uid=a.sub),a}))()}getWedaUserInfo(){var e=this;return je((function*(){return yield e.config.request(t.WEDA_USER_URL,{method:"GET",withCredentials:!0})}))()}deleteMe(e){var t=this;return je((function*(){var r=t.getParamsByVersion(e,"USER_ME_URL"),n="".concat(r.url,"?").concat(Me.parseParamsToSearch(r.params));return t.config.request(n,{method:"DELETE",withCredentials:!0})}))()}hasLoginState(){var e=this;return je((function*(){try{return yield e.config.credentialsClient.getAccessToken(),!0}catch(e){return!1}}))()}hasLoginStateSync(){return this.config.credentialsClient.getCredentialsSync()}getLoginState(){var e=this;return je((function*(){return e.config.credentialsClient.getCredentialsAsync()}))()}transByProvider(e){var r=this;return je((function*(){return r.config.request(t.USER_TRANS_BY_PROVIDER_URL,{method:"PATCH",body:e,withCredentials:!0})}))()}grantToken(e){var t=this;return je((function*(){var r=t.getParamsByVersion(e,"AUTH_TOKEN_URL");return t.config.request(r.url,{method:"POST",body:r.params})}))()}getProviders(){var e=this;return je((function*(){return e.config.request(t.PROVIDER_LIST,{method:"GET",withCredentials:!0})}))()}unbindProvider(e){var r=this;return je((function*(){return r.config.request("".concat(t.PROVIDER_UNBIND_URL,"/").concat(e.provider_id),{method:"DELETE",withCredentials:!0})}))()}checkPassword(e){var r=this;return je((function*(){return r.config.request("".concat(t.CHECK_PWD_URL),{method:"POST",withCredentials:!0,body:e})}))()}editContact(e){var r=this;return je((function*(){return r.config.request("".concat(t.BIND_CONTACT_URL),{method:"PATCH",withCredentials:!0,body:e})}))()}setPassword(e){var r=this;return je((function*(){return r.config.request("".concat(t.AUTH_SET_PASSWORD),{method:"PATCH",withCredentials:!0,body:e})}))()}updatePasswordByOld(e){var t=this;return je((function*(){var r=yield t.sudo({password:e.old_password});return t.setPassword({sudo_token:r.sudo_token,new_password:e.new_password})}))()}sudo(e){var r=this;return je((function*(){return r.config.request("".concat(t.SUDO_URL),{method:"POST",withCredentials:!0,body:e})}))()}sendVerificationCodeToCurrentUser(e){var r=this;return je((function*(){return e.target="CUR_USER",r.config.request(t.VERIFICATION_URL,{method:"POST",body:e,withCredentials:!0,withCaptcha:!0})}))()}changeBoundProvider(e){var r=this;return je((function*(){return r.config.request("".concat(t.PROVIDER_LIST,"/").concat(e.provider_id,"/trans"),{method:"POST",body:{provider_trans_token:e.trans_token},withCredentials:!0})}))()}setUserProfile(e){var r=this;return je((function*(){return r.config.request(t.USER_PRIFILE_URL,{method:"PATCH",body:e,withCredentials:!0})}))()}updateUserBasicInfo(e){var r=this;return je((function*(){return r.config.request(t.USER_BASIC_EDIT_URL,{method:"POST",withCredentials:!0,body:e})}))()}queryUserProfile(e){var r=this;return je((function*(){var n=new xe(e);return r.config.request("".concat(t.USER_QUERY_URL,"?").concat(n.toString()),{method:"GET",withCredentials:!0})}))()}setCustomSignFunc(e){this.getCustomSignTicketFn=e}signInWithCustomTicket(){var e=this;return je((function*(){var t=e.getCustomSignTicketFn;if(!t)return Promise.reject({error:"failed_precondition",error_description:"please use setCustomSignFunc to set custom sign function"});var r=yield t();return e.signInCustom({provider_id:"custom",ticket:r})}))()}resetPassword(e){var r=this;return je((function*(){return r.config.request(t.AUTH_RESET_PASSWORD,{method:"POST",body:e})}))()}authorize(e){var r=this;return je((function*(){return r.config.request(t.AUTHORIZE_URL,{method:"POST",withCredentials:!0,body:e})}))()}authorizeDevice(e){var r=this;return je((function*(){return r.config.request(t.AUTHORIZE_DEVICE_URL,{method:"POST",withCredentials:!0,body:e})}))()}deviceAuthorize(e){var r=this;return je((function*(){return r.config.request(t.AUTH_GET_DEVICE_CODE,{method:"POST",body:e,withCredentials:!0})}))()}authorizeInfo(e){var r=this;return je((function*(){var n="".concat(t.AUTHORIZE_INFO_URL,"?").concat(Me.parseParamsToSearch(e)),o=!0,i=!1;return(yield r.hasLoginState())&&(i=!0,o=!1),r.config.request(n,{method:"GET",withBasicAuth:o,withCredentials:i})}))()}checkUsername(e){var r=this;return je((function*(){return r.config.request(t.CHECK_USERNAME,{method:"GET",body:e,withCredentials:!0})}))()}checkIfUserExist(e){var r=this;return je((function*(){var n=new xe(e);return r.config.request("".concat(t.CHECK_IF_USER_EXIST,"?").concat(n.toString()),{method:"GET"})}))()}loginScope(){var e=this;return je((function*(){return e.config.credentialsClient.getScope()}))()}loginGroups(){var e=this;return je((function*(){return e.config.credentialsClient.getGroups()}))()}refreshTokenForce(e){var t=this;return je((function*(){var r=yield t.config.credentialsClient.getCredentials();return yield t.config.credentialsClient.refreshToken(He(He({},r),{},{version:(null==e?void 0:e.version)||"v1"}))}))()}getCredentials(){var e=this;return je((function*(){return e.config.credentialsClient.getCredentials()}))()}getPublicKey(){var e=this;return je((function*(){return e.config.request(o.AUTH_PUBLIC_KEY,{method:"POST",body:{}})}))()}getEncryptParams(e){var t=this;return je((function*(){var{isEncrypt:r}=e;delete e.isEncrypt;var n=(0,h.I)(e),o=Ve(r,t.config.adapter);if(!o)return e;var i="",a="";try{var s=yield t.getPublicKey();if(i=s.public_key,a=s.public_key_thumbprint,!i||!a)throw s}catch(e){throw e}return{params:o.getEncryptInfo({publicKey:i,payload:n}),public_key_thumbprint:a}}))()}getProviderSubType(){var e=this;return je((function*(){return e.config.request(t.GET_PROVIDER_TYPE,{method:"POST",body:{provider_id:"weda"}})}))()}verifyCaptchaData(e){var r=this;return je((function*(){var{token:n,key:o}=e;return r.config.request(t.VERIFY_CAPTCHA_DATA_URL,{method:"POST",body:{token:n,key:o},withCredentials:!1})}))()}createCaptchaData(e){var r=this;return je((function*(){var{state:n,redirect_uri:o}=e;return r.config.request(t.CAPTCHA_DATA_URL,{method:"POST",body:{state:n,redirect_uri:o},withCredentials:!1})}))()}getMiniProgramCode(e){var r=this;return je((function*(){return r.config.request(t.GET_MINIPROGRAM_QRCODE,{method:"POST",body:e})}))()}getMiniProgramQrCodeStatus(e){var r=this;return je((function*(){return r.config.request(t.GET_MINIPROGRAM_QRCODE_STATUS,{method:"POST",body:e})}))()}getUserBehaviorLog(e){var r=this;return je((function*(){var n="".concat(t.GET_USER_BEHAVIOR_LOG,"?").concat({LOGIN:"query[action]=USER_LOGIN",MODIFY:"ne_query[action]=USER_LOGIN"}[e.type],"&limit=").concat(e.limit).concat(e.page_token?"&page_token=".concat(e.page_token):"");return r.config.request(n,{method:"GET",withCredentials:!0})}))()}modifyPassword(e){var r=this;return je((function*(){var n="",o="",i=Ve(!0,r.config.adapter);if(!i)throw new Error("do not support encrypt, a encrypt util required.");try{var a=yield r.getPublicKey();if(n=a.public_key,o=a.public_key_thumbprint,!n||!o)throw a}catch(e){throw e}var s=e.password?i.getEncryptInfo({publicKey:n,payload:e.password}):"",c=i.getEncryptInfo({publicKey:n,payload:e.new_password});return r.config.request(t.USER_BASIC_EDIT_URL,{method:"POST",withCredentials:!0,body:{user_id:e.user_id,encrypt_password:s,encrypt_new_password:c,public_key_thumbprint:o}})}))()}modifyPasswordWithoutLogin(e){var t=this;return je((function*(){var r="",n="",i=Ve(!0,t.config.adapter);if(!i)throw new Error("do not support encrypt, a encrypt util required.");try{var a=yield t.getPublicKey();if(r=a.public_key,n=a.public_key_thumbprint,!r||!n)throw a}catch(e){throw e}var s=e.password?i.getEncryptInfo({publicKey:r,payload:e.password}):"",c=i.getEncryptInfo({publicKey:r,payload:e.new_password});return t.config.request(o.AUTH_RESET_PASSWORD,{method:"POST",body:{username:e.username,password:s,new_password:c,public_key_thumbprint:n}})}))()}restoreUrlState(e,t){if(void 0!==e)try{var r=new URL(window.location.href);r.search=e,r.hash=t||"",window.history.replaceState(null,"",r.toString())}catch(e){}}}class Be extends Error{constructor(e){super(e.error_description||e.message),this.__isAuthError=!0,this.name="AuthError",this.status=e.error,this.code=e.error_code}}function We(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Fe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?We(Object(r),!0).forEach((function(t){Ke(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):We(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ke(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ye{constructor(e){var{apiOrigin:t,apiPath:r=s,clientId:n,env:o,storage:i,request:a,baseRequest:c,anonymousSignInFunc:u,wxCloud:l,adapter:d,onCredentialsError:f,headers:p,i18n:h,useWxCloud:v,eventBus:y,detectSessionInUrl:g,debug:_}=e;this.detectSessionInUrl=null!=g&&g,this.oauth2client=new ue({apiOrigin:t,apiPath:r,clientId:n,env:o,storage:i,baseRequest:c||a,anonymousSignInFunc:u,wxCloud:l,onCredentialsError:f,headers:p||{},i18n:h,useWxCloud:v,eventBus:y,debug:_}),this.authApi=new Me(Fe(Fe({credentialsClient:this.oauth2client},e),{},{request:a?this.oauth2client.request.bind(this.oauth2client):void 0,adapter:d})),g&&this.oauth2client.setGetInitialSession(this.authApi.getInitialSession.bind(this.authApi))}initializeSession(e){this.detectSessionInUrl&&(this.oauth2client.setOnInitialSessionObtained(e),this.oauth2client.initialize())}}})(),n})());