@accelbyte/sdk 0.0.0-dev-20240906023252 → 0.0.0-dev-20240911051006

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.
@@ -4,8 +4,29 @@ if (!global.crypto) {
4
4
  global.crypto = webcrypto;
5
5
  }
6
6
 
7
- // src/utils/Network.ts
7
+ // src/utils/ApiUtils.ts
8
8
  import axios from "axios";
9
+ var ApiUtils = class {
10
+ };
11
+ ApiUtils.mergeAxiosConfigs = (config, overrides) => {
12
+ return {
13
+ ...config,
14
+ ...overrides,
15
+ headers: {
16
+ ...config == null ? void 0 : config.headers,
17
+ ...overrides == null ? void 0 : overrides.headers
18
+ }
19
+ };
20
+ };
21
+ ApiUtils.is4xxError = (error) => {
22
+ if (axios.isAxiosError(error) && error.response) {
23
+ return error.response.status >= 400 && error.response.status <= 499;
24
+ }
25
+ return false;
26
+ };
27
+
28
+ // src/utils/Network.ts
29
+ import axios2 from "axios";
9
30
  import qs from "query-string";
10
31
 
11
32
  // src/utils/SdkDevice.ts
@@ -49,7 +70,7 @@ var isMobile = (opts) => {
49
70
  // src/utils/Network.ts
50
71
  var _Network = class _Network {
51
72
  static create(...configs) {
52
- const axiosInstance = axios.create(
73
+ const axiosInstance = axios2.create(
53
74
  Object.assign(
54
75
  {
55
76
  paramsSerializer: qs.stringify
@@ -113,9 +134,27 @@ var AccelByteSDK = class _AccelByteSDK {
113
134
  }
114
135
  }
115
136
  };
116
- this.axiosInstance = Network.create({ baseURL: coreConfig.baseURL, ...this.axiosConfig.request });
137
+ this.axiosInstance = this.createAxiosInstance();
117
138
  this.token = {};
118
139
  }
140
+ createAxiosInstance() {
141
+ const axiosInstance = Network.create({ baseURL: this.coreConfig.baseURL, ...this.axiosConfig.request });
142
+ const interceptors = this.axiosConfig.interceptors;
143
+ if (interceptors) {
144
+ for (const interceptor of interceptors) {
145
+ if (interceptor.type === "request") {
146
+ axiosInstance.interceptors.request.use(interceptor == null ? void 0 : interceptor.onRequest, interceptor.onError);
147
+ }
148
+ if (interceptor.type === "response") {
149
+ axiosInstance.interceptors.response.use(interceptor == null ? void 0 : interceptor.onSuccess, interceptor.onError);
150
+ }
151
+ }
152
+ }
153
+ return axiosInstance;
154
+ }
155
+ /**
156
+ * Assembles and returns the current Axios instance along with core and Axios configurations.
157
+ */
119
158
  assembly() {
120
159
  return {
121
160
  axiosInstance: this.axiosInstance,
@@ -123,6 +162,12 @@ var AccelByteSDK = class _AccelByteSDK {
123
162
  axiosConfig: this.axiosConfig
124
163
  };
125
164
  }
165
+ /**
166
+ * Creates a new instance of AccelByteSDK with a shallow copy of the current configurations.
167
+ * Optionally allows excluding interceptors.
168
+ * @param {boolean} [opts.interceptors] - Whether to include interceptors in the clone. Default is true.
169
+ * @returns {AccelByteSDK} A new instance of AccelByteSDK with the cloned configuration.
170
+ */
126
171
  clone(opts) {
127
172
  const newConfigs = {
128
173
  coreConfig: { ...this.coreConfig },
@@ -133,6 +178,9 @@ var AccelByteSDK = class _AccelByteSDK {
133
178
  }
134
179
  return new _AccelByteSDK(newConfigs);
135
180
  }
181
+ /**
182
+ * Adds interceptors to the current Axios configuration.
183
+ */
136
184
  addInterceptors(interceptors) {
137
185
  if (!this.axiosConfig.interceptors) {
138
186
  this.axiosConfig.interceptors = [];
@@ -145,11 +193,18 @@ var AccelByteSDK = class _AccelByteSDK {
145
193
  if (!((_a = this.axiosConfig) == null ? void 0 : _a.interceptors)) return this;
146
194
  if (!filterCallback) {
147
195
  this.axiosConfig.interceptors = void 0;
196
+ this.axiosInstance.interceptors.request.clear();
197
+ this.axiosInstance.interceptors.response.clear();
148
198
  return this;
149
199
  }
150
200
  this.axiosConfig.interceptors = this.axiosConfig.interceptors.filter(filterCallback);
201
+ this.axiosInstance = this.createAxiosInstance();
151
202
  return this;
152
203
  }
204
+ /**
205
+ * Updates the SDK's core and Axios configurations.
206
+ * Merges the provided configurations with the current ones.
207
+ */
153
208
  setConfig({ coreConfig, axiosConfig }) {
154
209
  this.coreConfig = {
155
210
  ...this.coreConfig,
@@ -157,19 +212,36 @@ var AccelByteSDK = class _AccelByteSDK {
157
212
  };
158
213
  this.axiosConfig = {
159
214
  ...this.axiosConfig,
160
- ...axiosConfig
215
+ ...axiosConfig == null ? void 0 : axiosConfig.interceptors,
216
+ request: ApiUtils.mergeAxiosConfigs(this.axiosConfig.request, axiosConfig == null ? void 0 : axiosConfig.request)
161
217
  };
218
+ this.axiosInstance = this.createAxiosInstance();
162
219
  return this;
163
220
  }
221
+ /**
222
+ * Set accessToken and refreshToken and updates the Axios request headers to use Bearer authentication.
223
+ */
164
224
  setToken(token) {
165
225
  this.token = {
166
226
  ...this.token,
167
227
  ...token
168
228
  };
229
+ const configOverride = { headers: { Authorization: this.token.accessToken ? `Bearer ${this.token.accessToken}` : "" } };
230
+ this.axiosConfig = {
231
+ ...this.axiosConfig,
232
+ request: ApiUtils.mergeAxiosConfigs(this.axiosInstance.defaults, configOverride)
233
+ };
234
+ this.axiosInstance = this.createAxiosInstance();
169
235
  }
236
+ /**
237
+ * Removes the currently set token.
238
+ */
170
239
  removeToken() {
171
240
  this.token = {};
172
241
  }
242
+ /**
243
+ * Retrieves the current token configuration.
244
+ */
173
245
  getToken() {
174
246
  return this.token;
175
247
  }
@@ -202,7 +274,7 @@ var ERROR_CODE_TOKEN_EXPIRED = 10196;
202
274
  var ERROR_USER_BANNED = 10134;
203
275
 
204
276
  // src/interceptors/AuthInterceptors.ts
205
- import axios2 from "axios";
277
+ import axios3 from "axios";
206
278
 
207
279
  // src/utils/DesktopChecker.ts
208
280
  var _DesktopChecker = class _DesktopChecker {
@@ -446,69 +518,83 @@ var LoginUrls = /* @__PURE__ */ ((LoginUrls2) => {
446
518
  LoginUrls2["REVOKE"] = "/iam/v3/oauth/revoke";
447
519
  return LoginUrls2;
448
520
  })(LoginUrls || {});
449
- var refreshSession = ({ axiosConfig, refreshToken, clientId, tokenUrl }) => {
450
- const config = {
451
- ...axiosConfig,
452
- withCredentials: false,
453
- headers: {
454
- "Content-Type": "application/x-www-form-urlencoded",
455
- Authorization: `Basic ${Buffer.from(`${clientId}:`).toString("base64")}`
456
- }
457
- };
458
- const axios4 = Network.create(config);
459
- const payload = {
460
- refresh_token: refreshToken || void 0,
461
- client_id: clientId,
462
- grant_type: "refresh_token"
463
- };
464
- if (tokenUrl === "/iam/v4/oauth/token" /* GRANT_TOKEN_V4 */) {
465
- return new OAuth20V4$(axios4).postOauthToken_v4(payload);
466
- }
467
- const oauth20 = new OAuth20$(axios4);
468
- return oauth20.postOauthToken(payload);
469
- };
470
- var refreshWithLock = ({
471
- axiosConfig,
472
- refreshToken,
473
- clientId,
474
- tokenUrl
475
- }) => {
476
- if (RefreshSession.isLocked()) {
477
- return Promise.resolve().then(async () => {
478
- while (RefreshSession.isLocked()) {
479
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
521
+ var noOp = () => {
522
+ };
523
+ var RefreshToken = class {
524
+ constructor({ config, interceptors }) {
525
+ // Return Promise<true> if refresh in any tab is successful;
526
+ this.runWithLock = () => {
527
+ if (RefreshSession.isLocked()) {
528
+ return Promise.resolve().then(async () => {
529
+ while (RefreshSession.isLocked()) {
530
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
531
+ }
532
+ return {};
533
+ });
480
534
  }
481
- return {};
482
- });
483
- }
484
- RefreshSession.lock(REFRESH_EXPIRY);
485
- let isLocallyRefreshingToken = true;
486
- (async () => {
487
- while (isLocallyRefreshingToken) {
488
535
  RefreshSession.lock(REFRESH_EXPIRY);
489
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
490
- }
491
- })();
492
- return Promise.resolve().then(doRefreshSession({ axiosConfig, clientId, refreshToken, tokenUrl })).finally(() => {
493
- isLocallyRefreshingToken = false;
494
- RefreshSession.unlock();
495
- });
496
- };
497
- var doRefreshSession = ({ axiosConfig, clientId, refreshToken, tokenUrl }) => async () => {
498
- if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
499
- return false;
500
- }
501
- const result = await refreshSession({ axiosConfig, clientId, refreshToken, tokenUrl });
502
- if (result.error) {
503
- return false;
536
+ let isLocallyRefreshingToken = true;
537
+ (async () => {
538
+ while (isLocallyRefreshingToken) {
539
+ RefreshSession.lock(REFRESH_EXPIRY);
540
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
541
+ }
542
+ })();
543
+ return Promise.resolve().then(() => this.run()).finally(() => {
544
+ isLocallyRefreshingToken = false;
545
+ RefreshSession.unlock();
546
+ });
547
+ };
548
+ this.run = async () => {
549
+ const { axiosConfig, refreshToken } = this.config;
550
+ if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
551
+ return false;
552
+ }
553
+ const result = await this.refreshToken();
554
+ if (result.error) {
555
+ return false;
556
+ }
557
+ return result.response.data;
558
+ };
559
+ this.refreshToken = () => {
560
+ const { axiosConfig, refreshToken, clientId, tokenUrl } = this.config;
561
+ const config = {
562
+ ...axiosConfig,
563
+ withCredentials: false,
564
+ headers: {
565
+ "Content-Type": "application/x-www-form-urlencoded",
566
+ Authorization: `Basic ${Buffer.from(`${clientId}:`).toString("base64")}`
567
+ }
568
+ };
569
+ const axios4 = Network.create(config);
570
+ for (const interceptor of this.interceptors) {
571
+ if (interceptor.type === "request") {
572
+ axios4.interceptors.request.use(interceptor == null ? void 0 : interceptor.onRequest, interceptor.onError);
573
+ }
574
+ if (interceptor.type === "response") {
575
+ axios4.interceptors.response.use(interceptor == null ? void 0 : interceptor.onSuccess, interceptor.onError);
576
+ }
577
+ }
578
+ const payload = {
579
+ refresh_token: refreshToken || void 0,
580
+ client_id: clientId,
581
+ grant_type: "refresh_token"
582
+ };
583
+ if (tokenUrl === "/iam/v4/oauth/token" /* GRANT_TOKEN_V4 */) {
584
+ return new OAuth20V4$(axios4).postOauthToken_v4(payload);
585
+ }
586
+ const oauth20 = new OAuth20$(axios4);
587
+ return oauth20.postOauthToken(payload);
588
+ };
589
+ this.config = config;
590
+ this.interceptors = interceptors || [];
504
591
  }
505
- return result.response.data;
506
592
  };
507
- var uponRefreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
593
+ var refreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
508
594
  if (tokenResponse) {
509
595
  const { access_token } = tokenResponse;
510
596
  if (!axiosConfig.withCredentials && access_token) {
511
- return axios2({
597
+ return axios3({
512
598
  ...errorConfig,
513
599
  headers: {
514
600
  ...errorConfig.headers,
@@ -516,7 +602,7 @@ var uponRefreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig,
516
602
  }
517
603
  });
518
604
  } else {
519
- return axios2(errorConfig);
605
+ return axios3(errorConfig);
520
606
  }
521
607
  }
522
608
  if (onSessionExpired) {
@@ -524,6 +610,49 @@ var uponRefreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig,
524
610
  }
525
611
  throw error;
526
612
  };
613
+ var createAuthInterceptor = ({
614
+ clientId,
615
+ onSessionExpired,
616
+ onGetUserSession,
617
+ expectedErrorUrls = Object.values({ ...LoginUrls, ...GrantTokenUrls }),
618
+ getRefreshToken,
619
+ tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */
620
+ }) => {
621
+ return {
622
+ type: "response",
623
+ name: "session-expired",
624
+ onError: (e) => {
625
+ const error = e;
626
+ const { config, response } = error;
627
+ if (axios3.isCancel(error)) {
628
+ return Promise.reject(error);
629
+ }
630
+ if (!response) {
631
+ console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config == null ? void 0 : config.baseURL}${config == null ? void 0 : config.url}. ${error.message}
632
+ `);
633
+ }
634
+ if ((response == null ? void 0 : response.status) === 401) {
635
+ const { url } = config || {};
636
+ const axiosConfig = config;
637
+ const refreshToken = getRefreshToken();
638
+ if (!url || url && expectedErrorUrls.includes(url)) {
639
+ return Promise.reject(error);
640
+ }
641
+ const refresh = new RefreshToken({
642
+ config: { axiosConfig, clientId, refreshToken, tokenUrl },
643
+ interceptors: [
644
+ createRefreshSessionInterceptor({ tokenUrl }),
645
+ createGetSessionInterceptor({ onGetUserSession: onGetUserSession || noOp, tokenUrl })
646
+ ]
647
+ });
648
+ return refresh.runWithLock().then((tokenResponse) => {
649
+ return refreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
650
+ });
651
+ }
652
+ return Promise.reject(error);
653
+ }
654
+ };
655
+ };
527
656
  var createRefreshSessionInterceptor = (options) => {
528
657
  const { tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */ } = options || {};
529
658
  return {
@@ -557,41 +686,6 @@ var createGetSessionInterceptor = ({
557
686
  return response;
558
687
  }
559
688
  });
560
- var createSessionExpiredInterceptor = ({
561
- clientId,
562
- onSessionExpired,
563
- expectedErrorUrls = Object.values({ ...LoginUrls, ...GrantTokenUrls }),
564
- getRefreshToken,
565
- tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */
566
- }) => {
567
- return {
568
- type: "response",
569
- name: "session-expired",
570
- onError: (e) => {
571
- const error = e;
572
- const { config, response } = error;
573
- if (axios2.isCancel(error)) {
574
- return Promise.reject(error);
575
- }
576
- if (!response) {
577
- console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config == null ? void 0 : config.baseURL}${config == null ? void 0 : config.url}. ${error.message}
578
- `);
579
- }
580
- if ((response == null ? void 0 : response.status) === 401) {
581
- const { url } = config || {};
582
- const axiosConfig = config;
583
- const refreshToken = getRefreshToken();
584
- if (!url || url && expectedErrorUrls.includes(url)) {
585
- return Promise.reject(error);
586
- }
587
- return refreshWithLock({ axiosConfig, clientId, refreshToken, tokenUrl }).then((tokenResponse) => {
588
- return uponRefreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
589
- });
590
- }
591
- return Promise.reject(error);
592
- }
593
- };
594
- };
595
689
 
596
690
  // src/constants/paths.ts
597
691
  var INTERNAL_SERVICES = {
@@ -687,27 +781,6 @@ var ErrorInterceptors = [
687
781
  }
688
782
  ];
689
783
 
690
- // src/utils/ApiUtils.ts
691
- import axios3 from "axios";
692
- var ApiUtils = class {
693
- };
694
- ApiUtils.mergeAxiosConfigs = (config, overrides) => {
695
- return {
696
- ...config,
697
- ...overrides,
698
- headers: {
699
- ...config == null ? void 0 : config.headers,
700
- ...overrides == null ? void 0 : overrides.headers
701
- }
702
- };
703
- };
704
- ApiUtils.is4xxError = (error) => {
705
- if (axios3.isAxiosError(error) && error.response) {
706
- return error.response.status >= 400 && error.response.status <= 499;
707
- }
708
- return false;
709
- };
710
-
711
784
  // src/utils/Type.ts
712
785
  function isType(schema, data) {
713
786
  return schema.safeParse(data).success;
@@ -778,15 +851,14 @@ export {
778
851
  IamErrorCode,
779
852
  Network,
780
853
  RefreshSession,
854
+ RefreshToken,
781
855
  SdkDevice,
782
856
  UrlHelper,
783
857
  Validate,
858
+ createAuthInterceptor,
784
859
  createCustomPathInterceptor,
785
860
  createGetSessionInterceptor,
786
861
  createRefreshSessionInterceptor,
787
- createSessionExpiredInterceptor,
788
- doRefreshSession,
789
- isType,
790
- refreshWithLock
862
+ isType
791
863
  };
792
864
  //# sourceMappingURL=index.node.js.map