@accelbyte/sdk 3.0.8 → 4.0.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.
@@ -1,864 +1,939 @@
1
- 'use strict';
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
2
29
 
3
- var crypto = require('crypto');
4
- var axios = require('axios');
5
- var qs = require('query-string');
6
- var uuid = require('uuid');
7
- var zod = require('zod');
30
+ // src/index.node.ts
31
+ var index_node_exports = {};
32
+ __export(index_node_exports, {
33
+ AccelByte: () => AccelByte,
34
+ AccelByteSDK: () => AccelByteSDK,
35
+ ApiUtils: () => ApiUtils,
36
+ BrowserHelper: () => BrowserHelper,
37
+ CodeGenUtil: () => CodeGenUtil,
38
+ DecodeError: () => DecodeError,
39
+ DesktopChecker: () => DesktopChecker,
40
+ ERROR_CODE_LINK_DELETION_ACCOUNT: () => ERROR_CODE_LINK_DELETION_ACCOUNT,
41
+ ERROR_CODE_TOKEN_EXPIRED: () => ERROR_CODE_TOKEN_EXPIRED,
42
+ ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT: () => ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT,
43
+ ERROR_USER_BANNED: () => ERROR_USER_BANNED,
44
+ ErrorInterceptors: () => ErrorInterceptors,
45
+ IamErrorCode: () => IamErrorCode,
46
+ Network: () => Network,
47
+ RefreshSession: () => RefreshSession,
48
+ RefreshToken: () => RefreshToken,
49
+ SdkDevice: () => SdkDevice,
50
+ UrlHelper: () => UrlHelper,
51
+ Validate: () => Validate,
52
+ createAuthInterceptor: () => createAuthInterceptor,
53
+ createCustomPathInterceptor: () => createCustomPathInterceptor,
54
+ createGetSessionInterceptor: () => createGetSessionInterceptor,
55
+ createRefreshSessionInterceptor: () => createRefreshSessionInterceptor,
56
+ isType: () => isType
57
+ });
58
+ module.exports = __toCommonJS(index_node_exports);
8
59
 
9
- function _interopNamespaceDefault(e) {
10
- var n = Object.create(null);
11
- if (e) {
12
- Object.keys(e).forEach(function (k) {
13
- if (k !== 'default') {
14
- var d = Object.getOwnPropertyDescriptor(e, k);
15
- Object.defineProperty(n, k, d.get ? d : {
16
- enumerable: true,
17
- get: function () { return e[k]; }
18
- });
19
- }
20
- });
21
- }
22
- n.default = e;
23
- return Object.freeze(n);
60
+ // src/polyfills/node.ts
61
+ var import_crypto = require("crypto");
62
+ if (!global.crypto) {
63
+ global.crypto = import_crypto.webcrypto;
24
64
  }
25
65
 
26
- var uuid__namespace = /*#__PURE__*/_interopNamespaceDefault(uuid);
66
+ // src/utils/ApiUtils.ts
67
+ var import_axios = __toESM(require("axios"), 1);
68
+ var ApiUtils = class {
69
+ };
70
+ ApiUtils.mergeAxiosConfigs = (config, overrides) => {
71
+ return {
72
+ ...config,
73
+ ...overrides,
74
+ headers: {
75
+ ...config == null ? void 0 : config.headers,
76
+ ...overrides == null ? void 0 : overrides.headers
77
+ }
78
+ };
79
+ };
80
+ ApiUtils.is4xxError = (error) => {
81
+ if (import_axios.default.isAxiosError(error) && error.response) {
82
+ return error.response.status >= 400 && error.response.status <= 499;
83
+ }
84
+ return false;
85
+ };
27
86
 
28
- /*
29
- * Copyright (c) 2018-2024 AccelByte Inc. All Rights Reserved
30
- * This is licensed software from AccelByte Inc, for limitations
31
- * and restrictions contact your company contract manager.
32
- */
33
- if (!global.crypto) {
34
- global.crypto = crypto.webcrypto;
35
- }
87
+ // src/utils/Network.ts
88
+ var import_axios2 = __toESM(require("axios"), 1);
89
+ var import_query_string = __toESM(require("query-string"), 1);
36
90
 
37
- var _a;
38
- class SdkDevice {
39
- }
40
- _a = SdkDevice;
41
- SdkDevice.ID_KEY = 'deviceId';
42
- SdkDevice.TYPE = {
43
- MOBILE: 'mobile',
44
- DESKTOP: 'desktop'
45
- };
46
- SdkDevice.getType = () => {
47
- return isMobile() ? SdkDevice.TYPE.MOBILE : SdkDevice.TYPE.DESKTOP;
48
- };
49
- SdkDevice.generateUUID = () => {
50
- const deviceIdInUUID = uuid__namespace.v4().split('-').join('');
51
- localStorage.setItem(SdkDevice.ID_KEY, deviceIdInUUID);
52
- return deviceIdInUUID;
53
- };
54
- SdkDevice.getDeviceId = () => {
55
- return localStorage.getItem(_a.ID_KEY) || _a.generateUUID();
56
- };
57
- /*
58
- Bellow function is copied from npm 'is-mobile'
59
- */
60
- const mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
61
- const tabletRE = /android|ipad|playbook|silk/i;
62
- const isMobile = (opts) => {
63
- if (!opts)
64
- opts = {};
65
- let ua = opts.ua;
66
- if (!ua && typeof navigator !== 'undefined')
67
- ua = navigator.userAgent;
68
- if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
69
- ua = ua.headers['user-agent'];
70
- }
71
- if (typeof ua !== 'string')
72
- return false;
73
- let result = mobileRE.test(ua) || (!!opts.tablet && tabletRE.test(ua));
74
- if (!result &&
75
- opts.tablet &&
76
- opts.featureDetect &&
77
- navigator &&
78
- navigator.maxTouchPoints > 1 &&
79
- ua.indexOf('Macintosh') !== -1 &&
80
- ua.indexOf('Safari') !== -1) {
81
- result = true;
82
- }
83
- return result;
91
+ // src/utils/SdkDevice.ts
92
+ var uuid = __toESM(require("uuid"), 1);
93
+ var _SdkDevice = class _SdkDevice {
94
+ };
95
+ _SdkDevice.ID_KEY = "deviceId";
96
+ _SdkDevice.TYPE = {
97
+ MOBILE: "mobile",
98
+ DESKTOP: "desktop"
99
+ };
100
+ _SdkDevice.getType = () => {
101
+ return isMobile() ? _SdkDevice.TYPE.MOBILE : _SdkDevice.TYPE.DESKTOP;
102
+ };
103
+ _SdkDevice.generateUUID = () => {
104
+ const deviceIdInUUID = uuid.v4().split("-").join("");
105
+ localStorage.setItem(_SdkDevice.ID_KEY, deviceIdInUUID);
106
+ return deviceIdInUUID;
107
+ };
108
+ _SdkDevice.getDeviceId = () => {
109
+ return localStorage.getItem(_SdkDevice.ID_KEY) || _SdkDevice.generateUUID();
110
+ };
111
+ var SdkDevice = _SdkDevice;
112
+ var mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
113
+ var tabletRE = /android|ipad|playbook|silk/i;
114
+ var isMobile = (opts) => {
115
+ if (!opts) opts = {};
116
+ let ua = opts.ua;
117
+ if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent;
118
+ if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") {
119
+ ua = ua.headers["user-agent"];
120
+ }
121
+ if (typeof ua !== "string") return false;
122
+ let result = mobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua);
123
+ if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) {
124
+ result = true;
125
+ }
126
+ return result;
84
127
  };
85
128
 
86
- /*
87
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
88
- * This is licensed software from AccelByte Inc, for limitations
89
- * and restrictions contact your company contract manager.
90
- */
91
- const requestInterceptors = new Map();
92
- const responseInterceptors = new Map();
93
- const injectRequestInterceptors = (requestInterceptor, errorInterceptor) => {
94
- const pair = { interceptor: requestInterceptor, errorInterceptor };
95
- const ejectId = axios.interceptors.request.use(requestInterceptor, errorInterceptor);
96
- requestInterceptors.set(ejectId, pair);
97
- return ejectId;
98
- };
99
- const injectResponseInterceptors = (responseInterceptor, errorInterceptor) => {
100
- const pair = { interceptor: responseInterceptor, errorInterceptor };
101
- const ejectId = axios.interceptors.response.use(responseInterceptor, errorInterceptor);
102
- responseInterceptors.set(ejectId, pair);
103
- return ejectId;
104
- };
105
- const loggerInterceptor = (axiosInstance) => {
106
- axiosInstance.interceptors.request.use(config => {
107
- return config;
108
- }, error => {
109
- return Promise.reject(error);
110
- });
111
- };
112
- class Network {
113
- //
114
- static create(...configs) {
115
- const axiosInstance = axios.create(Object.assign({
116
- paramsSerializer: qs.stringify
117
- }, ...configs));
118
- Array.from(requestInterceptors).forEach(([_key, interceptorPair]) => {
119
- const { interceptor, errorInterceptor } = interceptorPair;
120
- axiosInstance.interceptors.request.use(interceptor, errorInterceptor);
121
- });
122
- Array.from(responseInterceptors).forEach(([_key, interceptorPair]) => {
123
- const { interceptor, errorInterceptor } = interceptorPair;
124
- axiosInstance.interceptors.response.use(interceptor, errorInterceptor);
125
- });
126
- loggerInterceptor(axiosInstance);
127
- return axiosInstance;
128
- }
129
- static withBearerToken(accessToken, config) {
130
- return Network.create(config || {}, {
131
- headers: { Authorization: `Bearer ${accessToken}` }
132
- });
133
- }
134
- }
135
- Network.setDeviceTokenCookie = () => {
136
- const deviceId = SdkDevice.getDeviceId();
137
- document.cookie = `device_token=${deviceId}; path=/;`;
138
- };
139
- Network.removeDeviceTokenCookie = () => {
140
- document.cookie = `device_token=; expires=${new Date(0).toUTCString()}`;
141
- };
142
- Network.getFormUrlEncodedData = (data) => {
143
- const formPayload = new URLSearchParams();
144
- const formKeys = Object.keys(data);
145
- formKeys.forEach(key => {
146
- if (data[key])
147
- formPayload.append(key, data[key]);
148
- });
149
- return formPayload;
129
+ // src/utils/Network.ts
130
+ var _Network = class _Network {
131
+ static create(...configs) {
132
+ const axiosInstance = import_axios2.default.create(
133
+ Object.assign(
134
+ {
135
+ paramsSerializer: import_query_string.default.stringify
136
+ },
137
+ ...configs
138
+ )
139
+ );
140
+ return axiosInstance;
141
+ }
142
+ static withBearerToken(accessToken, config) {
143
+ return _Network.create(config || {}, {
144
+ headers: { Authorization: `Bearer ${accessToken}` }
145
+ });
146
+ }
147
+ };
148
+ _Network.setDeviceTokenCookie = () => {
149
+ const deviceId = SdkDevice.getDeviceId();
150
+ document.cookie = `device_token=${deviceId}; path=/;`;
151
+ };
152
+ _Network.removeDeviceTokenCookie = () => {
153
+ document.cookie = `device_token=; expires=${(/* @__PURE__ */ new Date(0)).toUTCString()}`;
150
154
  };
155
+ _Network.getFormUrlEncodedData = (data) => {
156
+ const formPayload = new URLSearchParams();
157
+ const formKeys = Object.keys(data);
158
+ formKeys.forEach((key) => {
159
+ if (data[key]) formPayload.append(key, data[key]);
160
+ });
161
+ return formPayload;
162
+ };
163
+ var Network = _Network;
151
164
 
152
- const ERROR_ELIGIBILITY_CODE = 13130;
153
- const injectErrorInterceptors = ({ baseUrl, onError, onTooManyRequest, onUserEligibilityChange }) => {
154
- injectResponseInterceptors(response => {
155
- return response;
156
- }, (error) => {
157
- if (error.response) {
158
- const { response } = error;
159
- if (response?.status === 403 && response?.config.url.includes(baseUrl) && response?.config.withCredentials) {
160
- if (response.data.errorCode === ERROR_ELIGIBILITY_CODE && onUserEligibilityChange) {
161
- onUserEligibilityChange();
162
- }
163
- }
164
- if (response?.status === 429 /* TooManyRequests */ && onTooManyRequest) {
165
- onTooManyRequest(error);
166
- }
167
- }
168
- if (onError) {
169
- onError(error);
170
- }
171
- throw error;
172
- });
165
+ // src/AccelByteSDK.ts
166
+ var AccelByte = {
167
+ SDK: (param) => {
168
+ return new AccelByteSDK(param);
169
+ }
170
+ };
171
+ var AccelByteSDK = class _AccelByteSDK {
172
+ constructor({ coreConfig, axiosConfig }) {
173
+ var _a;
174
+ this.coreConfig = {
175
+ ...coreConfig,
176
+ useSchemaValidation: coreConfig.useSchemaValidation ?? true
177
+ };
178
+ this.axiosConfig = {
179
+ /**
180
+ * when user create a variable to store intercepters and passed into sdk
181
+ * the sdk will use the variable as reference value,
182
+ * so when new interceptor added, reference value will also has the new interceptor,
183
+ * to avoid this we create shallow copy for the interceptors
184
+ */
185
+ interceptors: (axiosConfig == null ? void 0 : axiosConfig.interceptors) ? [...axiosConfig.interceptors] : void 0,
186
+ request: {
187
+ timeout: 6e4,
188
+ withCredentials: true,
189
+ ...axiosConfig == null ? void 0 : axiosConfig.request,
190
+ headers: {
191
+ "Content-Type": "application/json",
192
+ ...(_a = axiosConfig == null ? void 0 : axiosConfig.request) == null ? void 0 : _a.headers
193
+ }
194
+ }
195
+ };
196
+ this.axiosInstance = this.createAxiosInstance();
197
+ this.token = {};
198
+ }
199
+ createAxiosInstance() {
200
+ const axiosInstance = Network.create({ baseURL: this.coreConfig.baseURL, ...this.axiosConfig.request });
201
+ const interceptors = this.axiosConfig.interceptors;
202
+ if (interceptors) {
203
+ for (const interceptor of interceptors) {
204
+ if (interceptor.type === "request") {
205
+ axiosInstance.interceptors.request.use(interceptor == null ? void 0 : interceptor.onRequest, interceptor.onError);
206
+ }
207
+ if (interceptor.type === "response") {
208
+ axiosInstance.interceptors.response.use(interceptor == null ? void 0 : interceptor.onSuccess, interceptor.onError);
209
+ }
210
+ }
211
+ }
212
+ return axiosInstance;
213
+ }
214
+ /**
215
+ * Assembles and returns the current Axios instance along with core and Axios configurations.
216
+ */
217
+ assembly() {
218
+ return {
219
+ axiosInstance: this.axiosInstance,
220
+ coreConfig: this.coreConfig,
221
+ axiosConfig: this.axiosConfig
222
+ };
223
+ }
224
+ /**
225
+ * Creates a new instance of AccelByteSDK with a shallow copy of the current configurations.
226
+ * Optionally allows excluding interceptors.
227
+ * @param {boolean} [opts.interceptors] - Whether to include interceptors in the clone. Default is true.
228
+ * @returns {AccelByteSDK} A new instance of AccelByteSDK with the cloned configuration.
229
+ */
230
+ clone(opts) {
231
+ const newConfigs = {
232
+ coreConfig: { ...this.coreConfig },
233
+ axiosConfig: { ...this.axiosConfig }
234
+ };
235
+ if ((opts == null ? void 0 : opts.interceptors) === false) {
236
+ delete newConfigs.axiosConfig.interceptors;
237
+ }
238
+ const newSdkInstance = new _AccelByteSDK(newConfigs);
239
+ newSdkInstance.setToken(this.token);
240
+ return newSdkInstance;
241
+ }
242
+ /**
243
+ * Adds interceptors to the current Axios configuration.
244
+ */
245
+ addInterceptors(interceptors) {
246
+ if (!this.axiosConfig.interceptors) {
247
+ this.axiosConfig.interceptors = [];
248
+ }
249
+ this.axiosConfig.interceptors.push(...interceptors);
250
+ return this;
251
+ }
252
+ removeInterceptors(filterCallback) {
253
+ var _a;
254
+ if (!((_a = this.axiosConfig) == null ? void 0 : _a.interceptors)) return this;
255
+ if (!filterCallback) {
256
+ this.axiosConfig.interceptors = void 0;
257
+ this.axiosInstance.interceptors.request.clear();
258
+ this.axiosInstance.interceptors.response.clear();
259
+ return this;
260
+ }
261
+ this.axiosConfig.interceptors = this.axiosConfig.interceptors.filter(filterCallback);
262
+ this.axiosInstance = this.createAxiosInstance();
263
+ return this;
264
+ }
265
+ /**
266
+ * Updates the SDK's core and Axios configurations.
267
+ * Merges the provided configurations with the current ones.
268
+ */
269
+ setConfig({ coreConfig, axiosConfig }) {
270
+ this.coreConfig = {
271
+ ...this.coreConfig,
272
+ ...coreConfig
273
+ };
274
+ this.axiosConfig = {
275
+ ...this.axiosConfig,
276
+ ...axiosConfig == null ? void 0 : axiosConfig.interceptors,
277
+ request: ApiUtils.mergeAxiosConfigs(this.axiosConfig.request, axiosConfig == null ? void 0 : axiosConfig.request)
278
+ };
279
+ this.axiosInstance = this.createAxiosInstance();
280
+ return this;
281
+ }
282
+ /**
283
+ * Set accessToken and refreshToken and updates the Axios request headers to use Bearer authentication.
284
+ */
285
+ setToken(token) {
286
+ this.token = {
287
+ ...this.token,
288
+ ...token
289
+ };
290
+ const configOverride = { headers: { Authorization: this.token.accessToken ? `Bearer ${this.token.accessToken}` : "" } };
291
+ this.axiosConfig = {
292
+ ...this.axiosConfig,
293
+ request: ApiUtils.mergeAxiosConfigs(this.axiosInstance.defaults, configOverride)
294
+ };
295
+ this.axiosInstance = this.createAxiosInstance();
296
+ }
297
+ /**
298
+ * Removes the currently set token.
299
+ */
300
+ removeToken() {
301
+ this.token = {};
302
+ const configOverride = { headers: { Authorization: void 0 } };
303
+ this.axiosConfig = {
304
+ ...this.axiosConfig,
305
+ request: ApiUtils.mergeAxiosConfigs(this.axiosInstance.defaults, configOverride)
306
+ };
307
+ this.axiosInstance = this.createAxiosInstance();
308
+ }
309
+ /**
310
+ * Retrieves the current token configuration.
311
+ */
312
+ getToken() {
313
+ return this.token;
314
+ }
173
315
  };
174
316
 
175
- /*
176
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
177
- * This is licensed software from AccelByte Inc, for limitations
178
- * and restrictions contact your company contract manager.
179
- */
180
- class BrowserHelper {
181
- }
182
- BrowserHelper.isOnBrowser = () => {
183
- return typeof window !== 'undefined' && window.document;
317
+ // src/constants/IamErrorCode.ts
318
+ var IamErrorCode = /* @__PURE__ */ ((IamErrorCode2) => {
319
+ IamErrorCode2[IamErrorCode2["InternalServerError"] = 2e4] = "InternalServerError";
320
+ IamErrorCode2[IamErrorCode2["UnauthorizedAccess"] = 20001] = "UnauthorizedAccess";
321
+ IamErrorCode2[IamErrorCode2["ValidationError"] = 20002] = "ValidationError";
322
+ IamErrorCode2[IamErrorCode2["ForbiddenAccess"] = 20003] = "ForbiddenAccess";
323
+ IamErrorCode2[IamErrorCode2["TooManyRequests"] = 20007] = "TooManyRequests";
324
+ IamErrorCode2[IamErrorCode2["UserNotFound"] = 20008] = "UserNotFound";
325
+ IamErrorCode2[IamErrorCode2["TokenIsExpired"] = 20011] = "TokenIsExpired";
326
+ IamErrorCode2[IamErrorCode2["InsufficientPermissions"] = 20013] = "InsufficientPermissions";
327
+ IamErrorCode2[IamErrorCode2["InvalidAudience"] = 20014] = "InvalidAudience";
328
+ IamErrorCode2[IamErrorCode2["InsufficientScope"] = 20015] = "InsufficientScope";
329
+ IamErrorCode2[IamErrorCode2["UnableToParseRequestBody"] = 20019] = "UnableToParseRequestBody";
330
+ IamErrorCode2[IamErrorCode2["InvalidPaginationParameters"] = 20021] = "InvalidPaginationParameters";
331
+ IamErrorCode2[IamErrorCode2["TokenIsNotUserToken"] = 20022] = "TokenIsNotUserToken";
332
+ IamErrorCode2[IamErrorCode2["InvalidRefererHeader"] = 20023] = "InvalidRefererHeader";
333
+ IamErrorCode2[IamErrorCode2["SubdomainMismatch"] = 20030] = "SubdomainMismatch";
334
+ return IamErrorCode2;
335
+ })(IamErrorCode || {});
336
+
337
+ // src/constants/LinkAccount.ts
338
+ var ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT = 10200;
339
+ var ERROR_CODE_LINK_DELETION_ACCOUNT = 10135;
340
+ var ERROR_CODE_TOKEN_EXPIRED = 10196;
341
+ var ERROR_USER_BANNED = 10134;
342
+
343
+ // src/interceptors/AuthInterceptors.ts
344
+ var import_axios3 = __toESM(require("axios"), 1);
345
+
346
+ // src/utils/DesktopChecker.ts
347
+ var _DesktopChecker = class _DesktopChecker {
348
+ static isDesktopApp() {
349
+ return _DesktopChecker.desktopApp && !_DesktopChecker.isInIframe();
350
+ }
351
+ static isInIframe() {
352
+ try {
353
+ return window.self !== window.top;
354
+ } catch (error) {
355
+ return true;
356
+ }
357
+ }
358
+ // borrowed from https://github.com/cheton/is-electron
359
+ static isElectron() {
360
+ if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") {
361
+ return true;
362
+ }
363
+ if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) {
364
+ return true;
365
+ }
366
+ if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) {
367
+ return true;
368
+ }
369
+ return false;
370
+ }
184
371
  };
372
+ _DesktopChecker.desktopApp = _DesktopChecker.isElectron();
373
+ var DesktopChecker = _DesktopChecker;
185
374
 
186
- class RefreshSession {
187
- }
188
- // --
189
- RefreshSession.KEY = 'RefreshSession.lock';
190
- RefreshSession.isLocked = () => {
191
- if (!BrowserHelper.isOnBrowser())
192
- return false;
193
- const lockStatus = localStorage.getItem(RefreshSession.KEY);
194
- if (!lockStatus) {
195
- return false;
196
- }
197
- const lockExpiry = Number(lockStatus);
198
- if (isNaN(lockExpiry)) {
199
- return false;
200
- }
201
- return lockExpiry > new Date().getTime();
202
- };
203
- RefreshSession.lock = (expiry) => {
204
- if (!BrowserHelper.isOnBrowser())
205
- return;
206
- localStorage.setItem(RefreshSession.KEY, `${new Date().getTime() + expiry}`);
207
- };
208
- RefreshSession.unlock = () => {
209
- if (!BrowserHelper.isOnBrowser())
210
- return;
211
- localStorage.removeItem(RefreshSession.KEY);
212
- };
213
- RefreshSession.sleepAsync = (timeInMs) => new Promise(resolve => setTimeout(resolve, timeInMs));
214
- RefreshSession.isBearerAuth = (config) => {
215
- // @ts-ignore
216
- if (config?.headers?.Authorization?.toLowerCase().indexOf('bearer') > -1) {
217
- return true;
218
- }
219
- return false;
375
+ // src/utils/BrowserHelper.ts
376
+ var BrowserHelper = class {
377
+ };
378
+ BrowserHelper.isOnBrowser = () => {
379
+ return typeof window !== "undefined" && window.document;
220
380
  };
221
381
 
222
- /*
223
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
224
- * This is licensed software from AccelByte Inc, for limitations
225
- * and restrictions contact your company contract manager.
226
- */
227
- class CodeGenUtil {
228
- /**
229
- * Returns a hash code from a string
230
- * @param {String} str The string to hash.
231
- * @return {Number} A 32bit integer
232
- * @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
233
- */
234
- static hashCode(str) {
235
- let hash = 0;
236
- for (let i = 0, len = str.length; i < len; i++) {
237
- const chr = str.charCodeAt(i);
238
- hash = (hash << 5) - hash + chr;
239
- hash |= 0; // Convert to 32bit integer
240
- }
241
- return hash;
242
- }
243
- }
244
- CodeGenUtil.getFormUrlEncodedData = (data) => {
245
- const formPayload = new URLSearchParams();
246
- const formKeys = Object.keys(data);
247
- formKeys.forEach(key => {
248
- if (typeof data[key] !== 'undefined')
249
- formPayload.append(key, data[key]);
250
- });
251
- return formPayload;
382
+ // src/utils/RefreshSession.ts
383
+ var _RefreshSession = class _RefreshSession {
384
+ };
385
+ // --
386
+ _RefreshSession.KEY = "RefreshSession.lock";
387
+ _RefreshSession.isLocked = () => {
388
+ if (!BrowserHelper.isOnBrowser()) return false;
389
+ const lockStatus = localStorage.getItem(_RefreshSession.KEY);
390
+ if (!lockStatus) {
391
+ return false;
392
+ }
393
+ const lockExpiry = Number(lockStatus);
394
+ if (isNaN(lockExpiry)) {
395
+ return false;
396
+ }
397
+ return lockExpiry > (/* @__PURE__ */ new Date()).getTime();
398
+ };
399
+ _RefreshSession.lock = (expiry) => {
400
+ if (!BrowserHelper.isOnBrowser()) return;
401
+ localStorage.setItem(_RefreshSession.KEY, `${(/* @__PURE__ */ new Date()).getTime() + expiry}`);
252
402
  };
403
+ _RefreshSession.unlock = () => {
404
+ if (!BrowserHelper.isOnBrowser()) return;
405
+ localStorage.removeItem(_RefreshSession.KEY);
406
+ };
407
+ _RefreshSession.sleepAsync = (timeInMs) => new Promise((resolve) => setTimeout(resolve, timeInMs));
408
+ _RefreshSession.isBearerAuth = (config) => {
409
+ var _a, _b;
410
+ if (((_b = (_a = config == null ? void 0 : config.headers) == null ? void 0 : _a.Authorization) == null ? void 0 : _b.toLowerCase().indexOf("bearer")) > -1) {
411
+ return true;
412
+ }
413
+ return false;
414
+ };
415
+ var RefreshSession = _RefreshSession;
253
416
 
254
- class Validate {
255
- static validateOrReturnResponse(useSchemaValidation, networkCall, Codec, modelName) {
256
- return useSchemaValidation ? Validate.responseType(() => networkCall(), Codec, modelName) : Validate.unsafeResponse(() => networkCall());
257
- }
258
- static responseType(networkCall, Codec, modelName) {
259
- return wrapNetworkCallSafely(async () => {
260
- const response = await networkCall();
261
- const decodeResult = Codec.safeParse(response.data);
262
- if (!decodeResult.success && response.status !== 204) {
263
- throw new DecodeError({ error: decodeResult.error, response, modelName });
264
- }
265
- return response;
266
- });
267
- }
268
- static unsafeResponse(networkCall) {
269
- return wrapNetworkCallSafely(() => networkCall());
270
- }
271
- static safeParse(data, Codec) {
272
- const result = Codec.safeParse(data);
273
- if (result.success) {
274
- return result.data;
275
- }
276
- return null;
277
- }
278
- }
279
- async function wrapNetworkCallSafely(networkCallFunction) {
280
- try {
281
- const response = await networkCallFunction();
282
- // Cleanup so we avoid polluting the response
283
- // @ts-ignore
284
- delete response.headers; // perhaps this may be required?
285
- // @ts-ignore
286
- delete response.statusText;
287
- // @ts-ignore
288
- delete response.config; // axios specific
289
- delete response.request;
290
- return { response, error: null };
291
- }
292
- catch (error) {
293
- return { response: null, error: error };
294
- }
295
- }
296
- class DecodeError extends Error {
297
- constructor({ error, response, modelName }) {
298
- const msg = `response from url "${response.config.url}" doesn't match model "${modelName}"`;
299
- super(msg);
300
- console.error(msg, error);
301
- }
302
- }
417
+ // ../sdk-iam/src/generated-definitions/TokenWithDeviceCookieResponseV3.ts
418
+ var import_zod4 = require("zod");
303
419
 
304
- /*
305
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
306
- * This is licensed software from AccelByte Inc, for limitations
307
- * and restrictions contact your company contract manager.
308
- */
309
- const JwtBanV3 = zod.z.object({
310
- ban: zod.z.string(),
311
- disabledDate: zod.z.string().nullish(),
312
- enabled: zod.z.boolean(),
313
- endDate: zod.z.string(),
314
- targetedNamespace: zod.z.string()
420
+ // ../sdk-iam/src/generated-definitions/JwtBanV3.ts
421
+ var import_zod = require("zod");
422
+ var JwtBanV3 = import_zod.z.object({
423
+ ban: import_zod.z.string(),
424
+ disabledDate: import_zod.z.string().nullish(),
425
+ enabled: import_zod.z.boolean(),
426
+ endDate: import_zod.z.string(),
427
+ targetedNamespace: import_zod.z.string()
315
428
  });
316
429
 
317
- /*
318
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
319
- * This is licensed software from AccelByte Inc, for limitations
320
- * and restrictions contact your company contract manager.
321
- */
322
- const NamespaceRole = zod.z.object({ namespace: zod.z.string(), roleId: zod.z.string() });
430
+ // ../sdk-iam/src/generated-definitions/NamespaceRole.ts
431
+ var import_zod2 = require("zod");
432
+ var NamespaceRole = import_zod2.z.object({ namespace: import_zod2.z.string(), roleId: import_zod2.z.string() });
323
433
 
324
- /*
325
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
326
- * This is licensed software from AccelByte Inc, for limitations
327
- * and restrictions contact your company contract manager.
328
- */
329
- const PermissionV3 = zod.z.object({
330
- action: zod.z.number().int(),
331
- resource: zod.z.string(),
332
- schedAction: zod.z.number().int().nullish(),
333
- schedCron: zod.z.string().nullish(),
334
- schedRange: zod.z.array(zod.z.string()).nullish()
434
+ // ../sdk-iam/src/generated-definitions/PermissionV3.ts
435
+ var import_zod3 = require("zod");
436
+ var PermissionV3 = import_zod3.z.object({
437
+ action: import_zod3.z.number().int(),
438
+ resource: import_zod3.z.string(),
439
+ schedAction: import_zod3.z.number().int().nullish(),
440
+ schedCron: import_zod3.z.string().nullish(),
441
+ schedRange: import_zod3.z.array(import_zod3.z.string()).nullish()
335
442
  });
336
443
 
337
- /*
338
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
339
- * This is licensed software from AccelByte Inc, for limitations
340
- * and restrictions contact your company contract manager.
341
- */
342
- const TokenWithDeviceCookieResponseV3 = zod.z.object({
343
- access_token: zod.z.string(),
344
- auth_trust_id: zod.z.string().nullish(),
345
- bans: zod.z.array(JwtBanV3).nullish(),
346
- display_name: zod.z.string().nullish(),
347
- expires_in: zod.z.number().int(),
348
- is_comply: zod.z.boolean().nullish(),
349
- jflgs: zod.z.number().int().nullish(),
350
- namespace: zod.z.string(),
351
- namespace_roles: zod.z.array(NamespaceRole).nullish(),
352
- permissions: zod.z.array(PermissionV3),
353
- platform_id: zod.z.string().nullish(),
354
- platform_user_id: zod.z.string().nullish(),
355
- refresh_expires_in: zod.z.number().int().nullish(),
356
- refresh_token: zod.z.string().nullish(),
357
- roles: zod.z.array(zod.z.string()).nullish(),
358
- scope: zod.z.string(),
359
- simultaneous_platform_id: zod.z.string().nullish(),
360
- simultaneous_platform_user_id: zod.z.string().nullish(),
361
- token_type: zod.z.string(),
362
- unique_display_name: zod.z.string().nullish(),
363
- user_id: zod.z.string().nullish(),
364
- xuid: zod.z.string().nullish()
444
+ // ../sdk-iam/src/generated-definitions/TokenWithDeviceCookieResponseV3.ts
445
+ var TokenWithDeviceCookieResponseV3 = import_zod4.z.object({
446
+ access_token: import_zod4.z.string(),
447
+ auth_trust_id: import_zod4.z.string().nullish(),
448
+ bans: import_zod4.z.array(JwtBanV3).nullish(),
449
+ display_name: import_zod4.z.string().nullish(),
450
+ expires_in: import_zod4.z.number().int(),
451
+ is_comply: import_zod4.z.boolean().nullish(),
452
+ jflgs: import_zod4.z.number().int().nullish(),
453
+ namespace: import_zod4.z.string(),
454
+ namespace_roles: import_zod4.z.array(NamespaceRole).nullish(),
455
+ permissions: import_zod4.z.array(PermissionV3),
456
+ platform_id: import_zod4.z.string().nullish(),
457
+ platform_user_id: import_zod4.z.string().nullish(),
458
+ refresh_expires_in: import_zod4.z.number().int().nullish(),
459
+ refresh_token: import_zod4.z.string().nullish(),
460
+ roles: import_zod4.z.array(import_zod4.z.string()).nullish(),
461
+ scope: import_zod4.z.string(),
462
+ simultaneous_platform_id: import_zod4.z.string().nullish(),
463
+ simultaneous_platform_user_id: import_zod4.z.string().nullish(),
464
+ token_type: import_zod4.z.string(),
465
+ unique_display_name: import_zod4.z.string().nullish(),
466
+ user_id: import_zod4.z.string().nullish(),
467
+ xuid: import_zod4.z.string().nullish()
365
468
  });
366
469
 
367
- /*
368
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
369
- * This is licensed software from AccelByte Inc, for limitations
370
- * and restrictions contact your company contract manager.
371
- */
372
- class OAuth20$ {
373
- // @ts-ignore
374
- constructor(axiosInstance, namespace) {
375
- this.axiosInstance = axiosInstance;
376
- this.namespace = namespace;
377
- }
378
- postOauthToken(data) {
379
- const params = {};
380
- const url = '/iam/v3/oauth/token';
381
- const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
382
- ...params,
383
- headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' }
384
- });
385
- return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, 'TokenWithDeviceCookieResponseV3');
386
- }
387
- }
470
+ // src/utils/CodeGenUtil.ts
471
+ var CodeGenUtil = class {
472
+ /**
473
+ * Returns a hash code from a string
474
+ * @param {String} str The string to hash.
475
+ * @return {Number} A 32bit integer
476
+ * @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
477
+ */
478
+ static hashCode(str) {
479
+ let hash = 0;
480
+ for (let i = 0, len = str.length; i < len; i++) {
481
+ const chr = str.charCodeAt(i);
482
+ hash = (hash << 5) - hash + chr;
483
+ hash |= 0;
484
+ }
485
+ return hash;
486
+ }
487
+ };
488
+ CodeGenUtil.getFormUrlEncodedData = (data) => {
489
+ const formPayload = new URLSearchParams();
490
+ const formKeys = Object.keys(data);
491
+ formKeys.forEach((key) => {
492
+ if (typeof data[key] !== "undefined") formPayload.append(key, data[key]);
493
+ });
494
+ return formPayload;
495
+ };
388
496
 
389
- /*
390
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
391
- * This is licensed software from AccelByte Inc, for limitations
392
- * and restrictions contact your company contract manager.
393
- */
394
- class DesktopChecker {
395
- static isDesktopApp() {
396
- return DesktopChecker.desktopApp && !DesktopChecker.isInIframe();
397
- }
398
- static isInIframe() {
399
- try {
400
- return window.self !== window.top;
401
- }
402
- catch (error) {
403
- return true;
404
- }
405
- }
406
- // borrowed from https://github.com/cheton/is-electron
407
- static isElectron() {
408
- // @ts-ignore Renderer process
409
- if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
410
- return true;
411
- }
412
- // Main process
413
- if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {
414
- return true;
415
- }
416
- // Detect the user agent when the `nodeIntegration` option is set to false
417
- if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {
418
- return true;
419
- }
420
- return false;
421
- }
422
- }
423
- DesktopChecker.desktopApp = DesktopChecker.isElectron();
497
+ // src/utils/Validate.ts
498
+ var Validate = class _Validate {
499
+ static validateOrReturnResponse(useSchemaValidation, networkCall, Codec, modelName) {
500
+ return useSchemaValidation ? _Validate.responseType(() => networkCall(), Codec, modelName) : _Validate.unsafeResponse(() => networkCall());
501
+ }
502
+ static responseType(networkCall, Codec, modelName) {
503
+ return wrapNetworkCallSafely(async () => {
504
+ const response = await networkCall();
505
+ const decodeResult = Codec.safeParse(response.data);
506
+ if (!decodeResult.success && response.status !== 204) {
507
+ throw new DecodeError({ error: decodeResult.error, response, modelName });
508
+ }
509
+ return response;
510
+ });
511
+ }
512
+ static unsafeResponse(networkCall) {
513
+ return wrapNetworkCallSafely(() => networkCall());
514
+ }
515
+ static safeParse(data, Codec) {
516
+ const result = Codec.safeParse(data);
517
+ if (result.success) {
518
+ return result.data;
519
+ }
520
+ return null;
521
+ }
522
+ };
523
+ async function wrapNetworkCallSafely(networkCallFunction) {
524
+ try {
525
+ const response = await networkCallFunction();
526
+ return { response, error: null };
527
+ } catch (error) {
528
+ return { response: null, error };
529
+ }
530
+ }
531
+ var DecodeError = class extends Error {
532
+ constructor({ error, response, modelName }) {
533
+ const msg = `response from url "${response.config.url}" doesn't match model "${modelName}"`;
534
+ super(msg);
535
+ console.error(msg, error);
536
+ }
537
+ };
424
538
 
425
- /*
426
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
427
- * This is licensed software from AccelByte Inc, for limitations
428
- * and restrictions contact your company contract manager.
429
- */
430
- const REFRESH_EXPIRY = 1000;
431
- const REFRESH_EXPIRY_UPDATE_RATE = 500;
432
- const REFRESH_EXPIRY_CHECK_RATE = 1000;
433
- var LoginUrls;
434
- (function (LoginUrls) {
435
- LoginUrls["GRANT_TOKEN"] = "/iam/v3/oauth/token";
436
- LoginUrls["REVOKE"] = "/iam/v3/oauth/revoke";
437
- })(LoginUrls || (LoginUrls = {}));
438
- /* eslint camelcase: 0 */
439
- const refreshSession = ({ axiosConfig, refreshToken, clientId }) => {
440
- const config = {
441
- ...axiosConfig,
442
- // Ideally withCredentials should be `true` to make sure that cookies always included when refreshing token
443
- // especially on cross-origin requests.
444
- // But if refreshToken is provided (e.g. from Launcher), we can set it to false and send refresh_token via payload.
445
- withCredentials: !refreshToken,
446
- headers: {
447
- 'Content-Type': 'application/x-www-form-urlencoded',
448
- Authorization: `Basic ${Buffer.from(`${clientId}:`).toString('base64')}`
449
- }
450
- };
451
- const axios = Network.create(config);
452
- const payload = {
453
- refresh_token: refreshToken || undefined,
454
- client_id: clientId,
455
- grant_type: 'refresh_token'
456
- };
457
- const oauth20 = new OAuth20$(axios, 'NAMESPACE-NOT-REQUIRED');
458
- return oauth20.postOauthToken(payload);
459
- };
460
- // Return Promise<true> if refresh in any tab is successful;
461
- const refreshWithLock = ({ axiosConfig, refreshToken, clientId }) => {
462
- //
463
- if (RefreshSession.isLocked()) {
464
- return Promise.resolve().then(async () => {
465
- // This block is executed when other tab / request is refreshing
466
- while (RefreshSession.isLocked()) {
467
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
468
- }
469
- return {};
470
- });
471
- }
472
- RefreshSession.lock(REFRESH_EXPIRY);
473
- let isLocallyRefreshingToken = true;
474
- (async () => {
475
- // eslint-disable-next-line no-unmodified-loop-condition
476
- while (isLocallyRefreshingToken) {
477
- RefreshSession.lock(REFRESH_EXPIRY);
478
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
479
- }
480
- })();
481
- return Promise.resolve()
482
- .then(doRefreshSession({ axiosConfig, clientId, refreshToken }))
483
- .finally(() => {
484
- isLocallyRefreshingToken = false;
485
- RefreshSession.unlock();
486
- });
487
- };
488
- const doRefreshSession = ({ axiosConfig, clientId, refreshToken }) => async () => {
489
- // we need this to check if app use “withCredentials: false” and don’t have refreshToken it should return false,
490
- // because we track it as a logout user, if not do this even user logout on the desktop app (that use withCredentials: false)
491
- // will automatically login with refreshSession
492
- if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
493
- return false;
494
- }
495
- const result = await refreshSession({ axiosConfig, clientId, refreshToken });
496
- if (result.error) {
497
- return false;
498
- }
499
- return result.response.data;
500
- };
501
- const injectAuthInterceptors = (clientId, getSDKConfig, onSessionExpired, onGetUserSession, getRefreshToken) => {
502
- // ===== request
503
- injectRequestInterceptors(async (config) => {
504
- // need to lock on the desktop as well to sleep other request before refresh session is done
505
- const isRefreshTokenUrl = config.url === LoginUrls.GRANT_TOKEN;
506
- // eslint-disable-next-line no-unmodified-loop-condition
507
- while (RefreshSession.isLocked() && !isRefreshTokenUrl) {
508
- await RefreshSession.sleepAsync(200);
509
- }
510
- return config;
511
- }, (error) => {
512
- return Promise.reject(error);
513
- });
514
- // ===== response
515
- injectResponseInterceptors(response => {
516
- const { config, status } = response;
517
- if (config.url === LoginUrls.GRANT_TOKEN && status === 200 && onGetUserSession) {
518
- const { access_token, refresh_token } = response.data;
519
- if (access_token) {
520
- onGetUserSession(access_token, refresh_token ?? '');
521
- }
522
- }
523
- return response;
524
- }, async (error) => {
525
- const { config, response } = error;
526
- if (axios.isCancel(error)) {
527
- // expected case, exit
528
- throw error;
529
- }
530
- if (!response) {
531
- console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config?.baseURL}${config?.url}. ${error.message}\n`);
532
- }
533
- if (response?.status === 401) {
534
- const { url } = config || {};
535
- const axiosConfig = getSDKConfig();
536
- const refreshToken = getRefreshToken ? getRefreshToken() : undefined;
537
- // expected business case, exit
538
- // @ts-ignore
539
- if (Object.values(LoginUrls).includes(url)) {
540
- throw error;
541
- }
542
- // need to lock on the desktop as well to prevent multiple token request
543
- return refreshWithLock({ axiosConfig, clientId, refreshToken }).then(tokenResponse => {
544
- return uponRefreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
545
- });
546
- }
547
- return Promise.reject(error);
548
- });
549
- };
550
- const uponRefreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
551
- //
552
- if (tokenResponse) {
553
- const { access_token } = tokenResponse;
554
- // desktop
555
- if (!axiosConfig.withCredentials && access_token) {
556
- return axios({
557
- ...errorConfig,
558
- headers: {
559
- ...errorConfig.headers,
560
- Authorization: `Bearer ${access_token}`
561
- }
562
- });
563
- // web
564
- }
565
- else {
566
- return axios(errorConfig);
567
- }
568
- }
569
- if (onSessionExpired) {
570
- onSessionExpired();
571
- }
572
- throw error;
539
+ // src/interceptors/AuthInterceptorDeps.ts
540
+ var OAuth20$ = class {
541
+ // @ts-ignore
542
+ constructor(axiosInstance) {
543
+ this.axiosInstance = axiosInstance;
544
+ }
545
+ postOauthToken(data) {
546
+ const params = {};
547
+ const url = "/iam/v3/oauth/token";
548
+ const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
549
+ ...params,
550
+ headers: { ...params.headers, "content-type": "application/x-www-form-urlencoded" }
551
+ });
552
+ return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, "TokenWithDeviceCookieResponseV3");
553
+ }
554
+ };
555
+ var OAuth20V4$ = class {
556
+ // @ts-ignore
557
+ // prettier-ignore
558
+ constructor(axiosInstance) {
559
+ this.axiosInstance = axiosInstance;
560
+ }
561
+ /**
562
+ * This endpoint supports grant type: 1. Grant Type == &lt;code&gt;authorization_code&lt;/code&gt;: It generates the user token by given the authorization code which generated in &#34;/iam/v3/authenticate&#34; API response. It should also pass in the redirect_uri, which should be the same as generating the authorization code request. 2. Grant Type == &lt;code&gt;password&lt;/code&gt;: The grant type to use for authenticating a user, whether it&#39;s by email / username and password combination or through platform. 3. Grant Type == &lt;code&gt;refresh_token&lt;/code&gt;: Used to get a new access token for a valid refresh token. 4. Grant Type == &lt;code&gt;client_credentials&lt;/code&gt;: It generates a token by checking the client credentials provided through Authorization header. 5. Grant Type == &lt;code&gt;urn:ietf:params:oauth:grant-type:extend_client_credentials&lt;/code&gt;: It generates a token by checking the client credentials provided through Authorization header. It only allows publisher/studio namespace client. In generated token: 1. There wil be no roles, namespace_roles &amp; permission. 2. The scope will be fixed as &#39;extend&#39;. 3. There will have a new field &#39;extend_namespace&#39;, the value is from token request body. 6. Grant Type == &lt;code&gt;urn:ietf:params:oauth:grant-type:login_queue_ticket&lt;/code&gt;: It generates a token by validating the login queue ticket against login queue service. ## Access Token Content Following is the access token’s content: - **namespace**. It is the namespace the token was generated from. - **display_name**. The display name of the sub. It is empty if the token is generated from the client credential - **roles**. The sub’s roles. It is empty if the token is generated from the client credential - **namespace_roles**. The sub’s roles scoped to namespace. Improvement from roles, which make the role scoped to specific namespace instead of global to publisher namespace - **permissions**. The sub or aud’ permissions - **bans**. The sub’s list of bans. It is used by the IAM client for validating the token. - **jflgs**. It stands for Justice Flags. It is a special flag used for storing additional status information regarding the sub. It is implemented as a bit mask. Following explains what each bit represents: - 1: Email Address Verified - 2: Phone Number Verified - 4: Anonymous - 8: Suspicious Login - **aud**. The aud is the targeted resource server. - **iat**. The time the token issues at. It is in Epoch time format - **exp**. The time the token expires. It is in Epoch time format - **client_id**. The UserID. The sub is omitted if the token is generated from client credential - **scope**. The scope of the access request, expressed as a list of space-delimited, case-sensitive strings ## Bans The JWT contains user&#39;s active bans with its expiry date. List of ban types can be obtained from /bans. ## Device Cookie Validation _**For grant type &#34;password&#34; only**_ Device Cookie is used to protect the user account from brute force login attack, &lt;a target=&#34;_blank&#34; href=&#34;https://owasp.org/www-community/Slow_Down_Online_Guessing_Attacks_with_Device_Cookies&#34;&gt;more detail from OWASP&lt;a&gt;. This endpoint will read device cookie from request header **Auth-Trust-Id**. If device cookie not found, it will generate a new one and set it into response body **auth_trust_id** when successfully login. ## Track Login History This endpoint will track login history to detect suspicious login activity, please provide **Device-Id** (alphanumeric) in request header parameter otherwise it will set to &#34;unknown&#34;. Align with General Data Protection Regulation in Europe, user login history will be kept within 28 days by default&#34; ## 2FA remember device To remember device for 2FA, should provide cookie: device_token or header: Device-Token ## Response note If it is a user token request and user hasn&#39;t accepted required legal policy, the field &lt;code&gt;is_comply&lt;/code&gt; will be false in response and responsed token will have no permission. action code: 10703
563
+ */
564
+ postOauthToken_v4(data, queryParams) {
565
+ const params = { code_challenge_method: "plain", ...queryParams };
566
+ const url = "/iam/v4/oauth/token";
567
+ const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
568
+ ...params,
569
+ headers: { ...params.headers, "content-type": "application/x-www-form-urlencoded" }
570
+ });
571
+ return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, "TokenWithDeviceCookieResponseV3");
572
+ }
573
573
  };
574
574
 
575
- /*
576
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
577
- * This is licensed software from AccelByte Inc, for limitations
578
- * and restrictions contact your company contract manager.
579
- */
580
- class ApiUtils {
581
- }
582
- ApiUtils.mergedConfigs = (config, overrides) => {
583
- return {
584
- ...config,
585
- ...overrides?.config,
586
- headers: {
587
- ...config.headers,
588
- ...overrides?.config?.headers
589
- }
590
- };
591
- };
592
- ApiUtils.is4xxError = (error) => {
593
- if (axios.isAxiosError(error) && error.response) {
594
- return error.response.status >= 400 && error.response.status <= 499;
595
- }
596
- return false;
575
+ // src/interceptors/AuthInterceptors.ts
576
+ var REFRESH_EXPIRY = 1e3;
577
+ var REFRESH_EXPIRY_UPDATE_RATE = 500;
578
+ var REFRESH_EXPIRY_CHECK_RATE = 1e3;
579
+ var GrantTokenUrls = /* @__PURE__ */ ((GrantTokenUrls2) => {
580
+ GrantTokenUrls2["GRANT_TOKEN"] = "/iam/v3/oauth/token";
581
+ GrantTokenUrls2["GRANT_TOKEN_V4"] = "/iam/v4/oauth/token";
582
+ return GrantTokenUrls2;
583
+ })(GrantTokenUrls || {});
584
+ var LoginUrls = /* @__PURE__ */ ((LoginUrls2) => {
585
+ LoginUrls2["REVOKE"] = "/iam/v3/oauth/revoke";
586
+ return LoginUrls2;
587
+ })(LoginUrls || {});
588
+ var noOp = () => {
589
+ };
590
+ var RefreshToken = class {
591
+ constructor({ config, interceptors }) {
592
+ // Return Promise<true> if refresh in any tab is successful;
593
+ this.runWithLock = () => {
594
+ if (RefreshSession.isLocked()) {
595
+ return Promise.resolve().then(async () => {
596
+ while (RefreshSession.isLocked()) {
597
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
598
+ }
599
+ return {};
600
+ });
601
+ }
602
+ RefreshSession.lock(REFRESH_EXPIRY);
603
+ let isLocallyRefreshingToken = true;
604
+ (async () => {
605
+ while (isLocallyRefreshingToken) {
606
+ RefreshSession.lock(REFRESH_EXPIRY);
607
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
608
+ }
609
+ })();
610
+ return Promise.resolve().then(() => this.run()).finally(() => {
611
+ isLocallyRefreshingToken = false;
612
+ RefreshSession.unlock();
613
+ });
614
+ };
615
+ this.run = async () => {
616
+ const { axiosConfig, refreshToken } = this.config;
617
+ if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
618
+ return false;
619
+ }
620
+ const result = await this.refreshToken();
621
+ if (result.error) {
622
+ return false;
623
+ }
624
+ return result.response.data;
625
+ };
626
+ this.refreshToken = () => {
627
+ const { axiosConfig, refreshToken, clientId, tokenUrl } = this.config;
628
+ const config = {
629
+ ...axiosConfig,
630
+ /**
631
+ * Ideally `withCredentials` should be `true` to make sure that
632
+ * cookies always included when refreshing token
633
+ * especially on cross-origin requests.
634
+ * But if `refreshToken` is provided (e.g. from Launcher),
635
+ * we can set it to false and send refresh_token via payload.
636
+ */
637
+ withCredentials: !refreshToken,
638
+ headers: {
639
+ "Content-Type": "application/x-www-form-urlencoded",
640
+ Authorization: `Basic ${Buffer.from(`${clientId}:`).toString("base64")}`
641
+ }
642
+ };
643
+ const axios4 = Network.create(config);
644
+ for (const interceptor of this.interceptors) {
645
+ if (interceptor.type === "request") {
646
+ axios4.interceptors.request.use(interceptor == null ? void 0 : interceptor.onRequest, interceptor.onError);
647
+ }
648
+ if (interceptor.type === "response") {
649
+ axios4.interceptors.response.use(interceptor == null ? void 0 : interceptor.onSuccess, interceptor.onError);
650
+ }
651
+ }
652
+ const payload = {
653
+ refresh_token: refreshToken || void 0,
654
+ client_id: clientId,
655
+ grant_type: "refresh_token"
656
+ };
657
+ if (tokenUrl === "/iam/v4/oauth/token" /* GRANT_TOKEN_V4 */) {
658
+ return new OAuth20V4$(axios4).postOauthToken_v4(payload);
659
+ }
660
+ const oauth20 = new OAuth20$(axios4);
661
+ return oauth20.postOauthToken(payload);
662
+ };
663
+ this.config = config;
664
+ this.interceptors = interceptors || [];
665
+ }
666
+ };
667
+ var refreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
668
+ if (tokenResponse) {
669
+ const { access_token } = tokenResponse;
670
+ if (!axiosConfig.withCredentials && access_token) {
671
+ return (0, import_axios3.default)({
672
+ ...errorConfig,
673
+ headers: {
674
+ ...errorConfig.headers,
675
+ Authorization: `Bearer ${access_token}`
676
+ }
677
+ });
678
+ } else {
679
+ return (0, import_axios3.default)(errorConfig);
680
+ }
681
+ }
682
+ if (onSessionExpired) {
683
+ onSessionExpired();
684
+ }
685
+ throw error;
597
686
  };
687
+ var createAuthInterceptor = ({
688
+ clientId,
689
+ onSessionExpired,
690
+ onGetUserSession,
691
+ expectedErrorUrls = Object.values({ ...LoginUrls, ...GrantTokenUrls }),
692
+ getRefreshToken,
693
+ tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */
694
+ }) => {
695
+ return {
696
+ type: "response",
697
+ name: "session-expired",
698
+ onError: (e) => {
699
+ const error = e;
700
+ const { config, response } = error;
701
+ if (import_axios3.default.isCancel(error)) {
702
+ return Promise.reject(error);
703
+ }
704
+ if (!response) {
705
+ console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config == null ? void 0 : config.baseURL}${config == null ? void 0 : config.url}. ${error.message}
706
+ `);
707
+ }
708
+ if ((response == null ? void 0 : response.status) === 401) {
709
+ const { url } = config || {};
710
+ const axiosConfig = config;
711
+ const refreshToken = getRefreshToken == null ? void 0 : getRefreshToken();
712
+ if (!url || url && expectedErrorUrls.includes(url)) {
713
+ return Promise.reject(error);
714
+ }
715
+ const refresh = new RefreshToken({
716
+ config: { axiosConfig, clientId, refreshToken, tokenUrl },
717
+ interceptors: [
718
+ createRefreshSessionInterceptor({ tokenUrl }),
719
+ createGetSessionInterceptor({ onGetUserSession: onGetUserSession || noOp, tokenUrl })
720
+ ]
721
+ });
722
+ return refresh.runWithLock().then((tokenResponse) => {
723
+ return refreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
724
+ });
725
+ }
726
+ return Promise.reject(error);
727
+ }
728
+ };
729
+ };
730
+ var createRefreshSessionInterceptor = (options) => {
731
+ const { tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */ } = options || {};
732
+ return {
733
+ type: "request",
734
+ name: "refresh-session",
735
+ onError: (error) => Promise.reject(error),
736
+ onRequest: async (config) => {
737
+ const isRefreshTokenUrl = config.url === tokenUrl;
738
+ while (RefreshSession.isLocked() && !isRefreshTokenUrl) {
739
+ await RefreshSession.sleepAsync(200);
740
+ }
741
+ return config;
742
+ }
743
+ };
744
+ };
745
+ var createGetSessionInterceptor = ({
746
+ tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */,
747
+ onGetUserSession
748
+ }) => ({
749
+ type: "response",
750
+ name: "get-session",
751
+ onError: (error) => Promise.reject(error),
752
+ onSuccess: (response) => {
753
+ const { config, status } = response;
754
+ if (config.url === tokenUrl && status === 200) {
755
+ const { access_token, refresh_token } = response.data;
756
+ if (access_token) {
757
+ onGetUserSession(access_token, refresh_token ?? "");
758
+ }
759
+ }
760
+ return response;
761
+ }
762
+ });
598
763
 
599
- /*
600
- * Copyright (c) 2023 AccelByte Inc. All Rights Reserved
601
- * This is licensed software from AccelByte Inc, for limitations
602
- * and restrictions contact your company contract manager.
603
- */
604
- const internalServiceMap = {
605
- '/achievement': 'justice-achievement-service',
606
- '/basic': 'justice-basic-service',
607
- '/buildinfo': 'justice-buildinfo-service',
608
- '/chat': 'justice-chat-service',
609
- '/cloudsave': 'justice-cloudsave-service',
610
- '/content-management': 'justice-odin-content-management-service',
611
- '/differ': 'justice-differ',
612
- '/dsmcontroller': 'justice-dsm-controller-service',
613
- '/event': 'justice-event-log-service',
614
- '/game-telemetry': 'analytics-game-telemetry-api',
615
- '/gdpr': 'justice-gdpr-service',
616
- '/group': 'justice-group-service',
617
- '/iam': 'justice-iam-service',
618
- '/leaderboard': 'justice-leaderboard-service',
619
- '/agreement': 'justice-legal-service',
620
- '/lobby': 'justice-lobby-server',
621
- '/match2': 'justice-matchmaking-v2',
622
- '/matchmaking': 'justice-matchmaking',
623
- '/odin-config': 'justice-odin-config-service',
624
- '/platform': 'justice-platform-service',
625
- '/qosm': 'justice-qos-manager-service',
626
- '/reporting': 'justice-reporting-service',
627
- '/seasonpass': 'justice-seasonpass-service',
628
- '/session': 'justice-session-service',
629
- '/sessionbrowser': 'justice-session-browser-service',
630
- '/social': 'justice-social-service',
631
- '/ugc': 'justice-ugc-service',
632
- '/config': 'justice-config-service'
633
- };
634
- const injectInternalNetworkInterceptors = () => {
635
- injectRequestInterceptors(async (config) => {
636
- const { url } = config;
637
- if (url) {
638
- // url example = "/iam/v1/..."
639
- const firstPath = url.split('/')[1];
640
- const internalServiceName = internalServiceMap[`/${firstPath}`];
641
- if (internalServiceName) {
642
- config.baseURL = `http://${internalServiceName}`;
643
- // final url will be
644
- // http://${service-name}/{url}
645
- }
646
- }
647
- return config;
648
- }, (error) => {
649
- return Promise.reject(error);
650
- });
764
+ // src/constants/paths.ts
765
+ var INTERNAL_SERVICES = {
766
+ "/achievement": "justice-achievement-service",
767
+ "/basic": "justice-basic-service",
768
+ "/buildinfo": "justice-buildinfo-service",
769
+ "/chat": "justice-chat-service",
770
+ "/cloudsave": "justice-cloudsave-service",
771
+ "/content-management": "justice-odin-content-management-service",
772
+ "/differ": "justice-differ",
773
+ "/dsmcontroller": "justice-dsm-controller-service",
774
+ "/event": "justice-event-log-service",
775
+ "/game-telemetry": "analytics-game-telemetry-api",
776
+ "/gdpr": "justice-gdpr-service",
777
+ "/group": "justice-group-service",
778
+ "/iam": "justice-iam-service",
779
+ "/leaderboard": "justice-leaderboard-service",
780
+ "/agreement": "justice-legal-service",
781
+ // sdk-legal
782
+ "/lobby": "justice-lobby-server",
783
+ "/match2": "justice-matchmaking-v2",
784
+ // sdk-matchmaking
785
+ "/matchmaking": "justice-matchmaking",
786
+ // sdk-matchmaking-v1
787
+ "/odin-config": "justice-odin-config-service",
788
+ "/platform": "justice-platform-service",
789
+ "/qosm": "justice-qos-manager-service",
790
+ "/reporting": "justice-reporting-service",
791
+ "/seasonpass": "justice-seasonpass-service",
792
+ "/session": "justice-session-service",
793
+ "/sessionbrowser": "justice-session-browser-service",
794
+ "/social": "justice-social-service",
795
+ "/ugc": "justice-ugc-service",
796
+ "/config": "justice-config-service"
651
797
  };
652
798
 
653
- /*
654
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
655
- * This is licensed software from AccelByte Inc, for limitations
656
- * and restrictions contact your company contract manager.
657
- */
658
- class AccelbyteSDKImpl {
659
- constructor(options, config, events) {
660
- this.getRefreshToken = () => this.refreshToken;
661
- this.getConfig = () => this.config;
662
- this.refreshTokensImpl = (accessToken, refreshToken) => {
663
- if (refreshToken) {
664
- this.refreshToken = refreshToken;
665
- }
666
- const configOverride = { headers: { Authorization: accessToken ? `Bearer ${accessToken}` : '' } };
667
- this.config = ApiUtils.mergedConfigs(this.config, { config: configOverride });
668
- };
669
- this.options = {
670
- ...options
671
- };
672
- this.events = events;
673
- this.config = {
674
- timeout: 60000,
675
- baseURL: options.baseURL,
676
- withCredentials: true,
677
- ...config,
678
- headers: {
679
- 'Content-Type': 'application/json',
680
- ...config?.headers
681
- }
682
- };
683
- // TODO: instead of having a "global" axios interceptors, we can create the instance here.
684
- // ```
685
- // this.axiosInstance = Network.create(...)
686
- // this.axiosInstance.interceptors.use(...)
687
- // ```
688
- // After that, our SDK assembly will return this axiosInstance, which will be used by each of the service SDKs.
689
- // ```
690
- // const { axiosInstance, opts } = sdk.assembly()
691
- // axiosInstance.defaults = {
692
- // ...axiosInstance.defaults,
693
- // ...args.config,
694
- // headers: {
695
- // ...axiosInstance.defaults.headers,
696
- // ...args.config.headers
697
- // }
698
- // }
699
- // ```
700
- // This way, each of the SDK instance will have their own interceptors and will not "pollute"
701
- // the global axios interceptors. It's easier to test in isolation as well, because with the global
702
- // interceptors, we can't isolate test the SDK instance... or maybe we can, with `axios.interceptors.request.clear`,
703
- // but they can't be done in parallel.
704
- }
705
- init() {
706
- const { baseURL, clientId, customInterceptors, useInternalNetwork } = this.options;
707
- if (customInterceptors) {
708
- injectRequestInterceptors(customInterceptors.request, customInterceptors.error);
709
- injectResponseInterceptors(customInterceptors.response, customInterceptors.error);
710
- }
711
- else {
712
- // Default interceptors.
713
- if (useInternalNetwork) {
714
- injectInternalNetworkInterceptors();
715
- }
716
- injectAuthInterceptors(clientId, this.getConfig, this.events?.onSessionExpired, this.events?.onGetUserSession, this.getRefreshToken);
717
- injectErrorInterceptors({
718
- baseUrl: baseURL,
719
- onError: this.events?.onError,
720
- onUserEligibilityChange: this.events?.onUserEligibilityChange,
721
- onTooManyRequest: this.events?.onTooManyRequest
722
- });
723
- }
724
- // TODO reintegrate doVersionDiagnostics later on
725
- // setTimeout(() => this.doVersionDiagnostics(), TIMEOUT_TO_DIAGNOSTICS)
726
- return {
727
- refreshTokens: (accessToken, refreshToken) => this.refreshTokensImpl(accessToken, refreshToken),
728
- assembly: () => {
729
- return {
730
- config: this.config,
731
- namespace: this.options.namespace,
732
- clientId: this.options.clientId,
733
- redirectURI: this.options.redirectURI,
734
- baseURL: this.options.baseURL,
735
- refreshToken: this.refreshToken,
736
- useSchemaValidation: this.options.useSchemaValidation !== undefined ? this.options.useSchemaValidation : true
737
- };
738
- }
739
- };
740
- }
741
- }
742
- const sdkInit = ({ options, config, onEvents }) => {
743
- const sdkFactory = new AccelbyteSDKImpl(options, config, onEvents);
744
- return sdkFactory.init();
745
- };
746
- // ts-prune-ignore-next
747
- const Accelbyte = { SDK: sdkInit };
799
+ // src/interceptors/CustomPathInterceptor.ts
800
+ var createCustomPathInterceptor = ({ basePath, isInternalNetwork }) => {
801
+ return {
802
+ type: "request",
803
+ name: "custom-base-path",
804
+ onRequest: async (config) => {
805
+ var _a, _b;
806
+ const { url } = config;
807
+ if (url) {
808
+ const firstPath = url.split("/")[1];
809
+ const servicePath = `/${firstPath}`;
810
+ const newBasePath = basePath == null ? void 0 : basePath[servicePath];
811
+ const internalPath = (_a = INTERNAL_SERVICES) == null ? void 0 : _a[servicePath];
812
+ if (isInternalNetwork && internalPath) {
813
+ config.baseURL = `http://${internalPath}`;
814
+ }
815
+ if (newBasePath) {
816
+ config.url = (_b = config.url) == null ? void 0 : _b.replace(servicePath, newBasePath);
817
+ }
818
+ }
819
+ return config;
820
+ },
821
+ onError: (error) => Promise.reject(error)
822
+ };
823
+ };
748
824
 
749
- /*
750
- * Copyright (c) 2024 AccelByte Inc. All Rights Reserved
751
- * This is licensed software from AccelByte Inc, for limitations
752
- * and restrictions contact your company contract manager.
753
- */
754
- // More detail: https://github.com/AccelByte/go-restful-plugins/blob/master/pkg/auth/iam/event.go
755
- exports.IamErrorCode = void 0;
756
- (function (IamErrorCode) {
757
- IamErrorCode[IamErrorCode["InternalServerError"] = 20000] = "InternalServerError";
758
- IamErrorCode[IamErrorCode["UnauthorizedAccess"] = 20001] = "UnauthorizedAccess";
759
- IamErrorCode[IamErrorCode["ValidationError"] = 20002] = "ValidationError";
760
- IamErrorCode[IamErrorCode["ForbiddenAccess"] = 20003] = "ForbiddenAccess";
761
- IamErrorCode[IamErrorCode["TooManyRequests"] = 20007] = "TooManyRequests";
762
- IamErrorCode[IamErrorCode["UserNotFound"] = 20008] = "UserNotFound";
763
- IamErrorCode[IamErrorCode["TokenIsExpired"] = 20011] = "TokenIsExpired";
764
- IamErrorCode[IamErrorCode["InsufficientPermissions"] = 20013] = "InsufficientPermissions";
765
- IamErrorCode[IamErrorCode["InvalidAudience"] = 20014] = "InvalidAudience";
766
- IamErrorCode[IamErrorCode["InsufficientScope"] = 20015] = "InsufficientScope";
767
- IamErrorCode[IamErrorCode["UnableToParseRequestBody"] = 20019] = "UnableToParseRequestBody";
768
- IamErrorCode[IamErrorCode["InvalidPaginationParameters"] = 20021] = "InvalidPaginationParameters";
769
- IamErrorCode[IamErrorCode["TokenIsNotUserToken"] = 20022] = "TokenIsNotUserToken";
770
- IamErrorCode[IamErrorCode["InvalidRefererHeader"] = 20023] = "InvalidRefererHeader";
771
- IamErrorCode[IamErrorCode["SubdomainMismatch"] = 20030] = "SubdomainMismatch";
772
- })(exports.IamErrorCode || (exports.IamErrorCode = {}));
825
+ // src/interceptors/ErrorInterceptor.ts
826
+ var ERROR_ELIGIBILITY_CODE = 13130;
827
+ var ErrorInterceptors = [
828
+ {
829
+ type: "response",
830
+ name: "user-eligibilitiy-change",
831
+ onError: (e) => {
832
+ const error = e;
833
+ if (error.response) {
834
+ const { response } = error;
835
+ if ((response == null ? void 0 : response.status) === 403 && (response == null ? void 0 : response.config).url.includes(process.env.BASE_URL) && (response == null ? void 0 : response.config.withCredentials)) {
836
+ if (response.data.errorCode === ERROR_ELIGIBILITY_CODE) {
837
+ }
838
+ }
839
+ }
840
+ return Promise.reject(error);
841
+ }
842
+ },
843
+ {
844
+ type: "response",
845
+ name: "too-many-request",
846
+ onError: (e) => {
847
+ const error = e;
848
+ if (error.response) {
849
+ const { response } = error;
850
+ if ((response == null ? void 0 : response.status) === 429) {
851
+ }
852
+ }
853
+ return Promise.reject(error);
854
+ }
855
+ }
856
+ ];
773
857
 
774
- /*
775
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
776
- * This is licensed software from AccelByte Inc, for limitations
777
- * and restrictions contact your company contract manager.
778
- */
779
- const ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT = 10200;
780
- const ERROR_CODE_LINK_DELETION_ACCOUNT = 10135;
781
- const ERROR_CODE_TOKEN_EXPIRED = 10196;
782
- const ERROR_USER_BANNED = 10134;
858
+ // src/utils/Type.ts
859
+ function isType(schema, data) {
860
+ return schema.safeParse(data).success;
861
+ }
783
862
 
784
- /*
785
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
786
- * This is licensed software from AccelByte Inc, for limitations
787
- * and restrictions contact your company contract manager.
788
- */
789
- class UrlHelper {
790
- static trimSlashFromStringEnd(pathString) {
791
- let newString = pathString;
792
- while (newString[newString.length - 1] === '/') {
793
- newString = newString.slice(0, -1);
794
- }
795
- return newString;
796
- }
797
- static trimSlashFromStringStart(pathString) {
798
- let newString = pathString;
799
- while (newString[0] === '/') {
800
- newString = newString.slice(1);
801
- }
802
- return newString;
803
- }
804
- static trimSlashFromStringEdges(pathString) {
805
- return UrlHelper.trimSlashFromStringStart(this.trimSlashFromStringEnd(pathString));
806
- }
807
- static combinePaths(...paths) {
808
- const completePath = paths.join('/');
809
- // Replace 2 or more consecutive slashes with a single slash.
810
- // This is also the behavior from Node's `path.join`.
811
- return completePath.replace(/\/{2,}/g, '/');
812
- }
813
- static combineURLPaths(urlString, ...paths) {
814
- const url = new URL(urlString);
815
- const { origin } = url;
816
- const pathname = UrlHelper.trimSlashFromStringEdges(UrlHelper.combinePaths(url.pathname, ...paths));
817
- return new URL(pathname, origin).toString();
818
- }
819
- static removeQueryParam(fullUrlString, param) {
820
- const url = new URL(fullUrlString);
821
- const params = url.searchParams;
822
- const pathname = this.trimSlashFromStringEnd(url.pathname);
823
- // Remove the query parameter
824
- params.delete(param);
825
- // Preserving other URL attributes
826
- let newUrlString;
827
- if (params.toString() === '')
828
- newUrlString = `${url.origin}${pathname}${url.hash}`;
829
- else
830
- newUrlString = `${url.origin}${pathname}?${params.toString()}${url.hash}`;
831
- return newUrlString;
832
- }
833
- }
834
- UrlHelper.isCompleteURLString = (urlString) => {
835
- try {
836
- const url = new URL(urlString);
837
- return url.hostname !== '';
838
- }
839
- catch (error) { }
840
- return false;
863
+ // src/utils/UrlHelper.ts
864
+ var _UrlHelper = class _UrlHelper {
865
+ static trimSlashFromStringEnd(pathString) {
866
+ let newString = pathString;
867
+ while (newString[newString.length - 1] === "/") {
868
+ newString = newString.slice(0, -1);
869
+ }
870
+ return newString;
871
+ }
872
+ static trimSlashFromStringStart(pathString) {
873
+ let newString = pathString;
874
+ while (newString[0] === "/") {
875
+ newString = newString.slice(1);
876
+ }
877
+ return newString;
878
+ }
879
+ static trimSlashFromStringEdges(pathString) {
880
+ return _UrlHelper.trimSlashFromStringStart(this.trimSlashFromStringEnd(pathString));
881
+ }
882
+ static combinePaths(...paths) {
883
+ const completePath = paths.join("/");
884
+ return completePath.replace(/\/{2,}/g, "/");
885
+ }
886
+ static combineURLPaths(urlString, ...paths) {
887
+ const url = new URL(urlString);
888
+ const { origin } = url;
889
+ const pathname = _UrlHelper.trimSlashFromStringEdges(_UrlHelper.combinePaths(url.pathname, ...paths));
890
+ return new URL(pathname, origin).toString();
891
+ }
892
+ static removeQueryParam(fullUrlString, param) {
893
+ const url = new URL(fullUrlString);
894
+ const params = url.searchParams;
895
+ const pathname = this.trimSlashFromStringEnd(url.pathname);
896
+ params.delete(param);
897
+ let newUrlString;
898
+ if (params.toString() === "") newUrlString = `${url.origin}${pathname}${url.hash}`;
899
+ else newUrlString = `${url.origin}${pathname}?${params.toString()}${url.hash}`;
900
+ return newUrlString;
901
+ }
841
902
  };
842
-
843
- exports.Accelbyte = Accelbyte;
844
- exports.ApiUtils = ApiUtils;
845
- exports.BrowserHelper = BrowserHelper;
846
- exports.CodeGenUtil = CodeGenUtil;
847
- exports.DecodeError = DecodeError;
848
- exports.DesktopChecker = DesktopChecker;
849
- exports.ERROR_CODE_LINK_DELETION_ACCOUNT = ERROR_CODE_LINK_DELETION_ACCOUNT;
850
- exports.ERROR_CODE_TOKEN_EXPIRED = ERROR_CODE_TOKEN_EXPIRED;
851
- exports.ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT = ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT;
852
- exports.ERROR_USER_BANNED = ERROR_USER_BANNED;
853
- exports.Network = Network;
854
- exports.RefreshSession = RefreshSession;
855
- exports.SdkDevice = SdkDevice;
856
- exports.UrlHelper = UrlHelper;
857
- exports.Validate = Validate;
858
- exports.doRefreshSession = doRefreshSession;
859
- exports.injectAuthInterceptors = injectAuthInterceptors;
860
- exports.injectErrorInterceptors = injectErrorInterceptors;
861
- exports.injectRequestInterceptors = injectRequestInterceptors;
862
- exports.injectResponseInterceptors = injectResponseInterceptors;
863
- exports.refreshWithLock = refreshWithLock;
864
- //# sourceMappingURL=index.cjs.map
903
+ _UrlHelper.isCompleteURLString = (urlString) => {
904
+ try {
905
+ const url = new URL(urlString);
906
+ return url.hostname !== "";
907
+ } catch (error) {
908
+ }
909
+ return false;
910
+ };
911
+ var UrlHelper = _UrlHelper;
912
+ // Annotate the CommonJS export names for ESM import in node:
913
+ 0 && (module.exports = {
914
+ AccelByte,
915
+ AccelByteSDK,
916
+ ApiUtils,
917
+ BrowserHelper,
918
+ CodeGenUtil,
919
+ DecodeError,
920
+ DesktopChecker,
921
+ ERROR_CODE_LINK_DELETION_ACCOUNT,
922
+ ERROR_CODE_TOKEN_EXPIRED,
923
+ ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT,
924
+ ERROR_USER_BANNED,
925
+ ErrorInterceptors,
926
+ IamErrorCode,
927
+ Network,
928
+ RefreshSession,
929
+ RefreshToken,
930
+ SdkDevice,
931
+ UrlHelper,
932
+ Validate,
933
+ createAuthInterceptor,
934
+ createCustomPathInterceptor,
935
+ createGetSessionInterceptor,
936
+ createRefreshSessionInterceptor,
937
+ isType
938
+ });
939
+ //# sourceMappingURL=index.cjs.map