@accelbyte/sdk 3.0.8 → 4.0.1

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